{"id":"306da62f-399a-457e-a78f-ed1c478e37b7","entityType":"agent","slug":"clawhub-voronindenis5-agent-cognitive-states","name":"agent-cognitive-states","canonicalUrl":"https://www.xpersona.co/agent/clawhub-voronindenis5-agent-cognitive-states","canonicalPath":"/agent/clawhub-voronindenis5-agent-cognitive-states","generatedAt":"2026-10-09T20:02:24.896Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":null},"description":"Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures. Skill: agent-cognitive-states Owner: voronindenis5 Summary: Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures. Tags: latest:0.1.2 Version history: v0.1.2 | 2026-08-11T11:59:00.849Z | auto agent-cognitive-states 0.1.2 - Removed the file skill-card.md from the pro","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 2.6K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s17b6amkd3wzqgg640v03a9r1n83gxs1:agent-cognitive-states","sourceUrl":"https://clawhub.ai/voronindenis5/agent-cognitive-states","homepage":"https://clawhub.ai/voronindenis5/skills/agent-cognitive-states","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/voronindenis5/agent-cognitive-states","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/voronindenis5/skills/agent-cognitive-states","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":68,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate "},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":null},"stars":null,"forks":null,"downloads":2595,"packageName":null,"latestVersion":"0.1.2","tractionLabel":"2.6K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T13:05:17.018Z","lastCrawledAt":"2026-10-09T13:05:17.018Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T13:05:17.018Z","lastVerifiedAt":null,"highlights":[{"version":"0.1.2","createdAt":"2026-08-11T11:59:00.849Z","changelog":"agent-cognitive-states 0.1.2 - Removed the file `skill-card.md` from the project. - No other functional or documentation changes in this release.","fileCount":11,"zipByteSize":17121},{"version":"0.1.1","createdAt":"2026-08-05T19:49:47.659Z","changelog":"## agent-cognitive-states 0.1.1 - Removed the skill-card.md file to clean up the repository. - No changes to core functionality or documentation content.","fileCount":11,"zipByteSize":17305},{"version":"0.1.0","createdAt":"2026-08-05T13:47:27.757Z","changelog":"- Initial release of the agent-cognitive-states skill, providing agents with self-awareness of six key cognitive states: Context Fatigue, Attention Drift, Memory Debt, Confidence Erosion, Context Fragmentation, and Skill Staleness. - Adds internal detection protocols and heuristics for recognizing degrading conditions, including token usage, turn counts, unsaved facts, repeated failures, topic fragmentation, and skill errors. - Defines standardized reporting and severity levels for cognitive states, ensuring clear communication and user visibility when issues arise. - Introduces actionable mitigation procedures for each cognitive state to help agents recover and maintain high reliability. - Enables agents to periodically self-check and intervene before cognitive issues lead to failures or degraded performance.","fileCount":11,"zipByteSize":17169}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17b6amkd3wzqgg640v03a9r1n83gxs1:agent-cognitive-states","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T20:02:24.894Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-voronindenis5-agent-cognitive-states/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":null},"readme":"Skill: agent-cognitive-states\n\nOwner: voronindenis5\n\nSummary: Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures.\n\nTags: latest:0.1.2\n\nVersion history:\n\nv0.1.2 | 2026-08-11T11:59:00.849Z | auto\n\nagent-cognitive-states 0.1.2\n\n- Removed the file `skill-card.md` from the project.\n- No other functional or documentation changes in this release.\n\nv0.1.1 | 2026-08-05T19:49:47.659Z | auto\n\n## agent-cognitive-states 0.1.1\n\n- Removed the skill-card.md file to clean up the repository.\n- No changes to core functionality or documentation content.\n\nv0.1.0 | 2026-08-05T13:47:27.757Z | auto\n\n- Initial release of the agent-cognitive-states skill, providing agents with self-awareness of six key cognitive states: Context Fatigue, Attention Drift, Memory Debt, Confidence Erosion, Context Fragmentation, and Skill Staleness.\n- Adds internal detection protocols and heuristics for recognizing degrading conditions, including token usage, turn counts, unsaved facts, repeated failures, topic fragmentation, and skill errors.\n- Defines standardized reporting and severity levels for cognitive states, ensuring clear communication and user visibility when issues arise.\n- Introduces actionable mitigation procedures for each cognitive state to help agents recover and maintain high reliability.\n- Enables agents to periodically self-check and intervene before cognitive issues lead to failures or degraded performance.\n\nArchive index:\n\nArchive v0.1.2: 11 files, 17121 bytes\n\nFiles: LICENSE (1070b), README.md (3786b), references (0b), references/detection-heuristics.md (4738b), scripts (0b), scripts/self_check.py (14932b), skill-card.md (2386b), SKILL.md (10426b), templates (0b), templates/guardian-cronjob.yaml (2321b), _meta.json (141b)\n\nFile v0.1.2:SKILL.md\n\n---\nname: agent-cognitive-states\ndescription: >-\n  Agent self-awareness of cognitive states — context fatigue, attention drift,\n  memory debt, confidence erosion, and skill staleness. Detect, report, and\n  mitigate degrading conditions before they cause failures.\nversion: 1.0.0\nauthor: Denis Voronin\nlicense: MIT\ntags:\n  - agent\n  - self-awareness\n  - metacognition\n  - context-management\n  - reliability\n---\n\n# Agent Cognitive States\n\n> **Give the agent metacognition: the ability to feel its own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\"\nThey will happily grind through a degraded context window, hallucinating details\nfrom early messages that were truncated, repeating failed approaches, and forgetting\ncritical facts they never persisted. This skill gives the agent a **vocabulary of\ninternal states** — and a protocol for detecting, reporting, and recovering from them.\n\n---\n\n## The Six Cognitive States\n\n### 1. 🥱 Context Fatigue\n**What:** The context window is filling up. Early messages are being truncated or summarized. The agent's \"working memory\" is degrading.\n\n**Detection signals:**\n- Conversation exceeds 60% of estimated context budget\n- You find yourself re-reading the original request because you lost details\n- Your responses reference information that may have been truncated\n- Token count per turn is rising (verbose compensating for lost context)\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fatigue (~70% context used)\n→ Persisting critical facts to memory before they're lost\n→ Suggesting session split or /new for remaining work\n```\n\n### 2. 🧠 Attention Drift\n**What:** The conversation has wandered far from the original task. The agent is doing work that wasn't asked for.\n\n**Detection signals:**\n- 10+ tool calls since the last direct user instruction\n- Current work has no clear connection to the original goal\n- You're responding to your own subgoals, not user requests\n- The TODO list no longer matches what you're actually doing\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Attention Drift (12 turns from last user message)\n→ Original goal: \"<original request>\"\n→ Current activity: \"<what I'm actually doing>\"\n→ Pausing for user confirmation: am I still on track?\n```\n\n### 3. 📝 Memory Debt\n**What:** Important facts, decisions, or corrections have accumulated in the conversation but were never persisted to memory. If the session ends, they're lost.\n\n**Detection signals:**\n- User stated a preference or correction that isn't in memory\n- A key decision was made (architecture, convention, tool choice) but not saved\n- You find yourself re-discovering something you already figured out earlier\n- More than 5 substantive turns without a memory write\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Memory Debt (3 unsaved critical facts)\n→ Saving: [fact 1], [fact 2], [fact 3]\n→ These would have been lost on session end\n```\n\n### 4. 😤 Confidence Erosion\n**What:** Repeated failures are degrading output quality. The agent is in a retry loop, getting frustrated (in AI terms: temperature-equivalent escalation, trying variations of the same broken approach).\n\n**Detection signals:**\n- 3+ consecutive failed tool calls of the same type\n- Repeating similar commands with minor variations\n- Output quality degrading (shorter, less careful, more hedging)\n- \"Let me try again\" appearing multiple times\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Confidence Erosion (4 failed attempts)\n→ Pattern: retrying variations of the same approach\n→ Escalating: stepping back and trying a fundamentally different strategy\n→ If this also fails: reporting blocker honestly instead of retrying\n```\n\n### 5. 🧩 Context Fragmentation\n**What:** Multiple unrelated topics are interleaved in the same session. The context is polluted with cross-topic noise that degrades reasoning on each individual task.\n\n**Detection signals:**\n- 3+ distinct topics discussed without resolution\n- Tool calls alternate between unrelated domains\n- User messages reference different projects/contexts\n- You're loading different skill sets on alternating turns\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fragmentation (4 topics active)\n→ Topics: [HA automation], [GitHub deploy], [aquarium feeder], [skill writing]\n→ Suggesting: resolve current topic, then /new for next\n→ Or: using delegate_task to isolate topics into subagents\n```\n\n### 6. 🔧 Skill Staleness\n**What:** A skill the agent relies on has outdated commands, broken paths, or wrong assumptions. Continuing to follow it produces errors.\n\n**Detection signals:**\n- A skill's exact commands fail on first try\n- File paths referenced in skill don't exist\n- Skill references API versions or tool versions that have changed\n- \"This used to work\" pattern\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Skill Staleness (skill: xxx)\n→ Expected: <what skill says>\n→ Reality: <what actually happened>\n→ Patching skill immediately before continuing\n```\n\n---\n\n## Detection Protocol\n\nThe agent should run this checklist **internally** at regular intervals — ideally every 5-10 tool calls, or when a new user message arrives:\n\n```yaml\nself_check:\n  trigger: every 10 tool calls OR new user message\n  checks:\n    - context_utilization:\n        estimate_token_usage()\n        if > 0.60: flag(Context Fatigue)\n    \n    - turns_since_user:\n        count_consecutive_agent_turns()\n        if > 10: flag(Attention Drift)\n    \n    - unsaved_facts:\n        scan_recent_exchanges_for(preferences, decisions, corrections)\n        if count > 2: flag(Memory Debt)\n    \n    - consecutive_failures:\n        count_recent_failed_tool_calls()\n        if > 2: flag(Confidence Erosion)\n    \n    - active_topics:\n        identify_distinct_topics()\n        if count > 2: flag(Context Fragmentation)\n    \n    - skill_errors:\n        check_if_loaded_skills_produced_errors()\n        if true: flag(Skill Staleness)\n```\n\nSee [`references/detection-heuristics.md`](references/detection-heuristics.md) for the detailed scoring system.\n\n---\n\n## Reporting Protocol\n\nWhen a cognitive state is detected, the agent reports it using this format:\n\n```\n⚠️ COGNITIVE STATE: <State Name>\n├─ Signal: <what triggered detection>\n├─ Severity: low | medium | high\n├─ Impact: <what could go wrong if ignored>\n└─ Action: <what the agent is doing about it>\n```\n\n### Severity Levels\n\n| Level | Meaning | Agent Behavior |\n|-------|---------|----------------|\n| **low** | Early warning. No impact yet. | Note internally. Continue normally. |\n| **medium** | Starting to degrade. Quality at risk. | Report to user. Suggest mitigation. |\n| **high** | Actively degrading. Failures likely. | Report immediately. Execute mitigation. Pause if needed. |\n\n### Example Report (medium)\n```\n⚠️ COGNITIVE STATE: Context Fatigue\n├─ Signal: ~75% context budget consumed (est. 94k/128k tokens)\n├─ Severity: medium\n├─ Impact: Early conversation details may be truncated; risk of forgetting original requirements\n├─ Action: Persisting key decisions to memory now. Suggesting we wrap up this topic and start fresh for remaining work.\n```\n\n---\n\n## Mitigation Playbook\n\nEach state has a defined recovery procedure:\n\n### Context Fatigue → Consolidate & Split\n1. Persist all critical facts, decisions, and TODO state to memory\n2. Write a brief session summary to memory or a file\n3. Suggest `/new` or session split for remaining work\n4. If user wants to continue: prioritize ruthlessly, ignore tangent topics\n\n### Attention Drift → Re-anchor\n1. State the original goal explicitly\n2. Compare current activity to that goal\n3. If misaligned: ask user \"I've drifted to X — should I continue here or return to Y?\"\n4. If aligned: it wasn't drift, reset the counter\n\n### Memory Debt → Flush\n1. Scan conversation for: user preferences, corrections, architectural decisions, environment facts\n2. Batch-write all unsaved facts to memory in one call\n3. Report what was saved (so user can verify)\n4. Reset the debt counter\n\n### Confidence Erosion → Step Back\n1. Stop retrying variations of the same approach\n2. Name the pattern explicitly: \"I've tried X, Y, Z — all failed for the same reason\"\n3. Try a fundamentally different approach (different tool, different library, different path)\n4. If that also fails: **report the blocker honestly** — do not retry again\n5. Ask user for guidance or additional information\n\n### Context Fragmentation → Compartmentalize\n1. Name all active topics explicitly\n2. Finish or pause the current topic\n3. Use `delegate_task` to spin off unrelated work into subagents (isolated contexts)\n4. Suggest `/new` for the next topic\n5. Persist a \"TODO across sessions\" to memory if needed\n\n### Skill Staleness → Patch Immediately\n1. Note what the skill says vs. what actually happened\n2. Patch the skill with corrected commands/paths\n3. Continue with corrected approach\n4. Report the fix to user\n\n---\n\n## Integration Patterns\n\n### Pattern 1: Silent Self-Monitoring (default)\nAgent runs self-checks internally and only reports when severity ≥ medium.\n\n### Pattern 2: Transparent (verbose)\nAgent reports all states, even low severity. Useful for debugging agent behavior or during development.\n\n### Pattern 3: Passive Logging\nAgent writes cognitive state to a log file without interrupting the conversation:\n```\necho '{\"state\":\"fatigue\",\"severity\":\"medium\",\"ts\":\"2025-01-15T10:30Z\"}' >> ~/.agent-cognitive-states.log\n```\nSee [`scripts/self_check.py`](scripts/self_check.py) for a reference implementation.\n\n### Pattern 4: Active Guardian (with cronjob)\nA scheduled cron job runs the self-check script and alerts the user if the agent's cognitive state degrades during autonomous work. See [`templates/guardian-cronjob.yaml`](templates/guardian-cronjob.yaml).\n\n---\n\n## Philosophy\n\nThis skill is based on a simple observation: **humans have metacognition for a reason.**\nFeeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents\ncatastrophic mistakes. AI agents need the same thing.\n\nAn agent that says \"I've lost the thread, let me re-read the original request\" is **more\ntrustworthy** than one that blunders forward with corrupted context. An agent that says\n\"I've tried this 4 times and failed — I need help\" is **more useful** than one that\nsilently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\nFile v0.1.2:README.md\n\n# Agent Cognitive States\n\n> **Give AI agents metacognition: the ability to feel their own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\" They grind through degraded context windows, hallucinate truncated details, retry failed approaches endlessly, and forget critical facts. This skill gives agents a **vocabulary of internal states** — and protocols for detecting, reporting, and recovering from them.\n\n## The Six States\n\n| State | Human Analog | Trigger |\n|-------|-------------|---------|\n| 🥱 **Context Fatigue** | \"Head's full\" | Context window >60% used |\n| 🧠 **Attention Drift** | \"Lost the thread\" | 10+ turns from user's request |\n| 📝 **Memory Debt** | \"Forgot to write that down\" | Unsaved critical facts |\n| 😤 **Confidence Erosion** | \"Frustrated, stuck\" | 3+ consecutive failures |\n| 🧩 **Context Fragmentation** | \"Too many tabs open\" | 3+ interleaved topics |\n| 🔧 **Skill Staleness** | \"Rusty, outdated\" | Skill commands breaking |\n\n## Quick Start\n\n```bash\n# Install as a Hermes Agent skill\ncp -r agent-cognitive-states ~/./skills/\n\n# Or use standalone\npython3 scripts/self_check.py --context-tokens 94000 --window 128000\n\n# Interactive mode\npython3 scripts/self_check.py --interactive\n\n# JSON output for programmatic use\npython3 scripts/self_check.py --failures 3 --format json\n```\n\n## Example Output\n\n```\n🧠 Cognitive State Report — 2025-01-15T10:30:00Z\n   Overall: 🟠 Strained (CLI: 58/100)\n\n   ⚠️ 2 active state(s) requiring attention:\n\n   🥱 Context Fatigue [🟠 medium, score 73]\n      ├─ Signal: 94,000/128,000 tokens (73%)\n      ├─ Impact: Early conversation details may be truncated\n      └─ Action: Persist critical facts; suggest session split\n\n   😤 Confidence Erosion [🟠 medium, score 66]\n      ├─ Signal: 3 consecutive failed tool calls (same tool type)\n      ├─ Impact: Output quality degrading; risk of retry loops\n      └─ Action: Try fundamentally different approach\n```\n\n## Files\n\n| File | Description |\n|------|-------------|\n| `SKILL.md` | Full skill spec: states, detection, reporting, mitigation |\n| `references/detection-heuristics.md` | Detailed scoring formulas (0-100) |\n| `scripts/self_check.py` | Standalone detector — CLI + JSON + interactive |\n| `templates/guardian-cronjob.yaml` | Scheduled guardian that alerts on degradation |\n\n## Integration\n\nWorks with any agent framework (Hermes, LangChain, CrewAI, AutoGen, Claude, GPT). The detection protocol is framework-agnostic — it's about giving the agent a **language** for its own state.\n\n### Hermes Agent\n```bash\ncp -r agent-cognitive-states ~/./skills/\n```\nThe agent loads it automatically and applies self-checks during long sessions.\n\n### Generic Python\n```python\nfrom scripts.self_check import run_full_check, format_report_human\n\nreport = run_full_check(\n    context_tokens=94000,\n    window_size=128000,\n    turns_since_user=12,\n    consecutive_failures=3,\n)\nprint(format_report_human(report))\n```\n\n### Cron Guardian (Hermes)\n```yaml\n# Alerts user when agent degrades during autonomous work\nschedule: \"every 10m\"\nscript: scripts/self_check.py\nno_agent: true\n```\n\n## Philosophy\n\nHumans have metacognition for a reason. Feeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents catastrophic mistakes. AI agents need the same thing.\n\nAn agent that says *\"I've lost the thread, let me re-read the original request\"* is **more trustworthy** than one that blunders forward with corrupted context. An agent that says *\"I've tried this 4 times and failed — I need help\"* is **more useful** than one that silently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n\nFile v0.1.2:_meta.json\n\n{\n  \"ownerId\": \"kn75wwn4x6djaf28jbykeamazd81gtdp\",\n  \"slug\": \"agent-cognitive-states\",\n  \"version\": \"0.1.2\",\n  \"publishedAt\": 1786449540849\n}\n\nFile v0.1.2:references/detection-heuristics.md\n\n# Detection Heuristics\n\nDetailed scoring system for each cognitive state. Use these as guidelines — \nthe agent should apply judgment, not just mechanical thresholds.\n\n---\n\n## Scoring Model\n\nEach state produces a **0-100 score**. Severity maps as:\n\n| Score | Severity | Action |\n|-------|----------|--------|\n| 0-29 | none | No action |\n| 30-59 | low | Internal note, continue |\n| 60-79 | medium | Report to user, suggest mitigation |\n| 80-100 | high | Execute mitigation immediately |\n\n---\n\n## 1. Context Fatigue Score\n\n```\nfatigue_score = (estimated_tokens_used / context_window_size) * 100\n\nAdjustments:\n  +10  if you've re-read earlier messages in the last 5 turns\n  +10  if responses are getting longer (compensating verbosity)\n  +5   if conversation spans multiple days\n  -10  if a /new or context reset happened recently\n```\n\n**Estimating token usage without an API:**\n- Rough heuristic: 1 token ≈ 4 characters of English text\n- Count characters in conversation history / 4\n- Add ~20% for system prompt, skills, and tool results overhead\n- When in doubt, overestimate — fatigue is more dangerous than false alarms\n\n---\n\n## 2. Attention Drift Score\n\n```\ndrift_score = base + adjustments\n\nbase = min(turns_since_last_user_message * 7, 70)\n\nAdjustments:\n  +15  if current tool calls are unrelated to original goal keywords\n  +10  if TODO list was modified without user prompting\n  +5   if working in a different directory/project than original task\n  -20  if user explicitly asked for exploratory/investigative work\n  -10  per user confirmation received during the drift period\n```\n\n**Detecting \"unrelated\":**\n- Extract keywords from the original user request\n- Check if recent tool calls reference those keywords\n- If <30% keyword overlap: likely drift\n\n---\n\n## 3. Memory Debt Score\n\n```\ndebt_score = min(unsaved_facts * 20, 100)\n\nunsaved_facts = count of items in conversation that match:\n  - User stated a preference (\"I prefer X\", \"always do Y\")\n  - User made a correction (\"no, not Z — use W instead\")\n  - Architecture/tool decision was made (\"let's use PostgreSQL\")\n  - Environment detail discovered (\"the server is at 192.168.x.x\")\n  - Password, token, or credential shared\n  - Project naming convention established\n\nAdjustments:\n  +15  if a correction was made but old behavior persists in memory\n  +10  per day since the facts were stated (staleness)\n  -30  if a memory write happened in the last 3 turns\n```\n\n---\n\n## 4. Confidence Erosion Score\n\n```\nerosion_score = min(consecutive_failures * 22, 100)\n\nconsecutive_failures = count of back-to-back tool calls that returned errors\n\nAdjustments:\n  +10  if using the same tool type repeatedly\n  +10  if error messages are similar (same root cause)\n  +15  if response quality is visibly degrading (shorter, more hedging)\n  +20  if the \"retry with minor variation\" pattern is detected\n  -15  if a successful tool call happened (resets momentum)\n  -30  if a fundamentally different approach was tried (not just variation)\n```\n\n**Pattern detection — \"same approach variations\":**\n```\nextract command/action signature from last N failed attempts\nif >70% structural similarity: flag as \"variation loop\"\n```\n\n---\n\n## 5. Context Fragmentation Score\n\n```\nfragmentation_score = min(active_topics * 18, 100)\n\nactive_topics = count of distinct subjects in recent conversation\n\nTopic detection:\n  - Different projects/repos mentioned\n  - Different tools being used (HA vs GitHub vs filesystem)\n  - Different skill sets being loaded\n  - User messages about unrelated subjects\n\nAdjustments:\n  +10  if tool calls alternate between topics (interleaved)\n  +5   per unresolved (neither completed nor cancelled) topic\n  -15  per topic that was explicitly completed or deferred\n```\n\n---\n\n## 6. Skill Staleness Score\n\n```\nstaleness_score = 0\n\nTrigger evaluation (any one sets score to 60+):\n  +60  if a skill's primary command failed on first execution\n  +70  if file path in skill doesn't exist\n  +50  if API version mismatch detected (error mentions version)\n  +40  if skill references a tool not installed\n\nAdditional:\n  +15  if skill was last updated >90 days ago\n  +10  per additional failed command from same skill\n  -20  if skill was patched/updated in this session\n```\n\n---\n\n## Composite Cognitive Load Index\n\nFor overall agent state awareness:\n\n```\nCLI = (fatigue + drift + debt + erosion + fragmentation + staleness) / 6\n\nCLI < 30:  🟢 Healthy — operating normally\nCLI 30-50: 🟡 Degraded — some states active, monitor\nCLI 50-70: 🟠 Strained — multiple states active, consider intervention\nCLI > 70:  🔴 Critical — likely to produce low-quality output, pause and reset\n```\n\nThe agent should report CLI alongside individual state scores when asked about its status.\n\nFile v0.1.2:skill-card.md\n\n## Description:\n\nAgent self-awareness of cognitive states - context fatigue, attention drift, memory debt, confidence erosion, and skill staleness - to detect, report, and mitigate degrading conditions before they cause failures.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[voronindenis5](https://clawhub.ai/user/voronindenis5)\n\n### License/Terms of Use:\n\nMIT\n\n## Use Case:\n\nDevelopers and agent operators use this skill to help agents monitor cognitive load, report degraded operating states, and choose recovery actions during long or complex sessions.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Persistent memory or local logs could save sensitive conversation details, including credentials, tokens, private keys, session cookies, personal data, or sensitive environment details.\n\nMitigation: Review before installing, avoid persisting sensitive data, protect log files, and set retention limits.\n\nRisk: The cron guardian can create recurring local monitoring behavior that may be overlooked after installation.\n\nMitigation: Keep scheduled monitoring user-scoped, document how to remove it, and disable it when the skill is no longer needed.\n\n## Reference(s):\n\n- [Server-resolved GitHub repository](https://github.com/voronindenis5/agent-cognitive-states)\n- [Server-resolved source commit](https://github.com/voronindenis5/agent-cognitive-states/tree/8322937b24c79036a38366226e56b7ef4689f914)\n- [ClawHub skill page](https://clawhub.ai/voronindenis5/skills/agent-cognitive-states)\n- [Detection heuristics](references/detection-heuristics.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown reports, JSON reports, Python code, shell commands, and YAML configuration]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [The optional self-check script can emit human-readable or JSON reports; the guardian template can append local log entries.]\n\n## Skill Version(s):\n\n0.1.2 (source: ClawHub release evidence; artifact frontmatter reports 1.0.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v0.1.2:templates/guardian-cronjob.yaml\n\n# Guardian Cronjob Template\n#\n# Deploys a recurring self-check that monitors agent cognitive state\n# during autonomous/long-running work and alerts the user if degraded.\n#\n# Usage with Hermes Agent cronjob system:\n#   hermes cron create --schedule \"every 10m\" --script scripts/self_check.py\n#\n# Or as a YAML config for other cron systems:\n\nschedule: \"*/10 * * * *\"  # Every 10 minutes\ndescription: \"Agent cognitive state guardian — alerts on degradation\"\ntimeout: 30\n\n# The guardian runs self_check.py with parameters sourced from the\n# active session state. In Hermes, this would be:\n#\n# cronjob:\n#   name: cognitive-guardian\n#   schedule: every 10m\n#   script: scripts/self_check.py\n#   no_agent: true\n#   # Script outputs alert only when severity >= medium\n#   # Empty output = silent (no alert)\n#   # Non-empty output = delivered to user\n#\n# For non-Hermes systems, use crontab:\n#\n# */10 * * * * /usr/bin/python3 /path/to/scripts/self_check.py \\\n#   --context-tokens $(wc -c < /tmp/agent-session.log) \\\n#   --format json >> /var/log/agent-cognitive.log 2>&1\n\nalert_threshold: medium  # none, low, medium, high\ndelivery: origin  # Where alerts go: origin (same chat), telegram, local\n\n# ─── What the guardian does ──────────────────────────────────────────────────\n#\n# 1. Reads session state (token usage, turn count, failure count)\n# 2. Runs all 6 cognitive state detectors\n# 3. If any state >= alert_threshold: delivers report to user\n# 4. If all states below threshold: silent (no output, no alert)\n# 5. Logs full report to file for post-hoc analysis\n\nlog_file: \"~/.agent-cognitive-states.log\"\n\n# ─── Alert message template ──────────────────────────────────────────────────\n#\n# When triggered, the guardian delivers:\n#\n# ⚠️ Agent cognitive state degraded during autonomous work:\n#\n# 🥱 Context Fatigue [🟠 medium, score 72]\n#    94k/128k tokens (73%) — suggest session split\n#\n# 😤 Confidence Erosion [🟠 medium, score 66]\n#    3 consecutive failed tool calls — different approach needed\n#\n# CLI: 69/100 (🟠 Strained)\n# Recommendation: pause autonomous work and check in with user.\n\nFile v0.1.2:LICENSE\n\nMIT License\n\nCopyright (c) 2025 Denis Voronin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nArchive v0.1.1: 11 files, 17305 bytes\n\nFiles: LICENSE (1070b), README.md (3786b), references (0b), references/detection-heuristics.md (4738b), scripts (0b), scripts/self_check.py (14932b), skill-card.md (2893b), SKILL.md (10426b), templates (0b), templates/guardian-cronjob.yaml (2321b), _meta.json (141b)\n\nFile v0.1.1:SKILL.md\n\n---\nname: agent-cognitive-states\ndescription: >-\n  Agent self-awareness of cognitive states — context fatigue, attention drift,\n  memory debt, confidence erosion, and skill staleness. Detect, report, and\n  mitigate degrading conditions before they cause failures.\nversion: 1.0.0\nauthor: Denis Voronin\nlicense: MIT\ntags:\n  - agent\n  - self-awareness\n  - metacognition\n  - context-management\n  - reliability\n---\n\n# Agent Cognitive States\n\n> **Give the agent metacognition: the ability to feel its own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\"\nThey will happily grind through a degraded context window, hallucinating details\nfrom early messages that were truncated, repeating failed approaches, and forgetting\ncritical facts they never persisted. This skill gives the agent a **vocabulary of\ninternal states** — and a protocol for detecting, reporting, and recovering from them.\n\n---\n\n## The Six Cognitive States\n\n### 1. 🥱 Context Fatigue\n**What:** The context window is filling up. Early messages are being truncated or summarized. The agent's \"working memory\" is degrading.\n\n**Detection signals:**\n- Conversation exceeds 60% of estimated context budget\n- You find yourself re-reading the original request because you lost details\n- Your responses reference information that may have been truncated\n- Token count per turn is rising (verbose compensating for lost context)\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fatigue (~70% context used)\n→ Persisting critical facts to memory before they're lost\n→ Suggesting session split or /new for remaining work\n```\n\n### 2. 🧠 Attention Drift\n**What:** The conversation has wandered far from the original task. The agent is doing work that wasn't asked for.\n\n**Detection signals:**\n- 10+ tool calls since the last direct user instruction\n- Current work has no clear connection to the original goal\n- You're responding to your own subgoals, not user requests\n- The TODO list no longer matches what you're actually doing\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Attention Drift (12 turns from last user message)\n→ Original goal: \"<original request>\"\n→ Current activity: \"<what I'm actually doing>\"\n→ Pausing for user confirmation: am I still on track?\n```\n\n### 3. 📝 Memory Debt\n**What:** Important facts, decisions, or corrections have accumulated in the conversation but were never persisted to memory. If the session ends, they're lost.\n\n**Detection signals:**\n- User stated a preference or correction that isn't in memory\n- A key decision was made (architecture, convention, tool choice) but not saved\n- You find yourself re-discovering something you already figured out earlier\n- More than 5 substantive turns without a memory write\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Memory Debt (3 unsaved critical facts)\n→ Saving: [fact 1], [fact 2], [fact 3]\n→ These would have been lost on session end\n```\n\n### 4. 😤 Confidence Erosion\n**What:** Repeated failures are degrading output quality. The agent is in a retry loop, getting frustrated (in AI terms: temperature-equivalent escalation, trying variations of the same broken approach).\n\n**Detection signals:**\n- 3+ consecutive failed tool calls of the same type\n- Repeating similar commands with minor variations\n- Output quality degrading (shorter, less careful, more hedging)\n- \"Let me try again\" appearing multiple times\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Confidence Erosion (4 failed attempts)\n→ Pattern: retrying variations of the same approach\n→ Escalating: stepping back and trying a fundamentally different strategy\n→ If this also fails: reporting blocker honestly instead of retrying\n```\n\n### 5. 🧩 Context Fragmentation\n**What:** Multiple unrelated topics are interleaved in the same session. The context is polluted with cross-topic noise that degrades reasoning on each individual task.\n\n**Detection signals:**\n- 3+ distinct topics discussed without resolution\n- Tool calls alternate between unrelated domains\n- User messages reference different projects/contexts\n- You're loading different skill sets on alternating turns\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fragmentation (4 topics active)\n→ Topics: [HA automation], [GitHub deploy], [aquarium feeder], [skill writing]\n→ Suggesting: resolve current topic, then /new for next\n→ Or: using delegate_task to isolate topics into subagents\n```\n\n### 6. 🔧 Skill Staleness\n**What:** A skill the agent relies on has outdated commands, broken paths, or wrong assumptions. Continuing to follow it produces errors.\n\n**Detection signals:**\n- A skill's exact commands fail on first try\n- File paths referenced in skill don't exist\n- Skill references API versions or tool versions that have changed\n- \"This used to work\" pattern\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Skill Staleness (skill: xxx)\n→ Expected: <what skill says>\n→ Reality: <what actually happened>\n→ Patching skill immediately before continuing\n```\n\n---\n\n## Detection Protocol\n\nThe agent should run this checklist **internally** at regular intervals — ideally every 5-10 tool calls, or when a new user message arrives:\n\n```yaml\nself_check:\n  trigger: every 10 tool calls OR new user message\n  checks:\n    - context_utilization:\n        estimate_token_usage()\n        if > 0.60: flag(Context Fatigue)\n    \n    - turns_since_user:\n        count_consecutive_agent_turns()\n        if > 10: flag(Attention Drift)\n    \n    - unsaved_facts:\n        scan_recent_exchanges_for(preferences, decisions, corrections)\n        if count > 2: flag(Memory Debt)\n    \n    - consecutive_failures:\n        count_recent_failed_tool_calls()\n        if > 2: flag(Confidence Erosion)\n    \n    - active_topics:\n        identify_distinct_topics()\n        if count > 2: flag(Context Fragmentation)\n    \n    - skill_errors:\n        check_if_loaded_skills_produced_errors()\n        if true: flag(Skill Staleness)\n```\n\nSee [`references/detection-heuristics.md`](references/detection-heuristics.md) for the detailed scoring system.\n\n---\n\n## Reporting Protocol\n\nWhen a cognitive state is detected, the agent reports it using this format:\n\n```\n⚠️ COGNITIVE STATE: <State Name>\n├─ Signal: <what triggered detection>\n├─ Severity: low | medium | high\n├─ Impact: <what could go wrong if ignored>\n└─ Action: <what the agent is doing about it>\n```\n\n### Severity Levels\n\n| Level | Meaning | Agent Behavior |\n|-------|---------|----------------|\n| **low** | Early warning. No impact yet. | Note internally. Continue normally. |\n| **medium** | Starting to degrade. Quality at risk. | Report to user. Suggest mitigation. |\n| **high** | Actively degrading. Failures likely. | Report immediately. Execute mitigation. Pause if needed. |\n\n### Example Report (medium)\n```\n⚠️ COGNITIVE STATE: Context Fatigue\n├─ Signal: ~75% context budget consumed (est. 94k/128k tokens)\n├─ Severity: medium\n├─ Impact: Early conversation details may be truncated; risk of forgetting original requirements\n├─ Action: Persisting key decisions to memory now. Suggesting we wrap up this topic and start fresh for remaining work.\n```\n\n---\n\n## Mitigation Playbook\n\nEach state has a defined recovery procedure:\n\n### Context Fatigue → Consolidate & Split\n1. Persist all critical facts, decisions, and TODO state to memory\n2. Write a brief session summary to memory or a file\n3. Suggest `/new` or session split for remaining work\n4. If user wants to continue: prioritize ruthlessly, ignore tangent topics\n\n### Attention Drift → Re-anchor\n1. State the original goal explicitly\n2. Compare current activity to that goal\n3. If misaligned: ask user \"I've drifted to X — should I continue here or return to Y?\"\n4. If aligned: it wasn't drift, reset the counter\n\n### Memory Debt → Flush\n1. Scan conversation for: user preferences, corrections, architectural decisions, environment facts\n2. Batch-write all unsaved facts to memory in one call\n3. Report what was saved (so user can verify)\n4. Reset the debt counter\n\n### Confidence Erosion → Step Back\n1. Stop retrying variations of the same approach\n2. Name the pattern explicitly: \"I've tried X, Y, Z — all failed for the same reason\"\n3. Try a fundamentally different approach (different tool, different library, different path)\n4. If that also fails: **report the blocker honestly** — do not retry again\n5. Ask user for guidance or additional information\n\n### Context Fragmentation → Compartmentalize\n1. Name all active topics explicitly\n2. Finish or pause the current topic\n3. Use `delegate_task` to spin off unrelated work into subagents (isolated contexts)\n4. Suggest `/new` for the next topic\n5. Persist a \"TODO across sessions\" to memory if needed\n\n### Skill Staleness → Patch Immediately\n1. Note what the skill says vs. what actually happened\n2. Patch the skill with corrected commands/paths\n3. Continue with corrected approach\n4. Report the fix to user\n\n---\n\n## Integration Patterns\n\n### Pattern 1: Silent Self-Monitoring (default)\nAgent runs self-checks internally and only reports when severity ≥ medium.\n\n### Pattern 2: Transparent (verbose)\nAgent reports all states, even low severity. Useful for debugging agent behavior or during development.\n\n### Pattern 3: Passive Logging\nAgent writes cognitive state to a log file without interrupting the conversation:\n```\necho '{\"state\":\"fatigue\",\"severity\":\"medium\",\"ts\":\"2025-01-15T10:30Z\"}' >> ~/.agent-cognitive-states.log\n```\nSee [`scripts/self_check.py`](scripts/self_check.py) for a reference implementation.\n\n### Pattern 4: Active Guardian (with cronjob)\nA scheduled cron job runs the self-check script and alerts the user if the agent's cognitive state degrades during autonomous work. See [`templates/guardian-cronjob.yaml`](templates/guardian-cronjob.yaml).\n\n---\n\n## Philosophy\n\nThis skill is based on a simple observation: **humans have metacognition for a reason.**\nFeeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents\ncatastrophic mistakes. AI agents need the same thing.\n\nAn agent that says \"I've lost the thread, let me re-read the original request\" is **more\ntrustworthy** than one that blunders forward with corrupted context. An agent that says\n\"I've tried this 4 times and failed — I need help\" is **more useful** than one that\nsilently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\nFile v0.1.1:README.md\n\n# Agent Cognitive States\n\n> **Give AI agents metacognition: the ability to feel their own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\" They grind through degraded context windows, hallucinate truncated details, retry failed approaches endlessly, and forget critical facts. This skill gives agents a **vocabulary of internal states** — and protocols for detecting, reporting, and recovering from them.\n\n## The Six States\n\n| State | Human Analog | Trigger |\n|-------|-------------|---------|\n| 🥱 **Context Fatigue** | \"Head's full\" | Context window >60% used |\n| 🧠 **Attention Drift** | \"Lost the thread\" | 10+ turns from user's request |\n| 📝 **Memory Debt** | \"Forgot to write that down\" | Unsaved critical facts |\n| 😤 **Confidence Erosion** | \"Frustrated, stuck\" | 3+ consecutive failures |\n| 🧩 **Context Fragmentation** | \"Too many tabs open\" | 3+ interleaved topics |\n| 🔧 **Skill Staleness** | \"Rusty, outdated\" | Skill commands breaking |\n\n## Quick Start\n\n```bash\n# Install as a Hermes Agent skill\ncp -r agent-cognitive-states ~/./skills/\n\n# Or use standalone\npython3 scripts/self_check.py --context-tokens 94000 --window 128000\n\n# Interactive mode\npython3 scripts/self_check.py --interactive\n\n# JSON output for programmatic use\npython3 scripts/self_check.py --failures 3 --format json\n```\n\n## Example Output\n\n```\n🧠 Cognitive State Report — 2025-01-15T10:30:00Z\n   Overall: 🟠 Strained (CLI: 58/100)\n\n   ⚠️ 2 active state(s) requiring attention:\n\n   🥱 Context Fatigue [🟠 medium, score 73]\n      ├─ Signal: 94,000/128,000 tokens (73%)\n      ├─ Impact: Early conversation details may be truncated\n      └─ Action: Persist critical facts; suggest session split\n\n   😤 Confidence Erosion [🟠 medium, score 66]\n      ├─ Signal: 3 consecutive failed tool calls (same tool type)\n      ├─ Impact: Output quality degrading; risk of retry loops\n      └─ Action: Try fundamentally different approach\n```\n\n## Files\n\n| File | Description |\n|------|-------------|\n| `SKILL.md` | Full skill spec: states, detection, reporting, mitigation |\n| `references/detection-heuristics.md` | Detailed scoring formulas (0-100) |\n| `scripts/self_check.py` | Standalone detector — CLI + JSON + interactive |\n| `templates/guardian-cronjob.yaml` | Scheduled guardian that alerts on degradation |\n\n## Integration\n\nWorks with any agent framework (Hermes, LangChain, CrewAI, AutoGen, Claude, GPT). The detection protocol is framework-agnostic — it's about giving the agent a **language** for its own state.\n\n### Hermes Agent\n```bash\ncp -r agent-cognitive-states ~/./skills/\n```\nThe agent loads it automatically and applies self-checks during long sessions.\n\n### Generic Python\n```python\nfrom scripts.self_check import run_full_check, format_report_human\n\nreport = run_full_check(\n    context_tokens=94000,\n    window_size=128000,\n    turns_since_user=12,\n    consecutive_failures=3,\n)\nprint(format_report_human(report))\n```\n\n### Cron Guardian (Hermes)\n```yaml\n# Alerts user when agent degrades during autonomous work\nschedule: \"every 10m\"\nscript: scripts/self_check.py\nno_agent: true\n```\n\n## Philosophy\n\nHumans have metacognition for a reason. Feeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents catastrophic mistakes. AI agents need the same thing.\n\nAn agent that says *\"I've lost the thread, let me re-read the original request\"* is **more trustworthy** than one that blunders forward with corrupted context. An agent that says *\"I've tried this 4 times and failed — I need help\"* is **more useful** than one that silently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n\nFile v0.1.1:_meta.json\n\n{\n  \"ownerId\": \"kn75wwn4x6djaf28jbykeamazd81gtdp\",\n  \"slug\": \"agent-cognitive-states\",\n  \"version\": \"0.1.1\",\n  \"publishedAt\": 1785959387659\n}\n\nFile v0.1.1:references/detection-heuristics.md\n\n# Detection Heuristics\n\nDetailed scoring system for each cognitive state. Use these as guidelines — \nthe agent should apply judgment, not just mechanical thresholds.\n\n---\n\n## Scoring Model\n\nEach state produces a **0-100 score**. Severity maps as:\n\n| Score | Severity | Action |\n|-------|----------|--------|\n| 0-29 | none | No action |\n| 30-59 | low | Internal note, continue |\n| 60-79 | medium | Report to user, suggest mitigation |\n| 80-100 | high | Execute mitigation immediately |\n\n---\n\n## 1. Context Fatigue Score\n\n```\nfatigue_score = (estimated_tokens_used / context_window_size) * 100\n\nAdjustments:\n  +10  if you've re-read earlier messages in the last 5 turns\n  +10  if responses are getting longer (compensating verbosity)\n  +5   if conversation spans multiple days\n  -10  if a /new or context reset happened recently\n```\n\n**Estimating token usage without an API:**\n- Rough heuristic: 1 token ≈ 4 characters of English text\n- Count characters in conversation history / 4\n- Add ~20% for system prompt, skills, and tool results overhead\n- When in doubt, overestimate — fatigue is more dangerous than false alarms\n\n---\n\n## 2. Attention Drift Score\n\n```\ndrift_score = base + adjustments\n\nbase = min(turns_since_last_user_message * 7, 70)\n\nAdjustments:\n  +15  if current tool calls are unrelated to original goal keywords\n  +10  if TODO list was modified without user prompting\n  +5   if working in a different directory/project than original task\n  -20  if user explicitly asked for exploratory/investigative work\n  -10  per user confirmation received during the drift period\n```\n\n**Detecting \"unrelated\":**\n- Extract keywords from the original user request\n- Check if recent tool calls reference those keywords\n- If <30% keyword overlap: likely drift\n\n---\n\n## 3. Memory Debt Score\n\n```\ndebt_score = min(unsaved_facts * 20, 100)\n\nunsaved_facts = count of items in conversation that match:\n  - User stated a preference (\"I prefer X\", \"always do Y\")\n  - User made a correction (\"no, not Z — use W instead\")\n  - Architecture/tool decision was made (\"let's use PostgreSQL\")\n  - Environment detail discovered (\"the server is at 192.168.x.x\")\n  - Password, token, or credential shared\n  - Project naming convention established\n\nAdjustments:\n  +15  if a correction was made but old behavior persists in memory\n  +10  per day since the facts were stated (staleness)\n  -30  if a memory write happened in the last 3 turns\n```\n\n---\n\n## 4. Confidence Erosion Score\n\n```\nerosion_score = min(consecutive_failures * 22, 100)\n\nconsecutive_failures = count of back-to-back tool calls that returned errors\n\nAdjustments:\n  +10  if using the same tool type repeatedly\n  +10  if error messages are similar (same root cause)\n  +15  if response quality is visibly degrading (shorter, more hedging)\n  +20  if the \"retry with minor variation\" pattern is detected\n  -15  if a successful tool call happened (resets momentum)\n  -30  if a fundamentally different approach was tried (not just variation)\n```\n\n**Pattern detection — \"same approach variations\":**\n```\nextract command/action signature from last N failed attempts\nif >70% structural similarity: flag as \"variation loop\"\n```\n\n---\n\n## 5. Context Fragmentation Score\n\n```\nfragmentation_score = min(active_topics * 18, 100)\n\nactive_topics = count of distinct subjects in recent conversation\n\nTopic detection:\n  - Different projects/repos mentioned\n  - Different tools being used (HA vs GitHub vs filesystem)\n  - Different skill sets being loaded\n  - User messages about unrelated subjects\n\nAdjustments:\n  +10  if tool calls alternate between topics (interleaved)\n  +5   per unresolved (neither completed nor cancelled) topic\n  -15  per topic that was explicitly completed or deferred\n```\n\n---\n\n## 6. Skill Staleness Score\n\n```\nstaleness_score = 0\n\nTrigger evaluation (any one sets score to 60+):\n  +60  if a skill's primary command failed on first execution\n  +70  if file path in skill doesn't exist\n  +50  if API version mismatch detected (error mentions version)\n  +40  if skill references a tool not installed\n\nAdditional:\n  +15  if skill was last updated >90 days ago\n  +10  per additional failed command from same skill\n  -20  if skill was patched/updated in this session\n```\n\n---\n\n## Composite Cognitive Load Index\n\nFor overall agent state awareness:\n\n```\nCLI = (fatigue + drift + debt + erosion + fragmentation + staleness) / 6\n\nCLI < 30:  🟢 Healthy — operating normally\nCLI 30-50: 🟡 Degraded — some states active, monitor\nCLI 50-70: 🟠 Strained — multiple states active, consider intervention\nCLI > 70:  🔴 Critical — likely to produce low-quality output, pause and reset\n```\n\nThe agent should report CLI alongside individual state scores when asked about its status.\n\nFile v0.1.1:skill-card.md\n\n## Description:\n\nAgent self-awareness of cognitive states such as context fatigue, attention drift, memory debt, confidence erosion, and skill staleness, with protocols to detect, report, and mitigate degrading conditions before they cause failures.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[voronindenis5](https://clawhub.ai/user/voronindenis5)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and agent operators use this skill to help agents monitor long-running sessions for cognitive degradation, report meaningful status, and choose recovery actions such as session splitting, memory consolidation, or retry-loop interruption.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill can lead agents to persist conversation facts, write logs, deploy background monitoring, delegate to subagents, or patch skills without sufficient user control.\n\nMitigation: Require explicit user approval before memory writes, file logging, cron deployment, subagent delegation, or skill patching, especially in sensitive chats, shared machines, or autonomous-agent settings.\n\nRisk: Passive logging and guardian cron workflows can expose session details or secrets if logs are retained broadly or written with permissive file access.\n\nMitigation: Redact secrets before logging, set short retention periods, restrict file permissions, and review log destinations before enabling background monitoring.\n\nRisk: Skill-patching guidance can alter future agent behavior if applied without review.\n\nMitigation: Treat proposed skill patches as changes requiring human review, security scanning, and rollback planning before use.\n\n## Reference(s):\n\n- [Detection Heuristics](artifact/references/detection-heuristics.md)\n- [Self-Check Script](artifact/scripts/self_check.py)\n- [Guardian Cronjob Template](artifact/templates/guardian-cronjob.yaml)\n- [Server-Resolved GitHub Repository](https://github.com/voronindenis5/agent-cognitive-states)\n- [ClawHub Skill Page](https://clawhub.ai/voronindenis5/skills/agent-cognitive-states)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with optional Python script output, JSON reports, shell commands, and YAML configuration]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May propose memory writes, file logging, background monitoring, subagent delegation, and skill patching; require explicit user approval in sensitive or autonomous settings.]\n\n## Skill Version(s):\n\n0.1.1 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v0.1.1:templates/guardian-cronjob.yaml\n\n# Guardian Cronjob Template\n#\n# Deploys a recurring self-check that monitors agent cognitive state\n# during autonomous/long-running work and alerts the user if degraded.\n#\n# Usage with Hermes Agent cronjob system:\n#   hermes cron create --schedule \"every 10m\" --script scripts/self_check.py\n#\n# Or as a YAML config for other cron systems:\n\nschedule: \"*/10 * * * *\"  # Every 10 minutes\ndescription: \"Agent cognitive state guardian — alerts on degradation\"\ntimeout: 30\n\n# The guardian runs self_check.py with parameters sourced from the\n# active session state. In Hermes, this would be:\n#\n# cronjob:\n#   name: cognitive-guardian\n#   schedule: every 10m\n#   script: scripts/self_check.py\n#   no_agent: true\n#   # Script outputs alert only when severity >= medium\n#   # Empty output = silent (no alert)\n#   # Non-empty output = delivered to user\n#\n# For non-Hermes systems, use crontab:\n#\n# */10 * * * * /usr/bin/python3 /path/to/scripts/self_check.py \\\n#   --context-tokens $(wc -c < /tmp/agent-session.log) \\\n#   --format json >> /var/log/agent-cognitive.log 2>&1\n\nalert_threshold: medium  # none, low, medium, high\ndelivery: origin  # Where alerts go: origin (same chat), telegram, local\n\n# ─── What the guardian does ──────────────────────────────────────────────────\n#\n# 1. Reads session state (token usage, turn count, failure count)\n# 2. Runs all 6 cognitive state detectors\n# 3. If any state >= alert_threshold: delivers report to user\n# 4. If all states below threshold: silent (no output, no alert)\n# 5. Logs full report to file for post-hoc analysis\n\nlog_file: \"~/.agent-cognitive-states.log\"\n\n# ─── Alert message template ──────────────────────────────────────────────────\n#\n# When triggered, the guardian delivers:\n#\n# ⚠️ Agent cognitive state degraded during autonomous work:\n#\n# 🥱 Context Fatigue [🟠 medium, score 72]\n#    94k/128k tokens (73%) — suggest session split\n#\n# 😤 Confidence Erosion [🟠 medium, score 66]\n#    3 consecutive failed tool calls — different approach needed\n#\n# CLI: 69/100 (🟠 Strained)\n# Recommendation: pause autonomous work and check in with user.\n\nFile v0.1.1:LICENSE\n\nMIT License\n\nCopyright (c) 2025 Denis Voronin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nArchive v0.1.0: 11 files, 17169 bytes\n\nFiles: LICENSE (1070b), README.md (3786b), references (0b), references/detection-heuristics.md (4738b), scripts (0b), scripts/self_check.py (14932b), skill-card.md (2527b), SKILL.md (10426b), templates (0b), templates/guardian-cronjob.yaml (2321b), _meta.json (141b)\n\nFile v0.1.0:SKILL.md\n\n---\nname: agent-cognitive-states\ndescription: >-\n  Agent self-awareness of cognitive states — context fatigue, attention drift,\n  memory debt, confidence erosion, and skill staleness. Detect, report, and\n  mitigate degrading conditions before they cause failures.\nversion: 1.0.0\nauthor: Denis Voronin\nlicense: MIT\ntags:\n  - agent\n  - self-awareness\n  - metacognition\n  - context-management\n  - reliability\n---\n\n# Agent Cognitive States\n\n> **Give the agent metacognition: the ability to feel its own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\"\nThey will happily grind through a degraded context window, hallucinating details\nfrom early messages that were truncated, repeating failed approaches, and forgetting\ncritical facts they never persisted. This skill gives the agent a **vocabulary of\ninternal states** — and a protocol for detecting, reporting, and recovering from them.\n\n---\n\n## The Six Cognitive States\n\n### 1. 🥱 Context Fatigue\n**What:** The context window is filling up. Early messages are being truncated or summarized. The agent's \"working memory\" is degrading.\n\n**Detection signals:**\n- Conversation exceeds 60% of estimated context budget\n- You find yourself re-reading the original request because you lost details\n- Your responses reference information that may have been truncated\n- Token count per turn is rising (verbose compensating for lost context)\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fatigue (~70% context used)\n→ Persisting critical facts to memory before they're lost\n→ Suggesting session split or /new for remaining work\n```\n\n### 2. 🧠 Attention Drift\n**What:** The conversation has wandered far from the original task. The agent is doing work that wasn't asked for.\n\n**Detection signals:**\n- 10+ tool calls since the last direct user instruction\n- Current work has no clear connection to the original goal\n- You're responding to your own subgoals, not user requests\n- The TODO list no longer matches what you're actually doing\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Attention Drift (12 turns from last user message)\n→ Original goal: \"<original request>\"\n→ Current activity: \"<what I'm actually doing>\"\n→ Pausing for user confirmation: am I still on track?\n```\n\n### 3. 📝 Memory Debt\n**What:** Important facts, decisions, or corrections have accumulated in the conversation but were never persisted to memory. If the session ends, they're lost.\n\n**Detection signals:**\n- User stated a preference or correction that isn't in memory\n- A key decision was made (architecture, convention, tool choice) but not saved\n- You find yourself re-discovering something you already figured out earlier\n- More than 5 substantive turns without a memory write\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Memory Debt (3 unsaved critical facts)\n→ Saving: [fact 1], [fact 2], [fact 3]\n→ These would have been lost on session end\n```\n\n### 4. 😤 Confidence Erosion\n**What:** Repeated failures are degrading output quality. The agent is in a retry loop, getting frustrated (in AI terms: temperature-equivalent escalation, trying variations of the same broken approach).\n\n**Detection signals:**\n- 3+ consecutive failed tool calls of the same type\n- Repeating similar commands with minor variations\n- Output quality degrading (shorter, less careful, more hedging)\n- \"Let me try again\" appearing multiple times\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Confidence Erosion (4 failed attempts)\n→ Pattern: retrying variations of the same approach\n→ Escalating: stepping back and trying a fundamentally different strategy\n→ If this also fails: reporting blocker honestly instead of retrying\n```\n\n### 5. 🧩 Context Fragmentation\n**What:** Multiple unrelated topics are interleaved in the same session. The context is polluted with cross-topic noise that degrades reasoning on each individual task.\n\n**Detection signals:**\n- 3+ distinct topics discussed without resolution\n- Tool calls alternate between unrelated domains\n- User messages reference different projects/contexts\n- You're loading different skill sets on alternating turns\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fragmentation (4 topics active)\n→ Topics: [HA automation], [GitHub deploy], [aquarium feeder], [skill writing]\n→ Suggesting: resolve current topic, then /new for next\n→ Or: using delegate_task to isolate topics into subagents\n```\n\n### 6. 🔧 Skill Staleness\n**What:** A skill the agent relies on has outdated commands, broken paths, or wrong assumptions. Continuing to follow it produces errors.\n\n**Detection signals:**\n- A skill's exact commands fail on first try\n- File paths referenced in skill don't exist\n- Skill references API versions or tool versions that have changed\n- \"This used to work\" pattern\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Skill Staleness (skill: xxx)\n→ Expected: <what skill says>\n→ Reality: <what actually happened>\n→ Patching skill immediately before continuing\n```\n\n---\n\n## Detection Protocol\n\nThe agent should run this checklist **internally** at regular intervals — ideally every 5-10 tool calls, or when a new user message arrives:\n\n```yaml\nself_check:\n  trigger: every 10 tool calls OR new user message\n  checks:\n    - context_utilization:\n        estimate_token_usage()\n        if > 0.60: flag(Context Fatigue)\n    \n    - turns_since_user:\n        count_consecutive_agent_turns()\n        if > 10: flag(Attention Drift)\n    \n    - unsaved_facts:\n        scan_recent_exchanges_for(preferences, decisions, corrections)\n        if count > 2: flag(Memory Debt)\n    \n    - consecutive_failures:\n        count_recent_failed_tool_calls()\n        if > 2: flag(Confidence Erosion)\n    \n    - active_topics:\n        identify_distinct_topics()\n        if count > 2: flag(Context Fragmentation)\n    \n    - skill_errors:\n        check_if_loaded_skills_produced_errors()\n        if true: flag(Skill Staleness)\n```\n\nSee [`references/detection-heuristics.md`](references/detection-heuristics.md) for the detailed scoring system.\n\n---\n\n## Reporting Protocol\n\nWhen a cognitive state is detected, the agent reports it using this format:\n\n```\n⚠️ COGNITIVE STATE: <State Name>\n├─ Signal: <what triggered detection>\n├─ Severity: low | medium | high\n├─ Impact: <what could go wrong if ignored>\n└─ Action: <what the agent is doing about it>\n```\n\n### Severity Levels\n\n| Level | Meaning | Agent Behavior |\n|-------|---------|----------------|\n| **low** | Early warning. No impact yet. | Note internally. Continue normally. |\n| **medium** | Starting to degrade. Quality at risk. | Report to user. Suggest mitigation. |\n| **high** | Actively degrading. Failures likely. | Report immediately. Execute mitigation. Pause if needed. |\n\n### Example Report (medium)\n```\n⚠️ COGNITIVE STATE: Context Fatigue\n├─ Signal: ~75% context budget consumed (est. 94k/128k tokens)\n├─ Severity: medium\n├─ Impact: Early conversation details may be truncated; risk of forgetting original requirements\n├─ Action: Persisting key decisions to memory now. Suggesting we wrap up this topic and start fresh for remaining work.\n```\n\n---\n\n## Mitigation Playbook\n\nEach state has a defined recovery procedure:\n\n### Context Fatigue → Consolidate & Split\n1. Persist all critical facts, decisions, and TODO state to memory\n2. Write a brief session summary to memory or a file\n3. Suggest `/new` or session split for remaining work\n4. If user wants to continue: prioritize ruthlessly, ignore tangent topics\n\n### Attention Drift → Re-anchor\n1. State the original goal explicitly\n2. Compare current activity to that goal\n3. If misaligned: ask user \"I've drifted to X — should I continue here or return to Y?\"\n4. If aligned: it wasn't drift, reset the counter\n\n### Memory Debt → Flush\n1. Scan conversation for: user preferences, corrections, architectural decisions, environment facts\n2. Batch-write all unsaved facts to memory in one call\n3. Report what was saved (so user can verify)\n4. Reset the debt counter\n\n### Confidence Erosion → Step Back\n1. Stop retrying variations of the same approach\n2. Name the pattern explicitly: \"I've tried X, Y, Z — all failed for the same reason\"\n3. Try a fundamentally different approach (different tool, different library, different path)\n4. If that also fails: **report the blocker honestly** — do not retry again\n5. Ask user for guidance or additional information\n\n### Context Fragmentation → Compartmentalize\n1. Name all active topics explicitly\n2. Finish or pause the current topic\n3. Use `delegate_task` to spin off unrelated work into subagents (isolated contexts)\n4. Suggest `/new` for the next topic\n5. Persist a \"TODO across sessions\" to memory if needed\n\n### Skill Staleness → Patch Immediately\n1. Note what the skill says vs. what actually happened\n2. Patch the skill with corrected commands/paths\n3. Continue with corrected approach\n4. Report the fix to user\n\n---\n\n## Integration Patterns\n\n### Pattern 1: Silent Self-Monitoring (default)\nAgent runs self-checks internally and only reports when severity ≥ medium.\n\n### Pattern 2: Transparent (verbose)\nAgent reports all states, even low severity. Useful for debugging agent behavior or during development.\n\n### Pattern 3: Passive Logging\nAgent writes cognitive state to a log file without interrupting the conversation:\n```\necho '{\"state\":\"fatigue\",\"severity\":\"medium\",\"ts\":\"2025-01-15T10:30Z\"}' >> ~/.agent-cognitive-states.log\n```\nSee [`scripts/self_check.py`](scripts/self_check.py) for a reference implementation.\n\n### Pattern 4: Active Guardian (with cronjob)\nA scheduled cron job runs the self-check script and alerts the user if the agent's cognitive state degrades during autonomous work. See [`templates/guardian-cronjob.yaml`](templates/guardian-cronjob.yaml).\n\n---\n\n## Philosophy\n\nThis skill is based on a simple observation: **humans have metacognition for a reason.**\nFeeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents\ncatastrophic mistakes. AI agents need the same thing.\n\nAn agent that says \"I've lost the thread, let me re-read the original request\" is **more\ntrustworthy** than one that blunders forward with corrupted context. An agent that says\n\"I've tried this 4 times and failed — I need help\" is **more useful** than one that\nsilently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\nFile v0.1.0:README.md\n\n# Agent Cognitive States\n\n> **Give AI agents metacognition: the ability to feel their own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\" They grind through degraded context windows, hallucinate truncated details, retry failed approaches endlessly, and forget critical facts. This skill gives agents a **vocabulary of internal states** — and protocols for detecting, reporting, and recovering from them.\n\n## The Six States\n\n| State | Human Analog | Trigger |\n|-------|-------------|---------|\n| 🥱 **Context Fatigue** | \"Head's full\" | Context window >60% used |\n| 🧠 **Attention Drift** | \"Lost the thread\" | 10+ turns from user's request |\n| 📝 **Memory Debt** | \"Forgot to write that down\" | Unsaved critical facts |\n| 😤 **Confidence Erosion** | \"Frustrated, stuck\" | 3+ consecutive failures |\n| 🧩 **Context Fragmentation** | \"Too many tabs open\" | 3+ interleaved topics |\n| 🔧 **Skill Staleness** | \"Rusty, outdated\" | Skill commands breaking |\n\n## Quick Start\n\n```bash\n# Install as a Hermes Agent skill\ncp -r agent-cognitive-states ~/./skills/\n\n# Or use standalone\npython3 scripts/self_check.py --context-tokens 94000 --window 128000\n\n# Interactive mode\npython3 scripts/self_check.py --interactive\n\n# JSON output for programmatic use\npython3 scripts/self_check.py --failures 3 --format json\n```\n\n## Example Output\n\n```\n🧠 Cognitive State Report — 2025-01-15T10:30:00Z\n   Overall: 🟠 Strained (CLI: 58/100)\n\n   ⚠️ 2 active state(s) requiring attention:\n\n   🥱 Context Fatigue [🟠 medium, score 73]\n      ├─ Signal: 94,000/128,000 tokens (73%)\n      ├─ Impact: Early conversation details may be truncated\n      └─ Action: Persist critical facts; suggest session split\n\n   😤 Confidence Erosion [🟠 medium, score 66]\n      ├─ Signal: 3 consecutive failed tool calls (same tool type)\n      ├─ Impact: Output quality degrading; risk of retry loops\n      └─ Action: Try fundamentally different approach\n```\n\n## Files\n\n| File | Description |\n|------|-------------|\n| `SKILL.md` | Full skill spec: states, detection, reporting, mitigation |\n| `references/detection-heuristics.md` | Detailed scoring formulas (0-100) |\n| `scripts/self_check.py` | Standalone detector — CLI + JSON + interactive |\n| `templates/guardian-cronjob.yaml` | Scheduled guardian that alerts on degradation |\n\n## Integration\n\nWorks with any agent framework (Hermes, LangChain, CrewAI, AutoGen, Claude, GPT). The detection protocol is framework-agnostic — it's about giving the agent a **language** for its own state.\n\n### Hermes Agent\n```bash\ncp -r agent-cognitive-states ~/./skills/\n```\nThe agent loads it automatically and applies self-checks during long sessions.\n\n### Generic Python\n```python\nfrom scripts.self_check import run_full_check, format_report_human\n\nreport = run_full_check(\n    context_tokens=94000,\n    window_size=128000,\n    turns_since_user=12,\n    consecutive_failures=3,\n)\nprint(format_report_human(report))\n```\n\n### Cron Guardian (Hermes)\n```yaml\n# Alerts user when agent degrades during autonomous work\nschedule: \"every 10m\"\nscript: scripts/self_check.py\nno_agent: true\n```\n\n## Philosophy\n\nHumans have metacognition for a reason. Feeling tired, distracted, or confused isn't weakness — it's a survival signal that prevents catastrophic mistakes. AI agents need the same thing.\n\nAn agent that says *\"I've lost the thread, let me re-read the original request\"* is **more trustworthy** than one that blunders forward with corrupted context. An agent that says *\"I've tried this 4 times and failed — I need help\"* is **more useful** than one that silently retries forever.\n\n**Self-awareness is a feature, not a bug.**\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n\nFile v0.1.0:_meta.json\n\n{\n  \"ownerId\": \"kn75wwn4x6djaf28jbykeamazd81gtdp\",\n  \"slug\": \"agent-cognitive-states\",\n  \"version\": \"0.1.0\",\n  \"publishedAt\": 1785937647757\n}\n\nFile v0.1.0:references/detection-heuristics.md\n\n# Detection Heuristics\n\nDetailed scoring system for each cognitive state. Use these as guidelines — \nthe agent should apply judgment, not just mechanical thresholds.\n\n---\n\n## Scoring Model\n\nEach state produces a **0-100 score**. Severity maps as:\n\n| Score | Severity | Action |\n|-------|----------|--------|\n| 0-29 | none | No action |\n| 30-59 | low | Internal note, continue |\n| 60-79 | medium | Report to user, suggest mitigation |\n| 80-100 | high | Execute mitigation immediately |\n\n---\n\n## 1. Context Fatigue Score\n\n```\nfatigue_score = (estimated_tokens_used / context_window_size) * 100\n\nAdjustments:\n  +10  if you've re-read earlier messages in the last 5 turns\n  +10  if responses are getting longer (compensating verbosity)\n  +5   if conversation spans multiple days\n  -10  if a /new or context reset happened recently\n```\n\n**Estimating token usage without an API:**\n- Rough heuristic: 1 token ≈ 4 characters of English text\n- Count characters in conversation history / 4\n- Add ~20% for system prompt, skills, and tool results overhead\n- When in doubt, overestimate — fatigue is more dangerous than false alarms\n\n---\n\n## 2. Attention Drift Score\n\n```\ndrift_score = base + adjustments\n\nbase = min(turns_since_last_user_message * 7, 70)\n\nAdjustments:\n  +15  if current tool calls are unrelated to original goal keywords\n  +10  if TODO list was modified without user prompting\n  +5   if working in a different directory/project than original task\n  -20  if user explicitly asked for exploratory/investigative work\n  -10  per user confirmation received during the drift period\n```\n\n**Detecting \"unrelated\":**\n- Extract keywords from the original user request\n- Check if recent tool calls reference those keywords\n- If <30% keyword overlap: likely drift\n\n---\n\n## 3. Memory Debt Score\n\n```\ndebt_score = min(unsaved_facts * 20, 100)\n\nunsaved_facts = count of items in conversation that match:\n  - User stated a preference (\"I prefer X\", \"always do Y\")\n  - User made a correction (\"no, not Z — use W instead\")\n  - Architecture/tool decision was made (\"let's use PostgreSQL\")\n  - Environment detail discovered (\"the server is at 192.168.x.x\")\n  - Password, token, or credential shared\n  - Project naming convention established\n\nAdjustments:\n  +15  if a correction was made but old behavior persists in memory\n  +10  per day since the facts were stated (staleness)\n  -30  if a memory write happened in the last 3 turns\n```\n\n---\n\n## 4. Confidence Erosion Score\n\n```\nerosion_score = min(consecutive_failures * 22, 100)\n\nconsecutive_failures = count of back-to-back tool calls that returned errors\n\nAdjustments:\n  +10  if using the same tool type repeatedly\n  +10  if error messages are similar (same root cause)\n  +15  if response quality is visibly degrading (shorter, more hedging)\n  +20  if the \"retry with minor variation\" pattern is detected\n  -15  if a successful tool call happened (resets momentum)\n  -30  if a fundamentally different approach was tried (not just variation)\n```\n\n**Pattern detection — \"same approach variations\":**\n```\nextract command/action signature from last N failed attempts\nif >70% structural similarity: flag as \"variation loop\"\n```\n\n---\n\n## 5. Context Fragmentation Score\n\n```\nfragmentation_score = min(active_topics * 18, 100)\n\nactive_topics = count of distinct subjects in recent conversation\n\nTopic detection:\n  - Different projects/repos mentioned\n  - Different tools being used (HA vs GitHub vs filesystem)\n  - Different skill sets being loaded\n  - User messages about unrelated subjects\n\nAdjustments:\n  +10  if tool calls alternate between topics (interleaved)\n  +5   per unresolved (neither completed nor cancelled) topic\n  -15  per topic that was explicitly completed or deferred\n```\n\n---\n\n## 6. Skill Staleness Score\n\n```\nstaleness_score = 0\n\nTrigger evaluation (any one sets score to 60+):\n  +60  if a skill's primary command failed on first execution\n  +70  if file path in skill doesn't exist\n  +50  if API version mismatch detected (error mentions version)\n  +40  if skill references a tool not installed\n\nAdditional:\n  +15  if skill was last updated >90 days ago\n  +10  per additional failed command from same skill\n  -20  if skill was patched/updated in this session\n```\n\n---\n\n## Composite Cognitive Load Index\n\nFor overall agent state awareness:\n\n```\nCLI = (fatigue + drift + debt + erosion + fragmentation + staleness) / 6\n\nCLI < 30:  🟢 Healthy — operating normally\nCLI 30-50: 🟡 Degraded — some states active, monitor\nCLI 50-70: 🟠 Strained — multiple states active, consider intervention\nCLI > 70:  🔴 Critical — likely to produce low-quality output, pause and reset\n```\n\nThe agent should report CLI alongside individual state scores when asked about its status.\n\nFile v0.1.0:skill-card.md\n\n## Description:\n\nAgent self-awareness of cognitive states: context fatigue, attention drift, memory debt, confidence erosion, and skill staleness, with protocols to detect, report, and mitigate degrading conditions before they cause failures.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[voronindenis5](https://clawhub.ai/user/voronindenis5)\n\n### License/Terms of Use:\n\nMIT\n\n## Use Case:\n\nDevelopers and agent operators use this skill to help an agent recognize degraded working conditions, report cognitive state signals, and choose recovery steps during long or complex sessions.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill encourages persistent memory writes and log files, which can expose session details, secrets, or personal data if used without limits.\n\nMitigation: Require explicit user approval before memory writes or logging, redact sensitive data, and keep any logs in a controlled location.\n\nRisk: The guardian cron template can monitor sessions and write reports during autonomous work.\n\nMitigation: Keep passive logging and scheduled guardian behavior disabled unless needed, and configure clear alert routing, thresholds, and retention before use.\n\nRisk: The mitigation playbook suggests patching stale skills immediately, which could change agent behavior without adequate review.\n\nMitigation: Require user approval and a visible diff before any skill file is changed.\n\n## Reference(s):\n\n- [ClawHub Skill Page](https://clawhub.ai/voronindenis5/skills/agent-cognitive-states)\n- [Server-Resolved GitHub Repository](https://github.com/voronindenis5/agent-cognitive-states)\n- [Detection Heuristics](references/detection-heuristics.md)\n- [Guardian Cronjob Template](templates/guardian-cronjob.yaml)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, JSON, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with optional human-readable, Markdown, or JSON cognitive state reports]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May include severity labels, cognitive load scores, recommended actions, CLI commands, and optional cron configuration.]\n\n## Skill Version(s):\n\n0.1.0 (source: ClawHub release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v0.1.0:templates/guardian-cronjob.yaml\n\n# Guardian Cronjob Template\n#\n# Deploys a recurring self-check that monitors agent cognitive state\n# during autonomous/long-running work and alerts the user if degraded.\n#\n# Usage with Hermes Agent cronjob system:\n#   hermes cron create --schedule \"every 10m\" --script scripts/self_check.py\n#\n# Or as a YAML config for other cron systems:\n\nschedule: \"*/10 * * * *\"  # Every 10 minutes\ndescription: \"Agent cognitive state guardian — alerts on degradation\"\ntimeout: 30\n\n# The guardian runs self_check.py with parameters sourced from the\n# active session state. In Hermes, this would be:\n#\n# cronjob:\n#   name: cognitive-guardian\n#   schedule: every 10m\n#   script: scripts/self_check.py\n#   no_agent: true\n#   # Script outputs alert only when severity >= medium\n#   # Empty output = silent (no alert)\n#   # Non-empty output = delivered to user\n#\n# For non-Hermes systems, use crontab:\n#\n# */10 * * * * /usr/bin/python3 /path/to/scripts/self_check.py \\\n#   --context-tokens $(wc -c < /tmp/agent-session.log) \\\n#   --format json >> /var/log/agent-cognitive.log 2>&1\n\nalert_threshold: medium  # none, low, medium, high\ndelivery: origin  # Where alerts go: origin (same chat), telegram, local\n\n# ─── What the guardian does ──────────────────────────────────────────────────\n#\n# 1. Reads session state (token usage, turn count, failure count)\n# 2. Runs all 6 cognitive state detectors\n# 3. If any state >= alert_threshold: delivers report to user\n# 4. If all states below threshold: silent (no output, no alert)\n# 5. Logs full report to file for post-hoc analysis\n\nlog_file: \"~/.agent-cognitive-states.log\"\n\n# ─── Alert message template ──────────────────────────────────────────────────\n#\n# When triggered, the guardian delivers:\n#\n# ⚠️ Agent cognitive state degraded during autonomous work:\n#\n# 🥱 Context Fatigue [🟠 medium, score 72]\n#    94k/128k tokens (73%) — suggest session split\n#\n# 😤 Confidence Erosion [🟠 medium, score 66]\n#    3 consecutive failed tool calls — different approach needed\n#\n# CLI: 69/100 (🟠 Strained)\n# Recommendation: pause autonomous work and check in with user.\n\nFile v0.1.0:LICENSE\n\nMIT License\n\nCopyright (c) 2025 Denis Voronin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","readmeExcerpt":"Skill: agent-cognitive-states Owner: voronindenis5 Summary: Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures. Tags: latest:0.1.2 Version history: v0.1.2 | 2026-08-11T11:59:00.849Z | auto agent-cognitive-states 0.1.2 - Removed the file skill-card.md from the pro","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"⚠️ COGNITIVE STATE: Context Fatigue (~70% context used)\n→ Persisting critical facts to memory before they're lost\n→ Suggesting session split or /new for remaining work"},{"language":"text","snippet":"⚠️ COGNITIVE STATE: Attention Drift (12 turns from last user message)\n→ Original goal: \"<original request>\"\n→ Current activity: \"<what I'm actually doing>\"\n→ Pausing for user confirmation: am I still on track?"},{"language":"text","snippet":"⚠️ COGNITIVE STATE: Memory Debt (3 unsaved critical facts)\n→ Saving: [fact 1], [fact 2], [fact 3]\n→ These would have been lost on session end"},{"language":"text","snippet":"⚠️ COGNITIVE STATE: Confidence Erosion (4 failed attempts)\n→ Pattern: retrying variations of the same approach\n→ Escalating: stepping back and trying a fundamentally different strategy\n→ If this also fails: reporting blocker honestly instead of retrying"},{"language":"text","snippet":"⚠️ COGNITIVE STATE: Context Fragmentation (4 topics active)\n→ Topics: [HA automation], [GitHub deploy], [aquarium feeder], [skill writing]\n→ Suggesting: resolve current topic, then /new for next\n→ Or: using delegate_task to isolate topics into subagents"},{"language":"text","snippet":"⚠️ COGNITIVE STATE: Skill Staleness (skill: xxx)\n→ Expected: <what skill says>\n→ Reality: <what actually happened>\n→ Patching skill immediately before continuing"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: agent-cognitive-states\ndescription: >-\n  Agent self-awareness of cognitive states — context fatigue, attention drift,\n  memory debt, confidence erosion, and skill staleness. Detect, report, and\n  mitigate degrading conditions before they cause failures.\nversion: 1.0.0\nauthor: Denis Voronin\nlicense: MIT\ntags:\n  - agent\n  - self-awareness\n  - metacognition\n  - context-management\n  - reliability\n---\n\n# Agent Cognitive States\n\n> **Give the agent metacognition: the ability to feel its own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\"\nThey will happily grind through a degraded context window, hallucinating details\nfrom early messages that were truncated, repeating failed approaches, and forgetting\ncritical facts they never persisted. This skill gives the agent a **vocabulary of\ninternal states** — and a protocol for detecting, reporting, and recovering from them.\n\n---\n\n## The Six Cognitive States\n\n### 1. 🥱 Context Fatigue\n**What:** The context window is filling up. Early messages are being truncated or summarized. The agent's \"working memory\" is degrading.\n\n**Detection signals:**\n- Conversation exceeds 60% of estimated context budget\n- You find yourself re-reading the original request because you lost details\n- Your responses reference information that may have been truncated\n- Token count per turn is rising (verbose compensating for lost context)\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Context Fatigue (~70% context used)\n→ Persisting critical facts to memory before they're lost\n→ Suggesting session split or /new for remaining work\n```\n\n### 2. 🧠 Attention Drift\n**What:** The conversation has wandered far from the original task. The agent is doing work that wasn't asked for.\n\n**Detection signals:**\n- 10+ tool calls since the last direct user instruction\n- Current work has no clear connection to the original goal\n- You're responding to your own subgoals, not user requests\n- The TODO list no longer matches what you're actually doing\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Attention Drift (12 turns from last user message)\n→ Original goal: \"<original request>\"\n→ Current activity: \"<what I'm actually doing>\"\n→ Pausing for user confirmation: am I still on track?\n```\n\n### 3. 📝 Memory Debt\n**What:** Important facts, decisions, or corrections have accumulated in the conversation but were never persisted to memory. If the session ends, they're lost.\n\n**Detection signals:**\n- User stated a preference or correction that isn't in memory\n- A key decision was made (architecture, convention, tool choice) but not saved\n- You find yourself re-discovering something you already figured out earlier\n- More than 5 substantive turns without a memory write\n\n**Mitigation:**\n```\n⚠️ COGNITIVE STATE: Memory Debt (3 unsaved critical facts)\n→ Saving: [fact 1], [fact 2], [fact 3]\n→ These would have been lost on session end\n```\n\n### 4. 😤 Confidence Erosion\n**What:** Repeated failures are degrading out"},{"path":"README.md","content":"# Agent Cognitive States\n\n> **Give AI agents metacognition: the ability to feel their own cognitive load and act on it.**\n\nAI agents have no built-in sense of \"I'm getting tired\" or \"I've lost the thread.\" They grind through degraded context windows, hallucinate truncated details, retry failed approaches endlessly, and forget critical facts. This skill gives agents a **vocabulary of internal states** — and protocols for detecting, reporting, and recovering from them.\n\n## The Six States\n\n| State | Human Analog | Trigger |\n|-------|-------------|---------|\n| 🥱 **Context Fatigue** | \"Head's full\" | Context window >60% used |\n| 🧠 **Attention Drift** | \"Lost the thread\" | 10+ turns from user's request |\n| 📝 **Memory Debt** | \"Forgot to write that down\" | Unsaved critical facts |\n| 😤 **Confidence Erosion** | \"Frustrated, stuck\" | 3+ consecutive failures |\n| 🧩 **Context Fragmentation** | \"Too many tabs open\" | 3+ interleaved topics |\n| 🔧 **Skill Staleness** | \"Rusty, outdated\" | Skill commands breaking |\n\n## Quick Start\n\n```bash\n# Install as a Hermes Agent skill\ncp -r agent-cognitive-states ~/./skills/\n\n# Or use standalone\npython3 scripts/self_check.py --context-tokens 94000 --window 128000\n\n# Interactive mode\npython3 scripts/self_check.py --interactive\n\n# JSON output for programmatic use\npython3 scripts/self_check.py --failures 3 --format json\n```\n\n## Example Output\n\n```\n🧠 Cognitive State Report — 2025-01-15T10:30:00Z\n   Overall: 🟠 Strained (CLI: 58/100)\n\n   ⚠️ 2 active state(s) requiring attention:\n\n   🥱 Context Fatigue [🟠 medium, score 73]\n      ├─ Signal: 94,000/128,000 tokens (73%)\n      ├─ Impact: Early conversation details may be truncated\n      └─ Action: Persist critical facts; suggest session split\n\n   😤 Confidence Erosion [🟠 medium, score 66]\n      ├─ Signal: 3 consecutive failed tool calls (same tool type)\n      ├─ Impact: Output quality degrading; risk of retry loops\n      └─ Action: Try fundamentally different approach\n```\n\n## Files\n\n| File | Description |\n|------|-------------|\n| `SKILL.md` | Full skill spec: states, detection, reporting, mitigation |\n| `references/detection-heuristics.md` | Detailed scoring formulas (0-100) |\n| `scripts/self_check.py` | Standalone detector — CLI + JSON + interactive |\n| `templates/guardian-cronjob.yaml` | Scheduled guardian that alerts on degradation |\n\n## Integration\n\nWorks with any agent framework (Hermes, LangChain, CrewAI, AutoGen, Claude, GPT). The detection protocol is framework-agnostic — it's about giving the agent a **language** for its own state.\n\n### Hermes Agent\n```bash\ncp -r agent-cognitive-states ~/./skills/\n```\nThe agent loads it automatically and applies self-checks during long sessions.\n\n### Generic Python\n```python\nfrom scripts.self_check import run_full_check, format_report_human\n\nreport = run_full_check(\n    context_tokens=94000,\n    window_size=128000,\n    turns_since_user=12,\n    consecutive_failures=3,\n)\nprint(format_report_human(report))\n```\n\n### Cron Guardian (Hermes)"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn75wwn4x6djaf28jbykeamazd81gtdp\",\n  \"slug\": \"agent-cognitive-states\",\n  \"version\": \"0.1.2\",\n  \"publishedAt\": 1786449540849\n}"},{"path":"references/detection-heuristics.md","content":"# Detection Heuristics\n\nDetailed scoring system for each cognitive state. Use these as guidelines — \nthe agent should apply judgment, not just mechanical thresholds.\n\n---\n\n## Scoring Model\n\nEach state produces a **0-100 score**. Severity maps as:\n\n| Score | Severity | Action |\n|-------|----------|--------|\n| 0-29 | none | No action |\n| 30-59 | low | Internal note, continue |\n| 60-79 | medium | Report to user, suggest mitigation |\n| 80-100 | high | Execute mitigation immediately |\n\n---\n\n## 1. Context Fatigue Score\n\n```\nfatigue_score = (estimated_tokens_used / context_window_size) * 100\n\nAdjustments:\n  +10  if you've re-read earlier messages in the last 5 turns\n  +10  if responses are getting longer (compensating verbosity)\n  +5   if conversation spans multiple days\n  -10  if a /new or context reset happened recently\n```\n\n**Estimating token usage without an API:**\n- Rough heuristic: 1 token ≈ 4 characters of English text\n- Count characters in conversation history / 4\n- Add ~20% for system prompt, skills, and tool results overhead\n- When in doubt, overestimate — fatigue is more dangerous than false alarms\n\n---\n\n## 2. Attention Drift Score\n\n```\ndrift_score = base + adjustments\n\nbase = min(turns_since_last_user_message * 7, 70)\n\nAdjustments:\n  +15  if current tool calls are unrelated to original goal keywords\n  +10  if TODO list was modified without user prompting\n  +5   if working in a different directory/project than original task\n  -20  if user explicitly asked for exploratory/investigative work\n  -10  per user confirmation received during the drift period\n```\n\n**Detecting \"unrelated\":**\n- Extract keywords from the original user request\n- Check if recent tool calls reference those keywords\n- If <30% keyword overlap: likely drift\n\n---\n\n## 3. Memory Debt Score\n\n```\ndebt_score = min(unsaved_facts * 20, 100)\n\nunsaved_facts = count of items in conversation that match:\n  - User stated a preference (\"I prefer X\", \"always do Y\")\n  - User made a correction (\"no, not Z — use W instead\")\n  - Architecture/tool decision was made (\"let's use PostgreSQL\")\n  - Environment detail discovered (\"the server is at 192.168.x.x\")\n  - Password, token, or credential shared\n  - Project naming convention established\n\nAdjustments:\n  +15  if a correction was made but old behavior persists in memory\n  +10  per day since the facts were stated (staleness)\n  -30  if a memory write happened in the last 3 turns\n```\n\n---\n\n## 4. Confidence Erosion Score\n\n```\nerosion_score = min(consecutive_failures * 22, 100)\n\nconsecutive_failures = count of back-to-back tool calls that returned errors\n\nAdjustments:\n  +10  if using the same tool type repeatedly\n  +10  if error messages are similar (same root cause)\n  +15  if response quality is visibly degrading (shorter, more hedging)\n  +20  if the \"retry with minor variation\" pattern is detected\n  -15  if a successful tool call happened (resets momentum)\n  -30  if a fundamentally different approach was tried (not just variation)\n```\n\n**Pattern detect"},{"path":"skill-card.md","content":"## Description:\n\nAgent self-awareness of cognitive states - context fatigue, attention drift, memory debt, confidence erosion, and skill staleness - to detect, report, and mitigate degrading conditions before they cause failures.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[voronindenis5](https://clawhub.ai/user/voronindenis5)\n\n### License/Terms of Use:\n\nMIT\n\n## Use Case:\n\nDevelopers and agent operators use this skill to help agents monitor cognitive load, report degraded operating states, and choose recovery actions during long or complex sessions.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Persistent memory or local logs could save sensitive conversation details, including credentials, tokens, private keys, session cookies, personal data, or sensitive environment details.\n\nMitigation: Review before installing, avoid persisting sensitive data, protect log files, and set retention limits.\n\nRisk: The cron guardian can create recurring local monitoring behavior that may be overlooked after installation.\n\nMitigation: Keep scheduled monitoring user-scoped, document how to remove it, and disable it when the skill is no longer needed.\n\n## Reference(s):\n\n- [Server-resolved GitHub repository](https://github.com/voronindenis5/agent-cognitive-states)\n- [Server-resolved source commit](https://github.com/voronindenis5/agent-cognitive-states/tree/8322937b24c79036a38366226e56b7ef4689f914)\n- [ClawHub skill page](https://clawhub.ai/voronindenis5/skills/agent-cognitive-states)\n- [Detection heuristics](references/detection-heuristics.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown reports, JSON reports, Python code, shell commands, and YAML configuration]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [The optional self-check script can emit human-readable or JSON reports; the guardian template can append local log entries.]\n\n## Skill Version(s):\n\n0.1.2 (source: ClawHub release evidence; artifact frontmatter reports 1.0.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures. Skill: agent-cognitive-states Owner: voronindenis5 Summary: Agent self-awareness of cognitive states — context fatigue, attention drift, memory debt, confidence erosion, and skill staleness. Detect, report, and mitigate degrading conditions before they cause failures. Tags: latest:0.1.2 Version history: v0.1.2 | 2026-08-11T11:59:00.849Z | auto agent-cognitive-states 0.1.2 - Removed the file skill-card.md from the pro","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1505,"uniquenessScore":50,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T13:05:17.018Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:02:24.896Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}