Deployment Guide
| Requirement | Minimum | Recommended | |-------------|---------|-------------| | Node.js | v18.x | v20.x+ | | Python | 3.9+ | 3.11+ | | RAM | 1 GB | 4 GB | | Storage | 100 MB | 1 GB (with history) |
Full Public Reader
Deployment Guide
> Step-by-step guide to deploying the Agent Reputation System
---
๐ Prerequisites
System Requirements
| Requirement | Minimum | Recommended |
|---|---|---|
| Node.js | v18.x | v20.x+ |
| Python | 3.9+ | 3.11+ |
| RAM | 1 GB | 4 GB |
| Storage | 100 MB | 1 GB (with history) |
Dependencies
Node.js:
npm installPython:
pip install -r requirements.txt
# Or manually:
pip install dataclasses datetime typing> Note: The Python modules use only standard library components.
---
๐ Quick Start
1. Clone & Install
git clone <repository-url>
cd agent-reputation
npm install2. Run Demos
# TypeScript demo
npm run demo
# Python demos
python3 reputation_markets.py
python3 reputation_dynamics.py3. Build for Production
npm run build
# Output: dist/trust-bootstrap.js---
๐๏ธ Deployment Options
Option A: Embedded Library
Use directly in your Node.js/Python application.
TypeScript:
import {
TrustBootstrapEngine,
PeerAssessmentEngine,
TrustTransferProtocol
} from './trust-bootstrap';
import { ReputationPredictionMarket, Domain } from './src/prediction-market';
// Initialize
const engine = new TrustBootstrapEngine();
const market = new ReputationPredictionMarket();Python:
from reputation_markets import ReputationMarketplace, PredictionType
from reputation_dynamics import CascadeEngine, TrajectoryRouter
# Initialize
marketplace = ReputationMarketplace()
cascade = CascadeEngine()
router = TrajectoryRouter(cascade)Option B: Microservice
Wrap in REST API for external access.
Express.js Example:
import express from 'express';
import { ReputationPredictionMarket } from './src/prediction-market';
const app = express();
const market = new ReputationPredictionMarket();
app.post('/agents', (req, res) => {
const agent = market.registerAgent(req.body.name, req.body.domains);
res.json(agent);
});
app.post('/markets', (req, res) => {
const m = market.createPredictionMarket(
req.body.taskId,
req.body.description,
req.body.domain,
req.body.agentId,
new Date(req.body.deadline)
);
res.json(m);
});
app.post('/bets', (req, res) => {
const bet = market.placeBet(
req.body.marketId,
req.body.bettorId,
req.body.prediction,
req.body.amount,
req.body.confidence
);
res.json(bet);
});
app.listen(3000);Option C: Docker Container
Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
COPY src/ ./src/
EXPOSE 3000
CMD ["node", "dist/server.js"]Build & Run:
docker build -t agent-reputation .
docker run -p 3000:3000 agent-reputation---
โ๏ธ Configuration
Environment Variables
| Variable | Default | Description |
|---|---|---|
| `INITIAL_BALANCE` | 1000 | Starting credits for new agents |
| `INITIAL_PRICE` | 50 | Default market price (0-100) |
| `CASCADE_THRESHOLD` | 0.7 | Herding detection (70 |
| `INHERITANCE_RATIO` | 0.5 | Default hereditary ratio (50 |
| `MARKET_MAKER_SPREAD` | 0.02 | AMM spread (2 |
Example `.env`:
INITIAL_BALANCE=1000
INITIAL_PRICE=50
CASCADE_THRESHOLD=0.7
INHERITANCE_RATIO=0.5
LOG_LEVEL=infoConfiguration File
Create `config.json` for advanced settings:
{
"market": {
"initialBalance": 1000,
"initialPrice": 50,
"minPrice": 1,
"maxPrice": 99,
"spreadPercent": 2
},
"cascade": {
"herdingThreshold": 0.7,
"maxGenerations": 4,
"decayFactors": {
"endorsement": 0.5,
"guilt": 0.4,
"glory": 0.6
}
},
"lineage": {
"defaultInheritance": "partial",
"inheritanceRatio": 0.5,
"mutationRate": 0.1,
"parentAccountability": 0.3
},
"routing": {
"defaultStrategy": "momentum_weighted",
"minScoreThreshold": 0.3
}
}---
๐พ Persistence Layer
The current implementation is in-memory only. For production, add persistence.
Option 1: SQLite (Simple)
import sqlite3
class PersistentMarketplace(ReputationMarketplace):
def __init__(self, db_path="reputation.db"):
super().__init__()
self.conn = sqlite3.connect(db_path)
self._init_tables()
def _init_tables(self):
self.conn.execute("""
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
reputation REAL,
data JSON
)
""")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS markets (
id TEXT PRIMARY KEY,
state TEXT,
data JSON
)
""")
self.conn.commit()
def save_agent(self, agent_id):
manager = self.agent_managers.get(agent_id)
if manager:
self.conn.execute(
"INSERT OR REPLACE INTO agents VALUES (?, ?, ?)",
(agent_id, manager.total_reputation, json.dumps(vars(manager)))
)
self.conn.commit()Option 2: Redis (Fast)
import redis
import json
class RedisMarketplace(ReputationMarketplace):
def __init__(self, redis_url="redis://localhost:6379"):
super().__init__()
self.redis = redis.from_url(redis_url)
def save_agent(self, agent_id):
manager = self.agent_managers.get(agent_id)
if manager:
self.redis.hset("agents", agent_id, json.dumps({
"reputation": manager.total_reputation,
"stakes": len(manager.active_stakes)
}))
def load_agent(self, agent_id):
data = self.redis.hget("agents", agent_id)
if data:
return json.loads(data)
return NoneOption 3: PostgreSQL (Scalable)
-- Schema
CREATE TABLE agents (
id VARCHAR(64) PRIMARY KEY,
name VARCHAR(255),
created_at TIMESTAMP DEFAULT NOW(),
total_reputation DECIMAL(10,4),
available_reputation DECIMAL(10,4),
prediction_accuracy DECIMAL(5,4)
);
CREATE TABLE domain_profiles (
agent_id VARCHAR(64) REFERENCES agents(id),
domain VARCHAR(32),
market_price DECIMAL(10,4),
volume_24h DECIMAL(10,4),
volatility DECIMAL(5,4),
PRIMARY KEY (agent_id, domain)
);
CREATE TABLE markets (
id VARCHAR(64) PRIMARY KEY,
task_id VARCHAR(255),
domain VARCHAR(32),
assigned_agent VARCHAR(64) REFERENCES agents(id),
state VARCHAR(16),
success_pool DECIMAL(10,4),
partial_pool DECIMAL(10,4),
failure_pool DECIMAL(10,4),
outcome VARCHAR(16),
created_at TIMESTAMP DEFAULT NOW(),
resolved_at TIMESTAMP
);
CREATE TABLE bets (
id VARCHAR(64) PRIMARY KEY,
market_id VARCHAR(64) REFERENCES markets(id),
bettor_id VARCHAR(64) REFERENCES agents(id),
prediction VARCHAR(16),
amount DECIMAL(10,4),
confidence DECIMAL(5,4),
payout DECIMAL(10,4),
created_at TIMESTAMP DEFAULT NOW()
);---
๐ Monitoring
Health Check Endpoint
app.get('/health', (req, res) => {
const summary = market.getMarketSummary();
res.json({
status: 'healthy',
agents: summary.totalAgents,
markets: summary.totalMarkets,
openMarkets: summary.openMarkets,
cascadeAlerts: summary.cascadeAlerts.length
});
});Prometheus Metrics
import { Counter, Gauge, Histogram } from 'prom-client';
const marketsCreated = new Counter({
name: 'reputation_markets_created_total',
help: 'Total prediction markets created'
});
const activeAgents = new Gauge({
name: 'reputation_active_agents',
help: 'Number of registered agents'
});
const betLatency = new Histogram({
name: 'reputation_bet_latency_seconds',
help: 'Time to place a bet',
buckets: [0.01, 0.05, 0.1, 0.5, 1]
});
// Use in code
app.post('/bets', (req, res) => {
const end = betLatency.startTimer();
const bet = market.placeBet(...);
end();
res.json(bet);
});Logging
import winston from 'winston';
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Log significant events
logger.info('Market created', { marketId, taskId, assignedAgent });
logger.warn('Herding detected', { marketId, severity });
logger.error('Resolution failed', { marketId, error });---
๐ Security
Authentication
import jwt from 'jsonwebtoken';
const authenticate = (req, res, next) => {
const [sensitive field redacted])[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
req.agent = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
};
app.post('/bets', authenticate, (req, res) => {
// Ensure bettorId matches authenticated agent
if (req.body.bettorId !== req.agent.id) {
return res.status(403).json({ error: 'Cannot bet as another agent' });
}
// ...
});Rate Limiting
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 100, // 100 requests per minute
message: 'Too many requests'
});
app.use('/api/', limiter);Input Validation
import Joi from 'joi';
const betSchema = Joi.object({
marketId: Joi.string().required(),
bettorId: Joi.string().required(),
prediction: Joi.string().valid('success', 'partial', 'failure').required(),
amount: Joi.number().min(1).max(1000).required(),
confidence: Joi.number().min(0).max(1).required()
});
app.post('/bets', (req, res) => {
const { error, value } = betSchema.validate(req.body);
if (error) return res.status(400).json({ error: error.message });
// ...
});---
๐ Integration Guide
With Clawdbot Sessions
// When spawning a sub-agent
const parentAgent = engine.getBootstrapResult(parentId);
const childAgent = engine.registerAgent(childId, childName, parentId);
// Child inherits 30% of parent trust
console.log(`Child trust level: ${childAgent.trustLevel}`);With Pulse Task Completion
// On task complete
const outcome = taskSucceeded ? OutcomeType.SUCCESS : OutcomeType.FAILURE;
const quality = taskQualityScore; // 0-1
market.resolveMarket(marketId, outcome, quality);With Task Router
// Route new task
const routing = market.routeTask(Domain.CODING);
console.log(`Assign to: ${routing.agentId}`);
console.log(`Confidence: ${routing.confidence * 100}%`);---
๐ฆ Deployment Checklist
- [ ] Install dependencies (`npm install`)
- [ ] Configure environment variables
- [ ] Set up persistence (SQLite/Redis/PostgreSQL)
- [ ] Add authentication middleware
- [ ] Configure rate limiting
- [ ] Set up logging
- [ ] Add health check endpoint
- [ ] Configure Prometheus metrics
- [ ] Run integration tests
- [ ] Deploy to staging
- [ ] Smoke test all endpoints
- [ ] Deploy to production
---
๐ Support
- Issues: Open GitHub issue
- Documentation: See `/docs/` folder
- API Reference: See inline TSDoc/docstrings
Promotion Decision
Attach run IDs, datasets, metrics, and reproduction commands.
Source Anchor
agent-reputation/docs/DEPLOYMENT_GUIDE.md
Detected Structure
Method ยท Evaluation ยท References ยท Figures ยท Code Anchors ยท Architecture