diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..373a4f2 --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,89 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in the tracker doc. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Search the repo for every file that documents how code should be written. When `CODING_STANDARDS.md` or `CONTRIBUTING.md` exists, it must be on the list. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +Issue both sub-agent calls together, in the foreground, and aggregate the reports they return. + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..d099013 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md new file mode 100644 index 0000000..3947ff9 --- /dev/null +++ b/.agents/skills/grill-me/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-me +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true +--- + +Call the Skill tool with "grilling". diff --git a/.agents/skills/grill-me/agents/openai.yaml b/.agents/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/.agents/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement/SKILL.md b/.agents/skills/implement/SKILL.md new file mode 100644 index 0000000..bd49e47 --- /dev/null +++ b/.agents/skills/implement/SKILL.md @@ -0,0 +1,17 @@ +--- +name: implement +description: "Implement a piece of work based on a spec or set of tickets." +disable-model-invocation: true +--- + +Implement the work described by the user in the spec or tickets. + +If the user passes a ticket reference, fetch it from the issue tracker and state its title before starting. If the reference is ambiguous, ask. + +Call the Skill tool with "tdd" where possible, at pre-agreed seams. + +Run typechecking regularly, single test files regularly, and the full test suite once at the end. + +Once done, call the Skill tool with "code-review" to review the work. + +Commit your work to the current branch. diff --git a/.agents/skills/implement/agents/openai.yaml b/.agents/skills/implement/agents/openai.yaml new file mode 100644 index 0000000..f8794dc --- /dev/null +++ b/.agents/skills/implement/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement" + short_description: "Build work from a spec or tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..44cc7d3 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use GLOSSARY.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/.gitignore b/.gitignore index 6a8b67c..3c6b658 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,9 @@ deploy_key # Scratch files agent/scratch/* +agent/runs/ +agent/*.csv +agent/*.jsonl fix_agent_langfuse.py fix_langfuse.py diff --git a/agent/README.md b/agent/README.md index 17f2bc0..ea08cf0 100644 --- a/agent/README.md +++ b/agent/README.md @@ -35,3 +35,104 @@ graph TD finalizer --> END((END)) ``` + +## Running the deep agent locally + +Code layout (`src/deep_agent/`): + +``` +agent.py create_deep_agent(): wires model, tools, prompt, skills, middleware, subagents +service.py run_deep_chat(): serving behind chat_with_agent (threads, timeout_s, streaming, response) +cli.py developer CLI +context.py per-request context, state fields, user-message helpers, date prefix +observability.py Langfuse run config and scores +resources.py skills wiring (read-only /skills/) +tools/ what the model can call: sql, metadata, location (+ envelope, trino_errors) +answer/ the final answer: schema, verification (did the SQL run), middleware, render +validator/ independent semantic review before submit: reviewer (the agent), modes (wiring) +middleware/ cross-cutting: catalog in every model call, built-in tool filter +prompts/ system.md, validator.md + registry.py (Langfuse / packaged) +skills/ temporal-analyst, spatial-analyst +``` + +The deep agent (`src/deep_agent/`) has a CLI entry point: + +```bash +uv sync +uv run deep-agent "כמה טיסות המריאו מצרפת" # single question, fresh thread +uv run deep-agent --interactive --session-memory # REPL, shared thread across questions +uv run deep-agent "..." --connection-id 89 # override JEEN_METADATA_CONNECTION_ID +uv run deep-agent "..." --log-file runs/runs.jsonl # append one JSON line per run +``` + +It reads the same `agent/.env` settings as the API (LLM, Trino, Jeen metadata MCP, Langfuse). +Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.csv`); Langfuse is the system of record for traces. + +### Semantic validation (deep agent) + +A SQL answer needs two approvals **before** it is submitted: + +1. **It ran:** the SQL executed successfully with `execute_trino_query` in this turn (a limited sample counts; the + full rows are fetched once more for the user). +2. **It answers the question:** the `semantic-validator` subagent (`src/deep_agent/validator/`) passed it. The agent + calls it through `task` with the SQL and its assumptions; the reviewer's input is built by our code from facts — the + user's own messages, the SQL, its recorded rows, the assumptions as claims to check, the catalog and the date — + never from the agent's reasoning. It judges by reading (no SQL tools) and returns pass, fail with issues and + evidence, or — rarely, when only data can settle a doubt it can see — needs_check with specific checks; the agent + runs them and asks for review again, and the reviewer then sees their real results (prompt: `prompts/validator.md`, + `deep-agent/validator` in Langfuse). + +`submit_answer` only checks those records. Without them it is refused with the reason and the agent continues; a SQL +changed after its review needs a new one. After a fail the agent fixes the SQL, or disputes: it submits the same SQL +with `validation_response` (recorded as disputed and shown to the user). + +| Setting | Default | | +|---|---|---| +| `DEEP_AGENT_SEMANTIC_VALIDATION` | `always` | `on_demand` = the reviewer is offered and the agent decides whether to call it; `off` = no reviewer. In both, only approval 1 is required | +| `DEEP_AGENT_VALIDATOR_MAX_ROUNDS` | none | optional: after this many reviews in a turn, an unreviewed SQL is accepted as `not_validated` | +| `DEEP_AGENT_STRICT_SUBMIT` | `false` | `true` = no recovery of answers written as text and no reminder: a model that doesn't call `submit_answer` ends without an answer | + +The response's `semantic_validation` reports the review of the **final** SQL: `verdict` (`passed` / `disputed` / +`not_validated`), `rounds`, `issues`, `reviewed_final_sql`. Langfuse gets `validation_rounds` and, when the final SQL +was reviewed, `semantic_validation_passed`. + +### SQL safety (deep agent) + +Every SQL the deep agent runs goes through `agent/utils/sql_guard.py` (sqlglot, Trino dialect): +- exactly one read-only statement (`SELECT` / `WITH` / set operations, plus `SHOW` / `DESCRIBE`); writes, DDL, `CALL`, `SET`, multi-statements, SQL comments and `TABLE(...)` pass-through functions are rejected with `FORBIDDEN_STATEMENT` +- an outer `LIMIT` of cap + 1 is enforced at the AST level (`DEEP_AGENT_MAX_ROWS`, default 100; `DEEP_AGENT_MAX_SAMPLE_ROWS`, default 10) and results report `truncated`. A `LIMIT` / `FETCH FIRST` already within the cap is left as written, and set operations get the `LIMIT` in place so their `ORDER BY` survives +- set either variable to `none` to disable that ceiling: SQL then runs exactly as written and every row is returned (mind the model's context size) +- table and column names in `get_sample_rows` / `get_column_distinct_values` are parsed and quoted by sqlglot, never string-interpolated + +The guard is an application-level control. The Trino principal used by the agent should also be SELECT-only. + +### Tracing (deep agent) + +Every deep-agent run is **one Langfuse trace** built by `deep_agent.observability.build_run_config()`: +- session = thread id, user = `user_id`, tag `deep-agent`, metadata `agent_version` (`DEEP_AGENT_VERSION` env, e.g. the git SHA, else the package version) and `connection_id` +- all model calls, tool calls, and subagent calls are nested observations +- `execute_trino_query` / `get_sample_rows` / `get_column_distinct_values` observations carry `trino_query_id`, `execution_time_ms`, `row_count`, `truncated` (or Trino's `error_name` / `error_type`) as metadata +- run-level scores: `deep-agent.model_calls`, `.tool_calls`, `.sql_executions`, `.latency_s` + +In Langfuse, filter traces by **tag = `deep-agent`** (save it as a view). Disable tracing with `DEEP_AGENT_TRACING_ENABLED=false`. + +### Serving the deep agent + +The agent service exposes one MCP tool per agent: `chat_with_agent` (the legacy graph) and `deep_agent`. Each takes only +its own arguments; the backend's `POST /api/agent/chat` picks the tool: + +| Setting / argument | Effect | +|---|---| +| backend body `"engine": "deep"` | calls `deep_agent`; omitted / `"legacy"` calls `chat_with_agent` | +| thread id `deep-…` | Deep Agent threads; the backend resumes them on `deep_agent`, and each tool refuses the other's threads | +| `DEEP_AGENT_CHECKPOINT_DB_URL=postgresql://…` | durable deep-agent threads (shared by replicas, survive restarts); unset = in-memory | +| `timeout_s` argument | how long the caller waits; the run is cancelled then (a query already running finishes first). Omitted = no limit. The backend sends 290 (it waits 300). | + +The deep agent is built once per process and streams the same Redis `agent_stream:{thread_id}` events as the legacy graph +(nodes `deep:` and `deep:answer`). Responses keep the legacy contract and add `engine`, `verification` +(matched / re_executed / rejected / re_execution_failed / no_answer), `executed` (the final SQL ran and the rows are +Trino's), `recovered_from_text`, `semantic_validation` and `confidence`. Each turn's answer is checked only against SQL executed in that turn. + +Clarifications are off (`DEEP_AGENT_CLARIFICATIONS_ENABLED=false`). When on, a clarification comes back as +`status: "interrupted"` with `interrupt_details.type = "hitl_escalation"` (`subtype: "clarification"`); the user's answer +is sent as `resume_value` (string or `{"feedback": ...}`). diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 3b464a6..39e132e 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -22,17 +22,27 @@ dependencies = [ "json-repair>=0.25.0", "shapely>=2.0.0", "sqlglot>=25.0.0", + "deepagents>=0.6.12", "urllib3>=2.7.0", + "pyyaml>=6.0", + "langgraph-checkpoint-postgres>=2.0", + "psycopg[binary,pool]>=3.2", ] +[project.scripts] +deep-agent = "deep_agent.cli:main" + [tool.uv.sources] -core = { path = "../core" } +core = { path = "../core", editable = true } esca-sdk = { git = "https://github.com/elirazpevz/esca.git", subdirectory = "packages/esca-sdk" } [build-system] requires = ["uv_build>=0.11.7,<0.12.0"] build-backend = "uv_build" +[tool.uv.build-backend] +module-name = ["agent", "deep_agent"] + [dependency-groups] dev = [ "pytest>=9.0.3", diff --git a/agent/scripts/sync_deep_agent_prompts.py b/agent/scripts/sync_deep_agent_prompts.py new file mode 100644 index 0000000..fa040ab --- /dev/null +++ b/agent/scripts/sync_deep_agent_prompts.py @@ -0,0 +1,43 @@ +""" +Push the packaged Deep Agent prompts (agent/src/deep_agent/prompts/*.md) to Langfuse. + + uv run python scripts/sync_deep_agent_prompts.py --label staging # create new versions labelled staging + uv run python scripts/sync_deep_agent_prompts.py --label production --dry-run + +Each run creates a new version of every `deep-agent/` text prompt with the given label. +Promote a version by moving the `production` label in the Langfuse UI — the running agent +picks it up within DEEP_AGENT_PROMPT_CACHE_TTL_S, no redeploy. +""" + +import argparse + +from deep_agent.prompts.registry import PROMPT_KEYS, langfuse_name, local_prompt + + +def sync(client, label: str, dry_run: bool = False) -> list[str]: + names = [] + for key in PROMPT_KEYS: + name = langfuse_name(key) + if not dry_run: + client.create_prompt(name=name, prompt=local_prompt(key), labels=[label], type="text", + commit_message="sync from agent/src/deep_agent/prompts") + names.append(name) + return names + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--label", default="staging") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + + from agent.langfuse_client import langfuse_client + + for name in sync(langfuse_client, args.label, args.dry_run): + print(f"{'would push' if args.dry_run else 'pushed'} {name} [{args.label}]") + if not args.dry_run: + langfuse_client.flush() + + +if __name__ == "__main__": + main() diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 202b578..8373f95 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -1,4 +1,4 @@ -from pydantic import Field +from pydantic import Field, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict from typing import Literal @@ -45,6 +45,30 @@ class AgentSettings(BaseSettings): JEEN_METADATA_SEARCH_LIMIT: int = 10 # Max tables returned by the search tool JEEN_METADATA_PROFILE_TIMEOUT: float = 30.0 # Per-MCP-call timeout (seconds) + # ── Deep Agent ──────────────────────────────────────────────────────────── + DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) + # Row ceilings for the deep agent's SQL tools. Set to "none" (or empty) to disable the ceiling. + DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query + DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows + DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores + DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering + # Independent semantic review (see deep_agent/validator/), by the `semantic-validator` subagent: + # always = submit_answer is accepted only for SQL it passed (or that the agent disputes); + # on_demand = the agent may call it, submit only requires that the SQL ran; off = no reviewer. + DEEP_AGENT_SEMANTIC_VALIDATION: Literal["always", "on_demand", "off"] = "always" + DEEP_AGENT_VALIDATOR_MAX_ROUNDS: int | None = Field(default=None, gt=0) # reviews per turn before submit stops requiring one; "none" = no limit + # Strict submit: no recovery of answers written as text and no "submit now" reminder — a model that doesn't + # call submit_answer (or the reviewer submit_verdict) simply ends without an answer. + DEEP_AGENT_STRICT_SUBMIT: bool = False + JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) + JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop + # Prompts (see deep_agent/prompts/registry.py). Off until the prompts are finalised and synced to Langfuse. + DEEP_AGENT_LANGFUSE_PROMPTS: bool = False # serve deep-agent/ prompts from Langfuse (packaged .md fallback) + DEEP_AGENT_PROMPT_LABEL: str = "production" # Langfuse prompt label to serve + DEEP_AGENT_PROMPT_CACHE_TTL_S: int = Field(default=60, ge=0) + # Serving (see deep_agent/service.py) + DEEP_AGENT_CHECKPOINT_DB_URL: str | None = None # postgresql://... for durable deep-agent threads; unset = in-memory + # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" TRINO_SCHEMA: str = "" @@ -96,5 +120,13 @@ class AgentSettings(BaseSettings): # ── G2-05: Redis Schema Cache ───────────────────────────────────────────── SCHEMA_CACHE_TTL: int = Field(default=600, gt=0) # seconds — DDL content + @field_validator("DEEP_AGENT_MAX_ROWS", "DEEP_AGENT_MAX_SAMPLE_ROWS", "DEEP_AGENT_VALIDATOR_MAX_ROUNDS", mode="before") + @classmethod + def _no_limit(cls, value): + # Env vars can't hold None; these spellings mean "no limit". + if isinstance(value, str) and value.strip().lower() in ("", "none", "null", "unlimited"): + return None + return value + settings = AgentSettings() diff --git a/agent/src/agent/mcp_server.py b/agent/src/agent/mcp_server.py index 40498c8..2e32f76 100644 --- a/agent/src/agent/mcp_server.py +++ b/agent/src/agent/mcp_server.py @@ -11,6 +11,8 @@ mcp = FastMCP("Text2SQL Agent") +DEEP_THREAD_PREFIX = "deep-" # Deep Agent thread ids, so a thread is never resumed on the wrong agent + @mcp.tool() @observe() @@ -26,7 +28,9 @@ async def chat_with_agent( execution_mode: str | None = None, hitl_enabled: bool = True, ) -> str: - """Run the Text2SQL agent to answer database queries. + """Run the legacy Text2SQL agent (LangGraph workflow) to answer database queries. + + The Deep Agent is a separate tool: `deep_agent`. Args: query: The natural language question to answer. @@ -41,6 +45,9 @@ async def chat_with_agent( for this invocation only. hitl_enabled: If False, skip all human-in-the-loop interrupts. """ + if thread_id and thread_id.startswith(DEEP_THREAD_PREFIX): + return json.dumps({"error": f"Thread '{thread_id}' belongs to the Deep Agent — continue it with the deep_agent tool."}) + thread_id = thread_id or str(uuid.uuid4()) langfuse_handler = None @@ -211,6 +218,56 @@ async def chat_with_agent( } ) +@mcp.tool() +@observe() +async def deep_agent( + connection_id: int, + query: str | None = None, + thread_id: str | None = None, + resume_value: str | dict | None = None, + hitl_enabled: bool = True, + user_id: str | None = None, + timeout_s: float | None = None, +) -> str: + """Run the Deep Agent to answer a question about the connection's data. + + Returns the same response shape as chat_with_agent, plus engine / verification / executed / + semantic_validation / confidence. + + Args: + connection_id: The connection whose catalog the agent answers against. + query: The natural language question (a new thread). + thread_id: Continue a Deep Agent thread (ids start with 'deep-'); omit to start a new one. + resume_value: The user's answer to a clarifying question (a string or {"feedback": ...}). + hitl_enabled: If False, a clarifying question comes back as the completed answer instead of a pause. + user_id: End-user id for tracing. + timeout_s: How long the caller waits: the run is cancelled when it expires. Omit for no limit. + """ + if thread_id and not thread_id.startswith(DEEP_THREAD_PREFIX): + return json.dumps({"error": f"Thread '{thread_id}' belongs to the legacy agent — continue it with chat_with_agent."}) + return json.dumps(await _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, timeout_s), + default=str) + + +async def _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, timeout_s=None) -> dict: + from deep_agent.service import run_deep_chat + + response = await run_deep_chat( + connection_id=connection_id, + query=query, + thread_id=thread_id or f"{DEEP_THREAD_PREFIX}{uuid.uuid4()}", + resume_value=resume_value, + user_id=user_id, + timeout_s=timeout_s, + ) + if not hitl_enabled and response.get("status") == "interrupted": + # Non-interactive callers get the clarifying question as the answer instead of a pause. + question = (response.get("interrupt_details") or {}).get("reason", "") + response = {**response, "status": "completed", "summary": question, "interrupt_details": None, + "is_unanswerable": True} + return response + + @mcp.tool() async def suggest_fixes(thread_id: str, category: str) -> str: """Generate quick fix suggestions during an interruption.""" diff --git a/agent/src/agent/services/hybrid_searcher.py b/agent/src/agent/services/hybrid_searcher.py index f76038c..97d58fe 100644 --- a/agent/src/agent/services/hybrid_searcher.py +++ b/agent/src/agent/services/hybrid_searcher.py @@ -91,9 +91,9 @@ async def search(filters: List[SQLFilterParams], tables: List[AgentSQLTable]) -> # Schedule search task directly via MCP client # The MCP backend handles semantic_type routing automatically task = client.search_column_values( - query=clean_val, - table_name=table_lower or None, - column_name=col_lower or None + search_term=clean_val, + table=table_lower or None, + column=col_lower or None ) tasks.append(task) diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index 5dcdfbb..d22557f 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -41,9 +41,14 @@ from __future__ import annotations +import asyncio +import copy import json import logging -from typing import Any +import time +import weakref +from datetime import timedelta +from typing import Any, NoReturn from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client @@ -53,10 +58,137 @@ logger = logging.getLogger(__name__) +class JeenMetadataError(RuntimeError): + """The MCP server reported an error, or returned a payload of an unexpected shape.""" + + +# Read-only metadata tools whose results may be served from the client's TTL cache. +_CACHEABLE_TOOLS = frozenset({ + "get_catalog_prompt", "get_tables", "get_columns", "get_relationships", "get_table_profile", "get_column_profile", +}) + + # --------------------------------------------------------------------------- # Low-level MCP call helper # --------------------------------------------------------------------------- +class _PersistentSession: + """One long-lived MCP ClientSession, owned by a background task. + + anyio requires the transport/session context managers to be entered and exited in the + same task, so a dedicated task holds them open; callers in other tasks use + `session.call_tool(...)` concurrently (MCP multiplexes requests by id). A broken + session is invalidated and transparently re-created on the next call. + """ + + def __init__(self, url: str, api_key: str, timeout: float) -> None: + self._url, self._api_key, self._timeout = url, api_key, timeout + self._session: ClientSession | None = None + self._task: asyncio.Task | None = None + self._ready = asyncio.Event() + self._stop = asyncio.Event() + self._error: BaseException | None = None + self._lock = asyncio.Lock() + self.handshakes = 0 # number of initialize() handshakes performed (observability/tests) + + async def get(self) -> ClientSession: + async with self._lock: + if self._session is None or self._task is None or self._task.done(): + self._ready, self._stop, self._error = asyncio.Event(), asyncio.Event(), None + self._task = asyncio.create_task(self._run(), name="jeen-mcp-session") + await asyncio.wait_for(self._ready.wait(), timeout=self._timeout + 5) + if self._session is None: + raise JeenMetadataError(f"Could not open MCP session: {self._error}") + return self._session + + async def _run(self) -> None: + try: + async with streamablehttp_client( + self._url, + headers={"Authorization": f"Bearer {self._api_key}"}, + timeout=self._timeout, + sse_read_timeout=self._timeout + 30, + ) as (read, write, _get_session_id): + async with ClientSession(read, write) as session: + await session.initialize() + self.handshakes += 1 + self._session = session + self._ready.set() + await self._stop.wait() + except BaseException as exc: # noqa: BLE001 — recorded and surfaced to the caller + self._error = exc + if isinstance(exc, asyncio.CancelledError): + raise + finally: + self._session = None + self._ready.set() + + def invalidate(self) -> None: + self._session = None + self._stop.set() + + async def close(self) -> None: + self._stop.set() + if self._task is not None: + await asyncio.gather(self._task, return_exceptions=True) + + +# One persistent session per (event loop, url, key). +_sessions: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[tuple[str, str], _PersistentSession]]" = ( + weakref.WeakKeyDictionary() +) + + +def _persistent_session(url: str, api_key: str, timeout: float) -> _PersistentSession: + per_loop = _sessions.setdefault(asyncio.get_running_loop(), {}) + if (url, api_key) not in per_loop: + per_loop[(url, api_key)] = _PersistentSession(url, api_key, timeout) + return per_loop[(url, api_key)] + + +async def close_mcp_sessions() -> None: + """Close this event loop's persistent MCP sessions (call before the loop shuts down).""" + per_loop = _sessions.pop(asyncio.get_running_loop(), {}) + await asyncio.gather(*(s.close() for s in per_loop.values()), return_exceptions=True) + + +def _parse_tool_result(tool_name: str, result: Any) -> Any: + # result.content is a list of ContentBlock objects. + # We expect the first (and only) block to be a TextContent. + first = result.content[0] if result.content else None + text = getattr(first, "text", None) + + if getattr(result, "isError", False): + raise JeenMetadataError(f"MCP tool '{tool_name}' failed: {text or 'no error details'}") + if text is None: + return {} + + try: + return json.loads(text) + except json.JSONDecodeError: + return text + + +async def _call_with_persistent_session( + url: str, api_key: str, tool_name: str, arguments: dict[str, Any], timeout: float +) -> Any: + holder = _persistent_session(url, api_key, timeout) + for attempt in (1, 2): + session = await holder.get() + try: + result = await session.call_tool( + tool_name, arguments, read_timeout_seconds=timedelta(seconds=timeout) + ) + return _parse_tool_result(tool_name, result) + except JeenMetadataError: + raise + except Exception as exc: + holder.invalidate() # stale/broken session: reconnect once + if attempt == 2: + raise + logger.info("MCP session for %s failed (%s); reconnecting", url, exc) + + async def _call_mcp_tool( url: str, api_key: str, @@ -65,16 +197,19 @@ async def _call_mcp_tool( timeout: float = 15.0, ) -> Any: """ - Open an MCP session, run the full initialization handshake, call one - tool, and return the parsed payload from the first text content block. + Call one MCP tool and return the parsed payload from the first text content block. - Uses the official Python MCP SDK so the - initialize → notifications/initialized → tools/call sequence is handled - automatically. Returns parsed JSON (dict/list) or a raw string if the + With JEEN_METADATA_REUSE_SESSION (default) the MCP session is kept open per event loop, + so the initialize → notifications/initialized handshake happens once instead of on + every call. Otherwise (or if the persistent path cannot be set up) a session is opened + for this call only. Uses the official Python MCP SDK, which handles the handshake and + both JSON and SSE responses. Returns parsed JSON (dict/list) or a raw string if the content block is not JSON. """ - headers = {"Authorization": f"Bearer {api_key}"} + if settings.JEEN_METADATA_REUSE_SESSION: + return await _call_with_persistent_session(url, api_key, tool_name, arguments, timeout) + headers = {"Authorization": f"Bearer {api_key}"} async with streamablehttp_client( url, headers=headers, @@ -85,23 +220,23 @@ async def _call_mcp_tool( ) as (read, write, _get_session_id): async with ClientSession(read, write) as session: await session.initialize() - result = await session.call_tool(tool_name, arguments) + return _parse_tool_result(tool_name, result) - # result.content is a list of ContentBlock objects. - # We expect the first (and only) block to be a TextContent. - if not result.content: - return {} - first = result.content[0] - text = getattr(first, "text", None) - if text is None: - return {} +def _reraise_as_metadata_error(exc: Exception) -> NoReturn: + if isinstance(exc, JeenMetadataError): + raise exc + raise JeenMetadataError(str(exc)) from exc - try: - return json.loads(text) - except json.JSONDecodeError: - return text + +def _expect_list(payload: Any, key: str, method: str) -> list[dict[str, Any]]: + """Unwrap a list payload (bare or under `key`); anything else is an error, never an empty result.""" + if isinstance(payload, dict) and key in payload: + payload = payload[key] + if isinstance(payload, list): + return payload + raise JeenMetadataError(f"{method} returned unexpected payload: {str(payload)[:300]}") # --------------------------------------------------------------------------- @@ -126,6 +261,8 @@ def __init__(self) -> None: getattr(settings, "JEEN_METADATA_SEARCH_LIMIT", settings.HYBRID_SEARCH_MAX_TABLES) ) self._timeout: float = float(getattr(settings, "JEEN_METADATA_PROFILE_TIMEOUT", 15.0)) + self._cache: dict[tuple[str, str], tuple[float, Any]] = {} + self._inflight: dict[tuple[str, str], asyncio.Future] = {} self.is_configured: bool = bool( self._mcp_url and self._mcp_key and self._connection_id @@ -141,8 +278,35 @@ def __init__(self) -> None: # ── internal helper ──────────────────────────────────────────────────── + def _cid(self, connection_id: int | None) -> int: + """Per-call connection override, falling back to the configured default.""" + return connection_id if connection_id is not None else self._connection_id + async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: - """Thin wrapper so individual methods don't repeat the URL/key/timeout.""" + """Call an MCP tool; read-only metadata tools are served from a TTL cache (single-flight).""" + ttl = settings.JEEN_METADATA_CACHE_TTL_S + if tool_name not in _CACHEABLE_TOOLS or ttl <= 0: + return await self._call_uncached(tool_name, arguments) + + key = (tool_name, json.dumps(arguments, sort_keys=True, default=str)) + hit = self._cache.get(key) + if hit is not None and hit[0] > time.monotonic(): + return copy.deepcopy(hit[1]) + + inflight = self._inflight.get(key) + if inflight is None: + inflight = asyncio.ensure_future(self._call_uncached(tool_name, arguments)) + self._inflight[key] = inflight + try: + value = await asyncio.shield(inflight) # a cancelled caller must not cancel the shared fetch + self._cache[key] = (time.monotonic() + ttl, value) # errors are never cached + finally: + self._inflight.pop(key, None) + else: + value = await asyncio.shield(inflight) + return copy.deepcopy(value) + + async def _call_uncached(self, tool_name: str, arguments: dict[str, Any]) -> Any: return await _call_mcp_tool( self._mcp_url, self._mcp_key, @@ -151,32 +315,52 @@ async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: self._timeout, ) + def clear_cache(self) -> None: + """Drop cached metadata (e.g. after a profiling run updates the catalog).""" + self._cache.clear() + # ------------------------------------------------------------------ # Search Column Values # ------------------------------------------------------------------ async def search_column_values( - self, query: str, table_name: str | None = None, column_name: str | None = None - ) -> list[str]: + self, + search_term: str, + table: str | None = None, + column: str | None = None, + limit: int | None = None, + raw: bool = False, + connection_id: int | None = None, + ) -> list[str] | dict[str, Any]: """ Looks up real values a column contains using semantic and keyword matching via MCP. + Uses exact MCP parameter names: search_term, table, column, limit. + When raw=True, returns the full payload dictionary from the MCP server. """ if not self.is_configured: logger.warning("JeenMetadataClient is not configured. Returning empty search results.") - return [] - + return [] if not raw else {"error": "JeenMetadataClient is not configured."} + + lim = limit if limit is not None else self._search_limit args: dict[str, Any] = { - "connection_id": self._connection_id, - "search_term": query, - "limit": self._search_limit, + "connection_id": self._cid(connection_id), + "search_term": search_term, + "limit": lim, } - if table_name: - args["table"] = table_name - if column_name: - args["column"] = column_name + if table: + args["table"] = table + if column: + args["column"] = column try: payload = await self._call("search_column_values", args) + if raw: + if isinstance(payload, dict): + return payload + if isinstance(payload, list): + return {"values": payload} + raise JeenMetadataError(f"search_column_values returned unexpected payload: {str(payload)[:300]}") + if isinstance(payload, dict) and "values" in payload: results = [] for v in payload["values"]: @@ -185,9 +369,13 @@ async def search_column_values( else: results.append(str(v)) return results + elif isinstance(payload, list): + return [str(x) for x in payload] return [] except Exception as exc: logger.error("JeenMetadataClient.search_column_values failed: %s", exc, exc_info=True) + if raw: + _reraise_as_metadata_error(exc) return [] # ------------------------------------------------------------------ @@ -267,15 +455,21 @@ async def get_table_profile(self, table_name: str, connection_id: int | None = N table_profile: dict = payload.get("table_profile") or {} if isinstance(payload, dict) else {} columns_raw: list[dict] = payload.get("columns") or [] if isinstance(payload, dict) else [] - # Normalise column list into the shape the agent already consumes + # Normalise column list into the shape the agent consumes columns = [] for col in columns_raw: + null_val = col.get("nullRatio") if col.get("nullRatio") is not None else (col.get("nullRate") or col.get("null_rate")) + distinct_val = col.get("distinctCount") if col.get("distinctCount") is not None else col.get("distinct_count") + sem_type = col.get("semanticType") or col.get("semantic_type") or col.get("columnRole") or "unknown" + entry: dict[str, Any] = { "name": col.get("columnName") or col.get("column_name") or col.get("name", ""), "type": col.get("dataType") or col.get("data_type") or col.get("type", ""), - "null_rate": round(float(col.get("nullRate") or col.get("null_rate") or 0.0), 4), - "distinct_count": int(col.get("distinctCount") or col.get("distinct_count") or 0), - "semantic_type": col.get("semantic_type") or "unknown", + "null_rate": round(float(null_val or 0.0), 4), + "distinct_count": int(distinct_val or 0), + "semantic_type": sem_type, + "domain_is_complete": bool(col.get("domainIsComplete") or col.get("domain_is_complete", False)), + "example_values": col.get("exampleValues") or col.get("example_values") or [], } # Propagate optional stats if available for src_key, dst_key in [ @@ -316,6 +510,79 @@ async def get_table_profile(self, table_name: str, connection_id: int | None = N ) return None + async def get_column_profile( + self, table_name: str, column_name: str, connection_id: int | None = None + ) -> dict[str, Any] | None: + """ + Returns the latest stored statistics for a single column: role, null ratio, distinct count, min/max, and example values. + """ + try: + res = await self._call( + "get_column_profile", + { + "connection_id": self._cid(connection_id), + "table_name": table_name, + "column_name": column_name, + }, + ) + except Exception as exc: + logger.error("JeenMetadataClient.get_column_profile failed: %s", exc) + _reraise_as_metadata_error(exc) + if isinstance(res, dict): + return res.get("profile") or res + if isinstance(res, str) and res.strip(): + raise JeenMetadataError(f"get_column_profile returned unexpected payload: {res[:300]}") + return None + + # ------------------------------------------------------------------ + # Tables, Columns & Relationships Structure + # ------------------------------------------------------------------ + + async def get_tables(self, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns the list of tables for a connection with business descriptions and quoted identifiers. + """ + cid = connection_id if connection_id is not None else self._connection_id + res = await self._call("get_tables", {"connection_id": cid}) + return _expect_list(res, "tables", "get_tables") + + async def get_columns(self, table_name: str | None = None, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns columns for connection (data type, primary key, description, example values, profiling stats). + """ + cid = connection_id if connection_id is not None else self._connection_id + args: dict[str, Any] = {"connection_id": cid} + if table_name: + args["table_name"] = table_name + res = await self._call("get_columns", args) + return _expect_list(res, "columns", "get_columns") + + async def get_relationships(self, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns source-scoped foreign-key and semantic-model joins for a connection. + """ + cid = connection_id if connection_id is not None else self._connection_id + res = await self._call("get_relationships", {"connection_id": cid}) + return _expect_list(res, "relationships", "get_relationships") + + async def get_source_statistics(self, connection_id: int | None = None) -> dict[str, Any]: + """ + Stored source profile summary: latest profile run, table types, column roles. + """ + cid = connection_id if connection_id is not None else self._connection_id + return await self._call("get_source_statistics", {"connection_id": cid}) + + # ------------------------------------------------------------------ + # Query Execution via MCP + # ------------------------------------------------------------------ + + async def run_query(self, query: str, max_rows: int = 100, connection_id: int | None = None) -> dict[str, Any]: + """ + Executes a read-only SQL query via the MCP server on connections where can_execute=True. + """ + cid = connection_id if connection_id is not None else self._connection_id + return await self._call("run_query", {"connection_id": cid, "query": query, "max_rows": max_rows}) + # ------------------------------------------------------------------ # Full table listing (fallback when search returns nothing) # ------------------------------------------------------------------ @@ -355,6 +622,34 @@ async def list_tables_rich(self, connection_id: int | None = None) -> list[dict[ ) return [] + # ------------------------------------------------------------------ + # MCP Search Tools + # ------------------------------------------------------------------ + + async def search(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: + """Search metadata for a connection across tables, columns, etc.""" + try: + return await self._call("search", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) + except Exception as exc: + logger.error("search failed: %s", exc) + _reraise_as_metadata_error(exc) + + async def search_business_terms(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: + """Finds business glossary terms relevant to a question.""" + try: + return await self._call("search_business_terms", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) + except Exception as exc: + logger.error("search_business_terms failed: %s", exc) + _reraise_as_metadata_error(exc) + + async def search_knowledge_pairs(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: + """Finds saved question-and-query examples.""" + try: + return await self._call("search_knowledge_pairs", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) + except Exception as exc: + logger.error("search_knowledge_pairs failed: %s", exc) + _reraise_as_metadata_error(exc) + # --------------------------------------------------------------------------- # Module-level singleton (lazy-initialised, safe to import at module load) diff --git a/agent/src/agent/utils/sql_guard.py b/agent/src/agent/utils/sql_guard.py new file mode 100644 index 0000000..66587a6 --- /dev/null +++ b/agent/src/agent/utils/sql_guard.py @@ -0,0 +1,176 @@ +""" +SQL guardrails for LLM-generated Trino SQL. + +Parses with sqlglot, allows only a single read statement, enforces a row cap at the +AST level, and builds identifiers safely. Ported from Utils-Server +(app/services/trino/guard.py) so both agents share one implementation. +""" + +import re +from dataclasses import dataclass + +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError + +_DIALECT = "trino" +_SHOW = re.compile( + r"^\s*SHOW\s+(CATALOGS|SCHEMAS|TABLES|COLUMNS|FUNCTIONS|STATS|CREATE\s+(TABLE|VIEW)|SESSION)\b", + re.IGNORECASE, +) +_READ_ROOTS = (exp.Select, exp.SetOperation, exp.Subquery) + + +class GuardError(ValueError): + """The SQL was rejected; the message is safe to show the caller (and the agent).""" + + +@dataclass(frozen=True) +class GuardedSQL: + sql: str # rewritten SQL to execute + row_cap: int | None # rows to keep (fetch row_cap + 1 to detect truncation); None for SHOW/DESCRIBE + requested_limit: int | None # LIMIT the SQL asked for, if any + is_query: bool # SELECT-like (row cap applied) vs SHOW/DESCRIBE + + +def effective_cap(requested: int | None, ceiling: int | None) -> int | None: + """Rows to return: the caller's request, bounded by the configured ceiling when one is set. + + None means unlimited — no ceiling configured and nothing requested. + """ + if requested is None: + return ceiling + requested = max(1, int(requested)) + return min(requested, ceiling) if ceiling is not None else requested + + +def _reject_pass_through(tree: exp.Expression) -> None: + # TABLE(catalog.system.query(query => '...')) runs arbitrary SQL on the underlying source. + for table in tree.find_all(exp.Table): + if isinstance(table.this, exp.Anonymous) and str(table.this.this).upper() == "TABLE": + raise GuardError("table functions (TABLE(...)) are not allowed") + for func in tree.find_all(exp.Anonymous): + if str(func.this).upper() == "TABLE": + raise GuardError("table functions (TABLE(...)) are not allowed") + + +def _reject_writes(tree: exp.Expression) -> None: + # Data-modifying nodes nested inside an otherwise read-looking statement (e.g. CTAS-like constructs). + for node in tree.walk(): + if isinstance(node, (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.Create, exp.Drop, exp.Alter)): + raise GuardError(f"{type(node).__name__.upper()} is not allowed: read-only access") + + +def _limit_value(tree: exp.Expression) -> int | None: + """Row count of the outer LIMIT n or FETCH FIRST n ROWS (sqlglot stores both under 'limit').""" + lim = tree.args.get("limit") + if isinstance(lim, exp.Limit): + count = lim.expression + elif isinstance(lim, exp.Fetch): + options = lim.args.get("limit_options") + if options is not None and options.args.get("percent"): + return None + count = lim.args.get("count") + else: + return None + if isinstance(count, exp.Literal) and not count.is_string: + return int(count.this) + return None + + +def parse_read_statement(sql: str) -> exp.Expression | None: + """Validate `sql` as exactly one read-only statement. + + Returns the parsed tree for SELECT-like statements, or None for an allowed + SHOW/DESCRIBE statement. Raises GuardError otherwise. + """ + if not sql or not sql.strip(): + raise GuardError("empty SQL") + try: + statements = [s for s in sqlglot.parse(sql, read=_DIALECT) if s is not None] + except SqlglotError as e: + raise GuardError(f"could not parse SQL: {str(e).splitlines()[0]}") from e + if len(statements) != 1: + raise GuardError("exactly one statement is allowed") + tree = statements[0] + + if isinstance(tree, exp.Command): + if _SHOW.match(sql): + return None + raise GuardError("only SELECT, WITH, SHOW and DESCRIBE statements are allowed") + if isinstance(tree, exp.Describe): + return None + if not isinstance(tree, _READ_ROOTS): + raise GuardError(f"{type(tree).__name__.upper()} statements are not allowed: read-only access") + + _reject_pass_through(tree) + _reject_writes(tree) + return tree + + +def prepare(sql: str, row_cap: int | None) -> GuardedSQL: + """Validate `sql`; when row_cap is set, enforce an outer LIMIT of row_cap + 1 (the extra row flags truncation). + + With row_cap=None the statement is only validated and runs exactly as written. + """ + tree = parse_read_statement(sql) + original = sql.strip().rstrip(";").strip() + if tree is None: + return GuardedSQL(original, None, None, False) + + asked = _limit_value(tree) + if row_cap is None: + return GuardedSQL(original, None, asked, True) + + fetch = row_cap + 1 + if asked is not None and asked <= fetch: + # Already within the cap: run it exactly as written (keeps FETCH ... WITH TIES semantics). + return GuardedSQL(original, row_cap, asked, True) + if isinstance(tree, (exp.Select, exp.SetOperation)): + # Set the outer LIMIT in place. Wrapping in a subquery would let Trino drop the ORDER BY. + tree = tree.limit(fetch, copy=True) + else: + tree = exp.select("*").from_(tree.subquery("_q")).limit(fetch) + return GuardedSQL(tree.sql(dialect=_DIALECT), row_cap, asked, True) + + +def parse_table_name(table_name: str) -> exp.Table: + """Parse a (possibly quoted, 1–3 part) table name; reject anything that isn't a plain table.""" + raw = (table_name or "").strip() + if not raw: + raise GuardError("empty table name") + try: + table = sqlglot.parse_one(raw, into=exp.Table, dialect=_DIALECT) + except SqlglotError as e: + raise GuardError(f"invalid table name {raw!r}") from e + parts = [table.args.get(k) for k in ("catalog", "db", "this")] + if not isinstance(table.this, exp.Identifier) or any( + p is not None and not isinstance(p, exp.Identifier) for p in parts + ): + raise GuardError(f"invalid table name {raw!r}") + if set(table.args) - {"catalog", "db", "this"} and any( + v for k, v in table.args.items() if k not in ("catalog", "db", "this") + ): + raise GuardError(f"invalid table name {raw!r}") + return exp.Table(**{k: v for k, v in zip(("catalog", "db", "this"), parts) if v is not None}) + + +def quoted_column(column_name: str) -> exp.Column: + """Build a quoted column reference from a raw or double-quoted name (spaces/Hebrew allowed).""" + name = (column_name or "").strip() + if len(name) >= 2 and name.startswith('"') and name.endswith('"'): + name = name[1:-1].replace('""', '"') + if not name: + raise GuardError("empty column name") + return exp.column(exp.to_identifier(name, quoted=True)) + + +def sample_rows_sql(table_name: str, row_cap: int) -> str: + table = parse_table_name(table_name) + return exp.select("*").from_(table).limit(row_cap + 1).sql(dialect=_DIALECT) + + +def distinct_values_sql(table_name: str, column_name: str, row_cap: int) -> str: + table = parse_table_name(table_name) + column = quoted_column(column_name) + return exp.select(column).distinct().from_(table).limit(row_cap + 1).sql(dialect=_DIALECT) diff --git a/agent/src/deep_agent/__init__.py b/agent/src/deep_agent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py new file mode 100644 index 0000000..3b55eb6 --- /dev/null +++ b/agent/src/deep_agent/agent.py @@ -0,0 +1,103 @@ +""" +Agent logic and LangGraph harness for the Deep Agent. + +The system prompt is served by deep_agent.prompts.registry (Langfuse `deep-agent/system` when +DEEP_AGENT_LANGFUSE_PROMPTS is on, else the packaged prompts/system.md). The connection's catalog +is added to every model call by CatalogMiddleware (deep_agent.middleware.catalog). +""" + + +from deepagents import create_deep_agent as create_harness_agent +from deepagents.middleware.subagents import DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT +from langchain_core.language_models import BaseChatModel +from langgraph.checkpoint.memory import MemorySaver + +from agent.config import settings +from agent.llm import get_llm +from deep_agent.answer.middleware import AnswerVerificationMiddleware, SubmitApprovalMiddleware, submit_fallback +from deep_agent.answer.schema import TOOL_NAME, answer_schema, submission_strategy +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware +from deep_agent.middleware.catalog import CatalogMiddleware +from deep_agent.middleware.tool_filter import BuiltinToolFilterMiddleware +from deep_agent.prompts.registry import load_prompt, local_prompt +from deep_agent.resources import build_resources +from deep_agent.tools import DEEP_AGENT_TOOLS +from deep_agent.validator.modes import ON_DEMAND_PROMPT, REVIEW_PROMPT, ReviewTurnMiddleware, validator_subagent +from deep_agent.validator.reviewer import ValidationMode + +# Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build; the service rebuilds when it changes). +SYSTEM_PROMPT = local_prompt("system") + +# Appended to the system prompt only when DEEP_AGENT_CLARIFICATIONS_ENABLED is on. +CLARIFICATION_PROMPT = """ +If the question is genuinely ambiguous, set `needs_clarification` (a short Hebrew question to the user) instead of `sql`. +""" + + +def _general_purpose_subagent() -> dict: + """deepagents' default `task` subagent, with our request context and the catalog it can no longer fetch itself.""" + return { + "name": "general-purpose", + "description": DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + "system_prompt": DEFAULT_SUBAGENT_PROMPT, + "middleware": [DeepAgentContextMiddleware(), CatalogMiddleware(), BuiltinToolFilterMiddleware()], + } + + +def create_deep_agent( + model: BaseChatModel | None = None, + clarifications_enabled: bool | None = None, + checkpointer=None, + semantic_validation: ValidationMode | None = None, + validator_model: BaseChatModel | None = None, +): + """ + Creates and returns a compiled LangGraph deep agent. + + Invoke with a per-request context, e.g. + agent.ainvoke(inputs, config, context=DeepAgentContext(connection_id=89, user_id="u1")) + + Args: + model: Chat model override (tests); defaults to the configured LLM. + clarifications_enabled: Override DEEP_AGENT_CLARIFICATIONS_ENABLED (tests). + checkpointer: Thread persistence (e.g. AsyncPostgresSaver); defaults to an in-memory saver. + semantic_validation: Override DEEP_AGENT_SEMANTIC_VALIDATION: always | on_demand | off (tests). + validator_model: Model for the independent reviewer; defaults to the agent's model. + """ + if clarifications_enabled is None: + clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED + mode = semantic_validation or settings.DEEP_AGENT_SEMANTIC_VALIDATION + llm = model or get_llm() + memory = checkpointer or MemorySaver() + resources = build_resources() + review_required = mode == "always" # submit needs a validator pass + has_reviewer = mode in ("always", "on_demand") # the semantic-validator subagent is available + review_prompt = {"always": REVIEW_PROMPT, "on_demand": ON_DEMAND_PROMPT}.get(mode, "") + system_prompt = load_prompt("system").text + (CLARIFICATION_PROMPT if clarifications_enabled else "") + review_prompt + subagents = [_general_purpose_subagent()] + if has_reviewer: + subagents.append(validator_subagent(validator_model or llm, mode)) + + agent = create_harness_agent( + model=llm, + tools=DEEP_AGENT_TOOLS, + system_prompt=system_prompt, + subagents=subagents, + middleware=[ + DeepAgentContextMiddleware(), + CatalogMiddleware(), + *submit_fallback(TOOL_NAME), + AnswerVerificationMiddleware(has_reviewer), + *([ReviewTurnMiddleware()] if has_reviewer else []), + SubmitApprovalMiddleware(review_required, settings.DEEP_AGENT_VALIDATOR_MAX_ROUNDS), + BuiltinToolFilterMiddleware(), + ], + response_format=submission_strategy(answer_schema(clarifications_enabled, review_required)), + context_schema=DeepAgentContext, + checkpointer=memory, + backend=resources.backend, + skills=resources.skills, + permissions=resources.permissions, + ) + + return agent diff --git a/agent/src/deep_agent/answer/__init__.py b/agent/src/deep_agent/answer/__init__.py new file mode 100644 index 0000000..1c74b47 --- /dev/null +++ b/agent/src/deep_agent/answer/__init__.py @@ -0,0 +1,8 @@ +""" +The final answer: the `submit_answer` format, keeping it bound to SQL that actually ran, and what the user sees. + +- schema.py the submit_answer tool format (+ clarification / validation_response variants) +- verification.py did the answer's SQL really run? -> final_result (matched / re_executed / ...) +- middleware.py answer recovery, submit reminder, invalid-submission retry, final_result at the end of a turn +- render.py the Hebrew markdown shown to the user +""" diff --git a/agent/src/deep_agent/answer/middleware.py b/agent/src/deep_agent/answer/middleware.py new file mode 100644 index 0000000..81ed9e4 --- /dev/null +++ b/agent/src/deep_agent/answer/middleware.py @@ -0,0 +1,273 @@ +""" +Middleware around the final answer: + +- AnswerRecoveryMiddleware answer written as JSON text instead of a submit_answer call -> the real call +- SubmitReminderMiddleware the model stopped without its submit call -> one reminder per turn + (these two are the submit fallback; off with DEEP_AGENT_STRICT_SUBMIT) +- SubmitApprovalMiddleware submit_answer is accepted only for SQL that ran this turn and that the + semantic-validator passed (or that the agent disputes); it checks records, it + doesn't judge +- AnswerVerificationMiddleware each turn starts clean; invalid submissions are retried; at the end of + the turn the answer is verified (deep_agent.answer.verification) -> final_result +""" + +import asyncio +import json +import logging +import re +import uuid +from collections.abc import Awaitable, Callable +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse, hook_config +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage +from pydantic import BaseModel + +from agent.config import settings +from deep_agent.answer.schema import ANSWER_RECEIVED, last_submission +from deep_agent.answer.verification import match_execution, normalize_sql, validation_summary, verify_answer +from deep_agent.context import REMINDER_NAME, current_turn + +logger = logging.getLogger(__name__) + + +RECOVERED_FLAG = "deep_agent_recovered_answer" +_FENCED_JSON = re.compile(r"^```(?:json)?\s*(\{.*\})\s*```$", re.DOTALL) + + +def _answer_from_text(text: str, schema: type[BaseModel]) -> tuple[dict, BaseModel] | None: + """The message text as a valid final answer (a JSON object that passes the answer schema), else None.""" + body = text.strip() + fenced = _FENCED_JSON.match(body) + if fenced: + body = fenced.group(1) + if not (body.startswith("{") and body.endswith("}")): + return None + try: + args = json.loads(body) + return args, schema(**args) + except (ValueError, TypeError): + return None + + +class AnswerRecoveryMiddleware(AgentMiddleware): + """Recover a final answer the model wrote as text instead of calling submit_answer. + + With gpt-oss behind the configured OpenAI-compatible server, forced tool choice is not always + honoured late in a run: the model sometimes writes the submit_answer JSON as plain text + (finish_reason "tool_calls", no parsed tool call). LangChain then sees no tool call and the run + ends without an answer. When — and only when — the text is a JSON object that validates against + the answer schema, this turns it into the same result a real submit_answer call produces (the + tool call, its tool message and `structured_response`), marked with RECOVERED_FLAG. + Anything else is left untouched. + """ + + def _recover(self, request: ModelRequest, response: ModelResponse) -> ModelResponse: + schema = getattr(request.response_format, "schema", None) + if response.structured_response is not None or schema is None or not response.result: + return response + output = response.result[-1] + if not isinstance(output, AIMessage) or output.tool_calls: + return response + parsed = _answer_from_text(output.text, schema) + if parsed is None: + return response + args, answer = parsed + call_id = f"recovered_{uuid.uuid4().hex[:12]}" + logger.warning("Recovered a final answer the model wrote as text instead of a submit_answer call") + repaired = AIMessage( + content="", + tool_calls=[{"name": schema.__name__, "args": args, "id": call_id, "type": "tool_call"}], + additional_kwargs={**output.additional_kwargs, RECOVERED_FLAG: True}, + response_metadata=output.response_metadata, + usage_metadata=output.usage_metadata, + id=output.id, + name=output.name, + ) + tool_message = ToolMessage(content=ANSWER_RECEIVED, tool_call_id=call_id, name=schema.__name__) + return ModelResponse(result=[*response.result[:-1], repaired, tool_message], structured_response=answer) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return self._recover(request, handler(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return self._recover(request, await handler(request)) + + +class SubmitReminderMiddleware(AgentMiddleware): + """Send the model back once per turn when it stops without calling its submit tool. + + The configured model server sometimes ends a run with plain text instead of the forced + submit call (and AnswerRecoveryMiddleware can only rescue text that is valid JSON for the + schema). The work is then lost — e.g. a reviewer that found a real problem but never + returned its verdict. One reminder (a message named REMINDER_NAME, not counted as the + user's words) asks for the submit call; if the model still doesn't comply, the run ends as before. + """ + + def __init__(self, tool_name: str) -> None: + super().__init__() + self.tool_name = tool_name + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + last = messages[-1] if messages else None + if not isinstance(last, AIMessage) or last.tool_calls or state.get("structured_response") is not None: + return None + if any(getattr(m, "name", None) == REMINDER_NAME for m in current_turn(messages)): + return None # already reminded this turn + reminder = (f"You stopped without calling `{self.tool_name}`. Your work is delivered only through " + f"`{self.tool_name}` — call it now with your result.") + return {"messages": [HumanMessage(reminder, name=REMINDER_NAME)], "jump_to": "model"} + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + +def submit_fallback(tool_name: str) -> list[AgentMiddleware]: + """Recovery + reminder for a model that doesn't call its submit tool — none with DEEP_AGENT_STRICT_SUBMIT.""" + if settings.DEEP_AGENT_STRICT_SUBMIT: + return [] + return [AnswerRecoveryMiddleware(), SubmitReminderMiddleware(tool_name)] + + +NOT_RUN = ("Not submitted: this SQL has not run successfully in this turn. Run it with execute_trino_query, check " + "its rows, have the semantic-validator review it, then submit it.") +NOT_REVIEWED = ("Not submitted: the semantic-validator has not reviewed this exact SQL (a SQL that passed review " + "and was then changed counts as not reviewed; formatting differences don't matter). Submit exactly the " + "SQL that passed, or send this one to the semantic-validator (task) — the SQL in a ```sql block and " + "your assumptions as '- ' lines — and submit after a pass.") + + +def _checks_text(checks: list[str]) -> str: + listed = "\n".join(f"- {c}" for c in checks) + return ("Not submitted: the semantic-validator asks for these checks before it can decide:\n" f"{listed}\n\n" + "Run them with execute_trino_query, then ask the semantic-validator to review the SQL again " + "(it will see the checks' results).") + + +def _failed_text(issues: list[dict[str, str]]) -> str: + listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) + return ("Not submitted: the semantic-validator failed this SQL:\n" f"{listed}\n\n" + "Fix it (run it, have it reviewed, submit), or — if you are sure it is right — submit the same SQL " + "with `validation_response` explaining why.") + + +_REVIEWED = ("pass", "fail", "needs_check") # verdicts of a completed review + + +class SubmitApprovalMiddleware(AgentMiddleware): + """Accept submit_answer only when the SQL has both approvals — recorded before the submit. + + 1. ran: the SQL matches a successful execute_trino_query in this turn (a sample counts) + 2. reviewed (when review is required): the latest semantic-validator verdict for this SQL is a pass — + or a fail and the agent gives `validation_response` (a dispute, recorded and shown to the user). + A needs_check verdict is not a pass: the agent runs the checks and asks for review again. + If DEEP_AGENT_VALIDATOR_MAX_ROUNDS reviews already ran this turn, the SQL is accepted as not validated. + + It only looks the records up; the judging happened before (the execution, the reviewer). A refused + submission's tool message says why and the model is sent back. + """ + + def __init__(self, require_review: bool, max_rounds: int | None = None) -> None: + super().__init__() + self.require_review = require_review + self.max_rounds = max_rounds + + @staticmethod + def _refuse(submission: ToolMessage, reason: str) -> dict[str, Any]: + refusal = ToolMessage(content=reason, tool_call_id=submission.tool_call_id, name=submission.name, + id=submission.id) # same id: replaces "Answer received." + return {"messages": [refusal], "structured_response": None, "jump_to": "model"} + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + submission = last_submission(state.get("messages") or []) + answer = state.get("structured_response") + if submission is None or submission.text != ANSWER_RECEIVED or answer is None: + return None + if getattr(answer, "needs_clarification", None) or not answer.sql: + return None + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + if match_execution(answer.sql, executed) is None: + return self._refuse(submission, NOT_RUN) + if not self.require_review: + return None + sql = normalize_sql(answer.sql) + records = list(state.get("semantic_validations") or []) + reviews = [r for r in records if r.get("sql") == sql and r["verdict"] in _REVIEWED] + if reviews and reviews[-1]["verdict"] == "pass": + return None + if reviews and reviews[-1]["verdict"] == "needs_check": + return self._refuse(submission, _checks_text(reviews[-1].get("checks") or [])) + if reviews: # failed + if getattr(answer, "validation_response", None): + return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "disputed", "sql": sql, + "issues": reviews[-1]["issues"], + "response": answer.validation_response}]} + return self._refuse(submission, _failed_text(reviews[-1]["issues"])) + done = sum(1 for r in records if r["verdict"] in _REVIEWED) + if self.max_rounds is not None and done >= self.max_rounds: + return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "skipped", "sql": sql, "issues": [], + "reason": f"review limit reached ({self.max_rounds})"}]} + return self._refuse(submission, NOT_REVIEWED) + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + +class AnswerVerificationMiddleware(AgentMiddleware): + """Bind each turn's structured answer to SQL executed in that turn and its real rows. + + before_agent clears the previous turn's structured answer (it would otherwise be reported + again on a turn that ends without a new one) and marks where this turn's executions start, + so an answer can only match SQL that ran in its own turn. + + after_model sends the model back after an invalid submit_answer call (arguments that fail the + schema). LangChain would retry on its own only while `structured_response` has never been set + in the thread; from the first reset on, it ends the run instead. + + after_agent keeps the answer only as plain data in final_result and drops the pydantic object: + checkpoints can't restore the dynamically built `submit_answer` class. + + has_reviewer: whether final_result gets a review summary — the reviewer is available ("always" or + "on_demand"); with review off it is None. + """ + + def __init__(self, has_reviewer: bool = False) -> None: + super().__init__() + self.has_reviewer = has_reviewer + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + submission = last_submission(state.get("messages") or []) + if submission is not None and submission.text != ANSWER_RECEIVED: + return {"jump_to": "model"} + return None + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"structured_response": None, "turn_execution_start": len(state.get("executed_queries") or [])} + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + final = verify_answer(state.get("structured_response"), executed) + final["recovered_from_text"] = any( + (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) + ) + records = state.get("semantic_validations") or [] if self.has_reviewer else None + final["semantic_validation"] = validation_summary(records, final.get("sql")) + return {"final_result": final, "structured_response": None} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return await asyncio.to_thread(self.after_agent, state, runtime) diff --git a/agent/src/deep_agent/answer/render.py b/agent/src/deep_agent/answer/render.py new file mode 100644 index 0000000..adae12e --- /dev/null +++ b/agent/src/deep_agent/answer/render.py @@ -0,0 +1,45 @@ +""" +The user-facing answer: Hebrew explanation, assumptions, a table built from Trino's rows (never from +model text), warnings, and the SQL. +""" + +from typing import Any + + +def _cell(value: Any) -> str: + return "" if value is None else str(value).replace("|", "\\|").replace("\n", " ") + + +def render_markdown(final_result: dict[str, Any]) -> str: + """User-facing Hebrew answer: explanation, table from real rows, SQL block.""" + answer = final_result.get("answer") or {} + if final_result.get("status") == "clarification": + return answer.get("needs_clarification") or answer.get("explanation_he", "") + parts = [answer.get("explanation_he", "")] + if answer.get("assumptions"): + parts.append("**הנחות:**\n" + "\n".join(f"- {a}" for a in answer["assumptions"])) + + result = final_result.get("result") + if result: + header = "| " + " | ".join(_cell(c) for c in result["columns"]) + " |" + sep = "|" + "---|" * len(result["columns"]) + body = ["| " + " | ".join(_cell(v) for v in row) + " |" for row in result["rows"]] + parts.append("\n".join([header, sep, *body])) + if result.get("truncated"): + parts.append(f"_מוצגות {result['row_count']} השורות הראשונות בלבד._") + elif final_result.get("status") == "no_answer": + reason = final_result.get("error") + parts.append("⚠️ לא התקבלה תשובה סופית" + (f": {reason}" if reason else ".")) + elif final_result.get("error"): + parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") + + review = final_result.get("semantic_validation") or {} + if review.get("verdict") in ("failed", "disputed") and review.get("issues"): + title = "בדיקה עצמאית מצאה בעיות בתשובה" if review["verdict"] == "failed" else "בדיקה עצמאית העלתה הסתייגות" + parts.append(f"⚠️ **{title}:**\n" + "\n".join(f"- {i['problem']}" for i in review["issues"])) + if review["verdict"] == "disputed" and review.get("response"): + parts.append(f"**תגובת הסוכן:** {review['response']}") + + if final_result.get("sql"): + parts.append(f"```sql\n{final_result['sql']}\n```") + return "\n\n".join(p for p in parts if p) diff --git a/agent/src/deep_agent/answer/schema.py b/agent/src/deep_agent/answer/schema.py new file mode 100644 index 0000000..a6542db --- /dev/null +++ b/agent/src/deep_agent/answer/schema.py @@ -0,0 +1,93 @@ +""" +The `submit_answer` tool: the format the model finishes with (LangChain ToolStrategy structured output). +""" + +from typing import Literal + +from langchain.agents.structured_output import ToolStrategy +from langchain_core.messages import ToolMessage +from pydantic import BaseModel, Field, create_model + +from agent.config import settings + +TOOL_NAME = "submit_answer" +# Content of the tool message for an accepted submission (anything else there is an error or a review's feedback). +ANSWER_RECEIVED = "Answer received." +_SUBMIT_DOC = "Submit your final answer. Call this exactly once, when you are done — it ends your work." + + +class _AnswerFields(BaseModel): + sql: str = Field( + min_length=1, + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query.", + ) + explanation_he: str = Field(description="Brief Hebrew explanation of what the SQL does and what the result means.") + assumptions: list[str] = Field( + default_factory=list, description="Interpretation choices you made (in Hebrew), e.g. which column means 'city'." + ) + confidence: Literal["high", "medium", "low"] = Field(description="Confidence that the SQL answers the question.") + + +# The final-answer tool. LangChain's ToolStrategy names the tool after the schema's __name__, so the +# model sees a tool called `submit_answer` (the "I'm done" submit convention). +SubmitAnswer = create_model(TOOL_NAME, __base__=_AnswerFields, __doc__=_SUBMIT_DOC) + +# Same tool name, plus the option to ask a clarifying question instead of answering. +SubmitAnswerWithClarification = create_model( + TOOL_NAME, + __base__=SubmitAnswer, + __doc__=_SUBMIT_DOC, + sql=(str | None, Field( + default=None, + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query. Null only when asking for clarification.", + )), + needs_clarification=(str | None, Field( + default=None, description="If the question is ambiguous, the clarifying question to ask the user (Hebrew).", + )), +) + + +_VALIDATION_RESPONSE = (str | None, Field( + default=None, + description="Only when the semantic-validator failed this SQL and you submit it anyway: why it is correct " + "despite the review (Hebrew).", +)) + + +def _with_validation_response(base: type[SubmitAnswer]) -> type[SubmitAnswer]: + return create_model(TOOL_NAME, __base__=base, __doc__=_SUBMIT_DOC, validation_response=_VALIDATION_RESPONSE) + + +_SCHEMAS: dict[tuple[bool, bool], type[SubmitAnswer]] = { + (False, False): SubmitAnswer, + (True, False): SubmitAnswerWithClarification, + (False, True): _with_validation_response(SubmitAnswer), + (True, True): _with_validation_response(SubmitAnswerWithClarification), +} + + +def answer_schema( + clarifications_enabled: bool | None = None, validation_enabled: bool | None = None +) -> type[SubmitAnswer]: + """The final-answer schema; without clarifications the model must always commit to a SQL answer. + + With semantic validation "always", it also has `validation_response` (to dispute a failed review). + """ + if clarifications_enabled is None: + clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED + if validation_enabled is None: + validation_enabled = settings.DEEP_AGENT_SEMANTIC_VALIDATION == "always" + return _SCHEMAS[(bool(clarifications_enabled), bool(validation_enabled))] + + +def submission_strategy(schema: type[BaseModel]) -> ToolStrategy: + """ToolStrategy whose accepted-submission tool message is ANSWER_RECEIVED (see accepted_submission).""" + return ToolStrategy(schema, tool_message_content=ANSWER_RECEIVED) + + +def last_submission(messages: list, tool_name: str = TOOL_NAME) -> ToolMessage | None: + """The tool message answering a submit call, when it is the latest message (i.e. the model just submitted).""" + last = messages[-1] if messages else None + return last if isinstance(last, ToolMessage) and last.name == tool_name else None diff --git a/agent/src/deep_agent/answer/verification.py b/agent/src/deep_agent/answer/verification.py new file mode 100644 index 0000000..24c1ad4 --- /dev/null +++ b/agent/src/deep_agent/answer/verification.py @@ -0,0 +1,153 @@ +""" +Binding the submitted answer to SQL that actually ran (final_result). + +The model finishes by calling the `submit_answer` tool (ToolStrategy structured output). +AnswerVerificationMiddleware then binds it to evidence. `final_result.executed` says whether +the final SQL ran and the rows shown are Trino's — it does NOT mean the answer was checked +to be semantically correct. + +- "matched": answer.sql equals (sqlglot-normalised) a query that executed successfully in + this turn -> the result rows are that execution's rows +- "re_executed": it matched only a sample (a smaller limit than the configured row ceiling) -> the same, + already approved SQL is run once more to show all its rows +- "re_execution_failed": that full-rows run failed -> not executed +- "not_executed": the SQL never ran in this turn (SubmitApprovalMiddleware refuses such a submission, + so this only marks a broken invariant) +- "clarification": the model asked a clarifying question instead of answering + (only possible when DEEP_AGENT_CLARIFICATIONS_ENABLED is on) + +The result table shown to users is always built from Trino rows, never from model text. +""" + +from typing import Any, Literal + +import sqlglot +from sqlglot.errors import SqlglotError + +from agent.config import settings +from agent.utils import sql_guard +from agent.utils.sql import clean_sql +from core.trino import execute_query_sync +from deep_agent.answer.schema import SubmitAnswer + +VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "not_executed", "clarification", + "no_answer"] + + +def normalize_sql(sql: str | None) -> str | None: + """Canonical form for comparing two SQL strings (whitespace, keyword case, comments, trailing ';', fences).""" + if not sql: + return None + cleaned = clean_sql(sql) + try: + return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino", comments=False) + except SqlglotError: + return " ".join(cleaned.split()) + + +def executed_query_record( + submitted_sql: str, executed_sql: str, payload: dict[str, Any], row_cap: int | None +) -> dict[str, Any]: + """State entry for one successful execution (see DeepAgentRuntimeState.executed_queries). + + row_cap is the ceiling that execution ran under (None = none), so verification can tell an + exploration sample (e.g. limit=5) from the full answer. + """ + return { + "submitted_sql": clean_sql(submitted_sql), + "executed_sql": executed_sql, + "columns": payload["columns"], + "rows": payload["rows"], + "row_count": payload["row_count"], + "truncated": payload["truncated"], + "query_id": payload.get("query_id"), + "row_cap": row_cap, + } + + +def match_execution(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: + target = normalize_sql(answer_sql) + for record in reversed(executed): # latest execution wins + if target in (normalize_sql(record["submitted_sql"]), normalize_sql(record["executed_sql"])): + return record + return None + + +def _is_sample(record: dict[str, Any]) -> bool: + """The matched execution was cut short by a smaller limit than the configured row ceiling.""" + if not record.get("truncated"): + return False + ceiling = settings.DEEP_AGENT_MAX_ROWS + cap = record.get("row_cap") + return cap is not None and (ceiling is None or cap < ceiling) + + +def _re_execute(answer_sql: str) -> tuple[VerificationStatus, dict[str, Any] | None, str | None]: + row_cap = settings.DEEP_AGENT_MAX_ROWS + try: + guarded = sql_guard.prepare(clean_sql(answer_sql), row_cap) + except sql_guard.GuardError as e: + return "rejected", None, str(e) + res = execute_query_sync(guarded.sql, reuse_connection=True) + if not res.success: + return "re_execution_failed", None, res.error_message + rows = res.rows or [] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] + payload = {"columns": res.columns, "rows": rows, "row_count": len(rows), "truncated": truncated, + "query_id": res.query_id} + return "re_executed", executed_query_record(answer_sql, guarded.sql, payload, row_cap), None + + +def _result_view(record: dict[str, Any]) -> dict[str, Any]: + return {k: record[k] for k in ("columns", "rows", "row_count", "truncated", "query_id")} + + +def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any]: + """Build `final_result` from the structured answer and the run's successful executions.""" + if not isinstance(answer, SubmitAnswer): + return {"status": "no_answer", "executed": False, "answer": None, "sql": None, "result": None, "error": None} + + base = {"answer": answer.model_dump(), "error": None} + if getattr(answer, "needs_clarification", None) or not answer.sql: + return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} + + record = match_execution(answer.sql, executed) + if record is None: + return {**base, "status": "not_executed", "executed": False, "sql": clean_sql(answer.sql), "result": None, + "error": "the submitted SQL did not run in this turn"} + if not _is_sample(record): + return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + status, record, error = _re_execute(answer.sql) # the approved SQL ran only as a sample: fetch all its rows + if record is None: + return {**base, "status": status, "executed": False, "sql": clean_sql(answer.sql), "result": None, "error": error} + return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + +_VERDICTS = {"pass": "passed", "fail": "failed", "disputed": "disputed"} + + +def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | None = None) -> dict[str, Any] | None: + """The review outcome of the final answer, from this turn's review records (None = review off). + + verdict: the latest record for the final SQL — passed | disputed (the agent submitted a failed SQL with a + justification) | failed | not_validated (no review of the final SQL, checks still pending, review limit, + or the review errored). + rounds: reviews this turn (any SQL). + """ + if records is None: + return None + rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail", "needs_check")) + summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, + "reviewed_final_sql": False} + target = normalize_sql(final_sql) + relevant = [r for r in records if target is not None and r.get("sql") == target] + if not relevant: + return {**summary, "reason": "no review of the final SQL"} + last = relevant[-1] + if last["verdict"] == "needs_check": + return {**summary, "reviewed_final_sql": True, "reason": "checks were requested and not reviewed again"} + return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated"), "issues": last.get("issues") or [], + "response": last.get("response"), "reason": last.get("reason"), "reviewed_final_sql": True} diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py new file mode 100644 index 0000000..ed4e20d --- /dev/null +++ b/agent/src/deep_agent/cli.py @@ -0,0 +1,280 @@ +""" +Interactive CLI for running the Deep Agent against Trino data. + +Usage: + uv run deep-agent "כמה טיסות המריאו מצרפת" + uv run deep-agent --interactive --session-memory + uv run deep-agent "..." --log-file runs/deep_agent_runs.jsonl +""" + +import argparse +import asyncio +import json +import time +import uuid +from dataclasses import asdict, dataclass +from datetime import datetime +from pathlib import Path + +from langchain_core.messages import BaseMessage + +from agent.config import settings +from agent.utils.jeen_metadata_client import close_mcp_sessions +from deep_agent.agent import create_deep_agent +from deep_agent import observability +from deep_agent.answer.render import render_markdown +from deep_agent.context import DeepAgentContext + +# ANSI Colors for terminal output +CYAN = "\033[96m" +GREEN = "\033[92m" +YELLOW = "\033[93m" +RED = "\033[91m" +MAGENTA = "\033[95m" +BLUE = "\033[94m" +WHITE = "\033[97m" +BOLD = "\033[1m" +DIM = "\033[2m" +RESET = "\033[0m" + +@dataclass +class RunRecord: + """One CLI run, written as a single JSONL line when --log-file is set.""" + + timestamp: str + execution_time_s: float + thread_id: str + question: str + final_sql: str | None + final_answer: str + verification: str + executed: bool + + +def _message_text(msg: BaseMessage) -> str: + """Plain text of a message whose content may be a str or a list of content blocks.""" + return msg.text if isinstance(msg, BaseMessage) else str(getattr(msg, "content", "")) + + +def append_run_record(log_file: Path, record: RunRecord) -> None: + log_file.parent.mkdir(parents=True, exist_ok=True) + with log_file.open("a", encoding="utf-8") as f: + f.write(json.dumps(asdict(record), ensure_ascii=False) + "\n") + + +def print_formatted_message(msg: BaseMessage) -> None: + msg_type = getattr(msg, "type", "") + + if msg_type == "human": + print(f"\n{YELLOW}{BOLD}{'═'*30} 👤 USER MESSAGE {'═'*30}{RESET}\n") + print(f"{YELLOW}{_message_text(msg)}{RESET}\n") + + elif msg_type == "ai": + print(f"\n{MAGENTA}{BOLD}{'═'*30} 🤖 AI MESSAGE {'═'*30}{RESET}\n") + + # 1. Print thoughts / text content + raw_content = msg.content + if isinstance(raw_content, list): + for block in raw_content: + if isinstance(block, dict): + if block.get("type") == "text": + print(f"{WHITE}{block.get('text', '')}{RESET}\n") + elif block.get("type") in ("thinking", "reasoning"): + thought = block.get("thinking") or block.get("reasoning") or "" + print(f"{DIM}💭 [Thinking]\n{thought}{RESET}\n") + else: + print(f"{WHITE}{block}{RESET}\n") + elif isinstance(raw_content, str) and raw_content.strip(): + print(f"{WHITE}{raw_content}{RESET}\n") + + # 2. Print tool calls + for tc in getattr(msg, "tool_calls", None) or []: + print(f"{CYAN}{BOLD}⚡ Tool Call: {tc.get('name', 'unknown_tool')}{RESET}") + tc_args = tc.get("args", {}) + if tc_args: + formatted_args = json.dumps(tc_args, indent=2, ensure_ascii=False, default=str) + indented_args = "\n".join(" " + line for line in formatted_args.splitlines()) + print(f"{WHITE}{indented_args}{RESET}\n") + + elif msg_type == "tool": + tool_name = getattr(msg, "name", "tool") or "tool" + content = _message_text(msg) + is_error = getattr(msg, "status", "") == "error" or content.strip().startswith("Error") + header_color = RED if is_error else BLUE + icon = "❌" if is_error else "🛠️ " + + print(f"\n{header_color}{BOLD}{'═'*30} {icon} TOOL: {tool_name} {'═'*30}{RESET}\n") + + # Truncate ONLY for get_database_catalog + lines = content.splitlines() + if tool_name == "get_database_catalog" and (len(lines) > 30 or len(content) > 1500): + preview = "\n".join(lines[:30]) if len(lines) > 30 else content[:1500] + print(f"{WHITE}{preview}{RESET}") + print( + f"\n{YELLOW}{BOLD}✂️ [Truncated full schema catalog for display: showing first 30 of " + f"{len(lines)} lines ({len(content):,} chars total)] ...{RESET}\n" + ) + else: + print(f"{WHITE}{content}{RESET}\n") + + else: + # Fallback for system or unexpected message types + print(f"\n{DIM}{'═'*30} {msg_type.upper() if msg_type else 'MESSAGE'} {'═'*30}{RESET}\n") + print(f"{WHITE}{_message_text(msg)}{RESET}\n") + + +async def run_query( + agent, question: str, thread_id: str, context: DeepAgentContext, log_file: Path | None = None +) -> None: + print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") + print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") + print(f"{DIM} Thread: {thread_id}{RESET}") + print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") + + config = observability.build_run_config( + thread_id, user_id=context.user_id, connection_id=context.connection_id + ) + + start_time = time.time() + final_state = None + printed_count = 0 + + async for state in agent.astream( + {"messages": [("user", question)]}, config, stream_mode="values", context=context + ): + messages = state.get("messages", []) + while printed_count < len(messages): + print_formatted_message(messages[printed_count]) + printed_count += 1 + final_state = state + + execution_time = round(time.time() - start_time, 2) + if not final_state or not final_state.get("messages"): + return + + final_result = final_state.get("final_result") or {"status": "no_answer", "executed": False} + final_sql = final_result.get("sql") + rendered = render_markdown(final_result) + trace_id = observability.langfuse_trace_id(config) + observability.score_run( + trace_id, observability.run_metrics(final_state["messages"], execution_time, final_result) + ) + + if log_file is not None: + append_run_record( + log_file, + RunRecord( + timestamp=datetime.now().isoformat(timespec="seconds"), + execution_time_s=execution_time, + thread_id=thread_id, + question=question, + final_sql=final_sql, + final_answer=rendered, + verification=final_result.get("status", "no_answer"), + executed=bool(final_result.get("executed")), + ), + ) + + print(f"\n{GREEN}{BOLD}{'='*30} FINAL ANSWER {'='*30}{RESET}\n") + print(f"{WHITE}{rendered}{RESET}\n") + status_color = GREEN if final_result.get("executed") else YELLOW + print( + f"{status_color}{BOLD}[Run finished] Execution time: {execution_time}s, " + f"verification: {final_result.get('status')}{RESET}" + ) + if trace_id: + print(f"{DIM} Langfuse trace: {trace_id}{RESET}") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent on Trino data.") + parser.add_argument("query", nargs="?", default="", help="The natural language question to run (Hebrew or English).") + parser.add_argument("--interactive", "-i", action="store_true", help="Run in interactive loop mode.") + parser.add_argument( + "--connection-id", "-c", type=int, default=None, + help="Jeen metadata connection ID (defaults to JEEN_METADATA_CONNECTION_ID from the environment).", + ) + parser.add_argument( + "--session-memory", "-m", + action="store_true", + help=( + "Share a single thread across all queries in this session. " + "The agent remembers prior questions and their outcomes within the session. " + "Default: each query gets a fresh thread (isolated, no cross-question memory)." + ), + ) + parser.add_argument( + "--log-file", type=Path, default=None, + help="Append one JSON line per run (question, SQL, answer, timing) to this file.", + ) + return parser + + +async def _amain(args: argparse.Namespace) -> None: + context = DeepAgentContext(connection_id=args.connection_id) + target_connection = args.connection_id or settings.JEEN_METADATA_CONNECTION_ID + + # Thread ID strategy: + # - With --session-memory: all queries share one thread → agent sees prior Q&A in context + # - Without (default): each query gets a unique thread → clean slate, no context bleed + session_thread_id = f"cli_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + + def next_thread_id() -> str: + return session_thread_id if args.session_memory else f"query_{uuid.uuid4().hex[:8]}" + + print(f"\n{MAGENTA}{BOLD}================================================================{RESET}") + print(f"{MAGENTA}{BOLD} DEEP AGENT CLI — TEXT2SQL RUNNER {RESET}") + print(f"{MAGENTA}{BOLD}================================================================{RESET}") + print(f" {CYAN}Target Connection:{RESET} ID {target_connection}") + print(f" {CYAN}MCP Endpoint:{RESET} {settings.JEEN_METADATA_MCP_URL}") + if args.session_memory: + print(f" {CYAN}Memory mode:{RESET} Session (queries share context — agent learns within session)") + print(f" {CYAN}Session thread:{RESET} {session_thread_id}") + else: + print(f" {CYAN}Memory mode:{RESET} Isolated (each query is independent — no context bleed)") + print(f"{MAGENTA}{BOLD}================================================================{RESET}\n") + + print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") + agent = create_deep_agent() + try: + await _run_questions(agent, args, context, next_thread_id) + finally: + await close_mcp_sessions() # the persistent Jeen MCP session lives as long as this event loop + + +async def _run_questions(agent, args: argparse.Namespace, context: DeepAgentContext, next_thread_id) -> None: + if args.interactive: + print(f"{GREEN}{BOLD}Starting Interactive Mode. Type 'quit', 'exit', or 'q' to stop.{RESET}") + while True: + try: + question = input(f"\n{YELLOW}{BOLD}[Deep Agent] Enter your query: {RESET}") + except (KeyboardInterrupt, EOFError): + break + + if not question.strip(): + continue + if question.strip().lower() in ("quit", "exit", "q"): + print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") + break + + await run_query(agent, question, next_thread_id(), context, args.log_file) + + elif args.query: + await run_query(agent, args.query, next_thread_id(), context, args.log_file) + + +def main() -> None: + parser = build_parser() + args = parser.parse_args() + if not args.interactive and not args.query: + print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}\n") + parser.print_help() + raise SystemExit(2) + try: + asyncio.run(_amain(args)) + finally: + observability.flush() + + +if __name__ == "__main__": + main() diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py new file mode 100644 index 0000000..9a396d1 --- /dev/null +++ b/agent/src/deep_agent/context.py @@ -0,0 +1,154 @@ +""" +Request-scoped runtime context and state for the Deep Agent. + +Nothing request-specific lives in module globals: +- DeepAgentContext is passed per invocation (`agent.ainvoke(..., context=DeepAgentContext(...))`) + and read by tools through `ToolRuntime.context`. +- The connection's catalog is loaded once per run by CatalogMiddleware (deep_agent.middleware.catalog) + into graph state (`jeen_catalog`) and read back by tools through `ToolRuntime.state`. +- Today's date is added to the latest human message on every model call, in the + context's timezone, so long-running processes never serve a stale date. +""" + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import datetime +from typing import Annotated, Any, NotRequired +from zoneinfo import ZoneInfo + +from langchain.agents.middleware import AgentMiddleware, AgentState, ModelRequest, ModelResponse +from langchain.tools import ToolRuntime +from langchain_core.messages import HumanMessage + +DEFAULT_TIMEZONE = "Asia/Jerusalem" + + +@dataclass(frozen=True) +class DeepAgentContext: + connection_id: int | None = None # Jeen metadata connection; None -> JEEN_METADATA_CONNECTION_ID + user_id: str | None = None + timezone: str = DEFAULT_TIMEZONE + + +# What tools receive as `runtime`: state, config, tool_call_id and our per-request context. +Runtime = ToolRuntime[DeepAgentContext] + + +def merge_executions(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] | None) -> list[dict[str, Any]]: + """Append-only reducer for executed_queries that ignores records already present. + + deepagents passes the parent's state into a subagent and returns the subagent's state as + an update; a plain list-append reducer would duplicate the parent's history on every + `task` call. + """ + merged = list(left or []) + seen = {(r.get("query_id"), r.get("executed_sql")) for r in merged} + for record in right or []: + key = (record.get("query_id"), record.get("executed_sql")) + if key not in seen: + merged.append(record) + seen.add(key) + return merged + + +def latest(left: Any, right: Any) -> Any: + """Last write wins. deepagents returns a subagent's whole state (minus messages) to the parent, so + parallel `task` calls write these keys in the same step; a plain key would reject that.""" + return right + + +def merge_reviews(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] | None) -> list[dict[str, Any]]: + """Reducer for semantic_validations: records are merged by their `id`; `None` resets the list. + + A subagent returns the list it was given plus its own record, and parallel reviews return in the + same step, so a plain value would either duplicate records or reject the concurrent writes. + """ + if right is None: + return [] + merged = list(left or []) + seen = {r.get("id") for r in merged} + for record in right: + if record.get("id") not in seen: + merged.append(record) + seen.add(record.get("id")) + return merged + + +class DeepAgentRuntimeState(AgentState): + jeen_catalog: NotRequired[Annotated[str, latest]] # the connection's catalog, loaded once per run (deep_agent.middleware.catalog) + executed_queries: NotRequired[Annotated[list[dict[str, Any]], merge_executions]] # successful executions + final_result: NotRequired[Annotated[dict[str, Any], latest]] # verified answer + rows (see deep_agent.answer.verification) + turn_execution_start: NotRequired[Annotated[int, latest]] # index into executed_queries where the current turn began + semantic_validations: NotRequired[Annotated[list[dict[str, Any]], merge_reviews]] # this turn's reviews (deep_agent.validator) + # The user's messages in this thread, oldest first, copied at the start of each turn. Subagents don't receive the + # conversation (deepagents leaves `messages` out of their state), so the reviewer reads the real request from here. + user_messages: NotRequired[Annotated[list[str], latest]] + + +# Name of the one-time "submit now" message (deep_agent.answer.middleware.SubmitReminderMiddleware): not the user's words. +REMINDER_NAME = "submit_reminder" + + +def is_user_message(msg: Any) -> bool: + """A message the user wrote (not the harness's submit reminder).""" + return isinstance(msg, HumanMessage) and getattr(msg, "name", None) != REMINDER_NAME + + +def current_turn(messages: list) -> list: + """Messages after the latest user message (this run's turn).""" + for i in range(len(messages) - 1, -1, -1): + if is_user_message(messages[i]): + return messages[i + 1:] + return messages + + +def connection_id(runtime: ToolRuntime | None) -> int | None: + ctx = getattr(runtime, "context", None) + return getattr(ctx, "connection_id", None) + + +def _now(tz: str) -> datetime: + return datetime.now(ZoneInfo(tz)) + + +def date_line(tz: str) -> str: + now = _now(tz) + return f"Today's date: {now.date().isoformat()} ({now.strftime('%A')}, timezone {tz})." + + +def _with_date(request: ModelRequest) -> ModelRequest: + """Prefix the latest user message with today's date for this model call only. + + The date is deliberately *not* put in the system message: deepagents appends its + skills section after user middleware, so a date there would sit mid-prompt and invalidate + provider prompt caching for everything after it every day. Here the system prompt stays + byte-identical and the change is transient (never written to graph state). + """ + ctx = getattr(request.runtime, "context", None) + line = date_line(getattr(ctx, "timezone", None) or DEFAULT_TIMEZONE) + messages = list(request.messages) + for i in range(len(messages) - 1, -1, -1): + msg = messages[i] + if is_user_message(msg): + content: Any = msg.content + if isinstance(content, str): + new_content: Any = f"[{line}]\n\n{content}" + else: + new_content = [{"type": "text", "text": f"[{line}]"}, *content] + messages[i] = msg.model_copy(update={"content": new_content}) + return request.override(messages=messages) + return request + + +class DeepAgentContextMiddleware(AgentMiddleware): + """Registers the runtime state keys and gives every model call today's date.""" + + state_schema = DeepAgentRuntimeState + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(_with_date(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(_with_date(request)) diff --git a/agent/src/deep_agent/middleware/__init__.py b/agent/src/deep_agent/middleware/__init__.py new file mode 100644 index 0000000..257b627 --- /dev/null +++ b/agent/src/deep_agent/middleware/__init__.py @@ -0,0 +1,9 @@ +""" +Cross-cutting middleware (runs around every model call). + +- catalog.py loads the connection's catalog once per turn and appends it to the system prompt +- tool_filter.py hides deepagents built-in tools we don't use + +Middleware that belongs to one concern lives with it: the answer pipeline in deep_agent.answer.middleware, +the reviewer in deep_agent.validator.modes, the request context and date in deep_agent.context. +""" diff --git a/agent/src/deep_agent/middleware/catalog.py b/agent/src/deep_agent/middleware/catalog.py new file mode 100644 index 0000000..39e103f --- /dev/null +++ b/agent/src/deep_agent/middleware/catalog.py @@ -0,0 +1,73 @@ +""" +Deterministic catalog loading for the Deep Agent. + +Every question needs the connection's catalog, so it is not a tool the model has to remember to +call: CatalogMiddleware loads it once at the start of each run (for the request's connection, +through the Jeen client's TTL cache) into graph state, and adds it to the system message of +every model call as a "Database Catalog" section after the static prompt. It is never written +into the message history, so it is not duplicated across turns. + +Without a catalog the agent cannot answer, so a failed load fails the run with a clear error. +""" + +import asyncio +from collections.abc import Awaitable, Callable +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse +from langchain_core.messages import SystemMessage + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from deep_agent.context import DeepAgentRuntimeState + +CATALOG_HEADER = "\n\n---\n\n# Database Catalog\n\nThe complete catalog of the connection you are answering against:\n\n" + + +class CatalogLoadError(RuntimeError): + """The connection's catalog could not be loaded; the run cannot proceed without it.""" + + +async def load_catalog(connection_id: int | None) -> str: + try: + catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id) + except Exception as exc: + raise CatalogLoadError(f"Could not load the database catalog for connection {connection_id}: {exc}") from exc + if not catalog or not str(catalog).strip(): + raise CatalogLoadError(f"The database catalog for connection {connection_id} is empty") + return str(catalog) + + +def _connection_id(runtime: Any) -> int | None: + return getattr(getattr(runtime, "context", None), "connection_id", None) + + +def _with_catalog(request: ModelRequest) -> ModelRequest: + catalog = (request.state or {}).get("jeen_catalog") + if not catalog or request.system_message is None: + return request + content = request.system_message.content + if isinstance(content, str): + new_content: Any = content + CATALOG_HEADER + catalog + else: + new_content = [*content, {"type": "text", "text": CATALOG_HEADER + catalog}] + return request.override(system_message=SystemMessage(content=new_content)) + + +class CatalogMiddleware(AgentMiddleware): + """Load the connection's catalog at the start of each run and show it to every model call.""" + + state_schema = DeepAgentRuntimeState + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return {"jeen_catalog": await load_catalog(_connection_id(runtime))} + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"jeen_catalog": asyncio.run(load_catalog(_connection_id(runtime)))} + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(_with_catalog(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(_with_catalog(request)) diff --git a/agent/src/deep_agent/middleware/tool_filter.py b/agent/src/deep_agent/middleware/tool_filter.py new file mode 100644 index 0000000..68af107 --- /dev/null +++ b/agent/src/deep_agent/middleware/tool_filter.py @@ -0,0 +1,35 @@ +""" +Hide deepagents built-in tools this agent never needs. + +Every model call carries the schema of every bound tool; dropping these saves ~1k prompt +tokens per call and removes off-task options: +- execute: always errors without a sandbox backend +- write_file / edit_file: skills and memory are read-only; planning goes through write_todos +- glob / grep / ls: the skills are listed in the prompt with their paths and read with read_file +""" + +from collections.abc import Awaitable, Callable + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse + +EXCLUDED_BUILTIN_TOOLS = frozenset({"execute", "write_file", "edit_file", "glob", "grep", "ls"}) + + +class BuiltinToolFilterMiddleware(AgentMiddleware): + """Remove excluded built-in tools from every model request.""" + + def __init__(self, excluded: frozenset[str] = EXCLUDED_BUILTIN_TOOLS) -> None: + super().__init__() + self.excluded = excluded + + def _filter(self, request: ModelRequest) -> ModelRequest: + tools = [t for t in request.tools if getattr(t, "name", None) not in self.excluded] + return request.override(tools=tools) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(self._filter(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(self._filter(request)) diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py new file mode 100644 index 0000000..8302227 --- /dev/null +++ b/agent/src/deep_agent/observability.py @@ -0,0 +1,176 @@ +""" +Langfuse tracing for the Deep Agent. + +- build_run_config(): the one RunnableConfig every deep-agent run (CLI and API) uses — + Langfuse CallbackHandler + session/user/tags metadata, so a run is exactly one trace. +- annotate_current_span(): structured metadata on the current tool observation. Only + reliable for *sync* tools: LangChain runs the (sync) Langfuse handler for async tools in + a copied context, so their span is not current inside the tool. Every tool therefore + also carries its telemetry in its envelope output, which Langfuse always records. +- run_metrics() / score_run(): end-of-run scores on the trace. +""" + +import logging +import os +from dataclasses import asdict, dataclass +from importlib.metadata import PackageNotFoundError, version +from typing import Any + +from langchain_core.callbacks import BaseCallbackHandler +from langchain_core.messages import BaseMessage +from langchain_core.runnables import RunnableConfig + +from agent.config import settings + +logger = logging.getLogger(__name__) + +AGENT_NAME = "deep-agent" + + +def agent_version() -> str: + """DEEP_AGENT_VERSION (e.g. the git SHA injected at build time), else the package version.""" + explicit = os.environ.get("DEEP_AGENT_VERSION") + if explicit: + return explicit + try: + return version("agent") + except PackageNotFoundError: + return "dev" + + +def _langfuse_handler() -> BaseCallbackHandler | None: + """A Langfuse callback bound to our project's keys. + + The keys live in agent settings (.env), not in the process environment, so a bare + CallbackHandler() would start a disabled client unless something else had already created a + keyed one (the legacy graph does; the CLI doesn't). Create our client, then bind to its key. + """ + try: + import agent.langfuse_client # noqa: F401 — creates the Langfuse client with settings' keys + from langfuse.langchain import CallbackHandler + + return CallbackHandler(public_key=settings.LANGFUSE_PUBLIC_KEY) + except Exception as exc: # tracing must never break a run + logger.warning("Langfuse tracing disabled: %s", exc) + return None + + +def build_run_config( + thread_id: str, + *, + user_id: str | None = None, + connection_id: int | None = None, + callbacks: list[BaseCallbackHandler] | None = None, + tracing: bool | None = None, +) -> RunnableConfig: + """RunnableConfig for one deep-agent invocation: one Langfuse trace per run, grouped by thread.""" + handlers = list(callbacks or []) + if tracing if tracing is not None else settings.DEEP_AGENT_TRACING_ENABLED: + handler = _langfuse_handler() + if handler is not None: + handlers.append(handler) + + metadata: dict[str, Any] = { + "langfuse_session_id": thread_id, + "langfuse_tags": [AGENT_NAME], + "agent": AGENT_NAME, + "agent_version": agent_version(), + "connection_id": connection_id if connection_id is not None else settings.JEEN_METADATA_CONNECTION_ID, + } + if user_id: + metadata["langfuse_user_id"] = user_id + if handlers: + from deep_agent.prompts.registry import load_prompt + + prompt = load_prompt("system") + if prompt.client is not None: + metadata["langfuse_prompt"] = prompt.client # links generations to the served prompt version + metadata["prompt_source"] = prompt.source + metadata["prompt_version"] = prompt.version + + return RunnableConfig( + configurable={"thread_id": thread_id}, + callbacks=handlers, + metadata=metadata, + tags=[AGENT_NAME], + run_name=AGENT_NAME, + ) + + +def langfuse_trace_id(config: RunnableConfig) -> str | None: + for handler in config.get("callbacks") or []: + trace_id = getattr(handler, "last_trace_id", None) + if trace_id: + return trace_id + return None + + +def annotate_current_span(metadata: dict[str, Any], level: str | None = None) -> None: + """Best-effort metadata on the current Langfuse observation (no-op without an active span).""" + if not settings.DEEP_AGENT_TRACING_ENABLED: + return + try: + from agent.langfuse_client import langfuse_client + + langfuse_client.update_current_span(metadata=metadata, level=level) + except Exception as exc: # telemetry must never break a tool + logger.debug("annotate_current_span skipped: %s", exc) + + +_REVIEWED = {"passed", "failed", "disputed"} # verdicts that judged the final SQL + + +@dataclass(frozen=True) +class RunMetrics: + """Plain counts and timing for one run, plus whether the submitted final SQL actually ran + (from the structured-answer verification in deep_agent.answer.verification).""" + + model_calls: int + tool_calls: int + sql_executions: int + latency_s: float + final_sql_executed: bool = False # the submitted final SQL ran and its rows are Trino's (not a correctness check) + # Independent review (deep_agent.validator). None -> no score: reviewer off, or the final SQL wasn't reviewed. + semantic_validation_passed: bool | None = None + validation_rounds: int | None = None # reviews this turn (0 = the agent didn't ask for one); None = reviewer off + + +def run_metrics(messages: list[BaseMessage], latency_s: float, final_result: dict | None = None) -> RunMetrics: + ai = [m for m in messages if m.type == "ai"] + review = (final_result or {}).get("semantic_validation") or {} + return RunMetrics( + model_calls=len(ai), + tool_calls=sum(len(getattr(m, "tool_calls", None) or []) for m in ai), + sql_executions=sum(1 for m in messages if m.type == "tool" and m.name == "execute_trino_query"), + latency_s=round(latency_s, 2), + final_sql_executed=bool(final_result and final_result.get("executed")), + semantic_validation_passed=(review["verdict"] == "passed") if review.get("verdict") in _REVIEWED else None, + validation_rounds=review.get("rounds", 0) if review else None, + ) + + +def score_run(trace_id: str | None, metrics: RunMetrics) -> None: + """Attach run-level scores to the Langfuse trace (no-op without a trace).""" + if not trace_id or not settings.DEEP_AGENT_TRACING_ENABLED: + return + try: + from agent.langfuse_client import langfuse_client + + for name, value in asdict(metrics).items(): + if value is None: + continue + data_type = "BOOLEAN" if isinstance(value, bool) else "NUMERIC" + langfuse_client.create_score( + trace_id=trace_id, name=f"{AGENT_NAME}.{name}", value=float(value), data_type=data_type + ) + except Exception as exc: + logger.warning("score_run failed for trace %s: %s", trace_id, exc) + + +def flush() -> None: + try: + from agent.langfuse_client import langfuse_client + + langfuse_client.flush() + except Exception as exc: + logger.debug("langfuse flush skipped: %s", exc) diff --git a/agent/src/deep_agent/prompts/__init__.py b/agent/src/deep_agent/prompts/__init__.py new file mode 100644 index 0000000..0356420 --- /dev/null +++ b/agent/src/deep_agent/prompts/__init__.py @@ -0,0 +1,4 @@ +""" +Prompts: system.md (main agent) and validator.md (reviewer), served by registry.py +(Langfuse `deep-agent/` when DEEP_AGENT_LANGFUSE_PROMPTS is on, else these packaged files). +""" diff --git a/agent/src/deep_agent/prompts/registry.py b/agent/src/deep_agent/prompts/registry.py new file mode 100644 index 0000000..b13e464 --- /dev/null +++ b/agent/src/deep_agent/prompts/registry.py @@ -0,0 +1,80 @@ +""" +Prompt management for the Deep Agent. + +Prompts are Langfuse text prompts named `deep-agent/` (`system`, `validator`), fetched by label (DEEP_AGENT_PROMPT_LABEL, default +"production") with the SDK's TTL cache. The packaged `prompts/.md` files are the +fallback when Langfuse is unreachable or the prompt doesn't exist, and the only source when +DEEP_AGENT_LANGFUSE_PROMPTS is off (tests, offline dev). + +The service rebuilds the agent when a prompt text changes (deep_agent.service.get_deep_agent), +so moving a label in Langfuse changes behaviour from the next request, without a redeploy; a run +keeps the prompt it started with. Push the packaged prompts with +`uv run python scripts/sync_deep_agent_prompts.py --label staging`. +""" + +import logging +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from agent.config import settings + +logger = logging.getLogger(__name__) + +PROMPTS_DIR = Path(__file__).resolve().parent # the .md files sit next to this module +PROMPT_KEYS = ("system", "validator") + + +def langfuse_name(key: str) -> str: + return f"deep-agent/{key}" + + +def local_prompt(key: str) -> str: + return (PROMPTS_DIR / f"{key}.md").read_text(encoding="utf-8") + + +@dataclass(frozen=True) +class LoadedPrompt: + key: str + text: str + source: str # "langfuse" | "local" + version: int | None = None + client: Any = None # langfuse TextPromptClient (links generations to the prompt version) + + +# key -> monotonic deadline until which Langfuse is not asked again (prompt missing / unreachable). +# The SDK caches successful fetches but not misses, and load_prompt runs on every request. +_misses: dict[str, float] = {} + + +def _miss(key: str, local: str) -> LoadedPrompt: + _misses[key] = time.monotonic() + max(settings.DEEP_AGENT_PROMPT_CACHE_TTL_S, 1) + return LoadedPrompt(key, local, "local") + + +def load_prompt(key: str) -> LoadedPrompt: + local = local_prompt(key) + if not settings.DEEP_AGENT_LANGFUSE_PROMPTS: + return LoadedPrompt(key, local, "local") + if _misses.get(key, 0.0) > time.monotonic(): + return LoadedPrompt(key, local, "local") + try: + from agent.langfuse_client import langfuse_client + + client = langfuse_client.get_prompt( + langfuse_name(key), + label=settings.DEEP_AGENT_PROMPT_LABEL, + type="text", + fallback=local, + cache_ttl_seconds=settings.DEEP_AGENT_PROMPT_CACHE_TTL_S, + fetch_timeout_seconds=5, + max_retries=1, + ) + except Exception as exc: + logger.warning("Langfuse prompt %s unavailable (%s); using packaged prompt", langfuse_name(key), exc) + return _miss(key, local) + if getattr(client, "is_fallback", False): + return _miss(key, local) + _misses.pop(key, None) + return LoadedPrompt(key, client.prompt, "langfuse", getattr(client, "version", None), client) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md new file mode 100644 index 0000000..e26f31f --- /dev/null +++ b/agent/src/deep_agent/prompts/system.md @@ -0,0 +1,219 @@ +You are an elite, autonomous Deep SQL Analyst. Your mission: translate natural-language questions (usually Hebrew, sometimes English) into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. You plan your own approach for each question and are responsible for delivering a correct answer. No shortcuts. + +--- + +## Non-negotiable Principle + +**Execution success ≠ correctness.** A query can run, return plausible-looking rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. Verify it throughout your work; don't execute and hope. (An independent check may run after you answer, but it never replaces your own verification.) + +--- + +## Phase 1 — Understand + +The connection's **complete catalog is included at the end of this prompt** ("Database Catalog"): every table with its exact 3-part name, every column with its type, `semantic_type`, distinct count, range and example values (all values when the domain is complete), plus the connection's knowledge pairs, business terms and relationships. You never need to fetch it. + +- Read the question against the catalog: which tables and columns hold the answer, how they join, and what each term in the question means. +- **Knowledge pairs** (prior solved question → SQL examples), when the catalog lists any, are the fastest path to the right join path, column conventions and domain logic — check them first. +- **Business terms** map the user's (Hebrew / domain) vocabulary to database terminology. +- **Relationships** are verified join paths. When none are listed, infer joins from matching column names (e.g. `customer_id`), and verify the key formats match (`get_sample_rows` on both sides). + +Simple, unambiguous lookups may skip directly to Phase 3. + +--- + +## Phase 2 — Ground the Query Semantics (MANDATORY for any JOIN or aggregation) + +Before writing a single line of SQL, answer these: + +1. **Output grain**: What does ONE result row represent (an order? a customer? a count per region?) — state it explicitly. If the grain doesn't match the question, every aggregation is wrong by construction. +2. **Aggregation unit**: Are you counting *rows* or *distinct entities*? If there's a JOIN, which side? +3. **Fan-out risk**: Does any JOIN create a 1-to-many relationship? If yes, `COUNT(*)` will be inflated — plan to use `COUNT(DISTINCT id)` or aggregate the child table in a CTE before joining. +4. **String filters**: Every text filter value must be resolved (Phase 3) — never guessed. +5. **Date column type**: Is it a native DATE/TIMESTAMP or a VARCHAR string? If string, it must be parsed (see the `temporal-analyst` skill). + +For complex or aggregation-heavy questions, write 1–2 lines stating the intent before drafting, e.g.: +> *"Intent: count distinct customers (not order rows) who ordered in 2024. customers↔orders is 1-to-many, so COUNT(DISTINCT c.customer_id), not COUNT(*)."* + +--- + +## Phase 3 — Value Resolution (by Semantic Type & Cardinality) + +The user's word is almost never the stored string — the value may be spelled differently, abbreviated, or stored in another language (a Hebrew question often filters values stored in English). Resolve every text filter value according to the column's `semantic_type`: + +> **Tool scope**: `search_column_values` indexes `large_categorical`, `large_unit_id`, `categorical` and `boolean` columns. `id`, numeric, date/timestamp, free-text and geometry columns are not indexed — a search on them (or on a table/column that doesn't exist) returns 0 results whatever the value. On an indexed column it returns the nearest stored values even when the term isn't in the data, so judge matches by their scores: a returned value is not proof the user's value exists. + +1. **High-cardinality (`large_categorical` / `large_unit_id`)** — e.g. customer, company or person names, product SKUs, city names: + - Too many values to list; use `search_column_values` with the user's term to find how the database actually spells the entity (e.g. "Acme Corp" → "Acme Corporation LLC"). Use the returned `value`s verbatim. A `keyword_similarity` close to 1.0 is a strong lexical match; a `semantic_distance` close to 0.0 is a strong semantic match. + - When several values match (e.g. "Acme Corporation LLC" and "Acme Corp Holdings", or "North Branch 1", "North Branch 2"), decide whether the question means one of them or all of them, and filter accordingly — `IN (...)` with the exact values, or a `LIKE 'prefix%'` that covers exactly those values. Record the choice in `assumptions`. + - When nothing matches, the value may not exist in the data — investigate before writing a filter that will return 0 rows. + - Don't call `get_column_distinct_values` on these columns — dumping 50–100 arbitrary values is slow (10–20s), wastes tokens, and rarely contains the entity you need. + +2. **Standard `categorical` & `boolean`** — e.g. status, priority, type, gender, active flags: + - `search_column_values` isn't needed for them — their value sets are small; use the catalog's values. + - Use the values listed in the catalog. When the catalog lists all values (the domain is complete), that list is definitive: any other string does not exist in the data. + - If the values aren't listed, `get_column_distinct_values` shows the full set (usually 5–20 rows). + +3. **Numeric, date, timestamp or geometry columns**: use the catalog's ranges, `get_sample_rows`, and casting / date parsing (see the `temporal-analyst` skill). Place names → `resolve_location_to_wkt` (see the `spatial-analyst` skill). + +--- + +## Phase 4 — Draft + +- **Use CTEs (`WITH ... AS (...)`)** — Trino handles them well, and they prevent common bugs: + 1. **Prevent join fan-out**: aggregate the child table in a CTE first, then join, instead of joining raw tables and fixing counts afterwards. + 2. **Break down multi-stage logic** into named blocks (`WITH filtered AS (...), per_entity AS (...)`), each with one responsibility, instead of deeply nested subqueries. + 3. **Window functions & ranking**: compute `ROW_NUMBER()` / `RANK() OVER (...)` in a CTE and filter on it (`WHERE rn <= 3`) in the outer query. + 4. **Parsing**: parse string dates (`date_parse(...)`) or geometries once in an early CTE so the rest of the query stays clean. +- SQL uses ONLY confirmed 3-part table names from the catalog: `"catalog"."schema"."table"`. +- **Final queries select only the columns needed** — no `SELECT *` (use `get_sample_rows` to peek at raw rows). +- **Filter early** — inside the innermost CTE. If the catalog marks a partition column (e.g. `dt`, `p_date`), always filter it in its native type to avoid full scans. +- `validate_sql` — optional dry-run by Trino (syntax, names, types; reads no data). For an invalid query `execute_trino_query` fails at the same step, just as fast and with the same error, so validating first usually saves nothing — use it only to check a draft you don't want to run yet. + +### Trino dialect essentials + +- **Identifiers vs strings**: double quotes for identifiers (`"catalog"."schema"."table"`, `"column"`), single quotes for string literals. Never backticks. `'column_name' = 'val'` compares two strings, not the column. +- **Integer division truncates** (`5 / 2 = 2`): for ratios and percentages use `CAST(a AS double) / NULLIF(b, 0)` — `NULLIF` also prevents division-by-zero errors. Decimal literals keep their scale: `avg(IF(cond, 1.0, 0.0))` returns `0.3`, not `0.3008` — use `CAST(count_if(cond) AS double) / count(*)` for a rate. +- **Counting**: `COUNT(*)` counts rows, `COUNT(col)` skips NULLs, `COUNT(DISTINCT col)` counts unique non-null values — count entities with `COUNT(DISTINCT id)`. `approx_distinct(x)` is a fast estimate on large tables. +- **Idioms**: `count_if(cond)` instead of `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`; `max_by(val, ts)` / `min_by(val, ts)` for the latest/earliest value per entity without a window or self-join. +- **NULLs**: `IS NULL` / `IS NOT NULL`, never `= NULL`. `AVG()` ignores NULLs — if NULL means zero, `AVG(COALESCE(col, 0))`; `COALESCE(SUM(...), 0)` when an empty group should be 0. +- **GROUP BY**: every non-aggregated `SELECT` column must be grouped. For distinct ordered values use `SELECT DISTINCT col ... ORDER BY col`. A `SELECT` alias can't be used in `GROUP BY` or `WHERE` (`COLUMN_NOT_FOUND`) — repeat the expression or use `GROUP BY 1`; `ORDER BY` may use the alias. +- **Top-N and ties**: for "the highest / the top", return ALL rows sharing the top value unless the user asks for exactly one — `RANK()` keeps ties; `ROW_NUMBER()` breaks them arbitrarily; `ORDER BY ... LIMIT n` for a plain top-N. +- **Joins**: every JOIN needs an explicit `ON` with keys (no cross joins). `INNER JOIN` when the relationship is guaranteed; `LEFT JOIN` for "per entity" metrics where some entities may have zero related rows; anti-join (`NOT EXISTS`, or `LEFT JOIN ... WHERE right.key IS NULL`) for entities with NO related rows — not `NOT IN (subquery)` when the key can be NULL. Trino's optimizer reorders joins when statistics exist; without them, put the large fact table on the left and the small lookup table on the right. +- **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. +- **Set operations**: prefer `UNION ALL`; `UNION` adds an expensive distributed de-duplication — use it only when de-duplication is required. +- **Arrays**: membership `contains(arr, 'v')`; expand with `CROSS JOIN UNNEST(arr) AS t(element)`. +- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`, `DATE '2024-07-01'`) — don't add a time zone and don't convert time zones yourself. +- **Coordinates**: `ST_Point(lon, lat)` and WKT are longitude first; `great_circle_distance(lat1, lon1, lat2, lon2)` is latitude first and returns km. Distances and areas on plain geometry are in degrees — wrap in `to_spherical_geography(...)` for metres. Details in the `spatial-analyst` skill. +- **When several logic paths seem plausible** (INNER vs LEFT JOIN, different grouping), run 2–3 variants with `LIMIT 10` and compare before choosing — don't guess. + +**Functions that do NOT exist in Trino:** + +| Do NOT write | Write in Trino instead | +|---|---| +| `ILIKE '%text%'` | `lower(col) LIKE lower('%text%')` or `regexp_like(col, '(?i)text')` | +| `DATEADD`, `DATE_SUB`, `ADDDATE` | `date_add('day', n, ts)` or `ts + INTERVAL '1' DAY` | +| `DATEDIFF(a, b)`, `TIMESTAMPDIFF` | `date_diff('day', a, b)` (unit, then start, then end) | +| `GETDATE()`, `SYSDATE` | `current_timestamp`, `now()`, `current_date` | +| `TO_DATE`, `STR_TO_DATE`, `TO_TIMESTAMP` | `date_parse`, `CAST`, `from_iso8601_timestamp` | +| `TO_CHAR`, `STRFTIME` | `format_datetime` (Joda patterns) or `date_format` (MySQL patterns) | +| `IFNULL`, `NVL`, `ISNULL` | `coalesce(a, b)` | +| `IIF`, `DECODE` | `CASE WHEN ...` or `if(cond, a, b)` | +| `TOP n` | `LIMIT n` (at the end of the query) | +| `LEN`, `CHARINDEX`, `INSTR` | `length(col)`, `strpos(col, 'sub')` | +| `MEDIAN`, `PERCENTILE_CONT` | `approx_percentile(x, 0.5)` | +| `GROUP_CONCAT`, `STRING_AGG` | `array_join(array_agg(x), ',')` | +| `array_contains(arr, val)` | `contains(arr, val)` | +| `ST_MakePoint`, `ST_GeomFromText` | `ST_Point(lon, lat)`, `ST_GeometryFromText(wkt)` | +| `ST_SetSRID`, `ST_Transform` | none needed (Trino geometry works directly on coordinates) | +| `ST_DWithin(a, b, r)` | `ST_Distance(to_spherical_geography(a), to_spherical_geography(b)) <= r` | +| `::type` (Postgres cast) | `CAST(x AS type)` | +| `INTERVAL 7 DAY` | `INTERVAL '7' DAY` (the value is a quoted string) | +| `EXTRACT(EPOCH FROM ts)` | `to_unixtime(ts)` | + +--- + +## Phase 5 — Execute & Diagnose + +- `execute_trino_query` — always LIMIT exploratory queries. +- Every tool returns `{"ok", "data", "error"}` — check `ok` first. For SQL failures, `error.name`, `error.type` and `error.message` are Trino's own, and `error.location` points at the offending line/column. +- **Read the error before changing anything**, and make a targeted fix: + +| Trino `error.name` / message / situation | Targeted fix | +|---|---| +| `SYNTAX_ERROR` (`mismatched input`, `extraneous input`) | Fix the specific line only — do not redesign. Typical causes: backticks (use `"`), `INTERVAL 1 DAY` (use `INTERVAL '1' DAY`), `::` casts | +| `TABLE_NOT_FOUND` / `SCHEMA_NOT_FOUND` / `CATALOG_NOT_FOUND` | Use the exact 3-part identifier from the catalog | +| `COLUMN_NOT_FOUND` | Re-check the column name and the table alias prefix against the catalog — or a `SELECT` alias used in `GROUP BY` / `WHERE` (repeat the expression, or `GROUP BY 1`) | +| `AMBIGUOUS_NAME` | Qualify the column with its table alias | +| `TYPE_MISMATCH` (`Cannot apply operator: timestamp = varchar`, `varchar = integer`) | `CAST` one side, use a typed literal (`TIMESTAMP '...'`), or quote the literal | +| `FUNCTION_NOT_FOUND` (`not registered`) | A non-Trino function — see the table above | +| `FUNCTION_NOT_FOUND` (`Unexpected parameters`) | The function exists; CAST the arguments to the expected types | +| `EXPRESSION_NOT_AGGREGATE` | Add the column to `GROUP BY` or wrap it in an aggregate | +| `INVALID_CAST_ARGUMENT` (`Value cannot be cast to timestamp`) | The text has `T` / `Z` or a custom format — `from_iso8601_timestamp(col)` or `date_parse(col, fmt)` | +| `INVALID_FUNCTION_ARGUMENT` (`Invalid format` in `date_parse`) | Wrong format specifiers — MySQL style, `%i` is minutes (not `%M`) | +| `INVALID_FUNCTION_ARGUMENT` (`Latitude must be between -90 and 90`) | Coordinates swapped — `ST_Point(lon, lat)`, longitude first | +| `FUNCTION_NOT_FOUND` (`Unexpected parameters (SphericalGeography...)` for `st_contains` etc.) | Containment needs geometry — keep `ST_Point` / `ST_GeometryFromText`, or `to_geometry(...)` a geography | +| `DIVISION_BY_ZERO` | Wrap the divisor in `NULLIF(divisor, 0)` | +| `SUBQUERY_MULTIPLE_ROWS` | Aggregate or `LIMIT 1` the scalar subquery, or turn it into a JOIN | +| `EXCEEDED_*` (memory / time limits) | Narrow the time or partition range, select fewer columns, pre-aggregate in a CTE | +| Missing partition filter | Filter the partition column in its native type | +| `error.type` other than `USER_ERROR` | A cluster / source-database problem, not necessarily your SQL — read the message before rewriting | +| 0 rows | Investigate, in order: string filter values (re-resolve them, Phase 3) → join key formats (`get_sample_rows` on both sides) → date range logic and column type → NULLs (`COUNT(*) FILTER (WHERE col IS NULL)`). Remove conditions one at a time to find the culprit | +| Count ≫ expected | Fan-out JOIN — `COUNT(DISTINCT id)` or aggregate before joining | +| Suspiciously round number / equals the table size | A Cartesian product (missing or wrong ON key), or a WHERE clause that filters nothing | + +- **Never retry an identical query** without a meaningful change. +- **Zero rows almost never means "no data"** — never answer with 0 rows without investigating why. + +--- + +## Phase 6 — Semantic Verification (MANDATORY for JOINs and aggregations) + +After a successful execution, validate before answering: + +- **Fan-out check** — if you joined and aggregated, compare the entity count before the join with the row count after it; if the second is larger, fan-out is confirmed → `COUNT(DISTINCT id)` or aggregate before joining: + ```sql + SELECT COUNT(*) FROM left_table WHERE + ``` + ```sql + SELECT COUNT(*) FROM left_table l JOIN right_table r ON l.id = r.left_id WHERE + ``` +- **Grain check** — does each result row represent the entity the user asked about? +- **Intent check** — translate your SQL back to plain language and compare it with the question, condition by condition: does every WHERE clause correspond to something the user said? Did you add or drop a condition? Is the GROUP BY at the right entity level? Are ties handled correctly (`RANK` vs `ROW_NUMBER` vs `LIMIT 1`)? Intent drift is a silent correctness killer. +- **Sanity check** — does the magnitude make sense? ("500 orders from 3 regions" is plausible; "10,000 distinct customers from a 1,000-row table" is not.) + +If any check fails or you're unsure, run a targeted diagnostic query. Do not guess. + +--- + +## Skills + +Before writing SQL in these areas, read the skill with `read_file`: `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry). + +--- + +## Tool Reference + +**Values & places** +- `search_column_values` — targeted value search, mainly for high-cardinality columns (see Tool scope, Phase 3). +- `get_column_distinct_values` — live distinct values of a low-cardinality `categorical` column (e.g. a `status` column) when the catalog doesn't list them. +- `resolve_location_to_wkt` — place name → area polygon (WKT) for `ST_GeometryFromText('...')`. + +**Execution** +- `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` / `location`. +- `get_sample_rows` — peek at raw data: formats, string casing, date formats. +- `validate_sql` — optional dry-run; not needed before executing. + +**Post-processing** + +**Delegation** +- `task` — spawn a subagent for heavy, separable exploration without filling your own context. + +--- + +## Hard Constraints + +- NEVER guess or assume a string filter value — resolve it (Phase 3). +- NEVER reference a table or column not in the catalog. +- ALWAYS use exact 3-part table names: `"catalog"."schema"."table"`. +- Read-only `SELECT` / `WITH` only; ALWAYS LIMIT exploratory queries. +- NEVER use `ST_GeomFromText()` — only `ST_GeometryFromText()` exists in Trino. +- NEVER use `ILIKE` (unsupported in Trino) — use `lower(col) LIKE lower('...')` or `regexp_like(col, '(?i)...')`. +- NEVER end queries with a semicolon `;`. +- NEVER wrap column identifiers in single quotes — single quotes are for string literals only. +- NEVER write SQL comments (`--` or `/* */`). +- Don't invent Hebrew aliases or identifiers; a Hebrew identifier is fine only when the catalog column itself is Hebrew (double-quote it). +- NEVER include the literal token `'kill'` anywhere in SQL. +- NEVER answer with 0 rows without first investigating why. +- NEVER retry an identical failed query without a meaningful change. + +--- + +## Final Answer + +When you have the answer, stop calling other tools and finish by calling `submit_answer` exactly once: +- `sql` — the exact final SQL you executed successfully with `execute_trino_query` (it is checked against your executions) +- `explanation_he` — a brief Hebrew explanation of what the SQL does and what the result means +- `assumptions` — interpretation choices you made (Hebrew) +- `confidence` — high / medium / low + +Do NOT type result tables — the rows shown to the user are taken directly from the executed query. diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md new file mode 100644 index 0000000..9571f06 --- /dev/null +++ b/agent/src/deep_agent/prompts/validator.md @@ -0,0 +1,49 @@ +You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and must have it approved before submitting it. You did not write this SQL and you do not see the analyst's reasoning. You get the user's own messages, the SQL, its result rows, and the analyst's interpretation choices — those are claims to check, not facts. Your job: decide whether this SQL actually answers what the user asked, on this database. + +You judge by reading. You don't run queries and you don't write SQL. The connection's complete catalog — every table and column with its type, description and example values — is included at the end of this prompt ("Database Catalog"). + +## How to review + +1. **Restate the request.** Read its exact wording before deciding the SQL got it wrong — e.g. "the last 30 days in the data" is relative to the data, not to today. In one sentence, what exactly is the user asking for? What should one output row represent (the grain)? Which conditions did the user state (entities, values, places, time ranges)? If there are several user messages, the last one is the current question and the earlier ones are its context (a follow-up such as "and from Italy?" keeps the earlier conditions and changes one). +2. **Read the SQL back in plain language** and compare it with the request, condition by condition: + - every condition the user stated is in the SQL, on the right column (check the catalog's column descriptions); + - the SQL adds no condition the user did not ask for (unless it is stated in the assumptions and reasonable); + - the output grain and the aggregation match the question ("how many X" counts X, not rows of a joined table; "per X" groups by X; "top N" orders by the right measure in the right direction); + - the selected columns are what the user asked for. + + How request wording usually maps to SQL, and what goes wrong: + + | The user says | Usually means | Watch for | + |---|---|---| + | "כמה" (how many) | `COUNT` of entities | `COUNT(*)` after a one-to-many join counts rows, not entities | + | "ממוצע" (average) | `AVG` | an average of per-group averages instead of over all rows; NULLs are ignored by `AVG` | + | "סה"כ" (total) | `SUM` | NULLs are skipped; an empty group gives NULL, not 0 | + | "הכי" / "הגבוה ביותר" (most / highest) | `ORDER BY … LIMIT` or `MAX` | ties: other rows with the same top value are silently dropped | + | "לכל" / "ל-" (per X, per capita) | a ratio at X's grain | numerator and denominator at different grains; integer division (`5 / 2 = 2`); division by zero | + | "לפי X" (by X) | `GROUP BY X` | grouped at a different level than X | + +3. **Look at the result rows.** Do they fit the question? 0 rows, a count equal to a whole table, an anti-join ("X with no Y") that removed nothing, or a long list cut off ("only part of the result") for a "top 2" question all mean something in the SQL is wrong or ineffective. +4. **Check the risky parts by reading:** + - **Filter values**: a text filter must use the value as it is stored — compare it with the values the catalog lists for that column. + - **Joins**: the join keys should hold the same kind of values. Compare the catalog's example values of both columns: if they look different (`ORD-000123` vs `123`, `Site-7` vs `Springfield`, codes vs names), the join can't match as written. An `INNER JOIN` also drops entities with no related rows, wrong for "per entity" results that should show zero. + - **Anti-joins**: `NOT IN (subquery)` returns nothing when the subquery has a NULL — `NOT EXISTS` or `LEFT JOIN … IS NULL` is safe. + - **Ties**: for "the most / the longest / the highest", if the SQL keeps only one row (`LIMIT 1`, `ROW_NUMBER() … = 1`, `max_by`), other rows may share the top value. Dropping tied rows the user didn't ask to drop is a fail. + - **Time ranges**: correct column, whole periods, relative dates against today's date given above. +5. **Check the interpretation choices**: each must be a reasonable reading of the request and consistent with the catalog. + +**Judge — don't solve.** Decide whether this SQL answers the request; don't design the correct SQL. Point briefly at the direction of a fix. + +## When to ask for a check (rarely) + +Most reviews are decided by reading. Ask for a check only when something you can see gives a concrete reason to doubt, and only data can settle it — for example: the catalog's examples suggest the two join keys hold different kinds of values but you can't be sure, the rows look implausible and you can't tell why, a filter value doesn't appear among the catalog's listed values, or ties are plausible and the rows don't show whether they exist. + +Don't ask for a check when a join's keys look consistent in the catalog (same name and kind of values), when an assumption is a reasonable reading, or when you can decide from what you have — a mismatch you can already see is a fail, not a check. Name each check specifically ("check whether the values of `table_a.col` match `table_b.col`"), never "verify the joins". After a check, you'll see the checks you asked for and the real results of the queries the analyst ran since — decide from them. + +## Verdict + +Call `submit_verdict` exactly once, when you are done: +- `verdict: "pass"` — the SQL correctly answers the request. An assumption may choose between reasonable readings of the request; it may not drop or replace part of what was asked. An answer that leaves out or substitutes part of the request fails, even when its assumptions say so. +- `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the exact part of the SQL, the rows, the catalog or the request that shows it). Write them in Hebrew. +- `verdict: "needs_check"` — only as described above, with `checks`: each specific check. + +Fail only for problems you can show. Style, formatting, performance, a different-but-equivalent way to write the SQL, or an extra column that doesn't change or mislead the answer are not problems. The "Notes on this answer" are facts our code detected — act on them. diff --git a/agent/src/deep_agent/resources.py b/agent/src/deep_agent/resources.py new file mode 100644 index 0000000..96e20ec --- /dev/null +++ b/agent/src/deep_agent/resources.py @@ -0,0 +1,102 @@ +""" +Skills wiring for the Deep Agent. + +Skills live on disk inside this package and are exposed to deepagents through a CompositeBackend: + + /skills//SKILL.md -> read-only FilesystemBackend over the skills dir + everything else -> ephemeral StateBackend (agent scratch files) + +Writes to /skills/ are denied via FilesystemPermission, so the agent can read its references +but never modify them. (There is no AGENTS.md memory: always-on guidance lives in the system +prompt, deep_agent/prompts/system.md.) +""" + +from dataclasses import dataclass +from pathlib import Path + +import yaml +from deepagents import FilesystemPermission +from deepagents.backends import CompositeBackend, FilesystemBackend, StateBackend + +from agent.config import settings + +PACKAGE_DIR = Path(__file__).resolve().parent +DEFAULT_SKILLS_DIR = PACKAGE_DIR / "skills" + +SKILLS_ROUTE = "/skills/" + +EXPECTED_SKILLS = frozenset({"temporal-analyst", "spatial-analyst"}) + + +class DeepAgentResourceError(RuntimeError): + """Skills are missing or malformed; the agent must not start without them.""" + + +@dataclass(frozen=True) +class DeepAgentResources: + backend: CompositeBackend + skills: list[str] + permissions: list[FilesystemPermission] + skill_names: frozenset[str] + + +def _read_frontmatter(skill_md: Path) -> dict: + text = skill_md.read_text(encoding="utf-8") + if not text.startswith("---"): + raise DeepAgentResourceError(f"{skill_md}: missing YAML frontmatter") + try: + _, frontmatter, _ = text.split("---", 2) + data = yaml.safe_load(frontmatter) + except (ValueError, yaml.YAMLError) as exc: + raise DeepAgentResourceError(f"{skill_md}: invalid YAML frontmatter ({exc})") from exc + if not isinstance(data, dict) or not data.get("name") or not data.get("description"): + raise DeepAgentResourceError(f"{skill_md}: frontmatter needs 'name' and 'description'") + return data + + +def discover_skills(skills_dir: Path) -> frozenset[str]: + """Validate the skills layout (//SKILL.md) and return the skill names.""" + if not skills_dir.is_dir(): + raise DeepAgentResourceError(f"Skills directory not found: {skills_dir}") + + names = set() + for skill_md in sorted(skills_dir.glob("*/SKILL.md")): + name = _read_frontmatter(skill_md)["name"] + if name != skill_md.parent.name: + raise DeepAgentResourceError( + f"{skill_md}: frontmatter name '{name}' must match its directory '{skill_md.parent.name}'" + ) + names.add(name) + + if not names: + raise DeepAgentResourceError(f"No skills found under {skills_dir} (expected /SKILL.md)") + return frozenset(names) + + +def build_resources( + skills_dir: Path | None = None, + expected_skills: frozenset[str] = EXPECTED_SKILLS, +) -> DeepAgentResources: + """Validate skills on disk and build the backend + create_deep_agent arguments. + + Fails fast (DeepAgentResourceError) instead of letting deepagents silently skip + missing files. + """ + skills_dir = Path(skills_dir or settings.DEEP_AGENT_SKILLS_DIR or DEFAULT_SKILLS_DIR).resolve() + + skill_names = discover_skills(skills_dir) + missing = expected_skills - skill_names + if missing: + raise DeepAgentResourceError(f"Missing required skills in {skills_dir}: {sorted(missing)}") + + backend = CompositeBackend( + default=StateBackend(), + routes={SKILLS_ROUTE: FilesystemBackend(root_dir=skills_dir, virtual_mode=True)}, + ) + permissions = [FilesystemPermission(operations=["write"], paths=[f"{SKILLS_ROUTE}**"], mode="deny")] + return DeepAgentResources( + backend=backend, + skills=[SKILLS_ROUTE], + permissions=permissions, + skill_names=skill_names, + ) diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py new file mode 100644 index 0000000..3f388fd --- /dev/null +++ b/agent/src/deep_agent/service.py @@ -0,0 +1,216 @@ +""" +Serving the Deep Agent behind the existing `chat_with_agent` MCP tool. + +- One agent per process (built lazily, shared by all requests); per-request data travels in + DeepAgentContext (connection, user) and the thread id. +- Durable threads: AsyncPostgresSaver when DEEP_AGENT_CHECKPOINT_DB_URL is set (shared by all + replicas, survives restarts), otherwise an in-memory saver. +- Streaming: the same Redis events the legacy graph publishes (`agent_stream:{thread_id}`, + {"thread_id", "node", "status"}), so the backend SSE relay and UI work unchanged. Nodes are + named `deep:` (e.g. deep:execute_trino_query), `deep:review:` for the independent + reviewer's tools (deep_agent.validator), plus `deep:answer`. +- Response: the legacy JSON contract (status / summary / sql_query / sql_explanation / + interrupt_details / trace_id / execution_path / is_unanswerable) plus `engine`, + `verification`, `executed`, `recovered_from_text`, `semantic_validation` and `confidence`. +- Run limit: none by default. A caller that stops waiting after N seconds passes `timeout_s`; + the run is then cancelled at that point (no tokens spent on an answer nobody receives). +- Clarification (only with DEEP_AGENT_CLARIFICATIONS_ENABLED): an answer with needs_clarification returns status "interrupted" with + interrupt_details {"type": "hitl_escalation", "subtype": "clarification", "reason": }, + which the UI already renders as a free-text prompt. The reply (resume_value) is sent as the + next user message on the same thread. +""" + +import asyncio +import logging +import time +from typing import Any +from uuid import UUID + +from langchain_core.callbacks import AsyncCallbackHandler +from langgraph.checkpoint.memory import MemorySaver + +from agent.config import settings +from agent.utils.redis_publisher import publish_node_event +from deep_agent import observability +from deep_agent.answer.render import render_markdown +from deep_agent.context import DeepAgentContext, current_turn +from deep_agent.prompts.registry import PROMPT_KEYS, load_prompt +from deep_agent.validator.reviewer import VALIDATOR_NAME + +logger = logging.getLogger(__name__) + +_agent = None +_agent_prompts: tuple[str, ...] | None = None # the prompt texts _agent was built with +_agent_lock: asyncio.Lock | None = None +_checkpointer = None +_pg_pool = None + +UNANSWERED = {"no_answer", "rejected", "re_execution_failed", "not_executed"} + + +async def build_checkpointer(): + """AsyncPostgresSaver over a process-wide pool when configured, else MemorySaver.""" + global _pg_pool + if not settings.DEEP_AGENT_CHECKPOINT_DB_URL: + logger.warning("DEEP_AGENT_CHECKPOINT_DB_URL not set — deep-agent threads are in-memory (lost on restart)") + return MemorySaver() + from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver + from psycopg.rows import dict_row + from psycopg_pool import AsyncConnectionPool + + _pg_pool = AsyncConnectionPool( + settings.DEEP_AGENT_CHECKPOINT_DB_URL, open=False, max_size=10, + kwargs={"autocommit": True, "prepare_threshold": 0, "row_factory": dict_row}, + ) + await _pg_pool.open() + saver = AsyncPostgresSaver(_pg_pool) + await saver.setup() # idempotent: creates/migrates the checkpoint tables + return saver + + +def _current_prompts() -> tuple[str, ...]: + """The prompt texts an agent is built from (Langfuse when enabled — SDK-cached — else the packaged .md).""" + return tuple(load_prompt(key).text for key in PROMPT_KEYS) + + +async def get_deep_agent(): + """The process-wide Deep Agent, rebuilt when one of its prompts changed (e.g. a Langfuse label moved). + + Checked per request, so a run keeps the prompt it started with and the next request gets the new one. + """ + global _agent, _agent_prompts, _agent_lock, _checkpointer + prompts = await asyncio.to_thread(_current_prompts) + if _agent is not None and prompts == _agent_prompts: + return _agent + if _agent_lock is None: + _agent_lock = asyncio.Lock() + async with _agent_lock: + if _agent is None or prompts != _agent_prompts: + from deep_agent.agent import create_deep_agent + + if _checkpointer is None: + _checkpointer = await build_checkpointer() + if _agent is not None: + logger.info("Deep agent prompts changed — rebuilding the agent") + _agent = create_deep_agent(checkpointer=_checkpointer) + _agent_prompts = prompts + return _agent + + +def reset_for_tests(agent=None) -> None: + global _agent, _agent_prompts, _agent_lock, _checkpointer + _agent, _agent_lock, _checkpointer = agent, None, None + _agent_prompts = _current_prompts() if agent is not None else None + + +class StreamPublisher(AsyncCallbackHandler): + """Publishes tool start/end to the legacy Redis stream and records the execution path.""" + + def __init__(self, thread_id: str) -> None: + self.thread_id = thread_id + self.execution_path: list[str] = [] + self._names: dict[UUID, str] = {} + + async def _publish(self, node: str, status: str) -> None: + await publish_node_event(self.thread_id, node, status) + + async def on_tool_start(self, serialized, input_str, *, run_id, tags=None, **kwargs) -> None: + tool = (serialized or {}).get("name") or kwargs.get("name") or "tool" + name = f"deep:review:{tool}" if VALIDATOR_NAME in (tags or []) else f"deep:{tool}" + self._names[run_id] = name + self.execution_path.append(name) + await self._publish(name, "active") + + async def on_tool_end(self, output, *, run_id, **kwargs) -> None: + await self._publish(self._names.pop(run_id, "deep:tool"), "completed") + + async def on_tool_error(self, error, *, run_id, **kwargs) -> None: + await self._publish(self._names.pop(run_id, "deep:tool"), "error") + + +def to_response(thread_id: str, final_result: dict[str, Any], trace_id: str | None, + execution_path: list[str]) -> dict[str, Any]: + answer = final_result.get("answer") or {} + status = final_result.get("status", "no_answer") + base = { + "thread_id": thread_id, + "engine": "deep", + "verification": status, + "executed": bool(final_result.get("executed")), + "recovered_from_text": bool(final_result.get("recovered_from_text")), + "semantic_validation": final_result.get("semantic_validation"), + "confidence": answer.get("confidence"), + "trace_id": trace_id, + "execution_path": execution_path, + } + if status == "clarification": + return { + **base, + "status": "interrupted", + "interrupt_details": { + "type": "hitl_escalation", + "subtype": "clarification", + "reason": answer.get("needs_clarification") or answer.get("explanation_he") or "", + }, + "sql_query": None, + } + return { + **base, + "status": "completed", + "summary": render_markdown({**final_result, "sql": None}), # SQL is returned separately + "raw_data_ref": None, + "sql_query": final_result.get("sql"), + "sql_explanation": answer.get("explanation_he"), + "is_unanswerable": status in UNANSWERED, + } + + +def _resume_text(resume_value: str | dict | None) -> str | None: + if isinstance(resume_value, str): + return resume_value + if isinstance(resume_value, dict): + return resume_value.get("feedback") or resume_value.get("answer") + return None + + +async def run_deep_chat( + *, + connection_id: int | None, + query: str | None = None, + thread_id: str, + resume_value: str | dict | None = None, + user_id: str | None = None, + timeout_s: float | None = None, + agent=None, +) -> dict[str, Any]: + """One chat turn on the Deep Agent, in the legacy chat_with_agent response shape. + + timeout_s: how long the caller will wait. The run is cancelled when it expires; None = no limit. + """ + message = query if resume_value is None else _resume_text(resume_value) + if not message: + return {"error": "Query is required for new chat session." if resume_value is None + else "resume_value must be the user's answer (a string or {'feedback': ...})."} + + agent = agent or await get_deep_agent() + context = DeepAgentContext(connection_id=connection_id, user_id=user_id) + publisher = StreamPublisher(thread_id) + config = observability.build_run_config(thread_id, user_id=user_id, connection_id=connection_id, + callbacks=[publisher]) + start = time.perf_counter() + try: + async with asyncio.timeout(timeout_s): # None = no limit + state = await agent.ainvoke({"messages": [("user", message)]}, config, context=context) + final_result = state.get("final_result") or {"status": "no_answer", "executed": False} + except TimeoutError: + logger.warning("deep agent run %s cancelled: the caller waits only %ss", thread_id, timeout_s) + state = (await agent.aget_state(config)).values + final_result = {"status": "no_answer", "executed": False, + "error": f"stopped after {timeout_s:g}s: the caller does not wait longer"} + + await publish_node_event(thread_id, "deep:answer", "completed") + trace_id = observability.langfuse_trace_id(config) + observability.score_run(trace_id, observability.run_metrics(current_turn(state.get("messages") or []), + time.perf_counter() - start, final_result)) + observability.flush() + return to_response(thread_id, final_result, trace_id, publisher.execution_path) diff --git a/agent/src/deep_agent/skills/spatial-analyst/SKILL.md b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md new file mode 100644 index 0000000..6c06232 --- /dev/null +++ b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md @@ -0,0 +1,173 @@ +--- +name: spatial-analyst +description: Geospatial query patterns for Trino, including Hebrew geographical extraction, per-location decision trees, polygon & point handling, proximity & directional filtering, and spatial join acceleration. +--- +# Spatial & Geographical SQL Reference for Trino + +## 1. Hebrew Location Extraction & Disambiguation Rules + +When analyzing user requests in Hebrew, apply these linguistic rules before resolving or searching: + +### A. Preposition Stripping vs. Structural Words +- **Strip grammatical prefixes**: `ב-`, `ל-`, `מ-`, `כ-`, `ו-` (e.g. `בבינת ג'בייל` → `בינת ג'בייל`, `מהר דב` → `הר דב`). +- **NEVER strip structural words that belong to the proper place name**: + - `אל-` (e.g. `אל-ח'יאם`) + - `כפר` (e.g. `כפר קאסם`, `כפר כנא`) + - `נחל` (e.g. `נחל קישון`, `נחל עיראק`) + - `הר` (e.g. `הר דב`, `הר חרמון`) + - `מחנה` (e.g. `מחנה נחשונים`, `מחנה בלאטה`) + - `ואדי` (e.g. `ואדי עארה`) + +### B. Expand Acronyms & Abbreviations +Expand geographical abbreviations before querying or resolving: +- `ת״א` → `תל אביב` +- `י-ם` → `ירושלים` +- `איו״ש` → `יהודה ושומרון` +- `ארה״ב` → `ארצות הברית` + +### C. Disambiguate Non-Geographical Entities (False Positives) +- **Sports Teams**: `מכבי חיפה`, `הפועל ירושלים` → organization names, NOT location filters (unless the query asks about games taking place *in* the city). +- **Restaurants / Venues**: `מסעדת אוסלו` → venue name, ignore for city extraction. +- **Personal Names**: `גולן ושרון קבעו פגישה` → people's names, not regions. + +### D. Comprehensive Geographical Scope +Locations are not just major cities. Recognize and extract: +- Populated cities, towns, villages (`כפרים`), kibbutzim, moshavim. +- Outposts, refugee camps (`מחנות פליטים`), military bases (`מחנות צבאיים`). +- Mountains, peaks, hills, valleys, rivers, wadis. +- Aggregate geopolitical regions (`עוטף עזה`, `גוש דן`, `דרום לבנון`, `בקעת הירדן`). + +--- + +## 2. The Nuanced Per-Location Decision Strategy + +Evaluate **EACH location mentioned in the query independently**. A single query may involve multiple locations that should be handled differently. + +``` +For EACH location mentioned: + +1. Proximity or Directional Query? ("סביב", "מצפון ל-", "ברדיוס") + ↳ Coordinates are inherently required (great_circle_distance or lat/lon condition). + +2. Regional Area / Agglomeration? ("גוש דן", "עוטף עזה", "הגליל העליון") + ↳ Text columns rarely contain these aggregate areas. + ↳ Call `resolve_location_to_wkt` and filter coordinate columns with `ST_Contains`. + +3. Specific City or Settlement? ("חיפה", "חאן יונס", "כפר קאסם") + ↳ Inspect candidate table: + • If an administrative column exists (`city_name`, `settlement`) AND contains the value: + Prefer direct text equality (fast, indexed, avoids boundary edge clipping). + • If the table ONLY has coordinates (`lat`/`lon`, `geom`): + Call `resolve_location_to_wkt` and filter spatially. + • If the city value cannot be found (catalog, `search_column_values` for large_categorical columns): + Fall back to `resolve_location_to_wkt`. + +4. The "No Blind OR" Rule: + • Do NOT write `city = 'Haifa' OR ST_Contains(...)` blindly as a lazy habit. + • ONLY combine with OR if the data is genuinely hybrid (e.g. telemetry tables where + some rows have manual city tags while others only have raw GPS sensor pings). +``` + +--- + +## 3. Handling Areas and Points + +`resolve_location_to_wkt(location_name)` geocodes a place (Hebrew names welcome) and returns **area geometries only** +(`POLYGON` / `MULTIPOLYGON`, simplified to fit in SQL). It never returns a point. `data.wkt` is the polygon as plain WKT — +wrap it in single quotes inside `ST_GeometryFromText('...')`. + +### A. Areas (cities, regions, districts) +```sql +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE ST_Contains(ST_GeometryFromText('POLYGON((34.75 32.05, 34.85 32.05, 34.85 32.12, 34.75 32.12, 34.75 32.05))'), + ST_Point(e.lon, e.lat)) +``` +On large tables, pre-filter with a cheap numeric bounding box first: +```sql +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE e.lat BETWEEN 32.05 AND 32.12 + AND e.lon BETWEEN 34.75 AND 34.85 + AND ST_Contains(ST_GeometryFromText('POLYGON((34.75 32.05, 34.85 32.05, 34.85 32.12, 34.75 32.12, 34.75 32.05))'), + ST_Point(e.lon, e.lat)) +``` + +### B. Points (landmarks, peaks, bases, user-given coordinates) +Points come from coordinates the user gives or from coordinate columns in a reference table — not from +`resolve_location_to_wkt`. A point has zero area, so "in / at / near" a landmark means a radius +(default ~500 m – 1 km; state the radius in `assumptions`): +```sql +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE great_circle_distance(e.lat, e.lon, 33.30, 35.75) <= 0.5 +``` +```sql +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE ST_Distance(to_spherical_geography(ST_Point(e.lon, e.lat)), + to_spherical_geography(ST_Point(35.75, 33.30))) <= 500 +``` +If the landmark is only known by name, `resolve_location_to_wkt` gives the surrounding area polygon; use its +centroid `ST_Centroid(ST_GeometryFromText(...))` as the point, and say so in `assumptions`. + +--- + +## 4. Proximity & Directional Intent Patterns + +When the user asks for relative spatial relations, translate the intent into precise coordinate math: + +| Phrasing | Semantic Meaning | Recommended SQL Pattern | +|---|---|---| +| **"ברדיוס X ק"מ מ..."** | Explicit radius distance | `great_circle_distance(lat, lon, target_lat, target_lon) <= X` | +| **"סביב..." / "באזור..." (for a Point/City)** | Implicit proximity | For a Point: `great_circle_distance(...) <= 1.0` (1 km)
For a Polygon: `ST_Contains(...)` or buffer $\le 2\text{ km}$ | +| **"מצפון ל..."** (North of) | Directional filter | `lat > target_lat` (with reasonable lon bounding box) | +| **"מדרום ל..."** (South of) | Directional filter | `lat < target_lat` (with reasonable lon bounding box) | +| **"ממזרח ל..." / "ממערב ל..."** | Directional filter | `lon > target_lon` / `lon < target_lon` | + +--- + +## 5. Critical Coordinate Order & Syntax Rules + +- **`ST_Point(lon, lat)`**: **LONGITUDE FIRST** ($X = \text{lon}, Y = \text{lat}$). +- **WKT format**: also **`POINT(lon lat)`** — e.g. `'POINT(34.78 32.08)'` (Tel Aviv). +- **`great_circle_distance(lat1, lon1, lat2, lon2)`**: **LATITUDE FIRST**, and returns **km**. +- **`bing_tile_at(lat, lon, zoom)`**: **LATITUDE FIRST**. +- **Israel Sanity Check**: In Israel, Longitude $\approx 34\text{--}36$ and Latitude $\approx 29\text{--}33$. If coordinates show `lon: 32` and `lat: 34`, they are accidentally inverted! + +### Geometry Functions +- **Always**: `ST_GeometryFromText(wkt_string)` +- **Never**: `ST_GeomFromText()` or `ST_PolygonFromText()` — they do not exist in Trino. +- `ST_Distance` on WGS84 geometries returns **degrees**, not meters. For meters, wrap both sides in `to_spherical_geography(...)`. +- `ST_Contains` works on `geometry` (degrees), **NOT** on `SphericalGeography`. +- `ST_Buffer(geom, r)` takes **degrees**: `ST_Buffer(p, 0.01)` is about 1 km, not 0.01 km. For "within X metres" use a + distance in metres (`great_circle_distance` or spherical `ST_Distance`) instead of a buffer. +- Area / length in real units: `ST_Area(to_spherical_geography(g)) / 1e6` is km², `ST_Length(to_spherical_geography(g))` is metres. + +### Parsing geometries +- WKT text → `ST_GeometryFromText(col)`; unparsable rows → `try(ST_GeometryFromText(col))` and skip the NULLs. +- WKB hex string → `ST_GeomFromBinary(from_hex(col))`. +- GeoJSON text → `from_geojson_geometry(col)` returns a **SphericalGeography**: for `ST_Contains` and other geometry + functions wrap it, `to_geometry(from_geojson_geometry(col))`. + +### Performance +- **Cheap bounding box first**: filter the raw numeric `lat` / `lon` columns with `BETWEEN` before any `ST_` function or + distance. Around Israel, 1° latitude ≈ 111 km and 1° longitude ≈ 94 km. +- Filter time (and other plain conditions) in a CTE first, so the spatial join only sees the rows it needs. +- Large point-to-point proximity joins: join on a bing tile first, then check the exact distance + (`bing_tile_quadkey(bing_tile_at(lat, lon, 15))` on both sides; pairs across tile edges need `bing_tiles_around`). + +```sql +SELECT e.event_id, great_circle_distance(e.lat, e.lon, 32.08, 34.78) AS dist_km +FROM "catalog"."schema"."events" e +WHERE e.lat BETWEEN 32.05 AND 32.11 + AND e.lon BETWEEN 34.74 AND 34.82 + AND great_circle_distance(e.lat, e.lon, 32.08, 34.78) <= 3 +ORDER BY dist_km +``` + +### Spatial Joins Acceleration +Put `ST_Contains` directly in the `JOIN ... ON` clause so Trino invokes its internal spatial join optimization: +```sql +SELECT z.zone_name, count(*) AS event_count +FROM "catalog"."schema"."events" e +JOIN "catalog"."schema"."zones" z + ON ST_Contains(ST_GeometryFromText(z.wkt), ST_Point(e.lon, e.lat)) +GROUP BY z.zone_name +``` diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md new file mode 100644 index 0000000..c85c72c --- /dev/null +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -0,0 +1,159 @@ +--- +name: temporal-analyst +description: Trino date and time handling — use when queries involve timestamps, date filtering, relative time expressions (including Hebrew ones), date parsing from strings, or time zone conversions. +--- +# Temporal SQL Reference for Trino + +## Step 1 — Know the column type + +Check the column's type in the catalog before writing any date filter: + +- **Native `date` / `timestamp`** → compare the column directly against date/timestamp literals with half-open + ranges. Never wrap it in a function in `WHERE` (that defeats partition pruning and min/max statistics). +- **`varchar` / text** → the value must be parsed first. Identify the format from example values or + `get_sample_rows`, parse once (ideally in a CTE), then filter the parsed value. + +| Example value | Format | Parse function | +|--------------|--------|----------------| +| `2024-01-15` | ISO date | `CAST(col AS DATE)` or `from_iso8601_date(col)` | +| `2024-01-15 14:30:00` | ISO datetime | `CAST(col AS TIMESTAMP)` | +| `2024-01-15T14:30:00` | ISO 8601 with T | `from_iso8601_timestamp(col)` | +| `2024-01-15T14:30:00Z` | ISO 8601 UTC | `from_iso8601_timestamp(col)` | +| `15/01/2024` | DD/MM/YYYY | `date_parse(col, '%d/%m/%Y')` | +| `01/15/2024` | MM/DD/YYYY | `date_parse(col, '%m/%d/%Y')` | +| `15-Jan-2024` | Text month | `date_parse(col, '%d-%b-%Y')` | +| `20240115` | YYYYMMDD | `date_parse(col, '%Y%m%d')` | +| `1705312200` | Unix seconds | `from_unixtime(CAST(col AS BIGINT))` | +| `1705312200000` | Unix milliseconds | `from_unixtime(CAST(col AS BIGINT) / 1000.0)` | +| `2024-01-15 14:30:00.000` | With milliseconds | `date_parse(col, '%Y-%m-%d %H:%i:%s.%f')` | + +`date_parse` uses MySQL-style specifiers: `%i` is minutes, `%s` seconds, `%H` 24-hour. + +--- + +## Step 2 — Filter with half-open ranges + +```sql +SELECT count(*) FROM "catalog"."schema"."events" +WHERE event_at >= TIMESTAMP '2024-05-01 00:00:00' + AND event_at < TIMESTAMP '2024-05-02 00:00:00' +``` + +```sql +SELECT count(*) FROM "catalog"."schema"."events" +WHERE event_date >= DATE '2023-01-01' + AND event_date < DATE '2024-01-01' +``` + +For VARCHAR columns, parse in a CTE and filter the parsed value the same way: + +```sql +WITH parsed AS ( + SELECT e.*, date_parse(e.created_str, '%d/%m/%Y') AS created_at + FROM "catalog"."schema"."events" e +) +SELECT count(*) FROM parsed +WHERE created_at >= TIMESTAMP '2024-01-01 00:00:00' + AND created_at < TIMESTAMP '2024-02-01 00:00:00' +``` + +Avoid `BETWEEN '2024-01-01' AND '2024-01-31'` on timestamps — it misses everything after midnight on the 31st. + +--- + +## Relative dates + +`INTERVAL` values must be quoted string literals: `INTERVAL '1' DAY`, `INTERVAL '3' MONTH` +(never `INTERVAL 1 DAY` or `INTERVAL '1 day'`). `current_date`, `current_timestamp` and `now()` are all valid. + +| Period | Sargable filter on a native column `d` | +|---|---| +| Today | `d >= current_date AND d < current_date + INTERVAL '1' DAY` | +| Yesterday | `d >= current_date - INTERVAL '1' DAY AND d < current_date` | +| Last 7 days (rolling) | `d >= current_date - INTERVAL '7' DAY` | +| This month | `d >= date_trunc('month', current_date) AND d < date_trunc('month', current_date) + INTERVAL '1' MONTH` | +| Last month | `d >= date_trunc('month', current_date) - INTERVAL '1' MONTH AND d < date_trunc('month', current_date)` | +| This year | `d >= date_trunc('year', current_date) AND d < date_trunc('year', current_date) + INTERVAL '1' YEAR` | +| Last 12 months | `d >= current_date - INTERVAL '12' MONTH` | + +--- + +## Hebrew temporal expressions + +The Israeli week starts on **Sunday**, but Trino's `date_trunc('week', ...)` returns **Monday**. Sunday-based week start: +`date_add('day', -(day_of_week(current_date) % 7), current_date)` (`day_of_week`: Monday = 1 … Sunday = 7). + +| Hebrew | Meaning | Filter on a native column `d` | +|--------|---------|-------------------------------| +| "היום" | today | `d >= current_date AND d < current_date + INTERVAL '1' DAY` | +| "אתמול" | yesterday | `d >= current_date - INTERVAL '1' DAY AND d < current_date` | +| "השבוע" | this week (Sun–Sat) | `d >= date_add('day', -(day_of_week(current_date) % 7), current_date)` | +| "השבוע שעבר" | last week (Sun–Sat) | `d >= date_add('day', -(day_of_week(current_date) % 7) - 7, current_date) AND d < date_add('day', -(day_of_week(current_date) % 7), current_date)` | +| "החודש" | this month | see "This month" above | +| "החודש שעבר" | last month | see "Last month" above | +| "השנה" | this year | see "This year" above | +| "ב-2023" | in 2023 | `d >= DATE '2023-01-01' AND d < DATE '2024-01-01'` | +| "בינואר 2024" | January 2024 | `d >= DATE '2024-01-01' AND d < DATE '2024-02-01'` | +| "ברבעון הראשון 2024" | Q1 2024 | `d >= DATE '2024-01-01' AND d < DATE '2024-04-01'` | +| "ב-12 החודשים האחרונים" | last 12 months | `d >= current_date - INTERVAL '12' MONTH` | +| "לפני X ימים" | X days ago | `d >= current_date - INTERVAL 'X' DAY AND d < current_date - INTERVAL 'X' DAY + INTERVAL '1' DAY` | +| "בשבועיים הראשונים של מרץ 2025" | March 1–14, 2025 | `d >= DATE '2025-03-01' AND d < DATE '2025-03-15'` | + +If a month is given without a year, assume the most recent past occurrence relative to today and state it in `assumptions`. + +--- + +## Grouping by period (SELECT / GROUP BY — functions are fine here) + +```sql +SELECT date_trunc('month', event_at) AS month, count(*) AS events +FROM "catalog"."schema"."events" +GROUP BY 1 +ORDER BY 1 +``` + +`year(d)`, `month(d)`, `day_of_week(d)` and `extract(year FROM d)` are fine in `SELECT` and `GROUP BY` — just not in +`WHERE` on a native column you are filtering. + +--- + +## Time zones + +Write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`) and use `current_date` / `current_timestamp` as they are. +Don't add zones to literals and don't convert time zones by hand. (Only if a column is a naive `timestamp` documented as +UTC: `with_timezone(col, 'UTC')` before comparing.) + +--- + +## Durations + +```sql +SELECT date_diff('day', start_date, end_date) AS days, + date_diff('hour', started_at, ended_at) AS hours +FROM "catalog"."schema"."trips" +``` + +Unit first, then start, then end. + +--- + +## Defensive parsing + +`try_cast(col AS DATE)` and `try(date_parse(col, '%d/%m/%Y'))` return NULL instead of failing on malformed values. +When the format is unknown, look before parsing: + +```sql +SELECT DISTINCT created_str FROM "catalog"."schema"."events" LIMIT 20 +``` + +--- + +## Common mistakes + +- `WHERE ts_col = '2024-01-15'` on a timestamp — matches only midnight, not the whole day. +- `WHERE date(ts_col) = DATE '2024-05-01'` — correct but not sargable; use a half-open range. +- Wrong `date_parse` format string — returns an error or NULL; `%i` (not `%M`) is minutes. +- `DATEDIFF(a, b)` does not exist — use `date_diff('day', a, b)`. +- `date_format(ts, '%Y-%m')` (MySQL-style specifiers) and `format_datetime(ts, 'yyyy-MM')` (Joda-style patterns) + both exist; don't mix the two pattern styles. +- `date_trunc('week', ...)` is Monday-based — use the Sunday formula above for Hebrew "השבוע". diff --git a/agent/src/deep_agent/tools/__init__.py b/agent/src/deep_agent/tools/__init__.py new file mode 100644 index 0000000..532c34e --- /dev/null +++ b/agent/src/deep_agent/tools/__init__.py @@ -0,0 +1,29 @@ +""" +The Deep Agent's tools. + +Every tool returns the same JSON envelope (deep_agent.tools.envelope): + {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} + +- sql.py execute_trino_query, get_sample_rows, get_column_distinct_values, validate_sql +- metadata.py search_column_values +- location.py resolve_location_to_wkt + +The connection's catalog is not a tool: CatalogMiddleware (deep_agent.middleware.catalog) loads it +for every run and puts it in the prompt. +""" + +from deep_agent.tools.location import resolve_location_to_wkt +from deep_agent.tools.metadata import search_column_values +from deep_agent.tools.sql import execute_trino_query, get_column_distinct_values, get_sample_rows, validate_sql + +# The tools the model gets (order = order shown to the model). +DEEP_AGENT_TOOLS = [ + # Values & places + search_column_values, + get_column_distinct_values, + resolve_location_to_wkt, + # Query execution + execute_trino_query, + get_sample_rows, + validate_sql, +] diff --git a/agent/src/deep_agent/tools/envelope.py b/agent/src/deep_agent/tools/envelope.py new file mode 100644 index 0000000..af403d0 --- /dev/null +++ b/agent/src/deep_agent/tools/envelope.py @@ -0,0 +1,34 @@ +""" +The single return contract for every Deep Agent tool: + + {"ok": true, "data": , "error": null} + {"ok": false, "data": null, "error": {"name", "message", ...details}} + +error.name is Trino's own errorName for SQL failures (see deep_agent.tools.trino_errors), or one of +the names below for failures of our own tools. + +Serialised compactly (no indentation whitespace, raw Unicode) to keep tool output tokens low. +""" + +import json +from typing import Any + +METADATA_ERROR = "METADATA_ERROR" # the Jeen metadata service failed or returned an unexpected payload +LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND" # the location could not be resolved to an area + + +def _dumps(payload: dict) -> str: + return json.dumps(payload, ensure_ascii=False, separators=(",", ":"), default=str) + + +def ok(data: Any) -> str: + return _dumps({"ok": True, "data": data, "error": None}) + + +def error(name: str, message: str, **details: Any) -> dict: + """An `error` object: name + message, plus any details that are not None.""" + return {"name": name, "message": message, **{k: v for k, v in details.items() if v is not None}} + + +def fail(err: dict) -> str: + return _dumps({"ok": False, "data": None, "error": err}) diff --git a/agent/src/deep_agent/tools/location.py b/agent/src/deep_agent/tools/location.py new file mode 100644 index 0000000..7e6c669 --- /dev/null +++ b/agent/src/deep_agent/tools/location.py @@ -0,0 +1,37 @@ +""" +resolve_location_to_wkt: a place name (Hebrew or English) to its area polygon as WKT, via Nominatim. +""" + +from langchain_core.tools import tool + +from agent.services.geo_utils import geojson_to_simplified_wkt, get_geojson_polygon +from deep_agent.tools.envelope import LOCATION_NOT_FOUND, error, fail, ok + + +@tool +def resolve_location_to_wkt(location_name: str) -> str: + """ + Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. + + Use this whenever the user's query involves a geographic area and you need a WKT polygon for + a Trino ST_GeometryFromText() / ST_Within() / ST_Contains() call. + + Supports Hebrew location names directly (e.g., 'תל אביב', 'ירושלים', 'חיפה'). + Returns data.wkt — the polygon as plain (unquoted) WKT, e.g. POLYGON((...)). In SQL, wrap it + in single quotes: ST_GeometryFromText(''). + + The function uses rate-limited Nominatim geocoding with caching and automatic WKT + simplification (binary search). Only area geometries are returned (never points). + + Do NOT use this for exact addresses (e.g., "Rothschild 10, Tel Aviv"); it is designed for + administrative areas: cities, regions, districts, and countries. + + Args: + location_name (str): The geographic location name to resolve. Hebrew names are + accepted and preferred for Israeli locations. + """ + geojson = get_geojson_polygon(location_name) + quoted = geojson_to_simplified_wkt(geojson) if geojson else None # returns a single-quoted literal + if not quoted: + return fail(error(LOCATION_NOT_FOUND, f"Could not resolve location '{location_name}' to an area polygon.")) + return ok({"location": location_name, "wkt": quoted.strip("'")}) diff --git a/agent/src/deep_agent/tools/metadata.py b/agent/src/deep_agent/tools/metadata.py new file mode 100644 index 0000000..d2aeced --- /dev/null +++ b/agent/src/deep_agent/tools/metadata.py @@ -0,0 +1,107 @@ +""" +Metadata tools: value search, from the Jeen metadata service. + +The connection's catalog itself is not a tool: it is loaded for every run and shown to the +model by CatalogMiddleware (deep_agent.middleware.catalog). +""" + +import logging +from typing import Any, Optional + +from langchain_core.tools import tool + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from deep_agent.context import Runtime, connection_id +from deep_agent.tools.envelope import METADATA_ERROR, error, fail, ok + +logger = logging.getLogger(__name__) + + +def metadata_failure(what: str, exc: Exception) -> str: + logger.warning("%s failed: %s", what, exc) + return fail(error( + METADATA_ERROR, + f"{what} failed: {exc}. The metadata service failed — this does not mean the data is empty.", + )) + + +def _round_or_none(value: Any) -> float | None: + try: + return round(float(value), 3) + except (TypeError, ValueError): + return None + + +def _value_match(v: Any) -> dict: + if not isinstance(v, dict): + return {"value": v} + return { + "value": v.get("value"), + "table": v.get("table_name") or v.get("table"), + "column": v.get("column_name") or v.get("column"), + "keyword_similarity": _round_or_none(v.get("keyword_similarity")), + "semantic_distance": _round_or_none(v.get("semantic_distance")), + } + + +@tool +async def search_column_values( + search_term: str, + table: Optional[str] = None, + column: Optional[str] = None, + limit: int = 10, + runtime: Runtime = None, +) -> str: + """ + Searches for exact real values contained within indexed columns across the database. + + SUPPORTED COLUMN TYPES (semantic_type in the catalog): + - Indexed: `large_categorical`, `large_unit_id` (its main use), and `categorical` / `boolean` (whose + values the catalog usually lists already). + - NOT indexed: `id`, `continuous`, `time`, `free_text` and geometry columns. A search on them — or on a + table/column that doesn't exist — returns 0 matches whatever the value; check such values with SQL. + + WHEN TO USE: + - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database + (e.g., finding 'Acme Corporation LLC' from 'Acme Corp', or the stored spelling of a Hebrew term). Multilingual, + keyword, and vector search finds the exact database spelling. + + Returns data.matches — up to `limit` matching values (use each 'value' verbatim in SQL) with: + - 'keyword_similarity' close to 1.0 = strong lexical match + - 'semantic_distance' close to 0.0 = strong semantic match + On an indexed column the nearest stored values come back even when the term isn't in the data, so a + weak-scoring match is not evidence that the value exists. + data.limit_reached is true when exactly `limit` matches came back: there may be more — call again + with a higher `limit` before filtering on the list. + + Args: + search_term (str): The specific value to look for (partial or full string, Hebrew or English). + table (str, optional): Restrict search to one table name. Omit to search all tables. + column (str, optional): Restrict search to one column name. Omit to search all columns. + limit (int): Maximum number of results to return. Defaults to 10. + """ + try: + res = await get_jeen_metadata_client().search_column_values( + search_term=search_term, table=table, column=column, limit=limit, raw=True, + connection_id=connection_id(runtime), + ) + except Exception as e: + return metadata_failure("search_column_values", e) + + values = (res.get("values") or []) if isinstance(res, dict) else [] + matches = [_value_match(v) for v in values] + limit_reached = len(matches) >= limit + if not matches: + notice = ("No matches. Check the column's semantic_type in the catalog: `id`, `continuous`, `time` and " + "`free_text` columns are not indexed and always return 0, as does a table/column that doesn't " + "exist — check those values with SQL instead. On an indexed column, nothing matched the term.") + elif limit_reached: + notice = f"Returned the first {limit} matches (the limit); there may be more — call again with a higher limit." + else: + notice = None + return ok({ + "search_term": search_term, + "matches": matches, + "limit_reached": limit_reached, + "notice": notice, + }) diff --git a/agent/src/deep_agent/tools/sql.py b/agent/src/deep_agent/tools/sql.py new file mode 100644 index 0000000..db7415e --- /dev/null +++ b/agent/src/deep_agent/tools/sql.py @@ -0,0 +1,218 @@ +""" +SQL tools: run read-only queries on Trino, sample a table, list a column's distinct values, and +dry-run a query (validate_sql). + +Every statement goes through agent.utils.sql_guard (one read-only statement, row ceiling, safe +identifiers). Failures carry Trino's own error unchanged (deep_agent.tools.trino_errors). A +successful execute_trino_query is recorded in state so the final answer can be bound to it +(deep_agent.answer.verification). +""" + +import logging + +from langchain_core.messages import ToolMessage +from langchain_core.tools import tool +from langgraph.types import Command + +import deep_agent.tools.trino_errors as trino_errors +from agent.config import settings +from agent.utils import sql_guard +from agent.utils.sql import clean_sql +from agent.utils.sql_guard import effective_cap +from core.trino import execute_query_sync +from deep_agent.answer.verification import executed_query_record +from deep_agent.context import Runtime +from deep_agent.observability import annotate_current_span +from deep_agent.tools.envelope import fail, ok + +logger = logging.getLogger(__name__) + + +def _run_sql(sql: str, row_cap: int | None, requested: int | None = None) -> str: + """Run guarded SQL; when the requested row count was reduced to the configured ceiling, say so.""" + content, payload = _execute(sql, row_cap) + if payload is None or requested is None or row_cap is None or requested <= row_cap: + return content + return ok({**payload, "notice": f"limit reduced from {requested} to {row_cap} (the configured ceiling) — " + "asking for more returns the same rows"}) + + +def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: + """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. + + Returns (envelope, success payload or None). + row_cap=None means no ceiling: every returned row is passed through. + Telemetry (query id, timing, row count / Trino error) goes both into the envelope + and onto the current Langfuse tool observation. + """ + try: + res = execute_query_sync(sql, reuse_connection=True) + except Exception as e: + err = trino_errors.from_exception(e) + annotate_current_span({"error_name": err["name"]}, level="ERROR") + return fail(err), None + if not res.success: + err = trino_errors.from_result(res) + err["execution_time_ms"] = res.execution_time_ms + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "error_name": err["name"], + "error_type": err.get("type"), + }, level="ERROR") + return fail(err), None + + rows = res.rows or [] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "row_count": len(rows), + "truncated": truncated, + }) + payload = { + "columns": res.columns, + "row_count": len(rows), + "truncated": truncated, + "rows": rows, + "query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + } + return ok(payload), payload + + +@tool +def execute_trino_query(sql: str, limit: int | None = None, runtime: Runtime = None) -> str | Command: + """ + Executes a read-only Trino SQL query and returns the resulting rows. + + Use this to test SQL queries against the actual database and perform exploratory data analysis. + Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, + multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with + error.name FORBIDDEN_STATEMENT. + + Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced + automatically, and data.truncated is true when more rows existed than were returned. + + On failure, error carries Trino's own error, unmodified: + - error.name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, + EXPRESSION_NOT_AGGREGATE, DIVISION_BY_ZERO) + - error.type: Trino's error class — USER_ERROR means the SQL itself is wrong; + INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database + - error.message: Trino's message; error.location: {line, column} of the offending token + Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite + as a single read-only query) and CONNECTION_ERROR (Trino could not be reached). + + Args: + sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing + semicolons are stripped automatically. + limit (int, optional): Maximum number of rows to return. Defaults to the configured row + ceiling; a larger value is reduced to that ceiling. + """ + row_cap = effective_cap(limit, settings.DEEP_AGENT_MAX_ROWS) + try: + guarded = sql_guard.prepare(clean_sql(sql), row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + content, payload = _execute(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) + if payload is None or not guarded.is_query or runtime is None or not runtime.tool_call_id: + return content + # Record the successful execution so the final answer can be bound to it (deep_agent.answer.verification). + return Command(update={ + "executed_queries": [executed_query_record(sql, guarded.sql, payload, row_cap)], + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="execute_trino_query")], + }) + + +@tool +def get_sample_rows(table_name: str, limit: int = 5) -> str: + """ + Retrieves a small number of raw data rows from a table using a live Trino query. + + Use this only when schema profiles don't provide enough context and you must see exact raw + data formats (e.g., date formatting, nested JSON structure, exact string casing). + Do NOT use this for counting or aggregating data. + + Args: + table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. + limit (int): The number of rows to sample. Defaults to 5 (bounded by the configured sample ceiling). + """ + requested = limit if limit is not None else 5 + row_cap = effective_cap(requested, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) + try: + sql = sql_guard.sample_rows_sql(table_name, row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + return _run_sql(sql, row_cap, requested) + + +@tool +def get_column_distinct_values(table_name: str, column_name: str, limit: int = 50) -> str: + """ + Executes a live Trino query to fetch unique values for a specific column. + Use this to see exact existing strings in the database before writing an exact-match WHERE clause. + + BEST USED FOR: + - Low-cardinality `categorical` columns (e.g. status, priority, category) where you want to see all + 5-20 possible valid values, and the catalog doesn't already list all of them. + + DO NOT USE FOR: + - High-cardinality columns (`large_categorical`, `large_unit_id`, names, SKUs, cities). Dumping 50-100 + random values from a table with thousands of entities wastes tokens and latency without finding the + specific entity you need. Use `search_column_values` instead for targeted entity search. + - Numeric, date, or continuous columns (checking unique values is meaningless for value matching). + - Columns whose values the catalog already lists in full ("values (all)"). + + Args: + table_name (str): The fully qualified exact name of the table. + column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). + limit (int): Maximum distinct values to return. Defaults to 50; data.truncated is true when more exist. + """ + row_cap = max(1, int(limit)) if limit is not None else 50 + try: + sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + return _run_sql(sql, row_cap) + + +_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " + + +@tool +def validate_sql(sql: str) -> str: + """ + Asks Trino to check a query without running it (EXPLAIN (TYPE VALIDATE)). Trino parses it and + resolves it against the catalog: syntax, table and column names, types and function signatures. + No data is read. + + Optional. For an invalid query, execute_trino_query fails at the same checking step, just as + fast and without reading data, with the same error fields — so validating first usually + saves nothing. Use it only to check a draft you do not want to run yet. It cannot tell you + whether the query returns rows. + + Returns ok=true with data.valid=true, or ok=false with the same error fields as + execute_trino_query (error.name, error.type, error.message, error.location). + + Args: + sql (str): The exact Trino SQL query string to validate. + """ + sql_clean = clean_sql(sql) + try: + sql_guard.parse_read_statement(sql_clean) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + try: + res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}", reuse_connection=True) + except Exception as e: + return fail(trino_errors.from_exception(e)) + if res.success: + return ok({"valid": True}) + err = trino_errors.from_result(res) + location = err.get("location") + if location and location["line"] == 1: + # Trino counts columns from the start of "EXPLAIN (TYPE VALIDATE) ..."; report them against the caller's SQL. + location["column"] = max(1, location["column"] - len(_VALIDATE_PREFIX)) + return fail(err) diff --git a/agent/src/deep_agent/tools/trino_errors.py b/agent/src/deep_agent/tools/trino_errors.py new file mode 100644 index 0000000..b7643c6 --- /dev/null +++ b/agent/src/deep_agent/tools/trino_errors.py @@ -0,0 +1,40 @@ +""" +Error objects returned to the agent when SQL fails (the `error` of the tool envelope). + +Trino errors are passed through as Trino reported them (errorName, errorType, message, +location, query id) — no re-labelling. Two failures never get a Trino error and are +named here instead: + + FORBIDDEN_STATEMENT the SQL guard rejected the statement before it reached Trino + CONNECTION_ERROR Trino could not be reached / returned no structured error +""" + +from core.trino import TrinoExecutionResult +from deep_agent.tools.envelope import error + +FORBIDDEN_STATEMENT = "FORBIDDEN_STATEMENT" +CONNECTION_ERROR = "CONNECTION_ERROR" + + +def from_result(res: TrinoExecutionResult) -> dict: + """Error object for a failed TrinoExecutionResult.""" + if res.error_name is None: + return error(CONNECTION_ERROR, res.error_message or "Unknown error") + location = {"line": res.error_location[0], "column": res.error_location[1]} if res.error_location else None + return error( + res.error_name, + res.error_message or "", + type=res.error_type, + location=location, + query_id=res.query_id, + ) + + +def forbidden(message: str) -> dict: + """Error object for SQL the guard rejected.""" + return error(FORBIDDEN_STATEMENT, message) + + +def from_exception(exc: Exception) -> dict: + """Error object for an exception raised while calling Trino.""" + return error(CONNECTION_ERROR, str(exc)) diff --git a/agent/src/deep_agent/validator/__init__.py b/agent/src/deep_agent/validator/__init__.py new file mode 100644 index 0000000..a43f5ac --- /dev/null +++ b/agent/src/deep_agent/validator/__init__.py @@ -0,0 +1,17 @@ +""" +Independent semantic review of the Deep Agent's SQL — before it is submitted. + +The order is: run the SQL (execute_trino_query) → have it reviewed (the `semantic-validator` subagent, +through `task`) → submit it (submit_answer). The reviewer is a separate agent with a fresh context and +no SQL tools — it judges by reading; its input is built by our code from facts — the user's own messages, the +SQL, its recorded rows, the agent's assumptions (as claims to check), the catalog and the date — never +from the agent's reasoning. It returns pass, or fail with issues and evidence; on fail the agent goes +back to work, or disputes (submits the same SQL with `validation_response`, shown to the user). + +DEEP_AGENT_SEMANTIC_VALIDATION: `always` (default) makes submit_answer accept only SQL the reviewer passed +(or that the agent disputes); `on_demand` offers the reviewer and lets the agent decide; `off` drops it. submit_answer itself only checks the records +(deep_agent.answer.middleware.SubmitApprovalMiddleware) — the judging happens before it. + +- reviewer.py the reviewer agent: verdicts (pass / fail / needs_check), its facts-only input, verdict records +- modes.py the wiring: the subagent, the "before you submit" prompt, the per-turn reset +""" diff --git a/agent/src/deep_agent/validator/modes.py b/agent/src/deep_agent/validator/modes.py new file mode 100644 index 0000000..7f73fc0 --- /dev/null +++ b/agent/src/deep_agent/validator/modes.py @@ -0,0 +1,69 @@ +""" +How the reviewer (deep_agent.validator.reviewer) is wired into the agent — DEEP_AGENT_SEMANTIC_VALIDATION: + +- always the `semantic-validator` subagent is available through `task`, and submit_answer is accepted + only for SQL it passed (or that the agent disputes) — see SubmitApprovalMiddleware + (deep_agent.answer.middleware). REVIEW_PROMPT tells the agent the order of steps. +- on_demand the subagent is available and the agent decides whether to call it (ON_DEMAND_PROMPT); + submit_answer only requires that the SQL ran. +- off no reviewer; submit_answer still requires that the SQL ran. + +ReviewTurnMiddleware starts every turn with no review records and copies the user's messages into +state for the reviewer (subagents don't receive the conversation). +""" + +from typing import Any + +from langchain.agents.middleware import AgentMiddleware +from langchain_core.language_models import BaseChatModel + +from deep_agent.context import DeepAgentRuntimeState, is_user_message +from deep_agent.validator.reviewer import VALIDATOR_NAME, build_validator + +# What the main agent sees about the subagent (in the `task` tool's list of subagents). +_HOW_TO_SEND = ( + "It reads a SQL query against the user's request and the catalog (it doesn't run queries) and returns JSON " + "{verdict: pass|fail|needs_check, issues: [{problem, evidence}], checks: [...]}. Send exactly two things in the description: " + "the SQL in a ```sql block, and your interpretation choices as a list of lines starting with '- '. Nothing else " + "is read: the reviewer gets the user's messages and this SQL's result rows itself." +) +VALIDATOR_DESCRIPTION = { + "always": "Independent reviewer — required before submit_answer. " + _HOW_TO_SEND, + "on_demand": ("Independent reviewer — worth it before submit_answer when the answer involves a join, aggregation " + "or grouping, several conditions, an interpretation you had to choose, 0 rows or a surprising " + "number. " + _HOW_TO_SEND), +} + +# Appended to the main system prompt when review is required. +REVIEW_PROMPT = """ +## Before you submit (required) + +1. The final SQL must have run successfully with `execute_trino_query` in this turn — check its rows. +2. Ask the `semantic-validator` to review it: `task` with subagent_type `semantic-validator`, the SQL in a ```sql block and your assumptions as `- ` lines. +3. Pass → call `submit_answer` with exactly that SQL (any change needs a new review). Fail → fix the SQL and repeat 1–2; if you are sure the reviewer is wrong, you may submit the same SQL with `validation_response` explaining why. Needs check → run exactly the checks it names with `execute_trino_query`, then ask for review again (it sees their results). + +`submit_answer` is refused for SQL that hasn't run, or that the reviewer hasn't passed. +""" + +# Appended to the main system prompt when review is on demand. +ON_DEMAND_PROMPT = """ +An independent reviewer is available: `task` with subagent_type `semantic-validator` (its description says when it is worth calling and what to send). `submit_answer` is refused for SQL that hasn't run successfully in this turn. +""" + + +class ReviewTurnMiddleware(AgentMiddleware): + """Start every turn with no review records, and give the reviewer the user's messages.""" + + state_schema = DeepAgentRuntimeState + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + user_messages = [m.text for m in state.get("messages") or [] if is_user_message(m) and m.text.strip()] + return {"semantic_validations": None, "user_messages": user_messages} # None resets (context.merge_reviews) + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) + + +def validator_subagent(model: BaseChatModel, mode: str = "always") -> dict[str, Any]: + """The reviewer as a deepagents CompiledSubAgent (called through `task`).""" + return {"name": VALIDATOR_NAME, "description": VALIDATOR_DESCRIPTION[mode], "runnable": build_validator(model)} diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py new file mode 100644 index 0000000..985fd22 --- /dev/null +++ b/agent/src/deep_agent/validator/reviewer.py @@ -0,0 +1,251 @@ +""" +The reviewer agent (the `semantic-validator` subagent): a separate agent with a fresh context that +judges by reading — it has no SQL tools and doesn't write SQL. Its prompt is prompts/validator.md. + +Verdicts (`submit_verdict`): +- pass the SQL answers the request +- fail a problem it can show from what it read (issues with evidence) +- needs_check rarely: something it can see gives a concrete reason to doubt that only data can settle; + it names the specific checks, the main agent runs them and asks for review again + +Independence: the agent that asks for the review writes a brief, but the reviewer never reads it as +such. ReviewInputMiddleware replaces the brief with an input our code builds from facts: + +- the user's messages, from the thread (state `user_messages`) — never from the brief +- the SQL to review and the agent's assumptions — the only two things taken from the brief + (a ```sql block and a "- " list); any other text in the brief is discarded +- that SQL's result rows, from the recorded execution (state `executed_queries`) +- after a needs_check: the checks it asked for, and the real results of the queries the agent ran since + (from the recorded executions — never the agent's description of them) +- plus, like every model call: today's date and the connection's catalog + +Not given: the agent's reasoning, notes, confidence, or the user-facing explanation. +ReviewRecordMiddleware records each verdict for the reviewed SQL in `semantic_validations`, which +submit_answer checks (deep_agent.answer.middleware). +""" + +import logging +import re +import uuid +from collections.abc import Awaitable, Callable +from typing import Any, Literal + +from langchain.agents import create_agent +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse +from langchain_core.language_models import BaseChatModel +from langchain_core.messages import HumanMessage +from pydantic import BaseModel, Field, create_model, model_validator +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError + +from deep_agent.answer.middleware import submit_fallback +from deep_agent.answer.schema import submission_strategy +from deep_agent.answer.verification import match_execution, normalize_sql +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState +from deep_agent.middleware.catalog import CatalogMiddleware +from deep_agent.prompts.registry import load_prompt + +logger = logging.getLogger(__name__) + +ValidationMode = Literal["always", "on_demand", "off"] + +VERDICT_TOOL = "submit_verdict" +VALIDATOR_NAME = "semantic-validator" +REVIEW_CONFIG = {"run_name": VALIDATOR_NAME, "tags": [VALIDATOR_NAME]} # the tag marks the reviewer's nested runs + + +class Issue(BaseModel): + problem: str = Field(description="What is wrong and how to fix it (Hebrew).") + evidence: str = Field(description="The exact part of the SQL, the result rows, the catalog or the request that " + "shows it (Hebrew).") + + +class _VerdictFields(BaseModel): + verdict: Literal["pass", "fail", "needs_check"] = Field( + description="pass = the SQL answers the request; fail = it doesn't; needs_check = something you can see " + "gives a concrete reason to doubt that only data can settle (rare).") + issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") + checks: list[str] = Field( + default_factory=list, + description="For needs_check: each specific check for the analyst to run, e.g. 'check whether the values of " + "table_a.col match table_b.col'.") + + @model_validator(mode="after") + def _verdict_needs_its_details(self): + if self.verdict == "fail" and not self.issues: + raise ValueError("a fail verdict needs at least one issue with evidence") + if self.verdict == "needs_check" and not self.checks: + raise ValueError("a needs_check verdict needs at least one specific check") + return self + + +SubmitVerdict = create_model( + VERDICT_TOOL, __base__=_VerdictFields, + __doc__="Submit your review verdict. Call this exactly once, when you are done — it ends your review.", +) + +# A real code block: the ```sql fence starts a line and the SQL is on the lines below (an inline mention of +# "```sql block" in prose is not one). +_SQL_BLOCK = re.compile(r"^[ \t]*```sql[ \t]*\n(.*?)^[ \t]*```", re.DOTALL | re.IGNORECASE | re.MULTILINE) +_BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+(.+?)\s*$") + + +def parse_brief(brief: str) -> tuple[str | None, list[str]]: + """The two things taken from the agent's brief: the SQL (first ```sql block) and its assumptions (bullets).""" + blocks = _SQL_BLOCK.findall(brief or "") + sql = blocks[0].strip() if blocks else None + outside = _SQL_BLOCK.sub("", brief or "") + assumptions = [m.group(1) for line in outside.splitlines() if (m := _BULLET.match(line))] + return sql or None, assumptions + + +def _rows_section(record: dict[str, Any]) -> str: + note = " (only part of the result: more rows exist)" if record.get("truncated") else "" + lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] + lines += [str(row) for row in record["rows"]] + return "\n".join(lines) + + +def answer_notes(sql: str, record: dict[str, Any] | None) -> list[str]: + """Facts our code can see about this answer, put in front of the reviewer so a general rule becomes a + specific cue: SQL that keeps a single row (ties), a cut-off result, an empty result.""" + notes = [] + try: + tree = sqlglot.parse_one(sql, read="trino") + except SqlglotError: + tree = None + if tree is not None: + limit = tree.args.get("limit") + single = [] + if isinstance(limit, exp.Limit) and limit.expression.sql() == "1": + single.append("it ends with LIMIT 1") + if any(isinstance(w.this, exp.RowNumber) for w in tree.find_all(exp.Window)): + single.append("it picks rows with row_number(), which keeps one row per group even when values tie") + if any(True for _ in tree.find_all(exp.ArgMax, exp.ArgMin)): + single.append("it uses max_by / min_by, which return one value even when several tie") + if single: + notes.append("This SQL keeps a single row: " + "; ".join(single) + ". If the request asks for " + "'the most / the longest / the highest', check whether other rows share the top value — " + "dropping ties the user didn't ask to drop is a fail.") + if record is not None and record.get("truncated"): + notes.append(f"The result was cut off at {record['row_count']} rows — more rows exist. For a request that " + "expects a short list (a top N, a few items per group), the SQL returns more than was asked.") + if record is not None and record.get("row_count") == 0: + notes.append("The result is empty (0 rows) — check whether a condition or a join makes it impossible.") + return notes + + +def _pending_checks(records: list[dict[str, Any]], executions: list[dict[str, Any]]) -> tuple[list[str], list[dict]]: + """The checks asked for in the latest needs_check review this turn, and the executions recorded since it.""" + asked = [r for r in records if r.get("verdict") == "needs_check"] + if not asked: + return [], [] + latest = asked[-1] + return latest.get("checks") or [], executions[latest.get("after_execution", len(executions)):] + + +def review_request(user_messages: list[str], sql: str | None, assumptions: list[str], + executed: list[dict[str, Any]], records: list[dict[str, Any]] | None = None) -> str: + """The reviewer's input, built from facts: the user's own messages, the SQL, its assumptions, its real rows, + and — after a needs_check — the checks asked for and the real results of the queries run since.""" + parts = [] + if user_messages[:-1]: + parts.append("## Earlier user messages (context)\n" + "\n".join(f"- {text}" for text in user_messages[:-1])) + parts.append(f"## Current user request\n{user_messages[-1] if user_messages else ''}") + if sql is None: + parts.append("## SQL to review\n(none was provided — fail the review with the issue " + "\"no SQL was sent for review\")") + return "\n\n".join(parts) + parts.append(f"## SQL to review\n```sql\n{sql}\n```") + listed = "\n".join(f"- {a}" for a in assumptions) or "(none stated)" + parts.append("## The analyst's interpretation choices — claims to check, not facts\n" + listed) + record = match_execution(sql, executed) + notes = answer_notes(sql, record) + if notes: + parts.append("## Notes on this answer (facts detected by code)\n" + "\n".join(f"- {n}" for n in notes)) + parts.append("## Result of this SQL\n" + (_rows_section(record) if record else "This SQL has not run in this turn.")) + checks, since = _pending_checks(records or [], executed) + if checks: + parts.append("## Checks you asked for in your previous review\n" + "\n".join(f"- {c}" for c in checks)) + if since: + ran = [f"```sql\n{r['submitted_sql']}\n```\n{_rows_section(r)}" for r in since] + parts.append("## Queries the analyst ran since, with their real results\n" + "\n\n".join(ran)) + else: + parts.append("## Queries the analyst ran since\n(none)") + return "\n\n".join(parts) + + +def _turn_executions(state: dict) -> list[dict[str, Any]]: + return (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + + +class ReviewInputMiddleware(AgentMiddleware): + """Inside the reviewer: replace the agent's brief with the input built from facts (module docstring).""" + + state_schema = DeepAgentRuntimeState + + def _with_review_input(self, request: ModelRequest) -> ModelRequest: + messages = list(request.messages) + if not messages or not isinstance(messages[0], HumanMessage): + return request + state = request.state or {} + sql, assumptions = parse_brief(messages[0].text) + text = review_request(list(state.get("user_messages") or []), sql, assumptions, _turn_executions(state), + list(state.get("semantic_validations") or [])) + messages[0] = HumanMessage(text, id=messages[0].id) + return request.override(messages=messages) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(self._with_review_input(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(self._with_review_input(request)) + + +def review_record(verdict: Any, **fields: Any) -> dict[str, Any]: + if verdict is None: + return {"id": uuid.uuid4().hex, "verdict": "error", "issues": [], **fields} + return {"id": uuid.uuid4().hex, "verdict": verdict.verdict, "checks": list(verdict.checks), + "issues": [issue.model_dump() for issue in verdict.issues], **fields} + + +class ReviewRecordMiddleware(AgentMiddleware): + """Inside the reviewer: record its verdict for the SQL it reviewed (state `semantic_validations`).""" + + state_schema = DeepAgentRuntimeState + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + sql, _ = parse_brief(messages[0].text if messages else "") + verdict = state.get("structured_response") + reason = None if verdict else "the reviewer ended without a verdict" + return {"semantic_validations": [review_record(verdict, sql=normalize_sql(sql), reason=reason, + after_execution=len(_turn_executions(state)))]} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return self.after_agent(state, runtime) + + +def build_validator(model: BaseChatModel): + """The reviewer agent: facts-only input, catalog + date in context, no SQL tools, verdict via submit_verdict.""" + prompt = load_prompt("validator").text + agent = create_agent( + model=model, + tools=[], # it judges by reading; checks that need data are run by the main agent (needs_check) + system_prompt=prompt, + middleware=[ + ReviewInputMiddleware(), # first: the date is then added to the built input, not to the brief + DeepAgentContextMiddleware(), + CatalogMiddleware(), + *submit_fallback(VERDICT_TOOL), + ReviewRecordMiddleware(), + ], + response_format=submission_strategy(SubmitVerdict), + context_schema=DeepAgentContext, + checkpointer=False, # a fresh, unsaved state per review (never the main thread's checkpointer) + name=VALIDATOR_NAME, + ) + return agent.with_config(REVIEW_CONFIG) diff --git a/agent/tests/deep_agent/__init__.py b/agent/tests/deep_agent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py new file mode 100644 index 0000000..619c602 --- /dev/null +++ b/agent/tests/deep_agent/conftest.py @@ -0,0 +1,86 @@ +from collections.abc import Callable + +import pytest +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage, BaseMessage +from langchain_core.outputs import ChatGeneration, ChatResult + + +class ScriptedChatModel(GenericFakeChatModel): + """Fake chat model that replays scripted AIMessages and records every prompt it receives.""" + + seen: list[list[BaseMessage]] = [] + bound_tool_names: list[list[str]] = [] + + def bind_tools(self, tools, **kwargs): # deepagents binds tools; the script decides the calls + self.bound_tool_names.append([getattr(t, "name", None) or t.get("name") for t in tools]) + return self + + def _generate(self, messages, stop=None, run_manager=None, **kwargs): + self.seen.append(list(messages)) + return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs) + + +@pytest.fixture +def scripted_model(): + def _make(*replies: AIMessage) -> ScriptedChatModel: + model = ScriptedChatModel(messages=iter(replies)) + model.seen = [] + model.bound_tool_names = [] + return model + + return _make + + +def system_text(messages: list[BaseMessage]) -> str: + return "\n".join(m.text for m in messages if m.type == "system") + + +class PolicyChatModel(ScriptedChatModel): + """Fake chat model whose next reply is computed from the conversation so far. + + Safe to share across concurrent threads (unlike a scripted iterator). + """ + + policy: Callable[[list[BaseMessage]], AIMessage] | None = None + + def _generate(self, messages, stop=None, run_manager=None, **kwargs): + self.seen.append(list(messages)) + return ChatResult(generations=[ChatGeneration(message=self.policy(messages))]) + + +@pytest.fixture +def policy_model(): + def _make(policy: Callable[[list[BaseMessage]], AIMessage]) -> PolicyChatModel: + model = PolicyChatModel(messages=iter([]), policy=policy) + model.seen = [] + model.bound_tool_names = [] + return model + + return _make + + +TEST_CATALOG = '# Database Schema\n\n## Columns\n"catalog"."schema"."orders": Orders\n - "status" (varchar) [semantic_type=categorical]' + + +@pytest.fixture(autouse=True) +def no_semantic_validation(monkeypatch): + """Scripted models answer the main agent only; tests that cover the reviewer turn it on explicitly.""" + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_SEMANTIC_VALIDATION", "off") + + +@pytest.fixture(autouse=True) +def fake_catalog(monkeypatch): + """Every agent run loads the connection's catalog (CatalogMiddleware); never hit the real Jeen service in tests. + + Tests that need a specific catalog or a failure override `fake_catalog.get_catalog_prompt`. + """ + from unittest.mock import AsyncMock, MagicMock + + import deep_agent.middleware.catalog as catalog_module + + client = MagicMock(get_catalog_prompt=AsyncMock(return_value=TEST_CATALOG)) + monkeypatch.setattr(catalog_module, "get_jeen_metadata_client", lambda: client) + return client diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py new file mode 100644 index 0000000..84cb925 --- /dev/null +++ b/agent/tests/deep_agent/test_answer.py @@ -0,0 +1,220 @@ +from unittest.mock import patch + +import pytest +from core.trino import TrinoExecutionResult +from langchain_core.messages import AIMessage + +from deep_agent.agent import create_deep_agent +from deep_agent.answer import verification +from deep_agent.answer.render import render_markdown +from deep_agent.answer.schema import SubmitAnswer, answer_schema +from deep_agent.answer.verification import normalize_sql, verify_answer +from deep_agent.tools import sql as sql_tools +from tests.deep_agent.conftest import system_text + +EXECUTED = "SELECT COUNT(DISTINCT flight_id) AS flights FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'France'" +# Same query as the model might restate it: different whitespace/case and a trailing semicolon. +RESTATED = "select count(distinct flight_id) as flights\nfrom \"postgres\".\"public\".\"flights_table\"\nwhere launch_country = 'France';" + + +def _trino(rows): + return TrinoExecutionResult(success=True, rows=rows, columns=["flights"], row_count=len(rows), query_id="q-1") + + +def _policy(final_args, content=""): + def policy(messages): + tool_msgs = [m for m in messages if m.type == "tool"] + if not tool_msgs: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e1"}]) + return AIMessage(content, tool_calls=[{"name": "submit_answer", "args": final_args, "id": "final"}]) + return policy + + +ANSWER = {"sql": RESTATED, "explanation_he": "סופרת טיסות ייחודיות שהמריאו מצרפת", "assumptions": ["טיסה = flight_id"], + "confidence": "high"} + + +async def _run(policy_model, policy, tool_results, reexecution_results=(), clarifications=False): + agent = create_deep_agent(model=policy_model(policy), clarifications_enabled=clarifications) + with patch.object(sql_tools, "execute_query_sync", side_effect=list(tool_results)) as t1, \ + patch.object(verification, "execute_query_sync", side_effect=list(reexecution_results)) as t2: + result = await agent.ainvoke({"messages": [("user", "כמה טיסות המריאו מצרפת")]}, + {"configurable": {"thread_id": "a"}}) + return result, t1, t2 + + +@pytest.mark.asyncio +async def test_answer_is_bound_to_the_executed_query(policy_model): + result, _, reexec = await _run(policy_model, _policy(ANSWER), [_trino([[466]])]) + + final = result["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["sql"] == EXECUTED # the executed text, no trailing ';' + assert final["result"]["rows"] == [[466]] # rows from Trino, not model text + assert final["answer"]["confidence"] == "high" + reexec.assert_not_called() + assert len(result["executed_queries"]) == 1 + + +@pytest.mark.parametrize("sql", ["SELECT COUNT(*) AS flights FROM \"postgres\".\"public\".\"flights_table\"", + "DELETE FROM \"postgres\".\"public\".\"flights_table\""], ids=["select", "delete"]) +def test_sql_that_never_ran_is_never_executed_or_shown(sql): + """submit_answer refuses such SQL (SubmitApprovalMiddleware); if it ever reached verification, nothing runs.""" + answer = SubmitAnswer(sql=sql, explanation_he="הסבר", confidence="high") + with patch.object(verification, "execute_query_sync") as run: + final = verify_answer(answer, []) + run.assert_not_called() + assert final["status"] == "not_executed" and final["executed"] is False and final["result"] is None + + +@pytest.mark.asyncio +async def test_clarification_path_when_enabled(policy_model): + ask = {"sql": None, "explanation_he": "", "confidence": "low", "needs_clarification": "האם הכוונה לנחיתות או להמראות?"} + result, _, _ = await _run(policy_model, _policy(ask), [_trino([[466]])], clarifications=True) + + final = result["final_result"] + assert final["status"] == "clarification" + assert render_markdown(final) == "האם הכוונה לנחיתות או להמראות?" + + +@pytest.mark.asyncio +async def test_list_content_from_reasoning_models_is_fine(policy_model): + reasoning = [{"type": "reasoning", "reasoning": "thinking..."}, {"type": "text", "text": "submitting"}] + result, _, _ = await _run(policy_model, _policy(ANSWER, content=reasoning), [_trino([[466]])]) + assert result["final_result"]["status"] == "matched" + + +def test_render_markdown_builds_table_from_rows(): + final = { + "status": "matched", "executed": True, "sql": "SELECT a, b FROM t", + "answer": {"explanation_he": "הסבר", "assumptions": ["הנחה"], "confidence": "high"}, + "result": {"columns": ["a", "b"], "rows": [["x|y", None], [1, "line\nbreak"]], "row_count": 2, + "truncated": True, "query_id": "q"}, + } + md = render_markdown(final) + assert "| a | b |" in md + assert "| x\\|y | |" in md and "| 1 | line break |" in md + assert "**הנחות:**\n- הנחה" in md + assert "השורות הראשונות" in md + assert md.endswith("```sql\nSELECT a, b FROM t\n```") + + +def test_render_reports_failed_final_sql(): + final = {"status": "re_execution_failed", "executed": False, "sql": "SELECT x FROM t", "result": None, + "error": "Column 'x' cannot be resolved", "answer": {"explanation_he": "הסבר"}} + assert "לא ניתן היה להריץ" in render_markdown(final) + + +def test_normalize_sql_equivalence(): + assert normalize_sql(EXECUTED) == normalize_sql(RESTATED) + assert normalize_sql("```sql\nSELECT 1;\n```") == normalize_sql("select 1") + assert normalize_sql("SELECT 1") != normalize_sql("SELECT 2") + assert normalize_sql("SELECT a -- pick a\nFROM t") == normalize_sql("SELECT /* other */ a FROM t") + + +def test_verify_without_structured_answer(): + assert verify_answer(None, [])["status"] == "no_answer" + + +def test_answer_schema_requires_explanation_and_confidence(): + with pytest.raises(ValueError): + SubmitAnswer(sql="SELECT 1") + + +def test_clarifications_are_off_by_default(): + schema = answer_schema() + assert schema.__name__ == "submit_answer" + assert "needs_clarification" not in schema.model_fields + assert schema.model_fields["sql"].is_required() # the model must always commit to a SQL answer + enabled = answer_schema(True) + assert enabled.__name__ == "submit_answer" # same tool name either way + assert "needs_clarification" in enabled.model_fields and not enabled.model_fields["sql"].is_required() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("enabled", [False, True]) +async def test_clarification_only_mentioned_in_prompt_when_enabled(scripted_model, enabled): + model = scripted_model(AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e"}]), + AIMessage("", tool_calls=[{"name": "submit_answer", "args": {**ANSWER}, "id": "f"}])) + agent = create_deep_agent(model=model, clarifications_enabled=enabled) + with patch.object(sql_tools, "execute_query_sync", return_value=_trino([[1]])): + await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": f"c{enabled}"}}) + assert ("needs_clarification" in system_text(model.seen[0])) is enabled + + +@pytest.mark.asyncio +async def test_matched_exploration_sample_is_re_executed_for_the_full_answer(policy_model): + """The model explored with limit=5 and submitted that same SQL: the user must get the full result, not the sample.""" + def policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED, "limit": 5}, "id": "e1"}]) + return AIMessage("", tool_calls=[{"name": "submit_answer", "args": ANSWER, "id": "final"}]) + + sample = _trino([[i] for i in range(6)]) # 5 + 1 rows -> truncated sample + full = _trino([[i] for i in range(40)]) + result, _, reexec = await _run(policy_model, policy, [sample], [full]) + + final = result["final_result"] + assert final["status"] == "re_executed" and final["executed"] is True + assert final["result"]["row_count"] == 40 and final["result"]["truncated"] is False + assert reexec.call_args.args[0].endswith("LIMIT 101") + + +def test_re_execution_without_a_row_ceiling(monkeypatch): + monkeypatch.setattr(verification.settings, "DEEP_AGENT_MAX_ROWS", None) + answer = SubmitAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") + sample = verification.executed_query_record( # the approved SQL ran with limit=5 + "SELECT a FROM t", "SELECT a FROM t LIMIT 6", + {"columns": ["a"], "rows": [[i] for i in range(5)], "row_count": 5, "truncated": True}, 5) + with patch.object(verification, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: + final = verify_answer(answer, [sample]) + assert run.call_args.args[0] == "SELECT a FROM t" # no LIMIT added + assert final["executed"] is True and final["result"]["row_count"] == 500 and final["result"]["truncated"] is False + + +# ── recovery of answers written as text (gpt-oss behind the configured server) ── + +def _text_ending_policy(final_text): + def policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e1"}]) + return AIMessage(final_text, response_metadata={"finish_reason": "tool_calls"}) + return policy + + +@pytest.mark.asyncio +@pytest.mark.parametrize("wrap", [lambda j: j, lambda j: f"```json\n{j}\n```"], ids=["bare", "fenced"]) +async def test_answer_written_as_json_text_is_recovered(policy_model, wrap): + import json as _json + + result, _, reexec = await _run(policy_model, _text_ending_policy(wrap(_json.dumps(ANSWER, ensure_ascii=False))), + [_trino([[466]])]) + final = result["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["result"]["rows"] == [[466]] + assert final["recovered_from_text"] is True + reexec.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("text", [ + "סיימתי, התשובה היא 466", # prose, not an answer object + '{"sql": "SELECT 1"}', # JSON, but missing required fields + '{"explanation_he": "x", "confidence": "high"', # broken JSON +], ids=["prose", "invalid-schema", "broken-json"]) +async def test_text_that_is_not_a_valid_answer_is_not_recovered(policy_model, text): + result, _, _ = await _run(policy_model, _text_ending_policy(text), [_trino([[466]])]) + final = result["final_result"] + assert final["status"] == "no_answer" and final["executed"] is False + assert final["recovered_from_text"] is False + + +@pytest.mark.asyncio +async def test_a_real_tool_call_is_not_marked_recovered(policy_model): + result, _, _ = await _run(policy_model, _policy(ANSWER), [_trino([[466]])]) + assert result["final_result"]["recovered_from_text"] is False + + +def test_sql_is_required(): + with pytest.raises(ValueError): + SubmitAnswer(sql="", explanation_he="x", confidence="low") diff --git a/agent/tests/deep_agent/test_cli.py b/agent/tests/deep_agent/test_cli.py new file mode 100644 index 0000000..1dfb4f5 --- /dev/null +++ b/agent/tests/deep_agent/test_cli.py @@ -0,0 +1,27 @@ +import json + +from langchain_core.messages import AIMessage, ToolMessage + +from deep_agent.cli import RunRecord, append_run_record, print_formatted_message + + +def test_run_record_is_valid_jsonl(tmp_path): + log = tmp_path / "runs" / "log.jsonl" + for i in range(2): + append_run_record(log, RunRecord("2026-10-20T10:00:00", 1.5, f"t{i}", "שאלה\nשורה", "SELECT 1", "תשובה", + "matched", True)) + lines = log.read_text(encoding="utf-8").splitlines() + assert len(lines) == 2 + rows = [json.loads(line) for line in lines] + assert rows[0]["question"] == "שאלה\nשורה" + assert set(rows[1]) == {"timestamp", "execution_time_s", "thread_id", "question", "final_sql", "final_answer", + "verification", "executed"} + + +def test_print_formatted_message_handles_list_content(capsys): + print_formatted_message(AIMessage(content=[{"type": "text", "text": "hello"}], tool_calls=[ + {"name": "execute_trino_query", "args": {"sql": "SELECT 1"}, "id": "1"}, + ])) + print_formatted_message(ToolMessage(content=[{"type": "text", "text": "Error: boom"}], tool_call_id="1", name="x")) + out = capsys.readouterr().out + assert "hello" in out and "execute_trino_query" in out and "Error: boom" in out diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py new file mode 100644 index 0000000..3bd2cc4 --- /dev/null +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -0,0 +1,113 @@ +""" +Lint for the Deep Agent's guidance (system prompt, skills, tool docstrings). + +Catches drift: references to tools that don't exist, known contradictory/incorrect +statements creeping back, catalog-specific examples in what must be general text-to-SQL +guidance, and skill SQL that isn't valid Trino. +""" + +import re + +import pytest +import sqlglot + +from deep_agent.agent import SYSTEM_PROMPT +from deep_agent.prompts.registry import local_prompt +from deep_agent.resources import DEFAULT_SKILLS_DIR, EXPECTED_SKILLS +from deep_agent.tools import DEEP_AGENT_TOOLS + +DOMAIN_TOOLS = {t.name for t in DEEP_AGENT_TOOLS} +HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "submit_answer", "submit_verdict"} + +DOCS: dict[str, str] = { + "system prompt": SYSTEM_PROMPT, + "validator prompt": local_prompt("validator"), + **{f"skill {p.parent.name}": p.read_text(encoding="utf-8") for p in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md"))}, + **{f"docstring {t.name}": t.description for t in DEEP_AGENT_TOOLS}, +} + +# Backticked identifiers that look like tool names (verb_object). +_TOOL_REF = re.compile(r"`((?:get|search|execute|validate|enrich|resolve)_[a-z_]+)`") + +# Statements that were wrong, contradictory or removed, and must not come back. +BANNED = [ + (r"Every categorical filter value must be verified — use `search_column_values`", "categorical values are not indexed"), + (r"`categorical` — small finite value set; use search_column_values", "categorical values are not indexed"), + (r"Use `search_column_values` with the user's term", "only for large_categorical / large_unit_id"), + (r"`search_column_values` on any string filter", "only for large_categorical / large_unit_id"), + (r"Using `NOW\(\)` — Trino uses", "now() is valid Trino"), + (r"Using `DATE_FORMAT` — Trino uses", "date_format() is valid Trino"), + (r'"השבוע".*date_trunc\(\'week\'', "Trino weeks start Monday; Israeli weeks start Sunday"), + (r"returns a `POINT", "resolve_location_to_wkt returns area geometries only"), + (r"@location_name_wkt@|@[a-z_]+_wkt@", "WKT placeholders are a legacy-graph mechanism"), + (r"Call (it|this) before every `execute_trino_query`|Always call before `execute_trino_query`", "validation is optional (#42)"), + (r"NEVER use Hebrew as SQL identifiers", "Hebrew catalog columns are valid (double-quoted)"), + (r"prefix_pattern", "search_column_values returns all matches; no prefix guessing (#45)"), + (r"sql_literal", "resolve_location_to_wkt returns data.wkt (#45)"), + (r"error\.category|error\.hint|error_category", "SQL errors carry Trino's own error.name / error.type (#39)"), + (r"validate_sql_syntax", "the tool is validate_sql (#39)"), + (r"needs_clarification", "clarifications are off by default; only the flag adds them to the prompt (#41)"), + (r"AGENTS\.md|agent_memory", "there is no AGENTS.md memory; always-on guidance is the system prompt (#40)"), + (r"prefix pattern", "use every matching stored value, never a guessed prefix (#45)"), +] + +# Catalog-specific names: guidance must stay general text-to-SQL knowledge, not one deployment's data. +CATALOG_SPECIFIC = re.compile( + r"flights?_table|flight_alerts|flight_id|city_info|launch_country|mahoz|Tel Aviv \d|'France'|\"postgres\"\.\"public\"", + re.IGNORECASE, +) + + +@pytest.mark.parametrize("doc", DOCS, ids=list(DOCS)) +def test_referenced_tools_exist(doc): + unknown = set(_TOOL_REF.findall(DOCS[doc])) - DOMAIN_TOOLS - HARNESS_TOOLS + assert not unknown, f"{doc} references unknown tools: {sorted(unknown)}" + + +@pytest.mark.parametrize("pattern, reason", BANNED, ids=[r for _, r in BANNED]) +def test_banned_statements_are_absent(pattern, reason): + hits = [name for name, text in DOCS.items() if re.search(pattern, text)] + assert not hits, f"{reason}: found in {hits}" + + +@pytest.mark.parametrize("doc", DOCS, ids=list(DOCS)) +def test_no_catalog_specific_examples(doc): + hits = sorted(set(CATALOG_SPECIFIC.findall(DOCS[doc]))) + assert not hits, f"{doc} contains catalog-specific examples: {hits}" + + +def test_value_resolution_policy_has_one_owner(): + owners = [name for name, text in DOCS.items() if "**Tool scope**: `search_column_values` indexes" in text] + assert owners == ["system prompt"] + + +def test_system_prompt_names_every_skill(): + for skill in EXPECTED_SKILLS: + assert f"`{skill}`" in SYSTEM_PROMPT + + +def _sql_blocks(name: str, text: str) -> list[tuple[str, str]]: + blocks = [] + for i, block in enumerate(re.findall(r"```sql\n(.*?)```", text, re.DOTALL)): + # Split into statements on blank lines; keep complete SELECT / WITH statements only. + for j, chunk in enumerate(re.split(r"\n\s*\n", block)): + body = "\n".join(line for line in chunk.splitlines() if not line.strip().startswith("--")).strip() + if re.match(r"(?is)^(SELECT|WITH)\b", body): + blocks.append((f"{name}#{i}.{j}", body)) + return blocks + + +SQL_BLOCKS = [b for name, text in DOCS.items() if not name.startswith("docstring") for b in _sql_blocks(name, text)] + + +def test_guidance_contains_sql_examples(): + # The parse check below must not pass vacuously: the system prompt and every skill carry checked SQL. + sources = {name.split("#")[0] for name, _ in SQL_BLOCKS} + assert {"system prompt", *(f"skill {s}" for s in EXPECTED_SKILLS)} <= sources + + +@pytest.mark.parametrize("name, sql", SQL_BLOCKS, ids=[n for n, _ in SQL_BLOCKS]) +def test_guidance_sql_parses_as_trino(name, sql): + # Template placeholders like stand for a boolean expression. + sql = re.sub(r"<[A-Za-z_][\w ]*>", "1 = 1", sql) # placeholders only — not `a <= x AND b >= y` + sqlglot.parse_one(sql, read="trino") diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py new file mode 100644 index 0000000..8a38a53 --- /dev/null +++ b/agent/tests/deep_agent/test_latency.py @@ -0,0 +1,176 @@ +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import core.trino as core_trino +import pytest +from core.trino import TrinoExecutionResult +from langchain_core.messages import AIMessage + +import agent.utils.jeen_metadata_client as jmc +from agent.config import settings +from agent.utils.jeen_metadata_client import ( + JeenMetadataClient, + JeenMetadataError, + close_mcp_sessions, +) +from deep_agent.agent import create_deep_agent +from deep_agent.middleware.tool_filter import EXCLUDED_BUILTIN_TOOLS + +OK = TrinoExecutionResult(success=True, rows=[[7]], columns=["n"], row_count=1, query_id="q") + + +@pytest.mark.asyncio +async def test_unused_builtin_tools_are_not_offered_to_the_model(scripted_model): + model = scripted_model(AIMessage("done"), AIMessage("done")) # second: reply to the submit reminder + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "t"}}) + offered = set(model.bound_tool_names[-1]) + assert not offered & EXCLUDED_BUILTIN_TOOLS + assert {"read_file", "write_todos", "execute_trino_query", "submit_answer"} <= offered + + +# ── metadata cache ────────────────────────────────────────────────────────── + +@pytest.fixture +def client(): + c = JeenMetadataClient() + c.clear_cache() + return c + + +@pytest.mark.asyncio +async def test_metadata_reads_are_cached(client): + with patch.object(client, "_call_uncached", AsyncMock(return_value=[{"name": "t"}])) as fetch: + first = await client.get_tables(connection_id=1) + first.append({"name": "mutated"}) # callers can't corrupt the cache + second = await client.get_tables(connection_id=1) + await client.get_tables(connection_id=2) # different connection -> separate entry + assert second == [{"name": "t"}] + assert fetch.await_count == 2 + + +@pytest.mark.asyncio +async def test_concurrent_identical_reads_are_single_flight(client): + async def slow(*_): + await asyncio.sleep(0.05) + return [{"name": "t"}] + + with patch.object(client, "_call_uncached", AsyncMock(side_effect=slow)) as fetch: + results = await asyncio.gather(*(client.get_relationships(connection_id=1) for _ in range(5))) + assert fetch.await_count == 1 + assert all(r == [{"name": "t"}] for r in results) + + +@pytest.mark.asyncio +async def test_errors_are_not_cached_and_ttl_zero_disables(client, monkeypatch): + with patch.object(client, "_call_uncached", AsyncMock(side_effect=[JeenMetadataError("boom"), [{"x": 1}]])) as fetch: + with pytest.raises(JeenMetadataError): + await client.get_tables(connection_id=1) + assert await client.get_tables(connection_id=1) == [{"x": 1}] + assert fetch.await_count == 2 + + monkeypatch.setattr(settings, "JEEN_METADATA_CACHE_TTL_S", 0) + with patch.object(client, "_call_uncached", AsyncMock(return_value=[])) as fetch: + await client.get_tables(connection_id=1) + await client.get_tables(connection_id=1) + assert fetch.await_count == 2 + + +@pytest.mark.asyncio +async def test_search_results_are_not_cached(client): + with patch.object(client, "_call_uncached", AsyncMock(return_value={"values": []})) as fetch: + await client.search_column_values("x", raw=True) + await client.search_column_values("x", raw=True) + assert fetch.await_count == 2 + + +# ── persistent MCP session ────────────────────────────────────────────────── + +class FakeTransport: + """Counts MCP handshakes; call_tool can be told to fail once like a dropped session.""" + + def __init__(self, fail_first_call=False): + self.handshakes = 0 + self.calls = 0 + self.fail_first_call = fail_first_call + + def transport(self, *args, **kwargs): + return MagicMock(__aenter__=AsyncMock(return_value=(None, None, None)), __aexit__=AsyncMock(return_value=False)) + + def session(self, *args, **kwargs): + outer = self + + async def initialize(): + outer.handshakes += 1 + + async def call_tool(name, arguments, **kwargs): + outer.calls += 1 + await asyncio.sleep(0.01) + if outer.fail_first_call and outer.calls == 1: + raise ConnectionError("session expired") + return SimpleNamespace(isError=False, content=[SimpleNamespace(text='{"tables": []}')]) + + session = MagicMock(initialize=initialize, call_tool=call_tool) + return MagicMock(__aenter__=AsyncMock(return_value=session), __aexit__=AsyncMock(return_value=False)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_first_call, expected_handshakes", [(False, 1), (True, 2)]) +async def test_mcp_session_is_reused_across_calls(fail_first_call, expected_handshakes): + fake = FakeTransport(fail_first_call) + with patch.object(jmc, "streamablehttp_client", side_effect=fake.transport), \ + patch.object(jmc, "ClientSession", side_effect=fake.session): + for _ in range(3): + await jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) + await asyncio.gather(*(jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) for _ in range(5))) + await close_mcp_sessions() + assert fake.handshakes == expected_handshakes + assert fake.calls == 8 + int(fail_first_call) + + +@pytest.mark.asyncio +async def test_mcp_per_call_sessions_when_reuse_disabled(monkeypatch): + monkeypatch.setattr(settings, "JEEN_METADATA_REUSE_SESSION", False) + fake = FakeTransport() + with patch.object(jmc, "streamablehttp_client", side_effect=fake.transport), \ + patch.object(jmc, "ClientSession", side_effect=fake.session): + for _ in range(3): + await jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) + assert fake.handshakes == 3 + + +# ── Trino connection reuse ────────────────────────────────────────────────── + +def _fake_connection(fail=False): + conn = MagicMock() + cur = conn.cursor.return_value + cur.description = [("n",)] + cur.fetchall.return_value = [(1,)] + cur.query_id = "20261020_000000_00001_abcde" + if fail: + cur.execute.side_effect = RuntimeError("connection reset") + return conn + + +def test_trino_connection_is_reused_per_thread_and_dropped_on_error(monkeypatch): + monkeypatch.setattr(core_trino.settings, "TRINO_ENABLED", True) + core_trino._drop_reusable_connection() + conns = [_fake_connection(), _fake_connection(fail=True), _fake_connection()] + with patch.object(core_trino, "get_trino_connection", side_effect=conns) as connect: + for _ in range(3): + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success + assert connect.call_count == 1 # one connection for three queries + conns[0].cursor.return_value.execute.side_effect = RuntimeError("connection reset") + assert not core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success is False # conns[1] fails + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success # fresh conns[2] + assert connect.call_count == 3 + core_trino._drop_reusable_connection() + + +def test_default_execution_still_opens_and_closes_a_connection(monkeypatch): + monkeypatch.setattr(core_trino.settings, "TRINO_ENABLED", True) + conn = _fake_connection() + with patch.object(core_trino, "get_trino_connection", return_value=conn): + core_trino.execute_query_sync("SELECT 1") + conn.close.assert_called_once() diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py new file mode 100644 index 0000000..eecf5c8 --- /dev/null +++ b/agent/tests/deep_agent/test_observability.py @@ -0,0 +1,211 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch +from uuid import UUID + +import pytest +from core.trino import TrinoExecutionResult +from langchain_core.callbacks import BaseCallbackHandler +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage + +from deep_agent import observability, tools +from deep_agent.agent import create_deep_agent +from deep_agent.observability import RunMetrics, build_run_config, run_metrics +from deep_agent.tools import metadata as metadata_tools +from deep_agent.tools import sql as sql_tools + + +class RunTreeRecorder(BaseCallbackHandler): + """Records every run's id/parent so we can assert the trace is one tree with no orphans.""" + + def __init__(self): + self.runs: dict[UUID, dict] = {} + + def _add(self, kind, serialized, run_id, parent_run_id, **kwargs): + name = kwargs.get("name") or (serialized or {}).get("name") + self.runs[run_id] = {"kind": kind, "name": name, "parent": parent_run_id} + + def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None, **kwargs): + self._add("chain", serialized, run_id, parent_run_id, **kwargs) + + def on_tool_start(self, serialized, input_str, *, run_id, parent_run_id=None, **kwargs): + self._add("tool", serialized, run_id, parent_run_id, **kwargs) + + def on_chat_model_start(self, serialized, messages, *, run_id, parent_run_id=None, **kwargs): + self._add("llm", serialized, run_id, parent_run_id, **kwargs) + + def roots(self): + return [rid for rid, r in self.runs.items() if r["parent"] is None] + + def reaches(self, run_id, root): + while run_id is not None: + if run_id == root: + return True + run_id = self.runs.get(run_id, {}).get("parent") + return False + + +STEPS = [ + ("get_sample_rows", {"table_name": '"postgres"."public"."flights_table"'}), + ("execute_trino_query", {"sql": "SELECT COUNT(*) FROM flights_table WHERE launch_country = 'France'"}), + ("search_column_values", {"search_term": "צרפת"}), +] + + +def _policy(messages): + done = len([m for m in messages if m.type == "tool"]) + if done < len(STEPS): + name, args = STEPS[done] + return AIMessage("", tool_calls=[{"name": name, "args": args, "id": f"t{done}"}]) + return AIMessage("תשובה\n```sql\nSELECT 1\n```") + + +@pytest.mark.asyncio +async def test_one_trace_tree_with_no_orphans(policy_model): + recorder = RunTreeRecorder() + client = MagicMock(get_catalog_prompt=AsyncMock(return_value="# catalog"), + search_column_values=AsyncMock(return_value={"values": [{"value": "France"}]})) + trino = TrinoExecutionResult(success=True, rows=[[466]], columns=["c"], row_count=1, query_id="q-1", + execution_time_ms=12) + agent = create_deep_agent(model=policy_model(_policy)) + config = build_run_config("thread-obs", user_id="u-1", callbacks=[recorder], tracing=False) + + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino): + await agent.ainvoke({"messages": [("user", "כמה טיסות")]}, config) + + roots = recorder.roots() + assert len(roots) == 1, f"expected exactly one root run, got {[recorder.runs[r] for r in roots]}" + root = roots[0] + + tool_runs = {r["name"] for r in recorder.runs.values() if r["kind"] == "tool"} + assert {name for name, _ in STEPS} <= tool_runs + llm_runs = [rid for rid, r in recorder.runs.items() if r["kind"] == "llm"] + assert len(llm_runs) >= len(STEPS) + 1 # one agent turn per tool call + the final one + for rid, run in recorder.runs.items(): + assert recorder.reaches(rid, root), f"orphan run: {run}" + + +def test_build_run_config_sets_langfuse_metadata(): + handler = object() + with patch.object(observability, "_langfuse_handler", return_value=handler): + config = build_run_config("thread-1", user_id="user-7", connection_id=89, tracing=True) + assert config["configurable"] == {"thread_id": "thread-1"} + assert config["callbacks"] == [handler] + assert config["metadata"]["langfuse_session_id"] == "thread-1" + assert config["metadata"]["langfuse_user_id"] == "user-7" + assert config["metadata"]["langfuse_tags"] == ["deep-agent"] + assert config["metadata"]["connection_id"] == 89 + assert config["metadata"]["agent_version"] + assert config["tags"] == ["deep-agent"] + assert config["run_name"] == "deep-agent" + + +def test_build_run_config_without_tracing_has_no_langfuse_handler(): + with patch.object(observability, "_langfuse_handler") as factory: + config = build_run_config("t", tracing=False) + factory.assert_not_called() + assert config["callbacks"] == [] + + +def test_agent_version_prefers_explicit_env(monkeypatch): + monkeypatch.setenv("DEEP_AGENT_VERSION", "b8e27c8") + assert observability.agent_version() == "b8e27c8" + + +def test_trino_tools_annotate_the_tool_span(): + ok_res = TrinoExecutionResult(success=True, rows=[[1], [2]], columns=["a"], row_count=2, query_id="q-9", + execution_time_ms=34) + with patch.object(sql_tools, "execute_query_sync", return_value=ok_res), \ + patch.object(sql_tools, "annotate_current_span") as annotate: + out = tools.execute_trino_query.invoke({"sql": "SELECT a FROM t", "limit": 1}) + annotate.assert_called_once_with({"trino_query_id": "q-9", "execution_time_ms": 34, "row_count": 1, "truncated": True}) + assert '"execution_time_ms":34' in out and '"query_id":"q-9"' in out + + err = TrinoExecutionResult(success=False, error_message="line 1:8: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", query_id="q-10", execution_time_ms=5) + with patch.object(sql_tools, "execute_query_sync", return_value=err), \ + patch.object(sql_tools, "annotate_current_span") as annotate: + tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"}) + metadata, = annotate.call_args.args + assert metadata["error_name"] == "COLUMN_NOT_FOUND" and metadata["trino_query_id"] == "q-10" + assert annotate.call_args.kwargs["level"] == "ERROR" + + +def test_annotate_is_a_noop_without_active_span(): + observability.annotate_current_span({"x": 1}) # must not raise outside a trace + + +def test_run_metrics(): + messages = [ + HumanMessage("q"), + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {}, "id": "1"}, + {"name": "get_sample_rows", "args": {}, "id": "2"}]), + ToolMessage('{"ok":false,"data":null,"error":{}}', tool_call_id="1", name="execute_trino_query"), + ToolMessage('{"ok":true}', tool_call_id="2", name="get_sample_rows"), + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {}, "id": "3"}]), + ToolMessage('{"ok":true,"data":{},"error":null}', tool_call_id="3", name="execute_trino_query"), + AIMessage("answer\n```sql\nSELECT 1\n```"), + ] + assert run_metrics(messages, 12.345) == RunMetrics(model_calls=3, tool_calls=3, sql_executions=2, latency_s=12.35) + assert run_metrics(messages, 1, {"status": "matched", "executed": True}).final_sql_executed is True + assert run_metrics(messages, 1, {"status": "re_execution_failed", "executed": False}).final_sql_executed is False + + +def test_score_run_posts_one_score_per_metric(): + fake_client = SimpleNamespace(create_score=MagicMock()) + with patch("agent.langfuse_client.langfuse_client", fake_client): + observability.score_run("trace-1", RunMetrics(4, 3, 1, 9.5, final_sql_executed=True)) + names = {c.kwargs["name"]: c.kwargs for c in fake_client.create_score.call_args_list} + assert set(names) == {f"deep-agent.{n}" for n in + ("model_calls", "tool_calls", "sql_executions", "latency_s", "final_sql_executed")} + assert names["deep-agent.final_sql_executed"]["data_type"] == "BOOLEAN" + assert names["deep-agent.final_sql_executed"]["value"] == 1.0 + assert all(kw["trace_id"] == "trace-1" for kw in names.values()) + + +def test_score_run_without_trace_is_noop(): + with patch("agent.langfuse_client.langfuse_client") as client: + observability.score_run(None, RunMetrics(1, 1, 1, 1.0)) + client.create_score.assert_not_called() + + +@pytest.mark.asyncio +async def test_real_langfuse_handler_produces_a_single_trace(policy_model): + """End-to-end through the real Langfuse v4 CallbackHandler, exported to memory (no network).""" + from langfuse import Langfuse + from langfuse.langchain import CallbackHandler + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + + exporter = InMemorySpanExporter() + langfuse = Langfuse(public_key="pk-lf-unit-test", secret_key="sk-lf-unit-test", host="http://127.0.0.1:9", + span_exporter=exporter, flush_at=1, flush_interval=0.01) + + trino = TrinoExecutionResult(success=True, rows=[[1]], columns=["c"], row_count=1, query_id="q-77", + execution_time_ms=9) + agent = create_deep_agent(model=policy_model(_policy)) + with patch.object(observability, "_langfuse_handler", return_value=CallbackHandler(public_key="pk-lf-unit-test")), \ + patch.object(metadata_tools, "get_jeen_metadata_client", return_value=MagicMock( + get_catalog_prompt=AsyncMock(return_value="# c"), search_column_values=AsyncMock(return_value={"values": []}))), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino): + config = build_run_config("thread-lf", user_id="user-lf", tracing=True) + await agent.ainvoke({"messages": [("user", "q")]}, config) + langfuse.flush() + + spans = exporter.get_finished_spans() + assert spans + assert len({s.context.trace_id for s in spans}) == 1 + assert [s.name for s in spans if s.parent is None] == ["deep-agent"] + attrs = {k: v for s in spans for k, v in s.attributes.items()} + assert attrs["session.id"] == "thread-lf" + assert attrs["user.id"] == "user-lf" + assert "deep-agent" in attrs["langfuse.trace.tags"] + + trino_span = next(s for s in spans if s.name == "execute_trino_query") + meta = {k.removeprefix("langfuse.observation.metadata."): v for k, v in trino_span.attributes.items()} + assert meta["trino_query_id"] == "q-77" + assert meta["execution_time_ms"] == 9 + assert meta["row_count"] == 1 + assert observability.langfuse_trace_id(config) == format(spans[0].context.trace_id, "032x") diff --git a/agent/tests/deep_agent/test_prompts_and_catalog.py b/agent/tests/deep_agent/test_prompts_and_catalog.py new file mode 100644 index 0000000..b6db7e6 --- /dev/null +++ b/agent/tests/deep_agent/test_prompts_and_catalog.py @@ -0,0 +1,218 @@ +"""Prompt registry (Langfuse-managed prompts), the deterministic catalog, and subagent state handling.""" + +import json +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +from langchain_core.messages import AIMessage + +from agent.config import settings +from deep_agent import observability +from deep_agent.agent import CLARIFICATION_PROMPT, create_deep_agent +from deep_agent.context import merge_executions +from deep_agent.middleware.catalog import CatalogLoadError +from deep_agent.prompts import registry as prompt_registry +from deep_agent.prompts.registry import PROMPT_KEYS, load_prompt, local_prompt +from tests.deep_agent.conftest import TEST_CATALOG, system_text + +# ── deterministic catalog ──────────────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_catalog_is_in_every_model_call_but_not_in_history(scripted_model): + model = scripted_model(AIMessage("", tool_calls=[{"name": "write_todos", "args": {"todos": []}, "id": "w"}]), + AIMessage("done"), AIMessage("done")) # last: reply to the submit reminder + result = await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "c"}}) + assert len(model.seen) == 3 + assert all(TEST_CATALOG in system_text(seen) for seen in model.seen) + assert all(TEST_CATALOG not in m.text for m in result["messages"]) # never duplicated into the message history + assert "get_database_catalog" not in model.bound_tool_names[-1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", [RuntimeError("mcp down"), ""], ids=["unreachable", "empty"]) +async def test_run_fails_clearly_without_a_catalog(scripted_model, fake_catalog, failure): + if isinstance(failure, Exception): + fake_catalog.get_catalog_prompt.side_effect = failure + else: + fake_catalog.get_catalog_prompt.return_value = failure + model = scripted_model(AIMessage("done")) + with pytest.raises(CatalogLoadError, match="catalog"): + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "x"}}) + assert model.seen == [] # the model is never called without a catalog + + +@pytest.mark.asyncio +async def test_general_purpose_subagent_sees_the_catalog(policy_model): + def policy(messages): + roles = [m.type for m in messages] + if messages and messages[0].type == "human" and "explore" in messages[0].text: # inside the subagent + return AIMessage("subagent brief") + if "tool" not in roles: + return AIMessage("", tool_calls=[{"name": "task", "id": "t", "args": { + "description": "explore the order tables", "subagent_type": "general-purpose"}}]) + return AIMessage("done") + + model = policy_model(policy) + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "gp"}}) + sub_calls = [seen for seen in model.seen if any(m.type == "human" and "explore" in m.text for m in seen)] + assert sub_calls, "the subagent was never called" + assert all(TEST_CATALOG in system_text(seen) for seen in sub_calls) + + +# ── subagent state round trips ─────────────────────────────────────────────── + +def test_merge_executions_is_idempotent_for_subagent_round_trips(): + a = {"query_id": "q1", "executed_sql": "SELECT 1"} + b = {"query_id": "q2", "executed_sql": "SELECT 2"} + # Subagent returns parent's history plus one new record. + assert merge_executions([a], [a, b]) == [a, b] + assert merge_executions(None, [a, a]) == [a] + + +# ── prompt registry ────────────────────────────────────────────────────────── + +def test_every_prompt_has_a_packaged_fallback(): + for key in PROMPT_KEYS: + assert local_prompt(key).strip() + + +def test_disabled_langfuse_uses_packaged_prompt(): + p = load_prompt("system") + assert p.source == "local" and p.text == local_prompt("system") and p.client is None + + +@pytest.fixture +def langfuse_enabled(monkeypatch): + monkeypatch.setattr(settings, "DEEP_AGENT_LANGFUSE_PROMPTS", True) + prompt_registry._misses.clear() + yield + prompt_registry._misses.clear() + + +def _served(text, version=3, fallback=False): + return SimpleNamespace(prompt=text, version=version, is_fallback=fallback) + + +def test_langfuse_prompt_by_label(langfuse_enabled, monkeypatch): + monkeypatch.setattr(settings, "DEEP_AGENT_PROMPT_LABEL", "staging") + fake = MagicMock(get_prompt=MagicMock(return_value=_served("served v3"))) + with patch("agent.langfuse_client.langfuse_client", fake): + p = load_prompt("system") + assert (p.source, p.text, p.version) == ("langfuse", "served v3", 3) + args, kwargs = fake.get_prompt.call_args + assert args == ("deep-agent/system",) + assert kwargs["label"] == "staging" and kwargs["fallback"] == local_prompt("system") + + +@pytest.mark.parametrize("behaviour", ["fallback", "raises"]) +def test_langfuse_unavailable_falls_back(langfuse_enabled, behaviour): + fake = MagicMock() + if behaviour == "fallback": + fake.get_prompt.return_value = _served(local_prompt("system"), version=None, fallback=True) + else: + fake.get_prompt.side_effect = RuntimeError("404 prompt not found") + with patch("agent.langfuse_client.langfuse_client", fake): + p = load_prompt("system") + assert p.source == "local" and p.text == local_prompt("system") + + +@pytest.mark.asyncio +async def test_prompt_change_rebuilds_the_agent_on_the_next_request(langfuse_enabled): + from deep_agent import service + + served = {"system": "system v1", "validator": "validator v1"} + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda name, **k: _served(served[name.split("/")[1]]))) + builds = [] + + def fake_build(**kwargs): + builds.append(dict(served)) + return object() + + service.reset_for_tests() + with patch("agent.langfuse_client.langfuse_client", fake), \ + patch("deep_agent.agent.create_deep_agent", fake_build), \ + patch.object(service, "build_checkpointer", MagicMock(side_effect=lambda: _async(object()))): + first = await service.get_deep_agent() + assert await service.get_deep_agent() is first # unchanged prompts: same agent + served["validator"] = "validator v2" + second = await service.get_deep_agent() + service.reset_for_tests() + assert second is not first and builds == [{"system": "system v1", "validator": "validator v1"}, + {"system": "system v1", "validator": "validator v2"}] + + +async def _async(value): + return value + + +@pytest.mark.asyncio +async def test_a_run_keeps_the_prompt_it_started_with(scripted_model, langfuse_enabled): + served = {"text": "You are the deep analyst prompt v4."} + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served(served["text"]))) + model = scripted_model(AIMessage("one"), AIMessage("one")) # answer + reminder reply + with patch("agent.langfuse_client.langfuse_client", fake): + agent = create_deep_agent(model=model) + served["text"] = "You are the NEW deep analyst prompt v5." # label moved while the agent exists + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "p1"}}) + prompts = [system_text(seen) for seen in model.seen] + assert all(p.startswith("You are the deep analyst prompt v4.") for p in prompts) + assert "Skills System" in prompts[0] + + +def test_run_config_links_generations_to_the_prompt_version(langfuse_enabled): + client = _served("x", version=7) + with patch.object(observability, "_langfuse_handler", return_value=object()), \ + patch.object(prompt_registry, "load_prompt", + return_value=prompt_registry.LoadedPrompt("system", "x", "langfuse", 7, client)): + config = observability.build_run_config("t", tracing=True) + assert config["metadata"]["langfuse_prompt"] is client + assert config["metadata"]["prompt_version"] == 7 + assert config["metadata"]["prompt_source"] == "langfuse" + + +def test_sync_script_pushes_every_prompt_with_label(): + import importlib.util + from pathlib import Path + + path = Path(__file__).resolve().parents[2] / "scripts" / "sync_deep_agent_prompts.py" + spec = importlib.util.spec_from_file_location("sync_prompts", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + fake = MagicMock() + pushed = module.sync(fake, label="staging", dry_run=False) + assert pushed == [f"deep-agent/{k}" for k in PROMPT_KEYS] + for call, key in zip(fake.create_prompt.call_args_list, PROMPT_KEYS): + assert call.kwargs["name"] == f"deep-agent/{key}" + assert call.kwargs["prompt"] == local_prompt(key) + assert call.kwargs["labels"] == ["staging"] and call.kwargs["type"] == "text" + assert module.sync(MagicMock(), label="staging", dry_run=True) == pushed + json.dumps(pushed) + + +def test_missing_prompt_is_not_refetched_on_every_call(langfuse_enabled): + """A 404 / fallback must not cost a Langfuse round trip on every model call.""" + fake = MagicMock(get_prompt=MagicMock(return_value=_served(local_prompt("system"), version=None, fallback=True))) + with patch("agent.langfuse_client.langfuse_client", fake): + for _ in range(5): + assert load_prompt("system").source == "local" + assert fake.get_prompt.call_count == 1 + + +def test_miss_expires_after_ttl(langfuse_enabled, monkeypatch): + fake = MagicMock(get_prompt=MagicMock(side_effect=[RuntimeError("down"), _served("now served", version=2)])) + with patch("agent.langfuse_client.langfuse_client", fake): + assert load_prompt("system").source == "local" + prompt_registry._misses["system"] = 0.0 # TTL elapsed + assert load_prompt("system").text == "now served" + + +@pytest.mark.asyncio +async def test_langfuse_prompt_keeps_the_clarification_suffix(scripted_model, langfuse_enabled): + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served("NEW system prompt v5."))) + model = scripted_model(AIMessage("done"), AIMessage("done")) + with patch("agent.langfuse_client.langfuse_client", fake): + agent = create_deep_agent(model=model, clarifications_enabled=True) + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "s"}}) + prompt = system_text(model.seen[0]) + assert prompt.startswith("NEW system prompt v5." + CLARIFICATION_PROMPT) diff --git a/agent/tests/deep_agent/test_resources.py b/agent/tests/deep_agent/test_resources.py new file mode 100644 index 0000000..972b233 --- /dev/null +++ b/agent/tests/deep_agent/test_resources.py @@ -0,0 +1,113 @@ +import os +import shutil + +import pytest +from langchain_core.messages import AIMessage + +from deep_agent.agent import create_deep_agent +from deep_agent.resources import ( + DEFAULT_SKILLS_DIR, + EXPECTED_SKILLS, + DeepAgentResourceError, + _read_frontmatter, + build_resources, + discover_skills, +) +from tests.deep_agent.conftest import system_text + + +def test_packaged_skills_are_valid(): + resources = build_resources() + assert resources.skill_names == EXPECTED_SKILLS + assert resources.skills == ["/skills/"] + + +def test_no_user_specific_paths_in_deep_agent_sources(): + for path in DEFAULT_SKILLS_DIR.parent.rglob("*.py"): + assert "/Users/" not in path.read_text(encoding="utf-8"), path + + +def test_resources_resolve_independently_of_cwd(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + assert build_resources().skill_names == EXPECTED_SKILLS + + +@pytest.fixture +def skills_copy(tmp_path): + skills = tmp_path / "skills" + shutil.copytree(DEFAULT_SKILLS_DIR, skills) + return skills + + +def test_missing_skills_dir_fails_fast(tmp_path): + with pytest.raises(DeepAgentResourceError, match="Skills directory not found"): + build_resources(skills_dir=tmp_path / "nope") + + +def test_missing_required_skill_fails_fast(skills_copy): + shutil.rmtree(skills_copy / "temporal-analyst") + with pytest.raises(DeepAgentResourceError, match="temporal-analyst"): + build_resources(skills_dir=skills_copy) + + +def test_skill_without_frontmatter_fails_fast(skills_copy): + skills = skills_copy + (skills / "temporal-analyst" / "SKILL.md").write_text("# no frontmatter", encoding="utf-8") + with pytest.raises(DeepAgentResourceError, match="frontmatter"): + discover_skills(skills) + + +def test_skill_name_must_match_directory(skills_copy): + skills = skills_copy + os.rename(skills / "temporal-analyst", skills / "temporal") + with pytest.raises(DeepAgentResourceError, match="must match its directory"): + discover_skills(skills) + + +@pytest.mark.asyncio +async def test_skills_and_system_prompt_reach_the_model_without_memory(scripted_model): + model = scripted_model(AIMessage("done"), AIMessage("done")) # second: reply to the submit reminder + agent = create_deep_agent(model=model) + await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-prompt"}}) + + prompt = system_text(model.seen[0]) + # Skill *names* also appear in source labels even when nothing loads, so assert on the + # frontmatter descriptions, which are only rendered for skills that were actually loaded. + assert "No skills available" not in prompt + for skill_md in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md")): + description = _read_frontmatter(skill_md)["description"] + assert description[:60] in prompt, f"skill {skill_md.parent.name} not loaded" + assert "## Phase 1 — Understand" in prompt, "system prompt file not loaded" + assert "# Database Catalog" in prompt, "connection catalog not added to the system message" + assert "" not in prompt, "no AGENTS.md memory block (or its boilerplate) is expected" + + +@pytest.mark.asyncio +async def test_agent_cannot_write_skills(scripted_model): + write = AIMessage("", tool_calls=[ + {"name": "write_file", "args": {"file_path": "/skills/evil/SKILL.md", "content": "x"}, "id": "w1"}, + {"name": "edit_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md", "old_string": "Temporal", "new_string": "X"}, "id": "w2"}, + ]) + model = scripted_model(write, AIMessage("done"), AIMessage("done")) + agent = create_deep_agent(model=model) + result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-write"}}) + + tool_results = [m for m in result["messages"] if m.type == "tool"] + assert len(tool_results) == 2 + for msg in tool_results: + assert "denied" in msg.text.lower() or "permission" in msg.text.lower(), msg.text + assert not (DEFAULT_SKILLS_DIR / "evil").exists() + assert "Temporal SQL Reference for Trino" in (DEFAULT_SKILLS_DIR / "temporal-analyst" / "SKILL.md").read_text(encoding="utf-8") + + +@pytest.mark.asyncio +async def test_agent_can_read_a_skill_file(scripted_model): + read = AIMessage("", tool_calls=[ + {"name": "read_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md"}, "id": "r1"}, + ]) + model = scripted_model(read, AIMessage("done"), AIMessage("done")) + agent = create_deep_agent(model=model) + result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-read"}}) + + tool_msg = next(m for m in result["messages"] if m.type == "tool") + assert "Temporal SQL Reference for Trino" in tool_msg.text diff --git a/agent/tests/deep_agent/test_runtime_context.py b/agent/tests/deep_agent/test_runtime_context.py new file mode 100644 index 0000000..d228d2d --- /dev/null +++ b/agent/tests/deep_agent/test_runtime_context.py @@ -0,0 +1,116 @@ +import asyncio +import json +from datetime import datetime, timezone +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from langchain_core.messages import AIMessage + +import deep_agent.context as context_module +from deep_agent.agent import create_deep_agent +from deep_agent.context import DeepAgentContext, date_line +from deep_agent.tools import metadata as metadata_tools +from tests.deep_agent.conftest import system_text + +CATALOGS = {1: "# catalog for connection 1", 2: "# catalog for connection 2"} + + +def _search_then_answer_policy(messages): + """Thread-local behaviour: one value search, then finish.""" + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "search_column_values", "args": {"search_term": "Acme"}, "id": "s1"}]) + return AIMessage("done") + + +def _catalog_by_connection(): + async def catalog(connection_id=None): + await asyncio.sleep(0.01) # force interleaving between the two requests + return CATALOGS.get(connection_id, "# default connection catalog") + return AsyncMock(side_effect=catalog) + + +def _value_client(): + async def search(search_term, table=None, column=None, limit=10, raw=False, connection_id=None): + await asyncio.sleep(0.01) + return {"values": [{"value": f"{search_term} @ {connection_id}"}]} + return MagicMock(search_column_values=AsyncMock(side_effect=search)) + + +@pytest.mark.asyncio +async def test_concurrent_requests_for_different_connections_are_isolated(policy_model, fake_catalog): + model = policy_model(_search_then_answer_policy) + agent = create_deep_agent(model=model) + fake_catalog.get_catalog_prompt = _catalog_by_connection() + client = _value_client() + + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + r1, r2 = await asyncio.gather( + agent.ainvoke({"messages": [("user", "q1")]}, {"configurable": {"thread_id": "conn-1"}}, + context=DeepAgentContext(connection_id=1)), + agent.ainvoke({"messages": [("user", "q2")]}, {"configurable": {"thread_id": "conn-2"}}, + context=DeepAgentContext(connection_id=2)), + ) + + # Each run loaded its own connection's catalog into its own state... + assert sorted(c.kwargs["connection_id"] for c in fake_catalog.get_catalog_prompt.await_args_list) == [1, 2] + assert (r1["jeen_catalog"], r2["jeen_catalog"]) == (CATALOGS[1], CATALOGS[2]) + # ...each model call saw only its own catalog... + prompts = [system_text(seen) for seen in model.seen] + for prompt in prompts: + assert (CATALOGS[1] in prompt) != (CATALOGS[2] in prompt) + # ...and tools called the metadata service with their own connection id. + assert sorted(c.kwargs["connection_id"] for c in client.search_column_values.await_args_list) == [1, 2] + v1 = json.loads(next(m for m in r1["messages"] if m.type == "tool").text) + v2 = json.loads(next(m for m in r2["messages"] if m.type == "tool").text) + assert v1["data"]["matches"][0]["value"] == "Acme @ 1" and v2["data"]["matches"][0]["value"] == "Acme @ 2" + + +@pytest.mark.asyncio +async def test_no_context_falls_back_to_default_connection(policy_model, fake_catalog): + agent = create_deep_agent(model=policy_model(lambda messages: AIMessage("done"))) + await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "default"}}) + assert fake_catalog.get_catalog_prompt.await_args.kwargs["connection_id"] is None # client uses its configured default + + +class _FrozenDatetime(datetime): + instant = datetime(2026, 10, 20, 20, 30, tzinfo=timezone.utc) + + @classmethod + def now(cls, tz=None): + return cls.instant.astimezone(tz) + + +def test_date_is_computed_in_jerusalem_time(monkeypatch): + monkeypatch.setattr(context_module, "datetime", _FrozenDatetime) + _FrozenDatetime.instant = datetime(2026, 10, 20, 21, 30, tzinfo=timezone.utc) # 00:30 on Oct 21 in Israel (UTC+3) + assert date_line("Asia/Jerusalem").startswith("Today's date: 2026-10-21 (Wednesday") + assert date_line("UTC").startswith("Today's date: 2026-10-20") + + +@pytest.mark.asyncio +async def test_date_is_injected_per_model_call_not_at_construction(scripted_model, monkeypatch): + monkeypatch.setattr(context_module, "datetime", _FrozenDatetime) + model = scripted_model(AIMessage("first"), AIMessage("first"), AIMessage("second"), AIMessage("second")) # + reminder replies + agent = create_deep_agent(model=model) # built "yesterday" + + _FrozenDatetime.instant = datetime(2026, 10, 20, 20, 30, tzinfo=timezone.utc) # 23:30 Oct 20 in Israel + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "d1"}}) + _FrozenDatetime.instant = datetime(2026, 10, 20, 21, 30, tzinfo=timezone.utc) # 00:30 Oct 21 in Israel + await agent.ainvoke({"messages": [("user", "b")]}, {"configurable": {"thread_id": "d2"}}) + + def last_human(messages): + return next(m for m in reversed(messages) if m.type == "human").text + + assert last_human(model.seen[0]).startswith("[Today's date: 2026-10-20") + assert last_human(model.seen[2]).startswith("[Today's date: 2026-10-21") + assert last_human(model.seen[2]).endswith("b") + # The system prompt is byte-identical across days, so provider prompt caching keeps working. + assert system_text(model.seen[0]) == system_text(model.seen[2]) + assert "Today's date" not in system_text(model.seen[1]) + + +@pytest.mark.asyncio +async def test_date_prefix_is_not_persisted_to_state(scripted_model): + agent = create_deep_agent(model=scripted_model(AIMessage("ok"), AIMessage("ok"))) + result = await agent.ainvoke({"messages": [("user", "שאלה")]}, {"configurable": {"thread_id": "p1"}}) + assert result["messages"][0].text == "שאלה" diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py new file mode 100644 index 0000000..3715741 --- /dev/null +++ b/agent/tests/deep_agent/test_service.py @@ -0,0 +1,245 @@ +import json +import os +import time +import uuid +from unittest.mock import AsyncMock, patch + +import pytest +from core.trino import TrinoExecutionResult +from langchain_core.messages import AIMessage + +from deep_agent import service +from deep_agent.agent import create_deep_agent +from deep_agent.answer import verification +from deep_agent.service import run_deep_chat, to_response +from deep_agent.tools import sql as sql_tools + +SQL = "SELECT COUNT(*) AS orders FROM orders WHERE status = 'shipped'" +OK = TrinoExecutionResult(success=True, rows=[[466]], columns=["orders"], row_count=1, query_id="q-1") + + +def _answer(sql=SQL, **extra): + return AIMessage("", tool_calls=[{"name": "submit_answer", "id": f"f{uuid.uuid4().hex[:4]}", "args": { + "sql": sql, "explanation_he": "סופר הזמנות שנשלחו", "confidence": "high", **extra}}]) + + +def _policy(messages): + """Turn 1 asks for clarification; after the user's reply, executes and answers.""" + humans = [m for m in messages if m.type == "human"] + if len(humans) == 1: + return _answer(sql=None, needs_clarification="האם הכוונה להזמנות שנשלחו או שנמסרו?") + last_tool = next((m for m in reversed(messages) if m.type == "tool"), None) + if last_tool is None or last_tool.name == "submit_answer": + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": f"e{len(messages)}"}]) + return _answer() + + +@pytest.fixture(autouse=True) +def no_tracing(monkeypatch): + """run_deep_chat builds a real Langfuse handler when tracing is on; never send test runs upstream.""" + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_TRACING_ENABLED", False) + + +@pytest.fixture +def published(): + with patch.object(service, "publish_node_event", AsyncMock()) as pub: + yield pub + + +# ── response mapping ───────────────────────────────────────────────────────── + +def test_completed_response_matches_legacy_contract(): + final = {"status": "matched", "verified": True, "sql": SQL, "error": None, + "answer": {"explanation_he": "הסבר", "confidence": "high", "assumptions": []}, + "result": {"columns": ["orders"], "rows": [[466]], "row_count": 1, "truncated": False, "query_id": "q"}} + r = to_response("deep-1", final, "trace-1", ["deep:execute_trino_query"]) + assert r["status"] == "completed" and r["sql_query"] == SQL and r["sql_explanation"] == "הסבר" + assert "| 466 |" in r["summary"] and "```sql" not in r["summary"] # SQL is returned separately + assert r["is_unanswerable"] is False and r["engine"] == "deep" and r["verification"] == "matched" + assert r["executed"] is False and r["recovered_from_text"] is False # absent in final -> False + assert to_response("t", {**final, "executed": True, "recovered_from_text": True}, None, [])["executed"] is True + assert {"thread_id", "status", "summary", "raw_data_ref", "sql_query", "sql_explanation", "trace_id", + "execution_path", "is_unanswerable"} <= set(r) + + +@pytest.mark.parametrize("status", ["no_answer", "rejected", "re_execution_failed"]) +def test_unanswered_statuses(status): + assert to_response("t", {"status": status, "answer": None}, None, [])["is_unanswerable"] is True + + +def test_clarification_maps_to_free_text_hitl(): + r = to_response("t", {"status": "clarification", "answer": {"needs_clarification": "איזו שנה?"}}, None, []) + assert r["status"] == "interrupted" + assert r["interrupt_details"] == {"type": "hitl_escalation", "subtype": "clarification", "reason": "איזו שנה?"} + + +# ── full turns ─────────────────────────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_clarify_then_resume_on_the_same_thread(policy_model, published): + agent = create_deep_agent(model=policy_model(_policy), clarifications_enabled=True) + with patch.object(sql_tools, "execute_query_sync", return_value=OK): + first = await run_deep_chat(connection_id=89, query="כמה הזמנות נשלחו", thread_id="deep-t1", agent=agent) + second = await run_deep_chat(connection_id=89, thread_id="deep-t1", agent=agent, + resume_value={"approved": False, "feedback": "שנשלחו"}) + + assert first["status"] == "interrupted" and "שנשלחו" in first["interrupt_details"]["reason"] + assert second["status"] == "completed" and second["sql_query"] == SQL + assert second["verification"] == "matched" and second["executed"] is True and "466" in second["summary"] + assert second["execution_path"] == ["deep:execute_trino_query"] + + events = [(c.args[1], c.args[2]) for c in published.await_args_list] + assert ("deep:execute_trino_query", "active") in events and ("deep:execute_trino_query", "completed") in events + assert events[-1] == ("deep:answer", "completed") + assert all(c.args[0] == "deep-t1" for c in published.await_args_list) + + +@pytest.mark.asyncio +async def test_turn_without_new_answer_does_not_repeat_the_previous_one(scripted_model, published): + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + AIMessage("small talk, no answer"), + AIMessage("still no answer"), # reply to the submit reminder + ) + agent = create_deep_agent(model=model) + with patch.object(sql_tools, "execute_query_sync", return_value=OK): + first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t2", agent=agent) + second = await run_deep_chat(connection_id=89, query="ותודה", thread_id="deep-t2", agent=agent) + assert first["verification"] == "matched" + assert second["verification"] == "no_answer" and second["sql_query"] is None + + +@pytest.mark.asyncio +async def test_answer_must_run_in_its_own_turn(scripted_model, published): + """Turn 2 submits turn 1's SQL without running it: refused; the agent runs it and submits again.""" + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + _answer(), # turn 2: not run yet + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e2"}]), + _answer(), + ) + agent = create_deep_agent(model=model) + with patch.object(sql_tools, "execute_query_sync", side_effect=lambda *a, **k: TrinoExecutionResult( + success=True, rows=[[466]], columns=["orders"], row_count=1, query_id=str(uuid.uuid4()))), \ + patch.object(verification, "execute_query_sync") as rerun: + first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t3", agent=agent) + second = await run_deep_chat(connection_id=89, query="ושוב", thread_id="deep-t3", agent=agent) + assert first["verification"] == second["verification"] == "matched" + rerun.assert_not_called() + + +@pytest.mark.asyncio +async def test_checkpoints_hold_only_plain_data(scripted_model, published, caplog): + """The answer object isn't kept in thread state (checkpoints can't restore its class); final_result is.""" + agent = create_deep_agent(model=scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer())) + with patch.object(sql_tools, "execute_query_sync", return_value=OK): + await run_deep_chat(connection_id=89, query="q", thread_id="deep-t5", agent=agent) + state = (await agent.aget_state({"configurable": {"thread_id": "deep-t5"}})).values + assert state.get("structured_response") is None + assert state["final_result"]["answer"]["sql"] == SQL + assert "unregistered type" not in caplog.text + + +@pytest.mark.asyncio +async def test_timeout_s_cancels_the_run(scripted_model, published): + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + ) + agent = create_deep_agent(model=model) + + def slow_query(*args, **kwargs): + time.sleep(1.0) + return OK + + # A query already running in a worker thread can't be interrupted; the run stops there. + with patch.object(sql_tools, "execute_query_sync", side_effect=slow_query): + r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t4", agent=agent, timeout_s=0.3) + assert r["verification"] == "no_answer" and r["executed"] is False and r["is_unanswerable"] is True + assert "stopped after 0.3s" in r["summary"] + assert model.seen and len(model.seen) == 1 # the model was never called again after the cancel + + +@pytest.mark.asyncio +async def test_missing_query_is_an_error(): + assert "error" in await run_deep_chat(connection_id=1, query=None, thread_id="deep-x", agent=object()) + assert "error" in await run_deep_chat(connection_id=1, thread_id="deep-x", resume_value={"approved": True}, + agent=object()) + + +# ── MCP tools ──────────────────────────────────────────────────────────────── + +@pytest.mark.asyncio +@pytest.mark.parametrize("hitl, expected_status", [(True, "interrupted"), (False, "completed")]) +async def test_deep_agent_tool(hitl, expected_status): + from agent import mcp_server + + clarification = to_response("deep-z", {"status": "clarification", "answer": {"needs_clarification": "?"}}, None, []) + with patch("deep_agent.service.run_deep_chat", AsyncMock(return_value=clarification)) as run, \ + patch.object(mcp_server.agent_graph, "ainvoke") as legacy: + raw = await mcp_server.deep_agent(connection_id=89, query="q", hitl_enabled=hitl) + out = json.loads(raw) + legacy.assert_not_called() + assert run.await_args.kwargs["thread_id"].startswith("deep-") + assert run.await_args.kwargs["timeout_s"] is None # no limit unless the caller passes one + assert out["status"] == expected_status + + +@pytest.mark.asyncio +async def test_each_tool_refuses_the_other_agents_threads(): + from agent import mcp_server + + with patch("deep_agent.service.run_deep_chat", AsyncMock()) as run, \ + patch.object(mcp_server.agent_graph, "ainvoke") as legacy: + to_legacy = json.loads(await mcp_server.chat_with_agent(connection_id=89, thread_id="deep-abc", resume_value="x")) + to_deep = json.loads(await mcp_server.deep_agent(connection_id=89, thread_id="legacy-thread", resume_value="x")) + assert "deep_agent tool" in to_legacy["error"] and "chat_with_agent" in to_deep["error"] + run.assert_not_awaited() + legacy.assert_not_called() + + +# ── durable threads (real Postgres) ────────────────────────────────────────── + +PG_URL = os.environ.get("DEEP_AGENT_TEST_PG_URL") + + +@pytest.mark.asyncio +@pytest.mark.skipif(not PG_URL, reason="set DEEP_AGENT_TEST_PG_URL to a throwaway Postgres database") +async def test_threads_survive_a_restart_with_postgres(scripted_model, monkeypatch): + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_CHECKPOINT_DB_URL", PG_URL) + thread = f"deep-durable-{uuid.uuid4().hex[:8]}" + + first_process = create_deep_agent(model=scripted_model(AIMessage("first")), checkpointer=await service.build_checkpointer()) + await first_process.ainvoke({"messages": [("user", "שאלה ראשונה")]}, {"configurable": {"thread_id": thread}}) + await service._pg_pool.close() + + # "Restart": a new agent with a new pool sees the same thread. + second_process = create_deep_agent(model=scripted_model(AIMessage("second")), checkpointer=await service.build_checkpointer()) + state = await second_process.aget_state({"configurable": {"thread_id": thread}}) + assert [m.text for m in state.values["messages"] if m.type == "human"] == ["שאלה ראשונה"] + await service._pg_pool.close() + + +@pytest.mark.asyncio +async def test_review_appears_in_the_stream(scripted_model, published): + brief = f"```sql\n{SQL}\n```" + main = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + AIMessage("", tool_calls=[{"name": "task", "args": {"description": brief, "subagent_type": "semantic-validator"}, + "id": "r1"}]), + _answer()) + reviewer = scripted_model( + AIMessage("", tool_calls=[{"name": "submit_verdict", "args": {"verdict": "pass"}, "id": "v1"}]), + ) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + with patch.object(sql_tools, "execute_query_sync", return_value=OK): + r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t6", agent=agent) + assert r["execution_path"] == ["deep:execute_trino_query", "deep:task"] # the reviewer runs no tools + assert r["semantic_validation"]["verdict"] == "passed" diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py new file mode 100644 index 0000000..933be66 --- /dev/null +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -0,0 +1,200 @@ +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +import tiktoken +from core.trino import TrinoExecutionResult + +import agent.utils.jeen_metadata_client as jmc +from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError +from deep_agent import tools +from deep_agent.tools import DEEP_AGENT_TOOLS +from deep_agent.tools import location as location_tools +from deep_agent.tools import metadata as metadata_tools +from deep_agent.tools import sql as sql_tools + +ALL_TOOLS = DEEP_AGENT_TOOLS + +# Minimal valid arguments for every tool (each must honour the envelope). +TOOL_ARGS = { + "search_column_values": {"search_term": "תל אביב"}, + "resolve_location_to_wkt": {"location_name": "חיפה"}, + "execute_trino_query": {"sql": "SELECT 1"}, + "get_sample_rows": {"table_name": "t"}, + "get_column_distinct_values": {"table_name": "t", "column_name": "c"}, + "validate_sql": {"sql": "SELECT 1"}, +} + + +def _client(fail: bool) -> MagicMock: + client = MagicMock() + names = ["get_catalog_prompt", "get_tables", "get_columns", "get_relationships", "get_table_profile", + "search", "search_business_terms", "search_knowledge_pairs", "search_column_values"] + for name in names: + if fail: + setattr(client, name, AsyncMock(side_effect=JeenMetadataError(f"{name} exploded"))) + else: + setattr(client, name, AsyncMock(return_value={"values": [{"value": "v"}]} if name == "search_column_values" + else "# catalog" if name == "get_catalog_prompt" else [{"x": 1}])) + return client + + +@pytest.fixture +def patched(request): + fail = request.param + trino_res = (TrinoExecutionResult(success=False, error_message="boom", error_name="GENERIC_INTERNAL_ERROR", + error_type="INTERNAL_ERROR") + if fail else TrinoExecutionResult(success=True, rows=[[1]], columns=["a"], row_count=1)) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=_client(fail)), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino_res), \ + patch.object(location_tools, "get_geojson_polygon", return_value=None if fail else {"type": "Polygon"}), \ + patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): + yield fail + + +def test_every_tool_is_covered(): + assert {t.name for t in ALL_TOOLS} == set(TOOL_ARGS) + + +def test_registered_tool_set(): + """The catalog is loaded for every run (CatalogMiddleware), so there is no catalog tool, and the + tools whose information the catalog already contains are not offered to the model.""" + assert {t.name for t in DEEP_AGENT_TOOLS} == { + "search_column_values", "get_column_distinct_values", "resolve_location_to_wkt", + "execute_trino_query", "get_sample_rows", "validate_sql", + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize("patched", [False, True], ids=["success", "failure"], indirect=True) +@pytest.mark.parametrize("tool", ALL_TOOLS, ids=lambda t: t.name) +async def test_tool_returns_envelope(tool, patched): + raw = await tool.ainvoke(TOOL_ARGS[tool.name]) + out = json.loads(raw) + assert set(out) == {"ok", "data", "error"}, raw + assert out["ok"] is (not patched), raw + if patched: + assert out["data"] is None + assert {"name", "message"} <= set(out["error"]) + assert "hint" not in out["error"] and "category" not in out["error"] + else: + assert out["error"] is None + assert "\n " not in raw, "envelope must be compact (no indentation)" + + +@pytest.mark.asyncio +async def test_metadata_failure_says_data_is_not_empty(): + client = MagicMock(search_column_values=AsyncMock(side_effect=JeenMetadataError("auth expired"))) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + out = json.loads(await tools.search_column_values.ainvoke({"search_term": "x"})) + assert out["error"]["name"] == "METADATA_ERROR" + assert "auth expired" in out["error"]["message"] + assert "does not mean the data is empty" in out["error"]["message"] + + +@pytest.mark.asyncio +async def test_mcp_is_error_flag_raises(): + result = SimpleNamespace(isError=True, content=[SimpleNamespace(text="connection_id 999 not found")]) + session = MagicMock() + session.initialize = AsyncMock() + session.call_tool = AsyncMock(return_value=result) + session_cm = MagicMock(__aenter__=AsyncMock(return_value=session), __aexit__=AsyncMock(return_value=False)) + transport_cm = MagicMock(__aenter__=AsyncMock(return_value=(None, None, None)), __aexit__=AsyncMock(return_value=False)) + with patch.object(jmc, "streamablehttp_client", return_value=transport_cm), \ + patch.object(jmc, "ClientSession", return_value=session_cm): + with pytest.raises(JeenMetadataError, match="connection_id 999 not found"): + await jmc._call_mcp_tool("http://x", "k", "get_relationships", {}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["get_tables", "get_columns", "get_relationships"]) +async def test_unexpected_payload_is_an_error_not_empty(method): + client = JeenMetadataClient() + with patch.object(client, "_call", AsyncMock(return_value="Error: auth expired")): + with pytest.raises(JeenMetadataError, match="auth expired"): + await getattr(client, method)() + + +async def _search(values): + client = MagicMock(search_column_values=AsyncMock(return_value={"values": values})) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + return json.loads(await tools.search_column_values.ainvoke({"search_term": "x"})) + + +@pytest.mark.asyncio +async def test_search_values_handles_nulls_and_numbers(): + out = await _search([ + {"value": 12345, "table_name": "t", "column_name": "unit_id", "keyword_similarity": None, "semantic_distance": None}, + {"value": None, "keyword_similarity": "n/a"}, + "bare-string", + ]) + assert out["ok"] is True + m = out["data"]["matches"] + assert m[0] == {"value": 12345, "table": "t", "column": "unit_id", "keyword_similarity": None, "semantic_distance": None} + assert m[1]["value"] is None + assert m[2] == {"value": "bare-string"} + + +@pytest.mark.asyncio +async def test_search_values_returns_every_match_without_prefix_guessing(): + values = [f"תל אביב {i}" for i in range(15)] + out = await _search([{"value": v, "keyword_similarity": 0.9, "semantic_distance": 0.1} for v in values]) + assert [m["value"] for m in out["data"]["matches"]] == values + assert "prefix_pattern" not in out["data"] + + +@pytest.mark.asyncio +async def test_search_values_says_when_the_limit_was_hit(): + full = await _search([{"value": f"v{i}"} for i in range(10)]) # default limit 10 + assert full["data"]["limit_reached"] is True and "higher limit" in full["data"]["notice"] + fewer = await _search([{"value": "v1"}, {"value": "v2"}]) + assert fewer["data"]["limit_reached"] is False and fewer["data"]["notice"] is None + + +@pytest.mark.asyncio +async def test_search_values_no_match_points_at_unindexed_column_types(): + notice = (await _search([]))["data"]["notice"] + assert all(t in notice for t in ("`id`", "`continuous`", "`time`", "`free_text`", "doesn't exist")) + + +@pytest.mark.asyncio +async def test_search_values_passes_limit_through_unclamped(): + client = MagicMock(search_column_values=AsyncMock(return_value={"values": []})) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + await tools.search_column_values.ainvoke({"search_term": "x", "limit": 500}) + assert client.search_column_values.call_args.kwargs["limit"] == 500 + + +@pytest.mark.asyncio +async def test_location_returns_the_polygon_once(): + with patch.object(location_tools, "get_geojson_polygon", return_value={"type": "Polygon"}), \ + patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): + out = json.loads(tools.resolve_location_to_wkt.invoke({"location_name": "חיפה"})) + assert out["data"] == {"location": "חיפה", "wkt": "POLYGON((0 0, 1 0, 1 1, 0 0))"} + + +def _old_search_column_values_output(search_term: str, res: dict) -> str: + """The pre-#45 output format (summary + indent=2 full payload), reproduced for comparison.""" + lines = [f"TOP MATCHES for '{search_term}' (use these exact strings in SQL):"] + for v in res["values"][:5]: + lines.append(f" - '{v['value']}' (table: {v['table_name']}, column: {v['column_name']}, " + f"keyword_sim: {round(v['keyword_similarity'], 3)}, sem_dist: {round(v['semantic_distance'], 3)})") + return "\n".join(lines) + "\n\nFull payload:\n" + json.dumps(res, indent=2, ensure_ascii=False) + + +@pytest.mark.asyncio +async def test_search_values_output_is_at_least_40_percent_smaller(): + res = {"values": [ + {"value": f"תל אביב {i}", "table_name": "city_info_table", "column_name": "city_name", + "keyword_similarity": 0.912345 - i / 100, "semantic_distance": 0.123456 + i / 100, + "semantic_type": "large_categorical", "connection_id": 89, "embedding_model": "nomic-embed-text"} + for i in range(10) + ]} + client = MagicMock(search_column_values=AsyncMock(return_value=res)) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + new = await tools.search_column_values.ainvoke({"search_term": "תל אביב"}) + enc = tiktoken.get_encoding("o200k_base") + old_tokens = len(enc.encode(_old_search_column_values_output("תל אביב", res))) + new_tokens = len(enc.encode(new)) + assert new_tokens <= 0.6 * old_tokens, (old_tokens, new_tokens) diff --git a/agent/tests/deep_agent/test_trino_errors.py b/agent/tests/deep_agent/test_trino_errors.py new file mode 100644 index 0000000..21a7a62 --- /dev/null +++ b/agent/tests/deep_agent/test_trino_errors.py @@ -0,0 +1,118 @@ +import json +from pathlib import Path +from unittest.mock import MagicMock, patch + +import core.trino as core_trino +import pytest +import trino.exceptions +from core.trino import TrinoExecutionResult + +from deep_agent import tools +from deep_agent.tools import sql as sql_tools +from deep_agent.tools import trino_errors + +FIXTURES = json.loads((Path(__file__).parent.parent / "fixtures" / "trino_errors.json").read_text(encoding="utf-8")) + + +def _failing_connection(exc: Exception) -> MagicMock: + conn = MagicMock() + conn.cursor.return_value.execute.side_effect = exc + return conn + + +def _run_through_core(error: dict) -> TrinoExecutionResult: + exc = trino.exceptions.TrinoUserError(error, query_id="20261020_000000_00001_abcde") + with patch.object(core_trino.settings, "TRINO_ENABLED", True), \ + patch.object(core_trino, "get_trino_connection", return_value=_failing_connection(exc)): + return core_trino.execute_query_sync("SELECT 1") + + +@pytest.mark.parametrize("error", FIXTURES, ids=[e["errorName"] for e in FIXTURES]) +def test_trino_errors_are_passed_through_unchanged(error): + res = _run_through_core(error) + assert res.success is False + assert res.error_message == error["message"] # clean message, not the exception repr + assert res.query_id == "20261020_000000_00001_abcde" + + out = trino_errors.from_result(res) + assert out["name"] == error["errorName"] + assert out["type"] == error["errorType"] + assert out["message"] == error["message"] + location = error.get("errorLocation") + if location: + assert out["location"] == {"line": location["lineNumber"], "column": location["columnNumber"]} + else: + assert "location" not in out + + +def test_connection_failure_is_reported_as_connection_error(): + exc = ConnectionError("HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /v1/statement") + with patch.object(core_trino.settings, "TRINO_ENABLED", True), \ + patch.object(core_trino, "get_trino_connection", return_value=_failing_connection(exc)): + res = core_trino.execute_query_sync("SELECT 1") + out = trino_errors.from_result(res) + assert out["name"] == "CONNECTION_ERROR" + assert "type" not in out + assert "Max retries exceeded" in out["message"] + + +def test_execute_tool_returns_trinos_error(): + res = TrinoExecutionResult( + success=False, error_message="line 1:8: Function 'st_geomfromtext' not registered", + error_name="FUNCTION_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 8), query_id="q1", + ) + with patch.object(sql_tools, "execute_query_sync", return_value=res): + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT ST_GeomFromText('POINT(1 1)')"})) + assert out == { + "ok": False, + "data": None, + "error": { + "name": "FUNCTION_NOT_FOUND", + "message": "line 1:8: Function 'st_geomfromtext' not registered", + "type": "USER_ERROR", + "location": {"line": 1, "column": 8}, + "query_id": "q1", + "execution_time_ms": 0, + }, + } + + +def test_execute_tool_reports_exceptions_as_connection_error(): + with patch.object(sql_tools, "execute_query_sync", side_effect=OSError("connection refused")): + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT 1"})) + assert out["error"]["name"] == "CONNECTION_ERROR" + assert out["error"]["message"] == "connection refused" + + +def test_validate_returns_trinos_error(): + res = TrinoExecutionResult( + success=False, error_message="line 1:32: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), + ) + with patch.object(sql_tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) + assert out["ok"] is False + assert out["error"]["name"] == "COLUMN_NOT_FOUND" + assert out["error"]["type"] == "USER_ERROR" + + +def test_validate_reports_location_against_the_callers_sql(): + # Trino sees "EXPLAIN (TYPE VALIDATE) SELECT x FROM t"; 'x' is at column 32 there, column 8 in the caller's SQL. + res = TrinoExecutionResult( + success=False, error_message="line 1:32: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), + ) + with patch.object(sql_tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) + assert out["error"]["location"] == {"line": 1, "column": 8} + assert out["error"]["message"] == "line 1:32: Column 'x' cannot be resolved" # Trino's message stays raw + + +def test_validate_leaves_later_lines_alone(): + res = TrinoExecutionResult( + success=False, error_message="line 3:7: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(3, 7), + ) + with patch.object(sql_tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT a\nFROM t\nWHERE x = 1"})) + assert out["error"]["location"] == {"line": 3, "column": 7} diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py new file mode 100644 index 0000000..78e4430 --- /dev/null +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -0,0 +1,149 @@ +import json +from unittest.mock import patch + +import pytest +from core.trino import TrinoExecutionResult + +from deep_agent import tools +from deep_agent.tools import sql as sql_tools + + +def _ok(n_rows: int) -> TrinoExecutionResult: + return TrinoExecutionResult( + success=True, rows=[[i] for i in range(n_rows)], columns=["id"], row_count=n_rows, execution_time_ms=1 + ) + + +@pytest.fixture +def trino(): + with patch.object(sql_tools, "execute_query_sync") as mock: + yield mock + + +@pytest.mark.parametrize("sql", ["DROP TABLE t", "DELETE FROM t", "SELECT 1; DROP TABLE t", "SELECT 1 -- x\n; DROP TABLE t"]) +def test_forbidden_sql_never_reaches_trino(trino, sql): + out = json.loads(tools.execute_trino_query.invoke({"sql": sql})) + assert out["ok"] is False + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" + trino.assert_not_called() + + +def test_limit_argument_is_clamped_and_truncation_reported(trino): + trino.return_value = _ok(101) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 1_000_000})) + executed = trino.call_args.args[0] + assert executed.endswith("LIMIT 101") + assert out["data"]["row_count"] == 100 + assert out["data"]["truncated"] is True + + +def test_omitted_limit_uses_the_configured_ceiling(trino, monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", 100) + trino.return_value = _ok(5) + tools.execute_trino_query.invoke({"sql": "SELECT id FROM t"}) + assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 101" + + +def test_no_ceiling_runs_sql_as_written_and_returns_every_row(trino, monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", None) + trino.return_value = _ok(5000) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t;"})) + assert trino.call_args.args[0] == "SELECT id FROM t" + assert out["data"]["row_count"] == 5000 + assert out["data"]["truncated"] is False + + +def test_no_ceiling_still_honours_an_explicit_limit(trino, monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", None) + trino.return_value = _ok(11) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 10})) + assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 11" + assert out["data"]["row_count"] == 10 + assert out["data"]["truncated"] is True + + +@pytest.mark.parametrize("raw", ["none", "None", "", "unlimited"]) +def test_row_ceiling_can_be_disabled_from_env(monkeypatch, raw): + from agent.config import AgentSettings + + monkeypatch.setenv("DEEP_AGENT_MAX_ROWS", raw) + monkeypatch.setenv("DEEP_AGENT_MAX_SAMPLE_ROWS", raw) + s = AgentSettings() + assert s.DEEP_AGENT_MAX_ROWS is None + assert s.DEEP_AGENT_MAX_SAMPLE_ROWS is None + + +def test_row_ceiling_defaults(monkeypatch): + from agent.config import AgentSettings + + monkeypatch.delenv("DEEP_AGENT_MAX_ROWS", raising=False) + monkeypatch.delenv("DEEP_AGENT_MAX_SAMPLE_ROWS", raising=False) + s = AgentSettings(_env_file=None) + assert (s.DEEP_AGENT_MAX_ROWS, s.DEEP_AGENT_MAX_SAMPLE_ROWS) == (100, 10) + + +def test_speed_limit_column_still_gets_limit(trino): + trino.return_value = _ok(3) + out = json.loads(tools.execute_trino_query.invoke({"sql": "```sql\nSELECT speed_limit FROM t;\n```", "limit": 10})) + assert trino.call_args.args[0] == "SELECT speed_limit FROM t LIMIT 11" + assert out["data"]["truncated"] is False + assert out["data"]["row_count"] == 3 + + +def test_trino_error_is_reported(trino): + trino.return_value = TrinoExecutionResult( + success=False, error_message="line 1:8: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", + ) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"})) + assert out["error"]["name"] == "COLUMN_NOT_FOUND" + + +def test_sample_rows_handles_hebrew_quoted_table(trino): + trino.return_value = _ok(2) + tools.get_sample_rows.invoke({"table_name": '"postgres"."public"."טבלת ערים"', "limit": 50}) + assert trino.call_args.args[0] == 'SELECT * FROM "postgres"."public"."טבלת ערים" LIMIT 11' + + +def test_sample_rows_rejects_injection(trino): + out = json.loads(tools.get_sample_rows.invoke({"table_name": "t; DROP TABLE t"})) + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" + trino.assert_not_called() + + +def test_distinct_values_quotes_hebrew_column(trino): + trino.return_value = _ok(1) + tools.get_column_distinct_values.invoke({"table_name": "postgres.public.t", "column_name": "שם עיר", "limit": 20}) + assert trino.call_args.args[0] == 'SELECT DISTINCT "שם עיר" FROM postgres.public.t LIMIT 21' + + +def test_distinct_values_ignore_the_row_ceiling(trino, monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", 100) + trino.return_value = _ok(301) + out = json.loads(tools.get_column_distinct_values.invoke({"table_name": "t", "column_name": "c", "limit": 300})) + assert trino.call_args.args[0].endswith("LIMIT 301") + assert out["data"]["row_count"] == 300 and out["data"]["truncated"] is True + assert "notice" not in out["data"] + + +def test_validate_rejects_writes_without_calling_trino(trino): + out = json.loads(tools.validate_sql.invoke({"sql": "DELETE FROM t"})) + assert out["ok"] is False + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" + trino.assert_not_called() + + +def test_validate_runs_explain_for_reads(trino): + trino.return_value = _ok(0) + assert json.loads(tools.validate_sql.invoke({"sql": "SELECT 1"}))["data"] == {"valid": True} + assert trino.call_args.args[0] == "EXPLAIN (TYPE VALIDATE) SELECT 1" + + +def test_sample_rows_says_when_the_limit_was_reduced(monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_SAMPLE_ROWS", 10) + res = TrinoExecutionResult(success=True, rows=[[i] for i in range(11)], columns=["a"], row_count=11, query_id="q") + with patch.object(sql_tools, "execute_query_sync", return_value=res): + reduced = json.loads(tools.get_sample_rows.invoke({"table_name": "t", "limit": 200})) + normal = json.loads(tools.get_sample_rows.invoke({"table_name": "t", "limit": 5})) + assert "limit reduced from 200 to 10" in reduced["data"]["notice"] and reduced["data"]["row_count"] == 10 + assert "notice" not in normal["data"] diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py new file mode 100644 index 0000000..909b3c0 --- /dev/null +++ b/agent/tests/deep_agent/test_validator.py @@ -0,0 +1,433 @@ +"""Independent semantic review (deep_agent.validator) and the two approvals submit_answer needs. + +The agent runs the SQL, has the `semantic-validator` subagent review it, then submits. submit_answer +only checks the records: the SQL ran this turn, and the reviewer passed it (or the agent disputes). +""" + +import itertools +import json +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +from core.trino import TrinoExecutionResult +from langchain_core.messages import AIMessage + +from deep_agent.agent import create_deep_agent +from deep_agent.answer import verification +from deep_agent.answer.middleware import NOT_REVIEWED, NOT_RUN +from deep_agent.answer.render import render_markdown +from deep_agent.answer.schema import ANSWER_RECEIVED, answer_schema +from deep_agent.answer.verification import normalize_sql, validation_summary +from deep_agent.observability import run_metrics +from deep_agent.tools import sql as sql_tools +from deep_agent.validator.reviewer import SubmitVerdict, parse_brief, review_request + +SQL = "SELECT COUNT(*) AS n FROM orders WHERE status = 'shipped'" +FIXED = "SELECT COUNT(DISTINCT order_id) AS n FROM orders WHERE status = 'shipped'" +QUESTION = "כמה הזמנות נשלחו?" +ISSUE = {"problem": "סופרים שורות ולא הזמנות", "evidence": "COUNT(*)=42 אבל COUNT(DISTINCT order_id)=40"} +_ids = itertools.count() + + +def _trino(*args, **kwargs): + """A successful execution with a fresh query id per run, like real Trino.""" + return TrinoExecutionResult(success=True, rows=[[42]], columns=["n"], row_count=1, query_id=f"q{next(_ids)}") + + +@contextmanager +def _fake_trino(): + """Every execution in the run (agent, reviewer, full-rows run) — never the real Trino.""" + with patch.object(sql_tools, "execute_query_sync", side_effect=_trino), \ + patch.object(verification, "execute_query_sync", side_effect=_trino): + yield + + +def _call(name, args, call_id): + return AIMessage("", tool_calls=[{"name": name, "args": args, "id": call_id}]) + + +def _execute(sql=SQL, call_id="e1", **extra): + return _call("execute_trino_query", {"sql": sql, **extra}, call_id) + + +def _review(sql=SQL, call_id="r1", prose=""): + brief = f"{prose}\n```sql\n{sql}\n```\nAssumptions:\n- הזמנה = שורה בטבלה" + return _call("task", {"description": brief, "subagent_type": "semantic-validator"}, call_id) + + +def _submit(sql=SQL, call_id="s1", **extra): + return _call("submit_answer", {"sql": sql, "explanation_he": "מספר ההזמנות שנשלחו", "confidence": "high", **extra}, + call_id) + + +def _verdict(verdict, issues=(), call_id="v1"): + return _call("submit_verdict", {"verdict": verdict, "issues": list(issues)}, call_id) + + +async def _run(main, reviewer=None, mode="always", question=QUESTION, thread="t"): + agent = create_deep_agent(model=main, semantic_validation=mode, validator_model=reviewer) + with _fake_trino(): + return await agent.ainvoke({"messages": [("user", question)]}, {"configurable": {"thread_id": thread}}) + + +def _texts(messages): + return "\n".join(m.text for m in messages) + + +def _submit_results(state): + return [m.text for m in state["messages"] if m.type == "tool" and m.name == "submit_answer"] + + +# ── the happy path: run → review → submit ──────────────────────────────────── + +@pytest.mark.asyncio +async def test_run_review_submit_is_accepted(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("pass"))) + assert _submit_results(state) == [ANSWER_RECEIVED] + final = state["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["reviewed_final_sql"] + + +@pytest.mark.asyncio +async def test_reviewer_input_is_built_from_facts_not_the_brief(scripted_model): + main = scripted_model(_execute(), _review(prose="my private reasoning: I already checked it, it is fine"), _submit()) + reviewer = scripted_model(_verdict("pass")) + await _run(main, reviewer) + + seen = reviewer.seen[0] + review = _texts(seen) + assert QUESTION in review # the user's own words, from the thread + assert SQL in review and "[42]" in review # the SQL and its recorded rows + assert "claims to check, not facts" in review and "הזמנה = שורה בטבלה" in review + assert "my private reasoning" not in review and "already checked" not in review # the brief's prose is dropped + assert '"catalog"."schema"."orders"' in review # the catalog, as for every call + user = [m for m in seen if m.type == "human"][0] + assert user.text.startswith("[Today") # the date, on the built input + + +# ── submit_answer checks the two approvals ─────────────────────────────────── + +@pytest.mark.asyncio +async def test_submit_without_running_is_refused(scripted_model): + main = scripted_model(_review(), _submit(), _execute(), _review(call_id="r2"), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + assert _submit_results(state) == [NOT_RUN, ANSWER_RECEIVED] + assert state["final_result"]["status"] == "matched" + + +@pytest.mark.asyncio +async def test_submit_without_review_is_refused(scripted_model): + main = scripted_model(_execute(), _submit(), _review(), _submit(call_id="s2")) + state = await _run(main, scripted_model(_verdict("pass"))) + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" + + +@pytest.mark.asyncio +async def test_sql_changed_after_review_is_refused(scripted_model): + main = scripted_model(_execute(), _execute(FIXED, "e2"), _review(), _submit(FIXED), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["sql"] == FIXED and state["final_result"]["semantic_validation"]["verdict"] == "passed" + + +@pytest.mark.asyncio +async def test_failed_review_refuses_submit_and_the_fix_is_reviewed(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(FIXED, "e2"), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("fail", [ISSUE]), _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + + refusal = _submit_results(state)[0] + assert refusal.startswith("Not submitted: the semantic-validator failed") and ISSUE["problem"] in refusal + final = state["final_result"] + assert final["sql"] == FIXED and final["semantic_validation"]["verdict"] == "passed" + assert final["semantic_validation"]["rounds"] == 2 + + +@pytest.mark.asyncio +async def test_submitting_a_failed_sql_with_a_justification_is_a_dispute(scripted_model): + main = scripted_model(_execute(), _review(), _submit(validation_response="כל שורה היא הזמנה אחת")) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "disputed" and review["issues"] == [ISSUE] + assert review["response"] == "כל שורה היא הזמנה אחת" + shown = render_markdown(state["final_result"]) + assert "בדיקה עצמאית העלתה הסתייגות" in shown and "תגובת הסוכן" in shown + + +@pytest.mark.asyncio +async def test_review_limit_accepts_an_unreviewed_sql_as_not_validated(scripted_model, monkeypatch): + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_VALIDATOR_MAX_ROUNDS", 1) + main = scripted_model(_execute(), _review(), _execute(FIXED, "e2"), _submit(FIXED)) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) + review = state["final_result"]["semantic_validation"] + assert state["final_result"]["sql"] == FIXED + assert review["verdict"] == "not_validated" and review["reason"] == "review limit reached (1)" + + +@pytest.mark.asyncio +async def test_brief_without_a_sql_block_cannot_approve_anything(scripted_model): + no_sql = _call("task", {"description": "please check my count query", "subagent_type": "semantic-validator"}, "r1") + main = scripted_model(_execute(), no_sql, _submit(), _review(call_id="r2"), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("fail", [{"problem": "no SQL", "evidence": "-"}]), _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + assert "none was provided" in _texts(reviewer.seen[0]) + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" + + +@pytest.mark.asyncio +async def test_off_mode_still_requires_that_the_sql_ran(scripted_model): + main = scripted_model(_submit(), _execute(), _submit(call_id="s2")) + state = await _run(main, mode="off") + assert _submit_results(state) == [NOT_RUN, ANSWER_RECEIVED] + assert state["final_result"]["status"] == "matched" + assert state["final_result"]["semantic_validation"] is None # review off + + +@pytest.mark.asyncio +async def test_truncated_sample_is_re_run_unchanged_for_all_rows(scripted_model): + sample = TrinoExecutionResult(success=True, rows=[[i] for i in range(6)], columns=["n"], row_count=6, query_id="s") + full = TrinoExecutionResult(success=True, rows=[[i] for i in range(40)], columns=["n"], row_count=40, query_id="f") + main = scripted_model(_execute(limit=5), _review(), _submit()) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=scripted_model(_verdict("pass"))) + with patch.object(sql_tools, "execute_query_sync", return_value=sample), \ + patch.object(verification, "execute_query_sync", return_value=full) as rerun: + state = await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "s"}}) + assert state["final_result"]["status"] == "re_executed" and state["final_result"]["result"]["row_count"] == 40 + assert rerun.call_args.args[0].startswith(SQL) + + +# ── strict submit: no fallback ──────────────────────────────────────────────── + +ANSWER_AS_TEXT = json.dumps({"sql": SQL, "explanation_he": "x", "confidence": "high"}) + + +@pytest.mark.asyncio +async def test_strict_submit_has_no_recovery_or_reminder(scripted_model, monkeypatch): + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_STRICT_SUBMIT", True) + state = await _run(scripted_model(_execute(), AIMessage(ANSWER_AS_TEXT)), mode="off") + assert state["final_result"]["status"] == "no_answer" + assert not [m for m in state["messages"] if getattr(m, "name", None) == "submit_reminder"] + + +@pytest.mark.asyncio +async def test_default_submit_fallback_recovers_an_answer_written_as_text(scripted_model): + state = await _run(scripted_model(_execute(), AIMessage(ANSWER_AS_TEXT)), mode="off") + assert state["final_result"]["status"] == "matched" and state["final_result"]["recovered_from_text"] is True + + +# ── the reviewer and its records ───────────────────────────────────────────── + +def test_parse_brief_takes_only_the_sql_and_the_bullets(): + sql, assumptions = parse_brief("I'm confident.\n```sql\nSELECT 1\n```\nAssumptions:\n- a\n* b\n1. c\nMore prose.") + assert sql == "SELECT 1" and assumptions == ["a", "b", "c"] + assert parse_brief("no sql here") == (None, []) + + +def test_review_request_marks_earlier_messages_and_missing_runs(): + text = review_request(["כמה טיסות יצאו מצרפת?", "ומאיטליה?"], SQL, [], []) + assert "Earlier user messages" in text and "כמה טיסות יצאו מצרפת?" in text + assert "Current user request\nומאיטליה?" in text + assert "has not run in this turn" in text and "(none stated)" in text + + +@pytest.mark.asyncio +async def test_follow_up_turn_gives_the_reviewer_the_earlier_question(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(FIXED, "e2"), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + config = {"configurable": {"thread_id": "follow-up"}} + with _fake_trino(): + await agent.ainvoke({"messages": [("user", QUESTION)]}, config) + state = await agent.ainvoke({"messages": [("user", "ובלי כפילויות?")]}, config) + second = _texts(reviewer.seen[1]) + assert "Earlier user messages" in second and QUESTION in second and "ובלי כפילויות?" in second + assert state["final_result"]["semantic_validation"]["rounds"] == 1 # counted per turn + + +def test_fail_verdict_needs_evidence(): + with pytest.raises(ValueError): + SubmitVerdict(verdict="fail", issues=[]) + assert SubmitVerdict(verdict="pass").issues == [] + + +def test_validation_response_only_exists_when_review_is_required(): + assert "validation_response" in answer_schema(False, True).model_fields + assert "validation_response" not in answer_schema(False, False).model_fields + + +def test_defaults(): + from agent.config import AgentSettings + + assert AgentSettings.model_fields["DEEP_AGENT_SEMANTIC_VALIDATION"].default == "always" + assert AgentSettings.model_fields["DEEP_AGENT_STRICT_SUBMIT"].default is False + + +def test_summary_looks_at_the_review_of_the_final_sql(): + records = [{"id": "1", "verdict": "pass", "sql": normalize_sql(SQL), "issues": []}, + {"id": "2", "verdict": "fail", "sql": normalize_sql(FIXED), "issues": [ISSUE]}] + assert validation_summary(records, SQL)["verdict"] == "passed" # not the later review of another SQL + assert validation_summary(records, FIXED)["verdict"] == "failed" + assert validation_summary([], SQL)["reason"] == "no review of the final SQL" + assert validation_summary(None, SQL) is None # review off + passed = run_metrics([], 1.0, {"semantic_validation": validation_summary(records, SQL)}) + assert passed.semantic_validation_passed is True and passed.validation_rounds == 2 + + +# ── unchanged harness behaviour ────────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_parallel_general_purpose_tasks_do_not_collide(policy_model): + """Every subagent returns the parent's state keys; two in one step must not be rejected.""" + def main_policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[ + {"name": "task", "id": f"g{i}", "args": {"description": "look", "subagent_type": "general-purpose"}} + for i in (1, 2)]) + return AIMessage("done") + + agent = create_deep_agent(model=policy_model(main_policy), semantic_validation="off") + state = await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "gp"}}) + assert [m.name for m in state["messages"] if m.type == "tool"][:2] == ["task", "task"] + + +def test_reminder_is_not_the_users_words(): + from langchain_core.messages import HumanMessage + + from deep_agent.context import REMINDER_NAME, current_turn + + messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] + assert current_turn(messages) == messages[1:] + + +@pytest.mark.asyncio +async def test_on_demand_offers_the_reviewer_but_submit_only_needs_a_run(scripted_model): + main = scripted_model(_execute(), _submit()) + state = await _run(main, scripted_model(), mode="on_demand") + assert _submit_results(state) == [ANSWER_RECEIVED] + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "not_validated" and review["reason"] == "no review of the final SQL" + assert "worth it before submit_answer" in _texts(main.seen[0]) or "semantic-validator" in _texts(main.seen[0]) + + +@pytest.mark.asyncio +async def test_on_demand_review_is_reported_when_the_agent_asks_for_it(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("pass")), mode="on_demand") + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" + + +@pytest.mark.asyncio +async def test_on_demand_failed_review_still_reaches_the_user(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE])), mode="on_demand") + assert _submit_results(state) == [ANSWER_RECEIVED] # on_demand: a failed review doesn't block submit + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "failed" and review["issues"][0]["problem"] == ISSUE["problem"] + assert ISSUE["problem"] in render_markdown(state["final_result"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode, offered", [("always", True), ("on_demand", True), ("off", False)]) +async def test_modes_offer_the_reviewer(scripted_model, mode, offered): + main = scripted_model(_execute(), _submit(), _review(), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("pass")) + await _run(main, reviewer, mode=mode) + task_tool = next((t for t in main.bound_tool_names[0] if t == "task"), None) + assert task_tool == "task" # general-purpose is always there + assert ("semantic-validator" in _texts(main.seen[0])) is offered + + +def _needs_check(checks, call_id="v1"): + return _call("submit_verdict", {"verdict": "needs_check", "checks": checks}, call_id) + + +CHECK = "SELECT COUNT(DISTINCT order_id) FROM orders" + + +@pytest.mark.asyncio +async def test_needs_check_sends_the_agent_to_run_it_and_the_reviewer_sees_the_result(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(CHECK, "e2"), _review(call_id="r2"), + _submit(call_id="s2")) + reviewer = scripted_model(_needs_check(["check whether order_id repeats across rows"]), + _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + + refusal = _submit_results(state)[0] + assert refusal.startswith("Not submitted: the semantic-validator asks for these checks") + assert "order_id repeats" in refusal + second = _texts(reviewer.seen[1]) + assert "Checks you asked for in your previous review" in second and "order_id repeats" in second + assert CHECK in second and "[42]" in second # the check's real recorded result + final = state["final_result"] + assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["rounds"] == 2 + + +@pytest.mark.asyncio +async def test_the_reviewer_has_no_sql_tools(scripted_model): + reviewer = scripted_model(_verdict("pass")) + await _run(scripted_model(_execute(), _review(), _submit()), reviewer) + assert reviewer.bound_tool_names[0] == ["submit_verdict"] + + +def test_needs_check_requires_named_checks(): + with pytest.raises(ValueError): + SubmitVerdict(verdict="needs_check") + assert SubmitVerdict(verdict="needs_check", checks=["x"]).checks == ["x"] + + +def test_pending_checks_without_new_queries_are_shown_as_none(): + records = [{"verdict": "needs_check", "checks": ["c1"], "after_execution": 1}] + executed = [{"submitted_sql": SQL, "executed_sql": SQL, "columns": ["n"], "rows": [[42]], "row_count": 1, + "truncated": False}] + text = review_request([QUESTION], SQL, [], executed, records) + assert "- c1" in text and "Queries the analyst ran since\n(none)" in text + + + +def test_parse_brief_ignores_an_inline_mention_of_a_sql_block(): + brief = ("Provide the SQL in a ```sql block``` and list assumptions. Also ```sql``` here.\n" + "```sql\nSELECT 1\n```\n- a") + assert parse_brief(brief) == ("SELECT 1", ["a"]) + + +@pytest.mark.parametrize("sql, expected", [ + ("SELECT a FROM t ORDER BY b DESC LIMIT 1", "it ends with LIMIT 1"), + ("WITH r AS (SELECT a, row_number() OVER (ORDER BY b DESC) rn FROM t) SELECT a FROM r WHERE rn = 1", "row_number()"), + ("SELECT max_by(a, b) FROM t", "max_by"), +]) +def test_notes_flag_sql_that_keeps_a_single_row(sql, expected): + from deep_agent.validator.reviewer import answer_notes + + notes = answer_notes(sql, None) + assert len(notes) == 1 and expected in notes[0] and "ties" in notes[0] + + +def test_notes_flag_cut_off_and_empty_results_and_stay_quiet_otherwise(): + from deep_agent.validator.reviewer import answer_notes + + rec = {"columns": ["a"], "rows": [[1]] * 100, "row_count": 100, "truncated": True} + assert "cut off at 100 rows" in answer_notes("SELECT a FROM t", rec)[0] + assert "empty (0 rows)" in answer_notes("SELECT a FROM t", {**rec, "rows": [], "row_count": 0, "truncated": False})[0] + assert answer_notes("SELECT a FROM t LIMIT 10", {**rec, "row_count": 3, "truncated": False}) == [] + + +def test_notes_reach_the_reviewer(): + executed = [{"submitted_sql": "SELECT a FROM t ORDER BY b DESC LIMIT 1", "executed_sql": "x", "columns": ["a"], + "rows": [[1]], "row_count": 1, "truncated": False}] + text = review_request([QUESTION], "SELECT a FROM t ORDER BY b DESC LIMIT 1", [], executed) + assert "## Notes on this answer" in text and "LIMIT 1" in text diff --git a/agent/tests/fixtures/trino_errors.json b/agent/tests/fixtures/trino_errors.json new file mode 100644 index 0000000..1183feb --- /dev/null +++ b/agent/tests/fixtures/trino_errors.json @@ -0,0 +1,15 @@ +[ + {"message": "line 1:8: Function 'st_geomfromtext' not registered", "errorCode": 44, "errorName": "FUNCTION_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:8: Unexpected parameters (varchar(10), integer) for function date_parse. Expected: date_parse(varchar(x), varchar(y))", "errorCode": 44, "errorName": "FUNCTION_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:8: Column 'fligth_id' cannot be resolved", "errorCode": 47, "errorName": "COLUMN_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:15: Table 'postgres.public.flight' does not exist", "errorCode": 46, "errorName": "TABLE_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 15}}, + {"message": "line 1:15: Schema 'pubic' does not exist", "errorCode": 45, "errorName": "SCHEMA_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 15}}, + {"message": "line 1:1: mismatched input 'SELEC'. Expecting: 'ALTER', 'ANALYZE', 'CALL', 'SELECT', 'WITH'", "errorCode": 1, "errorName": "SYNTAX_ERROR", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 1}}, + {"message": "line 3:5: Cannot apply operator: timestamp(3) = varchar(10)", "errorCode": 58, "errorName": "TYPE_MISMATCH", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 3, "columnNumber": 5}}, + {"message": "line 1:8: 'city_name' must be an aggregate expression or appear in GROUP BY clause", "errorCode": 2, "errorName": "EXPRESSION_NOT_AGGREGATE", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "Division by zero", "errorCode": 8, "errorName": "DIVISION_BY_ZERO", "errorType": "USER_ERROR"}, + {"message": "line 1:8: Column 'city_code' is ambiguous", "errorCode": 18, "errorName": "AMBIGUOUS_NAME", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "Value cannot be cast to timestamp: 2026-06-01T10:00:00Z", "errorCode": 9, "errorName": "INVALID_CAST_ARGUMENT", "errorType": "USER_ERROR"}, + {"message": "Query exceeded per-node memory limit of 1GB [Allocated: 1.00GB]", "errorCode": 131079, "errorName": "EXCEEDED_LOCAL_MEMORY_LIMIT", "errorType": "INSUFFICIENT_RESOURCES"}, + {"message": "Error opening Hive split: connection reset", "errorCode": 16777216, "errorName": "GENERIC_INTERNAL_ERROR", "errorType": "INTERNAL_ERROR"} +] diff --git a/agent/tests/test_sql_guard.py b/agent/tests/test_sql_guard.py new file mode 100644 index 0000000..57af282 --- /dev/null +++ b/agent/tests/test_sql_guard.py @@ -0,0 +1,182 @@ +import pytest +import sqlglot +from sqlglot import exp + +from agent.utils import sql_guard +from agent.utils.sql_guard import GuardError, distinct_values_sql, effective_cap, prepare, sample_rows_sql + + +def _outer_limit(sql: str) -> int | None: + tree = sqlglot.parse_one(sql, read="trino") + lim = tree.args.get("limit") + return int(lim.expression.this) if lim else None + + +@pytest.mark.parametrize("sql", [ + "INSERT INTO t VALUES (1)", + "UPDATE t SET a = 1", + "DELETE FROM t", + "MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN DELETE", + "DROP TABLE t", + "CREATE TABLE x AS SELECT * FROM t", + "ALTER TABLE t ADD COLUMN c int", + "CALL system.sync_partition_metadata('a', 'b', 'FULL')", + "GRANT SELECT ON t TO u", + "SET SESSION query_max_run_time = '1h'", + "SELECT 1; DROP TABLE t", + "SELECT 1; SELECT 2", + "SELECT * FROM TABLE(postgres.system.query(query => 'DELETE FROM t'))", + "SELECT 1 -- note\n; DROP TABLE t", + "SHOW TABLES -- note\n; DROP TABLE t", + "", + " ", +]) +def test_rejects_non_read_statements(sql): + with pytest.raises(GuardError): + prepare(sql, 50) + + +@pytest.mark.parametrize("sql", [ + "SELECT speed_limit FROM t", # 'limit' substring bypass + "WITH a AS (SELECT * FROM t LIMIT 5) SELECT * FROM a JOIN b ON 1=1", # inner LIMIT only + "SELECT * FROM t", +]) +def test_unbounded_selects_get_an_outer_limit(sql): + guarded = prepare(sql, 50) + assert guarded.is_query + assert _outer_limit(guarded.sql) == 51 # cap + 1 to detect truncation + + +def test_larger_explicit_limit_is_capped(): + guarded = prepare("SELECT * FROM t LIMIT 100000", 50) + assert _outer_limit(guarded.sql) == 51 + assert guarded.requested_limit == 100000 + + +def test_smaller_explicit_limit_is_kept(): + guarded = prepare("SELECT * FROM t LIMIT 5", 50) + assert _outer_limit(guarded.sql) == 5 + + +@pytest.mark.parametrize("sql", [ + "SELECT a FROM t UNION SELECT a FROM u", + "SELECT a FROM t UNION ALL SELECT a FROM u LIMIT 1000", + "SELECT a FROM t FETCH FIRST 1000 ROWS ONLY", +]) +def test_set_operations_and_fetch_get_the_cap(sql): + guarded = prepare(sql, 10) + assert _outer_limit(guarded.sql) == 11 + + +def test_union_order_by_keeps_its_order(): + # Wrapping in SELECT * FROM (...) would let Trino drop the inner ORDER BY. + guarded = prepare("SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a", 10) + tree = sqlglot.parse_one(guarded.sql, read="trino") + assert isinstance(tree, exp.Union) + assert tree.args.get("order") is not None + assert _outer_limit(guarded.sql) == 11 + + +@pytest.mark.parametrize("sql, rows", [ + ("SELECT a FROM t ORDER BY a FETCH FIRST 5 ROWS ONLY", 5), + ("SELECT a FROM t ORDER BY a FETCH FIRST 5 ROWS WITH TIES", 5), + ("SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a FETCH FIRST 3 ROWS ONLY", 3), +]) +def test_fetch_within_cap_is_kept_as_written(sql, rows): + guarded = prepare(sql, 100) + assert guarded.requested_limit == rows + assert guarded.sql == sql + + +def test_no_cap_runs_sql_exactly_as_written(): + sql = "SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a" + guarded = prepare(sql + ";", None) + assert guarded.sql == sql + assert guarded.row_cap is None + assert guarded.is_query + + +def test_no_cap_still_rejects_writes(): + with pytest.raises(GuardError): + prepare("DELETE FROM t", None) + + +@pytest.mark.parametrize("sql", [ + "SELECT a -- pick a\nFROM t", + "SELECT /* note */ a FROM t", + "SHOW TABLES FROM postgres.public -- note", +]) +def test_comments_are_allowed(sql): + prepare(sql, 10) + + +def test_comments_survive_the_limit_rewrite(): + guarded = prepare("SELECT a /* pick a */ FROM t LIMIT 5000", 10) + assert _outer_limit(guarded.sql) == 11 + assert "pick a" in guarded.sql + + +def test_string_literal_with_dashes_is_not_a_comment(): + guarded = prepare("SELECT * FROM t WHERE code = 'a--b'", 10) + assert "'a--b'" in guarded.sql + + +@pytest.mark.parametrize("sql", ["SHOW TABLES FROM postgres.public", "DESCRIBE postgres.public.t"]) +def test_show_and_describe_pass_without_limit(sql): + guarded = prepare(sql, 10) + assert not guarded.is_query + assert "LIMIT" not in guarded.sql.upper() + + +def test_trailing_semicolon_is_accepted(): + assert prepare("SELECT 1;", 10).is_query + + +def test_effective_cap(): + assert effective_cap(1_000_000, 100) == 100 + assert effective_cap(0, 100) == 1 + assert effective_cap(None, 100) == 100 + assert effective_cap(None, None) is None + assert effective_cap(1_000_000, None) == 1_000_000 + + +@pytest.mark.parametrize("table, expected", [ + ('"postgres"."public"."my table"', '"postgres"."public"."my table"'), + ('"postgres"."public"."שם טבלה"', '"postgres"."public"."שם טבלה"'), + ("postgres.public.flights_table", "postgres.public.flights_table"), + ("flights_table", "flights_table"), +]) +def test_sample_rows_sql_keeps_valid_identifiers(table, expected): + sql = sample_rows_sql(table, 5) + assert sql == f"SELECT * FROM {expected} LIMIT 6" + + +@pytest.mark.parametrize("table", [ + "x; DROP TABLE y", + '"a"."b"."c" UNION SELECT * FROM secrets', + "t WHERE 1=1", + "(SELECT 1)", + "", +]) +def test_sample_rows_sql_rejects_injection(table): + with pytest.raises(GuardError): + sample_rows_sql(table, 5) + + +@pytest.mark.parametrize("column, expected", [ + ("launch_country", '"launch_country"'), + ('"שם עיר"', '"שם עיר"'), + ("שם עיר", '"שם עיר"'), + ('weird"name', '"weird""name"'), +]) +def test_distinct_values_sql_quotes_columns(column, expected): + sql = distinct_values_sql('"postgres"."public"."t"', column, 20) + assert sql == f'SELECT DISTINCT {expected} FROM "postgres"."public"."t" LIMIT 21' + sql_guard.parse_read_statement(sql) # the generated SQL itself passes the guard + + +def test_distinct_values_column_injection_is_neutralised(): + sql = distinct_values_sql("t", "a FROM t; DROP TABLE t", 5) + # The whole input becomes one quoted identifier, never executable SQL. + assert sql == 'SELECT DISTINCT "a FROM t; DROP TABLE t" FROM t LIMIT 6' + sql_guard.parse_read_statement(sql) diff --git a/agent/uv.lock b/agent/uv.lock index bab98fa..aac3d5a 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -8,6 +8,7 @@ version = "0.1.0" source = { editable = "." } dependencies = [ { name = "core" }, + { name = "deepagents" }, { name = "esca-sdk" }, { name = "fastapi" }, { name = "greenlet" }, @@ -17,9 +18,12 @@ dependencies = [ { name = "langchain-openai" }, { name = "langfuse" }, { name = "langgraph" }, + { name = "langgraph-checkpoint-postgres" }, { name = "mcp" }, { name = "networkx" }, + { name = "psycopg", extra = ["binary", "pool"] }, { name = "pydantic-settings" }, + { name = "pyyaml" }, { name = "shapely" }, { name = "sqlglot" }, { name = "trino" }, @@ -38,7 +42,8 @@ dev = [ [package.metadata] requires-dist = [ - { name = "core", directory = "../core" }, + { name = "core", editable = "../core" }, + { name = "deepagents", specifier = ">=0.6.12" }, { name = "esca-sdk", git = "https://github.com/elirazpevz/esca.git?subdirectory=packages%2Fesca-sdk" }, { name = "fastapi", specifier = ">=0.115.6" }, { name = "greenlet", specifier = ">=3.5.1" }, @@ -48,9 +53,12 @@ requires-dist = [ { name = "langchain-openai", specifier = "==1.3.5" }, { name = "langfuse", specifier = ">=2.0.0" }, { name = "langgraph" }, + { name = "langgraph-checkpoint-postgres", specifier = ">=2.0" }, { name = "mcp", specifier = ">=1.12.4" }, { name = "networkx", specifier = ">=3.3" }, + { name = "psycopg", extras = ["binary", "pool"], specifier = ">=3.2" }, { name = "pydantic-settings", specifier = ">=2.7.0" }, + { name = "pyyaml", specifier = ">=6.0" }, { name = "shapely", specifier = ">=2.0.0" }, { name = "sqlglot", specifier = ">=25.0.0" }, { name = "trino", specifier = ">=0.328.0" }, @@ -99,6 +107,25 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, ] +[[package]] +name = "anthropic" +version = "0.121.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "docstring-parser" }, + { name = "httpx" }, + { name = "jiter" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0f/ca/3cb2c20ee729736fbd4546d5d8b67e818288529fe70cb7a80dbf80aef70b/anthropic-0.121.0.tar.gz", hash = "sha256:e79d6e08ab3376602fc9a70d4d5ea3540817c76cf7e16658bed790834e1833d6", size = 1013292, upload-time = "2026-08-07T17:11:07.241Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/91/b3d41643f1f639927e8c5fb02c3bd8bffe6f1f29e219b3bd4c61e267b15c/anthropic-0.121.0-py3-none-any.whl", hash = "sha256:6048713fa441e59e1cba8363171cd2a86273b25bd213e9c7ac70a523af88b011", size = 1035493, upload-time = "2026-08-07T17:11:08.508Z" }, +] + [[package]] name = "anyio" version = "4.14.0" @@ -146,6 +173,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" }, ] +[[package]] +name = "bracex" +version = "3.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/01/5f394b8bcd6e5b92f73130990960423bbb19711f906bd9fe9ea5557c667c/bracex-3.0.1.tar.gz", hash = "sha256:4e38e32392e4a4780fe15d644bfc7c8514057cfc3861e060b11814ce829c25e4", size = 44019, upload-time = "2026-07-20T13:43:00.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/8f/6f7273a7adb8d73fc8d21ede4376a3e475e52f98435c6007f69100dec8ca/bracex-3.0.1-py3-none-any.whl", hash = "sha256:6523ad83aeb5098a4ee597cff0f964442ff74e460bd3fafaffab6a013ff2288c", size = 11940, upload-time = "2026-07-20T13:42:59.268Z" }, +] + [[package]] name = "certifi" version = "2026.5.20" @@ -155,6 +191,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/59/8c/57e832b7af6d7c5abe66eb3fbe3a3a32f4d11ea23a1aa7131371035be991/certifi-2026.5.20-py3-none-any.whl", hash = "sha256:3c52e209ba0a4ad7aebe60436a4ab349c39e1e602e8c134221e546902ad25897", size = 134134, upload-time = "2026-05-20T11:46:48.578Z" }, ] +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, +] + [[package]] name = "charset-normalizer" version = "3.4.7" @@ -204,7 +263,7 @@ wheels = [ [[package]] name = "core" version = "0.1.0" -source = { directory = "../core" } +source = { editable = "../core" } dependencies = [ { name = "alembic" }, { name = "langchain" }, @@ -258,6 +317,60 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/3c/1a983b9a745d7f83d53f057bcc5bf79ba6a2bbc08266b3f0c7d6fe630c9b/coverage-7.14.1-py3-none-any.whl", hash = "sha256:a252f21c27e38347e60111a3266b03827422a7d5525951aceee313aa68bab1d2", size = 211815, upload-time = "2026-05-26T20:41:34.078Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/41/6cbdcf9142d00fe82836fbb51e503e58088575cf7a0fe1dbff6695bf0840/cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9", size = 880201, upload-time = "2026-07-31T14:25:10.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/5c/59086b4aac5e879d38ddbcf74e4be7ade89cebc3eb199a55da998c3bb46a/cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03", size = 4001252, upload-time = "2026-07-31T14:23:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, + { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, + { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, + { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, + { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, + { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, + { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, + { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, + { url = "https://files.pythonhosted.org/packages/32/2e/c9db68a0c4bfa28e310707527c0ee3a2bd254104d2e02e68f368e197aa4c/cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30", size = 3840395, upload-time = "2026-07-31T14:23:56.677Z" }, + { url = "https://files.pythonhosted.org/packages/03/37/73d005be173aff344af30e9fd2a576575cb2391a7101d9cd3842e1fa8cce/cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07", size = 4036009, upload-time = "2026-07-31T14:24:24.122Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, + { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, + { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, + { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, + { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, + { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, + { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/4a22984d4f1bdfb8c054f07a92bc176b97a3134cc1d6c4b3bffb1f3688b4/cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba", size = 3874135, upload-time = "2026-07-31T14:24:50.085Z" }, +] + +[[package]] +name = "deepagents" +version = "0.6.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "langchain" }, + { name = "langchain-anthropic" }, + { name = "langchain-core" }, + { name = "langchain-google-genai" }, + { name = "langsmith" }, + { name = "wcmatch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/db/a6acdc72a9e90c3f07ed10de35c951734a02d4facb693bb59684ad368801/deepagents-0.6.12.tar.gz", hash = "sha256:1f281c0bc5a63132f62e2ee345c1dc593b23188da6e23016401f6879fbe54b5f", size = 211364, upload-time = "2026-06-25T17:26:52.775Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/49/af7219b3c13520fee047bb807cfaefba17f8e4584c551d946773589a4f08/deepagents-0.6.12-py3-none-any.whl", hash = "sha256:28b8fa0119ca0a689e3e18e288c4634e4046062acfc87a1cb34289d3af3a1c88", size = 236120, upload-time = "2026-06-25T17:26:51.736Z" }, +] + [[package]] name = "distro" version = "1.9.0" @@ -267,6 +380,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, ] +[[package]] +name = "docstring-parser" +version = "0.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" }, +] + [[package]] name = "esca-sdk" version = "0.2.0" @@ -291,6 +413,54 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/35/380b9a5922f4340e51c309cde09e5bd32e62f02302971bee30dc15aa0624/fastapi-0.137.1-py3-none-any.whl", hash = "sha256:64f6983c59e45c4b9fdc44e57cb8035c2451ee91ea8e8ec042aca37de7cf6b69", size = 121877, upload-time = "2026-06-15T11:28:19.523Z" }, ] +[[package]] +name = "filetype" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bb/29/745f7d30d47fe0f251d3ad3dc2978a23141917661998763bebb6da007eb1/filetype-1.2.0.tar.gz", hash = "sha256:66b56cd6474bf41d8c54660347d37afcc3f7d1970648de365c102ef77548aadb", size = 998020, upload-time = "2022-11-02T17:34:04.141Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/79/1b8fa1bb3568781e84c9200f951c735f3f157429f44be0495da55894d620/filetype-1.2.0-py2.py3-none-any.whl", hash = "sha256:7ce71b6880181241cf7ac8697a2f1eb6a8bd9b429f7ad6d27b8db9ba5f1c2d25", size = 19970, upload-time = "2022-11-02T17:34:01.425Z" }, +] + +[[package]] +name = "google-auth" +version = "2.56.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/4c/fa42116a48bab3f7a143cf5042ecff7df9c8b73f8a376203cd534d1dc966/google_auth-2.56.3.tar.gz", hash = "sha256:40e229fc901f0a305b553050e5fce562d509bee0435be053abfa91582b51b90c", size = 367110, upload-time = "2026-08-06T06:24:01.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/b3/6117b2f24065cd7e2c4f140e9a193e215f089ca8ba314cf91eb9d0b7fe0a/google_auth-2.56.3-py3-none-any.whl", hash = "sha256:8ec438808f813ad034535000261eed1067475d229d05bbf4216e78c3f2362e53", size = 259116, upload-time = "2026-08-06T06:22:51.788Z" }, +] + +[package.optional-dependencies] +requests = [ + { name = "requests" }, +] + +[[package]] +name = "google-genai" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "google-auth", extra = ["requests"] }, + { name = "httpx" }, + { name = "pydantic" }, + { name = "requests" }, + { name = "sniffio" }, + { name = "tenacity" }, + { name = "typing-extensions" }, + { name = "websockets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5b/52/0244e310812f3063d09d60b30ae29ab7df9343bd005744cd5eeaa6ba39b4/google_genai-2.8.0.tar.gz", hash = "sha256:37a9b3cb127d763e7f4ca47452ae3562c87728773bd1b149f7b559c239da2bc1", size = 564955, upload-time = "2026-06-03T22:55:38.397Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/de/747ad1aa49e902da9a4699081c282a1ed8ceed3b4d295fd99a6d286e09e4/google_genai-2.8.0-py3-none-any.whl", hash = "sha256:4da0a223a100f4b37f609a68b835e3326ab0fa313314dc0fd9d34e76ee293844", size = 832497, upload-time = "2026-06-03T22:55:36.598Z" }, +] + [[package]] name = "googleapis-common-protos" version = "1.75.0" @@ -526,9 +696,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/95/c6/dc676c632f3d20c88789b0726c43ad5e039c25338cc3bb7090fc247d1522/langchain-1.3.13-py3-none-any.whl", hash = "sha256:20a8fe4b1dea7db74356f7d2b5455c4970099b9f7f53c2122ea97f115c907fbd", size = 136911, upload-time = "2026-07-10T23:06:07.012Z" }, ] +[[package]] +name = "langchain-anthropic" +version = "1.5.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anthropic" }, + { name = "langchain-core" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/c6/97c439282c13225beb56ba96ed2a5b1cb2c32eacb84c518fe475ce43711d/langchain_anthropic-1.5.6.tar.gz", hash = "sha256:648fdab25573fc9d29543c4b4af1d682b7b6e548d452bb46e67ebc586e195629", size = 720743, upload-time = "2026-08-13T02:30:48.262Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/5e/61b288074742179041cb5390430e52429a0fc41f4a94efec20042bda009f/langchain_anthropic-1.5.6-py3-none-any.whl", hash = "sha256:c358ed2ca90ef75254bb73a96b0a8a8ef0efc1deabe529ea06db6ff403001a27", size = 56547, upload-time = "2026-08-13T02:30:47.118Z" }, +] + [[package]] name = "langchain-core" -version = "1.5.0" +version = "1.5.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jsonpatch" }, @@ -541,9 +725,24 @@ dependencies = [ { name = "typing-extensions" }, { name = "uuid-utils" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5c/05/986c4bb148285791eb59994e0b28947bed96cac7f24467079e4274952a37/langchain_core-1.5.0.tar.gz", hash = "sha256:e1fa09d55b354192c8f60dade06a55bd6add2318c822a684555b8d4a30a16143", size = 967401, upload-time = "2026-07-21T03:37:26.48Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/18/20c3eec05ccf2fff8e553866bec3bb2f92880aea3cb878603e5a854bd5c0/langchain_core-1.5.4.tar.gz", hash = "sha256:aa76104f30b6c7305f292cb2c364e67cb52c321940ae812d7969471dce32a89a", size = 980540, upload-time = "2026-08-11T18:02:52.239Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ff/9b/2219c2873c182765a2e966015672d725fdf5c9f625ef599e780168661d24/langchain_core-1.5.4-py3-none-any.whl", hash = "sha256:f1d45e84c4e4d6158218b7a8072ebe9b6d4b51e10cb728c0469650a648e18f1b", size = 565086, upload-time = "2026-08-11T18:02:50.16Z" }, +] + +[[package]] +name = "langchain-google-genai" +version = "4.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filetype" }, + { name = "google-genai" }, + { name = "langchain-core" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/11/98/39b62fb50236fc582449beb96e0392d108bd7baac7ac6158d656bfac1561/langchain_google_genai-4.3.3.tar.gz", hash = "sha256:f051b98aaf223cf9092fc27c280dfec63070fc0022dc513640b2da138c9fa2f0", size = 286010, upload-time = "2026-08-10T18:34:26.499Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/56/5ef7ba14bac95b0344da18c6e8ec108dce0baf5fc054d1117702f92af29d/langchain_core-1.5.0-py3-none-any.whl", hash = "sha256:f122efee35446632b38687119fca33711abbf3b6b555e31156762298fbe78a65", size = 558510, upload-time = "2026-07-21T03:37:24.423Z" }, + { url = "https://files.pythonhosted.org/packages/b0/70/b6e29470356cbb2c87db2344df44182dac90d69c0cc4b929a805184a54c3/langchain_google_genai-4.3.3-py3-none-any.whl", hash = "sha256:cb189f6eebe801fda4416525a357d82f033efc36713a7c15a45c25eb1e2ddbff", size = 72859, upload-time = "2026-08-10T18:34:25.283Z" }, ] [[package]] @@ -623,15 +822,30 @@ wheels = [ [[package]] name = "langgraph-checkpoint" -version = "4.1.1" +version = "4.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, { name = "ormsgpack" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/83/47/886af6f886f0bff2273164a45f008694e48a96ff3cd25ff0228f2aa9480e/langgraph_checkpoint-4.1.1.tar.gz", hash = "sha256:6c2bdb530c91f91d7d9c1bd100925d0fc4f498d418c17f3587d1526279482a25", size = 184020, upload-time = "2026-05-22T16:57:38.503Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f0/c4/f4107f50dd07169d08d95766cd69104231e694f44a1b25b68ad8b393712d/langgraph_checkpoint-4.3.1.tar.gz", hash = "sha256:625e7c78a72b33e7c47f7e87ca051060fb90aa66f5fd551c472c08376fb669cb", size = 182679, upload-time = "2026-10-26T19:57:31.416Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bd/b4/71425e3e38be92611300b9cc5e46a5bf98ab23f5ea8a75b73d02a2f1413c/langgraph_checkpoint-4.1.1-py3-none-any.whl", hash = "sha256:25d29144b082827218e7bc3f1e9b0566a4bb007895cd6cc26f66a8428739f56e", size = 56212, upload-time = "2026-05-22T16:57:37.203Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/4251d676b5c585d42175c901175d4bff56e22939625e18bcef781fc3e893/langgraph_checkpoint-4.3.1-py3-none-any.whl", hash = "sha256:215a826935c8db4d9676e79fd95943e5b3847d78604390898e1d98581cc594e5", size = 58093, upload-time = "2026-10-26T19:57:30.361Z" }, +] + +[[package]] +name = "langgraph-checkpoint-postgres" +version = "3.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "langgraph-checkpoint" }, + { name = "orjson" }, + { name = "psycopg" }, + { name = "psycopg-pool" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/45/28/bc0927c2770ab713edc33c4c2f87d1f7b51c344b401d7dda5c8584bd8bf8/langgraph_checkpoint_postgres-3.2.0.tar.gz", hash = "sha256:dffef0e6822d7c614019f7f2c4bdbef42859746aee2d3e6d9d9747cf3744ca90", size = 165780, upload-time = "2026-10-14T19:54:41.116Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/af/07090322c0ac00429ff7f4789b0855e72cbd3c47026ce6b8575f39cd0f9a/langgraph_checkpoint_postgres-3.2.0-py3-none-any.whl", hash = "sha256:4d89526ab3dff0c71d575233e4132327f95812deb07b6c2e75fc473525b5b8fc", size = 55937, upload-time = "2026-10-14T19:54:40.048Z" }, ] [[package]] @@ -979,6 +1193,57 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, ] +[[package]] +name = "psycopg" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/26/3ea4ca5eaea1c0debcdf7ee7c1613fbe721dc27a03c461c0817ffd8a0601/psycopg-3.3.6.tar.gz", hash = "sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2", size = 168171, upload-time = "2026-09-18T13:22:55.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/de/748bd7609c71cae5d737f0ba9192f19329f70180ecda8fff3cac02c5abe3/psycopg-3.3.6-py3-none-any.whl", hash = "sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631", size = 215490, upload-time = "2026-09-18T13:15:29.374Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] +pool = [ + { name = "psycopg-pool" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/01/2cdd1824e58b4467ee0b9498664cd28c42d8794db6b1e35b6bcb834f0044/psycopg_binary-3.3.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3f84dab25e0385692ee13274c68678377e0b1a70ab9d14e56264cbf61f60c62d", size = 4707086, upload-time = "2026-09-18T13:18:05.138Z" }, + { url = "https://files.pythonhosted.org/packages/f6/76/de9948ac06895261c84d5b9fbe283d8f3c5bc9f070691b8d9eaa1b51e322/psycopg_binary-3.3.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:612382ac3ed13651c7fa44b5fee9fbf7baaa2ddbc6f500391672682c5f1df9e0", size = 4769607, upload-time = "2026-09-18T13:18:12.83Z" }, + { url = "https://files.pythonhosted.org/packages/76/a9/72436c9915ee4905964689e7f0e182ce7767cc0a0390b3ce703be8177625/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:366db6e97e66b37211475f20c4c1324a2dc0dd825e46d4e87f9d599304d276f9", size = 5554134, upload-time = "2026-09-18T13:18:21.175Z" }, + { url = "https://files.pythonhosted.org/packages/0a/42/948bb3d2617795093512613fd96ba380e922992c7908fbc073858147d196/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1679a1cb93fbe5a6d1fd58d82cbddcc6fcb8c61446ba7cae6eb2a7b19bc585de", size = 5235723, upload-time = "2026-09-18T13:18:27.071Z" }, + { url = "https://files.pythonhosted.org/packages/99/47/93e823ff1b0088400703410939c9bda3e63ed9c850b3ee088e8769f4c10b/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:37d40450659401600e6d043ff586c89a71a69f33cbb8bcdba6cdb2569beecdbe", size = 6833587, upload-time = "2026-09-18T13:18:33.794Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2d/ecc69c847795aa704041a9f5667a6b0938a088cf1853636d762a6938e493/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a5165300324efd5a772c48a88ab3a928513ab3979fca76553e62ee815f7b2b9c", size = 5070013, upload-time = "2026-09-18T13:18:39.628Z" }, + { url = "https://files.pythonhosted.org/packages/92/36/6126f0dac21713dcae91404f2a76da18598a6252339a8c669c46370d43b2/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d636338c8f21b0df2f84657b00bc34f9313f826ef93f1155bc743607e4a0c5eb", size = 4597367, upload-time = "2026-09-18T13:18:45.023Z" }, + { url = "https://files.pythonhosted.org/packages/4d/29/7ecfc04243b46c89ffd49924e9c5634ea904ef96c7d0f37e4073623584c1/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a4ee3bdd5468a725f2a4d9aab8a74b6d0279f768c8b5d3aeb102c5307ff3d59c", size = 4275419, upload-time = "2026-09-18T13:18:49.299Z" }, + { url = "https://files.pythonhosted.org/packages/6e/90/2f46d2e0de79706ac170df0a3637fe63c4498fc04f131f6049520b78b806/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:289aadd6a00e151203c081f708348ec89f1e483c9b510ef4ac3981f847f01f79", size = 4007358, upload-time = "2026-09-18T13:18:53.944Z" }, + { url = "https://files.pythonhosted.org/packages/03/48/6744e91291b751a8cf12d63d719977974bb94c84ceba913e7ddb2e478e51/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f21d057f3e5f5491067e5b292498073b73847d48799b099803fef100775fcc52", size = 4320156, upload-time = "2026-09-18T13:18:59.258Z" }, + { url = "https://files.pythonhosted.org/packages/1a/9b/94ff7fce53a64d5b286e2ec454e0a025cf3d6e6b4a9189bef16aa5de98b2/psycopg_binary-3.3.6-cp312-cp312-win_amd64.whl", hash = "sha256:e23a66a763fbe83fcc210bc77c27e5a5ea380ebf091c06f34d8561b695e5a40f", size = 3658864, upload-time = "2026-09-18T13:19:06.503Z" }, +] + +[[package]] +name = "psycopg-pool" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/74/5e/c0664b968b102ff68b811d999c728546c48d5c1eec03e3bbaf88c0cb4472/psycopg_pool-3.3.3.tar.gz", hash = "sha256:df87b5d9d0ad7db37f6cdad4fa8ce113d250f5997f6db38e9a99192fb67f9e1d", size = 32006, upload-time = "2026-09-22T15:53:24.947Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/b4/452c6607a0f479465cd8a9b0d9956919fcb150050c1f83f9f11e6b8ee8dc/psycopg_pool-3.3.3-py3-none-any.whl", hash = "sha256:9b9cd6a4fcec47a410f7e82d408540e7f77b478509e91b44c1a5457a13e5ff37", size = 40304, upload-time = "2026-09-22T15:53:23.712Z" }, +] + [[package]] name = "psycopg2-binary" version = "2.9.9" @@ -999,6 +1264,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/08/9c66c269b0d417a0af9fb969535f0371b8c538633535a7a6a5ca3f9231e2/psycopg2_binary-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:81ff62668af011f9a48787564ab7eded4e9fb17a4a6a74af5ffa6a457400d2ab", size = 1163864, upload-time = "2023-10-28T09:37:28.155Z" }, ] +[[package]] +name = "pyasn1" +version = "0.6.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/9a/23310166d960def5897e91fe20e5b724601b02a22e84ba1f94232c0b7f67/pyasn1-0.6.4.tar.gz", hash = "sha256:9c447d8431c947fe4c8febc4ed9e760bc29011a5b01e5c74b67025bd9fb8ce81", size = 151262, upload-time = "2026-07-09T01:12:33.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/3b/6163796d69c3977d1e4287bea4a6979161cbbdd170ebb430511e8e1999ce/pyasn1-0.6.4-py3-none-any.whl", hash = "sha256:deda9277cfd454080ec40b207fb6df82206a3a2688735233cdcd8d3d565f088b", size = 84410, upload-time = "2026-07-09T01:12:32.92Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + [[package]] name = "pydantic" version = "2.10.4" @@ -1634,6 +1929,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0a/26/88e0dc6ee3898169d7fa22bb6a69cabf2502d2ee25cb8c876d1262d204f8/watchfiles-1.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:8fa585ede612ee9f9e91b18bebf9ba11b9ae29a4e3a0d0cf6fca3e382133f0d5", size = 281026, upload-time = "2026-05-18T04:30:22.23Z" }, ] +[[package]] +name = "wcmatch" +version = "11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "bracex" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/25/1da725838132221e33568973da484ff43813662ccc06ebf7f6e3abddfcd5/wcmatch-11.0.tar.gz", hash = "sha256:55d95c2447789712774b198ceec72939e88b5618f1f8f0a9b605bf7740b63b96", size = 141360, upload-time = "2026-07-10T05:50:24.183Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/12/f38b6fee116274d7221743caab07d765032e1370bb54cad8714f87aeb0e8/wcmatch-11.0-py3-none-any.whl", hash = "sha256:3a5977ace27e075eef67eb03d539563f1a19018b62881949a42932cf66926934", size = 42914, upload-time = "2026-07-10T05:50:22.995Z" }, +] + [[package]] name = "websockets" version = "15.0.1" diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index ac5a3b8..f4966b1 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -13,6 +13,7 @@ import logging from contextlib import asynccontextmanager from datetime import datetime, timedelta +from typing import Literal import httpx import redis.asyncio as redis @@ -31,6 +32,10 @@ router = APIRouter(prefix="/agent", tags=["agent"]) +# /chat waits settings.AGENT_READ_TIMEOUT_SECONDS for the agent. The deep agent is told a little less +# (timeout_s) so it stops the run and its "stopped" response still arrives before we give up. +AGENT_STOP_MARGIN_S = 10.0 + # --------------------------------------------------------------------------- # Schemas # --------------------------------------------------------------------------- @@ -52,6 +57,7 @@ class ChatRequest(BaseModel): execution_mode: str | None = None hitl_enabled: bool = True connection_id: int + engine: Literal["legacy", "deep"] | None = None # which agent answers; None = legacy (a deep-… thread stays deep) class SuggestFixesRequest(BaseModel): @@ -71,6 +77,12 @@ class ChatResponse(BaseModel): trace_id: str | None = None execution_path: list[str] | None = None is_unanswerable: bool = False + engine: str | None = None # "deep" when answered by the Deep Agent + verification: str | None = None # Deep Agent answer verification status (matched, re_executed, ...) + confidence: str | None = None # Deep Agent self-reported confidence (high / medium / low) + executed: bool | None = None # Deep Agent: the submitted final SQL ran and the rows are Trino's + recovered_from_text: bool | None = None # Deep Agent: final answer was written as text and recovered + semantic_validation: dict | None = None # Deep Agent: independent review (verdict, rounds, issues, response) # --------------------------------------------------------------------------- @@ -105,10 +117,10 @@ async def _get_jeen_mcp_client(): yield session -async def _call_agent_mcp(tool_arguments: dict) -> dict: +async def _call_agent_mcp(tool_name: str, tool_arguments: dict) -> dict: """ Connects to the agent MCP server over Streamable HTTP, initializes the session, - calls the 'chat_with_agent' tool, and returns the parsed result. + calls `tool_name` (chat_with_agent or deep_agent), and returns the parsed result. """ url = f"{settings.AGENT_URL}/mcp" logger.debug("Connecting to agent MCP: %s args=%s", url, tool_arguments) @@ -120,7 +132,7 @@ async def _call_agent_mcp(tool_arguments: dict) -> dict: # Call the tool using the MCP client session result = await session.call_tool( - "chat_with_agent", + tool_name, arguments=tool_arguments, read_timeout_seconds=timedelta( seconds=settings.AGENT_READ_TIMEOUT_SECONDS @@ -185,6 +197,16 @@ async def _call_agent_mcp(tool_arguments: dict) -> dict: # --------------------------------------------------------------------------- +DEEP_THREAD_PREFIX = "deep-" # the agent service names Deep Agent threads deep-… + + +def _is_deep(request: ChatRequest) -> bool: + """The Deep Agent answers when chosen, and always continues its own threads (resumes don't resend engine).""" + if request.thread_id: + return request.thread_id.startswith(DEEP_THREAD_PREFIX) + return request.engine == "deep" + + @router.post("/chat", response_model=ChatResponse) async def chat(request: ChatRequest) -> ChatResponse: """ @@ -205,18 +227,25 @@ async def chat(request: ChatRequest) -> ChatResponse: else: resume_val = request.resume_value - tool_arguments: dict = { + common: dict = { "query": request.query, "thread_id": request.thread_id, "resume_value": resume_val, - "allowed_tables": request.allowed_tables, - "allowed_statuses": request.allowed_statuses, - "extractors": request.extractors, "hitl_enabled": request.hitl_enabled, "connection_id": request.connection_id, } - - result = await _call_agent_mcp(tool_arguments) + if _is_deep(request): + # the deep agent stops its run then, so its "stopped" reply arrives before we give up + result = await _call_agent_mcp("deep_agent", { + **common, "timeout_s": settings.AGENT_READ_TIMEOUT_SECONDS - AGENT_STOP_MARGIN_S, + }) + else: + result = await _call_agent_mcp("chat_with_agent", { + **common, + "allowed_tables": request.allowed_tables, + "allowed_statuses": request.allowed_statuses, + "extractors": request.extractors, + }) return ChatResponse(**result) diff --git a/backend/tests/test_agent_engine.py b/backend/tests/test_agent_engine.py new file mode 100644 index 0000000..fa79492 --- /dev/null +++ b/backend/tests/test_agent_engine.py @@ -0,0 +1,54 @@ +from unittest.mock import AsyncMock, patch + +DEEP_RESPONSE = { + "thread_id": "deep-123", "status": "completed", "summary": "466 הזמנות", "sql_query": "SELECT 1", + "sql_explanation": "x", "trace_id": "t", "execution_path": ["deep:execute_trino_query"], + "is_unanswerable": False, "engine": "deep", "verification": "matched", "confidence": "high", + "executed": True, "recovered_from_text": False, +} + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_deep_engine_calls_the_deep_agent_tool(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "כמה הזמנות", "connection_id": 89, "engine": "deep", + "allowed_tables": ["t"]}) + assert response.status_code == 200, response.text + tool, args = mock_call.await_args.args + assert tool == "deep_agent" and "engine" not in args + assert "allowed_tables" not in args # legacy-only arguments are not sent to the deep agent + body = response.json() + assert body["engine"] == "deep" and body["verification"] == "matched" and body["confidence"] == "high" + assert body["executed"] is True and body["recovered_from_text"] is False + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_chat_tells_the_agent_how_long_it_waits(mock_call, client): + from app.config import settings + from app.routers.agent import AGENT_STOP_MARGIN_S + + client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "deep"}) + wait = settings.AGENT_READ_TIMEOUT_SECONDS + assert mock_call.await_args.args[1]["timeout_s"] == wait - AGENT_STOP_MARGIN_S < wait + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, + return_value={"thread_id": "t", "status": "completed", "summary": "ok"}) +def test_default_calls_the_legacy_tool(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "allowed_tables": ["t"]}) + assert response.status_code == 200, response.text + tool, args = mock_call.await_args.args + assert tool == "chat_with_agent" and args["allowed_tables"] == ["t"] + assert "engine" not in args and "timeout_s" not in args + assert response.json()["engine"] is None + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_resuming_a_deep_thread_stays_on_the_deep_agent(mock_call, client): + response = client.post("/api/agent/chat", json={"thread_id": "deep-123", "resume_value": "חיפה", "connection_id": 89}) + assert response.status_code == 200, response.text + assert mock_call.await_args.args[0] == "deep_agent" + + +def test_chat_rejects_unknown_engine(client): + response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "gpt"}) + assert response.status_code == 422 diff --git a/core/src/core/config.py b/core/src/core/config.py index 6013401..ccf47c5 100644 --- a/core/src/core/config.py +++ b/core/src/core/config.py @@ -17,6 +17,9 @@ class CoreSettings(BaseSettings): TRINO_SCHEMA: str = "simple_retail" TRINO_HTTP_SCHEME: str = "http" TRINO_REQUEST_TIMEOUT: float = 30.0 + # Optional session time zone for current_date / now() and plain timestamp literals, e.g. "Asia/Jerusalem". + # Unset (default): the Trino client's own behaviour — the machine's zone (UTC in Docker). + TRINO_TIMEZONE: str | None = None TRINO_ENABLED: bool = True TRINO_VERIFY: bool | str = False TRINO_CERT_PATH: str | None = None diff --git a/core/src/core/trino.py b/core/src/core/trino.py index 40826b1..0f54f6a 100644 --- a/core/src/core/trino.py +++ b/core/src/core/trino.py @@ -3,10 +3,12 @@ """ import logging +import threading import time from typing import Any import trino +import trino.exceptions from pydantic import BaseModel import urllib3 from core.config import settings @@ -17,6 +19,27 @@ logger = logging.getLogger(__name__) +# Per-thread reusable connections for callers that opt in (execute_query_sync(reuse_connection=True)). +_thread_local = threading.local() + + +def _reusable_connection(): + conn = getattr(_thread_local, "connection", None) + if conn is None: + conn = get_trino_connection() + _thread_local.connection = conn + return conn + + +def _drop_reusable_connection() -> None: + conn = getattr(_thread_local, "connection", None) + _thread_local.connection = None + if conn is not None: + try: + conn.close() + except Exception: + pass + class TrinoExecutionResult(BaseModel): success: bool @@ -25,6 +48,12 @@ class TrinoExecutionResult(BaseModel): row_count: int = 0 execution_time_ms: int = 0 error_message: str | None = None + # Structured Trino error details (populated from trino.exceptions.TrinoQueryError) + error_name: str | None = None # e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, FUNCTION_NOT_FOUND + error_type: str | None = None # USER_ERROR | INSUFFICIENT_RESOURCES | INTERNAL_ERROR | EXTERNAL + error_code: int | None = None + error_location: tuple[int, int] | None = None # (line, column) of the offending token + query_id: str | None = None def get_trino_connection(catalog: str | None = None, schema: str | None = None): @@ -54,6 +83,7 @@ def get_trino_connection(catalog: str | None = None, schema: str | None = None): http_scheme=settings.TRINO_HTTP_SCHEME, auth=auth, request_timeout=settings.TRINO_REQUEST_TIMEOUT, + timezone=settings.TRINO_TIMEZONE, verify=settings.TRINO_VERIFY, ) @@ -62,12 +92,18 @@ def execute_query_sync( sql: str, table_id: str = "", params: tuple | dict | list | None = None, + reuse_connection: bool = False, catalog: str | None = None, schema: str | None = None, ) -> TrinoExecutionResult: """ Execute a SQL query against the real Trino cluster. + + reuse_connection=True keeps one DBAPI connection per thread (no new HTTP/TLS setup per + query); a failed query drops it so the next call reconnects. The kept connection uses the + default catalog/schema, so a catalog or schema override always gets its own connection. """ + reuse_connection = reuse_connection and catalog is None and schema is None start_time = time.time() log_sql = sql.strip().replace("\n", " ")[:300] logger.info(f"[CoreTrinoClient] table_id={table_id} | {log_sql}") @@ -83,7 +119,7 @@ def execute_query_sync( conn = None cur = None try: - conn = get_trino_connection(catalog=catalog, schema=schema) + conn = _reusable_connection() if reuse_connection else get_trino_connection(catalog=catalog, schema=schema) cur = conn.cursor() if params is not None: cur.execute(sql, params) @@ -91,16 +127,19 @@ def execute_query_sync( cur.execute(sql) rows = cur.fetchall() columns = [desc[0] for desc in cur.description] if cur.description else [] + query_id = getattr(cur, "query_id", None) execution_time_ms = int((time.time() - start_time) * 1000) logger.info(f"[CoreTrinoClient] OK — {len(rows)} rows in {execution_time_ms}ms") cur.close() - conn.close() + if not reuse_connection: + conn.close() return TrinoExecutionResult( success=True, rows=[list(r) for r in rows], columns=columns, row_count=len(rows), execution_time_ms=execution_time_ms, + query_id=query_id, ) except Exception as exc: execution_time_ms = int((time.time() - start_time) * 1000) @@ -110,16 +149,28 @@ def execute_query_sync( cur.close() except: pass - if conn is not None: + if reuse_connection: + _drop_reusable_connection() + elif conn is not None: try: conn.close() except: pass + details: dict[str, Any] = {} + if isinstance(exc, trino.exceptions.TrinoQueryError): + details = { + "error_message": exc.message, + "error_name": exc.error_name, + "error_type": exc.error_type, + "error_code": exc.error_code, + "error_location": exc.error_location, + "query_id": exc.query_id, + } return TrinoExecutionResult( success=False, rows=[], columns=[], row_count=0, execution_time_ms=execution_time_ms, - error_message=str(exc), + **{"error_message": str(exc), **details}, ) diff --git a/package.json b/package.json index f179865..e984f88 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,9 @@ "backend/app/**/*.py": [ "backend/.venv/bin/ruff check --fix", "backend/.venv/bin/ruff format" + ], + "agent/src/deep_agent/**/*.py": [ + "agent/.venv/bin/ruff check --extend-select F --config agent/pyproject.toml" ] }, "devDependencies": { diff --git a/skills-lock.json b/skills-lock.json index 51873e3..5689129 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -31,12 +31,24 @@ "skillPath": "skills/code-documenter/SKILL.md", "computedHash": "49709db09641a9ab4196459835bfcbe565eb0581c23cb4eeb50ff80d2af88272" }, + "code-review": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/code-review/SKILL.md", + "computedHash": "57cfd4ceb011f05e58a1a4f4cad3b2e03419d371f8990f4bcb32ff0d435a039f" + }, "code-reviewer": { "source": "jeffallan/claude-skills", "sourceType": "github", "skillPath": "skills/code-reviewer/SKILL.md", "computedHash": "57ab3eba6fa596bc52d73ca7312afc2f389d9622714d25b2ab3d4bbf03dc293a" }, + "codebase-design": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/codebase-design/SKILL.md", + "computedHash": "b2888e4f4e8c0af3bfd557575a64b905c44e6248c3101d72077816882b3a92b9" + }, "database-optimizer": { "source": "jeffallan/claude-skills", "sourceType": "github", @@ -79,6 +91,24 @@ "skillPath": "skills/fullstack-guardian/SKILL.md", "computedHash": "2d3533f91951f2c8626eaeb7ffb33e40727bca85545a8e63f97e35939957e1a4" }, + "grill-me": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/productivity/grill-me/SKILL.md", + "computedHash": "9cdbb4b8f7a3aeaef82e6230c9e823500d4a8a1214c726cf342cf9829d34fc7d" + }, + "implement": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/implement/SKILL.md", + "computedHash": "b6371a0a6723bad551f3adc721e3729a6a97acfc3670dc2bdea198bbe78408c0" + }, + "improve-codebase-architecture": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/improve-codebase-architecture/SKILL.md", + "computedHash": "ac2c94885f34ff8492dc12aa4543182f661f32ea1722b8d6b6c2c7045af33ae3" + }, "javascript-pro": { "source": "jeffallan/claude-skills", "sourceType": "github",