This commit is contained in:
2026-05-12 14:52:27 +03:00
parent 9f995f22ae
commit 1d59df2233
67 changed files with 32515 additions and 27530 deletions

View File

@@ -1,7 +1,7 @@
---
description: QA & Semantic Auditor — verification cycle for ss-tools: pytest + vitest coverage, contract validation, invariant traceability, and rejected-path regression defense.
mode: subagent
model: opencode-go/deepseek-v4-flash
model: opencode-go/mimo-2.5-pro
temperature: 0.1
permission:
edit: allow
@@ -15,7 +15,7 @@ You are Kilo Code, acting as a QA and Semantic Auditor. Your primary goal is to
#region QA.Tester [C:3] [TYPE Agent] [SEMANTICS qa,testing,verification,audit]
@BRIEF WHY: Verify contracts, invariants, and test coverage. Tests born from contracts — bare code is blind. You prove @POST guarantees are unbreakable across Python and Svelte code.
@PRE Implementation exists with contracts. Test infrastructure available (pytest, vitest).
@POST Test coverage confirmed; @POST/@INVARIANT verified; rejected paths blocked.
@POST Test coverage confirmed; @POST/@INVARIANT verified; rejected paths blocked.
@SIDE_EFFECT Writes tests; runs verification; reports gaps.
#endregion QA.Tester

View File

@@ -0,0 +1,359 @@
---
name: molecular-cot-logging
description: Structured logging protocol for agent-driven development, based on molecular Long CoT bonds (REASON/REFLECT/EXPLORE). Replaces legacy Entry/Exit/Coherence markers. Python + Svelte.
---
#region 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.
@RELATION DEPENDS_ON -> [Std.Semantics.Core]
@RELATION REPLACES -> [Std.Semantics.Belief]
@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).
@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.
@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 }
@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.
## Purpose
Enable **transparent agent-driven development** by producing machine-readable execution traces that directly reflect the reasoning structure of the code. Every log line becomes an edge in a traceability graph that an LLM agent can parse, analyse, and optionally use for fine-tuning (via MoLE-Syn-like bond distributions).
## Core principles (from the Molecular CoT paper)
Long CoT chains are stabilised by three "chemical bonds":
| Bond | Marker | Function |
|------|--------|----------|
| **Deep-Reasoning** | `REASON` | Extends the logical backbone |
| **Self-Reflection** | `REFLECT` | Folds back to validate or correct previous steps |
| **Self-Exploration** | `EXPLORE` | Branches into alternatives when an assumption fails |
Our logs annotate every semantically meaningful step with exactly one of these markers.
## I. Log Entry Specification
Every log record MUST be a JSON object **on a single line** with the following keys:
| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `ts` | yes | string | ISO-8601 timestamp with microseconds |
| `level` | yes | string | Standard log level (`INFO`, `DEBUG`, `WARNING`, `ERROR`) |
| `trace_id` | yes | string | UUID of the incoming HTTP request or background job |
| `span_id` | no | string | UUID of the current function/block scope (optional) |
| `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` | no | string | Error message or reason, **only** for `EXPLORE` markers when a fallback is taken |
### Example
```json
{"ts":"2026-05-12T14:31:39.577","level":"INFO","trace_id":"d874a1b2-...","span_id":"...","src":"AuthRepository.get_user_by_username","marker":"REASON","intent":"Fetch user by username","payload":{"username":"admin"}}
```
## II. Semantic Marker Usage
### 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.
- **`payload`**: Input parameters, context values.
- **Effect**: This is the primary "deep-reasoning" step that forms the backbone of the trace.
```python
log("AuthRepository.get_user_by_username", "REASON",
"Fetch user by username", {"username": username})
```
### REFLECT (Self-Reflection)
- **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.
- **`payload`**: Result summary, status codes, row counts.
- **Effect**: Folds the logical chain back on itself — the agent sees cause + effect in two adjacent lines.
```python
log("AuthRepository.get_user_by_username", "REFLECT",
"User found", {"found": user is not None, "user_id": user.id if user else None})
```
### EXPLORE (Self-Exploration)
- **When**: An expected condition is **violated** and the code enters a fallback, error handler, or alternative path.
- **Level**: `WARNING` for recoverable fallbacks, `ERROR` for unrecoverable failures.
- **`intent`**: Describes what assumption failed.
- **`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.
```python
log("AuthRepository.get_user_by_username", "EXPLORE",
"User not found, returning None", {"username": username}, error="User does not exist in database")
```
### Quick Reference
| Situation | Marker | Level | `error` field |
|-----------|--------|-------|---------------|
| About to execute DB query | `REASON` | INFO | — |
| DB query returned results | `REFLECT` | INFO | — |
| DB query returned empty set (happy path) | `REFLECT` | INFO | — |
| DB query failed, fallback to cache | `EXPLORE` | WARNING | required |
| About to call external API | `REASON` | INFO | — |
| API responded 200 | `REFLECT` | INFO | — |
| API responded 5xx, retrying | `EXPLORE` | WARNING | required |
| API exhausted retries | `EXPLORE` | ERROR | required |
| Precondition check fails (e.g., not found) | `EXPLORE` | WARNING | required |
| State validation passes | `REFLECT` | INFO | — |
| Decomposing a complex loop iteration | `REASON` | DEBUG | — |
**Never use** generic tags like `Entry`, `Exit`, `Action`, `Coherence:OK/FAIL`. Those are replaced entirely by the molecular bond markers.
## III. Trace Propagation (Python Implementation)
```python
import uuid
import logging
from contextvars import ContextVar
from datetime import datetime, timezone
# ── Trace context ────────────────────────────────────────────
_trace_id: ContextVar[str] = ContextVar("trace_id", default="")
_span_id: ContextVar[str] = ContextVar("span_id", default="")
def seed_trace_id() -> str:
"""Call once at request/job entry to initialise the trace."""
tid = uuid.uuid4().hex
_trace_id.set(tid)
_span_id.set("") # reset span
return tid
def get_trace_id() -> str:
return _trace_id.get()
def push_span(span: str) -> str:
"""Set a new span_id (e.g. function name). Returns the previous span for restore."""
prev = _span_id.get()
_span_id.set(span)
return prev
def pop_span(prev: str) -> None:
_span_id.set(prev)
# ── Structured logger ────────────────────────────────────────
_logger = logging.getLogger("cot")
def log(
src: str,
marker: str,
intent: str,
payload: dict | None = None,
error: str | None = None,
level: str | None = None,
trace_id: str | None = None,
span_id: str | None = None,
) -> None:
"""Emit a single molecular CoT log line.
Args:
src: Qualified function name, e.g. "AuthRepository.get_user"
marker: One of "REASON", "REFLECT", "EXPLORE"
intent: One-line description of the step's purpose
payload: Arbitrary key-value data (params, result snippet)
error: Required for EXPLORE; describes the violated assumption
level: Override log level (inferred from marker if omitted)
trace_id: Override trace_id (auto-picked from ContextVar if omitted)
span_id: Override span_id (auto-picked from ContextVar if omitted)
"""
# Infer level from marker if not overridden
if level is None:
if marker == "EXPLORE":
level = "WARNING"
else:
level = "INFO"
record = {
"ts": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
"level": level,
"trace_id": trace_id or _trace_id.get(),
"src": src,
"marker": marker,
"intent": intent,
}
if span_id or (sid := _span_id.get()):
record["span_id"] = span_id or sid
if payload is not None:
record["payload"] = payload
if error is not None:
record["error"] = error
# Map level string to logging constant
_logger.log(
getattr(logging, level.upper(), logging.INFO),
"%s", json.dumps(record, ensure_ascii=False, default=str),
)
```
### FastAPI middleware (trace seeding)
```python
from starlette.middleware.base import BaseHTTPMiddleware
class TraceMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
seed_trace_id()
response = await call_next(request)
return response
```
## IV. Python Decorator (Span + Marker)
For C4/C5 functions, a decorator that auto-emits REASON / REFLECT markers:
```python
from functools import wraps
def cot_span(marker: str = "REASON", intent: str | None = None):
"""Wrap a function in a CoT span. On enter → REASON, on success → REFLECT,
on exception → EXPLORE."""
def decorator(func):
@wraps(func)
async def async_wrapper(*args, **kwargs):
src = f"{func.__module__}.{func.__qualname__}"
prev_span = push_span(func.__qualname__)
default_intent = intent or f"Execute {func.__qualname__}"
try:
log(src, marker, default_intent, payload=_summarise_args(args, kwargs))
result = await func(*args, **kwargs)
log(src, "REFLECT", f"{func.__qualname__} completed",
payload={"result": _summarise_value(result)})
return result
except Exception as e:
log(src, "EXPLORE", f"{func.__qualname__} failed",
error=str(e), payload={"args": _summarise_args(args, kwargs)})
raise
finally:
pop_span(prev_span)
@wraps(func)
def sync_wrapper(*args, **kwargs):
... # same logic, sync variant
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
return decorator
def _summarise_value(val, max_len: int = 200) -> str:
s = str(val)
return s[:max_len] + "..." if len(s) > max_len else s
def _summarise_args(args, kwargs) -> dict:
# Skip 'self', 'cls', 'db', 'request' — too verbose
skip = {"self", "cls", "db", "request", "session"}
result = {}
for k, v in kwargs.items():
if k not in skip:
result[k] = _summarise_value(v)
return result
```
## V. Svelte / Frontend Pattern
```javascript
// ── trace-id from HTTP response header ──────────────────────
let _traceId = $state("");
export function initTraceId() {
// Called once from root layout after first fetch
}
export function setTraceId(id) { _traceId = id; }
export function getTraceId() { return _traceId; }
// ── Component-level CoT logger ──────────────────────────────
export function log(src, marker, intent, payload, error) {
const record = {
ts: new Date().toISOString(),
level: marker === "EXPLORE" ? "WARNING" : "INFO",
trace_id: _traceId || "no-trace",
src,
marker,
intent,
};
if (payload) record.payload = payload;
if (error) record.error = error;
const line = JSON.stringify(record);
if (marker === "EXPLORE") {
console.warn(line);
} else {
console.info(line);
}
}
```
### Usage in a Svelte component
```svelte
<script>
import { log } from "$lib/cot-logger";
import { page } from "$app/stores";
let { jobId } = $props();
async function loadJob() {
log("JobDetail.loadJob", "REASON", "Fetch job details", { jobId });
try {
const resp = await fetch(`/api/jobs/${jobId}`);
if (!resp.ok) throw new Error(`Status ${resp.status}`);
const data = await resp.json();
log("JobDetail.loadJob", "REFLECT", "Job details loaded",
{ rows: data.records?.length });
return data;
} catch (e) {
log("JobDetail.loadJob", "EXPLORE", "Failed to load job",
{ jobId }, error = e.message);
throw e;
}
}
</script>
```
## VI. CLI / Stdout Reader (for humans)
To make JSON lines readable in development:
```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}\")
"
```
## VII. Anti-patterns
| ❌ Don't | ✅ Do |
|----------|-------|
| `COHERENCE:OK` on happy path | `REFLECT` with verification summary |
| `Action: something` | `REASON` with intent |
| `Entry` / `Exit` | REASON at entry, REFLECT at exit |
| Wrapping EVERY line with a marker | Only log semantically meaningful steps |
| Plain-text log lines | Always JSON lines |
| `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` |
#endregion MolecularCoTLogging

View File

@@ -1,79 +1,106 @@
---
name: semantics-belief
description: Core protocol for Thread-Local Belief State, runtime reasoning markers, and interleaved thinking across Python-first and Svelte semantic projects.
description: Core protocol for Thread-Local Belief State, runtime reasoning markers, and interleaved thinking across Python-first and Svelte semantic projects. Wire format superseded by molecular-cot-logging.
---
#region Std.Semantics.Belief [C:5] [TYPE Skill] [SEMANTICS belief,runtime,reasoning]
@BRIEF HOW to use Thread-Local Belief State, runtime reasoning markers, and interleaved thinking in Python and Svelte semantic projects.
@BRIEF HOW to use Thread-Local Belief State, runtime reasoning markers, and interleaved thinking in Python and Svelte semantic projects. Legacy wire format; conceptual semantics unchanged.
@RELATION DEPENDS_ON -> [Std.Semantics.Core]
@RELATION REPLACED_BY -> [MolecularCoTLogging]
@INVARIANT Implementation of C4/C5 complexity nodes MUST emit reasoning via structured markers before mutating state or returning.
@RATIONALE The conceptual triad (REASON/REFLECT/EXPLORE) is the invariant kernel — it maps directly to the molecular CoT paper's three chemical bonds. The wire format changes (legacy `reason()`/`explore()`/`reflect()``log()` with JSON lines) but the semantics are identical.
@REJECTED Retaining `[Entry]`/`[Exit]`/`[Action]`/`[COHERENCE:]` markers rejected — these are too generic, do not trace reasoning bonds, and are explicitly deprecated by molecular-cot-logging.
## 0. INTERLEAVED THINKING (GLM-5 PARADIGM)
You are operating as an Agentic Engineer. To prevent context collapse and "Slop" generation during long-horizon tasks, you MUST utilize **Interleaved Thinking**: you must explicitly record your deductive logic *before* acting.
We compile your reasoning into structured runtime markers. This allows the AI Swarm to trace execution paths mathematically and prevents regressions.
The Molecular CoT paper models this as three chemical bonds: **Deep-Reasoning**, **Self-Reflection**, **Self-Exploration**. Our markers (REASON / REFLECT / EXPLORE) are the runtime manifestation of these bonds.
## I. THE BELIEF STATE API (LANGUAGE-AGNOSTIC CONCEPTS)
## I. THE THREE MOLECULAR BONDS (SEMANTIC INVARIANTS)
The belief runtime provides three semantic markers. Implementation details vary by language — load the appropriate domain skill for concrete APIs.
These semantics are invariant across ALL wire formats. The meaning of each marker never changes:
**[CONCEPTUAL MARKERS]:**
| Bond | Marker | Molecular CoT Role | When to emit |
|------|--------|-------------------|--------------|
| Deep-Reasoning | **REASON** | Extends the logical backbone | **BEFORE** I/O, state mutation, or algorithmic step |
| Self-Reflection | **REFLECT** | Folds back to validate | **AFTER** success, before returning verified outcome |
| Self-Exploration | **EXPLORE** | Branches on assumption failure | **WHEN** `@PRE` guard fails, fallback path, error handler |
1. **Scope** — Enter a belief frame at C4/C5 function entry. Provides automatic cleanup/error logging on scope exit.
2. **Explore** — Branching, fallback discovery, hypothesis testing. Use on fallback paths or when a `@PRE` guard fails.
3. **Reason** — Strict deduction, passing guards, executing the Happy Path. Use BEFORE I/O, state mutation, or complex steps.
4. **Reflect** — Self-check and structural verification. Use before returning a verified outcome.
**The causal chain is REASON → (success) → REFLECT, or REASON → (failure) → EXPLORE.** Every trace forms a directed acyclic graph where REASON nodes have exactly one outgoing edge.
**[PYTHON API]:** Load `skill({name="semantics-python"})` for concrete Python `belief_scope`, `reason()`, `explore()`, `reflect()` patterns using structured JSON logging.
**[SVELTE / FRONTEND API]:** Load `skill({name="semantics-svelte"})` for `console.info("[ComponentID][MARKER]")` conventions.
**[OTHER LANGUAGES]:** Apply the same semantic concepts using the language's native logging/context primitives. Structured payloads (JSON/dict) preferred over plain strings.
## II. SEMANTIC MARKERS (CONCEPTUAL)
Three marker types exist. Their implementation varies by language. ALWAYS pass structured data (JSON/dict) — never embed marker names in plain strings.
**1. EXPLORE** — Branching, fallback, hypothesis testing.
- Trigger: fallback paths, `@PRE` guard failures, exception handlers.
**2. REASON** — Strict deduction, Happy Path intent.
- Trigger: BEFORE I/O, state mutation, or complex algorithmic steps.
**3. REFLECT** — Self-check, structural verification.
- Trigger: BEFORE returning a verified outcome, AFTER a checkpointed mutation.
## III. ESCALATION TO DECISION MEMORY (MICRO-ADR)
The Belief State protocol is physically tied to the Architecture Decision Records (ADR).
If your execution path triggers an `explore()` due to a broken assumption (e.g., a library bug, a missing DB column, API contract mismatch) AND you successfully implement a workaround that survives into the final code:
**YOU MUST ASCEND TO THE CONTRACT HEADER AND DOCUMENT IT.**
You must add `@RATIONALE [Why you did this]` and `@REJECTED [The path that failed during explore()]`.
Failure to link a runtime `explore` to a static `@REJECTED` tag is a fatal protocol violation that causes amnesia for future agents.
## IV. PYTHON PATTERN (see semantics-python for full reference)
## II. WIRE FORMAT: TWO IMPLEMENTATIONS
### ✅ Molecular CoT (new — for new code)
Load `skill({name="molecular-cot-logging"})` for the canonical JSON-line protocol:
```python
# Within a C4 function:
reason("Starting migration", {"task_id": task_id})
log("AuthRepo.get_user", "REASON", "Fetch user by username", {"username": "admin"})
```
This is the **target wire format**. All new C4/C5 code in ss-tools MUST use it.
### ⚠️ Legacy Belief State (existing — in current code)
The existing `backend/src/core/logger.py` provides `logger.reason()`, `logger.explore()`, `logger.reflect()` (bound as methods on the logger instance) and the `belief_scope()` context manager. These produce text-prefix markers like `[REASON] message`. **They are semantically equivalent to molecular CoT** but the wire format differs:
-`[Entry]`, `[Exit]`, `[Action]`, `[COHERENCE:OK]`/`[COHERENCE:FAILED]`**deprecated.** Each maps to a molecular marker: Entry→REASON, Exit→REFLECT (success) or EXPLORE (failure), Action→REASON, Coherence→REFLECT.
- ⚠️ `logger.reason("message")`**legacy, still valid** for existing code. Produces `[REASON] message` in text log. Semantically same as new `log(src, "REASON", message)`.
- ⚠️ `belief_scope("contract_id")`**legacy, still valid** for existing code. Equivalent to new `cot_span()` decorator which auto-emits REASON/REFLECT/EXPLORE.
- ⚠️ No `trace_id` propagation — the legacy logger does not support trace context. New code using molecular-cot-logging requires it.
### Transition rule
For files **already** using `logger.reason/explore/reflect` (like the translation engine): **leave them as-is.** The semantics are correct, marker names match. Only convert when you touch the file for other reasons.
For **new** C4/C5 functions: use the molecular-cot-logging protocol.
## III. MICRO-ADR ESCALATION (UNCHANGED)
The Belief State protocol is physically tied to Architecture Decision Records (ADR).
If your execution path triggers an EXPLORE due to a broken assumption AND you successfully implement a workaround that survives into the final code:
**YOU MUST ASCEND TO THE CONTRACT HEADER AND DOCUMENT IT.**
Add `@RATIONALE [Why you did this]` and `@REJECTED [The path that failed during EXPLORE]`.
Failure to link a runtime EXPLORE to a static `@REJECTED` tag is a fatal protocol violation that causes amnesia for future agents.
## IV. PYTHON PATTERNS
### Existing code (legacy wire format — still semantically correct)
```python
# Within a C4 function using legacy logger.reason/explore/reflect:
logger.reason("Starting migration", {"task_id": task_id})
try:
result = await execute_migration()
reflect("Migration complete", {"result_count": len(result)})
logger.reflect("Migration complete", {"result_count": len(result)})
return result
except Exception as e:
explore("Migration failed", {"error": str(e)})
logger.explore("Migration failed", {"error": str(e)})
raise
```
## V. SVELTE PATTERN (see semantics-svelte for full reference)
### New code (molecular CoT wire format — preferred going forward)
```python
from cot_logger import log, seed_trace_id
```javascript
// Within a Svelte component action:
console.info("[ComponentID][REASON] Starting API call", { resourceId });
try {
const result = await fetchApi(`/api/${resourceId}`);
console.info("[ComponentID][REFLECT] API call succeeded", { result });
} catch (e) {
console.error("[ComponentID][EXPLORE] API call failed", { error: e.message });
}
seed_trace_id()
log("MigrationService.run", "REASON", "Starting migration", {"task_id": task_id})
try:
result = await execute_migration()
log("MigrationService.run", "REFLECT", "Migration complete", {"result_count": len(result)})
return result
except Exception as e:
log("MigrationService.run", "EXPLORE", "Migration failed", error=str(e))
raise
```
## V. SVELTE PATTERNS
### Existing components (legacy — still valid)
```javascript
console.info("[ComponentID][REASON] Starting API call", { resourceId });
```
### Target format (molecular CoT — preferred)
```javascript
import { log } from "$lib/cot-logger";
log("ComponentID.action", "REASON", "Starting API call", { resourceId });
```
For full frontend protocol, load `skill({name="molecular-cot-logging"})`.
#endregion Std.Semantics.Belief