α System Core — Algorithm Extraction
⚠ HERITAGE EXTRACTION — donor AMS α System Core (Wave 8 quarantine)
This file extracts the donor AMS α System Core from
src/server.js,src/middleware/, andsrc/db/(all deleted in R53). The 2-phase startup, the watcher startup in Phase 2, the 11-layer middleware stack, and thesrc/server.jsentry point are donor surface — Phase 0 Colibri targetssrc/server.ts(P0.2.1) with no file watcher (S17 §2 — stdio one-shot startup) and a 5-stage middleware chain:tool-lock → schema-validate → audit-enter → dispatch → audit-exit. The canonical Phase 0 α surface is in../../concepts/α-system-core.mdand../../spec/s17-mcp-surface.md.Read this file as donor genealogy only.
Algorithmic content extracted from AMS
src/server.js,src/middleware/, andsrc/db/for Colibri implementation reference.
2-Phase Startup Algorithm
The server must connect its MCP transport before any heavy initialization. The MCP client has a handshake timeout — delaying stdio connection causes client disconnects.
Phase 1: TRANSPORT
1. Create MCP Server instance
2. Register ListTools handler (static tool definitions — no DB needed)
3. Register ListResources handler
4. Register CallTool handler (gated behind initReady Promise)
5. Create StdioServerTransport
6. Call transport.connect() — handshake succeeds immediately
7. Create initReady Promise (gate for tool calls)
Phase 2: INIT (runs asynchronously after Phase 1 completes)
1. Connect to SQLite database (getDb())
2. Run schema migrations (migrate.js)
3. Load all domain modules (src/domains/*)
4. Start file watchers (src/watchers/index.js)
5. Bind HTTP dashboard server (src/dashboard/server.js)
6. Start health check loop (30s interval)
7. Resolve initReady Promise → queued tool calls begin executing
Promise gate pattern: Any CallTool request that arrives during Phase 2 awaits initReady. ListTools never awaits — tool definitions are statically imported. This prevents client timeout while ensuring no tool executes against an uninitialized database.
Critical invariant: console.log must be redirected to console.error before Phase 1. The MCP SDK’s StdioServerTransport.send() calls this._stdout.write() where _stdout = process.stdout. Any debug text on stdout corrupts the JSON-RPC wire format. Use console.log = console.error — do NOT override process.stdout.write directly.
Middleware Chain Order
11 middleware modules applied in strict sequence for every CallTool request:
CallTool request
│
1. tool-lock — serialized execution (one tool call at a time, prevents concurrent mutations)
2. acl — checks caller permissions against tool allowlist; injects project scope
3. audit — writes call metadata to audit table BEFORE execution begins
4. auth — JWT/API-key authentication (MCP tool calls only; not for dashboard HTTP)
5. auth-permissions — fine-grained permission checks beyond auth identity
6. metrics — call timing counters (start time recorded here)
7. orchestration — workflow coordination hooks
8. runtime-pid-lock — prevents duplicate server instances from racing
9. startup-lock — gates all calls until Phase 2 completes (implements initReady gate)
10. watcher-leader — leader election for file watchers in multi-instance deployments
11. index — middleware chain composition (wraps steps 1–10)
│
└─► handler dispatch (routeTool)
The actual CallTool dispatch chain from src/controllers/index.js wraps handlers as:
withSerializedToolExecution
→ runWithAclContext
→ runWithAuditContext
→ withRateLimit
→ withCircuitBreaker
→ withRetry
→ routeTool(name, args)
11 Middleware Module Descriptions
| Module | File | Description |
|---|---|---|
tool-lock |
src/middleware/tool-lock.js |
Mutex-based serialization. Only one tool executes at a time. Queues concurrent requests. |
acl |
src/middleware/acl.js |
Access control list check. Verifies caller identity has permission for named tool. Injects ACL context. |
audit |
src/middleware/audit.js |
Pre-execution audit write. Records caller, tool name, params hash, timestamp before handler runs. |
auth |
src/middleware/auth.js |
JWT/API-key validation. Supports trust, token, hybrid, required modes via AMS_AUTH_MODE. |
auth-permissions |
src/middleware/auth-permissions.js |
Granular permission model. Checks operation-level permissions beyond identity. |
metrics |
src/middleware/metrics.js |
Timing and call counters. Measures handler duration, records to metrics store. |
orchestration |
src/middleware/orchestration.js |
Workflow hooks. applyOrchestrationAfter attaches metadata to responses. |
runtime-pid-lock |
src/middleware/runtime-pid-lock.js |
PID file check. Prevents two server instances from owning the same DB file. |
startup-lock |
src/middleware/startup-lock.js |
Phase 2 gate. Rejects tool calls (or queues them) until initReady resolves. |
watcher-leader |
src/middleware/watcher-leader.js |
Leader election for file watcher ownership in potential multi-instance scenarios. |
index |
src/middleware/index.js |
Chain composition. Assembles and exports the full middleware pipeline. |
SQLite Single-Writer Model
- One process owns the database file exclusively
- No horizontal scaling, no replication
- 78 tables (74 regular + 4 FTS5 virtual) across 5 schema files
- Schema files:
schema.sql,schema-memory.sql,schema-thought.sql,schema-merkle.sql,vector-schema.sql gsd_projectsmust be created beforetasks(foreign key constraint)- DB path:
AMS_ROOT/data/ams.db tool-lockmiddleware enforces single-writer at the application layer (serialized tool execution)- All state mutations go through tool calls → every write is audited
Tool Routing: ListTools → CallTool → Handler Dispatch
ListTools request
→ Returns static tool array (no DB, no await, instantaneous)
→ Tool definitions sourced from 36+ controller/tool-definition arrays
→ resolveToolProfile() applies visibility rules (DEFAULT_HIDDEN_TOOLS, CORE_ALLOWLIST)
→ sanitizeToolForClient() strips oneOf/anyOf/allOf (MCP clients reject JSON Schema combinators)
CallTool request
→ Await initReady (Phase 2 gate)
→ Pass through middleware chain (see above)
→ routeTool(name, args) — sequential probe pattern:
For each controller in priority order:
result = controller.handle(name, args)
if result !== null: return result ← first match wins
→ Priority order: performance/audit/thought/merkle (unaudited fast path),
then Claude API tools,
then core domain handlers (roadmaps, tasks, analysis) with audit middleware
→ Strip internal _metrics keys before response serialization
→ safeStringify() handles circular references
Dashboard Server Pattern
The HTTP server is a supplementary monitoring interface, not an MCP tool surface.
- Implementation: Node.js native
httpmodule (not Express) - Location:
src/dashboard/server.js - WebSocket companion:
src/websocket/server.js(enabled viaCLAUDE_WEBSOCKET_ENABLED=true) - Does NOT expose MCP tools over HTTP
- Does NOT share the MCP middleware chain
- Binds on a separate port from the MCP stdio transport
- Started in Phase 2 (after DB is ready)
- Provides observability: health status, metrics, recent tool calls, queue depth
Health Check Loop
Runs every 30 seconds (configurable via AMS_HEALTH_INTERVAL):
| Check # | Type | What it checks | Failure action |
|---|---|---|---|
| 1 | SQL integrity | PRAGMA integrity_check on SQLite (sampled, not every cycle) |
Transition to SAFE_MODE |
| 2 | Memory pressure | Process RSS vs configurable threshold | Log warning; transition to SAFE_MODE if critical |
| 3 | Event loop latency | Measure tick delay via setImmediate timing |
Log warning; transition to DIAGNOSE if severe |
| 4 | Watcher status | Verify file watchers are alive, not stalled | Restart stalled watchers |
| 5 | Queue depth | Count pending tool calls in execution queue | Log warning if above threshold |
| 6 | DB connection | Ping SQLite with lightweight query | Reconnect or transition to SAFE_MODE |
Health check failures log to audit_log. Severe failures trigger runtime mode transitions (see γ Server Lifecycle).
See Also
-
[[concepts/α-system-core α System Core]] — concept overview -
[[concepts/γ-server-lifecycle γ Server Lifecycle]] — runtime modes and shutdown -
[[extractions/gamma-server-lifecycle-extraction γ Lifecycle Extraction]] — detailed phase algorithms -
[[architecture/middleware Middleware Architecture]] — middleware design details -
[[reference/controllers Controllers Reference]] — tool routing details