Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat: bootstrap the v2 core and node driver
kashorin38a2ac9457bc
diff --git a/README.md b/README.mdindex 96d99b50..94cd707e 100644--- a/README.md+++ b/README.md@@ -1,5 +1,10 @@# SVML+> **v2 bootstrap:** `packages/protocol`, `packages/core` and `packages/driver-node`+> now implement the domain-free typed state kernel and an explicitly registered Node Host.+> Frontend, `.svml` and `.svs` parsing are intentionally not part of this slice. The existing+> root compiler and standard library remain the executable v1 research oracle during migration.+Semantic Video Markup Language is a semantic source language for information-flowvideo. Script creates stable semantic addresses. A Composition selects onecontent-addressed `ProgramBasis` and one exact `SemanticMap`; flat Trackdiff --git a/package.json b/package.jsonindex a2c9d88e..e20f5714 100644--- a/package.json+++ b/package.json@@ -8,8 +8,12 @@},"scripts": {"build": "tsc -p tsconfig.json && node tools/copy-runtime.mjs",- "check": "tsc -p tsconfig.json --noEmit",- "test": "node --import tsx --test 'test/**/*.test.ts'",+ "check": "pnpm check:v1 && pnpm check:v2",+ "check:v1": "tsc -p tsconfig.json --noEmit",+ "check:v2": "tsc -p tsconfig.v2.json --noEmit",+ "test": "pnpm test:v1 && pnpm test:v2",+ "test:v1": "node --import tsx --test 'test/**/*.test.ts'",+ "test:v2": "node --import tsx --test 'packages/*/test/**/*.test.ts'","svml": "node --import tsx src/cli.ts"},"files": [diff --git a/packages/core/README.md b/packages/core/README.mdnew file mode 100644index 00000000..289bc225--- /dev/null+++ b/packages/core/README.md@@ -0,0 +1,10 @@+# `@svml/core`++Experimental v2 bootstrap microkernel.++The package accepts an already resolved module closure, typed authored modules and an explicit+finite build plan. It validates identities, schemas, immutable records, Needs, Receipts and+Derivations, then advances a serializable `BuildState` with pure `reduce(state, event)` calls.++It does not parse source, resolve package locations, execute implementations, access artifact+bytes, select providers or search for a workflow. Those responsibilities remain outside Core.diff --git a/packages/core/package.json b/packages/core/package.jsonnew file mode 100644index 00000000..23c48c22--- /dev/null+++ b/packages/core/package.json@@ -0,0 +1,12 @@+{+ "name": "@svml/core",+ "version": "0.0.0-dev",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "dependencies": {+ "@svml/protocol": "workspace:*"+ }+}diff --git a/packages/core/src/canonical.ts b/packages/core/src/canonical.tsnew file mode 100644index 00000000..a3a4a91f--- /dev/null+++ b/packages/core/src/canonical.ts@@ -0,0 +1,98 @@+import { createHash } from "node:crypto";++import type {+ CanonicalValue,+ Digest,+ StoredValue,+ TypeRef,+ TypedRecord,+} from "@svml/protocol";++import { CoreError } from "./error.js";++function normalize(value: unknown, path: string, ancestors: WeakSet<object>): CanonicalValue {+ if (value === null || typeof value === "boolean" || typeof value === "string") {+ return value;+ }++ if (typeof value === "number") {+ if (!Number.isFinite(value)) {+ throw new CoreError("NON_CANONICAL_NUMBER", `${path} must be finite`);+ }+ return Object.is(value, -0) ? 0 : value;+ }++ if (Array.isArray(value)) {+ if (ancestors.has(value)) throw new CoreError("CYCLIC_VALUE", `${path} contains a cycle`);+ ancestors.add(value);+ const result = value.map((item, index) => normalize(item, `${path}[${index}]`, ancestors));+ ancestors.delete(value);+ return result;+ }++ if (typeof value === "object") {+ const prototype = Object.getPrototypeOf(value);+ if (prototype !== Object.prototype && prototype !== null) {+ throw new CoreError("NON_CANONICAL_OBJECT", `${path} must be a plain object`);+ }+ if (ancestors.has(value)) throw new CoreError("CYCLIC_VALUE", `${path} contains a cycle`);+ ancestors.add(value);++ const result: Record<string, CanonicalValue> = {};+ const source = value as Record<string, unknown>;+ for (const key of Object.keys(source).sort()) {+ const descriptor = Object.getOwnPropertyDescriptor(source, key);+ if (descriptor === undefined || descriptor.get !== undefined || descriptor.set !== undefined) {+ throw new CoreError("NON_CANONICAL_ACCESSOR", `${path}.${key} must be a data property`);+ }+ const item = descriptor.value;+ if (item === undefined) {+ throw new CoreError("NON_CANONICAL_UNDEFINED", `${path}.${key} is undefined`);+ }+ Object.defineProperty(result, key, {+ value: normalize(item, `${path}.${key}`, ancestors),+ enumerable: true,+ configurable: true,+ writable: true,+ });+ }+ ancestors.delete(value);+ return result;+ }++ throw new CoreError("NON_CANONICAL_VALUE", `${path} contains ${typeof value}`);+}++export function canonicalize(value: unknown): CanonicalValue {+ return normalize(value, "$input", new WeakSet<object>());+}++export function canonicalStringify(value: unknown): string {+ return JSON.stringify(canonicalize(value));+}++export function digestOf(value: unknown): Digest {+ const hex = createHash("sha256").update(canonicalStringify(value), "utf8").digest("hex");+ return `sha256:${hex}`;+}++export function isDigest(value: string): value is Digest {+ return /^sha256:[0-9a-f]{64}$/u.test(value);+}++export function recordDigest(type: TypeRef, value: StoredValue): Digest {+ return digestOf({ type, value });+}++export function semanticRecordsDigest(records: readonly TypedRecord[]): Digest {+ return digestOf(+ [...records]+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((record) => ({+ id: record.id,+ type: record.type,+ value: record.value,+ conformance: record.conformance,+ })),+ );+}diff --git a/packages/core/src/error.ts b/packages/core/src/error.tsnew file mode 100644index 00000000..6b8b5056--- /dev/null+++ b/packages/core/src/error.ts@@ -0,0 +1,22 @@+export class CoreError extends Error {+ readonly code: string;+ readonly subject: string | undefined;++ constructor(code: string, message: string, subject?: string) {+ super(message);+ this.name = "CoreError";+ this.code = code;+ this.subject = subject;+ }+}++export function invariant(+ condition: unknown,+ code: string,+ message: string,+ subject?: string,+): asserts condition {+ if (!condition) {+ throw new CoreError(code, message, subject);+ }+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsnew file mode 100644index 00000000..6e45d33c--- /dev/null+++ b/packages/core/src/index.ts@@ -0,0 +1,19 @@+export { canonicalStringify, canonicalize, digestOf, isDigest, recordDigest } from "./canonical.js";+export { CoreError } from "./error.js";+export {+ computeClosureDigest,+ computeModuleDigest,+ createResolvedClosure,+ link,+ resolveProducer,+ resolveType,+ sealRecord,+ sealTypedModule,+ verifyClosure,+ verifyRecord,+} from "./link.js";+export { validatePlan } from "./plan.js";+export { reduce, start } from "./reducer.js";+export { verifyBuildState } from "./verify.js";+export { validateStoredValue } from "./schema.js";+export type { TypedRecordDraft } from "./link.js";diff --git a/packages/core/src/link.ts b/packages/core/src/link.tsnew file mode 100644index 00000000..7301b2d1--- /dev/null+++ b/packages/core/src/link.ts@@ -0,0 +1,303 @@+import type {+ Digest,+ LinkedProgram,+ ModuleManifest,+ ModuleRef,+ ProducerRef,+ ResolvedModule,+ ResolvedModuleClosure,+ ResolvedProducerDeclaration,+ ResolvedTypeDeclaration,+ TypeRef,+ TypedModule,+ TypedRecord,+} from "@svml/protocol";++import { digestOf, isDigest, recordDigest, semanticRecordsDigest } from "./canonical.js";+import { CoreError, invariant } from "./error.js";+import { moduleKey, producerKey, sameModule, typeKey } from "./reference.js";+import { validateStoredValue } from "./schema.js";++export type TypedRecordDraft = Omit<TypedRecord, "digest">;++function manifestRef(manifest: ModuleManifest): ModuleRef {+ return { name: manifest.name, version: manifest.version };+}++export function computeModuleDigest(manifest: ModuleManifest): Digest {+ return digestOf(manifest);+}++export function computeClosureDigest(modules: readonly ResolvedModule[]): Digest {+ return digestOf({+ format: "svml.closure@0",+ modules: [...modules]+ .sort((left, right) => moduleKey(left.ref).localeCompare(moduleKey(right.ref)))+ .map((module) => ({ ref: module.ref, digest: module.digest })),+ });+}++export function createResolvedClosure(+ manifests: readonly ModuleManifest[],+): ResolvedModuleClosure {+ const modules = manifests.map((manifest) => ({+ ref: manifestRef(manifest),+ digest: computeModuleDigest(manifest),+ manifest,+ }));+ const closure: ResolvedModuleClosure = {+ format: "svml.closure@0",+ modules,+ digest: computeClosureDigest(modules),+ };+ verifyClosure(closure);+ return closure;+}++function ensureUniqueNames(names: readonly string[], kind: string, owner: string): void {+ const seen = new Set<string>();+ for (const name of names) {+ invariant(name.length > 0, "EMPTY_NAME", `${kind} name in ${owner} is empty`, owner);+ invariant(!seen.has(name), "DUPLICATE_EXPORT", `${owner} declares duplicate ${kind} ${name}`, name);+ seen.add(name);+ }+}++export function verifyClosure(closure: ResolvedModuleClosure): void {+ invariant(closure.format === "svml.closure@0", "UNSUPPORTED_CLOSURE", "unsupported closure format");+ invariant(isDigest(closure.digest), "INVALID_DIGEST", "closure digest is invalid");++ const modules = new Map<string, ResolvedModule>();+ for (const module of closure.modules) {+ const key = moduleKey(module.ref);+ invariant(module.ref.name.length > 0, "EMPTY_MODULE_NAME", "module name is empty");+ invariant(module.ref.version.length > 0, "EMPTY_MODULE_VERSION", `${module.ref.name} version is empty`);+ invariant(module.manifest.format === "svml.module@0", "UNSUPPORTED_MODULE", `${key} format is unsupported`);+ invariant(!modules.has(key), "DUPLICATE_MODULE", `duplicate module ${key}`, key);+ invariant(+ sameModule(module.ref, manifestRef(module.manifest)),+ "MODULE_ID_MISMATCH",+ `${key} does not match its manifest identity`,+ key,+ );+ invariant(isDigest(module.digest), "INVALID_DIGEST", `${key} digest is invalid`, key);+ invariant(+ module.digest === computeModuleDigest(module.manifest),+ "MODULE_DIGEST_MISMATCH",+ `${key} manifest digest does not match`,+ key,+ );+ ensureUniqueNames(module.manifest.types.map((item) => item.name), "type", key);+ ensureUniqueNames(module.manifest.producers.map((item) => item.name), "producer", key);+ ensureUniqueNames(+ module.manifest.dependencies.map((item) => moduleKey(item.module)),+ "dependency",+ key,+ );+ for (const producer of module.manifest.producers) {+ ensureUniqueNames(producer.inputs.map((item) => item.name), "input port", `${key}#${producer.name}`);+ ensureUniqueNames(producer.outputs.map((item) => item.name), "output port", `${key}#${producer.name}`);+ ensureUniqueNames(producer.needs.map((item) => item.name), "need port", `${key}#${producer.name}`);+ invariant(+ isDigest(producer.implementation.digest),+ "INVALID_DIGEST",+ `${key}#${producer.name} implementation digest is invalid`,+ );+ }+ modules.set(key, module);+ }++ for (const module of closure.modules) {+ for (const dependency of module.manifest.dependencies) {+ const resolved = modules.get(moduleKey(dependency.module));+ invariant(+ resolved !== undefined,+ "MISSING_DEPENDENCY",+ `${moduleKey(module.ref)} requires ${moduleKey(dependency.module)}`,+ );+ invariant(+ resolved.digest === dependency.digest,+ "DEPENDENCY_DIGEST_MISMATCH",+ `${moduleKey(dependency.module)} does not match the required digest`,+ );+ }+ }++ invariant(+ closure.digest === computeClosureDigest(closure.modules),+ "CLOSURE_DIGEST_MISMATCH",+ "resolved module closure digest does not match",+ );++ for (const module of closure.modules) {+ const allowed = new Set([+ moduleKey(module.ref),+ ...module.manifest.dependencies.map((dependency) => moduleKey(dependency.module)),+ ]);+ for (const producer of module.manifest.producers) {+ for (const port of [...producer.inputs, ...producer.outputs]) {+ invariant(+ allowed.has(moduleKey(port.type.module)),+ "UNDECLARED_TYPE_DEPENDENCY",+ `${moduleKey(module.ref)}#${producer.name} references ${typeKey(port.type)} without a dependency`,+ );+ const target = modules.get(moduleKey(port.type.module));+ invariant(+ target?.manifest.types.some((type) => type.name === port.type.name),+ "UNKNOWN_TYPE",+ `${moduleKey(module.ref)}#${producer.name} references unknown type ${typeKey(port.type)}`,+ );+ }+ for (const port of producer.needs) {+ invariant(+ allowed.has(moduleKey(port.wants.module)),+ "UNDECLARED_TYPE_DEPENDENCY",+ `${moduleKey(module.ref)}#${producer.name} references ${typeKey(port.wants)} without a dependency`,+ );+ const target = modules.get(moduleKey(port.wants.module));+ invariant(+ target?.manifest.types.some((type) => type.name === port.wants.name),+ "UNKNOWN_TYPE",+ `${moduleKey(module.ref)}#${producer.name} references unknown type ${typeKey(port.wants)}`,+ );+ }+ }+ }+}++export function resolveType(+ closure: ResolvedModuleClosure,+ ref: TypeRef,+): ResolvedTypeDeclaration {+ const module = closure.modules.find((item) => sameModule(item.ref, ref.module));+ invariant(module !== undefined, "UNKNOWN_MODULE", `unknown module ${moduleKey(ref.module)}`, typeKey(ref));+ const declaration = module.manifest.types.find((item) => item.name === ref.name);+ invariant(declaration !== undefined, "UNKNOWN_TYPE", `unknown type ${typeKey(ref)}`, typeKey(ref));+ return { ...declaration, ref };+}++export function resolveProducer(+ closure: ResolvedModuleClosure,+ ref: ProducerRef,+): ResolvedProducerDeclaration {+ const module = closure.modules.find((item) => sameModule(item.ref, ref.module));+ invariant(+ module !== undefined,+ "UNKNOWN_MODULE",+ `unknown module ${moduleKey(ref.module)}`,+ producerKey(ref),+ );+ const declaration = module.manifest.producers.find((item) => item.name === ref.name);+ invariant(+ declaration !== undefined,+ "UNKNOWN_PRODUCER",+ `unknown producer ${producerKey(ref)}`,+ producerKey(ref),+ );+ return { ...declaration, ref };+}++export function sealRecord(record: TypedRecordDraft): TypedRecord {+ return { ...record, digest: recordDigest(record.type, record.value) };+}++export function verifyRecord(+ closure: ResolvedModuleClosure,+ record: TypedRecord,+): void {+ invariant(record.id.length > 0, "EMPTY_RECORD_ID", "record id is empty");+ invariant(isDigest(record.digest), "INVALID_DIGEST", `${record.id} digest is invalid`, record.id);+ invariant(+ record.digest === recordDigest(record.type, record.value),+ "RECORD_DIGEST_MISMATCH",+ `${record.id} digest does not match its value`,+ record.id,+ );+ const declaration = resolveType(closure, record.type);+ validateStoredValue(record.value, declaration.schema, `$record.${record.id}`);+ if (record.origin.kind === "authored") {+ invariant(isDigest(record.origin.sourceDigest), "INVALID_DIGEST", `${record.id} source digest is invalid`);+ invariant(+ isDigest(record.origin.frontendClosureDigest),+ "INVALID_DIGEST",+ `${record.id} frontend closure digest is invalid`,+ );+ invariant(record.conformance === "exact", "AUTHORED_SUBSTITUTE", `${record.id} authored record is substitute`);+ }+}++export function sealTypedModule(input: {+ readonly id: string;+ readonly closureDigest: Digest;+ readonly records: readonly TypedRecord[];+}): TypedModule {+ return {+ format: "svml.typed-module@0",+ id: input.id,+ closureDigest: input.closureDigest,+ records: input.records,+ semanticDigest: semanticRecordsDigest(input.records),+ };+}++export function link(+ closure: ResolvedModuleClosure,+ typedModules: readonly TypedModule[],+): LinkedProgram {+ verifyClosure(closure);+ const moduleIds = new Set<string>();+ const recordIds = new Set<string>();+ const records: TypedRecord[] = [];++ for (const typedModule of typedModules) {+ invariant(+ typedModule.format === "svml.typed-module@0",+ "UNSUPPORTED_TYPED_MODULE",+ `${typedModule.id} has an unsupported format`,+ );+ invariant(!moduleIds.has(typedModule.id), "DUPLICATE_TYPED_MODULE", typedModule.id, typedModule.id);+ moduleIds.add(typedModule.id);+ invariant(+ typedModule.closureDigest === closure.digest,+ "TYPED_MODULE_CLOSURE_MISMATCH",+ `${typedModule.id} was decoded against another module closure`,+ );+ invariant(+ typedModule.semanticDigest === semanticRecordsDigest(typedModule.records),+ "SEMANTIC_DIGEST_MISMATCH",+ `${typedModule.id} semantic digest does not match`,+ );+ for (const record of typedModule.records) {+ invariant(!recordIds.has(record.id), "DUPLICATE_RECORD", `duplicate record ${record.id}`, record.id);+ invariant(+ record.origin.kind === "authored",+ "NON_AUTHORED_MODULE_RECORD",+ `${typedModule.id} contains a non-authored input record`,+ record.id,+ );+ verifyRecord(closure, record);+ recordIds.add(record.id);+ records.push(record);+ }+ }++ return {+ closure,+ modules: typedModules,+ records,+ semanticDigest: digestOf(+ [...typedModules]+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((module) => ({ id: module.id, semanticDigest: module.semanticDigest })),+ ),+ };+}++export function assertKnownType(closure: ResolvedModuleClosure, ref: TypeRef): void {+ try {+ resolveType(closure, ref);+ } catch (error) {+ if (error instanceof CoreError) throw error;+ throw error;+ }+}diff --git a/packages/core/src/plan.ts b/packages/core/src/plan.tsnew file mode 100644index 00000000..fd14db0c--- /dev/null+++ b/packages/core/src/plan.ts@@ -0,0 +1,162 @@+import type {+ BuildPlan,+ LinkedProgram,+ ProducerStep,+ RecordId,+ TypeRef,+} from "@svml/protocol";++import { invariant } from "./error.js";+import { resolveProducer } from "./link.js";+import { sameType, typeKey } from "./reference.js";++function exactKeys(+ actual: Readonly<Record<string, unknown>>,+ expected: readonly string[],+ subject: string,+): void {+ const actualKeys = Object.keys(actual).sort();+ const expectedKeys = [...expected].sort();+ invariant(+ JSON.stringify(actualKeys) === JSON.stringify(expectedKeys),+ "PORT_BINDING_MISMATCH",+ `${subject} binds [${actualKeys.join(", ")}] but declares [${expectedKeys.join(", ")}]`,+ subject,+ );+}++type ProducedRecord = {+ readonly type: TypeRef;+ readonly step?: string;+};++export function validatePlan(program: LinkedProgram, plan: BuildPlan): void {+ invariant(plan.format === "svml.plan@0", "UNSUPPORTED_PLAN", "unsupported build plan format");+ invariant(plan.id.length > 0, "EMPTY_PLAN_ID", "build plan id is empty");+ invariant(plan.goals.length > 0, "EMPTY_PLAN_GOALS", "build plan has no goals");++ const records = new Map<RecordId, ProducedRecord>();+ for (const record of program.records) records.set(record.id, { type: record.type });++ const stepIds = new Set<string>();+ const needIds = new Set<string>();+ for (const step of plan.steps) {+ invariant(!stepIds.has(step.id), "DUPLICATE_STEP", `duplicate step ${step.id}`, step.id);+ stepIds.add(step.id);+ const producer = resolveProducer(program.closure, step.producer);+ exactKeys(step.inputs, producer.inputs.map((port) => port.name), `${step.id}.inputs`);+ exactKeys(step.outputs, producer.outputs.map((port) => port.name), `${step.id}.outputs`);+ exactKeys(step.needs, producer.needs.map((port) => port.name), `${step.id}.needs`);++ for (const port of producer.outputs) {+ const id = step.outputs[port.name];+ invariant(id !== undefined && id.length > 0, "EMPTY_RECORD_ID", `${step.id}.${port.name} is empty`);+ invariant(!records.has(id), "DUPLICATE_RECORD", `record ${id} has multiple producers`, id);+ records.set(id, { type: port.type, step: step.id });+ }+ for (const port of producer.needs) {+ const binding = step.needs[port.name];+ invariant(binding !== undefined, "MISSING_NEED_BINDING", `${step.id}.${port.name} is not bound`);+ invariant(binding.id.length > 0, "EMPTY_NEED_ID", `${step.id}.${port.name} need id is empty`);+ invariant(!needIds.has(binding.id), "DUPLICATE_NEED", `need ${binding.id} has multiple producers`);+ needIds.add(binding.id);+ invariant(binding.result.length > 0, "EMPTY_RECORD_ID", `${step.id}.${port.name} result id is empty`);+ invariant(+ !records.has(binding.result),+ "DUPLICATE_RECORD",+ `record ${binding.result} has multiple producers`,+ binding.result,+ );+ records.set(binding.result, { type: port.wants, step: step.id });+ }+ }++ for (const step of plan.steps) {+ const producer = resolveProducer(program.closure, step.producer);+ for (const port of producer.inputs) {+ const id = step.inputs[port.name];+ invariant(id !== undefined, "MISSING_INPUT_BINDING", `${step.id}.${port.name} is not bound`);+ const supplied = records.get(id);+ invariant(supplied !== undefined, "UNKNOWN_RECORD", `${step.id}.${port.name} references ${id}`, id);+ invariant(+ sameType(supplied.type, port.type),+ "INPUT_TYPE_MISMATCH",+ `${step.id}.${port.name} wants ${typeKey(port.type)} but ${id} is ${typeKey(supplied.type)}`,+ id,+ );+ }+ }++ for (const goal of plan.goals) {+ const supplied = records.get(goal.record);+ invariant(supplied !== undefined, "UNKNOWN_GOAL", `goal references ${goal.record}`, goal.record);+ invariant(+ sameType(supplied.type, goal.type),+ "GOAL_TYPE_MISMATCH",+ `goal wants ${typeKey(goal.type)} but ${goal.record} is ${typeKey(supplied.type)}`,+ goal.record,+ );+ }++ assertAcyclic(plan, records);+ assertAllStepsReachGoal(plan, records);+}++function assertAcyclic(plan: BuildPlan, records: ReadonlyMap<RecordId, ProducedRecord>): void {+ const dependencies = new Map<string, Set<string>>();+ for (const step of plan.steps) dependencies.set(step.id, new Set());+ for (const step of plan.steps) {+ const own = dependencies.get(step.id) as Set<string>;+ for (const input of Object.values(step.inputs)) {+ const producer = records.get(input)?.step;+ if (producer !== undefined) own.add(producer);+ }+ }++ const complete = new Set<string>();+ while (complete.size < plan.steps.length) {+ const ready = [...dependencies.entries()]+ .filter(([id, required]) => !complete.has(id) && [...required].every((item) => complete.has(item)))+ .map(([id]) => id);+ invariant(ready.length > 0, "PLAN_CYCLE", "build plan contains a producer cycle");+ ready.forEach((id) => complete.add(id));+ }+}++function assertAllStepsReachGoal(+ plan: BuildPlan,+ records: ReadonlyMap<RecordId, ProducedRecord>,+): void {+ const steps = new Map(plan.steps.map((step) => [step.id, step]));+ const required = new Set<string>();+ const queue = plan.goals+ .map((goal) => records.get(goal.record)?.step)+ .filter((step): step is string => step !== undefined);++ while (queue.length > 0) {+ const id = queue.pop() as string;+ if (required.has(id)) continue;+ required.add(id);+ const step = steps.get(id);+ invariant(step !== undefined, "UNKNOWN_STEP", `unknown step ${id}`, id);+ for (const input of Object.values(step.inputs)) {+ const dependency = records.get(input)?.step;+ if (dependency !== undefined) queue.push(dependency);+ }+ }++ for (const step of plan.steps) {+ invariant(+ required.has(step.id),+ "UNREACHABLE_STEP",+ `${step.id} does not contribute to any build goal`,+ step.id,+ );+ }+}++export function producerStep(plan: BuildPlan, id: string): ProducerStep {+ const step = plan.steps.find((item) => item.id === id);+ invariant(step !== undefined, "UNKNOWN_STEP", `unknown step ${id}`, id);+ return step;+}diff --git a/packages/core/src/reducer.ts b/packages/core/src/reducer.tsnew file mode 100644index 00000000..1f80369d--- /dev/null+++ b/packages/core/src/reducer.ts@@ -0,0 +1,387 @@+import type {+ BuildEvent,+ BuildPlan,+ BuildState,+ CanonicalValue,+ Conformance,+ CoreCommand,+ CoreTransition,+ Derivation,+ FulfillNeedCommand,+ InvokeProducerCommand,+ LinkedProgram,+ Need,+ NeedFulfilledEvent,+ ProducerCompletedEvent,+ Receipt,+ StoredValue,+ TypedRecord,+} from "@svml/protocol";++import { canonicalize, digestOf, recordDigest } from "./canonical.js";+import { CoreError, invariant } from "./error.js";+import { resolveProducer, resolveType, sealRecord } from "./link.js";+import { producerStep, validatePlan } from "./plan.js";+import { producerKey } from "./reference.js";+import { validateStoredValue } from "./schema.js";+import { verifyBuildState } from "./verify.js";++function commandId(build: string, kind: string, subject: string): string {+ return `command:${digestOf({ build, kind, subject })}`;+}++function eventDigest(event: BuildEvent): ReturnType<typeof digestOf> {+ return digestOf(event);+}++function withoutCommand(state: BuildState, id: string): readonly CoreCommand[] {+ return state.outstanding.filter((command) => command.id !== id);+}++function addAcceptedEvent(state: BuildState, event: BuildEvent): BuildState["acceptedEvents"] {+ return [...state.acceptedEvents, { id: event.id, digest: eventDigest(event) }];+}++function inheritedConformance(records: readonly TypedRecord[]): Conformance {+ return records.some((record) => record.conformance === "substitute") ? "substitute" : "exact";+}++function inputRecords(state: BuildState, command: InvokeProducerCommand): TypedRecord[] {+ return Object.values(command.inputs).map((id) => {+ const record = state.records.find((item) => item.id === id);+ invariant(record !== undefined, "MISSING_INPUT", `${command.step} input ${id} is missing`, id);+ return record;+ });+}++function normalizeStoredValue(value: StoredValue): StoredValue {+ if (value.kind === "inline") {+ return { kind: "inline", value: canonicalize(value.value) };+ }+ invariant(Number.isSafeInteger(value.size) && value.size >= 0, "INVALID_BLOB", "blob size is invalid");+ return { ...value };+}++function exactPortKeys(+ actual: Readonly<Record<string, unknown>>,+ expected: readonly string[],+ subject: string,+): void {+ const left = Object.keys(actual).sort();+ const right = [...expected].sort();+ invariant(+ JSON.stringify(left) === JSON.stringify(right),+ "PRODUCER_RESULT_PORT_MISMATCH",+ `${subject} returned [${left.join(", ")}] but must return [${right.join(", ")}]`,+ subject,+ );+}++function acceptProducerEvent(+ state: BuildState,+ command: InvokeProducerCommand,+ event: ProducerCompletedEvent,+): BuildState {+ const step = producerStep(state.plan, command.step);+ const stepState = state.steps.find((item) => item.id === step.id);+ invariant(stepState?.status === "pending", "STEP_ALREADY_COMPLETE", `${step.id} is already complete`, step.id);+ const producer = resolveProducer(state.program.closure, step.producer);+ exactPortKeys(event.outputs, producer.outputs.map((port) => port.name), `${step.id}.outputs`);+ exactPortKeys(event.needs, producer.needs.map((port) => port.name), `${step.id}.needs`);++ const inputs = inputRecords(state, command);+ const conformance = inheritedConformance(inputs);+ const derivationId = `derivation:${digestOf({+ build: state.id,+ command: command.id,+ event: eventDigest(event),+ inputs: inputs.map((record) => ({ id: record.id, digest: record.digest })),+ })}`;++ const outputs: TypedRecord[] = producer.outputs.map((port) => {+ const id = step.outputs[port.name];+ const rawValue = event.outputs[port.name];+ invariant(id !== undefined, "MISSING_OUTPUT_BINDING", `${step.id}.${port.name} is not bound`);+ invariant(rawValue !== undefined, "MISSING_OUTPUT_VALUE", `${step.id}.${port.name} returned no value`);+ const value = normalizeStoredValue(rawValue);+ validateStoredValue(value, resolveType(state.program.closure, port.type).schema, `$output.${step.id}.${port.name}`);+ return sealRecord({+ id,+ type: port.type,+ value,+ conformance,+ origin: { kind: "derived", derivation: derivationId },+ });+ });++ const needs: Need[] = producer.needs.map((port) => {+ const binding = step.needs[port.name];+ const constraints = event.needs[port.name];+ invariant(binding !== undefined, "MISSING_NEED_BINDING", `${step.id}.${port.name} is not bound`);+ invariant(constraints !== undefined, "MISSING_NEED_VALUE", `${step.id}.${port.name} returned no constraints`);+ const normalized = canonicalize(constraints);+ const requestDigest = digestOf({+ wants: port.wants,+ constraints: normalized,+ requestedBy: derivationId,+ result: binding.result,+ accepts: binding.accepts,+ });+ return {+ id: binding.id,+ wants: port.wants,+ constraints: normalized,+ requestedBy: derivationId,+ result: binding.result,+ accepts: binding.accepts,+ requestDigest,+ };+ });++ const derivation: Derivation = {+ id: derivationId,+ step: step.id,+ producer: step.producer,+ implementationDigest: producer.implementation.digest,+ inputs: inputs.map((record) => record.id),+ outputs: outputs.map((record) => record.id),+ needs: needs.map((need) => need.id),+ };++ return {+ ...state,+ records: [...state.records, ...outputs],+ needs: [...state.needs, ...needs],+ derivations: [...state.derivations, derivation],+ steps: state.steps.map((item) =>+ item.id === step.id ? { id: item.id, status: "complete", derivation: derivationId } : item,+ ),+ outstanding: withoutCommand(state, command.id),+ acceptedEvents: addAcceptedEvent(state, event),+ };+}++function acceptNeedEvent(+ state: BuildState,+ command: FulfillNeedCommand,+ event: NeedFulfilledEvent,+): BuildState {+ const need = state.needs.find((item) => item.id === command.need.id);+ invariant(need !== undefined, "UNKNOWN_NEED", `unknown need ${command.need.id}`, command.need.id);+ invariant(+ !state.records.some((record) => record.id === need.result),+ "NEED_ALREADY_FULFILLED",+ `${need.id} is already fulfilled`,+ need.id,+ );+ invariant(+ event.requestDigest === need.requestDigest,+ "REQUEST_DIGEST_MISMATCH",+ `${need.id} fulfillment is for another request`,+ need.id,+ );+ invariant(+ need.accepts === "substitute" || event.conformance === "exact",+ "SUBSTITUTE_NOT_ACCEPTED",+ `${need.id} requires exact fulfillment`,+ need.id,+ );++ const value = normalizeStoredValue(event.value);+ validateStoredValue(value, resolveType(state.program.closure, need.wants).schema, `$need.${need.id}`);+ const outputDigest = recordDigest(need.wants, value);+ const metadata = canonicalize(event.metadata);+ const receiptId = `receipt:${digestOf({+ need: need.id,+ requestDigest: event.requestDigest,+ fulfiller: event.fulfiller,+ conformance: event.conformance,+ delivery: event.delivery,+ output: need.result,+ outputDigest,+ metadata,+ })}`;+ const receipt: Receipt = {+ id: receiptId,+ need: need.id,+ requestDigest: need.requestDigest,+ fulfiller: event.fulfiller,+ conformance: event.conformance,+ delivery: event.delivery,+ output: need.result,+ outputDigest,+ metadata,+ };+ const record: TypedRecord = {+ id: need.result,+ type: need.wants,+ value,+ digest: outputDigest,+ conformance: event.conformance,+ origin: { kind: "observed", receipt: receipt.id },+ };++ return {+ ...state,+ records: [...state.records, record],+ receipts: [...state.receipts, receipt],+ outstanding: withoutCommand(state, command.id),+ acceptedEvents: addAcceptedEvent(state, event),+ };+}++function acceptFailure(state: BuildState, event: BuildEvent & { kind: "command-failed" }): BuildState {+ return {+ ...state,+ status: "failed",+ outstanding: [],+ acceptedEvents: addAcceptedEvent(state, event),+ diagnostics: [+ ...state.diagnostics,+ { code: event.code, message: event.message, subject: event.command },+ ],+ };+}++function applyEvent(state: BuildState, event: BuildEvent): BuildState {+ invariant(event.id.length > 0, "EMPTY_EVENT_ID", "event id is empty");+ const accepted = state.acceptedEvents.find((item) => item.id === event.id);+ if (accepted !== undefined) {+ invariant(+ accepted.digest === eventDigest(event),+ "EVENT_ID_REUSED",+ `${event.id} was already accepted with different content`,+ event.id,+ );+ return state;+ }++ const command = state.outstanding.find((item) => item.id === event.command);+ invariant(command !== undefined, "UNKNOWN_COMMAND", `event references ${event.command}`, event.command);++ if (event.kind === "command-failed") return acceptFailure(state, event);+ if (command.kind === "invoke-producer" && event.kind === "producer-completed") {+ return acceptProducerEvent(state, command, event);+ }+ if (command.kind === "fulfill-need" && event.kind === "need-fulfilled") {+ return acceptNeedEvent(state, command, event);+ }+ throw new CoreError(+ "EVENT_COMMAND_MISMATCH",+ `${event.kind} cannot complete ${command.kind}`,+ command.id,+ );+}++function goalsComplete(state: BuildState): boolean {+ return state.plan.goals.every((goal) => {+ const record = state.records.find((item) => item.id === goal.record);+ if (record === undefined) return false;+ return goal.accepts === "substitute" || record.conformance === "exact";+ });+}++function schedule(state: BuildState): CoreTransition {+ if (state.status !== "active") return { state, commands: [] };+ if (state.outstanding.length > 0) return { state, commands: state.outstanding };++ if (goalsComplete(state)) {+ const complete = {+ ...state,+ status: "complete" as const,+ };+ return {+ state: complete,+ commands: [+ {+ kind: "complete",+ id: commandId(state.id, "complete", state.plan.id),+ goals: state.plan.goals.map((goal) => goal.record),+ },+ ],+ };+ }++ const commands: CoreCommand[] = [];+ for (const need of state.needs) {+ if (state.records.some((record) => record.id === need.result)) continue;+ commands.push({+ kind: "fulfill-need",+ id: commandId(state.id, "need", need.id),+ need,+ });+ }++ for (const stepState of state.steps) {+ if (stepState.status !== "pending") continue;+ const step = producerStep(state.plan, stepState.id);+ if (!Object.values(step.inputs).every((id) => state.records.some((record) => record.id === id))) {+ continue;+ }+ commands.push({+ kind: "invoke-producer",+ id: commandId(state.id, "producer", step.id),+ step: step.id,+ producer: step.producer,+ inputs: step.inputs,+ });+ }++ commands.sort((left, right) => left.id.localeCompare(right.id));+ if (commands.length === 0) {+ const failed: BuildState = {+ ...state,+ status: "failed",+ diagnostics: [+ ...state.diagnostics,+ {+ code: "BUILD_DEADLOCK",+ message: "no command can make progress toward the requested goals",+ },+ ],+ };+ return { state: failed, commands: [] };+ }++ const scheduled: BuildState = { ...state, outstanding: commands };+ return { state: scheduled, commands };+}++export function start(program: LinkedProgram, plan: BuildPlan): BuildState {+ validatePlan(program, plan);+ const state: BuildState = {+ format: "svml.build@0",+ id: digestOf({+ closure: program.closure.digest,+ semantic: program.semanticDigest,+ plan,+ }),+ program,+ plan,+ status: "active",+ records: program.records,+ steps: plan.steps.map((step) => ({ id: step.id, status: "pending" })),+ needs: [],+ receipts: [],+ derivations: [],+ outstanding: [],+ acceptedEvents: [],+ diagnostics: [],+ };+ verifyBuildState(state);+ return state;+}++export function reduce(state: BuildState, event?: BuildEvent): CoreTransition {+ verifyBuildState(state);+ const next = event === undefined ? state : applyEvent(state, event);+ const transition = schedule(next);+ verifyBuildState(transition.state);+ return transition;+}++export function buildCommandKey(command: CoreCommand): string {+ if (command.kind === "invoke-producer") return producerKey(command.producer);+ if (command.kind === "fulfill-need") return command.need.id;+ return command.id;+}diff --git a/packages/core/src/reference.ts b/packages/core/src/reference.tsnew file mode 100644index 00000000..825edbe1--- /dev/null+++ b/packages/core/src/reference.ts@@ -0,0 +1,21 @@+import type { ModuleRef, ProducerRef, TypeRef } from "@svml/protocol";++export function moduleKey(ref: ModuleRef): string {+ return `${ref.name}@${ref.version}`;+}++export function typeKey(ref: TypeRef): string {+ return `${moduleKey(ref.module)}#${ref.name}`;+}++export function producerKey(ref: ProducerRef): string {+ return `${moduleKey(ref.module)}#${ref.name}`;+}++export function sameModule(left: ModuleRef, right: ModuleRef): boolean {+ return left.name === right.name && left.version === right.version;+}++export function sameType(left: TypeRef, right: TypeRef): boolean {+ return sameModule(left.module, right.module) && left.name === right.name;+}diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.tsnew file mode 100644index 00000000..be8569c6--- /dev/null+++ b/packages/core/src/schema.ts@@ -0,0 +1,114 @@+import type { CanonicalValue, StoredValue, ValueSchema } from "@svml/protocol";++import { canonicalStringify, isDigest } from "./canonical.js";+import { CoreError, invariant } from "./error.js";++function fail(path: string, message: string): never {+ throw new CoreError("VALUE_SCHEMA_MISMATCH", `${path} ${message}`, path);+}++function validateInline(value: CanonicalValue, schema: ValueSchema, path: string): void {+ switch (schema.kind) {+ case "null":+ if (value !== null) fail(path, "must be null");+ return;+ case "boolean":+ if (typeof value !== "boolean") fail(path, "must be a boolean");+ return;+ case "number":+ if (typeof value !== "number" || !Number.isFinite(value)) fail(path, "must be a number");+ if (schema.integer === true && !Number.isInteger(value)) fail(path, "must be an integer");+ if (schema.minimum !== undefined && value < schema.minimum) {+ fail(path, `must be >= ${schema.minimum}`);+ }+ if (schema.maximum !== undefined && value > schema.maximum) {+ fail(path, `must be <= ${schema.maximum}`);+ }+ return;+ case "string":+ if (typeof value !== "string") fail(path, "must be a string");+ if (schema.enum !== undefined && !schema.enum.includes(value)) {+ fail(path, `must be one of ${schema.enum.join(", ")}`);+ }+ if (schema.minLength !== undefined && [...value].length < schema.minLength) {+ fail(path, `must contain at least ${schema.minLength} characters`);+ }+ if (schema.maxLength !== undefined && [...value].length > schema.maxLength) {+ fail(path, `must contain at most ${schema.maxLength} characters`);+ }+ return;+ case "literal":+ if (canonicalStringify(value) !== canonicalStringify(schema.value)) {+ fail(path, "does not match the literal value");+ }+ return;+ case "array":+ if (!Array.isArray(value)) fail(path, "must be an array");+ if (schema.minItems !== undefined && value.length < schema.minItems) {+ fail(path, `must contain at least ${schema.minItems} items`);+ }+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {+ fail(path, `must contain at most ${schema.maxItems} items`);+ }+ value.forEach((item, index) => validateInline(item, schema.items, `${path}[${index}]`));+ return;+ case "object": {+ if (value === null || Array.isArray(value) || typeof value !== "object") {+ fail(path, "must be an object");+ }+ const object = value as Readonly<Record<string, CanonicalValue>>;+ for (const [name, field] of Object.entries(schema.fields)) {+ if (!Object.hasOwn(object, name)) {+ if (field.optional !== true) fail(`${path}.${name}`, "is required");+ continue;+ }+ validateInline(object[name] as CanonicalValue, field.schema, `${path}.${name}`);+ }+ if (schema.allowUnknown !== true) {+ for (const name of Object.keys(object)) {+ if (!Object.hasOwn(schema.fields, name)) fail(`${path}.${name}`, "is not declared");+ }+ }+ return;+ }+ case "oneOf": {+ let matches = 0;+ for (const variant of schema.variants) {+ try {+ validateInline(value, variant, path);+ matches += 1;+ } catch (error) {+ if (!(error instanceof CoreError) || error.code !== "VALUE_SCHEMA_MISMATCH") throw error;+ }+ }+ if (matches !== 1) fail(path, `must match exactly one variant, matched ${matches}`);+ return;+ }+ case "blob":+ fail(path, "must be a blob reference");+ }+}++export function validateStoredValue(value: StoredValue, schema: ValueSchema, path = "$value"): void {+ if (schema.kind === "blob") {+ invariant(value.kind === "blob", "VALUE_SCHEMA_MISMATCH", `${path} must be a blob`, path);+ invariant(isDigest(value.digest), "INVALID_BLOB", `${path}.digest is invalid`, path);+ invariant(Number.isSafeInteger(value.size) && value.size >= 0, "INVALID_BLOB", `${path}.size is invalid`);+ invariant(value.mediaType.length > 0, "INVALID_BLOB", `${path}.mediaType is empty`, path);+ if (schema.maxBytes !== undefined) {+ invariant(value.size <= schema.maxBytes, "VALUE_SCHEMA_MISMATCH", `${path} exceeds maxBytes`, path);+ }+ if (schema.mediaTypes !== undefined) {+ invariant(+ schema.mediaTypes.includes(value.mediaType),+ "VALUE_SCHEMA_MISMATCH",+ `${path}.mediaType is not accepted`,+ path,+ );+ }+ return;+ }++ invariant(value.kind === "inline", "VALUE_SCHEMA_MISMATCH", `${path} must be inline`, path);+ validateInline(value.value, schema, path);+}diff --git a/packages/core/src/verify.ts b/packages/core/src/verify.tsnew file mode 100644index 00000000..a14e14c1--- /dev/null+++ b/packages/core/src/verify.ts@@ -0,0 +1,262 @@+import type {+ BuildState,+ CoreCommand,+ Derivation,+ Need,+ Receipt,+ TypedRecord,+} from "@svml/protocol";++import { digestOf, isDigest } from "./canonical.js";+import { invariant } from "./error.js";+import { link, resolveProducer, verifyRecord } from "./link.js";+import { producerStep, validatePlan } from "./plan.js";+import { sameType } from "./reference.js";++function unique<T>(items: readonly T[], key: (item: T) => string, kind: string): void {+ const seen = new Set<string>();+ for (const item of items) {+ const id = key(item);+ invariant(!seen.has(id), "DUPLICATE_STATE_ID", `duplicate ${kind} ${id}`, id);+ seen.add(id);+ }+}++function needDigest(need: Need): ReturnType<typeof digestOf> {+ return digestOf({+ wants: need.wants,+ constraints: need.constraints,+ requestedBy: need.requestedBy,+ result: need.result,+ accepts: need.accepts,+ });+}++function findRecord(state: BuildState, id: string): TypedRecord | undefined {+ return state.records.find((record) => record.id === id);+}++function verifyDerivation(state: BuildState, derivation: Derivation): void {+ const step = producerStep(state.plan, derivation.step);+ const producer = resolveProducer(state.program.closure, derivation.producer);+ invariant(+ step.producer.module.name === derivation.producer.module.name &&+ step.producer.module.version === derivation.producer.module.version &&+ step.producer.name === derivation.producer.name,+ "DERIVATION_PRODUCER_MISMATCH",+ `${derivation.id} does not use its planned producer`,+ derivation.id,+ );+ invariant(+ derivation.implementationDigest === producer.implementation.digest,+ "IMPLEMENTATION_DIGEST_MISMATCH",+ `${derivation.id} implementation digest does not match`,+ derivation.id,+ );+ invariant(+ JSON.stringify([...derivation.inputs].sort()) ===+ JSON.stringify(Object.values(step.inputs).sort()),+ "DERIVATION_INPUT_MISMATCH",+ `${derivation.id} input records do not match its step`,+ derivation.id,+ );+ invariant(+ JSON.stringify([...derivation.outputs].sort()) ===+ JSON.stringify(Object.values(step.outputs).sort()),+ "DERIVATION_OUTPUT_MISMATCH",+ `${derivation.id} output records do not match its step`,+ derivation.id,+ );+ invariant(+ JSON.stringify([...derivation.needs].sort()) ===+ JSON.stringify(Object.values(step.needs).map((binding) => binding.id).sort()),+ "DERIVATION_NEED_MISMATCH",+ `${derivation.id} needs do not match its step`,+ derivation.id,+ );+}++function verifyReceipt(state: BuildState, receipt: Receipt): void {+ const need = state.needs.find((item) => item.id === receipt.need);+ invariant(need !== undefined, "RECEIPT_UNKNOWN_NEED", `${receipt.id} references an unknown need`);+ invariant(+ receipt.requestDigest === need.requestDigest,+ "REQUEST_DIGEST_MISMATCH",+ `${receipt.id} request digest does not match`,+ );+ invariant(+ need.accepts === "substitute" || receipt.conformance === "exact",+ "SUBSTITUTE_NOT_ACCEPTED",+ `${receipt.id} is a forbidden substitute`,+ );+ const record = findRecord(state, receipt.output);+ invariant(record !== undefined, "RECEIPT_OUTPUT_MISSING", `${receipt.id} output is missing`);+ invariant(record.digest === receipt.outputDigest, "RECEIPT_OUTPUT_MISMATCH", `${receipt.id} output differs`);+ invariant(+ record.origin.kind === "observed" && record.origin.receipt === receipt.id,+ "RECEIPT_ORIGIN_MISMATCH",+ `${receipt.id} output has another origin`,+ );+ invariant(+ receipt.id ===+ `receipt:${digestOf({+ need: receipt.need,+ requestDigest: receipt.requestDigest,+ fulfiller: receipt.fulfiller,+ conformance: receipt.conformance,+ delivery: receipt.delivery,+ output: receipt.output,+ outputDigest: receipt.outputDigest,+ metadata: receipt.metadata,+ })}`,+ "RECEIPT_DIGEST_MISMATCH",+ `${receipt.id} content does not match its identity`,+ );+}++function verifyOutstanding(state: BuildState, command: CoreCommand): void {+ if (command.kind === "complete") {+ invariant(false, "STORED_COMPLETE_COMMAND", "complete commands must not remain outstanding");+ }+ if (command.kind === "invoke-producer") {+ const step = state.steps.find((item) => item.id === command.step);+ invariant(step?.status === "pending", "OUTSTANDING_STEP_COMPLETE", `${command.step} is complete`);+ const planned = producerStep(state.plan, command.step);+ invariant(planned.producer.name === command.producer.name, "COMMAND_PRODUCER_MISMATCH", command.id);+ return;+ }+ const need = state.needs.find((item) => item.id === command.need.id);+ invariant(need !== undefined, "OUTSTANDING_NEED_UNKNOWN", `${command.need.id} is unknown`);+ invariant(findRecord(state, need.result) === undefined, "OUTSTANDING_NEED_COMPLETE", `${need.id} is fulfilled`);+}++export function verifyBuildState(state: BuildState): void {+ invariant(state.format === "svml.build@0", "UNSUPPORTED_BUILD", "unsupported build state format");+ invariant(isDigest(state.id), "INVALID_DIGEST", "build id is invalid");++ const linked = link(state.program.closure, state.program.modules);+ invariant(+ linked.semanticDigest === state.program.semanticDigest,+ "PROGRAM_SEMANTIC_DIGEST_MISMATCH",+ "linked program semantic digest does not match",+ );+ invariant(+ JSON.stringify(+ [...linked.records]+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((record) => ({ id: record.id, digest: record.digest })),+ ) ===+ JSON.stringify(+ [...state.program.records]+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((record) => ({ id: record.id, digest: record.digest })),+ ),+ "PROGRAM_RECORD_MISMATCH",+ "linked program records do not match its typed modules",+ );+ invariant(+ state.id ===+ digestOf({+ closure: state.program.closure.digest,+ semantic: state.program.semanticDigest,+ plan: state.plan,+ }),+ "BUILD_ID_MISMATCH",+ "build id does not match its program and plan",+ );+ validatePlan(state.program, state.plan);++ unique(state.records, (item) => item.id, "record");+ unique(state.steps, (item) => item.id, "step state");+ unique(state.needs, (item) => item.id, "need");+ unique(state.receipts, (item) => item.id, "receipt");+ unique(state.derivations, (item) => item.id, "derivation");+ unique(state.outstanding, (item) => item.id, "command");+ unique(state.acceptedEvents, (item) => item.id, "event");++ invariant(+ JSON.stringify(state.steps.map((item) => item.id).sort()) ===+ JSON.stringify(state.plan.steps.map((item) => item.id).sort()),+ "STEP_STATE_MISMATCH",+ "build step state does not match the plan",+ );++ for (const record of state.records) verifyRecord(state.program.closure, record);+ for (const authored of state.program.records) {+ const record = findRecord(state, authored.id);+ invariant(record?.digest === authored.digest, "AUTHORED_RECORD_CHANGED", `${authored.id} changed`);+ }++ for (const record of state.records) {+ if (record.origin.kind === "authored") {+ invariant(+ state.program.records.some((item) => item.id === record.id && item.digest === record.digest),+ "INJECTED_AUTHORED_RECORD",+ `${record.id} was not present in the linked author program`,+ );+ } else if (record.origin.kind === "derived") {+ const origin = record.origin;+ const derivation = state.derivations.find((item) => item.id === origin.derivation);+ invariant(+ derivation !== undefined,+ "DERIVED_ORIGIN_MISMATCH",+ `${record.id} has unknown derivation ${origin.derivation}`,+ );+ invariant(+ derivation.outputs.includes(record.id),+ "DERIVED_ORIGIN_MISMATCH",+ `${record.id} is not an output of ${origin.derivation}`,+ );+ const inputs = derivation.inputs.map((id) => findRecord(state, id));+ invariant(inputs.every((item) => item !== undefined), "DERIVATION_INPUT_MISSING", derivation.id);+ const expected = inputs.some((item) => item?.conformance === "substitute") ? "substitute" : "exact";+ invariant(record.conformance === expected, "CONFORMANCE_NOT_PROPAGATED", `${record.id} conformance differs`);+ } else {+ const origin = record.origin;+ const receipt = state.receipts.find((item) => item.id === origin.receipt);+ invariant(receipt?.output === record.id, "OBSERVED_ORIGIN_MISMATCH", `${record.id} has no receipt`);+ }+ }++ for (const need of state.needs) {+ invariant(need.requestDigest === needDigest(need), "NEED_DIGEST_MISMATCH", `${need.id} digest differs`);+ const derivation = state.derivations.find((item) => item.id === need.requestedBy);+ invariant(derivation?.needs.includes(need.id), "NEED_ORIGIN_MISMATCH", `${need.id} has no derivation`);+ }+ for (const receipt of state.receipts) verifyReceipt(state, receipt);+ for (const derivation of state.derivations) verifyDerivation(state, derivation);++ for (const stepState of state.steps) {+ if (stepState.status === "complete") {+ invariant(stepState.derivation !== undefined, "COMPLETE_STEP_NO_DERIVATION", stepState.id);+ invariant(+ state.derivations.some((item) => item.id === stepState.derivation && item.step === stepState.id),+ "STEP_DERIVATION_MISMATCH",+ stepState.id,+ );+ }+ }++ for (const command of state.outstanding) verifyOutstanding(state, command);+ for (const event of state.acceptedEvents) {+ invariant(event.id.length > 0, "EMPTY_EVENT_ID", "accepted event id is empty");+ invariant(isDigest(event.digest), "INVALID_DIGEST", `${event.id} digest is invalid`);+ }++ if (state.status === "complete") {+ invariant(state.outstanding.length === 0, "COMPLETE_WITH_COMMANDS", "complete build has commands");+ for (const goal of state.plan.goals) {+ const record = findRecord(state, goal.record);+ invariant(record !== undefined, "COMPLETE_GOAL_MISSING", `${goal.record} is missing`);+ invariant(sameType(record.type, goal.type), "COMPLETE_GOAL_TYPE_MISMATCH", goal.record);+ invariant(+ goal.accepts === "substitute" || record.conformance === "exact",+ "COMPLETE_GOAL_SUBSTITUTE",+ goal.record,+ );+ }+ }+ if (state.status === "failed") {+ invariant(state.diagnostics.length > 0, "FAILED_WITHOUT_DIAGNOSTIC", "failed build has no diagnostic");+ }+}diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.tsnew file mode 100644index 00000000..5d0015c6--- /dev/null+++ b/packages/core/test/core.test.ts@@ -0,0 +1,218 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ CoreError,+ canonicalize,+ reduce,+ start,+ validatePlan,+ verifyBuildState,+} from "@svml/core";+import type {+ BuildEvent,+ BuildState,+ FulfillNeedCommand,+ InvokeProducerCommand,+} from "@svml/protocol";++import { createGreetingBuild, producers } from "./greeting-fixture.js";++function onlyProducer(state: BuildState): { state: BuildState; command: InvokeProducerCommand } {+ const transition = reduce(state);+ assert.equal(transition.commands.length, 1);+ const command = transition.commands[0];+ assert.equal(command?.kind, "invoke-producer");+ return { state: transition.state, command: command as InvokeProducerCommand };+}++function producerEvent(+ command: InvokeProducerCommand,+ id: string,+ outputs: Record<string, { readonly kind: "inline"; readonly value: string | { readonly text: string } }>,+ needs: Record<string, string | { readonly prompt: string }> = {},+): BuildEvent {+ return {+ kind: "producer-completed",+ id,+ command: command.id,+ outputs,+ needs,+ };+}++function reachNeed(initial = createGreetingBuild()): {+ state: BuildState;+ command: FulfillNeedCommand;+} {+ let current = onlyProducer(initial);+ let transition = reduce(+ current.state,+ producerEvent(current.command, "event:prompt", {+ prompt: { kind: "inline", value: "Greet Ada" },+ }),+ );+ const request = transition.commands.find(+ (command): command is InvokeProducerCommand => command.kind === "invoke-producer",+ );+ assert.ok(request);+ transition = reduce(+ transition.state,+ producerEvent(request, "event:request", {}, { generation: { prompt: "Greet Ada" } }),+ );+ const command = transition.commands.find(+ (item): item is FulfillNeedCommand => item.kind === "fulfill-need",+ );+ assert.ok(command);+ return { state: transition.state, command };+}++test("Core executes an explicit finite plan through Need, Receipt and completion", () => {+ let current = reachNeed();+ let transition = reduce(current.state, {+ kind: "need-fulfilled",+ id: "event:fulfill",+ command: current.command.id,+ value: { kind: "inline", value: "Hello, Ada!" },+ requestDigest: current.command.need.requestDigest,+ fulfiller: "test:greeting",+ conformance: "exact",+ delivery: "executed",+ metadata: { model: "fixture" },+ });+ const assemble = transition.commands.find(+ (command): command is InvokeProducerCommand => command.kind === "invoke-producer",+ );+ assert.ok(assemble);+ transition = reduce(+ transition.state,+ producerEvent(assemble, "event:assemble", {+ document: { kind: "inline", value: { text: "Hello, Ada!" } },+ }),+ );++ assert.equal(transition.state.status, "complete");+ assert.equal(transition.commands[0]?.kind, "complete");+ assert.equal(transition.state.derivations.length, 3);+ assert.equal(transition.state.receipts.length, 1);+ assert.equal(transition.state.records.at(-1)?.origin.kind, "derived");+ verifyBuildState(transition.state);+});++test("accepted events are idempotent and conflicting reuse is rejected", () => {+ const initial = onlyProducer(createGreetingBuild());+ const event = producerEvent(initial.command, "event:stable", {+ prompt: { kind: "inline", value: "Greet Ada" },+ });+ const accepted = reduce(initial.state, event);+ const replayed = reduce(accepted.state, event);+ assert.deepEqual(replayed.state, accepted.state);+ assert.deepEqual(replayed.commands, accepted.commands);++ assert.throws(+ () =>+ reduce(+ accepted.state,+ producerEvent(initial.command, "event:stable", {+ prompt: { kind: "inline", value: "Different" },+ }),+ ),+ (error: unknown) => error instanceof CoreError && error.code === "EVENT_ID_REUSED",+ );+});++test("schema-invalid producer output is rejected before it becomes a Record", () => {+ const initial = onlyProducer(createGreetingBuild());+ assert.throws(+ () =>+ reduce(initial.state, {+ kind: "producer-completed",+ id: "event:invalid",+ command: initial.command.id,+ outputs: { prompt: { kind: "inline", value: 42 } },+ needs: {},+ }),+ (error: unknown) => error instanceof CoreError && error.code === "VALUE_SCHEMA_MISMATCH",+ );+});++test("an exact Need rejects a substitute fulfillment", () => {+ const current = reachNeed();+ assert.throws(+ () =>+ reduce(current.state, {+ kind: "need-fulfilled",+ id: "event:substitute",+ command: current.command.id,+ value: { kind: "inline", value: "Placeholder" },+ requestDigest: current.command.need.requestDigest,+ fulfiller: "test:placeholder",+ conformance: "substitute",+ delivery: "provided",+ metadata: {},+ }),+ (error: unknown) => error instanceof CoreError && error.code === "SUBSTITUTE_NOT_ACCEPTED",+ );+});++test("serialized BuildState survives a JSON round trip", () => {+ const current = reachNeed();+ const restored = JSON.parse(JSON.stringify(current.state)) as BuildState;+ verifyBuildState(restored);+ assert.deepEqual(reduce(restored).commands, reduce(current.state).commands);+});++test("authored values cannot be changed inside a resumed BuildState", () => {+ const tampered = structuredClone(createGreetingBuild()) as BuildState;+ const authored = tampered.records[0];+ assert.ok(authored);+ (authored as { value: unknown }).value = { kind: "inline", value: { name: "Mallory" } };+ assert.throws(+ () => verifyBuildState(tampered),+ (error: unknown) =>+ error instanceof CoreError &&+ ["SEMANTIC_DIGEST_MISMATCH", "RECORD_DIGEST_MISMATCH"].includes(error.code),+ );+});++test("an explicit plan cannot hide producer steps unrelated to its goals", () => {+ const state = createGreetingBuild();+ const plan = {+ ...state.plan,+ steps: [+ ...state.plan.steps,+ {+ id: "unused",+ producer: producers.makePrompt,+ inputs: { intent: "intent:root" },+ outputs: { prompt: "prompt:unused" },+ needs: {},+ },+ ],+ };+ assert.throws(+ () => validatePlan(state.program, plan),+ (error: unknown) => error instanceof CoreError && error.code === "UNREACHABLE_STEP",+ );+ assert.throws(() => start(state.program, plan), CoreError);+});++test("canonical values reject accessors and preserve hostile-looking keys as data", () => {+ const source: Record<string, unknown> = {};+ Object.defineProperty(source, "__proto__", {+ value: "data",+ enumerable: true,+ });+ const canonical = canonicalize(source);+ assert.equal(Object.hasOwn(canonical as object, "__proto__"), true);+ assert.equal((canonical as Record<string, unknown>).__proto__, "data");++ const accessor = Object.defineProperty({}, "secret", {+ enumerable: true,+ get: () => "must not execute",+ });+ assert.throws(+ () => canonicalize(accessor),+ (error: unknown) => error instanceof CoreError && error.code === "NON_CANONICAL_ACCESSOR",+ );+});diff --git a/packages/core/test/greeting-fixture.ts b/packages/core/test/greeting-fixture.tsnew file mode 100644index 00000000..c5283861--- /dev/null+++ b/packages/core/test/greeting-fixture.ts@@ -0,0 +1,168 @@+import {+ createResolvedClosure,+ digestOf,+ link,+ sealRecord,+ sealTypedModule,+ start,+} from "@svml/core";+import type {+ BuildPlan,+ BuildState,+ ModuleManifest,+ ProducerRef,+ TypeRef,+} from "@svml/protocol";++export const moduleRef = { name: "example.greeting", version: "0.0.0" } as const;++export const types = {+ intent: { module: moduleRef, name: "GreetingIntent" },+ prompt: { module: moduleRef, name: "TextPrompt" },+ generated: { module: moduleRef, name: "GeneratedText" },+ document: { module: moduleRef, name: "GreetingDocument" },+} satisfies Record<string, TypeRef>;++export const producers = {+ makePrompt: { module: moduleRef, name: "make-prompt" },+ requestText: { module: moduleRef, name: "request-text" },+ assemble: { module: moduleRef, name: "assemble" },+} satisfies Record<string, ProducerRef>;++export const implementationDigests = {+ makePrompt: digestOf("example.greeting/make-prompt@0"),+ requestText: digestOf("example.greeting/request-text@0"),+ assemble: digestOf("example.greeting/assemble@0"),+};++export const manifest: ModuleManifest = {+ format: "svml.module@0",+ name: moduleRef.name,+ version: moduleRef.version,+ dependencies: [],+ types: [+ {+ name: types.intent.name,+ schema: {+ kind: "object",+ fields: {+ name: { schema: { kind: "string", minLength: 1 } },+ },+ },+ },+ { name: types.prompt.name, schema: { kind: "string", minLength: 1 } },+ { name: types.generated.name, schema: { kind: "string", minLength: 1 } },+ {+ name: types.document.name,+ schema: {+ kind: "object",+ fields: {+ text: { schema: { kind: "string", minLength: 1 } },+ },+ },+ },+ ],+ producers: [+ {+ name: producers.makePrompt.name,+ inputs: [{ name: "intent", type: types.intent }],+ outputs: [{ name: "prompt", type: types.prompt }],+ needs: [],+ implementation: {+ kind: "registered",+ locator: "example.greeting/make-prompt",+ digest: implementationDigests.makePrompt,+ },+ },+ {+ name: producers.requestText.name,+ inputs: [{ name: "prompt", type: types.prompt }],+ outputs: [],+ needs: [{ name: "generation", wants: types.generated }],+ implementation: {+ kind: "registered",+ locator: "example.greeting/request-text",+ digest: implementationDigests.requestText,+ },+ },+ {+ name: producers.assemble.name,+ inputs: [{ name: "generated", type: types.generated }],+ outputs: [{ name: "document", type: types.document }],+ needs: [],+ implementation: {+ kind: "registered",+ locator: "example.greeting/assemble",+ digest: implementationDigests.assemble,+ },+ },+ ],+};++export function greetingPlan(options?: {+ readonly needAccepts?: "exact" | "substitute";+ readonly goalAccepts?: "exact" | "substitute";+}): BuildPlan {+ return {+ format: "svml.plan@0",+ id: "greeting",+ steps: [+ {+ id: "make-prompt",+ producer: producers.makePrompt,+ inputs: { intent: "intent:root" },+ outputs: { prompt: "prompt:root" },+ needs: {},+ },+ {+ id: "request-text",+ producer: producers.requestText,+ inputs: { prompt: "prompt:root" },+ outputs: {},+ needs: {+ generation: {+ id: "need:generation",+ result: "generated:root",+ accepts: options?.needAccepts ?? "exact",+ },+ },+ },+ {+ id: "assemble",+ producer: producers.assemble,+ inputs: { generated: "generated:root" },+ outputs: { document: "document:root" },+ needs: {},+ },+ ],+ goals: [+ {+ record: "document:root",+ type: types.document,+ accepts: options?.goalAccepts ?? "exact",+ },+ ],+ };+}++export function createGreetingBuild(options?: Parameters<typeof greetingPlan>[0]): BuildState {+ const closure = createResolvedClosure([manifest]);+ const authored = sealRecord({+ id: "intent:root",+ type: types.intent,+ value: { kind: "inline", value: { name: "Ada" } },+ conformance: "exact",+ origin: {+ kind: "authored",+ sourceDigest: digestOf("source:greeting"),+ frontendClosureDigest: digestOf("frontend:test"),+ sourceName: "greeting.test",+ },+ });+ const typedModule = sealTypedModule({+ id: "author:greeting",+ closureDigest: closure.digest,+ records: [authored],+ });+ return start(link(closure, [typedModule]), greetingPlan(options));+}diff --git a/packages/driver-node/README.md b/packages/driver-node/README.mdnew file mode 100644index 00000000..5f4b8672--- /dev/null+++ b/packages/driver-node/README.md@@ -0,0 +1,11 @@+# `@svml/driver-node`++Experimental Node Host for the v2 Core.++Driver v0 reads explicitly supplied static `svml.module.json` files, runs Host-registered producer+functions, dispatches typed Needs to registered handlers, stores content-addressed bytes and can+serialize or resume Core state.++It deliberately does not load implementation code from a package locator. A future sandboxed+executor must be designed and audited before third-party implementations can run. Frontend and+Import Prologue behavior are also outside this package version.diff --git a/packages/driver-node/package.json b/packages/driver-node/package.jsonnew file mode 100644index 00000000..a7fcd29f--- /dev/null+++ b/packages/driver-node/package.json@@ -0,0 +1,13 @@+{+ "name": "@svml/driver-node",+ "version": "0.0.0-dev",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "dependencies": {+ "@svml/core": "workspace:*",+ "@svml/protocol": "workspace:*"+ }+}diff --git a/packages/driver-node/src/artifacts.ts b/packages/driver-node/src/artifacts.tsnew file mode 100644index 00000000..2f43aa90--- /dev/null+++ b/packages/driver-node/src/artifacts.ts@@ -0,0 +1,25 @@+import { createHash } from "node:crypto";++import type { BlobRef, Digest } from "@svml/protocol";++import type { ArtifactStore } from "./types.js";++export class MemoryArtifactStore implements ArtifactStore {+ readonly #values = new Map<Digest, Uint8Array>();++ async put(bytes: Uint8Array, mediaType: string): Promise<BlobRef> {+ const copy = Uint8Array.from(bytes);+ const digest = `sha256:${createHash("sha256").update(copy).digest("hex")}` as Digest;+ this.#values.set(digest, copy);+ return { kind: "blob", digest, size: copy.byteLength, mediaType };+ }++ async get(digest: Digest): Promise<Uint8Array | undefined> {+ const value = this.#values.get(digest);+ return value === undefined ? undefined : Uint8Array.from(value);+ }++ async has(digest: Digest): Promise<boolean> {+ return this.#values.has(digest);+ }+}diff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.tsnew file mode 100644index 00000000..dd876bf5--- /dev/null+++ b/packages/driver-node/src/driver.ts@@ -0,0 +1,218 @@+import { digestOf, reduce, resolveProducer } from "@svml/core";+import type {+ BuildEvent,+ BuildState,+ CoreCommand,+ FulfillNeedCommand,+ InvokeProducerCommand,+ TypedRecord,+} from "@svml/protocol";++import { MemoryArtifactStore } from "./artifacts.js";+import { HostRegistry, producerRegistryKey, requirementRegistryKey } from "./registry.js";+import type {+ ArtifactStore,+ BlockedCommand,+ DriverJournalEntry,+ DriverRunResult,+ ProducerHandlerResult,+ RequirementHandlerResult,+} from "./types.js";++export type NodeDriverOptions = {+ readonly registry?: HostRegistry;+ readonly artifacts?: ArtifactStore;+ readonly maxEvents?: number;+};++type Executable =+ | {+ readonly command: InvokeProducerCommand;+ readonly run: () => Promise<ProducerHandlerResult>;+ }+ | {+ readonly command: FulfillNeedCommand;+ readonly run: () => Promise<RequirementHandlerResult>;+ };++export class NodeDriver {+ readonly registry: HostRegistry;+ readonly artifacts: ArtifactStore;+ readonly maxEvents: number;++ constructor(options: NodeDriverOptions = {}) {+ this.registry = options.registry ?? new HostRegistry();+ this.artifacts = options.artifacts ?? new MemoryArtifactStore();+ this.maxEvents = options.maxEvents ?? 1_000;+ }++ #producerInputs(state: BuildState, command: InvokeProducerCommand): Record<string, TypedRecord> {+ const inputs: Record<string, TypedRecord> = {};+ for (const [port, id] of Object.entries(command.inputs)) {+ const record = state.records.find((item) => item.id === id);+ if (record === undefined) throw new Error(`${command.id} input ${id} is missing`);+ Object.defineProperty(inputs, port, {+ value: structuredClone(record),+ enumerable: true,+ configurable: true,+ writable: true,+ });+ }+ return inputs;+ }++ #classify(+ state: BuildState,+ command: CoreCommand,+ ): { readonly executable?: Executable; readonly blocked?: BlockedCommand } {+ if (command.kind === "complete") return {};+ if (command.kind === "invoke-producer") {+ const registration = this.registry.producer(command.producer);+ if (registration === undefined) {+ return {+ blocked: {+ command: command.id,+ reason: "missing-producer",+ subject: producerRegistryKey(command.producer),+ },+ };+ }+ const declaration = resolveProducer(state.program.closure, command.producer);+ if (registration.implementationDigest !== declaration.implementation.digest) {+ return {+ blocked: {+ command: command.id,+ reason: "implementation-mismatch",+ subject: producerRegistryKey(command.producer),+ },+ };+ }+ return {+ executable: {+ command,+ run: async () =>+ registration.handler({+ command: structuredClone(command),+ producer: structuredClone(command.producer),+ inputs: this.#producerInputs(state, command),+ artifacts: this.artifacts,+ }),+ },+ };+ }++ const registration = this.registry.requirement(command.need.wants);+ if (registration === undefined) {+ return {+ blocked: {+ command: command.id,+ reason: "missing-handler",+ subject: requirementRegistryKey(command.need.wants),+ },+ };+ }+ return {+ executable: {+ command,+ run: async () =>+ registration.handler({+ command: structuredClone(command),+ need: structuredClone(command.need),+ artifacts: this.artifacts,+ }),+ },+ };+ }++ async #execute(executable: Executable): Promise<BuildEvent> {+ if (executable.command.kind === "invoke-producer") {+ const result = (await executable.run()) as ProducerHandlerResult;+ return {+ kind: "producer-completed",+ id: `event:${digestOf({+ kind: "producer-completed",+ command: executable.command.id,+ result,+ })}`,+ command: executable.command.id,+ outputs: result.outputs,+ needs: result.needs,+ };+ }++ const result = (await executable.run()) as RequirementHandlerResult;+ return {+ kind: "need-fulfilled",+ id: `event:${digestOf({+ kind: "need-fulfilled",+ command: executable.command.id,+ result,+ })}`,+ command: executable.command.id,+ value: result.value,+ requestDigest: executable.command.need.requestDigest,+ fulfiller: result.fulfiller,+ conformance: result.conformance,+ delivery: result.delivery,+ metadata: result.metadata,+ };+ }++ async run(initial: BuildState): Promise<DriverRunResult> {+ let state = initial;+ const journal: DriverJournalEntry[] = [];++ for (let processed = 0; processed < this.maxEvents; processed += 1) {+ const transition = reduce(state);+ state = transition.state;+ if (state.status === "complete") {+ return { status: "complete", state, journal, blocked: [] };+ }+ if (state.status === "failed") {+ return { status: "failed", state, journal, blocked: [] };+ }++ const classifications = transition.commands.map((command) => ({+ command,+ ...this.#classify(state, command),+ }));+ const selected = classifications.find((item) => item.executable !== undefined)?.executable;+ if (selected === undefined) {+ const blocked = classifications+ .map((item) => item.blocked)+ .filter((item): item is BlockedCommand => item !== undefined);+ journal.push(+ ...blocked.map((item) => ({+ command: item.command,+ kind: transition.commands.find((command) => command.id === item.command)?.kind ?? "fulfill-need",+ status: "blocked" as const,+ message: `${item.reason}: ${item.subject}`,+ })),+ );+ return { status: "paused", state, journal, blocked };+ }++ try {+ const event = await this.#execute(selected);+ const accepted = reduce(state, event);+ state = accepted.state;+ journal.push({+ command: selected.command.id,+ kind: selected.command.kind,+ status: "completed",+ event: event.id,+ });+ } catch (error) {+ journal.push({+ command: selected.command.id,+ kind: selected.command.kind,+ status: "error",+ message: error instanceof Error ? error.message : String(error),+ });+ return { status: "paused", state, journal, blocked: [] };+ }+ }++ return { status: "paused", state, journal, blocked: [] };+ }+}diff --git a/packages/driver-node/src/index.ts b/packages/driver-node/src/index.tsnew file mode 100644index 00000000..b97338e2--- /dev/null+++ b/packages/driver-node/src/index.ts@@ -0,0 +1,15 @@+export { MemoryArtifactStore } from "./artifacts.js";+export { NodeDriver } from "./driver.js";+export {+ loadModuleManifest,+ loadResolvedClosure,+ parseModuleManifest,+ parseModuleManifestText,+} from "./manifest.js";+export { parseBuildState, serializeBuildState } from "./persistence.js";+export {+ HostRegistry,+ producerRegistryKey,+ requirementRegistryKey,+} from "./registry.js";+export type * from "./types.js";diff --git a/packages/driver-node/src/manifest.ts b/packages/driver-node/src/manifest.tsnew file mode 100644index 00000000..481c3c32--- /dev/null+++ b/packages/driver-node/src/manifest.ts@@ -0,0 +1,249 @@+import { readFile } from "node:fs/promises";++import { canonicalize, createResolvedClosure, isDigest } from "@svml/core";+import type {+ Digest,+ ImplementationRef,+ ModuleDependency,+ ModuleManifest,+ ModuleRef,+ NeedPortDeclaration,+ ObjectFieldSchema,+ PortDeclaration,+ ProducerDeclaration,+ ResolvedModuleClosure,+ TypeDeclaration,+ TypeRef,+ ValueSchema,+} from "@svml/protocol";++function object(value: unknown, path: string): Record<string, unknown> {+ if (value === null || Array.isArray(value) || typeof value !== "object") {+ throw new Error(`${path} must be an object`);+ }+ return value as Record<string, unknown>;+}++function array(value: unknown, path: string): unknown[] {+ if (!Array.isArray(value)) throw new Error(`${path} must be an array`);+ return value;+}++function string(value: unknown, path: string): string {+ if (typeof value !== "string" || value.length === 0) throw new Error(`${path} must be a string`);+ return value;+}++function boolean(value: unknown, path: string): boolean {+ if (typeof value !== "boolean") throw new Error(`${path} must be a boolean`);+ return value;+}++function number(value: unknown, path: string): number {+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${path} must be a number`);+ return value;+}++function digest(value: unknown, path: string): Digest {+ const parsed = string(value, path);+ if (!isDigest(parsed)) throw new Error(`${path} must be a sha256 digest`);+ return parsed;+}++function moduleRef(value: unknown, path: string): ModuleRef {+ const parsed = object(value, path);+ return {+ name: string(parsed.name, `${path}.name`),+ version: string(parsed.version, `${path}.version`),+ };+}++function typeRef(value: unknown, path: string): TypeRef {+ const parsed = object(value, path);+ return {+ module: moduleRef(parsed.module, `${path}.module`),+ name: string(parsed.name, `${path}.name`),+ };+}++function optionalNumber(+ parsed: Record<string, unknown>,+ name: string,+ path: string,+): { readonly [key: string]: number } {+ return parsed[name] === undefined ? {} : { [name]: number(parsed[name], `${path}.${name}`) };+}++function valueSchema(value: unknown, path: string): ValueSchema {+ const parsed = object(value, path);+ const kind = string(parsed.kind, `${path}.kind`);+ switch (kind) {+ case "null":+ case "boolean":+ return { kind };+ case "number":+ return {+ kind,+ ...(parsed.integer === undefined ? {} : { integer: boolean(parsed.integer, `${path}.integer`) }),+ ...optionalNumber(parsed, "minimum", path),+ ...optionalNumber(parsed, "maximum", path),+ } as ValueSchema;+ case "string":+ return {+ kind,+ ...(parsed.enum === undefined+ ? {}+ : { enum: array(parsed.enum, `${path}.enum`).map((item, index) => string(item, `${path}.enum[${index}]`)) }),+ ...optionalNumber(parsed, "minLength", path),+ ...optionalNumber(parsed, "maxLength", path),+ } as ValueSchema;+ case "literal":+ return { kind, value: canonicalize(parsed.value) };+ case "array":+ return {+ kind,+ items: valueSchema(parsed.items, `${path}.items`),+ ...optionalNumber(parsed, "minItems", path),+ ...optionalNumber(parsed, "maxItems", path),+ } as ValueSchema;+ case "object": {+ const rawFields = object(parsed.fields, `${path}.fields`);+ const fields: Record<string, ObjectFieldSchema> = {};+ for (const [name, rawField] of Object.entries(rawFields)) {+ const field = object(rawField, `${path}.fields.${name}`);+ Object.defineProperty(fields, name, {+ value: {+ schema: valueSchema(field.schema, `${path}.fields.${name}.schema`),+ ...(field.optional === undefined+ ? {}+ : { optional: boolean(field.optional, `${path}.fields.${name}.optional`) }),+ },+ enumerable: true,+ configurable: true,+ writable: true,+ });+ }+ return {+ kind,+ fields,+ ...(parsed.allowUnknown === undefined+ ? {}+ : { allowUnknown: boolean(parsed.allowUnknown, `${path}.allowUnknown`) }),+ };+ }+ case "oneOf":+ return {+ kind,+ variants: array(parsed.variants, `${path}.variants`).map((item, index) =>+ valueSchema(item, `${path}.variants[${index}]`),+ ),+ };+ case "blob":+ return {+ kind,+ ...(parsed.mediaTypes === undefined+ ? {}+ : {+ mediaTypes: array(parsed.mediaTypes, `${path}.mediaTypes`).map((item, index) =>+ string(item, `${path}.mediaTypes[${index}]`),+ ),+ }),+ ...optionalNumber(parsed, "maxBytes", path),+ } as ValueSchema;+ default:+ throw new Error(`${path}.kind ${kind} is unsupported`);+ }+}++function dependency(value: unknown, path: string): ModuleDependency {+ const parsed = object(value, path);+ return {+ module: moduleRef(parsed.module, `${path}.module`),+ digest: digest(parsed.digest, `${path}.digest`),+ };+}++function typeDeclaration(value: unknown, path: string): TypeDeclaration {+ const parsed = object(value, path);+ return {+ name: string(parsed.name, `${path}.name`),+ schema: valueSchema(parsed.schema, `${path}.schema`),+ ...(parsed.description === undefined+ ? {}+ : { description: string(parsed.description, `${path}.description`) }),+ };+}++function port(value: unknown, path: string): PortDeclaration {+ const parsed = object(value, path);+ return {+ name: string(parsed.name, `${path}.name`),+ type: typeRef(parsed.type, `${path}.type`),+ };+}++function needPort(value: unknown, path: string): NeedPortDeclaration {+ const parsed = object(value, path);+ return {+ name: string(parsed.name, `${path}.name`),+ wants: typeRef(parsed.wants, `${path}.wants`),+ };+}++function implementation(value: unknown, path: string): ImplementationRef {+ const parsed = object(value, path);+ return {+ kind: string(parsed.kind, `${path}.kind`),+ locator: string(parsed.locator, `${path}.locator`),+ digest: digest(parsed.digest, `${path}.digest`),+ };+}++function producer(value: unknown, path: string): ProducerDeclaration {+ const parsed = object(value, path);+ return {+ name: string(parsed.name, `${path}.name`),+ inputs: array(parsed.inputs, `${path}.inputs`).map((item, index) =>+ port(item, `${path}.inputs[${index}]`),+ ),+ outputs: array(parsed.outputs, `${path}.outputs`).map((item, index) =>+ port(item, `${path}.outputs[${index}]`),+ ),+ needs: array(parsed.needs, `${path}.needs`).map((item, index) =>+ needPort(item, `${path}.needs[${index}]`),+ ),+ implementation: implementation(parsed.implementation, `${path}.implementation`),+ };+}++export function parseModuleManifest(value: unknown): ModuleManifest {+ const parsed = object(canonicalize(value), "$manifest");+ if (parsed.format !== "svml.module@0") throw new Error("$manifest.format must be svml.module@0");+ return {+ format: "svml.module@0",+ name: string(parsed.name, "$manifest.name"),+ version: string(parsed.version, "$manifest.version"),+ dependencies: array(parsed.dependencies, "$manifest.dependencies").map((item, index) =>+ dependency(item, `$manifest.dependencies[${index}]`),+ ),+ types: array(parsed.types, "$manifest.types").map((item, index) =>+ typeDeclaration(item, `$manifest.types[${index}]`),+ ),+ producers: array(parsed.producers, "$manifest.producers").map((item, index) =>+ producer(item, `$manifest.producers[${index}]`),+ ),+ };+}++export function parseModuleManifestText(text: string): ModuleManifest {+ return parseModuleManifest(JSON.parse(text) as unknown);+}++export async function loadModuleManifest(path: string): Promise<ModuleManifest> {+ return parseModuleManifestText(await readFile(path, "utf8"));+}++export async function loadResolvedClosure(paths: readonly string[]): Promise<ResolvedModuleClosure> {+ const manifests = await Promise.all(paths.map(async (path) => loadModuleManifest(path)));+ return createResolvedClosure(manifests);+}diff --git a/packages/driver-node/src/persistence.ts b/packages/driver-node/src/persistence.tsnew file mode 100644index 00000000..e4c2533f--- /dev/null+++ b/packages/driver-node/src/persistence.ts@@ -0,0 +1,13 @@+import { canonicalStringify, verifyBuildState } from "@svml/core";+import type { BuildState } from "@svml/protocol";++export function serializeBuildState(state: BuildState): string {+ verifyBuildState(state);+ return canonicalStringify(state);+}++export function parseBuildState(text: string): BuildState {+ const value = JSON.parse(text) as BuildState;+ verifyBuildState(value);+ return value;+}diff --git a/packages/driver-node/src/registry.ts b/packages/driver-node/src/registry.tsnew file mode 100644index 00000000..da418a10--- /dev/null+++ b/packages/driver-node/src/registry.ts@@ -0,0 +1,49 @@+import type { Digest, ProducerRef, TypeRef } from "@svml/protocol";++import type {+ ProducerHandler,+ ProducerRegistration,+ RequirementHandler,+ RequirementRegistration,+} from "./types.js";++function moduleKey(ref: { readonly name: string; readonly version: string }): string {+ return `${ref.name}@${ref.version}`;+}++export function producerRegistryKey(ref: ProducerRef): string {+ return `${moduleKey(ref.module)}#${ref.name}`;+}++export function requirementRegistryKey(ref: TypeRef): string {+ return `${moduleKey(ref.module)}#${ref.name}`;+}++export class HostRegistry {+ readonly #producers = new Map<string, ProducerRegistration>();+ readonly #requirements = new Map<string, RequirementRegistration>();++ registerProducer(+ producer: ProducerRef,+ implementationDigest: Digest,+ handler: ProducerHandler,+ ): void {+ const key = producerRegistryKey(producer);+ if (this.#producers.has(key)) throw new Error(`producer ${key} is already registered`);+ this.#producers.set(key, { producer, implementationDigest, handler });+ }++ registerRequirement(type: TypeRef, handler: RequirementHandler): void {+ const key = requirementRegistryKey(type);+ if (this.#requirements.has(key)) throw new Error(`requirement ${key} is already registered`);+ this.#requirements.set(key, { type, handler });+ }++ producer(ref: ProducerRef): ProducerRegistration | undefined {+ return this.#producers.get(producerRegistryKey(ref));+ }++ requirement(ref: TypeRef): RequirementRegistration | undefined {+ return this.#requirements.get(requirementRegistryKey(ref));+ }+}diff --git a/packages/driver-node/src/types.ts b/packages/driver-node/src/types.tsnew file mode 100644index 00000000..eee874c6--- /dev/null+++ b/packages/driver-node/src/types.ts@@ -0,0 +1,88 @@+import type {+ BlobRef,+ BuildState,+ CanonicalValue,+ Conformance,+ CoreCommand,+ Delivery,+ Digest,+ FulfillNeedCommand,+ InvokeProducerCommand,+ Need,+ ProducerRef,+ StoredValue,+ TypeRef,+ TypedRecord,+} from "@svml/protocol";++export type ProducerHandlerResult = {+ readonly outputs: Readonly<Record<string, StoredValue>>;+ readonly needs: Readonly<Record<string, CanonicalValue>>;+};++export type ProducerHandlerContext = {+ readonly command: InvokeProducerCommand;+ readonly producer: ProducerRef;+ readonly inputs: Readonly<Record<string, TypedRecord>>;+ readonly artifacts: ArtifactStore;+};++export type ProducerHandler = (+ context: ProducerHandlerContext,+) => ProducerHandlerResult | Promise<ProducerHandlerResult>;++export type RequirementHandlerResult = {+ readonly value: StoredValue;+ readonly fulfiller: string;+ readonly conformance: Conformance;+ readonly delivery: Delivery;+ readonly metadata: CanonicalValue;+};++export type RequirementHandlerContext = {+ readonly command: FulfillNeedCommand;+ readonly need: Need;+ readonly artifacts: ArtifactStore;+};++export type RequirementHandler = (+ context: RequirementHandlerContext,+) => RequirementHandlerResult | Promise<RequirementHandlerResult>;++export type ArtifactStore = {+ put(bytes: Uint8Array, mediaType: string): Promise<BlobRef>;+ get(digest: Digest): Promise<Uint8Array | undefined>;+ has(digest: Digest): Promise<boolean>;+};++export type DriverJournalEntry = {+ readonly command: string;+ readonly kind: CoreCommand["kind"];+ readonly status: "completed" | "blocked" | "error";+ readonly event?: string;+ readonly message?: string;+};++export type BlockedCommand = {+ readonly command: string;+ readonly reason: "missing-producer" | "implementation-mismatch" | "missing-handler";+ readonly subject: string;+};++export type DriverRunResult = {+ readonly status: "complete" | "paused" | "failed";+ readonly state: BuildState;+ readonly journal: readonly DriverJournalEntry[];+ readonly blocked: readonly BlockedCommand[];+};++export type ProducerRegistration = {+ readonly producer: ProducerRef;+ readonly implementationDigest: Digest;+ readonly handler: ProducerHandler;+};++export type RequirementRegistration = {+ readonly type: TypeRef;+ readonly handler: RequirementHandler;+};diff --git a/packages/driver-node/test/driver.test.ts b/packages/driver-node/test/driver.test.tsnew file mode 100644index 00000000..dadde5d6--- /dev/null+++ b/packages/driver-node/test/driver.test.ts@@ -0,0 +1,230 @@+import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import { reduce } from "@svml/core";+import {+ HostRegistry,+ MemoryArtifactStore,+ NodeDriver,+ loadResolvedClosure,+ parseBuildState,+ serializeBuildState,+} from "@svml/driver-node";++import {+ createGreetingBuild,+ implementationDigests,+ manifest,+ producers,+ types,+} from "../../core/test/greeting-fixture.js";++function inlineString(value: unknown): string {+ if (typeof value !== "string") throw new Error("expected inline string");+ return value;+}++type GreetingCalls = {+ prompt: number;+ request: number;+ assemble: number;+ fulfill: number;+};++function configuredRegistry(): {+ registry: HostRegistry;+ calls: GreetingCalls;+} {+ const registry = new HostRegistry();+ const calls = { prompt: 0, request: 0, assemble: 0, fulfill: 0 };++ registry.registerProducer(producers.makePrompt, implementationDigests.makePrompt, ({ inputs }) => {+ calls.prompt += 1;+ const intent = inputs.intent;+ if (intent?.value.kind !== "inline") throw new Error("intent must be inline");+ const value = intent.value.value;+ if (value === null || Array.isArray(value) || typeof value !== "object") {+ throw new Error("intent must be an object");+ }+ const name = inlineString((value as Readonly<Record<string, unknown>>).name);+ return {+ outputs: { prompt: { kind: "inline", value: `Greet ${name}` } },+ needs: {},+ };+ });++ registry.registerProducer(producers.requestText, implementationDigests.requestText, ({ inputs }) => {+ calls.request += 1;+ const prompt = inputs.prompt;+ assert.equal(prompt?.value.kind, "inline");+ return {+ outputs: {},+ needs: { generation: { prompt: inlineString(prompt.value.value) } },+ };+ });++ registry.registerProducer(producers.assemble, implementationDigests.assemble, ({ inputs }) => {+ calls.assemble += 1;+ const generated = inputs.generated;+ assert.equal(generated?.value.kind, "inline");+ return {+ outputs: {+ document: {+ kind: "inline",+ value: { text: inlineString(generated.value.value) },+ },+ },+ needs: {},+ };+ });++ return { registry, calls };+}++test("Driver pauses at an unbound Need, serializes, then resumes without rerunning producers", async () => {+ const { registry, calls } = configuredRegistry();+ const driver = new NodeDriver({ registry });+ const paused = await driver.run(createGreetingBuild());++ assert.equal(paused.status, "paused");+ assert.equal(paused.blocked[0]?.reason, "missing-handler");+ assert.deepEqual(calls, { prompt: 1, request: 1, assemble: 0, fulfill: 0 });++ const restored = parseBuildState(serializeBuildState(paused.state));+ registry.registerRequirement(types.generated, ({ need }) => {+ calls.fulfill += 1;+ assert.deepEqual(need.constraints, { prompt: "Greet Ada" });+ return {+ value: { kind: "inline", value: "Hello, Ada!" },+ fulfiller: "example:generation",+ conformance: "exact",+ delivery: "executed",+ metadata: { provider: "fixture" },+ };+ });++ const completed = await driver.run(restored);+ assert.equal(completed.status, "complete");+ assert.deepEqual(calls, { prompt: 1, request: 1, assemble: 1, fulfill: 1 });+ assert.equal(completed.state.receipts[0]?.delivery, "executed");+ assert.equal(completed.state.records.find((record) => record.id === "document:root")?.conformance, "exact");+});++test("substitute conformance propagates through later producer outputs", async () => {+ const { registry } = configuredRegistry();+ registry.registerRequirement(types.generated, () => ({+ value: { kind: "inline", value: "Placeholder" },+ fulfiller: "example:placeholder",+ conformance: "substitute",+ delivery: "provided",+ metadata: { reason: "preview" },+ }));+ const result = await new NodeDriver({ registry }).run(+ createGreetingBuild({ needAccepts: "substitute", goalAccepts: "substitute" }),+ );+ assert.equal(result.status, "complete");+ assert.equal(result.state.receipts[0]?.conformance, "substitute");+ assert.equal(result.state.records.find((record) => record.id === "document:root")?.conformance, "substitute");+});++test("Driver refuses a registered implementation whose digest differs from the locked closure", async () => {+ const registry = new HostRegistry();+ registry.registerProducer(producers.makePrompt, implementationDigests.assemble, () => ({+ outputs: { prompt: { kind: "inline", value: "wrong implementation" } },+ needs: {},+ }));+ const result = await new NodeDriver({ registry }).run(createGreetingBuild());+ assert.equal(result.status, "paused");+ assert.equal(result.blocked[0]?.reason, "implementation-mismatch");+ assert.equal(result.state.records.length, 1);+});++test("MemoryArtifactStore is content addressed and returns defensive copies", async () => {+ const store = new MemoryArtifactStore();+ const source = new Uint8Array([1, 2, 3]);+ const first = await store.put(source, "application/octet-stream");+ source[0] = 9;+ const second = await store.put(new Uint8Array([1, 2, 3]), "application/octet-stream");+ assert.equal(first.digest, second.digest);+ const loaded = await store.get(first.digest);+ assert.deepEqual(loaded, new Uint8Array([1, 2, 3]));+ if (loaded !== undefined) loaded[0] = 8;+ assert.deepEqual(await store.get(first.digest), new Uint8Array([1, 2, 3]));+});++test("Driver reads static manifests without executing package code", async () => {+ const directory = await mkdtemp(join(tmpdir(), "svml-driver-"));+ const path = join(directory, "svml.module.json");+ try {+ await writeFile(path, JSON.stringify(manifest), "utf8");+ const closure = await loadResolvedClosure([path]);+ assert.equal(closure.modules.length, 1);+ assert.equal(closure.modules[0]?.manifest.name, "example.greeting");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("Core still owns scheduling when Driver has every implementation", async () => {+ const { registry } = configuredRegistry();+ registry.registerRequirement(types.generated, () => ({+ value: { kind: "inline", value: "Hello, Ada!" },+ fulfiller: "example:cache",+ conformance: "exact",+ delivery: "cache",+ metadata: {},+ }));+ const start = createGreetingBuild();+ assert.equal(reduce(start).commands[0]?.kind, "invoke-producer");+ const result = await new NodeDriver({ registry }).run(start);+ assert.equal(result.status, "complete");+ assert.equal(result.state.receipts[0]?.delivery, "cache");+});++test("receipt metadata is covered by its identity during resume validation", async () => {+ const { registry } = configuredRegistry();+ registry.registerRequirement(types.generated, () => ({+ value: { kind: "inline", value: "Hello, Ada!" },+ fulfiller: "example:cache",+ conformance: "exact",+ delivery: "cache",+ metadata: { cacheKey: "stable" },+ }));+ const result = await new NodeDriver({ registry }).run(createGreetingBuild());+ assert.equal(result.status, "complete");+ const tampered = structuredClone(result.state);+ const receipt = tampered.receipts[0];+ assert.ok(receipt);+ (receipt as { metadata: unknown }).metadata = { cacheKey: "changed" };+ assert.throws(() => parseBuildState(JSON.stringify(tampered)), /content does not match its identity/u);+});++test("a transient Handler failure pauses and can resume without replaying completed producers", async () => {+ const { registry, calls } = configuredRegistry();+ let attempts = 0;+ registry.registerRequirement(types.generated, () => {+ calls.fulfill += 1;+ attempts += 1;+ if (attempts === 1) throw new Error("temporary outage");+ return {+ value: { kind: "inline", value: "Hello after retry" },+ fulfiller: "example:unstable",+ conformance: "exact",+ delivery: "executed",+ metadata: { attempt: attempts },+ };+ });++ const driver = new NodeDriver({ registry });+ const paused = await driver.run(createGreetingBuild());+ assert.equal(paused.status, "paused");+ assert.match(paused.journal.at(-1)?.message ?? "", /temporary outage/u);+ assert.deepEqual(calls, { prompt: 1, request: 1, assemble: 0, fulfill: 1 });++ const completed = await driver.run(paused.state);+ assert.equal(completed.status, "complete");+ assert.deepEqual(calls, { prompt: 1, request: 1, assemble: 1, fulfill: 2 });+});diff --git a/packages/protocol/README.md b/packages/protocol/README.mdnew file mode 100644index 00000000..4cd083b4--- /dev/null+++ b/packages/protocol/README.md@@ -0,0 +1,5 @@+# `@svml/protocol`++Data-only v2 bootstrap contracts shared by Core, Drivers and future modules. The package defines+canonical values, module and type references, records and origins, explicit plans, Needs,+Receipts, Derivations, events and commands. It contains no parser, runtime or video vocabulary.diff --git a/packages/protocol/package.json b/packages/protocol/package.jsonnew file mode 100644index 00000000..ca27b921--- /dev/null+++ b/packages/protocol/package.json@@ -0,0 +1,9 @@+{+ "name": "@svml/protocol",+ "version": "0.0.0-dev",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ }+}diff --git a/packages/protocol/src/build.ts b/packages/protocol/src/build.tsnew file mode 100644index 00000000..d0813445--- /dev/null+++ b/packages/protocol/src/build.ts@@ -0,0 +1,217 @@+import type {+ CommandId,+ DerivationId,+ Digest,+ EventId,+ NeedId,+ ProducerRef,+ ReceiptId,+ RecordId,+ StepId,+ TypeRef,+} from "./identity.js";+import type { ResolvedModuleClosure } from "./module.js";+import type { CanonicalValue, StoredValue } from "./value.js";++export type Conformance = "exact" | "substitute";+export type Delivery = "executed" | "cache" | "manual" | "provided";++export type SourceRange = {+ readonly start: number;+ readonly end: number;+};++export type AuthoredOrigin = {+ readonly kind: "authored";+ readonly sourceDigest: Digest;+ readonly frontendClosureDigest: Digest;+ readonly sourceName?: string;+ readonly range?: SourceRange;+};++export type DerivedOrigin = {+ readonly kind: "derived";+ readonly derivation: DerivationId;+};++export type ObservedOrigin = {+ readonly kind: "observed";+ readonly receipt: ReceiptId;+};++export type RecordOrigin = AuthoredOrigin | DerivedOrigin | ObservedOrigin;++export type TypedRecord = {+ readonly id: RecordId;+ readonly type: TypeRef;+ readonly value: StoredValue;+ readonly digest: Digest;+ readonly conformance: Conformance;+ readonly origin: RecordOrigin;+};++export type TypedModule = {+ readonly format: "svml.typed-module@0";+ readonly id: string;+ readonly closureDigest: Digest;+ readonly records: readonly TypedRecord[];+ readonly semanticDigest: Digest;+};++export type NeedAcceptance = "exact" | "substitute";++export type Need = {+ readonly id: NeedId;+ readonly wants: TypeRef;+ readonly constraints: CanonicalValue;+ readonly requestedBy: DerivationId;+ readonly result: RecordId;+ readonly accepts: NeedAcceptance;+ readonly requestDigest: Digest;+};++export type Receipt = {+ readonly id: ReceiptId;+ readonly need: NeedId;+ readonly requestDigest: Digest;+ readonly fulfiller: string;+ readonly conformance: Conformance;+ readonly delivery: Delivery;+ readonly output: RecordId;+ readonly outputDigest: Digest;+ readonly metadata: CanonicalValue;+};++export type Derivation = {+ readonly id: DerivationId;+ readonly step: StepId;+ readonly producer: ProducerRef;+ readonly implementationDigest: Digest;+ readonly inputs: readonly RecordId[];+ readonly outputs: readonly RecordId[];+ readonly needs: readonly NeedId[];+};++export type NeedBinding = {+ readonly id: NeedId;+ readonly result: RecordId;+ readonly accepts: NeedAcceptance;+};++export type ProducerStep = {+ readonly id: StepId;+ readonly producer: ProducerRef;+ readonly inputs: Readonly<Record<string, RecordId>>;+ readonly outputs: Readonly<Record<string, RecordId>>;+ readonly needs: Readonly<Record<string, NeedBinding>>;+};++export type BuildGoal = {+ readonly record: RecordId;+ readonly type: TypeRef;+ readonly accepts: NeedAcceptance;+};++export type BuildPlan = {+ readonly format: "svml.plan@0";+ readonly id: string;+ readonly steps: readonly ProducerStep[];+ readonly goals: readonly BuildGoal[];+};++export type LinkedProgram = {+ readonly closure: ResolvedModuleClosure;+ readonly modules: readonly TypedModule[];+ readonly records: readonly TypedRecord[];+ readonly semanticDigest: Digest;+};++export type StepState = {+ readonly id: StepId;+ readonly status: "pending" | "complete";+ readonly derivation?: DerivationId;+};++export type InvokeProducerCommand = {+ readonly kind: "invoke-producer";+ readonly id: CommandId;+ readonly step: StepId;+ readonly producer: ProducerRef;+ readonly inputs: Readonly<Record<string, RecordId>>;+};++export type FulfillNeedCommand = {+ readonly kind: "fulfill-need";+ readonly id: CommandId;+ readonly need: Need;+};++export type CompleteCommand = {+ readonly kind: "complete";+ readonly id: CommandId;+ readonly goals: readonly RecordId[];+};++export type CoreCommand = InvokeProducerCommand | FulfillNeedCommand | CompleteCommand;++export type ProducerCompletedEvent = {+ readonly kind: "producer-completed";+ readonly id: EventId;+ readonly command: CommandId;+ readonly outputs: Readonly<Record<string, StoredValue>>;+ readonly needs: Readonly<Record<string, CanonicalValue>>;+};++export type NeedFulfilledEvent = {+ readonly kind: "need-fulfilled";+ readonly id: EventId;+ readonly command: CommandId;+ readonly value: StoredValue;+ readonly requestDigest: Digest;+ readonly fulfiller: string;+ readonly conformance: Conformance;+ readonly delivery: Delivery;+ readonly metadata: CanonicalValue;+};++export type CommandFailedEvent = {+ readonly kind: "command-failed";+ readonly id: EventId;+ readonly command: CommandId;+ readonly code: string;+ readonly message: string;+};++export type BuildEvent = ProducerCompletedEvent | NeedFulfilledEvent | CommandFailedEvent;++export type AcceptedEvent = {+ readonly id: EventId;+ readonly digest: Digest;+};++export type BuildDiagnostic = {+ readonly code: string;+ readonly message: string;+ readonly subject?: string;+};++export type BuildState = {+ readonly format: "svml.build@0";+ readonly id: Digest;+ readonly program: LinkedProgram;+ readonly plan: BuildPlan;+ readonly status: "active" | "complete" | "failed";+ readonly records: readonly TypedRecord[];+ readonly steps: readonly StepState[];+ readonly needs: readonly Need[];+ readonly receipts: readonly Receipt[];+ readonly derivations: readonly Derivation[];+ readonly outstanding: readonly CoreCommand[];+ readonly acceptedEvents: readonly AcceptedEvent[];+ readonly diagnostics: readonly BuildDiagnostic[];+};++export type CoreTransition = {+ readonly state: BuildState;+ readonly commands: readonly CoreCommand[];+};diff --git a/packages/protocol/src/identity.ts b/packages/protocol/src/identity.tsnew file mode 100644index 00000000..ebc9135c--- /dev/null+++ b/packages/protocol/src/identity.ts@@ -0,0 +1,24 @@+export type Digest = `sha256:${string}`;++export type RecordId = string;+export type NeedId = string;+export type StepId = string;+export type DerivationId = string;+export type ReceiptId = string;+export type CommandId = string;+export type EventId = string;++export type ModuleRef = {+ readonly name: string;+ readonly version: string;+};++export type TypeRef = {+ readonly module: ModuleRef;+ readonly name: string;+};++export type ProducerRef = {+ readonly module: ModuleRef;+ readonly name: string;+};diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsnew file mode 100644index 00000000..db68b9f7--- /dev/null+++ b/packages/protocol/src/index.ts@@ -0,0 +1,4 @@+export type * from "./build.js";+export type * from "./identity.js";+export type * from "./module.js";+export type * from "./value.js";diff --git a/packages/protocol/src/module.ts b/packages/protocol/src/module.tsnew file mode 100644index 00000000..b3b0c63d--- /dev/null+++ b/packages/protocol/src/module.ts@@ -0,0 +1,66 @@+import type { Digest, ModuleRef, ProducerRef, TypeRef } from "./identity.js";+import type { ValueSchema } from "./value.js";++export type ModuleDependency = {+ readonly module: ModuleRef;+ readonly digest: Digest;+};++export type TypeDeclaration = {+ readonly name: string;+ readonly schema: ValueSchema;+ readonly description?: string;+};++export type PortDeclaration = {+ readonly name: string;+ readonly type: TypeRef;+};++export type NeedPortDeclaration = {+ readonly name: string;+ readonly wants: TypeRef;+};++export type ImplementationRef = {+ readonly kind: string;+ readonly locator: string;+ readonly digest: Digest;+};++export type ProducerDeclaration = {+ readonly name: string;+ readonly inputs: readonly PortDeclaration[];+ readonly outputs: readonly PortDeclaration[];+ readonly needs: readonly NeedPortDeclaration[];+ readonly implementation: ImplementationRef;+};++export type ModuleManifest = {+ readonly format: "svml.module@0";+ readonly name: string;+ readonly version: string;+ readonly dependencies: readonly ModuleDependency[];+ readonly types: readonly TypeDeclaration[];+ readonly producers: readonly ProducerDeclaration[];+};++export type ResolvedModule = {+ readonly ref: ModuleRef;+ readonly digest: Digest;+ readonly manifest: ModuleManifest;+};++export type ResolvedModuleClosure = {+ readonly format: "svml.closure@0";+ readonly modules: readonly ResolvedModule[];+ readonly digest: Digest;+};++export type ResolvedTypeDeclaration = TypeDeclaration & {+ readonly ref: TypeRef;+};++export type ResolvedProducerDeclaration = ProducerDeclaration & {+ readonly ref: ProducerRef;+};diff --git a/packages/protocol/src/value.ts b/packages/protocol/src/value.tsnew file mode 100644index 00000000..54303d7f--- /dev/null+++ b/packages/protocol/src/value.ts@@ -0,0 +1,68 @@+import type { Digest } from "./identity.js";++export type CanonicalValue =+ | null+ | boolean+ | number+ | string+ | readonly CanonicalValue[]+ | { readonly [key: string]: CanonicalValue };++export type BlobRef = {+ readonly kind: "blob";+ readonly digest: Digest;+ readonly size: number;+ readonly mediaType: string;+};++export type StoredValue =+ | {+ readonly kind: "inline";+ readonly value: CanonicalValue;+ }+ | BlobRef;++export type ValueSchema =+ | { readonly kind: "null" }+ | { readonly kind: "boolean" }+ | {+ readonly kind: "number";+ readonly integer?: boolean;+ readonly minimum?: number;+ readonly maximum?: number;+ }+ | {+ readonly kind: "string";+ readonly enum?: readonly string[];+ readonly minLength?: number;+ readonly maxLength?: number;+ }+ | {+ readonly kind: "literal";+ readonly value: CanonicalValue;+ }+ | {+ readonly kind: "array";+ readonly items: ValueSchema;+ readonly minItems?: number;+ readonly maxItems?: number;+ }+ | {+ readonly kind: "object";+ readonly fields: Readonly<Record<string, ObjectFieldSchema>>;+ readonly allowUnknown?: boolean;+ }+ | {+ readonly kind: "oneOf";+ readonly variants: readonly ValueSchema[];+ }+ | {+ readonly kind: "blob";+ readonly mediaTypes?: readonly string[];+ readonly maxBytes?: number;+ };++export type ObjectFieldSchema = {+ readonly schema: ValueSchema;+ readonly optional?: boolean;+};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex df6cc73a..e63a4cce 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -22,6 +22,23 @@ importers:specifier: 5.9.3version: 5.9.3+ packages/core:+ dependencies:+ '@svml/protocol':+ specifier: workspace:*+ version: link:../protocol++ packages/driver-node:+ dependencies:+ '@svml/core':+ specifier: workspace:*+ version: link:../core+ '@svml/protocol':+ specifier: workspace:*+ version: link:../protocol++ packages/protocol: {}+packages:'@emnapi/[email protected]':diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlnew file mode 100644index 00000000..924b55f4--- /dev/null+++ b/pnpm-workspace.yaml@@ -0,0 +1,2 @@+packages:+ - packages/*diff --git a/spec/core-kernel-v0.md b/spec/core-kernel-v0.mdnew file mode 100644index 00000000..aaae0682--- /dev/null+++ b/spec/core-kernel-v0.md@@ -0,0 +1,33 @@+# SVML Core Kernel v0++Status: executable bootstrap contract; deliberately incomplete.++Core v0 is a domain-free verifier and deterministic state reducer. It does not parse source,+resolve package locations, execute implementations, access an artifact store, call providers,+or search the global producer set for a path to a goal.++## Laws++1. Every referenced module, type and producer belongs to one immutable resolved closure.+2. Records are immutable. Only a Frontend-created typed module may introduce authored origin;+ producer and fulfillment events may append only derived or observed records.+3. Every missing external value is represented by a typed `Need` with explicit constraints and+ an exact/substitute acceptance rule.+4. Every appended record has an origin that reaches an authored record, producer derivation or+ fulfillment receipt.+5. A build executes only the finite steps in its explicit plan. Core never ranks or discovers+ an undeclared producer.+6. State and events are canonical data. Replaying an accepted event is idempotent, and a paused+ state can be serialized and resumed without semantic change.++## Boundary++Core owns linking, nominal type identity, structural value validation, plan validation,+state transitions and provenance verification.++The Node Driver owns manifest I/O, registered implementation execution, requirement handlers,+artifact bytes, journaling and pause/resume orchestration. Core emits commands; it never executes+them.++Frontend selection, `.svml`, `.svs`, Import Prologue and Surface Parser behavior are explicitly+outside Core v0 and Driver v0.diff --git a/tsconfig.v2.json b/tsconfig.v2.jsonnew file mode 100644index 00000000..b45c9222--- /dev/null+++ b/tsconfig.v2.json@@ -0,0 +1,15 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": true,+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "@svml/protocol": ["packages/protocol/src/index.ts"],+ "@svml/core": ["packages/core/src/index.ts"],+ "@svml/driver-node": ["packages/driver-node/src/index.ts"]+ }+ },+ "include": ["packages/**/*.ts"],+ "exclude": ["dist", "node_modules", "packages/*/dist"]+}