New:Socket for Asana Is Now Available.Learn more
Get Started

universal-agent-protocol

Package Overview
Dependencies
Maintainers
1
Versions
54
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

universal-agent-protocol

Autonomous AI agent memory system with CLAUDE.md protocol enforcement

latest
Source
npmnpm
Version
10.13.0
Version published
Weekly downloads
10
25%
Maintainers
1
Weekly downloads
 
Created
Source

Universal Agent Protocol (UAP) v8.7.0

npm version License: MIT

AI agents that learn, remember, and coordinate

Every lesson, every pattern, every memory preserved across sessions.

Not just in one conversation -- but forever.

Quick Start (30 seconds)

npm install -g universal-agent-protocol
cd your-project
uap init
uap setup -p all

Table of Contents

Feature Overview

CategoryComponentsPurpose
Memory23 modules4-layer persistent memory with embeddings, knowledge graph, compression
Coordination6 modulesMulti-agent lifecycle, work claims, messaging, overlap detection
Deploy Batching1 moduleSquash, merge, parallelize deploy actions across agents
Policy Enforcement6 modulesStore, evaluate, and enforce operational policies with audit trail
Browser1 moduleStealth web automation via CloakBrowser (Playwright drop-in)
MCP Router6 modules2-tool meta-router replacing N tool definitions (98% token savings)
Models4 modulesMulti-model routing, planning, execution, validation
Patterns22 patternsBattle-tested workflows from Terminal-Bench 2.0
Droids8+ expertsSpecialized agents for security, performance, docs, testing
Skills27 skillsReusable domain expertise (chess, polyglot, compression, etc.)
Tasks4 modulesFull task lifecycle with dependencies, claims, JSONL sync
Worktrees1 moduleIsolated git branches per agent, auto-numbered
Hooks2 hooksSession start (memory injection) and pre-compact (preservation)
CLI20+ commandsFull system management with rich dashboard visualization
Benchmarks10+ modulesTerminal-Bench adapter, Harbor integration, A/B comparison
LLM Optimization5 modulesQwen3.5 tool call fixes, llama.cpp optimizer, LoRA training
RTK1 module60-90% token savings on command outputs
Platforms6 platformsClaude, Factory, OpenCode, ForgeCode, VSCode, Cursor

1. Memory System (23 Components)

Architecture: 4 Layers

+-------------------------------------------------------------------+
|  L1: WORKING       | Recent actions        | 50 max  | SQLite    |
|  L2: SESSION        | Current session       | Per run | SQLite    |
|  L3: SEMANTIC       | Long-term learnings   | Qdrant  | Vectors   |
|  L4: KNOWLEDGE      | Entity relationships  | SQLite  | Graph     |
+-------------------------------------------------------------------+

Hierarchical Tiers (Hot/Warm/Cold)

TierEntriesAccess TimeBehavior
Hot10<1msAlways in context
Warm50<5msPromoted on access
Cold500~50msSemantic search only

Time-decay formula: effective_importance = importance * decayRate^daysSinceAccess

Memory Components

ComponentFilePurpose
Short-Term (SQLite)src/memory/short-term/sqlite.tsFTS5 full-text search, WAL mode, speculative cache
Short-Term (IndexedDB)src/memory/short-term/indexeddb.tsBrowser environment backend
Hierarchical Memorysrc/memory/hierarchical-memory.tsHot/warm/cold tiering with auto-promotion/demotion
Embedding Servicesrc/memory/embeddings.ts4 providers: Ollama, OpenAI, sentence-transformers, TF-IDF fallback
GitHub Backendsrc/memory/backends/github.tsStore memories as JSON files in a GitHub repo
Qdrant Backendsrc/memory/backends/qdrant-cloud.tsVector search with project-isolated collections
Serverless Qdrantsrc/memory/serverless-qdrant.tsAuto-start/stop Docker, cloud fallback, idle shutdown
Write Gatesrc/memory/write-gate.tsQuality filter: behavioral change, commitment, decision, stable fact, user request
Daily Logsrc/memory/daily-log.tsStaging area -- all writes land here first, user promotes
Correction Propagationsrc/memory/correction-propagator.tsCross-tier updates, old claims marked [superseded]
Memory Maintenancesrc/memory/memory-maintenance.tsPrune, decay, archive, deduplicate (similarity > 0.92)
Agent-Scoped Memorysrc/memory/agent-scoped-memory.tsPer-agent partitions, explicit cross-agent sharing
Memory Consolidationsrc/memory/memory-consolidator.tsTriggers every 10 entries, recursive summarization
Context Compressionsrc/memory/context-compressor.ts3 levels (light/medium/aggressive), token budgets
Semantic Compressionsrc/memory/semantic-compression.tsSimpleMem-style atomic facts, 30x token reduction
Multi-View (ENGRAM)src/memory/multi-view-memory.tsEpisodic/semantic/procedural typing, multi-index
Speculative Cachesrc/memory/speculative-cache.tsPre-computes likely queries, LRU with TTL
Knowledge Graphsrc/memory/knowledge-graph.tsEntities + relationships in SQLite, <20ms access
Dynamic Retrievalsrc/memory/dynamic-retrieval.tsAdaptive depth based on query complexity
Adaptive Contextsrc/memory/adaptive-context.ts21 optimizations, historical benefit tracking
Task Classifiersrc/memory/task-classifier.tsClassifies into 9 categories, suggests droids
Model Routersrc/memory/model-router.tsRoutes to optimal model by task type and cost
Prepopulationsrc/memory/prepopulate.tsImport from docs (markdown) and git history

2. Multi-Agent Coordination

How Agents Work Together Without Collisions

Agent A                    Agent B                    Agent C
   |                          |                          |
   v                          v                          v
[Register]              [Register]               [Register]
   |                          |                          |
   v                          v                          v
[Heartbeat 30s]         [Heartbeat 30s]          [Heartbeat 30s]
   |                          |                          |
   v                          v                          v
[Announce: src/auth/]   [Announce: src/api/]     [Announce: src/ui/]
   |                          |                          |
   v                          v                          v
[Overlap Check]         [Overlap Check]          [Overlap Check]
   |                          |                          |
   v                          v                          v
[Worktree: 001-auth]    [Worktree: 002-api]      [Worktree: 003-ui]
   |                          |                          |
   v                          v                          v
[Work in isolation]     [Work in isolation]      [Work in isolation]
   |                          |                          |
   v                          v                          v
[Queue deploy]          [Queue deploy]           [Queue deploy]
   |                          |                          |
   +----------+---------------+----------+---------------+
              |                          |
              v                          v
        [Deploy Batcher]           [Squash & Execute]

Coordination Components

ComponentFilePurpose
Coordination Servicesrc/coordination/service.tsAgent lifecycle, work claims, announcements, messaging
Coordination Databasesrc/coordination/database.tsSQLite with WAL: agents, claims, announcements, messages, deploys
Capability Routersrc/coordination/capability-router.tsRoutes tasks to droids by 18 capability types
Auto-Agentsrc/coordination/auto-agent.tsAutomatic registration, heartbeat, graceful shutdown
Pattern Routersrc/coordination/pattern-router.tsLoads Terminal-Bench patterns, always includes critical ones

Overlap Detection

Conflict risk levels: none | low | medium | high | critical

Detection checks:

  • File-level overlap (same files modified)
  • Directory-level overlap (same directories)
  • Collaboration suggestions (merge order, sequential vs parallel)

Messaging

  • Broadcast -- all agents
  • Direct -- specific agent
  • Channels -- broadcast, deploy, review, coordination
  • Priority -- normal, high, urgent
  • Read receipts -- delivery confirmation

3. Deploy Batching

Prevents deploy storms when multiple agents finish work simultaneously.

How It Works

Agent A queues: commit -> push
Agent B queues: commit -> push
Agent C queues: commit -> push
                    |
                    v
            [Deploy Batcher]
                    |
                    v
        Squash 3 commits into 1
        Single push to remote

Batch Windows (per action type)

ActionDefault WindowUrgent Window
commit30s3s
push5s1s
merge10s2s
workflow5s1s
deploy60s5s

Features

  • Squashing -- Multiple commits to same target become one
  • Merging -- Similar pending actions deduplicated
  • Parallel execution -- Independent workflows run concurrently
  • Sequential safety -- State-dependent actions (commit, push, merge) run in order
  • Timeout protection -- 300s default, prevents hung processes
  • Dry run -- Preview mode before execution
  • Urgent mode -- Reduces all windows to minimum

CLI

uap deploy queue --action commit --target main --message "feat: add auth"
uap deploy batch                    # Group pending actions
uap deploy execute                  # Run the batch
uap deploy status                   # View queue
uap deploy flush                    # Force-execute all pending
uap deploy config                   # View batch config
uap deploy set-config --urgent      # Enable urgent mode

4. Policy Enforcement System

Architecture (3 Layers)

                    Tool Call
                        |
                        v
              [EnforcedToolRouter]
                        |
                        v
                  [PolicyGate]
                   /    |    \
                  v     v     v
             [Policy] [Policy] [Policy]
              REQUIRED  RECOMMENDED  OPTIONAL
                  |
                  v
            [Allow / Block]
                  |
                  v
            [Audit Trail]

Components

ComponentFilePurpose
Policy Schemasrc/policies/schemas/policy.tsZod schemas for policies and executions
Database Managersrc/policies/database-manager.tsSQLite with WAL, JSON serialization, 3 tables
Policy Memorysrc/policies/policy-memory.tsCRUD, relevance search, tag/category filtering
Policy Toolssrc/policies/policy-tools.tsStore/execute Python enforcement tools
Policy Gatesrc/policies/policy-gate.tsMiddleware: check REQUIRED policies, block violations
Enforced Tool Routersrc/policies/enforced-tool-router.tsSingle entry point for all tool calls
Policy Convertersrc/policies/convert-policy-to-claude.tsMarkdown to CLAUDE.md format

Enforcement Levels

LevelBehavior
REQUIREDBlocks execution if violated, throws PolicyViolationError
RECOMMENDEDLogged but does not block
OPTIONALInformational only

Audit Trail

Every policy check is logged to policy_executions table:

  • Policy ID, tool name, operation, arguments
  • Allowed/blocked decision with reason
  • Timestamp

CLI

uap-policy add -f policies/image-rules.md -c image -l REQUIRED
uap-policy list
uap-policy check -o "vision_count" -a '{"image":"photo.png"}'
uap-policy audit -n 50
uap-policy convert -i <policy-id> -o output.md
uap-policy add-tool -p <id> -t count_elements -c scripts/count.py

5. Browser Automation (CloakBrowser)

Stealth web browser via CloakBrowser -- a Playwright drop-in with 33 source-level C++ patches.

Capabilities

FeatureStatus
Headless ChromeReal Chrome UA (not "HeadlessChrome")
webdriver flagfalse (undetectable)
Plugins5 detected (matches real browser)
window.chromePresent
reCAPTCHA v30.9 score
Cloudflare TurnstilePasses
FingerprintJSUndetected
Persistent profilesCookie/localStorage persistence

Usage

import { createWebBrowser } from 'universal-agent-protocol/browser';

const browser = createWebBrowser();
await browser.launch({ headless: true, humanize: true });
await browser.goto('https://example.com');
const content = await browser.getContent();
await browser.evaluate(() => document.title);
await browser.close();

6. MCP Router (98% Token Reduction)

Replaces N tool definitions with 2 meta-tools.

Before vs After

Before: 47 tools exposed = ~12,000 tokens in system prompt
After:  2 tools exposed  = ~200 tokens in system prompt
                           (98.3% reduction)

Components

ComponentFilePurpose
MCP Serversrc/mcp-router/server.tsExposes discover_tools and execute_tool
Config Parsersrc/mcp-router/config/parser.tsLoads MCP configs from standard paths
Fuzzy Searchsrc/mcp-router/search/fuzzy.tsTool discovery with fuzzy matching
Client Poolsrc/mcp-router/executor/client.tsManages connections to MCP servers
Output Compressorsrc/mcp-router/output-compressor.tsCompresses tool output
Session Statssrc/mcp-router/session-stats.tsPer-tool token consumption tracking

7. Multi-Model Architecture

3-Tier Execution

Tier 1: TaskPlanner    -- Decomposes task into subtasks
Tier 2: ModelRouter    -- Assigns optimal model per subtask
Tier 3: TaskExecutor   -- Executes with validation
ComponentFilePurpose
Model Routersrc/models/router.tsRoutes by complexity (critical/high/medium/low) and cost
Task Plannersrc/models/planner.tsDecomposition, dependency analysis, parallelization
Task Executorsrc/models/executor.tsExecutes plans with model clients
Plan Validatorsrc/models/plan-validator.tsCycle detection, coherence checks, timeout protection

8. Pattern System (22 Patterns)

Battle-tested patterns from Terminal-Bench 2.0 analysis, stored in .factory/patterns/.

PatternIDCategoryWhat It Prevents
Output ExistenceP12Verification37% of failures (missing output files)
Output FormatP14VerificationWrong format/encoding
Constraint ExtractionP17PlanningMissing hidden requirements
Task-FirstP16ExecutionOver-planning before doing
Impossible RefusalP19SafetyAttempting impossible tasks
AdversarialP20SecurityMissing attack vectors
Chess EngineP21DomainReinventing Stockfish
Git RecoveryP22RecoveryData loss during git ops
Compression CheckP23VerificationLossy compression errors
PolyglotP24Code-GolfSingle-language thinking
Service ConfigP25DevOpsMisconfigured services
Near-MissP26TestingAlmost-correct solutions
Smoke TestP28TestingUntested changes
Performance ThresholdP30OptimizationMissing perf targets
Round-TripP31VerificationEncode/decode mismatches
CLI VerifyP32VerificationBroken CLI commands
Numerical StabilityP33TestingFloating point errors
Image PipelineP34DomainImage processing errors
Decoder-FirstP35AnalysisWrong problem decomposition
Competition DomainP36ResearchMissing domain knowledge
IaC ParityIaCInfrastructureConfig drift
Iterative RefinementP13TestingFirst-attempt acceptance

9. Droids & Skills

Expert Droids (8+)

DroidFileSpecialization
Code Quality Guardian.factory/droids/code-quality-guardian.mdCode review, quality enforcement
Debug Expert.factory/droids/debug-expert.mdDebugging specialist
Documentation Expert.factory/droids/documentation-expert.mdDocumentation
ML Training Expert.factory/droids/ml-training-expert.mdML/training
Performance Optimizer.factory/droids/performance-optimizer.mdPerformance
Security Auditor.factory/droids/security-auditor.mdSecurity review
Sysadmin Expert.factory/droids/sysadmin-expert.mdSystem administration
Terminal-Bench Optimizer.factory/droids/terminal-bench-optimizer.mdBenchmark optimization

Skills (27 total)

Project Skills (5): codebase-navigator, memory-management, near-miss-iteration, terminal-bench, worktree-workflow

Claude Skills (5): hooks-session-start, hooks-pre-compact, scripts-tool-router, scripts-preload-memory, session-context-preservation-droid

Factory Skills (16): adversarial, balls-mode, batch-review, chess-engine, cli-design-expert, codebase-navigator, compression, git-forensics, near-miss, polyglot, sec-context-review, service-config, terminal-bench-strategies, typescript-node-expert, unreal-engine-developer

10. Task Management

Full task lifecycle with dependencies, claims, and JSONL sync for git versioning.

FeatureDescription
Typestask, bug, feature, epic, chore, story
Statusesopen, in_progress, blocked, done, wont_do
PrioritiesP0 (critical) through P4 (low)
Dependenciesblocks, related, discovered_from
ClaimsExclusive claim with worktree + announcement
JSONL SyncGit-versionable task export
CompactionArchive old closed tasks

11. Worktree System

Each agent works in an isolated git worktree to prevent conflicts.

uap worktree create my-feature
# Creates: .worktrees/001-my-feature/
# Branch:  001-my-feature
# Registry: .uap/worktree_registry.db

uap worktree list          # Show all worktrees
uap worktree pr 001        # Create PR
uap worktree cleanup 001   # Remove worktree + branch

Auto-numbered (NNN-slug) to prevent naming collisions between agents.

12. Hooks System

Session Start Hook

Runs at every session start:

  • Cleans stale agents (>24h no heartbeat)
  • Injects UAP compliance checklist (10 steps)
  • Loads recent memories (last 24h)
  • Surfaces open loops from session memories
  • Warns about stale worktrees

Pre-Compact Hook

Runs before context compaction:

  • Records compaction marker in memory
  • Checks if lessons were stored (warns if not)
  • Outputs compliance reminder
  • Cleans up agents from current session

Supported Platforms

uap hooks install claude
uap hooks install factory
uap hooks install cursor
uap hooks install vscode
uap hooks install opencode
uap hooks install forgecode

13. CLI Reference (20+ Commands)

Core

CommandDescription
uap initInitialize UAP in a project
uap setup -p allFull setup (memory, Qdrant, hooks, patterns)
uap generateRegenerate CLAUDE.md from templates
uap updateUpdate all components
uap analyzeAnalyze project structure
uap compliance checkVerify UAP compliance
uap dashboardRich terminal dashboard

Memory

CommandDescription
uap memory statusCheck memory system
uap memory query <search>Search memories
uap memory store <content>Store a learning (write-gated)
uap memory startStart Qdrant
uap memory prepopulateImport from docs/git
uap memory promotePromote daily log entries
uap memory correctCorrect a memory (propagates)
uap memory maintainRun maintenance (prune, decay, dedup)

Coordination

CommandDescription
uap agent registerRegister agent
uap agent heartbeatSend heartbeat
uap agent announceAnnounce work area
uap agent overlapsCheck for conflicts
uap agent broadcastMessage all agents
uap coord statusCoordination overview
uap coord cleanupClean stale agents

Deploy

CommandDescription
uap deploy queueQueue a deploy action
uap deploy batchGroup pending actions
uap deploy executeRun the batch
uap deploy flushForce-execute all
uap deploy statusView queue

Additional Binaries

BinaryDescription
uap-policyPolicy management (add, list, check, audit)
uap-tool-callsQwen3.5 tool call fixes
llama-optimizellama.cpp startup parameter generator

14. Benchmarking System

Terminal-Bench adapter for A/B comparison of UAM-enabled vs naive agents.

ComponentFilePurpose
Benchmark Frameworksrc/benchmarks/benchmark.tsTask schemas, verification functions
Benchmark Runnersrc/benchmarks/runner.tsOrchestrates execution
Naive Agentsrc/benchmarks/agents/naive-agent.tsBaseline without UAM
UAM Agentsrc/benchmarks/agents/uam-agent.tsUAM-enabled agent
SUPERGENIUS Agentsrc/uam_harbor/supergenius_agent.pyPython agent targeting 80%+
Harbor Datasetsharbor-datasets/Docker-sandboxed benchmark tasks

15. Qwen3.5 / Local LLM Optimization

ComponentFilePurpose
Tool Call Fixestools/agents/scripts/qwen_tool_call_*.pyFix Qwen3.5 tool call reliability
Chat Template Fixtools/agents/scripts/fix_qwen_chat_template.pyTemplate modifications
Llama Optimizersrc/bin/llama-server-optimize.tsOptimal llama.cpp params for 16/24GB VRAM
LoRA Trainingtools/agents/scripts/generate_lora_training_data.pyFine-tuning data generation
Qwen Settingsconfig/qwen35-settings.jsonModel-specific configuration

16. RTK (Rust Token Killer)

60-90% token savings on command outputs.

uap rtk install    # Install RTK
uap rtk status     # Check installation
uap rtk help       # Usage guide

17. Platform Integrations

PlatformDirectoryFeatures
Claude Code.claude/Hooks, skills, settings, commands, agents
Factory.AI.factory/Droids, skills, hooks, patterns, config
OpenCode.opencode/Plugin system, config
ForgeCode.forge/ZSH plugin, hooks
VSCode.vscode/Workspace settings, extensions
Beads.beads/Git-native issue tracking with JSONL, daemon RPC

18. Harness Feature Matrix

Every AI coding harness ships as a stateless editor with file and terminal access. UAP closes the gap between "tool that edits code" and "agent platform that learns, coordinates, and enforces policy." It works with 15 harnesses across 4 integration tiers -- same features everywhere, deeper wiring on first-class platforms.

What UAP Adds (and Why It Matters)

  • 4-layer persistent memory -- agents retain lessons, decisions, and corrections across sessions instead of starting from zero
  • Write gate -- 5-criteria quality filter prevents memory pollution so only high-value knowledge is stored
  • 22 battle-tested patterns -- Terminal-Bench 2.0 workflows eliminate the 37% of failures caused by missing output files, wrong formats, and skipped verification
  • Pattern RAG -- on-demand pattern retrieval saves ~12K tokens per session by injecting only relevant patterns
  • Worktree isolation -- each agent works in its own git worktree so parallel agents never corrupt each other's state
  • Multi-agent coordination -- heartbeats, overlap detection, and conflict risk assessment let 2-10+ agents collaborate without collisions
  • Deploy batching -- squash commits and serialize pushes to prevent deploy storms when multiple agents finish simultaneously
  • Policy enforcement -- required/recommended/optional rules with audit trail ensure agents follow project standards
  • Task management -- dependency-aware DAG with cycle detection, claims, and JSONL sync for git-versionable task tracking
  • Model routing -- routes subtasks to optimal models by complexity and cost across 6 presets
  • MCP Router -- replaces N tool definitions with 2 meta-tools for 98% token reduction in system prompts
  • RTK -- 60-90% token savings on command outputs via Rust-based compression
  • 12-gate compliance -- automated protocol verification catches drift before it ships
  • 20+ CLI commands -- full system management with rich dashboard visualization

Full 15-harness matrix with per-harness integration details: docs/reference/HARNESS-MATRIX.md

Baseline: What Harnesses Provide Natively

FeatureClaude CodeFactory.AIOpenCodeForgeCodeCursorVSCodeClineWindsurf
File system + terminalYesYesYesYesYesYesYesYes
Context fileCLAUDE.mdPROJECT.md----.cursorrules--.clinerules.windsurfrules
Native hooksYesYesPlugin APIZSHhooks.json------
MCP supportNativeNativeConfig--NativeVia extVia extVia ext
Persistent sessionsYesYesYesZSH envLimitedLimitedLimitedLimited
Local LLM support----NativeYesYesVia extYesYes
Persistent memory----------------
Pattern library----------------
Multi-agent coordination----------------
Policy enforcement----------------

The bottom four rows are the gap. No harness provides them. UAP does.

With UAP: Uniform Capabilities Across All Harnesses

CapabilityBenefitAll Harnesses
4-layer memory (L1-L4)Agents remember across sessionsYes
Write gate + tieringOnly high-value knowledge storedYes
22 patterns + RAGProven workflows, ~12K token savingsYes
Worktree isolationParallel agents, zero conflictsYes
Multi-agent coordinationHeartbeats, overlap detection, claimsYes
Deploy batchingNo push races, squashed commitsYes
Policy engineAudit-trailed rule enforcementYes
Task DAGDependency-aware work trackingYes
Model routerRight model for each subtaskYes
MCP Router98% system prompt token reductionYes
RTK compression60-90% output token savingsYes
12-gate complianceAutomated protocol verificationYes
20+ CLI commandsFull management + dashboardYes

Integration Tiers

TierHarnessesWhat You Get
T1 -- First-ClassClaude Code, Factory.AI, OpenCode, ForgeCodeNative hooks, dedicated config dir, uap sync, context file generation
T2 -- IDE-BasedCursor, VSCode, ClinePlatform-specific hooks, MCP config paths
T3 -- CLI/TerminalWindsurf, Codex CLI, Aider, Zed AIMapped to T1/T2 via CLAUDE.md or .cursorrules
T4 -- AdditionalGitHub Copilot, JetBrains AI, SWE-agent, ContinuePiggybacks on T2 infrastructure

All tiers receive identical UAP features. The difference is integration depth, not capability.

Guardrails

Completion Gates (Mandatory)

Every task must pass 3 gates before completion:

GateCheckPrevents
OUTPUT_EXISTSAll expected files existPhantom completions
CONSTRAINTS_METAll requirements verifiedPartial implementations
TESTS_PASSnpm test passes 100%Broken code

Write Gate (Memory Quality)

Evaluates 5 criteria before storing a memory:

  • Behavioral change -- Does this change how we work?
  • Commitment with consequences -- Is there a real commitment?
  • Decision with rationale -- Was a decision made and why?
  • Stable recurring fact -- Is this a durable fact?
  • Explicit user request -- Did the user ask to remember this?

Minimum score: 0.3 (configurable). Noise patterns filter acknowledgments and transient requests.

Policy Enforcement

REQUIRED policies block tool execution. Every check is logged to the audit trail. PolicyViolationError thrown with structured details.

Pattern Router

Critical patterns (Output Existence, Decoder-First) are always active regardless of task classification.

Correction Propagation

When a memory is corrected, old claims are marked [superseded] with date and reason across all tiers.

Stale Agent Cleanup

Session hooks automatically clean agents with no heartbeat for >24 hours.

Scaling: More Devs, More Agents

How Multiple Agents Avoid Collisions

MechanismHow It Works
Worktree isolationEach agent gets its own git worktree (.worktrees/NNN-slug/). No shared working directory.
Work announcementsAgents announce which files/directories they're touching. Overlap detection warns of conflicts.
Conflict risk levelsnone / low / medium / high / critical -- agents can decide whether to proceed.
Collaboration suggestionsSystem recommends merge order and sequential vs parallel work.
Deploy batchingMultiple agents' commits are squashed and pushed in a single batch, preventing push races.
Agent-scoped memoryEach agent has its own memory partition. Cross-agent sharing requires explicit promotion.
Heartbeat liveness30-second heartbeats detect crashed agents. Stale agents cleaned automatically.
Exclusive claimsTransaction-safe resource claiming with expiry prevents double-work.

Scaling from 1 to N Agents

1 agent:   No coordination needed. Worktree optional.
2-3 agents: Worktrees + announcements. Deploy batching recommended.
4-10 agents: Full coordination. Capability routing. Deploy batching required.
10+ agents: All of the above + agent-scoped memory + messaging channels.

Scaling from 1 to N Developers

ConcernSolution
Config conflicts.uap.json is project-scoped, not user-scoped
Memory conflictsSQLite WAL mode supports concurrent reads
Worktree namingAuto-numbered (001, 002, ...) prevents collisions
Deploy racesBatcher squashes and serializes state-dependent actions
Pattern driftPatterns indexed in Qdrant, shared across all agents
Policy consistencyPolicies stored in SQLite, enforced uniformly

Database Concurrency

All SQLite databases use WAL (Write-Ahead Logging) mode:

  • Multiple concurrent readers
  • Single writer with no reader blocking
  • Busy timeout prevents lock contention errors

Resource Isolation

agents/data/
  memory/
    short_term.db          # Shared memory (WAL mode)
    policies.db            # Shared policies (WAL mode)
  coordination/
    coordination.db        # Shared coordination (WAL mode)
.uap/tasks/
  tasks.db                 # Shared tasks (WAL mode)
.uap/
  worktree_registry.db     # Shared worktree registry
.worktrees/
  001-feature-a/           # Agent A's isolated checkout
  002-feature-b/           # Agent B's isolated checkout

Configuration

.uap.json (Project)

{
  "project": { "name": "my-project", "defaultBranch": "main" },
  "memory": {
    "shortTerm": { "enabled": true, "path": "./agents/data/memory/short_term.db" },
    "longTerm": { "enabled": true, "provider": "qdrant" }
  },
  "worktrees": { "enabled": true, "directory": ".worktrees" }
}

opencode.json (Platform)

{
  "provider": {
    "llama.cpp": {
      "options": { "baseURL": "http://localhost:8080/v1" },
      "models": {
        "qwen35-a3b-iq4xs": {
          "limit": { "context": 262144, "output": 81920 }
        }
      }
    }
  }
}

Testing & Quality

npm test              # 271 tests across 24 test files
npm run build         # TypeScript compilation
npm run lint          # ESLint
npm run format        # Prettier

Test Coverage

AreaTests
Deploy Batcher16 tests
CoordinationMulti-agent lifecycle
TasksCRUD, dependencies, claims
ModelsRouter, planner, validator
MemoryWrite gate, daily log, corrections, maintenance, scoped
MCP RouterFilter, output compressor
BrowserNavigation, evaluate, content extraction
DroidsParallel execution

Requirements

DependencyVersionRequiredPurpose
Node.js>= 18.0.0YesRuntime
gitLatestYesVersion control
DockerLatestNoLocal Qdrant
Python 3LatestNoEmbeddings, Pattern RAG

Attribution

Documentation | Issues | npm

Built for developers who want AI that learns.

Keywords

claude

FAQs

Package last updated on 16 Mar 2026

Related posts