A TypeScript framework for controlled AI execution. AOSP wraps every AI-initiated action in a structured lifecycle: shadow-execute first, verify the diff, then commit to reality — with full audit trails, policy enforcement, and rollback capability.
When an AI agent wants to take an action (write a file, call an API, modify a database), AOSP interposes a safety layer:
- Shadow execution — run the action in a sandbox, capture predicted side effects
- Policy check — evaluate against declarative rules (DSL) and risk thresholds
- Approval gate — route high-risk actions for human review
- Commit — apply the change to the real system
- Trace — record everything in a tamper-evident Merkle chain
This is the core loop. On top of it, AOSP adds temporal branching — the ability to fork execution into multiple parallel timelines, score all outcomes, and only commit the winner.
The orchestrator. Wires together all modules and drives the 10-step execution lifecycle (identity validation, state fetch, risk assessment, policy evaluation, blast radius analysis, shadow execution, approval, commit, state update, trace recording).
- PolicyEngine — programmatic policy rules with risk-level gating
- PolicyDSL — declarative rules like
DENY WHEN action MATCHES "delete_*" - ApprovalGateway — human-in-the-loop approval for high-risk actions
- BlastRadiusAnalyzer — graph-based impact analysis with transitive dependency tracking
- ShadowExecutor — preview actions without real side effects via pluggable adapters
- TransactionCoordinator — atomic multi-step execution with ordered rollback
- PipelineEngine — multi-stage pipelines with conditional branching and parallel stages
- TemporalBranchEngine — parallel timeline exploration (see below)
- IdentityManager — actor registration, trust levels, scope-based authorization
- TraceStore — structured event recording with query, export, and statistics
- MerkleChain — append-only hash chain for tamper-evident audit trails with per-entry proofs
- StateManager — surface state snapshots with history and diffing
- DriftDetector — detect unauthorized out-of-band changes by comparing expected vs. actual state
- MagicRecovery — automatic recovery strategies for failed operations
- ApiLayer — JSON message transport for remote AOSP operations
- HttpServer — HTTP server wrapping the API layer
- FilesystemAdapter — reference implementation for local filesystem operations (read, write, delete, list, mkdir) with shadow support and rollback
The standout feature. Given an intent (e.g., "set up a project"), AOSP can:
- Fork the intent into multiple competing strategies (minimal, standard, full-scaffold, etc.)
- Shadow-execute all strategies in parallel, capturing predicted diffs for each
- Score each timeline across 6 weighted dimensions: confidence, safety, minimality, completeness, speed, and reversibility — with auto-normalizing weights
- Rank timelines with risk-aware tiebreaking (score → risk level → reversibility)
- Commit only the winning timeline to reality
- Prune losing timelines (with cascade to child branches)
Additional temporal features:
- Reality Merge Requests — PR-style review objects with quorum-based approval and auto-expiry
- Pairwise Timeline Diffs — side-by-side comparison of any two timelines with per-dimension breakdown
- Counterfactual Analysis — "what if we'd picked the other timeline?" with avoided risks and sacrificed benefits
- Prevented Futures Report — tracks timelines that were blocked (high risk, low confidence, budget exceeded, policy denied)
- Non-Selection Proofs — SHA-256 hashed evidence of why each losing timeline lost, chained via Merkle-style hashing
- Branch Budgeting — limits on timeline count, fork depth, total intents, and wall-clock time
- 4 Pruning Strategies —
score_threshold,confidence_decay,risk_ceiling,diminishing_returns(independently configurable) - Commit-Time Revalidation — re-checks reality drift before merging
- Sandbox Mode — explore alternate futures with no real mutations
- Future Search Engine — query/filter timelines by score, risk, confidence, phase, name, surface
- Custom Safety Gate Checks — register dynamic pre-merge validation functions
- Action Diffs — structured per-action diff with content preview and size estimation
- Auto-Strategy Inference — generate strategy variants from a single intent
- Exploration Statistics — avg score, standard deviation, risk distribution, budget utilization
# Install dependencies
npm install
# Build
npm run build
# Run the interactive demo (12 steps covering the full feature set)
npm run demoimport { createAosp, createFilesystemSurface, FilesystemAdapter } from 'aosp';
const aosp = createAosp();
// Register a surface (the thing being acted upon)
const surface = createFilesystemSurface('my-fs', 'My Filesystem', '/tmp/workspace');
aosp.kernel.registerSurface(surface);
aosp.executor.registerAdapter(new FilesystemAdapter('my-fs', '/tmp/workspace'));
// Register an actor
aosp.identity.register({
id: 'agent-1', type: 'ai', name: 'My Agent',
trust: 'elevated', scopes: ['my-fs/*'],
});
// Execute with full lifecycle
const trace = await aosp.kernel.execute({
id: 'intent-1',
surface: 'my-fs',
action: 'write_file',
params: { path: 'hello.txt', content: 'Hello, world!' },
initiator: { id: 'agent-1', type: 'ai', name: 'My Agent', trust: 'elevated', scopes: ['my-fs/*'] },
timestamp: Date.now(),
metadata: {},
});
console.log(trace.status); // 'committed'const { temporal, executor } = createAosp();
temporal.setExecModule(executor as any);
temporal.registerSurface(surface);
temporal.setBudget({ maxTimelines: 10, maxDepth: 3, maxTotalIntents: 50 });
const result = await temporal.explore([
{ name: 'approach-a', intents: [/* ... */], metadata: {} },
{ name: 'approach-b', intents: [/* ... */], metadata: {} },
]);
console.log(result.comparison.winner.name); // best strategy
console.log(result.stats.avgScore); // exploration statistics
console.log(result.explorationProofHash); // tamper-evident hash
// Commit the winner
await temporal.merge(result.comparison.winner.id);# Full lifecycle execution
aosp execute <surface> <action> [params...]
# Shadow-only (preview)
aosp shadow <surface> <action> [params...]
# Trace management
aosp trace list
aosp trace show <id>
aosp trace export [id]
# Merkle chain
aosp chain verify
aosp chain show
# Policy DSL
aosp policy add '<expression>'
aosp policy list
# System status
aosp status
# Rollback
aosp rollback <traceId>
# Interactive demo
aosp demosrc/
kernel/ Kernel orchestrator + type definitions (~1,800 lines)
safe/ Policy engine, DSL, approval gateway, blast radius (~1,240 lines)
exec/ Shadow executor, transactions, pipelines, temporal branching (~2,460 lines)
id/ Identity and authorization (~180 lines)
trace/ Trace store + Merkle chain (~530 lines)
info/ State management + drift detection (~440 lines)
magic/ Recovery strategies (~170 lines)
api/ Transport layer + HTTP server (~440 lines)
adapters/ Reference filesystem adapter (~460 lines)
spec/ Protocol versioning (~80 lines)
cli/ CLI with 12-step demo (~570 lines)
index.ts Public API exports + convenience factory
~8,400 lines of TypeScript across 31 source files. Zero runtime dependencies beyond chalk, commander, and uuid.
- This is a protocol framework, not a production-ready system. It demonstrates the architecture for controlled AI execution.
- The shadow execution model depends on adapters faithfully simulating actions. The included filesystem adapter is a reference implementation.
- Temporal branching scores timelines based on shadow execution results. The scoring is only as good as the shadow predictions.
- There are no tests yet. The demo serves as an integration smoke test.
- The Merkle chain is in-memory. A production system would need persistent storage.
- Policy DSL supports basic patterns (
MATCHES,CONTAINS,EQUALS,GT,LT). Complex policies should use programmatic rules.
MIT