System Architecture GOTCHA framework, tool manifest, agent system documentation. AAOS — ALAI Agent Operating System Executive Summary AAOS is the enforcement runtime for the ALAI agent system. It turns optional protocols (RAG-first, GOTCHA, evidence tracking, quality gates) into mandatory runtime gates that every agent passes through on every lifecycle transition. Core insight: Enforcement belongs at state transitions , not at every tool call. Per-tool-call enforcement caused 348 blocks/session (system unusable). AAOS uses 4 gates at 4 transitions — proven workable. Spec file: ~/system/specs/aaos-architecture.md Deployed: 2026-04-02 MC Task: #6921 Architecture Layers Layer 5: INTERFACE — John (Orchestrator) | MC Dashboard | Slack | CLI Layer 4: ORCHESTRATION — pi-orchestrator.js | team-coordinator.js | pipeline-engine.js Layer 3: ENFORCEMENT — Spawn Gate | Exec Gate | Claim Gate | Close Gate Layer 2: LIBRARY — Tool Registry | Skill Registry | RAG Index | Agent Registry | Context Assembler Layer 1: COMPUTE — Ollama ANVIL (12 models) | Ollama FORGE (7 models) | Claude API | Local Tools Layer 0: PERSISTENCE — SQLite (54 DBs) | Filesystem | HiveMind | Qdrant (vector search) The 4 Enforcement Gates Gate When Checks Implementation SPAWN GATE Agent creation MC task exists & in_progress, GOTCHA written (H/M), team composition meets minimum, budget check kernel/spawn-gate.js + pi-orchestrator Step 4.5 EXEC GATE During execution WIP limit (max 3), tool whitelist, budget cap, timeout Existing hooks ( alai-hooks binary) CLAIM GATE Before "done" All claims labeled L0-L4, no L0/L1 in final report, evidence artifacts exist kernel/claim-gate.js CLOSE GATE Task completion QA-19 score meets threshold, metrics recorded to agent_metrics, learning posted to HiveMind mc.js done handler Trust Levels (ZAKON #21) Level Meaning Allowed L0 Unverified — agent says "done" with no evidence ❌ Never to CEO L1 Self-Tested — agent ran its own tests ❌ Never to CEO L2 Peer-Tested — validator or tester confirmed ✅ Minimum for reports L3 Machine-Verified — exit codes, HTTP responses, DOM checks ✅ Required for aggregate claims L4 Human-Verified — Alem confirmed ✅ Gold standard Library-in-the-Middle The Library is a Node.js module ( kernel/library.js ) that unifies access to all existing stores. Agents don't browse ~/system/ looking for files — they call the Context Assembler which returns exactly what they need, within a token budget. API const library = require('~/system/kernel/library.js'); // Assemble full context for an agent on a task library.assemble(taskId, agentId) → { coreProtocol, agentPersona, projectContext, ragContext, skillSet, toolWhitelist, rules, tokenBudget } // Individual registries library.tools.search(query) // Search 1310 tools library.tools.audit(toolName, agentId, taskId) // Record usage library.skills.forAgent(agentId) // Cookbook-matched skills library.context.rag(query, limit) // HiveMind semantic search library.agents.roster(taskType, priority) // Recommended team composition library.rules.forTask(taskType) // Relevant ZAKONs Token Budgets Model Max Context Tokens Claude Opus 32,000 Claude Sonnet 16,000 Claude Haiku 4,000 Ollama 32B 8,000 Ollama 8B 4,000 Team Composition Rules Config: ~/system/config/team-templates.json Task Type Min Team Required Roles Trivial fix 1 Builder only Feature (M priority) 3 Builder + Validator + Tester Feature (H priority) 5 Builder + Validator + 2 Testers + Security Architecture 3 Architect + Devil's Advocate + Validator Deploy 3 Builder + DevOps + Validator Financial 3 Builder + Finance + Validator Specialist Agents 22 agents total in specialist-mapping.json . Key additions (2026-04-02): Builders (Write/Edit access) Agent Company Domain Expertise Hadi Hariri CodeCraft Kotlin/Ktor Kotlin, Ktor, coroutines, Gradle, JVM optimization Lee Robinson CodeCraft Next.js 15 App Router, React Server Components, Tailwind, Vercel Testers (READ-ONLY — no Write/Edit) Agent Company Focus Style Angie Jones Proveo Test automation Frameworks, E2E, API contracts, regression James Bach Proveo Exploratory testing Skeptical, edge cases, "what would a real user do?" Lisa Crispin Proveo Agile testing Business rules, acceptance criteria, Given/When/Then Dorota Huizinga Proveo Performance testing Load testing, chaos engineering, p50/p95/p99 latencies Tester Assignment Rule H-priority: All 4 testers (minimum 3) M-priority: Angie Jones + 1 other (minimum 2) L-priority: Angie Jones (minimum 1) Database Schema (New Tables) All in ~/system/databases/mission-control.db agent_metrics CREATE TABLE agent_metrics ( id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, -- e.g., 'bruce-momjian' task_id INTEGER, -- MC task ID qa_score REAL, -- QA-19 score (0-19) token_count INTEGER, -- tokens consumed duration_seconds INTEGER, -- wall clock time escalated BOOLEAN DEFAULT 0, -- task escalated to higher model? model_used TEXT, -- e.g., 'sonnet', 'qwen3:32b' claim_count INTEGER DEFAULT 0, evidence_count INTEGER DEFAULT 0, defects_found INTEGER DEFAULT 0, trust_level TEXT DEFAULT 'L0', -- L0-L4 created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); team_composition CREATE TABLE team_composition ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, role TEXT NOT NULL, -- builder, validator, tester, security agent_id TEXT NOT NULL, assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP ); library_usage CREATE TABLE library_usage ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, agent_id TEXT, tool_name TEXT, skill_name TEXT, used_at DATETIME DEFAULT CURRENT_TIMESTAMP ); Pi-Orchestrator Integration Wired 2026-04-02. Backup: pi-orchestrator.js.bak-aaos-20260402 Imports (line 66-72): library.js + spawn-gate.js with graceful degradation Spawn Gate (Step 4.5, line 3288): Advisory check before task claim — logs warning if gate fails, doesn't block pi-orch Library Context (line 770-782): RAG preloading via library.assemble() injected into buildPrompt() Prompt Template (line 928): aaosContextBlock added between contextBlock and projectContextBlock Graceful degradation: If AAOS modules fail to load, pi-orchestrator works exactly as before. Infrastructure Status Component Status Details Docker ✅ UP v29.2 Qdrant ✅ UP 3 collections (sessions, knowledge, hivemind) on port 6333 Ollama ANVIL ✅ UP 12 models on localhost:11434 Ollama FORGE ✅ UP 7 models on 10.0.0.2:11434 Tool Shed ✅ UP 240 tools on port 3050 HiveMind ✅ UP 25,309 entries, keyword search working Hooks Binary ✅ UP 15.7MB arm64, 4 blocking + 1 advisory gate Enforcement Configuration File: ~/.claude/hooks/config/enforcement.json Hook ZAKON Mode HopBuild #5 BLOCKING RAG-First #12 BLOCKING QA-19 #14 BLOCKING Evidence #21 BLOCKING Agent Testing #20 ADVISORY (promote to blocking after 2 weeks) File Map New Files (created 2026-04-02) ~/system/kernel/library.js — Library-in-the-Middle (283 lines) ~/system/kernel/spawn-gate.js — SPAWN GATE enforcement ~/system/kernel/claim-gate.js — CLAIM GATE enforcement ~/system/config/team-templates.json — Team composition rules (6 types) ~/system/specs/aaos-architecture.md — Full architecture spec (1060 lines) ~/system/agents/definitions/hadi-hariri.md + .yaml — Kotlin/Ktor specialist ~/system/agents/definitions/lee-robinson.md + .yaml — Next.js 15 specialist ~/system/agents/definitions/james-bach.md + .yaml — Exploratory tester ~/system/agents/definitions/lisa-crispin.md + .yaml — Agile tester ~/system/agents/definitions/dorota-huizinga.md + .yaml — Performance tester ~/system/agents/identities/{hadi,lee,james,lisa,dorota}-*.md — Full identities Modified Files ~/system/tools/mc.js — CLOSE GATE metrics recording in done handler ~/system/kernel/pi-orchestrator.js — AAOS wiring (spawn-gate + library context) ~/system/agents/specialist-mapping.json — 5 new agents (total: 22) ~/system/databases/mission-control.db — 3 new tables Metrics & Learning Loop Every task completion records to agent_metrics : Agent ID, task ID, model used Duration (seconds from mc.js start to done) QA-19 score (if available) Evidence count (files in /tmp/evidence-{id}/ ) Trust level (L0-L4, based on evidence presence and force flag) Every non-forced completion also posts a learning entry to HiveMind (knowledge type). Success Criteria Zero agents complete a task without RAG preloading (measured by SPAWN GATE rejection count) Zero L0/L1 claims reach Alem (measured by CLAIM GATE + CEO-reported false claims) Every H-priority task has 3+ testers (measured by team_composition table) Agent quality improves over time (measured by avg QA-19 score per agent, monthly) Token efficiency improves (measured by qa_score / token_count ratio, monthly) Overview System Architecture Overview This book documents the GOTCHA framework, tool manifest, and agent system architecture. Owner: John Last Verified: 2026-02-17 Contents To be populated from ~/system/context/ GOTCHA Framework Last Verified: 2026-02-17 | Owner: John GOTCHA Framework Ovaj sistem koristi GOTCHA — 6-layer arhitektura za agentske sisteme: GOT (Engine) Goals — Šta treba da se desi (proces definicije u specs/, rules/) Orchestration — AI manager (John) koji koordinira izvršavanje Tools — Deterministički skripti koji rade posao (tools/) CHA (Context) Context — Reference materijal i domain knowledge (context/) Hard prompts — Reusable instruction templates (prompts/) Args — Behavior settings koji oblikuju ponašanje (config/) Princip AI greši kumulativno (90%^5 = 59%). Zato: Pouzdanost → deterministički kod (tools) Fleksibilnost → LLM (AI) Proces → goals/specs Znanje → context/memory Arhitektura John sjedi između onoga šta treba da se desi (goals) i kako se odradi (tools). Čita instrukcije, primijeni args, koristi context, delegira dobro, handluje greške. Directory Structure ~/system/ ├── tools/ ← Deterministički toolsi (PROVJERI manifest.md\!) ├── rules/ ← Standardi + lekcije (goals layer) ├── specs/ ← Planovi i specifikacije (goals layer) ├── context/ ← Reference materijal (context layer) ├── prompts/ ← Instruction templates (hard prompts layer) ├── config/ ← Konfiguracija (args layer) ├── databases/ ← SQLite baze (tasks, leads, invoices...) ├── memory/ ← MEMORY.md + sessions/ ├── agents/ ← identities/ + state/ + hivemind/ ├── backups/ ← Setup changelog + backups └── archive/ ← Arhivirani fajlovi References Original system : ~/clawd/ (backup, NE BRISATI) Tool manifest : ~/system/tools/manifest.md Rules : ~/system/rules/ Specs : ~/system/specs/ Tool Manifest Last Verified: 2026-02-17 | Owner: John Tools Manifest CHECK THIS BEFORE CREATING NEW TOOLS. If a tool exists, use it. If you create a new tool, add it here. TOOL-FIRST PROTOCOL: ~/system/rules/tool-first-protocol.md Redoslijed: Naši alati → Naši skillovi → Naša baza (HiveMind) → Internet → Ažuriraj bazu Last audit: 2026-02-13 — Spring cleaning: 22 deprecated tools archived, 3 empty DBs deleted, 1 broken daemon unloaded, MEMORY.md trimmed 229→184 lines. Task Management Tool Command Description task.sh ~/system/tools/task.sh list|add|start|done|block Task CLI using Taskwarrior 3 (cross-session) mc.js node ~/system/tools/mc.js list|add|start|done|show|routes Mission Control - Task management with agent routing mc.js routes node ~/system/tools/mc.js routes List available task routes (backend, frontend, devops, qa, bizdev, general) mc.js add --route node ~/system/tools/mc.js add "Task" --route backend Create task with route - auto-spawns agent on start Task → Agent Routing: MC tasks can be tagged with routes that automatically spawn appropriate Ollama agents when task starts. Routes: backend (dev), frontend (designer+dev), devops (devops), qa (auditor), bizdev (marketer), general (dev) Agent output is captured and stored in task.agent_output field Visible in mc.js show command If Ollama unavailable, gracefully degrades (logs error, doesn't block task) Agent runs in background via exec() - non-blocking Logs to HiveMind on spawn/completion/error Briefings & Analysis Tool Command Description council-briefing.js node ~/system/tools/council-briefing.js AI Council: 4 personas (Growth, Revenue, Skeptic, Ops) analyze business data via Ollama. Posts to Slack #exec. Nightly at 22:00. meeting-prep.js node ~/system/tools/meeting-prep.js [--ics file.ics] [--date YYYY-MM-DD] Calendar-aware meeting prep: ICS parsing, CRM attendee lookup, pipeline context, contextual notes. council-briefing.js node ~/system/tools/council-briefing.js --model 70b Use 70b model for deeper analysis council-briefing.js node ~/system/tools/council-briefing.js --dry-run Gather data only, no Ollama/Slack john-morning.sh bash ~/system/tools/john-morning.sh Morning routine: Quran, tasks, HiveMind, health, daily synthesis. Daily at 07:00. memory-synthesizer.js node ~/system/tools/memory-synthesizer.js daily [date] Summarize day's intel → HiveMind memo. Auto in morning-routine. memory-synthesizer.js node ~/system/tools/memory-synthesizer.js weekly Synthesize week → HiveMind memo. Auto Sundays 23:00. memory-synthesizer.js node ~/system/tools/memory-synthesizer.js promote Promote weekly → long-term knowledge memory-synthesizer.js node ~/system/tools/memory-synthesizer.js prune Delete daily memos >30 days memory-synthesizer.js node ~/system/tools/memory-synthesizer.js view [tier] View tiered memory (daily/weekly/longterm) Meeting & Transcript Processing Tool Command Description transcript-to-tasks.js node ~/system/tools/transcript-to-tasks.js Extract action items from meeting transcript → MC tasks via Ollama transcript-to-tasks.js node ~/system/tools/transcript-to-tasks.js --preview Preview extracted actions (no task creation) transcript-to-tasks.js node ~/system/tools/transcript-to-tasks.js --owner john Assign all extracted tasks to owner Formats: .txt, .md, .srt, .vtt. Tasks prefixed with [TRANSCRIPT]. Health & Quality Tool Command Description md-health.js node ~/system/tools/md-health.js Markdown health scanner: broken links, TODOs, empty files, stale dates. Integrated in AgentForge. md-health.js node ~/system/tools/md-health.js --json JSON output (for programmatic use) md-health.js node ~/system/tools/md-health.js --fix-todos List all TODOs across codebase md-health.js node ~/system/tools/md-health.js ~/path Scan specific path doc-index.sh bash ~/system/tools/doc-index.sh [--output file.json] [--verbose] Document indexer — scans ~/projects, ~/ALAI, ~/companies for all markdown files. Creates JSON index with metadata (path, category, size, modified). Output: ~/system/databases/doc-index.json doc-index.sh bash ~/system/tools/doc-index.sh --verbose Verbose mode — shows progress and breakdown by category API Utilities Tool Command Description api-fallback.js require('./api-fallback') Tiered API fallback + caching. fetchWithFallback(key, tiers, opts) tries each tier, caches result. api-fallback.js node ~/system/tools/api-fallback.js cache-stats Show cache stats api-fallback.js node ~/system/tools/api-fallback.js cache-clear Clear API cache Cache: ~/system/cache/api-fallback/ (file-based, per-key, TTL-aware) Usage Tracking Tool Command Description usage-tracker.js node ~/system/tools/usage-tracker.js log Log AI call usage (auto-hooked in agent-runner.js + council-briefing.js) usage-tracker.js node ~/system/tools/usage-tracker.js stats Usage summary (today, month, all-time) usage-tracker.js node ~/system/tools/usage-tracker.js stats --agent Per-agent breakdown usage-tracker.js node ~/system/tools/usage-tracker.js stats --month Daily breakdown this month usage-tracker.js node ~/system/tools/usage-tracker.js top Top agents by cost usage-tracker.js node ~/system/tools/usage-tracker.js recent [limit] Recent calls DB: ~/system/db/usage.db (SQLite). Auto-logged from agent-runner.js (Ollama) and council-briefing.js. Session Tracking Tool Command Description session-ledger.sh Auto (Stop/PreCompact hook) Deterministic session extraction (files, commands, topics, errors, git) session-search.sh bash ~/system/tools/session-search.sh topic|file|task|keyword|errors|recent Search sessions daily-consolidate.sh bash ~/system/tools/daily-consolidate.sh [YYYY-MM-DD] Consolidate day's sessions into daily log weekly-digest.sh bash ~/system/tools/weekly-digest.sh [YYYY-MM-DD] Generate weekly summary Session files: ~/system/memory/sessions/YYYY-MM-DD-HHMM-sessionid.md Memory Tool Command Description hivemind.js node ~/system/agents/hivemind/hivemind.js read [agent] [limit] Read shared intelligence (replaces memory-lookup.js) hivemind.js node ~/system/agents/hivemind/hivemind.js post Post intel hivemind.js node ~/system/agents/hivemind/hivemind.js query Search intel hivemind.js node ~/system/agents/hivemind/hivemind.js memo save|get|search|list Key-value memory store memory-indexer.py python ~/system/tools/memory-indexer.py Index memory for search Communication Tool Command Description slack.js node ~/system/tools/slack.js send "msg" Send message to Slack channel slack.js node ~/system/tools/slack.js read [limit] Read recent messages from channel slack.js node ~/system/tools/slack.js channels List all Slack channels slack.js node ~/system/tools/slack.js create-channel Create new channel slack.js node ~/system/tools/slack.js unread Check unread messages slack.js node ~/system/tools/slack.js users List workspace users slack.js node ~/system/tools/slack.js status Check Slack connection slack-bot.js node ~/system/tools/slack-bot.js Slack bot daemon — Claude Haiku via CLI (Socket Mode). AI backend: API → CLI → Ollama slack-bot.js node ~/system/tools/slack-bot.js --test Test AI backend connection email-to-task.js node ~/system/tools/email-to-task.js --from "x" --subject "y" --message-id "z" --class ACTION [--priority high] Auto-create MC tasks from ACTION emails with deduplication email-to-task.js node ~/system/tools/email-to-task.js --status Show email classification stats email-inbox.js node ~/system/tools/email-inbox.js status SQLite-backed email inbox — per-account stats (john, info, alai) email-inbox.js node ~/system/tools/email-inbox.js pending List unanswered ACTION emails email-inbox.js node ~/system/tools/email-inbox.js search "keyword" Full-text search in subject/from/sender name email-inbox.js node ~/system/tools/email-inbox.js mark responded|archived|read|ignored Update email status email-inbox.js node ~/system/tools/email-inbox.js stale [hours] Show emails unanswered > N hours (default 48) email-inbox.js node ~/system/tools/email-inbox.js insert --message-id "x" --account john --from-addr "x" --subject "x" --classification ACTION --priority high Insert email into inbox DB | MCP email | mcp__email__emails_find | Search emails (sender, subject, date, folder). Account: "john" or "info" | | MCP email | mcp__email__email_send | Send emails (to, subject, body, HTML, attachments) | | MCP email | mcp__email__email_respond | Reply/forward with proper threading | | MCP email | mcp__email__emails_modify | Mark read/unread, flag, archive, move | | MCP email | mcp__email__folders_list | List all email folders | EMAIL PRAVILO: SVE email operacije koriste MCP email tools (custom: email-mcp-bridge.js). Dva accounta: john@basicconsulting.no (account="john"), info@basicconsulting.no (account="info") Server: ~/system/tools/email-mcp-bridge.js (ImapFlow + Nodemailer, wraps our proven stack) Konfigurisano u ~/.claude/mcp.json mcpServers.email Credentials: ~/system/config/mail-credentials.json + mail-credentials-info.json Slack: alai-talk.slack.com (channels: ops, development, client-support, exec) Password Sharing & Credential Management Tool Command Description password-share.js node ~/system/tools/password-share.js create|retrieve|list|cleanup|audit Secure one-time password sharing with clients client-vault.js node ~/system/tools/client-vault.js init|add|list|get|rotate|check-rotation Per-client encrypted credential storage Agent Infrastructure Tool Command Description agent-reporter.js node ~/system/tools/agent-reporter.js --task --agent --status --summary Structured agent output — validates against schema, stores in mission-control.db, emits events, posts to HiveMind agent-reporter.js node ~/system/tools/agent-reporter.js --help Show usage and examples agent-reporter.js node ~/system/tools/agent-reporter.js --task 937 --agent B1 --status completed --summary "..." --deliverables '[...]' Full structured report with deliverables, metrics, evidence schema-validator.py PostToolUse hook on TaskUpdate Validates agent output JSON against agent-output-schema.json, logs violations to /tmp/schema-violations.log (warning-only, never blocks) goal-verifier.js node ~/system/tools/goal-verifier.js --task Automated goal verification — reads goal-schema.json, runs verification commands, updates statuses, stores in goals.db, emits events goal-verifier.js node ~/system/tools/goal-verifier.js --help Show usage, goal types, and operators goal-verifier.js node ~/system/tools/goal-verifier.js --task 937 --verbose Run verification with detailed output per goal goal-verifier.js node ~/system/tools/goal-verifier.js --task 937 --dry-run Preview what would be verified without running commands agent-worker.js node ~/system/tools/agent-worker.js Autonomous agent worker — polls MC every 5min, picks safe tasks, spawns Claude Code subagents, reports results agent-worker.js node ~/system/tools/agent-worker.js --once Run single cycle then exit agent-worker.js node ~/system/tools/agent-worker.js --dry-run Show next task without executing agent-worker.js node ~/system/tools/agent-worker.js --status Show worker status and config agent-worker.js node ~/system/tools/agent-worker.js --stop Stop daemon gracefully Agent Output Schema: ~/system/specs/agent-output-schema.json (JSON Schema draft-07) DB Table: mission-control.db.agent_reports (task_id, agent, status, summary, report_json) Event: agent.report emitted to event bus on report submission Created: 2026-02-15 (MC #937 Phase 1) Goal Schema: ~/system/specs/goal-schema.json (JSON Schema draft-07) DB: ~/system/databases/goals.db (goals, goal_history tables) Verification: verification-gate.py enforces goal verification for H/M priority tasks (if goal-schema.json present) Events: goal.verified , goal.failed emitted to event bus Created: 2026-02-15 (MC #937 Phase 4) Subagents (~/.claude/agents/) Agent Role Description builder.md Build Implements ONE task using GOTCHA, self-validates, reports via agent-reporter.js or TaskUpdate validator.md Verify Read-only GOTCHA compliance check + acceptance criteria, reports via agent-reporter.js Local AI (Ollama on Mac Studio M3 Ultra) 2 Tools — Executor + Orchestrator Tool Command Description agent-runner.js node ~/system/tools/agent-runner.js --task "X" Executor — sends ONE task to Ollama with agent identity + state agent-runner.js node ~/system/tools/agent-runner.js list List all agents with status agent-scheduler.js node ~/system/kernel/agent-scheduler.js spawn Orchestrator — forks agent-runner.js as child processes for parallel execution team-coordinator.js node ~/system/kernel/team-coordinator.js assign|execute|status|message|sync Team Orchestrator — multi-team coordination (Backend/Frontend/DevOps/QA) with cross-team messaging Relationship: agent-scheduler.js spawns agent-runner.js. Runner = single agent. Scheduler = multi-agent. team-coordinator.js uses scheduler for team execution. What agents do: Generate text responses via Ollama. They don't execute anything. State: ~/system/agents/state/*.json (persists between runs) Identities: ~/system/agents/identities/*.md (15 agents) | offline-mode.js | node ~/system/tools/offline-mode.js status | Offline Mode — check Ollama readiness for Claude fallback | | offline-mode.js | node ~/system/tools/offline-mode.js run "task" | Route task to best local model (auto-detects type) | | offline-mode.js | node ~/system/tools/offline-mode.js run "task" --agent dev | Use specific agent identity | | offline-mode.js | node ~/system/tools/offline-mode.js run "task" --text-only | Text-only mode (no tool execution) | | offline-mode.js | node ~/system/tools/offline-mode.js queue | Show outputs waiting for Claude review | | offline-mode.js | node ~/system/tools/offline-mode.js capabilities | What local models can/can't do | | offline-mode.js | node ~/system/tools/offline-mode.js batch tasks.txt | Run tasks from file (one per line) | | offline-mode.js | node ~/system/tools/offline-mode.js enable\|disable | Toggle offline mode on/off | | offline-mode.js | node ~/system/tools/offline-mode.js whitelist | Show safe read-only commands allowed offline | | offline-mode.js | node ~/system/tools/offline-mode.js check "command" | Check if command is whitelisted for offline use | Offline Mode: When Claude API hits usage limits, switch to local Ollama models. Auto-routes tasks to best model (qwen-coder for code, 70b for reasoning, 8b for trivial). All outputs saved to ~/system/offline-queue/ with NEEDS_REVIEW status. Claude reviews when back online. Capability matrix built in — knows what local models can/can't do. Created 2026-02-12. Tier Routing (CC Rate Limit Optimization) Tool Command Description ollama-engine.js require('./ollama-engine') Centralized Ollama API — generate(), classify(), healthCheck(). Consolidates duplicated Ollama HTTP code from 5+ files. ollama-engine.js node ~/system/tools/ollama-engine.js test Run health check + generate test tier-router.js require('./tier-router') Central AI Router — classify(caller, task) → {tier, engine, model}. Routes tasks to Ollama (free) or CC based on complexity. tier-router.js node ~/system/tools/tier-router.js test Run routing tests tier-router.js node ~/system/tools/tier-router.js classify Test classification for caller+task tier-router.js node ~/system/tools/tier-router.js stats Show routing stats (ollama vs cc) ollama-tool-agent.js node ~/system/tools/ollama-tool-agent.js --task "X" --model Y Ollama + Tools — multi-turn agent with read-only tools (read_file, glob, grep, list_dir, run_cmd). Replaces CC for explore/validate tasks. ollama-tool-agent.js node ~/system/tools/ollama-tool-agent.js --task "X" --verbose Verbose mode (show tool calls) Tier Routing Architecture: Tier 1 (Ollama 8b): classify, filter, extract, triage Tier 2 (Ollama 72b): summarize, draft, analyze, research, review Tier 2c (Ollama coder:32b): code review, debug, simple fix Tier 3 (CC Sonnet): multi-file coding, architecture Tier 4 (CC Opus): interactive sessions only Config: ~/system/config/tier-routing.json (caller→tier mapping, keywords, fallback) Integration: agent-worker.js routes tasks through tier-router before execution Fallback: Ollama failure → auto-escalate to CC Created: 2026-02-16 Models Model Size Use For qwen2.5-coder:32b 19GB Coding, debugging, refactoring llama3.1:70b 40GB Research, writing, analysis llama3.1:8b 5GB Fast validation, simple queries Routing & Decision Tool Command Description route.js node ~/system/tools/route.js project Lookup project (internal/external) route.js node ~/system/tools/route.js query "" Match request to company by routes route.js node ~/system/tools/route.js list List all projects and companies route.js node ~/system/tools/route.js add Add project to registry Registry: ~/system/databases/projects.json Event Bus Tool Command Description event-bus.js node ~/system/tools/event-bus.js emit [--publisher X] SQLite event bus — async emit/subscribe/dispatch. Decouples tools from point-to-point execSync. event-bus.js node ~/system/tools/event-bus.js list [--type X] [--status X] [--limit N] List events (supports * wildcard for type) event-bus.js node ~/system/tools/event-bus.js show Show event details with payload event-bus.js node ~/system/tools/event-bus.js replay Re-process a failed/completed event event-bus.js node ~/system/tools/event-bus.js dead-letter list|resolve|replay Dead letter queue management event-bus.js node ~/system/tools/event-bus.js stats Event bus statistics (counts, last 24h by type) event-bus.js node ~/system/tools/event-bus.js subscriptions list|register|seed Manage handler subscriptions event-bus.js node ~/system/tools/event-bus.js dispatch [--once] [--interval N] Start dispatch loop (default 2s) event-handlers.js require('./event-handlers.js') All subscriber handlers — task, lead, invoice, draft, email, job events Event Bus Architecture (Transactional Outbox Pattern): Domain tools (mc.js, sales-pipeline.js, invoice-generator.js, drafts.js) write events to outbox table in their own domain DB — same transaction as domain data. Atomic: if domain write succeeds, event is guaranteed. Daemon tools (email-agent.js, job-hunter-agent.js) use direct bus.emit() — no domain DB, fire-and-forget. Dispatcher daemon (event-dispatcher.js, 2s poll): Relay: reads outbox tables from 4 domain DBs → inserts into events.db → marks outbox processed Dispatch: claims pending events from events.db → calls registered handlers Handlers in event-handlers.js process events (Slack, HiveMind, Planka, leads, MC tasks, etc.) Retry: 3 attempts with backoff (0s → 30s → 2min) → dead letter queue → Slack alert DB: ~/system/databases/events.db (central store, separate from domain DBs) Outbox tables: mission-control.db, leads.db, invoices.db, drafts.db Daemon: com.john.event-dispatcher (KeepAlive=true) 13 event types: task.status_changed, task.created, lead.created, lead.stage_changed, lead.lost, invoice.created, invoice.overdue, invoice.paid, draft.created, draft.auto_approved, email.action_required, job.scored_perfect, job.scored_good Integrated tools: mc.js, sales-pipeline.js, invoice-generator.js, drafts.js (outbox), email-agent.js, job-hunter-agent.js (direct emit) GOTCHA Core Tool Command Description utils.js require('~/system/lib/utils') Shared utility library (log, file, path, time, validate) sales-pipeline.js node ~/system/tools/sales-pipeline.js add|list|show|advance|stats|forecast|auto-actions Lead CRM — tracks leads from prospect to won/lost. Auto-actions: archive old leads (lost >30d), escalate stale proposals (>14d no activity) outbound.js node ~/system/tools/outbound.js start|list|stats Cold outreach prospecting — 3-email sequence (Day 1 intro, Day 3 follow-up, Day 7 final). Creates lead (cold_email), drafts intro email (LOW risk), schedules Day 3+7 reminders. Tags leads with outbound-seq. email-to-contact.js node ~/system/tools/email-to-contact.js backfill Auto-populate contacts.db from email classifications. Creates contacts, logs interactions, skips spam/own. email-to-contact.js node ~/system/tools/email-to-contact.js stats CRM import statistics (auto-imported vs manual, interactions) contacts.js node ~/system/tools/contacts.js add|list|show|search|update|log|tag|stats Central contact database — all partners, clients, brokers, vendors contacts.js node ~/system/tools/contacts.js export-n8n Export n8n-monitored emails for Known Contact workflow contacts.js node ~/system/tools/contacts.js import-leads Import contacts from leads.db unified-crm.js node ~/system/tools/unified-crm.js pipeline|client|search|dashboard READ-ONLY integration layer across 5 databases (contacts, leads, invoices, tickets, MC tasks) contract-manager.js node ~/system/tools/contract-manager.js add|list|show|renew|terminate|renewal-check|status Contract lifecycle management — tracks contract status (draft→sent→signed→active→expired→terminated), auto-renewal alerts, MC task creation, Slack notifications. DB: contracts.db. Types: NDA, DPA, contract, SLA, MSA. contract-manager.js node ~/system/tools/contract-manager.js renewal-check [--dry-run] Check for contracts expiring within 30 days, create MC renewal tasks (auto-renew only), send Slack alerts to #ops document-store.js node ~/system/tools/document-store.js store Document storage & retention system — organizes business documents with retention policies. Standard path: ~/ALAI/clients/{client}/documents/{type}/. Types: contract (10y), nda (5y), invoice (5y), proposal (2y), dpa (10y), agreement (10y), signed (10y). DB: documents.db document-store.js node ~/system/tools/document-store.js list [client] [--type TYPE] List documents with optional filters document-store.js node ~/system/tools/document-store.js find Search documents by client/filename/notes document-store.js node ~/system/tools/document-store.js retention-check Flag documents past retention period (non-destructive) document-store.js node ~/system/tools/document-store.js stats Storage statistics by type and client send-signing-email.js node ~/system/tools/send-signing-email.js send|send-single|test|check ALAI branded document signing — creates DocuSeal submission + sends ALAI branded email with embedded logo via SMTP. Standard for all contracts/NDAs/DPAs. Always test first with test command. nda-generator.js node ~/system/tools/nda-generator.js create --name "Name" --company "Company" NDA PDF generator + DocuSeal signing flow — generates ALAI-branded NDA PDF via Puppeteer, uploads to DocuSeal, creates submission, sends ALAI branded signing emails. Flags: --preview (local PDF only), --test (send to post@alai.no), --orgnr, --address, --phone, --project. fiken.js node ~/system/tools/fiken.js status|companies|invoices|contacts|balances|dashboard Fiken API v2 integration — invoices list/show/sync, contacts list/show/sync, bank balances, CEO dashboard data. Syncs to invoices.db + contacts.db. invoice-generator.js node ~/system/tools/invoice-generator.js create|list|show|pay|pdf|send|remind|check-overdue|auto-remind|dashboard|stats Invoice CRUD with VAT, PDF/HTML generation, MCP email draft creation, auto-reminders (3 levels: friendly/firm/urgent), automatic escalation system (Day 7/14/30+) invoice-generator.js node ~/system/tools/invoice-generator.js auto-remind [--dry-run] Automatic invoice reminder escalation — Day 7: friendly (LOW risk draft), Day 14: firm (LOW risk draft + Slack), Day 30+: HIGH MC task + URGENT Slack. Norwegian templates. support-ticket.js node ~/system/tools/support-ticket.js create|list|show|update|assign|comment|stats Support ticket system with SLA tracking (P1-P4) email-to-ticket.js node ~/system/tools/email-to-ticket.js --sender "email" --subject "subject" --body "body" --uid uid Email → ticket bridge — detects support emails, creates tickets, generates ACK drafts, Slack + HiveMind notifications ticket-sla-checker.js node ~/system/tools/ticket-sla-checker.js SLA breach detector — monitors open tickets, escalates to Slack #ops, generates escalation drafts, HiveMind logs ticket-resolve-notify.js node ~/system/tools/ticket-resolve-notify.js --ticket-id TKT-12345 Resolution notifier — generates client resolution email draft, HiveMind log team-coordinator.js node ~/system/tools/team-coordinator.js teams|assign|handoff|block|unblock|sync|status Cross-team orchestration onboard-client.js node ~/system/tools/onboard-client.js new|status|list|timeline|undo One-command client onboarding — orchestrates project scaffold, sales pipeline, support, teams, routing, welcome email, pipeline events, HiveMind expansion-dashboard.js node ~/system/tools/expansion-dashboard.js [--compact] Aggregate view: companies, pipeline, invoices, support, teams proposal-gen.js node ~/system/tools/proposal-gen.js create|edit|pdf|send|list|show|approve|reject Professional proposal generator — auto-populates from leads, generates PDF, sends via SMTP (3 templates: standard, landing-page, webapp) pipeline-events.js node ~/system/tools/pipeline-events.js check-reminders Stage transition event handlers — auto-triggered by sales-pipeline.js on advance/lose, generates drafts (→ drafts.db), creates reminders (~/system/reminders/), logs to HiveMind, sends Slack notifications. Handlers: onQualified, onProposal, onNegotiating, onWon, onActive, onLost follow-up.js node ~/system/tools/follow-up.js check [--auto] Follow-up reminder processor — scans ~/system/reminders/ for due reminders, generates language-aware follow-up drafts (NO/EN/BS), 3 escalation levels (day 3/7/14), Slack alert on day 14 follow-up.js node ~/system/tools/follow-up.js list List all pending follow-up reminders with due dates and escalation levels follow-up.js node ~/system/tools/follow-up.js add Manually create follow-up reminder (types: proposal, inquiry) drafts.js node ~/system/tools/drafts.js list|show|approve|reject|send|stats Draft approval workflow — 3-level risk classification (low/medium/high), content-based pattern matching, smart auto-approval drafts.js node ~/system/tools/drafts.js process-auto [--dry-run] Auto-classify and process all pending drafts (LOW→approve+send, MEDIUM→approve+Slack+send, HIGH→manual) drafts.js node ~/system/tools/drafts.js auto-approve [--type type1,type2] Auto-approve low-risk drafts (optional type filter) drafts.js node ~/system/tools/drafts.js mark-sent [--message-id mid] Mark draft as sent (updates linked invoice status) drafts.js node ~/system/tools/drafts.js import Import JSON drafts from ~/system/drafts/ intake-analyzer.js node ~/system/tools/intake-analyzer.js detect-lang "text" Language detection (NO/EN/BS) via character markers + word frequency intake-analyzer.js node ~/system/tools/intake-analyzer.js analyze "text" Request analysis via Ollama — extracts category/scope/urgency, generates 3 pricing options from Vizu pricing.md intake-analyzer.js (module) const { detectLanguage, analyzeInquiry, generateOptions } = require('./intake-analyzer') Module API for client intake pipeline intake-analyzer.js: Language detector (æøå→NO, ćčšžđ→BS, word frequency lists) + request analyzer (Ollama llama3.1:8b JSON extraction) + option generator (reads ~/ALAI/pipeline/Vizu/finance/pricing.md, maps category→packages, generates A/B/C options). Heuristic fallback when Ollama unavailable. Pure Node.js, no dependencies. Created: 2026-02-13 (MC #840). follow-up.js: Automated follow-up reminder system. Proposal reminders: day 3 (gentle), day 7 (nudge), day 14 (final + Slack). General inquiry: day 5. Language-aware templates (NO/EN/BS) extracted from lead intake analysis. Idempotent processing (marks reminders as processed). Legacy reminder migration: infers missing escalation_level and lang fields from due date and lead notes. Wired into gotcha-health.sh (runs every 15 min). Reminder format: JSON files in ~/system/reminders/ with fields: id, lead_id, type, due_date, escalation_level, created_at, processed, lang. Created: 2026-02-13 (MC #840). Image Generation Tool Command Description image-gen.js node ~/system/tools/image-gen.js --prompt "desc" --output path.png Generate image via Gemini (free) or Together.ai image-gen.js node ~/system/tools/image-gen.js --setup gemini YOUR_KEY Save API key to config image-gen.js node ~/system/tools/image-gen.js --prompt "desc" --count 4 Generate multiple images Providers: Gemini (default, free, no CC), Together.ai (FLUX, free tier) Keys: ~/system/config/image-gen.json or env vars GEMINI_API_KEY , TOGETHER_API_KEY Get key: https://aistudio.google.com/apikey (2 min, no credit card) | brand-compositor.js | node ~/system/tools/brand-compositor.js all | Deterministic brand asset generator — resize/composite REAL logo (profile-pic.png) onto social banners, profiles, favicons. No AI generation. | | brand-compositor.js | node ~/system/tools/brand-compositor.js profile\|avatar\|banner-linkedin\|banner-twitter\|og-image\|favicon | Generate specific asset type | | design-engine.js | node ~/system/tools/design-engine.js render