Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

name github-readme
description Agent OS GitHub README — 主文档,用于开源仓库
type reference
originSessionId 44cc711c-2cf7-4901-9e69-30413e282e58

Agent OS 🧠

A self-evolving operating system for Claude Code.

Not a config. Not a prompt. An operating system that learns, evolves, and protects.

License: MIT Claude Code ChromaDB Hooks Safety


The Problem

Claude Code forgets everything between sessions. Agents don't learn from experience. Safety is an afterthought. Upgrades break your configuration.

The Solution

Agent OS transforms Claude Code from a stateless assistant into a self-evolving system that:

  • 🧠 Remembers across sessions with 4-layer memory (identity → active → on-demand → archive)
  • 🧬 Evolves agents that get smarter with each task (weight decay + Key Lesson upgrade)
  • 🛡️ Protects with 9-layer safety protocol derived from Claude Code source code analysis
  • 📊 Audits every tool call as structured JSONL with auto-generated summaries
  • 🔌 Auto-registers new agent roles on first encounter — they persist forever
  • 📦 Survives upgrades with VERSION_GUARD validation scripts

Architecture

┌──────────────────────────────────────────────────────────┐
│                    AGENT OS                              │
│                                                          │
│  ┌─────────────┐  ┌──────────────┐  ┌─────────────────┐  │
│  │ Dynamic     │  │ Agent        │  │ Hook Lifecycle  │  │
│  │ Memory      │  │ Evolution    │  │ 6 Events        │  │
│  │ Engine      │  │ System       │  │ 14 Scripts      │  │
│  └──────┬──────┘  └──────┬───────┘  └────────┬────────┘  │
│         │                │                    │           │
│  ┌──────┴────────────────┴────────────────────┴────────┐  │
│  │      MemPalace: ChromaDB Semantic Retrieval Layer     │  │
│  │      Wing → Hall → Room → Drawer  (96.6% recall)     │  │
│  └──────┬───────────────────────────────────────────────┘  │
│         │                                                  │
│  ┌──────┴───────────────────────────────────────────────┐  │
│  │   9-Layer LLM Safety Protocol (Source Code-Inspired)  │  │
│  │   Anti-Lazy│Anti-Hallucination│Anti-Fabrication│...   │  │
│  └──────┬───────────────────────────────────────────────┘  │
│         │                                                  │
│  ┌──────┴───────────────────────────────────────────────┐  │
│  │   Observation Pipeline (JSONL + Auto-Summary)         │  │
│  │   + Upgrade Safety System (VERSION_GUARD)             │  │
│  └──────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

7 Subsystems

1. Dynamic Memory Engine

Cross-session memory bridge with signal-file mechanism.

Feature Description
Signal Bridge .memory-process-signal.json bridges session boundaries — Hook writes, next session reads and processes
4-Layer Memory L0 Identity → L1 Active → L2 On-Demand → L3 Archive (lazy-loaded, never full scan)
Weight Decay weight × 0.95^(days/30) — experience decays over time, frequent use auto-upgrades
Key Lesson Weight ≥ 10 → promoted to core lesson, inherited by all similar agents automatically
ACT Early Stop Skips memory processing for simple conversations (< 5 tool calls) to save compute
Forced Archiving Recent Lessons > 10 → auto-archive, Key Lessons capped at 5

How it works:

Session ends → Hook writes signal file
                    ↓
Next session starts → Detects signal → 4-phase processing:
  Phase 1: Analyze previous conversation (decisions, constraints, preferences)
  Phase 2: Match dynamic Agent roles from extracted content
  Phase 3: Auto-update experience weights + decay calculation
  Phase 4: Output confirmation + delete signal file

2. Agent Evolution System

Agents that are not pre-defined — they are dynamically generated, accumulate experience, and auto-register new roles on first encounter.

First encounter:
  Semantic search → No match → Infer category → Create role → Auto-register via Hook
  Role registered in: EVOLUTION_DATA.md + INDEX.md + digest/ + archive/

Second encounter (same task):
  Semantic search → Hit → Load experience → Inject template → Generate evolved Agent

Ongoing evolution:
  Task complete → Weight update (+1/+2/+3) → Decay calc → Experience accumulation
  Weight ≥ 10 → Key Lesson upgrade → All future agents inherit this knowledge

Comparison:

Dimension Default Agents Agent OS
New task No matching role Auto-create + auto-register
Experience Starts from zero every time Weight system + historical inheritance
Dedup Easy to create duplicates Alias mapping prevents duplicates
Forgetting Lost when inactive Archive preserved, Tag Index points to it
Maturity Static Auto-upgrade to Key Lesson

Weight System:

Behavior Weight Change Trigger
Used for new task +2 Historical experience applied to new task
User accepted unmodified +1 User continued without changes
Problem didn't recur +3 Same class of problem doesn't reappear
Reduced task time +2 Similar task completed faster
Code without bugs +2 No subsequent fixes needed

6-Step Unified Routing (reduced from 21 steps to 6 deterministic steps):

  1. Task Fingerprint — Extract keywords (3-5 nouns), tech stack, domain (regex, not LLM inference)
  2. Recipe Match — Dynamic recipe → Fixed recipe → Alias mapping → Domain inference
  3. Role Init — Existing: read stats; New: one-command registration via Hook
  4. Experience Load — Hall: template → Room: tag match → Top 2 by weight → read evolution files
  5. Prompt Generate — Template injection (~700 tokens, no LLM subjective improvisation)
  6. Agent Create — Single role or team (concurrent)

3. Hook Lifecycle (6 Events, 14 Scripts)

Every lifecycle event triggers automated actions. No manual configuration needed.

Event Scripts What It Does
SessionStart 2 Memory processing + Safety protocol validation
PostToolUse 6 File verification + MemPalace sync + Auto-format + Auto-test + Audit log + Role registration
PostToolUseFailure 1 Structured error logging
PreCompact 1 Memory extraction before context compaction
Stop 1 Session summary + Memory persistence (with ACT early-stop)
SubagentStop 1 Agent evolution signal capture

Pre-Execution Guards (3 layers, run BEFORE any action):

Guard Trigger Function
dangerous-command-guard.sh Before Bash execution 3-level danger classification (fatal/high/warn) via awk pattern matching
sensitive-file-guard.sh Before Read/Write/Edit Sensitive file protection from config patterns
secrets-guard.sh Before Write/Edit API key hardcoding detection (AWS, GCP, etc.)

Shared Infrastructure:

  • hook-common.sh — 329 lines of shared functions: JSON parsing, path filtering, 4-level danger detection, debounce, project root finding, formatter caching, audit logging

4. MemPalace Semantic Retrieval

ChromaDB-backed vector search for intelligent memory access. Main storage remains Markdown files; MemPalace provides the semantic search augmentation layer.

Feature Description
5-Tier Decision Tree Known path → Grep → Semantic search → Cross-project discovery → Fallback
4-Layer Stack Wing → Hall → Room → Drawer (96.6% recall rate from MemPalace architecture)
Auto-Sync Edit .md file → PostToolUse Hook → mempalace mine → ChromaDB auto-update
Markdown Primary Vector search is augmentation, not replacement — primary storage is always human-readable Markdown

Retrieval Decision Flow:

Task: "optimize frontend React performance"
        ↓
L0: MEMORY.md → Identify "active project development"
        ↓
L1: EVOLUTION_DATA.md → Find frontend-developer has 5 task experiences
        ↓
L2: evolution/frontend-developer.md → Key Lessons match: React.memo, CSS variables
        ↓
L3: Tag Index shows [performance] has archive → Read archive/frontend-developer/performance.md

5. Safety Protocol (9 Layers)

Derived from Claude Code source code analysis (coordinatorMode.ts, verificationAgent.ts, ssrfGuard.ts). Each layer targets a specific failure mode observed in production LLM usage.

Layer Name Key Rule Example
1 Anti-Lazy Delegation Must specify file/line/I-O — no vague instructions Prohibits "based on your findings, fix the bug"
2 Anti-Hallucination Confidence label required for unverified info No guessing, no inferring beyond verified data
2.5 Proactive Assumption Presentation State assumptions before coding Present all options when multiple interpretations exist
3 Anti-Fabrication Never claim unexecuted commands Must actually run verification commands
3.5 Anti-Self-Rationalization 6 excuse patterns recognized and rejected "The code looks correct based on my reading" ≠ verified
3.6 Surgical Changes Only touch what's necessary (Karpathy principle) Don't "improve" adjacent code, comments, or formatting
4 Non-Anthropomorphic Identity AI system identity declaration No "thinking/feeling/understanding" language
5 Role Locking Strict task scope adherence >3 files touched must justify each one
6 Adversarial Verification Concurrency/boundary/idempotency/isolation tests Parallel requests to create-if-not-exists → duplicates?
7 SSRF Isolation Internal addresses blocked 10.x, 172.16-31.x, 192.168.x, 169.254.x prohibited
8 Tool Design Narrow interface + idempotent + actionable errors No "万能工具" (all-in-one tools)
9 Context Compact Delete newest tool results, preserve system prompt prefix System prefix defines capabilities — never lose it

6 Self-Rationalization Excuses Identified and Rejected:

# Excuse Required Action
1 "The code looks correct based on my reading" Reading ≠ verification, must run commands
2 "The implementer's tests already pass" Implementer is also an LLM, verify independently
3 "This is probably fine" "Probably" ≠ verification, must run
4 "Let me start the server and check the code" No — start the server and actually hit the endpoint
5 "I don't have a browser" Did you check MCP browser tools?
6 "This would take too long" Not your decision to make

6. Observation Pipeline

Every tool call captured, every conversation summarized, searchable by semantic query.

  • Structured JSONL with content-hash dedup (60-second window, prevents duplicate logging)
  • Tool response truncation (500 char max) prevents log bloat from large file outputs
  • Auto-generated Markdown summaries every 50 observations
  • Semantic search: mempalace_search("what did I change last time?")
  • Per-session files: observations/{date}/sess-{id}.jsonl

7. Upgrade Safety

Never lose your configuration after a Claude Code update.

  • VERSION_GUARD.md — Complete validation checklist with executable bash script
  • 8-category dangerous command pattern recognition: sudo, chmod 777, dd, kill -9, > file, env leak, path traversal, code execution entry
  • Protected file list: routing tables, index files, hooks, experience files, archive directories
  • Backup → Diff → Confirm → Execute → Log pattern for all destructive operations

Comparison: Default vs Agent OS

Capability Default Claude Code Agent OS
Cross-session memory ❌ Forgets everything ✅ 4-layer with decay algorithm
Agent experience ❌ Static, pre-defined ✅ Dynamic + weighted accumulation
Auto-testing ❌ Manual ✅ On every code change (30s debounce)
Safety protocol ❌ Basic prompts ✅ 9-layer source-inspired protocol
Audit trail ❌ None ✅ Full JSONL logging + auto-summaries
Upgrade survival ❌ Config may be lost ✅ VERSION_GUARD validation
Semantic search ❌ Keywords only ✅ ChromaDB vector search (96.6% recall)
Conversation replay ❌ Can't look back ✅ Observation pipeline
Experience evolution ❌ Starts fresh each time ✅ Key Lesson auto-upgrade
Prompt enhancement ❌ Raw input ✅ Tree-of-Thought + ReAct + quality gates
Pre-execution guards ❌ None ✅ 3-layer (danger/sensitive/secrets)

Quick Start

One-Minute Install

curl -fsSL https://raw.githubusercontent.com/Markhufei/agent-os/main/scripts/setup.sh | bash

Manual Install

git clone https://github.com/Markhufei/agent-os.git
cd agent-os
./scripts/setup.sh standard

Profiles

./scripts/setup.sh minimal      # Memory + Agent evolution only (~5 files)
./scripts/setup.sh standard     # + Hooks + Safety guards (~20 files)
./scripts/setup.sh production   # Full system, all 7 subsystems (~50 files)

Project Structure

agent-os/
├── README.md                        # This file
├── LICENSE                          # MIT License
├── CONTRIBUTING.md                  # Contribution guidelines
├── CLAUDE.md                        # Main config template
│
├── docs/
│   ├── architecture.md              # System architecture and design philosophy
│   ├── memory-system.md             # Dynamic Memory Engine deep dive
│   ├── agent-evolution.md           # Agent Evolution System deep dive
│   ├── hook-system.md               # Hook lifecycle deep dive
│   ├── safety-protocol.md           # 9-layer safety protocol deep dive
│   ├── mempalace.md                 # MemPalace semantic retrieval deep dive
│   ├── observation-pipeline.md      # Observation capture pipeline
│   ├── upgrade-safety.md            # Upgrade safety system
│   ├── installation.md              # Installation guide
│   ├── customization.md             # Customization guide
│   └── comparison.md                # Comparison with default Claude Code
│
├── src/
│   ├── CLAUDE.md                    # Main config (copy to ~/.claude/)
│   ├── settings.local.json          # Hook configuration template
│   ├── keybindings.json             # Keyboard shortcuts template
│   ├── hooks/                       # 14 hook scripts
│   ├── agents/                      # Agent definition templates
│   ├── rules/                       # Coding rule templates
│   └── skills/                      # Custom skill definitions
│
├── agent-evolution/                  # Agent Evolution System
│   ├── EVOLUTION_DATA.md            # Routing table template
│   ├── AGENT_TEMPLATE.md            # Agent generation template
│   ├── INDEX.md                     # Role index + alias mapping
│   ├── ROLES.md                     # Role definitions
│   ├── evolution/                   # Role experience templates
│   ├── digest/                      # Experience summaries
│   └── archive/                     # Archive directories
│
├── scripts/
│   ├── setup.sh                     # One-click install script
│   ├── validator.py                 # Configuration validator
│   └── cc-switch.sh                 # Model switcher
│
├── examples/
│   ├── minimal/                     # Minimal config (memory + agent)
│   ├── standard/                    # Standard config (+ hooks + safety)
│   └── production/                  # Production-grade full system
│
└── tests/                           # Hook script tests

Who Is This For?

  • Power Users who want production-grade Claude Code with persistent memory and evolving agents
  • Teams building standardized AI workflows across developers
  • Researchers studying LLM safety, agent evolution, and memory architectures
  • Solo Devs tired of repeating the same context every session

Attribution

Created by 黄士斐. If you use this in your project, please give a star and mention the source — it helps more people discover it.


🛡️ Privacy

All hooks run locally. No data leaves your machine. ChromaDB stores vectors on local disk. No telemetry, no phone home.

See our security model for details.


License

MIT — Free to use, modify, distribute. Just keep the copyright notice.


Built by 黄士斐 — from 30+ sessions of debugging, designing, and refining.

About

A self-evolving operating system for Claude Code — dynamic agent evolution, persistent memory, 9-layer safety

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages