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.
474 lines
22 KiB
Python
Executable File
474 lines
22 KiB
Python
Executable File
# #region Core.Logger.LoggerModule [C:5] [TYPE Module] [SEMANTICS pydantic, logging, json, formatter, structured]
|
|
# @defgroup Core Module group.
|
|
# @BRIEF Application logging system with CotJsonFormatter producing decision audit JSON output.
|
|
# @LAYER Core
|
|
# @RELATION CALLED_BY -> [Core.Logger.LoggerModule]
|
|
# @RELATION DEPENDS_ON -> [CotLoggerModule]
|
|
# @RELATION DEPENDS_ON -> [Core.WsLogHandler.WebSocketLogHandler]
|
|
# @PRE Python 3.7+ with cot_logger ContextVars available.
|
|
# @POST All log output is single-line JSON with ts, level, trace_id, src, marker, intent, payload, error, span_id.
|
|
# Both 'superset_tools_app' and 'cot' loggers have propagate=False — no text duplicates via root logger.
|
|
# @INVARIANT Every logger.info() call MUST produce exactly one JSON line (see [ADR LOG-002] for why).
|
|
# @STATUS ACCEPTED
|
|
# @RATIONALE Low-value logs (e.g. repeated "User principal resolved", "Fetching user by username", infrastructure cache hits) pollute traces. Adding more suppression/derivation in the logger core hides the problem and makes the system harder to reason about for both humans and agents. Instead, we remove or elevate the intent at the source (in modules), provide minimal infrastructure (derive_src, explicit src= support), and keep the logger simple.
|
|
# @REJECTED Only complicating the logger (more ifs, more derive logic, more special cases) — rejected because it treats symptoms, leads to fragile filters, and violates the principle that the log statement should be self-documenting at the call site.
|
|
# @POST Call sites must be audited and cleaned; new code must follow the pattern of meaningful intent + qualified src. Suppression list in logger is temporary and should shrink.
|
|
# @SIDE_EFFECT Configures global logger handlers and formatters; seeds global _enable_belief_state
|
|
# and _task_log_level; sets propagate=False on both loggers; writes JSON to console/files.
|
|
# @RELATION DEPENDS_ON -> [LOG-001:alembic/env.py:fileConfig]
|
|
# If alembic/env.py calls fileConfig() without disable_existing_loggers=False, Python 3.13's
|
|
# logging framework sets logger.disabled = True on 'superset_tools_app', silencing ALL output.
|
|
# @RATIONALE Replaced BeliefFormatter text-based [Entry]/[Exit]/[Action] logging with CotJsonFormatter
|
|
# JSON output. Old format was not machine-parseable and mixed presentation with intent. CotJsonFormatter
|
|
# produces structured JSON consistent with Molecular CoT protocol.
|
|
# @REJECTED Keeping both formatters side-by-side was rejected (two inconsistent output formats would
|
|
# confuse log consumers).
|
|
# @REJECTED Keeping propagate=True was rejected after uvicorn's dictConfig added a root logger handler
|
|
# that duplicates every log as plain text (see [ADR LOG-002]).
|
|
# @DATA_CONTRACT All log records conform to decision audit JSON schema: {ts, level, trace_id, src, marker, intent, span_id?, payload?, error?}
|
|
# @INVARIANT CotJsonFormatter.format() always returns valid single-line JSON string.
|
|
from contextlib import contextmanager
|
|
from datetime import UTC, datetime
|
|
import logging
|
|
from logging.handlers import RotatingFileHandler
|
|
import threading
|
|
import time
|
|
import types
|
|
from typing import Any
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
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 src.core.cot_formatter import CotJsonFormatter, set_payload_cap
|
|
from .ws_log_handler import WebSocketLogHandler
|
|
|
|
# Thread-local storage for belief state
|
|
_belief_state = threading.local()
|
|
|
|
# Global flag for belief state logging
|
|
_enable_belief_state = True
|
|
|
|
# Global task log level filter
|
|
_task_log_level = "INFO"
|
|
|
|
|
|
# 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.
|
|
|
|
|
|
# #region Core.Logger.LogEntry [C:1] [TYPE Class] [SEMANTICS log,entry,record,pydantic]
|
|
# @BRIEF A Pydantic model representing a single, structured log entry.
|
|
class LogEntry(BaseModel):
|
|
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
level: str
|
|
message: str
|
|
context: dict[str, Any] | None = None
|
|
# #endregion Core.Logger.LogEntry
|
|
|
|
|
|
# #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 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 = "", 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:
|
|
# Log entry as REASON (gated by _enable_belief_state)
|
|
if _enable_belief_state:
|
|
intent_msg = message or f"Entering {anchor_id}"
|
|
cot_log(anchor_id, "REASON", intent_msg, level="DEBUG")
|
|
yield
|
|
elapsed_ms = round((time.monotonic() - _start) * 1000, 1)
|
|
cot_log(
|
|
anchor_id, "REFLECT", f"{anchor_id}: completed",
|
|
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", claim=claim,
|
|
)
|
|
raise
|
|
finally:
|
|
reset_contract_scope(_contract_token)
|
|
_belief_state.anchor_id = old_anchor
|
|
# #endregion Core.Logger.BeliefScope
|
|
|
|
|
|
# #region Core.Logger.ConfigureLogger [C:4] [TYPE Function] [SEMANTICS logging,configuration,initialization,cot]
|
|
# @ingroup Core
|
|
# @BRIEF Configures the main logger and the CoT logger with CotJsonFormatter, file handlers, and global flags.
|
|
# @RELATION CALLS -> [CotJsonFormatter]
|
|
# @RELATION CALLS -> [CotLoggerModule]
|
|
# @PRE config is a valid LoggingConfig instance.
|
|
# @POST Logger levels, handlers, formatters, belief state flag, task log level, and
|
|
# propagate flags (False) are updated. Both loggers emit JSON only — no text duplicates.
|
|
# @SIDE_EFFECT Mutates global _enable_belief_state, _task_log_level; adds/removes handlers
|
|
# on both logger and cot_logger; sets propagate=False on both; creates file directories.
|
|
# @DATA_CONTRACT configure_logger() -> ENABLES both loggers. Every call to logger.info()
|
|
# MUST produce exactly one JSON line (not zero, not two). See [ADR LOG-001] and [ADR LOG-002].
|
|
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 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).
|
|
level = getattr(logging, config.level.upper(), logging.INFO)
|
|
logger.setLevel(level)
|
|
|
|
# Remove existing file handlers
|
|
handlers_to_remove = [h for h in logger.handlers if isinstance(h, RotatingFileHandler)]
|
|
for h in handlers_to_remove:
|
|
logger.removeHandler(h)
|
|
h.close()
|
|
|
|
# Add file handler if file_path is set
|
|
if config.file_path:
|
|
from pathlib import Path
|
|
log_file = Path(config.file_path)
|
|
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
file_handler = RotatingFileHandler(
|
|
config.file_path,
|
|
maxBytes=config.max_bytes,
|
|
backupCount=config.backup_count
|
|
)
|
|
file_handler.setFormatter(CotJsonFormatter())
|
|
file_handler.setLevel(level)
|
|
logger.addHandler(file_handler)
|
|
|
|
# Update existing handlers' formatters/levels to CotJsonFormatter
|
|
for handler in logger.handlers:
|
|
if not isinstance(handler, RotatingFileHandler):
|
|
handler.setFormatter(CotJsonFormatter())
|
|
handler.setLevel(level)
|
|
|
|
# Configure the 'cot' logger for consistent JSON output
|
|
from src.core.cot_logger import cot_logger
|
|
cot_logger.setLevel(level)
|
|
if not cot_logger.handlers:
|
|
cot_handler = logging.StreamHandler()
|
|
cot_handler.setFormatter(CotJsonFormatter())
|
|
cot_logger.addHandler(cot_handler)
|
|
for handler in cot_logger.handlers:
|
|
handler.setLevel(level)
|
|
|
|
# Disable propagation to prevent duplicate output via root logger handlers.
|
|
# Test fixtures that need caplog should set propagate=True in their setup.
|
|
# See ADR LOG-002 — was previously caller-side in ConfigManager but that
|
|
# caused duplication before ConfigManager ran.
|
|
logger.propagate = False
|
|
cot_logger.propagate = False
|
|
# #endregion Core.Logger.ConfigureLogger
|
|
|
|
|
|
# #region Core.Logger.GetTaskLogLevel [C:1] [TYPE Function] [SEMANTICS logging,configuration,getter]
|
|
# @BRIEF Returns the current task log level filter.
|
|
def get_task_log_level() -> str:
|
|
return _task_log_level
|
|
# #endregion Core.Logger.GetTaskLogLevel
|
|
|
|
|
|
# #region Core.Logger.ShouldLogTaskLevel [C:1] [TYPE Function] [SEMANTICS logging,filter,level]
|
|
# @BRIEF Checks if a log level should be recorded based on task_log_level setting.
|
|
def should_log_task_level(level: str) -> bool:
|
|
level_order = {"DEBUG": 0, "INFO": 1, "WARNING": 2, "ERROR": 3}
|
|
current_level = _task_log_level.upper()
|
|
check_level = level.upper()
|
|
|
|
current_order = level_order.get(current_level, 1)
|
|
check_order = level_order.get(check_level, 1)
|
|
|
|
return check_order >= current_order
|
|
# #endregion Core.Logger.ShouldLogTaskLevel
|
|
|
|
# Agent-centric globals _enable_agent_view/_hide_routine_infra removed.
|
|
# Suppression is centralized in shared/cot_logger.py. Use set_routine_suppression()
|
|
# from shared to configure at runtime.
|
|
|
|
|
|
# #region Core.Logger [C:2] [TYPE Global] [SEMANTICS logger,global,instance]
|
|
# @ingroup Core
|
|
# @BRIEF The global application logger instance configured with CotJsonFormatter, console handler, and WebSocketLogHandler.
|
|
logger = logging.getLogger("superset_tools_app")
|
|
|
|
# #region Core.Logger.Believed [C:2] [TYPE Function] [SEMANTICS decorator,belief,scope]
|
|
# @ingroup Core
|
|
# @BRIEF A decorator that wraps a function in a belief scope.
|
|
def believed(anchor_id: str):
|
|
def decorator(func):
|
|
def wrapper(*args, **kwargs):
|
|
with belief_scope(anchor_id):
|
|
return func(*args, **kwargs)
|
|
return wrapper
|
|
return decorator
|
|
# #endregion Core.Logger.Believed
|
|
logger.setLevel(logging.INFO)
|
|
|
|
# Create CotJsonFormatter (shared with all handlers)
|
|
_formatter = CotJsonFormatter()
|
|
|
|
# Add console handler when none configured yet
|
|
if not logger.handlers:
|
|
_console_handler = logging.StreamHandler()
|
|
_console_handler.setFormatter(_formatter)
|
|
logger.addHandler(_console_handler)
|
|
|
|
# Ring buffer for live app log console (/reports Logs tab + /ws/app-logs).
|
|
# Capacity ~3k lines (~1MB JSON) — enough for UI tail; export uses task DB / files.
|
|
_ws_handler = WebSocketLogHandler(capacity=3000)
|
|
_ws_handler.setFormatter(_formatter)
|
|
logger.addHandler(_ws_handler)
|
|
|
|
# Mirror CoT logger into the same buffer so the console sees full server stream.
|
|
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)
|
|
|
|
|
|
# #region Core.Logger.GetAppLogHandler [C:1] [TYPE Function] [SEMANTICS logging,buffer,accessor]
|
|
# @BRIEF Return the process-wide app log ring buffer handler for REST/WS tails.
|
|
def get_app_log_handler() -> WebSocketLogHandler:
|
|
return _ws_handler
|
|
# #endregion Core.Logger.GetAppLogHandler
|
|
|
|
# Example usage:
|
|
# logger.info("Application started", extra={"context_key": "context_value"})
|
|
# logger.error("An error occurred", exc_info=True)
|
|
|
|
|
|
# #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.
|
|
# One frame walk yields both the fallback src and the violation-branch loc.
|
|
src = explicit_src or user_extra.pop('src', None)
|
|
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}
|
|
# 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
|
|
|
|
|
|
# #region Core.Logger.EmitAtLevel [C:2] [TYPE Function] [SEMANTICS log,level,dispatch,helper]
|
|
# @ingroup Core
|
|
# @BRIEF Emit a marker record through the level-named logger method (info/warning/...),
|
|
# honoring an explicit ``level=`` override.
|
|
# @RATIONALE Dispatch goes through target.info/target.warning — NOT target.log(numeric) —
|
|
# because the established facade contract routes records through the level methods
|
|
# (tests and consumers patch/intercept logger.info etc.). The SSOT primitive's
|
|
# level= control is preserved by mapping the override name to the matching method.
|
|
# @INVARIANT Without level= override the emission path is byte-identical to the pre-override
|
|
# facade behavior (reason/reflect -> info, explore -> warning).
|
|
_LEVEL_METHOD_NAMES = {"DEBUG": "debug", "INFO": "info", "WARNING": "warning", "ERROR": "error", "CRITICAL": "critical"}
|
|
|
|
|
|
def _emit_at_level(target, level_override, default_level, msg, extra, kwargs):
|
|
method_name = _LEVEL_METHOD_NAMES.get(str(level_override).upper()) if level_override else None
|
|
emit = getattr(target, method_name, None) if method_name else None
|
|
if emit is None:
|
|
emit = {
|
|
logging.DEBUG: target.debug,
|
|
logging.INFO: target.info,
|
|
logging.WARNING: target.warning,
|
|
logging.ERROR: target.error,
|
|
logging.CRITICAL: target.critical,
|
|
}[default_level]
|
|
emit(msg, extra=extra, **kwargs)
|
|
# #endregion Core.Logger.EmitAtLevel
|
|
|
|
|
|
# #region Core.Logger.Reason [C:2] [TYPE Function] [SEMANTICS log,reason,marker,info]
|
|
# @ingroup Core
|
|
# @BRIEF Logs a REASON marker (INFO level) with structured extra data for CotJsonFormatter.
|
|
# @RATIONALE INFO level per decision audit protocol: REASON is the primary reasoning bond
|
|
# and must be visible in production. DEBUG is reserved for high-frequency loops
|
|
# and is requested explicitly via the ``level=`` kwarg.
|
|
def reason(self, msg, *args, **kwargs):
|
|
"""Log a REASON marker — strict deduction, core logic.
|
|
|
|
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"``).
|
|
"""
|
|
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
|
|
src = explicit_src or user_extra.pop('src', None)
|
|
src_declared = bool(src) and src not in {"superset_tools_app", "app_name", "root", ""}
|
|
if not src_declared:
|
|
src = derive_src()
|
|
|
|
# Central suppression via src/core/cot_logger.py is_routine_infra()
|
|
if is_routine_infra(msg):
|
|
return
|
|
|
|
extra = {'marker': 'REASON', 'intent': msg, 'src': src}
|
|
if error_val is not None:
|
|
extra['error'] = error_val
|
|
# 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.INFO, msg, extra, kwargs)
|
|
# #endregion Core.Logger.Reason
|
|
|
|
|
|
# #region Core.Logger.Reflect [C:2] [TYPE Function] [SEMANTICS log,reflect,marker,info]
|
|
# @ingroup Core
|
|
# @BRIEF Logs a REFLECT marker (INFO level) with structured extra data for CotJsonFormatter.
|
|
# @RATIONALE INFO level per decision audit protocol: REFLECT verifies outcomes and
|
|
# must be visible in production. DEBUG is reserved for high-frequency loops
|
|
# and is requested explicitly via the ``level=`` kwarg.
|
|
def reflect(self, msg, *args, **kwargs):
|
|
"""Log a REFLECT marker — self-check, structural validation.
|
|
|
|
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"``).
|
|
"""
|
|
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
|
|
src = explicit_src or user_extra.pop('src', None)
|
|
src_declared = bool(src) and src not in {"superset_tools_app", "app_name", "root", ""}
|
|
if not src_declared:
|
|
src = derive_src()
|
|
|
|
# Central suppression via src/core/cot_logger.py is_routine_infra()
|
|
if is_routine_infra(msg):
|
|
return
|
|
|
|
extra = {'marker': 'REFLECT', 'intent': msg, 'src': src}
|
|
if error_val is not None:
|
|
extra['error'] = error_val
|
|
# 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.INFO, msg, extra, kwargs)
|
|
# #endregion Core.Logger.Reflect
|
|
|
|
logger.explore = types.MethodType(explore, logger)
|
|
logger.reason = types.MethodType(reason, logger)
|
|
logger.reflect = types.MethodType(reflect, logger)
|
|
|
|
# #endregion Core.Logger
|
|
# #endregion Core.Logger.LoggerModule
|