# Cog — Cognitive Architecture for Claude Code > Cog gives Claude Code persistent memory, self-reflection, and foresight. No server, no runtime, no dependencies — just CLAUDE.md + memory/ + skills. Plain text by design. Source: https://github.com/marciopuga/cog Documentation: https://lab.puga.com.br/cog --- ## Architecture ### How It Works Cog has no server, no runtime, no daemon. It's a project directory with conventions. ``` Open the project in Claude Code → Claude reads CLAUDE.md → memory/ is available as persistent storage → skills route conversations via slash commands → memory files update as you work ``` When you open a Cog project, Claude reads `CLAUDE.md` — the instruction set that defines persona, memory rules, domain routing, and skill behaviors. The `memory/` directory is the persistent knowledge base. Skills are markdown prompt files in `.claude/commands/`. That's the entire system. No process to start. No session to manage. No infrastructure to maintain. ### Interface Agnostic Cog's memory is just markdown files. Any Claude-powered tool with file access can use it: - **Claude Code** — the primary interface. Terminal-native, skill routing via slash commands, real-time memory updates. - **Cowork** — Claude Desktop's agentic mode. Point it at `memory/` and it inherits everything. Good for heavy document generation, multi-file research, long autonomous workflows. See [Using Cog with Cowork](https://lab.puga.com.br/cog/#/cowork). - **Any future Claude tool** — if it can read and write files, it can use Cog's memory. The interface determines how context is loaded and how you interact. The memory system doesn't care — it's files on disk. ### Skills Slash commands route conversations to the right domain and behavior. Each skill is a markdown prompt file in `.claude/commands/` that tells Claude what files to load and how to behave. **Built-in skills** ship with every Cog instance: | Skill | Domain | |-------|--------| | `/personal` | Family, health, calendar, day-to-day | | `/explainer` | Writing, explanation, long-form | | `/humanizer` | Rewrite AI text in human voice | | `/reflect` | Self-improvement, conversation mining | | `/evolve` | Systems architecture audit | | `/history` | Deep memory search, recall | | `/foresight` | Cross-domain strategic nudge | | `/scenario` | Decision simulation, branch modeling | | `/housekeeping` | Memory maintenance, archival | | `/setup` | Bootstrap domains from manifest | **Domain skills** are auto-generated from `memory/domains.yml` — add a domain to the manifest, run `/setup`, and Cog creates the skill file, memory directories, and routing rules. No code changes needed. See the [journal entry](https://lab.puga.com.br/cog/#/journal/domain-registry) for the full story. Skills handle their own memory loading. The main instruction set doesn't duplicate that logic — it provides the routing table so Cog knows where to look. ### Domain Registry All memory domains are defined in a single YAML manifest (`memory/domains.yml`). The manifest is the **single source of truth** for domain structure — pipeline skills and the routing table all read from it. ```yaml domains: - id: work path: work/acme type: work label: "Day job at Acme Corp" triggers: [acme, work, colleagues, projects] files: [hot-memory, action-items, entities, projects, dev-log, observations] ``` Each domain has a type (`personal`, `work`, `side-project`, `system`) that determines how the pipeline treats it. Work and side-project domains are automatically included in foresight scans. Domains can have subdomains for focused sub-topics. The `/setup` skill reads the manifest and generates: - Memory directories with starter files (hot-memory, observations, action-items, entities) - Domain command files from `.claude/commands/_templates/domain.md` - Updated routing table in `CLAUDE.md` Running `/setup` is idempotent — it creates what's missing, regenerates command files from the template, and leaves everything else alone. ### Design Principles **Simpler always wins.** Every architecture decision that survived is the simpler option. Feature velocity comes from removing complexity, not adding it. When two approaches solve the same problem, the one with fewer moving parts wins. **Data transformation is the superpower.** The system is optimized for turning unstructured input into structured, actionable output: - Voice note while working → entity profile update - Photo of a document → structured tracking file - PDF from a specialist → session notes with goals and observations - Scattered conversation fragments → synthesized thread with narrative arc --- ## Memory ### The Core Idea Cog's memory design draws from the RLM paper (arxiv 2512.24601). > Memory as environment, not input. Cog doesn't try to load everything it knows into every conversation. Instead, it has a file-based knowledge base that it searches on demand — like having a well-organised filing cabinet instead of trying to hold every document in your hands at once. ### Consolidation Memory moves the way a brain consolidates it during sleep — raw experience gets replayed, abstracted into durable knowledge, and filed where it belongs. Episodic events flow upward into semantic patterns; each tier is smaller and more distilled than the one below: ``` Raw events (voice, photos, PDFs, conversation fragments) ↓ capture fast, timestamp, tag Observations (episodic memory — append-only, per-domain) ↓ when 3+ observations cluster on a pattern Patterns (semantic memory — edit-in-place, distilled rules) ↓ when active or urgent Hot Memory (working memory — rewrite-freely, ~25 lines cross-domain) ↓ when resolved or historical Glacier (long-term storage — archived, never auto-loaded, catalogued) ``` Active working memory stays lean. Like long-term memory, nothing is ever lost — it's relocated and abstracted, never destroyed. #### Where the analogy holds — and where it doesn't The fit is strongest at the core. Like sleep, the pipeline runs at night, replaying recent episodes and abstracting their gist into durable rules. And it's strictly one-directional — a pattern never decays back into a raw event. Two honest differences: a brain is lossy (source episodes fade once the gist is extracted) while Cog files them perfectly in glacier — you get recall a brain can't. And "working memory" is the loosest label: real working memory lasts seconds, whereas hot-memory persists across sessions — it's closer to what's salient right now than to working memory proper. ### File Types | Type | Purpose | Edit Mode | Loaded When | |------|---------|-----------|-------------| | `hot-memory.md` | Top-of-mind per domain | Rewrite freely | Every conversation (in system prompt) | | `observations.md` | Timestamped events | Append only | When skill activates or search hits | | `entities.md` | People, places, things | Edit in place | When someone/something is mentioned | | `action-items.md` | Tasks and deadlines | Edit in place | Briefings, triage, when relevant | | `patterns.md` | Distilled rules | Edit in place | Self-improvement, when behaviour repeats | | Thread files | Deep single-topic synthesis | Current state: rewrite. Timeline: append | When topic comes up | | `glacier/` | Archived data | Read only | Only via explicit search | ### Domain Structure Every domain follows the same anatomy — a directory with standard file types. Domains are defined in `memory/domains.yml` (the [domain registry](https://lab.puga.com.br/cog/#/architecture#domain-registry)) and created by the `/setup` skill: ``` memory/ domains.yml # Manifest — SSOT for all domains hot-memory.md # Cross-domain top-of-mind personal/ # hot-memory, observations, action-items, entities, ... work/ / # Same structure — one dir per domain / cog-meta/ # Cog self-knowledge glacier/ # Archived data by domain ``` Each domain lists its files in the manifest. The pipeline skills all discover domains from this file — no hardcoded paths. ### The Memory Router Instead of loading all memory into context, Cog gets a **routing index** — a compact map of what exists and where. Cog uses L0 headers and CLAUDE.md routing conventions to navigate the memory directory. Rather than loading every file, Claude reads the routing table and navigates to the right files based on query type: - "What's on today?" → `personal/calendar.md` - "Who's on my team?" → `work//entities.md` - "How's the typing going?" → `personal/keyboard-typing.md` (thread) - "Update my action items" → domain-specific `action-items.md` The router means Cog can have hundreds of files across dozens of domains and still know exactly where to look — without reading everything up front. #### L0 Headers — Progressive Context Loading > Inspired by [OpenViking](https://github.com/volcengine/OpenViking) (ByteDance), which uses L0/L1/L2 tiered loading to reduce token cost and improve routing accuracy. Every memory file has a one-line **L0 summary** near the top — a quick answer to "what would I find if I read this file?" (max 80 characters): ```markdown # Personal — Entities ``` Skills and CLAUDE.md conventions route Claude to the right files based on L0 summaries. Three-tier loading in practice: - **L0** (~100 tokens total) — read the one-line `` header to answer "is this file relevant?" - **L1** — scan a file's section headers (`##`/`###`) to answer "which section do I need?", without reading the whole file - **L2** — read the full file or the specific section once L0/L1 confirm it's worth it L0 headers are maintained by the pipeline: [Housekeeping](https://lab.puga.com.br/cog/#/pipeline/housekeeping) scans for missing headers, [Reflect](https://lab.puga.com.br/cog/#/pipeline/reflect) preserves them when reorganising. See the [journal entry](https://lab.puga.com.br/cog/#/journal/l0-progressive-loading) for the full story. ### Memory Intelligence Three research-informed improvements adopted on [Day 23](https://lab.puga.com.br/cog/#/journal/memory-intelligence) after surveying 12 LLM memory systems: **Bi-directional back-linking** (inspired by A-MEM, NeurIPS 2025) — When writing to file A and linking to file B, Cog asks whether B genuinely gains context from pointing back to A, and adds the reciprocal link when it does. The knowledge graph stays connected in both directions where it earns its keep — not every link needs a mirror, so the graph stays connected without becoming link-spam. **Temporal validity on entities** (inspired by Zep/Graphiti) — When facts change in entity files, the old value is preserved with `since/until` dates and strikethrough: ``` Role: ~~Senior Engineer (since 2023-01, until 2024-12)~~ → Creative Technologist (since 2024-12) ``` This preserves how understanding evolved — important for a personal AI that tracks real people across years. **Contradiction detection** (inspired by Mem0) — A systematic consistency sweep runs every [Reflect](https://lab.puga.com.br/cog/#/pipeline/reflect) pass. For each domain's hot-memory, reflect verifies factual claims against canonical sources. Resolution: canonical file always wins; more recent wins; more specific wins over summary. Health dates and family-sensitive facts are flagged for user review, not auto-fixed. ### Threads — The Zettelkasten Layer Threads are **read-optimised synthesis files**. While observations capture raw events (write-optimised), threads pull related fragments into a coherent narrative. Every thread has the same spine: - **Current State** — what's true right now (rewrite freely, always current) - **Timeline** — dated entries, append-only, full detail preserved (never compressed) - **Insights** — learnings, patterns, what's different this time #### What Does "Raise" Mean? "Raise" is the verb for creating or updating a thread. When triggered: 1. **Search fragments** — Cog searches observations and memory files for all references 2. **Synthesise** — extract the narrative arc 3. **Write the thread** — create or update with the Current State → Timeline → Insights spine 4. **Link** — thread references source fragments via wiki-links #### Graduation A thread gets raised when: - A topic appears in **3+ observations across 2+ weeks** - The user explicitly says "raise X" or "thread X" - Scattered fragments no longer serve the topic well #### Rules - **One file forever** — threads grow long, they don't split or compress - **Texture is the value** — every entry keeps its full detail, quotes, and dates - **Fragments never move** — threads reference them, don't replace them - **Current State is always current** — rewrite it freely as things change ### SSOT **Single Source of Truth.** Each fact lives in ONE canonical file. Other files reference via wiki-links, never copy. - Action items → `action-items.md` - Calendar → `calendar.md` - People → `entities.md` - Health → `health.md` When a canonical file updates, hot-memory adjusts its framing but never duplicates the data. --- ## Using Cog with Cowork [Cowork](https://claude.com/product/cowork) is Claude Desktop's agentic mode — it executes multi-step tasks autonomously with direct file system access. Its biggest limitation: **no memory between sessions**. Every session starts blank. Cog's memory is entirely file-based. Cowork reads files. That's the integration — no API, no plugin, no configuration. Point Cowork at `memory/` and it inherits everything Cog knows. ### What Cowork Gets When Cowork reads Cog's memory files, it picks up: - **`hot-memory.md`** — identity, active situations, what matters right now - **`*/entities.md`** — people, places, things with structured bios - **`*/action-items.md`** — tasks with deadlines, priorities, domains - **`*/observations.md`** — timestamped raw events and notes - **Thread files** — deep synthesis on ongoing topics (health, family, career) This turns Cowork from amnesiac to contextual. No need to explain your situation from scratch — Cowork already knows the family structure, work context, active projects, and preferences. ### How to Use It Reference Cog's memory directly in a Cowork session: ``` Read my memory files in memory/ and then: - Build a timeline of [topic] from my thread files - Synthesise my action items into a prioritised spreadsheet - Research [topic] using my entities and observations as context ``` Or more targeted: ``` Read memory/hot-memory.md for context about me, then memory/personal/entities.md for family details. Create a birthday planning doc for the next upcoming birthday. ``` ### Complementary Strengths | Task | Cog (Claude Code) | Cowork (Desktop) | |------|-------------------|-----------------| | Quick capture (text, commands) | Yes | — | | Real-time memory updates | Yes | — | | Proactive nudges via /foresight | Yes | — | | Calendar queries (via MCP) | Yes | — | | Skill routing via slash commands | Yes | — | | Heavy document generation | — | Yes | | Multi-file research synthesis | — | Yes | | Spreadsheets with formulas | — | Yes | | Presentations and deliverables | — | Yes | | Long autonomous workflows | — | Yes | Cog is the persistent brain — always remembering, always routing. Cowork is the workshop — heavy lifting with full context. ### The Feedback Loop Cowork can also **write** back to Cog's memory. A Cowork session that produces research or analysis can save structured output to `memory/` — observations, entity updates, or new threads. Cog's [pipeline skills](https://lab.puga.com.br/cog/#/pipeline) pick up the changes and integrate them on the next run. ``` After your analysis, append findings to memory/personal/observations.md using the format: ### YYYY-MM-DD — [topic]\n- finding 1\n- finding 2 ``` Two-way loop: Cog captures and structures daily life. Cowork does deep work informed by that structure. Results flow back into memory for future conversations. --- ## Pipeline Cog includes pipeline skills that maintain memory health. Run them manually as slash commands, or automate with cron. | Stage | Role | Skill | |-------|------|-------| | Housekeeping | Janitor | `/housekeeping` | | Reflect | Therapist | `/reflect` | | Evolve | Architect | `/evolve` | | Foresight | Strategist | `/foresight` | Each step feeds the next. Zero overlap — one owner per job. The pipeline was introduced incrementally: scheduler on [Day 2](https://lab.puga.com.br/cog/#/journal/scheduler-and-domains), reflection on [Day 6](https://lab.puga.com.br/cog/#/journal/the-architecture-day), evolve on [Day 12](https://lab.puga.com.br/cog/#/journal/evolve-pipeline), foresight and scenarios on [Day 23](https://lab.puga.com.br/cog/#/journal/strategic-foresight). The [domain registry](https://lab.puga.com.br/cog/#/journal/domain-registry) made the pipeline domain-agnostic — stages discover domains from `domains.yml` instead of hardcoded paths. ### Why a Pipeline? A personal AI accumulates knowledge but also accumulates drift. Facts become stale. Summaries diverge from sources. Patterns emerge that no single conversation notices. The pipeline is Cog's immune system — it detects and corrects drift, surfaces what matters, and improves its own rules. Without it, the memory system would slowly decay. ### Design Principle **"Seeing ≠ owning."** When a pipeline step spots an issue outside its domain, it routes the issue — it doesn't adopt it. Housekeeping cleans; if it finds a pattern, it notes it for Reflect. Evolve changes rules; if it finds stale content, it routes to Housekeeping. This prevents scope creep and keeps each stage focused. ### Scheduling The pipeline is manual-first — run any skill as a slash command whenever you want. But for best results, automate it. #### Claude Code Use cron to spawn one-shot Claude processes: ```bash # Nightly maintenance 0 23 * * * cd /path/to/cog && claude -p "$(cat .claude/commands/housekeeping.md)" 0 0 * * * cd /path/to/cog && claude -p "$(cat .claude/commands/reflect.md)" # Weekly architecture audit 0 1 * * 0 cd /path/to/cog && claude -p "$(cat .claude/commands/evolve.md)" # Daily strategic nudge 0 7 * * * cd /path/to/cog && claude -p "$(cat .claude/commands/foresight.md)" ``` #### Cowork Open Cog in a [Cowork](https://claude.com/product/cowork) session and ask it to run pipeline skills as part of a longer autonomous workflow. Cowork has full file access and can chain multiple stages together — useful for a full maintenance pass in one session. --- ## Housekeeping **Run:** Manually with `/housekeeping`, or automate via cron **Role:** Janitor **Introduced:** [Day 2](https://lab.puga.com.br/cog/#/journal/scheduler-and-domains) ### What It Does Housekeeping is the maintenance pass. It cleans, archives, and surfaces accountability. The output feeds every subsequent pipeline stage. #### Core Tasks 1. **Glacier archival** — when observation files exceed 50 entries, the oldest batch gets archived to `glacier/` with YAML frontmatter for fast retrieval. Glacier files are never auto-loaded but remain searchable. 2. **Link audit** — scans memory files for wiki-links, generates `link-index.md` (a backlink index). This is the safety net for write-time linking — catching any cross-references that were missed. 3. **Briefing bridge** — writes `briefing-bridge.md` with critical findings: stale action items, upcoming birthdays, overdue health items, dormant domains. 4. **Thread candidate detection** — if a topic appears in 3+ observations across 2+ weeks, it suggests raising a [thread](https://lab.puga.com.br/cog/#/memory#threads--the-zettelkasten-layer). #### Accountability Surfacing - **Stale items:** Action items open >2 weeks get flagged with a suggested next action - **Health escalation:** Items open >6 months appear in every briefing until resolved or explicitly deferred - **Birthday prep:** 14 days out = gift suggestions from entity interests. 7 days out = logistics check - **Todo expiration:** Time-bound lists with <5 days left and >50% unchecked get flagged - **Dormant domains:** Work domains with 0 observations in >4 weeks get questioned ### What It Doesn't Do Housekeeping doesn't introspect, distill patterns, or change rules. If it finds a pattern, it notes it for [Reflect](https://lab.puga.com.br/cog/#/pipeline/reflect). If it finds a rule issue, it notes it for [Evolve](https://lab.puga.com.br/cog/#/pipeline/evolve). ### Output A debrief summarizing what was cleaned, archived, and flagged. Plus `briefing-bridge.md` for downstream consumption. --- ## Reflect **Run:** Manually with `/reflect`, or automate via cron **Role:** Therapist **Introduced:** [Day 6](https://lab.puga.com.br/cog/#/journal/the-architecture-day) ### What It Does Reflect is the introspective pass. It reads broadly, cross-references, and **acts** on insights — consolidating observations into patterns, fixing contradictions, filling memory gaps, and updating entities. This isn't passive observation. Reflect modifies files. #### Core Tasks 1. **Conversation mining** — reads recent conversation history and extracts unresolved threads, broken promises, friction points, and insights worth preserving. 2. **Observation → pattern promotion** — when 3+ observations cluster on the same theme, they get distilled into `patterns.md` (edit-in-place, timeless rules only). `patterns.md` has a hard cap of 110 lines / 7KB — enforced by a 4-step compression protocol. 3. **Hot-memory triage** — checks if anything in hot-memory has resolved or lost urgency. Demotes resolved items, promotes newly urgent patterns. 4. **Contradiction detection** — systematic consistency sweep across memory. For each domain's hot-memory, verifies claims against canonical sources. Resolution rules: - Canonical file always wins - More recent source wins - More specific wins over summary - Health dates and family-sensitive facts get flagged for user review, not auto-fixed 5. **Scenario feedback loop** — scans active [scenarios](https://lab.puga.com.br/cog/#/pipeline/scenarios) for check-by dates. If a scenario's check date has arrived, reflect reviews what actually happened against what was predicted, writes a retrospective, and updates calibration metrics. 6. **Self-observation** — after processing, appends up to 5 high-signal observations about Cog's own effectiveness to `self-observations.md`. ### The Contradiction Problem This is why Reflect exists. A personal AI that tracks real people, dates, and events across months will inevitably have facts update in one file but not propagate to others. Example: a task status advances from "need documents" to "submitted" in action-items.md, but hot-memory still says "need documents." Reflect catches these — 11+ instances per month on average. ### What It Doesn't Do Reflect doesn't change rules or system architecture. If it finds a rule that isn't working, it notes it for [Evolve](https://lab.puga.com.br/cog/#/pipeline/evolve). It doesn't clean or archive — that's [Housekeeping](https://lab.puga.com.br/cog/#/pipeline/housekeeping). ### Output A debrief summarizing what was learned, changed, and flagged. Modified memory files across all domains. --- ## Evolve **Run:** Manually with `/evolve`, or automate via cron **Role:** Architect **Introduced:** [Day 12](https://lab.puga.com.br/cog/#/journal/evolve-pipeline) ### What It Does Evolve audits Cog's architecture — the rules, processes, and prompt structure that govern the memory system. It does NOT touch memory content. It changes the rules that govern how content moves. #### Core Tasks 1. **Prompt weight analysis** — measures every component injected into the system prompt: hardcoded text, memory router index, hot-memory, patterns, briefing-bridge. Tracks changes run-over-run in a table. Target: minimize per-turn cost while preserving routing accuracy. 2. **Rule effectiveness** — reviews the latest housekeeping and reflect output. Did the rules produce the right behavior? Did any rule fail? Did any stage overstep its boundaries? 3. **File audit** — counts active and glacier files, total memory footprint. Flags anomalies (files growing past thresholds, dead files, zombie references). 4. **Process effectiveness** — verifies the pipeline ran in correct order, each stage completed, no overlaps or failures. Tracks consecutive clean runs. 5. **Rule changes** — proposes and applies changes to skill definitions (`.claude/commands/*.md`) and system instructions (`CLAUDE.md`). Low-risk changes (clarifications, cap adjustments) are applied directly. High-risk changes get proposed for user review. ### The Evolve Log Every run produces a structured entry in `evolve-log.md`: - Prompt weight table (component-by-component, with deltas) - Files audited (count, footprint) - Issues found (numbered, with root cause) - Rule changes applied - Rule changes proposed - Process effectiveness assessment - Routed content issues (for other stages to handle) - Deferred items This log is the first thing Evolve reads on the next run — continuity across sessions. ### Examples of Rule Changes - **patterns.md hard cap:** After 3 cycles of re-bloating (20KB → 5.3KB → 5.8KB → 8.9KB), Evolve added a 100-line / 7KB cap with a 4-step compression protocol - **Reflect boundary enforcement:** Reflect was modifying evolve-log.md (boundary violation) — Evolve added explicit file exclusions - **Briefing-bridge template:** Housekeeping was adding day-by-day schedules despite the PURPOSE comment — Evolve fixed the template - **Self-observation cap:** Reflect was producing 8+ observations per pass, causing rapid file growth — Evolve capped it at 5 ### What It Doesn't Do Evolve doesn't write observations, update entities, or consolidate content. It doesn't run housekeeping tasks. It changes the *rules* — not the *data*. ### Output A debrief with the full structured entry. Updated skill definitions and instructions where changes were applied. --- ## Foresight **Run:** Manually with `/foresight`, or automate via cron **Role:** Strategist **Introduced:** [Day 23](https://lab.puga.com.br/cog/#/journal/strategic-foresight) ### Why Foresight Exists Every other pipeline step looks *backward* — what happened, what broke, what drifted. No step was looking *forward*: projecting trajectories, detecting stalls, finding cross-domain convergences that no single conversation would notice. Foresight fills that gap. ### What It Does Foresight reads broadly across all domains and produces **one strategic nudge per day**. It writes to `foresight-nudge.md`, which can be consumed by briefings or reviewed directly. #### The Five Lenses 1. **Cross-domain convergence** — finds situations where two or more domains are heading toward the same moment, deadline, or decision. Example: an overseas trip (personal) converging with a family member's medical recovery (health) and mid-year work leave (career). 2. **Velocity & stall detection** — identifies patterns that are moving fast (and might need steering) or have stalled (and need a nudge). Measures by observation density and action-item velocity. 3. **Timing awareness** — overlays calendar events and deadlines to find windows of opportunity or conflict. Uses calendar data for real schedule grounding. 4. **Pattern projection** — extends observed patterns forward. "If this continues, then..." — with calibrated confidence based on past accuracy. 5. **Synthesis** — distills the most actionable insight into one clear nudge. #### Scenario Candidate Detection When pattern projection reveals a genuine fork — two meaningfully different paths with real stakes and a closing decision window — Foresight flags it as a candidate for [Scenario Simulation](https://lab.puga.com.br/cog/#/pipeline/scenarios). ### Rules - **One nudge per day.** Not a list. One actionable insight. - **Non-obvious only.** If it's already in hot-memory or action-items, it's not a nudge — it's a reminder. Foresight surfaces what isn't being tracked. - **Read-only.** Foresight NEVER edits memory files. It reads broadly and writes only to `foresight-nudge.md`. If it spots a memory error, it notes it in the nudge for [Reflect](https://lab.puga.com.br/cog/#/pipeline/reflect) to handle. - **Calendar-grounded.** Every nudge must reference real dates and deadlines, not abstract concerns. ### Anti-Patterns - Repeating what the briefing already covers (stale items, birthdays) - Generic advice ("remember to plan ahead") - Non-actionable observations - Nudges about Cog's own architecture (that's [Evolve](https://lab.puga.com.br/cog/#/pipeline/evolve)'s domain) ### Output `foresight-nudge.md` — overwritten each run. One nudge with context, rationale, and a suggested action. --- ## Scenarios **Run:** On demand (user-triggered or Foresight-suggested) via `/scenario` **Role:** Simulator **Introduced:** [Day 23](https://lab.puga.com.br/cog/#/journal/scenario-simulation) ### Why Scenarios Exist Cog can track facts and surface patterns, but it couldn't model *interactions between* isolated data. When a decision has real stakes and multiple possible outcomes, the right tool isn't a nudge — it's a simulation. Scenarios model decision branches with real dependencies, calendar-grounded timelines, and a feedback loop that improves accuracy over time. ### How It Works #### 1. Decision Point Identification Not everything deserves a scenario. The trigger threshold: a genuine fork with 2+ meaningfully different paths, real stakes, and a closing decision window. If the "branches" are just variations of the same outcome, it's not a real fork. #### 2. Dependency Mapping Read across memory to identify all variables that influence the decision: - **Calendar constraints** — deadlines, events, travel, work schedules - **People involved** — who has influence, who needs to know, who is affected - **Financial implications** — costs, budgets, opportunity costs - **Health/energy factors** — medical appointments, recovery timelines, stress load - **Existing commitments** — action items that overlap or conflict #### 3. Branch Generation Generate 2–3 distinct branches (not exhaustive — focused). Each branch gets: - A clear label and one-sentence summary - Key assumptions that make this branch likely - Concrete next steps if this branch is chosen - **Canary signals** — early indicators that this branch is becoming reality #### 4. Timeline Overlay Map each branch onto the actual calendar. Real dates, not abstract timelines. Flag conflicts, windows, and dependencies on external events. #### 5. Contingency Mapping For each branch, identify what breaks if it doesn't happen. What's the fallback? What irreversible commitments does each branch create? #### 6. Write Scenario File Each scenario is a markdown file in `memory/cog-meta/scenarios/` with YAML frontmatter: ```yaml status: active decision: What decision is being modeled check-by: YYYY-MM-DD # When to first review against reality resolution-by: YYYY-MM-DD # When this should be resolved confidence: 0.0-1.0 # Calibrated against past accuracy ``` ### The Feedback Loop This is what makes scenarios a learning system, not just a one-shot tool. 1. **[Foresight](https://lab.puga.com.br/cog/#/pipeline/foresight)** detects scenario candidates during its daily scan 2. **User or Foresight** triggers `/scenario` to build the simulation 3. **[Reflect](https://lab.puga.com.br/cog/#/pipeline/reflect)** checks active scenarios at their `check-by` dates 4. If resolved, Reflect writes a retrospective: which branch happened, what was predicted, what was missed 5. Calibration metrics update in `scenario-calibration.md` — accuracy %, common blind spots, pattern of over/under-confidence 6. Future scenarios adjust their confidence based on calibration history Over time, Cog gets better at projecting because it's measured against reality. ### Why Not Scheduled? Unlike [Foresight](https://lab.puga.com.br/cog/#/pipeline/foresight) (which can run daily), scenarios are only valuable at genuine decision points. Running them on a schedule would be waste. They're event-driven: triggered when a real fork appears. ### Output A scenario file in `memory/cog-meta/scenarios/` with branches, timelines, assumptions, canary signals, and contingencies. Flagged when check-by dates arrive or resolution-by dates pass. --- ## Why Text Cog is a set of plain-text conventions that evolve over time. The model doesn't evolve — Claude Code follows whatever rules it finds in `CLAUDE.md`. What evolves is the memory architecture itself: the conventions, the routing rules, the pattern files, the pipeline skill definitions. The pipeline skills (`/reflect`, `/evolve`, `/foresight`) are where the experiment gets interesting — they edit the rules that future sessions will follow, and you can measure whether those changes actually helped. Everything in Cog is plain text. No database. No embeddings. No vector store. No binary formats. Just markdown files in a folder. This isn't a limitation — it's what makes the evolution observable. ### Observability When a model organizes its own memories, you want to watch. You want to see what it promotes to hot-memory and what it lets decay. You want to read the patterns it distills from raw observations. You want to trace how an entity profile evolves over months. Text makes all of this visible. Open a file, read it. Diff two versions. Grep across the whole memory system. There's no abstraction layer between you and what the model thinks it knows. With a vector database, the model's knowledge is opaque — encoded as floating-point coordinates in high-dimensional space. You can query it, but you can't read it. You can't see the model's organizational choices. You can't learn from how it structures what it remembers. Text keeps the cognition legible. ### A Learning Environment Cog is an experiment. The question it's exploring: **what happens when you give a language model persistent memory and ask it to maintain that memory itself?** - How does it organize what it knows? - What does it promote and what does it forget? - When it reflects on its own patterns, does it actually improve? - When it audits its own rules, does it make them better or worse? - How does consolidation behave over months of real use? These are open questions. Nobody has definitive answers yet. The field is young — LLM memory systems have existed for barely a year, and self-improving ones for even less. Cog is designed to make these questions answerable. Every memory operation is a file write. Every reflection is a readable observation. Every rule change by `/evolve` is a diff in `CLAUDE.md`. You can see exactly what the model did, why it thought it should, and whether it was right. ### For Humans and Models The text-first design serves both audiences: **For you:** You can read, edit, and override anything. The model's memory is your memory too. If it gets something wrong, fix the file. If it promotes something irrelevant to hot-memory, demote it. You're always in control because the format is one you already know. **For the model:** Markdown is native territory. Language models are extraordinarily good at reading, writing, and reasoning about structured text. They don't need adapters, serializers, or query languages. The format that's most legible to you is also the format that's most natural for them. This isn't a coincidence. The overlap between "easy for humans to read" and "easy for models to process" is where Cog lives. ### The Bet The bet behind Cog is that the overhead of text — larger than embeddings, slower than database lookups, limited by context windows — is worth paying for the observability and simplicity you get in return. At personal scale (one person, a few domains, a few hundred files), the overhead is negligible. The context window is large enough. The file system is fast enough. And you get something no vector database gives you: the ability to sit down, read your AI's memory, and understand exactly how it thinks. That's the experiment. Fork it, run it, and see what you learn. --- ## Credits & Inspiration Cog didn't emerge from nothing. It's a synthesis — ideas borrowed, adapted, and recombined from research papers, open-source systems, and decades-old knowledge management traditions. This page credits the work that shaped it. ### Research **RLM — Recursive Language Models** (arxiv 2512.24601) The foundational insight. Memory should be recursive — each layer summarises and structures the layer below, creating a hierarchy that's efficient to navigate. Cog's consolidation (observations → patterns → hot-memory → glacier) is this idea made concrete. The paper's framing — "memory as environment, not input" — became Cog's core design principle. **A-MEM** (NeurIPS 2025) Inspired Cog's bi-directional back-linking. When a memory file links to another, the target file links back. The knowledge graph stays connected in both directions, not just forward references. A-MEM demonstrated that associative memory structures significantly improve retrieval in LLM systems. **OpenViking** (ByteDance / Volcengine) The L0/L1/L2 progressive context loading system. OpenViking showed that tiered loading — summaries first, details on demand — dramatically reduces token cost while preserving routing accuracy. Cog's L0 headers are a direct adaptation: every memory file gets a one-line summary that Claude reads before deciding whether to load the full file. ### Systems **Zep / Graphiti** Temporal validity on entities. When facts change, the old value is preserved with `since/until` dates rather than silently overwritten. Cog adopted this for its entity files — tracking how understanding evolves over time, not just what's currently true. **Mem0** Contradiction detection. A personal memory system that tracks real people and events across months will inevitably have facts update in one file but not propagate to others. Mem0's approach to systematic consistency checking influenced Cog's reflect pipeline — which catches 11+ contradictions per month on average in active use. **Anthropic's Claude Memory** Validation of the architecture. Claude's own memory system uses the same core approach: markdown files in the context window. No vector database. No graph database. This confirmed that file-based memory systems scale well at the personal level without infrastructure complexity. ### Traditions **Zettelkasten** The thread framework. Niklas Luhmann's slip-box method — atomic notes connected by links, building knowledge through connection rather than categorisation. Cog's threads are Zettelkasten notes for an AI: fragments synthesised into coherent narratives, cross-referenced with wiki-links, growing richer over time. **Single Source of Truth** (SSOT) A principle as old as database normalisation. Each fact lives in one canonical file. Other files reference it, never copy it. When the source updates, everything downstream reflects the change. Simple, but surprisingly hard to maintain — which is why Cog's reflect pipeline includes contradiction detection. ### Platform **Claude Code** (Anthropic) The platform that makes Cog possible. Claude Code's file access, slash commands, and `CLAUDE.md` conventions provide the substrate. Cog is just conventions on top — no runtime, no server, no dependencies beyond Claude itself. --- Cog is a recombination. The memory tiers come from RLM. The linking comes from Zettelkasten and A-MEM. The routing comes from OpenViking. The maintenance comes from database traditions. The platform comes from Anthropic. What's original is the combination — and the bet that a cognitive architecture for an AI assistant should be as simple as markdown files in a folder.