feat(logging): self-diagnosing EXPLORE + shared/ absorption + belief analytics (ADR-0021/0022)

T0: absorb shared/ into backend — cot_logger→src/core, CotJsonFormatter→src/core/cot_formatter.py, _llm_http/_llm_health/ssl→src/core/utils; imports rewritten (26 prod + tests, patch targets); run.sh/backend.Dockerfile/requirements/.axiom source_dirs/semantic_health/AGENTS/INSTALL cleaned; ADR-0022 supersedes ADR-0015; fixed latent CI defects (ss_tools ImportError, record.message in logger tests, same-name test-module collision).

ADR-0021 wire enrichment (additive): contract_id/claim/error_code/loc fields; _contract_id ContextVar + resolve_contract_id (explicit > belief_scope > declared-src mirror, derived src never mirrors); EXPLORE auto-loc via single frame walk; facade error auto-fill; 2KB payload cap with payload_truncated/payload_bytes markers; migrated 85 error="CODE" sites to error_code= (12 files); pilot editor/load.py; superset preview payload-bomb inlined bodies removed.

Analytics SSOT src/core/log_stats.py (bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, intent families, coverage, insufficient-sample flag); pretty_cot.py --stats/--digest/--trajectory/--story over one engine; log_gap_service three-tier ground-truth triangulation (FAILED w/o EXPLORE etc.) + GET /api/reports/log-stats|task-log-gaps (polling-suppressed); scripts/cot_audit.py CLI; enriched fields persisted into task_logs.payload for tier queries.

Frontend: ReportsAnalyticsModel + AnalyticsStatsPanel (Logs tab) + TaskGapPanel and per-row T1/T2/T3 gap badges (Tasks tab); cot-logger.ts ADR-0021 opts; i18n en/ru. Scheduler console spam fixed: apscheduler logger demoted to WARNING via LoggingConfig.scheduler_log_level. .axiom belief patterns -> $OBJ.* (alias undercount). molecular-cot-logging skill updated (fields, decision rules, tie-break, CLI) and synced.

Reviewed orthogonally: F1 cot_span contract pollution, F2 cap boundary accounting, F3 digest over-dedup, F4 trace-state bound, F5 tier metadata — fixed with regression tests. Validation: backend 11287 passed + ruff + compileall; frontend 3446 passed + lint + build; CLI smoke on live app.log.
This commit is contained in:
2026-09-04 20:56:41 +03:00
parent 34a6507fa3
commit 65121cac6b
97 changed files with 3390 additions and 686 deletions

View File

@@ -4,13 +4,13 @@ description: Structured logging protocol for agent-driven development, based on
---
#region Std.Semantics.MolecularCoTLogging [C:5] [TYPE Skill] [SEMANTICS reasoning,runtime,logging,agentic]
@BRIEF Structured logging protocol for agent-driven development, based on molecular Long CoT bonds (Deep-Reasoning, Self-Reflection, Self-Exploration). Replaces legacy Entry/Exit/Coherence markers. Wire format is specified here; the Python implementation lives in `ss_tools.shared.cot_logger`.
@BRIEF Structured logging protocol for agent-driven development, based on molecular Long CoT bonds (Deep-Reasoning, Self-Reflection, Self-Exploration). Replaces legacy Entry/Exit/Coherence markers. Wire format is specified here; the Python implementation lives in `backend/src/core/cot_logger.py` (SSOT primitives), facade `src.core.logger`, formatter `src.core.cot_formatter` (ADR-0022 absorbed the former shared/ package).
@RELATION DEPENDS_ON -> [Std.Semantics.Core]
@RELATION DISPATCHES -> [Std.Semantics.Python]
@RELATION DISPATCHES -> [Std.Semantics.Svelte]
@RATIONALE Long CoT chains need stabilisation through explicit reasoning bonds. The three-marker system (REASON/REFLECT/EXPLORE) maps directly to the molecular CoT paper and produces machine-readable execution traces that LLM agents can parse, analyse, and use for fine-tuning (MoLE-Syn bond distributions). Without structured markers, agent-generated code exhibits invisible failures: a function returns `None` instead of raising — the agent's attention never sees it because there's no log; a fallback path activates silently — no EXPLORE marker, no trace. JSON-line format ensures every log entry is a self-contained, parseable unit that survives log rotation, aggregation, and agent parsing — unlike plain-text logs that require regex heuristics.
@REJECTED Legacy Entry/Exit/Action/Coherence markers rejected — they are too generic, do not map to reasoning structure, and prevent traceability graph analysis. Plain-text logging rejected — JSON lines are mandatory for agent parsing. Unstructured printf-style logging rejected — agents cannot reliably extract structured fields (trace_id, marker, intent) from free-form text, making automated diagnosis impossible. cot_span decorator rejected — replaced by belief_scope context manager + logger.reason/reflect/explore which gives more granular intent control per logical branch.
@DATA_CONTRACT LogEntry -> { ts: str, level: str, trace_id: str, span_id?: str, src: str, marker: REASON|REFLECT|EXPLORE, intent: str, payload?: object, error?: str }
@DATA_CONTRACT LogEntry -> { ts: str, level: str, trace_id: str, span_id?: str, src: str, marker: REASON|REFLECT|EXPLORE, intent: str, payload?: object (~2KB cap, payload_truncated/payload_bytes markers), error?: str, contract_id?: str, claim?: str, error_code?: str, loc?: str, elapsed_ms?: float, task_id?: str }
@INVARIANT Every log line MUST carry exactly one valid marker (REASON | REFLECT | EXPLORE). No markerless log lines in C4/C5 code.
@INVARIANT trace_id MUST propagate via ContextVar across async boundaries. Every incoming request or background job seeds a new trace_id.
@@ -43,8 +43,14 @@ Every log record MUST be a JSON object **on a single line** with the following k
| `src` | yes | string | Qualified function name, e.g. `AuthRepository.get_user_by_username` |
| `marker` | yes | string | One of `REASON`, `REFLECT`, `EXPLORE` (see below) |
| `intent` | yes | string | Human-readable one-line description of what this step intends to do/verify |
| `payload` | no | object | Arbitrary key-value data relevant to the step (params, result snippet) |
| `error` | conditional | string | Error message or reason. **Optional** for `REASON`/`REFLECT`, **required** for `EXPLORE` markers when a fallback or violation is taken |
| `payload` | no | object | Arbitrary key-value data relevant to the step (params, result snippet). Hard cap ~2KB: oversized payloads are truncated with `payload_truncated: true` + `payload_bytes` (ADR-0021/D5). Full bodies belong in evidence/task stores — reference them by id, never inline |
| `error` | conditional | string | Error message or reason. **Optional** for `REASON`/`REFLECT`; for `EXPLORE` auto-filled from `intent` when omitted — the falsification channel is never silent |
| `contract_id` | no | string | GRACE contract ID. Resolution (SSOT `resolve_contract_id`): explicit kwarg > `belief_scope` binding > mirror of the **declared** `src` (`_SRC` convention). Derived src never mirrors |
| `claim` | no | string | ≤ ~60-char pointer to the violated/verified declaration (`"PRE: scenario_id exists"`). Verbatim copies of @PRE/@POST are forbidden — the digest resolves `loc` to the full contract context |
| `error_code` | no | string | `<MODULE_PREFIX>_<SCREAMING_SNAKE>` machine-readable failure class for digest grouping (`EDITOR_SCENARIO_NOT_FOUND`, `CAPACITY_LEASE_NOT_ACTIVE`) |
| `loc` | no | string | EXPLORE only, auto-derived: `file:line` of the violated branch (repo-relative) |
| `elapsed_ms` | no | number | Auto: REASON records entry time; REFLECT/EXPLORE on the same (trace, src) emit the delta |
| `task_id` | no | string | Stamped by the formatter when a task context is bound — correlates app lines with `task_logs` |
### Example
@@ -59,7 +65,8 @@ Real wire line produced by `backend/src/services/mcp_ops_dispatch.py`:
### REASON (Deep-Reasoning)
- **When**: BEFORE an operation that extends the logical chain (DB query, API call, computation).
- **Level**: `INFO` by default, `DEBUG` for high-frequency loops.
- **`intent`**: Describes what the code is about to do.
- **`intent`**: Describes what the code is about to do. **Intent invariance**: no interpolated values in intent (they fragment digest grouping) — dynamic data goes to `payload`.
- **Event sufficiency**: a no-op tick of an idle loop is not an event (self-loop with zero informed value). Emit conditionally (only when something happened) or at `level="DEBUG"` — "no news, no tokens".
- **`payload`**: Input parameters, context values.
- **Effect**: This is the primary "deep-reasoning" step that forms the backbone of the trace.
@@ -73,6 +80,7 @@ logger.reason("Dispatching approved create_branch", src=_SRC,
- **When**: AFTER an operation to **verify the outcome** or check invariants.
- **Level**: `INFO` on success, `WARNING` if invariants partially degrade.
- **`intent`**: Describes what is being verified.
- **`claim`**: only for declared checkpoints (`"POST: rows written"` — verifying a @POST/@INVARIANT), not on every "completed" line.
- **`payload`**: Result summary, status codes, row counts.
- **Effect**: Folds the logical chain back on itself — the agent sees cause + effect in two adjacent lines.
@@ -83,20 +91,30 @@ logger.reflect("Lease heartbeat applied", src=_SRC,
```
### EXPLORE (Self-Exploration)
- **When**: An expected condition is **violated** and the code enters a fallback, error handler, or alternative path.
- **When**: An expected condition is **violated** and the code enters a fallback, error handler, or alternative path. Also the canonical marker for contract-legitimate misses (e.g. `@POST` sanctions returning None) — the violation is the **absence of a trace**, not the None itself.
- **Level**: `WARNING` for recoverable fallbacks, `ERROR` for unrecoverable failures.
- **`intent`**: Describes what assumption failed.
- **`intent`**: Describes what assumption failed (invariant text, no interpolation).
- **`claim`**: which declaration was violated (`"PRE: scenario_id exists"`).
- **`error_code`**: machine-readable class; the code lives HERE, while `error` carries the human sentence.
- **`payload`**: Relevant state at the branch point.
- **`error`**: **Required.** Explain what assumption was violated.
- **Effect**: Creates a branch in the trace — a future agent can see why the happy path was not taken.
- **`error`**: violated assumption; auto-filled from `intent` when omitted.
- **`loc`**: auto-derived file:line of the branch — do not pass manually.
- **Effect**: Creates a branch in the trace — a future agent can see why the happy path was not taken, which contract to open, and which declaration to re-check.
```python
# backend/src/services/dashboard_testing/execution/capacity.py
logger.explore("Claim rejected: unknown workload class", src=_SRC,
payload={"workload_class": workload_class},
error="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
# backend/src/services/dashboard_testing/editor/load.py
logger.explore("Scenario not found for editor load", src=_SRC,
claim="PRE: scenario_id exists",
error_code="EDITOR_SCENARIO_NOT_FOUND",
payload={"scenario_id": scenario_id},
error="no registry entry by scenario_id or scenario_key")
```
**Marker decision rules** (adapted from the Molecular CoT annotation protocol): label by the
behavioral style of the step, not by its correctness; on mixed intent choose the dominant one;
tie-break priority is **EXPLORE > REFLECT > REASON** — EXPLORE is the non-suppressible
falsification channel (deliberate inversion of the paper's self-reflection-first order).
### Quick Reference
| Situation | Marker | Level | `error` field |
@@ -117,30 +135,31 @@ logger.explore("Claim rejected: unknown workload class", src=_SRC,
## III. Trace Propagation (Python)
**SSOT implementation:** `shared/src/ss_tools/shared/cot_logger.py` (`ss_tools.shared.cot_logger`) — ContextVars (`trace_id`/`span_id`/`task_id`), `build_cot_event`, and the `log(src, marker, intent, ...)` primitive. Do not copy the logger into skills or call sites.
**SSOT implementation:** `backend/src/core/cot_logger.py` (`src.core.cot_logger`) — ContextVars (`trace_id`/`span_id`/`task_id`/`contract_id`), `build_cot_event`, `resolve_contract_id`, and the `log(src, marker, intent, ...)` primitive; the JSON formatter lives in `src/core/cot_formatter.py`. Do not copy the logger into skills or call sites. (The former `shared/` package was absorbed into backend per ADR-0022.)
**Single call-site convention — the intent-first facade, identical in both layers:**
**Single call-site convention — the intent-first facade:**
```python
# backend (backend/src/**):
from src.core.logger import belief_scope, logger
# shared layer (shared/src/**):
from ss_tools.shared.logger import logger
logger.reason("Dispatching approved create_branch", src=_SRC, payload={"dashboard_id": dashboard_id})
logger.reflect("Lease heartbeat applied", src=_SRC, payload={"lease_id": lease_id})
logger.explore("Claim rejected: unknown workload class", src=_SRC,
payload={"workload_class": workload_class}, error="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
logger.explore("Claim rejected: unknown workload class", src=_SRC, claim="PRE: workload class known",
error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS", payload={"workload_class": workload_class})
# level= overrides the record level for high-frequency plumbing lines:
logger.reason("Scheduler lifecycle: maintenance auto-end executed", src=_SRC, level="DEBUG")
# belief_scope binds the contract: anchor_id IS the GRACE contract ID, nested events inherit contract_id
with belief_scope("Core.Auth.Login", claim="POST: token issued"):
...
```
Facade rules (implemented in `src/core/logger.py` / `shared/.../logger.py`):
Facade rules (implemented in `src/core/logger.py`):
- the FIRST positional binds as `intent`; `src=`, `payload=`, `error=`, `level=` are keywords;
- the FIRST positional binds as `intent`; `src=`, `payload=`, `error=`, `level=`, `contract_id=`, `claim=`, `error_code=` are keywords;
- a single dict positional after the intent is promoted to `payload` (legacy shape, still valid);
- `src` omitted → derived from the call stack (`derive_src`); prefer an explicit `_SRC` contract id;
- `src` omitted → derived from the call stack (`derive_src`); prefer an explicit `_SRC` contract id — it also mirrors into `contract_id`;
- EXPLORE auto-derives `loc` (file:line) in the same frame walk;
- `reason`/`reflect` apply the central routine-infra suppression (`is_routine_infra`).
**The SSOT primitive `log(src, marker, intent, ...)` is src-first and module-internal** — it powers
@@ -183,6 +202,7 @@ function log(
intent: string, // human-readable one-liner
payload?: Record<string, unknown>, // params, result snippet
error?: string, // required for EXPLORE
opts?: { contract_id?: string; claim?: string; error_code?: string }, // ADR-0021 fields
): void;
```
@@ -233,26 +253,30 @@ const res = await requestApi("/api/endpoint");
if (res.trace_id) setTraceId(res.trace_id);
```
## V. CLI / Stdout Reader (for humans)
## V. CLI / Analytics Reader (agent-first)
To make JSON lines readable in development:
`scripts/pretty_cot.py` is the canonical reader (engine: `backend/src/core/log_stats.py` —
the same engine powers `GET /api/reports/log-stats` and the Reports UI panels; never duplicate it):
```bash
# Pretty-print the last 50 CoT lines
tail -50 app.log | python3 -c "
import sys, json
for line in sys.stdin:
line = line.strip()
if not line: continue
rec = json.loads(line)
m = rec.get('marker','?')
icon = {'REASON':'→','REFLECT':'✓','EXPLORE':'⚠'}.get(m, '·')
err = f\" | {rec['error']}\" if 'error' in rec else ''
pay = f\" | {rec.get('payload','')}\" if 'payload' in rec else ''
print(f\"{icon} {rec['level']:7} {rec['src']} — {rec['intent']}{pay}{err}\")
"
python scripts/pretty_cot.py backend/logs/app.log --last 80 # narrative grouped by trace
python scripts/pretty_cot.py backend/logs/app.log --trace <id> --story # causal story ending in VERDICT
python scripts/pretty_cot.py backend/logs/app.log* --digest # prioritized EXPLORE fix-map
python scripts/pretty_cot.py backend/logs/app.log* --stats # economy + bond matrix + orphan ratio
python scripts/pretty_cot.py backend/logs/app.log* --trajectory <ContractId> # belief trajectory
python scripts/pretty_cot.py backend/logs/app.log --follow
```
Ground-truth invisible-failure audit (no parser — SQL facts; needs DATABASE_URL):
```bash
cd backend && .venv/bin/python ../scripts/cot_audit.py --task-log-gaps [--since-days 7] [--json]
```
Syntactic silence audit (swallowed except/catch/suppress — finding codes per ADR-0021) runs in
axiom-mcp: MCP tool `audit`, operation `audit_belief_runtime`. Frontend: Reports → Logs tab
(Belief analytics panel) and Reports → Tasks tab (Belief gaps tiers T1/T2/T3).
## VI. Anti-patterns
| ❌ Don't | ✅ Do |
@@ -265,5 +289,10 @@ for line in sys.stdin:
| `marker` without `intent` | Every marker has a human-readable `intent` |
| Logging raw passwords or tokens in `payload` | Always sanitise sensitive data |
| Spread markers across multiple modules without trace_id | Always propagate `trace_id` |
| Silent failure branch (`return None` / `except: pass` without a trace) | EXPLORE with `claim` + `error_code` — a contract-legitimate None still needs a trace line |
| Verbatim copy of @PRE/@POST text into `claim` | ≤ ~60-char pointer; the digest resolves loc → full contract context |
| Interpolated values in `intent` (f-string ids/counts) | Invariant `intent`; dynamic values in `payload` |
| Inline request/response bodies in `payload` | Evidence-ref id + short diagnostic (2KB cap truncates anyway) |
| No-op loop tick at INFO on every pass | Conditional emit or `level="DEBUG"` — "no news, no tokens" |
#endregion Std.Semantics.MolecularCoTLogging

View File

@@ -46,9 +46,6 @@ indexing:
- backend/tests
- frontend/src
- frontend/tests
- agent/src
- agent/tests
- shared/src
doc_dirs:
- docs
- specs
@@ -431,14 +428,17 @@ belief_runtime:
- 'belief_scope($$$)'
- 'believed($$$)'
reason_patterns:
- 'logger.reason($$$)'
- '$OBJ.reason($$$)'
- 'log($$$, "REASON", $$$)'
- 'cot_log($$$, "REASON", $$$)'
reflect_patterns:
- 'logger.reflect($$$)'
- '$OBJ.reflect($$$)'
- 'log($$$, "REFLECT", $$$)'
- 'cot_log($$$, "REFLECT", $$$)'
explore_patterns:
- 'logger.explore($$$)'
- '$OBJ.explore($$$)'
- 'log($$$, "EXPLORE", $$$)'
- 'cot_log($$$, "EXPLORE", $$$)'
ts:
reason_patterns:
- 'log($$$, "REASON", $$$)'

View File

@@ -4,13 +4,13 @@ description: Structured logging protocol for agent-driven development, based on
---
#region Std.Semantics.MolecularCoTLogging [C:5] [TYPE Skill] [SEMANTICS reasoning,runtime,logging,agentic]
@BRIEF Structured logging protocol for agent-driven development, based on molecular Long CoT bonds (Deep-Reasoning, Self-Reflection, Self-Exploration). Replaces legacy Entry/Exit/Coherence markers. Wire format is specified here; the Python implementation lives in `ss_tools.shared.cot_logger`.
@BRIEF Structured logging protocol for agent-driven development, based on molecular Long CoT bonds (Deep-Reasoning, Self-Reflection, Self-Exploration). Replaces legacy Entry/Exit/Coherence markers. Wire format is specified here; the Python implementation lives in `backend/src/core/cot_logger.py` (SSOT primitives), facade `src.core.logger`, formatter `src.core.cot_formatter` (ADR-0022 absorbed the former shared/ package).
@RELATION DEPENDS_ON -> [Std.Semantics.Core]
@RELATION DISPATCHES -> [Std.Semantics.Python]
@RELATION DISPATCHES -> [Std.Semantics.Svelte]
@RATIONALE Long CoT chains need stabilisation through explicit reasoning bonds. The three-marker system (REASON/REFLECT/EXPLORE) maps directly to the molecular CoT paper and produces machine-readable execution traces that LLM agents can parse, analyse, and use for fine-tuning (MoLE-Syn bond distributions). Without structured markers, agent-generated code exhibits invisible failures: a function returns `None` instead of raising — the agent's attention never sees it because there's no log; a fallback path activates silently — no EXPLORE marker, no trace. JSON-line format ensures every log entry is a self-contained, parseable unit that survives log rotation, aggregation, and agent parsing — unlike plain-text logs that require regex heuristics.
@REJECTED Legacy Entry/Exit/Action/Coherence markers rejected — they are too generic, do not map to reasoning structure, and prevent traceability graph analysis. Plain-text logging rejected — JSON lines are mandatory for agent parsing. Unstructured printf-style logging rejected — agents cannot reliably extract structured fields (trace_id, marker, intent) from free-form text, making automated diagnosis impossible. cot_span decorator rejected — replaced by belief_scope context manager + logger.reason/reflect/explore which gives more granular intent control per logical branch.
@DATA_CONTRACT LogEntry -> { ts: str, level: str, trace_id: str, span_id?: str, src: str, marker: REASON|REFLECT|EXPLORE, intent: str, payload?: object, error?: str }
@DATA_CONTRACT LogEntry -> { ts: str, level: str, trace_id: str, span_id?: str, src: str, marker: REASON|REFLECT|EXPLORE, intent: str, payload?: object (~2KB cap, payload_truncated/payload_bytes markers), error?: str, contract_id?: str, claim?: str, error_code?: str, loc?: str, elapsed_ms?: float, task_id?: str }
@INVARIANT Every log line MUST carry exactly one valid marker (REASON | REFLECT | EXPLORE). No markerless log lines in C4/C5 code.
@INVARIANT trace_id MUST propagate via ContextVar across async boundaries. Every incoming request or background job seeds a new trace_id.
@@ -43,8 +43,14 @@ Every log record MUST be a JSON object **on a single line** with the following k
| `src` | yes | string | Qualified function name, e.g. `AuthRepository.get_user_by_username` |
| `marker` | yes | string | One of `REASON`, `REFLECT`, `EXPLORE` (see below) |
| `intent` | yes | string | Human-readable one-line description of what this step intends to do/verify |
| `payload` | no | object | Arbitrary key-value data relevant to the step (params, result snippet) |
| `error` | conditional | string | Error message or reason. **Optional** for `REASON`/`REFLECT`, **required** for `EXPLORE` markers when a fallback or violation is taken |
| `payload` | no | object | Arbitrary key-value data relevant to the step (params, result snippet). Hard cap ~2KB: oversized payloads are truncated with `payload_truncated: true` + `payload_bytes` (ADR-0021/D5). Full bodies belong in evidence/task stores — reference them by id, never inline |
| `error` | conditional | string | Error message or reason. **Optional** for `REASON`/`REFLECT`; for `EXPLORE` auto-filled from `intent` when omitted — the falsification channel is never silent |
| `contract_id` | no | string | GRACE contract ID. Resolution (SSOT `resolve_contract_id`): explicit kwarg > `belief_scope` binding > mirror of the **declared** `src` (`_SRC` convention). Derived src never mirrors |
| `claim` | no | string | ≤ ~60-char pointer to the violated/verified declaration (`"PRE: scenario_id exists"`). Verbatim copies of @PRE/@POST are forbidden — the digest resolves `loc` to the full contract context |
| `error_code` | no | string | `<MODULE_PREFIX>_<SCREAMING_SNAKE>` machine-readable failure class for digest grouping (`EDITOR_SCENARIO_NOT_FOUND`, `CAPACITY_LEASE_NOT_ACTIVE`) |
| `loc` | no | string | EXPLORE only, auto-derived: `file:line` of the violated branch (repo-relative) |
| `elapsed_ms` | no | number | Auto: REASON records entry time; REFLECT/EXPLORE on the same (trace, src) emit the delta |
| `task_id` | no | string | Stamped by the formatter when a task context is bound — correlates app lines with `task_logs` |
### Example
@@ -59,7 +65,8 @@ Real wire line produced by `backend/src/services/mcp_ops_dispatch.py`:
### REASON (Deep-Reasoning)
- **When**: BEFORE an operation that extends the logical chain (DB query, API call, computation).
- **Level**: `INFO` by default, `DEBUG` for high-frequency loops.
- **`intent`**: Describes what the code is about to do.
- **`intent`**: Describes what the code is about to do. **Intent invariance**: no interpolated values in intent (they fragment digest grouping) — dynamic data goes to `payload`.
- **Event sufficiency**: a no-op tick of an idle loop is not an event (self-loop with zero informed value). Emit conditionally (only when something happened) or at `level="DEBUG"` — "no news, no tokens".
- **`payload`**: Input parameters, context values.
- **Effect**: This is the primary "deep-reasoning" step that forms the backbone of the trace.
@@ -73,6 +80,7 @@ logger.reason("Dispatching approved create_branch", src=_SRC,
- **When**: AFTER an operation to **verify the outcome** or check invariants.
- **Level**: `INFO` on success, `WARNING` if invariants partially degrade.
- **`intent`**: Describes what is being verified.
- **`claim`**: only for declared checkpoints (`"POST: rows written"` — verifying a @POST/@INVARIANT), not on every "completed" line.
- **`payload`**: Result summary, status codes, row counts.
- **Effect**: Folds the logical chain back on itself — the agent sees cause + effect in two adjacent lines.
@@ -83,20 +91,30 @@ logger.reflect("Lease heartbeat applied", src=_SRC,
```
### EXPLORE (Self-Exploration)
- **When**: An expected condition is **violated** and the code enters a fallback, error handler, or alternative path.
- **When**: An expected condition is **violated** and the code enters a fallback, error handler, or alternative path. Also the canonical marker for contract-legitimate misses (e.g. `@POST` sanctions returning None) — the violation is the **absence of a trace**, not the None itself.
- **Level**: `WARNING` for recoverable fallbacks, `ERROR` for unrecoverable failures.
- **`intent`**: Describes what assumption failed.
- **`intent`**: Describes what assumption failed (invariant text, no interpolation).
- **`claim`**: which declaration was violated (`"PRE: scenario_id exists"`).
- **`error_code`**: machine-readable class; the code lives HERE, while `error` carries the human sentence.
- **`payload`**: Relevant state at the branch point.
- **`error`**: **Required.** Explain what assumption was violated.
- **Effect**: Creates a branch in the trace — a future agent can see why the happy path was not taken.
- **`error`**: violated assumption; auto-filled from `intent` when omitted.
- **`loc`**: auto-derived file:line of the branch — do not pass manually.
- **Effect**: Creates a branch in the trace — a future agent can see why the happy path was not taken, which contract to open, and which declaration to re-check.
```python
# backend/src/services/dashboard_testing/execution/capacity.py
logger.explore("Claim rejected: unknown workload class", src=_SRC,
payload={"workload_class": workload_class},
error="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
# backend/src/services/dashboard_testing/editor/load.py
logger.explore("Scenario not found for editor load", src=_SRC,
claim="PRE: scenario_id exists",
error_code="EDITOR_SCENARIO_NOT_FOUND",
payload={"scenario_id": scenario_id},
error="no registry entry by scenario_id or scenario_key")
```
**Marker decision rules** (adapted from the Molecular CoT annotation protocol): label by the
behavioral style of the step, not by its correctness; on mixed intent choose the dominant one;
tie-break priority is **EXPLORE > REFLECT > REASON** — EXPLORE is the non-suppressible
falsification channel (deliberate inversion of the paper's self-reflection-first order).
### Quick Reference
| Situation | Marker | Level | `error` field |
@@ -117,30 +135,31 @@ logger.explore("Claim rejected: unknown workload class", src=_SRC,
## III. Trace Propagation (Python)
**SSOT implementation:** `shared/src/ss_tools/shared/cot_logger.py` (`ss_tools.shared.cot_logger`) — ContextVars (`trace_id`/`span_id`/`task_id`), `build_cot_event`, and the `log(src, marker, intent, ...)` primitive. Do not copy the logger into skills or call sites.
**SSOT implementation:** `backend/src/core/cot_logger.py` (`src.core.cot_logger`) — ContextVars (`trace_id`/`span_id`/`task_id`/`contract_id`), `build_cot_event`, `resolve_contract_id`, and the `log(src, marker, intent, ...)` primitive; the JSON formatter lives in `src/core/cot_formatter.py`. Do not copy the logger into skills or call sites. (The former `shared/` package was absorbed into backend per ADR-0022.)
**Single call-site convention — the intent-first facade, identical in both layers:**
**Single call-site convention — the intent-first facade:**
```python
# backend (backend/src/**):
from src.core.logger import belief_scope, logger
# shared layer (shared/src/**):
from ss_tools.shared.logger import logger
logger.reason("Dispatching approved create_branch", src=_SRC, payload={"dashboard_id": dashboard_id})
logger.reflect("Lease heartbeat applied", src=_SRC, payload={"lease_id": lease_id})
logger.explore("Claim rejected: unknown workload class", src=_SRC,
payload={"workload_class": workload_class}, error="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
logger.explore("Claim rejected: unknown workload class", src=_SRC, claim="PRE: workload class known",
error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS", payload={"workload_class": workload_class})
# level= overrides the record level for high-frequency plumbing lines:
logger.reason("Scheduler lifecycle: maintenance auto-end executed", src=_SRC, level="DEBUG")
# belief_scope binds the contract: anchor_id IS the GRACE contract ID, nested events inherit contract_id
with belief_scope("Core.Auth.Login", claim="POST: token issued"):
...
```
Facade rules (implemented in `src/core/logger.py` / `shared/.../logger.py`):
Facade rules (implemented in `src/core/logger.py`):
- the FIRST positional binds as `intent`; `src=`, `payload=`, `error=`, `level=` are keywords;
- the FIRST positional binds as `intent`; `src=`, `payload=`, `error=`, `level=`, `contract_id=`, `claim=`, `error_code=` are keywords;
- a single dict positional after the intent is promoted to `payload` (legacy shape, still valid);
- `src` omitted → derived from the call stack (`derive_src`); prefer an explicit `_SRC` contract id;
- `src` omitted → derived from the call stack (`derive_src`); prefer an explicit `_SRC` contract id — it also mirrors into `contract_id`;
- EXPLORE auto-derives `loc` (file:line) in the same frame walk;
- `reason`/`reflect` apply the central routine-infra suppression (`is_routine_infra`).
**The SSOT primitive `log(src, marker, intent, ...)` is src-first and module-internal** — it powers
@@ -183,6 +202,7 @@ function log(
intent: string, // human-readable one-liner
payload?: Record<string, unknown>, // params, result snippet
error?: string, // required for EXPLORE
opts?: { contract_id?: string; claim?: string; error_code?: string }, // ADR-0021 fields
): void;
```
@@ -233,26 +253,30 @@ const res = await requestApi("/api/endpoint");
if (res.trace_id) setTraceId(res.trace_id);
```
## V. CLI / Stdout Reader (for humans)
## V. CLI / Analytics Reader (agent-first)
To make JSON lines readable in development:
`scripts/pretty_cot.py` is the canonical reader (engine: `backend/src/core/log_stats.py` —
the same engine powers `GET /api/reports/log-stats` and the Reports UI panels; never duplicate it):
```bash
# Pretty-print the last 50 CoT lines
tail -50 app.log | python3 -c "
import sys, json
for line in sys.stdin:
line = line.strip()
if not line: continue
rec = json.loads(line)
m = rec.get('marker','?')
icon = {'REASON':'→','REFLECT':'✓','EXPLORE':'⚠'}.get(m, '·')
err = f\" | {rec['error']}\" if 'error' in rec else ''
pay = f\" | {rec.get('payload','')}\" if 'payload' in rec else ''
print(f\"{icon} {rec['level']:7} {rec['src']} — {rec['intent']}{pay}{err}\")
"
python scripts/pretty_cot.py backend/logs/app.log --last 80 # narrative grouped by trace
python scripts/pretty_cot.py backend/logs/app.log --trace <id> --story # causal story ending in VERDICT
python scripts/pretty_cot.py backend/logs/app.log* --digest # prioritized EXPLORE fix-map
python scripts/pretty_cot.py backend/logs/app.log* --stats # economy + bond matrix + orphan ratio
python scripts/pretty_cot.py backend/logs/app.log* --trajectory <ContractId> # belief trajectory
python scripts/pretty_cot.py backend/logs/app.log --follow
```
Ground-truth invisible-failure audit (no parser — SQL facts; needs DATABASE_URL):
```bash
cd backend && .venv/bin/python ../scripts/cot_audit.py --task-log-gaps [--since-days 7] [--json]
```
Syntactic silence audit (swallowed except/catch/suppress — finding codes per ADR-0021) runs in
axiom-mcp: MCP tool `audit`, operation `audit_belief_runtime`. Frontend: Reports → Logs tab
(Belief analytics panel) and Reports → Tasks tab (Belief gaps tiers T1/T2/T3).
## VI. Anti-patterns
| ❌ Don't | ✅ Do |
@@ -265,5 +289,10 @@ for line in sys.stdin:
| `marker` without `intent` | Every marker has a human-readable `intent` |
| Logging raw passwords or tokens in `payload` | Always sanitise sensitive data |
| Spread markers across multiple modules without trace_id | Always propagate `trace_id` |
| Silent failure branch (`return None` / `except: pass` without a trace) | EXPLORE with `claim` + `error_code` — a contract-legitimate None still needs a trace line |
| Verbatim copy of @PRE/@POST text into `claim` | ≤ ~60-char pointer; the digest resolves loc → full contract context |
| Interpolated values in `intent` (f-string ids/counts) | Invariant `intent`; dynamic values in `payload` |
| Inline request/response bodies in `payload` | Evidence-ref id + short diagnostic (2KB cap truncates anyway) |
| No-op loop tick at INFO on every pass | Conditional emit or `level="DEBUG"` — "no news, no tokens" |
#endregion Std.Semantics.MolecularCoTLogging

View File

@@ -185,7 +185,7 @@ make docs-nav
1. **L0 — `docs/api/nav/root.map`** (инжектится в стартовый контекст агента через
`instructions` в `.kilo/kilo.jsonc`): семантический дайджест модулей — области
(`@BACKEND`/`@FRONTEND`/`@TOOLING`/`@SPECS`), на модуль: purpose, `kw:` (SEMANTICS-ключевики),
(`@BACKEND`/`@FRONTEND`/`@TOOLING`/`@SPECS`/`@MISC`), на модуль: purpose, `kw:` (SEMANTICS-ключевики),
`deps:` (агрегированные межмодульные зависимости), указатель `<Name>.map`.
Тестовый код (~49% графа) свёрнут в секцию `@TESTS`. Это снепшот на момент старта
сессии: после крупных мутаций перечитать файл с диска или запустить `make docs-nav`.

View File

@@ -30,7 +30,6 @@
|---|---|---|
| **backend/** | Python FastAPI, SQLAlchemy 2.0, APScheduler, PostgreSQL | REST API, бизнес-логика, плагины, MCP-сервер |
| **frontend/** | Svelte 5 (Runes), SvelteKit, Vite, Tailwind CSS | SPA-клиент |
| **shared/** | Python package | Общие утилиты (логирование, SSL, LLM HTTP) |
```
superset-tools/
@@ -62,7 +61,6 @@ superset-tools/
│ │ │ └── ...
│ │ └── ...
│ └── tests/
├── shared/ # Общий Python пакет (ss-tools-shared)
├── docker/ # Dockerfile, entrypoint, nginx
├── docs/ # Документация, ADR
├── specs/ # 40+ feature specifications
@@ -125,7 +123,6 @@ cd backend
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements-backend.txt
pip install -e ../shared
python3 -m uvicorn src.app:app --reload --port 8000
```

View File

@@ -1,9 +1,7 @@
# Full development requirements — backend only.
# For production Docker images, use:
# - requirements-backend.txt (FastAPI backend)
# For development, also install:
# - agent/requirements.txt (Gradio agent, separate project)
# - shared/ (pip install -e shared/) (shared utilities)
# All runtime packages are in-tree (src.*); no external local packages required.
-r requirements-backend.txt

View File

@@ -2,7 +2,7 @@
# #region Api.Agent.Status [C:2] [TYPE Module] [SEMANTICS api,agent,llm,status,health]
# @BRIEF Agent LLM provider health status endpoint — used by frontend for provider availability indicator.
# @RATIONALE Frontend performs health check at mount and auto-retries every 30s if provider unavailable.
# @RELATION DEPENDS_ON -> [ss_tools.shared._llm_health]
# @RELATION DEPENDS_ON -> [src.core.utils.llm_health]
from fastapi import APIRouter, Query
router = APIRouter(prefix="/api/agent", tags=["agent-status"])
@@ -15,14 +15,14 @@ router = APIRouter(prefix="/api/agent", tags=["agent-status"])
# "last_error": str, "retry_after_s": int}
# @POST force=true bypasses the 30s status cache for an immediate probe (frontend
# "Retry now" button must get a fresh check, not the stale cached status).
# @RATIONALE Uses ss_tools.shared._llm_health instead of src.agent._llm_health
# @RATIONALE Uses src.core.utils.llm_health instead of src.agent._llm_health
# because the agent code has been moved to a separate project. The shared
# module uses only openai+httpx (no gradio, no langchain), so it works in
# both backend and agent containers.
@router.get("/llm-status")
async def get_llm_status(force: bool = Query(False)):
"""Get cached LLM provider health status. Probes provider if cache expired."""
from ss_tools.shared._llm_health import _check_llm_provider_health, _llm_status
from src.core.utils.llm_health import _check_llm_provider_health, _llm_status
status = await _check_llm_provider_health(force=force)
return {
"status": status,

View File

@@ -528,7 +528,7 @@ async def probe_max_images(
raise HTTPException(status_code=400, detail="Provider has no default model set")
# Build the client with system SSL context
from ss_tools.shared._llm_http import get_shared_http_client
from src.core.utils.llm_http import get_shared_http_client
client = AsyncOpenAI(
api_key=api_key,

View File

@@ -17,8 +17,10 @@
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from ...core.logger import belief_scope
from ...core.database import get_db
from ...core.logger import belief_scope, logger
from ...core.task_manager import TaskManager
from ...dependencies import (
get_clean_release_repository,
@@ -36,11 +38,41 @@ from ...models.report import (
)
from ...schemas.auth import User
from ...services.clean_release.repository import CleanReleaseRepository
from ...services.reports.log_gap_service import compute_task_log_gaps
from ...services.reports.report_service import ReportsService
router = APIRouter(prefix="/api/reports", tags=["Reports"])
# #region Api.Reports.TailLines [C:2] [TYPE Function] [SEMANTICS reports,logs,file-tail,io]
# @ingroup Api
# @BRIEF Read the last `limit` lines of a JSONL file via seek-from-end — the UI polls
# this endpoint, so window=file must never load whole multi-MB rotations into memory.
# @PRE path may or may not exist.
# @POST Returns up to `limit` trailing lines (partial first line after seek is dropped);
# [] for missing/unreadable files.
# @RELATION CALLED_BY -> [Api.Reports.GetLogStats]
def _tail_lines(path, limit: int, avg_line_bytes: int = 1024) -> list[str]:
from pathlib import Path
try:
size = Path(path).stat().st_size
except OSError:
return []
want_bytes = max(64 * 1024, limit * avg_line_bytes)
try:
with Path(path).open("rb") as fh:
if size > want_bytes:
fh.seek(size - want_bytes)
fh.readline() # drop partial first line after seek
data = fh.read()
except OSError:
return []
lines = data.decode("utf-8", errors="replace").splitlines()
return lines[-limit:]
# #endregion Api.Reports.TailLines
# #region Api.Reports.ParseCsvEnumList [C:1] [TYPE Function]
# @BRIEF Parse comma-separated query value into enum list.
# @PRE raw may be None/empty or comma-separated values.
@@ -159,6 +191,78 @@ async def get_task_summary(
# #endregion Api.Reports.GetTaskSummary
# #region Api.Reports.GetLogStats [C:3] [TYPE Function] [SEMANTICS api,reports,logs,stats,analytics,belief]
# @ingroup Api
# @BRIEF CoT-log analytics (ADR-0021/D5-D6): token economics, bond transition matrix,
# orphan-EXPLORE ratio, coverage. Single computation engine src.core.log_stats —
# the CLI (scripts/pretty_cot.py --stats) and this endpoint must never drift
# (no-drift smoke in the acceptance run).
# @PRE authenticated request with tasks READ permission; window in {buffer, file}.
# @POST returns {window, lines_read, stats}; deterministic empty stats on empty window.
# @RELATION CALLS -> [Core.LogStats.ComputeStats]
@router.get("/log-stats")
async def get_log_stats(
window: str = Query("buffer", pattern="^(buffer|file)$"),
limit: int = Query(3000, ge=1, le=50000),
_=Depends(has_permission("tasks", "READ")),
):
with belief_scope("Api.Reports.GetLogStats", claim="POST: stats dict computed from window"):
import json as _json
from src.core.log_stats import compute_stats
from src.core.logger import get_app_log_handler
raw_lines: list[str] = []
if window == "buffer":
handler = get_app_log_handler()
raw_lines = [line.raw or "" for line in handler.get_recent_logs(limit=limit)]
else:
from pathlib import Path
log_path = Path("logs/app.log")
if log_path.exists():
raw_lines = _tail_lines(log_path, limit)
else:
logger.explore(
"App log file missing for stats window",
src="Api.Reports.GetLogStats",
claim="PRE: logs/app.log exists for window=file",
error_code="REPORTS_LOG_FILE_MISSING",
error=f"log file not found at {log_path.resolve()}",
payload={"cwd": str(Path.cwd()), "window": window},
)
records = []
for raw in raw_lines:
try:
parsed = _json.loads(raw)
except (TypeError, ValueError):
continue
if isinstance(parsed, dict):
records.append(parsed)
return {"window": window, "lines_read": len(records), "stats": compute_stats(records)}
# #endregion Api.Reports.GetLogStats
# #region Api.Reports.GetTaskLogGaps [C:3] [TYPE Function] [SEMANTICS api,reports,triangulation,gap,belief]
# @ingroup Api
# @BRIEF Ground-truth invisible-failure report (ADR-0021/D2): tasks FAILED without
# any EXPLORE marker (tier1), EXPLORE without contract binding (tier2), SUCCESS
# with EXPLORE fallbacks (tier3). Same engine as scripts/cot_audit.py --task-log-gaps.
# @PRE authenticated request with tasks READ permission; active DB session.
# @POST returns the three-tier JSON report; read-only.
# @RELATION CALLS -> [Services.Reports.LogGapService.ComputeGaps]
@router.get("/task-log-gaps")
async def get_task_log_gaps(
since_days: int = Query(7, ge=1, le=365),
limit: int = Query(200, ge=1, le=1000),
db: Session = Depends(get_db),
_=Depends(has_permission("tasks", "READ")),
):
with belief_scope("Api.Reports.GetTaskLogGaps", claim="POST: three-tier gap report"):
return compute_task_log_gaps(db, since_days=since_days, limit=limit)
# #endregion Api.Reports.GetTaskLogGaps
# #region Api.Reports.Get.Report.Detail [C:2] [TYPE Function]
# @ingroup Api
# @BRIEF Return one normalized report detail with diagnostics and next actions.

View File

@@ -14,7 +14,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ....core.config_manager import ConfigManager
from ss_tools.shared.cot_logger import get_trace_id, seed_trace_id, set_trace_id
from src.core.cot_logger import get_trace_id, seed_trace_id, set_trace_id
from ....core.database import SessionLocal, get_db
from ....core.logger import logger
from ....dependencies import get_config_manager, get_current_user, has_permission

View File

@@ -81,7 +81,7 @@ from .api.routes import (
)
from .api.routes.validation_tasks import router as validation_tasks
from .core.auth.security import get_password_hash
from ss_tools.shared.cot_logger import build_cot_event, get_trace_id, seed_trace_id, set_trace_id
from src.core.cot_logger import build_cot_event, get_trace_id, seed_trace_id, set_trace_id
from .core.database import SessionLocal, init_db
from .core.encryption_key import ensure_encryption_key
from .core.logger import belief_scope, logger
@@ -500,6 +500,8 @@ _POLLING_EXACT_PATHS = frozenset({
"/api/maintenance/events",
"/api/validation-tasks/status/batch",
"/api/git/repositories/status/batch",
"/api/reports/log-stats",
"/api/reports/task-log-gaps",
})

View File

@@ -90,6 +90,12 @@ class LoggingConfig(BaseModel):
max_bytes: int = 10 * 1024 * 1024
backup_count: int = 5
enable_belief_state: bool = True
payload_cap_bytes: int = 2048 # Hard cap on serialized payload per log line (ADR-0021/D5)
scheduler_log_level: str = (
"WARNING" # APScheduler's own logger: "Running job"/"executed successfully" INFO
# lines flood the console on every interval tick (5s jobs = zero-information
# self-loops, ADR-0021/D5 "no news — no tokens"). Set "INFO" to restore.
)
# Agent-centric options (target: high signal-to-noise for LLM agent traces)
agent_view: bool = True # When true, prefer higher-level intents and suppress routine infrastructure noise

View File

@@ -0,0 +1,203 @@
# #region Core.CotFormatter [C:3] [TYPE Module] [SEMANTICS logging,json,formatter,structured]
# @defgroup Core Core infrastructure constants and module registry.
# @BRIEF CotJsonFormatter — JSON formatter matching the Molecular CoT protocol.
# Moved from shared/logger.py (ADR-0022). The standalone agent-container pieces
# (setup_handler, module-level logger instance, monkey-patched reason/reflect/explore)
# were dropped with the agent; backend facade lives in src.core.logger.
# @LAYER Core
# @INVARIANT Formatters format, they don't suppress — suppression happens upstream
# in reason()/reflect() via is_routine_infra (ADR-0017). Payload capping is a
# size guardrail, not semantic suppression (ADR-0021/D5).
# @INVARIANT Output is always valid single-line JSON.
# @RELATION DEPENDS_ON -> [Shared.CotLoggerModule]
# @DATA_CONTRACT LogRecord(extra: marker,intent,payload,error,src,elapsed_ms,contract_id?,claim?,loc?,error_code?) -> single-line JSON
# #endregion Core.CotFormatter
import json
import logging
from datetime import UTC, datetime
from .cot_logger import (
_span_id,
_task_id,
_trace_id,
derive_src,
)
# Payload cap default (ADR-0021/D5): oversized payloads are truncated at the
# formatter with an explicit marker. Configurable via configure_logger().
_payload_cap_bytes: int = 2048
# #region Core.PayloadCapConfig [C:1] [TYPE Function] [SEMANTICS payload,cap,config]
# @ingroup Core
# @BRIEF Set the serialized payload cap (bytes) applied by CotJsonFormatter.
def set_payload_cap(cap_bytes: int) -> None:
global _payload_cap_bytes
_payload_cap_bytes = max(256, int(cap_bytes))
# #endregion Core.PayloadCapConfig
# #region Core.TruncatePayload [C:2] [TYPE Function] [SEMANTICS payload,truncate,guardrail]
# @ingroup Core
# @BRIEF Truncate oversized payloads to the cap, preserving dict keys and marking the cut.
# @POST Returns (payload, truncated_flag, original_bytes). Below cap: returned unchanged.
# @RATIONALE Token guardrail per D5/ADR-0021: a log line must never carry unbounded
# inline bodies (e.g. request bodies) — full data belongs in evidence stores.
def _truncate_payload(payload, cap: int):
try:
encoded = json.dumps(payload, ensure_ascii=False, default=str)
except (TypeError, ValueError):
encoded = repr(payload)
raw_bytes = len(encoded.encode("utf-8"))
if raw_bytes <= cap:
return payload, False, raw_bytes
if isinstance(payload, dict):
# Reserve headroom for braces + the __truncated_keys__ marker and charge a
# per-entry separator cost, so the final dump provably fits the hard cap.
budget = max(cap - 48, 64)
kept: dict = {}
truncated_count = 0
for key, value in payload.items():
try:
value_json = json.dumps({key: value}, ensure_ascii=False, default=str)
except (TypeError, ValueError):
value_json = json.dumps({key: repr(value)}, ensure_ascii=False)
cost = len(value_json.encode("utf-8")) + 2
if cost <= budget:
kept[key] = value
budget -= cost
else:
truncated_count += 1
if truncated_count:
kept["__truncated_keys__"] = truncated_count
return kept, True, raw_bytes
# Nothing was dropped by key accounting yet the raw dump exceeded the cap
# (serialization overhead) — fall through to the preview form.
preview_src = payload if isinstance(payload, str) else encoded
text = preview_src[: max(cap // 2, 64)]
return {"__truncated__": True, "preview": text}, True, raw_bytes
# #endregion Core.TruncatePayload
# #region Shared.CotJsonFormatter [C:3] [TYPE Class] [SEMANTICS logging,formatter,json,cot]
# @ingroup Core
# @BRIEF JSON formatter matching the Molecular CoT protocol.
# Reads structured data from LogRecord's extra attributes.
# Does NOT filter — formatters format, they don't suppress.
# Suppression happens upstream in reason()/reflect().
class CotJsonFormatter(logging.Formatter):
"""JSON formatter matching the Molecular CoT protocol.
Reads structured data from the LogRecord's extra attributes (marker, intent,
payload, error, src, elapsed_ms, contract_id, claim, loc, error_code) set via
the ``extra`` kwarg. Falls back to plain message wrapping when no structured
extra is present.
Output format (single-line JSON)::
{
"ts": "2026-05-12T10:30:00.123",
"level": "INFO",
"trace_id": "uuid-or-no-trace",
"src": "module.name",
"marker": "REASON|REFLECT|EXPLORE",
"intent": "human-readable intent",
"contract_id": "optional-contract",
"span_id": "optional-span",
"payload": { ... },
"payload_truncated": true,
"payload_bytes": 4096,
"elapsed_ms": 12.5,
"loc": "backend/src/...:123",
"claim": "PRE: user exists",
"error_code": "DEMO_NOT_FOUND",
"error": "..."
}
"""
# #region Shared.CotJsonFormatter.Format [C:3] [TYPE Function] [SEMANTICS format,json,record]
# @INVARIANT Output is always valid single-line JSON.
def format(self, record):
marker = getattr(record, 'marker', None)
intent = getattr(record, 'intent', None)
payload = getattr(record, 'payload', None)
error = getattr(record, 'error', None)
src = getattr(record, 'src', None)
elapsed_ms = getattr(record, 'elapsed_ms', None)
contract_id = getattr(record, 'contract_id', None)
claim = getattr(record, 'claim', None)
loc = getattr(record, 'loc', None)
error_code = getattr(record, 'error_code', None)
event_ts = getattr(record, 'ts', None)
event_trace_id = getattr(record, 'trace_id', None)
event_span_id = getattr(record, 'span_id', None)
# Agent-centric: never emit useless generic src names
bad_srcs = {"superset_tools_app", "app_name", "root", "", None}
if not src or src in bad_srcs:
src = derive_src(record.name)
if src in bad_srcs:
src = record.name or "unknown"
if not marker:
marker = "REASON"
if not intent:
intent = record.getMessage()
log_obj = {
"ts": event_ts or datetime.now(UTC).isoformat(timespec="milliseconds"),
"level": record.levelname,
"trace_id": event_trace_id if event_trace_id is not None else (_trace_id.get() or "no-trace"),
"src": src,
"marker": marker,
"intent": intent,
}
# ADR-0021 self-diagnosing fields (print only when present)
if contract_id:
log_obj["contract_id"] = contract_id
span_id = event_span_id or _span_id.get()
if span_id:
log_obj["span_id"] = span_id
# Correlate app CoT lines with task_logs / Reports cross-filter
task_id = _task_id.get() or None
if task_id:
log_obj["task_id"] = task_id
if payload is not None:
# Ensure payload.task_id is present when context is bound
if isinstance(payload, dict) and task_id and "task_id" not in payload:
payload = {**payload, "task_id": task_id}
log_obj["payload"] = payload
elif task_id:
log_obj["payload"] = {"task_id": task_id}
if claim:
log_obj["claim"] = claim
if loc:
log_obj["loc"] = loc
if error_code:
log_obj["error_code"] = error_code
if error is not None:
log_obj["error"] = error
if elapsed_ms is not None:
log_obj["elapsed_ms"] = elapsed_ms
line = json.dumps(log_obj, ensure_ascii=False, default=str)
# Payload cap fast path: a normal line pays exactly ONE serialization.
# Only a line already larger than the cap can contain an oversized payload
# (payload bytes <= line bytes), so the measuring dump runs on the cold
# pathological path exclusively and the hard cap stays provable.
if payload is not None and len(line.encode("utf-8")) > _payload_cap_bytes:
capped, truncated, original_bytes = _truncate_payload(payload, _payload_cap_bytes)
if truncated:
log_obj["payload"] = capped
log_obj["payload_truncated"] = True
log_obj["payload_bytes"] = original_bytes
line = json.dumps(log_obj, ensure_ascii=False, default=str)
return line
# #endregion Shared.CotJsonFormatter.Format
# #endregion Shared.CotJsonFormatter

View File

@@ -1,26 +1,31 @@
# #region Shared.CotLoggerModule [C:4] [TYPE Module] [SEMANTICS logging,cot,json,trace,structured]
# @defgroup Shared Shared lightweight utilities for backend and agent.
# @defgroup Core Core infrastructure constants and module registry.
# @BRIEF Structured JSON logger implementing the Molecular CoT protocol.
# SSOT for trace_id/span_id ContextVars, derive_src, log(), cot_span.
# Backend and agent container BOTH import from here.
# SSOT for trace_id/span_id/_contract_id ContextVars, derive_src, log(), cot_span.
# Single consumer: backend (absorbed from the former shared/ package per ADR-0022).
# @LAYER Core
# @RELATION CALLED_BY -> [Shared.SharedLoggerModule]
# @RELATION CALLED_BY -> [Core.Logger.LoggerModule, Shared.CotJsonFormatter]
# @PRE Python 3.7+ (ContextVar available).
# @POST JSON log records written to the 'cot' Python logger.
# @SIDE_EFFECT Writes structured JSON to the 'cot' Python logger.
# @DATA_CONTRACT log() -> Single-line JSON to logging.StreamHandler/file.
# @INVARIANT No dependency on FastAPI, SQLAlchemy, Gradio, LangChain, pydantic.
# Pure stdlib + standard logging.
# @RATIONALE SSOT for all CoT primitives. Backend previously had a separate copy
# (backend/src/core/cot_logger.py) which diverged. Now deprecated — use shared.
# @REJECTED Keeping backend copy was rejected — skip lists diverged (backend had "gunicorn",
# shared didn't), cot_span existed only in backend, suppression lists had 4 copies.
# One SSOT prevents drift.
# @RATIONALE SSOT for all CoT primitives. Lived in shared/src (ss_tools.shared.cot_logger)
# while a standalone agent container existed; the agent was removed, leaving
# backend as the only consumer — the package boundary became pure overhead
# (pip -e step in run.sh/Dockerfile, import indirection) and the module absorbed
# back into backend (ADR-0022).
# @REJECTED Keeping the shared/ package with one consumer was rejected — it preserved the
# duplicated logger facade that historically drifted (4 suppression lists).
# Renaming region IDs during the move was rejected (INV_6: inbound relations);
# Shared.* ID curation is a separate curator pass.
from contextvars import ContextVar
from contextvars import ContextVar, Token
from datetime import UTC, datetime
import inspect
import logging
from pathlib import Path
import time
from typing import Any, Literal, TypedDict
import uuid
@@ -32,6 +37,7 @@ import uuid
_trace_id: ContextVar[str] = ContextVar("_trace_id", default="")
_span_id: ContextVar[str] = ContextVar("_span_id", default="")
_task_id: ContextVar[str] = ContextVar("_task_id", default="")
_contract_id: ContextVar[str] = ContextVar("_contract_id", default="")
# #endregion Shared.TraceContext
# ── Timing tracking ─────────────────────────────────────────────────────────
@@ -52,12 +58,20 @@ class CanonicalCotEvent(TypedDict, total=False):
intent: str
payload: dict[str, Any]
error: str
contract_id: str
claim: str
error_code: str
loc: str
# #region Shared.BuildCotEvent [C:3] [TYPE Function] [SEMANTICS cot,event,builder,canonical]
# @ingroup Shared
# @BRIEF Build and validate one canonical Molecular CoT event for both sinks.
# @INVARIANT EXPLORE events always explain the violated assumption via error.
# @INVARIANT EXPLORE events always explain the violated assumption via error
# (auto-filled from intent when the call site omitted it).
# @DATA_CONTRACT contract_id: None=auto (scope ContextVar, then mirror of the declared
# src), ""=suppress mirroring (derived src), str=explicit GRACE contract ID.
# claim/error_code/loc are optional additive fields (ADR-0021 self-diagnosing EXPLORE).
def build_cot_event(
*,
src: str,
@@ -68,6 +82,10 @@ def build_cot_event(
level: str | None = None,
trace_id: str | None = None,
span_id: str | None = None,
contract_id: str | None = None,
claim: str | None = None,
error_code: str | None = None,
loc: str | None = None,
) -> CanonicalCotEvent:
if marker not in {"REASON", "REFLECT", "EXPLORE"}:
raise ValueError(f"Invalid CoT marker: {marker}")
@@ -87,6 +105,16 @@ def build_cot_event(
effective_span = span_id or _span_id.get()
if effective_span:
event["span_id"] = effective_span
# contract_id resolution is SSOT'd in resolve_contract_id (explicit > scope > declared-src mirror)
resolved_contract = resolve_contract_id(contract_id, src, src_declared=True)
if resolved_contract:
event["contract_id"] = resolved_contract
if claim:
event["claim"] = claim
if error_code:
event["error_code"] = error_code
if loc:
event["loc"] = loc
if payload is not None:
event["payload"] = payload
if error is not None:
@@ -131,10 +159,9 @@ _suppression_enabled: bool = True
# #endregion Shared.Suppression
# ── derive_src ──────────────────────────────────────────────────────────────
# Default skip list covers BOTH backend and shared call paths.
# Default skip list covers logging-internal frames (facade, SSOT, formatter).
_DEFAULT_SKIP: tuple[str, ...] = (
"src.core.logger", "src.core.cot_logger",
"ss_tools.shared.logger", "ss_tools.shared.cot_logger",
"src.core.logger", "src.core.cot_logger", "src.core.cot_formatter",
"logging",
"anyio", "starlette", "fastapi", "asyncio",
"middleware", "trace.__call__",
@@ -142,30 +169,39 @@ _DEFAULT_SKIP: tuple[str, ...] = (
)
# #region Shared.derive_src [C:2] [TYPE Function] [SEMANTICS src,qualified,inspect,agent-centric]
# #region Shared.derive_src [C:2] [TYPE Function] [SEMANTICS src,qualified,inspect,agent-centric,loc]
# @ingroup Shared
# @BRIEF Derive qualified src for logs to ensure agent-readable traces (stdlib only).
# @BRIEF Derive qualified src (and file:line) for logs to ensure agent-readable traces (stdlib only).
# @INVARIANT Never emits generic "superset_tools_app" or "root" when caller can be determined.
# @RELATION CALLED_BY -> [Shared.log, Shared.SharedLoggerModule]
def derive_src(
# @POST derive_src() returns the src string; _derive_src_loc() returns (src, loc) from ONE frame walk.
# @RELATION CALLED_BY -> [Shared.log, Core.Logger.LoggerModule, Shared.CotJsonFormatter]
_REPO_ROOT = Path(__file__).resolve().parents[3] # backend/src/core/ -> repo root
def _frame_loc(frame) -> str | None:
"""repo-relative 'path:line' for a frame; absolute path when outside the repo."""
filename = (frame.f_code.co_filename or "").strip()
if not filename:
return None
try:
return f"{Path(filename).resolve().relative_to(_REPO_ROOT)}:{frame.f_lineno}"
except ValueError:
return f"{filename}:{frame.f_lineno}"
def _derive_src_loc(
fallback: str | None = None,
*,
skip_substrings: tuple[str, ...] | None = None,
) -> str:
"""Derive qualified src from call stack (for agent-centric logging).
Args:
fallback: Returned if no business frame found.
skip_substrings: Custom skip list override. Defaults to _DEFAULT_SKIP
which covers both backend (src.core.logger) and
shared (ss_tools.shared.logger) internal frames.
"""
) -> tuple[str, str | None]:
"""One frame walk producing both the qualified src and its 'path:line' location."""
try:
frame = inspect.currentframe()
skip = skip_substrings if skip_substrings is not None else _DEFAULT_SKIP
max_walk = 40
walked = 0
best = None
best_loc = None
while frame and walked < max_walk:
frame = frame.f_back
@@ -197,16 +233,33 @@ def derive_src(
)
if is_app:
return candidate
return candidate, _frame_loc(frame)
if best is None:
best = candidate
best_loc = _frame_loc(frame)
if best:
return best
return best, best_loc
except Exception:
pass
return fallback or "unknown"
return fallback or "unknown", None
def derive_src(
fallback: str | None = None,
*,
skip_substrings: tuple[str, ...] | None = None,
) -> str:
"""Derive qualified src from call stack (for agent-centric logging).
Args:
fallback: Returned if no business frame found.
skip_substrings: Custom skip list override. Defaults to _DEFAULT_SKIP
which covers logging-internal frames
(src.core.logger / cot_logger / cot_formatter).
"""
return _derive_src_loc(fallback, skip_substrings=skip_substrings)[0]
# #endregion Shared.derive_src
# ── Suppression predicate ───────────────────────────────────────────────────
@@ -312,6 +365,55 @@ def clear_task_id() -> None:
_task_id.set("")
# #endregion Shared.task_id_context
# ── Contract scope API (ADR-0021) ───────────────────────────────────────────
# #region Shared.ContractScope [C:2] [TYPE Block] [SEMANTICS contract_id,contextvar,scope,belief]
# @ingroup Shared
# @BRIEF Contract-scoped identity: binds a GRACE contract ID so every nested CoT event
# inherits it (belief_scope / module _SRC convention). Token-based, async-safe.
# @POST Events emitted inside the scope carry contract_id unless a call site overrides it.
def set_contract_scope(contract_id: str) -> Token:
"""Bind contract_id for the current context; returns a Token for reset_contract_scope."""
return _contract_id.set(contract_id or "")
def reset_contract_scope(token: Token | None) -> None:
"""Restore the previous contract binding. Always call in finally."""
if token is None:
return
try:
_contract_id.reset(token)
except ValueError:
_contract_id.set("")
def get_contract_id() -> str:
"""Return the contract_id bound for this context, or empty string."""
return _contract_id.get() or ""
# #region Shared.ResolveContractId [C:2] [TYPE Function] [SEMANTICS contract_id,resolution,ssot]
# @ingroup Shared
# @BRIEF SSOT resolution of contract_id for one event: explicit kwarg > scope ContextVar
# > mirror of the DECLARED src (module _SRC convention). Derived src never mirrors.
# @DATA_CONTRACT (explicit: str|None, src: str|None, src_declared: bool) -> str|None
# explicit "" suppresses (None); explicit str wins; else scope; else declared src.
def resolve_contract_id(
explicit: str | None,
src: str | None,
*,
src_declared: bool,
) -> str | None:
"""Resolve the effective contract_id or None when the event carries no binding."""
if explicit is not None:
return explicit or None
scoped = _contract_id.get()
if scoped:
return scoped
return src if src_declared and src else None
# #endregion Shared.ResolveContractId
# #endregion Shared.ContractScope
# ── Span ID API ─────────────────────────────────────────────────────────────
# #region Shared.push_span [C:1] [TYPE Function] [SEMANTICS span_id,contextvar,stack]
@@ -346,11 +448,12 @@ def pop_span(prev: str) -> None:
# ── Core log function ───────────────────────────────────────────────────────
# #region Shared.log [C:2] [TYPE Function] [SEMANTICS log,json,structured,marker,agent-centric]
# #region Shared.log [C:3] [TYPE Function] [SEMANTICS log,json,structured,marker,agent-centric]
# @ingroup Shared
# @BRIEF Core structured logging function that emits a single-line JSON record.
# Supports elapsed_ms timing: call REASON first, then REFLECT/EXPLORE
# auto-computes elapsed milliseconds.
# auto-computes elapsed milliseconds. EXPLORE additionally carries loc
# (file:line of the violated branch) derived in the same frame walk.
def log(
src: str,
marker: str,
@@ -358,6 +461,10 @@ def log(
payload: dict[str, Any] | None = None,
error: str | None = None,
level: str | None = None,
*,
contract_id: str | None = None,
claim: str | None = None,
error_code: str | None = None,
) -> None:
"""Emit a single-line structured JSON log record through the 'cot' logger.
@@ -366,21 +473,36 @@ def log(
marker: Protocol marker — one of 'REASON', 'REFLECT', 'EXPLORE'.
intent: Short one-line description of intent or action.
payload: Optional structured data dict.
error: Required for EXPLORE markers; describes the violated assumption.
error: Required for EXPLORE markers; describes the violated assumption
(auto-filled from intent when omitted — the channel is never silent).
level: Log level override. Auto-inferred from marker if omitted
(REASON/REFLECT -> INFO, EXPLORE -> WARNING).
Side effects:
Writes single-line JSON to the 'cot' Python logger.
Tracks entry timestamps for elapsed_ms auto-computation.
contract_id: GRACE contract ID override. None = inherit from contract scope,
else mirror the explicitly declared src.
claim: Pointer to the violated/verified declaration (e.g. 'PRE: user exists').
error_code: Machine-readable failure class (e.g. 'EDITOR_SCENARIO_NOT_FOUND').
"""
if level is None:
level = "WARNING" if marker == "EXPLORE" else "INFO"
# Derive good src if caller passed a poor one
if not src or src in ("superset_tools_app", "app_name", "root", "", None):
bad_srcs = ("superset_tools_app", "app_name", "root", "", None)
loc: str | None = None
src_derived = not src or src in bad_srcs
if marker == "EXPLORE":
# One frame walk yields both the fallback src and the violation branch loc.
derived_src, loc = _derive_src_loc(None if src_derived else src)
if src_derived:
src = derived_src
elif src_derived:
# Derive good src if caller passed a poor one
src = derive_src(src)
resolved_contract = contract_id
if resolved_contract is None and src_derived:
# Derived src is not a declared identifier — never mirror it into contract_id.
resolved_contract = _contract_id.get() or ""
event = build_cot_event(
src=src,
marker=marker,
@@ -388,6 +510,10 @@ def log(
payload=payload,
error=error,
level=level,
contract_id=resolved_contract,
claim=claim,
error_code=error_code,
loc=loc,
)
# ── elapsed_ms auto-computation ────────────────────────────────────────
@@ -444,15 +570,20 @@ def cot_span(marker: str = "REASON", intent: str | None = None):
src = f"{func.__module__}.{func.__qualname__}"
prev_span = push_span(func.__qualname__)
default_intent = intent or f"Execute {func.__qualname__}"
# Span src is a derived python path, not a declared GRACE contract —
# suppress src mirroring (ADR-0021) but inherit an active contract scope.
span_contract = _contract_id.get() or ""
try:
log(src, marker, default_intent, payload=_summarise_args(args, kwargs))
log(src, marker, default_intent, payload=_summarise_args(args, kwargs),
contract_id=span_contract)
result = await func(*args, **kwargs)
log(src, "REFLECT", f"{func.__qualname__} completed",
payload={"result": _summarise_value(result)})
payload={"result": _summarise_value(result)}, contract_id=span_contract)
return result
except Exception as e:
log(src, "EXPLORE", f"{func.__qualname__} failed",
error=str(e), payload={"args": _summarise_args(args, kwargs)})
error=str(e), payload={"args": _summarise_args(args, kwargs)},
contract_id=span_contract)
raise
finally:
pop_span(prev_span)
@@ -462,15 +593,20 @@ def cot_span(marker: str = "REASON", intent: str | None = None):
src = f"{func.__module__}.{func.__qualname__}"
prev_span = push_span(func.__qualname__)
default_intent = intent or f"Execute {func.__qualname__}"
# Span src is a derived python path, not a declared GRACE contract —
# suppress src mirroring (ADR-0021) but inherit an active contract scope.
span_contract = _contract_id.get() or ""
try:
log(src, marker, default_intent, payload=_summarise_args(args, kwargs))
log(src, marker, default_intent, payload=_summarise_args(args, kwargs),
contract_id=span_contract)
result = func(*args, **kwargs)
log(src, "REFLECT", f"{func.__qualname__} completed",
payload={"result": _summarise_value(result)})
payload={"result": _summarise_value(result)}, contract_id=span_contract)
return result
except Exception as e:
log(src, "EXPLORE", f"{func.__qualname__} failed",
error=str(e), payload={"args": _summarise_args(args, kwargs)})
error=str(e), payload={"args": _summarise_args(args, kwargs)},
contract_id=span_contract)
raise
finally:
pop_span(prev_span)
@@ -516,13 +652,17 @@ __all__ = [
"cot_span",
"derive_src",
"emit_cot_event",
"get_contract_id",
"get_task_id",
"get_trace_id",
"is_routine_infra",
"log",
"pop_span",
"push_span",
"reset_contract_scope",
"resolve_contract_id",
"seed_trace_id",
"set_contract_scope",
"set_routine_suppression",
"set_task_id",
"set_trace_id",

View File

@@ -0,0 +1,388 @@
# #region Core.LogStats [C:3] [TYPE Module] [SEMANTICS logging,stats,bond,analytics,digest]
# @defgroup Core Core infrastructure constants and module registry.
# @BRIEF SSOT computation engine for CoT-log analytics (ADR-0021 / decisions D5-D6):
# volumes and token economics, marker histogram, trace-internal bond transition matrix,
# orphan-EXPLORE ratio, REFLECT pairing rate, top intent families, ADR-0021 field
# coverage, payload-cap hits. stdlib-only and pure — consumed by scripts/pretty_cot.py
# (agent CLI), GET /api/reports/log-stats (frontend panel), and tests. Single
# implementation by design: CLI and API must never drift (T10 no-drift smoke).
# @LAYER Core
# @INVARIANT Pure functions: no I/O, no mutation of inputs; identical events -> identical dicts.
# @INVARIANT All outputs are JSON-serializable (plain dict/list/str/int/float/bool/None).
# @RATIONALE Bond-structure metrics come from the Molecular CoT topology work: transition
# distributions stabilize across models/tasks (Pearson >0.9 at N>2k), while excessive
# exploration fragments reasoning and unverified deep-reasoning chains go rigid. The
# matrix here is conditional on EMITTED markers: "normal operation" is implemented as
# upstream suppression and is invisible by design (documented deviation, ADR-0021).
# @RELATION DEPENDS_ON -> [Core.CotFormatter]
import json
import re
from collections import Counter
from typing import Any, Iterable
# Stability threshold for distributional conclusions (Molecular CoT Appendix C.2).
MIN_SAMPLE_LINES = 2000
# Safety valve: per-trace structural state is bounded; volume/marker/intent metrics
# always cover the full input regardless (CLI users point at rotated 30MB+ files).
MAX_TRACKED_TRACES = 50_000
_MARKERS = ("REASON", "REFLECT", "EXPLORE")
_HEX_RUN = re.compile(r"[0-9a-fA-F]{8,}")
_DIGITS = re.compile(r"\d+")
_WS = re.compile(r"\s+")
# #region Core.LogStats.IntentFamily [C:1] [TYPE Function] [SEMANTICS intent,normalization]
# @ingroup Core
# @BRIEF Normalize an intent into a family key (uuid/hex runs and digits -> '#').
# @POST Interpolated intents collapse into one family — detects grouping-destroying f-strings.
def intent_family(intent: str) -> str:
text = _HEX_RUN.sub("#", intent or "")
text = _DIGITS.sub("#", text)
return _WS.sub(" ", text).strip()
# #endregion Core.LogStats.IntentFamily
# #region Core.LogStats.LineKey [C:1] [TYPE Function] [SEMANTICS pairing,key,span]
# @ingroup Core
# @BRIEF Pairing key for prediction/verification linkage: span > contract > src.
def _line_key(evt: dict[str, Any]) -> str:
return evt.get("span_id") or evt.get("contract_id") or evt.get("src") or ""
# #endregion Core.LogStats.LineKey
# #region Core.LogStats.ComputeStats [C:3] [TYPE Function] [SEMANTICS stats,metrics,bond-matrix,orphan]
# @ingroup Core
# @BRIEF Compute the full analytics dict over an iterable of parsed JSONL CoT events.
# @PRE Events are dicts as produced by CotJsonFormatter (parsed JSON lines).
# @POST Returns JSON-serializable dict: volumes, marker_mix, transitions (+normalized),
# orphan_explore, reflect_pairing, top_intents, coverage, payload caps, sample flag.
# Per-trace structural metrics track at most MAX_TRACKED_TRACES traces (flag
# traces_truncated); volume/marker/intent metrics always cover the full input.
# @SIDE_EFFECT None (pure).
def compute_stats(events: Iterable[dict[str, Any]]) -> dict[str, Any]:
lines = 0
total_bytes = 0
max_bytes = 0
marker_counts: Counter = Counter()
marker_bytes: Counter = Counter()
transitions: dict[str, Counter] = {m: Counter() for m in _MARKERS}
intent_counter: Counter = Counter()
family_counter: Counter = Counter()
truncated_count = 0
contract_cov = 0
claim_cov = 0
explore_total = 0
explore_code_cov = 0
first_ts: str | None = None
last_ts: str | None = None
per_trace: dict[str, dict[str, Any]] = {}
overflow_events = 0
for evt in events:
marker = evt.get("marker") or "REASON"
if marker not in _MARKERS:
marker = "REASON"
try:
raw_bytes = len(json.dumps(evt, ensure_ascii=False, default=str).encode("utf-8"))
except (TypeError, ValueError):
raw_bytes = len(str(evt).encode("utf-8"))
lines += 1
total_bytes += raw_bytes
if raw_bytes > max_bytes:
max_bytes = raw_bytes
marker_counts[marker] += 1
marker_bytes[marker] += raw_bytes
ts = evt.get("ts")
if ts:
if first_ts is None:
first_ts = ts
last_ts = ts
intent = evt.get("intent") or ""
intent_counter[intent] += 1
family_counter[intent_family(intent)] += 1
if evt.get("payload_truncated"):
truncated_count += 1
if evt.get("contract_id"):
contract_cov += 1
if evt.get("claim"):
claim_cov += 1
if marker == "EXPLORE":
explore_total += 1
if evt.get("error_code"):
explore_code_cov += 1
tid = evt.get("trace_id") or "no-trace"
state = per_trace.get(tid)
if state is None:
if len(per_trace) < MAX_TRACKED_TRACES:
state = {"prev": None, "reason_keys": set(), "reflect_keys": set(), "orphan": 0}
per_trace[tid] = state
else:
overflow_events += 1
if state is not None:
if marker == "EXPLORE" and _line_key(evt) not in state["reason_keys"]:
state["orphan"] += 1
if state["prev"]:
transitions[state["prev"]][marker] += 1
if marker == "REASON":
state["reason_keys"].add(_line_key(evt))
elif marker == "REFLECT":
state["reflect_keys"].add(_line_key(evt))
state["prev"] = marker
orphan_total = sum(s["orphan"] for s in per_trace.values())
reason_keys_total = sum(len(s["reason_keys"]) for s in per_trace.values())
paired_total = sum(len(s["reason_keys"] & s["reflect_keys"]) for s in per_trace.values())
transitions_out = {src: dict(dst) for src, dst in transitions.items()}
transitions_norm: dict[str, dict[str, float]] = {}
for src, dst in transitions.items():
row_total = sum(dst.values())
transitions_norm[src] = (
{k: round(v / row_total, 4) for k, v in dst.items()} if row_total else {}
)
def _pct(part: int, whole: int) -> float:
return round(100.0 * part / whole, 2) if whole else 0.0
return {
"lines": lines,
"bytes_total": total_bytes,
"tokens_approx": total_bytes // 4,
"avg_line_bytes": round(total_bytes / lines, 1) if lines else 0.0,
"max_line_bytes": max_bytes,
"window": {"traces": len(per_trace), "first_ts": first_ts, "last_ts": last_ts},
"marker_mix": {
m: {
"count": marker_counts.get(m, 0),
"bytes": marker_bytes.get(m, 0),
"pct": _pct(marker_counts.get(m, 0), lines),
}
for m in _MARKERS
},
"transitions": transitions_out,
"transitions_normalized": transitions_norm,
"orphan_explore": {
"count": orphan_total,
"ratio": round(orphan_total / explore_total, 4) if explore_total else 0.0,
"explore_total": explore_total,
},
"reflect_pairing": {
"rate": round(paired_total / reason_keys_total, 4) if reason_keys_total else 0.0,
"reason_keys": reason_keys_total,
"paired": paired_total,
},
"top_intents": [
{"intent": i, "count": c} for i, c in intent_counter.most_common(10)
],
"top_intent_families": [
{"family": f, "count": c, "distinct": sum(1 for i in intent_counter if intent_family(i) == f)}
for f, c in family_counter.most_common(10)
],
"payload_truncated_count": truncated_count,
"traces_truncated": overflow_events > 0,
"overflow_events": overflow_events,
"coverage": {
"contract_id_pct": _pct(contract_cov, lines),
"claim_pct": _pct(claim_cov, lines),
"error_code_pct_of_explore": _pct(explore_code_cov, explore_total),
},
"insufficient_sample": lines < MIN_SAMPLE_LINES,
"min_sample_lines": MIN_SAMPLE_LINES,
}
# #endregion Core.LogStats.ComputeStats
# #region Core.LogStats.ComputeDigest [C:3] [TYPE Function] [SEMANTICS digest,explore,grouping]
# @ingroup Core
# @BRIEF Group EXPLORE events into a prioritized fix map: contract_id > error_code > src.
# @POST List of groups sorted by count desc then recency; callee/caller double-logging
# of the same (trace, contract, code) counted once (dedup), duplicates reported.
def compute_digest(events: Iterable[dict[str, Any]], top: int = 20) -> list[dict[str, Any]]:
groups: dict[tuple, dict[str, Any]] = {}
seen_pairs: set[tuple] = set()
duplicates = 0
for evt in events:
if (evt.get("marker") or "") != "EXPLORE":
continue
contract_id = evt.get("contract_id") or ""
error_code = evt.get("error_code") or ""
src = evt.get("src") or "?"
dedup_key = (
evt.get("trace_id") or "",
contract_id,
error_code,
# Uncoded legacy lines: dedup only exact same src+intent within a trace
# (callee/caller double-logging); distinct failures must stay distinct.
src if not error_code else "",
"" if error_code else (evt.get("intent") or ""),
)
if dedup_key in seen_pairs:
duplicates += 1
continue
seen_pairs.add(dedup_key)
key = (contract_id, error_code, src)
group = groups.get(key)
if group is None:
group = {
"contract_id": contract_id or None,
"error_code": error_code or None,
"src": src,
"count": 0,
"first_ts": evt.get("ts"),
"last_ts": evt.get("ts"),
"last_example": None,
}
groups[key] = group
group["count"] += 1
if evt.get("ts"):
group["last_ts"] = evt["ts"]
payload = evt.get("payload")
snippet = None
if payload is not None:
try:
snippet = json.dumps(payload, ensure_ascii=False, default=str)[:180]
except (TypeError, ValueError):
snippet = str(payload)[:180]
group["last_example"] = {
"ts": evt.get("ts"),
"intent": evt.get("intent"),
"error": evt.get("error"),
"claim": evt.get("claim"),
"loc": evt.get("loc"),
"trace_id": evt.get("trace_id"),
"payload_snippet": snippet,
}
ordered = sorted(
groups.values(),
key=lambda g: (-g["count"], g["last_ts"] or ""),
)
result = ordered[: max(top, 1)]
if duplicates:
result.append({"__dedup_skipped__": duplicates})
return result
# #endregion Core.LogStats.ComputeDigest
# #region Core.LogStats.ComputeTrajectory [C:2] [TYPE Function] [SEMANTICS trajectory,belief,contract]
# @ingroup Core
# @BRIEF Belief trajectory of one contract: (ts, marker, claim/intent, error_code) rows.
# @POST Rows in chronological order across traces; matches contract_id, fallback src.
def compute_trajectory(events: Iterable[dict[str, Any]], contract_id: str) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for evt in events:
cid = evt.get("contract_id") or ""
src = evt.get("src") or ""
if cid != contract_id and src != contract_id:
continue
rows.append({
"ts": evt.get("ts"),
"trace_id": (evt.get("trace_id") or "")[:8],
"marker": evt.get("marker"),
"claim": evt.get("claim"),
"intent": evt.get("intent"),
"error_code": evt.get("error_code"),
"error": evt.get("error"),
})
rows.sort(key=lambda r: (r["ts"] or "", r["trace_id"] or ""))
return rows
# #endregion Core.LogStats.ComputeTrajectory
# #region Core.LogStats.Renderers [C:2] [TYPE Block] [SEMANTICS render,text,cli]
# @ingroup Core
# @BRIEF Text renderers shared by CLI and (optionally) API consumers.
_ICONS = {"REASON": "->", "REFLECT": "ok", "EXPLORE": "!!"}
def render_stats(stats: dict[str, Any]) -> str:
out: list[str] = []
mix = stats["marker_mix"]
out.append(
f"lines {stats['lines']} | bytes {stats['bytes_total']} | ~tokens {stats['tokens_approx']}"
f" | avg {stats['avg_line_bytes']}B max {stats['max_line_bytes']}B"
)
window = stats["window"]
out.append(f"traces {window['traces']} | first {window['first_ts']} | last {window['last_ts']}")
mix_line = " | ".join(
f"{m} {mix[m]['count']} ({mix[m]['pct']}%, {mix[m]['bytes']}B)" for m in _MARKERS
)
out.append("mix: " + mix_line)
out.append("bond matrix (trace-internal, row-normalized):")
norm = stats["transitions_normalized"]
out.append(" " + "".join(f"->{m:<9}" for m in _MARKERS))
for src_m in _MARKERS:
row = norm.get(src_m) or {}
cells = "".join(f"{row.get(dst_m, 0.0):<10.3f}" for dst_m in _MARKERS)
out.append(f"{src_m:<7} {cells}")
orphan = stats["orphan_explore"]
pairing = stats["reflect_pairing"]
out.append(
f"orphan EXPLORE: {orphan['count']}/{orphan['explore_total']}"
f" (ratio {orphan['ratio']}) | REFLECT pairing: {pairing['rate']}"
f" ({pairing['paired']}/{pairing['reason_keys']})"
)
out.append("top intents:")
for item in stats["top_intents"][:10]:
out.append(f" {item['count']:>7}x {item['intent'][:90]}")
cov = stats["coverage"]
out.append(
f"coverage: contract_id {cov['contract_id_pct']}% | claim {cov['claim_pct']}%"
f" | error_code {cov['error_code_pct_of_explore']}% of EXPLORE"
)
out.append(f"payload truncated lines: {stats['payload_truncated_count']}")
if stats["insufficient_sample"]:
out.append(
f"WARNING: insufficient sample (N={stats['lines']} < {stats['min_sample_lines']}) —"
" distributional conclusions unreliable"
)
return "\n".join(out)
def render_digest(groups: list[dict[str, Any]]) -> str:
out: list[str] = ["== EXPLORE digest (fix map, prioritized) =="]
for group in groups:
if "__dedup_skipped__" in group:
out.append(f"(dedup skipped {group['__dedup_skipped__']} double-logged events)")
continue
head = group["contract_id"] or group["src"]
code = f" [{group['error_code']}]" if group["error_code"] else ""
out.append(f"{group['count']:>5}x {head}{code}")
ex = group.get("last_example") or {}
if ex.get("claim"):
out.append(f" claim: {ex['claim']}")
if ex.get("error"):
out.append(f" error: {str(ex['error'])[:160]}")
if ex.get("loc"):
out.append(f" loc: {ex['loc']}")
if ex.get("payload_snippet"):
out.append(f" last: {ex['payload_snippet']}")
out.append(f" last seen: {group['last_ts']} trace={str(ex.get('trace_id'))[:8]}")
if len(out) == 1:
out.append("(no EXPLORE events — clean window)")
return "\n".join(out)
def render_trajectory(contract_id: str, rows: list[dict[str, Any]]) -> str:
out: list[str] = [f"== belief trajectory: {contract_id} ({len(rows)} events) =="]
for row in rows:
icon = _ICONS.get(row["marker"] or "", "??")
claim = f" claim={row['claim']}" if row.get("claim") else ""
code = f" code={row['error_code']}" if row.get("error_code") else ""
error = f" error={str(row['error'])[:120]}" if row.get("error") else ""
out.append(
f"{row['ts']} [{row['trace_id']}] {icon:<2} {str(row['intent'])[:100]}{claim}{code}{error}"
)
return "\n".join(out)
# #endregion Core.LogStats.Renderers
# #endregion Core.LogStats

View File

@@ -38,15 +38,19 @@ from typing import Any
from pydantic import BaseModel, Field
from ss_tools.shared.cot_logger import (
from src.core.cot_logger import (
_derive_src_loc,
_span_id,
_trace_id,
derive_src,
log as cot_log,
is_routine_infra,
reset_contract_scope,
resolve_contract_id,
set_contract_scope,
set_routine_suppression,
)
from ss_tools.shared.logger import CotJsonFormatter
from src.core.cot_formatter import CotJsonFormatter, set_payload_cap
from .ws_log_handler import WebSocketLogHandler
# Thread-local storage for belief state
@@ -59,8 +63,8 @@ _enable_belief_state = True
_task_log_level = "INFO"
# CotJsonFormatter imported from shared (ss_tools.shared.logger.CotJsonFormatter)
# Local suppression removed — suppression is centralized in shared/cot_logger.py is_routine_infra()
# CotJsonFormatter imported from src.core.cot_formatter
# Local suppression removed — suppression is centralized in src/core/cot_logger.py is_routine_infra()
# BeliefFormatter removed — text-based [REASON]/[REFLECT]/[EXPLORE] markers are rejected by the
# Molecular CoT protocol in favor of structured JSON fields.
@@ -75,15 +79,20 @@ class LogEntry(BaseModel):
# #endregion Core.Logger.LogEntry
# #region Core.Logger.BeliefScope [C:3] [TYPE Function] [SEMANTICS logging,context,belief_state,cot]
# #region Core.Logger.BeliefScope [C:4] [TYPE Function] [SEMANTICS logging,context,belief_state,cot,contract]
# @ingroup Core
# @BRIEF Context manager for decision audit structured logging. Uses cot_logger.log() for JSON output.
# anchor_id IS the GRACE contract ID: it binds the contract scope so every nested CoT event
# inherits contract_id (ADR-0021). claim names the declaration being checked (e.g. "POST: rows written").
# @PRE anchor_id must be provided.
# @POST Thread-local belief state is updated; REASON/REFLECT/EXPLORE markers emitted via structured JSON logger.
# @POST Thread-local belief state updated AND contract scope bound via ContextVar token;
# REASON/REFLECT (DEBUG) and EXPLORE (WARNING) emitted with contract_id (+claim when given).
# @SIDE_EFFECT Sets/resets the _contract_id ContextVar for the scope duration.
@contextmanager
def belief_scope(anchor_id: str, message: str = ""):
def belief_scope(anchor_id: str, message: str = "", claim: str | None = None):
old_anchor = getattr(_belief_state, 'anchor_id', None)
_belief_state.anchor_id = anchor_id
_contract_token = set_contract_scope(anchor_id)
_start = time.monotonic()
try:
@@ -95,16 +104,17 @@ def belief_scope(anchor_id: str, message: str = ""):
elapsed_ms = round((time.monotonic() - _start) * 1000, 1)
cot_log(
anchor_id, "REFLECT", f"{anchor_id}: completed",
payload={"elapsed_ms": elapsed_ms}, level="DEBUG",
payload={"elapsed_ms": elapsed_ms}, level="DEBUG", claim=claim,
)
except Exception as e:
elapsed_ms = round((time.monotonic() - _start) * 1000, 1)
cot_log(
anchor_id, "EXPLORE", f"{anchor_id}: assumption violated",
error=str(e), payload={"elapsed_ms": elapsed_ms}, level="WARNING",
error=str(e), payload={"elapsed_ms": elapsed_ms}, level="WARNING", claim=claim,
)
raise
finally:
reset_contract_scope(_contract_token)
_belief_state.anchor_id = old_anchor
# #endregion Core.Logger.BeliefScope
@@ -125,9 +135,18 @@ def configure_logger(config):
global _enable_belief_state, _task_log_level
_enable_belief_state = config.enable_belief_state
_task_log_level = config.task_log_level.upper()
# Suppression now handled centrally via shared/cot_logger.py
# Suppression now handled centrally via src/core/cot_logger.py
hide_routine = getattr(config, 'hide_routine_infra', True)
set_routine_suppression(enabled=hide_routine)
# Payload guardrail (ADR-0021/D5): formatter truncates oversized payloads
set_payload_cap(getattr(config, 'payload_cap_bytes', 2048))
# APScheduler library logger: its INFO "Running job"/"executed successfully"
# lines fire on every interval tick (5s jobs) and flood the console with
# zero-information self-loops (ADR-0021/D5). WARNING by default; the app's own
# scheduler wrappers (core/scheduler.py) emit the meaningful CoT lines.
scheduler_level = getattr(logging, str(getattr(config, 'scheduler_log_level', 'WARNING')).upper(), logging.WARNING)
logging.getLogger("apscheduler").setLevel(scheduler_level)
# Set logger level (and handler levels — NOTSET handlers alone are fine,
# but explicit set keeps runtime reconfigure obvious and testable).
@@ -162,7 +181,7 @@ def configure_logger(config):
handler.setLevel(level)
# Configure the 'cot' logger for consistent JSON output
from ss_tools.shared.cot_logger import cot_logger
from src.core.cot_logger import cot_logger
cot_logger.setLevel(level)
if not cot_logger.handlers:
cot_handler = logging.StreamHandler()
@@ -226,7 +245,7 @@ logger.setLevel(logging.INFO)
# Create CotJsonFormatter (shared with all handlers)
_formatter = CotJsonFormatter()
# Add console handler only if shared/logger.py didn't add one
# Add console handler when none configured yet
if not logger.handlers:
_console_handler = logging.StreamHandler()
_console_handler.setFormatter(_formatter)
@@ -239,7 +258,7 @@ _ws_handler.setFormatter(_formatter)
logger.addHandler(_ws_handler)
# Mirror CoT logger into the same buffer so the console sees full server stream.
from ss_tools.shared.cot_logger import cot_logger as _cot_logger
from src.core.cot_logger import cot_logger as _cot_logger
if not any(isinstance(h, WebSocketLogHandler) for h in _cot_logger.handlers):
_cot_logger.addHandler(_ws_handler)
@@ -256,36 +275,58 @@ def get_app_log_handler() -> WebSocketLogHandler:
# logger.error("An error occurred", exc_info=True)
# #region Core.Logger.Explore [C:2] [TYPE Function] [SEMANTICS log,explore,marker,warning]
# #region Core.Logger.Explore [C:3] [TYPE Function] [SEMANTICS log,explore,marker,warning,contract]
# @ingroup Core
# @BRIEF Logs an EXPLORE marker (WARNING level) with structured extra data for CotJsonFormatter.
# Enriched fields (ADR-0021): contract_id/claim/error_code; loc (file:line of the violated
# branch) auto-derived in the same frame walk as the src fallback — cold path only.
def explore(self, msg, *args, **kwargs):
"""Log an EXPLORE marker — searching, alternatives, violated assumptions.
Passes structured ``extra`` data so CotJsonFormatter produces proper JSON.
If the first positional arg is a dict, it is treated as the payload.
Optional ``level=`` kwarg overrides the record level (e.g. ``level="DEBUG"``).
Optional ``contract_id=`` / ``claim=`` / ``error_code=`` enrich the record;
``contract_id`` defaults to the active belief scope, then to a declared ``src=``.
"""
user_extra = kwargs.pop('extra', {})
error_val = kwargs.pop('error', None)
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
level_override = kwargs.pop('level', None)
contract_id = kwargs.pop('contract_id', None)
claim = kwargs.pop('claim', None)
error_code = kwargs.pop('error_code', None)
# Agent-centric: prefer explicit src= kwarg, then extra, then derive
# Agent-centric: prefer explicit src= kwarg, then extra, then derive.
# One frame walk yields both the fallback src and the violation-branch loc.
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src = derive_src()
src_declared = bool(src) and src not in {"superset_tools_app", "app_name", "root", ""}
derived_src, loc = _derive_src_loc()
if not src_declared:
src = derived_src
extra = {'marker': 'EXPLORE', 'intent': msg, 'src': src}
if error_val is not None:
extra['error'] = error_val
# SSOT invariant parity with build_cot_event: EXPLORE always explains the
# violated assumption — auto-fill error from intent when the call site omits it.
if error_val is None:
error_val = msg
extra['error'] = error_val
if loc:
extra['loc'] = loc
# If a single dict is passed as positional arg, treat it as payload
if not payload and len(args) == 1 and isinstance(args[0], dict):
payload = args[0]
args = ()
if payload is not None:
extra['payload'] = payload
resolved_contract = resolve_contract_id(contract_id, src, src_declared=src_declared)
if resolved_contract:
extra['contract_id'] = resolved_contract
if claim:
extra['claim'] = claim
if error_code:
extra['error_code'] = error_code
extra.update(user_extra)
_emit_at_level(self, level_override, logging.WARNING, msg, extra, kwargs)
# #endregion Core.Logger.Explore
@@ -337,13 +378,17 @@ def reason(self, msg, *args, **kwargs):
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
level_override = kwargs.pop('level', None)
contract_id = kwargs.pop('contract_id', None)
claim = kwargs.pop('claim', None)
error_code = kwargs.pop('error_code', None)
# Agent-centric: prefer explicit src= kwarg, then extra, then derive
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src_declared = bool(src) and src not in {"superset_tools_app", "app_name", "root", ""}
if not src_declared:
src = derive_src()
# Central suppression via shared/cot_logger.py is_routine_infra()
# Central suppression via src/core/cot_logger.py is_routine_infra()
if is_routine_infra(msg):
return
@@ -356,6 +401,13 @@ def reason(self, msg, *args, **kwargs):
args = ()
if payload is not None:
extra['payload'] = payload
resolved_contract = resolve_contract_id(contract_id, src, src_declared=src_declared)
if resolved_contract:
extra['contract_id'] = resolved_contract
if claim:
extra['claim'] = claim
if error_code:
extra['error_code'] = error_code
extra.update(user_extra)
_emit_at_level(self, level_override, logging.INFO, msg, extra, kwargs)
# #endregion Core.Logger.Reason
@@ -379,13 +431,17 @@ def reflect(self, msg, *args, **kwargs):
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
level_override = kwargs.pop('level', None)
contract_id = kwargs.pop('contract_id', None)
claim = kwargs.pop('claim', None)
error_code = kwargs.pop('error_code', None)
# Agent-centric: prefer explicit src= kwarg, then extra, then derive
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src_declared = bool(src) and src not in {"superset_tools_app", "app_name", "root", ""}
if not src_declared:
src = derive_src()
# Central suppression via shared/cot_logger.py is_routine_infra()
# Central suppression via src/core/cot_logger.py is_routine_infra()
if is_routine_infra(msg):
return
@@ -398,6 +454,13 @@ def reflect(self, msg, *args, **kwargs):
args = ()
if payload is not None:
extra['payload'] = payload
resolved_contract = resolve_contract_id(contract_id, src, src_declared=src_declared)
if resolved_contract:
extra['contract_id'] = resolved_contract
if claim:
extra['claim'] = claim
if error_code:
extra['error_code'] = error_code
extra.update(user_extra)
_emit_at_level(self, level_override, logging.INFO, msg, extra, kwargs)
# #endregion Core.Logger.Reflect

View File

@@ -58,7 +58,7 @@ def test_belief_scope_logs_reason_reflect_at_debug(caplog):
logger.info("Doing something important")
# Check that the logs contain the expected patterns
log_records = list(caplog.records)
log_messages = [record.message for record in log_records]
log_messages = [record.getMessage() for record in log_records]
assert any(_marker(r) == "REASON" and "TestFunction" in r.getMessage() for r in log_records), "REASON log not found"
assert any("Doing something important" in msg for msg in log_messages), "Inline info log not found"
assert any(_marker(r) == "REFLECT" for r in log_records), "REFLECT log not found"
@@ -136,7 +136,7 @@ def test_belief_scope_not_visible_at_info(caplog):
with belief_scope("InfoLevelFunction"):
logger.info("Doing something important")
log_records = list(caplog.records)
log_messages = [record.message for record in log_records]
log_messages = [record.getMessage() for record in log_records]
# Inline INFO log should be visible
assert any("Doing something important" in msg for msg in log_messages), "INFO log not found"
# REASON uses DEBUG level in decision audit → NOT visible at INFO
@@ -205,7 +205,7 @@ def test_enable_belief_state_flag(caplog):
logger.info("Doing something")
log_records = list(caplog.records)
log_messages = [record.message for record in log_records]
log_messages = [record.getMessage() for record in log_records]
# "Entering DisabledFunction" (explicit logger.reason()) should NOT be logged when disabled
assert not any("Entering" in msg for msg in log_messages), "REASON entry should not be logged when disabled"

View File

@@ -16,7 +16,7 @@
from datetime import UTC, datetime
from sqlalchemy.orm import Session
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.logger import belief_scope, logger
from src.models.mapping import Environment, ResourceMapping, ResourceType

View File

@@ -38,7 +38,7 @@ import uuid
from starlette.types import ASGIApp, Receive, Scope, Send
from ss_tools.shared.cot_logger import get_trace_id, seed_trace_id, set_trace_id
from src.core.cot_logger import get_trace_id, seed_trace_id, set_trace_id
# #region Core.Trace.TraceContextMiddleware [C:2] [TYPE Class] [SEMANTICS middleware, trace, context, asgi]

View File

@@ -11,7 +11,7 @@ from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from .async_job_runner import AsyncJobRunner
from .config_manager import ConfigManager

View File

@@ -52,7 +52,7 @@ class SupersetDatasetsPreviewMixin:
elif isinstance(request_body, dict):
request_payload_keys = sorted(request_body.keys())
strategy_diagnostics = {'endpoint': endpoint_path, 'endpoint_kind': endpoint_kind, 'request_transport': request_transport, 'contains_root_datasource': endpoint_kind == 'v1_chart_data' and 'datasource' in query_context, 'contains_form_datasource': endpoint_kind.startswith('legacy_') and 'datasource' in legacy_form_data, 'contains_query_object_datasource': bool(query_context.get('queries')) and isinstance(query_context['queries'][0], dict) and ('datasource' in query_context['queries'][0]), 'request_param_keys': request_param_keys, 'request_payload_keys': request_payload_keys}
app_logger.reason('Attempting Superset dataset preview compilation strategy', extra={'dataset_id': dataset_id, **strategy_diagnostics, 'request_params': request_params, 'request_payload': request_body, 'legacy_form_data': legacy_form_data if endpoint_kind.startswith('legacy_') else None, 'query_context': query_context if endpoint_kind == 'v1_chart_data' else None, 'template_param_count': len(template_params or {}), 'filter_count': len(effective_filters or [])})
app_logger.reason('Attempting Superset dataset preview compilation strategy', payload={'dataset_id': dataset_id, **strategy_diagnostics})
try:
response = await self.client.request(method='POST', endpoint=endpoint_path, params=request_params or None, data=request_body, headers=request_headers or None)
normalized = self._extract_compiled_sql_from_preview_response(response)
@@ -66,9 +66,9 @@ class SupersetDatasetsPreviewMixin:
app_logger.reflect('Belief protocol postcondition checkpoint for SupersetClientCompileDatasetPreview')
return normalized
except Exception as exc:
failure_diagnostics = {**strategy_diagnostics, 'success': False, 'error': str(exc)}
failure_diagnostics = {**strategy_diagnostics, 'success': False, 'error': str(exc)[:200]}
strategy_attempts.append(failure_diagnostics)
app_logger.explore('Superset dataset preview compilation strategy failed', extra={'dataset_id': dataset_id, **failure_diagnostics, 'request_params': request_params, 'request_payload': request_body})
app_logger.explore('Superset dataset preview compilation strategy failed', payload={'dataset_id': dataset_id, **failure_diagnostics}, error=str(exc)[:200], error_code='SUPERSET_PREVIEW_STRATEGY_FAILED')
raise SupersetAPIError(f'Superset preview compilation failed for all known strategies (attempts={strategy_attempts!r})')
# #endregion Core.DatasetsPreview.SupersetClientCompileDatasetPreview
# #region Core.DatasetsPreview.SupersetClientBuildDatasetPreviewLegacyFormData [TYPE Function] [C:4]

View File

@@ -1,6 +1,10 @@
# #region Test.CanonicalCotEvent [C:1] [TYPE Module] [SEMANTICS test,cot,event,builder]
# @ingroup Core
# @BRIEF Tests for build_cot_event SSOT — protocol completeness and EXPLORE error fallback.
# @RELATION BINDS_TO -> [Shared.BuildCotEvent]
import pytest
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
def test_builder_creates_protocol_complete_event():
@@ -13,6 +17,15 @@ def test_builder_creates_protocol_complete_event():
assert event["payload"] == {"dashboard_id": "d1"}
def test_builder_rejects_explore_without_error():
with pytest.raises(ValueError, match="EXPLORE events require error"):
build_cot_event(src="task.migration.recover", marker="EXPLORE", intent="Fallback")
def test_builder_rejects_invalid_marker():
with pytest.raises(ValueError, match="Invalid CoT marker"):
build_cot_event(src="task.migration.recover", marker="NOPE", intent="x")
def test_explore_without_error_falls_back_to_intent():
# SSOT contract: EXPLORE always carries error — build_cot_event enforces it
# by falling back to intent (the falsification channel is never silent).
event = build_cot_event(src="task.migration.recover", marker="EXPLORE", intent="Fallback taken")
assert event["error"] == "Fallback taken"
assert event["level"] == "WARNING"
# #endregion Test.CanonicalCotEvent

View File

@@ -12,7 +12,7 @@
from collections.abc import Callable
from typing import Any
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
from ..logger import belief_scope
from .task_logger import TaskLogger

View File

@@ -23,7 +23,7 @@ import asyncio
from datetime import datetime
from typing import Any
from ss_tools.shared.cot_logger import (
from src.core.cot_logger import (
CanonicalCotEvent,
build_cot_event,
seed_trace_id,

View File

@@ -30,7 +30,7 @@ from typing import Any
from ..logger import logger as main_logger # For agent-centric CoT emission from task lifecycle
from ss_tools.shared.cot_logger import (
from src.core.cot_logger import (
clear_task_id,
get_task_id,
get_trace_id,

View File

@@ -118,7 +118,7 @@ class TaskManager:
if not task:
return
if event is None:
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
marker = "EXPLORE" if str(level or "INFO").upper() in {"WARNING", "ERROR"} else "REASON"
event = build_cot_event(
src=source if source and "." in source else f"task.{source or 'system'}",

View File

@@ -64,6 +64,11 @@ class LogEntry(BaseModel):
intent: str = ""
payload: dict[str, Any] | None = None
error: str | None = None
# ADR-0021 enriched fields (persisted into task_logs.payload for gap analytics)
contract_id: str | None = None
claim: str | None = None
error_code: str | None = None
loc: str | None = None
@model_validator(mode="before")
@classmethod

View File

@@ -370,6 +370,15 @@ class TaskLogPersistenceService:
if log.payload is not None
else None
)
# Merge ADR-0021 enriched fields into the persisted payload so
# task-log gap analytics (tier 2/3) can query them without a schema change.
enrichment = {
key: getattr(log, key, None)
for key in ("contract_id", "claim", "error_code", "loc")
}
enrichment = {k: v for k, v in enrichment.items() if v}
if enrichment:
safe_payload = {**(safe_payload or {}), **enrichment}
rows.append(
{
"task_id": task_id,

View File

@@ -9,7 +9,7 @@ import asyncio
from collections.abc import Callable
from typing import Any
from ss_tools.shared.cot_logger import build_cot_event, emit_cot_event, set_task_id
from src.core.cot_logger import build_cot_event, emit_cot_event, set_task_id
from ..logger import logger as main_cot_logger # noqa: TID252

View File

@@ -24,8 +24,8 @@ from openai import (
RateLimitError,
)
from ._llm_http import get_shared_http_client
from .logger import logger
from .llm_http import get_shared_http_client
from ..logger import logger
# ── LLM provider health cache ─────────────────────────────────────────
_llm_status: dict[str, Any] = {

View File

@@ -25,7 +25,7 @@ from typing import Any
import httpx
from .logger import logger
from ..logger import logger
from .ssl import httpx_verify
# Module-level singleton clients, lazily initialized

View File

@@ -93,7 +93,7 @@ def get_session_idle_timeout_minutes() -> int:
"Session idle timeout resolved to a non-integer; falling back to the policy cache",
src="Dependencies.AppDependencies.SessionPolicyConfig",
payload={"value_type": type(value).__name__},
error="SESSION_POLICY_CONFIG_INVALID",
error_code="SESSION_POLICY_CONFIG_INVALID",
)
return session_policy.idle_timeout_minutes

View File

@@ -20,7 +20,7 @@ from typing import Any
import httpx
from ...core.logger import logger
from ss_tools.shared._llm_http import (
from src.core.utils.llm_http import (
get_shared_http_client,
sanitize_url,
call_openai_compatible,

View File

@@ -18,7 +18,7 @@ from datetime import UTC, datetime, timedelta
import uuid
from sqlalchemy.orm import Session
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from ...core.config_manager import ConfigManager
from ...core.config_models import GlobalSettings

View File

@@ -11,7 +11,7 @@ from datetime import UTC, date, datetime
import json
from typing import Any
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from ..models.clean_release import CandidateArtifact, ReleaseCandidate
from ..services.clean_release.approval_service import (
approve_candidate,

View File

@@ -22,7 +22,7 @@ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BACKEND_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, "..", ".."))
if BACKEND_ROOT not in sys.path:
sys.path.insert(0, BACKEND_ROOT)
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.logger import logger
from src.models.clean_release import (
CandidateArtifact,

View File

@@ -18,7 +18,7 @@ import sys
# Add src to path
sys.path.append(str(Path(__file__).parent.parent.parent))
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.auth.repository import AuthRepository
from src.core.auth.security import get_password_hash

View File

@@ -14,7 +14,7 @@ import sys
# Add src to path
sys.path.append(str(Path(__file__).parent.parent.parent))
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.encryption_key import ensure_encryption_key
from src.core.logger import belief_scope, logger

View File

@@ -19,7 +19,7 @@ import sys
sys.path.append(str(Path(__file__).parent.parent.parent))
from src.core.auth.repository import AuthRepository
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.database import SessionLocal
from src.core.logger import belief_scope, logger
from src.models.auth import Permission, Role

View File

@@ -19,7 +19,7 @@ sys.path.append(str(Path(__file__).parent.parent.parent))
from src.core.config_manager import ConfigManager
from src.core.config_models import Environment
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.logger import belief_scope, logger
from src.core.superset_client import SupersetClient

View File

@@ -19,7 +19,7 @@ import sys
sys.path.append(str(Path(__file__).parent.parent.parent))
from src.core.config_manager import ConfigManager
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.logger import logger
from src.core.superset_client import SupersetClient

View File

@@ -13,17 +13,29 @@ from src.core.logger import logger
from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision
_SRC = "ScenarioEditor.Load.Editor"
# #region ScenarioEditor.Load.Editor [C:3] [TYPE Function] [SEMANTICS scenario,editor,load,readonly,draft]
# @ingroup ScenarioEditor
# @BRIEF Return entry, graph and base revision for a read-only editor view.
# @PRE scenario_id exists; revision_id is omitted or belongs to the scenario.
# @POST Returns dirty=false and base_revision_id; missing records return None.
# Contract-legitimate None returns are observable: each emits EXPLORE with claim
# and error_code (ADR-0021) — the falsification channel is never silent.
def load_editor(db: Session, scenario_id: str, revision_id: str | None = None) -> dict | None:
entry = db.query(ScenarioRegistryEntry).filter(
(ScenarioRegistryEntry.scenario_id == scenario_id) | (ScenarioRegistryEntry.scenario_key == scenario_id)
).first()
if entry is None:
logger.explore(
"Scenario not found for editor load",
src=_SRC,
claim="PRE: scenario_id exists",
error_code="EDITOR_SCENARIO_NOT_FOUND",
payload={"scenario_id": scenario_id, "revision_id": revision_id},
error="no registry entry by scenario_id or scenario_key",
)
return None
query = db.query(ScenarioRevision).filter(ScenarioRevision.scenario_id == entry.scenario_id)
if revision_id is not None:
@@ -33,6 +45,14 @@ def load_editor(db: Session, scenario_id: str, revision_id: str | None = None) -
if revision is None:
revision = query.order_by(ScenarioRevision.created_at.desc()).first()
if revision is None:
logger.explore(
"Revision not found for editor load",
src=_SRC,
claim="PRE: revision_id omitted or belongs to the scenario",
error_code="EDITOR_REVISION_NOT_FOUND",
payload={"scenario_id": entry.scenario_id, "revision_id": revision_id},
error="no current or latest revision rows for scenario",
)
return None
result = {
"scenario_id": entry.scenario_id,
@@ -43,7 +63,7 @@ def load_editor(db: Session, scenario_id: str, revision_id: str | None = None) -
"dirty": False,
"validation": {"status": entry.validation_status, "findings": []},
}
logger.reflect("Editor projection loaded", src="ScenarioEditor.Load.Editor", payload={
logger.reflect("Editor projection loaded", src=_SRC, claim="POST: dirty=false and base_revision_id", payload={
"scenario_id": entry.scenario_id, "base_revision_id": revision.revision_id,
})
return result

View File

@@ -74,7 +74,7 @@ def _default_limit(workload_class: str, environment_class: str) -> int:
logger.explore(
"Unknown workload class rejected", src=_SRC,
payload={"workload_class": workload_class},
error="CAPACITY_UNKNOWN_WORKLOAD_CLASS",
error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS",
)
raise ValueError("CAPACITY_UNKNOWN_WORKLOAD_CLASS")
if environment_class == "PROD":
@@ -117,7 +117,7 @@ def _get_or_create_quota(db: Session, *, environment_id: str, workload_class: st
logger.explore(
"Quota creation race lost without a recoverable row", src=_SRC,
payload={"environment_id": environment_id, "workload_class": workload_class},
error="CAPACITY_QUOTA_RACE_LOST",
error_code="CAPACITY_QUOTA_RACE_LOST",
)
raise CapacityUnavailable("CAPACITY_QUOTA_RACE_LOST") from None
logger.reflect("Quota creation race resolved to existing row", src=_SRC, payload={"workload_class": workload_class})
@@ -157,16 +157,16 @@ def claim_capacity(
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
) -> dict[str, Any]:
if not environment_id.strip() or not provider_id.strip():
logger.explore("Claim rejected: missing environment or provider identity", src=_SRC, error="CAPACITY_IDENTITY_INVALID")
logger.explore("Claim rejected: missing environment or provider identity", src=_SRC, error_code="CAPACITY_IDENTITY_INVALID")
raise ValueError("CAPACITY_IDENTITY_INVALID")
if workload_class not in _LEASE_WORKLOAD_CLASSES:
logger.explore("Claim rejected: unknown workload class", src=_SRC, payload={"workload_class": workload_class}, error="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
logger.explore("Claim rejected: unknown workload class", src=_SRC, payload={"workload_class": workload_class}, error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
raise ValueError("CAPACITY_UNKNOWN_WORKLOAD_CLASS")
if not isinstance(requested_units, int) or requested_units < 1 or requested_units > _MAX_UNITS_PER_CLAIM:
logger.explore("Claim rejected: units out of range", src=_SRC, payload={"requested_units": requested_units}, error="CAPACITY_UNITS_INVALID")
logger.explore("Claim rejected: units out of range", src=_SRC, payload={"requested_units": requested_units}, error_code="CAPACITY_UNITS_INVALID")
raise ValueError("CAPACITY_UNITS_INVALID")
if ttl_seconds <= 0:
logger.explore("Claim rejected: non-positive ttl", src=_SRC, payload={"ttl_seconds": ttl_seconds}, error="CAPACITY_TTL_INVALID")
logger.explore("Claim rejected: non-positive ttl", src=_SRC, payload={"ttl_seconds": ttl_seconds}, error_code="CAPACITY_TTL_INVALID")
raise ValueError("CAPACITY_TTL_INVALID")
logger.reason(
@@ -192,7 +192,7 @@ def claim_capacity(
logger.explore(
"Capacity exhausted for environment/workload pair", src=_SRC,
payload={"environment_id": environment_id, "workload_class": workload_class, "active_units": quota.active_units, "limit_units": quota.limit_units},
error="CAPACITY_UNAVAILABLE",
error_code="CAPACITY_UNAVAILABLE",
)
raise CapacityUnavailable("CAPACITY_UNAVAILABLE")
@@ -242,20 +242,20 @@ def heartbeat_capacity(db: Session, lease_id: str, *, ttl_seconds: int = _DEFAUL
raise ValueError("CAPACITY_TTL_INVALID")
lease = db.query(CapacityLease).filter(CapacityLease.id == lease_id).one_or_none()
if lease is None:
logger.explore("Heartbeat for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error="CAPACITY_LEASE_NOT_ACTIVE")
logger.explore("Heartbeat for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_NOT_ACTIVE")
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
if lease.status != "claimed":
logger.explore(
"Heartbeat for a non-claimed lease", src=_SRC,
payload={"lease_id": lease_id, "status": lease.status},
error="CAPACITY_LEASE_NOT_ACTIVE",
error_code="CAPACITY_LEASE_NOT_ACTIVE",
)
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
now = _now()
if _as_aware(lease.expires_at) <= now:
_expire_lease_and_free(db, lease, now=_db_now())
db.flush()
logger.explore("Heartbeat arrived after lease expiry", src=_SRC, payload={"lease_id": lease_id}, error="CAPACITY_LEASE_NOT_ACTIVE")
logger.explore("Heartbeat arrived after lease expiry", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_NOT_ACTIVE")
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
lease.expires_at = _db_now() + timedelta(seconds=ttl_seconds)
lease.heartbeat_at = _db_now()
@@ -273,7 +273,7 @@ def heartbeat_capacity(db: Session, lease_id: str, *, ttl_seconds: int = _DEFAUL
def release_capacity(db: Session, lease_id: str) -> dict[str, Any]:
lease = db.query(CapacityLease).filter(CapacityLease.id == lease_id).one_or_none()
if lease is None:
logger.explore("Release for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error="CAPACITY_LEASE_UNKNOWN")
logger.explore("Release for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_UNKNOWN")
raise CapacityUnavailable("CAPACITY_LEASE_UNKNOWN")
if lease.status != "claimed":
logger.reflect("Release is idempotent for a terminal lease", src=_SRC, payload={"lease_id": lease_id, "status": lease.status})
@@ -338,7 +338,7 @@ def _expire_lease_and_free(db: Session, lease: CapacityLease, *, now: datetime)
logger.explore(
"Lease expired without release", src=_SRC,
payload={"lease_id": lease.id, "workload_class": lease.workload_class},
error="CAPACITY_LEASE_EXPIRED",
error_code="CAPACITY_LEASE_EXPIRED",
)
quota = (
db.query(CapacityQuota)

View File

@@ -48,13 +48,13 @@ def _now() -> datetime:
# @POST Returns the receipt projection; a duplicate attempt raises PROVIDER_OPERATION_DUPLICATE.
def open_provider_operation(db, *, attempt: int, effect_state: str = "unknown", summary: dict[str, Any] | None = None, **identity: Any) -> dict[str, Any]:
if any(not str(identity.get(field) or "").strip() for field in _OPEN_REQUIRED_FIELDS):
logger.explore("Receipt rejected: missing identity fields", src=_SRC, error="PROVIDER_OPERATION_IDENTITY_INVALID")
logger.explore("Receipt rejected: missing identity fields", src=_SRC, error_code="PROVIDER_OPERATION_IDENTITY_INVALID")
raise ValueError("PROVIDER_OPERATION_IDENTITY_INVALID")
if not isinstance(attempt, int) or attempt < 1:
logger.explore("Receipt rejected: attempt must be a positive integer", src=_SRC, payload={"attempt": attempt}, error="PROVIDER_OPERATION_IDENTITY_INVALID")
logger.explore("Receipt rejected: attempt must be a positive integer", src=_SRC, payload={"attempt": attempt}, error_code="PROVIDER_OPERATION_IDENTITY_INVALID")
raise ValueError("PROVIDER_OPERATION_IDENTITY_INVALID")
if effect_state not in _EFFECT_STATES:
logger.explore("Receipt rejected: unknown effect state", src=_SRC, payload={"effect_state": effect_state}, error="PROVIDER_OPERATION_IDENTITY_INVALID")
logger.explore("Receipt rejected: unknown effect state", src=_SRC, payload={"effect_state": effect_state}, error_code="PROVIDER_OPERATION_IDENTITY_INVALID")
raise ValueError("PROVIDER_OPERATION_IDENTITY_INVALID")
now = _now()
receipt = ProviderOperationReceipt(
@@ -73,7 +73,7 @@ def open_provider_operation(db, *, attempt: int, effect_state: str = "unknown",
db.flush()
except Exception as exc:
db.rollback()
logger.explore("Receipt creation raced an existing attempt", src=_SRC, payload={"run_id": identity.get("run_id"), "attempt": attempt}, error="PROVIDER_OPERATION_DUPLICATE")
logger.explore("Receipt creation raced an existing attempt", src=_SRC, payload={"run_id": identity.get("run_id"), "attempt": attempt}, error_code="PROVIDER_OPERATION_DUPLICATE")
raise ValueError("PROVIDER_OPERATION_DUPLICATE") from exc
logger.reflect("Provider operation receipt opened", src=_SRC, payload={"operation_id": receipt.operation_id, "action": receipt.action, "attempt": attempt})
return _project(receipt)
@@ -88,17 +88,17 @@ def open_provider_operation(db, *, attempt: int, effect_state: str = "unknown",
# PROVIDER_OPERATION_TERMINAL instead of being overwritten.
def complete_provider_operation(db, operation_id: str, *, status: str, effect_state: str, summary: dict[str, Any] | None = None) -> dict[str, Any]:
if status not in _TERMINAL_STATUSES or effect_state not in _EFFECT_STATES:
logger.explore("Receipt completion rejected: invalid status/effect pair", src=_SRC, payload={"status": status, "effect_state": effect_state}, error="PROVIDER_OPERATION_IDENTITY_INVALID")
logger.explore("Receipt completion rejected: invalid status/effect pair", src=_SRC, payload={"status": status, "effect_state": effect_state}, error_code="PROVIDER_OPERATION_IDENTITY_INVALID")
raise ValueError("PROVIDER_OPERATION_IDENTITY_INVALID")
receipt = db.query(ProviderOperationReceipt).filter(ProviderOperationReceipt.operation_id == operation_id).one_or_none()
if receipt is None:
logger.explore("Completion for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error="PROVIDER_OPERATION_UNKNOWN")
logger.explore("Completion for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error_code="PROVIDER_OPERATION_UNKNOWN")
raise ValueError("PROVIDER_OPERATION_UNKNOWN")
if receipt.status in _TERMINAL_STATUSES:
logger.explore(
"Late response refused overwrite of a terminal receipt", src=_SRC,
payload={"operation_id": operation_id, "status": receipt.status, "requested": status},
error="PROVIDER_OPERATION_TERMINAL",
error_code="PROVIDER_OPERATION_TERMINAL",
)
raise ValueError("PROVIDER_OPERATION_TERMINAL")
receipt.status = status
@@ -121,17 +121,17 @@ def complete_provider_operation(db, operation_id: str, *, status: str, effect_st
# source status raises PROVIDER_OPERATION_TERMINAL.
def reconcile_provider_operation(db, operation_id: str, *, resolution: str, effect_state: str, note: str = "") -> dict[str, Any]:
if resolution not in {"completed", "failed"} or effect_state not in _EFFECT_STATES:
logger.explore("Reconciliation rejected: invalid resolution/effect pair", src=_SRC, payload={"resolution": resolution}, error="PROVIDER_OPERATION_IDENTITY_INVALID")
logger.explore("Reconciliation rejected: invalid resolution/effect pair", src=_SRC, payload={"resolution": resolution}, error_code="PROVIDER_OPERATION_IDENTITY_INVALID")
raise ValueError("PROVIDER_OPERATION_IDENTITY_INVALID")
receipt = db.query(ProviderOperationReceipt).filter(ProviderOperationReceipt.operation_id == operation_id).one_or_none()
if receipt is None:
logger.explore("Reconciliation for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error="PROVIDER_OPERATION_UNKNOWN")
logger.explore("Reconciliation for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error_code="PROVIDER_OPERATION_UNKNOWN")
raise ValueError("PROVIDER_OPERATION_UNKNOWN")
if receipt.status != "reconciliation_required":
logger.explore(
"Reconciliation refused for a receipt that is not reconciliation_required", src=_SRC,
payload={"operation_id": operation_id, "status": receipt.status},
error="PROVIDER_OPERATION_TERMINAL",
error_code="PROVIDER_OPERATION_TERMINAL",
)
raise ValueError("PROVIDER_OPERATION_TERMINAL")
receipt.history = [*list(receipt.history or []), {"at": _now().isoformat(), "kind": "reconciliation", "resolution": resolution, "effect_state": effect_state, "note": note}]
@@ -151,7 +151,7 @@ def reconcile_provider_operation(db, operation_id: str, *, resolution: str, effe
def record_late_response(db, operation_id: str, payload: dict[str, Any]) -> dict[str, Any]:
receipt = db.query(ProviderOperationReceipt).filter(ProviderOperationReceipt.operation_id == operation_id).one_or_none()
if receipt is None:
logger.explore("Late response for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error="PROVIDER_OPERATION_UNKNOWN")
logger.explore("Late response for unknown receipt", src=_SRC, payload={"operation_id": operation_id}, error_code="PROVIDER_OPERATION_UNKNOWN")
raise ValueError("PROVIDER_OPERATION_UNKNOWN")
receipt.history = [*list(receipt.history or []), {"at": _now().isoformat(), "kind": "late_response", "payload": payload}]
receipt.updated_at = _now()
@@ -201,7 +201,7 @@ _RECONCILER_LOCK = threading.Lock()
# @BRIEF Register the reviewed reconciler for one provider_id; later registrations replace earlier ones.
def register_provider_reconciler(provider_id: str, reconciler: Callable[[dict[str, Any]], dict[str, Any]]) -> None:
if not provider_id.strip() or not callable(reconciler):
logger.explore("Reconciler registration rejected", src=_SRC, payload={"provider_id": provider_id}, error="PROVIDER_RECONCILER_INVALID")
logger.explore("Reconciler registration rejected", src=_SRC, payload={"provider_id": provider_id}, error_code="PROVIDER_RECONCILER_INVALID")
raise ValueError("PROVIDER_RECONCILER_INVALID")
with _RECONCILER_LOCK:
_RECONCILERS[provider_id] = reconciler
@@ -246,7 +246,7 @@ def reconcile_stale_provider_operations(db, *, older_than_seconds: int = 300, li
logger.explore(
"Reconciler verdict invalid; receipt left unresolved", src=_SRC,
payload={"operation_id": receipt.operation_id, "verdict": verdict},
error="PROVIDER_RECONCILER_VERDICT_INVALID",
error_code="PROVIDER_RECONCILER_VERDICT_INVALID",
)
continue
reconcile_provider_operation(

View File

@@ -61,14 +61,14 @@ class ProviderExecutionContext:
logger.explore(
"Provider context rejected: missing identity fields", src=_SRC,
payload={"run_id": self.run_id, "attempt": self.attempt},
error="PROVIDER_CONTEXT_INVALID",
error_code="PROVIDER_CONTEXT_INVALID",
)
raise ValueError("PROVIDER_CONTEXT_INVALID")
if not isinstance(self.attempt, int) or self.attempt < 1:
logger.explore(
"Provider context rejected: attempt must be a positive integer", src=_SRC,
payload={"attempt": self.attempt},
error="PROVIDER_CONTEXT_INVALID",
error_code="PROVIDER_CONTEXT_INVALID",
)
raise ValueError("PROVIDER_CONTEXT_INVALID")
return self
@@ -109,7 +109,7 @@ class ProviderExecutionResult:
logger.explore(
"Provider result rejected by schema", src=_SRC,
payload={"status": self.status, "shape_errors": shape_errors},
error="PROVIDER_RESULT_INVALID",
error_code="PROVIDER_RESULT_INVALID",
)
raise ValueError("PROVIDER_RESULT_INVALID")
return self
@@ -128,7 +128,7 @@ def create_operation_receipt(context: ProviderExecutionContext, *, provider_id:
logger.explore(
"Receipt rejected: provider identity missing", src=_SRC,
payload={"provider_id": provider_id},
error="PROVIDER_RESULT_INVALID",
error_code="PROVIDER_RESULT_INVALID",
)
raise ValueError("PROVIDER_RESULT_INVALID")
logger.reason(

View File

@@ -87,7 +87,7 @@ class ProviderEventLoop:
logger.explore(
"Provider loop did not report readiness", src=_SRC,
payload={"max_inflight": self._max_inflight},
error="PROVIDER_LOOP_START_TIMEOUT",
error_code="PROVIDER_LOOP_START_TIMEOUT",
)
raise RuntimeError("PROVIDER_LOOP_START_TIMEOUT")
logger.reflect("Provider loop started", src=_SRC, payload={"max_inflight": self._max_inflight})
@@ -142,23 +142,23 @@ class ProviderEventLoop:
logger.explore(
"Submit arrived with an already expired deadline", src=_SRC,
payload={"remaining": remaining},
error="PROVIDER_SUBMIT_DEADLINE",
error_code="PROVIDER_SUBMIT_DEADLINE",
)
raise TimeoutError("PROVIDER_SUBMIT_DEADLINE")
if not self.is_running:
logger.explore("Submit before loop start", src=_SRC, error="PROVIDER_LOOP_NOT_RUNNING")
logger.explore("Submit before loop start", src=_SRC, error_code="PROVIDER_LOOP_NOT_RUNNING")
raise RuntimeError("PROVIDER_LOOP_NOT_RUNNING")
if not self._slots.acquire(timeout=remaining):
logger.explore(
"No submission slot acquired before deadline", src=_SRC,
payload={"max_inflight": self._max_inflight},
error="PROVIDER_SUBMIT_OVERFLOW",
error_code="PROVIDER_SUBMIT_OVERFLOW",
)
raise ProviderSubmissionOverflow("PROVIDER_SUBMIT_OVERFLOW")
loop = self._loop
if loop is None:
self._slots.release()
logger.explore("Loop stopped while acquiring slot", src=_SRC, error="PROVIDER_LOOP_NOT_RUNNING")
logger.explore("Loop stopped while acquiring slot", src=_SRC, error_code="PROVIDER_LOOP_NOT_RUNNING")
raise RuntimeError("PROVIDER_LOOP_NOT_RUNNING")
try:
future = asyncio.run_coroutine_threadsafe(coroutine_factory(), loop)
@@ -171,7 +171,7 @@ class ProviderEventLoop:
future.cancel()
logger.explore(
"Provider coroutine exceeded the caller deadline; cancelled", src=_SRC,
error="PROVIDER_SUBMIT_DEADLINE",
error_code="PROVIDER_SUBMIT_DEADLINE",
)
raise TimeoutError("PROVIDER_SUBMIT_DEADLINE") from None
finally:

View File

@@ -93,7 +93,7 @@ def _admit_browser_action(
step: dict[str, Any],
) -> tuple[LiveAdapterResult | None, dict[str, Any] | None]:
if not event_loop.is_running:
logger.explore("Provider loop is not running; no I/O admitted", src=_SRC, error="BROWSER_LOOP_UNAVAILABLE")
logger.explore("Provider loop is not running; no I/O admitted", src=_SRC, error_code="BROWSER_LOOP_UNAVAILABLE")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_LOOP_UNAVAILABLE"), None
binding, error = binding_from_step(step, tool_code="BROWSER")
if binding is None:
@@ -102,33 +102,33 @@ def _admit_browser_action(
metadata = step.get("step_meta") if isinstance(step.get("step_meta"), dict) else {}
run_id = step.get("scenario_run_id")
if not isinstance(run_id, str) or not run_id:
logger.explore("Browser step has no persisted run identity", src=_SRC, error="BROWSER_RUN_UNRESOLVED")
logger.explore("Browser step has no persisted run identity", src=_SRC, error_code="BROWSER_RUN_UNRESOLVED")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_RUN_UNRESOLVED"), None
if metadata.get("environment_id") != binding.environment_id or metadata.get("dashboard_id") != binding.dashboard_id:
logger.explore(
"Browser step identity mismatches the registered binding", src=_SRC,
payload={"binding_ref": binding.binding_ref},
error="BROWSER_TARGET_MISMATCH",
error_code="BROWSER_TARGET_MISMATCH",
)
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_TARGET_MISMATCH"), None
descriptor = metadata.get("action_descriptor") if isinstance(metadata.get("action_descriptor"), dict) else {}
action = str(descriptor.get("action") or "")
if not action:
logger.explore("Browser action descriptor missing", src=_SRC, error="BROWSER_ACTION_DESCRIPTOR_REQUIRED")
logger.explore("Browser action descriptor missing", src=_SRC, error_code="BROWSER_ACTION_DESCRIPTOR_REQUIRED")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_DESCRIPTOR_REQUIRED"), None
if str(descriptor.get("tool") or "browser") != "browser":
logger.explore("Browser descriptor tool mismatch", src=_SRC, payload={"action": action}, error="BROWSER_ACTION_TOOL_MISMATCH")
logger.explore("Browser descriptor tool mismatch", src=_SRC, payload={"action": action}, error_code="BROWSER_ACTION_TOOL_MISMATCH")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_TOOL_MISMATCH"), None
mutating = bool(descriptor.get("mutating"))
if mutating or action not in _READ_ONLY_ACTIONS:
if not mutating:
logger.explore("Unsupported browser action rejected before I/O", src=_SRC, payload={"action": action}, error="BROWSER_ACTION_NOT_SUPPORTED")
logger.explore("Unsupported browser action rejected before I/O", src=_SRC, payload={"action": action}, error_code="BROWSER_ACTION_NOT_SUPPORTED")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_NOT_SUPPORTED"), None
contract_error = validate_mutation_contract(metadata)
if contract_error is not None:
return LiveAdapterResult(status="inconclusive", reason_code=contract_error), None
if action not in _MUTATION_ACTIONS:
logger.explore("Mutating action outside the supported catalog", src=_SRC, payload={"action": action}, error="BROWSER_ACTION_NOT_SUPPORTED")
logger.explore("Mutating action outside the supported catalog", src=_SRC, payload={"action": action}, error_code="BROWSER_ACTION_NOT_SUPPORTED")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_NOT_SUPPORTED"), None
contract = metadata.get("mutation_contract") or {}
inputs_error = validate_mutation_inputs(descriptor.get("inputs"), contract)
@@ -139,10 +139,10 @@ def _admit_browser_action(
from src.services.dashboard_testing.scenario.templates import action_registry_fingerprint
if registry_fingerprint != action_registry_fingerprint():
logger.explore("Browser registry fingerprint mismatch", src=_SRC, error="BROWSER_REGISTRY_MISMATCH")
logger.explore("Browser registry fingerprint mismatch", src=_SRC, error_code="BROWSER_REGISTRY_MISMATCH")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_REGISTRY_MISMATCH"), None
if mutating and not str(metadata.get("logical_step_id") or "").strip():
logger.explore("Mutating action without a persisted step identity", src=_SRC, error="BROWSER_ACTION_DESCRIPTOR_REQUIRED")
logger.explore("Mutating action without a persisted step identity", src=_SRC, error_code="BROWSER_ACTION_DESCRIPTOR_REQUIRED")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_DESCRIPTOR_REQUIRED"), None
return None, {
"binding": binding,
@@ -172,13 +172,13 @@ def _store_browser_evidence(
logger.explore(
"Browser evidence exceeds the durable size limit", src=_SRC,
payload={"run_id": run_id, "bytes": len(evidence), "limit": max_screenshot_bytes},
error="BROWSER_EVIDENCE_TOO_LARGE",
error_code="BROWSER_EVIDENCE_TOO_LARGE",
)
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_EVIDENCE_TOO_LARGE"), [], {}
digest = sha256(evidence).hexdigest()
content_ref = storage.store(run_id, digest, evidence)
if content_ref != f"draft:{run_id}:{digest}":
logger.explore("Evidence storage returned an unexpected ref", src=_SRC, error="BROWSER_EVIDENCE_REF_INVALID")
logger.explore("Evidence storage returned an unexpected ref", src=_SRC, error_code="BROWSER_EVIDENCE_REF_INVALID")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_EVIDENCE_REF_INVALID"), [], {}
return None, [content_ref], {content_ref: digest}
# #endregion ScenarioExecution.BrowserProvider.Evidence
@@ -279,20 +279,20 @@ def build_browser_provider(
outcome = event_loop.submit(transport_factory, timeout=action_timeout_seconds * 3)
except TimeoutError:
if mutating:
logger.explore("Mutating action deadline expired with unknown effect", src=_SRC, payload={"run_id": run_id}, error="BROWSER_MUTATION_RECONCILE_REQUIRED")
logger.explore("Mutating action deadline expired with unknown effect", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_MUTATION_RECONCILE_REQUIRED")
_finalize_provider_receipt(operation_id, "reconciliation_required", "unknown", summary={"phase": "timeout"})
return LiveAdapterResult(
status="inconclusive",
reason_code="BROWSER_MUTATION_RECONCILE_REQUIRED",
details={"effect_state": "unknown", "reconciliation_required": True, "retry_disposition": "after_reconciliation", "operation_id": operation_id},
)
logger.explore("Browser action exceeded the deadline", src=_SRC, payload={"run_id": run_id}, error="BROWSER_ACTION_TIMEOUT")
logger.explore("Browser action exceeded the deadline", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_ACTION_TIMEOUT")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_ACTION_TIMEOUT")
except ProviderSubmissionOverflow:
logger.explore("Browser submission overflowed the bounded queue", src=_SRC, payload={"run_id": run_id}, error="BROWSER_LOOP_OVERFLOW")
logger.explore("Browser submission overflowed the bounded queue", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_LOOP_OVERFLOW")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_LOOP_OVERFLOW")
except BrowserTransportPreconditionMismatch:
logger.explore("Mutation precondition mismatch; nothing mutated", src=_SRC, payload={"run_id": run_id}, error="BROWSER_MUTATION_PRECONDITION_MISMATCH")
logger.explore("Mutation precondition mismatch; nothing mutated", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_MUTATION_PRECONDITION_MISMATCH")
_finalize_provider_receipt(operation_id, "failed", "not_started", summary={"phase": "precondition_mismatch"})
return LiveAdapterResult(
status="inconclusive",
@@ -300,7 +300,7 @@ def build_browser_provider(
details={"effect_state": "not_started", "retry_disposition": "manual_only", "operation_id": operation_id},
)
except BrowserTransportUnsupported:
logger.explore("Transport cannot execute the action; nothing started", src=_SRC, payload={"action": action}, error="BROWSER_ACTION_NOT_SUPPORTED")
logger.explore("Transport cannot execute the action; nothing started", src=_SRC, payload={"action": action}, error_code="BROWSER_ACTION_NOT_SUPPORTED")
_finalize_provider_receipt(operation_id, "failed", "not_started", summary={"phase": "unsupported"})
return LiveAdapterResult(
status="inconclusive",
@@ -309,10 +309,10 @@ def build_browser_provider(
)
except RuntimeError as exc:
if str(exc) == "PROVIDER_LOOP_NOT_RUNNING":
logger.explore("Provider loop stopped mid-dispatch", src=_SRC, error="BROWSER_LOOP_UNAVAILABLE")
logger.explore("Provider loop stopped mid-dispatch", src=_SRC, error_code="BROWSER_LOOP_UNAVAILABLE")
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_LOOP_UNAVAILABLE")
if mutating:
logger.explore("Mutating action failed with unknown effect", src=_SRC, payload={"run_id": run_id}, error="BROWSER_MUTATION_RECONCILE_REQUIRED")
logger.explore("Mutating action failed with unknown effect", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_MUTATION_RECONCILE_REQUIRED")
_finalize_provider_receipt(operation_id, "reconciliation_required", "unknown", summary={"phase": "runtime_error"})
return LiveAdapterResult(
status="inconclusive",
@@ -323,7 +323,7 @@ def build_browser_provider(
evidence = outcome.evidence_png
if not evidence:
logger.explore("Transport produced no evidence", src=_SRC, payload={"run_id": run_id}, error="BROWSER_EVIDENCE_REQUIRED")
logger.explore("Transport produced no evidence", src=_SRC, payload={"run_id": run_id}, error_code="BROWSER_EVIDENCE_REQUIRED")
_finalize_provider_receipt(operation_id, "reconciliation_required" if mutating else "failed", "unknown" if mutating else "not_started", summary={"phase": "evidence_missing"})
return LiveAdapterResult(status="inconclusive", reason_code="BROWSER_EVIDENCE_REQUIRED")
rejection, artifact_refs, artifact_digests = _store_browser_evidence(
@@ -371,7 +371,7 @@ def build_browser_provider(
release_capacity(db, lease_id)
db.commit()
except Exception:
logger.explore("Capacity release failed after browser action", src=_SRC, payload={"lease_id": lease_id}, error="CAPACITY_RELEASE_FAILED")
logger.explore("Capacity release failed after browser action", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_RELEASE_FAILED")
return provider
# #endregion ScenarioExecution.BrowserProvider.Factory

View File

@@ -82,32 +82,32 @@ _MUTATION_PAGE_BODY = r"""
# assignment field is allowlisted with typed values, otherwise a stable rejection code.
def validate_mutation_inputs(inputs: Any, contract: dict[str, Any]) -> str | None:
if not isinstance(inputs, dict):
logger.explore("Mutation inputs missing", src=_SRC, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Mutation inputs missing", src=_SRC, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
table = inputs.get("table")
key_columns = inputs.get("key_columns")
assignments = inputs.get("assignments")
database_id = inputs.get("database_id")
if not isinstance(table, str) or not table.strip() or not isinstance(key_columns, list) or not key_columns:
logger.explore("Mutation table/key columns invalid", src=_SRC, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Mutation table/key columns invalid", src=_SRC, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
if not isinstance(database_id, int) or database_id <= 0:
logger.explore("Mutation database_id invalid", src=_SRC, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Mutation database_id invalid", src=_SRC, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
if not isinstance(assignments, dict) or not assignments:
logger.explore("Mutation assignments invalid", src=_SRC, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Mutation assignments invalid", src=_SRC, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
allowlist = [str(field) for field in contract.get("field_allowlist", [])]
for field, value in assignments.items():
if str(field) not in allowlist:
logger.explore("Assignment field outside the contract allowlist", src=_SRC, payload={"field": str(field)}, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Assignment field outside the contract allowlist", src=_SRC, payload={"field": str(field)}, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
if not (isinstance(value, (int, float)) or isinstance(value, str)):
logger.explore("Assignment value type invalid", src=_SRC, payload={"field": str(field)}, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Assignment value type invalid", src=_SRC, payload={"field": str(field)}, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
target_keys = contract.get("target_keys", [])
if len(key_columns) != len(target_keys):
logger.explore("Key columns do not match contract target keys", src=_SRC, error="BROWSER_MUTATION_INPUTS_INVALID")
logger.explore("Key columns do not match contract target keys", src=_SRC, error_code="BROWSER_MUTATION_INPUTS_INVALID")
return "BROWSER_MUTATION_INPUTS_INVALID"
return None
# #endregion ScenarioExecution.BrowserProvider.MutationSQL.Validate
@@ -140,16 +140,16 @@ def build_mutation_script(inputs: dict[str, Any], contract: dict[str, Any]) -> s
def validate_mutation_contract(metadata: dict[str, Any]) -> str | None:
contract = metadata.get("mutation_contract")
if not isinstance(contract, dict):
logger.explore("Mutation contract missing", src=_SRC, error="BROWSER_MUTATION_CONTRACT_INVALID")
logger.explore("Mutation contract missing", src=_SRC, error_code="BROWSER_MUTATION_CONTRACT_INVALID")
return "BROWSER_MUTATION_CONTRACT_INVALID"
if any(not str(contract.get(key) or "").strip() for key in _MUTATION_CONTRACT_REQUIRED_KEYS if key != "target_keys"):
logger.explore("Mutation contract has empty required keys", src=_SRC, error="BROWSER_MUTATION_CONTRACT_INVALID")
logger.explore("Mutation contract has empty required keys", src=_SRC, error_code="BROWSER_MUTATION_CONTRACT_INVALID")
return "BROWSER_MUTATION_CONTRACT_INVALID"
if bool(contract.get("retry_safe", True)) is not False:
logger.explore("Mutation contract must be retry_safe=false", src=_SRC, error="BROWSER_MUTATION_CONTRACT_INVALID")
logger.explore("Mutation contract must be retry_safe=false", src=_SRC, error_code="BROWSER_MUTATION_CONTRACT_INVALID")
return "BROWSER_MUTATION_CONTRACT_INVALID"
if len(str(contract.get("precondition_hash"))) != 64 or any(c not in "0123456789abcdef" for c in str(contract.get("precondition_hash"))):
logger.explore("Mutation precondition hash is not a 64-hex digest", src=_SRC, error="BROWSER_MUTATION_PRECONDITION_INVALID")
logger.explore("Mutation precondition hash is not a 64-hex digest", src=_SRC, error_code="BROWSER_MUTATION_PRECONDITION_INVALID")
return "BROWSER_MUTATION_PRECONDITION_INVALID"
target_keys = contract.get("target_keys")
if (
@@ -158,11 +158,11 @@ def validate_mutation_contract(metadata: dict[str, Any]) -> str | None:
or len(target_keys) > _MAX_MUTATION_TARGET_KEYS
or any(not isinstance(key, str) or not key.strip() for key in target_keys)
):
logger.explore("Mutation target keys invalid", src=_SRC, error="BROWSER_MUTATION_TARGETS_INVALID")
logger.explore("Mutation target keys invalid", src=_SRC, error_code="BROWSER_MUTATION_TARGETS_INVALID")
return "BROWSER_MUTATION_TARGETS_INVALID"
allowlist = contract.get("field_allowlist")
if not isinstance(allowlist, list) or not allowlist or any(not isinstance(key, str) or not key.strip() for key in allowlist):
logger.explore("Mutation field allowlist invalid", src=_SRC, error="BROWSER_MUTATION_CONTRACT_INVALID")
logger.explore("Mutation field allowlist invalid", src=_SRC, error_code="BROWSER_MUTATION_CONTRACT_INVALID")
return "BROWSER_MUTATION_CONTRACT_INVALID"
return None
# #endregion ScenarioExecution.BrowserProvider.MutationSQL.Contract

View File

@@ -57,7 +57,7 @@ def build_browser_reconciler(service: Any) -> Callable[[dict[str, Any]], dict[st
target_keys = [str(key) for key in context_data.get("target_keys", [])]
dashboard_id = context_data.get("dashboard_id")
if not all(inputs.values()) or not target_keys or not dashboard_id:
logger.explore("Reconciliation context incomplete", src=_SRC, payload={"operation_id": receipt.get("operation_id")}, error="BROWSER_RECONCILE_CONTEXT_INVALID")
logger.explore("Reconciliation context incomplete", src=_SRC, payload={"operation_id": receipt.get("operation_id")}, error_code="BROWSER_RECONCILE_CONTEXT_INVALID")
return {"resolution": "failed", "effect_state": "unknown", "note": "mutation context missing"}
expected_rows = [{**inputs["assignments"], **dict(zip(inputs["key_columns"], target_keys))}]
@@ -80,7 +80,7 @@ def build_browser_reconciler(service: Any) -> Callable[[dict[str, Any]], dict[st
logger.explore(
"Reconciliation observed a divergent row state", src=_SRC,
payload={"operation_id": receipt.get("operation_id"), "expected": expected_rows, "current": observation.get("rows")},
error="BROWSER_RECONCILE_STATE_DIVERGED",
error_code="BROWSER_RECONCILE_STATE_DIVERGED",
)
return {"resolution": "failed", "effect_state": "unknown", "note": "target row state diverged from the recorded assignments"}

View File

@@ -112,7 +112,7 @@ def build_playwright_browser_transport(service: Any) -> BrowserActionTransport:
logger.explore(
"Precondition hash mismatch; mutation aborted before the UPDATE", src=_SRC,
payload={"pre_hash": flow.get("pre_hash")},
error="BROWSER_MUTATION_PRECONDITION_MISMATCH",
error_code="BROWSER_MUTATION_PRECONDITION_MISMATCH",
)
raise BrowserTransportPreconditionMismatch("BROWSER_MUTATION_PRECONDITION_MISMATCH")
checkpoints.append("row_edited" if action == "row_edit" else "bulk_edited")

View File

@@ -45,7 +45,7 @@ def check_browser_executable(run_async: Callable[[Any], Any]) -> str | None:
try:
return run_async(asyncio.wait_for(probe(), timeout=_BROWSER_PROBE_TIMEOUT_SECONDS))
except TimeoutError:
logger.explore("Browser executable probe timed out", src=_SRC, error="BROWSER_PROBE_TIMEOUT")
logger.explore("Browser executable probe timed out", src=_SRC, error_code="BROWSER_PROBE_TIMEOUT")
return "BROWSER_PROBE_TIMEOUT"
except Exception as exc:
logger.explore("Browser executable probe failed", src=_SRC, error=repr(exc))

View File

@@ -91,7 +91,7 @@ def build_screenshot_provider(
def provider(context: Any) -> LiveAdapterResult:
if not event_loop.is_running:
logger.explore("Provider loop is not running; no I/O admitted", src=_SRC, error="SCREENSHOT_LOOP_UNAVAILABLE")
logger.explore("Provider loop is not running; no I/O admitted", src=_SRC, error_code="SCREENSHOT_LOOP_UNAVAILABLE")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_LOOP_UNAVAILABLE")
step = context.step
binding, error = binding_from_step(step, tool_code="SCREENSHOT")
@@ -101,7 +101,7 @@ def build_screenshot_provider(
metadata = step.get("step_meta") if isinstance(step.get("step_meta"), dict) else {}
run_id = step.get("scenario_run_id")
if not isinstance(run_id, str) or not run_id:
logger.explore("Screenshot step has no persisted run identity", src=_SRC, error="SCREENSHOT_RUN_UNRESOLVED")
logger.explore("Screenshot step has no persisted run identity", src=_SRC, error_code="SCREENSHOT_RUN_UNRESOLVED")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_RUN_UNRESOLVED")
if (
metadata.get("environment_id") != binding.environment_id
@@ -110,7 +110,7 @@ def build_screenshot_provider(
logger.explore(
"Screenshot step identity mismatches the registered binding", src=_SRC,
payload={"binding_ref": binding.binding_ref},
error="SCREENSHOT_TARGET_MISMATCH",
error_code="SCREENSHOT_TARGET_MISMATCH",
)
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_TARGET_MISMATCH")
@@ -147,19 +147,19 @@ def build_screenshot_provider(
try:
jpeg_paths, _archive = event_loop.submit(capture_factory, timeout=capture_timeout_seconds)
except TimeoutError:
logger.explore("Screenshot capture exceeded the deadline", src=_SRC, payload={"run_id": run_id}, error="SCREENSHOT_CAPTURE_TIMEOUT")
logger.explore("Screenshot capture exceeded the deadline", src=_SRC, payload={"run_id": run_id}, error_code="SCREENSHOT_CAPTURE_TIMEOUT")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_CAPTURE_TIMEOUT")
except ProviderSubmissionOverflow:
logger.explore("Screenshot submission overflowed the bounded queue", src=_SRC, payload={"run_id": run_id}, error="SCREENSHOT_LOOP_OVERFLOW")
logger.explore("Screenshot submission overflowed the bounded queue", src=_SRC, payload={"run_id": run_id}, error_code="SCREENSHOT_LOOP_OVERFLOW")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_LOOP_OVERFLOW")
except RuntimeError as exc:
if str(exc) == "PROVIDER_LOOP_NOT_RUNNING":
logger.explore("Provider loop is not running", src=_SRC, error="SCREENSHOT_LOOP_UNAVAILABLE")
logger.explore("Provider loop is not running", src=_SRC, error_code="SCREENSHOT_LOOP_UNAVAILABLE")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_LOOP_UNAVAILABLE")
raise
if not jpeg_paths:
logger.explore("Capture service produced no screenshots", src=_SRC, payload={"run_id": run_id}, error="SCREENSHOT_CAPTURE_EMPTY")
logger.explore("Capture service produced no screenshots", src=_SRC, payload={"run_id": run_id}, error_code="SCREENSHOT_CAPTURE_EMPTY")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_CAPTURE_EMPTY")
artifact_refs: list[str] = []
@@ -170,13 +170,13 @@ def build_screenshot_provider(
logger.explore(
"Screenshot exceeds the durable size limit", src=_SRC,
payload={"run_id": run_id, "bytes": len(raw), "limit": max_screenshot_bytes},
error="SCREENSHOT_TOO_LARGE",
error_code="SCREENSHOT_TOO_LARGE",
)
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_TOO_LARGE")
digest = sha256(raw).hexdigest()
content_ref = storage.store(run_id, digest, raw)
if content_ref != f"draft:{run_id}:{digest}":
logger.explore("Evidence storage returned an unexpected ref", src=_SRC, error="SCREENSHOT_EVIDENCE_REF_INVALID")
logger.explore("Evidence storage returned an unexpected ref", src=_SRC, error_code="SCREENSHOT_EVIDENCE_REF_INVALID")
return LiveAdapterResult(status="inconclusive", reason_code="SCREENSHOT_EVIDENCE_REF_INVALID")
artifact_refs.append(content_ref)
artifact_digests[content_ref] = digest
@@ -208,7 +208,7 @@ def build_screenshot_provider(
release_capacity(db, lease_id)
db.commit()
except Exception:
logger.explore("Capacity release failed after capture", src=_SRC, payload={"lease_id": lease_id}, error="CAPACITY_RELEASE_FAILED")
logger.explore("Capacity release failed after capture", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_RELEASE_FAILED")
return provider
# #endregion ScenarioExecution.ScreenshotProvider.Factory

View File

@@ -199,7 +199,7 @@ def start_run(
logger.explore(
"Idempotency key reused with a different request", src="ScenarioExecution.Runner.start_run",
payload={"idempotency_key": idempotency_key},
error="IDEMPOTENCY_KEY_REUSED",
error_code="IDEMPOTENCY_KEY_REUSED",
)
raise ValueError("IDEMPOTENCY_KEY_REUSED")
logger.reflect(
@@ -382,7 +382,7 @@ def _block_run_on_capacity(db: Session, run: ScenarioRun, step: ScenarioStepRun,
logger.explore(
"Capacity refused provider I/O; run returned to queue", src=_SRC_CAPACITY,
payload={"run_id": run.id, "logical_step_id": step.logical_step_id, "error_code": outcome.get("error_code")},
error="CAPACITY_BLOCKED",
error_code="CAPACITY_BLOCKED",
)
step.status = "queued"
step.started_at = None

View File

@@ -17,7 +17,7 @@ from sqlalchemy import func
from sqlalchemy.orm import Session
from ..core.logger import logger
from ss_tools.shared.cot_logger import cot_span # agent-centric automatic REASON/REFLECT spans
from src.core.cot_logger import cot_span # agent-centric automatic REASON/REFLECT spans
from ..core.task_manager import TaskManager
from ..core.utils.client_registry import get_superset_client
from ..core.task_manager.cleanup import TaskCleanupService

View File

@@ -0,0 +1,116 @@
# #region Services.Reports.LogGapService [C:3] [TYPE Module] [SEMANTICS reports,triangulation,gap,belief,task-logs]
# @defgroup Services Module group.
# @BRIEF Ground-truth triangulation of invisible task failures (ADR-0021 / decision D2):
# a task that ended FAILED is a FACT; absence of any EXPLORE marker in its task_logs
# is a FACT — together they prove the falsification channel stayed silent. No parser,
# no AST guessing: semantics come from outcomes, not from code shape.
# @LAYER Domain
# @RELATION DEPENDS_ON -> [Models.Task.TaskRecord]
# @RELATION DEPENDS_ON -> [Models.Task.TaskLogRecord]
# @INVARIANT Read-only: never writes task_records/task_logs.
# @DATA_CONTRACT (Session, since_days, limit) -> {tier1_invisible_failures,
# tier2_unbound_explore, tier3_silent_fallbacks, generated_at, since_days}
# @RATIONALE Tiers: T1 = FAILED and no EXPLORE at all (worst: invisible failure);
# T2 = FAILED with EXPLORE but none carries error_code/contract_id in payload
# (visible but not bound to a contract — measures ADR-0021 adoption);
# T3 = SUCCESS with EXPLORE (systematic fallbacks under a green task — early
# degradation signal, advisory).
import json
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import exists, select
from sqlalchemy.orm import Session
from ...models.task import TaskLogRecord, TaskRecord
_ENRICH_KEYS = ("contract_id", "claim", "error_code", "loc")
# #region Services.Reports.LogGapService.ComputeGaps [C:3] [TYPE Function] [SEMANTICS gap,query,tiers]
# @ingroup Services
# @BRIEF Compute the three-tier invisible-failure report for recent tasks.
# @PRE db is an active Session; since_days >= 1.
# @POST Returns JSON-serializable report dict; lists capped by `limit`.
# @SIDE_EFFECT None (read-only queries).
def compute_task_log_gaps(db: Session, since_days: int = 7, limit: int = 200) -> dict[str, Any]:
since_days = max(1, int(since_days or 7))
limit = max(1, min(int(limit or 200), 1000))
cutoff = datetime.now(UTC) - timedelta(days=since_days)
explore_exists = exists(
select(TaskLogRecord.id).where(
TaskLogRecord.task_id == TaskRecord.id,
TaskLogRecord.marker == "EXPLORE",
)
)
recent = TaskRecord.created_at >= cutoff
tier1_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "FAILED", recent, ~explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
tier3_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "SUCCESS", recent, explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
failed_bound_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "FAILED", recent, explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
tier2_rows = []
for task in failed_bound_rows:
payloads = db.execute(
select(TaskLogRecord.payload).where(
TaskLogRecord.task_id == task.id,
TaskLogRecord.marker == "EXPLORE",
)
).all()
bound = False
for (payload,) in payloads:
data = payload if isinstance(payload, dict) else _as_dict(payload)
if data and any(data.get(key) for key in ("contract_id", "error_code")):
bound = True
break
if not bound:
tier2_rows.append(task)
def _task_view(task: TaskRecord) -> dict[str, Any]:
return {
"task_id": task.id,
"type": task.type,
"status": task.status,
"error": (task.error or "")[:300] or None,
"created_at": task.created_at.isoformat() if task.created_at else None,
"finished_at": task.finished_at.isoformat() if task.finished_at else None,
}
return {
"since_days": since_days,
"generated_at": datetime.now(UTC).isoformat(timespec="seconds"),
"tier1_invisible_failures": [_task_view(t) for t in tier1_rows],
"tier2_unbound_explore": [_task_view(t) for t in tier2_rows],
"tier3_silent_fallbacks": [_task_view(t) for t in tier3_rows],
}
def _as_dict(payload: Any) -> dict[str, Any] | None:
if isinstance(payload, (str, bytes)):
try:
parsed = json.loads(payload)
return parsed if isinstance(parsed, dict) else None
except (TypeError, ValueError):
return None
return None
# #endregion Services.Reports.LogGapService.ComputeGaps
# #endregion Services.Reports.LogGapService

View File

@@ -17,15 +17,11 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
# Add shared/src to path for ss_tools.shared._llm_health
# Ensure backend/src is importable for src.api / src.core modules
_src = str(Path(__file__).resolve().parent.parent.parent / "src")
if _src not in sys.path:
sys.path.insert(0, _src)
_shared_src = str(Path(__file__).resolve().parent.parent.parent.parent / "shared" / "src")
if _shared_src not in sys.path:
sys.path.insert(0, _shared_src)
def _make_client() -> TestClient:
"""Build a TestClient with the agent status router."""
@@ -39,8 +35,8 @@ def _make_client() -> TestClient:
class TestGetLlmStatus:
"""GET /api/agent/llm-status"""
@patch("ss_tools.shared._llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
@patch("ss_tools.shared._llm_health._llm_status", {"status": "ok", "last_error": ""})
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
@patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""})
def test_status_ok(self):
"""Returns ok when LLM provider is healthy."""
client = _make_client()
@@ -52,8 +48,8 @@ class TestGetLlmStatus:
assert data["last_error"] == ""
assert data["retry_after_s"] == 0
@patch("ss_tools.shared._llm_health._check_llm_provider_health", AsyncMock(return_value="unavailable"))
@patch("ss_tools.shared._llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"})
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="unavailable"))
@patch("src.core.utils.llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"})
def test_status_unavailable(self):
"""Returns unavailable with retry_after_s > 0."""
client = _make_client()
@@ -65,8 +61,8 @@ class TestGetLlmStatus:
assert data["last_error"] == "Provider unreachable"
assert data["retry_after_s"] == 30
@patch("ss_tools.shared._llm_health._check_llm_provider_health", AsyncMock(return_value="timeout"))
@patch("ss_tools.shared._llm_health._llm_status", {"status": "timeout", "last_error": "Request timed out"})
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="timeout"))
@patch("src.core.utils.llm_health._llm_status", {"status": "timeout", "last_error": "Request timed out"})
def test_status_timeout(self):
"""Returns timeout status."""
client = _make_client()
@@ -75,8 +71,8 @@ class TestGetLlmStatus:
assert resp.status_code == 200
assert resp.json()["status"] == "timeout"
@patch("ss_tools.shared._llm_health._check_llm_provider_health", AsyncMock(return_value="auth_error"))
@patch("ss_tools.shared._llm_health._llm_status", {"status": "auth_error", "last_error": "Invalid API key"})
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="auth_error"))
@patch("src.core.utils.llm_health._llm_status", {"status": "auth_error", "last_error": "Invalid API key"})
def test_status_auth_error(self):
"""Returns auth_error status."""
client = _make_client()
@@ -86,8 +82,8 @@ class TestGetLlmStatus:
assert resp.json()["status"] == "auth_error"
assert resp.json()["last_error"] == "Invalid API key"
@patch("ss_tools.shared._llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
@patch("ss_tools.shared._llm_health._llm_status", {"status": "ok", "last_error": ""})
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
@patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""})
def test_no_auth_required(self):
"""Status endpoint does not require authentication."""
client = _make_client()
@@ -99,8 +95,8 @@ class TestGetLlmStatus:
"""_check_llm_provider_health is called on each request."""
mock_check = AsyncMock(return_value="ok")
with (
patch("ss_tools.shared._llm_health._check_llm_provider_health", mock_check),
patch("ss_tools.shared._llm_health._llm_status", {"status": "ok", "last_error": ""}),
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""}),
):
client = _make_client()
resp = client.get("/api/agent/llm-status")
@@ -113,8 +109,8 @@ class TestGetLlmStatus:
"Retry now" button gets a fresh probe instead of the 30s cached status."""
mock_check = AsyncMock(return_value="unavailable")
with (
patch("ss_tools.shared._llm_health._check_llm_provider_health", mock_check),
patch("ss_tools.shared._llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"}),
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
patch("src.core.utils.llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"}),
):
client = _make_client()
resp = client.get("/api/agent/llm-status?force=true")
@@ -127,8 +123,8 @@ class TestGetLlmStatus:
"""Without the force param the health check is called with force=False (cached)."""
mock_check = AsyncMock(return_value="ok")
with (
patch("ss_tools.shared._llm_health._check_llm_provider_health", mock_check),
patch("ss_tools.shared._llm_health._llm_status", {"status": "ok", "last_error": ""}),
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""}),
):
client = _make_client()
resp = client.get("/api/agent/llm-status")

View File

@@ -192,4 +192,100 @@ class TestGetReportDetail:
resp = client.get("/api/reports/report-missing")
assert resp.status_code == 404
assert "REPORT_NOT_FOUND" in resp.text
# ── analytics endpoints (ADR-0021) ──
class TestTailLines:
"""_tail_lines — seek-from-end reading for the polled window=file mode."""
def test_small_file_fully_read(self, tmp_path):
from src.api.routes.reports import _tail_lines
p = tmp_path / "small.log"
p.write_text("a\nb\nc\n", encoding="utf-8")
assert _tail_lines(p, 10) == ["a", "b", "c"]
def test_returns_last_limit_lines(self, tmp_path):
from src.api.routes.reports import _tail_lines
p = tmp_path / "app.log"
p.write_text("".join(f'{{"i": {i}}}\n' for i in range(100)), encoding="utf-8")
lines = _tail_lines(p, 5)
assert len(lines) == 5
import json as _json
assert _json.loads(lines[-1])["i"] == 99
def test_large_file_seek_drops_partial_line(self, tmp_path):
import json as _json
from src.api.routes.reports import _tail_lines
p = tmp_path / "big.log"
line = '{"i": %d, "pad": "' + "x" * 80 + '"}'
p.write_text("".join((line % i) + "\n" for i in range(3000)), encoding="utf-8")
assert p.stat().st_size > 64 * 1024 # forces the seek path
lines = _tail_lines(p, 25)
assert len(lines) == 25
for raw in lines:
_json.loads(raw) # no partial line fragments
assert _json.loads(lines[-1])["i"] == 2999
def test_missing_file_returns_empty(self, tmp_path):
from src.api.routes.reports import _tail_lines
assert _tail_lines(tmp_path / "nope.log", 10) == []
class TestGetLogStats:
"""GET /api/reports/log-stats — single-engine analytics endpoint."""
def test_buffer_window_shape(self):
client = _make_client()
resp = client.get("/api/reports/log-stats")
assert resp.status_code == 200
body = resp.json()
assert body["window"] == "buffer"
assert "lines" in body["stats"]
assert "marker_mix" in body["stats"]
assert "transitions_normalized" in body["stats"]
def test_invalid_window_rejected(self):
client = _make_client()
resp = client.get("/api/reports/log-stats", params={"window": "nope"})
assert resp.status_code == 422
def test_file_window_shape(self):
client = _make_client()
resp = client.get("/api/reports/log-stats", params={"window": "file"})
assert resp.status_code == 200
assert resp.json()["window"] == "file"
class TestGetTaskLogGaps:
"""GET /api/reports/task-log-gaps — three-tier triangulation endpoint."""
def test_returns_three_tiers(self):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from src.core.database import get_db
from src.models.task import TaskLogRecord, TaskRecord
# TestClient runs the ASGI app in a worker thread — share one in-memory
# connection across threads (StaticPool + check_same_thread=False).
engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TaskRecord.__table__.create(engine)
TaskLogRecord.__table__.create(engine)
session = sessionmaker(bind=engine)()
try:
client = _make_client(overrides={get_db: lambda: session})
resp = client.get("/api/reports/task-log-gaps")
assert resp.status_code == 200
body = resp.json()
for key in ("tier1_invisible_failures", "tier2_unbound_explore",
"tier3_silent_fallbacks"):
assert isinstance(body[key], list)
finally:
session.close()
# #endregion Test.Api.ReportsRoutes

View File

@@ -124,7 +124,7 @@ class TestEventBusAddLog:
@pytest.mark.asyncio
async def test_canonical_event_without_level_argument_uses_event_level(self, event_bus):
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
event = build_cot_event(
src="task.plugin",

View File

@@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch, PropertyMock
import pytest
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
from src.core.task_manager.models import LogFilter, LogStats, Task, TaskStatus

View File

@@ -17,13 +17,13 @@ class TestSeedTraceId:
"""seed_trace_id — generates UUID and sets ContextVar."""
def test_returns_uuid_string(self):
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
tid = seed_trace_id()
assert isinstance(tid, str)
assert len(tid) == 32 # UUID4 hex format (no hyphens)
def test_sets_trace_id(self):
from ss_tools.shared.cot_logger import seed_trace_id, get_trace_id
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
@@ -32,7 +32,7 @@ class TestSetTraceId:
"""set_trace_id — sets explicit trace ID."""
def test_sets_provided_id(self):
from ss_tools.shared.cot_logger import set_trace_id, get_trace_id
from src.core.cot_logger import set_trace_id, get_trace_id
set_trace_id("custom-trace-123")
assert get_trace_id() == "custom-trace-123"
@@ -41,13 +41,13 @@ class TestGetTraceId:
"""get_trace_id — returns current trace ID."""
def test_default_empty(self):
from ss_tools.shared.cot_logger import get_trace_id
from src.core.cot_logger import get_trace_id
# After seed, get_trace_id returns non-empty
# In a fresh test the ContextVar may be empty
pass # ContextVar has default ""
def test_after_seed_returns_value(self):
from ss_tools.shared.cot_logger import seed_trace_id, get_trace_id
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
@@ -56,7 +56,7 @@ class TestPushPopSpan:
"""push_span and pop_span — span stack operations."""
def test_push_returns_previous(self):
from ss_tools.shared.cot_logger import push_span, pop_span
from src.core.cot_logger import push_span, pop_span
prev1 = push_span("span-1")
# Initially empty
prev2 = push_span("span-2")
@@ -65,12 +65,12 @@ class TestPushPopSpan:
# After pop, current span is back to "span-1"
def test_push_pop_restores(self):
from ss_tools.shared.cot_logger import push_span
from src.core.cot_logger import push_span
prev = push_span("outer")
inner_prev = push_span("inner")
assert inner_prev == "outer"
# pop restores outer
from ss_tools.shared.cot_logger import pop_span
from src.core.cot_logger import pop_span
pop_span(inner_prev)
@@ -78,8 +78,8 @@ class TestLog:
"""log — structured JSON logging with markers."""
def test_reason_marker_info_level(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.info") as mock_info:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("TestModule", "REASON", "Testing reason")
mock_info.assert_called_once()
args, kwargs = mock_info.call_args
@@ -90,60 +90,60 @@ class TestLog:
assert extra["intent"] == "Testing reason"
def test_reflect_marker_info_level(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.info") as mock_info:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REFLECT", "Reflecting")
mock_info.assert_called_once()
def test_explore_marker_warning_level(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.warning") as mock_warn:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Exploring alternatives", error="Assumption violated")
mock_warn.assert_called_once()
def test_error_level_explicit(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.error") as mock_err:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.error") as mock_err:
log("Test", "REASON", "Error test", level="ERROR")
mock_err.assert_called_once()
def test_debug_level_explicit(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.debug") as mock_debug:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.debug") as mock_debug:
log("Test", "REASON", "Debug test", level="DEBUG")
mock_debug.assert_called_once()
def test_payload_included(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.info") as mock_info:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "With payload", payload={"key": "value"})
extra = mock_info.call_args[1]["extra"]
assert extra["payload"] == {"key": "value"}
def test_error_included(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.warning") as mock_warn:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Error case", error="Something broke")
extra = mock_warn.call_args[1]["extra"]
assert extra["error"] == "Something broke"
def test_payload_not_included_when_none(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.info") as mock_info:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "No payload")
extra = mock_info.call_args[1]["extra"]
assert "payload" not in extra
def test_error_not_included_when_none(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.info") as mock_info:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "No error")
extra = mock_info.call_args[1]["extra"]
assert "error" not in extra
def test_warning_level_inferred_from_explore(self):
from ss_tools.shared.cot_logger import log
with patch("ss_tools.shared.cot_logger.cot_logger.warning") as mock_warn:
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Auto warning")
mock_warn.assert_called_once()
@@ -152,7 +152,7 @@ class TestBuildCotEvent:
"""Canonical event construction enforces EXPLORE's explanation invariant."""
def test_explore_without_error_uses_intent_as_error(self):
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
event = build_cot_event(
src="task.test",
@@ -168,18 +168,141 @@ class TestTraceIdPropagation:
"""Trace ID propagation across async contexts."""
def test_seed_then_get(self):
from ss_tools.shared.cot_logger import seed_trace_id, get_trace_id
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
def test_set_then_get(self):
from ss_tools.shared.cot_logger import set_trace_id, get_trace_id
from src.core.cot_logger import set_trace_id, get_trace_id
set_trace_id("abc-123")
assert get_trace_id() == "abc-123"
def test_set_overrides_seed(self):
from ss_tools.shared.cot_logger import seed_trace_id, set_trace_id, get_trace_id
from src.core.cot_logger import seed_trace_id, set_trace_id, get_trace_id
seed_trace_id()
set_trace_id("override")
assert get_trace_id() == "override"
class TestContractScope:
"""contract_id ContextVar inheritance (ADR-0021 self-diagnosing EXPLORE)."""
def test_set_and_get(self):
from src.core.cot_logger import set_contract_scope, reset_contract_scope, get_contract_id
token = set_contract_scope("Core.Demo.Contract")
try:
assert get_contract_id() == "Core.Demo.Contract"
finally:
reset_contract_scope(token)
assert get_contract_id() == ""
def test_nested_scopes_restore_previous(self):
from src.core.cot_logger import set_contract_scope, reset_contract_scope, get_contract_id
outer = set_contract_scope("Outer.Contract")
inner = set_contract_scope("Inner.Contract")
assert get_contract_id() == "Inner.Contract"
reset_contract_scope(inner)
assert get_contract_id() == "Outer.Contract"
reset_contract_scope(outer)
assert get_contract_id() == ""
def test_event_inherits_scope_contract(self):
from src.core.cot_logger import build_cot_event, set_contract_scope, reset_contract_scope
token = set_contract_scope("Scoped.Contract")
try:
event = build_cot_event(src="some.func", marker="REASON", intent="x")
assert event["contract_id"] == "Scoped.Contract"
finally:
reset_contract_scope(token)
def test_explicit_contract_overrides_scope(self):
from src.core.cot_logger import build_cot_event, set_contract_scope, reset_contract_scope
token = set_contract_scope("Scoped.Contract")
try:
event = build_cot_event(
src="s", marker="REASON", intent="x", contract_id="Explicit.Contract"
)
assert event["contract_id"] == "Explicit.Contract"
finally:
reset_contract_scope(token)
class TestContractMirroring:
"""Explicit src mirrors into contract_id; derived src never mirrors."""
def test_explicit_src_mirrors(self):
from src.core.cot_logger import build_cot_event
event = build_cot_event(
src="ScenarioExecution.BrowserProvider", marker="EXPLORE", intent="failed", error="x"
)
assert event["contract_id"] == "ScenarioExecution.BrowserProvider"
def test_empty_contract_suppresses_mirror(self):
from src.core.cot_logger import build_cot_event
event = build_cot_event(src="auto.derived.name", marker="REASON", intent="x", contract_id="")
assert "contract_id" not in event
def test_log_derived_src_not_mirrored(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("", "REASON", "poor src")
extra = mock_info.call_args[1]["extra"]
assert "contract_id" not in extra
def test_cot_span_derived_src_not_mirrored(self):
"""Span src is a python path, not a GRACE ID — must never populate contract_id."""
from src.core.cot_logger import cot_span
@cot_span()
def spanned_op(n):
return n + 1
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
assert spanned_op(1) == 2
for call in mock_info.call_args_list:
assert "contract_id" not in call[1]["extra"]
def test_cot_span_inherits_contract_scope(self):
from src.core.cot_logger import cot_span, set_contract_scope, reset_contract_scope
@cot_span()
def spanned_op(n):
return n + 1
token = set_contract_scope("Scoped.Contract")
try:
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
spanned_op(2)
infos = [c[1]["extra"] for c in mock_info.call_args_list]
assert infos and all(e.get("contract_id") == "Scoped.Contract" for e in infos)
finally:
reset_contract_scope(token)
class TestEnrichedFields:
"""Optional additive fields: claim / error_code / loc."""
def test_claim_and_error_code_present(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Mod.Func", "EXPLORE", "not found", error="assumption broken",
claim="PRE: record exists", error_code="DEMO_NOT_FOUND")
extra = mock_warn.call_args[1]["extra"]
assert extra["claim"] == "PRE: record exists"
assert extra["error_code"] == "DEMO_NOT_FOUND"
def test_loc_present_on_explore(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Mod.Func", "EXPLORE", "boom", error="x")
extra = mock_warn.call_args[1]["extra"]
assert "loc" in extra
assert "test_cot_logger.py:" in extra["loc"]
def test_loc_absent_on_reason(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Mod.Func", "REASON", "planned step")
extra = mock_info.call_args[1]["extra"]
assert "loc" not in extra
# #endregion Test.CotLogger

View File

@@ -19,7 +19,7 @@ import pytest
@pytest.mark.asyncio
async def test_llm_rate_limit_uses_asyncio_sleep():
"""Verify call_openai_compatible retries on 429 using asyncio.sleep, not time.sleep."""
from ss_tools.shared._llm_http import call_openai_compatible
from src.core.utils.llm_http import call_openai_compatible
call_count = 0
@@ -48,7 +48,7 @@ async def test_llm_rate_limit_uses_asyncio_sleep():
mock_client = AsyncMock()
mock_client.post = AsyncMock(side_effect=mock_post_side_effect)
with patch("ss_tools.shared._llm_http.get_shared_http_client", return_value=mock_client):
with patch("src.core.utils.llm_http.get_shared_http_client", return_value=mock_client):
# Patch asyncio.sleep to verify it's called (not time.sleep)
sleep_calls = []
original_sleep = asyncio.sleep
@@ -57,7 +57,7 @@ async def test_llm_rate_limit_uses_asyncio_sleep():
sleep_calls.append(seconds)
await original_sleep(0) # Don't actually wait
with patch("ss_tools.shared._llm_http.asyncio.sleep", side_effect=tracking_sleep):
with patch("src.core.utils.llm_http.asyncio.sleep", side_effect=tracking_sleep):
content, finish_reason = await call_openai_compatible(
base_url="http://fake-llm.local",
api_key="test-key",
@@ -77,7 +77,7 @@ async def test_llm_rate_limit_uses_asyncio_sleep():
@pytest.mark.asyncio
async def test_call_openai_compatible_no_base_url():
"""Verify empty base_url raises ValueError immediately."""
from ss_tools.shared._llm_http import call_openai_compatible
from src.core.utils.llm_http import call_openai_compatible
with pytest.raises(ValueError, match="no base_url"):
await call_openai_compatible(
@@ -97,7 +97,7 @@ async def test_call_openai_compatible_no_base_url():
@pytest.mark.asyncio
async def test_call_openai_compatible_empty_choices():
"""Verify LLM response with empty choices raises ValueError."""
from ss_tools.shared._llm_http import call_openai_compatible
from src.core.utils.llm_http import call_openai_compatible
mock_response = MagicMock(spec=httpx.Response)
mock_response.status_code = 200
@@ -108,9 +108,9 @@ async def test_call_openai_compatible_empty_choices():
mock_client = AsyncMock()
mock_client.post = AsyncMock(return_value=mock_response)
with patch("ss_tools.shared._llm_http.get_shared_http_client", return_value=mock_client):
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http.get_shared_http_client", return_value=mock_client):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="no choices"):
await call_openai_compatible(
base_url="http://fake-llm.local",
@@ -129,7 +129,7 @@ async def test_call_openai_compatible_empty_choices():
@pytest.mark.asyncio
async def test_call_openai_compatible_refusal():
"""Verify LLM refusal response raises ValueError."""
from ss_tools.shared._llm_http import call_openai_compatible
from src.core.utils.llm_http import call_openai_compatible
mock_response = MagicMock(spec=httpx.Response)
mock_response.status_code = 200
@@ -142,9 +142,9 @@ async def test_call_openai_compatible_refusal():
mock_client = AsyncMock()
mock_client.post = AsyncMock(return_value=mock_response)
with patch("ss_tools.shared._llm_http.get_shared_http_client", return_value=mock_client):
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http.get_shared_http_client", return_value=mock_client):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="refused"):
await call_openai_compatible(
base_url="http://fake-llm.local",
@@ -163,7 +163,7 @@ async def test_call_openai_compatible_refusal():
@pytest.mark.asyncio
async def test_retry_does_not_block_event_loop():
"""Verify that 429 retry backoff allows other coroutines to run."""
from ss_tools.shared._llm_http import _do_http_request
from src.core.utils.llm_http import _do_http_request
concurrent_ran = False
@@ -193,7 +193,7 @@ async def test_retry_does_not_block_event_loop():
mock_client = AsyncMock()
mock_client.post = AsyncMock(side_effect=mock_post)
with patch("ss_tools.shared._llm_http.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
with patch("src.core.utils.llm_http.asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
# Run the HTTP request alongside a concurrent task
http_task = asyncio.create_task(_do_http_request(mock_client, "http://fake", {}, {}))
conc_task = asyncio.create_task(concurrent_task())

View File

@@ -17,13 +17,13 @@ sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))
import pytest
import httpx
from ss_tools.shared._llm_http import (
from src.core.utils.llm_http import (
_do_http_request,
_handle_response_format_fallback,
call_openai_compatible,
get_shared_http_client,
)
from ss_tools.shared.ssl import httpx_verify, system_ssl_context
from src.core.utils.ssl import httpx_verify, system_ssl_context
class TestGetVerify:
@@ -87,8 +87,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [{"finish_reason": "stop", "message": {"content": "Hello, world!"}}]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
content, finish_reason = await call_openai_compatible(
"https://api.openai.com",
"sk-test",
@@ -111,8 +111,8 @@ class TestCallOpenaiCompatible:
mock_response.text = "<html>upstream unavailable</html>"
mock_response.json.side_effect = json.JSONDecodeError("Expecting value", "", 0)
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="invalid JSON") as exc_info:
await call_openai_compatible(
"https://api.openai.com",
@@ -134,8 +134,8 @@ class TestCallOpenaiCompatible:
mock_response.json.return_value = {"choices": []}
mock_response.text = '{"choices": []}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="no choices"):
await call_openai_compatible(
"https://api.openai.com",
@@ -160,8 +160,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [{"finish_reason": "stop", "message": {"content": ""}}]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="empty content"):
await call_openai_compatible(
"https://api.openai.com",
@@ -181,8 +181,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [null]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="LLM response processing failed"):
await call_openai_compatible(
"https://api.openai.com",
@@ -207,8 +207,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [{"finish_reason": "stop", "message": {"refusal": "I cannot answer that", "content": null}}]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(ValueError, match="refused"):
await call_openai_compatible(
"https://api.openai.com",
@@ -230,8 +230,8 @@ class TestCallOpenaiCompatible:
)
mock_response.text = "Internal Server Error"
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with pytest.raises(httpx.HTTPStatusError):
await call_openai_compatible(
"https://api.openai.com",
@@ -252,8 +252,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [{"finish_reason": "stop", "message": {"content": "hi"}}]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
# disable_reasoning=False, so response_format should be set
content, _ = await call_openai_compatible(
"https://api.openai.com",
@@ -277,8 +277,8 @@ class TestCallOpenaiCompatible:
}
mock_response.text = '{"choices": [{"finish_reason": "stop", "message": {"content": "hi"}}]}'
with patch("ss_tools.shared._llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("ss_tools.shared._llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
with patch("src.core.utils.llm_http._do_http_request", AsyncMock(return_value=(mock_response, mock_response.text))):
with patch("src.core.utils.llm_http._handle_response_format_fallback", AsyncMock(side_effect=lambda _c, resp, text, *a, **k: (resp, text))):
content, _ = await call_openai_compatible(
"https://api.openai.com",
"sk-test",
@@ -327,7 +327,7 @@ class TestDoHttpRequest:
mock_client.post.side_effect = [mock_429, mock_200]
with patch("ss_tools.shared._llm_http.asyncio.sleep", AsyncMock()):
with patch("src.core.utils.llm_http.asyncio.sleep", AsyncMock()):
response, text = await _do_http_request(
mock_client,
"https://api.openai.com/chat/completions",
@@ -352,7 +352,7 @@ class TestDoHttpRequest:
mock_client.post.side_effect = [mock_429, mock_200]
with patch("ss_tools.shared._llm_http.asyncio.sleep", AsyncMock()) as mock_sleep:
with patch("src.core.utils.llm_http.asyncio.sleep", AsyncMock()) as mock_sleep:
response, _ = await _do_http_request(
mock_client,
"https://api.openai.com/chat/completions",
@@ -372,7 +372,7 @@ class TestDoHttpRequest:
mock_client.post.return_value = mock_429 # Always 429
with patch("ss_tools.shared._llm_http.asyncio.sleep", AsyncMock()):
with patch("src.core.utils.llm_http.asyncio.sleep", AsyncMock()):
response, _ = await _do_http_request(
mock_client,
"https://api.openai.com/chat/completions",
@@ -396,7 +396,7 @@ class TestDoHttpRequest:
mock_client.post.side_effect = [mock_429, mock_200]
with patch("ss_tools.shared._llm_http.asyncio.sleep", AsyncMock()) as mock_sleep:
with patch("src.core.utils.llm_http.asyncio.sleep", AsyncMock()) as mock_sleep:
response, _ = await _do_http_request(
mock_client,
"https://api.openai.com/chat/completions",

View File

@@ -160,7 +160,7 @@ class TestLogRequests:
async def test_log_existing_trace_skips_seed(self):
"""When a trace_id is already set, log_requests must not re-seed (484->486)."""
from src.app import log_requests
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
seed_trace_id()
async def call_next(r):
resp = MagicMock(); resp.status_code = 200; return resp

View File

@@ -0,0 +1,92 @@
# #region Test.CotFormatter [C:2] [TYPE Module] [SEMANTICS test,logging,formatter,cap,passthrough]
# @ingroup Core
# @BRIEF CotJsonFormatter: ADR-0021 field passthrough and payload-cap guardrail (D5).
# @RELATION BINDS_TO -> [Core.CotFormatter]
# @TEST_INVARIANT payload cap -> VERIFIED_BY: [TestPayloadCap::test_large_payload_truncated_with_marker]
# @TEST_INVARIANT additive wire format -> VERIFIED_BY: [TestPassthrough::test_absent_fields_not_emitted]
import json
import logging
from src.core import cot_formatter
from src.core.cot_formatter import CotJsonFormatter, _truncate_payload, set_payload_cap
def _record(**extra):
rec = logging.LogRecord("test.logger", logging.INFO, __file__, 1, "msg", None, None)
for key, value in extra.items():
setattr(rec, key, value)
return rec
class TestPassthrough:
"""ADR-0021 fields print only when present — wire format stays additive."""
def test_enriched_fields_emitted(self):
out = json.loads(CotJsonFormatter().format(_record(
marker="EXPLORE", intent="lookup failed", src="Mod.func",
contract_id="Mod.Contract", claim="PRE: record exists",
error_code="DEMO_NOT_FOUND", loc="backend/src/mod.py:42",
error="no row by id",
)))
assert out["contract_id"] == "Mod.Contract"
assert out["claim"] == "PRE: record exists"
assert out["error_code"] == "DEMO_NOT_FOUND"
assert out["loc"] == "backend/src/mod.py:42"
assert out["marker"] == "EXPLORE"
assert out["error"] == "no row by id"
def test_absent_fields_not_emitted(self):
out = json.loads(CotJsonFormatter().format(_record(
marker="REASON", intent="plan step", src="Mod.func",
)))
for key in ("contract_id", "claim", "error_code", "loc",
"payload_truncated", "payload_bytes"):
assert key not in out
class TestPayloadCap:
"""Hard cap on serialized payload (D5 token guardrail)."""
def test_small_payload_untouched(self):
out = json.loads(CotJsonFormatter().format(_record(
marker="REASON", intent="x", src="s", payload={"a": 1, "b": "two"},
)))
assert out["payload"] == {"a": 1, "b": "two"}
assert "payload_truncated" not in out
def test_large_payload_truncated_with_marker(self):
cap = cot_formatter._payload_cap_bytes
big = {f"k{i:03d}": "x" * 200 for i in range(40)} # ~9 KB
out = json.loads(CotJsonFormatter().format(_record(
marker="EXPLORE", intent="x", src="s", error="e", payload=big,
)))
assert out["payload_truncated"] is True
assert out["payload_bytes"] > cap
assert len(json.dumps(out["payload"], ensure_ascii=False).encode("utf-8")) < cap
def test_non_dict_large_payload_preview(self):
capped, truncated, original = _truncate_payload("y" * 9000, 2048)
assert truncated is True
assert original >= 9000
assert capped["__truncated__"] is True
assert capped["preview"].startswith("y")
def test_hard_cap_holds_with_many_small_keys(self):
"""Boundary accounting: separator/marker overhead must not break the cap."""
cap = 512
payload = {f"k{i:03d}": f"v{i:03d}" for i in range(200)} # ~2.4KB of small entries
capped, truncated, original = _truncate_payload(payload, cap)
assert truncated is True
dumped = json.dumps(capped, ensure_ascii=False, default=str)
assert len(dumped.encode("utf-8")) <= cap
assert capped.get("__truncated_keys__", 0) >= 1
assert original > cap
def test_set_payload_cap_has_floor(self):
old = cot_formatter._payload_cap_bytes
try:
set_payload_cap(10)
assert cot_formatter._payload_cap_bytes == 256
finally:
set_payload_cap(old)
# #endregion Test.CotFormatter

View File

@@ -77,8 +77,8 @@ def test_task_id_contextvar_stamps_formatter():
import json
import logging
from ss_tools.shared.cot_logger import clear_task_id, set_task_id
from ss_tools.shared.logger import CotJsonFormatter
from src.core.cot_logger import clear_task_id, set_task_id
from src.core.cot_formatter import CotJsonFormatter
set_task_id("task-xyz-123")
try:

View File

@@ -0,0 +1,85 @@
# #region Test.LogGapService [C:2] [TYPE Module] [SEMANTICS test,triangulation,gap,task-logs]
# @ingroup Core
# @BRIEF Three-tier ground-truth triangulation on in-memory SQLite fixtures.
# @RELATION BINDS_TO -> [Services.Reports.LogGapService.ComputeGaps]
# @TEST_INVARIANT FAILED without EXPLORE is provably invisible -> VERIFIED_BY: [TestTiers::test_tier1_failed_without_explore]
from datetime import UTC, datetime
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.models.task import TaskLogRecord, TaskRecord
from src.services.reports.log_gap_service import compute_task_log_gaps
@pytest.fixture()
def db():
engine = create_engine("sqlite:///:memory:")
TaskRecord.__table__.create(engine)
TaskLogRecord.__table__.create(engine)
session = sessionmaker(bind=engine)()
yield session
session.close()
def _task(db, task_id, status, type_="migration"):
db.add(TaskRecord(id=task_id, type=type_, status=status))
db.commit()
def _log(db, task_id, marker, payload=None):
db.add(TaskLogRecord(
task_id=task_id, timestamp=datetime.now(UTC), level="INFO",
trace_id="t", src="task.plugin", marker=marker, intent="i",
payload=payload,
))
db.commit()
class TestTiers:
def test_tier1_failed_without_explore(self, db):
_task(db, "t1", "FAILED")
_log(db, "t1", "REASON")
report = compute_task_log_gaps(db)
ids = [r["task_id"] for r in report["tier1_invisible_failures"]]
assert ids == ["t1"]
def test_failed_with_bound_explore_clean(self, db):
_task(db, "t2", "FAILED")
_log(db, "t2", "EXPLORE", payload={"error_code": "X_1"})
report = compute_task_log_gaps(db)
assert report["tier1_invisible_failures"] == []
assert report["tier2_unbound_explore"] == []
def test_tier2_explore_without_binding(self, db):
_task(db, "t3", "FAILED")
_log(db, "t3", "EXPLORE", payload={"info": "x"})
report = compute_task_log_gaps(db)
assert [r["task_id"] for r in report["tier2_unbound_explore"]] == ["t3"]
def test_tier2_contract_id_binding_counts(self, db):
_task(db, "t5", "FAILED")
_log(db, "t5", "EXPLORE", payload={"contract_id": "C.1"})
report = compute_task_log_gaps(db)
assert report["tier2_unbound_explore"] == []
def test_tier3_success_with_explore(self, db):
_task(db, "t4", "SUCCESS")
_log(db, "t4", "EXPLORE", payload={"contract_id": "C.1"})
report = compute_task_log_gaps(db)
assert [r["task_id"] for r in report["tier3_silent_fallbacks"]] == ["t4"]
def test_since_window_filters_old(self, db):
db.add(TaskRecord(id="old", type="backup", status="FAILED",
created_at=datetime(2020, 1, 1, tzinfo=UTC)))
db.commit()
report = compute_task_log_gaps(db, since_days=7)
assert all(r["task_id"] != "old" for r in report["tier1_invisible_failures"])
def test_report_is_json_serializable(self, db):
import json
_task(db, "t6", "FAILED")
report = compute_task_log_gaps(db)
assert json.loads(json.dumps(report))["since_days"] == 7
# #endregion Test.LogGapService

View File

@@ -0,0 +1,184 @@
# #region Test.LogStats [C:2] [TYPE Module] [SEMANTICS test,logging,stats,bond,analytics]
# @ingroup Core
# @BRIEF compute_stats/compute_digest/compute_trajectory engine tests on synthetic JSONL.
# @RELATION BINDS_TO -> [Core.LogStats]
# @TEST_INVARIANT bond matrix is trace-internal -> VERIFIED_BY: [TestComputeStats::test_transitions_are_trace_internal]
# @TEST_INVARIANT orphan EXPLORE detection -> VERIFIED_BY: [TestComputeStats::test_orphan_explore_ratio]
from src.core.log_stats import (
compute_digest,
compute_stats,
compute_trajectory,
intent_family,
render_digest,
render_stats,
render_trajectory,
)
def _evt(marker, intent="step", trace="t1", span=None, contract=None,
code=None, claim=None, ts="2026-09-04T10:00:00.000+00:00", **kw):
evt = {"ts": ts, "level": "INFO", "trace_id": trace, "src": kw.get("src", "Mod.f"),
"marker": marker, "intent": intent}
if span:
evt["span_id"] = span
if contract:
evt["contract_id"] = contract
if code:
evt["error_code"] = code
if claim:
evt["claim"] = claim
evt.update({k: v for k, v in kw.items() if k != "src"})
return evt
class TestComputeStats:
def test_volumes_and_mix(self):
events = [_evt("REASON"), _evt("REFLECT"), _evt("EXPLORE", error="x")]
stats = compute_stats(events)
assert stats["lines"] == 3
assert stats["marker_mix"]["REASON"]["count"] == 1
assert stats["marker_mix"]["EXPLORE"]["count"] == 1
assert stats["bytes_total"] > 0
assert stats["tokens_approx"] == stats["bytes_total"] // 4
def test_transitions_are_trace_internal(self):
events = [
_evt("REASON", trace="a"), _evt("REFLECT", trace="a"),
_evt("REASON", trace="b"),
]
stats = compute_stats(events)
# a: REASON->REFLECT counted; cross-trace REFLECT(a)->REASON(b) must NOT be counted
assert stats["transitions"]["REASON"]["REFLECT"] == 1
assert stats["transitions"]["REFLECT"] == {}
def test_orphan_explore_ratio(self):
events = [
_evt("REASON", src="Mod.f", trace="a"),
_evt("EXPLORE", src="Mod.f", trace="a", error="e1"), # paired
_evt("EXPLORE", src="Mod.g", trace="a", error="e2"), # orphan
]
stats = compute_stats(events)
assert stats["orphan_explore"]["explore_total"] == 2
assert stats["orphan_explore"]["count"] == 1
assert stats["orphan_explore"]["ratio"] == 0.5
def test_reflect_pairing_rate(self):
events = [
_evt("REASON", src="Mod.f", trace="a"),
_evt("REFLECT", src="Mod.f", trace="a"),
_evt("REASON", src="Mod.g", trace="a"), # never verified
]
stats = compute_stats(events)
pairing = stats["reflect_pairing"]
assert pairing["reason_keys"] == 2
assert pairing["paired"] == 1
assert pairing["rate"] == 0.5
def test_insufficient_sample_flag(self):
stats = compute_stats([_evt("REASON")])
assert stats["insufficient_sample"] is True
assert stats["min_sample_lines"] == 2000
def test_coverage_and_cap_counters(self):
events = [
_evt("EXPLORE", contract="C.1", code="X_1", claim="PRE: a", error="e"),
_evt("REASON"),
_evt("REASON", payload_truncated=True),
]
stats = compute_stats(events)
assert stats["coverage"]["contract_id_pct"] > 0
assert stats["coverage"]["error_code_pct_of_explore"] == 100.0
assert stats["payload_truncated_count"] == 1
def test_intent_family_normalizes_interpolation(self):
assert intent_family("Environment env-12 not found") == intent_family("Environment env-99 not found")
assert intent_family("Loaded 42 rows") == intent_family("Loaded 7 rows")
assert intent_family("a" * 3 + " " + "b") != intent_family("c d")
def test_trace_overflow_safety_valve(self, monkeypatch):
from src.core import log_stats
monkeypatch.setattr(log_stats, "MAX_TRACKED_TRACES", 2)
events = [_evt("REASON", trace=f"t{i}") for i in range(10)]
stats = log_stats.compute_stats(events)
assert stats["lines"] == 10 # volumes always full
assert stats["marker_mix"]["REASON"]["count"] == 10
assert stats["traces_truncated"] is True
assert stats["overflow_events"] == 8
def test_render_stats_is_text(self):
out = render_stats(compute_stats([_evt("REASON"), _evt("EXPLORE", error="x")]))
assert "bond matrix" in out
assert "insufficient sample" in out.lower() or "WARNING: insufficient" in out
class TestComputeDigest:
def test_groups_by_contract_and_code(self):
events = [
_evt("EXPLORE", contract="C.1", code="X_1", error="e", trace="a"),
_evt("EXPLORE", contract="C.1", code="X_1", error="e", trace="b"),
_evt("EXPLORE", contract="C.2", error="other", trace="c"),
_evt("REASON", trace="d"),
]
groups = compute_digest(events)
real = [g for g in groups if "__dedup_skipped__" not in g]
assert real[0]["contract_id"] == "C.1"
assert real[0]["count"] == 2
assert real[1]["contract_id"] == "C.2"
def test_dedup_same_trace_pair(self):
events = [
_evt("EXPLORE", contract="C.1", code="X_1", error="e", trace="a"),
_evt("EXPLORE", contract="C.1", code="X_1", error="e", trace="a"),
]
groups = compute_digest(events)
dedup = [g for g in groups if "__dedup_skipped__" in g]
assert dedup and dedup[0]["__dedup_skipped__"] == 1
real = [g for g in groups if "__dedup_skipped__" not in g]
assert real[0]["count"] == 1
def test_uncoded_distinct_intents_not_deduped(self):
"""Legacy lines without codes: distinct failures in one trace stay distinct."""
events = [
_evt("EXPLORE", src="Mod.f", error="first failure", trace="a"),
_evt("EXPLORE", src="Mod.f", error="second failure", trace="a", intent="other branch"),
]
groups = compute_digest(events)
dedup = [g for g in groups if "__dedup_skipped__" in g]
assert not dedup
real = [g for g in groups if "__dedup_skipped__" not in g]
assert real[0]["count"] == 2
def test_uncoded_identical_lines_deduped(self):
events = [
_evt("EXPLORE", src="Mod.f", error="same", trace="a"),
_evt("EXPLORE", src="Mod.f", error="same", trace="a"),
]
groups = compute_digest(events)
dedup = [g for g in groups if "__dedup_skipped__" in g]
assert dedup and dedup[0]["__dedup_skipped__"] == 1
def test_render_digest_text(self):
out = render_digest(compute_digest([_evt("EXPLORE", contract="C.1", code="X", error="e")]))
assert "C.1" in out and "[X]" in out
def test_empty_window(self):
assert "clean window" in render_digest(compute_digest([_evt("REASON")]))
class TestComputeTrajectory:
def test_rows_for_contract_chronological(self):
events = [
_evt("REASON", contract="C.9", ts="2026-09-04T10:00:02.000+00:00"),
_evt("EXPLORE", contract="C.9", error="e", claim="PRE: x",
ts="2026-09-04T10:00:01.000+00:00"),
_evt("REASON", contract="OTHER"),
]
rows = compute_trajectory(events, "C.9")
assert len(rows) == 2
assert rows[0]["marker"] == "EXPLORE" # sorted by ts
assert "belief trajectory" in render_trajectory("C.9", rows)
def test_src_fallback_match(self):
rows = compute_trajectory([_evt("REASON", src="C.5")], "C.5")
assert len(rows) == 1
# #endregion Test.LogStats

View File

@@ -192,7 +192,7 @@ class TestCotJsonFormatterEdgeCases:
def test_format_with_span_id(self):
"""Span ID included in output."""
import json
from ss_tools.shared.cot_logger import _span_id
from src.core.cot_logger import _span_id
token = _span_id.set("span-123")
try:

View File

@@ -20,7 +20,7 @@ from pathlib import Path
import pytest
from ss_tools.shared.cot_logger import seed_trace_id
from src.core.cot_logger import seed_trace_id
from src.core.logger import CotJsonFormatter, logger
# #region Test.Logger.WireFormat.Capture [C:2] [TYPE Fixture] [SEMANTICS test,logging,capture]
@@ -211,7 +211,7 @@ def test_backend_production_code_imports_facade_only():
except SyntaxError:
continue
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module == "ss_tools.shared.cot_logger":
if isinstance(node, ast.ImportFrom) and node.module == "src.core.cot_logger":
for alias in node.names:
if alias.name == "log":
offenders.append(f"{rel}:{node.lineno}")

View File

@@ -33,7 +33,7 @@ def _build_manager():
# #region Test.Core.TestUpdateGlobalSettingsHotAppliesLogLevel [C:2]
def test_update_global_settings_hot_applies_log_level():
"""FR-005: changing settings.logging.level reconfigures live loggers without restart."""
from ss_tools.shared.cot_logger import cot_logger
from src.core.cot_logger import cot_logger
configure_logger(
LoggingConfig(level="DEBUG", task_log_level="DEBUG", enable_belief_state=True)

View File

@@ -22,7 +22,7 @@ from src.core.logger import (
@pytest.fixture(autouse=True)
def reset_logger_state():
"""Reset logger state before each test to avoid cross-test contamination."""
from ss_tools.shared.cot_logger import cot_logger as _cot
from src.core.cot_logger import cot_logger as _cot
import logging as _logging
config = LoggingConfig(
level="DEBUG",
@@ -51,7 +51,7 @@ def reset_logger_state():
def _repropagate():
"""Re-enable propagation after configure_logger (which disables it)."""
from ss_tools.shared.cot_logger import cot_logger as _c
from src.core.cot_logger import cot_logger as _c
logger.propagate = True
_c.propagate = True
@@ -280,7 +280,7 @@ def test_enable_belief_state_flag(caplog):
def test_cot_json_formatter_output():
"""Test that CotJsonFormatter produces valid JSON with expected fields."""
import json
from ss_tools.shared.cot_logger import clear_task_id
from src.core.cot_logger import clear_task_id
# Formatters include a bound task ID for operational log correlation.
clear_task_id()
@@ -350,7 +350,7 @@ def test_cot_json_formatter_plain_message():
# @RELATION BINDS_TO -> [CotLoggerModule]
# @PURPOSE: Verify derive_src produces qualified names and bad generic src are avoided (core of agent-centric goal).
def test_derive_src_and_agent_src_enforcement():
from ss_tools.shared.cot_logger import derive_src
from src.core.cot_logger import derive_src
# In most real contexts this returns module.something
src = derive_src("fallback-test")
@@ -361,4 +361,113 @@ def test_derive_src_and_agent_src_enforcement():
# #endregion Test.Logger.TestDeriveSrcAndAgentSrcEnforcement
# #region Test.Logger.TestEnrichedFacade [C:3] [TYPE Function]
# @RELATION BINDS_TO -> [Core.Logger.Explore, Core.Logger.Reason, Core.Logger.Reflect]
# @PURPOSE: Facade accepts contract_id/claim/error_code kwargs; EXPLORE auto-derives loc.
def test_explore_facade_enriched_kwargs(caplog):
"""explore() passes enriched fields into the record extra (ADR-0021)."""
import json
_repropagate()
caplog.set_level(logging.DEBUG)
logger.explore(
"Lookup failed",
src="ScenarioEditor.Load.Editor",
claim="PRE: scenario_id exists",
error_code="EDITOR_SCENARIO_NOT_FOUND",
error="no registry entry",
payload={"scenario_id": "sc-1"},
)
record = caplog.records[-1]
parsed = json.loads(CotJsonFormatter().format(record))
assert parsed["marker"] == "EXPLORE"
assert parsed["contract_id"] == "ScenarioEditor.Load.Editor" # explicit src mirrors
assert parsed["claim"] == "PRE: scenario_id exists"
assert parsed["error_code"] == "EDITOR_SCENARIO_NOT_FOUND"
assert parsed["loc"].endswith(".py:" + str(record.lineno)) or ".py:" in parsed["loc"]
assert parsed["payload"]["scenario_id"] == "sc-1"
# #endregion Test.Logger.TestEnrichedFacade
# #region Test.Logger.TestReasonClaimKwarg [C:2] [TYPE Function]
# @RELATION BINDS_TO -> [Core.Logger.Reason]
# @PURPOSE: reason()/reflect() accept claim and explicit contract_id.
def test_reason_and_reflect_claim_kwargs(caplog):
import json
_repropagate()
caplog.set_level(logging.DEBUG)
logger.reason("Plan step", src="Mod.Func", claim="PRE: input ready")
logger.reflect("Step verified", src="Mod.Func", claim="POST: rows written")
reason_out = json.loads(CotJsonFormatter().format(caplog.records[-2]))
reflect_out = json.loads(CotJsonFormatter().format(caplog.records[-1]))
assert reason_out["claim"] == "PRE: input ready"
assert reason_out["contract_id"] == "Mod.Func"
assert reflect_out["claim"] == "POST: rows written"
assert "loc" not in reason_out and "loc" not in reflect_out
# #endregion Test.Logger.TestReasonClaimKwarg
# #region Test.Logger.TestBeliefScopeContractBinding [C:3] [TYPE Function]
# @RELATION BINDS_TO -> [Core.Logger.BeliefScope]
# @PURPOSE: belief_scope binds contract scope; nested facade calls inherit contract_id;
# exception path emits EXPLORE with claim and restores the previous scope.
def test_belief_scope_contract_binding_and_claim(caplog):
import json
from src.core.cot_logger import get_contract_id
_repropagate()
caplog.set_level(logging.DEBUG)
with belief_scope("Core.Demo.Scope", message="demo run", claim="POST: demo done"):
assert get_contract_id() == "Core.Demo.Scope"
logger.explore("inner fallback", error="assumption broke")
# scope restored after exit
assert get_contract_id() == ""
inner = [r for r in caplog.records if getattr(r, "intent", "") == "inner fallback"][-1]
inner_out = json.loads(CotJsonFormatter().format(inner))
assert inner_out["contract_id"] == "Core.Demo.Scope" # inherited from scope
# exception path: EXPLORE carries claim + contract
with pytest.raises(ValueError):
with belief_scope("Core.Demo.Fail", claim="PRE: positive input"):
raise ValueError("negative input")
fail_records = [
r for r in caplog.records
if getattr(r, "marker", None) == "EXPLORE" and getattr(r, "src", None) == "Core.Demo.Fail"
]
assert fail_records, "belief_scope must emit EXPLORE on exception"
fail_out = json.loads(CotJsonFormatter().format(fail_records[-1]))
assert fail_out["claim"] == "PRE: positive input"
assert fail_out["contract_id"] == "Core.Demo.Fail"
# #endregion Test.Logger.TestBeliefScopeContractBinding
# #region Test.Logger.TestSchedulerLogLevel [C:2] [TYPE Function]
# @RELATION BINDS_TO -> [Core.Logger.ConfigureLogger]
# @PURPOSE: configure_logger demotes the APScheduler library logger to WARNING by
# default (5s "Running job" console spam = zero-information self-loops,
# ADR-0021/D5) and honors LoggingConfig.scheduler_log_level override.
def test_scheduler_logger_demoted_by_default(caplog):
config = LoggingConfig(level="DEBUG", task_log_level="DEBUG", enable_belief_state=True)
configure_logger(config)
ap = logging.getLogger("apscheduler")
assert ap.level == logging.WARNING
ap.info("Running job spam")
assert "Running job spam" not in caplog.text
ap.warning("executor degraded")
assert "executor degraded" in caplog.text
def test_scheduler_logger_configurable():
config = LoggingConfig(
level="INFO", task_log_level="INFO", enable_belief_state=True,
scheduler_log_level="INFO",
)
configure_logger(config)
assert logging.getLogger("apscheduler").level == logging.INFO
# restore default for subsequent tests
configure_logger(LoggingConfig(level="INFO", task_log_level="INFO", enable_belief_state=True))
assert logging.getLogger("apscheduler").level == logging.WARNING
# #endregion Test.Logger.TestSchedulerLogLevel
# #endregion Test.Logger.TestLogger

View File

@@ -57,14 +57,14 @@ def test_app_has_expected_middleware():
def test_cot_logger_imports():
"""Core logging infrastructure is importable."""
from ss_tools.shared.cot_logger import (
from src.core.cot_logger import (
get_trace_id,
log,
pop_span,
push_span,
seed_trace_id,
)
from ss_tools.shared.cot_logger import _span_id as _cot_span_id
from src.core.cot_logger import _span_id as _cot_span_id
# Reset span context to isolate from prior tests
_cot_span_id.set("")

View File

@@ -13,7 +13,7 @@ sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
import asyncio
from datetime import datetime
import pytest
from ss_tools.shared.cot_logger import build_cot_event
from src.core.cot_logger import build_cot_event
from unittest.mock import AsyncMock, MagicMock, patch

View File

@@ -3,9 +3,8 @@
# @LAYER Infrastructure
# @RELATION DEPENDS_ON -> [EXT:path:docker/backend.entrypoint.sh]
# @RELATION DEPENDS_ON -> [EXT:path:backend/requirements-backend.txt]
# @RELATION DEPENDS_ON -> [EXT:path:shared/pyproject.toml]
# @PRE Docker builder context — корень проекта. backend/, shared/, docker/ доступны.
# @POST Образ с backend API, Playwright, shared-утилитами, entrypoint для bootstrap admin.
# @PRE Docker builder context — корень проекта. backend/, docker/ доступны.
# @POST Образ с backend API, Playwright, entrypoint для bootstrap admin.
FROM python:3.11-slim
@@ -28,14 +27,6 @@ COPY backend/requirements-backend.txt /app/backend/requirements-backend.txt
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r /app/backend/requirements-backend.txt
# Install shared package (LLM health, SSL, cot_logger)
COPY shared/ /app/shared/
RUN pip install --no-cache-dir -e /app/shared/
# Install shared LLM deps (openai, httpx for _llm_health)
RUN --mount=type=cache,target=/root/.cache/pip \
pip install "openai>=1.0.0" "httpx>=0.28.1"
# Browser binaries are required only by screenshot-capable deployments. API-only E2E
# stacks can opt out through INSTALL_PLAYWRIGHT_BROWSERS=0 to reduce image build pressure.
ARG INSTALL_PLAYWRIGHT_BROWSERS=1

View File

@@ -1,5 +1,6 @@
## @{ Doc.Adr.ADR0015 [C:1] [TYPE ADR]
# @STATUS ACCEPTED
# @STATUS SUPERSEDED
# @REPLACED_BY Doc.Adr.ADR0022
# @BRIEF Define package and Docker boundaries for the standalone conversational agent and its shared utilities.
# @RELATION BINDS_TO -> [agent/pyproject.toml]
# @RELATION BINDS_TO -> [shared/pyproject.toml]

View File

@@ -0,0 +1,103 @@
## @{ Doc.Adr.ADR0021 [C:4] [TYPE ADR]
# @STATUS ACCEPTED
# @BRIEF EXPLORE-событие самодиагностируемо: contract_id/claim/error_code/loc + токен-экономика лога + единственная детекция тихих отказов в axiom-mcp.
# @RELATION DEPENDS_ON -> [Doc.Adr.ADR0017]
# @RELATION DEPENDS_ON -> [Doc.Adr.ADR0022]
# @RELATION BINDS_TO -> [backend/src/core/cot_logger.py]
# @RELATION BINDS_TO -> [backend/src/core/cot_formatter.py]
# @RELATION BINDS_TO -> [backend/src/core/log_stats.py]
# @RELATION BINDS_TO -> [backend/src/services/reports/log_gap_service.py]
# @RELATION BINDS_TO -> [scripts/pretty_cot.py]
# @RELATION BINDS_TO -> [scripts/cot_audit.py]
# @RATIONALE Цель логирования — передать belief state агента в runtime и вернуть картину исправления
# при ошибке. Замеры app.log (18 383 строки): avg 281 B, max 286 B, EXPLORE 0, REFLECT 4%,
# REASON 96% — холостые heartbeat'и планировщика. Обогащение EXPLORE стоит ~+140 B на редком
# событии и экономит ≥1 read-вызов агента (300-2000 токенов) на диагностику. Теоретический базис
# (research/papers): heartbeat = self-loop ε-машины с нулевой informed value (2405.15943);
# bond-дистрибуция маркеров — измеримый инвариант здоровья рассуждения, избыток exploration
# фрагментирует, избыток deep-reasoning без reflection даёт ригидные цепи (Molecular Structure
# of Thought, arXiv 2601.06002); апдейт beliefs агента из логов — constrained Bayesian update:
# само-содержательные строки, causal-порядок, намеренная избыточность критических полей
# (2502.01954); error_code/contract_id/claim — ключи random-access binding, извлечение по
# содержанию, не по позиции (arXiv 2512.22471); трейс = belief trajectory, канонические примеры
# в скилле — управляющие интервенции (arXiv 2605.12412); суммаризация >45% разрушает bond-
# структуру — digest обязан сохранять структурные инварианты (матрица переходов), а не только прозу.
# @REJECTED String-only конвенция (кодировать контракт/claim внутри error-строки) — хрупкий
# regex-парсинг, ненадёжная агрегация,claim неотличим от описания.
# @REJECTED Runtime-магия в formatter (авто-резолв loc→#region на этапе эмиссии) — нарушение
# ADR-0017 (логгер тонкий), I/O в пути ошибки; резолв офлайн в digest и онлайн в axiom-индексе.
# @REJECTED Статический гейт по K1/K3 категориям (return-None-детекция, семантика «отказ vs
# альтернатива») — по теореме Райса семантические свойства неразрешимы; open-set lookup-форм
# и контракт-легитимный None (@POST sanctions None) дают лавину false positives/negatives.
# @REJECTED Дублирующий Python-walker тихих отказов в ss-tools — единственная детекция живёт
# в axiom-mcp audit_belief_runtime (конфиг-паттерны, граф контрактов, мультиязычность).
# @REJECTED pytest-гейт поверх axiom-бинаря — axiom-mcp соседний репозиторий, недостижим из
# CI ss-tools; гейт skip'ался бы всегда. Enforcement: агентские циклы + PR-diff review baseline.
# @REJECTED Схлопывание marker→level (info/warning/debug/error вместо REASON/REFLECT/EXPLORE) —
# severity и epistemic role ортогональны; REFLECT@WARNING и EXPLORE@WARNING требуют разных
# belief-апдейтов; collapse теряет pairing/аудит/канал фальсификации.
# @REJECTED 4-й маркер NOOP («normal operation» из статьи) — flood; normal operation реализован
# suppression'ом; матрица переходов условна по эмитированным маркерам (задокументированное
# отклонение от 4-состоятельного графа статьи).
# @REJECTED Безлимитный payload — токено-бомбы (inline request bodies) структурно невозможны:
# cap 2 KB в formatter с явным маркером усечения.
## Decision
###Wire-формат (аддитивные опциональные поля)
| Поле | Маркеры | Семантика |
|---|---|---|
| `contract_id` | все | GRACE-контракт; resolution SSOT `resolve_contract_id`: explicit kwarg > contract scope (belief_scope) > зеркало DECLARED src (`_SRC`-конвенция 13 модулей); derived src НЕ зеркалится |
| `claim` | все | Pointer ≤ ~60 символов на проверяемое/нарушенное объявление («PRE: scenario_id exists»); verbatim-копии @PRE/@POST запрещены — полный текст печатает digest-резолв |
| `error_code` | EXPLORE | `<MODULE_PREFIX>_<SCREAMING_SNAKE>` (EDITOR_/CAPACITY_/BROWSER_/PROVIDER_ — существующие образцы); миграция `error="CODE"` → `error_code="CODE"` выполнена (85 точек/12 файлов) |
| `loc` | EXPLORE | `backend/src/...:NNN` — file:line ветки отказа, единый frame-walk с derive_src; только холодный путь |
| `payload_truncated`/`payload_bytes` | все | Cap ~2048 B (`LoggingConfig.payload_cap_bytes`): обрезка с явным маркером, полные тела — в evidence/task-хранилищах |
Инварианты: EXPLORE всегда несёт `error` (facade и SSOT авто-заполняют из intent); intent
инвариантен (интерполяция значений запрещена — динамика в payload, иначе группировка digest
дробится); REFLECT-claim только для декларированных checkpoint'ов, не на каждом «completed».
### Детекция тихих отказов — категории
| Категория | Статус | Где |
|---|---|---|
| K0 swallowed exceptions (except/catch без raise/log; contextlib.suppress; except*) | аудит | axiom-mcp `audit_belief_runtime`: `BELIEF_SILENT_EXCEPT`, `BELIEF_SILENT_SUPPRESS` (warning); baseline `docs/audit/cot_silence_baseline.json` в ss-tools; escape `# cot-audit: allow` |
| K1 lookup-miss → return None без EXPLORE | advisory | axiom `BELIEF_SILENT_FALLBACK` (info) |
| K3-стиль (f-string intent, нет error=) | advisory | axiom `BELIEF_EXPLORE_UNSTRUCTURED` (info) |
| K2/K3-семантика | не автоматизируется | конвенция «лог на месте нарушенного предположения» + ground truth |
Ground truth вместо парсера: `scripts/cot_audit.py --task-log-gaps` и
`GET /api/reports/task-log-gaps` — три тира: T1 `task_records.status='FAILED'` ∧ ¬∃
`task_logs.marker='EXPLORE'` (доказуемо невидимый отказ); T2 EXPLORE без contract_id/error_code
в payload (не привязан к контракту); T3 SUCCESS ∧ EXPLORE (систематические фолбэки).
Enriched-поля persist'ятся в `task_logs.payload` (без миграции схемы).
### Аналитика (single engine `src/core/log_stats.py`)
`GET /api/reports/log-stats?window=buffer|file` и `pretty_cot.py --stats/--digest/--trajectory/
--story` питаются от одного модуля (no-drift smoke в acceptance). Метрики: объёмы/≈токены,
marker mix, матрица переходов внутри trace, orphan-EXPLORE ratio, REFLECT pairing rate,
top intent families, coverage новых полей, payload-cap hits, флаг insufficient sample (N<2k —
порог устойчивости распределений из Molecular §C.2). Референсный bond-профиль калибруется
пост-sweep прогоном (`docs/audit/bond_profile_baseline.json`), не хардкодится из литературы.
Фронт-панели: Reports→Logs (AnalyticsStatsPanel), Reports→Tasks (TaskGapPanel, клик по gap-
задаче переиспользует существующий cross-filter).
### Tie-break маркеров (адаптация annotation-rules статьи)
Метить по поведенческому стилю шага, не по правильности; доминирующий intent при смешении;
tie-break **EXPLORE > REFLECT > REASON** — осознанная инверсия порядка статьи
(self-reflection > exploration): у нас EXPLORE — несуппрессируемый канал фальсификации.
## Consequences
- EXPLORE-строка самодостаточна для старта исправления: где (loc+contract), что (claim+error),
класс (error_code), контекст (payload), ограничения правки (@REJECTED охватывающего контракта
через digest/axiom-резолв).
- Стоимость: +~140 B на EXPLORE (редкое событие); REASON/REFLECT не растут (поля опциональны).
- Один engine аналитики на CLI/API/UI — дрейф исключён no-drift smoke.
- Детекция K0 — cross-repo задача axiom-mcp (finding-коды выше — SSOT имен); до её завершения
enforcement = ground-truth триангуляция + конвенция.
## @} Doc.Adr.ADR0021

View File

@@ -0,0 +1,36 @@
## @{ Doc.Adr.ADR0022 [C:2] [TYPE ADR]
# @STATUS ACCEPTED
# @BRIEF Absorb the shared/ package into backend/ after the standalone agent removal; collapse the second runtime boundary and the duplicated logger facade.
# @RELATION DEPENDS_ON -> [Doc.Adr.ADR0015]
# @RELATION BINDS_TO -> [backend/src/core/cot_logger.py]
# @RELATION BINDS_TO -> [backend/src/core/cot_formatter.py]
# @RELATION BINDS_TO -> [backend/src/core/utils/llm_http.py]
# @RELATION BINDS_TO -> [backend/src/core/utils/llm_health.py]
# @RELATION BINDS_TO -> [backend/src/core/utils/ssl.py]
# @RATIONALE ADR-0015 justified shared/ by two independent Python runtimes (agent container + backend). The agent was removed (agent/ and docker/Dockerfile.agent no longer exist; src/agent was replaced by ss_tools.shared._llm_health per the agent_status route rationale). With a single consumer the package boundary became pure overhead: an editable pip install step in run.sh and backend.Dockerfile, import indirection (ss_tools.shared.* instead of src.core.*), and — critically — the boundary kept a duplicated logger facade alive (shared/logger.py for the "pydantic-free agent" vs backend/src/core/logger.py), reproducing the drift class ADR-0017 fought (4 suppression lists). CI never installed shared/ at all, so logger smoke tests failed on ImportError — the absorption fixes that structurally.
# @REJECTED Keeping shared/ for hypothetical future consumers was rejected — YAGNI plus a permanent pip -e step in two build systems for zero current benefit.
# @REJECTED Physically moving files while preserving the ss_tools.shared namespace inside backend/src was rejected — it keeps the indirection and does not force the facade consolidation.
# @REJECTED Renaming region IDs (Shared.CotLoggerModule, Shared.CotJsonFormatter, Shared.Ssl.*) during the move was rejected — INV_6: contracts have inbound relations (skills, @RELATION edges, tests); ID curation is a separate curator pass with an index rebuild.
## Decision
`shared/` is deleted. Mapping:
| Before | After |
|---|---|
| `ss_tools/shared/cot_logger.py` | `backend/src/core/cot_logger.py` (stdlib-only invariant kept) |
| `ss_tools/shared/logger.py` :: `CotJsonFormatter` | `backend/src/core/cot_formatter.py` |
| `ss_tools/shared/logger.py` :: instance/setup_handler/monkey-patched reason-reflect-explore | deleted (dead standalone agent path); the only facade is `backend/src/core/logger.py` |
| `ss_tools/shared/ssl.py` | `backend/src/core/utils/ssl.py` |
| `ss_tools/shared/_llm_http.py` | `backend/src/core/utils/llm_http.py` |
| `ss_tools/shared/_llm_health.py` | `backend/src/core/utils/llm_health.py` |
Infrastructure: run.sh no longer installs `../shared`; backend.Dockerfile no longer copies/installs it (openai/httpx already pinned in requirements-backend.txt); `.axiom/axiom_config.yaml` source_dirs drop `shared/src` and dead `agent/src`/`agent/tests`; ADR-0017's "single suppression list lives in shared/cot_logger.py" consequence relocates to `backend/src/core/cot_logger.py`. Existing venvs must run `pip uninstall ss-tools-shared`.
## Consequences
- One import namespace (`src.*`), one logger facade, one suppression list file; the CI smoke tests for logging become hermetic.
- Region IDs of the moved contracts keep their `Shared.*` names until a curator pass renames them with an Axiom rebuild (tracked separately).
- If a second runtime consumer ever appears again, extraction must be justified by a new ADR (0015's mechanism remains available as precedent).
## @} Doc.Adr.ADR0022

View File

@@ -32,12 +32,14 @@ ADR фиксирует принятое и проверяемое архитек
| [0012](ADR-0012-superset-testcontainers.md) | `ACCEPTED` | Интеграционные Superset-тесты используют Postgres, init/web контейнеры и `superset_config.py`. |
| [0013](ADR-0013-coverage-reporting.md) | `ACCEPTED` | `scripts/coverage-summary.sh` существует и собирает сводный отчёт. |
| [0014](ADR-0014-agent-source-copy-strategy.md) | `SUPERSEDED` | Заменён [ADR-0015](ADR-0015-agent-shared-package-boundaries.md). |
| [0015](ADR-0015-agent-shared-package-boundaries.md) | `ACCEPTED` | Agent и shared utilities выделены в отдельные installable packages. |
| [0015](ADR-0015-agent-shared-package-boundaries.md) | `SUPERSEDED` | Заменён ADR-0022: agent-контейнер удалён, второй runtime исчез. |
| [0016](ADR-0016-in-process-plugin-runtime.md) | `ACCEPTED` | Плагины загружаются в процессе из `backend/src/plugins` через `PluginBase`. |
| [0017](ADR-0017-agent-centric-logging.md) | `ACCEPTED` | Agent-centric traces achieved by editing call sites (meaningful intents, removal of per-request noise) rather than only adding complexity to the logger. |
| [0018](ADR-0018-rejected-dataset-review.md) | `REJECTED` | Dataset Review is removed from the active product; `specs/027-dataset-llm-orchestration/` is retained only as archived history. |
| [0019](ADR-0019-dashboard-import-mechanism.md) | `ACCEPTED` | UUID-трансформация БД (не strip_databases), cross-filter patching через IdMappingService, password injection flow (await_input→wait_for_input→retry), разделение dry-run/execute, парсинг имён YAML-файлов БД. |
| [0020](ADR-0020-maintenance-virtual-dataset-discovery.md) | `ACCEPTED` | Обнаружение виртуальных (SQL) датасетов в maintenance discovery через серверный фильтр `sql is_not_null` (fallback — клиентский скан по непустому `sql`); `AsyncAPIClient.request` поднимает не-2xx ответы (`raise_for_status`); sqlparse token-limit (10000) fallback к regex-only для гигантских виртуальных датасетов. |
| [0021](ADR-0021-self-diagnosing-explore.md) | `ACCEPTED` | Самодиагностируемый EXPLORE: опциональные `contract_id`/`claim`/`error_code`/`loc` в wire-формате; токен-экономика (payload-cap 2KB, heartbeat-правило, bond-метрики единым движком `src/core/log_stats.py`); ground-truth триангуляция task-log-gaps (T1/T2/T3); детекция тихих отказов — только в axiom-mcp (`BELIEF_SILENT_*`), без pytest-гейта. |
| [0022](ADR-0022-absorb-shared-into-backend.md) | `ACCEPTED` | Пакет `shared/` поглощён backend'ом после удаления агента: `cot_logger` → `src/core/`, `CotJsonFormatter` → `src/core/cot_formatter.py`, `_llm_*`/`ssl` → `src/core/utils/`; единый фасад `src/core/logger.py`; run.sh/Dockerfile без `pip install -e ../shared`. |
## Правила сопровождения

View File

@@ -5,6 +5,7 @@
// @RELATION BINDS_TO -> [Frontend.CotLogger]
// @TEST_CONTRACT: log -> Produces valid JSON line with correct marker and level
// @TEST_CONTRACT: log -> EXPLORE marker emits WARNING level and requires error field
// @TEST_CONTRACT: log -> opts (ADR-0021) add contract_id/claim/error_code; absent opts keep wire format additive
// @TEST_CONTRACT: setTraceId -> Updates trace ID for subsequent log calls
// @TEST_CONTRACT: getTraceId -> Returns 32-char hex UUID generated at module init
// @TEST_CONTRACT: resetTraceId -> Generates a new trace_id
@@ -245,4 +246,49 @@ describe('CoT Logger — pushSpan / popSpan / getSpanId', () => {
vi.restoreAllMocks();
});
});
describe('CoT Logger — ADR-0021 enriched opts', () => {
beforeEach(() => {
vi.resetModules();
vi.spyOn(console, 'info').mockImplementation(() => {});
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});
it('EXPLORE with opts carries contract_id, claim and error_code', async () => {
const { log } = await import('$lib/cot-logger.js');
log('EditorModel', 'EXPLORE', 'Scenario load failed', { scenarioId: 's1' }, 'not found', {
contract_id: 'ScenarioEditor.Load.Editor',
claim: 'PRE: scenario_id exists',
error_code: 'EDITOR_SCENARIO_NOT_FOUND',
});
const parsed = JSON.parse(vi.mocked(console.warn).mock.calls[0][0]);
expect(parsed.contract_id).toBe('ScenarioEditor.Load.Editor');
expect(parsed.claim).toBe('PRE: scenario_id exists');
expect(parsed.error_code).toBe('EDITOR_SCENARIO_NOT_FOUND');
});
it('opts fields absent when not provided (additive wire format)', async () => {
const { log } = await import('$lib/cot-logger.js');
log('Comp', 'REASON', 'plain step');
const parsed = JSON.parse(vi.mocked(console.info).mock.calls[0][0]);
expect(parsed.contract_id).toBeUndefined();
expect(parsed.claim).toBeUndefined();
expect(parsed.error_code).toBeUndefined();
});
it('partial opts emit only provided fields', async () => {
const { log } = await import('$lib/cot-logger.js');
log('Comp', 'REFLECT', 'checkpoint', undefined, undefined, { claim: 'POST: rows saved' });
const parsed = JSON.parse(vi.mocked(console.info).mock.calls[0][0]);
expect(parsed.claim).toBe('POST: rows saved');
expect(parsed.contract_id).toBeUndefined();
});
});
// #endregion Tests.CotLogger.CotLoggerTest

View File

@@ -0,0 +1,191 @@
<!-- #region Reports.AnalyticsStatsPanel [C:3] [TYPE Component] [SEMANTICS component,analytics,stats,belief,logs] -->
<!-- @BRIEF Collapsible CoT-log analytics panel for the Logs tab: token economics, -->
<!-- bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, top intents, -->
<!-- ADR-0021 field coverage. Display channel over the single backend engine. -->
<!-- @LAYER UI -->
<!-- @UX_STATE collapsed: header row with tier/mix summary chips only -->
<!-- @UX_STATE loading: skeleton pulse rows -->
<!-- @UX_STATE ready: full metrics body -->
<!-- @UX_STATE error: last good data dimmed + retry button -->
<!-- @UX_FEEDBACK Window switch (buffer/file) reloads stats; refresh updates loadedAt. -->
<!-- @UX_RECOVERY Error -> Retry re-runs both loaders; previous stats remain visible. -->
<!-- @UX_REACTIVITY Props: model (ReportsAnalyticsModel). All metrics $derived from model.stats. -->
<!-- @UX_TEST Expand panel on Logs tab -> matrix and mix visible; switch window=file -> reload; -->
<!-- kill backend -> error state with retry; restore -> refresh returns ready. -->
<!-- @RELATION BINDS_TO -> [Reports.AnalyticsModel] -->
<!-- @SIDE_EFFECT Calls parent model actions only; no direct network. -->
<script lang="ts">
import { Button } from '$lib/ui';
import { t } from '$lib/i18n/index.svelte.js';
import type { ReportsAnalyticsModel } from '$lib/models/ReportsAnalyticsModel.svelte.ts';
interface Props {
model: ReportsAnalyticsModel;
}
let { model }: Props = $props();
const MARKERS = ['REASON', 'REFLECT', 'EXPLORE'] as const;
function pct(value: number): string {
return `${(value * 100).toFixed(1)}%`;
}
function kb(bytes: number): string {
return bytes >= 1024 * 1024
? `${(bytes / 1024 / 1024).toFixed(1)}MB`
: `${(bytes / 1024).toFixed(1)}KB`;
}
</script>
<div class="rounded-lg border border-border bg-surface-muted/40">
<button
type="button"
class="flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm"
aria-expanded={model.expanded}
onclick={() => model.setExpanded(!model.expanded)}
>
<span class="font-semibold">
{$t.reports?.analytics_title || 'Belief analytics'}
</span>
<span class="flex items-center gap-2 text-xs text-text-muted">
{#if model.stats}
<span>{model.stats.lines} lines</span>
{#each MARKERS as marker (marker)}
<span>{marker[0]}: {model.stats.marker_mix?.[marker]?.count ?? 0}</span>
{/each}
{/if}
{#if model.statsState === 'loading'}
<span class="animate-pulse">…</span>
{/if}
<span>{model.expanded ? '▾' : '▸'}</span>
</span>
</button>
{#if model.expanded}
<div class="space-y-3 border-t border-border px-3 py-3">
<div class="flex flex-wrap items-center gap-2 text-xs">
<div class="flex gap-1" role="group" aria-label="stats window">
{#each ['buffer', 'file'] as win (win)}
<button
type="button"
class="rounded px-2 py-1 ring-1 {model.window === win
? 'bg-primary text-white ring-primary'
: 'bg-surface-muted text-text-muted ring-border'}"
onclick={() => model.setWindow(win)}
>
{win === 'buffer'
? $t.reports?.analytics_window_buffer || 'ring buffer'
: $t.reports?.analytics_window_file || 'app.log'}
</button>
{/each}
</div>
<Button variant="ghost" size="sm" onclick={() => model.refresh()}
>{$t.reports?.analytics_refresh || 'Refresh'}</Button
>
{#if model.loadedAt}
<span class="text-text-muted">
{model.loadedAt.toLocaleTimeString()}
</span>
{/if}
{#if model.statsState === 'error' || model.gapsState === 'error'}
<span class="text-destructive">{model.error}</span>
<Button variant="secondary" size="sm" onclick={() => model.refresh()}
>{$t.reports?.analytics_retry || 'Retry'}</Button
>
{/if}
</div>
{#if model.statsState === 'loading' && !model.stats}
<div class="space-y-2">
{#each [0, 1, 2] as row (row)}
<div class="h-4 w-full animate-pulse rounded bg-surface-muted"></div>
{/each}
</div>
{:else if model.stats}
{@const s = model.stats}
<div class="grid gap-3 md:grid-cols-2">
<div class="space-y-1 text-xs">
<div class="font-semibold">{$t.reports?.analytics_volume || 'Volume'}</div>
<div>
{s.lines} lines · {kb(s.bytes_total)} · ~{(s.tokens_approx / 1000).toFixed(0)}k tokens
· avg {s.avg_line_bytes}B · max {s.max_line_bytes}B
</div>
<div class="text-text-muted">
traces: {s.window.traces} · truncated payloads: {s.payload_truncated_count}
</div>
{#if s.insufficient_sample}
<div class="rounded bg-warning-light px-2 py-1 text-warning">
{$t.reports?.analytics_insufficient_sample ||
`Insufficient sample (N < ${s.min_sample_lines}) — distributions unreliable`}
</div>
{/if}
</div>
<div class="space-y-1 text-xs">
<div class="font-semibold">{$t.reports?.analytics_bonds || 'Bond health'}</div>
<div>
{$t.reports?.analytics_orphan || 'orphan EXPLORE'}:
{s.orphan_explore.count}/{s.orphan_explore.explore_total}
({pct(s.orphan_explore.ratio)})
</div>
<div>
{$t.reports?.analytics_pairing || 'REFLECT pairing'}: {pct(s.reflect_pairing.rate)}
({s.reflect_pairing.paired}/{s.reflect_pairing.reason_keys})
</div>
<div>
{$t.reports?.analytics_coverage || 'coverage'}:
contract_id {s.coverage.contract_id_pct}% · claim {s.coverage.claim_pct}% ·
error_code {s.coverage.error_code_pct_of_explore}%
</div>
</div>
</div>
<div class="text-xs">
<div class="mb-1 font-semibold">
{$t.reports?.analytics_matrix || 'Bond transition matrix (trace-internal)'}
</div>
<table class="w-full max-w-sm border-collapse">
<thead>
<tr class="text-text-muted">
<th class="p-1 text-left">from ↓ to →</th>
{#each MARKERS as marker (marker)}
<th class="p-1 text-right">{marker}</th>
{/each}
</tr>
</thead>
<tbody>
{#each MARKERS as srcMarker (srcMarker)}
<tr class="border-t border-border">
<td class="p-1 font-medium">{srcMarker}</td>
{#each MARKERS as dstMarker (dstMarker)}
<td class="p-1 text-right tabular-nums">
{(s.transitions_normalized?.[srcMarker]?.[dstMarker] ?? 0).toFixed(3)}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
{#if s.top_intents.length}
<div class="text-xs">
<div class="mb-1 font-semibold">
{$t.reports?.analytics_top_intents || 'Top intents (sweep candidates)'}
</div>
<ul class="space-y-0.5">
{#each s.top_intents.slice(0, 7) as item (item.intent)}
<li class="flex justify-between gap-2">
<span class="truncate">{item.intent}</span>
<span class="tabular-nums text-text-muted">{item.count}×</span>
</li>
{/each}
</ul>
</div>
{/if}
{/if}
</div>
{/if}
</div>
<!-- #endregion Reports.AnalyticsStatsPanel -->

View File

@@ -0,0 +1,131 @@
<!-- #region Reports.TaskGapPanel [C:3] [TYPE Component] [SEMANTICS component,analytics,gap,triangulation,tasks] -->
<!-- @BRIEF Invisible-failure gap panel for the Tasks tab (ADR-0021/D2): tier1 FAILED -->
<!-- tasks with zero EXPLORE markers, tier2 unbound EXPLORE, tier3 silent fallbacks. -->
<!-- Clicking a task reuses the existing Logs cross-filter (openLogsForTask). -->
<!-- @LAYER UI -->
<!-- @UX_STATE loading: pulse row; ready: tier summary + expandable lists; error: retry. -->
<!-- @UX_STATE empty-all: single muted line "no invisible failures in window". -->
<!-- @UX_FEEDBACK Tier counts as colored badges (t1 destructive, t2/t3 warning). -->
<!-- @UX_RECOVERY Error -> retry via model.refresh(); last good report stays visible. -->
<!-- @UX_REACTIVITY Props: model + onOpenLogs callback; tiers $derived from model.gaps. -->
<!-- @UX_TEST Seed a FAILED task without EXPLORE logs -> tier1 badge = 1; click chip -> -->
<!-- Logs tab opens with cross-filter pinned to that task. -->
<!-- @RELATION BINDS_TO -> [Reports.AnalyticsModel] -->
<!-- @SIDE_EFFECT Calls parent callbacks only. -->
<script lang="ts">
import { onMount } from 'svelte';
import { Button } from '$lib/ui';
import { t } from '$lib/i18n/index.svelte.js';
import type { ReportsAnalyticsModel, GapTask } from '$lib/models/ReportsAnalyticsModel.svelte.ts';
interface Props {
model: ReportsAnalyticsModel;
onOpenLogs: (_taskId: string) => void;
}
let { model, onOpenLogs }: Props = $props();
let expanded = $state(false);
onMount(() => {
if (!model.gaps && model.gapsState === 'idle') {
void model.loadGaps();
}
});
function rows(tier: GapTask[]): GapTask[] {
return tier.slice(0, 12);
}
</script>
<div class="rounded-lg border border-border bg-surface-muted/40 px-3 py-2 text-xs">
<div class="flex flex-wrap items-center gap-2">
<span class="font-semibold text-sm">
{$t.reports?.gaps_title || 'Belief gaps'}
</span>
<span
class="rounded-full px-2 py-0.5 font-bold {model.tier1Count
? 'bg-destructive-light text-destructive'
: 'bg-surface-muted text-text-muted ring-1 ring-border'}"
title={$t.reports?.gaps_tier1_hint || 'FAILED task without any EXPLORE marker — invisible failure'}
>
T1 {model.tier1Count}
</span>
<span
class="rounded-full px-2 py-0.5 {model.tier2Count
? 'bg-warning-light text-warning'
: 'bg-surface-muted text-text-muted ring-1 ring-border'}"
title={$t.reports?.gaps_tier2_hint || 'EXPLORE without contract_id/error_code binding'}
>
T2 {model.tier2Count}
</span>
<span
class="rounded-full px-2 py-0.5 {model.tier3Count
? 'bg-warning-light text-warning'
: 'bg-surface-muted text-text-muted ring-1 ring-border'}"
title={$t.reports?.gaps_tier3_hint || 'SUCCESS task with EXPLORE — silent fallbacks'}
>
T3 {model.tier3Count}
</span>
{#if model.gapsState === 'loading'}
<span class="animate-pulse text-text-muted">…</span>
{:else if model.gapsState === 'error'}
<span class="text-destructive">{model.error}</span>
<Button variant="secondary" size="sm" onclick={() => model.loadGaps()}>
{$t.reports?.analytics_retry || 'Retry'}
</Button>
{/if}
{#if model.gaps && (model.tier1Count + model.tier2Count + model.tier3Count) > 0}
<button
type="button"
class="ml-auto text-primary hover:underline"
onclick={() => (expanded = !expanded)}
>
{expanded ? '▾' : '▸'}
{$t.reports?.gaps_details || 'details'}
</button>
{/if}
</div>
{#if model.gaps && expanded}
<div class="mt-2 space-y-2 border-t border-border pt-2">
{#each [
{ label: $t.reports?.gaps_tier1 || 'T1 invisible failures', items: model.gaps.tier1_invisible_failures },
{ label: $t.reports?.gaps_tier2 || 'T2 unbound explore', items: model.gaps.tier2_unbound_explore },
{ label: $t.reports?.gaps_tier3 || 'T3 silent fallbacks', items: model.gaps.tier3_silent_fallbacks },
] as section (section.label)}
{#if section.items.length}
<div>
<div class="mb-1 font-semibold">{section.label} ({section.items.length})</div>
<div class="flex flex-wrap gap-1">
{#each rows(section.items) as task (task.task_id)}
<button
type="button"
class="rounded bg-surface-muted px-2 py-1 ring-1 ring-border hover:ring-primary"
title={task.error || task.task_id}
onclick={() => onOpenLogs(task.task_id)}
>
{task.type}: {task.task_id.slice(0, 8)}
</button>
{/each}
{#if section.items.length > 12}
<span class="px-1 py-1 text-text-muted">+{section.items.length - 12}</span>
{/if}
</div>
</div>
{/if}
{/each}
{#if model.gaps.generated_at}
<div class="text-text-muted">
{$t.reports?.gaps_window || 'window'}: {model.gaps.since_days}d ·
{model.gaps.generated_at}
</div>
{/if}
</div>
{:else if model.gaps && model.tier1Count + model.tier2Count + model.tier3Count === 0}
<div class="mt-1 text-text-muted">
{$t.reports?.gaps_empty || 'No invisible failures in the current window'}
</div>
{/if}
</div>
<!-- #endregion Reports.TaskGapPanel -->

View File

@@ -10,6 +10,8 @@
<!-- @UX_STATE empty: empty-state text supplied by parent. -->
<!-- @UX_STATE filtered_empty: EmptyState explains no matching tasks and exposes clear-filters recovery. -->
<!-- @UX_FEEDBACK hover: details tooltip; failed rows get destructive left border; status badges transition colors. -->
<!-- @UX_FEEDBACK belief-gap badge per row (T1 destructive, T2/T3 warning) when the task appears in the tri-tier gap report (ADR-0021). -->
<!-- @UX_TEST render with gapTiers -> T1 row shows destructive badge; click Logs action unchanged. -->
<!-- @RATIONALE TaskList is a pure presentational component that receives normalized TaskReport[] + ScreenState as props and renders selectable rows with status/type/time details. The filtered_empty state is distinct from empty — it renders an EmptyState with a clear-filters recovery action. Failed rows get a destructive left border for visual salience, and status badges use transition colors for smooth UI updates. Task selection emits onSelectTask(task_id) which the parent TaskCenterPage uses to open the TaskDrawer. -->
<!-- @REJECTED TaskList owning its own task data (via $effect + API call) rejected — all data flows from TaskCenter.Model, making the task table server-filterable and WebSocket-updatable without per-component fetch logic. Inline tooltip state for every row rejected — a single $state tooltipId atom with hover/focus event handlers keeps tooltip overhead constant regardless of list size. -->
<script lang="ts">
@@ -26,6 +28,8 @@
/** Task ids in the Logs tab cross-filter set (explicit highlight). */
logFilterTaskIds = [],
logFilterActive = false,
/** Belief-gap tier per task id (ADR-0021): T1 invisible failure, T2 unbound explore, T3 silent fallbacks. */
gapTiers = {},
onSelectTask = (_taskId: string) => {},
onOpenDetails = (_taskId: string) => {},
onOpenLogs = (_taskId: string) => {},
@@ -37,6 +41,7 @@
selectedTaskId?: string | null;
logFilterTaskIds?: string[];
logFilterActive?: boolean;
gapTiers?: Record<string, 'T1' | 'T2' | 'T3'>;
/** Select / pin task for log filter set (no drawer). */
onSelectTask?: (_taskId: string) => void;
/** Open Task Drawer for details / answer input. */
@@ -102,6 +107,7 @@
{#each tasks as task, index (task.report_id)}
{@const profile = getReportTypeProfile(task.task_type)}
{@const label = typeof profile.label === 'function' ? profile.label() : profile.label}
{@const gapTier = gapTiers[taskKey(task)]}
<div class="relative">
<div
role="button"
@@ -138,6 +144,21 @@
<span class="w-fit rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors duration-300 {getStatusClass(task.status)}">
{getStatusLabel(task)}
</span>
{#if gapTier}
<span
class="w-fit rounded-full px-2 py-0.5 text-[0.625rem] font-bold tracking-wide
{gapTier === 'T1'
? 'bg-destructive-light text-destructive ring-1 ring-destructive-ring'
: 'bg-warning-light text-warning ring-1 ring-warning-ring'}"
title={gapTier === 'T1'
? $t.reports?.gaps_tier1_hint || 'FAILED without EXPLORE — invisible failure'
: gapTier === 'T2'
? $t.reports?.gaps_tier2_hint || 'EXPLORE without contract binding'
: $t.reports?.gaps_tier3_hint || 'SUCCESS with silent fallbacks'}
>
{gapTier}
</span>
{/if}
{#if logFilterTaskIds.includes(taskKey(task))}
<span
class="w-fit rounded-full px-2 py-0.5 text-[0.625rem] font-bold uppercase tracking-wide

View File

@@ -67,5 +67,39 @@ describe('TaskList', () => {
const row = container.querySelector('[role="button"]');
expect(row?.className).toContain('border-l-destructive-ring');
});
it('renders T1 gap badge only for tasks present in gapTiers', () => {
render(TaskList, {
tasks: [
makeTask({ status: 'failed' }),
makeTask({ task_id: 'task-2', report_id: 'rep-2' }),
],
gapTiers: { 'task-1': 'T1' },
});
expect(screen.getByText('T1')).toBeDefined();
expect(screen.queryByText('T2')).toBeNull();
expect(screen.queryByText('T3')).toBeNull();
});
it('renders T2/T3 gap badges with warning styling', () => {
const { container } = render(TaskList, {
tasks: [
makeTask({ task_id: 'task-2', report_id: 'rep-2' }),
makeTask({ task_id: 'task-3', report_id: 'rep-3' }),
],
gapTiers: { 'task-2': 'T2', 'task-3': 'T3' },
});
expect(screen.getByText('T2')).toBeDefined();
expect(screen.getByText('T3')).toBeDefined();
const badges = Array.from(container.querySelectorAll('span')).filter(
(el) => el.textContent === 'T2' || el.textContent === 'T3',
);
expect(badges.every((b) => b.className.includes('bg-warning-light'))).toBe(true);
});
it('no gap badges when gapTiers is empty (default)', () => {
render(TaskList, { tasks: [makeTask({ status: 'failed' })] });
expect(screen.queryByText('T1')).toBeNull();
});
});
// #endregion Tests.TaskList.TaskListTest

View File

@@ -4,11 +4,13 @@
// @INVARIANT trace_id is generated on module init, never "no-trace". Updated from HTTP response headers.
// @INVARIANT span_id is propagated via pushSpan()/popSpan() for nested call tracing.
// @RELATION CALLED_BY -> [Std.Semantics.Svelte]
// @DATA_CONTRACT LogEntry -> { ts, level, trace_id, span_id?, src, marker, intent, payload?, error? }
// @DATA_CONTRACT LogEntry -> { ts, level, trace_id, span_id?, src, marker, intent, payload?, error?, contract_id?, claim?, error_code? }
// @RATIONALE trace_id now generated immediately (crypto.randomUUID), not waiting for first API response.
// Previously, ~first 3-5 log lines had trace_id="no-trace" — invisible to agent correlation.
// Backend hex format (no dashes) for X-Trace-ID header compatibility.
// initTraceId() removed — was just an alias for getTraceId() with misleading name.
// ADR-0021 fields (contract_id/claim/error_code) are additive and optional,
// mirroring the backend wire format; loc stays backend-only (server frames).
type LogMarker = "REASON" | "REFLECT" | "EXPLORE";
@@ -23,6 +25,16 @@ interface LogEntry {
intent: string;
payload?: Record<string, unknown>;
error?: string;
contract_id?: string;
claim?: string;
error_code?: string;
}
/** ADR-0021 enrichment options for log(). */
export interface LogOpts {
contract_id?: string;
claim?: string;
error_code?: string;
}
/** Generate a UUIDv4 in hex format (no dashes) — compatible with backend TraceContextMiddleware. */
@@ -100,7 +112,8 @@ export function getSpanId(): string {
* @example
* log("MigrationModel", "REASON", "Starting migration", { taskId })
* log("MigrationModel", "REFLECT", "Migration completed", { taskId, status })
* log("MigrationModel", "EXPLORE", "Migration failed", { taskId }, "Network timeout")
* log("MigrationModel", "EXPLORE", "Migration failed", { taskId }, "Network timeout",
* { contract_id: "Migration.RunTask", claim: "PRE: connection alive", error_code: "MIGRATION_TIMEOUT" })
*/
export function log(
src: string,
@@ -108,6 +121,7 @@ export function log(
intent: string,
payload?: Record<string, unknown>,
error?: string,
opts?: LogOpts,
): void {
const entry: LogEntry = {
ts: new Date().toISOString(),
@@ -128,6 +142,15 @@ export function log(
if (error !== undefined) {
entry.error = error;
}
if (opts?.contract_id) {
entry.contract_id = opts.contract_id;
}
if (opts?.claim) {
entry.claim = opts.claim;
}
if (opts?.error_code) {
entry.error_code = opts.error_code;
}
const line = JSON.stringify(entry);

View File

@@ -1,5 +1,27 @@
{
"title": "Reports",
"analytics_title": "Belief analytics",
"analytics_window_buffer": "ring buffer",
"analytics_window_file": "app.log",
"analytics_refresh": "Refresh",
"analytics_retry": "Retry",
"analytics_volume": "Volume",
"analytics_bonds": "Bond health",
"analytics_orphan": "orphan EXPLORE",
"analytics_pairing": "REFLECT pairing",
"analytics_coverage": "coverage",
"analytics_matrix": "Bond transition matrix (trace-internal)",
"analytics_top_intents": "Top intents (sweep candidates)",
"gaps_title": "Belief gaps",
"gaps_tier1": "T1 invisible failures",
"gaps_tier2": "T2 unbound explore",
"gaps_tier3": "T3 silent fallbacks",
"gaps_tier1_hint": "FAILED task without any EXPLORE marker — invisible failure",
"gaps_tier2_hint": "EXPLORE without contract_id/error_code binding",
"gaps_tier3_hint": "SUCCESS task with EXPLORE — systematic fallbacks under green status",
"gaps_details": "details",
"gaps_window": "window",
"gaps_empty": "No invisible failures in the current window",
"empty": "No reports available.",
"filtered_empty": "No reports match your filters.",
"loading": "Loading reports...",

View File

@@ -1,5 +1,27 @@
{
"title": "Отчеты",
"analytics_title": "Belief-аналитика",
"analytics_window_buffer": "ring buffer",
"analytics_window_file": "app.log",
"analytics_refresh": "Обновить",
"analytics_retry": "Повторить",
"analytics_volume": "Объём",
"analytics_bonds": "Здоровье связей",
"analytics_orphan": "orphan EXPLORE",
"analytics_pairing": "REFLECT-парность",
"analytics_coverage": "покрытие",
"analytics_matrix": "Матрица переходов (внутри trace)",
"analytics_top_intents": "Топ intent (кандидаты на sweep)",
"gaps_title": "Belief-пробелы",
"gaps_tier1": "T1 невидимые отказы",
"gaps_tier2": "T2 непривязанный explore",
"gaps_tier3": "T3 тихие фолбэки",
"gaps_tier1_hint": "Задача FAILED без единого EXPLORE — невидимый отказ",
"gaps_tier2_hint": "EXPLORE без привязки contract_id/error_code",
"gaps_tier3_hint": "SUCCESS с EXPLORE — систематические фолбэки под зелёным статусом",
"gaps_details": "детали",
"gaps_window": "окно",
"gaps_empty": "В текущем окне невидимых отказов нет",
"empty": "Отчеты отсутствуют.",
"filtered_empty": "Нет отчетов по выбранным фильтрам.",
"loading": "Загрузка отчетов...",

View File

@@ -0,0 +1,190 @@
// #region Reports.AnalyticsModel [C:4] [TYPE Model] [SEMANTICS reports,analytics,belief,stats,gap]
// @Namespace Reports
// @BRIEF Belief-state analytics for the Reports tabs: log economy & bond metrics
// (GET /api/reports/log-stats) and ground-truth invisible-failure gaps
// (GET /api/reports/task-log-gaps). Display channel over the single backend
// engine (src.core.log_stats / log_gap_service) — ADR-0021/T8b.
// @STATE idle|loading|ready|error per section
// @ACTION setExpanded, setWindow, loadStats, loadGaps, refresh, startAutoRefresh, stopAutoRefresh, destroy
// @UX_STATE Collapsed -> Expanded -> Loading -> Ready | Error(retry)
// @UX_FEEDBACK Tier badge counts update on every refresh; stale data marked by loadedAt.
// @UX_RECOVERY Error -> retry button reloads both sections; last good data stays visible.
// @RELATION DEPENDS_ON -> [api]
// @RELATION BINDS_TO -> [Api.Reports.GetLogStats]
// @RELATION BINDS_TO -> [Api.Reports.GetTaskLogGaps]
// @INVARIANT No client-side recomputation in v1 — endpoint responses are canonical.
import { SvelteDate } from 'svelte/reactivity';
import { log } from '$lib/cot-logger';
import { api } from '$lib/api.js';
const CID = 'Reports.AnalyticsModel';
const REFRESH_MS = 30_000;
export type AnalyticsSectionState = 'idle' | 'loading' | 'ready' | 'error';
export interface MarkerStat {
count: number;
bytes: number;
pct: number;
}
export interface LogStats {
lines: number;
bytes_total: number;
tokens_approx: number;
avg_line_bytes: number;
max_line_bytes: number;
window: { traces: number; first_ts: string | null; last_ts: string | null };
marker_mix: Record<string, MarkerStat>;
transitions: Record<string, Record<string, number>>;
transitions_normalized: Record<string, Record<string, number>>;
orphan_explore: { count: number; ratio: number; explore_total: number };
reflect_pairing: { rate: number; reason_keys: number; paired: number };
top_intents: { intent: string; count: number }[];
top_intent_families: { family: string; count: number; distinct: number }[];
payload_truncated_count: number;
coverage: { contract_id_pct: number; claim_pct: number; error_code_pct_of_explore: number };
insufficient_sample: boolean;
min_sample_lines: number;
}
export interface GapTask {
task_id: string;
type: string;
status: string;
error: string | null;
created_at: string | null;
finished_at: string | null;
}
export interface GapReport {
since_days: number;
generated_at: string;
tier1_invisible_failures: GapTask[];
tier2_unbound_explore: GapTask[];
tier3_silent_fallbacks: GapTask[];
}
// #region Reports.AnalyticsModel.Class [C:4] [TYPE Class]
export class ReportsAnalyticsModel {
stats: LogStats | null = $state(null);
gaps: GapReport | null = $state(null);
statsState: AnalyticsSectionState = $state('idle');
gapsState: AnalyticsSectionState = $state('idle');
error: string | null = $state(null);
window: 'buffer' | 'file' = $state('buffer');
expanded: boolean = $state(false);
loadedAt: Date | null = $state(null);
private _timer: ReturnType<typeof setInterval> | null = null;
private _destroyed = false;
tier1Count: number = $derived(this.gaps?.tier1_invisible_failures.length ?? 0);
tier2Count: number = $derived(this.gaps?.tier2_unbound_explore.length ?? 0);
tier3Count: number = $derived(this.gaps?.tier3_silent_fallbacks.length ?? 0);
/** Gap-tier badge map for Tasks tab rows: taskId -> tier (T1 wins over T2/T3). */
gapTiers: Record<string, 'T1' | 'T2' | 'T3'> = $derived.by(() => {
const out: Record<string, 'T1' | 'T2' | 'T3'> = {};
for (const task of this.gaps?.tier3_silent_fallbacks ?? []) out[task.task_id] = 'T3';
for (const task of this.gaps?.tier2_unbound_explore ?? []) out[task.task_id] = 'T2';
for (const task of this.gaps?.tier1_invisible_failures ?? []) out[task.task_id] = 'T1';
return out;
});
setExpanded(value: boolean): void {
this.expanded = value;
if (value) {
void this.refresh();
this.startAutoRefresh();
} else {
this.stopAutoRefresh();
}
}
setWindow(window: 'buffer' | 'file'): void {
this.window = window;
void this.loadStats();
}
async loadStats(): Promise<void> {
if (this._destroyed) return;
this.statsState = 'loading';
log(CID, 'REASON', 'Load CoT log stats', { window: this.window }, undefined, {
contract_id: CID,
claim: 'POST: stats section ready',
});
try {
const data = await api.fetchApi<{ window: string; lines_read: number; stats: LogStats }>(
`/reports/log-stats?window=${this.window}&limit=3000`,
);
if (!data?.stats) throw new Error('Malformed log-stats response');
this.stats = data.stats;
this.statsState = 'ready';
this.error = null;
this.loadedAt = new SvelteDate();
log(CID, 'REFLECT', 'CoT log stats loaded', {
lines: data.stats.lines,
insufficient_sample: data.stats.insufficient_sample,
}, undefined, { contract_id: CID, claim: 'POST: stats section ready' });
} catch (e: unknown) {
this.error = e instanceof Error ? e.message : 'Failed to load log stats';
this.statsState = 'error';
log(CID, 'EXPLORE', 'Log stats load failed', { window: this.window }, this.error, {
contract_id: CID,
claim: 'POST: stats section ready',
error_code: 'REPORTS_STATS_LOAD_FAILED',
});
}
}
async loadGaps(sinceDays = 7): Promise<void> {
if (this._destroyed) return;
this.gapsState = 'loading';
try {
const data = await api.fetchApi<GapReport>(
`/reports/task-log-gaps?since_days=${sinceDays}`,
);
if (!data || !Array.isArray(data.tier1_invisible_failures)) {
throw new Error('Malformed task-log-gaps response');
}
this.gaps = data;
this.gapsState = 'ready';
this.error = null;
this.loadedAt = new SvelteDate();
} catch (e: unknown) {
this.error = e instanceof Error ? e.message : 'Failed to load task log gaps';
this.gapsState = 'error';
log(CID, 'EXPLORE', 'Task log gaps load failed', { sinceDays }, this.error, {
contract_id: CID,
claim: 'POST: gaps section ready',
error_code: 'REPORTS_GAPS_LOAD_FAILED',
});
}
}
async refresh(): Promise<void> {
await Promise.allSettled([this.loadStats(), this.loadGaps()]);
}
startAutoRefresh(): void {
if (this._timer || this._destroyed) return;
this._timer = setInterval(() => {
if (!this._destroyed && this.expanded) void this.refresh();
}, REFRESH_MS);
}
stopAutoRefresh(): void {
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
}
destroy(): void {
this._destroyed = true;
this.stopAutoRefresh();
}
}
// #endregion Reports.AnalyticsModel.Class
// #endregion Reports.AnalyticsModel

View File

@@ -0,0 +1,146 @@
// #region Models.ReportsAnalyticsModel.Tests [C:2] [TYPE Module] [SEMANTICS test,model,reports,analytics]
// @BRIEF L1 unit tests for ReportsAnalyticsModel — state transitions, error recovery, auto-refresh.
// @RELATION BINDS_TO -> [Reports.AnalyticsModel]
// @TEST_EDGE: missing_field -> malformed responses handled gracefully
// @TEST_EDGE: external_fail -> fetch errors set section error state and emit EXPLORE
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("$lib/api.js", () => ({
api: { fetchApi: vi.fn() },
}));
vi.mock("$lib/cot-logger", () => ({ log: vi.fn() }));
import { ReportsAnalyticsModel } from "../ReportsAnalyticsModel.svelte.ts";
import { api } from "$lib/api.js";
import { log } from "$lib/cot-logger";
const fetchApi = api.fetchApi as ReturnType<typeof vi.fn>;
const logFn = log as ReturnType<typeof vi.fn>;
const STATS_FIXTURE = {
lines: 10,
bytes_total: 2800,
tokens_approx: 700,
avg_line_bytes: 280,
max_line_bytes: 300,
window: { traces: 2, first_ts: "t0", last_ts: "t1" },
marker_mix: {
REASON: { count: 8, bytes: 2000, pct: 80 },
REFLECT: { count: 2, bytes: 800, pct: 20 },
EXPLORE: { count: 0, bytes: 0, pct: 0 },
},
transitions: {},
transitions_normalized: {},
orphan_explore: { count: 0, ratio: 0, explore_total: 0 },
reflect_pairing: { rate: 0.5, reason_keys: 2, paired: 1 },
top_intents: [],
top_intent_families: [],
payload_truncated_count: 0,
coverage: { contract_id_pct: 10, claim_pct: 0, error_code_pct_of_explore: 0 },
insufficient_sample: true,
min_sample_lines: 2000,
};
const GAPS_FIXTURE = {
since_days: 7,
generated_at: "2026-09-04T12:00:00+00:00",
tier1_invisible_failures: [
{ task_id: "tbad", type: "backup", status: "FAILED", error: "boom", created_at: null, finished_at: null },
],
tier2_unbound_explore: [],
tier3_silent_fallbacks: [],
};
describe("ReportsAnalyticsModel", () => {
beforeEach(() => {
fetchApi.mockReset();
logFn.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("loadStats populates stats and ready state", async () => {
fetchApi.mockResolvedValue({ window: "buffer", lines_read: 10, stats: STATS_FIXTURE });
const model = new ReportsAnalyticsModel();
await model.loadStats();
expect(fetchApi).toHaveBeenCalledWith(expect.stringContaining("/reports/log-stats?window=buffer"));
expect(model.stats?.lines).toBe(10);
expect(model.statsState).toBe("ready");
expect(model.loadedAt).toBeInstanceOf(Date);
});
it("loadStats rejects malformed payload and emits EXPLORE with error_code", async () => {
fetchApi.mockResolvedValue({ window: "buffer" });
const model = new ReportsAnalyticsModel();
await model.loadStats();
expect(model.statsState).toBe("error");
const explore = logFn.mock.calls.find((c) => c[1] === "EXPLORE");
expect(explore).toBeTruthy();
expect(explore?.[5]?.error_code).toBe("REPORTS_STATS_LOAD_FAILED");
});
it("loadStats handles fetch exception", async () => {
fetchApi.mockRejectedValue(new Error("network down"));
const model = new ReportsAnalyticsModel();
await model.loadStats();
expect(model.statsState).toBe("error");
expect(model.error).toBe("network down");
});
it("loadGaps derives tier counts and gap task ids", async () => {
fetchApi.mockResolvedValue(GAPS_FIXTURE);
const model = new ReportsAnalyticsModel();
await model.loadGaps();
expect(model.gapsState).toBe("ready");
expect(model.tier1Count).toBe(1);
expect(model.tier2Count).toBe(0);
expect(model.gapTiers["tbad"]).toBe("T1");
});
it("loadGaps handles malformed response", async () => {
fetchApi.mockResolvedValue({ nope: true });
const model = new ReportsAnalyticsModel();
await model.loadGaps();
expect(model.gapsState).toBe("error");
});
it("setWindow switches to file window", async () => {
fetchApi.mockResolvedValue({ window: "file", lines_read: 0, stats: STATS_FIXTURE });
const model = new ReportsAnalyticsModel();
model.setWindow("file");
await Promise.resolve();
expect(fetchApi).toHaveBeenCalledWith(expect.stringContaining("window=file"));
});
it("setExpanded(true) triggers refresh and auto-refresh on interval", async () => {
vi.useFakeTimers();
fetchApi.mockResolvedValue({ window: "buffer", lines_read: 0, stats: STATS_FIXTURE });
const model = new ReportsAnalyticsModel();
model.setExpanded(true);
await vi.advanceTimersByTimeAsync(0);
const initialCalls = fetchApi.mock.calls.length;
expect(initialCalls).toBeGreaterThanOrEqual(2); // stats + gaps in refresh
await vi.advanceTimersByTimeAsync(30_000);
expect(fetchApi.mock.calls.length).toBeGreaterThan(initialCalls);
model.destroy();
const afterDestroy = fetchApi.mock.calls.length;
await vi.advanceTimersByTimeAsync(60_000);
expect(fetchApi.mock.calls.length).toBe(afterDestroy);
});
it("setExpanded(false) stops auto-refresh", async () => {
vi.useFakeTimers();
fetchApi.mockResolvedValue({ window: "buffer", lines_read: 0, stats: STATS_FIXTURE });
const model = new ReportsAnalyticsModel();
model.setExpanded(true);
await vi.advanceTimersByTimeAsync(0);
model.setExpanded(false);
const calls = fetchApi.mock.calls.length;
await vi.advanceTimersByTimeAsync(90_000);
expect(fetchApi.mock.calls.length).toBe(calls);
model.destroy();
});
});
// #endregion Models.ReportsAnalyticsModel.Tests

View File

@@ -14,10 +14,13 @@
import { replaceState } from "$app/navigation";
import { TaskCenterModel } from "$lib/models/TaskCenterModel.svelte.ts";
import { ReportsLogModel } from "$lib/models/ReportsLogModel.svelte.ts";
import { ReportsAnalyticsModel } from "$lib/models/ReportsAnalyticsModel.svelte.ts";
import SummaryPanel from "$lib/components/reports/SummaryPanel.svelte";
import FilterBar from "$lib/components/reports/FilterBar.svelte";
import TaskList from "$lib/components/reports/TaskList.svelte";
import ReportsLogPanel from "$lib/components/reports/ReportsLogPanel.svelte";
import AnalyticsStatsPanel from "$lib/components/reports/AnalyticsStatsPanel.svelte";
import TaskGapPanel from "$lib/components/reports/TaskGapPanel.svelte";
import TaskFilterChip from "$lib/components/reports/TaskFilterChip.svelte";
import {
buildTaskChipMeta,
@@ -38,6 +41,7 @@
let { data }: { data: PageData } = $props();
const m = new TaskCenterModel();
const logsModel = new ReportsLogModel();
const analytics = new ReportsAnalyticsModel();
let activeTab = $state<"tasks" | "logs">("tasks");
@@ -60,6 +64,7 @@
return () => {
m.destroy();
logsModel.destroy();
analytics.destroy();
};
});
@@ -221,7 +226,7 @@
})}
</span>
{/if}
<Button variant="ghost" size="sm" onclick={() => m.refreshSummary()}
<Button variant="ghost" size="sm" onclick={() => { m.refreshSummary(); void analytics.loadGaps(); }}
>{$t.reports?.refresh || "Refresh"}</Button
>
</div>
@@ -341,6 +346,8 @@
</div>
{/if}
<TaskGapPanel model={analytics} onOpenLogs={openLogsForTask} />
<FilterBar
filters={m.filters}
onApplyFilter={(partial: Partial<TaskCenterFilter>) => m.applyFilter(partial)}
@@ -355,6 +362,7 @@
selectedTaskId={m.selectedTaskId}
logFilterTaskIds={logsModel.filterTaskIds}
logFilterActive={logsModel.filterActive}
gapTiers={analytics.gapTiers}
filtered={m.hasActiveFilters}
onSelectTask={onSelectTask}
onOpenDetails={onOpenTaskDetails}
@@ -385,7 +393,10 @@
</div>
{/if}
{:else}
<ReportsLogPanel model={logsModel} taskChips={chipCache} />
<div class="space-y-3">
<AnalyticsStatsPanel model={analytics} />
<ReportsLogPanel model={logsModel} taskChips={chipCache} />
</div>
{/if}
</div>
<!-- #endregion Reports.Page.TaskCenterReportsPage -->

4
run.sh
View File

@@ -314,10 +314,6 @@ setup_backend() {
echo "Installing backend dependencies..."
pip install -r requirements.txt
fi
# Install shared package
if ! python3 -c "import ss_tools.shared" 2>/dev/null; then
pip install -e ../shared 2>/dev/null || true
fi
cd ..
}

108
scripts/cot_audit.py Normal file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env python3
# #region Scripts.CotAudit [C:2] [TYPE Script] [SEMANTICS audit,triangulation,gap,task-logs,cli]
# @BRIEF Agent CLI for the ground-truth invisible-failure triangulation (ADR-0021/D2).
# Thin offline wrapper around the SSOT service — NO parser, NO duplicated SQL:
# the same three-tier query powers GET /api/reports/task-log-gaps (frontend) and
# this script (agent without a running server). T1: FAILED task with no EXPLORE
# in task_logs (provably invisible failure); T2: FAILED with EXPLORE lacking
# contract_id/error_code binding; T3: SUCCESS with EXPLORE (silent fallbacks).
# @RELATION DEPENDS_ON -> [Services.Reports.LogGapService.ComputeGaps]
# @NOTE
# cd backend && .venv/bin/python ../scripts/cot_audit.py --task-log-gaps [--since-days 7] [--json]
# Requires DATABASE_URL (loads backend/.env like neighbouring scripts). Advisory: exit 0 always.
"""
cot_audit.py — ground-truth task-log gap report for agents.
Why SQL, not AST: whether a branch "should" have logged is semantically undecidable
statically (Rice); whether a FAILED task produced zero EXPLORE markers is a fact.
Detection of syntactic silence (swallowed exceptions) lives in axiom-mcp
(audit_belief_runtime, finding codes per ADR-0021) — single implementation there.
"""
# #endregion Scripts.CotAudit
import argparse
import json
import sys
from pathlib import Path
_REPO_ROOT = Path(__file__).resolve().parent.parent
_BACKEND = _REPO_ROOT / "backend"
def _bootstrap() -> None:
"""Put backend/src on sys.path and load backend/.env (mirrors run.sh behavior)."""
sys.path.insert(0, str(_BACKEND))
env_file = _BACKEND / ".env"
if env_file.exists():
import os
for line in env_file.read_text(encoding="utf-8", errors="replace").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
def task_log_gaps(since_days: int, limit: int, as_json: bool) -> None:
_bootstrap()
try:
from src.core.database import SessionLocal
from src.services.reports.log_gap_service import compute_task_log_gaps
db = SessionLocal()
except Exception as exc: # friendly operator/agent-facing failure, not a traceback
print(f"cot_audit: database unavailable ({type(exc).__name__}: {exc})", file=sys.stderr)
print(
"hint: run with backend/.env present (DATABASE_URL) — "
"cd backend && .venv/bin/python ../scripts/cot_audit.py --task-log-gaps",
file=sys.stderr,
)
if as_json:
print(json.dumps({"error": "database_unavailable"}, ensure_ascii=False))
return
try:
report = compute_task_log_gaps(db, since_days=since_days, limit=limit)
finally:
db.close()
if as_json:
print(json.dumps(report, ensure_ascii=False, indent=2))
return
icons = {
"tier1_invisible_failures": ("T1 INVISIBLE", "FAILED task, zero EXPLORE markers — fix the silent branch"),
"tier2_unbound_explore": ("T2 UNBOUND", "EXPLORE present but no contract_id/error_code — adopt ADR-0021 fields"),
"tier3_silent_fallbacks": ("T3 FALLBACK", "SUCCESS task with EXPLORE — systematic fallbacks under green status"),
}
print(f"== task-log gap report (since {report['since_days']}d, generated {report['generated_at']}) ==")
for key, (label, hint) in icons.items():
rows = report.get(key) or []
print(f"\n[{label}] {len(rows)} — {hint}")
for row in rows[:20]:
err = f" error={row['error']}" if row.get("error") else ""
print(f" {row['created_at']} {row['type']:<24} {row['task_id']}{err}")
if len(rows) > 20:
print(f" ... {len(rows) - 20} more (use --json for full report)")
def main() -> None:
parser = argparse.ArgumentParser(description="CoT ground-truth audits for agents")
parser.add_argument("--task-log-gaps", action="store_true",
help="Three-tier invisible-failure report from task_records/task_logs")
parser.add_argument("--since-days", type=int, default=7, help="Window in days (default 7)")
parser.add_argument("--limit", type=int, default=200, help="Max tasks per tier (default 200)")
parser.add_argument("--json", action="store_true", help="Machine-readable output")
args = parser.parse_args()
if args.task_log_gaps:
task_log_gaps(args.since_days, args.limit, args.json)
else:
parser.print_help()
# Advisory tool: never gates anything (decision D4).
sys.exit(0)
if __name__ == "__main__":
main()

View File

@@ -6,7 +6,12 @@
# python scripts/pretty_cot.py backend/logs/app.log --last 80
# tail -f logs/app.log | python scripts/pretty_cot.py
# python scripts/pretty_cot.py backend/logs/app.log --follow
# python scripts/pretty_cot.py backend/logs/app.log* --stats [--json]
# python scripts/pretty_cot.py backend/logs/app.log* --digest [--top 20] [--json]
# python scripts/pretty_cot.py backend/logs/app.log* --trajectory ScenarioExecution.BrowserProvider
# python scripts/pretty_cot.py backend/logs/app.log --trace <id> --story
# @INVARIANT Output is always a readable narrative grouped by trace_id.
# @RELATION DEPENDS_ON -> [Core.LogStats]
"""
pretty_cot.py — Agent-centric pretty printer for Molecular CoT logs.
@@ -33,8 +38,8 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Iterable, Optional
# ── Central suppression (mirrors shared/ss_tools/shared/cot_logger.py) ──
# This is the canonical list. If you update this, update shared too.
# ── Central suppression (mirrors backend/src/core/cot_logger.py) ──
# This is the canonical list. If you update this, update the backend module too.
_ROUTINE_PHRASES = (
"Reusing cached Superset auth tokens",
"Resolve authenticated user principal",
@@ -57,6 +62,26 @@ def _is_routine(intent: str) -> bool:
return any(p in intent for p in _ROUTINE_PHRASES)
# ── Analytics engine (SSOT: backend/src/core/log_stats.py — never duplicate) ──
_REPO_ROOT = Path(__file__).resolve().parent.parent
def _load_engine():
"""Load log_stats.py by file path — stdlib-only module, zero package side effects
(works from any python3 without the backend venv; zombie-mode friendly)."""
import importlib.util
engine_path = _REPO_ROOT / "backend" / "src" / "core" / "log_stats.py"
try:
spec = importlib.util.spec_from_file_location("cot_log_stats", engine_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception as exc: # pragma: no cover - environment dependent
print(f"Error: cannot load {engine_path} ({exc})", file=sys.stderr)
return None
ICONS = {
"REASON": "→",
"REFLECT": "✓",
@@ -126,6 +151,16 @@ def format_record(rec: dict[str, Any], compact: bool = False) -> str:
if error:
base += f" | error={error}"
error_code = rec.get("error_code")
claim = rec.get("claim")
loc = rec.get("loc")
contract = rec.get("contract_id")
if error_code:
base += f" | #{error_code}"
if claim:
base += f" | claim={claim}"
if payload and not compact:
try:
p = json.dumps(payload, ensure_ascii=False, default=str)[:180]
@@ -133,6 +168,11 @@ def format_record(rec: dict[str, Any], compact: bool = False) -> str:
except Exception:
pass
if loc and not compact:
base += f" | loc={loc}"
if contract and contract != src and not compact:
base += f" | cid={contract}"
if trace_short and not compact:
base = f"[{trace_short}] {base}"
@@ -204,11 +244,23 @@ def follow_file(file_path: str) -> None:
def main() -> None:
parser = argparse.ArgumentParser(description="Pretty-print Molecular CoT logs for agents")
parser.add_argument("files", nargs="*", help="Log files (JSON lines). Use - for stdin.")
parser.add_argument("--last", type=int, default=200, help="Only process last N lines")
parser.add_argument("--last", type=int, default=None,
help="Only process last N lines (narrative default: 200; analytics: all)")
parser.add_argument("--trace", help="Filter to a specific trace_id")
parser.add_argument("--compact", action="store_true", help="Less verbose output")
parser.add_argument("--no-group", action="store_true", help="Do not group by trace_id")
parser.add_argument("--follow", action="store_true", help="Follow (like tail -f)")
parser.add_argument("--stats", action="store_true",
help="Log-economy + bond-structure stats (engine: backend/src/core/log_stats.py)")
parser.add_argument("--digest", action="store_true",
help="Prioritized EXPLORE fix-map digest")
parser.add_argument("--top", type=int, default=20, help="Digest group limit (default 20)")
parser.add_argument("--trajectory", metavar="CONTRACT_ID",
help="Belief trajectory (ts, marker, claim) for one contract")
parser.add_argument("--story", action="store_true",
help="With --trace: chronological story ending in a VERDICT echo of EXPLOREs")
parser.add_argument("--json", action="store_true",
help="Machine-readable JSON output (with --stats/--digest/--trajectory)")
args = parser.parse_args()
@@ -218,6 +270,9 @@ def main() -> None:
follow_file(f)
return
analytics_mode = bool(args.stats or args.digest or args.trajectory or args.story)
effective_last = args.last if args.last else (None if analytics_mode else 200)
# ── Batch mode ─────────────────────────────────────────────────────────
sources: list[Any] = []
if not args.files:
@@ -233,9 +288,8 @@ def main() -> None:
for src in sources:
try:
lines = src if hasattr(src, "readline") else src.read_text(encoding="utf-8", errors="replace").splitlines()
if args.last and hasattr(lines, "__iter__") and not args.follow:
if isinstance(lines, list):
lines = lines[-args.last:]
if effective_last and isinstance(lines, list):
lines = lines[-effective_last:]
for line in lines:
rec = parse_line(line if isinstance(line, str) else line)
if rec:
@@ -245,8 +299,6 @@ def main() -> None:
except Exception as e:
print(f"Error reading: {e}", file=sys.stderr)
pretty_print(all_records, group_by_trace=not args.no_group, compact=args.compact)
# Close files
for s in sources:
if hasattr(s, "close") and s is not sys.stdin:
@@ -255,6 +307,46 @@ def main() -> None:
except Exception:
pass
# ── Analytics modes (single engine implementation — log_stats.py) ─────
if args.stats or args.digest or args.trajectory:
engine = _load_engine()
if engine is None:
sys.exit(2)
if args.stats:
stats = engine.compute_stats(all_records)
print(json.dumps(stats, ensure_ascii=False, indent=2) if args.json
else engine.render_stats(stats))
elif args.digest:
groups = engine.compute_digest(all_records, top=args.top)
print(json.dumps(groups, ensure_ascii=False, indent=2) if args.json
else engine.render_digest(groups))
else:
rows = engine.compute_trajectory(all_records, args.trajectory)
print(json.dumps(rows, ensure_ascii=False, indent=2) if args.json
else engine.render_trajectory(args.trajectory, rows))
return
if args.story:
# Chronological causal story; ends with a VERDICT echo (recency for
# constrained attention — the falsification must be the last thing read).
all_records.sort(key=lambda r: (r.get("ts") or ""))
for r in all_records:
line = format_record(r, compact=args.compact)
if line:
print(line)
verdicts = [r for r in all_records if r.get("marker") == "EXPLORE"]
if verdicts:
print("\n== VERDICT (falsified beliefs) ==")
for r in verdicts:
line = format_record(r, compact=False)
if line:
print(" " + line)
else:
print("\n== VERDICT: no EXPLORE in window — no falsified beliefs observed ==")
return
pretty_print(all_records, group_by_trace=not args.no_group, compact=args.compact)
if __name__ == "__main__":
main()

View File

@@ -35,13 +35,10 @@ SKIP_PARTS = {
PROD_ZONES = (
ROOT / "backend" / "src",
ROOT / "frontend" / "src",
ROOT / "agent" / "src",
ROOT / "shared" / "src",
)
ALL_ZONES = PROD_ZONES + (
ROOT / "backend" / "tests",
ROOT / "frontend" / "tests",
ROOT / "agent" / "tests",
)
REGION_OPEN = re.compile(

View File

@@ -1,17 +0,0 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "ss-tools-shared"
version = "0.1.0"
description = "Shared lightweight utilities for superset-tools backend and agent"
requires-python = ">=3.11"
dependencies = []
[project.optional-dependencies]
llm = ["openai>=1.0.0", "httpx>=0.28.1"]
[tool.setuptools.packages.find]
where = ["src"]
include = ["ss_tools.shared*"]

View File

@@ -1,10 +0,0 @@
# #region ss_tools.shared [C:1] [TYPE Package] [SEMANTICS shared,package,init]
# @BRIEF Shared lightweight utilities for superset-tools backend and agent.
# Contains: cot_logger (stdlib-only trace propagation),
# ssl (stdlib-only SSL context),
# logger (lightweight JSON logger, no pydantic),
# _llm_http (shared httpx.AsyncClient with system SSL),
# _llm_health (LLM health probe, openai+httpx).
# @INVARIANT No dependency on FastAPI, SQLAlchemy, Gradio, LangChain.
# @INVARIANT All HTTP clients use system_ssl_context() from ssl module.
# #endregion ss_tools.shared

View File

@@ -1,239 +0,0 @@
# #region Shared.SharedLoggerModule [C:3] [TYPE Module] [SEMANTICS logging,json,formatter,structured]
# @BRIEF Lightweight JSON logger for agent container and backend.
# Provides the same .reason()/.reflect()/.explore() API everywhere,
# backed by shared/cot_logger.py primitives and central suppression.
# @INVARIANT No dependency on FastAPI, SQLAlchemy, Gradio, LangChain, pydantic.
# @INVARIANT Every log.info/error/warning call produces single-line JSON.
# @DATA_CONTRACT Log record format:
# {ts, level, trace_id, src, marker, intent, span_id?, payload?, error?, elapsed_ms?}
# @RELATION DEPENDS_ON -> [Shared.CotLoggerModule]
# @RATIONALE Cleaned from 3 suppression lists to 1 (in cot_logger.py).
# CotJsonFormatter no longer filters — formatters format, they don't suppress.
import json
import logging
import sys
import types
from datetime import UTC, datetime
from .cot_logger import (
_span_id,
_task_id,
_trace_id,
derive_src,
is_routine_infra,
)
# #region Shared.CotJsonFormatter [C:2] [TYPE Class] [SEMANTICS logging,formatter,json,cot]
# @ingroup Shared
# @BRIEF JSON formatter matching the Molecular CoT protocol.
# Reads structured data from LogRecord's extra attributes.
# Does NOT filter — formatters format, they don't suppress.
# Suppression happens upstream in reason()/reflect().
class CotJsonFormatter(logging.Formatter):
"""JSON formatter matching the Molecular CoT protocol.
Reads structured data from the LogRecord's extra attributes (marker, intent,
payload, error, src, elapsed_ms) set via the ``extra`` kwarg. Falls back to
plain message wrapping when no structured extra is present.
Output format (single-line JSON)::
{
"ts": "2026-05-12T10:30:00.123",
"level": "INFO",
"trace_id": "uuid-or-no-trace",
"src": "module.name",
"marker": "REASON|REFLECT|EXPLORE",
"intent": "human-readable intent",
"span_id": "optional-span",
"payload": { ... },
"elapsed_ms": 12.5,
"error": "..."
}
"""
# #region Shared.CotJsonFormatter.Format [C:2] [TYPE Function] [SEMANTICS format,json,record]
# @INVARIANT Output is always valid single-line JSON.
def format(self, record):
marker = getattr(record, 'marker', None)
intent = getattr(record, 'intent', None)
payload = getattr(record, 'payload', None)
error = getattr(record, 'error', None)
src = getattr(record, 'src', None)
elapsed_ms = getattr(record, 'elapsed_ms', None)
event_ts = getattr(record, 'ts', None)
event_trace_id = getattr(record, 'trace_id', None)
event_span_id = getattr(record, 'span_id', None)
# Agent-centric: never emit useless generic src names
bad_srcs = {"superset_tools_app", "app_name", "root", "", None}
if not src or src in bad_srcs:
src = derive_src(record.name)
if src in bad_srcs:
src = record.name or "unknown"
if not marker:
marker = "REASON"
if not intent:
intent = record.getMessage()
log_obj = {
"ts": event_ts or datetime.now(UTC).isoformat(timespec="milliseconds"),
"level": record.levelname,
"trace_id": event_trace_id if event_trace_id is not None else (_trace_id.get() or "no-trace"),
"src": src,
"marker": marker,
"intent": intent,
}
span_id = event_span_id or _span_id.get()
if span_id:
log_obj["span_id"] = span_id
# Correlate app CoT lines with task_logs / Reports cross-filter
task_id = _task_id.get() or None
if task_id:
log_obj["task_id"] = task_id
if payload is not None:
# Ensure payload.task_id is present when context is bound
if isinstance(payload, dict) and task_id and "task_id" not in payload:
payload = {**payload, "task_id": task_id}
log_obj["payload"] = payload
elif task_id:
log_obj["payload"] = {"task_id": task_id}
if error is not None:
log_obj["error"] = error
if elapsed_ms is not None:
log_obj["elapsed_ms"] = elapsed_ms
return json.dumps(log_obj, ensure_ascii=False, default=str)
# #endregion Shared.CotJsonFormatter.Format
# #endregion Shared.CotJsonFormatter
# #region Shared._setup_logger [C:2] [TYPE Function] [SEMANTICS logging,setup,instance]
# @ingroup Shared
# @BRIEF Create and configure the shared JSON logger.
# Defers handler setup: backend/logger.py adds the console handler.
# For standalone use (agent container), call setup_handler().
# @INVARIANT Only ONE StreamHandler on superset_tools_app at any time.
_LOG_CONFIGURED = False
def setup_handler() -> None:
"""Add console handler to superset_tools_app. Safe to call multiple times."""
global _LOG_CONFIGURED
log = logging.getLogger("superset_tools_app")
if _LOG_CONFIGURED:
return
if not log.handlers:
formatter = CotJsonFormatter()
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
log.addHandler(console_handler)
log.propagate = False
_LOG_CONFIGURED = True
def _setup_logger() -> logging.Logger:
log = logging.getLogger("superset_tools_app")
return log
logger = _setup_logger()
setup_handler()
# #endregion Shared._setup_logger
# #region Shared.explore [C:2] [TYPE Function] [SEMANTICS log,explore,marker,warning]
# @ingroup Shared
# @BRIEF Log an EXPLORE marker (WARNING level) with structured extra data.
def explore(self, msg, *args, **kwargs):
user_extra = kwargs.pop('extra', {})
error_val = kwargs.pop('error', None)
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src = derive_src()
extra: dict = {'marker': 'EXPLORE', 'intent': msg, 'src': src}
if error_val is not None:
extra['error'] = error_val
if not payload and len(args) == 1 and isinstance(args[0], dict):
payload = args[0]
args = ()
if payload is not None:
extra['payload'] = payload
extra.update(user_extra)
self.warning(msg, extra=extra, **kwargs)
# #endregion Shared.explore
# #region Shared.reason [C:2] [TYPE Function] [SEMANTICS log,reason,marker,info]
# @ingroup Shared
# @BRIEF Log a REASON marker (INFO level) with structured extra data.
# Uses central is_routine_infra() for suppression (defense-in-depth).
def reason(self, msg, *args, **kwargs):
user_extra = kwargs.pop('extra', {})
error_val = kwargs.pop('error', None)
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src = derive_src()
# Central suppression — single source of truth
if is_routine_infra(msg):
return # keep agent traces clean (defense-in-depth, per ADR-0017)
extra: dict = {'marker': 'REASON', 'intent': msg, 'src': src}
if error_val is not None:
extra['error'] = error_val
if not payload and len(args) == 1 and isinstance(args[0], dict):
payload = args[0]
args = ()
if payload is not None:
extra['payload'] = payload
extra.update(user_extra)
self.info(msg, extra=extra, **kwargs)
# #endregion Shared.reason
# #region Shared.reflect [C:2] [TYPE Function] [SEMANTICS log,reflect,marker,info]
# @ingroup Shared
# @BRIEF Log a REFLECT marker (INFO level) with structured extra data.
# Uses central is_routine_infra() for suppression (defense-in-depth).
def reflect(self, msg, *args, **kwargs):
user_extra = kwargs.pop('extra', {})
error_val = kwargs.pop('error', None)
payload = kwargs.pop('payload', None)
explicit_src = kwargs.pop('src', None)
src = explicit_src or user_extra.pop('src', None)
if not src or src in {"superset_tools_app", "app_name", "root", ""}:
src = derive_src()
# Central suppression — single source of truth
if is_routine_infra(msg):
return # keep agent traces clean (defense-in-depth, per ADR-0017)
extra: dict = {'marker': 'REFLECT', 'intent': msg, 'src': src}
if error_val is not None:
extra['error'] = error_val
if not payload and len(args) == 1 and isinstance(args[0], dict):
payload = args[0]
args = ()
if payload is not None:
extra['payload'] = payload
extra.update(user_extra)
self.info(msg, extra=extra, **kwargs)
# #endregion Shared.reflect
# Monkey-patch the convenience methods onto the logger instance
logger.explore = types.MethodType(explore, logger)
logger.reason = types.MethodType(reason, logger)
logger.reflect = types.MethodType(reflect, logger)
# #endregion Shared.SharedLoggerModule