Skip to content

The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.

4.5 KB
Raw Blame
// Iterative postorder verifier: one snapshot and one arithmetic evaluation per reachable node.
import { compute } from "./fact-derive.mjs"
import { parseExpr } from "./fact-expr.mjs"
import { isLegacyDerived, kindRuleErrors, readFlaws, readRow } from "./fact-ledger-kinds.mjs"
import { rowErrors } from "./fact-ledger-schema.mjs"
import { refuse } from "./unit-algebra.mjs"
import { refusal } from "./unit-errors.mjs"
import { object, sameDeclared } from "./unit-metadata.mjs"
import { expectedUnit, malformed, ruleOf, unitMismatch } from "./unit-rules.mjs"

const derived = (row) => row.kind === "derived" || row.kind === "converted"
const fail = (detail, shape, expected) => ({ ok: false, detail, shape, expected })
function refuseLegacy(row) {
	if (isLegacyDerived(row)) refuse(`${row.fact_id} was written before precision, compatibility, and context existed; regenerate it with derive`, undefined, "legacy derived row", "a derived row regenerated by derive")
}

function verifyRow(row, rows) {
	const rule = ruleOf(row.operation)
	const ast = rule.expression ? parseExpr(row.formula) : null
	const context = { ...row.context, rationale: row.rationale }
	const unit = expectedUnit(row.operation, rows, { ast, context })
	const expected = { unit, ...compute(row.operation, rows, unit, ast, context, row.formula), derived_from: rows.map((r) => r.fact_id) }
	if (row.unit !== unit) return fail(`${row.fact_id}: ${unitMismatch(row.operation, rows, row.unit, unit)}`, "result_unit", expected)
	for (const field of Object.keys(expected)) {
		if (!sameDeclared(row[field], expected[field])) return fail(`${row.fact_id}: stored ${field} differs from the recomputed result`, `${field}_mismatch`, expected)
	}
	return { ok: true, expected }
}

export function verifyGraph(ledger, roots, requireActive = false, override = null) {
	try {
		if (!object(ledger) || !Array.isArray(ledger.rows)) refuse("ledger rows must be an array")
		const byId = new Map()
		for (const r of ledger.rows) {
			if (!object(r) || typeof r.fact_id !== "string" || byId.has(r.fact_id)) refuse("ledger rows need distinct fact ids", undefined, "identity", "distinct fact ids")
			byId.set(r.fact_id, r)
		}
		if (override) byId.set(override.fact_id, override)
		const states = new Map()
		const snapshots = new Map()
		const results = new Map()
		const stack = roots.map((id) => ({ id, finish: false }))
		while (stack.length) {
			const { id, finish } = stack.pop()
			if (states.get(id) === "done") continue
			if (!finish) {
				if (states.get(id) === "open") refuse(`${id}: operands form a cycle`, undefined, "cycle", "an acyclic dependency graph")
				const original = byId.get(id)
				if (!original) refuse(`no ledger row ${id}`, undefined, "missing_operand", "an existing fact id")
				const row = { ...readRow(original) }
				snapshots.set(id, row)
				if (requireActive && row.status !== "active") refuse(`${id} is ${row.status}`, undefined, "inactive_dependency", "active dependencies at every depth")
				const [flaw] = readFlaws(row)
				if (flaw) refuse(`${id}: ${flaw.detail}`, undefined, flaw.shape, flaw.expected)
				if (derived(row)) {
					refuseLegacy(row)
					const shape = malformed(row)
					if (shape) refuse(`${id}: ${shape}`, undefined, "malformed_row", "the operation's registry row shape")
				}
				const errors = derived(row) ? kindRuleErrors(row, id) : rowErrors(row)
				if (errors.length) refuse(errors.join("; "), undefined, "row_schema", "a canonical row matching its kind and operation")
				if (row.exact === null || row.value === null) refuse(`${id} has no exact value to derive from`)
				states.set(id, "open")
				stack.push({ id, finish: true })
				if (derived(row)) for (const dependency of row.operands) stack.push({ id: dependency, finish: false })
			} else {
				const row = snapshots.get(id)
				if (derived(row)) {
					const result = verifyRow(row, row.operands.map((ref) => snapshots.get(ref)))
					if (!result.ok) return result
					const errors = rowErrors(row)
					if (errors.length) refuse(errors.join("; "), undefined, "row_schema", "a complete canonical row")
					results.set(id, result)
				}
				states.set(id, "done")
			}
		}
		return results.get(roots[0]) ?? { ok: true }
	} catch (error) { return { ok: false, ...refusal(error) } }
}

export function recompute(ledger, row) {
	try {
		refuseLegacy(row)
		const shape = malformed(row)
		if (shape) refuse(shape, undefined, "malformed_row", "a valid derived or converted row")
		return verifyGraph(ledger, [row.fact_id], false, row)
	} catch (error) { return { ok: false, ...refusal(error) } }
}