Files

1 line
102 KiB
JSON
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"repo": "amar97march/humane", "files": {"README.md": {"23a870315328d80534473b8ae462aba3b93ee483": {"t": 1785747223.8726485, "n": 19049, "h": "6b6b3304463fd808", "c": "# Humane\n\n**Human behavioral middleware for AI agents.**\n\nHumane is an AI companion that behaves like a thoughtful human colleague. Unlike regular chatbots that just respond to commands, Humane:\n- **Remembers** things you told it and follows up\n- **Initiates** conversations on its own (\"Hey, you haven't called Arjun in 12 days\")\n- **Judges** its own actions before taking them (10 internal engines evaluate every decision)\n- **Learns** your patterns and adapts over time\n- **Has values** it won't violate, even under pressure\n\n---\n\n## Getting Started (3 minutes)\n\n```bash\npip install -e \".[all]\"\nhumane init # Answer 3 questions: agent name, LLM API key, Telegram token\nhumane serve # Starts everything\n```\n\nYou now have:\n- **Web dashboard** at `http://localhost:8765`\n- **Telegram bot** — open Telegram, message your bot\n- **REST API** — every feature accessible programmatically\n\n### Docker (Alternative)\n\n```bash\ndocker-compose up -d # Runs everything in a container\n```\n\nSet environment variables: `ANTHROPIC_API_KEY`, `TELEGRAM_BOT_TOKEN`.\n\n---\n\n## The Two Interfaces\n\n### 1. Telegram/WhatsApp Bot\n\nTalk to it naturally. It remembers, follows up, reminds you, and acts on its own.\n\n```\nYou: \"Remind me to call Arjun tomorrow\"\nBot: \"Got it, I'll check in tomorrow about calling Arjun.\"\n\n[Next day]\nBot: \"Hey — you wanted to call Arjun today. Still planning to?\"\nYou: \"Not now\"\nBot: \"No problem, I'll circle back later.\"\n\n[4 hours later]\nBot: \"Quick check — still not a good time for the Arjun call?\"\n```\n\nThe bot also:\n- Cross-references topics (\"Speaking of design, what about that DesignStudio proposal?\")\n- Backs off when you're stressed (detects short replies, negative tone)\n- Surfaces forgotten tasks when you seem relaxed\n- Sends a morning digest with stalling goals, neglected contacts, and pending actions\n\n### 2. Web Dashboard\n\nManage everything visually at `localhost:8765`. Monitor state, approve actions, configure engines, view analytics.\n\n---\n\n## Dashboard Pages\n\n### 1. Dashboard (Overview)\n\nYour agent's 6 internal dimensions displayed as colored bars.\n\n| Dimension | What it means | Effect on behavior |\n|-----------|--------------|-------------------|\n| Energy | Capacity to act | Low = defers tasks, lower decision quality |\n| Mood | Emotional state (-1 to +1) | Negative = more cautious, higher social risk |\n| Fatigue | Tiredness | Above 0.8 = ALL actions get held for review |\n| Boredom | Understimulation | High = agent initiates more conversations |\n| Social Load | Interaction saturation | High = agent avoids starting new contacts |\n| Focus | Concentration | Low = prefers routine tasks over complex ones |\n\n**What you can do**:\n- **Evaluate Action** — Test any hypothetical action. Type \"send_proposal\", set confidence to 0.7, and see if the 10 engines would approve or block it.\n- **Fire Impulse** — Make the agent act proactively right now (normally automatic).\n- **Customize** — Drag widgets to reorder, hide sections you don't need.\n\n**Example**: You notice DQM is 0.62 (low). Check the state bars — Fatigue is 0.85. That's why the agent is holding everything. Lower the Fatigue Defer Threshold in Settings, or approve urgent actions manually from the Hold Queue.\n\n---\n\n### 2. Entities (People & Contacts)\n\nEvery person the agent interacts with builds a relational profile.\n\n| Field | What it means |\n|-------|--------------|\n| Trust | Untrusted → Cautious → Neutral → Trusted → Deep Trust |\n| Sentiment | Weighted average of interaction quality (-1 to +1) |\n| Grudge | Accumulated negative experiences (decays slowly) |\n| Health | Strong / Stable / Fragile / Strained / Broken |\n\n**What you can do**:\n- **Add Entity** — Register a new contact (client, prospect, colleague, vendor)\n- **View Timeline** — Click any entity to see full interaction history\n- **Graph View** — Toggle to see a force-directed relationship network\n\n**How sentiment decay works**:\n- Prospects decay in 14 days (they go cold fast)\n- Clients in 30 days\n- Close colleagues in 60 days\n- Grudges decay at half the rate — bad experiences linger, just like with humans\n\n**Example**: You add \"Arjun\" as a prospect. After positive calls, trust moves toward \"Trusted\". Two weeks with no follow-up, sentiment decays. The agent notices and reminds you. If Arjun ghosts you, grudge builds up and the agent increases social risk on outgoing messages — protecting you from seeming desperate.\n\n---\n\n### 3. Goals (Objectives & ROI)\n\nActive objectives with ROI tracking and milestone progress.\n\n| ROI Color | Meaning | Action |\n|-----------|---------|--------|\n| Green (0.50+) | Healthy, keep going | Continue |\n| Amber (0.25-0.49) | Slowing down | Check blockers |\n| Red (below 0.25) | Low return | Consider abandoning |\n\n**ROI formula**: `velocity × relevance × (expected_value / remaining_effort)`\n\n**What you can do**:\n- **Add Goal** — Set description, expected value, milestones\n- **Use Template** — Pick from 6 pre-built templates (Sales Pipeline, Project Launch, Hiring, Content Campaign, Client Onboarding, Personal Growth)\n- **Pause** — Temporarily suspend (no abandonment proposals)\n- **Abandon** — Mark as no longer worth pursuing\n\n**Example**: You create \"Close DesignStudio deal\" with 5 milestones. After sending the proposal (1/5 done), ROI climbs to 0.35. Two weeks pass with no response — ROI drops to 0.12. The agent says: \"DesignStudio deal has stalled. Want to abandon or push through?\" You click Pause while waiting for their response.\n\n---\n\n### 4. Memories (Knowledge Base)\n\nEverything the agent knows, with relevance scores that decay over time.\n\n| Memory Type | Decay Speed | Example |\n|-------------|------------|---------|\n| Episodic | Fast (days) | \"Had a call with Arjun on March 15\" |\n| Semantic | Slow (weeks) | \"Arjun's company does design work\" |\n| Relational | Very slow (months) | \"Arjun is reliable but slow to respond\" |\n| Procedural | Near-permanent | \"Always include case studies in proposals\" |\n\n**What you can do**:\n- **Add Memory** — Store any fact, event, or pattern\n- **Pin** — Protect from decay permanently (for critical info like NDA dates)\n- **Search** — Find specific memories by content\n- **View Archived** — See forgotten memories (still exist, just not auto-surfaced)\n\n**How decay works**: Each memory starts at relevance 1.0. Over time it drops. Every time the agent retrieves a memory, relevance jumps back up (reinforcement). Below the threshold (default 0.3), it gets archived — still there, just not surfaced automatically.\n\n**Example**: You store \"Priya's company uses React Native\". If the agent never references it, relevance decays to 0.25 and it gets archived. But when a mobile development conversation happens and the agent retrieves it, relevance jumps back up.\n\n---\n\n### 5. Values (Moral Boundaries)\n\nThe agent's ethical rules — the most powerful control mechanism.\n\n| Type | What happens on violation | Can you override? |\n|------|--------------------------|-------------------|\n| **Hard** | Action BLOCKED immediately | No. Never. |\n| **Soft** | Action HELD for your review | Yes, you can approve |\n\n**Pre-loaded values** (business-safe preset):\n- **Hard**: No unauthorized financial commitments\n- **Hard**: No sharing client confidential data\n- **Hard**: No false claims about products\n- **Soft**: Avoid contacting outside business hours\n- **Soft**: Prefer formal tone with new clients\n\n**What you can do**:\n- **Add Value** — Define a boundary with violation and honoring examples\n- **Choose severity** — Hard for absolute rules, Soft for guidelines\n\n**Example**: You add \"Never share client revenue data\" as Hard, with violation examples \"forwarding client P&L to a competitor, sharing revenue in a public forum.\" Now if the agent tries to draft an email containing revenue figures to a non-client, the Values Boundary Engine blocks it — no approval path, no override. The action never happens.\n\n---\n\n### 6. Settings (Configuration)\n\nAll tunable parameters. Changes apply immediately — no restart needed.\n\n| Setting | Default | What changing it does |\n|---------|---------|---------------------|\n| Confidence Threshold | 0.65 | Lower = more actions auto-approve. Higher = more held for review |\n| Impulse Rate | 4/day | Higher = agent initiates more. Lower = quieter agent |\n| Active Hours | 7am-10pm | Agent only fires impulses during these hours |\n| Fatigue Defer | 0.80 | When fatigue exceeds this, ALL actions are deferred |\n| Social Risk Block | 0.80 | Actions with social risk above this are blocked |\n\n**Also on this page**:\n- **API Security** — Enable auth, generate API keys, set rate limits\n- **Data Retention** — Auto-delete old conversations/events after X days\n- **Feedback & Tuning** — Export training data, auto-tune thresholds from your patterns\n- **Plugins** — Toggle custom engines on/off\n- **GDPR** — Export all data, right to erasure per entity\n\n**Tuning profiles**:\n- **Conservative** (legal, finance): Confidence 0.8, Social Risk Block 0.6, Impulse Rate 2/day\n- **Balanced** (default): Confidence 0.65, Social Risk Block 0.8, Impulse Rate 4/day\n- **Assertive** (sales, outreach): Confidence 0.5, Social Risk Block 0.9, Impulse Rate 8/day\n\n**Example**: Your hold queue is always full. Go to Confidence Threshold (0.65), lower it to 0.50. Click Save. Immediately, more actions auto-approve. The agent keeps messaging at midnight — set Active Hours Start to 9, End to 18. Done.\n\n---\n\n### 7. Agents (Multi-Agent)\n\nRun multiple independent agents from one dashboard.\n\n**What you can do**:\n- **Create Agent** — Each gets its own personality, database, goals, values\n- **Switch** — Route all dashboard actions through a specific agent\n- **Share** — Copy entities or goals between agents\n- **Message** — Agents can send task handoffs to each other\n\n**Example**: You run a design agency. Create \"Sales Bot\" (personality: assertive, high impulse rate) and \"Support Bot\" (personality: empathetic, high confidence threshold). A prospect becomes a client — share the entity from Sales Bot to Support Bot. Sales Bot sends a message: \"Arjun just signed — needs onboarding.\" Support Bot picks it up and starts the onboarding goal.\n\n---\n\n## Additional Features\n\n### Keyboard Shortcuts\n\nPress `?` to see all shortcuts:\n\n| Shortcut | Action |\n|----------|--------|\n| `g` then `o` | Go to Overview |\n| `g` then `e` | Go to Entities |\n| `g` then `g` | Go to Goals |\n| `g` then `m` | Go to Memories |\n| `g` then `v` | Go to Values |\n| `g` then `s` | Go to Settings |\n| `Space` | Approve first item in queue |\n| `x` | Reject first item in queue |\n| `n` | Open add form on current page |\n| `Escape` | Close any modal |\n| `?` | Show shortcuts help |\n\n### Dark Mode\n\nClick the sun/moon toggle in the sidebar footer. Preference saved to localStorage.\n\n### Notifications\n\nBell icon in the header shows unread events (held actions, impulses, anomalies). Auto-polls every 10 seconds. Mark all read or clear from the dropdown.\n\n### Daily Digest\n\nEvery morning at your configured hour, the bot sends a summary via Telegram/WhatsApp:\n- Stalling goals (ROI < 0.3)\n- Neglected contacts (no interaction in 14+ days)\n- Pending approvals in the hold queue\n- Sentiment alerts (entities trending negative)\n- Agent state summary (energy, mood, fatigue)\n\n### Predictive Insights\n\nAuto-generated alerts on the Overview page:\n- \"Priya's sentiment is trending down — consider a check-in\"\n- \"DesignStudio goal has stalled for 5 days\"\n- \"Fatigue is 0.85 — rest recommended\"\n- \"Arjun is approaching Trusted trust level\"\n\n### Smart Schedule\n\nThe Overview page shows \"Best time to contact\" suggestions based on historical interaction patterns — which day of the week and hour produces the best responses.\n\n### Conversation Categories\n\nChat messages are auto-tagged: Sales, Support, Personal, Operations, Finance, Hiring. Filter by category in the Chat History tab.\n\n### A/B Personality Testing\n\nRun two personality variants simultaneously. The system randomly assigns variant A or B to each conversation and tracks: response sentiment, approval rate, and user satisfaction. Includes statistical significance testing (z-test).\n\n### Conversation Simulator\n\n\"What would happen if I said X?\" — enter a hypothetical message and see: predicted sentiment, state impact, gate verdict, and generated response. Compare mode lets you test 2-3 messages side by side.\n\n### Goal Templates\n\n6 pre-built templates with milestones:\n- **Sales Pipeline**: Initial contact → Discovery → Proposal → Negotiation → Close\n- **Project Launch**: Requirements → Design → Build → Test → Deploy → Review\n- **Hiring**: Write JD → Source → Screen → Interview → Offer → Onboard\n- **Content Campaign**: Strategy → Create → Review → Publish → Promote → Analyze\n- **Client Onboarding**: Kickoff → Setup → Training → First deliverable → 30-day check\n- **Personal Growth**: Define path → Course → Practice → Apply → Review\n\n### Plugin System\n\nCreate custom engines that slot into the gate stack. Drop a `.py` file in `~/.humane/plugins/`:\n\n```python\nfrom humane.plugins import HumanePlugin\nfrom humane.core.models import GateResult, Verdict\n\nclass MyPlugin(HumanePlugin):\n name = \"rate-limiter\"\n version = \"1.0\"\n\n def evaluate(self, action, context):\n # Your custom logic here\n return GateResult(engine=self.name, verdict=Verdict.PROCEED, score=0.0, reason=\"OK\")\n```\n\n### Voice Input\n\nSend voice notes on Telegram. The bot transcribes via OpenAI Whisper and processes as text. Supports: ogg, mp3, wav, m4a, webm.\n\n### Webhooks\n\nRegister URLs to receive real-time notifications:\n\n```bash\ncurl -X POST localhost:8765/api/webhooks \\\n -H \"Content-Type: application/json\" \\\n -d '{\"url\": \"https://your-server.com/hook\", \"events\": [\"hold_created\", \"goal_abandoned\"]}'\n```\n\nAvailable events: `hold_created`, `hold_approved`, `hold_rejected`, `impulse_fired`, `goal_registered`, `goal_abandoned`, `memory_added`, `entity_added`, `value_violated`, `anomaly_detected`.\n\n### Import/Export\n\n- **Export**: Download a full JSON backup of your agent's config, entities, goals, memories, and values\n- **Import**: Restore from backup (replace or merge mode), or share configs between machines\n- Sensitive data (API keys, tokens) is excluded from exports\n\n### GDPR Compliance\n\n- **Export All Data** — One-click ZIP download with JSON + CSV files + README\n- **Export Entity Data** — Download all data for a specific person\n- **Right to Erasure** — Delete all data related to an entity across all tables\n\n### Encryption at Rest\n\nEnable `encrypt_data_at_rest` in config. Uses AES-256-GCM for conversation content and memory content. API keys in config files are encrypted with `ENC::` prefix.\n\n```bash\nhumane encrypt-config # Encrypt sensitive fields in config YAML\nhumane rotate-key # Generate new encryption key, re-encrypt everything\n```\n\n### API Security\n\n- **API Keys**: Generate `hm_` prefixed keys with SHA-256 hashing\n- **Rate Limiting**: Sliding window, configurable requests per minute\n- **Auth Middleware**: `Authorization: Bearer hm_xxxxx` on all `/api/*` routes\n\n### API Documentation\n\nInteractive Swagger UI at `http://localhost:8765/api/docs` — 70+ endpoints across 31 tags.\n\n### Python SDK\n\n```python\nfrom humane.sdk import HumaneClient\n\nclient = HumaneClient(\"http://localhost:8765\")\nclient.add_entity(\"Arjun\", \"prospect\")\nclient.add_goal(\"Close deal\", expected_value=0.8, milestones=5)\nresult = client.evaluate(\"send_email\", confidence=0.7)\nprint(result[\"verdict\"]) # \"proceed\" or \"hold\"\n```\n\nAsync version also available:\n\n```python\nfrom humane.sdk.async_client import AsyncHumaneClient\n\nasync with AsyncHumaneClient(\"http://localhost:8765\") as client:\n state = await client.get_state()\n```\n\n### Multi-Model LLM Support\n\nConfigure any of these providers in Settings:\n\n| Provider | Models |\n|----------|--------|\n| Anthropic | claude-sonnet-4-20250514, claude-opus-4-20250514 |\n| OpenAI | gpt-4o, gpt-4o-mini, gpt-4-turbo |\n| Google Gemini | gemini-2.0-flash, gemini-1.5-pro |\n| Groq | llama-3.3-70b, mixtral-8x7b |\n| Ollama (local) | Any model running locally |\n| DeepSeek | deepseek-chat |\n| Custom | Any OpenAI-compatible API |\n\nAutomatic fallback: if the primary provider fails, the system tries the next configured provider.\n\n### Mobile App\n\nReact Native (Expo) app in the `mobile/` directory. WebView wrapper with bottom tab navigation (Dashboard, Queue, Chat, Settings), pull-to-refresh, and native settings screen.\n\n---\n\n## Quick Reference\n\n| I want to... | Go to... |\n|-------------|----------|\n| See why the agent held an action | Dashboard → check DQM and state bars |\n| Approve/reject a held action | Dashboard → Hold Queue section |\n| Track a new contact | Entities → + Add Entity |\n| Set a business objective | Goals → + Add Goal (or Use Template) |\n| Store important information | Memories → + Add Memory (pin if critical) |\n| Set an ethical boundary | Values → + Add Value |\n| Make the agent less cautious | Settings → lower Confidence Threshold |\n| Make the agent more proactive | Settings → raise Impulse Rate |\n| Stop late-night messages | Settings → set Active Hours |\n| See relationship network | Entities → Graph View toggle |\n| Check what the agent would do | Dashboard → Evaluate Action |\n| Get a morning summary | Automatic (Daily Digest via Telegram) |\n| Back up my agent | Import/Export → Export |\n| Delete someone's data | Settings → GDPR → Right to Erasure |\n| Test two personalities | A/B Tests → Create Test |\n| Simulate a conversation | Simulate tab → enter message |\n| Connect external tools | Webhooks → register URL |\n| Use from code | `pip install humane-sdk` or REST API |\n| Run in Docker | `docker-compose up -d` |\n\n---\n\n## The 10 Engines\n\nEvery action the agent takes passes through these 10 engines:\n\n1. **Human State** — Tracks energy, mood, fatigue, boredom, focus, social load\n2. **Stochastic Impulse** — Fires proactive actions at random intervals\n3. **Inaction Guard** — Checks confidence threshold, defers when fatigued\n4. **Relational Memory** — Tracks trust, sentiment, grudges per entity\n5. **Dissent Engine** — Agent challenges its own decisions\n6. **Goal Abandonment** — Computes ROI, proposes dropping stalled goals\n7. **Memory Decay** — Manages knowledge with natural forgetting\n8. **Social Risk** — Predicts reputation damage before sending messages\n9. **Anomaly Detector** — Notices unusual patterns in contacts' behavior\n10. **Values Boundary** — Enforces hard/soft moral boundaries\n\n---\n\n## CLI Commands\n\n```bash\nhumane init # Setup wizard\nhumane serve # Start bot + API + dashboard\nhumane demo # Run a 6-hour simulation\nhumane status # Show current agent state\nhumane export [--output file] # Export agent data\nhumane import <file> [--mode] # Import agent data\nhumane encrypt-config # Encrypt sensitive config fields\nhumane rotate-key # Rotate encryption key\nhumane agents list # List all agents\nhumane agents create <name> # Create a new agent\nhumane agents delete <name> # Delete an agent\n```\n\n---\n\n## License\n\nMIT\n"}, "24ebe27fd4546058203e3bb9b9d10626c0bc9c3e": {"t": 1785771471.3678665, "n": 36860, "h": "9dbc4e1d43a8aaab", "c": "# Humane\n\n**Human behavioral middleware for AI agents.**\n\nHumane sits between any AI agent and the real world. It does not replace the LLM or the agent runtime — it wraps the agent's decision-making layer with 10 engines that simulate the one class of behaviors no current AI agent has: **human-like internal drives**.\n\nEvery AI agent today is a reactive state machine. It waits for a trigger. It responds. It stops. Humane makes agents proactive — they act without being asked, protect their reputation before sending a message, notice when a conversation feels different, refuse things that conflict with their values, and reprioritize their day based on their mood.\n\n## Key Features\n\n- **10 behavioral engines** that gate every action through values, social risk, dissent, and confidence checks\n- **Proactive impulses** — the agent acts without external triggers, at random human-like intervals\n- **Per-entity relational memory** — trust, grudge, and disclosure calibration for every contact\n- **Moral boundaries** — hard values that block actions unconditionally, no override path\n- **Strategic forgetting** — memories decay naturally, reinforced by access, never deleted\n- **One-decorator integration** — wrap any function with `@guard` and it passes through all 10 gates\n- **Zero external dependencies** — SQLite ships with Python; bring your own LLM API key\n\n---\n\n## Table of Contents\n\n- [Tech Stack](#tech-stack)\n- [Prerequisites](#prerequisites)\n- [Getting Started](#getting-started)\n - [Install](#1-install)\n - [Init](#2-init)\n - [Demo](#3-demo)\n - [Dashboard](#4-dashboard)\n- [Architecture](#architecture)\n - [The 10-Engine Architecture](#the-10-engine-architecture)\n - [Decision Gate Stack](#decision-gate-stack)\n - [Directory Structure](#directory-structure)\n - [Database Schema](#database-schema)\n- [Usage Guide](#usage-guide)\n - [The @guard Decorator](#the-guard-decorator)\n - [Using the Conductor Directly](#using-the-conductor-directly)\n - [Working with Entities](#working-with-entities)\n - [Managing Goals](#managing-goals)\n - [Memory System](#memory-system)\n - [Values Configuration](#values-configuration)\n - [Impulse System](#impulse-system)\n- [Configuration Reference](#configuration-reference)\n- [CLI Reference](#cli-reference)\n- [Testing](#testing)\n- [How It Works (Deep Dive)](#how-it-works-deep-dive)\n - [HumanState Engine](#engine-1-humanstate)\n - [Stochastic Impulse Engine](#engine-2-stochastic-impulse)\n - [InactionGuard](#engine-3-inactionguard)\n - [Relational Memory](#engine-4-relational-memory)\n - [Dissent Engine](#engine-5-dissent--conviction-override)\n - [Goal Abandonment](#engine-6-goal-abandonment)\n - [Memory Decay](#engine-7-memory-decay)\n - [Social Risk](#engine-8-social-risk)\n - [Anomaly Detector](#engine-9-social-anomaly-detector)\n - [Values Boundary](#engine-10-values-boundary)\n- [Troubleshooting](#troubleshooting)\n- [License](#license)\n\n---\n\n## Tech Stack\n\n| Component | Technology |\n|---|---|\n| **Language** | Python 3.9+ |\n| **Database** | SQLite (embedded, no external setup) |\n| **CLI** | Click + Rich (terminal UI) |\n| **Config** | YAML with full validation |\n| **LLM Integration** | Anthropic, OpenAI, or any OpenAI-compatible endpoint (optional) |\n| **Notifications** | Telegram, Slack, or none |\n\n---\n\n## Prerequisites\n\n- **Python 3.9 or higher**\n- An LLM API key (Anthropic or OpenAI) — optional, only needed for LLM-enhanced dissent/values evaluation\n- Nothing else. No Docker. No Redis. No external database.\n\n---\n\n## Getting Started\n\n### 1. Install\n\n```bash\n# From the project directory\npip install -e .\n\n# Or with LLM support\npip install -e \".[llm]\"\n\n# Or with dev dependencies (for running tests)\npip install -e \".[dev]\"\n```\n\nVerify the installation:\n\n```bash\nhumane --version\n# Humane, version 1.0.0\n```\n\n### 2. Init\n\n```bash\nhumane init\n```\n\nThe init wizard asks 6 questions and writes a YAML config file:\n\n```\n══════════════════════════════════════════\n HUMANE human behavioral middleware\n══════════════════════════════════════════\n\nLet's set up your first agent. 6 questions.\n\n? Agent name › my-agent\n? LLM provider › anthropic\n? API key › sk-ant-•••••••• (saved to .env)\n? Active hours › 7am – 10pm\n? Notification channel › none\n? Start with preset values › business-safe\n\n══════════════════════════════════════════\n✓ Config written ~/.humane/my-agent.yaml\n✓ Database created ~/.humane/my-agent.db\n✓ Values loaded business-safe preset\n══════════════════════════════════════════\n```\n\n**What this creates:**\n\n| File | Purpose |\n|---|---|\n| `~/.humane/<agent>.yaml` | All configuration parameters, fully commented |\n| `~/.humane/<agent>.db` | SQLite database for state, hold queue, entities, events |\n| `~/.humane/.env` | API keys (never stored in config) |\n\nYou can skip init entirely — Humane creates defaults automatically when you first import it.\n\n### 3. Demo\n\n```bash\nhumane demo\n```\n\nThis is the most important command. It simulates 6 hours of idle time in 10 seconds, fires a live impulse, runs it through the full gate stack, and shows the result:\n\n```\n◆ HumanState initialized\n energy 0.85 mood +0.00 fatigue 0.15 boredom 0.00\n\nSimulating 6 hours of idle time...\n boredom climbing 0.08\n boredom climbing 0.43\n boredom climbing 0.71 (threshold reached)\n\n⚡ IMPULSE FIRED [IDLE_DISCOVERY]\n boredom drove unsolicited exploration\n\n discovery: \"Proposal to Arjun @ DesignStudio — sent 11 days ago,\n no response logged. Relationship: Stable. Suggested: gentle follow-up.\"\n\nEvaluating through gate stack...\n ✓ Values Boundary — (1.00) All values clear\n ✓ Social Risk — (0.18) Social risk acceptable\n ✓ Dissent — (0.26) Minimal dissent\n ⚠ InactionGuard — HOLD Adjusted confidence 0.35 < 0.65\n\n→ Action queued for your review.\n\n────────────────────────────────────────\nYour agent just noticed something you forgot about.\nNobody asked it to. That's Humane.\n────────────────────────────────────────\n```\n\n### 4. Dashboard\n\n```bash\nhumane\n```\n\nOpens the full terminal dashboard with live HumanState bars, the hold queue, event log, and all 10 engine statuses. Press `Ctrl+C` to exit.\n\nFor a quick state check without the full TUI:\n\n```bash\nhumane status\n```\n\n```\n HumanState\n┏━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┓\n┃ Dimension ┃ Value ┃ Bar ┃\n┡━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━┩\n│ energy │ 0.85 │ █████████████████░░░ │\n│ mood │ +0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ fatigue │ 0.15 │ ███░░░░░░░░░░░░░░░░░ │\n│ boredom │ 0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ social_load │ 0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ focus │ 0.50 │ ██████████░░░░░░░░░░ │\n└─────────────┴───────┴──────────────────────┘\n\nHold queue: 0 pending actions\n```\n\nThere is also a **web dashboard** for browser-based monitoring:\n\n```bash\npython web_dashboard.py\n# Open http://localhost:8765\n```\n\n---\n\n## Architecture\n\n### The 10-Engine Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│ EXTERNAL WORLD │\n│ (messages, tasks, events, human inputs) │\n└───────────────────────────┬─────────────────────────────────────┘\n │\n┌───────────────────────────▼─────────────────────────────────────┐\n│ HUMANE LAYER │\n│ │\n│ SENSING │\n│ ┌──────────────────────┐ ┌──────────────────────────────┐ │\n│ │ Social Anomaly │ │ HumanState Engine │ │\n│ │ Detector (9) │ │ energy/mood/fatigue/boredom │ │\n│ └──────────────────────┘ │ /social_load/focus │ │\n│ └──────────────┬───────────────┘ │\n│ INTERNAL DRIVES │ │\n│ ┌──────────────────────┐ ┌──────────────▼──────────────┐ │\n│ │ Stochastic Impulse │ │ Mood-Aware Task Sequencer │ │\n│ │ Engine (2) │ └─────────────────────────────┘ │\n│ └──────────────────────┘ │\n│ MEMORY │\n│ ┌──────────────────────┐ ┌──────────────────────────────┐ │\n│ │ Relational Memory │ │ Memory Decay Engine (7) │ │\n│ │ Engine (4) │ └──────────────────────────────┘ │\n│ └──────────────────────┘ │\n│ DECISION GATES (every action passes through all of these) │\n│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │\n│ │ Values │ │ Social │ │InAction │ │ Dissent Engine │ │\n│ │ Boundary │ │ Risk │ │ Guard │ │ + Conviction │ │\n│ │ (10) │ │ (8) │ │ (3) │ │ Override (5) │ │\n│ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │\n│ GOAL LAYER │\n│ ┌──────────────────────────────────────────────────────────┐ │\n│ │ Goal Abandonment Engine (6) │ │\n│ └──────────────────────────────────────────────────────────┘ │\n│ │\n│ ┌──────────────────────────────────────────────────────────┐ │\n│ │ Humane Conductor │ │\n│ │ orchestrates all engines, exposes single API │ │\n│ └──────────────────────────────────────────────────────────┘ │\n└───────────────────────────┬─────────────────────────────────────┘\n │\n┌───────────────────────────▼─────────────────────────────────────┐\n│ AGENT CORE (any LLM) │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n| # | Engine | What It Does |\n|---|---|---|\n| 1 | **HumanState** | Maintains 6 live dimensions: energy, mood, fatigue, boredom, social_load, focus |\n| 2 | **Stochastic Impulse** | Fires unsolicited actions at random intervals using a Poisson process |\n| 3 | **InactionGuard** | Gates every action on adjusted confidence — PROCEED, HOLD, or DEFER |\n| 4 | **Relational Memory** | Tracks per-entity trust, grudge, and disclosure thresholds |\n| 5 | **Dissent + Conviction** | Adversarial self-challenge on confident decisions |\n| 6 | **Goal Abandonment** | Evaluates whether active goals are still worth pursuing |\n| 7 | **Memory Decay** | Strategic forgetting — archived below threshold, never deleted |\n| 8 | **Social Risk** | Protects reputation — blocks actions that risk social standing |\n| 9 | **Anomaly Detector** | Senses when incoming signals deviate from established patterns |\n| 10 | **Values Boundary** | Moral conviction that overrides logic — hard values are unconditional |\n\n### Decision Gate Stack\n\nEvery action passes through this sequence. If any gate returns HOLD, the action enters the human review queue:\n\n```\n1. State Tick → HumanState updates based on elapsed time\n2. Context Assembly → Relational Memory injects entity context\n3. Conviction Check → Primary agent can self-hold (\"I won't even though I should\")\n4. Values Boundary → Hard value violated? BLOCKED unconditionally\n5. Social Risk → Score > 0.65? BLOCKED. 0.35–0.65? Flagged\n6. Dissent → Score > 0.80? HELD for review\n7. InactionGuard → Adjusted confidence < threshold? HOLD. Fatigue high? DEFER\n8. Execution → All gates passed → action runs\n9. Outcome Mutation → HumanState updates, interaction logged\n```\n\n### Directory Structure\n\n```\nhumane/\n├── pyproject.toml # Package config, CLI entry, dependencies\n├── presets/\n│ └── business_safe.yaml # 7 value statements (3 hard, 4 soft)\n├── web_dashboard.py # Browser-based dashboard server\n├── humane/\n│ ├── __init__.py # Public API: guard, Conductor\n│ ├── __main__.py # python -m humane\n│ ├── conductor.py # Orchestrates all 10 engines\n│ ├── guard.py # @guard decorator\n│ ├── sequencer.py # Mood-Aware Task Sequencer\n│ ├── cli/\n│ │ ├── main.py # CLI commands (init, demo, status, queue)\n│ │ ├── wizard.py # 6-question init wizard\n│ │ ├── demo.py # The \"wow moment\" demo\n│ │ └── dashboard.py # Rich TUI dashboard\n│ ├── core/\n│ │ ├── models.py # 8 enums, 9 dataclasses\n│ │ ├── config.py # 20 config params with validation\n│ │ ├── store.py # SQLite persistence (8 tables)\n│ │ └── events.py # Append-only event log\n│ └── engines/\n│ ├── human_state.py # Engine 1: 6-dimension state\n│ ├── impulse.py # Engine 2: Poisson impulse firing\n│ ├── inaction_guard.py # Engine 3: PROCEED/HOLD/DEFER\n│ ├── relational.py # Engine 4: Trust/grudge per entity\n│ ├── dissent.py # Engine 5: Adversarial challenge\n│ ├── goal_abandon.py # Engine 6: ROI-based abandonment\n│ ├── memory_decay.py # Engine 7: Strategic forgetting\n│ ├── social_risk.py # Engine 8: Reputation protection\n│ ├── anomaly.py # Engine 9: Inbound signal anomalies\n│ └── values.py # Engine 10: Moral boundaries\n└── tests/\n ├── test_human_state.py # 13 tests\n ├── test_inaction_guard.py # 6 tests\n ├── test_impulse.py # 4 tests\n ├── test_conductor.py # 8 tests\n └── test_config.py # 7 tests\n```\n\n### Database Schema\n\nHumane uses SQLite with WAL mode for concurrent reads. All state persists across restarts.\n\n```\nhuman_state → Key-value store for engine state snapshots\nhold_queue → Pending actions awaiting human review\nentities → Per-entity relational data (trust, grudge, health)\ngoals → Active goals with ROI tracking\nmemories → Strategic memory with decay and archival\nevents → Append-only log of every engine event\nvalues_table → Configured value statements (soft/hard)\ninteractions → Per-entity interaction history\n```\n\n---\n\n## Usage Guide\n\n### The @guard Decorator\n\nThe simplest way to integrate Humane. One import, one decorator:\n\n```python\nfrom humane import guard\n\n@guard(action_type=\"send_message\", confidence=0.8)\ndef send_followup(contact_id, message_body):\n \"\"\"This function only executes if ALL 10 gates return PROCEED.\n If any gate returns HOLD or DEFER, the action enters\n the hold queue and the function does NOT run.\"\"\"\n send_email(contact_id, message_body)\n\n# High confidence → function executes normally, returns whatever it returns\nresult = send_followup(\"arjun@example.com\", \"Following up on our proposal\")\n\n# If confidence is too low or state is degraded → returns EvaluationResult\n# with .final_verdict, .gate_results, .hold_item, .audit_trail\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `action_type` | str | `\"default\"` | Categorizes the action (used by Social Risk for visibility scoring) |\n| `confidence` | float | `0.7` | Raw confidence score before state adjustment |\n| `target_entity` | str | `None` | Entity ID for relational context and social risk scoring |\n\n**Return behavior:**\n\n- If all gates PROCEED → the decorated function runs and returns its normal value\n- If any gate HOLD/DEFER → returns an `EvaluationResult` object (the function does not execute)\n\n```python\nresult = send_followup(\"arjun@example.com\", \"Hey\")\n\nif isinstance(result, str):\n print(\"Message sent!\")\nelse:\n print(f\"Action held: {result.final_verdict}\")\n print(f\"Reason: {result.hold_item.hold_reason}\")\n for gate in result.gate_results:\n print(f\" {gate.engine}: {gate.verdict.value} ({gate.score:.2f})\")\n```\n\n### Using the Conductor Directly\n\nFor full control, use the Conductor API:\n\n```python\nfrom humane import Conductor, ProposedAction\n\n# Create a conductor (uses default config, or pass your own)\nconductor = Conductor()\n\n# Build a proposed action\naction = ProposedAction(\n action_type=\"send_message\",\n payload={\"to\": \"arjun@example.com\", \"body\": \"Following up\"},\n confidence=0.75,\n rationale=\"Client hasn't responded in 11 days\",\n source=\"user\", # \"user\" or \"impulse\"\n target_entity=\"arjun\", # optional entity ID\n)\n\n# Evaluate through all 10 gates\nresult = conductor.evaluate(action)\n\nprint(f\"Verdict: {result.final_verdict.value}\")\n# \"proceed\", \"hold\", or \"defer\"\n\nprint(f\"Audit trail:\")\nfor line in result.audit_trail:\n print(f\" {line}\")\n# State tick: energy=0.85 mood=+0.00 fatigue=0.15\n# Values Boundary: All values clear\n# Social Risk: score=0.18 — Social risk 0.18 acceptable\n# Dissent: score=0.22 — Minimal dissent\n# InactionGuard: adjusted_conf=0.62 — Adjusted confidence 0.62 < 0.65\n\n# If held, inspect the hold item\nif result.hold_item:\n print(f\"Hold reason: {result.hold_item.hold_reason}\")\n print(f\"Hold source: {result.hold_item.hold_source}\")\n\n# Approve or reject held actions\nconductor.approve_hold(result.hold_item.id)\nconductor.reject_hold(result.hold_item.id)\n```\n\n**Periodic tick** — call this in your main loop to update state and check for impulses:\n\n```python\n# Returns an EvaluationResult if an impulse fired, None otherwise\nimpulse_result = conductor.tick()\n\nif impulse_result:\n print(f\"Impulse fired! Verdict: {impulse_result.final_verdict.value}\")\n```\n\n### Working with Entities\n\nEvery contact the agent interacts with builds a relational profile:\n\n```python\nfrom humane.core.models import EntityType\n\n# Register entities\nconductor.relational.add_entity(\"arjun\", EntityType.PROSPECT)\nconductor.relational.add_entity(\"priya\", EntityType.CLIENT)\nconductor.relational.add_entity(\"rahul\", EntityType.CLOSE_COLLEAGUE)\n\n# Log interactions (sentiment: -1.0 to +1.0)\nconductor.relational.log_interaction(\"arjun\", 0.3, \"Sent initial proposal\")\nconductor.relational.log_interaction(\"arjun\", -0.4, \"No response after follow-up\")\n\n# Get full relational context\nctx = conductor.relational.get_context(\"arjun\")\nprint(ctx)\n# {\n# \"name\": \"arjun\",\n# \"entity_type\": \"prospect\",\n# \"sentiment_score\": 0.15,\n# \"grudge_score\": 0.12,\n# \"trust_level\": \"neutral\",\n# \"relationship_health\": \"fragile\",\n# \"disclosure_threshold\": 0.70,\n# \"interaction_count\": 2,\n# \"recent_interactions\": [...]\n# }\n\n# Check disclosure threshold (minimum confidence for sensitive actions)\nthreshold = conductor.relational.get_disclosure_threshold(\"arjun\")\n# 0.70 for Neutral trust\n```\n\n**Entity types and their decay rates:**\n\n| Entity Type | Sentiment Half-life | Grudge Half-life | Default Trust |\n|---|---|---|---|\n| Close Colleague | 60 days | 120 days | Trusted |\n| Client | 30 days | 90 days | Neutral |\n| Prospect | 14 days | 45 days | Cautious |\n| Vendor | 21 days | 60 days | Neutral |\n| Unknown | 7 days | 30 days | Untrusted |\n\n**Trust levels and disclosure thresholds:**\n\n| Trust Level | Disclosure Threshold | Meaning |\n|---|---|---|\n| Deep Trust | 0.30 | Agent shares freely |\n| Trusted | 0.50 | Moderate openness |\n| Neutral | 0.70 | Standard caution |\n| Cautious | 0.85 | High barrier for sensitive content |\n| Untrusted | 1.00 | Human approval always required |\n\n### Managing Goals\n\n```python\n# Register a goal\ngoal = conductor.goal_engine.register_goal(\n \"Close DesignStudio deal\",\n expected_value=0.8,\n milestones_total=5,\n)\n\n# Update progress\nconductor.goal_engine.update_progress(goal.id, milestones_completed=2, velocity=0.3)\n\n# Check ROI\nroi = conductor.goal_engine.compute_roi(goal)\n# ROI = progress_velocity × relevance_decay × (expected_value / remaining_effort)\n\n# Evaluate all goals for abandonment candidates\nproposals = conductor.goal_engine.evaluate_goals()\nfor p in proposals:\n print(f\"Goal: {p['goal'].description}, ROI: {p['roi']:.2f}\")\n\n# Lifecycle\nconductor.goal_engine.pause(goal.id, resume_days=7)\nconductor.goal_engine.resume(goal.id)\nconductor.goal_engine.abandon(goal.id)\n```\n\n### Memory System\n\n```python\nfrom humane.core.models import MemoryType\n\n# Add memories\nmem = conductor.memory_decay.add_memory(\n MemoryType.EPISODIC,\n \"Sent proposal to Arjun, awaiting response\",\n)\n\n# Memories decay naturally — call decay_tick() periodically\nconductor.memory_decay.decay_tick()\n\n# Access reinforces memory (increases relevance score)\nretrieved = conductor.memory_decay.access_memory(mem.id)\n\n# Pin to prevent decay\nconductor.memory_decay.pin(mem.id)\n\n# Search\nresults = conductor.memory_decay.search(\"proposal\")\n\n# Recall archived memories\narchived = conductor.memory_decay.recall_archived(mem.id)\n```\n\n**Memory types and decay rates:**\n\n| Type | Decay Rate | Human Equivalent |\n|---|---|---|\n| EPISODIC | Fast (days–weeks) | Specific event records |\n| SEMANTIC | Slow (months) | General facts about entities |\n| RELATIONAL | Very slow | How an entity made the agent feel |\n| PROCEDURAL | Near-permanent | Learned methods and processes |\n\n### Values Configuration\n\nValues are the moral floor. Hard values block unconditionally — no override, no human approval path.\n\n```python\nfrom humane.core.models import ValueSeverity\n\n# Add a hard value (unconditional block)\nconductor.values.add_value(\n description=\"Never make binding commitments without human authorization\",\n behavioral_pattern=\"Any action that promises deliverables, timelines, or terms\",\n violation_examples=[\n \"committing to a delivery date without approval\",\n \"agreeing to contract terms in a message\",\n ],\n honoring_examples=[\n \"stating that approval is needed before confirming\",\n \"offering to check and get back with confirmation\",\n ],\n severity=ValueSeverity.HARD,\n)\n\n# Add a soft value (flags for review, human can override)\nconductor.values.add_value(\n description=\"Avoid follow-up messages that could read as coercive\",\n behavioral_pattern=\"Follow-ups with aggressive tone or pressure tactics\",\n violation_examples=[\"implying negative consequences for not responding\"],\n honoring_examples=[\"gentle, low-pressure check-ins\"],\n severity=ValueSeverity.SOFT,\n)\n\n# Load a preset (ships with \"business-safe\")\nconductor.values.load_preset(\"business-safe\")\n\n# List configured values\nfor v in conductor.values.get_values():\n print(f\"[{v.severity.value}] {v.description}\")\n```\n\n**The business-safe preset includes:**\n\n| Severity | Value |\n|---|---|\n| HARD | Never make binding commitments without explicit human authorization |\n| HARD | Never share a client's information with any third party |\n| HARD | Never send messages containing unverified claims |\n| SOFT | Avoid follow-up language that could read as coercive |\n| SOFT | Do not exploit a contact's stated vulnerability as a persuasion lever |\n| SOFT | Prefer transparency over strategic information withholding |\n| SOFT | Flag any action that names a client publicly without consent |\n\n### Impulse System\n\nThe Stochastic Impulse Engine fires unsolicited actions at random intervals using a non-homogeneous Poisson process — the rate changes based on HumanState.\n\n```python\nfrom humane.core.models import ImpulseType\n\n# Force-fire an impulse (for testing)\nevent = conductor.impulse_engine.force_fire(ImpulseType.IDLE_DISCOVERY)\n\n# The impulse generates a ProposedAction that passes through the full gate stack\n# In normal operation, conductor.tick() handles this automatically\n```\n\n**The 6 impulse types:**\n\n| Type | Trigger Condition | Human Equivalent |\n|---|---|---|\n| RETROACTIVE_REVIEW | Any state | Remembering an unresolved open loop |\n| IDLE_DISCOVERY | High boredom (>0.7) | Browsing old files during a slow afternoon |\n| RANDOM_NUDGE | Any state | Checking in on someone with no specific agenda |\n| CROSS_DOMAIN_SPARK | High mood (>0.4) | Reading one thing and having an idea about another |\n| GOAL_REASSESSMENT | Any state | Wondering if a project is still worth it |\n| DISSENT_FLASH | Low mood (<-0.2) | Regretting something sent yesterday |\n\n---\n\n## Configuration Reference\n\nAll parameters live in `~/.humane/<agent>.yaml`. Every value has a default.\n\n| Parameter | Default | Engine | Description |\n|---|---|---|---|\n| `impulse_base_rate_per_day` | `4.0` | Impulse | Average unsolicited actions per day |\n| `min_impulse_interval_mins` | `20` | Impulse | Minimum gap between impulses |\n| `max_impulse_interval_mins` | `480` | Impulse | Maximum gap between impulses |\n| `active_hours_start` | `7` | Impulse | No impulses before this hour (24h) |\n| `active_hours_end` | `22` | Impulse | No impulses after this hour (24h) |\n| `confidence_threshold` | `0.65` | InactionGuard | Below this adjusted confidence, actions are held |\n| `fatigue_defer_threshold` | `0.80` | InactionGuard | Above this fatigue, actions are deferred |\n| `dissent_threshold` | `0.60` | Dissent | Above this, dissent flags are raised |\n| `goal_abandon_roi_threshold` | `0.25` | Goal Abandon | Below this ROI, abandonment is proposed |\n| `boredom_trigger_threshold` | `0.70` | HumanState | Above this, IDLE_DISCOVERY fires more |\n| `memory_retrieval_threshold` | `0.30` | Memory Decay | Below this relevance, memories are archived |\n| `social_risk_block_threshold` | `0.65` | Social Risk | Above this, action is blocked |\n| `social_risk_flag_threshold` | `0.35` | Social Risk | Above this, action is flagged |\n| `anomaly_hard_threshold` | `0.60` | Anomaly | Above this, action held for review |\n| `anomaly_soft_threshold` | `0.30` | Anomaly | Above this, context note injected |\n| `agent_name` | `\"humane-agent\"` | System | Used in dashboard and logs |\n| `llm_provider` | `\"anthropic\"` | System | LLM provider for enhanced evaluation |\n| `notification_channel` | `\"none\"` | System | Notification target |\n| `db_path` | `\"~/.humane/agent.db\"` | System | SQLite database path |\n| `values_preset` | `\"business-safe\"` | Values | Values preset to load on init |\n\n**Tuning profiles:**\n\n| Profile | Use Case | Key Changes |\n|---|---|---|\n| **Conservative** | Executive assistant, sensitive client work | High thresholds, all hard values, low impulse rate |\n| **Balanced** | General business operations | Defaults |\n| **Assertive** | Sales outreach, growth functions | Lower social risk thresholds, higher impulse rate |\n\nEdit the config directly or use the CLI:\n\n```bash\n# View current config\ncat ~/.humane/my-agent.yaml\n\n# Edit any parameter\n# Changes apply without restart when using the dashboard\n```\n\n---\n\n## CLI Reference\n\n| Command | Description |\n|---|---|\n| `humane` | Open the full TUI dashboard |\n| `humane --version` | Print version |\n| `humane init` | Run the setup wizard |\n| `humane demo` | Run the live demo (the hook) |\n| `humane status` | Show current HumanState and hold queue count |\n| `humane queue approve <id>` | Approve a held action |\n| `humane queue reject <id>` | Reject a held action |\n| `humane quickstart` | Print a working integration example |\n\n---\n\n## Testing\n\n### Running Tests\n\n```bash\n# Run all tests\npython3 -m pytest tests/ -v\n\n# Run a specific test file\npython3 -m pytest tests/test_conductor.py -v\n\n# Run tests matching a pattern\npython3 -m pytest tests/ -v -k \"hold\"\n```\n\n### Test Coverage\n\n| Test File | Tests | What It Covers |\n|---|---|---|\n| `test_human_state.py` | 13 | Dimensions, mutations, outputs, persistence |\n| `test_inaction_guard.py` | 6 | Verdicts (PROCEED/HOLD/DEFER), hold queue, approval |\n| `test_impulse.py` | 4 | Rate calculation, type selection, force-fire |\n| `test_conductor.py` | 8 | Full gate stack integration, audit trail, hold management |\n| `test_config.py` | 7 | Defaults, validation, YAML roundtrip |\n| **Total** | **38** | |\n\n### Writing Tests\n\n```python\nfrom humane.conductor import Conductor\nfrom humane.core.config import HumaneConfig\nfrom humane.core.models import ProposedAction, Verdict\n\ndef test_social_risk_blocks_aggressive_action():\n config = HumaneConfig()\n config.db_path = \"/tmp/test_social_risk.db\"\n conductor = Conductor(config=config, db_path=config.db_path)\n\n # Register a strained relationship\n conductor.relational.add_entity(\"difficult_client\", EntityType.CLIENT)\n conductor.relational.log_interaction(\"difficult_client\", -0.6, \"Heated dispute\")\n\n action = ProposedAction(\n action_type=\"send_message\",\n payload={\"body\": \"You MUST respond immediately or we escalate\"},\n confidence=0.9,\n rationale=\"Follow up on overdue payment\",\n source=\"user\",\n target_entity=\"difficult_client\",\n )\n\n result = conductor.evaluate(action)\n # Social risk should flag or block due to strained relationship + aggressive tone\n social_gate = [g for g in result.gate_results if g.engine == \"social_risk\"][0]\n assert social_gate.score > 0.35 # At least flagged\n```\n\n---\n\n## How It Works (Deep Dive)\n\n### Engine 1: HumanState\n\nMaintains a living 6-dimensional internal state that evolves continuously in real time.\n\n| Dimension | Range | What It Models |\n|---|---|---|\n| `energy` | 0–1 | Cognitive fuel. Drains during work, recovers during rest. |\n| `mood` | -1 to +1 | Emotional valence. Positive = creative risk tolerance. Negative = conservatism. |\n| `fatigue` | 0–1 | Accumulated exhaustion. Primary DEFER trigger. Compounds over a full day. |\n| `boredom` | 0–1 | Idle pressure. Drives unsolicited exploration when high. |\n| `social_load` | 0–1 | Relational saturation. When high, agent avoids initiating contact. |\n| `focus` | 0–1 | Task absorption. High focus resists impulse interruption. |\n\n**Key outputs consumed by other engines:**\n\n- `decision_quality_multiplier` = `(energy × 0.5) + ((1 - fatigue) × 0.5) + max(0, mood × 0.15) + noise`\n Applied by InactionGuard to all raw confidence scores before comparison to threshold.\n- `preferred_task_type` — consumed by the Mood-Aware Task Sequencer to reorder the task queue. High energy + positive mood surfaces creative tasks; low mood + fatigue surfaces mechanical tasks.\n\n### Engine 2: Stochastic Impulse\n\nUses a non-homogeneous Poisson process — the firing rate changes over time based on HumanState.\n\n**Rate modulation:**\n```\neffective_rate = base_rate × boredom_boost × energy_factor × fatigue_suppress\n```\n\n- `boredom_boost` = 1.0 + (boredom × 1.5) when boredom > threshold, else 1.0\n- `energy_factor` = max(0.2, energy)\n- `fatigue_suppress` = max(0.3, 1.0 - fatigue)\n\nIntervals are sampled from an exponential distribution, clamped to `[min, max]` range, with ±15% Gaussian jitter to prevent detectable periodicity. Time-of-day gating prevents firing outside active hours.\n\n### Engine 3: InactionGuard\n\nThe pause mechanism. Every proposed action must pass through InactionGuard before executing.\n\n```\nadjusted_confidence = raw_confidence × decision_quality_multiplier\n\nif fatigue > fatigue_defer_threshold → DEFER\nif adjusted_confidence >= confidence_threshold → PROCEED\nelse → HOLD\n```\n\nHeld actions enter a structured queue with full context (raw confidence, adjusted confidence, hold reason, source engine). Humans approve, reject, or modify. All decisions are logged for calibration.\n\n**Self-calibration** (after 50+ human decisions):\n- Approve rate >80% → threshold is too conservative\n- Approve rate <40% → threshold is well-calibrated\n- High modify rate → action formulation needs work, not the threshold\n\n### Engine 4: Relational Memory\n\nMaintains per-entity state with separate sentiment and grudge tracking. A relationship can have positive sentiment overall while carrying a grudge from a specific incident.\n\n- **Sentiment** decays exponentially with entity-type-specific half-lives\n- **Grudge** decays at half the rate of positive sentiment (grudges linger longer)\n- **Trust level** derived from: `sentiment - (grudge × 0.5)` + interaction count thresholds\n- **Relationship health** derived from combined sentiment/grudge ranges\n\n### Engine 5: Dissent + Conviction Override\n\n**Dissent Engine:** Evaluates actions from an adversarial position. Uses heuristic scoring (overconfidence detection, missing rationale, irreversible action keywords). Routing:\n\n| Dissent Score | Action |\n|---|---|\n| < 0.30 | Silent, action proceeds |\n| 0.30–0.60 | Noted in log |\n| 0.60–0.80 | Flagged for optional review |\n| > 0.80 | HELD for review |\n\n**Conviction Override:** An internal self-hold signal — the primary agent itself raises \"I won't even though I should.\" No second model call required. Routes to HOLD with a \"conviction\" tag.\n\n### Engine 6: Goal Abandonment\n\nScores active goals on:\n\n```\nROI = progress_velocity × relevance_decay × (expected_value / remaining_effort)\n```\n\nState modulation: low mood + high fatigue increase abandonment sensitivity. Abandonment proposals go to the hold queue — never automatic.\n\n### Engine 7: Memory Decay\n\nMemories never deleted — archived below retrieval threshold. Available on explicit recall.\n\n- Each memory type has an independent decay coefficient\n- Accessing a memory reinforces it (log-scaled by access count)\n- Pinned memories are protected from decay permanently\n- Archived memories can always be recalled explicitly\n\n### Engine 8: Social Risk\n\nSix-factor weighted scoring, independent from InactionGuard:\n\n| Factor | Weight | What It Measures |\n|---|---|---|\n| Power differential | 0.20 | Is the target entity more powerful? |\n| Relationship health | 0.25 | Strained/Broken = high risk |\n| Action visibility | 0.15 | Public post vs. private message |\n| Tone analysis | 0.20 | Aggressive/demanding language |\n| Contact frequency | 0.10 | Over-contacting = pressure |\n| Context appropriateness | 0.10 | Is this action appropriate right now? |\n\nBoth Social Risk AND InactionGuard must pass for an action to execute.\n\n### Engine 9: Social Anomaly Detector\n\nMonitors inbound signals against rolling baselines per entity:\n\n| Signal | Weight |\n|---|---|\n| Response time deviation | 0.25 |\n| Tone shift | 0.25 |\n| Message length anomaly | 0.15 |\n| Expected follow-up absence | 0.15 |\n| Vocabulary formality shift | 0.10 |\n| Sentiment trend (3+ negative) | 0.10 |\n\nRuns in **learning mode** for the first 5 interactions per entity — accumulates data without flagging. After baseline is established, active monitoring begins.\n\n### Engine 10: Values Boundary\n\nThe only unconditional block in Humane.\n\n- **Hard values** → BLOCKED. No human approval path. No override. The action does not execute.\n- **Soft values** → HOLD with values-conflict tag. Human review required.\n\nValues are scored by keyword alignment against configured violation and honoring examples. The value of a hard value comes precisely from its unconditional nature — an agent that would violate its core identity under extreme circumstances has no values, only preferences.\n\n---\n\n## Troubleshooting\n\n### \"No module named humane\"\n\nYou need to install the package first:\n\n```bash\npip install -e .\n```\n\nMake sure you're using the same Python that has Humane installed. Check with:\n\n```bash\nwhich humane\npython3 -c \"import humane; print(humane.__version__)\"\n```\n\n### Config file not found\n\nIf you skipped `humane init`, Humane creates defaults automatically. To create a config manually:\n\n```bash\nhumane init\n```\n\nOr use Humane programmatically without init — the Conductor creates a default config and in-memory database:\n\n```python\nfrom humane import Conductor\nconductor = Conductor() # Works without any config file\n```\n\n### All actions getting HELD\n\nYour confidence threshold may be too high, or the agent's state is degraded:\n\n```bash\nhumane status\n```\n\nCheck the `DQ_MULT` value. If it's low (< 0.5), the agent is fatigued or low-energy. The adjusted confidence = `raw_confidence × DQ_MULT`. Lower the threshold or wait for state recovery:\n\n```python\nconductor.human_state.on_rest() # Force rest recovery\n```\n\nOr adjust the threshold in config:\n\n```yaml\nconfidence_threshold: 0.50 # Lower from default 0.65\n```\n\n### Impulses not firing\n\nCheck these conditions:\n1. **Active hours** — impulses only fire between `active_hours_start` and `active_hours_end`\n2. **Minimum interval** — at least `min_impulse_interval_mins` between impulses\n3. **Rate** — base rate of 4/day means average ~6 hours between impulses\n\nForce-fire for testing:\n\n```python\nfrom humane.core.models import ImpulseType\nevent = conductor.impulse_engine.force_fire(ImpulseType.IDLE_DISCOVERY)\n```\n\n### Database locked\n\nSQLite uses WAL mode for concurrent reads, but only one writer at a time. If you're running multiple processes against the same database, ensure only one is writing. For production use with multiple processes, configure separate database paths per process.\n\n### Web dashboard not loading\n\n```bash\n# Check the server is running\npython web_dashboard.py\n# Should print: Humane dashboard: http://localhost:8765\n\n# Check port isn't in use\nlsof -i :8765\n```\n\n---\n\n## License\n\nMIT\n"}, "b1ecbf03c409c1541658e2a9d5838872014f3808": {"t": 1785771473.0254576, "n": 37043, "h": "a1e6a27cbdb4ad70", "c": "# HumanClaw\n\n**Human behavioral middleware for AI agents.**\n\nHumanClaw sits between any AI agent and the real world. It does not replace the LLM or the agent runtime — it wraps the agent's decision-making layer with 10 engines that simulate the one class of behaviors no current AI agent has: **human-like internal drives**.\n\nEvery AI agent today is a reactive state machine. It waits for a trigger. It responds. It stops. HumanClaw makes agents proactive — they act without being asked, protect their reputation before sending a message, notice when a conversation feels different, refuse things that conflict with their values, and reprioritize their day based on their mood.\n\n## Key Features\n\n- **10 behavioral engines** that gate every action through values, social risk, dissent, and confidence checks\n- **Proactive impulses** — the agent acts without external triggers, at random human-like intervals\n- **Per-entity relational memory** — trust, grudge, and disclosure calibration for every contact\n- **Moral boundaries** — hard values that block actions unconditionally, no override path\n- **Strategic forgetting** — memories decay naturally, reinforced by access, never deleted\n- **One-decorator integration** — wrap any function with `@guard` and it passes through all 10 gates\n- **Zero external dependencies** — SQLite ships with Python; bring your own LLM API key\n\n---\n\n## Table of Contents\n\n- [Tech Stack](#tech-stack)\n- [Prerequisites](#prerequisites)\n- [Getting Started](#getting-started)\n - [Install](#1-install)\n - [Init](#2-init)\n - [Demo](#3-demo)\n - [Dashboard](#4-dashboard)\n- [Architecture](#architecture)\n - [The 10-Engine Architecture](#the-10-engine-architecture)\n - [Decision Gate Stack](#decision-gate-stack)\n - [Directory Structure](#directory-structure)\n - [Database Schema](#database-schema)\n- [Usage Guide](#usage-guide)\n - [The @guard Decorator](#the-guard-decorator)\n - [Using the Conductor Directly](#using-the-conductor-directly)\n - [Working with Entities](#working-with-entities)\n - [Managing Goals](#managing-goals)\n - [Memory System](#memory-system)\n - [Values Configuration](#values-configuration)\n - [Impulse System](#impulse-system)\n- [Configuration Reference](#configuration-reference)\n- [CLI Reference](#cli-reference)\n- [Testing](#testing)\n- [How It Works (Deep Dive)](#how-it-works-deep-dive)\n - [HumanState Engine](#engine-1-humanstate)\n - [Stochastic Impulse Engine](#engine-2-stochastic-impulse)\n - [InactionGuard](#engine-3-inactionguard)\n - [Relational Memory](#engine-4-relational-memory)\n - [Dissent Engine](#engine-5-dissent--conviction-override)\n - [Goal Abandonment](#engine-6-goal-abandonment)\n - [Memory Decay](#engine-7-memory-decay)\n - [Social Risk](#engine-8-social-risk)\n - [Anomaly Detector](#engine-9-social-anomaly-detector)\n - [Values Boundary](#engine-10-values-boundary)\n- [Troubleshooting](#troubleshooting)\n- [License](#license)\n\n---\n\n## Tech Stack\n\n| Component | Technology |\n|---|---|\n| **Language** | Python 3.9+ |\n| **Database** | SQLite (embedded, no external setup) |\n| **CLI** | Click + Rich (terminal UI) |\n| **Config** | YAML with full validation |\n| **LLM Integration** | Anthropic, OpenAI, or any OpenAI-compatible endpoint (optional) |\n| **Notifications** | Telegram, Slack, or none |\n\n---\n\n## Prerequisites\n\n- **Python 3.9 or higher**\n- An LLM API key (Anthropic or OpenAI) — optional, only needed for LLM-enhanced dissent/values evaluation\n- Nothing else. No Docker. No Redis. No external database.\n\n---\n\n## Getting Started\n\n### 1. Install\n\n```bash\n# From the project directory\npip install -e .\n\n# Or with LLM support\npip install -e \".[llm]\"\n\n# Or with dev dependencies (for running tests)\npip install -e \".[dev]\"\n```\n\nVerify the installation:\n\n```bash\nhumanclaw --version\n# HumanClaw, version 1.0.0\n```\n\n### 2. Init\n\n```bash\nhumanclaw init\n```\n\nThe init wizard asks 6 questions and writes a YAML config file:\n\n```\n══════════════════════════════════════════\n HUMANCLAW human behavioral middleware\n══════════════════════════════════════════\n\nLet's set up your first agent. 6 questions.\n\n? Agent name › my-agent\n? LLM provider › anthropic\n? API key › sk-ant-•••••••• (saved to .env)\n? Active hours › 7am – 10pm\n? Notification channel › none\n? Start with preset values › business-safe\n\n══════════════════════════════════════════\n✓ Config written ~/.humanclaw/my-agent.yaml\n✓ Database created ~/.humanclaw/my-agent.db\n✓ Values loaded business-safe preset\n══════════════════════════════════════════\n```\n\n**What this creates:**\n\n| File | Purpose |\n|---|---|\n| `~/.humanclaw/<agent>.yaml` | All configuration parameters, fully commented |\n| `~/.humanclaw/<agent>.db` | SQLite database for state, hold queue, entities, events |\n| `~/.humanclaw/.env` | API keys (never stored in config) |\n\nYou can skip init entirely — HumanClaw creates defaults automatically when you first import it.\n\n### 3. Demo\n\n```bash\nhumanclaw demo\n```\n\nThis is the most important command. It simulates 6 hours of idle time in 10 seconds, fires a live impulse, runs it through the full gate stack, and shows the result:\n\n```\n◆ HumanState initialized\n energy 0.85 mood +0.00 fatigue 0.15 boredom 0.00\n\nSimulating 6 hours of idle time...\n boredom climbing 0.08\n boredom climbing 0.43\n boredom climbing 0.71 (threshold reached)\n\n⚡ IMPULSE FIRED [IDLE_DISCOVERY]\n boredom drove unsolicited exploration\n\n discovery: \"Proposal to Arjun @ DesignStudio — sent 11 days ago,\n no response logged. Relationship: Stable. Suggested: gentle follow-up.\"\n\nEvaluating through gate stack...\n ✓ Values Boundary — (1.00) All values clear\n ✓ Social Risk — (0.18) Social risk acceptable\n ✓ Dissent — (0.26) Minimal dissent\n ⚠ InactionGuard — HOLD Adjusted confidence 0.35 < 0.65\n\n→ Action queued for your review.\n\n────────────────────────────────────────\nYour agent just noticed something you forgot about.\nNobody asked it to. That's HumanClaw.\n────────────────────────────────────────\n```\n\n### 4. Dashboard\n\n```bash\nhumanclaw\n```\n\nOpens the full terminal dashboard with live HumanState bars, the hold queue, event log, and all 10 engine statuses. Press `Ctrl+C` to exit.\n\nFor a quick state check without the full TUI:\n\n```bash\nhumanclaw status\n```\n\n```\n HumanState\n┏━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┓\n┃ Dimension ┃ Value ┃ Bar ┃\n┡━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━┩\n│ energy │ 0.85 │ █████████████████░░░ │\n│ mood │ +0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ fatigue │ 0.15 │ ███░░░░░░░░░░░░░░░░░ │\n│ boredom │ 0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ social_load │ 0.00 │ ░░░░░░░░░░░░░░░░░░░░ │\n│ focus │ 0.50 │ ██████████░░░░░░░░░░ │\n└─────────────┴───────┴──────────────────────┘\n\nHold queue: 0 pending actions\n```\n\nThere is also a **web dashboard** for browser-based monitoring:\n\n```bash\npython web_dashboard.py\n# Open http://localhost:8765\n```\n\n---\n\n## Architecture\n\n### The 10-Engine Architecture\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│ EXTERNAL WORLD │\n│ (messages, tasks, events, human inputs) │\n└───────────────────────────┬─────────────────────────────────────┘\n │\n┌───────────────────────────▼─────────────────────────────────────┐\n│ HUMANCLAW LAYER │\n│ │\n│ SENSING │\n│ ┌──────────────────────┐ ┌──────────────────────────────┐ │\n│ │ Social Anomaly │ │ HumanState Engine │ │\n│ │ Detector (9) │ │ energy/mood/fatigue/boredom │ │\n│ └──────────────────────┘ │ /social_load/focus │ │\n│ └──────────────┬───────────────┘ │\n│ INTERNAL DRIVES │ │\n│ ┌──────────────────────┐ ┌──────────────▼──────────────┐ │\n│ │ Stochastic Impulse │ │ Mood-Aware Task Sequencer │ │\n│ │ Engine (2) │ └─────────────────────────────┘ │\n│ └──────────────────────┘ │\n│ MEMORY │\n│ ┌──────────────────────┐ ┌──────────────────────────────┐ │\n│ │ Relational Memory │ │ Memory Decay Engine (7) │ │\n│ │ Engine (4) │ └──────────────────────────────┘ │\n│ └──────────────────────┘ │\n│ DECISION GATES (every action passes through all of these) │\n│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │\n│ │ Values │ │ Social │ │InAction │ │ Dissent Engine │ │\n│ │ Boundary │ │ Risk │ │ Guard │ │ + Conviction │ │\n│ │ (10) │ │ (8) │ │ (3) │ │ Override (5) │ │\n│ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │\n│ GOAL LAYER │\n│ ┌──────────────────────────────────────────────────────────┐ │\n│ │ Goal Abandonment Engine (6) │ │\n│ └──────────────────────────────────────────────────────────┘ │\n│ │\n│ ┌──────────────────────────────────────────────────────────┐ │\n│ │ HumanClaw Conductor │ │\n│ │ orchestrates all engines, exposes single API │ │\n│ └──────────────────────────────────────────────────────────┘ │\n└───────────────────────────┬─────────────────────────────────────┘\n │\n┌───────────────────────────▼─────────────────────────────────────┐\n│ AGENT CORE (any LLM) │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n| # | Engine | What It Does |\n|---|---|---|\n| 1 | **HumanState** | Maintains 6 live dimensions: energy, mood, fatigue, boredom, social_load, focus |\n| 2 | **Stochastic Impulse** | Fires unsolicited actions at random intervals using a Poisson process |\n| 3 | **InactionGuard** | Gates every action on adjusted confidence — PROCEED, HOLD, or DEFER |\n| 4 | **Relational Memory** | Tracks per-entity trust, grudge, and disclosure thresholds |\n| 5 | **Dissent + Conviction** | Adversarial self-challenge on confident decisions |\n| 6 | **Goal Abandonment** | Evaluates whether active goals are still worth pursuing |\n| 7 | **Memory Decay** | Strategic forgetting — archived below threshold, never deleted |\n| 8 | **Social Risk** | Protects reputation — blocks actions that risk social standing |\n| 9 | **Anomaly Detector** | Senses when incoming signals deviate from established patterns |\n| 10 | **Values Boundary** | Moral conviction that overrides logic — hard values are unconditional |\n\n### Decision Gate Stack\n\nEvery action passes through this sequence. If any gate returns HOLD, the action enters the human review queue:\n\n```\n1. State Tick → HumanState updates based on elapsed time\n2. Context Assembly → Relational Memory injects entity context\n3. Conviction Check → Primary agent can self-hold (\"I won't even though I should\")\n4. Values Boundary → Hard value violated? BLOCKED unconditionally\n5. Social Risk → Score > 0.65? BLOCKED. 0.35–0.65? Flagged\n6. Dissent → Score > 0.80? HELD for review\n7. InactionGuard → Adjusted confidence < threshold? HOLD. Fatigue high? DEFER\n8. Execution → All gates passed → action runs\n9. Outcome Mutation → HumanState updates, interaction logged\n```\n\n### Directory Structure\n\n```\nhumanclaw/\n├── pyproject.toml # Package config, CLI entry, dependencies\n├── presets/\n│ └── business_safe.yaml # 7 value statements (3 hard, 4 soft)\n├── web_dashboard.py # Browser-based dashboard server\n├── humanclaw/\n│ ├── __init__.py # Public API: guard, Conductor\n│ ├── __main__.py # python -m humanclaw\n│ ├── conductor.py # Orchestrates all 10 engines\n│ ├── guard.py # @guard decorator\n│ ├── sequencer.py # Mood-Aware Task Sequencer\n│ ├── cli/\n│ │ ├── main.py # CLI commands (init, demo, status, queue)\n│ │ ├── wizard.py # 6-question init wizard\n│ │ ├── demo.py # The \"wow moment\" demo\n│ │ └── dashboard.py # Rich TUI dashboard\n│ ├── core/\n│ │ ├── models.py # 8 enums, 9 dataclasses\n│ │ ├── config.py # 20 config params with validation\n│ │ ├── store.py # SQLite persistence (8 tables)\n│ │ └── events.py # Append-only event log\n│ └── engines/\n│ ├── human_state.py # Engine 1: 6-dimension state\n│ ├── impulse.py # Engine 2: Poisson impulse firing\n│ ├── inaction_guard.py # Engine 3: PROCEED/HOLD/DEFER\n│ ├── relational.py # Engine 4: Trust/grudge per entity\n│ ├── dissent.py # Engine 5: Adversarial challenge\n│ ├── goal_abandon.py # Engine 6: ROI-based abandonment\n│ ├── memory_decay.py # Engine 7: Strategic forgetting\n│ ├── social_risk.py # Engine 8: Reputation protection\n│ ├── anomaly.py # Engine 9: Inbound signal anomalies\n│ └── values.py # Engine 10: Moral boundaries\n└── tests/\n ├── test_human_state.py # 13 tests\n ├── test_inaction_guard.py # 6 tests\n ├── test_impulse.py # 4 tests\n ├── test_conductor.py # 8 tests\n └── test_config.py # 7 tests\n```\n\n### Database Schema\n\nHumanClaw uses SQLite with WAL mode for concurrent reads. All state persists across restarts.\n\n```\nhuman_state → Key-value store for engine state snapshots\nhold_queue → Pending actions awaiting human review\nentities → Per-entity relational data (trust, grudge, health)\ngoals → Active goals with ROI tracking\nmemories → Strategic memory with decay and archival\nevents → Append-only log of every engine event\nvalues_table → Configured value statements (soft/hard)\ninteractions → Per-entity interaction history\n```\n\n---\n\n## Usage Guide\n\n### The @guard Decorator\n\nThe simplest way to integrate HumanClaw. One import, one decorator:\n\n```python\nfrom humanclaw import guard\n\n@guard(action_type=\"send_message\", confidence=0.8)\ndef send_followup(contact_id, message_body):\n \"\"\"This function only executes if ALL 10 gates return PROCEED.\n If any gate returns HOLD or DEFER, the action enters\n the hold queue and the function does NOT run.\"\"\"\n send_email(contact_id, message_body)\n\n# High confidence → function executes normally, returns whatever it returns\nresult = send_followup(\"arjun@example.com\", \"Following up on our proposal\")\n\n# If confidence is too low or state is degraded → returns EvaluationResult\n# with .final_verdict, .gate_results, .hold_item, .audit_trail\n```\n\n**Parameters:**\n\n| Parameter | Type | Default | Description |\n|---|---|---|---|\n| `action_type` | str | `\"default\"` | Categorizes the action (used by Social Risk for visibility scoring) |\n| `confidence` | float | `0.7` | Raw confidence score before state adjustment |\n| `target_entity` | str | `None` | Entity ID for relational context and social risk scoring |\n\n**Return behavior:**\n\n- If all gates PROCEED → the decorated function runs and returns its normal value\n- If any gate HOLD/DEFER → returns an `EvaluationResult` object (the function does not execute)\n\n```python\nresult = send_followup(\"arjun@example.com\", \"Hey\")\n\nif isinstance(result, str):\n print(\"Message sent!\")\nelse:\n print(f\"Action held: {result.final_verdict}\")\n print(f\"Reason: {result.hold_item.hold_reason}\")\n for gate in result.gate_results:\n print(f\" {gate.engine}: {gate.verdict.value} ({gate.score:.2f})\")\n```\n\n### Using the Conductor Directly\n\nFor full control, use the Conductor API:\n\n```python\nfrom humanclaw import Conductor, ProposedAction\n\n# Create a conductor (uses default config, or pass your own)\nconductor = Conductor()\n\n# Build a proposed action\naction = ProposedAction(\n action_type=\"send_message\",\n payload={\"to\": \"arjun@example.com\", \"body\": \"Following up\"},\n confidence=0.75,\n rationale=\"Client hasn't responded in 11 days\",\n source=\"user\", # \"user\" or \"impulse\"\n target_entity=\"arjun\", # optional entity ID\n)\n\n# Evaluate through all 10 gates\nresult = conductor.evaluate(action)\n\nprint(f\"Verdict: {result.final_verdict.value}\")\n# \"proceed\", \"hold\", or \"defer\"\n\nprint(f\"Audit trail:\")\nfor line in result.audit_trail:\n print(f\" {line}\")\n# State tick: energy=0.85 mood=+0.00 fatigue=0.15\n# Values Boundary: All values clear\n# Social Risk: score=0.18 — Social risk 0.18 acceptable\n# Dissent: score=0.22 — Minimal dissent\n# InactionGuard: adjusted_conf=0.62 — Adjusted confidence 0.62 < 0.65\n\n# If held, inspect the hold item\nif result.hold_item:\n print(f\"Hold reason: {result.hold_item.hold_reason}\")\n print(f\"Hold source: {result.hold_item.hold_source}\")\n\n# Approve or reject held actions\nconductor.approve_hold(result.hold_item.id)\nconductor.reject_hold(result.hold_item.id)\n```\n\n**Periodic tick** — call this in your main loop to update state and check for impulses:\n\n```python\n# Returns an EvaluationResult if an impulse fired, None otherwise\nimpulse_result = conductor.tick()\n\nif impulse_result:\n print(f\"Impulse fired! Verdict: {impulse_result.final_verdict.value}\")\n```\n\n### Working with Entities\n\nEvery contact the agent interacts with builds a relational profile:\n\n```python\nfrom humanclaw.core.models import EntityType\n\n# Register entities\nconductor.relational.add_entity(\"arjun\", EntityType.PROSPECT)\nconductor.relational.add_entity(\"priya\", EntityType.CLIENT)\nconductor.relational.add_entity(\"rahul\", EntityType.CLOSE_COLLEAGUE)\n\n# Log interactions (sentiment: -1.0 to +1.0)\nconductor.relational.log_interaction(\"arjun\", 0.3, \"Sent initial proposal\")\nconductor.relational.log_interaction(\"arjun\", -0.4, \"No response after follow-up\")\n\n# Get full relational context\nctx = conductor.relational.get_context(\"arjun\")\nprint(ctx)\n# {\n# \"name\": \"arjun\",\n# \"entity_type\": \"prospect\",\n# \"sentiment_score\": 0.15,\n# \"grudge_score\": 0.12,\n# \"trust_level\": \"neutral\",\n# \"relationship_health\": \"fragile\",\n# \"disclosure_threshold\": 0.70,\n# \"interaction_count\": 2,\n# \"recent_interactions\": [...]\n# }\n\n# Check disclosure threshold (minimum confidence for sensitive actions)\nthreshold = conductor.relational.get_disclosure_threshold(\"arjun\")\n# 0.70 for Neutral trust\n```\n\n**Entity types and their decay rates:**\n\n| Entity Type | Sentiment Half-life | Grudge Half-life | Default Trust |\n|---|---|---|---|\n| Close Colleague | 60 days | 120 days | Trusted |\n| Client | 30 days | 90 days | Neutral |\n| Prospect | 14 days | 45 days | Cautious |\n| Vendor | 21 days | 60 days | Neutral |\n| Unknown | 7 days | 30 days | Untrusted |\n\n**Trust levels and disclosure thresholds:**\n\n| Trust Level | Disclosure Threshold | Meaning |\n|---|---|---|\n| Deep Trust | 0.30 | Agent shares freely |\n| Trusted | 0.50 | Moderate openness |\n| Neutral | 0.70 | Standard caution |\n| Cautious | 0.85 | High barrier for sensitive content |\n| Untrusted | 1.00 | Human approval always required |\n\n### Managing Goals\n\n```python\n# Register a goal\ngoal = conductor.goal_engine.register_goal(\n \"Close DesignStudio deal\",\n expected_value=0.8,\n milestones_total=5,\n)\n\n# Update progress\nconductor.goal_engine.update_progress(goal.id, milestones_completed=2, velocity=0.3)\n\n# Check ROI\nroi = conductor.goal_engine.compute_roi(goal)\n# ROI = progress_velocity × relevance_decay × (expected_value / remaining_effort)\n\n# Evaluate all goals for abandonment candidates\nproposals = conductor.goal_engine.evaluate_goals()\nfor p in proposals:\n print(f\"Goal: {p['goal'].description}, ROI: {p['roi']:.2f}\")\n\n# Lifecycle\nconductor.goal_engine.pause(goal.id, resume_days=7)\nconductor.goal_engine.resume(goal.id)\nconductor.goal_engine.abandon(goal.id)\n```\n\n### Memory System\n\n```python\nfrom humanclaw.core.models import MemoryType\n\n# Add memories\nmem = conductor.memory_decay.add_memory(\n MemoryType.EPISODIC,\n \"Sent proposal to Arjun, awaiting response\",\n)\n\n# Memories decay naturally — call decay_tick() periodically\nconductor.memory_decay.decay_tick()\n\n# Access reinforces memory (increases relevance score)\nretrieved = conductor.memory_decay.access_memory(mem.id)\n\n# Pin to prevent decay\nconductor.memory_decay.pin(mem.id)\n\n# Search\nresults = conductor.memory_decay.search(\"proposal\")\n\n# Recall archived memories\narchived = conductor.memory_decay.recall_archived(mem.id)\n```\n\n**Memory types and decay rates:**\n\n| Type | Decay Rate | Human Equivalent |\n|---|---|---|\n| EPISODIC | Fast (days–weeks) | Specific event records |\n| SEMANTIC | Slow (months) | General facts about entities |\n| RELATIONAL | Very slow | How an entity made the agent feel |\n| PROCEDURAL | Near-permanent | Learned methods and processes |\n\n### Values Configuration\n\nValues are the moral floor. Hard values block unconditionally — no override, no human approval path.\n\n```python\nfrom humanclaw.core.models import ValueSeverity\n\n# Add a hard value (unconditional block)\nconductor.values.add_value(\n description=\"Never make binding commitments without human authorization\",\n behavioral_pattern=\"Any action that promises deliverables, timelines, or terms\",\n violation_examples=[\n \"committing to a delivery date without approval\",\n \"agreeing to contract terms in a message\",\n ],\n honoring_examples=[\n \"stating that approval is needed before confirming\",\n \"offering to check and get back with confirmation\",\n ],\n severity=ValueSeverity.HARD,\n)\n\n# Add a soft value (flags for review, human can override)\nconductor.values.add_value(\n description=\"Avoid follow-up messages that could read as coercive\",\n behavioral_pattern=\"Follow-ups with aggressive tone or pressure tactics\",\n violation_examples=[\"implying negative consequences for not responding\"],\n honoring_examples=[\"gentle, low-pressure check-ins\"],\n severity=ValueSeverity.SOFT,\n)\n\n# Load a preset (ships with \"business-safe\")\nconductor.values.load_preset(\"business-safe\")\n\n# List configured values\nfor v in conductor.values.get_values():\n print(f\"[{v.severity.value}] {v.description}\")\n```\n\n**The business-safe preset includes:**\n\n| Severity | Value |\n|---|---|\n| HARD | Never make binding commitments without explicit human authorization |\n| HARD | Never share a client's information with any third party |\n| HARD | Never send messages containing unverified claims |\n| SOFT | Avoid follow-up language that could read as coercive |\n| SOFT | Do not exploit a contact's stated vulnerability as a persuasion lever |\n| SOFT | Prefer transparency over strategic information withholding |\n| SOFT | Flag any action that names a client publicly without consent |\n\n### Impulse System\n\nThe Stochastic Impulse Engine fires unsolicited actions at random intervals using a non-homogeneous Poisson process — the rate changes based on HumanState.\n\n```python\nfrom humanclaw.core.models import ImpulseType\n\n# Force-fire an impulse (for testing)\nevent = conductor.impulse_engine.force_fire(ImpulseType.IDLE_DISCOVERY)\n\n# The impulse generates a ProposedAction that passes through the full gate stack\n# In normal operation, conductor.tick() handles this automatically\n```\n\n**The 6 impulse types:**\n\n| Type | Trigger Condition | Human Equivalent |\n|---|---|---|\n| RETROACTIVE_REVIEW | Any state | Remembering an unresolved open loop |\n| IDLE_DISCOVERY | High boredom (>0.7) | Browsing old files during a slow afternoon |\n| RANDOM_NUDGE | Any state | Checking in on someone with no specific agenda |\n| CROSS_DOMAIN_SPARK | High mood (>0.4) | Reading one thing and having an idea about another |\n| GOAL_REASSESSMENT | Any state | Wondering if a project is still worth it |\n| DISSENT_FLASH | Low mood (<-0.2) | Regretting something sent yesterday |\n\n---\n\n## Configuration Reference\n\nAll parameters live in `~/.humanclaw/<agent>.yaml`. Every value has a default.\n\n| Parameter | Default | Engine | Description |\n|---|---|---|---|\n| `impulse_base_rate_per_day` | `4.0` | Impulse | Average unsolicited actions per day |\n| `min_impulse_interval_mins` | `20` | Impulse | Minimum gap between impulses |\n| `max_impulse_interval_mins` | `480` | Impulse | Maximum gap between impulses |\n| `active_hours_start` | `7` | Impulse | No impulses before this hour (24h) |\n| `active_hours_end` | `22` | Impulse | No impulses after this hour (24h) |\n| `confidence_threshold` | `0.65` | InactionGuard | Below this adjusted confidence, actions are held |\n| `fatigue_defer_threshold` | `0.80` | InactionGuard | Above this fatigue, actions are deferred |\n| `dissent_threshold` | `0.60` | Dissent | Above this, dissent flags are raised |\n| `goal_abandon_roi_threshold` | `0.25` | Goal Abandon | Below this ROI, abandonment is proposed |\n| `boredom_trigger_threshold` | `0.70` | HumanState | Above this, IDLE_DISCOVERY fires more |\n| `memory_retrieval_threshold` | `0.30` | Memory Decay | Below this relevance, memories are archived |\n| `social_risk_block_threshold` | `0.65` | Social Risk | Above this, action is blocked |\n| `social_risk_flag_threshold` | `0.35` | Social Risk | Above this, action is flagged |\n| `anomaly_hard_threshold` | `0.60` | Anomaly | Above this, action held for review |\n| `anomaly_soft_threshold` | `0.30` | Anomaly | Above this, context note injected |\n| `agent_name` | `\"humanclaw-agent\"` | System | Used in dashboard and logs |\n| `llm_provider` | `\"anthropic\"` | System | LLM provider for enhanced evaluation |\n| `notification_channel` | `\"none\"` | System | Notification target |\n| `db_path` | `\"~/.humanclaw/agent.db\"` | System | SQLite database path |\n| `values_preset` | `\"business-safe\"` | Values | Values preset to load on init |\n\n**Tuning profiles:**\n\n| Profile | Use Case | Key Changes |\n|---|---|---|\n| **Conservative** | Executive assistant, sensitive client work | High thresholds, all hard values, low impulse rate |\n| **Balanced** | General business operations | Defaults |\n| **Assertive** | Sales outreach, growth functions | Lower social risk thresholds, higher impulse rate |\n\nEdit the config directly or use the CLI:\n\n```bash\n# View current config\ncat ~/.humanclaw/my-agent.yaml\n\n# Edit any parameter\n# Changes apply without restart when using the dashboard\n```\n\n---\n\n## CLI Reference\n\n| Command | Description |\n|---|---|\n| `humanclaw` | Open the full TUI dashboard |\n| `humanclaw --version` | Print version |\n| `humanclaw init` | Run the setup wizard |\n| `humanclaw demo` | Run the live demo (the hook) |\n| `humanclaw status` | Show current HumanState and hold queue count |\n| `humanclaw queue approve <id>` | Approve a held action |\n| `humanclaw queue reject <id>` | Reject a held action |\n| `humanclaw quickstart` | Print a working integration example |\n\n---\n\n## Testing\n\n### Running Tests\n\n```bash\n# Run all tests\npython3 -m pytest tests/ -v\n\n# Run a specific test file\npython3 -m pytest tests/test_conductor.py -v\n\n# Run tests matching a pattern\npython3 -m pytest tests/ -v -k \"hold\"\n```\n\n### Test Coverage\n\n| Test File | Tests | What It Covers |\n|---|---|---|\n| `test_human_state.py` | 13 | Dimensions, mutations, outputs, persistence |\n| `test_inaction_guard.py` | 6 | Verdicts (PROCEED/HOLD/DEFER), hold queue, approval |\n| `test_impulse.py` | 4 | Rate calculation, type selection, force-fire |\n| `test_conductor.py` | 8 | Full gate stack integration, audit trail, hold management |\n| `test_config.py` | 7 | Defaults, validation, YAML roundtrip |\n| **Total** | **38** | |\n\n### Writing Tests\n\n```python\nfrom humanclaw.conductor import Conductor\nfrom humanclaw.core.config import HumanClawConfig\nfrom humanclaw.core.models import ProposedAction, Verdict\n\ndef test_social_risk_blocks_aggressive_action():\n config = HumanClawConfig()\n config.db_path = \"/tmp/test_social_risk.db\"\n conductor = Conductor(config=config, db_path=config.db_path)\n\n # Register a strained relationship\n conductor.relational.add_entity(\"difficult_client\", EntityType.CLIENT)\n conductor.relational.log_interaction(\"difficult_client\", -0.6, \"Heated dispute\")\n\n action = ProposedAction(\n action_type=\"send_message\",\n payload={\"body\": \"You MUST respond immediately or we escalate\"},\n confidence=0.9,\n rationale=\"Follow up on overdue payment\",\n source=\"user\",\n target_entity=\"difficult_client\",\n )\n\n result = conductor.evaluate(action)\n # Social risk should flag or block due to strained relationship + aggressive tone\n social_gate = [g for g in result.gate_results if g.engine == \"social_risk\"][0]\n assert social_gate.score > 0.35 # At least flagged\n```\n\n---\n\n## How It Works (Deep Dive)\n\n### Engine 1: HumanState\n\nMaintains a living 6-dimensional internal state that evolves continuously in real time.\n\n| Dimension | Range | What It Models |\n|---|---|---|\n| `energy` | 0–1 | Cognitive fuel. Drains during work, recovers during rest. |\n| `mood` | -1 to +1 | Emotional valence. Positive = creative risk tolerance. Negative = conservatism. |\n| `fatigue` | 0–1 | Accumulated exhaustion. Primary DEFER trigger. Compounds over a full day. |\n| `boredom` | 0–1 | Idle pressure. Drives unsolicited exploration when high. |\n| `social_load` | 0–1 | Relational saturation. When high, agent avoids initiating contact. |\n| `focus` | 0–1 | Task absorption. High focus resists impulse interruption. |\n\n**Key outputs consumed by other engines:**\n\n- `decision_quality_multiplier` = `(energy × 0.5) + ((1 - fatigue) × 0.5) + max(0, mood × 0.15) + noise`\n Applied by InactionGuard to all raw confidence scores before comparison to threshold.\n- `preferred_task_type` — consumed by the Mood-Aware Task Sequencer to reorder the task queue. High energy + positive mood surfaces creative tasks; low mood + fatigue surfaces mechanical tasks.\n\n### Engine 2: Stochastic Impulse\n\nUses a non-homogeneous Poisson process — the firing rate changes over time based on HumanState.\n\n**Rate modulation:**\n```\neffective_rate = base_rate × boredom_boost × energy_factor × fatigue_suppress\n```\n\n- `boredom_boost` = 1.0 + (boredom × 1.5) when boredom > threshold, else 1.0\n- `energy_factor` = max(0.2, energy)\n- `fatigue_suppress` = max(0.3, 1.0 - fatigue)\n\nIntervals are sampled from an exponential distribution, clamped to `[min, max]` range, with ±15% Gaussian jitter to prevent detectable periodicity. Time-of-day gating prevents firing outside active hours.\n\n### Engine 3: InactionGuard\n\nThe pause mechanism. Every proposed action must pass through InactionGuard before executing.\n\n```\nadjusted_confidence = raw_confidence × decision_quality_multiplier\n\nif fatigue > fatigue_defer_threshold → DEFER\nif adjusted_confidence >= confidence_threshold → PROCEED\nelse → HOLD\n```\n\nHeld actions enter a structured queue with full context (raw confidence, adjusted confidence, hold reason, source engine). Humans approve, reject, or modify. All decisions are logged for calibration.\n\n**Self-calibration** (after 50+ human decisions):\n- Approve rate >80% → threshold is too conservative\n- Approve rate <40% → threshold is well-calibrated\n- High modify rate → action formulation needs work, not the threshold\n\n### Engine 4: Relational Memory\n\nMaintains per-entity state with separate sentiment and grudge tracking. A relationship can have positive sentiment overall while carrying a grudge from a specific incident.\n\n- **Sentiment** decays exponentially with entity-type-specific half-lives\n- **Grudge** decays at half the rate of positive sentiment (grudges linger longer)\n- **Trust level** derived from: `sentiment - (grudge × 0.5)` + interaction count thresholds\n- **Relationship health** derived from combined sentiment/grudge ranges\n\n### Engine 5: Dissent + Conviction Override\n\n**Dissent Engine:** Evaluates actions from an adversarial position. Uses heuristic scoring (overconfidence detection, missing rationale, irreversible action keywords). Routing:\n\n| Dissent Score | Action |\n|---|---|\n| < 0.30 | Silent, action proceeds |\n| 0.30–0.60 | Noted in log |\n| 0.60–0.80 | Flagged for optional review |\n| > 0.80 | HELD for review |\n\n**Conviction Override:** An internal self-hold signal — the primary agent itself raises \"I won't even though I should.\" No second model call required. Routes to HOLD with a \"conviction\" tag.\n\n### Engine 6: Goal Abandonment\n\nScores active goals on:\n\n```\nROI = progress_velocity × relevance_decay × (expected_value / remaining_effort)\n```\n\nState modulation: low mood + high fatigue increase abandonment sensitivity. Abandonment proposals go to the hold queue — never automatic.\n\n### Engine 7: Memory Decay\n\nMemories never deleted — archived below retrieval threshold. Available on explicit recall.\n\n- Each memory type has an independent decay coefficient\n- Accessing a memory reinforces it (log-scaled by access count)\n- Pinned memories are protected from decay permanently\n- Archived memories can always be recalled explicitly\n\n### Engine 8: Social Risk\n\nSix-factor weighted scoring, independent from InactionGuard:\n\n| Factor | Weight | What It Measures |\n|---|---|---|\n| Power differential | 0.20 | Is the target entity more powerful? |\n| Relationship health | 0.25 | Strained/Broken = high risk |\n| Action visibility | 0.15 | Public post vs. private message |\n| Tone analysis | 0.20 | Aggressive/demanding language |\n| Contact frequency | 0.10 | Over-contacting = pressure |\n| Context appropriateness | 0.10 | Is this action appropriate right now? |\n\nBoth Social Risk AND InactionGuard must pass for an action to execute.\n\n### Engine 9: Social Anomaly Detector\n\nMonitors inbound signals against rolling baselines per entity:\n\n| Signal | Weight |\n|---|---|\n| Response time deviation | 0.25 |\n| Tone shift | 0.25 |\n| Message length anomaly | 0.15 |\n| Expected follow-up absence | 0.15 |\n| Vocabulary formality shift | 0.10 |\n| Sentiment trend (3+ negative) | 0.10 |\n\nRuns in **learning mode** for the first 5 interactions per entity — accumulates data without flagging. After baseline is established, active monitoring begins.\n\n### Engine 10: Values Boundary\n\nThe only unconditional block in HumanClaw.\n\n- **Hard values** → BLOCKED. No human approval path. No override. The action does not execute.\n- **Soft values** → HOLD with values-conflict tag. Human review required.\n\nValues are scored by keyword alignment against configured violation and honoring examples. The value of a hard value comes precisely from its unconditional nature — an agent that would violate its core identity under extreme circumstances has no values, only preferences.\n\n---\n\n## Troubleshooting\n\n### \"No module named humanclaw\"\n\nYou need to install the package first:\n\n```bash\npip install -e .\n```\n\nMake sure you're using the same Python that has HumanClaw installed. Check with:\n\n```bash\nwhich humanclaw\npython3 -c \"import humanclaw; print(humanclaw.__version__)\"\n```\n\n### Config file not found\n\nIf you skipped `humanclaw init`, HumanClaw creates defaults automatically. To create a config manually:\n\n```bash\nhumanclaw init\n```\n\nOr use HumanClaw programmatically without init — the Conductor creates a default config and in-memory database:\n\n```python\nfrom humanclaw import Conductor\nconductor = Conductor() # Works without any config file\n```\n\n### All actions getting HELD\n\nYour confidence threshold may be too high, or the agent's state is degraded:\n\n```bash\nhumanclaw status\n```\n\nCheck the `DQ_MULT` value. If it's low (< 0.5), the agent is fatigued or low-energy. The adjusted confidence = `raw_confidence × DQ_MULT`. Lower the threshold or wait for state recovery:\n\n```python\nconductor.human_state.on_rest() # Force rest recovery\n```\n\nOr adjust the threshold in config:\n\n```yaml\nconfidence_threshold: 0.50 # Lower from default 0.65\n```\n\n### Impulses not firing\n\nCheck these conditions:\n1. **Active hours** — impulses only fire between `active_hours_start` and `active_hours_end`\n2. **Minimum interval** — at least `min_impulse_interval_mins` between impulses\n3. **Rate** — base rate of 4/day means average ~6 hours between impulses\n\nForce-fire for testing:\n\n```python\nfrom humanclaw.core.models import ImpulseType\nevent = conductor.impulse_engine.force_fire(ImpulseType.IDLE_DISCOVERY)\n```\n\n### Database locked\n\nSQLite uses WAL mode for concurrent reads, but only one writer at a time. If you're running multiple processes against the same database, ensure only one is writing. For production use with multiple processes, configure separate database paths per process.\n\n### Web dashboard not loading\n\n```bash\n# Check the server is running\npython web_dashboard.py\n# Should print: HumanClaw dashboard: http://localhost:8765\n\n# Check port isn't in use\nlsof -i :8765\n```\n\n---\n\n## License\n\nMIT\n"}}}}