Prime Language
Technical Specification
Prime is a statically typed, object-oriented language for business logic that applications let people and models add safely: reports, rules and handlers. Prime compiles to compact stack bytecode executed by PrimeVM, a sandboxed virtual machine written in Rust that runs natively and as WebAssembly. Its longer-term design adds probabilistic types, first-class tensors and model inference to the language; this specification marks which parts are implemented today and which are proposals.
Status of this Specification
Version 0.2 revises the v0.1 draft against the compiler and VM in the Prime repository, which are the source of truth. Every section and feature carries one of these labels:
| Label | Meaning |
|---|---|
| Implemented | In the compiler and VM today; examples so marked compile with the current toolchain. |
| Partial | Part of the described behaviour exists; the text says which part. |
| Proposed v0.2 | A planned addition for the next implementation steps. Not available yet. |
| Roadmap | Longer-term design. Not implemented; its keywords are reserved and rejected by the compiler (E0003). Examples are illustrative and do not compile. |
The normative description of the implemented language is
Prime Core v0.2; you can run it in
the playground. Passing tests show that the tested cases behave as
asserted, not that a program is correct in general.
0.1 Implementation Matrix
| Area | Status | Notes |
|---|---|---|
Classes, modules, pub/priv, static and instance methods | Implemented | No inheritance, interfaces or prot. |
Types: int float string boolean date datetime duration, list, map, T?, var | Implemented | No byte, no user generics. |
Statements, queries (select … from), print, ++/-- | Implemented | Queries need a host data source. |
Bytecode VM: PrimeVM 0.2 (stack, .primevm v3, default) and PrimeVM 0.1 (register, v2); interpreter, native and WebAssembly | Implemented | Same results on both; no JIT, no GPU. |
| Sandbox limits: instructions, memory, call depth, time, output | Implemented | Memory is approximate; reference cycles are not freed. |
| Host modules (JSON), report profile, wasm ABI, browser runtime | Implemented | Data sources are not available in browsers. |
| Tests, fixtures, admission rule | Implemented | @MockInfer and AI assertions are roadmap. |
| Machine-readable diagnostics | Implemented | Flat format of §5.2; the v0.1 envelope is withdrawn. |
| Agent code mode | Partial | Run protocol exists; grant, MCP mapping, host descriptions are proposed. |
| Grammar export for constrained decoding; verified training data | Proposed v0.2 | No grammar artefact or sample tooling yet. |
std.tensors: Tensor on the CPU (matmul, transpose, element-wise, reductions) | Implemented | Shapes checked at run time; §2.3. |
| GPU (CUDA) backend for tensors | Proposed v0.2 | See §10. No GPU code exists. |
tensor<T, …>, infer(), prob<T> | Roadmap | Reserved words; §2.2, §2.3, §3. |
qstate and the quantum API | Roadmap | §4. |
Concurrency (async, threads, channels) | Roadmap | The VM is single-threaded and synchronous. |
0.2 Current Use and Future GPU Work
Prime's first embedding is the report engine of NaviSpy Monitor: its backend runs PrimeVM through the WebAssembly ABI on the CPU, with reports ported from a previous implementation and their outputs compared case by case. That embedding uses no tensors, inference or GPU. GPU acceleration (§10) is a proposal and is not used by any Prime program today.
Language Architecture Overview
1.1 Design Philosophy Partial
Prime is built on the conviction that the next generation of general-purpose languages must treat AI inference and quantum computation as first-class language concerns — not as external library calls made over opaque APIs. In the same way that Go made concurrency a core language primitive (goroutines, channels) and Rust made memory safety a compile-time guarantee (ownership, lifetimes), Prime makes probabilistic reasoning and linear resource management structural properties of the type system itself.
Three structural pillars define Prime:
-
Object-Oriented Familiarity. Implemented
Prime adopts a Java-inspired class and module system: classes with fields and
methods, one module per file, imports, and
pub/privaccess checked by the compiler. Inheritance, interfaces and aprotmodifier are not part of the language yet. -
Roadmap
Probabilistic Type Integration. The
prob<T>wrapper elevates uncertainty into the type system. The compiler tracks confidence at every inference boundary and enforces explicit handling of low-confidence branches — making probabilistic programs as rigorous as deterministic ones. -
Roadmap
Quantum Readiness via Linear Types. The
qstatemodifier subjects a variable to the compiler's linear-type borrow checker, enforcing the No-Cloning Theorem at compile time. When Prime targets quantum hardware or a simulator, these invariants are already guaranteed — no runtime assertion required.
Today Prime is a sandboxed language for application logic — reports, rules, handlers — that runs inside a host application with explicit capabilities, limits and tests. It has no file, network or process access of its own. Wider general-purpose use and the AI and quantum pillars above are design goals, not current capabilities.
1.2 Compilation Pipeline Implemented
| Stage | Artifact | Responsibility |
|---|---|---|
prime-syntax — lexer, parser |
AST | Hand-written recursive-descent parser; reports every syntax error as a structured diagnostic (§5.2). |
prime-check — resolver, type checker |
Typed program | Resolves modules, classes and host modules; checks types, optionals, access and annotations. |
prime-vm — compiler |
.primevm module |
Emits stack bytecode for PrimeVM 0.2 (§1.3), or register bytecode for PrimeVM 0.1 with --vm 0.1; prime build writes it to a file. |
prime-vm — PrimeVM |
Result, output, diagnostics | Interprets the bytecode within the sandbox limits; calls the host for host functions and data sources. Built natively and as WebAssembly (prime-wasm). |
The command-line tool is prime (check, parse,
build, run, test, disasm). There are
no AI, tensor or quantum instructions; v0.1's INFER, QGATE and
TMUL opcodes do not exist.
1.3 Stack-Based Bytecode Implemented
PrimeVM 0.2 is a stack machine. Instructions take their operands from
the operand stack and push their result: ADD pops two values and pushes
one. Immediate operands are only constants, local slots, functions, host imports and
jump targets, so most instructions are a single byte and the bytecode reads like
assembler. A frame is its local slots — parameters first — followed by its operand
stack; arguments are pushed by the caller and become the callee's first locals without
copying, and RET replaces them with the result.
static int square(int x) { return x * x; } pub static void main() { int a = 3; int b = 4; int c = square(a) + square(b) * 2; print(c); }
; prime disasm — square: params 1, locals 1 LOAD 0 ; x LOAD 0 MUL RET RETV ; end of body (unreachable here) ; main: params 0, locals 3 PUSHK k0 ; 3 STORE 0 ; a PUSHK k1 ; 4 STORE 1 ; b LOAD 0 CALL f0, 1 ; square(a) LOAD 1 CALL f0, 1 ; square(b) PUSHK k2 ; 2 MUL ADD STORE 2 ; c LOAD 2 PRINT RETV
Instructions are encoded as one opcode byte followed by LEB128 operands. The stack holds tagged values: the checker proves types at compile time and the VM still checks operand types, overflow and division by zero at run time.
PrimeVM 0.1, the register machine of the first release, is kept and
selectable (prime … --vm 0.1, the playground's combo box): every
instruction names its registers (ADD r2, r2, r4), and arguments are copied
into the callee's registers. Both machines run the same language with identical results.
Over the bundled examples the stack code is 32% smaller (1.9 against 3.3 bytes per
instruction) and has 18% more instructions; programs execute 2–39% more instructions on
the stack machine. Details: Prime Core v0.2 §13.
1.4 Module System Implemented
Each .prime file declares exactly one module at its head, followed by its
imports. A project is resolved and checked as a whole, so modules may import each
other. Modules are the unit of access control: priv members are visible
only inside their module. std.* modules are built into PrimeVM
(core, math, text, time,
collections, assert); other imports are host modules supplied
by the embedding application. There is no std.io.
module weather.reports.daily_rainfall; import std.math; import std.time; import demo.weather; // a host module
1.5 Comparison with Go and Rust
| Feature | Go | Rust | Prime |
|---|---|---|---|
| Memory management | Tracing GC | Ownership / borrow checker | Reference counting in the VM; cycles are not yet freed |
| Sandboxing | None | None | No I/O of its own; host capabilities; instruction, memory, depth and time limits |
| Concurrency model | Goroutines + channels | async/await + Send/Sync | None (single-threaded VM); roadmap |
| Probabilistic types | None (library only) | None (library only) | Roadmap: prob<T> |
| Tensor math | None (library only) | None (library only) | Proposed host module (§10); roadmap: tensor<T, Dims> |
| AI inference | External call | External call | Roadmap: infer() via a host inference module |
| Quantum safety | None | None | Roadmap: linear qstate |
| Compilation target | Native binary | Native binary / WASM | Stack bytecode (.primevm) for PrimeVM, which runs natively and as WebAssembly |
Type System & Primitives
2.1 Implemented Types Implemented
| Type | Representation | Default | Run-time behaviour |
|---|---|---|---|
int | 64-bit signed | 0 | Overflow stops the run with E0402 (checked at run time, not at compile time). |
float | 64-bit IEEE 754 | 0.0 | Never NaN or infinite: division by zero is E0401, invalid operations such as Math.sqrt(-1.0) are E0407. |
string | Immutable UTF-8, shared by reference | "" | == compares values. Not interned. |
boolean | — | false | Only true and false; no truthiness. |
date, datetime, duration | Days, seconds, milliseconds | — | Literals d"2026-11-13", dt"…T10:00:00", 30m; arithmetic between them is typed. |
list<T>, map<K, V> | Reference values | — | Index errors stop the run (E0404); maps keep insertion order. |
T? | Optional | null | Must be checked (!= null narrows) or defaulted (?:) before use — a compiler guarantee. |
| classes | Reference values | — | new C(field: value); reference-counted. |
void | — | — | Return type only. |
byte, user-defined generics and function types are not part of the
language. Full rules: Prime Core v0.2 §4.
int customerId = 481923; float riskScore = 0.74; string policyRef = "POL-2024-EU-00391"; boolean isEligible = true; date due = d"2026-12-31"; duration slack = 2h + 30m; float? discount = null; float applied = discount ?: 0.0;
2.2 Probabilistic Types — prob<T> Roadmap
prob<T> and confidence propagation do not exist yet. The words prob and confidence are reserved: the compiler rejects them with E0003.
Code in this section is illustrative and does not compile; error codes shown in it are
placeholders, not entries of the implemented code table.
A confidence value produced by a model is a score from that model, not a calibrated probability; the rules below describe how the compiler would track it, not how reliable it is.
prob<T> wraps any type T together with a
compiler-managed confidence scalar in the range [0.0, 1.0].
Confidence is a type-level annotation — not a runtime field — that the compiler
propagates through the dataflow graph and exposes as a read-only property.
Declaration Syntax
prob<T> identifier = value confidence float_literal ;
Compiler Rules
- The
confidenceclause is mandatory on any direct literal assignment to aprob<T>variable. - When a
prob<T>is produced by aninfer()expression, confidence is populated from the model's softmax output — no explicit clause is written. - Confidence propagates through arithmetic: for binary operations
a op b, the result confidence ismin(a.confidence, b.confidence)(conservative model). - Assigning a
prob<T>to a bareTvariable is a compile-time error unless guarded by aconfidence >= thresholdgate.
Example
// Direct construction prob<string> tradingIntent = "BUY" confidence 0.94; // Accessing properties float c = tradingIntent.confidence; // 0.94 string v = tradingIntent.value; // "BUY" // Confidence-gated unwrap — required before assigning to classical type if (tradingIntent.confidence >= 0.90) { string confirmed = tradingIntent.value; executeOrder(confirmed); } else { flagForReview(tradingIntent); }
2.3 Tensors — std.tensors Implemented
The standard library module std.tensors provides Tensor: a dense,
immutable tensor of float with 1–8 dimensions, computed on the CPU in both
PrimeVM 0.2 and 0.1 and in the playground. Operations return new tensors; shapes are
checked when an operation runs, and a mismatch is a runtime error naming both shapes
(add: shapes [2, 3] and [3, 2] differ). Sizes are capped (about one million
elements per tensor, ten million multiply-adds per matmul) because a built-in
cannot be interrupted by the instruction limit.
// Tensors (std.tensors): matrices on the CPU, and a tiny neural network. module sandbox.tensors; import std.math; import std.tensors; pub class Main { pub static void main() { Tensor a = Tensor.matrix([[1.0, 2.0], [3.0, 4.0]]); Tensor b = Tensor.matrix([[0.5, 0.0], [0.0, 2.0]]); print("a + b = " + string(a.add(b))); print("a × b = " + string(a.matmul(b))); print("transpose = " + string(a.transpose())); print("sum, mean = " + string(a.sum()) + ", " + string(a.mean())); // A 2-3-1 network: input × weights, ReLU, × output weights. Tensor input = Tensor.matrix([[1.0, 0.5]]); Tensor w1 = Tensor.matrix([[0.2, -0.5, 1.0], [0.7, 0.1, -0.3]]); Tensor w2 = Tensor.matrix([[1.0], [-1.0], [0.5]]); Tensor hidden = input.matmul(w1).relu(); print("hidden = " + string(hidden)); print("output = " + string(Math.round(hidden.matmul(w2).get(0, 0), 4))); } }
Methods: Tensor.of, vector, matrix,
zeros, fill, identity; shape,
rank, size, get, toList;
add, sub, mul, scale,
abs, relu, matmul, transpose,
dot, reshape, sum, mean,
min, max (Prime Core v0.2 §10).
2.4 Tensor Types — tensor<T, Dims...> Roadmap
tensor are reserved: the compiler rejects them with E0003.
Code in this section is illustrative and does not compile; error codes shown in it are
placeholders, not entries of the implemented code table.
Tensor types are native to Prime's type system. Shape is encoded in the type signature and checked at compile time — mismatched shapes cause a type error, not a runtime panic. No external library is required.
Syntax
tensor<float, 2, 3> // 2×3 matrix of float64 tensor<int, 4> // 1-D vector of 4 int64 tensor<float, 3, 3, 3> // 3-D tensor
Native Operators
| Operator | Operation | Shape Constraint |
|---|---|---|
+ | Element-wise addition | Identical shape required. |
- | Element-wise subtraction | Identical shape required. |
* | Matrix multiplication | tensor<T,M,N> * tensor<T,N,P> → tensor<T,M,P> |
@ | Hadamard (element-wise) product | Identical shape required. |
.T | Transpose | tensor<T,M,N>.T → tensor<T,N,M> |
tensor<float, 2, 3> featureMatrix = [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ]; tensor<float, 3, 2> projection = [ [1.0, 0.0], [0.0, 1.0], [0.5, 0.5] ]; // (2×3) * (3×2) → (2×2) — shape verified at compile time tensor<float, 2, 2> reduced = featureMatrix * projection; tensor<float, 3, 2> transposed = featureMatrix.T;
featureMatrix * featureMatrix (both 2×3) emits:
"E0051: matrix multiplication requires inner dimensions to match: got 3 ≠ 2."
No shape mismatch can reach runtime.
Native AI Keywords & Dispatch
RoadmapNo model integration exists in PrimeVM today.
infer() and its clauses do not exist yet. The words infer, classifying and as are reserved: the compiler rejects them with E0003.
Code in this section is illustrative and does not compile; error codes shown in it are
placeholders, not entries of the implemented code table.
3.1 The infer() Operator
infer() is a first-class language keyword — not a library call — that
suspends the executing coroutine, serialises input into PrimeVM's inference protocol,
dispatches to the local 0.3B model, and deserialises the result into a
prob<T> value. The confidence scalar comes from the model's
post-softmax probability for the top-1 token class.
Syntax Forms
// Form 1 — open-ended generation prob<string> result = infer(inputExpr); // Form 2 — constrained classification prob<string> label = infer(inputExpr) classifying ["LabelA", "LabelB", "LabelC"]; // Form 3 — typed generation with schema hint prob<float> score = infer(inputExpr) as float;
Lowering Proposed
PrimeVM has no inference instructions. The proposed
lowering adds none: infer() compiles to an ordinary host call of an
inference module that the application grants, so permissions, limits and errors work as
for any host function. The call is synchronous from Prime's point of view; the VM has no
coroutines.
; prob<string> label = infer(text) classifying ["A", "B"]; (proposed, PrimeVM 0.2) LOAD 0 ; text NEWLIST ; labels: then DUP, PUSHK, CALLB list.add per label CALLH h0, 2 ; h0 = inference.classify(text, labels) → host object STORE 1 ; label
3.2 Enterprise Classification Example
Document triage pipeline for a regulatory compliance platform. Incoming case narratives are classified into three disposition categories; low-confidence results are routed to human review.
module com.example.compliance.triage; pub class CaseTriage { pub static string triageCase(string narrative, int caseId) { prob<string> classification = infer(narrative) classifying ["APPROVE", "ESCALATE", "REJECT"]; if (classification.confidence >= 0.92) { auditLog(caseId, classification.value, classification.confidence); return classification.value; } if (classification.confidence >= 0.70) { string enriched = "[REVIEW CONTEXT] " + narrative; prob<string> refined = infer(enriched) classifying ["APPROVE", "ESCALATE", "REJECT"]; if (refined.confidence >= 0.85) { auditLog(caseId, refined.value, refined.confidence); return refined.value; } } ReviewQueue.enqueue(caseId, classification.confidence); return "PENDING_REVIEW"; } priv static void auditLog(int id, string disposition, float conf) { AuditStore.write(id, disposition, conf, Timestamp.now()); } }
classifying clause enables logit masking (see §5.1). PrimeVM passes
the label set to the inference subsystem, so the model can only emit tokens that
prefix one of the declared labels. Hallucinated output categories are impossible at
the VM level.
Quantum-Ready System — Linear Types
RoadmapLong-term research direction; no quantum types, linear checking or quantum API exist.
Quantum API do not exist yet. The words qstate are reserved: the compiler rejects them with E0003.
Code in this section is illustrative and does not compile; error codes shown in it are
placeholders, not entries of the implemented code table.
4.1 The qstate Modifier
A variable declared with qstate enters the compiler's
linear-type borrow checker. Linear types guarantee a value is consumed
exactly once — it cannot be copied, aliased, or read after being passed to a gate
function. This directly encodes the No-Cloning Theorem: an arbitrary
unknown quantum state cannot be duplicated.
Compiler Rules
- A
qstatevariable may appear as an argument to a gate function at most once after its declaration. - Any gate function accepting a
qstateparameter consumes it. Subsequent references are compile-time errors. qstatevariables may not be captured by closures or assigned to non-qstatebindings.Quantum.measure()collapses aqstateregister into a classicalboolean. This is a consuming operation.
4.2 Quantum Gate API
| Method | Input | Output | Description |
|---|---|---|---|
Quantum.register(n) | int | qstate | Allocates an n-qubit register in |0⟩. |
Quantum.applyHadamard(q) | qstate (consumed) | qstate | Hadamard gate; puts qubit into superposition. |
Quantum.applyCNOT(ctrl, tgt) | two qstates (consumed) | qstate | Controlled-NOT; entangles two qubits. |
Quantum.applyPhase(q, theta) | qstate (consumed), float | qstate | Phase rotation by θ radians. |
Quantum.measure(q) | qstate (consumed) | boolean | Collapses state; returns classical measurement. |
4.3 Hybrid Quantum–Classical Example
module com.example.quantum.demo; pub class QuantumDecisionGate { pub static string evaluatePath(string workflowId) { // Allocate a 2-qubit register — both qubits in |0⟩ qstate reg = Quantum.register(2); // Hadamard — reg is consumed, q1 produced qstate q1 = Quantum.applyHadamard(reg); // Split into single-qubit handles — q1 consumed on first .qubit() call qstate ctrl = q1.qubit(0); qstate tgt = q1.qubit(1); // Entangle — ctrl and tgt consumed, entangled pair produced qstate entangled = Quantum.applyCNOT(ctrl, tgt); // Measure — collapses to classical boolean; entangled is consumed boolean outcome = Quantum.measure(entangled.qubit(0)); // Classical branching on quantum measurement result if (outcome) { WorkflowEngine.route(workflowId, "PATH_ALPHA"); return "PATH_ALPHA"; } else { WorkflowEngine.route(workflowId, "PATH_BETA"); return "PATH_BETA"; } } }
qstate reg = Quantum.register(1); qstate a = Quantum.applyHadamard(reg); qstate b = Quantum.applyHadamard(reg); // E0041 — reg already consumed
E0041: use of moved qstate variable 'reg' at line 3.
Linear type constraint: qstate may only be consumed once.
AI-Assisted Authoring
Prime is designed to be written by models as well as by people. A strict grammar, a type checker, native tests and a sandboxed VM make every piece of machine-written code checkable: it either compiles, passes its tests and runs within its limits, or it is rejected with a structured reason. Four mechanisms build on that: constrained decoding (§5.1) keeps generated code valid, the error loop (§5.2) lets a model repair it, verified training data (§5.3) teaches a model to write Prime, and code mode (§5.4) lets agents act through Prime programs instead of individual tool calls.
Prime standardizes the interfaces — what valid code is, how it is checked, what a verified example looks like, how an agent submits code — not the models or the training methods behind them. Prompt formats, tokenizers and fill-in-the-middle tokens belong to the model and its tooling and are not part of the language.
5.1 Grammar-Constrained Decoding Proposed v0.2
A decoder can mask, at each step, the tokens that cannot continue a valid program, so a
model cannot emit syntax from other languages (def, fn,
lambda). Prime's grammar is context-free and small enough for this, but the
implementation does not ship a grammar artefact yet: the parser is hand-written
(recursive descent), and there is no prime.cfg.
Proposed for v0.2: a prime grammar command that exports the grammar of §7 in
a format decoders accept (for example GBNF), versioned with the compiler. A grammar
alone cannot exclude unknown API names or ill-typed expressions — those depend on the
host modules and types in scope. They are caught by the checker, whose diagnostics feed
the loop of §5.2; type-aware decoding is a later research item.
5.2 Compiler / VM Error Feedback Loop Implemented
Every compile, test and runtime error is a JSON object with a stable code and a 1-based
position (prime check --json, prime test --json, and the
errors/error fields of the WebAssembly ABI). hint
is present only when the compiler has a repair suggestion. The v0.1 envelope
(prime_error, schema_version, stage,
fatal) was never implemented and is withdrawn.
Diagnostic Object
{
"phase": "lex | parse | resolve | type | test | runtime | limit",
"code": "E0301", // stable; see Prime Core Appendix A
"file": "string",
"line": 3, // 1-based
"column": 29, // 1-based
"message": "string",
"hint": "string" // optional
}
Concrete Error Example
{"phase":"type","code":"E0301","file":"wet_days.prime","line":7,"column":16,
"message":"expected string, found int","hint":"convert with string(x)"}
Proposed v0.2 end positions (end_line,
end_column) for precise repairs.
Self-Correction Loop Protocol Proposed
The diagnostics above exist; the loop itself is tooling around them, not yet built.
- The model generates a candidate: a whole file, or the code between a given prefix and suffix.
- PrimeVM checks the assembled source and runs its tests. On success, the code is presented to the developer or agent.
- On failure, the JSON error document is passed back with the original context and the model generates a correction. After at most 3 iterations the error is shown to the developer.
- Every attempt is logged; failed attempts with their corrections become repair samples (§5.3).
5.3 Verified Training Data Proposed v0.2
Nothing in this subsection is implemented; prime check --json and prime test --json are the building blocks it would use.
A model learns to write Prime from examples, and Prime can prove an example correct. The toolchain therefore defines one sample format and one verification pipeline that every Prime training set uses, whether it comes from human code, generated code or the correction log of §5.2. Training itself — pretraining, supervised fine-tuning, reinforcement learning — runs in standard ML frameworks outside Prime; this section fixes only what goes in and how it is checked.
| Sample kind | Content | Teaches |
|---|---|---|
verified | Task, accepted source, its tests | Writing correct Prime from a request (SFT) |
repair | Failing source, its diagnostics, corrected source | Fixing code from compiler and test errors |
completion | Prefix, suffix and the accepted middle | Editor completion; the trainer chooses the token format |
Sample Record (JSON Lines, one sample per line)
{
"schema": "prime-sample/1",
"kind": "verified | repair | completion",
"task": "string", // natural-language request, may be empty
"hosts": ["demo.weather"], // host modules the code may use
"source": "string", // accepted Prime source (the target)
"broken": "string | null", // repair: the failing source
"diagnostics": [ ... ], // repair: §5.2 errors of "broken"
"prefix": "string | null", // completion: code before the gap
"suffix": "string | null", // completion: code after the gap
"verification": {
"compiler": "prime 0.1.0",
"fingerprint": "sha256 of the sources",
"tests_passed": 6,
"tests_failed": 0,
"admitted": true,
"instructions": 18342
}
}
Verification Pipeline
- Check —
prime checkwith the declared host modules. Samples that do not parse or type-check are kept only as thebrokenside of a repair sample. - Test —
prime testruns the sample's tests in the sandbox with fixture data; averifiedsample needs at least one test and no failures. - Admit — the admission rule of §6 must accept every report in the sample.
- Deduplicate — samples with the same compiled fingerprint are stored once.
- Record — the compiler version and results are written into
verification, so a set can be re-verified when the compiler changes.
Reward for Reinforcement Learning
The same pipeline scores a model's output, so reinforcement learning needs no learned reward model. A candidate is checked and then run against tests the model cannot see or change:
| Outcome | Reward |
|---|---|
| Does not parse | 0.0 |
| Parses, fails type checking | 0.1 |
| Type-checks; p of n hidden tests pass | 0.2 + 0.6 × p / n |
| All hidden tests pass and admitted | 1.0 |
5.4 Prime for Agents (Code Mode) Partial
Implemented: host modules, the run protocol below and its limits. Proposed: host descriptions, MCP mapping, run logging.
An agent that needs several tool calls to answer a request can instead write one Prime program that makes those calls, and submit it to PrimeVM. The program is type-checked against the tools it may use, runs under a fixed budget, and returns one result or one structured error. Tools are host modules: the host declares their functions and types, and a program can call nothing else.
// Written by an agent for the request: // "On which days of this period did it rain more than 20 mm at the station?" module agent.wet_days; import std.math; import demo.weather; @Report(id = "agent_wet_days", title = "Days over 20 mm", mobile = false) pub class WetDays { const float LIMIT_MM = 20.0; pub static void run(ReportContext ctx) { int days = 0; for (date day : ctx.period.days()) { float mm = rainfall(ctx.station, day); if (mm > LIMIT_MM) { ctx.out.row(day, metric("rainfall", Math.round(mm, 1), Unit.MM)); days += 1; } } ctx.out.total(metric("days_over_limit", days, Unit.NONE)); } }
Tools as Host Modules
Host modules are declared in JSON (as hosts/demo.weather.json)
Implemented. The mapping from Model Context Protocol
(MCP) tools onto host functions below is Proposed; so is
the description field — today's declaration format rejects unknown fields,
including description.
| MCP tool | Prime host function |
|---|---|
name | function name in a host module (one module per MCP server) |
description | description, shown to the model with the declaration |
inputSchema properties | typed parameters: string, integer → int, number → float, boolean, array → list<T>, object → a declared host class |
| result content | return type, decoded and type-checked at the call |
| tool error | runtime error E0405 at the calling line |
Run Protocol Implemented
The WebAssembly ABI (prime-wasm, Prime Core §18.2) compiles a project and
runs one entry point. The host modules passed to prime_load are the run's
capabilities: code that uses anything else does not compile.
// prime_load: compile, and optionally run the project's tests
{ "sources": [{ "name": "wet_days.prime", "text": "..." }],
"hosts": ["<host declaration JSON>"],
"fixtures": {}, "test": true }
→ { "ok": true, "errors": [], "reports": [...], "imports": [...], "main": null,
"tests": [...], "admission": [...] }
// prime_run: a report (with a context object from the host) or any function
{ "report": "agent_wet_days", "context": 7,
"fuel": 20000000, "memory": 67108864, "timeout_ms": 5000 }
{ "function": "agent.wet_days.Main.main", "args": [] }
→ { "ok": true, "value": null, "output": ["..."], "instructions": 18342 }
→ { "ok": false, "error": { "phase": "limit", "code": "E0501", ... }, "output": [...] }
Proposed an agent-facing wrapper with an explicit
grant list and a single result field.
| Guarantee | How PrimeVM enforces it | Status |
|---|---|---|
| Capability | Only the host modules passed to the run type-check; the language has no other I/O. | Implemented |
| Budget | Instruction, memory, call-depth and time limits per run (E0501–E0504); memory is approximate. | Implemented |
| Determinism | The standard library reads no clock or randomness and maps keep insertion order; results still depend on the data the host returns. | Implemented |
| Repairability | Every failure is a §5.2 diagnostic with a position. | Implemented |
| Audit | Compiled modules carry a fingerprint of their sources; logging runs is up to the host. | Partial |
Native Test Framework
6.1 Annotations Implemented
| Annotation | Target | Behaviour | Status |
|---|---|---|---|
@TestSpecification | Class | Marks a test class. Each test runs on a fresh object in a fresh VM (statics reset). | Implemented |
@Test, @Test(timeout = n) | Method | A test case: pub void, no parameters. Default timeout 2 000 ms (E0504). | Implemented |
@Fixture(source, file) | Method | Supplies host data for the test from a JSON file next to the test (no database or network in tests). | Implemented |
@MockInfer(label, conf) | Method | Fixed result for infer() calls. Rejected today as an unknown annotation (E0207). | Roadmap |
6.2 Assertion API
| Method | Description | Status |
|---|---|---|
Assert.equals(expected, actual) | Fails if the values differ. | Implemented |
Assert.isTrue(c), Assert.isFalse(c) | Fails on the other boolean. | Implemented |
Assert.isNull(v) | Fails unless v is null. | Implemented |
Assert.near(expected, actual, epsilon) | Numbers within epsilon. | Implemented |
Assert.notEquals(a, b) | Fails if equal. | Proposed |
Assert.confidenceAbove, Assert.tensorEquals | For prob and tensor values. | Roadmap |
Assert.throws(ErrorType, lambda) | Needs exceptions and lambdas, which Prime does not have. | Roadmap |
Assert is usable only inside test classes — a compiler guarantee.
6.3 Admission Rule Implemented
prime test and the WebAssembly prime_load run all tests and
decide, per report: a report is admitted only if its folder has at least one
test and every test in that folder passes. The embedding application loads only
admitted reports, so a failing new version never replaces a working one. Prime scripts
cannot modify data, so there is nothing to roll back after a test.
Admission shows that the tested cases behave as asserted under their fixtures. It does not prove that a program is correct for inputs the tests do not cover.
6.4 Concrete Test Suite Implemented
From examples/daily_rainfall_test.prime; it passes with prime test --host hosts/demo.weather.json examples/.
module weather.reports.daily_rainfall_test; import std.assert; import demo.weather; @TestSpecification pub class DailyRainfallTests { @Test(timeout = 500) @Fixture(source = "rainfall", file = "fixtures/rainfall_2026-10-29.json") pub void oneRowPerDayAndRoundedTotal() { ReportResult r = Reports.run("daily_rainfall", station: 1, from: d"2026-10-29", to: d"2026-10-31"); Assert.equals(3, r.rowCount()); Assert.equals("2026-10-29", r.label(0)); Assert.near(12.35, r.value(0, "rainfall"), 0.001); Assert.near(112.35, r.total("rainfall_total"), 0.001); } @Test @Fixture(source = "rainfall", file = "fixtures/rainfall_2026-10-29.json") pub void negativeRainfallCountsAsZero() { ReportResult r = Reports.run("daily_rainfall", station: 1, from: d"2026-10-30", to: d"2026-10-30"); Assert.near(0.0, r.value(0, "rainfall"), 0.0); Assert.near(0.0, r.total("rainfall_total"), 0.0); } @Test @Fixture(source = "rainfall", file = "fixtures/rainfall_2026-10-29.json") pub void daysWithoutDataUseTheDefault() { ReportResult r = Reports.run("daily_rainfall", station: 2, from: d"2026-10-01", to: d"2026-10-31"); Assert.equals(31, r.rowCount()); Assert.near(0.0, r.total("rainfall_total"), 0.0); } }
6.5 Illustrative AI Test Suite Roadmap
The v0.1 example below uses @MockInfer and tensors; it does not compile today.
module com.example.compliance.triage.tests; @TestSpecification pub class CaseTriageTests { @Test @MockInfer(label = "APPROVE", conf = 0.97) pub void highConfidenceApproveTakesDirectPath() { string result = CaseTriage.triageCase("Customer meets all KYC criteria.", 1001); Assert.equals("APPROVE", result); } @Test @MockInfer(label = "REJECT", conf = 0.95) pub void highConfidenceRejectIsLogged() { string result = CaseTriage.triageCase("Sanctioned entity match detected.", 1002); Assert.equals("REJECT", result); Assert.isTrue(AuditStore.contains(1002)); } @Test @MockInfer(label = "ESCALATE", conf = 0.55) pub void lowConfidenceRoutesToReviewQueue() { string result = CaseTriage.triageCase("Ambiguous counterparty relationship.", 1003); Assert.equals("PENDING_REVIEW", result); Assert.isTrue(ReviewQueue.contains(1003)); } @Test pub void tensorRiskScoreIsCorrect() { tensor<float, 2, 2> a = [[1.0, 2.0], [3.0, 4.0]]; tensor<float, 2, 2> b = [[0.5, 0.5], [0.5, 0.5]]; tensor<float, 2, 2> product = a * b; tensor<float, 2, 2> expected = [[1.5, 1.5], [3.5, 3.5]]; Assert.tensorEquals(expected, product, 0.0001); } @Test(timeout = 500) @MockInfer(label = "APPROVE", conf = 0.99) pub void triageCompletesWithinSLA() { string result = CaseTriage.triageCase("SLA stress test narrative.", 9999); Assert.equals("APPROVE", result); } }
EBNF Grammar
Notation: [ X ] optional, { X } zero or more,
( X | Y ) alternation, terminals in quotes. The first block is
Implemented: it describes what the hand-written parser
(crates/prime-syntax) accepts. Lexical details — comments, string escapes,
number formats such as 1_000 and 0x1F — are in
Prime Core v0.2 §3. v0.1's grammar fragment
(with prot, byte and the quantum productions) is replaced.
(* Prime Core v0.2 — the language the parser accepts *)
file = module_decl { import_decl } { class_decl } ;
module_decl = "module" qualified_name ";" ;
import_decl = "import" qualified_name ";" ;
qualified_name = identifier { "." identifier } ;
class_decl = { annotation } [ visibility ] "class" identifier "{" { member } "}" ;
visibility = "pub" | "priv" ; (* default: priv *)
member = { annotation } [ visibility ] [ "static" ]
( "const" type identifier "=" expr ";"
| type identifier [ "=" expr ] ";" (* field *)
| ( type | "void" ) identifier "(" [ param { "," param } ] ")" block ) ;
param = type identifier ;
annotation = "@" identifier [ "(" [ identifier "=" literal { "," identifier "=" literal } ] ")" ] ;
type = base_type [ "?" ] ;
base_type = "int" | "float" | "string" | "boolean" | "date" | "datetime" | "duration"
| "list" "<" type ">" | "map" "<" type "," type ">" | qualified_name ;
block = "{" { statement } "}" ;
statement = block | simple ";" | if_stmt | while_stmt | for_stmt | foreach_stmt
| "break" ";" | "continue" ";" | "return" [ expr ] ";" ;
simple = ( type | "var" ) identifier "=" expr
| target ( "=" | "+=" | "-=" | "*=" | "/=" | "%=" ) expr
| target ( "++" | "--" ) | ( "++" | "--" ) target
| expr ; (* a call *)
target = identifier | postfix "." identifier | postfix "[" expr "]" ;
if_stmt = "if" "(" expr ")" block [ "else" ( if_stmt | block ) ] ;
while_stmt = "while" "(" expr ")" block ;
for_stmt = "for" "(" [ simple ] ";" [ expr ] ";" [ simple ] ")" block ;
foreach_stmt = "for" "(" ( type | "var" ) identifier ":" ( expr | select ) ")" block ;
select = "select" "from" postfix [ "where" or_expr ]
[ "order" "by" order_key { "," order_key } ] [ "top" additive ] ;
order_key = expr [ "asc" | "desc" ] ;
expr = or_expr [ "?" expr ":" expr | "?:" expr ] ;
or_expr = and_expr { "||" and_expr } ;
and_expr = equality { "&&" equality } ;
equality = comparison [ ( "==" | "!=" ) comparison ] ; (* not chained *)
comparison = additive [ ( "<" | "<=" | ">" | ">=" ) additive ] ; (* not chained *)
additive = multiplicative { ( "+" | "-" ) multiplicative } ;
multiplicative = unary { ( "*" | "/" | "%" ) unary } ;
unary = ( "-" | "!" ) unary | postfix ;
postfix = primary { "." identifier | "(" [ arg { "," arg } ] ")" | "[" expr "]" } ;
arg = [ identifier ":" ] expr ;
primary = literal | identifier | "(" expr ")"
| "new" qualified_name "(" [ arg { "," arg } ] ")"
| ( "int" | "float" | "string" | "boolean" ) "(" expr ")"
| "[" [ expr { "," expr } ] "]"
| "{" [ expr ":" expr { "," expr ":" expr } ] "}" ;
literal = int_literal | float_literal | string_literal | "true" | "false" | "null"
| 'd"' date '"' | 'dt"' datetime '"' | duration_literal ; (* 30m, 1h30m *)
7.1 Roadmap Extensions Roadmap
(* Roadmap extensions — reserved today (E0003); not accepted by the parser *)
base_type = … | "prob" "<" type ">" | "tensor" "<" base_type { "," int_literal } ">"
| "qstate" ;
var_decl = type identifier "=" expr [ "confidence" float_literal ] ;
infer_expr = "infer" "(" expr ")" [ "classifying" "[" string_literal { "," string_literal } "]" ]
[ "as" base_type ] ;
tensor_literal = "[" tensor_row { "," tensor_row } "]" ;
tensor_row = "[" numeric_literal { "," numeric_literal } "]" | numeric_literal ;
End-to-End Enterprise Use Case
RoadmapIllustrative: this file uses infer(), prob, tensors and qstate and does not compile today. A complete, runnable report with its tests is examples/daily_rainfall.prime (Prime Core v0.2 §19, §15).
The following .prime file sketches a
Customer Risk Assessment Pipeline. It ingests customer workflow data,
classifies intent via infer(), computes a tensor-based multi-factor risk
score, runs a quantum-simulated optimisation gate for high-exposure decisions, and
validates all logic with an embedded test suite — all in one self-contained module.
module com.example.risk.assessment; import com.example.quantum.Gates; import com.example.store.AuditStore; import com.example.store.ReviewQueue; import com.example.workflow.WorkflowEngine; import std.time.Timestamp; // ── Data transfer objects ───────────────────────────────────────────────────── pub class CustomerWorkflow { pub int customerId; pub string narrative; pub float requestedExposure; pub string jurisdiction; pub int accountAgeDays; } pub class AssessmentResult { pub string disposition; // "APPROVE" | "ESCALATE" | "REJECT" | "PENDING_REVIEW" pub float riskScore; // composite 0.0–1.0 pub float aiConfidence; pub string quantumPath; // "DETERMINISTIC" | "Q_STANDARD" | "Q_BIFURCATED" pub string auditTimestamp; } // ── Main pipeline ───────────────────────────────────────────────────────────── pub class RiskAssessmentPipeline { // Segment weight matrix: 3 segments × 4 risk dimensions // Dimensions: [credit_history, exposure_ratio, jurisdiction_risk, tenure_score] // Segments: [retail, institutional, sovereign] priv static tensor<float, 3, 4> SEGMENT_WEIGHTS = [ [0.35, 0.25, 0.20, 0.20], [0.20, 0.40, 0.25, 0.15], [0.10, 0.30, 0.45, 0.15] ]; pub static AssessmentResult assess(CustomerWorkflow wf, int segmentIdx) { // ── Step 1: AI Intent Classification ──────────────────────────────────── prob<string> intent = infer(wf.narrative) classifying ["APPROVE", "ESCALATE", "REJECT"]; if (intent.confidence < 0.65) { ReviewQueue.enqueue(wf.customerId, intent.confidence); AssessmentResult r; r.disposition = "PENDING_REVIEW"; r.riskScore = -1.0; r.aiConfidence = intent.confidence; r.quantumPath = "N/A"; r.auditTimestamp = Timestamp.now(); return r; } // ── Step 2: Tensor Multi-Factor Risk Score ────────────────────────────── // Normalise four customer features into a 1×4 vector and dot-product // with the selected segment weight column to get a scalar risk score. float creditNorm = CustomerData.getCreditNorm(wf.customerId); float exposureNorm = wf.requestedExposure / CustomerData.getLimit(wf.customerId); float jurisdRisk = JurisdictionTable.getRiskScore(wf.jurisdiction); float tenureNorm = Math.min(1.0, wf.accountAgeDays / 1825.0); tensor<float, 1, 4> features = [[creditNorm, exposureNorm, jurisdRisk, tenureNorm]]; tensor<float, 4, 1> weightCol = SEGMENT_WEIGHTS.row(segmentIdx).T; // (1×4) * (4×1) → (1×1) tensor<float, 1, 1> scoreTensor = features * weightCol; float compositeRisk = scoreTensor.scalar(); // ── Step 3: Quantum Optimisation Gate ─────────────────────────────────── // High-exposure requests (risk > 0.60) pass through a Hadamard-entangled // decision gate modelling portfolio diversification under uncertainty. string quantumPath = "DETERMINISTIC"; if (compositeRisk > 0.60) { qstate reg = Quantum.register(2); qstate superposed = Quantum.applyHadamard(reg); qstate ctrl = superposed.qubit(0); qstate tgt = superposed.qubit(1); qstate entangled = Quantum.applyCNOT(ctrl, tgt); boolean qDecision = Quantum.measure(entangled.qubit(0)); if (qDecision) { compositeRisk = compositeRisk * 1.15; quantumPath = "Q_BIFURCATED"; } else { quantumPath = "Q_STANDARD"; } } // ── Step 4: Final Disposition ──────────────────────────────────────────── string disposition; if (intent.value == "REJECT" || compositeRisk > 0.85) { disposition = "REJECT"; } else if (intent.value == "ESCALATE" || compositeRisk > 0.55) { disposition = "ESCALATE"; } else { disposition = "APPROVE"; } // ── Step 5: Audit and Return ───────────────────────────────────────────── AuditStore.write(wf.customerId, disposition, compositeRisk, intent.confidence, Timestamp.now()); AssessmentResult result; result.disposition = disposition; result.riskScore = compositeRisk; result.aiConfidence = intent.confidence; result.quantumPath = quantumPath; result.auditTimestamp = Timestamp.now(); return result; } } // ── Embedded test suite ─────────────────────────────────────────────────────── @TestSpecification pub class RiskAssessmentPipelineTests { priv static CustomerWorkflow retailWorkflow(float exposure, int ageDays) { CustomerWorkflow w; w.customerId = 88001; w.narrative = "Standard retail credit line application."; w.requestedExposure = exposure; w.jurisdiction = "EU-DE"; w.accountAgeDays = ageDays; return w; } @Test @MockInfer(label = "APPROVE", conf = 0.96) pub void lowRiskRetailCustomerIsApproved() { CustomerWorkflow w = retailWorkflow(5000.0, 2190); AssessmentResult r = RiskAssessmentPipeline.assess(w, 0); Assert.equals("APPROVE", r.disposition); Assert.isTrue(r.riskScore < 0.55); Assert.equals("DETERMINISTIC", r.quantumPath); } @Test @MockInfer(label = "APPROVE", conf = 0.91) pub void highExposureTriggersQuantumGate() { CustomerWorkflow w = retailWorkflow(980000.0, 365); AssessmentResult r = RiskAssessmentPipeline.assess(w, 0); Assert.isTrue(r.quantumPath == "Q_BIFURCATED" || r.quantumPath == "Q_STANDARD"); } @Test @MockInfer(label = "REJECT", conf = 0.98) pub void aiRejectOverridesLowTensorRisk() { CustomerWorkflow w = retailWorkflow(1000.0, 3650); AssessmentResult r = RiskAssessmentPipeline.assess(w, 0); Assert.equals("REJECT", r.disposition); Assert.isTrue(AuditStore.contains(88001)); } @Test @MockInfer(label = "APPROVE", conf = 0.50) pub void veryLowConfidenceRoutesToReviewQueue() { CustomerWorkflow w = retailWorkflow(20000.0, 730); AssessmentResult r = RiskAssessmentPipeline.assess(w, 0); Assert.equals("PENDING_REVIEW", r.disposition); Assert.isTrue(ReviewQueue.contains(88001)); } @Test pub void segmentWeightsFormProbabilitySimplex() { tensor<float, 3, 4> w = [ [0.35, 0.25, 0.20, 0.20], [0.20, 0.40, 0.25, 0.15], [0.10, 0.30, 0.45, 0.15] ]; Assert.equals(1.0, w.row(0).sum(), 0.001); Assert.equals(1.0, w.row(1).sum(), 0.001); Assert.equals(1.0, w.row(2).sum(), 0.001); } @Test(timeout = 300) @MockInfer(label = "APPROVE", conf = 0.93) pub void fullPipelineCompletesWithinSLA() { CustomerWorkflow w = retailWorkflow(15000.0, 1095); AssessmentResult r = RiskAssessmentPipeline.assess(w, 0); Assert.isTrue(r.disposition != ""); } }
Playground
Run Prime in this page. The playground compiles and executes code with the real PrimeVM,
built to WebAssembly from the same Rust crates as the prime command, entirely
in your browser. Choose an example or write your own: a class Main with
pub static void main() is run and what it writes with print is
shown, and every @Test is run and the admission rule (§6) applied.
spec/prime-core-v0.2.md. The
tensor<…> type, infer(), prob,
qstate and the other roadmap features of §2–§4 are reserved words and are
rejected by the compiler (the std.tensors library of §2.3 is available).
Host functions (data of the embedding application) are not available in the browser.
The combo box picks what runs your code: Prime v0.2 · stack VM (the
default), Prime v0.2 · register VM — the same v0.2 language on the
register machine kept from v0.1, to compare bytecode — or the Prime v0.1
release, the frozen compiler and VM of v0.1 (git tag v0.1), which
rejects what v0.2 added, such as std.tensors.
The output shows the lines written with print, test results and admission verdicts,
and diagnostics with phase, code, line and column (Prime Core §14). Each run gets
20 million instructions and 3 seconds; nothing leaves the page.
GPU and Tensor Backend
Proposed v0.2No GPU code exists. Prime programs run on the CPU today, including the NaviSpy Monitor reports.
PrimeVM runs as WebAssembly in its embeddings and in browsers, where a GPU is not reachable. GPU work therefore belongs to the embedding application's native code and reaches Prime through host calls — the same boundary as every other host function. No new instructions and no change to the machine model are needed.
| Concern | Proposal |
|---|---|
| Boundary | The Tensor class of std.tensors (§2.3) keeps its API; a GPU-capable host implements it natively, and Prime holds handles to tensors that live in the host. |
| Data | Dense, row-major; f32 on the device by default, f64 available; shapes checked by the host at run time first, by the type system later. |
| Ownership and transfers | Tensors belong to the run and are freed when it ends; uploads and downloads are explicit operations. |
| Synchronisation and errors | Calls are synchronous from Prime's point of view; device errors and out-of-memory become diagnostics at the calling line. |
| Limits and permissions | Operations charge instructions by size; a per-run device-memory limit; per-operation size caps against the time limit; the tensor module is a capability the host grants. |
| CPU fallback | Today's CPU implementation of std.tensors is the reference; GPU results are compared with it within stated tolerances, since GPU reductions are not bit-identical. |
| Implementation | Established libraries (cuBLAS first; an inference runtime once a model exists) before any custom kernels. |
The first milestone and its benchmark — fleet-wide fuel-anomaly detection, scalar Prime
versus CPU tensors versus CUDA, measured end to end — are described in the repository
(docs/proposals/cuda-gpu-backend.md). No performance figures exist yet.