From 9f94e25e58b519c123a40fe9b6c6e2f77ae1c8f2 Mon Sep 17 00:00:00 2001 From: Aether AI Date: Thu, 23 Jul 2026 07:43:52 -0400 Subject: [PATCH] docs: clarify Nano implementation boundaries --- .github/workflows/ci.yml | 34 +- BUILD_ORDER.md | 141 ++------ README.md | 414 ++++++---------------- SECURITY.md | 74 ++-- docs/README.md | 36 +- docs/architecture.md | 72 ++++ docs/language.md | 102 ++++++ docs/nano-optimization-loop.md | 73 ++-- docs/papers/01-why-nano.md | 5 +- docs/papers/02-the-agentic-compiler.md | 3 + docs/papers/03-determinism.md | 3 + docs/papers/04-provenance.md | 3 + docs/papers/05-why-not-go.md | 3 + docs/papers/06-why-not-typescript.md | 3 + docs/papers/07-nano-vs-pine.md | 3 + docs/papers/08-llm-integration.md | 3 + docs/papers/09-autonomous-systems.md | 3 + docs/papers/10-nano-family.md | 3 + docs/papers/11-performance.md | 5 +- docs/papers/12-security.md | 3 + docs/papers/13-design-principles.md | 3 + docs/papers/14-future-work.md | 5 +- docs/papers/15-closed-loop-engineering.md | 3 + docs/papers/16-quantum-computing.md | 3 + docs/papers/17-heterogeneous-compute.md | 3 + docs/papers/README.md | 70 ++-- docs/status.md | 32 ++ nano/__init__.py | 7 +- nano/library/README.md | 107 +++--- nano/loop/__init__.py | 7 +- nano/loop/graph.py | 9 +- nano/loop/mutation.py | 16 +- nano/loop/nodes.py | 8 +- nano/loop/quantum.py | 31 +- nano/memory/patterns.py | 16 +- nano/runtime/effects.py | 7 +- pyproject.toml | 21 +- tests/test_readme_example.py | 36 ++ 38 files changed, 658 insertions(+), 712 deletions(-) create mode 100644 docs/architecture.md create mode 100644 docs/language.md create mode 100644 docs/status.md create mode 100644 tests/test_readme_example.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40fb137..b27f932 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,11 +14,41 @@ jobs: python-version: ["3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} + - name: Set up Python uses: actions/setup-python@v5 with: - python-version: ${{ matrix.python-version }} + python-version: "${{ matrix.python-version }}" - name: Install run: pip install -e . pytest - name: Run tests run: pytest -q + + package: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + - name: Build wheel + run: python -m pip wheel --no-deps --wheel-dir dist . + - name: Verify packaged strategy assets + run: | + python - <<'PY' + from pathlib import Path + from zipfile import ZipFile + + wheel = next(Path("dist").glob("*.whl")) + expected = { + "nano/examples/momentum.nano", + "nano/examples/momentum_ir.json", + "nano/library/momentum/rsi_oversold_reversal.nano", + "nano/library/momentum/rsi_oversold_reversal_ir.json", + } + with ZipFile(wheel) as archive: + packaged = set(archive.namelist()) + + missing = sorted(expected - packaged) + assert not missing, f"wheel is missing documented strategy assets: {missing}" + PY diff --git a/BUILD_ORDER.md b/BUILD_ORDER.md index 7d0dda7..7ceafaa 100644 --- a/BUILD_ORDER.md +++ b/BUILD_ORDER.md @@ -1,140 +1,65 @@ -# Nano — Build Order +# Nano build notes -**Locked strategy: IR-first.** Nano does not start as a programming language. It starts as a -**deterministic intelligence execution graph** (Nano IR + reference runtime). The language becomes -the human-friendly way to author those graphs, later. This matches how LLVM and Qiskit evolved: -representation and execution first, surface syntax second. +> This is a record of the implementation sequence and architectural constraints. For the current API and maturity boundary, see [docs/architecture.md](docs/architecture.md), [docs/language.md](docs/language.md), and [docs/status.md](docs/status.md). -Nano is the execution abstraction that lets a host trading platform tie together its risk gates, -provenance, deterministic-execution discipline, and runtime separation. Any platform with those -pieces can embed it; Aether ATS is the first consumer. +## The durable constraint -## The one architectural lock +Nano strategies **propose**; a host gate **decides**. The language has no order, exchange, network, or external-actuation primitive. Its terminal runtime output is an `Intent`, which a host-owned `DecisionGate` may approve or reject. +```text +.nano rule -> StrategyGraph -> reference runtime -> Intent -> host DecisionGate -> Decision record ``` -Nano: "Execute this intent." -Risk gate: "Is execution allowed?" -``` - -**Nano never places trades.** Strategies produce intents: - -```json -{ "intent": "BUY", "asset": "BTC", "confidence": 0.91 } -``` - -A pluggable risk engine disposes: **components propose, gates decide.** This is enforced -structurally — the IR has no order/exchange primitive, only `Intent` nodes, and emitting intents -requires `intent.emit` in the module's effect manifest. ---- +The effect manifest is a small strategy-IR boundary: intent-bearing graphs must declare `intent.emit`, and unknown effects are rejected at load time. It is not a general capability sandbox; the Python host process remains trusted. -## Build order +## Implemented sequence -### Milestone 1 — Nano IR ✅ +### 1. Strategy IR and validation -`nano/ir/` — a few primitives only: - -| Node | Purpose | -|---|---| -| `Schedule(interval)` | when the graph evaluates ("5m") | -| `Condition(signal, operator, value)` | e.g. RSI < 30 | -| `Intent(action, asset, confidence)` | proposal, never an order | -| `Agent(name)` | later — named behavior blocks | - -Target: this JSON **is** a runnable strategy: +`nano/ir/` defines the versioned `StrategyGraph` representation. It supports a schedule, flat numeric conditions, intents, and metadata-only agent labels. A valid serialized strategy includes its version and effect manifest: ```json { "type": "Strategy", + "nanoIrVersion": "0.1.0", + "name": "Momentum", + "effects": ["intent.emit", "log.append"], "nodes": [ - { "type": "Schedule", "interval": "5m" }, - { "type": "Condition", "signal": "RSI", "operator": "<", "value": 30 }, - { "type": "Intent", "action": "BUY", "asset": "BTC" } + {"type": "Schedule", "interval": "5m"}, + {"type": "Condition", "signal": "RSI", "operator": "<", "value": 30}, + {"type": "Intent", "action": "BUY", "asset": "BTC"} ] } ``` -### Milestone 2 — Reference interpreter ✅ - -`nano/runtime/` — execute before you compile: - -```python -result = interpreter.execute(strategy_graph, market_frame) -``` - -1. Load IR (manifest-checked). 2. Evaluate conditions against injected signal series -(no ambient clock, no lookahead). 3. Produce intents. 4. Log everything (replayable). - -Pipeline shape: `price stream → condition → TRUE → Intent → [hand-off] → risk engine → -execution decision`. The hand-off is Milestone 5. - -### Milestone 3 — Example corpus ✅ - -`nano/examples/` — becomes the language test suite: `basic_rsi`, `momentum`, `mean_reversion`, -`volatility_guard`, `risk_manager`, `ai_agent`. Hand-written IR JSON now; the same examples must -compile from `.nano` source in Milestone 4 and produce identical IR. - -### Milestone 4 — `.nano` syntax → IR ✅ - -`nano/compiler/` — lexer, parser, compiler for the strategy subset: - -```nano -strategy Momentum { - every 5m { - if RSI(14) < 30 { execute() } - } -} -``` - -compiles to exactly the Milestone-1 JSON. Conformance rule: compiled IR replays identically to the -hand-written IR for every example. +### 2. Deterministic reference runtime -### Milestone 5 — Risk-gate integration ✅ (reference adapter in `nano/bridge/`) +`nano/runtime/` evaluates validated strategy IR against an injected `MarketFrame`. The caller supplies timestamps and aligned signal series. The runtime emits intents and an ordered, in-memory event log; it does not fetch data or act externally. -First execution integration. Flow: `Nano IR → bridge (host-platform adapter) → risk engine → -execution decision`. The bridge loads IR, verifies the effect manifest, streams recorded market -frames through the interpreter, and forwards intents into the host platform's risk/release-gate -discipline. The backtester runs the same IR against historical frames — bit-identical replay is -the acceptance test. The reference adapter here defines the `RiskEngine` protocol any platform -can implement; Aether ATS is the first consumer. +### 3. Conformance corpus -An optional `ProvenanceRiskEngine` (`nano/bridge/provenance.py`) wraps any `RiskEngine` to bind -each decision to a signed, independently verifiable receipt — for platforms that need -non-repudiable proof a decision happened, not just a log line. Fully outside the language: a -`.nano` author can't see or reach it. Requires the optional `provenance` extra -(`pip install aether-nano[provenance]`); see `examples/provenance_signing_demo.py`. +`nano/examples/` contains paired source and IR fixtures. `nano/library/` extends that pattern with a trading-oriented strategy corpus. The tests compile pairs, validate IR, and replay reference execution. -### Milestone 6 — Editor tooling ✅ engine layer (`nano/aethercode/`; extension packaging pending) +### 4. .nano source compiler -Not a whole IDE. The pure language-service engine first: syntax highlighting (semantic tokens), -diagnostics, IR preview (`when RSI < 30` → shows the compiled ConditionNode). Packaged as a -VS-Code-style extension by the host editor. +`nano/compiler/` implements the locked v0.1 grammar with a handwritten lexer and recursive-descent parser. The compiler lowers source to canonical strategy IR; it does not implement static typing, optimization passes, or bytecode generation. -### Milestone 7 — Host-platform compiler inputs +### 5. Host decision-gate bridge -Advanced compiler-input integrations (systems that discover computational patterns and feed them -to Nano) live in the host platform, not this repo. +`nano/bridge/` connects the reference runtime to a host-provided `DecisionGate` and records its decisions. `Backtester.verify_replay()` detects differences between two serialized bridge runs. The bridge remains a reference adapter: policy, persistence, and external action belong to the host. -### Where Nano++ starts +### 6. Editor-service helpers -Much later, as an extension over the same IR (`Nano → Nano IR → Nano++`). Do not begin with -advanced computational features; the mistake would be building that syntax before the execution -graph is proven. +`nano/aethercode/` provides syntax/semantic tokens, diagnostics, and IR-preview functions. It is an engine layer, not a packaged editor extension. ---- +## Adjacent experimental primitives -## Original 30-day plan (for the record) +- `nano/memory/` provides standalone pattern retrieval and an `escalate` boolean; it is not a runtime model-routing system. +- `nano/loop/` provides separate loop-document validation, mutation-admission helpers, and a deterministic simulator protocol; it does not execute an autonomous loop. +- `nano/bridge/provenance.py` is an optional adapter that requires its external dependency and signs side-channel receipts. -| Week | Build | Exit | -|---|---|---| -| 1 | Nano package, IR schema, JSON serialization, basic interpreter | A JSON strategy executes deterministically | -| 2 | Lexer/parser, `.nano` files compile to IR | `if RSI < 30 { buy() }` works end-to-end | -| 3 | Risk-gate bridge, risk-layer hand-off, backtester | Nano strategies simulate against a host risk engine | -| 4 | Editor extension: highlighting + IR visualizer | Developer edits Nano with live IR preview | +## Work that remains outside the v0.1 implementation -## Alternate ordering (rejected) +The repository does not currently provide CLI commands, a type system, look-ahead analysis, an LLM runtime, automatic escalation, live data or exchange connectors, persistent core audit storage, general agent coordination, a loop executor, or real quantum-hardware dispatch. -For the record: building the bridge inside a host trading platform first, then extracting the -package, was rejected because the IR + runtime are ecosystem-wide — many runtimes and tools -consume them — so they belong in the standalone repo from day one, with the host platform as the -first *consumer*, not the owner. +The [design-note series](docs/papers/README.md) discusses some of these possible directions. It is not a substitute for the implemented contract. diff --git a/README.md b/README.md index 5f471d8..6f03648 100644 --- a/README.md +++ b/README.md @@ -1,381 +1,169 @@
-Nano — deterministic AI agent compiler +Nano logo # Nano -### The first compiled language for autonomous systems. - -**Compile reasoning into deterministic, auditable execution.** - -*Reason once. Compile forever.* +### A deterministic DSL for replayable, host-governed decision rules. [![CI](https://github.com/DBarr3/Nano/actions/workflows/ci.yml/badge.svg)](https://github.com/DBarr3/Nano/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-22d3ee.svg)](LICENSE) [![Python](https://img.shields.io/badge/python-3.10%2B-38bdf8.svg)](pyproject.toml) -[![Tests](https://img.shields.io/badge/tests-173%20passing-22c55e.svg)](tests) -[![Made by Aether AI](https://img.shields.io/badge/made%20by-Aether%20AI-0ea5e9.svg)](https://aethersystems.net) -[![GitHub Repo stars](https://img.shields.io/github/stars/DBarr3/Nano?style=social)](https://github.com/DBarr3/Nano/stargazers) - -**[Website](https://aethersystems.net)** · **[Playground (Aether Code) →](https://app.aethersystems.net/code)** · **[Papers →](docs/papers/README.md)** - -⭐ **Star this repo** — it's the single biggest signal that helps other engineers find Nano.
---- +> **Alpha reference implementation (v0.1.0).** Nano compiles a deliberately small `.nano` strategy into validated, serializable IR. Its reference runtime evaluates caller-supplied numeric signals on a caller-supplied schedule and returns proposed actions (`Intent` values) plus an ordered event log. A host-owned gate decides whether to approve any proposal. -> Current AI agents ask a model what to do on every step. -> -> Nano compiles reasoning into execution graphs that can **run, replay, audit, and improve**. +Nano is for systems that need repeatable, inspectable threshold decisions without letting the decision rule call an exchange, API, or other external system directly. The checked-in examples are trading-oriented, but the core contract is useful anywhere a host supplies numeric signals, owns the policy boundary, and needs deterministic replay. -> **Status:** research preview · Milestones 1–6 shipped · **173 tests passing**. The IR, compiler, -> interpreter, risk-gate bridge, and optimization loop are real and tested; the CLI and -> `Series` typing are still design. [Full status ↓](#status--whats-real) +## Why Nano? -## What is Nano? +A host application often needs to answer two separate questions: -Nano is an open-source **compiler and runtime for deterministic AI agents**. +1. **What rule should propose an action?** +2. **May that action have consequences here and now?** -Today's agents repeatedly do: +Nano keeps those questions separate. A `.nano` program describes the first as a compact, versioned artifact. The host retains the second through its own `DecisionGate`. This makes rule evaluation easy to replay, test, and audit without treating the rule as an authority to act. -``` -Observe → LLM → Decide → Act → Repeat -``` +Nano does **not** include an LLM runtime, automatic escalation, a live data feed, an exchange/API connector, or an action executor. Those remain host concerns. -Expensive, slow, and different every run. Nano changes the loop: +## From source to a governed decision +```text +.nano source + | + v +lexer -> parser -> canonical StrategyGraph IR + | + v +reference interpreter + injected MarketFrame + | + v +Intent(s) + ordered per-run event log + | + v +optional NanoBridge -> host DecisionGate -> Decision record(s) ``` -Reason once - ↓ -Compile behavior - ↓ -Execute deterministically - ↓ -Escalate only when needed -``` - -Instead of running an LLM for every decision, Nano compiles agent behavior into reusable -execution graphs. Known situations execute deterministically. Unknown situations escalate -back to reasoning. - -The result: - -- **Lower inference cost** — the model runs on escalation, not on every tick -- **Reproducible behavior** — identical inputs replay bit-for-bit, log included -- **Audit trails** — every decision is proposed, gated, and recorded -- **Safer autonomous systems** — programs emit intents; a policy gate decides - -> Nano is not a replacement for intelligence. -> -> Nano is the **compiled memory** of intelligence. - -## Why Nano exists - -Current AI agents spend intelligence repeatedly. Nano compiles intelligence once and reuses it. - -The model is the **author** and the **escalation path** — never the per-tick decision -bottleneck. That single inversion is what makes deterministic AI agents possible: inference -becomes the exception; execution becomes the default. -## Nano vs. the alternatives +The reference interpreter is a pure function of a validated strategy graph and a `MarketFrame`: the same inputs produce the same result. A bridge replay is deterministic only when the host gate is deterministic too; `Backtester.verify_replay()` compares two complete runs and reports divergence. -| Approach | Strength | Limitation | -|---|---|---| -| Hand-written scripts | Fast | No reasoning layer, no audit trail | -| LLM-in-the-loop agents | Flexible | Expensive, slow, inconsistent | -| Workflow engines | Reliable | Heavy ops, not AI-native | -| **Nano** | **Intelligence + deterministic execution** | New architecture | +The base event log is returned in memory with each result. Durable storage, signed receipts, and real-world actuation are outside the core runtime. -
-Full capability comparison +## Run a real strategy -
+Create an environment and install the package from a checkout: -| Capability | Nano | Typical agent frameworks | -|---|---|---| -| Deterministic, bit-identical replay | ✅ core guarantee | ❌ | -| Serializable execution-graph IR | ✅ | ❌ | -| LLM required on every decision | ❌ — only on escalation | usually | -| Actions gated by a policy layer | ✅ enforced in the IR | limited / opt-in | -| Signed provenance receipts | ✅ optional adapter | rare | -| Backtest / live parity | ✅ same artifact | rare | -| Dedicated server infrastructure | ❌ pure Python | varies | - -
- -The full argument — the orchestration crisis, prompt compilation, the state-management -landscape — is [Paper 01: Why Nano](docs/papers/01-why-nano.md). - -Any system where an AI proposes actions and something must decide whether they run is a Nano -target: autonomous agents, automation pipelines, monitoring and response workflows, robotics — -anywhere an **Observe → Decide → Act → Record** loop exists. Quantitative trading is the -**first workload, not the product**: deterministic inputs, replayable history, measurable -outcomes. - ---- - -## Architecture — the missing layer between AI and execution - -``` - .nano source (human- or AI-authored) - │ - ▼ - Compiler - (lexer → parser → type checks) - │ - ▼ - Nano IR - (deterministic, serializable execution graph) - │ - ┌─────────────┼─────────────┐ - ▼ ▼ ▼ - Backtest Paper Live - (recorded (simulated (via your - frames) gate) risk gate) -``` - -Everything compiles to **Nano IR** — a hardware-independent, deterministic, serializable -execution graph. The same program runs in local development, historical backtesting, and live -execution because it *is* the same artifact: +```bash +python -m venv .venv +# macOS/Linux +source .venv/bin/activate +# Windows PowerShell +# .venv\Scripts\Activate.ps1 +pip install -e ".[dev]" +python -m pytest -q ``` -Write Once. Optimize Everywhere. Execute Anywhere. -``` - -Every compiled workflow carries provenance and a fallback route. Known states execute -deterministically; unknown states escalate back to reasoning. -## See Nano in action +This is valid Nano v0.1.0 source from the checked-in conformance corpus: + ```nano strategy Momentum { - every 5m { - - observe market - - if RSI(14) < 30 - and volume > average { - - execute() + if RSI(14) < 30 { + buy(BTC, 0.91) } } } ``` + -What happens to that file: - -``` -strategy.nano - ↓ - Compiler type-checked, effect-checked - ↓ - Nano IR content-addressed execution graph - ↓ - Replay bit-identical against recorded frames - ↓ - Decision gate intent approved or rejected, with reason - ↓ - Recorded result append-only audit log -``` +`RSI(14)` is a source-level signal convention. In v0.1.0, the host computes and injects the `RSI` series; the lookback label is not stored separately in strategy IR. See the [language reference](docs/language.md) for the full rule. -The scheduler owns the clock, the gate owns every order, and every decision is replayable -bit-for-bit. - -## Quickstart - -> **Prefer the browser?** The Nano compiler runs live in **[Aether Code](https://app.aethersystems.net/code)** — -> a VS Code–style web IDE with syntax highlighting, inline diagnostics, and an IR preview. Write a -> `.nano` strategy, compile it, and replay it deterministically without installing anything. +Compile and run it against an injected frame: ```python -from nano.compiler import compile_source -from nano.runtime.interpreter import MarketFrame, execute -from nano.bridge import NanoBridge +from pathlib import Path -graph = compile_source(open("strategy.nano").read()) +from nano.compiler import compile_source +from nano.runtime import MarketFrame, execute -frame = MarketFrame(timestamps=(0,), signals={"RSI": [25.0]}) +source = Path("nano/examples/momentum.nano").read_text(encoding="utf-8") +graph = compile_source(source) +frame = MarketFrame( + timestamps=(0, 300), + signals={"RSI": (45.0, 22.0)}, +) -# Direct interpretation — pure, deterministic result = execute(graph, frame) - -# Or bridge into your own decision gate (any object with a .decide() method) -bridge = NanoBridge(my_risk_engine) -bridge.load(graph.to_dict()) -frame_result = bridge.run(frame) +print([intent.to_dict() for intent in result.intents]) +# [{'intent': 'BUY', 'timestamp': 300, 'asset': 'BTC', 'confidence': 0.91}] ``` -See [`nano/examples/`](nano/examples/) for the conformance corpus (`basic_rsi`, `momentum`, -`mean_reversion`, `volatility_guard`, `risk_manager`, `ai_agent`) — each exists as `.nano` -source and hand-written IR JSON that must match bit-for-bit. - -### Find your path - -| I want to… | Go to | -|---|---| -| **Run something now** | [Quickstart](#quickstart) above · [Aether Code](https://app.aethersystems.net/code) | -| **See real strategies** | [`nano/examples/`](nano/examples/) · [`nano/library/`](nano/library/README.md) | -| **Read the argument in depth** | [The paper series](docs/papers/README.md) — one question per paper | -| **Understand the guarantees** | [Deterministic by construction](#deterministic-by-construction) | -| **See how it's built** | [BUILD_ORDER.md](BUILD_ORDER.md) | -| **Know what's real vs. roadmap** | [Status](#status--whats-real) | -| **Contribute** | [CONTRIBUTING.md](CONTRIBUTING.md) | - ---- - -## The defining rule: agents propose, gates decide +To involve policy, provide a complete host gate. The gate returns a record; it does not cause Nano to place an order or call an API: -A Nano program **cannot act on the world directly**. There is no exchange API, no -side-effecting call in the language — programs emit *intents*, and a pluggable gate disposes of -each one (approve or reject, with a recorded reason). In trading that gate is a risk engine -(implement the `DecisionGate` protocol in `nano/bridge/`); in any other agentic system it's -whatever policy layer owns the consequences. +```python +from nano.bridge import Decision, NanoBridge -Every action is therefore proposed, gated, logged, and replayable — which is what makes -autonomy auditable. It also enables AI-in-the-loop improvement: an analysis system proposes -evidence-backed patches, a human disposes, the compiler recompiles, and release gates govern -deployment. **Nothing self-modifies silently.** -For deployments that need proof a decision happened — not just a log line — an optional adapter -(`nano/bridge/provenance.py`, `pip install aether-nano[provenance]`) wraps any gate so every -disposition also produces a signed, independently re-verifiable receipt. Entirely outside the -language. +class ApproveForDemo: + def decide(self, intent, *, frame): + return Decision(intent=intent, approved=True, reason="demo policy") -## Deterministic by construction -| Guarantee | How | -|---|---| -| Deterministic replay | No ambient clock or RNG — time and entropy are injected, logged inputs | -| Strategies can't bypass risk | No exchange API in the language; programs emit intents, the runtime disposes | -| No look-ahead in backtests | `Series` types make peeking at the future a compile error *(design)* | -| Least-privilege execution | Every IR module carries an effect manifest — a capability boundary | -| Reproducible builds | Content-addressed IR, pinned package hashes | -| Gated self-improvement | AI-compiled workflows pass admission gates before any runtime loads them | +bridge = NanoBridge(ApproveForDemo()) +bridge.load(graph.to_dict()) +bridge_result = bridge.run(frame) +print([decision.to_dict() for decision in bridge_result.decisions]) +``` -Restrictions are the feature. Nano intentionally removes sockets, randomness, arbitrary IO, -threads, and mutable globals — each one destroys replayability. +## The language is intentionally small -## Nano architecture roadmap +| Current capability | What it means | +| --- | --- | +| One strategy, schedule, and rule | A v0.1 strategy has at most one `every` block and one `if` rule. | +| Numeric, host-provided signals | Conditions compare named signal series with numeric literals; Nano does not calculate indicators or fetch data. | +| AND-only conditions | Every condition must pass before the rule emits its intents. | +| Five intent actions | `buy`, `sell`, `execute`, `pause`, and `observe` emit proposals. `execute()` does not execute code. | +| Manifest validation | The strategy IR rejects unknown node/effect names and intent nodes without `intent.emit`; it is not a static type system. | +| Agent labels | `agent Name` is metadata today; the interpreter does not coordinate agents. | -Three conceptual tiers over one compiler and one IR. A user starts with `buy when RSI < 30` -and never has to leave the language as their agents grow. +There are no variables, arithmetic, functions, imports, `or`/`not`, user-defined actions, type checking, or CLI in the current implementation. The exact grammar and execution semantics are documented in [docs/language.md](docs/language.md). -| Tier | Question it answers | State | -|---|---|---| -| **Nano** (this repo) | *What should the agent do?* — rules and intents | shipped | -| **Nano+** | *How should it reason and coordinate?* — memory, confidence routing, multi-agent | roadmap | -| **Nano++** | *How is complex computation optimized and secured?* — optimization, quantum research track | early | +## What ships today -``` -Shipped → IR · compiler · deterministic interpreter · risk-gate bridge - backtester · pattern memory · editor services · optimization loop +| Implemented and tested | Experimental or optional | Not implemented | +| --- | --- | --- | +| `.nano` lexer, parser, canonical strategy IR, and reference interpreter | `PatternStore` lookup primitive (not wired into the runtime) | LLM calls, automatic escalation, or agent orchestration | +| Host `DecisionGate` bridge and deterministic replay checker | `LoopGraph` validation/hash helpers and a deterministic simulator protocol | CLI, type system, `Series`, or general strategy graphs | +| Diagnostics, semantic tokens, and IR preview helpers | Protocol-C provenance adapter when its optional dependency is installed | Live feeds, exchange/API execution, or persistent core audit storage | +| Source/IR conformance corpus and strategy corpus | Real quantum-hardware dispatch | Autonomous loop execution or self-modifying deployment | -Next → CLI (nano compile / replay / visualize) - Series look-ahead typing (no-peek backtests as a compile error) +For a fuller implementation map, see [Architecture](docs/architecture.md) and [Status](docs/status.md). -Then → Nano+ adaptive layer — memory, confidence routing, multi-agent - Real quantum-hardware dispatch (research) -``` +## A tested strategy corpus -The Nano++ autonomous optimization loop ([`nano/loop/`](nano/loop/)) already ships a -vendor-agnostic `QuantumRuntime` protocol with a deterministic `SimulatorRuntime` reference -backend. Real-hardware dispatch remains research, not a promise. Details and sequencing: -[BUILD_ORDER.md](BUILD_ORDER.md) · [Paper 14: Future Work](docs/papers/14-future-work.md). - -## FAQ - -**Is Nano an LLM?** -No. Nano is a compilation and execution layer. Models create reasoning; Nano compiles it into -deterministic execution graphs and runs them. - -**Does Nano replace AI models?** -No — it changes *when* they run. Models author behavior and handle novel situations; compiled -graphs handle everything repeatable. Inference becomes the exception, not the default. - -**Can Nano run without an LLM?** -Yes. Compiled programs execute deterministically with no model in the loop. You can write -`.nano` source by hand and never touch a model. - -**Can a Nano program place an order / call an API / act on the world?** -No, by construction. Programs emit *intents*; a pluggable gate (your risk engine, policy -layer, or a human) approves or rejects each one, with a recorded reason. - -**Is this only for trading?** -No. Trading is the first workload because it is the most measurable one. The architecture -targets any Observe → Decide → Act → Record loop: automation, monitoring/response, robotics. - -**How is this different from LangChain or LangGraph?** -Those orchestrate live model calls; state and control flow involve the model at runtime. Nano -compiles behavior *ahead of time* into a replayable IR — the model is never the router. See -[Paper 01](docs/papers/01-why-nano.md) for the full landscape comparison. - -**Is it production-ready?** -It is a research preview with 173 passing tests. The core (IR, compiler, interpreter, bridge) -is real and tested; the CLI and several typing features are still design. The -[status table](#status--whats-real) is kept honest. - -## The paper series - -Seventeen short papers, each answering one question — **[docs/papers/](docs/papers/README.md)**. -Start with these four; they carry the whole thesis: -[Why Nano](docs/papers/01-why-nano.md) → [The Agentic Compiler](docs/papers/02-the-agentic-compiler.md) -→ [Determinism](docs/papers/03-determinism.md) → [Provenance](docs/papers/04-provenance.md). - -| Papers | Theme | -|---|---| -| [Why Nano](docs/papers/01-why-nano.md) · [The Agentic Compiler](docs/papers/02-the-agentic-compiler.md) · [Determinism](docs/papers/03-determinism.md) · [Provenance](docs/papers/04-provenance.md) | the core thesis | -| [Why Not Go](docs/papers/05-why-not-go.md) · [Why Not TypeScript](docs/papers/06-why-not-typescript.md) · [Nano vs. Pine](docs/papers/07-nano-vs-pine.md) | positioning | -| [LLM Integration](docs/papers/08-llm-integration.md) · [Autonomous Systems](docs/papers/09-autonomous-systems.md) · [The Nano Family](docs/papers/10-nano-family.md) | scope | -| [Performance](docs/papers/11-performance.md) · [Security](docs/papers/12-security.md) · [Design Principles](docs/papers/13-design-principles.md) · [Future Work](docs/papers/14-future-work.md) | engineering | -| [Closed-Loop Engineering](docs/papers/15-closed-loop-engineering.md) · [Quantum Computing](docs/papers/16-quantum-computing.md) · [Heterogeneous Compute](docs/papers/17-heterogeneous-compute.md) | the horizon | - -## Status — what's real - -| Shipped (tested) | Design / roadmap / research | -|---|---| -| Nano IR (`nano/ir/`) | CLI (`nano compile` / `replay` / `visualize`) | -| Reference interpreter (`nano/runtime/`) | `Series` look-ahead typing | -| `.nano` → IR compiler (`nano/compiler/`) | Nano+ adaptive layer (memory, multi-agent) | -| Risk-gate bridge + backtester (`nano/bridge/`) | Real quantum-hardware dispatch | -| Editor services (`nano/aethercode/`) | Cognitive execution / confidence routing | -| Pattern cache (`nano/memory/`) + optimization loop (`nano/loop/`) | | -| Conformance corpus (`nano/examples/`) + strategy library (`nano/library/`) | | - -Every claim in the docs cites shipped code or is explicitly labeled design, roadmap, or -research. +Nano includes a paired source/IR corpus that keeps the language contract concrete: -## Contributing +- [`nano/examples/`](nano/examples/) contains the core conformance fixtures. +- [`nano/library/`](nano/library/README.md) contains 15 trading-oriented strategies across momentum, mean-reversion, trend, volatility, volume, and risk categories. -Contributions are welcome — the [strategy library](nano/library/README.md) is the easiest -entry point (add a classic strategy as `.nano` source + expected IR), and -[CONTRIBUTING.md](CONTRIBUTING.md) covers setup, tests, and where help is most valuable. -Security reports: see [SECURITY.md](SECURITY.md). +Each pair is compiled, round-tripped through `StrategyGraph`, and replayed in the test suite. The corpus demonstrates syntax and deterministic behavior; it is not a strategy registry, a performance guarantee, or production trading advice. ## Documentation -| Document | Contents | -|---|---| -| [Paper Series](docs/papers/README.md) | 17 papers — one question each | -| [Build Order](BUILD_ORDER.md) | IR-first build sequence, the intent/gate lock, milestone status | -| [Strategy Library](nano/library/README.md) | Pine-inspired quant strategy corpus + contribution guide | -| [Optimization Loop](docs/nano-optimization-loop.md) | Nano++ autonomous optimization loop overview | -| [Contributing](CONTRIBUTING.md) | Dev setup, test workflow, contribution areas | -| [Security Policy](SECURITY.md) | Reporting, threat model, what determinism does and doesn't protect | +| Need | Start here | +| --- | --- | +| Exact grammar and runtime semantics | [Language reference](docs/language.md) | +| Module boundaries and data flow | [Architecture](docs/architecture.md) | +| Implemented vs. experimental vs. planned work | [Status](docs/status.md) | +| Strategy-corpus conventions | [Strategy corpus](nano/library/README.md) | +| Integration and contribution setup | [Contributing](CONTRIBUTING.md) | +| Security boundaries and reporting | [Security policy](SECURITY.md) | +| Design essays and research directions | [Paper series](docs/papers/README.md) | ---- +The paper series records design arguments and research directions; it is not the API specification. When a paper and the reference documentation differ, the source and tests define current behavior. -
- -**Nano is part of the [Aether](https://aethersystems.net) ecosystem** — autonomous AI, quantitative -trading, and cryptographic execution provenance. Built by **Aether AI LLC**. - -[Website](https://aethersystems.net) · [Aether Code (web IDE)](https://app.aethersystems.net/code) · [Papers](docs/papers/README.md) · [Strategy Library](nano/library/README.md) - -If Nano's ideas resonate, a ⭐ helps others find it. - -
+## Contributing -*Naming is under trademark review; the language codename and `.nano` extension are stable for -development.* +Nano is most useful when its compact contract stays explicit. Contributions should preserve deterministic reference execution, the intent/gate boundary, conformance coverage, and clear implemented-versus-planned labeling. See [CONTRIBUTING.md](CONTRIBUTING.md) for setup and contribution paths. diff --git a/SECURITY.md b/SECURITY.md index 32d057f..240b725 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,57 +1,45 @@ -# Security Policy +# Security policy -Nano is infrastructure for autonomous systems — security posture is a design pillar, not an -afterthought. This document covers how to report issues and what the architecture does and -does not protect. +Nano is an alpha reference implementation for deterministic, host-governed decision rules. This document explains how to report a vulnerability and what the current code does and does not protect. ## Reporting a vulnerability -Please **do not** open a public issue for security-sensitive reports. Instead use -[GitHub private vulnerability reporting](https://github.com/DBarr3/Nano/security/advisories/new) -on this repository. Include a reproduction if possible. You'll get an acknowledgment, and -fixes for confirmed issues are prioritized ahead of all feature work. +Please do not open a public issue for security-sensitive reports. Use [GitHub private vulnerability reporting](https://github.com/DBarr3/Nano/security/advisories/new) and include a minimal reproduction where possible. The latest `main` branch is the supported security-fix target. -Currently supported for security fixes: the latest state of `main`. +## Security properties of the current core -## Threat model +| Concern | Current protection | +| --- | --- | +| Malformed strategy IR | `StrategyGraph.from_dict()` validates the supported version, nodes, effects, and intent-manifest requirement. | +| A strategy directly calling an external system | The v0.1 grammar and reference runtime expose only intent emission; there is no exchange, network, subprocess, or action primitive. | +| Reference-runtime reproducibility | The interpreter consumes caller-provided frames and does not read an ambient clock, RNG, or network. Identical graph/frame inputs produce the same reference result. | +| Gate separation | `NanoBridge` forwards intents to a host-provided `DecisionGate` and records its returned decisions. It does not execute them. | +| Optional receipt verification | The optional Protocol-C adapter can sign and verify host decision receipts when its dependency is installed. | -What Nano's design defends against, by construction: +## Boundaries and non-goals -| Threat | Defense | -|---|---| -| A compiled program acting on the world directly | No actuation/exchange/network primitive exists in the language; programs emit intents, a gate disposes | -| A program exceeding its declared capabilities | Effect manifests on every IR module, validated at load time — undeclared effects fail closed | -| Nondeterministic or unreproducible execution | No ambient clock/RNG/IO; time and entropy are injected, logged inputs; replay is bit-identical | -| Silent self-modification | Proposed graph changes pass admission gates (validation, replay verification, sign-off) before any runtime loads them | -| Tampered execution history | Append-only audit log; optional provenance adapter produces signed, independently re-verifiable receipts | -| Malicious or malformed IR | Schema validation at load; content-addressed graphs — the hash you audited is the artifact that runs | +Nano is **not** an OS sandbox, a complete authorization system, or a durable audit platform. -## Assumptions and non-goals — read this +- **The host process is trusted.** Any Python code in the same process, including a data feed, gate, or dependency, can perform side effects outside Nano's strategy boundary. +- **The host owns the gate.** Nano cannot guarantee that a host policy is correct, deterministic, or safe. `Backtester.verify_replay()` can detect divergent gate results; it cannot prevent a permissive gate from approving a bad action. +- **Inputs are caller-provided.** Deterministic replay means identical inputs reproduce the reference result. It does not authenticate market data, prove its provenance, or prevent poisoned inputs. +- **The base log is in memory.** It is an ordered result value, not durable append-only storage or tamper-proof evidence. Durable storage and signing are integration responsibilities. +- **Strategy IR is not content-addressed.** The separate experimental `LoopGraph` has a content hash; `StrategyGraph` does not. +- **No LLM/runtime escalation exists in the core.** Model safety, prompt injection, live actuation, and autonomous deployment are outside the current implementation. -Nano's guarantees are **language-level and IR-level**, enforced by a reference interpreter -written in Python. Be clear about the boundary: +## In scope for reports -- **The host process is trusted.** Nano is not an OS sandbox. Code running in the same Python - process as the interpreter (your gate, your data feed, an installed package) is outside the - boundary and can do anything Python can do. -- **The gate is yours.** Nano guarantees every intent reaches your gate with a full record; it - cannot guarantee your gate's policy is correct. A permissive gate approves bad trades - deterministically. -- **Inputs are trusted-as-logged.** Determinism means identical inputs replay identically. It - does not authenticate the inputs themselves — feed integrity is the deployment's job. -- **The escalation path is a model.** Anything routed back to LLM reasoning inherits LLM - failure modes (including prompt injection). Nano bounds *when* that path is used and gates - its output; it does not make the model safe. +- strategy-IR validation bypasses or manifest violations that lead to invalid reference execution; +- an intent/action path that bypasses the `DecisionGate` boundary in the shipped core; +- nondeterministic behavior from identical graph/frame inputs in the reference runtime; +- defects in optional provenance receipt verification, when the optional dependency is installed; and +- security-relevant crashes or data corruption in the public Python API. -Paper [12 — Security](docs/papers/12-security.md) covers the capability-restriction argument -in depth. +## Out of scope -## Scope for reports +- vulnerabilities in a host's gate, data feed, execution connector, or Python environment; +- market losses or strategy quality; +- unsupported research proposals described only in design notes; and +- third-party supply-chain defects without a Nano-specific integration issue. -In scope: IR validation bypasses, effect-manifest escapes, determinism violations (same graph + -same inputs → different result or log), intent/gate boundary escapes, provenance-receipt -forgery. - -Out of scope: vulnerabilities in your gate implementation, market losses from strategy logic, -Python-ecosystem supply-chain issues (report those upstream — but tell us if Nano's pinning -should catch them). +For the implementation map, see [docs/architecture.md](docs/architecture.md). For current maturity, see [docs/status.md](docs/status.md). diff --git a/docs/README.md b/docs/README.md index 7c6e2ea..8ec888d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,14 +1,28 @@ -# docs/ +# Nano documentation -Documentation for the Nano language and runtime. +This directory separates the **implemented contract** from **design notes and research directions**. -- **[papers/](papers/)** — the research-paper series. One question per paper, from - *Why Nano?* through determinism, provenance, the language comparisons, and the - quantum / heterogeneous-compute research track. Start at [papers/README.md](papers/README.md). -- **[nano-optimization-loop.md](nano-optimization-loop.md)** — overview of the Nano++ - autonomous optimization loop (`nano/loop/`). +For questions about what Nano does today, start with the reference documents below. The source and test suite are authoritative when documentation is unclear or out of date. -For the top-level story, see the repository [README.md](../README.md) and -[BUILD_ORDER.md](../BUILD_ORDER.md). The language contract is defined by the code: -`nano/ir/` (the IR schema), `nano/runtime/` (the reference interpreter), and -`nano/examples/` (the conformance corpus). +## Reference documentation + +| Document | Purpose | +| --- | --- | +| [Architecture](architecture.md) | The actual source -> IR -> interpreter -> host-gate flow and module boundaries. | +| [Language reference](language.md) | The locked v0.1.0 grammar, IR shape, and execution semantics. | +| [Status](status.md) | Implemented, experimental, optional, and unimplemented capabilities. | +| [Strategy corpus](../nano/library/README.md) | Conventions for paired `.nano` and IR examples. | +| [Build notes](../BUILD_ORDER.md) | Historical sequencing and the project's architectural constraints. | +| [Security policy](../SECURITY.md) | Reporting process and the boundary of Nano's guarantees. | + +## Integration examples + +- [`../examples/`](../examples/) contains runnable host-integration demonstrations. +- [`../nano/examples/`](../nano/examples/) is the source/IR conformance fixture corpus, not a generic application-examples directory. +- [`../nano/aethercode/`](../nano/aethercode/) contains pure editor-service helpers (diagnostics, semantic tokens, and IR preview), not a packaged editor extension. + +## Design notes and research directions + +[`papers/`](papers/) contains essays about the broader Nano thesis, possible LLM integration, autonomous optimization, and research directions. These documents may describe proposals that are not part of the runtime. Treat them as design material, not as a language specification or a promise of current behavior. + +For the project entry point, return to the repository [README](../README.md). diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..5b3e13d --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,72 @@ +# Nano architecture + +> This page describes the code in the repository today. It does not describe proposed LLM routing, live execution, or a general-purpose agent platform. + +## Core flow + +```text +.nano source + -> nano.compiler (tokenize, parse, codegen) + -> StrategyGraph (validated, serializable IR) + -> nano.runtime.execute(graph, MarketFrame) + -> Intent(s) + ordered per-run LogEntry values + -> optional NanoBridge + -> host DecisionGate + -> Decision record(s) +``` + +The core is deliberately small. It is a Python reference implementation for deterministic evaluation of threshold rules over host-injected numeric signal series. + +## The compiler and strategy IR + +`nano/compiler/` contains a handwritten lexer and recursive-descent parser. `compile_source()` turns a valid `.nano` program into an immutable `StrategyGraph`. + +`StrategyGraph` is a flat, validated strategy representation: + +- one optional `ScheduleNode`; +- zero or more `ConditionNode` values; +- zero or more `IntentNode` values; and +- zero or more metadata-only `AgentNode` values. + +It is called a graph for the project's conceptual model, but the current `StrategyGraph` has no edges or branching topology. At runtime, all conditions gate all intents. `StrategyGraph.from_dict()` validates the version, known node types, known effect names, and the requirement that an intent-bearing strategy declares `intent.emit`. It is not a type checker, an optimizer, or a content-addressed artifact. + +## Deterministic reference execution + +`nano/runtime/` evaluates a graph against a `MarketFrame`: + +- timestamps and signal series are injected by the caller; +- the scheduler expands the strategy interval over those timestamps; +- conditions are evaluated in source/IR order and short-circuit on the first failure; +- if every condition passes, the runtime emits each configured intent; and +- the result contains immutable intents and an ordered, in-memory event log. + +The interpreter has no network, wall clock, random-number source, or side-effecting action path. Identical graphs and frames produce identical reference results. This does not authenticate input data or sandbox the Python host process. + +## Governance boundary + +`nano/runtime/` never acts on an intent. `nano/bridge/NanoBridge` forwards each emitted `Intent` to a host-defined `DecisionGate` and records the returned `Decision` in the bridge result. + +The host owns policy, external action, persistence, and feed integrity. A `DecisionGate` is a protocol, not a built-in risk engine or exchange integration. For bridge-level replay, the gate must behave deterministically; `Backtester.verify_replay()` runs the same graph/frames/gate twice and raises when the serialized reports differ. + +`nano/bridge/provenance.py` is an optional host adapter. When its external dependency is installed, it can sign decision receipts as a side channel. It is outside the language and deliberately uses time/entropy for signing, so it is not part of the base deterministic result. + +## Supporting modules + +| Module | Current role | Important boundary | +| --- | --- | --- | +| `nano/aethercode/` | Pure diagnostics, semantic-token, and IR-preview helpers. | Not a packaged LSP or IDE integration. | +| `nano/memory/` | In-memory pattern matching that returns context and an `escalate` boolean. | It is not called by the compiler, interpreter, or bridge and does not call a model. | +| `nano/loop/` | Separate experimental `LoopGraph` validator, mutation-admission helper, and deterministic simulator protocol. | There is no loop compiler or executor, model integration, deployment system, or QPU connector. | +| `nano/examples/` | Paired `.nano` source and expected-IR conformance fixtures. | They are language test assets, not generic runnable programs. | +| `nano/library/` | Paired, trading-oriented strategy corpus. | It demonstrates syntax and test conformance; it is not a registry or investment advice. | + +## Trust boundaries + +Nano provides a narrow execution contract, not a complete security boundary: + +- **Nano validates strategy IR.** It does not validate the correctness or provenance of market data. +- **Nano proposes intents.** The host gate decides whether to approve them; external actuation is the host's responsibility. +- **The reference runtime is deterministic.** A nondeterministic gate, mutable host environment, or different input frame can change a larger system's outcome. +- **The base log is in memory.** Durable audit storage and cryptographic proof require host integration. + +See [language.md](language.md) for the source contract and [status.md](status.md) for maturity boundaries. diff --git a/docs/language.md b/docs/language.md new file mode 100644 index 0000000..4baf698 --- /dev/null +++ b/docs/language.md @@ -0,0 +1,102 @@ +# Nano language reference (v0.1.0) + +Nano v0.1.0 is a compact DSL for scheduled threshold rules. It is intentionally not a general-purpose programming language. + +## Valid example + +```nano +strategy Momentum { + agent Analyst + + every 5m { + if RSI(14) < 30 and VOLUME > 1000000 { + buy(BTC, 0.91) + observe() + } + } +} +``` + +This program emits `BUY` and `OBSERVE` intents only when both injected signal values satisfy their comparisons. It does not calculate `RSI`, fetch market data, invoke `Analyst`, or place an order. + +## Grammar + +```text +program := "strategy" IDENT "{" item* "}" +item := schedule | agent +agent := "agent" IDENT +schedule := "every" INTERVAL "{" [rule] "}" +rule := "if" condition ("and" condition)* "{" action+ "}" +condition := IDENT ["(" INT ")"] OP NUMBER +action := "buy" "(" IDENT ["," NUMBER] ")" + | "sell" "(" IDENT ["," NUMBER] ")" + | "execute" "(" ")" + | "pause" "(" ")" + | "observe" "(" ")" +``` + +`INTERVAL` is an integer followed by `s`, `m`, `h`, or `d` (for example `5m` or `1h`). `OP` is one of `<`, `<=`, `>`, `>=`, `==`, or `!=`. Numeric literals are non-negative integers or decimals. + +## Semantic constraints + +- A strategy may have **at most one** `every` block. +- An `every` block may have **at most one** `if` rule. +- Multiple conditions are joined with logical **AND** and are evaluated in order. +- A condition compares one named signal with one numeric literal. The right-hand side cannot be another identifier. +- The only actions are `buy`, `sell`, `execute`, `pause`, and `observe`. +- `buy` and `sell` require an asset identifier and accept an optional confidence value in `[0, 1]`. +- `agent Name` is parsed and stored as metadata, but has no runtime behavior in v0.1.0. + +There are no variables, arithmetic, boolean `or`/`not`, function declarations, loops, imports, user-defined actions, I/O, or external API calls. + +## Signals and lookback labels + +Signals are supplied by the host in a `MarketFrame` mapping: + +```python +MarketFrame( + timestamps=(0, 300), + signals={"RSI": (45.0, 22.0), "VOLUME": (900000.0, 1200000.0)}, +) +``` + +Nano does not calculate indicators. A data feed must compute `RSI`, `VOLUME`, or any other named signal before calling the runtime. + +The optional parenthesized integer in a condition is a source-level convention only: `RSI(14)` and `RSI` compile to the same `ConditionNode(signal="RSI", ...)`. Use the annotation to document the feed contract; do not expect the runtime to apply a lookback window. + +## Compilation result + +`compile_source()` emits a `StrategyGraph` that serializes to canonical JSON-like data: + +```json +{ + "type": "Strategy", + "nanoIrVersion": "0.1.0", + "name": "Momentum", + "effects": ["intent.emit", "log.append"], + "nodes": [ + {"type": "Schedule", "interval": "5m"}, + {"type": "Condition", "signal": "RSI", "operator": "<", "value": 30}, + {"type": "Intent", "action": "BUY", "asset": "BTC", "confidence": 0.91} + ] +} +``` + +The v0.1 compiler always emits the same two effect declarations. Load-time validation rejects unknown node/effect names and intent nodes without `intent.emit`. It does not implement general static typing, control-flow analysis, content hashing, or optimization passes. + +## Runtime semantics + +For each scheduled timestamp, the reference interpreter: + +1. reads each required signal from the injected frame; +2. evaluates conditions in order, stopping at the first false condition; +3. emits every configured intent when all conditions pass; and +4. records ordered execution events in the returned result. + +A strategy with no conditions emits no intents under the current interpreter. An invalid interval string supplied through raw IR may be rejected when the scheduler executes it rather than at IR load time. + +## Errors + +The lexer and parser raise `NanoSyntaxError` with a 1-based line and column. IR load validation raises `IRValidationError` or `ManifestViolation` when the serialized strategy shape violates the supported contract. + +For host integration and replay semantics, see [architecture.md](architecture.md). diff --git a/docs/nano-optimization-loop.md b/docs/nano-optimization-loop.md index 1d1ef5b..848d6c6 100644 --- a/docs/nano-optimization-loop.md +++ b/docs/nano-optimization-loop.md @@ -1,68 +1,41 @@ -# Nano++ — The Autonomous Optimization Loop +# Nano++ experimental loop primitives -**Status:** design + reference implementation (`nano/loop/`). +**Status:** experimental data-model and admission primitives in `nano/loop/`; not an executable autonomous optimization system. -Nano started by describing trading strategies. Nano++ describes **execution itself**: it turns an -optimization *process* into a deterministic, replayable execution graph. The reasoning model does -not stay in the loop — it *builds* the loop, then the loop runs on its own. +Nano++ is a research direction adjacent to the core strategy DSL. The code currently provides three narrowly scoped building blocks: -``` -Think once → Compile → Execute N times → Only think again when necessary. -``` - -## The universal lifecycle +1. `LoopGraph` validates and serializes a separate loop document with ordered node references and effect declarations. +2. `admit_mutation()` makes a deterministic admission decision from caller-supplied candidate facts such as replay match, regression count, benchmark delta, and allowed capabilities. +3. `QuantumRuntime` defines a protocol and `SimulatorRuntime` returns deterministic, hash-derived reference results for a `QuantumJob`. -Trading, security response, quantum-circuit tuning, robotics — different domains, one shape: +None of these modules executes a loop, invokes a model, performs benchmarking, mutates a running system, deploys changes, or dispatches work to a real quantum processor. -``` -observe → propose → compile → execute → measure → verify → admit → repeat -``` +## What LoopGraph does -Every stage is deterministic, every transition recorded, every optimization replayable. Domains -supply different node payloads; the lifecycle never changes. Trading emits BUY/SELL; another -domain emits a different `Execute` payload — the graph is identical. +A `LoopGraph` is a validated, serializable document whose nodes have IDs, stage names, ordered input references, and free-form attributes. It rejects unknown stages, forward references, duplicate IDs, unknown effects, and stages that lack their required declared capability. -## Universal node vocabulary (`nano/loop/nodes.py`) - -Fifteen stage kinds compose any autonomous loop: - -`Observe` · `Infer` · `Evaluate` · `Optimize` · `Mutate` · `Verify` · `Gate` · `Execute` · -`Pause` · `Replay` · `Checkpoint` · `Rollback` · `Escalate` · `Sign` · `Benchmark` +```text +Loop document -> LoopGraph.from_dict() -> validation / content_hash() +``` -A `LoopGraph` (`nano/loop/graph.py`) is a validated, content-addressable DAG. Forward references -and undeclared capabilities are load-time rejections — the same effect-manifest security model the -strategy IR uses: a stage that needs a capability the graph did not declare cannot run. +`LoopGraph.content_hash()` is deterministic for the loop document. This property belongs to the separate experimental loop representation; it does not make `StrategyGraph` content-addressed and does not provide loop execution or replay. -## Safe self-mutation (`nano/loop/mutation.py`) +## Mutation admission -A loop that rewrites itself must never mutate live. Every proposed change becomes an engineering -artifact through four gates in order: +`Candidate` is input to `admit_mutation()`, not an artifact that Nano creates by itself. The helper checks, in order: -``` -1. Proposal — a model proposes an improvement -2. Compilation — the proposal becomes a deterministic artifact -3. Verification — replay match · benchmark gain · zero regressions · static analysis · capability check -4. Admission — policy · risk · provenance · capability ceiling +```text +replay match -> no regressions -> static flag -> benchmark gain -> capability ceiling ``` -`admit_mutation` returns the blocking stage + reason on failure, or a gated artifact marked -`admitted_pending_deploy` on success. **Nothing deploys automatically** — an operator does. -Components propose; gates decide. +On success it returns an `admitted_pending_deploy` record. A host or operator must decide whether and how to deploy anything. This is useful as a small policy primitive, not evidence of autonomous self-modification. -## Vendor-agnostic quantum runtime (`nano/loop/quantum.py`) +## Simulator protocol -Nano knows *quantum jobs*, not vendors. A `QuantumJob(circuit_id, shots, params)` carries no -vendor field; a backend implements the `QuantumRuntime` protocol -(`submit(job) → QuantumResult{backend, fidelity, distribution}`). Swapping hardware swaps the -runtime, never the loop. `SimulatorRuntime` is the deterministic reference backend, so loop -replays stay bit-identical whether they run on a simulator today or dedicated hardware later. +`SimulatorRuntime` implements `QuantumRuntime.submit(job)` as a pure, hash-derived reference calculation. It exists to make the interface testable without a vendor dependency. There is no real hardware connector, performance claim, or quantum advantage claim in this repository. -## Why it matters +## Relationship to core Nano -One execution model across every autonomous system. The loop is deterministic and replayable, so -"why did the system do that?" always has an exact, reproducible answer — and a self-improving -system can never ship an unverified change. Trading is the proving ground because it has -deterministic inputs and measurable outcomes; the architecture generalizes to any -Observe → Decide → Act → Record loop. +The core `.nano` strategy pipeline is documented in [architecture.md](architecture.md). It compiles source into `StrategyGraph` and runs it over a `MarketFrame`. Nano++ does not share a runtime or executor with that path today. -*Reference implementation: `nano/loop/` and `nano/memory/`, covered by the repo test suite.* +For current maturity boundaries, see [status.md](status.md) and the [design-notes index](papers/README.md). diff --git a/docs/papers/01-why-nano.md b/docs/papers/01-why-nano.md index 8b978cd..6afd1fc 100644 --- a/docs/papers/01-why-nano.md +++ b/docs/papers/01-why-nano.md @@ -1,5 +1,8 @@ # 01 — Why Nano +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Autonomous systems stop reasoning about the same thing over and over by compiling known reasoning into deterministic execution — Nano is the language, IR, and engine-governed runtime that makes that compilation possible. --- @@ -97,7 +100,7 @@ Nano's first workload is trading strategy execution — not because trading is t ## What exists today -Honestly stated: the IR, the deterministic reference interpreter, the pattern memory layer, the `.nano` → IR compiler (`nano/compiler/`), the risk-gate bridge and backtester (`nano/bridge/`), the strategy library (`nano/library/`), editor language services (`nano/aethercode/`), and the Nano++ optimization loop with a deterministic quantum simulator backend (`nano/loop/`) are implemented, covered by 173 passing tests. Every example compiles from `.nano` source to bit-identical IR and replays deterministically. The CLI (`nano compile` / `nano replay` / `nano visualize`) and real quantum-hardware dispatch remain design and research, tracked in [BUILD_ORDER.md](../../BUILD_ORDER.md) and paper [14](14-future-work.md). Comparative claims about other frameworks above describe their documented designs, not benchmarks we have run. +Honestly stated: the IR, the deterministic reference interpreter, the pattern memory layer, the `.nano` → IR compiler (`nano/compiler/`), the risk-gate bridge and backtester (`nano/bridge/`), the strategy library (`nano/library/`), editor language services (`nano/aethercode/`), and the Nano++ optimization loop with a deterministic quantum simulator backend (`nano/loop/`) are implemented and covered by the repository test suite. Every example compiles from `.nano` source to bit-identical IR and replays deterministically. The CLI (`nano compile` / `nano replay` / `nano visualize`) and real quantum-hardware dispatch remain design and research, tracked in [BUILD_ORDER.md](../../BUILD_ORDER.md) and paper [14](14-future-work.md). Comparative claims about other frameworks above describe their documented designs, not benchmarks we have run. --- diff --git a/docs/papers/02-the-agentic-compiler.md b/docs/papers/02-the-agentic-compiler.md index a785978..e8ce27b 100644 --- a/docs/papers/02-the-agentic-compiler.md +++ b/docs/papers/02-the-agentic-compiler.md @@ -1,5 +1,8 @@ # 02 — The Agentic Compiler +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano's compiler does not translate algorithms into machine code — it extracts repeatable decisions from a reasoning model and fixes them into a deterministic, auditable execution graph. --- diff --git a/docs/papers/03-determinism.md b/docs/papers/03-determinism.md index 79ca84c..268364f 100644 --- a/docs/papers/03-determinism.md +++ b/docs/papers/03-determinism.md @@ -1,5 +1,8 @@ # 03 — Determinism +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano is deterministic so that "why did the agent do that?" has an exact, mechanically checkable answer — every execution can be replayed bit-for-bit from its recorded inputs. --- diff --git a/docs/papers/04-provenance.md b/docs/papers/04-provenance.md index f688afd..479d626 100644 --- a/docs/papers/04-provenance.md +++ b/docs/papers/04-provenance.md @@ -1,5 +1,8 @@ # 04 — Provenance: Protocol C +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Protocol C is Nano's cryptographic execution protocol — a chain of verifiable answers to who proposed a behavior, what compiled, what executed, who approved it, what changed, and when. --- diff --git a/docs/papers/05-why-not-go.md b/docs/papers/05-why-not-go.md index 22014c7..151e014 100644 --- a/docs/papers/05-why-not-go.md +++ b/docs/papers/05-why-not-go.md @@ -1,5 +1,8 @@ # 05 — Why Not Go? +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Go tells a computer how to compute; Nano tells an autonomous system when to act — they solve different problems, and a serious deployment will often use both. --- diff --git a/docs/papers/06-why-not-typescript.md b/docs/papers/06-why-not-typescript.md index 7fd1a3f..6210a61 100644 --- a/docs/papers/06-why-not-typescript.md +++ b/docs/papers/06-why-not-typescript.md @@ -1,5 +1,8 @@ # 06 — Why Not TypeScript? (And Why Not Python?) +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** TypeScript models applications and Python models reasoning — Nano models deterministic decision graphs, and removing application machinery from the language is not missing functionality, it is removing uncertainty. --- diff --git a/docs/papers/07-nano-vs-pine.md b/docs/papers/07-nano-vs-pine.md index 82a7371..06a64a8 100644 --- a/docs/papers/07-nano-vs-pine.md +++ b/docs/papers/07-nano-vs-pine.md @@ -1,5 +1,8 @@ # 07 — Nano vs. Pine Script and Trading DSLs +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Pine Script draws indicators and fires alerts inside a charting product; Nano compiles decisions into a gated, replayable execution substrate — they share a surface vocabulary and almost nothing else. --- diff --git a/docs/papers/08-llm-integration.md b/docs/papers/08-llm-integration.md index 6dec40c..974b645 100644 --- a/docs/papers/08-llm-integration.md +++ b/docs/papers/08-llm-integration.md @@ -1,5 +1,8 @@ # 08 — LLM Integration +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano is the model-agnostic execution substrate beneath reasoning models — Claude, GPT, Gemini, or a local model all compile to the same IR, and the economics of compiled memory versus per-decision inference decide the architecture. --- diff --git a/docs/papers/09-autonomous-systems.md b/docs/papers/09-autonomous-systems.md index 38d19c2..e81d782 100644 --- a/docs/papers/09-autonomous-systems.md +++ b/docs/papers/09-autonomous-systems.md @@ -1,5 +1,8 @@ # 09 — Autonomous Systems +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Every autonomous system runs the same loop — Observe, Decide, Act, Record — and Nano compiles the Decide stage wherever that loop exists, with autonomous trading (ATS) as the first workload rather than the product. --- diff --git a/docs/papers/10-nano-family.md b/docs/papers/10-nano-family.md index fda314d..a1b75a9 100644 --- a/docs/papers/10-nano-family.md +++ b/docs/papers/10-nano-family.md @@ -1,5 +1,8 @@ # 10 — The Nano Family +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano, Nano+, and Nano++ are three capability tiers over one compiler and one IR — deterministic execution, adaptive execution, and large-scale computational execution — so a user grows without ever migrating. --- diff --git a/docs/papers/11-performance.md b/docs/papers/11-performance.md index 4f7a074..fb6573e 100644 --- a/docs/papers/11-performance.md +++ b/docs/papers/11-performance.md @@ -1,5 +1,8 @@ # 11 — Performance +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano's performance claim is architectural — replacing per-decision inference with compiled execution removes orders of magnitude of latency and cost by construction — while the runtime's own constants remain deliberately unmeasured until there are benchmarks worth trusting. --- @@ -22,7 +25,7 @@ Three shipped components define the execution profile: ## What is honestly unmeasured -The repository currently ships correctness tests (121 of them), not benchmarks. The following numbers do not exist yet, and no document in this series should be read as implying them: +The repository currently ships correctness tests, not benchmarks. The following numbers do not exist yet, and no document in this series should be read as implying them: - Interpreter throughput (ticks/second) on realistic strategy graphs and frame sizes. - Pattern retrieval latency as a function of store size. diff --git a/docs/papers/12-security.md b/docs/papers/12-security.md index 752a0b1..844dd9c 100644 --- a/docs/papers/12-security.md +++ b/docs/papers/12-security.md @@ -1,5 +1,8 @@ # 12 — Security +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano's security model is capability restriction by construction — effect manifests, no actuation primitives in the language, load-time validation, and admission gates — so least privilege is a property of the artifact, not a policy around it. --- diff --git a/docs/papers/13-design-principles.md b/docs/papers/13-design-principles.md index 297ccb4..013add7 100644 --- a/docs/papers/13-design-principles.md +++ b/docs/papers/13-design-principles.md @@ -1,5 +1,8 @@ # 13 — Design Principles +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Six principles govern every Nano decision — determinism, the intent/dispose split, IR-first construction, injected effects, content addressing, and gated self-improvement — and each is a rule that resolves design arguments before they start. --- diff --git a/docs/papers/14-future-work.md b/docs/papers/14-future-work.md index d4da6f5..2e71a76 100644 --- a/docs/papers/14-future-work.md +++ b/docs/papers/14-future-work.md @@ -1,5 +1,8 @@ # 14 — Future Work +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** The build order is deliberate — with the IR, interpreter, compiler front end, risk-gate bridge, and editor services shipped, the remaining work is the CLI, the cognitive execution layer, and real-hardware dispatch on the quantum research track — each stage proven on the shipped IR before the next begins. --- @@ -13,7 +16,7 @@ **Goal: a meaningful result in under a minute.** ``` -pip install nano +pip install aether-nano nano compile strategy.json # validate IR, report manifest and content hash nano replay strategy.json frame.json # execute; print intents + audit log; verify bit-identical re-run nano visualize strategy.json # render the execution graph diff --git a/docs/papers/15-closed-loop-engineering.md b/docs/papers/15-closed-loop-engineering.md index 8317a89..f59ce69 100644 --- a/docs/papers/15-closed-loop-engineering.md +++ b/docs/papers/15-closed-loop-engineering.md @@ -1,5 +1,8 @@ # 15 — Closed-Loop Engineering +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Nano turns autonomous improvement into an engineering loop — execute, measure, propose, verify by replay, gate, recompile — where every iteration is evidence-backed and nothing changes without passing through a gate. --- diff --git a/docs/papers/16-quantum-computing.md b/docs/papers/16-quantum-computing.md index 7a23426..c9e62e6 100644 --- a/docs/papers/16-quantum-computing.md +++ b/docs/papers/16-quantum-computing.md @@ -1,5 +1,8 @@ # 16 — Quantum Computing +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** Quantum computing enters Nano as a research track, not a promise — the shipped Nano++ loop already models vendor-agnostic quantum jobs with a deterministic simulator backend, while real-hardware dispatch and any advantage claim remain squarely research. --- diff --git a/docs/papers/17-heterogeneous-compute.md b/docs/papers/17-heterogeneous-compute.md index b7b9b13..2570fd1 100644 --- a/docs/papers/17-heterogeneous-compute.md +++ b/docs/papers/17-heterogeneous-compute.md @@ -1,5 +1,8 @@ # 17 — Heterogeneous Compute +> **Design-note scope:** This essay may discuss proposals or research hypotheses beyond Nano v0.1.0. For the implemented contract, see [Architecture](../architecture.md), [Language](../language.md), and [Status](../status.md). + + **Answer in one sentence:** One IR, many backends — Nano's long-term execution model dispatches the same validated graph to the reference interpreter, native runtimes, distributed clusters, or specialized hardware, with the choice of backend invisible to the graph's meaning and guarantees. --- diff --git a/docs/papers/README.md b/docs/papers/README.md index 1fa0e07..2de4bcb 100644 --- a/docs/papers/README.md +++ b/docs/papers/README.md @@ -1,49 +1,41 @@ -# The Nano Paper Series +# Nano design notes and research directions -Seventeen short papers, each answering one question about Nano — the compiled execution architecture for autonomous engineering systems. Read [01](01-why-nano.md) first; the rest stand alone. +> **Important:** this series explores the broader Nano thesis. It is not the language specification, an API reference, or evidence that a capability is implemented. For current behavior, start with the [architecture](../architecture.md), [language reference](../language.md), and [status](../status.md). -## The core thesis +These short essays record the rationale behind the project, possible future directions, and trade-offs worth testing. Some arguments intentionally extend beyond the alpha Python reference runtime. When a paper differs from the code or reference documentation, the code and tests define the current contract. -| # | Paper | One line | -|---|---|---| -| 01 | [Why Nano](01-why-nano.md) | Autonomous systems stop re-reasoning by compiling known reasoning into deterministic execution. | -| 02 | [The Agentic Compiler](02-the-agentic-compiler.md) | Nano compiles decisions, not algorithms — and moves the LLM from inside the hot loop to above it. | -| 03 | [Determinism](03-determinism.md) | "Why did the agent do that?" is answered by bit-identical replay, not reconstruction (implemented). | -| 04 | [Provenance: Protocol C](04-provenance.md) | A cryptographic execution protocol: who proposed, what compiled, what executed, who approved, what changed, when. | +## Core ideas -## Positioning +| # | Paper | Question it explores | +| --- | --- | --- | +| 01 | [Why Nano](01-why-nano.md) | Why might deterministic compiled rules complement model-driven systems? | +| 02 | [The Agentic Compiler](02-the-agentic-compiler.md) | What would it mean to compile decisions rather than invoke a model every time? | +| 03 | [Determinism](03-determinism.md) | Why does deterministic replay matter for a reference runtime? | +| 04 | [Provenance: Protocol C](04-provenance.md) | How could an optional host integration add signed decision receipts? | -| # | Paper | One line | -|---|---|---| -| 05 | [Why Not Go?](05-why-not-go.md) | Go tells a computer how to compute; Nano tells an autonomous system when to act — complementary layers. | -| 06 | [Why Not TypeScript?](06-why-not-typescript.md) | TS models applications and Python models reasoning; Nano models deterministic decision graphs — removing uncertainty, not functionality. | -| 07 | [Nano vs. Pine Script](07-nano-vs-pine.md) | Pine draws indicators; Nano compiles gated, replayable decisions — no order primitive, intents plus effect manifests. | +## Positioning and scope -## Scope +| # | Paper | Question it explores | +| --- | --- | --- | +| 05 | [Why Not Go?](05-why-not-go.md) | Where might a narrow decision DSL fit beside general-purpose languages? | +| 06 | [Why Not TypeScript?](06-why-not-typescript.md) | What is different about modeling constrained decisions? | +| 07 | [Nano vs. Pine Script](07-nano-vs-pine.md) | How do the strategy examples compare with indicator-oriented scripting? | +| 08 | [LLM Integration](08-llm-integration.md) | What could model integration look like? *(Not implemented in Nano v0.1.0.)* | +| 09 | [Autonomous Systems](09-autonomous-systems.md) | Which broader system shapes motivate the project? | +| 10 | [The Nano Family](10-nano-family.md) | What is the proposed Nano / Nano+ / Nano++ framing? | -| # | Paper | One line | -|---|---|---| -| 08 | [LLM Integration](08-llm-integration.md) | Model-agnostic substrate: any reasoning model compiles to the same IR; the economics of compiled memory decide the architecture. | -| 09 | [Autonomous Systems](09-autonomous-systems.md) | The Observe → Decide → Act → Record loop generalizes everywhere; ATS trading is the first workload, not the product. | -| 10 | [The Nano Family](10-nano-family.md) | Nano / Nano+ / Nano++ — deterministic, adaptive, and computational execution over one compiler and one IR. | +## Engineering and research tracks -## Engineering +| # | Paper | Question it explores | +| --- | --- | --- | +| 11 | [Performance](11-performance.md) | What should future benchmarks measure? | +| 12 | [Security](12-security.md) | Which constraints can the strategy IR enforce, and where are host boundaries? | +| 13 | [Design Principles](13-design-principles.md) | Which architectural constraints should guide future work? | +| 14 | [Future Work](14-future-work.md) | Which capabilities are still unimplemented or experimental? | +| 15 | [Closed-Loop Engineering](15-closed-loop-engineering.md) | What might governed self-improvement require? | +| 16 | [Quantum Computing](16-quantum-computing.md) | When might specialized optimization backends be worth researching? | +| 17 | [Heterogeneous Compute](17-heterogeneous-compute.md) | What could portable execution across backends mean? | -| # | Paper | One line | -|---|---|---| -| 11 | [Performance](11-performance.md) | The win is architectural — execution replaces inference; the runtime's own constants are honestly unmeasured. | -| 12 | [Security](12-security.md) | Capability restriction by construction: absent primitives, effect manifests, load-time validation, admission gates. | -| 13 | [Design Principles](13-design-principles.md) | Six non-negotiable rules — determinism, intent/dispose, IR-first, injected effects, content addressing, gated change. | -| 14 | [Future Work](14-future-work.md) | With IR, compiler, bridge, and editor services shipped: the CLI, `Series` typing, cognitive execution layer, quantum hardware dispatch — in that order. | +## Reading responsibly -## The horizon - -| # | Paper | One line | -|---|---|---| -| 15 | [Closed-Loop Engineering](15-closed-loop-engineering.md) | Execute → measure → propose → verify by replay → gate → recompile: self-improvement as a governed engineering loop. | -| 16 | [Quantum Computing](16-quantum-computing.md) | A research track, sized honestly: if quantum backends ever win on real optimization workloads, the IR is ready to dispatch them. | -| 17 | [Heterogeneous Compute](17-heterogeneous-compute.md) | One IR, many backends — interpreter to cluster to accelerator — with bit-identical replay as the conformance contract. | - ---- - -Grounding: papers cite the shipped implementation (`nano/ir/`, `nano/runtime/`, `nano/memory/`, `nano/compiler/`, `nano/bridge/`, `nano/library/`, `nano/aethercode/`, `nano/loop/` — 173 tests) and mark everything else as design, roadmap, or research. Build sequence: [BUILD_ORDER.md](../../BUILD_ORDER.md). +The shipped repository includes a small strategy DSL, serializable strategy IR, deterministic reference interpreter, host decision-gate bridge, test corpus, and several experimental primitives. It does **not** include an LLM runtime, automatic escalation, general loop executor, live exchange integration, or real quantum dispatch. Use [status.md](../status.md) as the concise capability map. diff --git a/docs/status.md b/docs/status.md new file mode 100644 index 0000000..fa4c295 --- /dev/null +++ b/docs/status.md @@ -0,0 +1,32 @@ +# Nano status + +Nano is an **alpha reference implementation**. This page distinguishes code that is present today from adjacent experiments and future work. + +| Area | Status | Evidence and boundary | +| --- | --- | --- | +| `.nano` lexer, parser, and canonical code generation | Implemented | `nano/compiler/` parses the locked v0.1 grammar and produces `StrategyGraph`. There is no type system or optimizer pipeline. | +| Strategy IR validation | Implemented | `nano/ir/` validates the supported data shape and selected effect-manifest constraints. `StrategyGraph` is serializable but not content-addressed. | +| Reference interpreter and scheduler | Implemented | `nano/runtime/` evaluates injected `MarketFrame` data deterministically and returns intents plus an in-memory log. | +| Host decision-gate bridge and replay checker | Implemented | `nano/bridge/` forwards intents to a caller-provided `DecisionGate`; it never actuates externally. | +| Source/IR conformance corpus and strategy corpus | Implemented | `nano/examples/` and `nano/library/` are paired source/IR test assets. | +| Editor-service helpers | Implemented | `nano/aethercode/` provides diagnostics, semantic tokens, and IR-preview functions. Packaging an editor extension is separate work. | +| Protocol-C provenance wrapper | Optional integration | `nano/bridge/provenance.py` requires its extra dependency and signs side-channel receipts outside the core runtime. | +| Pattern retrieval | Experimental primitive | `PatternStore` matches in-memory patterns and returns context plus an `escalate` boolean. It is not connected to a model or runtime routing path. | +| Loop validation, mutation admission, and simulator protocol | Experimental primitives | `nano/loop/` validates/hashes a separate loop document and gates caller-supplied candidate facts. It has no compiler, executor, deployment system, or live quantum backend. | + +## Not implemented in this repository + +- CLI commands such as `nano compile`, `nano replay`, or `nano visualize` +- static typing, `Series`, look-ahead protection, arithmetic, or indicator computation +- LLM calls, automatic escalation, confidence routing, or multi-agent coordination +- live market data, exchange/API clients, order execution, or a built-in policy/risk engine +- persistent core audit storage, full provenance chains, or input-data authentication +- a general strategy-DAG executor, autonomous loop runner, self-modifying deployment, or real quantum-hardware dispatch + +## Reading the research material + +The [paper series](papers/README.md) explores broader design hypotheses. It is intentionally more ambitious than the alpha runtime. Do not infer an implemented API, benchmark, or guarantee from a paper unless it is corroborated by the reference documentation and code. + +## Compatibility posture + +The public Python functions exported by `nano.compiler`, `nano.runtime`, and `nano.bridge` are the usable API surface for v0.1.0. The grammar and IR version are intentionally narrow while the conformance corpus establishes expected behavior. As an alpha project, breaking changes may occur before a stable release. diff --git a/nano/__init__.py b/nano/__init__.py index d251ad3..3b06609 100644 --- a/nano/__init__.py +++ b/nano/__init__.py @@ -1,7 +1,8 @@ -"""Nano — deterministic intelligence execution graphs. +"""Nano - deterministic, host-governed rule execution. -IR-first: the execution graph (nano.ir) and reference runtime (nano.runtime) -come before the surface language (nano.compiler, Milestone 4). +The core package provides a small IR-first strategy DSL, a reference +interpreter, and host-gate integration primitives. It does not include an LLM +runtime, live-action connector, or general agent executor. """ __version__ = "0.1.0" diff --git a/nano/library/README.md b/nano/library/README.md index e72307b..d9e33f1 100644 --- a/nano/library/README.md +++ b/nano/library/README.md @@ -1,23 +1,18 @@ -# Nano Strategy Library +# Nano strategy corpus -The community strategy library for Nano — think TradingView's Pine public -library, but every entry is a **compilable, replayable, risk-gated artifact**. -Each strategy is a pair: +This directory is a paired, trading-oriented **conformance corpus** for the Nano v0.1.0 language. It is not a package registry, a live-strategy service, or investment advice. -- `.nano` — the human-readable source -- `_ir.json` — the canonical Nano IR it compiles to, byte-diffable and - verified by the conformance suite (`tests/test_library.py`) +Every entry has two files: -Nothing here places trades. A library strategy only **emits intents** -(`{"intent": "BUY", "asset": "BTCUSD", "confidence": 0.85}`); your risk engine -/ execution gate decides whether execution is allowed. That separation is -structural: the IR has no order or exchange primitive, and emitting intents -requires `intent.emit` in the strategy's effect manifest. +- `.nano` - source written in the locked Nano grammar +- `_ir.json` - the canonical strategy IR expected from that source -## Category map +`tests/test_library.py` verifies that each pair compiles to the expected IR, round-trips through `StrategyGraph`, and produces deterministic reference-runtime results. The corpus makes the small language contract concrete. + +## Categories | Category | Strategies | -|---|---| +| --- | --- | | `momentum/` | `rsi_oversold_reversal`, `stochastic_oversold`, `williams_r_reversal`, `roc_momentum` | | `mean_reversion/` | `bollinger_band_touch`, `zscore_reversion`, `cci_extreme` | | `trend/` | `golden_cross`, `macd_histogram_flip`, `donchian_breakout` | @@ -25,65 +20,49 @@ requires `intent.emit` in the strategy's effect manifest. | `volume/` | `volume_spike_confirmation`, `obv_trend` | | `risk/` | `max_drawdown_breaker` | -## Pine -> Nano translation conventions +## Signal conventions -Nano v0.1.0 is deliberately tiny: conditions compare **named signal series** -against numbers. Signals are injected at runtime by the host data feed — the -language never computes indicators. Anything Pine derives in-script (crosses, -spreads, band math) becomes a *named signal* with a documented convention: +Nano compares **host-provided named signal series** with numeric literals. It does not calculate indicators or fetch market data. The names and transformations below are conventions a host data feed must implement. -| Pine expression | Nano signal | Convention | -|---|---|---| -| `ta.rsi(close, 14)` | `RSI(14)` | raw RSI, 0..100 | -| `ta.stoch(...)` %K | `STOCH_K(14)` | raw %K, 0..100 | -| `ta.wpr(14)` | `WILLR_POS(14)` | Williams %R **+ 100** (0..100; number literals are non-negative) | -| `ta.roc(close, 10)` | `ROC(10)` | percent change over the window | +| Pine-style expression | Nano signal | Feed convention | +| --- | --- | --- | +| `ta.rsi(close, 14)` | `RSI(14)` | Raw RSI, 0-100 | +| `ta.stoch(...)` %K | `STOCH_K(14)` | Raw %K, 0-100 | +| `ta.wpr(14)` | `WILLR_POS(14)` | Williams %R + 100 (0-100) | +| `ta.roc(close, 10)` | `ROC(10)` | Percent change over the window | | Bollinger %B | `BB_PCT_B(20)` | `(close - lower) / (upper - lower)` | | Bollinger width | `BB_WIDTH(20)` | `(upper - lower) / middle * 100` | -| z-score | `ZSCORE_NEG(20)` | **negated** z-score: `-(close - sma) / stdev` | -| `ta.cci(20)` | `CCI_NEG(20)` | **negated** CCI (>= 100 is the classic < -100 zone) | -| `ta.crossover(sma50, sma200)` | `SMA_SPREAD(50)` | `SMA(50) - SMA(200)`; > 0 = post-golden-cross regime | -| MACD histogram | `MACD_HIST(9)` | MACD line - signal line | -| Donchian breakout | `DONCHIAN_POS(20)` | `(close - lower) / (upper - lower)`; >= 1 = new channel high | -| `ta.atr(14) / close` | `ATR_PCT(14)` | ATR as percent of price | +| z-score | `ZSCORE_NEG(20)` | Negated z-score | +| `ta.cci(20)` | `CCI_NEG(20)` | Negated CCI | +| `ta.crossover(sma50, sma200)` | `SMA_SPREAD(50)` | `SMA(50) - SMA(200)` | +| MACD histogram | `MACD_HIST(9)` | MACD line minus signal line | +| Donchian breakout | `DONCHIAN_POS(20)` | `(close - lower) / (upper - lower)` | +| `ta.atr(14) / close` | `ATR_PCT(14)` | ATR as a percentage of price | | `ta.mom(close, 10)` | `MOM(10)` | `close - close[10]` | | volume spike | `VOL_RATIO(20)` | `volume / sma(volume, 20)` | -| OBV trend | `OBV_SLOPE(20)` | linear-regression slope of OBV | -| equity drawdown | `DRAWDOWN` | portfolio drawdown, percent | +| OBV trend | `OBV_SLOPE(20)` | Linear-regression slope of OBV | +| equity drawdown | `DRAWDOWN` | Portfolio drawdown percentage | -Two rules fall out of the grammar: +Two v0.1 details matter: -1. **Non-negative literals.** Nano number literals cannot be negative, so - signals with negative natural ranges are shifted (`WILLR_POS`) or negated - (`ZSCORE_NEG`, `CCI_NEG`) by the feed. Document the transform in a `//` - comment next to the condition. -2. **The `(N)` argument is documentation.** `RSI(14)` and `RSI` compile to the - same `Condition` node; the lookback lives in the feed's signal definition. - Keep it in source anyway — it is the contract with the data feed. +1. Number literals cannot be negative. If an indicator naturally has a negative range, transform it in the feed and document the convention in a `//` comment. +2. The parenthesized integer is documentation only. `RSI(14)` and `RSI` compile to the same `ConditionNode(signal="RSI", ...)`; the feed owns the actual lookback calculation. -## How intents flow +## Intent boundary +```text +host MarketFrame -> Nano reference runtime -> Intent(s) + -> host DecisionGate -> Decision record(s) ``` -market frames -> Nano runtime -> Intent(BUY/SELL/EXECUTE/PAUSE/OBSERVE) - -> your risk engine / execution gate -> execution decision -``` -The runtime is a pure function of (IR, MarketFrame): identical inputs replay -bit-identically, so every library strategy is backtestable and auditable by -construction. `PAUSE`/`OBSERVE` intents (see `risk/`, `volatility/`) are how a -strategy asks the downstream gate to halt or watch; an optional `agent Name` -declaration names the behavior block that should take over. - -## Contributing a strategy - -1. Pick a category folder (or propose a new one). -2. Write `.nano` within the v0.1.0 grammar: one `every` block, one `if` - rule (and-chains allowed), actions from `buy/sell/execute/pause/observe`. - Document every derived-signal convention in a `//` comment. -3. Generate its partner: `python -c "from nano.compiler import compile_to_dict; ..."` - and save the result as `_ir.json` (same formatting style as existing - entries). -4. Run `python -m pytest tests/test_library.py -q` — the conformance suite - globs this directory, so your pair is picked up automatically. The pair - must compile bit-identically and the IR must round-trip; nothing merges - without a green suite. +A corpus strategy can emit `BUY`, `SELL`, `EXECUTE`, `PAUSE`, or `OBSERVE` intents. It cannot place a trade or call an external API. The host owns policy and any real-world action. + +## Adding a strategy + +1. Choose an existing category or propose a new one. +2. Add `.nano` using the [v0.1 grammar](../../docs/language.md): one `every` block, one `if` rule, AND-chained conditions, and supported intent actions. +3. Add the matching `_ir.json` with the canonical `compile_to_dict()` output. +4. Document every derived-signal convention in a source comment. +5. Run `python -m pytest tests/test_library.py -q`. + +The pair must compile to the checked-in IR, round-trip through the validator, and replay deterministically under the test frames before it is ready to merge. diff --git a/nano/loop/__init__.py b/nano/loop/__init__.py index c787942..60acc04 100644 --- a/nano/loop/__init__.py +++ b/nano/loop/__init__.py @@ -1,8 +1,7 @@ -"""Nano++ autonomous optimization loop. +"""Experimental Nano++ loop primitives. -The universal lifecycle (observe -> propose -> compile -> execute -> measure -> -verify -> admit -> repeat) as deterministic, replayable IR. One loop model -across trading, engineering, and quantum optimization workloads. +This package exposes loop-document validation, mutation-admission helpers, and +a deterministic simulator protocol. It does not execute an autonomous loop. """ from .graph import KNOWN_LOOP_EFFECTS, LoopGraph diff --git a/nano/loop/graph.py b/nano/loop/graph.py index aeee5ba..b8a1fc5 100644 --- a/nano/loop/graph.py +++ b/nano/loop/graph.py @@ -1,10 +1,7 @@ -"""LoopGraph — a compiled autonomous optimization loop (Nano++). +"""Validated Nano++ LoopGraph data model. -A LoopGraph is to an optimization *process* what a StrategyGraph is to a trading -rule: a validated, content-addressable, replayable DAG. Trading, engineering, -and quantum-optimization workloads each supply different node payloads over the -same graph. Load-time validation is the security boundary — forward references, -unknown stages, and undeclared capabilities are rejected here, not at runtime. +A LoopGraph serializes, validates, and hashes a proposed loop document. This +module does not compile or execute a loop, perform replay, or deploy changes. """ from __future__ import annotations diff --git a/nano/loop/mutation.py b/nano/loop/mutation.py index 438e524..b7c7373 100644 --- a/nano/loop/mutation.py +++ b/nano/loop/mutation.py @@ -1,17 +1,7 @@ -"""Safe self-mutation — the four-stage admission pipeline (Nano++). +"""Deterministic Nano++ mutation-admission helper. -Autonomous systems that rewrite their own loops must never mutate live. Every -proposed change becomes an engineering artifact that passes four gates in order: - - 1. Proposal — a model proposes an improvement (upstream; a Candidate) - 2. Compilation — the proposal is a deterministic loop artifact - 3. Verification — replay match, benchmark gain, zero regressions, static - analysis, capability validation - 4. Admission — policy, risk, provenance, capability ceiling - -Nothing here deploys. `admit_mutation` returns a decision + (on success) the -admitted artifact for a human/operator to deploy. This mirrors the trading -system's release-gate discipline: components propose, gates decide. +``admit_mutation`` evaluates caller-supplied candidate facts and returns an +admission record. It does not generate, compile, verify, or deploy a mutation. """ from __future__ import annotations diff --git a/nano/loop/nodes.py b/nano/loop/nodes.py index 9d81fad..9ad1ee5 100644 --- a/nano/loop/nodes.py +++ b/nano/loop/nodes.py @@ -1,9 +1,7 @@ -"""Universal loop-stage vocabulary (Nano++). +"""Experimental Nano++ loop-document vocabulary. -Trading uses BUY/SELL intents; an engineering tool proposes design changes; a -quantum engineer runs circuit execution. Underneath, they are the same -lifecycle. These stage kinds are that lifecycle, made into IR nodes so the -optimization *process itself* becomes a deterministic, replayable graph. +These values describe and validate a separate loop data model. They do not +execute stages, invoke reasoning models, or provide autonomous coordination. """ from __future__ import annotations diff --git a/nano/loop/quantum.py b/nano/loop/quantum.py index fbdaebf..d99e816 100644 --- a/nano/loop/quantum.py +++ b/nano/loop/quantum.py @@ -1,31 +1,8 @@ -"""Abstract quantum runtime interface (Nano++). +"""Experimental specialized-compute runtime protocol. -Nano++ introduces a vendor-neutral execution interface for specialized compute backends. - -Nano does not know IBM Quantum, IonQ, Azure Quantum, Rigetti, or D-Wave. - -Nano knows **jobs** -A backend implements the `QuantumRuntime` protocol. The optimization loop submits a portable execution request, receives a structured result, and continues without knowing whether the computation ran on: - -- a deterministic simulator -- a noise model -- a quantum processor -- a future accelerator backend - -Changing hardware means changing the runtime — not rewriting the agent, compiler, or execution graph. - -The reference implementation is `SimulatorRuntime`. - -It is intentionally deterministic: -- no ambient randomness -- no external state -- seed derived from job content -- identical inputs produce identical outputs - -This allows Nano optimization loops to be replayed bit-for-bit during development, testing, and research. - -Real quantum hardware dispatch remains an experimental research direction. -The stable abstraction is the runtime boundary. +The repository ships a deterministic simulator reference implementation. It +does not include a real quantum backend, hardware dispatch, or performance +claim. """ from __future__ import annotations diff --git a/nano/memory/patterns.py b/nano/memory/patterns.py index 38d9d9a..762db61 100644 --- a/nano/memory/patterns.py +++ b/nano/memory/patterns.py @@ -1,14 +1,8 @@ -"""Nano memory layer — the semantic cache of learned behavior. +"""Standalone pattern-retrieval primitive. -Nano is not a replacement for ATS intelligence. It is the intelligence -acceleration layer: compiled patterns answer "have we already solved this type -of problem?" A match supplies context to ATS reasoning — ATS still thinks, it -just starts with knowledge. No match escalates to LLM reasoning. - -Every pattern records: what happened, why, how often, how confident, and when -it should expire. Patterns never execute anything — they inform. Provenance is -mandatory so AQRC-compiled patterns stay distinguishable from hand-authored -ones and can be gated accordingly. +A PatternStore matches caller-provided observations against stored conditions +and returns context plus an ``escalate`` flag. It does not invoke a model and +is not wired into the core compiler, interpreter, or bridge. """ from __future__ import annotations @@ -106,7 +100,7 @@ def retrieve( now: int, min_confidence: float = 0.0, ) -> RetrievalResult: - """Known pattern -> context for ATS reasoning. No match -> escalate.""" + """Known pattern -> context; no match -> an escalation flag for the caller.""" matched = tuple( p for p in self.patterns diff --git a/nano/runtime/effects.py b/nano/runtime/effects.py index 28c546f..f7891f5 100644 --- a/nano/runtime/effects.py +++ b/nano/runtime/effects.py @@ -1,8 +1,7 @@ -"""Intents and the append-only execution log. +"""Intent values and the ordered, in-memory execution log. -Nano never places trades. The runtime's terminal output is a tuple of Intents — -proposals a downstream gate (the host platform's risk engine) may accept or reject. -Components propose; gates decide. +Nano never places trades. The reference runtime returns Intents as proposals +for a downstream host gate to accept or reject, together with per-run events. """ from __future__ import annotations diff --git a/pyproject.toml b/pyproject.toml index 8feb484..52ed3d3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,15 +1,14 @@ [project] name = "aether-nano" version = "0.1.0" -description = "A compiled execution architecture for autonomous engineering systems — compile AI reasoning into deterministic, auditable execution." +description = "A deterministic strategy DSL and reference runtime for host-governed decision rules." readme = "README.md" license = { text = "MIT" } requires-python = ">=3.10" authors = [{ name = "Aether AI LLC" }] keywords = [ - "nano", "aether", "compiler", "deterministic-execution", "autonomous-ai", - "ai-agents", "quantitative-trading", "algorithmic-trading", "llm", - "execution-engine", "provenance", "dsl", + "nano", "aether", "compiler", "deterministic-execution", "dsl", + "quantitative-trading", "algorithmic-trading", "execution-engine", "provenance", ] classifiers = [ "Development Status :: 3 - Alpha", @@ -28,10 +27,10 @@ dependencies = [] Homepage = "https://aethersystems.net" "Aether Code (web IDE)" = "https://app.aethersystems.net/code" Repository = "https://github.com/DBarr3/Nano" -Documentation = "https://github.com/DBarr3/Nano/tree/main/docs/papers" +Documentation = "https://github.com/DBarr3/Nano/tree/main/docs" [project.optional-dependencies] -# Signed, non-repudiable audit receipts over risk-gate decisions. +# Signed, non-repudiable audit receipts over decision-gate records. # See nano/bridge/provenance.py. provenance = ["aether-protocol-c"] dev = ["pytest>=7"] @@ -45,3 +44,13 @@ build-backend = "setuptools.build_meta" [tool.setuptools.packages.find] include = ["nano*"] + +# The source/IR conformance and strategy corpora live alongside the package. +# Ship them deliberately so installed distributions retain the documented assets. +[tool.setuptools.package-data] +nano = [ + "examples/*.nano", + "examples/*.json", + "library/*/*.nano", + "library/*/*.json", +] diff --git a/tests/test_readme_example.py b/tests/test_readme_example.py new file mode 100644 index 0000000..dde0867 --- /dev/null +++ b/tests/test_readme_example.py @@ -0,0 +1,36 @@ +"""Regression coverage for the marked Nano example in the repository README.""" + +from pathlib import Path +import re + +from nano.compiler import compile_source + + +_ROOT = Path(__file__).resolve().parents[1] +_START = "" +_END = "" + + +def _readme_example() -> str: + text = (_ROOT / "README.md").read_text(encoding="utf-8") + match = re.search( + rf"{re.escape(_START)}\s*```nano\s*\n(?P.*?)\n```\s*{re.escape(_END)}", + text, + re.DOTALL, + ) + assert match is not None, "README must contain a marked Nano example" + return match.group("source") + + +def test_readme_nano_example_compiles_to_the_documented_strategy() -> None: + graph = compile_source(_readme_example()) + + assert graph.name == "Momentum" + assert graph.schedule is not None + assert graph.schedule.interval == "5m" + assert [(condition.signal, condition.operator, condition.value) for condition in graph.conditions] == [ + ("RSI", "<", 30) + ] + assert [intent.to_dict() for intent in graph.intents] == [ + {"type": "Intent", "action": "BUY", "asset": "BTC", "confidence": 0.91} + ]