/** * The authoring flow (Extension Spec §5.2). Code Mode writes a function; it is * **tested against supplied examples** (input → expected); registration is * blocked until the examples pass — the accuracy mechanism. The staged unit * (source, descriptor, test results) is reviewed and a *separate* approval step * registers it. Approval never happens inside the isolate: the compiled function * body cannot register anything (no capability, and registration is this * ordinary API, called from the chat/host layer after a human approves). */ import { compileCodeFunction } from './compile' import { registerCompiled } from './persist' import type { CodeFunctionSpec, CompiledCodeFunction } from './compile' import type { CellValue, FnContext, Workbook } from '@tanstack/spreadsheet-core' export interface Example { args: Array expected: CellValue } export interface ExampleResult extends Example { actual: CellValue pass: boolean } export interface StagedFunction { compiled: CompiledCodeFunction results: Array /** True iff every supplied example passed — the gate for registration. */ passed: boolean } /** Run a compiled function against literal argument values (no workbook). */ function runOnce( compiled: CompiledCodeFunction, args: Array, ): CellValue { const ctx = { args: { length: args.length, scalar: (i: number) => args[i] ?? null, range: () => null, node: () => { throw new Error('code functions receive scalar arguments only') }, }, clock: { now: () => 0 }, rng: { random: () => 0 }, } as unknown as FnContext return compiled.def.evaluate!(ctx) } function sameValue(a: CellValue, b: CellValue): boolean { if ( a !== null && b !== null && typeof a === 'object' && typeof b === 'object' ) { return ( a.kind === b.kind && (a.kind !== 'error' || a.code === (b as typeof a).code) ) } return Object.is(a, b) } /** * Compile a function and run it against the supplied examples. Does **not** * register — that is a separate, human-approved step ({@link approveAndRegister}). */ export function stageFunction( spec: CodeFunctionSpec, examples: Array = [], ): StagedFunction { const compiled = compileCodeFunction(spec) const results: Array = examples.map((ex) => { const actual = runOnce(compiled, ex.args) return { ...ex, actual, pass: sameValue(actual, ex.expected) } }) // The gate requires at least one supplied, passing example — an empty example // list cannot produce `passed: true` (that was the vacuous-truth bug). return { compiled, results, passed: results.length > 0 && results.every((r) => r.pass), } } /** * Register a staged function (the approval-gated step). Throws if its examples * did not pass — a function cannot be registered until it is verified. */ export function approveAndRegister(wb: Workbook, staged: StagedFunction): void { if (!staged.passed) { throw new Error( `cannot register ${staged.compiled.spec.name}: supplied examples failed`, ) } registerCompiled(wb, staged.compiled) }