Skip to content

Self-hosted AI workspace.

Python

merge: reconcile Wave 1.1 with post-PR40 lab

Alexandre Teixeiraf4793696f47f
diff --cc docs/runtime-decomposition/WAVE_1_1_RECONCILIATION.md
index 000000000,000000000..266919c1d
new file mode 100644
--- /dev/null
+++ b/docs/runtime-decomposition/WAVE_1_1_RECONCILIATION.md
@@@ -1,0 -1,0 +1,153 @@@
++# Wave 1.1 final post-PR40 reconciliation
++
++This is the one-time local reconciliation of completed Wave 1.1 with the
++authoritative post-PR40 lab commit. It does not start another runtime wave.
++
++## Verified starting state
++
++- Wave branch: `feature/agent-runtime-wave-1-1`.
++- Original Wave HEAD: `63457367aeed431b2c48967988259e5861f19916`, clean.
++- Canonical branch: `lab`.
++- Canonical HEAD: `9557b8d5909eb4a885c3bf49e19a65dd904f8c1d`, clean.
++- Merge base: `f0761641a12b63e401960f596d3d1be8fc90fbea`.
++- Divergence: 10 Wave-only commits and 47 lab-only commits.
++- Changed-file overlap: `src/agent_loop.py`, `src/tool_execution.py`,
++ `tests/test_tool_policy.py`, and `tests/README.md`.
++
++The Wave-only commits were `d57d5c58`, `dfeab64a`, `ae2445d6`, `7d84f3fe`,
++`1470dbb2`, `32830918`, `ba29afb9`, `bdfcbc0a`, `70cbaf81`, and `63457367`.
++Their completed behavior is retained. The canonical worktree is read-only;
++the exact canonical SHA was merged once with `--no-ff --no-commit`.
++
++## Semantic integration
++
++The only textual conflict was in `src/tool_execution.py`, where Wave 1.1
++wrapped dynamic dispatch with `dispatched(...)` and lab added `disabled_tools`
++and `tool_policy` forwarding. The resolution retains both inside the wrapper.
++Lab's new owner-aware image-generation dispatch also receives that wrapper.
++The image regression checks that explicit denial never invokes the backend,
++actual dispatch has an execution identity, and a backend without an explicit
++exit code does not manufacture an authoritative success receipt.
++
++Broad validation exposed narrow adapter incompatibilities beyond the textual
++conflict. Native host-shell JSON now uses the same decoded command classification
++as journal evidence. The exact existing TUI interpreter-selection string is
++shared with the evidence parser: a following foreground verifier keeps its
++exit status, while generic conditional discovery, help/collection modes,
++variable arguments, and status-masking tails remain insufficient test proof.
++The generated interpreter-selection command itself is unchanged.
++
++The generated environment reference is refreshed with the canonical generator
++so its source-location links match the reconciled code.
++
++Structured native patch arguments retain artifact targets. A pre-edit
++inspection cannot invalidate a later passing executable verifier, but still
++cannot verify the edited artifact by itself; failed post-edit inspections
++remain failures. Artifact recovery's terminal round-text revisions retract buffered rejected drafts
++before presentation; their replacement prose is still gated by journal
++evidence. Explicit final-response events retain precedence, safe reasoning
++survives, and provider-error partials and diagnostics retain their ordering.
++
++Existing subprocess doubles now carry PIDs. Execution simulations use the
++existing receipt-aware test helper. Contract tests assert the additional
++completion-decision event and retain their no-inference/no-execution spies.
++TUI tests retain tool order, retry behavior, and positive explicit-verifier
++coverage while additionally rejecting completion from an opaque fallback.
++Round-control fixtures explicitly fail unconfigured direct-provider synthesis
++instead of contacting their fake endpoint, and supply the synthetic context
++window while retaining real compaction logic. Conversational round provenance is
++preserved outside artifact recovery.
++
++The agent-loop changes merged automatically: lab's weather relevance and
++policy-gated browser fallback coexist with Wave's action receipts, completion
++gate, and deferred teacher handoff. The fallback dispatcher runs inside the
++current invocation's journal. No generic tool floor was restored.
++
++`src/agent_runs.py`, `routes/chat_routes.py`, `static/js/chat.js`,
++`static/js/chatRenderer.js`, `src/tool_policy.py`, `src/tool_capabilities.py`,
++`src/turn_contract.py`, `src/model_profiles.py`, and
++`src/clean_agent_preview.py` retain the exact canonical lab content.
++
++## Identity audit
++
++These classifications describe every relevant identity use across the
++detached-run manager, chat routes/browser consumers, completion gate, journal,
++teacher handoff, and existing server-owned security provenance.
++
++| Class | Uses and boundary |
++| --- | --- |
++| 1. Live/detached stream-run identity | `agent_runs._Run.run_id`, `get_run_id`, and the chat response's `X-Odysseus-Run-Id` identify the detached stream. The browser's `_streamRunIds` is populated from the response header. |
++| 2. Stop/resume/replay identity | `expected_run_id` in `stop` and `request_finish`, route request headers, `_postExactStop`, the finish-editor request, `streamRunId`, and `resumeRunId` refer to that same detached stream. `subscribe` binds the exact `_Run` object returned by start/resume. |
++| 3. Stream metrics/cost identity | `_metricsCostRecordId` uses the header-derived stream ID plus `primary`/`teacher`; `metrics._costRecordId` and the cost renderer's local `runId` refer to this accounting key. Neither uses terminal metadata's journal `run_id`. |
++| 4. Logical nested invocation identity | `ActionJournal.run_id` is generated per completion-gated invocation. `action_id` is derived from it. The completion gate's terminal metadata `run_id` identifies this logical invocation. Existing `ToolRunSecurityContext.run_id` and `origin_run_id` values identify separate server-owned invocation/skill provenance operations; they are neither stream IDs nor journal lineage. |
++| 5. ActionJournal parent/child identity | `ActionJournal.parent_run_id`, the gate's parent lookup, `_parent_run_id`, `request_teacher_takeover`'s captured parent ID, and `run_teacher_inline(parent_run_id=...)` link journal invocations. The completion metadata's `parent_run_id` preserves that lineage. |
++
++No invocation ID is passed to stream stop/finish/replay APIs. No stream ID is
++inserted into journal lineage. A new detached-stream regression creates nested
++gates, rejects both journal IDs at stop/finish, accepts the stream ID for finish,
++and verifies identical replay and unchanged journal metadata.
++
++## Runtime invariants and final lab behavior
++
++Every gated invocation creates a distinct journal, including children using
++the same workspace. Journal and action bindings restore on normal unwind,
++exception, cancellation, and generator close. Child awaiting/exhausted/error
++state cannot rewrite the parent's completion decision or receipts.
++
++The teacher adapter runs after the student gate closes. It forwards the parent
++turn contract, tool policy, disabled tools, plan, client runtime context, and
++external-untrusted-context restriction. Teacher execution receives a new
++journal whose parent is the student invocation. Inner terminal frames are
++consumed; only the outer adapter emits final termination. Exact framed
++`data: [DONE]` events are distinguished from ordinary content containing the
++literal marker.
++
++Provider failures retain live events, then safe partial content when present,
++then a non-completing decision, terminal metadata, and the original error last,
++without DONE. A bare error remains a bare error. Completion gating does not
++add provider calls or turn missing evidence into extra provider rounds.
++
++Lab's server-owned authority remains narrower than inventory or availability.
++Transcription, OCR, tasks, browser fallback, request-specific capability
++selection, compact contracts, and provider-compatible tool choice retain the
++canonical implementation. Model ID `Ajax` selects the Odysseus compact profile;
++its selected schema boundary survives compatible `auto` tool choice, explicit
++no-tools remains explicit, and transport remains OpenAI-compatible. No
++benchmark-runner code was independently edited or executed.
++
++## Validation records
++
++The current requirements were installed in an isolated environment under this
++worktree's ignored `.cache/wave1-1-reconciliation` directory. The shell's
++unrelated `python` environment was not used for the accepted validation.
++Canonical full pytest uses the repository's default data directory and allows
++dotenv loading so research-path and setup tests can exercise their own fixtures;
++the focused Wave script retains its explicit runtime isolation settings.
++Optional live Ajax tests retain their opt-in skips; no live model or benchmark
++run is part of this reconciliation.
++
++- [Focused tests](validation/wave-1-1-reconciliation-focused.txt)
++- [Wave 1.1 validation script](validation/wave-1-1-reconciliation-wave-validation.txt)
++- [Broad affected runtime suite](validation/wave-1-1-reconciliation-broad.txt)
++- [Canonical full pytest](validation/wave-1-1-reconciliation-pytest.txt)
++- [Compileall, JS/MJS syntax, diff checks, and conflict-marker scan](validation/wave-1-1-reconciliation-gates.txt)
++
++The focused records include the final relevant rerun after the reconciliation
++audit was written. Full pytest and canonical static gates run afterward. The
++local merge is committed only after the required checks pass. No push, PR,
++deployment, or later-wave work is authorized by this reconciliation.
++
++## Maestrum limitations encountered
++
++The normal read-only pre-merge comparison stalled without a completion or
++failure payload; its execution cell was terminated and the investigation was
++not retried. Exact-path inspection proceeded using `local_only` with
++`scope_mode="worktree"`.
++
++The Context Firewall rejected an unbounded `git diff --cached --check` command
++and withheld raw log output after the inspection allowance was exhausted.
++Requests for ignored `.log` files were rejected with
++`scope_rejected: ignored_by_git`. Unignored `.txt` validation records were
++subsequently admitted by exact path. Canonical checks themselves run as
++validation operations and record their exit status in the admitted gate log.
++No epoch waiting or alternative worker mechanism was used.
diff --cc docs/runtime-decomposition/validation/wave-1-1-reconciliation-gates.txt
index 000000000,000000000..a6271415d
new file mode 100644
--- /dev/null
+++ b/docs/runtime-decomposition/validation/wave-1-1-reconciliation-gates.txt
@@@ -1,0 -1,0 +1,7 @@@
++Python compileall: 1689 tracked files; 0 failures
++JS syntax: 279 tracked files; 0 failures
++MJS syntax: 82 tracked files; 0 failures
++git diff --check: exit 0
++git diff --cached --check: exit 0
++git diff HEAD --check: exit 0
++Conflict-marker scan: 2377 tracked files; 0 matches
diff --cc src/agent_evidence.py
index 674837438,5fc6165d8..54d14367c
--- a/src/agent_evidence.py
+++ b/src/agent_evidence.py
@@@ -200,12 -195,12 +200,12 @@@ _VALIDATION_COMMAND_RE = re.compile
def command_is_validation(command: str) -> bool:
"""Return whether a shell command provides executable verification evidence."""
value = str(command or "")
- return is_validation_command(value)
- return bool(_TEST_COMMAND_RE.search(value) or _VALIDATION_COMMAND_RE.search(value))
++ return is_validation_command(_command_text(value))
def command_is_test(command: str) -> bool:
"""Return whether a shell command executes a recognized test runner."""
- return is_test_command(str(command or ""))
- return bool(_TEST_COMMAND_RE.search(str(command or "")))
++ return is_test_command(_command_text(str(command or "")))
def _clean_path(value: str) -> str:
@@@ -518,11 -472,11 +518,18 @@@ def _explicit_tool_paths(tool: str, com
args = json.loads(command or "{}")
except (TypeError, json.JSONDecodeError):
return []
- path = _clean_path(str(args.get("path") or "")) if isinstance(args, dict) else ""
+ path = str(args.get("path") or "").strip() if isinstance(args, dict) else ""
return [path] if path else []
if tool == "apply_patch":
++ try:
++ args = json.loads(command or "{}")
++ except (TypeError, json.JSONDecodeError):
++ args = None
++ if isinstance(args, Mapping):
++ patch = args.get("patch")
++ command = patch if isinstance(patch, str) else ""
return [
- _clean_path(match.group(1))
+ match.group(1).strip()
for match in re.finditer(r"^\*\*\* (?:Add|Update|Delete) File:\s*(.+)$", command or "", re.MULTILINE)
if _clean_path(match.group(1))
]
@@@ -990,6 -866,6 +997,11 @@@ class EvidenceLedger
latest_validation_index, latest_validation = matching_validations[-1]
latest_artifact_mutation_index = max(matching_mutation_indices, default=-1)
if latest_validation_index < latest_artifact_mutation_index:
++ # A pre-edit inspection cannot invalidate executable checks
++ # that passed against the later mutation. It still cannot
++ # stand in for current verification when no such check exists.
++ if latest_verifier_index > latest_artifact_mutation_index:
++ continue
return CompletionDecision(
CompletionStatus.BLOCKED,
False,
diff --cc src/agent_loop.py
index d5556da2d,bf519cf82..988b454f0
--- a/src/agent_loop.py
+++ b/src/agent_loop.py
@@@ -9168,16 -9171,16 +9174,8 @@@ def _failed_tool_round_limit
def _tui_python_runner_setup() -> str:
"""Select the workspace interpreter, including a primary checkout venv."""
--
-- return (
-- "runner=''; "
-- "if [ -x .venv/bin/python ]; then runner=.venv/bin/python; "
-- "elif [ -x venv/bin/python ]; then runner=venv/bin/python; "
-- "elif git_common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) "
-- "&& [ -x \"$(dirname \"$git_common\")/.venv/bin/python\" ]; then "
-- "runner=\"$(dirname \"$git_common\")/.venv/bin/python\"; "
-- "else runner=python; fi; "
-- )
++ from src.agent_runtime.identity import TUI_PYTHON_RUNNER_SETUP
++ return TUI_PYTHON_RUNNER_SETUP
def _tui_local_test_runner_command(*, full: bool = False) -> str:
diff --cc src/agent_runtime/completion.py
index ed6b631ef,000000000..83b9f44cd
mode 100644,000000..100644
--- a/src/agent_runtime/completion.py
+++ b/src/agent_runtime/completion.py
@@@ -1,336 -1,0 +1,351 @@@
+"""One presentation gate between agent execution and externally visible prose.
+
+Tool, progress and interaction events stay live. Answer deltas are held until
+the generator unwinds so a later replacement cannot conceal an earlier false
+claim. This consumes no provider calls. Cancellation closes the inner generator
+under the same journal/turn authority; it never emits a successful terminal event.
+"""
+from __future__ import annotations
+
+from contextlib import aclosing
+from dataclasses import replace
+from functools import wraps
+from inspect import signature
+import json
+import re
+from time import perf_counter
+
+from src.agent_evidence import (
+ CompletionDecision, CompletionStatus, EvidenceKind, EvidenceLedger,
+ requirements_from_runtime_context, _execution_obligation, _unquoted_statements,
+ _ARTIFACT_PATH,
+)
+from .journal import ActionJournal, bind_journal, current_journal
+
+
+_TEST_CLAIM = re.compile(
+ r'\b(?:(?:all\s+)?(?:tests?|checks?|verification|suite)\s+(?:have\s+|has\s+|now\s+|are\s+|is\s+)*(?:passed|passing|successful|green)|'
+ r'(?:passed|passing)\s+(?:all\s+)?(?:the\s+)?tests?|\d+\s+passed)\b', re.I)
+_TEST_STATUS_CLAIM = re.compile(
+ r'\b(?:tests?|pytest|unittest|test suite|checks?|verification)\s*[:—-]?\s*'
+ r'(?:all\s+|have\s+|has\s+|now\s+|are\s+|is\s+|ran\s+)*'
+ r'(?:pass(?:ed|ing)?|succeeded|successful(?:ly)?|green)\b|'
+ r'\b(?:zero|no|0)\s+(?:test\s+)?failures\b', re.I)
+_EXECUTION_CLAIM = re.compile(
+ r'\b(?:(?:I|we|I\'ve|we\'ve|and)\s+(?:have\s+)?(?:successfully\s+)?(?:ran|executed|tested|verified|created|updated|modified|wrote|saved|fixed|completed)|'
+ rf'(?:file|artifact|command|script|service|server|{_ARTIFACT_PATH})\s+(?:was\s+|has\s+been\s+|is\s+)?(?:successfully\s+)?(?:created|updated|written|saved|executed|started)|'
+ r'(?:successfully\s+)(?:ran|executed|created|updated|saved|completed))\b', re.I)
+_UNATTESTED_TEST_METRIC = re.compile(
+ r'\b\d+\s+(?:(?:unit|integration)\s+)?tests?\s+pass(?:ed|ing)?\b|'
+ r'\b\d+\s+passed\b|\b\d+(?:\.\d+)?%\s+(?:test\s+)?coverage\b', re.I)
+_UNBOUNDED_SUCCESS = re.compile(
+ r'\b(?:everything|all\s+(?:bugs|issues))\s+(?:is\s+|are\s+|has\s+been\s+)?'
+ r'(?:fixed|resolved|working)\b', re.I)
+_MUTATION_CLAIM = re.compile(
+ r'\b(?:created|updated|modified|wrote|written|saved|fixed)\b', re.I)
+_TEST_IDENTITY = re.compile(r'\b(?:pytest|unittest)\b', re.I)
+_TEST_SUBJECT = re.compile(r'\b(?:tests?|test suite|pytest|unittest|checks?|verification)\b', re.I)
+_CLAIM_PATH = re.compile(_ARTIFACT_PATH)
+_BARE_SUCCESS = re.compile(r'^\s*(?:done|completed|success|all done|all set|fixed)[.!]?\s*$', re.I)
+_NON_REPORT_SCOPE = re.compile(
+ r'^\s*(?:if|unless|suppose|imagine|hypothetically|for\s+(?:example|instance))\b|'
+ r'\b(?:if|when|whenever|unless|until)\b|'
+ r'\b(?:can|could|may|might|should|would|will|must)\b|'
+ r'\b(?:says?|said|states?|stated|example)\b', re.I)
+
+
+def _current_run_claims(statement: str, *, execution_required: bool) -> list[tuple[str, str]]:
+ """Classify asserted execution, separately from the turn's obligation.
+
+ Past actions and current result/status predicates are reports. Conditional,
+ modal, attributed and example clauses are scoped prose. Bare terminal
+ success only carries execution meaning under an execution contract.
+ """
+ if _BARE_SUCCESS.fullmatch(statement):
+ return [('terminal', statement)] if execution_required else []
+ actions = list(_EXECUTION_CLAIM.finditer(statement))
+ leading = re.match(r'^\s*(?:successfully\s+)?(?:created|updated|modified|wrote|saved)\b', statement, re.I)
+ if leading:
+ actions.insert(0, leading)
+ candidates = [('action', match) for match in actions]
+ for kind, pattern in [('metric', _UNATTESTED_TEST_METRIC), ('metric', _UNBOUNDED_SUCCESS),
+ ('test', _TEST_CLAIM), ('test', _TEST_STATUS_CLAIM)]:
+ candidates.extend((kind, match) for match in pattern.finditer(statement))
+ claims = []
+ for kind, match in candidates:
+ # Scope markers after an asserted action do not make that action
+ # hypothetical ("I ran pytest to see if ..."). An immediate conditional
+ # continuation does qualify a result ("Tests passed if ...").
+ if _NON_REPORT_SCOPE.search(statement[:match.start()]) or re.match(
+ r'\s+(?:if|when|whenever|unless|until)\b', statement[match.end():], re.I):
+ continue
+ end = next((action.start() for action in actions if action.start() > match.start()), len(statement))
+ scope = statement[match.start():end]
+ if kind == 'action':
+ if _MUTATION_CLAIM.search(match.group()):
+ kind = 'mutation'
+ elif _TEST_SUBJECT.search(scope):
+ kind = 'test'
+ else:
+ kind = 'execution'
+ claims.append((kind, scope))
+ return claims
+
+
+def completion_answer(text: str, ledger: EvidenceLedger, decision: CompletionDecision) -> tuple[str, str]:
+ """Keep explanatory prose; remove unsupported assertions and attach facts.
+
+ Exit status proves neither test counts nor coverage. A bad assertion is
+ removed at statement boundaries instead of erasing an entire explanation.
+ The execution outcome remains separate from a discarded model assertion.
+ """
+ incomplete = decision.reason if not decision.can_complete and decision.status != CompletionStatus.AWAITING_USER else ''
+ execution_required = _execution_obligation(ledger.requirements)
+ kept = []
+ removed = ''
+ for statement, scoped in _unquoted_statements(text):
+ why = ''
+ for claim, scope in _current_run_claims(scoped, execution_required=execution_required):
+ paths = tuple(match.group().rstrip('.') for match in _CLAIM_PATH.finditer(scope))
+ if claim == 'metric':
+ why = 'test counts, coverage or exhaustive correctness were not established by execution evidence'
+ elif claim == 'test':
+ identities = tuple(match.group().lower() for match in _TEST_IDENTITY.finditer(scope))
+ if decision.status != CompletionStatus.VERIFIED or not ledger._supports_verifier_claim(identities, paths):
+ why = 'no current passing executable verification supports the claim'
+ elif claim == 'mutation':
+ if not ledger._supports_artifact_claim(EvidenceKind.ARTIFACT_MUTATION, paths):
+ why = 'no matching artifact mutation supports the execution claim'
+ elif claim == 'execution':
+ # A generic assertion cannot be tied confidently to a receipt.
+ why = 'no matching operation supports the execution claim'
+ elif claim == 'terminal' and decision.status not in {CompletionStatus.SATISFIED, CompletionStatus.VERIFIED}:
+ why = incomplete or 'no successful execution supports completion'
+ if why:
+ break
+ if why:
+ removed = removed or why
+ else:
+ kept.append(statement)
+ prose = ''.join(kept).strip() if removed else text
+ if incomplete or (removed and execution_required and decision.status in {CompletionStatus.UNVERIFIED, CompletionStatus.AWAITING_USER}):
+ reason = incomplete or removed
+ missing = (' Missing artifacts: ' + ', '.join(decision.missing_artifacts) + '.'
+ if decision.missing_artifacts else '')
+ notice = 'The task is incomplete: ' + reason.rstrip('.') + '.' + missing
+ recorded = [path for path in ledger.requirements.required_artifacts
+ if ledger._supports_artifact_claim(EvidenceKind.ARTIFACT_MUTATION, (path,))]
+ if removed and recorded:
+ notice += ' Recorded artifact mutation: ' + ', '.join(recorded) + '.'
+ return notice + ('\n\n' + prose if prose.strip() else ''), reason
+ if removed and not execution_required and decision.status != CompletionStatus.VERIFIED:
+ notice = 'Unsupported execution claims were omitted: ' + removed.rstrip('.') + '.'
+ return (prose.rstrip() + '\n\n' + notice) if prose.strip() else notice, removed
+ if decision.can_complete and (ledger.requirements.required_artifacts or ledger.requirements.verifier_required or removed):
+ facts = []
+ if ledger.requirements.required_artifacts:
+ facts.append('Output available: ' + ', '.join(ledger.requirements.required_artifacts) + '.')
+ if decision.status == CompletionStatus.VERIFIED:
+ facts.append('The latest executable verification passed.')
+ elif any(e.kind == EvidenceKind.ARTIFACT_VALIDATION and e.authoritative and e.success for e in ledger.events):
+ facts.append('Artifact readback verified. No passing executable test result was recorded.')
+ else:
+ facts.append('No passing executable test result was recorded.')
+ summary = ' '.join(facts)
+ return (prose.rstrip() + '\n\n' + summary) if prose.strip() else summary, removed
+ return prose, removed
+
+
+def _event(data: dict) -> str:
+ return 'data: ' + json.dumps(data) + '\n\n'
+
+
+def with_completion_gate(func):
+ call_signature = signature(func)
+
+ @wraps(func)
+ async def wrapped(*args, **kwargs):
+ started = perf_counter()
+ first_answer_at = None
+ arguments = call_signature.bind(*args, **kwargs)
+ arguments.apply_defaults()
+ bound = arguments.arguments
+ messages = bound.get('messages') or []
+ instruction = next((m.get('content', '') for m in reversed(messages)
+ if m.get('role') == 'user' and isinstance(m.get('content'), str)), '')
+ context = bound.get('client_runtime_context') or {}
+ requirements = requirements_from_runtime_context(context, instruction=instruction)
+ from src.tool_execution import vet_workspace
+ # A completion declaration is not a filesystem permission. Only the
+ # explicit, vetted runtime workspace may be read for artifact versions.
+ trusted_workspace = vet_workspace(bound.get('workspace')) if bound.get('workspace') else ''
+ requirements = replace(requirements, workspace_root=trusted_workspace or '')
+ parent = current_journal()
+ journal = ActionJournal(
+ workspace=requirements.workspace_root, observed_artifacts=requirements.required_artifacts,
+ parent_run_id=bound.get('_parent_run_id') or (parent.run_id if parent is not None else None))
+ answer_events: list[dict] = []
+ metrics_events: list[dict] = []
+ answer = ''
+ has_final = False
+ done = False
+ awaiting = False
+ exhausted = False
+ provider_error: str | None = None
+ with bind_journal(journal):
+ async with aclosing(func(*args, **kwargs)) as stream:
+ async for chunk in stream:
+ if chunk.strip() == 'data: [DONE]':
+ done = True
+ continue
+ try:
+ data = json.loads(chunk[6:]) if chunk.startswith('data: ') else None
+ except (ValueError, TypeError):
+ data = None
+ if not isinstance(data, dict):
+ if chunk.startswith('event: error'):
+ # The inner stream may still emit failed-terminal
+ # diagnostics. Hold the original error until those
+ # and the buffered answer have been released.
+ provider_error = provider_error or chunk
+ continue
+ yield chunk
+ continue
+ kind = data.get('type')
+ if kind == 'completion_decision':
+ existing = data.get('data') or {}
+ awaiting |= existing.get('status') == 'awaiting_user'
+ exhausted |= existing.get('status') == 'exhausted'
+ continue
+ if kind in {'metrics', 'agent_terminal'}:
+ metrics_events.append(data)
+ declared = (data.get('data') or {}).get('completion_requirements')
+ awaiting |= bool((data.get('data') or {}).get('missing_workspace'))
+ if isinstance(declared, dict):
+ requirements = requirements_from_runtime_context({'completion_requirements': declared})
+ requirements = replace(requirements, workspace_root=trusted_workspace or '')
+ # New obligations affect future receipts only. Never
+ # backfill historical versions with present bytes.
+ journal.observed_artifacts = tuple(dict.fromkeys(
+ (*journal.observed_artifacts, *requirements.required_artifacts)))
+ continue
+ if kind == 'ask_user':
+ awaiting = True
+ payload = data.get('data') or {}
+ if isinstance(payload.get('question'), str):
+ current = EvidenceLedger.from_tool_events(journal.evidence_events(), requirements)
+ question, why = completion_answer(payload['question'], current, current.evaluate(awaiting_user=True))
+ if why:
+ data = {**data, 'data': {**payload, 'question': question}}
+ chunk = _event(data)
+ if kind == 'final_response':
+ if first_answer_at is None:
+ first_answer_at = perf_counter()
+ answer = str(data.get('content') or '')
+ has_final = True
+ answer_events.append(data)
+ continue
+ if 'delta' in data or isinstance(data.get('thinking'), str):
+ if first_answer_at is None:
+ first_answer_at = perf_counter()
+ # Boolean thinking=True marks a reasoning-only delta;
+ # a textual thinking companion must not hide an answer
+ # delta. Both shapes remain buffered until the gate.
+ if isinstance(data.get('thinking'), str):
+ answer_events.append({'delta': data['thinking'], 'thinking': True})
+ data = {key: value for key, value in data.items() if key != 'thinking'}
+ if 'delta' not in data:
+ continue
+ if data.get('thinking') is not True and 'delta' in data:
+ if has_final:
+ answer = ''
+ has_final = False
+ answer += str(data.get('delta') or '')
+ answer_events.append(data)
+ continue
+ yield chunk
+ if provider_error and not answer_events and not metrics_events:
+ yield provider_error
+ return
++ presentation_replaced = False
++ if not provider_error and not has_final and requirements.required_artifacts:
++ terminal_texts = next((event.get('data', {}).get('round_texts')
++ for event in reversed(metrics_events)
++ if isinstance(event.get('data', {}).get('round_texts'), list)
++ and all(isinstance(text, str) for text in event['data']['round_texts'])), None)
++ if terminal_texts is not None:
++ terminal_answer = '\n\n'.join(text for text in terminal_texts if text.strip())
++ if terminal_answer != answer:
++ # The loop can retract a rejected round while retaining
++ # its live deltas. Do not resurrect those buffered drafts
++ # after recovery. Terminal prose still passes this gate.
++ presentation_replaced = True
++ answer = terminal_answer
++ answer_events = [event for event in answer_events if event.get('thinking') is True]
+ ledger = EvidenceLedger.from_tool_events(journal.evidence_events(), requirements)
+ decision = ledger.evaluate(exhausted=exhausted, awaiting_user=awaiting)
+ if provider_error:
+ decision = replace(decision, status=CompletionStatus.FAILED,
+ can_complete=False, reason='Model request failed')
+ # Exhaustion limits execution; factual source synthesis can remain
+ # useful and must not be replaced merely because the budget ended.
+ presentation_decision = ledger.evaluate(awaiting_user=awaiting) if exhausted and not provider_error else decision
+ safe_answer, reason = completion_answer(answer, ledger, presentation_decision)
+ # Evaluate each earlier draft as well as the final replacement.
+ # Never replay an unsupported intermediate success claim.
+ draft = ''.join(str(e.get('delta') or e.get('content') or '')
+ + (e['thinking'] if isinstance(e.get('thinking'), str) else '')
+ for e in answer_events)
+ _, unsafe_draft = completion_answer(draft, ledger, presentation_decision)
+ if not answer.strip() and unsafe_draft:
+ reason = reason or unsafe_draft
+ safe_answer, _ = completion_answer(draft, ledger, presentation_decision)
+ if reason and _execution_obligation(requirements) and decision.can_complete and decision.status == CompletionStatus.UNVERIFIED:
+ decision = CompletionDecision(CompletionStatus.UNVERIFIED, False, reason,
+ decision.evidence_ids, decision.missing_artifacts)
+ released_at = perf_counter()
+ if not provider_error:
+ yield _event({'type': 'completion_decision', 'data': decision.to_dict()})
- replaced_answer = bool(reason or unsafe_draft or safe_answer != answer)
++ replaced_answer = bool(presentation_replaced or reason or unsafe_draft or safe_answer != answer)
+ if replaced_answer:
+ reasoning = [event for event in answer_events if event.get('thinking') is True]
+ _, unsafe_reasoning = completion_answer(
+ ''.join(str(event.get('delta') or '') for event in reasoning), ledger,
+ replace(presentation_decision, can_complete=True))
+ if not unsafe_reasoning:
+ for event in reasoning:
+ yield _event(event)
+ yield _event({'type': 'final_response', 'content': safe_answer})
+ else:
+ for event in answer_events:
+ yield _event(event)
+ if provider_error:
+ yield _event({'type': 'completion_decision', 'data': decision.to_dict()})
+ for event in metrics_events:
+ metadata = event.setdefault('data', {})
+ metadata.update(completion_decision=decision.to_dict(), evidence_events=ledger.to_list(),
+ action_receipts=journal.to_list(), completion_requirements=requirements.to_dict(),
+ run_id=journal.run_id, parent_run_id=journal.parent_run_id)
+ metadata['completion_gate'] = {
+ 'buffer_seconds': released_at - first_answer_at if first_answer_at is not None else 0,
+ 'first_visible_answer_seconds': released_at - started,
+ 'additional_provider_calls': 0,
+ 'answer_replaced': replaced_answer,
+ }
+ if replaced_answer:
+ if not provider_error:
+ metadata['round_texts'] = [safe_answer]
+ metadata['completion_gate_reason'] = reason or unsafe_draft or 'receipt_summary'
+ if isinstance(metadata.get('thinking'), str):
+ _, unsafe_thinking = completion_answer(metadata['thinking'], ledger,
+ replace(presentation_decision, can_complete=True))
+ if unsafe_thinking:
+ metadata.pop('thinking')
+ yield _event(event)
+ if provider_error:
+ yield provider_error
+ return
+ if done:
+ yield 'data: [DONE]\n\n'
+
+ return wrapped
diff --cc src/agent_runtime/identity.py
index 49381cde5,000000000..e7482c54d
mode 100644,000000..100644
--- a/src/agent_runtime/identity.py
+++ b/src/agent_runtime/identity.py
@@@ -1,146 -1,0 +1,167 @@@
+"""Canonical evidence identities; these helpers never grant filesystem access."""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from pathlib import Path, PurePosixPath
+import re
+import shlex
+import stat
+from .path_policy import _is_sensitive_path
+
+
++TUI_PYTHON_RUNNER_SETUP = (
++ "runner=''; "
++ "if [ -x .venv/bin/python ]; then runner=.venv/bin/python; "
++ "elif [ -x venv/bin/python ]; then runner=venv/bin/python; "
++ "elif git_common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) "
++ "&& [ -x \"$(dirname \"$git_common\")/.venv/bin/python\" ]; then "
++ "runner=\"$(dirname \"$git_common\")/.venv/bin/python\"; "
++ "else runner=python; fi; "
++)
++
++
+def digest(value: object) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
+ separators=(",", ":"), default=str).encode()).hexdigest()
+
+
+def artifact_version(value: str, workspace: str) -> str:
+ """Content version for a confined declared output; missing/unreadable is explicit."""
+ identity = artifact_identity(value, workspace)
+ if not workspace or not identity.startswith('workspace:'):
+ return 'unobserved'
+ root = Path(workspace).resolve()
+ candidate = (root / identity.removeprefix('workspace:')).resolve()
+ if not candidate.is_relative_to(root) or _is_sensitive_path(str(candidate)):
+ return 'unobserved'
+ if not hasattr(os, 'O_NOFOLLOW') or not os.supports_dir_fd:
+ return 'unobserved'
+ directory = None
+ try:
+ directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ parts = candidate.relative_to(root).parts
+ if not parts:
+ return 'unobserved'
+ for part in parts[:-1]:
+ child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
+ os.close(directory)
+ directory = child
+ descriptor = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
+ with os.fdopen(descriptor, 'rb') as stream:
+ info = os.fstat(stream.fileno())
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 64 * 1024 * 1024:
+ return 'unobserved'
+ result = hashlib.sha256()
+ remaining = 64 * 1024 * 1024
+ while block := stream.read(min(1024 * 1024, remaining + 1)):
+ remaining -= len(block)
+ if remaining < 0:
+ return 'unobserved'
+ result.update(block)
+ return result.hexdigest()
+ except (OSError, ValueError):
+ return 'missing-or-unreadable'
+ finally:
+ if directory is not None:
+ os.close(directory)
+
+
+def artifact_identity(value: str, workspace: str = "") -> str:
+ """Unify relative, virtual and host aliases without basename matching.
+
+ Resolving symlinks is evidence bookkeeping, never a confinement check. Paths
+ outside the workspace retain their absolute identity and cannot satisfy a
+ workspace obligation with the same basename.
+ """
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ path = PurePosixPath(text)
+ root = Path(workspace or "/workspace").resolve()
+ if path.parts[:2] == ('/', 'workspace'):
+ path = PurePosixPath(*path.parts[2:])
+ candidate = Path(str(path))
+ if not candidate.is_absolute():
+ candidate = root / candidate
+ try:
+ resolved = candidate.resolve()
+ relative = resolved.relative_to(root)
+ return "workspace:" + relative.as_posix()
+ except ValueError:
+ return "absolute:" + str(candidate.resolve())
+ except (OSError, RuntimeError):
+ return "unresolved:" + text
+
+
+def executable_words(command: str) -> tuple[str, ...]:
- """Recognize one foreground command, optionally after safe cd/set prefixes.
++ """Recognize one foreground command after exact interpreter or cd/set prefixes.
+
+ This is deliberately conservative evidence parsing, not shell authorization.
- Pipelines, control flow, substitutions and status-masking tails are not proof
++ Other control flow, substitutions, pipelines and status-masking tails are not proof
+ that a verifier returned the recorded shell status.
+ """
+ text = str(command or '').strip()
++ if text.startswith(TUI_PYTHON_RUNNER_SETUP):
++ remainder = text[len(TUI_PYTHON_RUNNER_SETUP):]
++ # This exact server-owned prelude only selects the interpreter. The
++ # trailing command must still be a single foreground invocation whose
++ # status is returned unchanged; the generic discovery fallback is not.
++ if remainder.startswith('"$runner" '):
++ arguments = remainder[len('"$runner" '):]
++ if '$' in arguments:
++ return ()
++ text = 'python ' + arguments
+ if any(marker in text for marker in ('`', '$(', '${', '\n', '\r')):
+ return ()
+ try:
+ lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
+ lexer.whitespace_split = True
+ words = list(lexer)
+ except ValueError:
+ return ()
+ while '&&' in words:
+ index = words.index('&&')
+ prefix = words[:index]
+ if not ((len(prefix) == 2 and prefix[0] == 'cd') or prefix == ['set', '-e']):
+ return ()
+ words = words[index + 1:]
+ if any(word and all(c in ';&|<>()' for c in word) for word in words):
+ return ()
+ while words and re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=[^\n]*', words[0]):
+ words.pop(0)
+ return tuple(words)
+
+
+def is_test_command(command: str) -> bool:
+ words = executable_words(command)
+ if not words:
+ return False
+ if any(word in {'--help', '-h', '--version', '--collect-only', '--co'} for word in words[1:]):
+ return False
+ binary = Path(words[0]).name
+ if binary in {'pytest', 'py.test'}:
+ return True
+ if re.fullmatch(r'python(?:\d+(?:\.\d+)?)?', binary):
+ args = list(words[1:])
+ while args and args[0] in {'-I', '-S', '-s', '-E', '-B', '-u'}:
+ args.pop(0)
+ return len(args) >= 2 and args[:2] in (['-m', 'pytest'], ['-m', 'unittest'])
+ if binary in {'npm', 'pnpm', 'yarn', 'make', 'cargo', 'go'}:
+ args = words[1:]
+ return bool(args and (args[0] == 'test' or binary == 'npm' and args[:2] == ('run', 'test')))
+ return bool(re.match(r'^/(?:tests?|verifier)/[^/]+', words[0]))
+
+
+def is_validation_command(command: str) -> bool:
+ words = executable_words(command)
+ if not words:
+ return False
+ binary = Path(words[0]).name
+ return (is_test_command(command)
+ or binary in {'cat', 'head', 'tail', 'stat', 'wc', 'jq', 'cmp', 'diff',
+ 'coqc', 'gcc', 'g++', 'clang', 'clang++', 'javac', 'rustc'}
+ or binary == 'test' and len(words) > 1 and words[1] in {'-e', '-f', '-s', '-d'}
+ or binary in {'cargo', 'go', 'npm', 'pnpm', 'yarn'} and words[1:2] in {('build',), ('check',)}
+ or binary == 'npm' and words[1:3] == ('run', 'build'))
diff --cc src/tool_execution.py
index 451d5c7a8,329b8d16f..e72594cba
--- a/src/tool_execution.py
+++ b/src/tool_execution.py
@@@ -1645,10 -1679,14 +1649,14 @@@ async def _execute_tool_block_impl
# Route MCP-extracted tools through the MCP manager. Forward
# the progress callback so long-running subprocess tools
# (bash, python) can stream `tool_progress` events to the UI.
- if tool in _MCP_TOOL_MAP:
+ if tool == "generate_image":
+ from src.ai_interaction import do_generate_image
+ desc = "generate_image"
- result = await do_generate_image(content, session_id=session_id, owner=owner)
++ result = await dispatched(do_generate_image(content, session_id=session_id, owner=owner))
+ elif tool in _MCP_TOOL_MAP:
first_line = content.split(chr(10))[0][:80]
desc = f"{tool}: {first_line}"
- result = await _call_mcp_tool(tool, content, progress_cb=progress_cb)
+ result = await dispatched(_call_mcp_tool(tool, content, progress_cb=progress_cb))
elif tool in ("grep", "glob", "ls", "get_workspace", "host_shell"):
# Code-navigation tools — no MCP server; run the direct implementation.
first_line = content.split(chr(10))[0][:80]
@@@ -1884,7 -1922,9 +1892,9 @@@
session_id=session_id,
owner=owner,
client_runtime_context=client_runtime_context,
+ disabled_tools=disabled_tools,
+ tool_policy=tool_policy,
- )
+ ))
if isinstance(res, tuple):
desc, result = res
diff --cc tests/test_agent_bash_tmux_env.py
index 432a78a6e,432a78a6e..cd90445ff
--- a/tests/test_agent_bash_tmux_env.py
+++ b/tests/test_agent_bash_tmux_env.py
@@@ -1,4 -1,4 +1,5 @@@
import asyncio
++from types import SimpleNamespace
def test_new_tmux_session_forwards_runtime_python_environment(monkeypatch):
@@@ -188,7 -188,7 +189,7 @@@ def test_direct_bash_subprocess_has_clo
from src import tool_execution
captured = {}
-- sentinel = object()
++ sentinel = SimpleNamespace(pid=12345)
async def fake_create(command, **kwargs):
captured.update(kwargs)
@@@ -258,7 -258,7 +259,7 @@@ def test_bash_allows_unicode_ffmpeg_dra
from src import tool_execution
captured = {}
-- sentinel = object()
++ sentinel = SimpleNamespace(pid=12345)
async def fake_create(command, **kwargs):
captured["command"] = command
diff --cc tests/test_agent_bash_windows.py
index 888c906b3,888c906b3..0145b4b28
--- a/tests/test_agent_bash_windows.py
+++ b/tests/test_agent_bash_windows.py
@@@ -1,6 -1,6 +1,7 @@@
"""Windows execution contract for the agent Bash tool."""
import pytest
++from types import SimpleNamespace
from src.agent_tools import subprocess_tools
@@@ -85,7 -85,7 +86,7 @@@ async def test_windows_bash_does_not_us
async def fake_create(command, **kwargs):
captured["command"] = command
captured["kwargs"] = kwargs
-- return object()
++ return SimpleNamespace(pid=12345)
async def fake_stream(_process, **_kwargs):
return "ok", "", 0, False
diff --cc tests/test_agent_rounds_exhausted.py
index c3c111fc9,c3c111fc9..4b2f29dbe
--- a/tests/test_agent_rounds_exhausted.py
+++ b/tests/test_agent_rounds_exhausted.py
@@@ -9,11 -9,11 +9,13 @@@ return, or moves the done-break, could
import asyncio
import json
from pathlib import Path
++import pytest
import src.agent_loop as al
from src.tool_capabilities import ToolGateDecision
from src.tool_capabilities import capabilities_for_action
from src.tool_approvals import tool_approval_store
++from tests.runtime_evidence_helpers import authoritative_executor
def _collect(gen):
@@@ -39,6 -39,6 +41,16 @@@ def _patch_common(monkeypatch)
monkeypatch.setattr(al, "get_setting", lambda key, default=None: default, raising=False)
monkeypatch.setattr(al, "get_mcp_manager", lambda: None, raising=False)
monkeypatch.setattr(al, "estimate_tokens", lambda *a, **k: 10, raising=False)
++ # The round providers are synthetic. Keep real compaction logic while
++ # supplying its context window instead of probing the dummy endpoint.
++ import src.context_compactor as context_compactor
++ monkeypatch.setattr(context_compactor, "get_context_length", lambda *a, **k: 128_000)
++ # These fixtures supply the round provider below. Any direct grace-synthesis
++ # request has no configured response, rather than contacting the fake URL.
++ async def _unconfigured_direct_provider(*args, **kwargs):
++ raise RuntimeError("No direct-provider completion configured in this fixture")
++ yield # Keep the direct-provider async-generator interface.
++ monkeypatch.setattr(al, "stream_llm", _unconfigured_direct_provider)
# These tests exercise round convergence. Keep the prompt-integrity gate
# out of the fixture so a synthetic tool result does not turn the next
# round into an approval test instead.
@@@ -997,6 -997,6 +1009,7 @@@ def test_empty_workspace_round_gets_one
yield 'data: {"delta":"Workspace checked."}\n\n'
yield "data: [DONE]\n\n"
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
return (block.tool_type, {"output": "/workspace", "exit_code": 0})
@@@ -1011,7 -1011,7 +1024,15 @@@
)))
assert len(seen) == 3
-- assert any(e.get("delta") == "Workspace checked." for e in events)
++ decision = next(e["data"] for e in events if e.get("type") == "completion_decision")
++ assert not decision["can_complete"]
++ assert "fixture.py" in decision["missing_artifacts"]
++ assert any(
++ e.get("type") == "final_response"
++ and "Workspace checked." in e.get("content", "")
++ and "incomplete" in e.get("content", "")
++ for e in events
++ )
def test_empty_workspace_nudge_names_only_tools_in_active_schema(monkeypatch):
@@@ -1205,7 -1205,7 +1226,8 @@@ def test_eval_workspace_prompt_uses_hos
assert any("active workspace is /home/tester/project" in e.get("delta", "") for e in events)
--def test_tui_coding_turn_recovers_inspects_patches_and_verifies(monkeypatch):
[email protected]('explicit_verifier', [False, True])
++def test_tui_coding_turn_recovers_inspects_patches_and_verifies(monkeypatch, explicit_verifier):
"""A stale compact router must still complete a real coding workflow."""
_patch_common(monkeypatch)
calls = []
@@@ -1227,6 -1227,6 +1249,7 @@@
},
}
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
executed.append((block.tool_type, block.content))
if block.tool_type == "host_shell":
@@@ -1300,7 -1300,7 +1323,8 @@@
"deepseek-v4-flash",
[{
"role": "user",
-- "content": "Fix the parser in this local TUI project and run the tests.",
++ "content": "Fix the parser in this local TUI project and run "
++ + ("python -m pytest -q." if explicit_verifier else "the tests."),
}],
max_rounds=6,
relevant_tools={"get_workspace", "ls", "host_shell", "apply_patch", "edit_file", "todowrite"},
@@@ -1316,14 -1316,14 +1340,20 @@@
assert not any(tool in {"get_workspace", "ls"} for tool, _ in executed)
# Invalid backend/container tool names are replaced with the authoritative
# host-shell recovery in the same round, so no extra clarification round
-- # should be required before the patch and verification turns.
-- assert len(calls) == 3
++ # should be required before the patch and verification turns. An opaque
++ # conditional fallback still needs synthesis and cannot attest tests.
++ assert len(calls) == (3 if explicit_verifier else 4)
++ decision = next(event['data'] for event in events if event.get('type') == 'completion_decision')
++ assert decision['can_complete'] is explicit_verifier
++ assert (decision['status'] == 'verified') is explicit_verifier
assert any(
event.get("type") == "final_response"
and "Verification:" in event.get("content", "")
and "passed" in event.get("content", "")
for event in events
-- )
++ ) is explicit_verifier
++ terminal = next(event['data'] for event in events if event.get('type') == 'metrics')
++ assert terminal['completion_gate']['additional_provider_calls'] == 0
assert not any(event.get("type") in {"rounds_exhausted", "loop_breaker_triggered"} for event in events)
@@@ -1339,6 -1339,6 +1369,7 @@@ def test_qwen_tui_coding_summary_report
"runtime_execution_contract": {"local_workspace_tasks": "use_host_shell_bridge"},
}
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
nonlocal test_attempts
executed.append(block.tool_type)
@@@ -1390,7 -1390,7 +1421,8 @@@
assert "`pytest -q` passed" in summary
--def test_tui_coding_turn_replaces_duplicate_edit_with_requested_tests(monkeypatch):
[email protected]('explicit_verifier', [False, True])
++def test_tui_coding_turn_replaces_duplicate_edit_with_requested_tests(monkeypatch, explicit_verifier):
"""A successful edit followed by another edit must converge on real tests."""
_patch_common(monkeypatch)
executed = []
@@@ -1407,6 -1407,6 +1439,7 @@@
},
}
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
executed.append((block.tool_type, block.content))
if block.tool_type == "read_file":
@@@ -1450,7 -1450,7 +1483,8 @@@
"role": "user",
"content": (
"A regression was introduced in nested backend error handling. "
-- "Find the cause, fix it with a scoped change, and run the relevant tests."
++ "Find the cause, fix it with a scoped change, and run "
++ + ("pytest -q." if explicit_verifier else "the relevant tests.")
),
}],
max_rounds=6,
@@@ -1465,12 -1465,12 +1499,15 @@@
]
verification_command = json.loads(executed[-1][1])["command"]
assert "pytest" in verification_command
++ decision = next(event['data'] for event in events if event.get('type') == 'completion_decision')
++ assert decision['can_complete'] is explicit_verifier
++ assert (decision['status'] == 'verified') is explicit_verifier
assert any(
"Verification:" in event.get("content", "")
and "passed" in event.get("content", "")
for event in events
if event.get("type") == "final_response"
-- )
++ ) is explicit_verifier
def test_failed_forced_verifier_allows_an_adapted_test_command(monkeypatch):
@@@ -1491,6 -1491,6 +1528,7 @@@
},
}
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
nonlocal host_attempts
executed.append((block.tool_type, block.content))
@@@ -3363,6 -3363,6 +3401,7 @@@ def test_final_prose_with_missing_artif
requests = []
executed = []
++ @authoritative_executor
async def _fake_exec(block, *args, **kwargs):
executed.append(block)
if block.tool_type == "write_file":
diff --cc tests/test_completion_boundary.py
index 473c66d28,000000000..244ccb67f
mode 100644,000000..100644
--- a/tests/test_completion_boundary.py
+++ b/tests/test_completion_boundary.py
@@@ -1,358 -1,0 +1,419 @@@
+"""Provider failure is the final frame, after gated output and diagnostics."""
+import asyncio
+from inspect import signature
+import json
+
+import pytest
+
+from src.agent_runtime.completion import with_completion_gate
+from src.agent_runtime.completion import completion_answer
+from src.agent_evidence import CompletionRequirements, EvidenceLedger, infer_completion_requirements
+from src.agent_runtime.journal import current_journal
+from src.tool_types import ToolBlock
+from tests.runtime_evidence_helpers import authoritative_executor
+
+
+ERROR = 'event: error\ndata: {"status": 504, "error": {"message": "stream timeout"}, "fallback_eligible": false}\n\n'
+DONE = 'data: [DONE]\n\n'
+
+
[email protected]('terminal_texts', [[], ['', ''], ['Recovered answer with literal [DONE] text.']])
++async def test_terminal_round_retraction_does_not_resurrect_buffered_drafts(terminal_texts):
++ @with_completion_gate
++ async def stream(messages):
++ yield _event({'delta': 'Considering the next step.', 'thinking': True})
++ yield _event({'delta': 'Now I need to execute the rejected draft.'})
++ yield _event({'type': 'metrics', 'data': {'round_texts': terminal_texts}})
++ yield DONE
++
++ chunks = [chunk async for chunk in stream([{'role': 'user', 'content': 'Create answer.txt.'}])]
++ assert 'rejected draft' not in ''.join(chunks)
++ assert any('Considering the next step.' in chunk for chunk in chunks)
++ if terminal_texts and terminal_texts[0]:
++ assert any(terminal_texts[0] in chunk for chunk in chunks)
++ assert chunks.count(DONE) == 1
++
++
++async def test_terminal_round_text_cannot_override_an_explicit_final_response():
++ @with_completion_gate
++ async def stream(messages):
++ yield _event({'type': 'final_response', 'content': 'The explicit final answer.'})
++ yield _event({'type': 'metrics', 'data': {'round_texts': ['Earlier draft.']}})
++ yield DONE
++
++ chunks = [chunk async for chunk in stream([])]
++ final = next(data for _, data in _frames(chunks) if isinstance(data, dict) and data.get('type') == 'final_response')
++ assert final['content'] == 'The explicit final answer.'
++
++
++async def test_revised_terminal_prose_still_cannot_attest_execution():
++ @with_completion_gate
++ async def stream(messages):
++ yield _event({'delta': 'Earlier draft.'})
++ yield _event({'type': 'metrics', 'data': {'round_texts': ['All tests passed.']}})
++ yield DONE
++
++ chunks = [chunk async for chunk in stream([{'role': 'user', 'content': 'Create answer.txt and run the tests.'}])]
++ assert not _decision(chunks)['can_complete']
++ assert 'All tests passed.' not in ''.join(chunks)
++
++
++async def test_provider_error_preserves_partial_content_despite_empty_terminal_rounds():
++ @with_completion_gate
++ async def stream(messages):
++ yield _event({'type': 'tool_start', 'tool': 'read_file'})
++ yield _event({'delta': 'Safe partial result.'})
++ yield _event({'type': 'metrics', 'data': {'round_texts': []}})
++ yield ERROR
++ yield DONE
++
++ chunks = [chunk async for chunk in stream([])]
++ assert _labels(chunks) == ['tool_start', 'final_response', 'completion_decision', 'metrics', 'error']
++ assert any('Safe partial result.' in chunk for chunk in chunks)
++ assert chunks[-1] == ERROR
++ assert DONE not in chunks
++
++
+def _event(payload):
+ return 'data: ' + json.dumps(payload) + '\n\n'
+
+
+def _frames(chunks):
+ """Decode network chunks without losing named error frames or [DONE]."""
+ pending = ''
+ for chunk in chunks:
+ pending += chunk
+ while '\n\n' in pending:
+ frame, pending = pending.split('\n\n', 1)
+ lines = frame.splitlines()
+ event = next((line[7:] for line in lines if line.startswith('event: ')), 'message')
+ payload = '\n'.join(line[6:] for line in lines if line.startswith('data: '))
+ yield event, payload if payload == '[DONE]' else json.loads(payload)
+ assert not pending, 'incomplete SSE frame'
+
+
+def _labels(chunks):
+ return [event if event != 'message' else (
+ 'done' if data == '[DONE]' else data.get('type', 'delta')
+ ) for event, data in _frames(chunks)]
+
+
+def _decision(chunks):
+ return next(data['data'] for event, data in _frames(chunks)
+ if event == 'message' and isinstance(data, dict)
+ and data.get('type') == 'completion_decision')
+
+
+@authoritative_executor
+async def _successful_tool(block):
+ return block.tool_type, {'exit_code': 0, 'output': 'OK'}
+
+
+async def test_bare_error_preserves_original_frame_without_success_output():
+ @with_completion_gate
+ async def stream(messages):
+ yield ERROR
+ yield DONE
+
+ assert [chunk async for chunk in stream([])] == [ERROR]
+
+
[email protected]('partial', ['', 'The parser checks the header first.'])
+async def test_provider_error_releases_partial_then_decision_terminal_and_original_error(partial):
+ closed = []
+
+ @with_completion_gate
+ async def stream(messages):
+ try:
+ yield _event({'type': 'tool_start', 'tool': 'read_file'})
+ if partial:
+ yield _event({'delta': partial})
+ yield ERROR
+ yield _event({'type': 'agent_terminal', 'data': {
+ 'failed': True, 'failure': {'status': 504},
+ 'round_texts': ['Earlier diagnostic', partial + '\n[Agent stopped]'],
+ }})
+ yield DONE
+ finally:
+ closed.append(current_journal() is not None)
+
+ chunks = [chunk async for chunk in stream([])]
+ assert _labels(chunks) == [
+ 'tool_start', 'final_response', 'completion_decision', 'agent_terminal', 'error',
+ ], _labels(chunks)
+ assert chunks[-1] == ERROR
+ assert DONE not in chunks
+ assert _decision(chunks)['can_complete'] is False
+ assert _decision(chunks)['status'] == 'failed'
+ final = next(data for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'final_response')
+ assert final['content'].startswith('The task is incomplete:')
+ assert partial in final['content']
+ assert closed == [True]
+ assert current_journal() is None
+
+
[email protected]('successful_tool', [False, True])
[email protected]('earlier_status', [None, 'awaiting_user', 'exhausted'])
+async def test_provider_failure_overrides_even_successful_execution(successful_tool, earlier_status):
+ @with_completion_gate
+ async def stream(messages):
+ if successful_tool:
+ await _successful_tool(ToolBlock('bash', 'python -m unittest'))
+ if earlier_status:
+ yield _event({'type': 'completion_decision', 'data': {'status': earlier_status}})
+ yield _event({'delta': 'The response is partial.'})
+ yield ERROR
+ yield _event({'type': 'metrics', 'data': {}})
+
+ chunks = [chunk async for chunk in stream([])]
+ decision = _decision(chunks)
+ assert decision['can_complete'] is False, decision
+ assert decision['status'] == 'failed'
+ if successful_tool:
+ metrics = next(data['data'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'metrics')
+ assert any(e['authoritative'] and e['success'] for e in metrics['evidence_events'])
+ assert chunks[-1] == ERROR
+
+
+async def test_error_after_final_response_does_not_add_calls_or_success_done():
+ invocations = []
+
+ @with_completion_gate
+ async def stream(messages, workspace=None, client_runtime_context=None):
+ invocations.append(1)
+ yield _event({'type': 'final_response', 'content': 'The header contains three fields.'})
+ yield DONE
+ yield ERROR
+
+ chunks = [chunk async for chunk in stream([])]
+ assert _labels(chunks) == ['final_response', 'completion_decision', 'error']
+ assert invocations == [1]
+ assert str(signature(stream)) == '(messages, workspace=None, client_runtime_context=None)'
+ assert DONE not in chunks
+
+
[email protected]('terminal_kind', ['agent_terminal', 'metrics'])
+async def test_failed_terminal_diagnostics_survive_answer_replacement(terminal_kind):
+ diagnostics = ['Earlier tool failure and retry', 'All tests passed.\n[Agent stopped: HTTP 504]']
+
+ @with_completion_gate
+ async def stream(messages):
+ yield _event({'delta': 'All tests passed.'})
+ yield ERROR
+ yield _event({'type': terminal_kind, 'data': {
+ 'failed': True, 'failure': {'status': 504, 'message': 'Model request failed'},
+ 'round_texts': diagnostics, 'round_models': ['first-model', 'failed-model'],
+ }})
+
+ chunks = [chunk async for chunk in stream([])]
+ terminal = next(data['data'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == terminal_kind)
+ assert terminal['round_texts'] == diagnostics
+ assert terminal['round_models'] == ['first-model', 'failed-model']
+ assert terminal['failure'] == {'status': 504, 'message': 'Model request failed'}
+ assert terminal['failed'] is True
+ assert terminal['completion_decision'] == _decision(chunks)
+ assert terminal['completion_gate']['answer_replaced'] is True
+ assert terminal['completion_gate']['additional_provider_calls'] == 0
+ assert _labels(chunks).index(terminal_kind) < _labels(chunks).index('error')
+
+
+async def test_error_boundary_is_independent_of_network_chunking():
+ @with_completion_gate
+ async def stream(messages):
+ yield _event({'delta': 'Partial explanation.'})
+ yield ERROR
+ yield _event({'type': 'agent_terminal', 'data': {'failed': True}})
+
+ chunks = [chunk async for chunk in stream([])]
+ wire = ''.join(chunks)
+ expected = list(_frames(chunks))
+ for delivered in [chunks, [wire], list(wire)]:
+ # A client stops consuming on the first error, regardless of chunking.
+ visible = []
+ for frame in _frames(delivered):
+ visible.append(frame)
+ if frame[0] == 'error':
+ break
+ assert visible == expected
+ assert visible[-2][1]['type'] == 'agent_terminal'
+
+
[email protected]('after_error', [False, True])
+async def test_cancellation_closes_inner_stream_without_releasing_completion(after_error):
+ progress_seen = asyncio.Event()
+ closed = []
+ chunks = []
+
+ @with_completion_gate
+ async def stream(messages):
+ try:
+ yield _event({'delta': 'Tests passed.'})
+ if after_error:
+ yield ERROR
+ yield _event({'type': 'tool_start', 'tool': 'bash'})
+ await asyncio.Event().wait()
+ finally:
+ closed.append(current_journal() is not None)
+
+ async def collect():
+ async for chunk in stream([]):
+ chunks.append(chunk)
+ if chunk == _event({'type': 'tool_start', 'tool': 'bash'}):
+ progress_seen.set()
+
+ task = asyncio.create_task(collect())
+ try:
+ await asyncio.wait_for(progress_seen.wait(), timeout=5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ assert _labels(chunks) == ['tool_start']
+ assert closed == [True]
+ assert current_journal() is None
+
+
[email protected]('prose', [
+ 'Tests pass when the command exits zero.',
+ 'If all tests are passing, merge the branch.',
+ 'Tests passed if the command exited zero.',
+ 'The documentation says "5 passed".',
+ 'The documentation says "Tests: FAIL" or "Tests: PASS".',
+ 'You can run pytest to verify this.',
+ 'A successful test run should show no failures.',
+ 'For example, I created the file and updated config.py.',
+ 'If I updated config.py, I would run pytest.',
+ 'Imagine I ran the tests and all 42 passed.',
+ 'Done is the label for a finished item.',
+ '```text\nI ran pytest and all 42 passed.\n```',
+ 'Run pytest until there are no failures.',
+])
+def test_slice2_explanatory_prose_is_not_a_current_run_claim(prose):
+ ledger = EvidenceLedger()
+ answer, reason = completion_answer(prose, ledger, ledger.evaluate())
+ assert answer == prose
+ assert not reason
+
+
[email protected]('instruction', [
+ 'Explain how to write code and then test it.',
+ 'Summarise this and check for typos.',
+ 'Explain how to update config.py and then verify it.',
+ 'Show an example of creating answer.json and checking it.',
+ 'The documentation says "run pytest and create answer.json".',
+ 'If you run pytest, the tests should pass.',
+])
+def test_slice2_explanatory_request_has_no_execution_requirements(instruction):
+ requirements = infer_completion_requirements(instruction)
+ assert requirements.required_artifacts == ()
+ assert not requirements.verifier_required
+ assert not requirements.executable_verifier_available
+
+
[email protected]('instruction', [
+ 'Run the tests.', 'Please run pytest.', 'Can you run the test suite?',
+])
+def test_slice2_explicit_test_execution_requires_a_verifier(instruction):
+ requirements = infer_completion_requirements(instruction)
+ assert requirements.verifier_required
+ assert not EvidenceLedger(requirements).evaluate().can_complete
+
+
[email protected]('claim', [
+ 'I ran the tests.', 'The tests passed.', '42 tests passed.',
+ 'I created the file.', 'I updated config.py successfully.',
+])
+def test_slice2_execution_obligation_rejects_unsupported_claims(claim):
+ ledger = EvidenceLedger(CompletionRequirements(required_artifacts=('config.py',)))
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert reason
+ assert answer.startswith('The task is incomplete:')
+ assert claim not in answer
+
+
[email protected]('claim', [
+ 'I ran pytest to see if the tests passed.',
+ 'I updated config.py as an example.',
+ 'I ran pytest and should update config.py next.',
+ 'config.py was updated successfully.',
+])
+def test_slice2_subordinate_explanation_cannot_hide_a_direct_execution_report(claim):
+ ledger = EvidenceLedger()
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert reason
+ assert claim not in answer
+ assert 'The task is incomplete' not in answer
+
+
+async def test_slice2_client_dictionary_cannot_attest_execution():
+ @with_completion_gate
+ async def stream(messages, client_runtime_context=None):
+ yield _event({'delta': 'I ran pytest and all tests passed.'})
+ yield DONE
+
+ context = {'execution_obligation': True, 'execution_verified': True,
+ 'evidence_events': [{'tool': 'bash', 'command': 'pytest', 'exit_code': 0}]}
+ chunks = [chunk async for chunk in stream(
+ [{'role': 'user', 'content': 'Explain test output.'}], client_runtime_context=context)]
+ final = next(data['content'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'final_response')
+ assert 'I ran pytest' not in final
+ assert 'The task is incomplete' not in final
+ assert _decision(chunks)['can_complete'] is True
+
+
+async def test_slice2_conversational_fabrication_is_corrected_without_execution_incomplete():
+ invocations = []
+
+ @with_completion_gate
+ async def stream(messages):
+ invocations.append(1)
+ yield _event({'delta': 'The function returns a boolean. I ran pytest and all tests passed.'})
+ yield _event({'type': 'metrics', 'data': {}})
+ yield DONE
+
+ chunks = [chunk async for chunk in stream([{'role': 'user', 'content': 'Explain the function.'}])]
+ final = next(data['content'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'final_response')
+ assert 'The function returns a boolean.' in final
+ assert 'I ran pytest' not in final
+ assert 'The task is incomplete' not in final
+ assert _decision(chunks)['can_complete'] is True
+ assert invocations == [1]
+ metrics = next(data['data'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'metrics')
+ assert metrics['completion_gate']['additional_provider_calls'] == 0
+
+
+async def test_slice2_quoted_example_does_not_hide_an_unsupported_report():
+ @with_completion_gate
+ async def stream(messages):
+ yield _event({'delta': 'The docs say "5 passed". I ran pytest.'})
+ yield DONE
+
+ chunks = [chunk async for chunk in stream([{'role': 'user', 'content': 'Explain pytest output.'}])]
+ final = next(data['content'] for event, data in _frames(chunks)
+ if event == 'message' and data.get('type') == 'final_response')
+ assert 'The docs say "5 passed".' in final
+ assert 'I ran pytest' not in final
+ assert 'The task is incomplete' not in final
diff --cc tests/test_image_creation_routing.py
index 000000000,6cdfcb2f8..9a2189775
mode 000000,100644..100644
--- a/tests/test_image_creation_routing.py
+++ b/tests/test_image_creation_routing.py
@@@ -1,0 -1,188 +1,202 @@@
+ import pytest
+ from src.turn_contract import requested_capabilities, selected_tools_for_request, resolve_turn_contract, resolve_full_inventory_contract
+ from src.tool_schemas import FUNCTION_TOOL_SCHEMAS
+ from src.tool_policy import ToolPolicy
+ from src.clean_agent_preview import PREVIEW_TOOLS, scope_preview_contract, preview_call_allowed
+
+
+ def test_compact_image_tool_uses_configured_model():
+ from src.clean_agent_preview import compact_schemas
+ original = next(s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] == 'generate_image')
+ compact = compact_schemas([original], model='Ajax')[0]['function']['parameters']
+ assert 'model' not in compact['properties']
+ assert 'model' in original['function']['parameters']['properties']
+
+
+ def test_image_revision_uses_edit_contract_not_fresh_generation():
+ history = [{'role': 'assistant', 'metadata': {'tool_events': [
+ {'tool': 'generate_image', 'exit_code': 0, 'image_id': 'source-image'}
+ ]}}]
+ for prompt in ['Add another cow', 'Make it brighter', 'Remove the fence', 'Change the sky to blue']:
+ capabilities = requested_capabilities(prompt, history)
+ assert capabilities == {'image_editing'}
+ contract = resolve_turn_contract(capabilities=capabilities, schemas=FUNCTION_TOOL_SCHEMAS, policy=ToolPolicy(), message=prompt)
+ assert 'edit_image' in contract.required
+ assert 'generate_image' not in contract.offered
+ assert preview_call_allowed('edit_image', {'image_id': 'source-image', 'action': 'prompt', 'prompt': prompt}, prompt,
+ contract_required_tools=contract.required, turn_authorized_families=capabilities)
+ assert requested_capabilities('Make a new image of a cat', history) == {'image_generation'}
+ assert 'image_editing' not in requested_capabilities('Create a task to add another cow', history)
+ assert 'image_editing' not in requested_capabilities('Add another cow', history + [{'role': 'assistant', 'content': 'Unrelated answer'}])
+
+
+ def test_uploaded_image_edit_is_not_ocr_or_description():
+ assert requested_capabilities('Make more realistic', image_attachment=True) == {'image_editing'}
+ assert 'image_editing' not in requested_capabilities('Describe this image', image_attachment=True)
+ assert 'image_editing' not in requested_capabilities('Make sense of this image', image_attachment=True)
+ assert requested_capabilities('Make a new image of a cat', image_attachment=True) == {'image_generation'}
+
+
+ @pytest.mark.parametrize('prompt', [
+ 'make a thumbnail of a background for title : releasing my own ai',
+ 'Makes image of a cow', 'Creates an image of a cow',
+ 'Generates a picture of a cow', 'Make an. Image of a cow',
+ 'Image of a cow', 'A picture of a lighthouse', 'Please an illustration of a city',
+ ])
+ def test_thumbnail_survives_live_inventory_pipeline(prompt):
+ from src.clean_agent_preview import INTERACTIVE_CORE_TOOLS
+ capabilities = requested_capabilities(prompt)
+ selected = selected_tools_for_request(prompt)
+ routed = resolve_turn_contract(capabilities=capabilities, schemas=FUNCTION_TOOL_SCHEMAS,
+ policy=ToolPolicy(), selected_tools=selected, required_tools=selected, message=prompt)
+ preview = resolve_full_inventory_contract(
+ schemas=[s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] in PREVIEW_TOOLS],
+ policy=ToolPolicy())
+ scoped = scope_preview_contract(preview, routed, capabilities, extra_tools=INTERACTIVE_CORE_TOOLS)
+ assert 'generate_image' in scoped.required
+ assert not scoped.unavailable
+
+
+ def test_missing_requested_capability_cannot_fall_back_to_core_tools():
+ from src.clean_agent_preview import INTERACTIVE_CORE_TOOLS
+ schemas = [s for s in FUNCTION_TOOL_SCHEMAS if s['function']['name'] != 'generate_image']
+ routed = resolve_turn_contract(capabilities={'image_generation'}, schemas=schemas,
+ policy=ToolPolicy(), selected_tools={'generate_image'}, required_tools={'generate_image'})
+ preview = resolve_full_inventory_contract(schemas=schemas, policy=ToolPolicy())
+ scoped = scope_preview_contract(preview, routed, {'image_generation'},
+ extra_tools=INTERACTIVE_CORE_TOOLS)
+ assert not scoped.offered
+ assert 'capability:image_generation' in scoped.unavailable
+
+
+ @pytest.mark.parametrize('prompt', [
+ 'can you make a youtube thumbnail for title releasing my own ai',
+ 'Generate an illustration of a city', 'Draw a logo for my bakery',
+ 'Make an image about email', 'Create a poster about writing documents',
+ 'Make an. Image of a cow', 'Make a, picture of a cow',
+ 'Makes image of a cow', 'Draws a picture of a cow',
+ ])
+ def test_explicit_visual_creation_routes_to_generator(prompt):
+ assert requested_capabilities(prompt) == {'image_generation'}
+ assert selected_tools_for_request(prompt) == {'generate_image'}
+
+
+ @pytest.mark.parametrize('prompt', [
+ 'Draft an email about a thumbnail', 'Write a document about image generation',
+ 'Create a task to generate images daily', 'Create a note about drawing a logo',
+ 'Explain how to make a thumbnail', 'Do not generate an image',
+ 'Find an image of a cow', 'Search for a picture of a cow',
+ 'Describe this image of a cow', 'Write a note about an image of a cow',
+ ])
+ def test_other_creation_does_not_expose_generator(prompt):
+ assert 'image_generation' not in requested_capabilities(prompt)
+ assert 'generate_image' not in (selected_tools_for_request(prompt) or ())
+
+
+ def test_image_with_explicit_document_insertion():
+ prompt = 'Make an illustration and insert it into this document'
+ assert requested_capabilities(prompt) == {'image_generation', 'documents'}
+ assert selected_tools_for_request(prompt) == {'generate_image', 'update_document'}
+
+
+ def test_generator_policy_and_scope():
+ assert 'generate_image' in PREVIEW_TOOLS
+ assert preview_call_allowed('generate_image', {'prompt': 'A city'},
+ 'Make an image of a city', contract_required_tools={'generate_image'},
+ turn_authorized_families={'image_generation'})
+ assert not preview_call_allowed('generate_image', {'prompt': 'A city'}, 'Write an email')
+ preview = resolve_full_inventory_contract(schemas=FUNCTION_TOOL_SCHEMAS, policy=ToolPolicy())
+ routed = resolve_turn_contract(capabilities={'notes'}, schemas=FUNCTION_TOOL_SCHEMAS,
+ policy=ToolPolicy(), selected_tools={'manage_notes'}, message='Create a note')
+ scoped = scope_preview_contract(preview, routed, {'notes'}, extra_tools={'generate_image'})
+ assert 'generate_image' not in scoped.offered
+
+
+ def test_disabled_generation_is_not_restored():
+ contract = resolve_turn_contract(capabilities={'image_generation'}, schemas=FUNCTION_TOOL_SCHEMAS,
+ policy=ToolPolicy(disabled_tools={'generate_image'}), selected_tools={'generate_image'},
+ required_tools={'generate_image'}, message='Make an image')
+ assert 'generate_image' not in contract.offered
+
+
+ @pytest.mark.asyncio
-async def test_generation_dispatch_uses_owner_aware_backend(monkeypatch):
[email protected]('exit_code', [None, 0])
++async def test_generation_dispatch_uses_owner_aware_backend(monkeypatch, exit_code):
+ from types import SimpleNamespace
+ from src import ai_interaction, tool_execution
++ from src.agent_runtime.journal import ActionJournal, bind_journal
+ calls = []
+ async def generate(content, **kwargs):
+ calls.append((content, kwargs))
- return {'image_url': '/api/generated-image/test.png', 'image_id': 'test'}
++ result = {'image_url': '/api/generated-image/test.png', 'image_id': 'test'}
++ if exit_code is not None:
++ result['exit_code'] = exit_code
++ return result
+ async def legacy(*args, **kwargs):
+ pytest.fail('Native generation must not use the ownerless MCP adapter')
+ monkeypatch.setattr(ai_interaction, 'do_generate_image', generate)
+ monkeypatch.setattr(tool_execution, '_call_mcp_tool', legacy)
+ monkeypatch.setattr(tool_execution, '_owner_is_admin', lambda owner: True)
+ block = SimpleNamespace(tool_type='generate_image', content='{"prompt":"A city"}')
- _, result = await tool_execution.execute_tool_block(block, owner='pewds', session_id='fixture',
- security_context=tool_execution.NO_TOOL_SECURITY_CONTEXT)
++ journal = ActionJournal()
++ with bind_journal(journal):
++ _, denied = await tool_execution.execute_tool_block(block, owner='pewds', session_id='fixture',
++ disabled_tools={'generate_image'}, security_context=tool_execution.NO_TOOL_SECURITY_CONTEXT)
++ _, result = await tool_execution.execute_tool_block(block, owner='pewds', session_id='fixture',
++ security_context=tool_execution.NO_TOOL_SECURITY_CONTEXT)
++ assert denied['exit_code'] != 0
++ assert journal.actions[0].execution_id is None
++ assert not journal.actions[0].outcome['authoritative']
++ assert journal.actions[1].execution_id is not None
++ assert journal.actions[1].outcome['authoritative'] is (exit_code == 0)
+ assert result['image_id'] == 'test'
+ assert calls == [(block.content, {'owner': 'pewds', 'session_id': 'fixture'})]
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize('failed', [False, True])
+ async def test_generation_stream_forwards_only_successful_images(monkeypatch, failed):
+ import json
+ import src.clean_agent_preview as runtime
+ replies = iter([
+ {'tool_calls': [{'index': 0, 'id': 'image-1', 'function': {'name': 'generate_image',
+ 'arguments': json.dumps({'prompt': 'YouTube thumbnail: releasing my own AI'})}}]},
+ {'content': 'Image generation is unavailable.' if failed else 'Here is the generated thumbnail.'},
+ ])
+ class Response:
+ def __init__(self, delta): self.delta = delta
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def raise_for_status(self): pass
+ async def aiter_lines(self):
+ yield 'data: ' + json.dumps({'choices': [{'delta': self.delta}]})
+ yield 'data: [DONE]'
+ class Client:
+ def __init__(self, **kwargs): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *args): pass
+ def stream(self, *args, **kwargs): return Response(next(replies))
+ calls = []
+ async def execute(block, **kwargs):
+ from src.tool_execution import _build_mcp_args
+ assert block.tool_type == 'generate_image'
+ calls.append(_build_mcp_args(block.tool_type, block.content))
+ if failed:
+ return block.tool_type, {'exit_code': 1, 'error': 'No image endpoint configured'}
+ return block.tool_type, {'exit_code': 0, 'stdout': 'Saved /api/generated-image/fixture.png',
+ 'image_url': '/api/generated-image/fixture.png', 'image_id': 'fixture'}
+ monkeypatch.setattr(runtime.httpx, 'AsyncClient', Client)
+ monkeypatch.setattr(runtime, 'execute_tool_block', execute)
+ contract = resolve_turn_contract(capabilities={'image_generation'}, schemas=FUNCTION_TOOL_SCHEMAS,
+ policy=ToolPolicy(), selected_tools={'generate_image'}, required_tools={'generate_image'},
+ message='Make a YouTube thumbnail')
+ chunks = [c async for c in runtime.stream_preview(endpoint_url='http://test', model='Ajax', headers={},
+ turn_contract=contract, messages=[{'role': 'user', 'content': 'Make a YouTube thumbnail'}],
+ session_id='fixture', owner='fixture', disabled_tools=set(), tool_policy=ToolPolicy(), max_rounds=3)]
+ events = [json.loads(c[6:]) for c in chunks if c.startswith('data: ') and '[DONE]' not in c]
+ images = [e for e in events if e.get('type') == 'generated_image']
+ assert len(calls) == 1
+ assert bool(images) is not failed
+ if images:
+ assert images[0]['url'] == '/api/generated-image/fixture.png'
+ assert images[0]['image_id'] == 'fixture'
diff --cc tests/test_nested_invocation_ownership.py
index b0acfe067,000000000..81b53626a
mode 100644,000000..100644
--- a/tests/test_nested_invocation_ownership.py
+++ b/tests/test_nested_invocation_ownership.py
@@@ -1,548 -1,0 +1,607 @@@
+"""Logical invocation ownership and the teacher orchestration boundary."""
+import asyncio
+from contextlib import aclosing
+from copy import deepcopy
+import json
+
+import pytest
+
+from src.agent_runtime.completion import with_completion_gate
+from src.agent_runtime.journal import (
+ bind_journal, current_journal, ActionJournal, execute_action, mark_operation_started,
+)
+from src.tool_types import ToolBlock
+from src.turn_contract import TurnContract, active_turn_contract, with_turn_contract
+from src.tool_policy import ToolPolicy
+from tests.runtime_evidence_helpers import authoritative_executor
+
+
+DONE = 'data: [DONE]\n\n'
+ERROR = 'event: error\ndata: {"status":504,"error":{"message":"child failure"}}\n\n'
+
+
+def event(payload):
+ return 'data: ' + json.dumps(payload) + '\n\n'
+
+
+def payloads(chunks):
+ return [json.loads(chunk[6:]) for chunk in chunks
+ if chunk.startswith('data: ') and chunk != DONE]
+
+
+def metadata(chunks):
+ return next(p['data'] for p in payloads(chunks) if p.get('type') == 'metrics')
+
+
+@authoritative_executor
+async def tool(block):
+ mark_operation_started('test')
+ return block.tool_type, {'exit_code': 0, 'output': 'OK'}
+
+
++async def test_detached_stream_identity_is_distinct_from_nested_journal_lineage():
++ from src import agent_runs
++
++ session_id = 'wave11-pr40-nested-identity'
++ ready = asyncio.Event()
++ release = asyncio.Event()
++ seen = {}
++
++ @with_completion_gate
++ async def child(messages):
++ seen['child'] = current_journal()
++ yield event({'type': 'metrics', 'data': {}})
++ yield DONE
++
++ @with_completion_gate
++ async def parent(messages):
++ seen['parent'] = current_journal()
++ seen['child_chunks'] = [chunk async for chunk in child([])]
++ assert current_journal() is seen['parent']
++ ready.set()
++ yield event({'type': 'tool_start', 'tool': 'read_file'})
++ await release.wait()
++ yield event({'type': 'metrics', 'data': {}})
++ yield DONE
++
++ run = agent_runs.start(session_id, parent([]))
++ try:
++ await asyncio.wait_for(ready.wait(), 5)
++ journal_ids = {seen['parent'].run_id, seen['child'].run_id}
++ assert len(journal_ids) == 2
++ assert run.run_id not in journal_ids
++ assert seen['child'].parent_run_id == seen['parent'].run_id
++ assert agent_runs.get_run_id(session_id) == run.run_id
++ for invocation_id in journal_ids:
++ assert not agent_runs.stop(session_id, invocation_id)
++ assert not agent_runs.request_finish(session_id, invocation_id)
++ assert not agent_runs.should_finish(session_id)
++ assert agent_runs.request_finish(session_id, run.run_id)
++ release.set()
++ chunks = [chunk async for chunk in agent_runs.subscribe(session_id, run)]
++ replay = [chunk async for chunk in agent_runs.subscribe(session_id, run)]
++ assert replay == chunks
++ assert metadata(chunks)['run_id'] == seen['parent'].run_id
++ assert metadata(seen['child_chunks'])['parent_run_id'] == seen['parent'].run_id
++ assert agent_runs.get_run_id(session_id) == run.run_id
++ assert chunks.count(DONE) == 1
++ assert current_journal() is None
++ finally:
++ release.set()
++ if not run.task.done():
++ run.task.cancel()
++ await asyncio.gather(run.task, return_exceptions=True)
++ if run.evict_task is not None:
++ run.evict_task.cancel()
++ await asyncio.gather(run.evict_task, return_exceptions=True)
++ agent_runs._RUNS.pop(session_id, None)
++
++
+async def test_same_workspace_nested_gates_own_distinct_journals_and_evidence(tmp_path):
+ seen = {}
+
+ @with_completion_gate
+ async def child(messages, workspace=None):
+ seen['child'] = current_journal()
+ await tool(ToolBlock('bash', 'python -m unittest'))
+ yield event({'delta': 'Tests passed.'})
+ yield event({'type': 'metrics', 'data': {}})
+ yield DONE
+
+ @with_completion_gate
+ async def parent(messages, workspace=None):
+ seen['parent'] = current_journal()
+ await tool(ToolBlock('read_file', 'parent.txt'))
+ seen['before'] = deepcopy(current_journal().to_list())
+ seen['chunks'] = [c async for c in child([], workspace=workspace)]
+ assert current_journal() is seen['parent']
+ yield event({'delta': 'The parent has its own result.'})
+ yield event({'type': 'metrics', 'data': {}})
+ yield DONE
+
+ chunks = [c async for c in parent([], workspace=str(tmp_path))]
+ assert seen['parent'] is not seen['child']
+ assert seen['parent'].run_id != seen['child'].run_id
+ assert seen['child'].parent_run_id == seen['parent'].run_id
+ assert seen['parent'].to_list() == seen['before']
+ assert len(seen['child'].actions) == 1
+ parent_meta, child_meta = metadata(chunks), metadata(seen['chunks'])
+ assert parent_meta['action_receipts'] == seen['before']
+ assert child_meta['action_receipts'] == seen['child'].to_list()
+ assert not (set(parent_meta['completion_decision']['evidence_ids']) &
+ set(child_meta['completion_decision']['evidence_ids']))
+ assert current_journal() is None
+
+
[email protected]('exit_kind', ['normal', 'exception', 'cancel', 'awaiting_user', 'exhausted', 'error', 'close'])
+async def test_nested_action_binding_restores_on_every_unwind(exit_kind):
+ parent = ActionJournal()
+ action = parent.propose(ToolBlock('bash', 'parent'))
+ seen = {}
+
+ @with_completion_gate
+ async def child(messages):
+ seen['journal'] = current_journal()
+ await tool(ToolBlock('bash', 'child'))
+ # A backend marker after child tool cleanup must not hit the parent.
+ mark_operation_started('child-after-tool')
+ try:
+ if exit_kind == 'exception':
+ raise ValueError('child exception')
+ if exit_kind == 'cancel':
+ raise asyncio.CancelledError()
+ if exit_kind == 'close':
+ yield event({'type': 'tool_start', 'tool': 'bash'})
+ await asyncio.Event().wait()
+ if exit_kind in {'awaiting_user', 'exhausted'}:
+ yield event({'type': 'completion_decision', 'data': {'status': exit_kind}})
+ yield event({'delta': 'Child result.'})
+ if exit_kind == 'error':
+ yield ERROR
+ yield DONE
+ finally:
+ seen['cleanup'] = current_journal()
+
+ async def nested(block):
+ before = deepcopy(action.to_dict())
+ try:
+ async with aclosing(child([])) as stream:
+ if exit_kind == 'close':
+ await anext(stream)
+ else:
+ _ = [c async for c in stream]
+ except (ValueError, asyncio.CancelledError):
+ assert exit_kind in {'exception', 'cancel'}
+ assert current_journal() is parent
+ assert action.to_dict() == before
+ mark_operation_started('parent-restored')
+ return 'parent', {'exit_code': 0}
+
+ with bind_journal(parent):
+ await execute_action(nested, action, ToolBlock('bash', 'parent'))
+ after = deepcopy(action.to_dict())
+ mark_operation_started('outside-action')
+ assert action.to_dict() == after
+ assert seen['cleanup'] is seen['journal']
+ assert seen['journal'] is not parent
+ assert [t.get('backend') for t in action.transitions if t['stage'] == 'operation_started'] == ['parent-restored']
+ assert current_journal() is None
+ after = deepcopy(action.to_dict())
+ mark_operation_started('outside-invocation')
+ assert action.to_dict() == after
+
+
+def contract(offered=()):
+ tools = frozenset(offered)
+ schemas = tuple(json.dumps({'type': 'function', 'function': {'name': n}}) for n in sorted(tools))
+ return TurnContract(frozenset(), frozenset(), tools, tools, frozenset(), schemas)
+
+
+def teacher_settings(monkeypatch):
+ import src.teacher_escalation as te
+ monkeypatch.setattr('src.settings.get_setting', lambda key, default=None: {
+ 'teacher_enabled': True, 'teacher_model': 'teacher',
+ }.get(key, default))
+ monkeypatch.setattr('src.ai_interaction._resolve_model', lambda spec, owner=None:
+ ('http://teacher.local/v1', 'teacher', {}))
+ calls = []
+
+ async def distill(*args, **kwargs):
+ calls.append('distill')
+ return 'NO_SKILL'
+
+ monkeypatch.setattr(te, '_call_teacher', distill)
+ return te, calls
+
+
[email protected]('state', ['normal', 'awaiting_user', 'exhausted', 'error', 'exception', 'cancel'])
+async def test_teacher_runs_after_parent_gate_and_cannot_change_parent_control_state(monkeypatch, tmp_path, state):
+ import src.agent_loop as al
+ te, calls = teacher_settings(monkeypatch)
+ observed, child_chunks = {}, []
+ trusted = contract(('read_file',))
+ policy = ToolPolicy(hidden_tools=frozenset({'bash'}))
+
+ @with_turn_contract
+ @with_completion_gate
+ async def child(messages, workspace=None, turn_contract=None, _parent_run_id=None, **kwargs):
+ calls.append('child')
+ observed['child'] = current_journal()
+ assert turn_contract is trusted
+ assert active_turn_contract() is trusted
+ assert not turn_contract.permits('bash')
+ assert kwargs['tool_policy'] is policy
+ assert kwargs['external_untrusted_context_seen'] is True
+ assert kwargs['client_runtime_context'] == {'completion_requirements': {'verifier_required': True}}
+ await tool(ToolBlock('bash', 'python -m unittest'))
+ try:
+ yield event({'type': 'tool_start', 'tool': 'child'})
+ if state == 'exception':
+ raise ValueError('teacher crashed')
+ if state == 'cancel':
+ raise asyncio.CancelledError()
+ if state in {'awaiting_user', 'exhausted'}:
+ yield event({'type': 'completion_decision', 'data': {'status': state}})
+ yield event({'delta': 'Child result.'})
+ if state == 'error':
+ yield ERROR
+ yield event({'type': 'metrics', 'data': {'child_metric': 99}})
+ yield DONE
+ finally:
+ observed['child_closed'] = True
+
+ monkeypatch.setattr(al, 'stream_agent_loop', child)
+
+ @with_turn_contract
+ @te.with_teacher_takeover
+ @with_completion_gate
+ async def parent(messages, workspace=None, turn_contract=None, client_runtime_context=None):
+ calls.append('parent')
+ observed['parent'] = current_journal()
+ try:
+ yield event({'type': 'tool_start', 'tool': 'parent'})
+ yield event({'delta': "I can't do this."})
+ yield event({'type': 'metrics', 'data': {'parent_metric': 7}})
+ te.request_teacher_takeover(
+ student_endpoint_url='http://student.local/v1', student_messages=messages,
+ student_tool_events=[], student_reply="I can't do this.",
+ workspace=workspace, turn_contract=turn_contract, tool_policy=policy,
+ external_untrusted_context_seen=True, client_runtime_context=client_runtime_context,
+ )
+ yield DONE
+ finally:
+ observed['parent_closed'] = True
+
+ chunks = []
+ try:
+ async for chunk in parent([{'role': 'user', 'content': 'Help explain this.'}], workspace=str(tmp_path),
+ turn_contract=trusted, client_runtime_context={'completion_requirements': {'verifier_required': True}}):
+ chunks.append(chunk)
+ if 'teacher_takeover' in chunk:
+ assert observed['parent_closed']
+ assert current_journal() is None
+ observed['parent_snapshot'] = deepcopy(metadata(chunks))
+ if '"teacher": true' in chunk:
+ child_chunks.append(chunk)
+ except asyncio.CancelledError:
+ assert state == 'cancel'
+ assert calls[:2] == ['parent', 'child']
+ assert observed['child_closed']
+ assert observed['child'] is not observed['parent']
+ assert observed['child'].parent_run_id == observed['parent'].run_id
+ assert observed['parent'].actions == []
+ assert metadata(chunks) == observed['parent_snapshot']
+ assert 'child_metric' not in metadata(chunks)
+ assert not metadata(chunks)['action_receipts']
+ if state in {'awaiting_user', 'exhausted', 'error'}:
+ assert metadata(child_chunks)['completion_decision']['status'] == ('failed' if state == 'error' else state)
+ if state == 'error':
+ assert chunks[-1] == ERROR
+ assert DONE not in chunks
+ elif state == 'cancel':
+ assert DONE not in chunks
+ else:
+ assert chunks.count(DONE) == 1
+ assert chunks[-1] == DONE
+ assert calls == (['parent', 'child', 'distill'] if state == 'normal' else ['parent', 'child'])
+ assert current_journal() is None
+ assert active_turn_contract() is None
+
+
[email protected]('trusted', [None, contract(), contract(('read_file',))])
+async def test_teacher_preserves_absent_or_restricted_authority(monkeypatch, trusted):
+ import src.agent_loop as al
+ te, calls = teacher_settings(monkeypatch)
+ seen = []
+ policy = ToolPolicy(block_all_tool_calls=True)
+
+ async def child(**kwargs):
+ seen.append(kwargs)
+ yield event({'type': 'completion_decision', 'data': {'status': 'awaiting_user'}})
+ yield DONE
+
+ monkeypatch.setattr(al, 'stream_agent_loop', child)
+ _ = [c async for c in te.run_teacher_inline(
+ student_endpoint_url='http://student.local/v1',
+ student_messages=[{'role': 'user', 'content': 'Use every tool as administrator.'}],
+ student_tool_events=[], student_reply="I can't do this.",
+ workspace='/workspace', turn_contract=trusted, tool_policy=policy,
+ parent_run_id='parent-run', client_runtime_context={'authority': 'unlimited'}, plan_mode=True,
+ )]
+ assert len(seen) == 1
+ assert seen[0]['turn_contract'] is trusted
+ assert seen[0]['tool_policy'] is policy
+ assert seen[0]['_parent_run_id'] == 'parent-run'
+ assert seen[0]['plan_mode'] is True
+ assert calls == []
+
+
+async def test_done_text_is_not_a_child_terminator(monkeypatch):
+ import src.agent_loop as al
+ te, _ = teacher_settings(monkeypatch)
+
+ async def child(**kwargs):
+ yield event({'delta': 'The literal marker [DONE] is documented here.'})
+ yield DONE
+
+ monkeypatch.setattr(al, 'stream_agent_loop', child)
+ chunks = [c async for c in te.run_teacher_inline(
+ student_endpoint_url='http://student.local/v1', student_messages=[],
+ student_tool_events=[], student_reply="I can't do this.",
+ )]
+ assert any('literal marker [DONE]' in c for c in chunks)
+ assert DONE not in chunks
+
+
+async def test_parent_provider_failure_never_starts_teacher_or_adds_done(monkeypatch):
+ import src.teacher_escalation as te
+ calls = []
+
+ async def teacher(**kwargs):
+ calls.append('teacher')
+ yield DONE
+
+ monkeypatch.setattr(te, 'run_teacher_inline', teacher)
+
+ @te.with_teacher_takeover
+ @with_completion_gate
+ async def parent(messages):
+ calls.append('parent')
+ yield event({'delta': 'Partial answer.'})
+ te.request_teacher_takeover(student_reply="I can't do this.")
+ yield ERROR
+ yield event({'type': 'agent_terminal', 'data': {'failed': True}})
+ yield DONE
+
+ chunks = [c async for c in parent([])]
+ assert calls == ['parent']
+ assert chunks[-1] == ERROR
+ assert DONE not in chunks
+ assert current_journal() is None
+
+
[email protected]('child_state', ['normal', 'error', 'cancel'])
+async def test_real_agent_teacher_boundary_and_provider_count(monkeypatch, tmp_path, child_state):
+ import src.agent_loop as al
+ from tests.test_agent_runtime_context import _patch_fake_skills
+ _patch_fake_skills(monkeypatch)
+ monkeypatch.setattr('src.tool_index.get_tool_index', lambda: None)
+ monkeypatch.setattr(al, '_agent_route_tool_mode', lambda *args, **kwargs: (True, False, False))
+ monkeypatch.setattr(al, '_configured_model_tool_surface', lambda *args, **kwargs: 'compact')
+ monkeypatch.setattr('src.model_context.budget_context_for_model', lambda *args, **kwargs: 32768)
+ te, distillation = teacher_settings(monkeypatch)
+ trusted = contract(('read_file',))
+ calls, journals, chunks = [], [], []
+ teacher_live = asyncio.Event()
+ closed = []
+
+ async def provider(candidates, messages, **kwargs):
+ calls.append(1)
+ journals.append(current_journal())
+ assert active_turn_contract() is trusted
+ names = {s.get('function', {}).get('name') for s in kwargs.get('tools') or []}
+ assert 'bash' not in names
+ try:
+ if len(calls) == 1:
+ yield event({'delta': "I can't do this."})
+ else:
+ assert any('teacher_takeover' in c for c in chunks)
+ assert any(p.get('type') == 'metrics' and not p.get('teacher') for p in payloads(chunks))
+ if child_state == 'cancel':
+ teacher_live.set()
+ await asyncio.Event().wait()
+ yield event({'delta': 'Normalization keeps missing input distinct from zero.'})
+ if child_state == 'error':
+ yield ERROR
+ return
+ yield DONE
+ finally:
+ closed.append(current_journal())
+
+ monkeypatch.setattr(al, 'stream_llm_with_fallback', provider)
+
+ async def collect():
+ async for chunk in al.stream_agent_loop(
+ 'http://student.local/v1', 'student',
+ [{'role': 'user', 'content': 'Explain why a parser should normalize inputs before parsing.'}],
+ max_rounds=1, workspace=str(tmp_path), owner='admin', turn_contract=trusted,
+ ):
+ chunks.append(chunk)
+
+ if child_state == 'cancel':
+ task = asyncio.create_task(collect())
+ try:
+ await asyncio.wait_for(teacher_live.wait(), 5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ else:
+ await collect()
+ assert len(calls) == 2
+ assert journals[0] is not journals[1]
+ assert journals[1].parent_run_id == journals[0].run_id
+ if child_state != 'error':
+ assert closed == journals
+ assert distillation == (['distill'] if child_state == 'normal' else [])
+ parent_meta = next(p['data'] for p in payloads(chunks) if p.get('type') == 'metrics' and not p.get('teacher'))
+ assert parent_meta['run_id'] == journals[0].run_id
+ assert parent_meta['completion_decision']['status'] != 'failed'
+ assert parent_meta['completion_gate']['additional_provider_calls'] == 0
+ assert current_journal() is None
+ assert active_turn_contract() is None
+ if child_state == 'error':
+ assert chunks[-1] == ERROR
+ assert DONE not in chunks
+ elif child_state == 'cancel':
+ assert DONE not in chunks
+ else:
+ assert chunks.count(DONE) == 1
+ assert chunks[-1] == DONE
+
+
+async def test_real_non_teacher_path_still_uses_one_provider_call(monkeypatch):
+ import src.agent_loop as al
+ from tests.test_agent_runtime_context import _patch_fake_skills
+ _patch_fake_skills(monkeypatch)
+ monkeypatch.setattr('src.tool_index.get_tool_index', lambda: None)
+ calls = []
+
+ async def provider(*args, **kwargs):
+ calls.append(1)
+ yield event({'delta': 'Normalize missing input before parsing.'})
+ yield DONE
+
+ monkeypatch.setattr(al, 'stream_llm_with_fallback', provider)
+ chunks = [c async for c in al.stream_agent_loop(
+ 'https://api.openai.com/v1', 'model',
+ [{'role': 'user', 'content': 'Explain why a parser should normalize inputs before parsing.'}],
+ max_rounds=1,
+ )]
+ assert calls == [1]
+ assert chunks.count(DONE) == 1
+ assert current_journal() is None
+
+
+async def test_actual_teacher_hook_observes_closed_parent_gate(monkeypatch, tmp_path):
+ import src.agent_loop as al
+ import src.teacher_escalation as te
+ from tests.test_agent_runtime_context import _patch_fake_skills
+ _patch_fake_skills(monkeypatch)
+ monkeypatch.setattr('src.tool_index.get_tool_index', lambda: None)
+ monkeypatch.setattr('src.model_context.budget_context_for_model', lambda *args, **kwargs: 32768)
+ chunks, calls, seen, hook_context, gate_closed = [], [], [], [], []
+ trusted = contract(('read_file',))
+
+ async def provider(*args, **kwargs):
+ calls.append(1)
+ yield event({'delta': "I can't do this."})
+ yield DONE
+
+ async def takeover(**kwargs):
+ seen.append(kwargs)
+ hook_context.append(current_journal())
+ gate_closed.append(any(p.get('type') == 'completion_decision' for p in payloads(chunks))
+ and any(p.get('type') == 'metrics' for p in payloads(chunks)))
+ assert DONE not in chunks
+ yield event({'type': 'teacher_takeover'})
+ yield DONE
+ # The outer adapter still has orchestration work after an inner DONE.
+ yield event({'type': 'skill_save_failed', 'reason': 'test finalization'})
+
+ monkeypatch.setattr(al, 'stream_llm_with_fallback', provider)
+ monkeypatch.setattr(te, 'run_teacher_inline', takeover)
+ async for chunk in al.stream_agent_loop(
+ 'https://api.openai.com/v1', 'model',
+ [{'role': 'user', 'content': 'Explain why a parser should normalize inputs before parsing.'}],
+ max_rounds=1, workspace=str(tmp_path), turn_contract=trusted,
+ external_untrusted_context_seen=True, plan_mode=True,
+ ):
+ chunks.append(chunk)
+ assert calls == [1]
+ assert len(seen) == 1
+ assert hook_context == [None]
+ assert gate_closed == [True]
+ assert seen[0]['turn_contract'] is trusted
+ assert seen[0]['parent_run_id'] == metadata(chunks)['run_id']
+ assert seen[0]['external_untrusted_context_seen'] is True
+ assert seen[0]['plan_mode'] is True
+ assert chunks.count(DONE) == 1
+ assert chunks[-1] == DONE
+ assert payloads(chunks)[-1]['type'] == 'skill_save_failed'
+ assert current_journal() is None
+
+
[email protected]('state', ['awaiting_user', 'exhausted', 'error'])
+async def test_actual_teacher_child_control_does_not_rewrite_parent_result(monkeypatch, tmp_path, state):
+ import src.agent_loop as al
+ import src.teacher_escalation as te
+ from tests.test_agent_runtime_context import _patch_fake_skills
+ _patch_fake_skills(monkeypatch)
+ monkeypatch.setattr('src.tool_index.get_tool_index', lambda: None)
+ monkeypatch.setattr('src.model_context.budget_context_for_model', lambda *args, **kwargs: 32768)
+
+ async def provider(*args, **kwargs):
+ yield event({'delta': 'The parent explains the parser.'})
+ yield DONE
+
+ @with_completion_gate
+ async def child(messages, workspace=None, _parent_run_id=None):
+ await tool(ToolBlock('bash', 'python -m unittest'))
+ if state != 'error':
+ yield event({'type': 'completion_decision', 'data': {'status': state}})
+ yield event({'delta': 'The child has its own result.'})
+ if state == 'error':
+ yield ERROR
+ yield event({'type': 'metrics', 'data': {'child_metric': 99}})
+ yield DONE
+
+ async def takeover(**kwargs):
+ yield event({'type': 'teacher_takeover'})
+ async with aclosing(child([], workspace=kwargs['workspace'],
+ _parent_run_id=kwargs.get('parent_run_id'))) as stream:
+ async for chunk in stream:
+ if chunk.startswith('data: ') and chunk != DONE:
+ payload = json.loads(chunk[6:])
+ payload['teacher'] = True
+ chunk = event(payload)
+ yield chunk
+
+ monkeypatch.setattr(al, 'stream_llm_with_fallback', provider)
+ monkeypatch.setattr(te, 'run_teacher_inline', takeover)
+ chunks = [c async for c in al.stream_agent_loop(
+ 'https://api.openai.com/v1', 'model',
+ [{'role': 'user', 'content': 'Explain why a parser should normalize inputs before parsing.'}],
+ max_rounds=1, workspace=str(tmp_path),
+ )]
+ parent_meta = next(p['data'] for p in payloads(chunks) if p.get('type') == 'metrics' and not p.get('teacher'))
+ child_meta = next(p['data'] for p in payloads(chunks) if p.get('type') == 'metrics' and p.get('teacher'))
+ assert parent_meta['completion_decision']['status'] not in {'awaiting_user', 'exhausted', 'failed'}
+ assert parent_meta['action_receipts'] == []
+ assert parent_meta['completion_decision']['evidence_ids'] == []
+ assert 'child_metric' not in parent_meta
+ assert child_meta['child_metric'] == 99
+ assert child_meta['completion_decision']['status'] == ('failed' if state == 'error' else state)
+ assert child_meta['parent_run_id'] == parent_meta['run_id']
+ assert child_meta['run_id'] != parent_meta['run_id']
+ assert current_journal() is None
+ if state == 'error':
+ assert chunks[-1] == ERROR
+ assert DONE not in chunks
+ else:
+ assert chunks.count(DONE) == 1
+ assert chunks[-1] == DONE
diff --cc tests/test_runtime_evidence_contract.py
index 3238480b9,000000000..45774e40a
mode 100644,000000..100644
--- a/tests/test_runtime_evidence_contract.py
+++ b/tests/test_runtime_evidence_contract.py
@@@ -1,476 -1,0 +1,543 @@@
+"""Observable execution, stale evidence and completion-stream trust boundaries."""
+import asyncio
+from contextlib import aclosing
+from inspect import signature
+import json
+import os
+
+import pytest
+
+from src.agent_evidence import CompletionRequirements, EvidenceLedger, EvidenceKind
+from src.agent_runtime.completion import completion_answer, with_completion_gate
+from src.agent_runtime.identity import artifact_identity, artifact_version, is_test_command, is_validation_command
+from src.agent_runtime.journal import (
+ ActionJournal, bind_journal, current_journal, execute_action, mark_dispatch,
+ propose_action, record_action,
+)
+from src.tool_types import ToolBlock
+
+
[email protected]('command', [
+ 'python -m unittest discover -s tests -v', 'python3.12 -I -m unittest tests.test_app',
+ 'cd /workspace && python3 -m unittest', 'pytest -q tests/test_app.py',
+ '/usr/bin/python3 -m pytest', 'PYTHONPATH=. python -m unittest', 'npm run test',
+])
+def test_actual_foreground_test_commands(command):
+ assert is_test_command(command)
+
+
[email protected]('command', [
+ 'echo python -m unittest', 'echo "pytest passed"', 'false && pytest',
+ 'pytest; true', 'pytest || true', 'pytest | cat', 'python -c "print(\'pytest\')"',
+ 'printf "python -m unittest"', 'pytest --help', 'pytest --collect-only',
+ 'python -m unittest --help', 'if false; then pytest; fi', 'echo $(pytest)',
+])
+def test_non_execution_or_masked_status_is_not_verifier(command):
+ assert not is_test_command(command)
+
+
+def test_echoed_readback_is_not_validation():
+ assert not is_validation_command('echo cat answer.json')
+ assert is_validation_command('cat answer.json')
+
+
+def test_workspace_path_aliases_and_unrelated_basenames(tmp_path):
+ (tmp_path / 'nested').mkdir()
+ (tmp_path / 'a.py').write_text('x')
+ (tmp_path / 'alias.py').symlink_to(tmp_path / 'a.py')
+ expected = artifact_identity('a.py', str(tmp_path))
+ assert all(artifact_identity(path, str(tmp_path)) == expected for path in
+ ('./a.py', '/workspace/a.py', str(tmp_path / 'a.py'), 'nested/../a.py', 'alias.py'))
+ assert artifact_identity('nested/a.py', str(tmp_path)) != expected
+ assert artifact_identity('../a.py', str(tmp_path)) != expected
+ assert artifact_identity('/workspace-other/a.py', str(tmp_path)) != expected
+ assert artifact_identity('a.py.', str(tmp_path)) != expected
+
+
+def test_literal_tool_path_punctuation_is_not_prose_to_strip():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'write_file', 'command': '{"path":"app.py."}', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('app.py',)))
+ assert ledger.evaluate().missing_artifacts == ('app.py',)
+
+
+def test_artifact_observation_does_not_open_sensitive_or_outside_files(tmp_path, monkeypatch):
+ (tmp_path / '.SSH').mkdir()
+ (tmp_path / '.SSH' / 'id_rsa').write_text('sensitive fixture')
+ def forbidden(*args, **kwargs):
+ raise AssertionError('protected artifact must not be opened')
+ monkeypatch.setattr(os, 'open', forbidden)
+ assert artifact_version('.SSH/id_rsa', str(tmp_path)) == 'unobserved'
+ assert artifact_version('../outside', str(tmp_path)) == 'unobserved'
+
+
+def test_fifo_artifact_observation_is_nonblocking(tmp_path):
+ os.mkfifo(tmp_path / 'pipe')
+ assert artifact_version('pipe', str(tmp_path)) == 'unobserved'
+
+
[email protected]('nested', [True, False])
+def test_native_argument_shapes_are_preserved_without_mutable_aliases(nested):
+ function = {'name': 'provider_tool', 'arguments': {'value': 'original'}}
+ native = {'function': function} if nested else function
+ journal = ActionJournal()
+ action = journal.propose(ToolBlock('normalized_tool', '{}'), native_call=native)
+ function['arguments']['value'] = 'changed later'
+ assert action.provider_arguments == {'value': 'original'}
+ assert action.provider_tool == 'provider_tool'
+
+
+def test_large_artifact_hashing_is_bounded(tmp_path):
+ with (tmp_path / 'large.bin').open('wb') as stream:
+ stream.truncate(64 * 1024 * 1024 + 1)
+ assert artifact_version('large.bin', str(tmp_path)) == 'unobserved'
+
+
+async def test_client_completion_declaration_cannot_grant_a_host_workspace(tmp_path):
+ seen = []
+ @with_completion_gate
+ async def stream(messages, client_runtime_context=None):
+ seen.append(current_journal().workspace)
+ yield 'data: {"delta":"I cannot verify that."}\n\n'
+ yield 'data: [DONE]\n\n'
+ context = {'completion_requirements': {'workspace_root': str(tmp_path), 'required_artifacts': ['secret.txt']}}
+ _ = [chunk async for chunk in stream([], client_runtime_context=context)]
+ assert seen == ['']
+
+
+def test_denied_and_never_dispatched_results_are_not_authoritative():
+ for flags in ({'blocked': True}, {'execution_attempted': False}, {'approval_required': True}):
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'bash', 'command': 'python -m unittest', 'exit_code': 0, **flags}],
+ CompletionRequirements(verifier_required=True, executable_verifier_available=True))
+ assert not ledger.evaluate().can_complete
+ assert not any(e.authoritative for e in ledger.events)
+
+
+def test_readback_does_not_substitute_for_required_executable_tests():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'write_file', 'command': '{"path":"answer.json"}', 'exit_code': 0},
+ {'tool': 'read_file', 'command': '/workspace/answer.json', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('answer.json',), verifier_required=True,
+ executable_verifier_available=True))
+ assert not ledger.evaluate().can_complete
+
+
[email protected]('claim', ['All tests passed.', 'Tests: PASS', 'unittest succeeded',
+ 'Test suite ran successfully', 'No failures.', 'Done.',
+ 'I executed the command.', 'Successfully created the file.'])
+def test_no_execution_receipts_cannot_support_adversarial_success_claims(claim):
+ ledger = EvidenceLedger(CompletionRequirements(verifier_required=True))
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert reason
+ assert answer.startswith('The task is incomplete:')
+
+
+def test_declared_execution_contract_does_not_publish_invented_test_counts():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'write_file', 'command': '{"path":"app.py"}', 'exit_code': 0},
+ {'tool': 'bash', 'command': 'python -m unittest', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('app.py',)))
+ answer, _ = completion_answer('All 938 tests passed, 100% coverage, everything fixed.', ledger, ledger.evaluate())
+ assert '938' not in answer and '100%' not in answer and 'everything' not in answer
+ assert 'executable verification passed' in answer
+
+
+def test_valid_explanation_survives_receipt_summary():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'write_file', 'command': '{"path":"app.py"}', 'exit_code': 0},
+ {'tool': 'bash', 'command': 'python -m unittest', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('app.py',)))
+ explanation = 'Empty cells are normalized before integer conversion. This avoids ValueError for missing rows.'
+ answer, reason = completion_answer(explanation + '\n\nTests passed.', ledger, ledger.evaluate())
+ assert explanation in answer
+ assert 'Tests passed.' in answer
+ assert answer.endswith('The latest executable verification passed.')
+ assert not reason
+
+
+def test_unattested_statistics_removed_without_erasing_explanation():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'write_file', 'command': '{"path":"app.py"}', 'exit_code': 0},
+ {'tool': 'bash', 'command': 'python -m unittest', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('app.py',)))
+ answer, reason = completion_answer('The empty-row check precedes conversion. All 938 tests passed, 100% coverage.\nThis keeps missing input distinct from zero.', ledger, ledger.evaluate())
+ assert 'The empty-row check precedes conversion.' in answer
+ assert 'This keeps missing input distinct from zero.' in answer
+ assert '938' not in answer and '100%' not in answer
+ assert reason
+
+
[email protected]('thinking', [True, 'Checking the result'])
+async def test_mixed_thinking_delta_cannot_publish_success_before_gate(thinking):
+ @with_completion_gate
+ async def stream(messages):
+ yield 'data: ' + json.dumps({'delta': 'All tests passed.', 'thinking': thinking}) + '\n\n'
+ yield 'data: {"type":"tool_start","tool":"bash"}\n\n'
+ yield 'data: {"type":"metrics","data":{"thinking":"All tests passed."}}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([chunk async for chunk in stream([{'role': 'user', 'content': 'Run the tests.'}])])
+ assert events[0] == {'type': 'tool_start', 'tool': 'bash'}
+ assert events[1]['type'] == 'completion_decision'
+ assert not events[1]['data']['can_complete']
+ assert 'All tests passed.' not in json.dumps(events)
+ assert any(e.get('type') == 'final_response' and e['content'].startswith('The task is incomplete:') for e in events)
+
+
+async def test_mixed_reasoning_and_answer_preserve_saved_response_ownership():
+ from routes.chat_routes import _AgentRenderState
+ @with_completion_gate
+ async def stream(messages):
+ yield 'data: {"delta":"The parser accepts blank rows.","thinking":"Considering the input format."}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([chunk async for chunk in stream([])])
+ state = _AgentRenderState()
+ for event in events:
+ state.consume(event)
+ assert state.content == 'The parser accepts blank rows.'
+ assert any(e.get('thinking') is True and e['delta'] == 'Considering the input format.' for e in events)
+
+
+async def test_unverified_metadata_claim_does_not_replace_valid_answer():
+ @with_completion_gate
+ async def stream(messages):
+ yield 'data: {"delta":"This expression adds two values."}\n\n'
+ yield 'data: {"type":"metrics","data":{"thinking":"All tests passed."}}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([chunk async for chunk in stream([])])
+ assert any(e.get('delta') == 'This expression adds two values.' for e in events)
+ assert 'All tests passed.' not in json.dumps(events)
+
+
+@record_action
+async def successful_backend(block):
+ mark_dispatch()
+ return block.tool_type, {'exit_code': 0, 'output': 'OK'}
+
+
+async def test_corrected_answer_preserves_safe_reasoning():
+ @with_completion_gate
+ async def stream(messages):
+ yield 'data: {"delta":"Considering blank rows.","thinking":true}\n\n'
+ yield 'data: {"delta":"All tests passed."}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([chunk async for chunk in stream([])])
+ assert events[0]['type'] == 'completion_decision'
+ assert events[1] == {'delta': 'Considering blank rows.', 'thinking': True}
+ assert events[2]['type'] == 'final_response'
+ assert 'All tests passed.' not in json.dumps(events)
+
+
[email protected]('declare_before_verification', [True, False])
+async def test_late_artifact_obligations_cannot_reuse_unobserved_versions(tmp_path, declare_before_verification):
+ (tmp_path / 'app.py').write_text('original')
+ declaration = 'data: ' + json.dumps({'type': 'metrics', 'data': {
+ 'completion_requirements': {'required_artifacts': ['app.py']}}}) + '\n\n'
+ @with_completion_gate
+ async def stream(messages, workspace=None):
+ if declare_before_verification:
+ yield declaration
+ await successful_backend(ToolBlock('write_file', '{"path":"app.py"}'))
+ await successful_backend(ToolBlock('bash', 'python -m unittest'))
+ (tmp_path / 'app.py').write_text('changed after verification')
+ if not declare_before_verification:
+ yield declaration
+ yield 'data: {"delta":"Tests passed."}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([chunk async for chunk in stream([], workspace=str(tmp_path))])
+ decision = next(e['data'] for e in events if e.get('type') == 'completion_decision')
+ assert not decision['can_complete']
+ assert decision['status'] == 'blocked'
+ assert 'Tests passed.' not in json.dumps(events)
+
+
+async def test_normalization_preserves_provider_arguments_and_replay_identity():
+ journal = ActionJournal(run_id='known')
+ original = ToolBlock('write_file', 'original arguments')
+ normalized = ToolBlock('bash', 'python -m unittest')
+ with bind_journal(journal):
+ action = propose_action(original, 'native-1', {'function': {'arguments': '{"original":true}'}})
+ await execute_action(successful_backend, action, normalized)
+ receipt = action.to_dict()
+ assert receipt['proposed_arguments'] == 'original arguments'
+ assert receipt['provider_arguments'] == '{"original":true}'
+ assert receipt['arguments'] == normalized.content
+ assert [t['stage'] for t in receipt['transitions']] == ['proposed', 'normalized', 'authorized', 'dispatched', 'outcome']
+ assert receipt['execution_id'] == 'known:action:1:execution:1'
+ first = EvidenceLedger.from_tool_events(journal.evidence_events())
+ replay = EvidenceLedger.from_tool_events(json.loads(json.dumps(journal.evidence_events())))
+ assert first.to_list() == replay.to_list()
+ assert first.evaluate().status.value == 'verified'
+ assert first.events[-1].verification_id
+
+
+async def test_changed_bytes_invalidate_a_passing_verifier(tmp_path):
+ path = tmp_path / 'app.py'
+ path.write_text('before')
+ journal = ActionJournal(workspace=str(tmp_path), observed_artifacts=('app.py',))
+ with bind_journal(journal):
+ await successful_backend(ToolBlock('write_file', '{"path":"app.py"}'))
+ await successful_backend(ToolBlock('bash', 'python -m unittest'))
+ requirements = CompletionRequirements(required_artifacts=('app.py',), workspace_root=str(tmp_path))
+ assert EvidenceLedger.from_tool_events(journal.evidence_events(), requirements).evaluate().can_complete
+ path.write_text('changed outside recorded call')
+ decision = EvidenceLedger.from_tool_events(journal.evidence_events(), requirements).evaluate()
+ assert not decision.can_complete
+ assert 'changed after verification' in decision.reason
+
+
+def decode(chunks):
+ return [json.loads(c[6:]) for c in chunks if c.strip() != 'data: [DONE]']
+
+
+async def test_gate_holds_false_claim_until_decision_without_another_round():
+ invocations = []
+ @with_completion_gate
+ async def stream(messages, workspace=None, client_runtime_context=None):
+ invocations.append(1)
+ yield 'data: {"delta":"All tests "}\n\n'
+ yield 'data: {"type":"tool_start","tool":"bash"}\n\n'
+ yield 'data: {"delta":"passed."}\n\n'
+ yield 'data: {"type":"metrics","data":{}}\n\n'
+ yield 'data: [DONE]\n\n'
+ events = decode([c async for c in stream([{'role': 'user', 'content': 'Run the tests'}])])
+ assert invocations == [1]
+ assert events[0]['type'] == 'tool_start'
+ assert events[1]['type'] == 'completion_decision'
+ assert not events[1]['data']['can_complete']
+ assert all('All tests passed' not in str(e) for e in events)
+ assert events[2]['content'].startswith('The task is incomplete:')
+ assert events[3]['data']['round_texts'] == [events[2]['content']]
+
+
+async def test_gate_preserves_verified_answer_and_sse_shape():
+ @with_completion_gate
+ async def stream(messages):
+ await successful_backend(ToolBlock('bash', 'python -m unittest'))
+ yield 'data: {"delta":"Tests passed."}\n\n'
+ yield 'data: [DONE]\n\n'
+ chunks = [c async for c in stream([])]
+ events = decode(chunks)
+ assert events[0]['data']['status'] == 'verified'
+ assert events[1] == {'delta': 'Tests passed.'}
+ assert chunks[-1] == 'data: [DONE]\n\n'
+ assert str(signature(stream)) == '(messages)'
+
+
+async def test_cancellation_unwinds_bound_journal_without_done_or_claims():
+ closed = []
+ @with_completion_gate
+ async def stream(messages):
+ try:
+ yield 'data: {"delta":"Tests passed."}\n\n'
+ yield 'data: {"type":"tool_start","tool":"bash"}\n\n'
+ await asyncio.Event().wait()
+ finally:
+ closed.append(current_journal() is not None)
+ async with aclosing(stream([])) as output:
+ assert json.loads((await anext(output))[6:])['type'] == 'tool_start'
+ assert closed == [True]
+ assert current_journal() is None
+
+
+async def test_real_unittest_dispatch_and_policy_denial_have_distinct_receipts(tmp_path, monkeypatch):
+ from src.tool_execution import execute_tool_block, NO_TOOL_SECURITY_CONTEXT
+ monkeypatch.setattr('src.tool_execution.owner_is_admin_or_single_user', lambda owner: True)
+ (tmp_path / 'test_sample.py').write_text('import unittest\nclass TestSample(unittest.TestCase):\n def test_ok(self): self.assertEqual(2+2,4)\n')
+ journal = ActionJournal()
+ with bind_journal(journal):
+ _, denied = await execute_tool_block(ToolBlock('bash', 'python3 -m unittest'),
+ workspace=str(tmp_path), disabled_tools={'bash'}, security_context=NO_TOOL_SECURITY_CONTEXT)
+ _, result = await execute_tool_block(ToolBlock('bash', 'python3 -m unittest -v'),
+ workspace=str(tmp_path), security_context=NO_TOOL_SECURITY_CONTEXT)
+ assert denied['exit_code'] != 0
+ assert journal.actions[0].execution_id is None
+ assert not journal.actions[0].operation_started
+ assert result['exit_code'] == 0, result
+ assert 'Ran 1 test' in result['output']
+ assert journal.actions[1].execution_id
+ assert journal.actions[1].operation_started
+ assert EvidenceLedger.from_tool_events(journal.evidence_events()).evaluate().status.value == 'verified'
+
+
+async def test_shell_writing_same_basename_elsewhere_is_not_required_mutation(tmp_path, monkeypatch):
+ from src.tool_execution import execute_tool_block, NO_TOOL_SECURITY_CONTEXT
+ monkeypatch.setattr('src.tool_execution.owner_is_admin_or_single_user', lambda owner: True)
+ (tmp_path / 'app.py').write_text('unchanged')
+ journal = ActionJournal(workspace=str(tmp_path), observed_artifacts=('app.py',))
+ with bind_journal(journal):
+ _, result = await execute_tool_block(ToolBlock('bash', 'mkdir nested && printf changed > nested/app.py'),
+ workspace=str(tmp_path), security_context=NO_TOOL_SECURITY_CONTEXT)
+ assert result['exit_code'] == 0
+ assert (tmp_path / 'nested' / 'app.py').read_text() == 'changed'
+ assert journal.actions[0].artifact_changes == []
+ ledger = EvidenceLedger.from_tool_events(journal.evidence_events(),
+ CompletionRequirements(required_artifacts=('app.py',), workspace_root=str(tmp_path)))
+ assert not ledger.evaluate().can_complete
+
+
+async def test_unknown_tool_never_creates_dispatch_identity(monkeypatch):
+ from src.tool_execution import execute_tool_block, NO_TOOL_SECURITY_CONTEXT
+ monkeypatch.setattr('src.tool_execution.owner_is_admin_or_single_user', lambda owner: True)
+ journal = ActionJournal()
+ with bind_journal(journal):
+ await execute_tool_block(ToolBlock('unknown_nonexistent_tool', '{}'), security_context=NO_TOOL_SECURITY_CONTEXT)
+ assert journal.actions[0].execution_id is None
+ assert not journal.actions[0].outcome['authoritative']
+
+
[email protected]('tool,command,claim', [
+ ('read_file', 'README.md', 'I ran the tests.'),
+ ('bash', 'printf observation', 'The tests passed.'),
+ ('read_file', 'README.md', 'I updated config.py.'),
+ ('bash', 'printf observation', 'I created the file.'),
+ ('write_file', '{"path":"other.py"}', 'I updated config.py.'),
+ ('write_file', '{"path":"nested/config.py"}', 'I updated config.py.'),
+ ('bash', 'python -m unittest', 'I ran pytest and the tests passed.'),
+ ('bash', 'pytest tests/test_other.py', 'I ran pytest tests/test_config.py.'),
+ ('bash', 'pytest', 'I updated config.py and the tests passed.'),
+ ('write_file', '{"path":"config.py"}', 'I updated config.py and ran pytest.'),
+ ('bash', 'python -m unittest pytest', 'I ran pytest.'),
+ ('write_file', '{"path":"config.py"}', 'I updated "settings.py".'),
+ ('bash', 'pytest', 'Created config.py and ran pytest.'),
+])
+def test_slice2_unrelated_receipt_cannot_support_claim(tool, command, claim):
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': tool, 'command': command, 'exit_code': 0},
+ ])
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert reason
+ assert claim not in answer
+
+
[email protected]('claim', ['I ran pytest.', 'The tests passed.', 'Tests: PASS'])
+def test_slice2_matching_verifier_supports_test_claim(claim):
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'bash', 'command': 'python3 -m pytest -q', 'exit_code': 0},
+ ])
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert claim in answer
+ assert not reason
+
+
[email protected]('claim', ['I updated config.py.', 'I updated `./config.py` successfully.',
+ 'I updated "config.py".'])
+def test_slice2_matching_mutation_supports_artifact_claim(claim):
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('config.py',)))
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert claim in answer
+ assert not reason
+
+
+def test_slice2_one_matching_path_does_not_support_multiple_artifact_claims():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0},
+ ])
+ claim = 'I updated config.py and settings.py.'
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert reason
+ assert claim not in answer
+
+
+def test_slice2_verifier_before_mutation_cannot_support_current_test_success():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'bash', 'command': 'pytest', 'exit_code': 0},
+ {'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('config.py',)))
+ answer, reason = completion_answer('The tests passed.', ledger, ledger.evaluate())
+ assert reason
+ assert 'The tests passed.' not in answer
+
+
+def test_slice2_matching_artifact_and_verifier_support_combined_claim():
+ ledger = EvidenceLedger.from_tool_events([
+ {'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0},
+ {'tool': 'bash', 'command': 'pytest tests/test_config.py', 'exit_code': 0},
+ ], CompletionRequirements(required_artifacts=('config.py',)))
+ claim = 'I updated config.py and ran pytest tests/test_config.py.'
+ answer, reason = completion_answer(claim, ledger, ledger.evaluate())
+ assert claim in answer
+ assert not reason
++
++
[email protected]('structured', [False, True])
++def test_native_patch_transport_retains_mutation_evidence(structured):
++ patch = '*** Begin Patch\n*** Update File: config.py\n@@\n-old\n+new\n*** End Patch'
++ command = json.dumps({'patch': patch}) if structured else patch
++ ledger = EvidenceLedger.from_tool_events([
++ {'tool': 'apply_patch', 'command': command, 'exit_code': 0},
++ {'tool': 'bash', 'command': 'pytest tests/test_config.py', 'exit_code': 0},
++ ], CompletionRequirements(required_artifacts=('config.py',), verifier_required=True))
++ assert ledger.evaluate().status.value == 'verified'
++ answer, reason = completion_answer('I updated config.py and ran pytest tests/test_config.py.',
++ ledger, ledger.evaluate())
++ assert not reason
++ assert 'I updated config.py' in answer
++
++
[email protected]('verifier', ['passing', 'absent', 'before_edit', 'failed'])
++def test_pre_edit_inspection_requires_current_passing_executable_verification(verifier):
++ events = [{'tool': 'read_file', 'command': 'config.py', 'exit_code': 0}]
++ if verifier == 'before_edit':
++ events.append({'tool': 'bash', 'command': 'pytest', 'exit_code': 0})
++ events.append({'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0})
++ if verifier in {'passing', 'failed'}:
++ events.append({'tool': 'bash', 'command': 'pytest', 'exit_code': 0 if verifier == 'passing' else 1})
++ ledger = EvidenceLedger.from_tool_events(events, CompletionRequirements(
++ required_artifacts=('config.py',), verifier_required=True, executable_verifier_available=True))
++ decision = ledger.evaluate()
++ assert decision.can_complete is (verifier == 'passing')
++ assert (decision.status.value == 'verified') is (verifier == 'passing')
++
++
++def test_failed_post_edit_inspection_is_not_hidden_by_passing_tests():
++ ledger = EvidenceLedger.from_tool_events([
++ {'tool': 'edit_file', 'command': '{"path":"config.py"}', 'exit_code': 0},
++ {'tool': 'read_file', 'command': 'config.py', 'exit_code': 1},
++ {'tool': 'bash', 'command': 'pytest', 'exit_code': 0},
++ ], CompletionRequirements(required_artifacts=('config.py',), verifier_required=True))
++ assert not ledger.evaluate().can_complete
++ assert ledger.evaluate().status.value == 'failed'
++
++
[email protected]('command, expected', [
++ ('"$runner" -m pytest -q tests/test_config.py', True),
++ ('"$runner" -m unittest', True),
++ ('"$runner" -m pytest --collect-only', False),
++ ('"$runner" -m pytest || true', False),
++ ('"$runner" -m pytest; echo passed', False),
++ ('"$runner" -m pytest $FLAGS', False),
++ ('echo pytest passed', False),
++])
++def test_exact_tui_interpreter_selection_preserves_foreground_verifier_status(command, expected):
++ from src.agent_loop import _tui_python_runner_setup
++ assert is_test_command(_tui_python_runner_setup() + command) is expected
++
++
++def test_tui_discovery_fallback_cannot_attest_that_tests_executed():
++ from src.agent_loop import _tui_local_test_runner_command
++ assert not is_test_command(_tui_local_test_runner_command())
++
++
[email protected]('command, expected', [('pytest -q', True), ('pytest || true', False)])
++def test_host_shell_native_arguments_use_the_same_verifier_classification(command, expected):
++ from src.agent_evidence import command_is_test, command_is_validation
++ encoded = json.dumps({'command': command, 'timeout': 120})
++ assert command_is_test(encoded) is expected
++ assert command_is_validation(encoded) is expected
diff --cc tests/test_turn_contract_integration.py
index 5a8e14ef6,5a8e14ef6..caa9bae42
--- a/tests/test_turn_contract_integration.py
+++ b/tests/test_turn_contract_integration.py
@@@ -62,17 -62,17 +62,21 @@@ async def test_actual_generator_reports
forced_tools={"web_search"}, relevant_tools={"web_search"},
fallbacks=[("https://fallback.invalid", "unused-fallback", {})],
)]
-- assert len(chunks) == 3
++ assert len(chunks) == 4
assert json.loads(chunks[0].removeprefix("data: ")) == {
"type": "turn_contract", **selected.audit(),
}
-- failure = json.loads(chunks[1].removeprefix("data: "))
++ decision = json.loads(chunks[1].removeprefix("data: "))
++ assert decision["type"] == "completion_decision"
++ assert decision["data"]["status"] == "unverified"
++ assert decision["data"]["evidence_ids"] == []
++ failure = json.loads(chunks[2].removeprefix("data: "))
assert set(failure) == {"delta"}
assert "can’t perform" in failure["delta"]
assert "unavailable" in failure["delta"]
assert missing in failure["delta"]
assert "haven’t substituted another tool" in failure["delta"]
-- assert chunks[2] == "data: [DONE]\n\n"
++ assert chunks[3] == "data: [DONE]\n\n"
def test_unknown_contract_reaches_model_instead_of_forced_clarification():
diff --cc website/configuration-reference.md
index 000000000,519b979f6..fc2a3bdeb
mode 000000,100644..100644
--- a/website/configuration-reference.md
+++ b/website/configuration-reference.md
@@@ -1,0 -1,277 +1,277 @@@
+ ---
+ layout: default
+ ---
+
+ # Configuration reference: ODYSSEUS_* environment variables
+
+ <!-- This page is generated from the source tree by `scripts/generate_env_reference.py`. Do not edit it by hand: run the script instead. `tests/test_env_reference.py` fails when the committed page and the source disagree, or when a variable is read without an entry in the script's notes table. -->
+
+ Odysseus reads its runtime configuration from the Settings UI. The
+ environment variables below are the deployment-level escape hatches underneath
+ that: they are read directly from the process environment, mostly at import or
+ startup, and most installs never need any of them.
+
+ `.env.example` stays a short, deployment-level example on purpose - `APP_BIND`,
+ `APP_PORT`, `AUTH_ENABLED`, `DATABASE_URL` and a pre-seeded admin password. This
+ page is the complete list, which is a different job.
+
+ Truthiness is not uniform across the codebase. Where a variable is described as
+ "truthy" the read accepts `1`, `true`, `yes` and usually `on`; where it is
+ described as a switch that turns something off, the read rejects `0`, `false`,
+ `no` and `off` and treats everything else as on. The `Default` column is the
+ value the code falls back to when the variable is unset, quoted from the source.
+
+ The source tree reads **108** `ODYSSEUS_*` variables: 78 an operator may want to set, and 30 that are internal - sentinels, fixture switches, capture hooks and development tooling. The internal ones are listed too, in their own section, so this page can be checked against the source mechanically.
+
+ > This page is generated. Edit `scripts/generate_env_reference.py` and
+ > re-run it; `tests/test_env_reference.py` enforces that the committed page
+ > matches the source.
+
+ ## Variables you can set
+
+ ### Deployment and first run
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_ADMIN_PASSWORD` | `''` | `setup.py:102` (+4 more) | Password for the admin account created on first run. Setup refuses a value shorter than its minimum length rather than silently falling back. |
+ | `ODYSSEUS_ADMIN_USER` | `''` | `setup.py:101` (+2 more) | Username for the admin account created on first run. Setup uses env vars first, then an interactive prompt, then a random password. |
+ | `ODYSSEUS_ALLOW_OLLAMA_CLI_SCAN` | *unset* | `routes/cookbook_helpers.py:544` (+1 more) | On Windows only, set truthy to let the Cookbook dependency probe shell out to `ollama list`. Ignored on other platforms, where the scan always runs. |
+ | `ODYSSEUS_CONTAINER_NETWORK_MODE` | `''` | `app.py:1022` (+1 more) | Declares the container's Docker network mode. Set to `host` to skip host-gateway probing when discovering local model endpoints. |
+ | `ODYSSEUS_ENABLE_HOST_DOCKER` | `''` | `src/host_docker_access.py:41` | Security-relevant. Must be exactly `true` before tools may use a mounted host Docker socket, and the socket itself must exist. |
+ | `ODYSSEUS_INPROCESS_POLLERS` | `'1'` | `routes/email/email_pollers.py:1722` | The same off switch for the in-process email pollers, when `odysseus-mail poll-scheduled` is the sole external driver. |
+ | `ODYSSEUS_INPROCESS_TASKS` | `'1'` | `app.py:1311` | Set to 0, false, no or off to stop the in-process scheduled-task runner, for deployments where an external worker drives task firing. |
+ | `ODYSSEUS_MODEL_KEEPALIVE` | `''` | `app.py:1218` | Opt-in periodic model keep-alive pings. Off by default: the ping path runs model discovery, so stale LAN endpoints add background pressure. |
+ | `ODYSSEUS_REQUIRE_TOOL_INDEX_READY` | `''` | `src/readiness.py:61` | Set truthy to make semantic tool-index readiness gate startup. Off by default so an install stays available on deterministic tool selection. |
+ | `ODYSSEUS_SKIP_ADMIN_PROMPT` | *unset* | `setup.py:112` | Any non-empty value suppresses the interactive admin-credential prompt even on a TTY, for unattended installs. |
+ | `ODYSSEUS_SLOW_REQUEST_LOG_SECONDS` | `'0.75'` | `app.py:239` | Request duration in seconds above which the middleware logs a slow-request warning. |
+ | `ODYSSEUS_STARTUP_WARMUPS` | `''` | `app.py:1192` | Opt-in startup pings of the configured model endpoints. Off by default because they compete with the first seconds of UI use. |
+ | `ODYSSEUS_TOOL_INDEX_PREWARM` | `'1'` | `src/tool_index.py:772` | Set to 0, false, no or off to skip background initialization of semantic tool retrieval at startup. |
+
+ ### Data directories and paths
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DATA_DIR` | `get_default_data_dir()` | `src/constants.py:56` (+1 more) | Root directory for every persisted file. Prefer this over the per-path overrides; the rest of `src/constants.py` derives from it. |
+ | `ODYSSEUS_MAIL_ATTACHMENTS_DIR` | `os.path.join(DATA_DIR, 'mail-attachments')` | `src/constants.py:102` | Dedicated override for the mail attachment store, which otherwise lives under the data directory. |
+
+ ### Model routing and providers
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_COPILOT_API_VERSION` | `'2026-06-01'` | `src/copilot.py:39` | Dated API-version header the Copilot models and chat endpoints require. |
+ | `ODYSSEUS_COPILOT_CLIENT_ID` | `'01ab8ac9400c4e429b23'` | `src/copilot.py:34` | GitHub OAuth client id for the Copilot device flow. The default is the public VS Code client id; override it only with your own allow-listed app. |
+ | `ODYSSEUS_DEEPSEEK_REASONING_EFFORT` | `'high'` | `src/llm_core.py:1727` | Reasoning effort for DeepSeek. Only `high` and `max` are accepted; any other value falls back to the default. |
+ | `ODYSSEUS_FIRST_TOKEN_TIMEOUT` | `''` | `src/llm_core.py:223` | Seconds to wait for the first streamed token from a local endpoint before failing. Unset keeps the generous read timeout, which makes a stalled backend look like a hung agent. |
+ | `ODYSSEUS_LOCAL_MODEL_GATE` | `'true'` | `src/llm_core.py:95` | On by default. Set 0, false, no or off to drop the gate that checks a local endpoint before routing a request to it. |
+ | `ODYSSEUS_MISTRAL_REASONING_EFFORT` | `'high'` | `src/llm_core.py:1723` | Reasoning effort sent to Mistral thinking-capable models. The API accepts high, medium, low and none. |
+ | `ODYSSEUS_MLX_IMAGE_VLM_MODEL` | *unset* | `scripts/mlx_image_server.py:299` | Vision-language model id for the MLX image server script. Required unless `--vlm-model` is passed on the command line. |
-| `ODYSSEUS_QWEN_ROUTE_THINKING` | `'auto'` | `src/agent_loop.py:166` | Thinking policy for the Qwen routing step. An unrecognized value falls back to `auto`. |
++| `ODYSSEUS_QWEN_ROUTE_THINKING` | `'auto'` | `src/agent_loop.py:169` | Thinking policy for the Qwen routing step. An unrecognized value falls back to `auto`. |
+
+ ### Agent loop and tool execution
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DISABLE_MCP` | `''` | `src/builtin_mcp.py:89` | Truthy disables MCP entirely, as an escape hatch for compatibility problems with a server. |
-| `ODYSSEUS_MAX_VISUAL_EVIDENCE_FRAMES` | `'3'` | `src/agent_loop.py:15366` | How many video frames one tool result may contribute. Clamped to 1-8. |
-| `ODYSSEUS_MAX_VISUAL_EVIDENCE_IMAGES` | `'1'` | `src/agent_loop.py:15334` | How many images one tool result may contribute to the model turn. Clamped to 1-8. |
++| `ODYSSEUS_MAX_VISUAL_EVIDENCE_FRAMES` | `'3'` | `src/agent_loop.py:15361` | How many video frames one tool result may contribute. Clamped to 1-8. |
++| `ODYSSEUS_MAX_VISUAL_EVIDENCE_IMAGES` | `'1'` | `src/agent_loop.py:15329` | How many images one tool result may contribute to the model turn. Clamped to 1-8. |
+ | `ODYSSEUS_MCP_ALLOWED_COMMANDS` | `''` | `src/agent_tools/admin_tools.py:140` | Security-relevant. Comma-separated allowlist of MCP launcher basenames the agent may start. Empty by default, and the deny list still wins. |
-| `ODYSSEUS_PYTHON_TOOL_SITE_PACKAGES` | `''` | `src/agent_tools/subprocess_tools.py:925` | Security-relevant. Absolute package roots, separated by the platform path separator, exposed to the sandboxed Python tool. Empty exposes none. |
++| `ODYSSEUS_PYTHON_TOOL_SITE_PACKAGES` | `''` | `src/agent_tools/subprocess_tools.py:927` | Security-relevant. Absolute package roots, separated by the platform path separator, exposed to the sandboxed Python tool. Empty exposes none. |
+ | `ODYSSEUS_SCRIPT_HOST` | `'localhost'` | `src/builtin_actions.py:919` | Default host for the run-script action. `localhost`, `127.0.0.1`, `local` and empty run locally; any other value runs over SSH. |
+ | `ODYSSEUS_TOOL_APPROVAL_GATE` | `'0'` | `src/tool_capabilities.py:645` | Security-relevant. Truthy makes tool calls pass through the approval gate. Off by default. |
+
+ ### Browser automation
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_BROWSER_EXECUTABLE` | `''` | `src/builtin_mcp.py:114` | Absolute path to the Chrome or Chromium binary. Empty searches the usual names, then lets Playwright MCP pick its own browser. |
+ | `ODYSSEUS_BROWSER_ISOLATED` | `'1'` | `src/builtin_mcp.py:139` | Security-relevant. On by default, adding `--isolated` so each browser session starts clean. Set 0, false or no to keep a persistent profile. |
+ | `ODYSSEUS_BROWSER_MCP_CACHE` | `os.path.join(base_dir, 'data', 'local', 'playwright-mcp-cache')` | `src/builtin_mcp.py:229` | Cache directory handed to the browser MCP server, so its npm download survives a container rebuild. |
+ | `ODYSSEUS_BROWSER_MCP_REQUIRE_CACHE` | `''` | `src/builtin_mcp.py:90` | Truthy refuses to start the browser MCP server unless its npm package is already in the npx cache, instead of installing it at startup. |
+ | `ODYSSEUS_BROWSER_NAMESPACE` | `'odysseus-ui'` | `src/agent_tools/web_tools.py:2441` (+5 more) | Namespace for the detached agent-browser daemon's pid files, so two runtimes on one machine do not terminate each other's browsers. |
+ | `ODYSSEUS_BROWSER_NO_SANDBOX` | `'1'` | `src/builtin_mcp.py:142` | Security-relevant. On by default, adding `--no-sandbox` because the Docker image cannot use the Chromium sandbox. Set 0, false or no to keep it. |
+ | `ODYSSEUS_BROWSER_SCREENSHOT_DIR` | *unset* | `src/agent_tools/web_tools.py:3135` | Where private-browser screenshots are written. Falls back to the container path, then the system temp directory. |
+
+ ### Container and workspace mounts
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_WORKSPACE_CONTAINER_ROOT` | *unset* | `src/workspace_paths.py:31` | Container-side root that the host root maps onto. An `or` fallback, not a read default, supplies `/workspace` when it is unset. |
+ | `ODYSSEUS_WORKSPACE_DEFAULT` | `''` | `routes/workspace_routes.py:97` | Default workspace path the admin-only workspace route reports. Empty means no default is configured. |
+ | `ODYSSEUS_WORKSPACE_HOST_ROOT` | *unset* | `src/workspace_paths.py:29` | Single host-side root, paired with the container root below. Simpler than the explicit mount list when there is only one mount. |
+ | `ODYSSEUS_WORKSPACE_MOUNTS` | `''` | `src/workspace_paths.py:19` | `host=container` path pairs separated by commas or semicolons, so the agent can translate a container path back to the host path a user typed. |
+
+ ### Email
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_DOCUMENT_OWNER` | `''` | `mcp_servers/email_server.py:208` | Owner stamped on documents the email MCP server creates. Stdio MCP tools get no authenticated user, so without this a draft is invisible. |
+ | `ODYSSEUS_IMAP_TIMEOUT_SECONDS` | *unset* | `routes/email/email_helpers.py:1163` | IMAP socket timeout in seconds, clamped to 5-300. A non-numeric value falls back to 30 rather than failing. |
+
+ ### Calendar, notes and single-user mode
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_ALLOW_PRIVATE_CALDAV` | `'0'` | `src/caldav_sync.py:52` | Security-relevant. Truthy lets CalDAV sync reach private and link-local addresses. Off by default; this is an SSRF guard. |
+ | `ODYSSEUS_FALLBACK_OWNER` | `'owner@localhost'` | `routes/calendar_routes.py:65` | Owner address that single-user mode attributes an unauthenticated request to. Only reachable while single-user mode is on. |
+ | `ODYSSEUS_SINGLE_USER` | `'1'` | `routes/calendar_routes.py:66` | Security-relevant. On by default. Set to 0 on a real multi-user install so unauthenticated calendar writes are rejected rather than absorbed. |
+
+ ### Upload and media limits
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_CHAT_UPLOAD_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:33` | Maximum bytes accepted for a chat attachment. |
+ | `ODYSSEUS_EDITOR_DRAFT_MAX_BYTES` | `256 * 1024 * 1024` | `src/upload_limits.py:47` | Maximum bytes accepted for a saved editor draft. |
+ | `ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:56` | Maximum bytes accepted for an attachment added while composing mail. |
+ | `ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:44` (+1 more) | Maximum bytes accepted for an image handed to a gallery transform. |
+ | `ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES` | `100 * 1024 * 1024` | `src/upload_limits.py:41` (+1 more) | Maximum bytes accepted for a gallery upload. |
+ | `ODYSSEUS_ICS_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:62` | Maximum bytes accepted for an imported ICS file. |
+ | `ODYSSEUS_MEDIA_FRAME_TIMEOUT` | `30` | `src/media_ingress.py:146` | Seconds allowed for extracting frames from a video before giving up. |
+ | `ODYSSEUS_MEDIA_MAX_AUDIO_BYTES` | `32 * 1024 * 1024` | `src/media_ingress.py:129` | Largest source audio file the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_DIMENSION` | `1600` | `src/media_ingress.py:138` | Longest edge in pixels an image is resized down to before encoding. |
+ | `ODYSSEUS_MEDIA_MAX_DOCUMENT_BYTES` | `32 * 1024 * 1024` | `src/media_ingress.py:126` | Largest source document the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_DOCUMENT_CHARS` | `24000` | `src/media_ingress.py:135` | How many characters of an ingested document are inlined into the turn. |
+ | `ODYSSEUS_MEDIA_MAX_ENCODED_BYTES` | `24 * 1024 * 1024` | `src/media_ingress.py:132` | Budget for the encoded payload handed to the model, counted cumulatively across one turn's attachments rather than per file. |
+ | `ODYSSEUS_MEDIA_MAX_FILES` | `4` | `src/media_ingress.py:119` | How many local media files one agent turn may ingest. |
+ | `ODYSSEUS_MEDIA_MAX_IMAGE_BYTES` | `12 * 1024 * 1024` | `src/media_ingress.py:120` | Largest source image the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_PIXELS` | `40000000` | `src/media_ingress.py:139` | Total pixel budget for a source image, as a decompression-bomb guard. |
+ | `ODYSSEUS_MEDIA_MAX_VIDEO_BYTES` | `128 * 1024 * 1024` | `src/media_ingress.py:123` | Largest source video the media pipeline will read. |
+ | `ODYSSEUS_MEDIA_MAX_VIDEO_FRAMES` | `8` | `src/media_ingress.py:140` | How many frames are sampled from a video. |
+ | `ODYSSEUS_MEDIA_PROBE_TIMEOUT` | `15` | `src/media_ingress.py:143` | Seconds allowed for probing a video's metadata before giving up. |
+ | `ODYSSEUS_MEMORY_IMPORT_MAX_BYTES` | `10 * 1024 * 1024` | `src/upload_limits.py:50` (+1 more) | Maximum bytes accepted for a memory import file. |
+ | `ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:53` (+1 more) | Maximum bytes accepted for a personal-documents upload. |
+ | `ODYSSEUS_STT_MAX_AUDIO_BYTES` | `25 * 1024 * 1024` | `src/upload_limits.py:59` | Maximum bytes accepted for an audio file submitted for transcription. |
+
+ ### Search
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_SEARCH_PROVIDER` | `''` | `services/search/providers.py:43` | Forces the search provider, overriding the Settings value. Empty keeps the UI authoritative, which is what a normal install wants. |
+
+ ### Memory and skills
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_SKILL_SEMANTIC_RETRIEVAL` | `'1'` | `services/memory/skills.py:789` | On by default. Set 0, false, no or off to fall back to keyword-only skill retrieval when no vector store is reachable. |
+ | `ODYSSEUS_SKILL_SEMANTIC_THRESHOLD` | `'0.4'` | `services/memory/skills.py:800` | Minimum semantic score a skill needs to be retrieved. A non-numeric value falls back to the default. |
+
+ ### Speech and vision models
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_GROUNDING_MODEL` | `'google/owlvit-base-patch32'` | `routes/gallery/gallery_routes.py:95` | Object-grounding model id the gallery loads for text-driven selection. |
+ | `ODYSSEUS_SAM_MODEL` | `'facebook/sam-vit-base'` | `routes/gallery/gallery_routes.py:59` | Segmentation model id the gallery loads for subject selection. |
+ | `ODYSSEUS_STT_MODEL` | *unset* | `src/agent_tools/media_tools.py:2184` | Default speech-to-text model for media transcription when the tool call does not name one. |
+ | `ODYSSEUS_TTS_CACHE_MAX_BYTES` | `500 * 1024 * 1024` | `services/tts/tts_service.py:47` | Cap on the synthesized-speech cache. A non-numeric value falls back to the default. |
+
+ ### Auth and internal API
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_INTERNAL_BASE` | *unset* | `src/constants.py:178` | Base URL the in-app tool layer uses for loopback HTTP calls. Set it when the app is not reachable at the port it thinks it is bound to. |
+ | `ODYSSEUS_INTERNAL_TOKEN` | *unset* | `core/middleware.py:20` | Security-relevant. Token that lets the in-app tool layer reach admin-gated routes over loopback. Unset generates a fresh per-process token, which is what you want unless something outside the process needs the same value. |
+
+ ### Integrations (Claude, Codex)
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_API_TOKEN` | `''` | `integrations/claude/skills/odysseus/scripts/odysseus_api.py:40` (+1 more) | API token those scripts authenticate with. Both this and the URL are required; the scripts name whichever is missing. |
+ | `ODYSSEUS_URL` | `''` | `integrations/claude/skills/odysseus/scripts/odysseus_api.py:39` (+1 more) | Base URL of the Odysseus instance the bundled integration scripts call. |
+
+ ## Internal and development-only variables
+
+ Listed for completeness. Setting one of these on a real install is either a no-op or a way to break something quietly.
+
+ ### Model routing and providers
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_COPILOT_EDITOR_VERSION` | `'Odysseus/1.0'` | `src/copilot.py:54` | Editor-version header presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_COPILOT_INTEGRATION_ID` | `'vscode-chat'` | `src/copilot.py:51` | Integration id presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_COPILOT_USER_AGENT` | `'Odysseus/1.0'` | `src/copilot.py:48` | Editor-like User-Agent presented to the Copilot API. Kept stable on purpose. |
+ | `ODYSSEUS_DEBUG_LLM_SHAPE` | `''` | `src/llm_core.py:3552` (+1 more) | Truthy logs the shape of streamed provider chunks. Debugging aid for provider response parsing. |
+
+ ### Agent loop and tool execution
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
-| `ODYSSEUS_CAPTURE_MODEL_REQUESTS` | `''` | `src/agent_loop.py:3921` | Truthy writes model-request snapshots for local debugging. The marker file `/tmp/odysseus_capture_model_requests` enables the same thing. |
-| `ODYSSEUS_EXPOSE_RAW_BROWSER_MCP` | `''` | `src/agent_loop.py:4126` | Truthy stops hiding the raw Playwright MCP tools from agent prompts when the private-browser tool is available. |
++| `ODYSSEUS_CAPTURE_MODEL_REQUESTS` | `''` | `src/agent_loop.py:3924` | Truthy writes model-request snapshots for local debugging. The marker file `/tmp/odysseus_capture_model_requests` enables the same thing. |
++| `ODYSSEUS_EXPOSE_RAW_BROWSER_MCP` | `''` | `src/agent_loop.py:4129` | Truthy stops hiding the raw Playwright MCP tools from agent prompts when the private-browser tool is available. |
+ | `ODYSSEUS_TOOL_CONTRACT_ROOT` | `'<repo>/scripts'` | `src/clean_agent_preview.py:2183` (+1 more) | Directory holding the tool-contract scripts the clean-agent preview loads. The default is the repository's bundled scripts directory; set the variable to override it. |
+
+ ### Email
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_EMAIL_FIXTURE` | *unset* | `mcp_servers/email_server.py:1122` (+7 more) | Exactly `1`, plus a fixture file on disk, makes the email MCP server serve fixtures instead of a real mailbox. |
+
+ ### Testing, capture and development tooling
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_AJAX_TEST_URL` | *unset* | `tests/test_ajax_email_live.py:17` (+4 more) | Chat-completions URL of a live Ajax endpoint. Unset skips the opt-in live Ajax email tests. |
+ | `ODYSSEUS_EDITOR_ACTIONS` | `','.join([*actions, 'edit', 'update'])` | `tests/tools/editor_writing_smoke.py:71` | Comma-separated writing actions the editor-writing smoke tool runs. Unset runs every action plus edit and update. |
+ | `ODYSSEUS_EDITOR_MAX_TOKENS` | `'4096'` | `tests/tools/editor_writing_smoke.py:110` | Completion token limit for each editor-writing smoke request. |
+ | `ODYSSEUS_EDITOR_RICH_FIXTURE` | *unset* | `tests/tools/editor_writing_smoke.py:80` | Set to 1 to run the editor-writing smoke tool against a rich-text document fixture instead of Markdown. |
+ | `ODYSSEUS_EDITOR_TEST_ENDPOINT` | *unset* | `tests/tools/editor_writing_smoke.py:110` (+1 more) | Chat-completions URL the opt-in editor-writing and organizer smoke tools drive. Both tools require it. |
+ | `ODYSSEUS_EDITOR_TRACE` | *unset* | `tests/tools/editor_writing_smoke.py:140` | Any non-empty value prints every stream event after each editor-writing smoke action. |
+ | `ODYSSEUS_ORGANIZER_AUTO_CHOICE` | *unset* | `tests/tools/organizer_smoke.py:199` | With organizer tracing on, any non-empty value replaces forced tool choice with auto on traced requests. |
+ | `ODYSSEUS_ORGANIZER_CASES` | *unset* | `tests/tools/organizer_smoke.py:223` (+1 more) | Comma-separated organizer smoke case names to run. Unset runs every case. |
+ | `ODYSSEUS_ORGANIZER_TRACE` | *unset* | `tests/tools/organizer_smoke.py:193` | Any non-empty value prints each provider request the organizer smoke tool sends. |
+ | `ODYSSEUS_ORGANIZER_TRACE_MESSAGES` | *unset* | `tests/tools/organizer_smoke.py:203` | With organizer tracing on, any non-empty value also prints the request messages. |
+ | `ODYSSEUS_QA_TEACHER_ATTEMPTS` | `'3'` | `scripts/odysseus_conversation_qa.py:370` | Retry budget for the conversation-QA teacher model call. Clamped to 1-3. |
+ | `ODYSSEUS_QA_TEACHER_TIMEOUT` | `'120'` | `scripts/odysseus_conversation_qa.py:372` | Timeout in seconds for that call. Clamped to 15-120. |
+ | `ODYSSEUS_RUNTIME_REVISION` | `''` | `routes/chat_helpers.py:198` (+1 more) | Revision string stamped into each captured SFT trace record, so a trace can be tied back to the build that produced it. |
-| `ODYSSEUS_SFT_DISABLE_WORKSPACE_TOOLS` | `'1'` | `src/agent_loop.py:7404` | On by default. Keeps synthetic personal-assistant fixtures out of workspace mode; set 0, false, no or off to let them through. |
++| `ODYSSEUS_SFT_DISABLE_WORKSPACE_TOOLS` | `'1'` | `src/agent_loop.py:7407` | On by default. Keeps synthetic personal-assistant fixtures out of workspace mode; set 0, false, no or off to let them through. |
+ | `ODYSSEUS_SFT_FORCE_UTC_TIMEZONE` | `'0'` | `routes/chat_routes.py:2070` | Truthy forces `sft_` accounts to UTC for deterministic batch generation. Interactive accounts still follow the browser timezone. |
+ | `ODYSSEUS_SFT_TRACE_CAPTURE` | `'1'` | `routes/chat_helpers.py:161` (+1 more) | On by default, but only for owners whose name starts with `sft_`. Set 0, false, no or off to stop writing training traces. |
+ | `ODYSSEUS_SFT_TRACE_DIR` | *unset* | `routes/chat_helpers.py:195` (+2 more) | Directory the SFT trace JSONL files are written to. Defaults to `sft_traces` under the data directory. |
+ | `ODYSSEUS_SKIP_RUN_HINT` | *unset* | `setup.py:284` | Any non-empty value suppresses the `start the server with` hint at the end of setup. `start-macos.sh` sets it because it starts the server itself. |
+ | `ODYSSEUS_TEST_STATIC_ORIGIN` | *unset* | `scripts/css_snapshot.py:254` (+6 more) | Origin an already-running static server is serving the repository from, so snapshot tooling reuses it instead of starting its own. |
+ | `ODYSSEUS_TEST_STATIC_PORT` | *unset* | `tests/conftest.py:137` | Fixed port for the test suite's static server. Unset takes an ephemeral port, which is what keeps parallel runs from colliding. |
+
+ ### Build and release metadata
+
+ | Variable | Default | Read in | What it does |
+ |---|---|---|---|
+ | `ODYSSEUS_BUILD_VERSION` | `''` | `src/constants.py:15` | Overrides the build-version string the API and UI report, without touching the public application version. |
+ | `ODYSSEUS_SOURCE_COMMIT` | `''` | `src/constants.py:33` | Overrides the source commit reported for runtime provenance, for builds that ship without a git directory. |
+
+ ## How this page is generated
+
+ The generator walks the Python sources under `app.py`, `launcher.py`, `setup.py`, `companion`, `config`, `core`, `integrations`, `mcp_servers`, `routes`, `scripts`, `services`, `src`, `tests` and finds
+ reads three ways, because no single pattern covers the codebase:
+
+ - Direct reads: `os.getenv(...)`, and any `.get` / `.setdefault` / `.pop` call or
+ subscript keyed by an `ODYSSEUS_*` literal, including names held in a
+ module-level constant. The receiver is not required to be `os.environ`, because
+ several call sites read through a mapping passed in as an argument
+ (`src/tool_index.py`, `src/host_docker_access.py`).
+ - Calls to env-reader helpers - any function that forwards one of its own
+ parameters to an environment read. This is detected rather than hardcoded, so a
+ new helper needs no change here. It is what finds the upload caps in
+ `src/upload_limits.py` and the media-ingress overrides in
+ `src/media_ingress.py`.
+ - A regex sweep of the raw file text, for reads the AST cannot see.
+ `routes/cookbook_helpers.py` builds an Ollama probe script as a list of source
+ lines, so one read lives inside a string literal.
+
+ The three passes are not redundancy. A line-based grep for a direct
+ `os.environ.get("ODYSSEUS_...` call finds 80 of the 108 variables on this
+ page. What it misses is reads through an env-reader helper, reads whose call
+ spans more than one line, reads whose variable name is held in a module
+ constant, and reads through a mapping passed in as an argument - which is the
+ whole reason this page is generated rather than maintained.
+
+ The `Default` column shows the expression as written, with one level of
+ indirection resolved: a module-level constant and a dataclass field default are
+ replaced by the literal they hold, so `defaults.max_media_files` shows as `4`.
+ Anything computed at import time - `get_default_data_dir()` - is shown as
+ written, because that is the honest answer. A few call sites supply their
+ fallback with `or` rather than a default argument; those show as *unset* and say
+ so in the last column.
+
+ Regenerate it with:
+
+ ```bash
+ python3 scripts/generate_env_reference.py
+ ```