Skip to content

Deep agent (separate deep_agent MCP tool) + review round - #67

Merged
benben-ship-it merged 41 commits into
mainfrom
feature/deep-agent-updated
Nov 23, 2026
Merged

benben-ship-it merged 41 commits into
mainfrom
feature/deep-agent-updated

Conversation

@benben-ship-it

@benben-ship-it benben-ship-it commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Adds the deep agent — a new Text-to-SQL engine built on LangGraph deepagents — exposed as its own MCP tool deep_agent. chat_with_agent stays the existing (structured) agent, unchanged in behaviour. The backend's POST /api/agent/chat calls deep_agent when the request has "engine": "deep" (default: the structured agent). Code: agent/src/deep_agent/ (map in agent/README.md).

Follow-up work made after this PR's review round is in #68, stacked on this one.

How the deep agent answers

  1. Explore & draft with 6 tools (execute_trino_query, search_column_values, get_column_distinct_values, get_sample_rows, validate_sql, resolve_location_to_wkt); the connection's full Jeen catalog is in the prompt on every call.
  2. Run — every statement goes through agent/utils/sql_guard.py (one read-only statement, optional row ceiling, safe identifiers).
  3. Review — a separate semantic-validator subagent judges the SQL by reading (no SQL tools), from facts only: the user's messages, the SQL, its real rows, the agent's assumptions, the catalog.
  4. Submit — submit_answer is accepted only for SQL that ran this turn and passed review (or that the agent disputes, shown to the user). The result table always comes from Trino's rows.

Review round (all comments answered)

SQL comments allowed; distinct values follow their own limit; get_column_profile and enrich_sql_filters removed; search_column_values docs corrected (what it really indexes); prompts rebuilt on change instead of swapped per model call; on_demand reviews reported correctly.

Tests

Deep agent + SQL guard 305 passed, backend 48. (The structured agent's 7 failing refiner tests on main are fixed in #68.)

Try it

POST /api/agent/chat with {"query": "...", "connection_id": 89, "engine": "deep"}, or the CLI: cd agent && uv run deep-agent -i -m.

🤖 Generated with Claude Code

benben-ship-it and others added 30 commits August 13, 2026 14:27
…ratch files

- Move run_deep_agent.py to deep_agent.cli with a [project.scripts]
  'deep-agent' entry point; no sys.path hacks or global urllib3
  warning suppression
- Package deep_agent in the wheel (uv_build module-name list)
- Handle list-form message content (fixes TypeError in SQL extraction)
- Replace CWD CSV logging with opt-in, schema-stable JSONL (--log-file)
- Remove agent/deep_agent_logs.csv and agent/test_stream.py; ignore
  agent/runs/, agent/*.csv, agent/*.jsonl

Closes #46

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Skills and memory were silently never loaded: paths were hardcoded to
another developer's machine, the default StateBackend reads from agent
state rather than disk, and each skill directory was passed as a skill
source instead of their parent.

- Package skills/ and memory/AGENTS.md inside deep_agent (ship in wheel)
- CompositeBackend: /skills/ and /memory/ -> read-only FilesystemBackend,
  everything else -> StateBackend; writes to both denied via permissions
- build_resources() validates layout + frontmatter and fails fast
- DEEP_AGENT_SKILLS_DIR / DEEP_AGENT_MEMORY_DIR overrides
- create_deep_agent(model=...) for tests; scripted fake chat model fixture

Closes #34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and improve-codebase-architecture agent skills

Installed from mattpocock/skills; lock entries added to skills-lock.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tifiers

- agent/utils/sql_guard.py (ported from Utils-Server trino guard): one
  read statement only; rejects writes/DDL/CALL/SET, multi-statements,
  comments (tokenizer-based, so 'a--b' literals are fine) and TABLE(...)
  pass-through; enforces outer LIMIT cap+1 incl. CTE/UNION/FETCH cases
- execute_trino_query / get_sample_rows / get_column_distinct_values /
  validate_sql_syntax go through the guard; limits clamped via
  DEEP_AGENT_MAX_ROWS / DEEP_AGENT_MAX_SAMPLE_ROWS; 'truncated' flag
- identifiers parsed/quoted with sqlglot (spaces, Hebrew, "" escaping)
- nested execute_trino_query.invoke() replaced by a shared _run_sql helper

Closes #35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… ceilings optional

On top of #35 (review fixes):
- FETCH FIRST n ROWS was not recognised as a limit and got replaced by the
  cap, so a "top 5" query returned up to cap rows; it is now read as the
  requested limit and left as written when within the cap (WITH TIES kept)
- set operations were wrapped in SELECT * FROM (...) LIMIT, which lets Trino
  drop the inner ORDER BY; the LIMIT is now set on the set operation itself
- SQL already within the cap runs exactly as written (no sqlglot rewrite)
- DEEP_AGENT_MAX_ROWS / DEEP_AGENT_MAX_SAMPLE_ROWS keep their 100 / 10
  defaults but accept "none" (or empty / "unlimited") to disable the ceiling;
  with no ceiling the SQL is validated only and every row is returned
- execute_trino_query's limit argument now defaults to the configured ceiling

Verified the ORDER BY and FETCH cases against a real Trino 443.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#39, revised)

Based on deep-agent/39-trino-errors (aa55bf9), revised in review:
- core: TrinoExecutionResult keeps Trino's structured error (error_name,
  error_type, error_code, error_location, query_id) and the clean message;
  query_id on success too
- trino_errors.py passes Trino's errorName / errorType / message / location
  through unchanged — no category mapping, hints or keyword heuristics.
  Only two non-Trino names: FORBIDDEN_STATEMENT (SQL guard) and
  CONNECTION_ERROR (Trino unreachable / no structured error)
- validate_sql_syntax renamed validate_sql: it runs EXPLAIN (TYPE VALIDATE),
  which checks syntax, names, types and signatures; returns JSON. Line-1
  error_location columns are corrected for the EXPLAIN prefix (message raw)
- prompt and AGENTS.md updated to error_name / validate_sql
- agent installs core as an editable path dependency

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…value search (#45, revised)

Based on deep-agent/45-tool-contracts (5e89569), revised in review:
- envelope.py: every tool returns {ok, data, error}; error = {name, message,
  ...details}. error.name is Trino's own code for SQL failures (#39) or one
  of METADATA_ERROR / NOT_FOUND / INVALID_INPUT / ENRICHMENT_ERROR /
  LOCATION_NOT_FOUND for our tools. No category/hint layer.
- Jeen client: honour MCP isError and unexpected payloads by raising
  JeenMetadataError instead of returning []/None/{"error"}; METADATA_ERROR
  tells the model the data is not necessarily empty
- get_database_catalog stays plain text (no JSON escaping of the catalog)
- search_column_values: no duplicated payload, all matches returned, no
  prefix guessing, limit passed through unclamped
- resolve_location_to_wkt returns the polygon once (data.wkt, unquoted)
- DEEP_AGENT_TOOLS defined once; dead code removed; ruff (pyflakes) on
  deep_agent via lint-staged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…obals (#38)

Based on deep-agent/38-runtime-context (06e28d3), adapted to the revised stack:
- DeepAgentContext (connection_id, user_id, timezone) passed per invocation
  via context_schema; tools read it through a hidden ToolRuntime parameter
  and pass connection_id to every Jeen client call
- connection capabilities written to the thread's graph state by
  get_database_catalog (Command update, plain-text catalog kept); module
  global removed
- today's date injected per model call (Asia/Jerusalem) as a transient
  prefix on the latest human message; system prompt no longer formatted
- JeenMetadataClient: per-call connection_id on search*/column profile
- CLI passes context instead of mutating client._connection_id

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h_sql_filters (#36)

Based on deep-agent/36-catalog-state (071782e), adapted to the revised stack:
- get_database_catalog caches the raw catalog in the thread's state (jeen_catalog)
- enrich_sql_filters takes only {sql}: the catalog comes from state (fetched once
  and cached if missing); the user request is every human message in the
  thread, oldest first, so a reply to a clarifying question is appended to the
  original question instead of replacing it
- ToolRuntime.config forwarded to EnrichmentOrchestrator so enrichment LLM
  calls are children of the agent trace
- INVALID_INPUT removed from the envelope (no longer used)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…run scores (#37)

Based on deep-agent/37-tracing (0253804), adapted to the revised stack:
- observability.py: build_run_config() (Langfuse handler, session/user/tags,
  agent_version + connection_id metadata, run_name) so every run is one trace
- Trino tools annotate their observation with trino_query_id,
  execution_time_ms, row_count, truncated, or Trino's raw error_name /
  error_type at level ERROR; execution_time_ms also in the envelope
- run scores are plain facts only: model_calls, tool_calls, sql_executions,
  latency_s (no "any query succeeded" / text-heuristic final-SQL scores)
- CLI uses build_run_config, scores the run, prints the trace id, flushes
- DEEP_AGENT_TRACING_ENABLED setting; README tracing section

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
)

Based on deep-agent/41-structured-answer (f2c3e80), revised in review:
- DeepAgentAnswer (sql, explanation_he, assumptions, confidence) via
  ToolStrategy structured output (forced tool choice)
- execute_trino_query records successful runs in state (executed_queries,
  append-only, with the row cap each ran under)
- AnswerVerificationMiddleware binds the answer to evidence: matched /
  re_executed / rejected / re_execution_failed; final_result.executed means
  the final SQL ran and rows are Trino's (not a correctness check)
- a "matched" execution that was only a smaller sample than the row ceiling
  is re-executed so users get the full result; re-execution honours an
  unset ceiling
- clarifications behind DEEP_AGENT_CLARIFICATIONS_ENABLED (default off): no
  needs_clarification field, sql required, not mentioned in prompt/AGENTS.md
- render_markdown builds the user table from real rows; run score
  final_sql_executed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…evised)

Based on deep-agent/42-loop-bounds (6590244), revised in review:
- JeenMetadataClient: TTL + single-flight cache for read-only metadata tools
  (JEEN_METADATA_CACHE_TTL_S); persistent MCP session per event loop
  (JEEN_METADATA_REUSE_SESSION), closed once when the CLI/benchmark exits
- core: opt-in per-thread Trino connection reuse (deep agent opts in)
- BuiltinToolFilterMiddleware hides execute/write_file/edit_file/glob/grep
- validate_sql optional, with accurate guidance (execute fails just as fast
  for invalid queries, reading no data)
- deep-agent-bench: latency p50/p95, calls, tokens, executed rate
- dropped from the PR: model/tool/SQL call caps, run wall-clock timeout,
  recursion-limit override, LLM timeout/retry override (it never reached the
  real client) and best-effort answers from the last executed query

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…kills (#40, revised)

Based on deep-agent/40-guidance (800c031), revised in review:
- system prompt moved to deep_agent/prompts/system.md: our full prompt plus
  the unique AGENTS.md content (CTE rules, grain/fan-out/intent checks, error
  table, lessons learned), each topic stated once; value-resolution policy has
  one owner; reconciled with Trino error fields, no prefix_pattern / sql_literal,
  clarifications only via the flag
- AGENTS.md and the deepagents memory feature removed (static text framed as
  "may be outdated" + ~1.1k tokens of boilerplate); skills-only backend
- skill fixes from the PR, verified on Trino: Sunday-based Hebrew week, half-open
  ranges, with_timezone, now()/date_format valid, areas-only spatial (data.wkt),
  optimizer-aware join advice, categorical policy, typo/example fixes
- all catalog-specific examples replaced with general ones (prompt, skills,
  tool docstrings)
- test_guidance_lint: tool refs exist, banned statements absent, no
  catalog-specific names, single policy owner, guidance SQL parses as Trino
- always-on guidance per model call: 6,026 -> 3,074 tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…prompt, Langfuse prompts, answer recovery (#48, revised)

Based on deep-agent/48-subagents-prompts (949f3a6, adcdce9), revised in review:
- taken from #48: Langfuse-managed prompts (prompt_registry, per-call refresh,
  miss cache, trace links to the served version, sync script) — off by
  default until the prompts are finalised; merge_executions reducer
- not taken: the schema-scout / value-resolver / result-verifier subagents
- catalog is deterministic: CatalogMiddleware loads it once per run for the
  request's connection and adds it to every model call's system message (never
  to history); a failed or empty load fails the run; the built-in general-purpose
  subagent gets it too; get_database_catalog tool and the capabilities mechanism
  removed
- tools 16 -> 8; get_database_tables / get_table_columns / get_table_profile /
  get_table_relationships / search_metadata / search_business_terms /
  search_knowledge_pairs kept unregistered (the catalog contains their data)
- trino-expert folded into the system prompt (dialect essentials, non-Trino
  function table, merged error table verified on Trino); skill removed
- answer tool renamed submit_answer
- AnswerRecoveryMiddleware: gpt-oss on the configured server often writes the
  final answer JSON as text despite forced tool choice; text that validates
  against the answer schema is turned into the submit_answer result and marked
  (final_result.recovered_from_text); anything else stays no_answer
- verified end to end on the real catalog + Trino: 4/4 questions answered

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rable threads (#43, revised)

- deep_agent/service.py: process-wide agent via create_deep_agent(checkpointer=...),
  AsyncPostgresSaver when DEEP_AGENT_CHECKPOINT_DB_URL is set (else in-memory),
  Redis stream events (deep:<tool>, deep:answer), legacy response contract plus
  engine / verification / executed / recovered_from_text / confidence
- no run timeout or best-effort answers; the caller passes timeout_s (how long it
  waits) and the run is cancelled then; omitted = no limit. Backend sends 290 of its 300s
- answers are verified only against SQL executed in the same turn (turn_execution_start);
  each turn starts with the previous answer cleared; the answer object is not kept in
  checkpoints (only final_result plain data)
- chat_with_agent: engine / user_id / timeout_s arguments, AGENT_ENGINE default,
  deep-* thread ids routed back to the deep agent
- backend: engine passthrough, timeout_s, new response fields
- core: TRINO_TIMEZONE (default Asia/Jerusalem) as the Trino session time zone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ository)

Removes deep_agent/benchmark.py, the deep-agent-bench command, its question set and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It returned at most `limit` matches (default 10) while promising "every matching value",
with nothing saying the list was cut. It now documents "up to `limit`" and returns
`limit_reached` plus a notice to call again with a higher limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- deep_agent/validator.py: a reviewer agent with a fresh context (user's messages, SQL,
  rows, assumptions, catalog — not the main agent's reasoning), read-only diagnostic tools
  and a submit_verdict (pass / fail + issues with evidence). It judges, it doesn't solve.
  DEEP_AGENT_SEMANTIC_VALIDATION: always (default: every submitted answer is reviewed; on
  fail the agent fixes it or resubmits with validation_response = dispute), on_demand
  (a `semantic-validator` task subagent), off. Optional DEEP_AGENT_VALIDATOR_MAX_ROUNDS.
- final_result / response `semantic_validation` (verdict, rounds, issues, reviewed_final_sql),
  Langfuse scores semantic_validation_passed / validation_rounds, deep:review:<tool> stream
  events, Hebrew warning in the answer on failed / disputed
- prompts/validator.md (deep-agent/validator in Langfuse); the semantic-validation skill is
  removed — its unique checks moved into the reviewer prompt
- SubmitReminderMiddleware: one "submit now" reminder per turn when the model ends with
  text instead of its submit call (main agent and reviewer)
- fix: an invalid submit_answer call ended the run instead of retrying (since #43)
- fix: parallel `task` calls crashed on jeen_catalog / final_result / turn_execution_start
  (last-value reducers; since #48)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eo parsing/performance

Merged from the Trino text-to-SQL skill, each claim checked on our Trino (480):
- system prompt: half-open time filters on the raw column; named dates are Israel time
  (TIMESTAMP '... Asia/Jerusalem', not UTC — 455 vs 452 alerts for July 1-14); coordinate
  order and degrees vs metres; error row for st_contains on SphericalGeography
- temporal-analyst: Israel-time boundaries, Israel-day bucketing, UTC date partitions
- spatial-analyst: ST_Buffer in degrees, km² areas, WKT/WKB/GeoJSON parsing
  (from_geojson_geometry returns SphericalGeography — wrap in to_geometry for containment),
  bbox pre-filter, time-filter CTE before spatial joins, bing-tile proximity joins
- guidance lint: placeholder regex no longer swallows `a <= x AND b >`

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…/ prompts/, drop 7 unused tools

Pure move/split — no behaviour change:
- tools/: sql, metadata, enrichment, location (+ envelope, trino_errors); __init__ holds
  DEEP_AGENT_TOOLS
- answer/: schema, verification, middleware, render
- validator/: reviewer (the reviewer agent) and modes (always gate / on_demand subagent)
- middleware/: catalog, tool_filter; prompts/: system.md, validator.md + registry
- current_turn() and the tool Runtime type moved to context.py
- removed the 7 unregistered metadata tools (get_database_tables, get_table_columns,
  get_table_profile, get_table_relationships, search_metadata, search_business_terms,
  search_knowledge_pairs) and their tests; the catalog already carries their information
- tests patch Trino / Jeen in the module that uses them; README code map

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…simpler time guidance

- answer schema: `sql` must be non-empty (the model must commit to a SQL answer)
- reviewer prompt: an assumption may choose between readings of the request but may not drop
  or replace part of it (Q3 dropped "per 10,000 residents" as an "assumption" and passed)
- time guidance: one line — times are Israel time, plain literals, no zones, no hand conversion
  to UTC (a hand conversion caused a wrong month boundary); the temporal skill's long time-zone
  section is reduced to the same
- Trino rule: decimal literals keep their scale (avg(IF(c, 1.0, 0.0)) returns 0.3, not 0.3008)
- hide the built-in `ls` tool: skill paths are already in the prompt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and a validator pass

- order: run the SQL (execute_trino_query) → have it reviewed (`semantic-validator` subagent,
  through `task`) → submit_answer. The reviewer no longer runs inside the submit step.
- SubmitApprovalMiddleware: submit_answer only looks up two records for the exact SQL — it ran
  successfully this turn (a sample counts), and the validator passed it (or the agent disputes a
  fail with `validation_response`). Otherwise it is refused with the reason and the agent continues;
  a SQL changed after its review needs a new one.
- reviewer independence: its input is built by our code from facts — the user's own messages
  (copied into state `user_messages` each turn; subagents don't get the conversation), the SQL, its
  recorded rows, the assumptions as claims to check, catalog and date. The rest of the brief is
  discarded; no reasoning, confidence or earlier verdicts.
- final rows: the approved run's rows; a sample is re-run unchanged for all rows; SQL that never
  ran is never executed (status not_executed if the invariant ever breaks).
- DEEP_AGENT_SEMANTIC_VALIDATION: always (default, validator pass required) | on_demand (offered,
  submit only needs a run) | off. DEEP_AGENT_STRICT_SUBMIT: no recovery / reminder — a model that
  doesn't call submit_answer ends without an answer. Optional DEEP_AGENT_VALIDATOR_MAX_ROUNDS.
- review summary reports the review of the final SQL; README and docstrings updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…untraced)

The keys live in agent settings (.env), not in the process environment, so a bare
CallbackHandler() started a disabled client ("Langfuse client initialized without public_key")
unless the legacy graph had already created a keyed one — true behind the agent service, not in
the CLI. The deep agent now creates our keyed client and binds the handler to its public key;
if tracing can't start, the run continues with a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rare needs_check run by the agent

- semantic-validator: no SQL tools; it reads the request, the SQL, its result rows, the assumptions
  and the catalog (types, descriptions, example values). Verdicts: pass | fail (issues with evidence)
  | needs_check (rare: a concrete, visible doubt only data can settle, with specific checks)
- needs_check: submit_answer refuses with the checks; the agent runs them and asks again; the next
  review sees the checks it asked for and the real results of the queries run since (recorded
  executions, never the agent's description)
- reviewer prompt rewritten for reading: when (and when not) to ask for a check, ties, cut-off
  results, join keys judged from the catalog's example values
- brief parser: only a real ```sql code block counts (an inline mention in prose did)
- main agent: SELECT aliases can't be used in GROUP BY / WHERE (verified on Trino); sample and
  distinct-value tools say when the requested limit was reduced to the ceiling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… (single row, cut-off, empty)

General rules buried in the reviewer's prompt (ties, cut-off lists) were sometimes not applied.
Our code now detects the facts and puts them next to the SQL as specific cues: SQL that keeps one
row (LIMIT 1 / row_number() / max_by → check ties), a cut-off result, an empty result. Two prompt
lines: read the request's exact wording before failing; an extra harmless column is not a problem.
On the 15-question set: a new real catch (DENSE_RANK over five levels), no wrong fails (was 2),
24–80s per question (was 33–117s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts:
- backend/app/routers/agent.py: keep main's configurable AGENT_READ_TIMEOUT_SECONDS for the MCP
  wait; the deep agent is told to stop AGENT_STOP_MARGIN_S (10s) before it
- core/src/core/trino.py: keep both main's catalog/schema overrides and this branch's per-thread
  connection reuse; the reused connection applies only without a catalog/schema override

Legacy refiner tests failing after the merge fail on origin/main alone as well (not caused here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
benben-ship-it and others added 2 commits November 2, 2026 11:16
… longer claims the session zone

The Israel session-zone pin (#43) lives in shared core and also changed the legacy agent and the
eval service. It is now opt-in (TRINO_TIMEZONE=Asia/Jerusalem); unset keeps the Trino client's own
behaviour. The deep agent's guidance keeps the same advice (plain literals, no zones, no hand
conversion) without stating what the session zone is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mote branch)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: a56635db-1b65-4879-b179-2717dc9402f1
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Comment on lines +129 to +137
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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing summary field on porpuse?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"summary": answer.get("needs_clarification") or answer.get("explanation_he") or "",
dont you need something like this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional — it follows the legacy contract: an interrupted response has no summary; the question goes in interrupt_details.reason (the line you suggest is already there, L135), which is what the UI's pause card shows. Callers with hitl_enabled=False get it converted to completed with summary = the question in mcp_server._deep_chat. Also, this path is only live with DEEP_AGENT_CLARIFICATIONS_ENABLED (off by default); the clarification response shape will be revisited in the upcoming ambiguity work.

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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this is always and not sometning like "on demand"?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validation_response is how the agent disputes a failed review. Only always needs it: there, submit is accepted only for SQL the reviewer passed (or that the agent disputes, shown to the user). In on_demand submit doesn't require a review, so there's nothing to dispute — the agent can just submit. always is the default for now (every answer is independently reviewed before submit); longer term we plan on_demand. While checking this I renamed a misleading parameter and added a test that a failed on_demand review still reaches the user (8e74b9c).

Comment thread core/src/core/trino.py
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Image

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this — it doesn't apply. A Trino DBAPI connection is an HTTP session, not a persistent socket: pooled sockets closed by the server/proxy are detected and replaced on reuse, and the trino client already retries ConnectionError/Timeout (max_attempts=3, on both submit and fetch). Verified on Trino: ran a query on the reused connection, killed its socket, then ran another on the same connection object — it succeeded with no error surfaced. So no extra retry layer; it would only double the library's own.

Comment thread agent/src/agent/utils/sql_guard.py Outdated
if not sql or not sql.strip():
raise GuardError("empty SQL")
if _has_comments(sql):
raise GuardError("SQL comments are not allowed")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we not allow SQL comments?

I don't know if it happens a lot, but LLMs tend to love adding comments to everything they write.
And it also doesn't seem very harmful to have comments in an SQL query.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — the ban came from the Utils-Server port. The guard validates the parsed AST (single read statement, no writes/table functions), so a comment can't hide anything; comments are now allowed (and ignored when matching submitted vs executed SQL). The prompt still asks the model not to write them, but a query that has one no longer fails. (693b8e9)

Comment thread agent/src/agent/config.py Outdated
# ── Deep Agent ────────────────────────────────────────────────────────────
DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (<dir>/<name>/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 / get_column_distinct_values

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do we set that number to? and what are the implications?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DEEP_AGENT_MAX_ROWS (default 100; none = no cap) limits the rows per query that go back into the model's context — it protects tokens/latency, and the tool reports truncated so the agent knows it saw a cut-off result. DEEP_AGENT_MAX_SAMPLE_ROWS (10) does the same for get_sample_rows. get_column_distinct_values no longer uses this ceiling — it follows its own limit (default 50) (12631f9). Implication today: the user's answer table comes from the same execution, so it's also capped (marked as partial). Delivering the full result separately (like the legacy raw_data_ref/ESCA path) is a planned follow-up.

return first.get("text", "") if isinstance(first, dict) else str(first or "")


class PromptRefreshMiddleware(AgentMiddleware):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this middleware is unnecessary and makes the process more complicated, if an agent's trajectory has already started, I think we are fine with the prompt not updating while the run started.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on not changing the prompt mid-run — removed the middleware. One nuance: the agent is built once per process, so without anything the prompt would only update on restart, not just after the run. Now the service checks the (SDK-cached) prompt texts per request and rebuilds the agent when one changed: each run keeps the prompt it started with, and a Langfuse label change takes effect from the next request without a redeploy. (6fe2b3e)

Comment thread agent/src/deep_agent/prompts/system.md Outdated

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` searches ONLY `large_categorical` and `large_unit_id` columns — the only column types it indexes. Standard `categorical` and `boolean` columns are not indexed and return 0 matches; numeric, date/timestamp and geometry columns are not indexed either.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe when calling the search column tool on unsupported columns it should show the LLM an error rather than a silent 0 results.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — checked on the live Jeen service: an unindexed column, a non-existent column and a real no-match all come back as the same empty result, so the tool can't tell them apart from the response. Rather than a second metadata lookup for what the catalog already shows, the no-match notice now points the agent at the column's semantic_type (id/continuous/time/free_text are not indexed and always return 0). Also fixed the docs: categorical/boolean are indexed (the prompt said they return 0), and on indexed columns the nearest values come back even for terms not in the data, so matches are judged by score. (f49c4e0)

Comment thread agent/src/deep_agent/tools/__init__.py Outdated
# Values & places
search_column_values,
get_column_distinct_values,
get_column_profile,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the profile tool needed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — removed. The catalog already carries type / semantic type / distinct count / range / examples, and anything else (NULLs, top values, distribution) is one quick SQL query away, and fresher than the stored profile. It was also never called in our test runs (0 calls vs. 155 executions). (04b3ef0)



@tool
async def enrich_sql_filters(sql: str, runtime: Runtime = None) -> str | Command:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this needed on top of the search large categories?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, removed from the deep agent. It was the legacy pipeline's enrichment step (search + a separate LLM picks the spelling + AST rewrite) wrapped as a tool. In the deep agent that's the agent's own job (search_column_values + judging matches, recorded in assumptions), so the tool only added a hidden second LLM decision and a rewrite that has to be re-run. It was also rarely used (2 calls in our test runs). The legacy graph keeps it. (4f8b1aa)

@@ -0,0 +1,17 @@
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validator is a tool right?
when do we expect the agent to call it, and why not have it as a fixed step after the LLM submits the SQL, I guess it depends on how expensive is it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a subagent (called via deepagents' task), not a plain tool, and it only reads — no SQL tools. In the default always mode it is effectively a fixed step, just placed before submit rather than after: submit_answer is refused unless that exact SQL ran and the reviewer passed it (or the agent disputes a fail, which is shown to the user). Before rather than after so a failed review sends the agent back to work inside the same loop, instead of reopening a submitted answer — submit stays only a submit. Cost: one extra model call per review (catalog + question + SQL + assumptions + rows, no query execution), repeated only when the SQL changes. Longer term we plan on_demand (the agent decides when to call it).

benben-ship-it and others added 8 commits November 8, 2026 14:22
…ed vs executed SQL

The comment ban came from the Utils-Server port. The guard checks the parsed
AST (single read statement, no writes/table functions), so a comment cannot hide
anything; rejecting it only cost the agent a failed tool call. The prompt still
asks for no comments. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… query row ceiling

get_column_distinct_values borrowed DEEP_AGENT_MAX_ROWS, so asking for 200
values silently became 100. It now returns up to the requested limit
(default 50) and reports truncated when more exist. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… (it reports on_demand reviews too)

The parameter was named review_required but receives has_reviewer, so it
read as if on_demand reviews were dropped from final_result. Test that a
failed on_demand review still reaches the user. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… of swapping it per model call

PromptRefreshMiddleware replaced the system/validator prompt on every model
call, so moving a Langfuse label mid-run switched prompts halfway through a
trajectory. The service now compares the current prompt texts (SDK-cached)
per request and rebuilds the agent when one changed: a run keeps the prompt
it started with, the next request gets the new one, still without a
redeploy. The checkpointer is kept across rebuilds. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s; clearer no-match notice

Checked on the live Jeen service: categorical and boolean columns are indexed
too (the docs said they return 0), while id / continuous / time / free_text
columns and non-existent tables/columns return 0 whatever the value. On an
indexed column the nearest values come back even for a term not in the data,
so a match is judged by its scores. The no-match notice now points at the
column's semantic_type instead of suggesting the value doesn't exist.
(PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The catalog already carries type / semantic type / distinct count / range /
examples, and NULLs, top values or a distribution are one SQL query away
(fresher than the stored profile). It was never called in our test runs.
Also corrects the tool reference line for search_column_values. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It wrapped the legacy graph's enrichment step (value search + a separate LLM
picks the spelling + AST rewrite). In the deep agent resolving values is the
agent's own job (search_column_values, judging matches, recorded in
assumptions), so the tool added a hidden second LLM decision and a rewrite
that had to be re-run; it was rarely used. Also drops the context helpers
only it used (cached_catalog, user_request). The legacy graph keeps its
enrichment pipeline. (PR #67 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… in chat_with_agent

chat_with_agent showed both agents' arguments and picked one by engine /
AGENT_ENGINE / thread prefix, so half its arguments silently did nothing.
Now each agent has its own tool with only its own arguments: chat_with_agent
is the legacy graph, deep_agent the Deep Agent. Each refuses the other's
threads (deep-… ids). The backend keeps its engine field and uses it to pick
the tool; resumes of deep-… threads go to deep_agent. AGENT_ENGINE removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benben-ship-it benben-ship-it changed the title Feature/deep agent updated Deep agent (separate deep_agent MCP tool) + legacy agent fixes Nov 10, 2026
…tag and result details, backend migrations on start)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benben-ship-it
benben-ship-it force-pushed the feature/deep-agent-updated branch from 1e91ccd to b467b13 Compare November 18, 2026 14:35
@benben-ship-it benben-ship-it changed the title Deep agent (separate deep_agent MCP tool) + legacy agent fixes Deep agent (separate deep_agent MCP tool) + review round Nov 18, 2026
benben-ship-it added a commit that referenced this pull request Nov 22, 2026
Gives the stacked branches a single common base, so PR #68 shows only its own
changes (two separate merges of main had left two merge bases).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benben-ship-it
benben-ship-it merged commit 5f448f2 into main Nov 23, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants