diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1176869 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +examples/output/ +.vite/ diff --git a/src/cots.ts b/src/cots.ts index 52bf2b9..dee466a 100644 --- a/src/cots.ts +++ b/src/cots.ts @@ -62,6 +62,27 @@ export type ClaimType = "factual" | "normative" | "predictive" | "evaluative"; export type Polarity = "supports" | "contradicts" | "contextualises"; export type Action = "created" | "appealed" | "rerun" | "corrected" | "escalated" | "superseded"; +export type FlagType = + | "drift-detected" + | "segment-signal-divergence" + | "parameter-set-out-of-range" + | "temporal-validity-expired"; + +export type DecisionOnValidation = "passed" | "flagged" | "escalated"; + +export interface ValidationFlag { + flag_type: FlagType; + message: string; + detected_at: ISO8601; +} + +export interface ValidationRecord { + flags: ValidationFlag[]; + decision_on_validation: DecisionOnValidation; + validated_at: ISO8601; + validated_by: string; +} + export interface DecisionRecord { id: URI; decision_text: string; @@ -71,6 +92,8 @@ export interface DecisionRecord { responsible_authority: { authority_id: string; authority_type: "human" | "organisational" | "automated" }; audit_history: AuditEntry[]; created_at: ISO8601; + /** Layer 2 Validation record (COTS schema v1.1.0, RFC-0001). Optional: producers that have not floored Layer 2 do not emit it. */ + validation?: ValidationRecord; } export interface AuditEntry { diff --git a/src/layer2/layer2.ts b/src/layer2/layer2.ts new file mode 100644 index 0000000..79d2781 --- /dev/null +++ b/src/layer2/layer2.ts @@ -0,0 +1,128 @@ +/** + * Layer 2 (Runtime Validation). Takes a Layer 1 COTS plus operator-provided + * calibration data, evaluates the runtime signals, and attaches a Validation + * record to each DecisionRecord. + * + * Implements the v0.2 contract at + * https://github.com/Source-Engineering/source-engineering-architecture/blob/main/layer-contracts/layer-2-runtime-validation.md + * and the COTS schema v1.1.0 `decisions[*].validation` field per RFC-0001. + * + * Layer 2 does not reject; it flags. A flagged decision is still exposed to + * Layer 3, which is the layer that can reject. + */ + +import type { Cots, DecisionRecord, Context, ValidationRecord } from "../cots.js"; + +export type FlagType = + | "drift-detected" + | "segment-signal-divergence" + | "parameter-set-out-of-range" + | "temporal-validity-expired"; + +export interface CalibrationData { + /** Per-segment calibration drift, measured as divergence from the calibrated baseline. */ + drift?: { segment: string; divergence: number; threshold: number }[]; + /** Parameter-set ranges the operator declares acceptable for this decision-type. */ + parameterSet?: { parameter: string; min: number; max: number }[]; + /** Segments the operator declares in-calibration; divergence on unlisted segments is a flag. */ + segments?: string[]; +} + +export interface Layer2Options { + validatedBy?: string; + now?: string; +} + +export type Layer2ErrorReason = "calibration-data-missing" | "context-missing"; + +export class Layer2Error extends Error { + constructor(public readonly reason: Layer2ErrorReason) { + super(reason); + } +} + +const isIso8601 = (value: string): boolean => { + return !Number.isNaN(Date.parse(value)); +}; + +const validateDecision = ( + decision: DecisionRecord, + context: Context, + calibration: CalibrationData, + now: string +): ValidationRecord => { + const flags: ValidationRecord["flags"] = []; + + for (const d of calibration.drift ?? []) { + if (d.divergence > d.threshold) { + flags.push({ + flag_type: "drift-detected", + message: `Calibration drift detected on segment '${d.segment}' (${d.divergence} divergence, threshold ${d.threshold}).`, + detected_at: now, + }); + } + } + + if (calibration.segments !== undefined) { + for (const d of calibration.drift ?? []) { + if (d.divergence > 0 && !calibration.segments.includes(d.segment)) { + flags.push({ + flag_type: "segment-signal-divergence", + message: `Segment '${d.segment}' is outside the operator-declared in-calibration segments.`, + detected_at: now, + }); + } + } + } + + const ranges = calibration.parameterSet ?? []; + const params: Record = { + temperature: context.parameters.temperature, + top_p: context.parameters.top_p, + tool_budget: context.parameters.tool_budget, + retrieval_depth: context.parameters.retrieval_depth, + }; + for (const range of ranges) { + const value = params[range.parameter]; + if (value !== undefined && (value < range.min || value > range.max)) { + flags.push({ + flag_type: "parameter-set-out-of-range", + message: `Parameter '${range.parameter}' is ${value}; operator range is [${range.min}, ${range.max}].`, + detected_at: now, + }); + } + } + + return { + flags, + decision_on_validation: flags.length > 0 ? "flagged" : "passed", + validated_at: now, + validated_by: "layer2-runtime-validation", + }; +}; + +export class Layer2 { + constructor(private readonly calibration: CalibrationData) {} + + /** + * Attach Validation records to every DecisionRecord in the COTS. + * Throws Layer2Error on the contract's failure modes. + */ + validate(cots: Cots, options: Layer2Options = {}): Cots { + if (this.calibration === undefined || this.calibration === null) { + throw new Layer2Error("calibration-data-missing"); + } + if (cots.context === undefined || cots.context === null) { + throw new Layer2Error("context-missing"); + } + const now = options.now ?? new Date().toISOString(); + const validatedBy = options.validatedBy ?? "layer2-runtime-validation"; + + const decisions = cots.decisions.map((decision) => { + const record = validateDecision(decision, cots.context, this.calibration, now); + return { ...decision, validation: { ...record, validated_by: validatedBy } }; + }); + + return { ...cots, decisions }; + } +} diff --git a/tests/layer2.test.ts b/tests/layer2.test.ts new file mode 100644 index 0000000..2596e64 --- /dev/null +++ b/tests/layer2.test.ts @@ -0,0 +1,102 @@ +/** + * Tests for the Layer 2 (Runtime Validation) module. Mirrors the conformance + * suite's canonical test cases (TC-L2-01 .. TC-L2-06) and adds tests for the + * reference implementation's own behaviour per the v0.2 contract: + * https://github.com/Source-Engineering/source-engineering-architecture/blob/main/layer-contracts/layer-2-runtime-validation.md + */ + +import { describe, it, expect } from "vitest"; +import { Layer1 } from "../src/layer1/layer1.js"; +import { Layer2, Layer2Error } from "../src/layer2/layer2.js"; +import { MockModelAdapter } from "../src/adapters/mock-adapter.js"; +import { LegalSummarizationDecisionType } from "../src/decision-types/legal-summarization.js"; +import type { SourceArtifact } from "../src/cots.js"; + +const SAMPLE_SOURCE: SourceArtifact = { + id: "urn:source-engineering:source:test-001", + origin: { system_name: "Test", system_version: "1.0.0", configuration_hash: "0".repeat(64) }, + version: { content_hash: "1".repeat(64), issued_at: "2026-10-10T08:00:00Z" }, + authority: { asserted_by: "test", trust_score: 0.9 }, + temporal_validity: { valid_from: "2026-10-10T08:00:00Z", valid_until: null }, + content_reference: { uri: "https://example.com/test.pdf", media_type: "application/pdf" }, +}; + +const buildCots = async () => { + const layer1 = new Layer1(LegalSummarizationDecisionType, new MockModelAdapter()); + return layer1.invoke( + { document: { uri: "https://example.com/test.pdf", media_type: "application/pdf" } }, + [SAMPLE_SOURCE] + ); +}; + +const NOW = "2026-10-11T12:00:00Z"; + +describe("Layer 2 (Runtime Validation)", () => { + it("TC-L2-01: attaches a well-formed Validation record to every decision", async () => { + const cots = await buildCots(); + const layer2 = new Layer2({ drift: [{ segment: "contract-law", divergence: 0.05, threshold: 0.1 }] }); + const validated = layer2.validate(cots, { now: NOW }); + for (const decision of validated.decisions) { + expect(decision.validation).toBeDefined(); + expect(decision.validation!.decision_on_validation).toBe("passed"); + expect(decision.validation!.flags).toHaveLength(0); + expect(decision.validation!.validated_at).toBe(NOW); + } + }); + + it("TC-L2-01: raises drift-detected when divergence exceeds the threshold", async () => { + const cots = await buildCots(); + const layer2 = new Layer2({ drift: [{ segment: "contract-law", divergence: 0.14, threshold: 0.1 }] }); + const validated = layer2.validate(cots, { now: NOW }); + const flags = validated.decisions[0].validation!.flags; + expect(flags.some((f) => f.flag_type === "drift-detected")).toBe(true); + expect(validated.decisions[0].validation!.decision_on_validation).toBe("flagged"); + }); + + it("raises segment-signal-divergence for drift on an operator-undeclared segment", async () => { + const cots = await buildCots(); + const layer2 = new Layer2({ + drift: [{ segment: "tort", divergence: 0.02, threshold: 0.1 }], + segments: ["contract-law"], + }); + const validated = layer2.validate(cots, { now: NOW }); + expect( + validated.decisions[0].validation!.flags.some((f) => f.flag_type === "segment-signal-divergence") + ).toBe(true); + }); + + it("raises parameter-set-out-of-range when a context parameter is outside the operator range", async () => { + const cots = await buildCots(); + const layer2 = new Layer2({ parameterSet: [{ parameter: "temperature", min: 0, max: 0.2 }] }); + const validated = layer2.validate(cots, { now: NOW }); + expect( + validated.decisions[0].validation!.flags.some((f) => f.flag_type === "parameter-set-out-of-range") + ).toBe(true); + }); + + it("does not reject: a flagged decision is still returned, not thrown", async () => { + const cots = await buildCots(); + const layer2 = new Layer2({ drift: [{ segment: "contract-law", divergence: 0.9, threshold: 0.1 }] }); + expect(() => layer2.validate(cots, { now: NOW })).not.toThrow(); + expect(layer2.validate(cots, { now: NOW }).decisions[0].validation!.decision_on_validation).toBe("flagged"); + }); + + it("returns calibration-data-missing when calibration is absent", async () => { + const cots = await buildCots(); + const layer2 = new Layer2(undefined as never); + expect(() => layer2.validate(cots)).toThrow(Layer2Error); + expect(() => layer2.validate(cots)).toThrow(/calibration-data-missing/); + }); + + it("returns context-missing when the COTS carries no context", async () => { + const cots = await buildCots(); + const broken = { ...cots, context: undefined } as never; + const layer2 = new Layer2({ drift: [] }); + expect(() => layer2.validate(broken)).toThrow(/context-missing/); + }); + + it("TC-L2-06: leaves a v1.0.0 COTS untouched (the field is optional; Layer 2 is opt-in)", async () => { + const cots = await buildCots(); + expect(cots.decisions[0].validation).toBeUndefined(); + }); +});