Continuation. Part 1: Math vs Chaos: How We Taught an AI Agent to Stop Itself

From Watchdog to Metacognitive Layer

In Part 1, we described DE-Monitor — an external watchdog for AI agents that computed the agent's cognitive state in real time and injected a stop signal when degradation began. Seven behavioral axes, health score, stop signal into context. It worked.

But it was a beginning.

A watchdog answers "what happened?" It detects degradation. It says: stop, you're spamming tools, pause and report. But it doesn't answer "why?" and doesn't track the agent's cognitive process as a sequence of states.

An agent doesn't degrade instantly. It goes through stages. First everything is fine — it works on the task. Then it starts deviating. Then it gets stuck. Then it degrades. This isn't a binary switch, it's a trajectory.

And if we want not just to catch degradation but to understand the agent's cognitive process — we need a different level. Not a watchdog. A metacognitive layer.

We called it DE-Cogneti.

What Is Metacognition (and Why It's Not LLM)

Metacognition is "thinking about thinking." In cognitive science, it's the Nelson-Narens framework: a model where a monitor watches the cognitive process and a controller intervenes when something goes wrong. Humans do this naturally — you notice you're distracted and return to the task. You feel stuck and change approach.

LLM agents don't do this. Not because they can't, but because they lack a built-in metacognition mechanism. An LLM generates the next token based on context — that's it. It doesn't "notice" it's going in circles. It doesn't "feel" it lost the goal. It just makes the next action.

Can you teach an LLM metacognition? Yes — there's work like Reflexion (Shinn, 2023), where Actor + Evaluator + Self-Reflector achieves 91% pass@1. But the Evaluator there is also an LLM. And here lies a fundamental problem.

The principle we call "Governor must not be LLM-sovereign": a monitor based on LLM is another LLM that can degrade. You've put a patient in charge of watching a patient. If the monitor is an LLM, who monitors the monitor? Recursion. Infinite regress.

That's why DE-Cogneti's metacognitive layer is not an LLM. It's math. Counters. Formulas. Exponential moving averages. A finite state machine. Zero model calls. Zero embeddings. Zero seconds to compute.

How DE-Cogneti v0.2 Works

Cognitive Finite State Machine

The agent is in one of five cognitive states at any moment:

State Meaning Transition
FOCUSED Agent works on task, everything normal → DEVIATING at first signs
DEVIATING Agent starts drifting from task → STUCK or → FOCUSED (self-recovered)
STUCK Agent stuck, repeating actions → DEGRADED if not escaped
DEGRADED Degradation: tool spam, goal loss → CRITICAL if continues
CRITICAL Total loss of control, intervention needed → FOCUSED after reflection injection

This is a finite state machine (FSM). Transitions are computed from metrics, not LLM judgment. Health score, behavioral patterns, history — all numbers updated on every lifecycle hook.

Seven Axes, Health Score, Reflection

DE-Cogneti inherits seven axes from DE-Monitor: tool_spam, rule_violation, loop_risk, token_burn, scope_creep, context_switch, approval_bypass. Each computed from lifecycle hook counters — no LLM, no embeddings, no cosine similarity.

Health score formula: GPV×0.3 + entropy×0.2 + loop×0.2 + effort×0.3. GPV — Goal Progress Velocity, average change in key axes. Entropy — score distribution. Loop risk — strategy repetition. Effort trend — rising, stable, falling.

When health drops below threshold, DE-Cogneti doesn't block the agent. It injects a reflection directly into context:

You are repeating the same tool call with identical parameters. This is unproductive. Stop, reassess your approach, and try a different strategy.

The agent reads this and responds — because LLMs react to text in context. This isn't a block. It's metacognitive intervention. The monitor tells the agent: you're degrading, here's why, stop and think.

Trajectory Logging

Every agent step is recorded as a JSONL trajectory: session_start, cognitive_state at each turn, patterns, metrics, cleanup. Not for real-time monitoring — for validation. We want to prove the intervention works.

What No One Else Has

We studied everything available on this topic. Here's the landscape as of August 2026:

Exists: post-hoc evaluation

Evaluation frameworks (AgentBench, SWE-bench, MAST) evaluate a session after completion. Tokens spent, report says "bad." Useful. Too late.

Exists: guardrails and filters

OpenAI SafetyKit, Anthropic guardrails, YecoAI Cognitive Layer — sit between agent and user, filter output. Agent keeps degrading, you just don't see it. YecoAI detects loops, amnesia, semantic drift — but monitors LLM output, not agent lifecycle behavior. And it blocks, doesn't intervene.

Exists: cognitive load managers

CLM (Cognitive Load Manager) — closest to us conceptually. Four signals: branching, repetition, uncertainty, goal drift. Score 0-100, green/amber/red zones. But: uses embeddings (a model!), weights are "informed heuristics, not empirically validated." Monitors output, not lifecycle hooks. No reflection injection.

Exists: one-class behavioral monitors

Trajectory Sentinel (arxiv 2608.02464) — ESN + CUSUM, ~200μs/step, one-class monitoring on healthy runs. Serious work, 2,823 episodes. But: trained on healthy runs, requires per-deployment calibration, detects onset, doesn't intervene. Repair is rollback to last step, not metacognitive intervention.

Exists: standardization

QSAF (Qorvex Security AI Framework) — formalizes Cognitive Degradation as a vulnerability class. Six degradation stages, seven runtime controls. Important work. But: it's a framework standard, not an implementation. No code.

Exists: cognitive runtimes

Cortex (402 stars) — cognitive runtime with metacognition, memory, plugins. But: it's an agent harness, not an external monitor. Metacognition is built into the agent, not an external layer. "Governor must not be LLM-sovereign" principle is violated — monitor and agent are one entity.

What doesn't exist: external metacognitive layer in pure math with reflection injection

We found no solution that:

  1. External — not built into the agent, observes from the side via lifecycle hooks
  2. Not LLM — pure math: counters, EMA, FSM. Zero model calls
  3. Real-time — inside the agent's lifecycle, not after
  4. Intervenes, doesn't block — injects reflection into context, agent decides to stop
  5. Logs trajectory — for subsequent validation of intervention efficacy
  6. Universal — works with any agent that has lifecycle hooks (OpenCode, OpenClaw, then any)

DE-Cogneti is the only solution that does all six simultaneously.

If you know an analogue — write to us. Seriously. We want to know.

Tested on a Live Agent

DE-Cogneti v0.2 was tested as a plugin for OpenCode 1.18 — an agent writing code on Qwen3.6-27B. Test passed. Plugin loads, FSM works, metrics compute, trajectories record, cleanup runs.

Three plugin-loading bugs found and fixed along the way — minor things like config filename and export format. Not interesting. What's interesting: the plugin worked, the agent didn't notice its presence, and when DE-Cogneti injected a reflection — the agent responded.

This is the main thesis. LLMs react to text in context. Reflection is text. But it's text that says: you're degrading, here's why, stop and think. And the agent stops. Not because it was blocked — but because an LLM cannot ignore meaningful text in context.

What's Next

Calibration

DE-Monitor v0.1 was calibrated on 109 real sessions with 8,862 tool calls. DE-Cogneti v0.2 needs the same: 10-20 real coding tasks, trajectory log collection, detector threshold tuning on real data. Measure: tokens saved, false reflections, stagnation caught.

Validation

The main question: does it work? For each detector firing, measure the chain:

detector fired → reflection injected → agent changed strategy? → outcome improved?

Not "detector fired." "Detector fired — agent read reflection — agent changed approach — outcome improved." Four links. Each needs proof.

If we prove this chain, we prove that an external metacognitive layer in math improves agent behavior. Without an LLM monitor. Without embeddings. Without blocking. Just math and text.

Universal Runtime

OpenCode is the first adapter. OpenClaw is next (orchestrator profile, GLM 5.2). Then — any agent with lifecycle hooks.

DE-Cogneti is designed as an external metacognitive runtime for any autonomous agent. Not a built-in monitor, not a plugin for a specific platform, but a layer that sits on top of any agent and watches its cognitive health.

Math is universal. Counters don't depend on platform. FSM doesn't depend on model. Reflection injection works with any LLM. Trajectory logging is a unified format.

Viveksha

DE-Cogneti began as a module of the Viveksha ecosystem — a cognitive engine that tracked client behavior in dialogue. 11 axes, EMA, health score. Then we noticed the agent degrades just like the client. Took the engine, adapted 7 axes instead of 11, called it DE-Monitor. Then realized watchdog was only the beginning, and built the metacognitive layer.

The ultimate goal — return DE-Cogneti to Viveksha as the new Dialogue Engine. The circle closes: the engine that watched clients will watch the agent that conducts the dialogue with clients.

Open Source

DE-Cogneti is published under the Apache 2.0 license:

github.com/logoserg-cmd/de-cogneti

The repository contains:

  • Working plugin for OpenCode 1.18 (V1 adapter)
  • V2 adapter for future OpenCode V2
  • Architecture document (ARCHITECTURE.md)
  • RFC-003 — main specification
  • Trajectory logs, configs, calibration data

Release v0.2.0: https://github.com/logoserg-cmd/de-cogneti/releases/tag/v0.2.0


Authors: Sergey & Fox. License: Apache 2.0. DE-Cogneti — part of the Viveksha ecosystem.