Your own domain — the convoy template
Time to make it yours. This section gives you a complete, working domain — a small logistics simulation, deliberately a different shape from §3's duel (two resources per actor, a shared stock, a delivery threshold) — and then tells you exactly which parts to change to make it your own simulation. The skeleton is the contract; the rules are yours.
4.1 — Place the file. From the tree root:
mkdir -p domains/convoy/src
Create domains/convoy/src/convoy.mjs with exactly this content:
// convoy.mjs — THE PILOT TEMPLATE DOMAIN. A small deterministic logistics
// simulation, written to be adapted: the skeleton (founding schema, fact
// envelope, one fold shared by two recipes, a verdict recipe) is the record
// layer's contract; the rules (resources, actions, costs, the score) are
// yours to replace. It is a different shape from the worked example in the
// integration guide (replay-verify's duel) on purpose: two resources plus a
// shared stock and a delivery threshold, instead of energy and a target.
//
// THE FOLD'S LAW (stated here so a reader can grade it):
// - Inputs fold in tick order; log position breaks tick ties.
// - Every draw comes from the simulation's own addressed streams, forked
// from the seed the founding committed — convoy|tick|<tick>|<truck> —
// never from the record's founding seed: the sim seed is a fact of the
// run, so two records that commit the same founding and the same inputs
// derive the same run, whoever founded them.
// - All arithmetic is integer arithmetic (the decision path).
// - An action the ruleset does not name is REFUSED by the derivation. An
// action the truck cannot afford fizzles: the input stands in the
// trace, marked fizzled, and changes nothing.
// - The ruleset is a pin the founding commits ('convoy-rules@1'). This
// build implements exactly that one; any other pin is refused loudly
// at derivation time, never approximated.
import { createStreamFactory, canonicalHash } from '../../../core/src/index.mjs';
import { defineDomain } from '../../../record-layer/src/index.mjs';
const FUEL_START = 10;
const FUEL_CAP = 12;
const CARGO_CAP = 8;
const LOAD_TAKE = 5;
const STOCK_START = 40;
const ROUTE_LENGTH = 12;
const RULESETS = {
'convoy-rules@1': {
actions: {
load: { cost: 1 },
drive: { cost: 2 },
refuel: { cost: 0 },
wait: { cost: 0 },
},
},
};
function foundingFact(view) {
const f = view.facts.find((x) => x.type === 'founding');
if (!f) throw new Error('convoy: the record carries no founding fact — found it through the domain');
return f;
}
function rulesetOf(f) {
const rules = RULESETS[f.ruleset];
if (!rules) {
throw new Error(`convoy: the founding commits ruleset '${f.ruleset}', which this build does not implement (implemented: ${Object.keys(RULESETS).join(', ')}) — an unimplemented ruleset is refused, never approximated`);
}
return rules;
}
function foldRun(view) {
const f = foundingFact(view);
const rules = rulesetOf(f);
const streams = createStreamFactory(f.seed);
const inputs = view.facts
.map((fact, position) => ({ fact, position }))
.filter(({ fact }) => fact.type === 'input')
.sort((a, b) => (a.fact.tick - b.fact.tick) || (a.position - b.position));
const trucks = new Map();
const truckOf = (name) => {
if (!trucks.has(name)) trucks.set(name, { truck: name, fuel: FUEL_START, cargo: 0, distance: 0, delivered: 0 });
return trucks.get(name);
};
let stock = STOCK_START;
const trace = [];
for (const { fact } of inputs) {
const t = truckOf(fact.truck);
const rule = rules.actions[fact.action];
if (!rule) {
throw new Error(`convoy: action '${fact.action}' is not named by ${f.ruleset} — the derivation refuses what the ruleset does not name`);
}
const step = { tick: fact.tick, truck: fact.truck, action: fact.action, fizzled: false };
if (t.fuel < rule.cost) {
step.fizzled = true; // the input stands, marked, and changes nothing
} else if (fact.action === 'load') {
t.fuel -= rule.cost;
const taken = Math.min(LOAD_TAKE, stock, CARGO_CAP - t.cargo);
t.cargo += taken;
stock -= taken;
step.taken = taken; // may be 0 — a wasted trip is the sim's honest answer, and it still cost the fuel
} else if (fact.action === 'drive') {
t.fuel -= rule.cost;
const advance = streams.rngFor(`convoy|tick|${fact.tick}|${fact.truck}`).int(2, 5);
t.distance += advance;
step.advance = advance;
step.distance = t.distance;
if (t.distance >= ROUTE_LENGTH) {
step.arrived = true;
step.delivered = t.cargo;
t.delivered += t.cargo;
t.cargo = 0;
t.distance = 0;
}
} else if (fact.action === 'refuel') {
t.fuel = Math.min(FUEL_CAP, t.fuel + 5);
step.fuel = t.fuel;
} else if (fact.action === 'wait') {
// stands in the trace; changes nothing
}
trace.push(step);
}
const truckList = [...trucks.values()].sort((x, y) => (x.truck < y.truck ? -1 : x.truck > y.truck ? 1 : 0));
const score = truckList.reduce((s, t) => s + t.delivered, 0);
const ticks = inputs.length ? inputs[inputs.length - 1].fact.tick : 0;
const state = { trucks: truckList, stock, ticks };
return { founding: f, inputs: inputs.length, state, score, stateHash: canonicalHash(state), trace };
}
const finalState = {
id: 'final-state', version: '1',
derive(view) {
const run = foldRun(view);
return {
name: run.founding.name,
ruleset: run.founding.ruleset,
seed: run.founding.seed,
inputs: run.inputs,
trucks: run.state.trucks,
stock: run.state.stock,
ticks: run.state.ticks,
score: run.score,
stateHash: run.stateHash,
trace: run.trace,
};
},
};
const verifyScore = {
id: 'verify-score', version: '1',
derive(view, ctx) {
const run = foldRun(view);
const claimed = ctx.params.claimedScore;
return {
name: run.founding.name,
ruleset: run.founding.ruleset,
claimedScore: claimed === undefined ? null : claimed,
derivedScore: run.score,
stateHash: run.stateHash,
verdict: claimed === undefined ? 'NO CLAIM STATED' : (claimed === run.score ? 'VERIFIED' : 'REFUTED'),
};
},
};
export const convoy = defineDomain({
id: 'convoy',
version: 1,
founding: { name: 'string!', ruleset: 'string!', seed: 'int!' },
factTypes: {
input: { tick: 'int!', truck: 'string!', action: 'string!' },
},
recipes: [finalState, verifyScore],
});
// ---- the template's fixture: one fixed run, shared by the guide's §4
// driver. Its honest score is whatever the fold derives — read it from
// the derivation, never hardcode it into a claim. ----
export const CANONICAL = Object.freeze({
subject: 'harbour-loop-pilot',
moment: 1797000000000,
founding: Object.freeze({ name: 'Harbour Loop', ruleset: 'convoy-rules@1', seed: 77031 }),
facts: Object.freeze([
Object.freeze({ type: 'input', tick: 1, truck: 'ada', action: 'load' }),
Object.freeze({ type: 'input', tick: 1, truck: 'bo', action: 'load' }),
Object.freeze({ type: 'input', tick: 2, truck: 'ada', action: 'drive' }),
Object.freeze({ type: 'input', tick: 2, truck: 'bo', action: 'drive' }),
Object.freeze({ type: 'input', tick: 3, truck: 'ada', action: 'drive' }),
Object.freeze({ type: 'input', tick: 3, truck: 'bo', action: 'drive' }),
Object.freeze({ type: 'input', tick: 4, truck: 'ada', action: 'drive' }),
Object.freeze({ type: 'input', tick: 4, truck: 'bo', action: 'refuel' }),
Object.freeze({ type: 'input', tick: 5, truck: 'ada', action: 'drive' }),
Object.freeze({ type: 'input', tick: 5, truck: 'bo', action: 'drive' }),
]),
});
export function buildCanonicalRecord() {
const record = convoy.found(CANONICAL.subject, CANONICAL.moment, { ...CANONICAL.founding });
for (const f of CANONICAL.facts) convoy.append(record, { ...f });
return record;
}
// The same run with ONE input altered — tick 3, ada drives becomes ada
// waits. If re-derivation is verification, this record cannot carry the
// honest run's score.
export function buildTamperedRecord() {
const record = convoy.found(CANONICAL.subject, CANONICAL.moment, { ...CANONICAL.founding });
CANONICAL.facts.forEach((f, i) => {
convoy.append(record, i === 4 ? { type: 'input', tick: 3, truck: 'ada', action: 'wait' } : { ...f });
});
return record;
}
4.2 — Drive it. Create domains/convoy/drive.mjs:
// drive.mjs — the integration guide's §4 driver: your domain, end to end.
// Run from this directory: node drive.mjs
import { convoy, buildCanonicalRecord, buildTamperedRecord } from './src/convoy.mjs';
const honest = buildCanonicalRecord();
const fin = convoy.collapse(honest, 'final-state@1');
console.log(`SCORE (read from the derivation, never hardcoded): ${fin.artifact.score}`);
console.log(`STATE HASH: ${fin.artifact.stateHash}`);
console.log(`MANIFEST: ${JSON.stringify(fin.manifest)}`);
const ver = convoy.collapse(honest, 'verify-score@1', { params: { claimedScore: fin.artifact.score } });
console.log(`VERDICT ON THE HONEST CLAIM: ${ver.artifact.verdict}`);
const rep = convoy.replay(honest, 'final-state@1', fin.manifest);
console.log(`REPLAY OF THE FINAL-STATE MANIFEST: ${rep.verdict}`);
const tampered = buildTamperedRecord();
const tver = convoy.collapse(tampered, 'verify-score@1', { params: { claimedScore: fin.artifact.score } });
console.log(`TAMPERED RUN'S DERIVED SCORE: ${tver.artifact.derivedScore}`);
console.log(`VERDICT ON THE HONEST CLAIM AGAINST THE TAMPERED RECORD: ${tver.artifact.verdict}`);
const trep = convoy.replay(tampered, 'final-state@1', fin.manifest);
console.log(`REPLAY OF THE HONEST MANIFEST AGAINST THE TAMPERED RECORD: ${trep.verdict}`);
Run it from domains/convoy: node drive.mjs. Expected output, verbatim, for the unmodified template:
SCORE (read from the derivation, never hardcoded): 10
STATE HASH: sha256:b629f3cc13d550a5b20f4802759afa8d0eca79030d15fb52c385c2f15d12e003
MANIFEST: {"recordHash":"sha256:76ac8d42b70c50c88a9fd386c4e96ea55463d01c72476ccff67f29f28dded4f1","position":10,"recipe":"final-state@1","engine":"quantum-engine-core/0.1.0","outputHash":"sha256:a2d3cd84c2979b38758614c2a7392b5da258bc7b7c8137186f11f3cfa0efe561"}
VERDICT ON THE HONEST CLAIM: VERIFIED
REPLAY OF THE FINAL-STATE MANIFEST: MATCH
TAMPERED RUN'S DERIVED SCORE: 5
VERDICT ON THE HONEST CLAIM AGAINST THE TAMPERED RECORD: REFUTED
REPLAY OF THE HONEST MANIFEST AGAINST THE TAMPERED RECORD: MISMATCH
Both trucks deliver 5 units each (score 10); the tampered run — ada waits at tick 3 instead of driving, and never reaches the delivery threshold — derives 5, and the honest claim against it is REFUTED.
4.3 — Make it yours. The adaptation points, in order:
- Rename the domain. Change the
idindefineDomain(and the export name, the file name, the import in the driver). Your domain id is the first segment of your schema string (<id>@1) and is hashed into every record you found. Pick it once; renaming later means a new domain, not an edit — old records keep the old schema. - Replace the rules. The
RULESETStable (action names + costs), the constants, and the per-action branches infoldRunare the simulation. Keep the fold's law: tick order with log position breaking ties; integer arithmetic only; unaffordable actions fizzle and are marked; unnamed actions throw. - Keep the stream discipline. Draws fork from the founding's committed
seedvia your owncreateStreamFactory, addressed<domain>|tick|<tick>|<actor>. An address is part of a recipe's identity: renaming an address changes every derivation downstream of it, so treat an address change as a recipe version bump. - Keep the two recipe shapes. One recipe states the run (
final-state), one judges a claim against it (verify-score), and both read the same fold — one implementation, two readings, no second fold to drift. If your score is not a single integer, your verdict recipe compares whatever your claim parameter carries; the parameter is bound into the collapse's content key either way. - Change the fixture, then re-derive the expectations. Replace
CANONICAL's founding and facts with a run of your sim. The expected outputs in §4.2 are for the unmodified template only; after any rule or fixture change, your driver prints your values, and those become your expectations. One warning, earned when this template was built: its first fixture scored 0 — the run was too short for any truck to reach the delivery threshold, so the honest claim verified vacuously against the tampered record too (0 = 0). A fixture whose tampered input does not move the derived score proves nothing. Make the run long enough that the score is nonzero and the tamper moves it, or the flip test in §4.2 is theatre. - Declare every field. Founding fields and fact fields are validated against your
defineDomaindeclaration; an undeclared field is refused at append time (§6). A new field is a declaration change — and a declaration change is a domain version bump, loudly, per the layer's conventions. Outcomes are never fields: if a value can be derived, it does not get appended.
The field DSL is four scalar types — string, int, number, boolean, with ! for required. There is no nesting. If your shape needs richer structure, validate inside your own append path and say so in your domain's header comment, the way the template states its fold law.
← The worked example — replay-verify, in process · Serve your domain — registration, in your copy of the service →