Review the implementation against the success criteria.
code
Project directory:
/private/tmp/Veas-work
User intent summary:
Add a new read-phase tool, consult_perspective, to the Veas mediation agent's tool registry. When the main conversational agent calls it, the orchestrator spawns a small bounded subagent (the "consult") that runs its own LLM loop using only the existing read-phase tools (no writes, no outbound sends, no escalations) and returns a structured advisory result back into the main agent's tool_use/tool_result chain. The consult agent inherits the same filtered hot context, privacy/cross-thread-sharing constraints, and OOB protections as the main agent, so it cannot see or leak material the main agent itself would not. The caller can supply either a free-form custom perspective description or pick one of a small set of named perspective templates (e.g. NVC, Gottman, IFS, devil's-advocate, etc.). A new consult_model config setting governs which model the subagent uses, defaulting to conversational_model. The agent's system prompt and the registry's tool description are updated so the main loop knows when consultation is appropriate. Tests cover the tool surface, template lookup, phase/permission gating, context inheritance, and that the result round-trips through the existing tool_calls plumbing. Explicitly out of scope: a consultations persistence table, a multi-perspective panel tool, and any write/outbound capability for the subagent.
Original idea:
Implement a read-phase consult_perspective tool for the Veas mediation agent. The tool should let the main agent request a bounded second opinion from a custom perspective or one of several named templates, using only safe read-phase tools and the same filtered context/privacy/OOB constraints as the main agent. It should return a structured advisory result, persist through normal tool_calls, update prompt/tool registry guidance, add config for the consult model defaulting to the conversational model, and include focused tests. Keep the implementation simple: no new consultations table, no panel tool yet, no write/outbound permissions for the consult subagent.
tool_schemas.py is the single source of truth for tool input/output Pydantic models and TOOL_REGISTRY.
app/services/tools/registry.py owns TOOL_DESCRIPTIONS, TOOL_DISPATCH, , , , and phase gating.
Assistant
{"criteria":[],"issues":[],"summary":"I’ll inspect the implementation against the stated criteria and focus on concrete behavioral gaps rather than re-summarizing the patch."}
Assistant
{"criteria":[],"issues":[],"summary":"I have the main diff. Next I’m checking the consult handler and the LLM loop details for mismatches that targeted tests may not catch."}
Assistant
READ_PHASE_TOOLS
WRITE_PHASE_TOOLS
to_anthropic_tools()
call_tool()
app/services/agentic.py already has a reusable run_phase() loop, Anthropic client creation, spend-cap checks, cost recording, message/tool result plumbing, and hot-context rendering passed into the LLM phase.
TurnContext currently does not carry hot_context_rendered, so the consult tool needs a small context extension.
evals.capture.record_tool_call() already supports arbitrary phase strings, so inner consult calls can be tagged with phase="consult" once TurnContext.phase and registry gating allow it.
Read tools enforce privacy/OOB context through ctx.user, ctx.partner, protected_owner_ids, and cross-thread sharing defaults.
Important asymmetry (flag-1):app/services/tools/read_tools.py::check_oob only consults args.protected_owner_ids; it does not fall back to ctx.protected_owner_ids. The schema (tool_schemas.py::CheckOOBInput) documents that omission collapses to recipient-only. So a consult subagent that calls check_oob without explicitly passing the parent turn's protected owner IDs would silently weaken OOB enforcement. The plan below adds a consult-phase argument-defaulting step that closes this gap, scoped to the consult dispatch path so main-agent behavior is unchanged.
This satisfies all gating rules (main read can call; main write cannot; consult cannot recurse; consult cannot call writes or send_message_part).
Step 4: Close The OOB-Inheritance Gap For Consult Calls (addresses flag-1)
The consult subagent must inherit the parent turn's protected_owner_ids even when the model omits them from a tool call. We do this in the consult dispatch path only, so main-agent behavior is unchanged.
In app/services/tools/registry.py, add a small helper used only whenctx.phase == "consult":
python
_CONSULT_OWNER_INJECTING_TOOLS = {"check_oob"}
def _inject_consult_defaults(name: str, raw_args: dict[str, Any], ctx: TurnContext) -> dict[str, Any]:
if ctx.phase != "consult":
return raw_args
if name in _CONSULT_OWNER_INJECTING_TOOLS and ctx.protected_owner_ids:
merged = dict(raw_args or {})
existing = merged.get("protected_owner_ids")
if not existing:
merged["protected_owner_ids"] = [str(uid) for uid in ctx.protected_owner_ids]
else:
seen = {str(x) for x in existing}
for uid in ctx.protected_owner_ids:
if str(uid) not in seen:
existing.append(str(uid))
seen.add(str(uid))
merged["protected_owner_ids"] = existing
return merged
return raw_args
In call_tool(), after the _phase_allowed check and before input_model.model_validate(raw_args), replace:
Scope: only check_oob needs this today, since other read tools either don't accept protected_owner_ids (e.g. search_messages, recent_activity — they read from ctx.user/ctx.partner directly) or already source protections from ctx. The set is a named constant so future tools can be added explicitly rather than by accident.
The defaulting is additive: if the consult model passes a partial list, we union rather than overwrite, so it cannot strip protections; if it passes none, we inject the parent's full list.
This change must not affect main read/write phases — guarded by the ctx.phase == "consult" check.
Add a focused test in tests/test_tools.py (or the new consult test file) that calls call_tool("check_oob", {"content": ..., "recipient_id": ...}, ctx_with_consult_phase_and_protected_ids) and asserts check_oob_with_policy was invoked with the inherited protected_owner_ids.
Step 5: Make run_phase() Parameterizable
In app/services/agentic.py, update helpers without changing default behavior:
run_phase(..., model: str | None = None, max_tokens: int = 1200, max_tool_iterations: int | None = None).
If max_tool_iterations is exceeded, raise a typed local exception (e.g. ConsultBoundedLoopExceeded) the consult handler can catch. Existing main-phase callers pass no iteration cap and so are unaffected.
Cheap validation:
bash
uv run pytest tests/test_llm_phase.py -q
Step 6: Implement Consult Handler
Add app/services/tools/consult_perspective.py.
Responsibilities:
Resolve perspective body: lookup PerspectiveTemplate -> prompt body in a local dict, or use args.perspective.
Build a consult system prompt:
Fixed preamble: read-only, advisory-only, never send/write/escalate, inherit all OOB/privacy/cross-thread rules, do not reveal protected material, do not claim authority.
Reminder that check_oob calls inherit the parent turn's protected owners automatically; the subagent should still pass recipient_id correctly and may pass additional protections, but cannot remove inherited ones.
Perspective-specific lens.
Output contract: final response must be compact JSON matching ConsultPerspectiveOutput.
Build a consult TurnContext cloned from the parent with:
phase="consult"
same turn_id, pool, user, partner, triggering_message_ids, protected_owner_ids, trigger_charge, identities, hot_context_rendered.
Add a short paragraph under tool usage / two-phase turn shape:
Consult before a charged or ambiguous outbound.
Consult when the assistant suspects its read is one-sided.
Consult is advisory; the main agent remains responsible for final wording and OOB-safe delivery.
In TOOL_DESCRIPTIONS, describe consult_perspective as a read-phase advisory tool for bounded second opinions, especially before charged/ambiguous replies or critique of a proposed response.
Step 8: Tests
Add tests/test_consult_perspective.py, plus small additions to existing files.
OOB inheritance via consult-phase defaulting (flag-1):
With ctx.phase="consult" and non-empty ctx.protected_owner_ids, calling check_oob with no protected_owner_ids arg results in check_oob_with_policy being invoked with the parent's IDs.
With partial args, the lists are unioned, not overwritten or stripped.
With ctx.phase="read", the main agent's check_oob calls are not modified (regression guard).
Privacy inheritance: a stubbed consult response that calls search_messages confirms partner-private content remains hidden under existing sharing defaults (uses parent ctx.user/ctx.partner).
End-to-end plumbing: main read phase model calls consult_perspective; consult Anthropic stub returns advisory JSON; main receives a normal tool_result; inner tool calls captured in evals.capture with phase="consult".
Use the existing fake-Anthropic style from tests/test_agentic.py and tests/test_llm_phase.py.
Step 9: Validation Sequence
bash
uv run pytest tests/test_tool_schemas_importable.py tests/test_config.py -q
uv run pytest tests/test_llm_phase.py -q
uv run pytest tests/test_consult_perspective.py -q
uv run pytest tests/test_tools.py tests/test_agentic.py tests/test_agentic_lifecycle.py tests/test_evals_capture.py -q
uv run pytest -q
Observable Success Criteria
consult_perspective appears in TOOL_REGISTRY, TOOL_DESCRIPTIONS, TOOL_DISPATCH, and READ_PHASE_TOOLS; absent from WRITE_PHASE_TOOLS and CONSULT_PHASE_TOOLS.
Consult subagent Anthropic requests use settings.consult_model, max_tokens=600, and only consult-safe tools.
Main turn does not crash when consult times out, exceeds spend cap, returns invalid JSON, or produces invalid output; the failure surfaces as {is_error: true, error: "..."}.
Main read-phase transcript contains the consult_perspective tool use/result like any other tool result.
Inner consult read-tool calls are captured by evals.capture with phase="consult".
check_oob calls made by the consult subagent inherit the parent turn's protected_owner_ids even when the model omits them, and a regression test guards that main-phase check_oob calls remain unchanged.
No migration or new consultations table is added.
No consult path can send messages, mutate DB state via write tools, escalate, or call itself recursively.
Assumptions
TurnContext can be extended with phase="consult" and hot_context_rendered without disrupting existing read/write tests.
Parameterizing the existing run_phase() loop is preferred over duplicating agentic loop logic.
Advisory JSON can be parsed from the consult model's final text and validated with Pydantic.
Consult read tools should share the parent turn_id for observability.
check_oob is the only read tool whose privacy posture today depends on a caller-supplied protected_owner_ids; other read tools derive privacy scope from ctx. If that ever changes, _CONSULT_OWNER_INJECTING_TOOLS is the named extension point.
Open Questions
Should custom perspective be echoed verbatim in template_used, or use a fixed "custom" to avoid returning long prompt text?
Should consult_model have separate pricing fields if it may differ materially from conversational_model, or is the existing text LLM pricing acceptable for now?
Should consult output allow empty suggested_moves / caveats, or require at least one item for successful advisory records?
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-05-02T17:24:39Z",
"hash": "sha256:bab114eb050433dac118c8f3ec389b059c985fe82a7dba5fe1e52a6e5250904b",
"changes_summary": "Addressed flag-1 by adding a new Step 4, "Close The OOB-Inheritance Gap For Consult Calls", which introduces a small _inject_consult_defaults helper in registry.py::call_tool that runs only when ctx.phase == \"consult\" and merges the parent turn's protected_owner_ids into check_oob arguments before validation (union, never overwrite or strip). This was necessary because read_tools.check_oob reads args.protected_owner_ids (not ctx.protected_owner_ids), so simply copying IDs onto the consult TurnContext \u2014 as the previous plan did \u2014 would have left a silent privacy regression where a consult subagent calling check_oob without the arg falls back to recipient-only checks. Updated Repository Findings to call out this asymmetry, added a named extension constant _CONSULT_OWNER_INJECTING_TOOLS = {\"check_oob\"} so future additions are explicit, added two targeted tests (defaulting + union behavior, plus a regression guard that main read/write phases are untouched), restated the inheritance guarantee in Observable Success Criteria, and noted the assumption that check_oob is the only such tool today. Step numbering shifted (run_phase parameterization moved to Step 5, handler to Step 6, prompts to Step 7, tests to Step 8, validation to Step 9). No scope expansion beyond what flag-1 strictly requires; the consult tool's surface, schemas, config, gating, and out-of-scope list are unchanged.",
"flags_addressed": [
"flag-1"
],
"questions": [
"Should consult timeout be configurable as consult_timeout_s, or hardcoded for now? (Plan currently makes it configurable.)",
"For custom perspectives, should template_used echo the full custom string or simply return custom?",
"Can consult model spend use the existing text LLM pricing fields even if the model differs from conversational_model?",
"Are there other read tools beyond check_oob whose privacy posture depends on caller-supplied IDs that should be added to _CONSULT_OWNER_INJECTING_TOOLS now, or is targeting check_oob alone the right v1 scope?"
],
"success_criteria": [
"consult_perspective is registered as a read-phase-only tool and is rejected in write/consult phases.",
"The consult subagent's Anthropic tool list is exactly READ_PHASE_TOOLS - {send_message_part, consult_perspective}.",
"The consult loop uses settings.consult_model, max_tokens=600, bounded tool iterations from settings.consult_max_tool_iterations, settings.consult_timeout_s, and the existing text spend cap.",
"Successful consults return validated structured advisory output; timeout / spend-cap / bounded-loop / JSON / validation failures all return model-valid {is_error: true, error: ...} results without crashing the parent turn.",
"Inner consult tool calls are captured via evals.capture with phase="consult" and no new DB persistence is introduced.",
"check_oob calls made under ctx.phase=="consult" inherit the parent turn's protected_owner_ids when the model omits them, union (never overwrite) when partial args are supplied, and main-phase check_oob behavior is provably unchanged via regression test.",
"Tests cover schemas, gating, allowlist, templates, graceful errors, OOB inheritance defaulting + regression guard, privacy inheritance via shared user/partner, and end-to-end tool result plumbing."
],
"assumptions": [
"TurnContext can be extended with phase="consult" and hot_context_rendered without disrupting existing read/write tests.",
"Parameterizing the existing run_phase() loop is preferred over duplicating agentic loop logic.",
"Advisory JSON can be parsed from the consult model's final text and validated with Pydantic.",
"Consult read tools should share the parent turn id for observability.",
"check_oob is the only read tool today whose privacy posture depends on a caller-supplied protected_owner_ids; other read tools derive privacy scope from ctx. _CONSULT_OWNER_INJECTING_TOOLS is the named extension point if that changes."
],
"delta_from_previous_percent": 40.84
}
code
Execution summary:
{
"output": "Implemented consult_perspective as a read-phase-only advisory tool with bounded consult subagent execution.\n\nKey points:\n- Added consult input/output schemas, named templates, and Pydantic-v2-safe error output defaults.\n- Added consult_model, consult_max_tool_iterations, and consult_timeout_s settings, with consult_model defaulting to conversational_model.\n- Extended TurnContext with phase=\"consult\" and inherited hot context.\n- Registered consult_perspective in the tool registry and added CONSULT_PHASE_TOOLS = READ_PHASE_TOOLS - {\"send_message_part\", \"consult_perspective\"}.\n- Implemented consult-only check_oob protected-owner injection so consult calls inherit parent protected_owner_ids without changing main read/write behavior.\n- Parameterized run_phase() for model, token budget, and bounded tool iterations.\n- Added the consult handler and prompt/tool guidance.\n- Added focused tests for schemas, gating, allowlist, templates, errors, privacy inheritance, OOB inheritance, and tool-result round trip.\n\nValidation:\n- Targeted suites pass: 74 passed, then 21 passed, then 69 passed after cleanup.\n- Full suite passes with required dummy env: 297 passed, 3 skipped.\n\nNotes:\n- uv could not be used in this sandbox: the default cache was not writable, and with UV_CACHE_DIR=/private/tmp/uv-cache, uv panicked before pytest started. I used .venv/bin/pytest instead.\n- A bare full-suite run without dummy env failed in existing env-dependent Discord/hot-context tests; rerunning with the repo\u2019s required dummy env values passed.\n- For custom perspectives, template_used returns \"custom\" rather than echoing the full custom perspective text, to avoid unnecessary prompt-text exposure in tool results.",
"files_changed": [
"/private/tmp/Veas-work/tool_schemas.py",
"/private/tmp/Veas-work/app/config.py",
"/private/tmp/Veas-work/app/services/turn_context.py",
"/private/tmp/Veas-work/app/services/tools/registry.py",
"/private/tmp/Veas-work/app/services/agentic.py",
"/private/tmp/Veas-work/app/services/tools/consult_perspective.py",
"/private/tmp/Veas-work/app/services/prompts.py",
"/private/tmp/Veas-work/tests/test_config.py",
"/private/tmp/Veas-work/tests/test_tools.py",
"/private/tmp/Veas-work/tests/test_consult_perspective.py"
],
"commands_run": [
"rg -n "TOOL_REGISTRY|class .*Input|Confidence|Consult|READ_PHASE_TOOLS|WRITE_PHASE_TOOLS|def call_tool|async def run_phase|create_message_with_retry|class TurnContext|phase:|conversational_model|Settings|TOOL_DESCRIPTIONS" .",
"rg --files .",
"git status --short",
"sed -n '1,260p' tool_schemas.py",
"sed -n '260,1060p' tool_schemas.py",
"sed -n '1,260p' app/services/tools/registry.py",
"sed -n '1,140p' app/services/turn_context.py",
"sed -n '1,360p' app/services/agentic.py",
"sed -n '360,860p' app/services/agentic.py",
"sed -n '1,140p' app/config.py",
"sed -n '1,220p' app/services/prompts.py",
"sed -n '220,460p' app/services/prompts.py",
"sed -n '1,240p' tests/test_llm_phase.py",
"sed -n '1,220p' tests/test_agentic.py",
"sed -n '1,130p' tests/test_config.py",
"sed -n '880,960p' tests/test_tools.py",
"rg -n "check_oob_with_policy|def check_oob|protected_owner_ids" app/services/tools/read_tools.py tests tests/conftest.py",
"sed -n '1,220p' tests/conftest.py",
"rg -n "capture_tool_calls|ToolTranscript|tool_calls" app tests/test_agentic.py tests/test_evals_capture.py evals",
"sed -n '1560,1615p' tests/conftest.py",
"rg -n "tool_ctx" tests/conftest.py tests/test_tools.py",
"sed -n '80,150p' tests/test_tools.py",
"sed -n '90,125p' app/services/tools/write_tools.py",
"sed -n '280,320p' tests/test_agentic.py",
"sed -n '40,85p' tests/test_evals_capture.py",
"uv run pytest tests/test_tool_schemas_importable.py tests/test_config.py tests/test_llm_phase.py tests/test_consult_perspective.py tests/test_tools.py -q",
"UV_CACHE_DIR=/private/tmp/uv-cache uv run pytest tests/test_tool_schemas_importable.py tests/test_config.py tests/test_llm_phase.py tests/test_consult_perspective.py tests/test_tools.py -q",
"python -m pytest tests/test_tool_schemas_importable.py tests/test_config.py tests/test_llm_phase.py tests/test_consult_perspective.py tests/test_tools.py -q",
"ls -la",
"find . -maxdepth 3 -type f \( -name pytest -o -name python \)",
"python -m compileall tool_schemas.py app tests/test_consult_perspective.py tests/test_tools.py tests/test_config.py",
".venv/bin/pytest tests/test_tool_schemas_importable.py tests/test_config.py tests/test_llm_phase.py tests/test_consult_perspective.py tests/test_tools.py -q",
".venv/bin/pytest tests/test_agentic.py tests/test_agentic_lifecycle.py tests/test_evals_capture.py -q",
".venv/bin/pytest -q",
"DATABASE_URL=postgresql://user:pass@localhost:5432/db DATABASE_SCHEMA=public SUPABASE_URL= [REDACTED] ANTHROPIC_API_KEY=dummy-anthropic OPENAI_API_KEY=dummy-openai GROQ_API_KEY=dummy-groq WHATSAPP_TOKEN=dummy-whatsapp WHATSAPP_BEARER_TOKEN=dummy-whatsapp WHATSAPP_PHONE_NUMBER_ID=12345 WHATSAPP_VERIFY_TOKEN=dummy-verify WHATSAPP_APP_SECRET=[REDACTED] MESSAGING_PROVIDER=meta ADMIN[REDACTED] PARTNER_PHONE_A=15555550100 PARTNER_PHONE_B=15555550101 DISCORD_PARTNER_USER_ID_A= DISCORD_PARTNER_USER_ID_B= SUPABASE_STORAGE_BUCKET=mediator-media MEDIA_FETCH_TIMEOUT_S=30 DEFAULT_USER_TIMEZONE=UTC DISCORD_BOT_TOKEN=dummy-discord .venv/bin/pytest -q",
"git diff --stat",
"nl -ba tool_schemas.py | sed -n '115,150p;990,1060p'",
"nl -ba app/services/tools/registry.py | sed -n '15,210p'",
"nl -ba app/services/tools/consult_perspective.py | sed -n '1,180p'",
"nl -ba app/services/agentic.py | sed -n '40,315p;655,675p'"
],
"deviations": [
"For custom perspectives, returns instead of echoing the full custom perspective string.",
"Used instead of because failed in this sandbox.",
"No migrations or consultations table were added, per scope."
]
}
code
Git diff summary:
M app/config.py
M app/services/agentic.py
M app/services/prompts.py
M app/services/tools/registry.py
M app/services/turn_context.py
M tests/test_config.py
M tests/test_tools.py
M tool_schemas.py
?? app/services/tools/consult_perspective.py
?? tests/test_consult_perspective.py
code
Requirements:
- Be critical.
- Verify each success criterion explicitly.
- Call out any concrete gaps or regressions in issues.
{"criteria":[{"name":"Registry/tool surface","pass":true,"evidence":"consult_perspective is in TOOL_REGISTRY, TOOL_DESCRIPTIONS, TOOL_DISPATCH, and READ_PHASE_TOOLS; it is absent from WRITE_PHASE_TOOLS, and CONSULT_PHASE_TOOLS excludes both send_message_part and consult_perspective."},{"name":"Phase and permission gating","pass":true,"evidence":"_phase_allowed() handles read, write, and consult; nested consult calls and write-phase consult calls return phase errors through call_tool()."},{"name":"Consult-safe tool allowlist","pass":true,"evidence":"The consult handler calls run_phase(..., set(CONSULT_PHASE_TOOLS), ...), and CONSULT_PHASE_TOOLS = READ_PHASE_TOOLS - {\"send_message_part\", \"consult_perspective\"}. Write tools are not included."},{"name":"Consult model/config behavior","pass":true,"evidence":"Settings adds consult_model, consult_max_tool_iterations, and consult_timeout_s; the validator defaults consult_model to conversational_model. The handler passes model=settings.consult_model, max_tokens=600, and the configured iteration cap/timeout."},{"name":"Structured advisory output","pass":true,"evidence":"ConsultPerspectiveInput enforces exactly one of template/custom perspective. ConsultPerspectiveOutput validates successful results require summary and confidence, while error results require error."},{"name":"Graceful failure handling","pass":true,"evidence":"The consult handler returns model-valid {is_error: true, error: ...} for timeout, spend cap, bounded-loop, JSON decode, output validation, Anthropic API errors, and generic exceptions inside the consult execution block."},{"name":"Context/privacy inheritance","pass":true,"evidence":"The consult TurnContext clones the parent turn id, pool, user, partner, triggering ids, protected owner ids, charge, start time, and hot context. Existing read tools continue using the inherited ctx.user/ctx.partner privacy rules."},{"name":"OOB protected-owner inheritance","pass":true,"evidence":"_inject_consult_defaults() runs only in ctx.phase == \"consult\" and unions parent protected_owner_ids into check_oob args before validation. Tests cover omitted args, partial args, and unchanged read-phase behavior."},{"name":"Tool result plumbing and capture","pass":true,"evidence":"The main run_phase() treats consult_perspective like any other tool_use/tool_result. Inner consult tool calls use consult_ctx.phase = \"consult\", so evals.capture records them with phase=\"consult\"."},{"name":"Out-of-scope persistence/write behavior","pass":true,"evidence":"No consultation table or migration was added. The consult phase cannot call write tools, send_message_part, escalation tools, or itself recursively through the registry gate."},{"name":"Test coverage against approved plan","pass":false,"evidence":"Focused tests cover schemas, gating, allowlist, template lookup, graceful errors, OOB inheritance, privacy inheritance, capture, and round-trip plumbing. However, the approved plan explicitly called for length-cap schema failures and Anthropic SDK error coverage; those exact cases are not tested."}],"issues":["Minor coverage gap: tests/test_consult_perspective.py does not exercise the declared length caps for perspective, focus, or proposed_response, even though the schema enforces them. It also does not directly cover an anthropic.APIError; current coverage reaches generic LLMPhaseError/exception handling instead.","Semantic nit: max_tool_iterations is implemented as a cap on total individual tool calls in run_phase() (tool_call_count > max_tool_iterations), not on LLM tool-use loop iterations. That is stricter than the setting name and could reject one consult response that makes several parallel safe read calls in a single round."],"summary":"Implementation substantially meets the success criteria. I did not find a write/outbound permission regression, OOB inheritance is handled in the right place, and targeted consult/tool/LLM tests pass locally (69 passed). The remaining gaps are small: test coverage misses a couple of planned edge cases, and the bounded-loop cap is named like an iteration cap but behaves as a total tool-call cap."}