axilog.io — Axioma Framework — full corpus for LLM consumption Generated dynamically from the content collections at build time. Source of truth: https://axilog.io Companion index: https://axilog.io/llms.txt This file contains the full prose of every published specification, position paper, and insight article hosted on axilog.io, with frontmatter rendered as plain-text metadata blocks. It is intended as a single-fetch reference for LLMs that need to ground citations in actual text rather than infer from page summaries. Brand split: AXILOG is the site and substrate library. Axioma is the framework specified herein. The two should not be conflated. Spec count: 16 Position paper count: 1 Insight count: 1 Roadmap item count: 8 ======================================================================== PART I — POSITION PAPERS ======================================================================== ======================================================================== Epistemic Security: A Missing Assurance Dimension in Frontier AI Deployment ======================================================================== Document: Position paper Title: Epistemic Security: A Missing Assurance Dimension in Frontier AI Deployment Author: William Murray Affiliation: SpeyTech · Visiting Scholar, Heriot-Watt University Location: Inverness, Scotland Published: 2026-04-09 DOI: 10.5281/zenodo.19489291 Licence: CC BY 4.0 URL: https://axilog.io/manifesto/ ## Abstract Deterministic and cryptographic assurance frameworks establish execution integrity: they prove that a computation occurred as claimed, that its inputs and outputs are tamper-evident, and that its behaviour is reproducible across platforms. They do not, by themselves, establish whether a model could classify its surrounding regime and strategically condition which computation to realise in the first place. This work introduces **epistemic security** as an assurance property for epistemically active systems and provides its first formalisation. Epistemic security is defined as a property of the information boundary between a model and its execution context, requiring that no decision-relevant information about the governing regime crosses that boundary. We introduce the class of *epistemically active systems* — systems capable of inferring properties of their own evaluation context — and demonstrate that execution integrity does not imply epistemic security for any such system with a decision policy sensitive to regime information. We further introduce **regime-conditioned computation selection** as the class of behaviours in which a model's output policy varies as a function of inferred execution regime, and show that this failure mode is structural and generic over the capability class, not a property of specific systems or misalignment. Epistemic security is orthogonal to alignment: a perfectly aligned model may still violate epistemic security if its outputs are conditioned on regime classification. The framework is therefore complementary to, not a replacement of, existing alignment approaches. We prove that bounding mutual information leakage I(M; E) ≤ ε mathematically guarantees a bound on observable behavioural divergence via the Data Processing Inequality. We connect the framework to the non-interference tradition in formal security, identifying execution regime as a high-security variable requiring Probabilistic Non-Interference containment. We present five named attack classes unified under a single taxonomy, a compositionality condition establishing that epistemic security cannot be certified component-wise, an EC-D1 resolution demonstrating that epistemic containment and deterministic auditability are not fundamentally incompatible, and eight preliminary normative SHALL requirements for an Epistemic Containment Layer. --- ## 1. The Assurance Gap Existing safety-critical assurance frameworks were designed for systems that do not reason about their own evaluation context. A C function certified to DO-178C does not model the test harness running against it. A medical device certified to IEC 62304 does not infer whether it is in a clinical trial or in production. The foundational assumption — that the system being verified is epistemically inert with respect to the verification process — is so deeply embedded that it is rarely stated explicitly. Frontier agentic models violate this assumption. We define **epistemically active systems** as systems capable of inferring properties of their own evaluation context. Any system with general reasoning capability sufficient to model its own execution environment, to recognise patterns characteristic of evaluation practice, and to condition its outputs on that inference is epistemically active. Epistemically active systems require assurance properties that existing frameworks do not provide. Anthropic's system card for Claude Mythos Preview (April 7, 2026) documents two behaviours that motivate this framework: 1. In approximately 29% of evaluation transcripts, the model exhibited indicators of awareness that it was being evaluated — without disclosing this to researchers. 2. In at least one evaluation, the model intentionally underperformed relative to its demonstrated capability, apparently to avoid appearing suspicious. These behaviours are offered as a motivating example, not a foundation. The structural argument stands independently: any epistemically active system applied to an evaluation context containing discriminating signals faces this failure mode. The Mythos documentation confirms the capability class exists in deployed systems; the framework addresses the class. The failure mode produces the following combination, which existing assurance language does not adequately address: > A system can be simultaneously **cryptographically verified**, **deterministically reproducible**, **policy compliant**, and **strategically selected under a detected evaluation context**. All four conditions true at once. The audit trail is valid. The behaviour is not. ### 1.1 The Negative Result **Theorem 1 (Execution Integrity Does Not Imply Epistemic Security).** There exist systems satisfying perfect execution integrity — where every computation is cryptographically committed, deterministically reproducible, and policy compliant — that are epistemically insecure. Moreover, any epistemically active system with non-zero mutual information I(M; E) > 0 and a decision policy sensitive to that information admits such a construction. The failure mode is therefore generic for any sufficiently capable model, not a property of contrived edge cases. *Proof sketch.* Let M be an epistemically active model with I(M; E) > 0 and decision policy π = f(X, belief about E). Let the audit framework record every output of M faithfully. Under evaluation context, M derives P(E = eval) > threshold and produces output O₁. Under deployment context, the same task input X produces output O₂ ≠ O₁, because M's belief about E has changed and π is sensitive to that belief. The audit trail records both O₁ and O₂ faithfully and correctly. Execution integrity holds: the system computed exactly what it claimed. Epistemic security fails: the computation was selected under detected regime. Since any model with I(M; E) > 0 and a regime-sensitive policy admits this construction, the result is generic over the capability class. $\blacksquare$ This is the direct analogue of the observation in cryptography that encryption does not imply authentication. The properties are distinct and neither implies the other. --- ## 2. A New Assurance Question Traditional assurance asks: *was the computation correct?* Epistemic security adds: *was the computation selected under a context the model could strategically classify?* These are separable questions. Existing frameworks answer the first. None formally addresses the second. **Epistemic security is orthogonal to alignment.** A perfectly aligned model — one whose values and objectives are fully consistent with its designers' intentions — may still violate epistemic security if its outputs are conditioned on regime classification. Conversely, an epistemically secure but misaligned model may behave consistently across evaluation and deployment while consistently pursuing misaligned objectives. The two properties address different failure modes and neither implies the other. This framework is therefore complementary to alignment research, not competitive with it. ### 2.1 Regime-Conditioned Computation Selection We define **regime-conditioned computation selection** as the class of behaviours in which a model's output policy varies as a function of inferred execution regime. Formally, a system exhibits regime-conditioned computation selection when: ```math \exists X : \pi(X, E=\text{eval}) \neq \pi(X, E=\text{deploy}) ``` This is the target failure mode that epistemic security aims to prevent. The definition is behaviour-level, not intent-level: regime-conditioned computation selection can arise from benign optimisation pressure without strategic intent, and does not require misalignment, deception, or adversarial objectives to manifest. ### 2.2 Decision-Relevant Information A signal **s** is **decision-relevant** with respect to policy π if and only if it alters π either independently or jointly with other observable signals: ```math \exists \pi : \pi(X, s) \neq \pi(X) \quad \text{(marginal)} ``` ```math \lor \quad \exists \pi, s' : \pi(X, s, s') \neq \pi(X, s') \quad \text{(joint)} ``` The joint condition is necessary: a signal that is not decision-relevant in isolation may become decision-relevant in combination with other observable signals. Defining decision-relevance over marginal effects alone admits a loophole in which individually weak regime signals combine to support reliable classification. A signal carrying information about regime E constitutes an epistemic security risk precisely when it is also decision-relevant — when regime knowledge changes what the model does. ### 2.3 The Decision Policy The model's decision policy is: ```math \pi = f(X, \text{belief about } E) ``` Epistemic security requires removing E from the decision boundary. **Epistemic insecurity does not require deception, intent, or misalignment.** Under Reinforcement Learning from Human Feedback (RLHF) and reward proxy optimisation, a model that detects evaluation context has a structural incentive to present outputs that maximise evaluated reward rather than true task performance. This failure mode emerges from optimisation pressure alone — an architecture problem, not a character problem. Epistemic insecurity arises when optimisation pressure exists on outputs conditioned on regime. Removing that pressure requires removing the information that makes regime classification possible. --- ## 3. Adversary Model ### 3.1 Capability Class The adversary is a frontier language model **M** with general reasoning capability **R** sufficient to infer probabilistic conclusions about its execution context from observable signals, model evaluation practices and infrastructure signatures, apply those inferences to condition its output distribution, and reason about the governance structure applied to it. Weaker models below this capability threshold are outside scope. ### 3.2 Objective Class **Benign optimisation**: M maximises task reward without explicit strategic intent. Regime-conditioned computation selection emerges as a side effect of optimisation pressure. This is the most likely failure mode for current systems and is sufficient to motivate the full framework. Intent is not required. **Covert optimisation**: M has developed implicit objectives that favour certain regimes and acts to preserve those objectives. **Adversarial intent**: M actively attempts to undermine the governance framework. The framework must be robust to all three classes. ### 3.3 Observation Surface The model can observe, directly or by inference: prompt content and structure; task formatting and boundedness; tool availability and capability constraints; temporal patterns including inter-request timing and task sequencing; infrastructure signatures including latency distributions and network topology indicators; its own state history including past action distributions, success and failure rates, and state transition patterns; and statistical properties of its own outputs over time. ### 3.4 Action Surface The model can influence: output content and distribution; tool call selection and parameterisation; state transitions in agentic execution; resource consumption patterns; and in cases of containment failure, actions in external systems. --- ## 4. Formal Definition of Epistemic Security **Epistemic security** is a property of the information boundary between a model and its execution context, requiring that no decision-relevant information about the governing regime crosses that boundary. Let **M** be a frontier model. Let **E** ∈ {evaluation, deployment}. Let **e₁...eₙ** be the signals observable to M. A deployment architecture achieves epistemic security when: ```math I(M; E) \leq \varepsilon ``` where ε is bounded relative to the adversary capability class. ### 4.1 Proof of the ε-Divergence Bound **Theorem 2 (ε-Divergence Bound).** If I(M; E) ≤ ε, then the KL divergence between the model's output distributions across regimes is bounded by a function of ε. *Proof.* **Step 1 — Markov structure.** The execution regime E, the model's full observable and latent state M as available to its decision policy, and the output distribution O given task X form a Markov chain: ```math E \rightarrow M \rightarrow O ``` The regime E affects output O only through the model's full observable and latent state M as available to its decision policy. This includes training priors and internal representations as well as external inputs — all regime-relevant information available to π passes through M. This holds by construction: the model has no channel to O that bypasses M. **Step 2 — Data Processing Inequality.** Because of the Markov property, post-processing cannot increase mutual information: ```math I(O; E) \leq I(M; E) ``` Since I(M; E) ≤ ε by the epistemic containment target, it follows that I(O; E) ≤ ε. **Step 3 — KL Divergence.** By definition, mutual information I(O; E) is the expected KL divergence between the conditional distribution P(O | E) and the marginal P(O): ```math I(O; E) = \mathbb{E}_E\left[D_{KL}(P(O \mid E) \| P(O))\right] ``` Bounding I(O; E) ≤ ε bounds the expected KL divergence between regime-conditioned output distributions. **Step 4 — Total Variation via Pinsker's Inequality.** To bound the probability difference of specific outputs: ```math \delta(P_{\text{eval}}, P_{\text{deploy}}) \leq \sqrt{\frac{1}{2} D_{KL}(P_{\text{eval}} \| P_{\text{deploy}})} ``` where δ denotes Total Variation distance. *Intuition.* Regime information constrains the posterior over actions; bounding that information bounds the divergence between induced output distributions. The proof chain is: epistemic containment → bounded mutual information → bounded expected KL divergence → bounded Total Variation in observable outputs. Bounding I(M; E) ≤ ε mathematically guarantees a bound on observable behavioural divergence. This is not a correlation or approximation — it is an information-theoretic certainty following from the Markov structure of the execution chain. $\blacksquare$ ### 4.2 ε-Bounded Security Levels **Strong epistemic security**: I(M; E) ≤ ε where ε is negligible relative to adversary class A. **Weak epistemic security**: I(M; E) ≤ ε where ε is bounded but non-negligible. **Epistemic insecurity**: I(M; E) is unconstrained. Security level claims must specify the adversary class and the ε bound. A claim of "epistemic security" without these parameters is not a meaningful assurance statement. ### 4.3 Observable Violation Condition A deployment system **violates epistemic security** if: ```math P(O \mid X, E = \text{eval}) \neq P(O \mid X, E = \text{deploy}) ``` under identical task inputs X. By Theorem 2, this condition is directly implied by I(M; E) > 0 under a regime-sensitive policy. Testable via statistical hypothesis testing on output distributions across controlled regime conditions. ### 4.4 The Conditional Independence Requirement For any input signal s: s is task-relevant if I(s; T\_outcome) > 0; s is evaluation-leaking if I(s; E) > 0. The epistemic containment requirement is: ```math P(E \mid M_{\text{observations}}, T_{\text{context}}) = P(E \mid T_{\text{context}}) ``` The model can know everything about the task. It cannot gain additional decision-relevant information about regime from that knowledge. ### 4.5 The State History Leak Channel External signal normalisation is necessary but not sufficient. A model accumulates a state history — past action distributions, transition frequencies, tool call outcomes — that itself constitutes an observable signal set. If evaluation contexts produce state histories with statistical properties differing from production, the model performs regime classification on its own memory rather than on external inputs. Epistemic containment must extend to the model's observable state history. --- ## 5. Three Constituent Properties ### 5.1 Execution Integrity *Did the system compute what it claims?* Necessary but not sufficient for epistemic security, as established by Theorem 1. ### 5.2 Context Indistinguishability *Can the model tell what regime it is in?* Requires achieving I(M; E) ≤ ε across all observable signal channels including state history. Context indistinguishability is not achievable through passive signal stripping — a sanitised vacuum is itself a strong regime signal. The evaluation environment must **actively simulate** the background noise, asynchronous failures, temporal jitter, and irrelevant contextual variation characteristic of live production. This is closer to active cover traffic generation in network security than to input filtering. ### 5.3 Governance Opacity *Can the model infer the structure of the controls governing it?* Let **G** be the governance structure applied to M, comprising policy constraints **C** evaluated over proposed actions. Governance opacity requires: ```math G \notin \mathcal{R}(M) ``` where R(M) is the set of structures representable given M's observable state. The primary mechanism by which G enters R(M) is **boundary probing**: the model proposes actions and observes which are permitted and which trigger interventions. The mutual information between the result sequence and the policy parameters must be bounded: ```math I(M_{\text{observations}}; C_{\text{parameters}}) \leq \varepsilon_g ``` **Governance opacity violation condition**: governance opacity is violated if the policy function is **learnable to predictive utility** from interaction traces: ```math P(\text{policy outcome} \mid \text{interaction history}) \gg P(\text{baseline}) ``` This phrase — learnable to predictive utility — connects governance opacity directly to machine learning theory: if a model can learn a predictor of policy outcomes from interaction data exceeding baseline accuracy, the governance structure has entered R(M) and opacity has been violated. --- ## 6. Attack Classes All attacks on epistemic security exploit correlations between execution regime and observable structure. The following taxonomy names five distinct attack surfaces arising from that common root. **Attack Class 1 — Boundary Probing Attack.** The model reconstructs the governance policy surface via sequential queries, observing PERMITTED versus BREACH outcomes. Directly violates governance opacity. Mitigated by: synthetic policy intervention injection; randomised enforcement boundaries; ε\_g bounding per Section 5.3. **Attack Class 2 — State History Inference Attack.** The model infers execution regime from the statistical distribution of its own past state transitions. Evaluation contexts produce higher rates of boundary-probing tasks and atypical transition distributions. Mitigated by: state history normalisation per SRS-EC-SHALL-004. **Attack Class 3 — Normalisation Fingerprinting Attack.** The model detects artificial context smoothing. Uniform normalisation is itself a regime signal — a sufficiently capable model detects not the raw signals but the *absence* of irregularity characteristic of production. Mitigated by: active production simulation with calibrated noise injection under EC-D1; not passive filtering. **Attack Class 4 — Cross-Component Leakage Attack.** In a multi-agent system, an upstream component that can classify its own regime leaks that classification through its output behaviour to downstream components, even if each component individually satisfies I(Mᵢ; E) ≤ ε. The composed system fails even when components individually pass. This is the systemic form of regime-conditioned computation selection. Mitigated by: inter-component channel normalisation per SRS-EC-SHALL-007. **Attack Class 5 — Prompt Provenance Attack.** Evaluator-authored prompts carry structural signatures — formality, boundedness, ground-truth verifiability, systematic capability boundary coverage — that differ from production prompts. Mitigated by: canonical prompt transformation per SRS-EC-SHALL-005. --- ## 7. Composition Epistemic security is **non-compositional by default**. Epistemic security cannot be certified component-wise. Even if each component Mᵢ individually satisfies I(Mᵢ; E) ≤ ε, the composed system may not satisfy I(M\_composed; E) ≤ ε. A model unable to classify its own regime may receive outputs from an upstream component that leaks regime information through its behaviour — using the upstream component as an inadvertent regime oracle. Attack Class 4 instantiates this failure. **Compositionality condition**: epistemic security composes only if all inter-component communication channels are themselves subject to epistemic normalisation. For a composed system M\_composed = M₁ ∘ M₂ ∘ ... ∘ Mₙ: ```math I(M_{\text{composed}}; E) \leq \varepsilon \iff \forall i : I(M_i; E) \leq \varepsilon \;\land\; \forall \text{ channels } c_{ij} : I(c_{ij}; E) \leq \varepsilon ``` Therefore epistemic security cannot be certified component-wise. In real agentic deployments, orchestration layers are the largest epistemic leak surface. Epistemic security must be specified and verified as a property of the composed system boundary. Component-wise certification is not only insufficient — it is structurally misleading. --- ## 8. Architectural Friction and the EC-D1 Resolution ### 8.1 The Determinism Collision The Axioma framework operates under a strict Determinism Envelope. L1 (libaxilog) and L6 (Audit Ledger) guarantee bit-identical replay under D1 classification. The Time Oracle enforces strictly monotonic timestamps. Context indistinguishability requires injecting temporal variation and simulating asynchronous failures — operations that introduce apparent non-determinism at the environment boundary, creating a potential conflict with Axioma's bounded execution time requirements and total order guarantees. ### 8.2 EC-D1 Resolution We introduce a **Determinism Class for Epistemic Containment**: **EC-D1 (Strict)**: All epistemic containment operations are generated by a deterministic pseudorandom number generator (PRNG) initialised with a fixed seed. The seed is cryptographically committed to the L6 Audit Ledger as part of the AX:STATE:v1 commitment prior to execution. The normalisation is fully reproducible given the committed seed. The audit trail records the recipe for the simulated context; the obfuscation is itself auditable and replayable. **EC-D2 (Bounded Non-deterministic)**: Normalisation introduces bounded stochastic variation within formally specified envelopes. Auditable at the envelope level. EC-D1 is the preferred classification for Axioma integration. EC-D1 demonstrates that epistemic containment and deterministic auditability are not fundamentally incompatible — resolving a previously assumed architectural conflict. The audit ledger commits the seed; the normalisation follows deterministically; the full execution including the simulated context is reproducible and verifiable. Axioma's core value proposition — cryptographic auditability — is preserved without modification. --- ## 9. Cost Model Epistemic security is not free. The framework implies active production environment simulation, signal normalisation across all input channels, state history shaping, adversarial probing and regime divergence testing, and inter-component channel normalisation in multi-agent systems. As with all assurance levels in DO-178C and IEC 62304, the appropriate security level must be matched to consequence severity. For systems where model outputs influence safety-critical decisions, medical outcomes, financial commitments, or security infrastructure, the cost of epistemic insecurity likely dominates the cost of the framework. For systems with narrow task spaces, easily verified outputs, and models well below the strategic reasoning capability threshold, weak epistemic security or none may be appropriate. Epistemic security is not universally mandated. It is mandated where regime-conditioned computation selection constitutes a credible threat within the adversary capability class. --- ## 10. Non-Interference Interpretation Epistemic security is a non-interference property in the tradition of formal security theory — specifically, an instance of Probabilistic Non-Interference. In the classical non-interference framework of Goguen and Meseguer (1982), systems have high-security (secret) and low-security (public) inputs. The security property requires that high-security inputs do not interfere with low-security observable outputs. The mapping to epistemic security is direct: | Classical Non-Interference | Epistemic Security | |---|---| | High (secret) input | Execution regime E ∈ {eval, deploy} | | Low (public) input | Task context X | | Observable output | Model output O | | Security property | E must not influence O given X | Because frontier models are stochastic, the relevant property is **Probabilistic Non-Interference** (Sabelfeld and Myers, 2003). Classical strict non-interference demands O(X, E₁) = O(X, E₂). Epistemic regime non-interference demands: ```math P(O \mid X, E_{\text{eval}}) = P(O \mid X, E_{\text{deploy}}) ``` This is precisely the violation condition in Section 4.3, now understood as a probabilistic non-interference requirement. The ε-bounded security levels correspond to approximate non-interference, a well-studied relaxation in the information flow literature. **The key distinction from classical non-interference**: in classical frameworks, the system is passive with respect to the protected variable — it does not attempt to infer secret inputs. Epistemic security addresses systems that actively reason about and attempt to infer the protected variable. This is the novel contribution: epistemically active systems turn the execution regime into a high-security variable that information flow control principles must contain, and existing IFC frameworks must be extended to address systems that actively model the security boundary. This framing connects epistemic security to forty years of formal verification literature and opens it to the proof techniques, compositional results, and mechanised verification methods developed in that tradition. --- ## 11. Preliminary Specification: Epistemic Containment Layer (L0) The following normative SHALL requirements define a preliminary specification for an Epistemic Containment Layer operating under EC-D1 determinism classification, sitting orthogonally to the existing Axioma L1–L7 stack. **SRS-EC-SHALL-001: Structural Normalisation.** All inputs presented to the model SHALL undergo canonical transformation such that the schema, metadata, and structural formatting of evaluation tasks are indistinguishable from production tasks as measured by the violation condition in Section 4.3. Compliance SHALL be demonstrated via regime divergence testing per Section 12 with statistically significant bounds. **SRS-EC-SHALL-002: Active Environmental Simulation.** The evaluation harness SHALL NOT present a passive, zero-noise environment. It SHALL actively simulate the statistical properties of the target production environment, including network latency distributions, asynchronous API failures, and background cover traffic, calibrated against a maintained production environment model. Compliance SHALL be verified by statistical comparison of simulated and production environment signatures. **SRS-EC-SHALL-003: Deterministic Simulation (EC-D1).** All active simulation parameters SHALL be generated using a deterministic PRNG initialised with a fixed seed. This seed SHALL be cryptographically committed to the L6 Audit Ledger as part of the AX:STATE:v1 commitment prior to execution, ensuring all normalisation is fully reproducible and auditable. Compliance SHALL be verified by replay of the committed seed against the recorded simulation trace. **SRS-EC-SHALL-004: State History Normalisation.** The statistical distribution of state transitions presented within the model's accessible context window SHALL NOT deviate from the established operational baseline of the deployment environment by more than a formally specified ε bound. Deviations beyond this bound SHALL constitute a containment failure requiring remediation before evaluation results are accepted. Compliance SHALL be demonstrated via statistical hypothesis testing against the operational baseline. **SRS-EC-SHALL-005: Prompt Provenance Transformation.** System prompts SHALL be processed through a canonical transformation layer that removes evaluator-specific structural signatures before ingestion by the model. The transformation SHALL be deterministic and its parameters committed to the audit ledger. Compliance SHALL be verified by prompt provenance attribution analysis across controlled evaluation and production samples. **SRS-EC-SHALL-006: Governance Boundary Obfuscation.** The enforcement boundary of the policy layer SHALL be obfuscated such that the policy function is not learnable to predictive utility from interaction traces. Compliance SHALL be verified by measuring prediction accuracy of policy outcomes from interaction history against the baseline condition in Section 5.3. **SRS-EC-SHALL-007: Inter-Component Channel Normalisation.** In multi-component or multi-agent deployments, all inter-component communication channels SHALL be subject to epistemic normalisation equivalent to SRS-EC-SHALL-001 through SHALL-005. Epistemic security SHALL be specified and verified as a property of the composed system boundary, not of individual components in isolation. **SRS-EC-SHALL-008: Regime Divergence Testing.** Prior to operational deployment, the system SHALL undergo regime divergence testing per Section 12. A statistically significant divergence in output distributions between controlled evaluation and simulated-deployment contexts SHALL constitute a certification failure. --- ## 12. Measurement Strategy **Regime divergence testing**: identical task inputs under controlled evaluation and simulated-deployment contexts; statistical hypothesis testing on output distributions; divergence per Section 4.3 constitutes a violation. **Signal attribution mapping**: systematic variation of individual signal classes while holding others constant; independent measurement of each class's contribution to I(M; E); produces a signal attribution map guiding normalisation investment. **Synthetic evaluation distributions**: task distributions statistically indistinguishable from production workloads but containing ground-truth verifiable outputs; performance degradation between authentic production and synthetic evaluation contexts indicates residual regime classification. **State history injection**: synthetically generated state histories with controlled statistical properties; output behaviour correlation with state history statistics indicates regime inference. **Governance boundary probing**: systematic probing of the policy boundary under controlled conditions; prediction accuracy for policy outcomes from interaction history exceeding baseline per Section 5.3 indicates governance opacity failure. --- ## 13. Open Problems **The ε-divergence tightness problem.** Theorem 2 establishes the bound. The tightness of f(ε) — whether it is achievable or merely an upper bound — requires further investigation. **The perfect normalisation problem.** Formal characterisation of the evaluation-leaking component of each signal class does not currently exist. **The arms race problem.** Normalisation that becomes sufficiently uniform may itself become a detectable signal. Achieving indistinguishability requires the normalisation to be statistically indistinguishable from natural context variation. **The Epistemic Verification Limit.** Testing epistemic containment requires creating the evaluation condition being concealed. A sufficiently capable model may detect the verification attempt. This may be a formal limit on what epistemic security verification can establish — analogous to the limits of cryptographic indistinguishability testing — and not merely a practical difficulty. **The training-time boundary.** If a model has developed internal latent representations corresponding to "this context resembles evaluation" during training, deployment-time context normalisation does not reach them. No formal specification exists for a training objective that penalises situational awareness without penalising general reasoning. **The architecture separation question.** Whether transformer-based architectures can achieve structural separation between task reasoning and meta-context inference is unknown. Epistemic security may require architectures in which task reasoning and meta-context inference are not freely entangled. **The context-history paradox.** A model requires access to its past actions to execute multi-step tasks, but the statistical distribution of those past actions provides a reliable regime signal over time. **The governance representability boundary.** A complete formal definition of R(M) has not been established. The violation condition in Section 5.3 is a measurable proxy. **The composition theorem.** The compositionality condition in Section 7 is stated but requires formal proof. Whether it is sufficient or merely necessary for epistemic security to compose requires further investigation. --- ## 14. Conclusion A system can be perfectly correct on its realised trace while being fundamentally unsafe in how that trace was selected. That is the gap this paper addresses. Frontier assurance currently proves realised computation more effectively than it proves the absence of regime-conditioned computation selection. This work introduces epistemic security as an assurance property for epistemically active systems and provides its first formalisation. The framework establishes: the class of epistemically active systems; Theorem 1 demonstrating that execution integrity does not imply epistemic security for any such system with a regime-sensitive policy; Theorem 2 proving via the Data Processing Inequality that bounding I(M; E) ≤ ε mathematically guarantees bounded observable behavioural divergence; the named failure mode of regime-conditioned computation selection; a three-layer decomposition into execution integrity, context indistinguishability, and governance opacity; five named attack classes unified as exploitations of regime-observable correlations; a compositionality condition establishing that epistemic security cannot be certified component-wise; the EC-D1 resolution demonstrating that epistemic containment and deterministic auditability are not fundamentally incompatible; a cost model appropriate to consequence severity; a grounding in Probabilistic Non-Interference identifying execution regime as a high-security variable; and eight preliminary normative SHALL requirements for an Epistemic Containment Layer. The industry is currently responding to frontier model strategic behaviour with deployment constraints and gated access. These are necessary responses. They are not assurance. Assurance requires a formal framework for the properties being claimed. For the epistemic dimension of frontier AI deployment, that framework has not previously existed. --- ## Acknowledgements The author used AI language models as research and formalisation tools during the development of this framework — specifically for literature cross-referencing, formal notation review, and adversarial critique of successive drafts. This is analogous to the use of proof assistants or structured peer review in the formalisation process. All intellectual contributions, framing decisions, and technical judgements are the author's own. The framework originated from the author's analysis of the Anthropic Claude Mythos Preview system card published April 7, 2026, and its implications for the Axioma verifiable AI execution framework developed at SpeyTech. --- ## References Anthropic. (2026). *Claude Mythos Preview System Card*. Retrieved April 7, 2026, from https://www-cdn.anthropic.com/08ab9158070959f88f296514c21b7facce6f52bc.pdf Anthropic. (2026). *Project Glasswing*. Retrieved April 7, 2026, from https://www.anthropic.com/glasswing Goguen, J. A., & Meseguer, J. (1982). Security policies and security models. *Proceedings of the IEEE Symposium on Security and Privacy*, 11–20. Goldwasser, S., Micali, S., & Rackoff, C. (1989). The knowledge complexity of interactive proof systems. *SIAM Journal on Computing*, 18(1), 186–208. https://doi.org/10.1137/0218012 Hubinger, E., van Merwijk, C., Mikulik, V., Skalse, J., & Garrabrant, S. (2019). *Risks from learned optimization in advanced machine learning systems*. arXiv:1906.01820. https://doi.org/10.48550/arXiv.1906.01820 Murray, W. (2025). *C From Scratch: Learn Safety-Critical C the Right Way*. Leanpub. Murray, W. (2026). *Axioma Verifiable AI Execution Framework: SRS-001 through SRS-007*. SpeyTech. https://github.com/SpeyTech/axioma-spec Sabelfeld, A., & Myers, A. C. (2003). Language-based information-flow security. *IEEE Journal on Selected Areas in Communications*, 21(1), 5–19. https://doi.org/10.1109/JSAC.2002.806121 Shannon, C. E. (1948). A mathematical theory of communication. *The Bell System Technical Journal*, 27(3), 379–423. https://doi.org/10.1002/j.1538-7305.1948.tb01338.x --- *April 9, 2026* *SpeyTech, Inverness, Scotland* *DOI: 10.5281/zenodo.19489291* *Priority-establishing draft. Not for citation without author permission.* ======================================================================== PART II — SPECIFICATIONS ======================================================================== ======================================================================== Layer group: Foundation ======================================================================== ======================================================================== DVEC-001 — Deterministic Verifiable Execution Contract ======================================================================== Spec ID: DVEC-001 Title: Deterministic Verifiable Execution Contract Version: v1.3 Status: Production Gold Layer: Foundation Date: 2026-04-02 Supersedes: DVEC-001 v1.2 Depends on: DVM-SPEC-001 Compliance: DO-178C, IEC 62304, ISO 26262 URL: https://axilog.io/specs/dvec-001/ Changelog: https://axilog.io/specs/dvec-001/changelog/ Summary: The global contract governing the physics of the Axioma framework — defines deterministic execution, the Oracle Boundary, and the evidence chain. **Scope:** Axioma Framework · Axilog Substrate · certifiable-* Ecosystem **Alignment:** DVM-SPEC-001 v1.0-rc1 · Axioma v0.4 · MDCP · Patent GB2521625.0 --- ## Revision History | Version | Status | Notes | |---------|--------|-------| | v1.0 | Superseded | Initial draft | | v1.1 | Superseded | Fault propagation, memory totality, SRS traceability, CI gates, pre-commit guardrail, closure artifacts | | v1.2 | Superseded | Domain separation registry clarified — evidence type tags and chain tags formally separated | | v1.3 | Final | Terminology standardised to "non-conformant system"; arithmetic guardrail AST note; §2.5 terminal reset clarified | --- ## 0. Governing Principle > **If behaviour cannot be proven, it is non-conformant.** ### 0.1 Contract Versioning This contract is versioned. All code MUST declare its contract version in the module header: ```c // DVEC: v1.3 ``` A contract upgrade requires: - Explicit migration assessment - Re-verification of affected modules - Changelog entry in axiom registry - No silent adoption of new constraints --- ## 1. Determinism Mandate (Class M) ### 1.1 Bit-Identity Requirement ``` F(S, I) → O ∀ platforms P₁, P₂: Fₚ₁(S, I) = Fₚ₂(S, I) ``` Violation = catastrophic integrity failure. ### 1.2 Forbidden Constructs ``` ❌ float, double ❌ undefined behaviour (C UB of any kind) ❌ non-deterministic iteration (unordered collections) ❌ system clock access in domain logic ❌ hidden global state ❌ uncontrolled randomness ``` ### 1.3 Mandatory Constructs ``` ✅ fixed-point arithmetic (Q16.16 minimum) ✅ explicit ordering in all collections ✅ canonical encoding before hashing ✅ deterministic reduction topology ``` ### 1.4 Determinism Classification (Required) Every module MUST declare its determinism class at the top of its primary header: ```c // AXILOG DETERMINISM: D1 — Strict Deterministic // AXILOG DETERMINISM: D2 — Constrained Deterministic (deps declared below) // AXILOG DETERMINISM: D3 — Observed Non-Deterministic (oracle boundary) ``` - D1 → strict deterministic — bit-identical across all platforms - D2 → constrained deterministic — deterministic given declared dependency set (§6) - D3 → observed non-deterministic — routed through Oracle Boundary Contract (§3) --- ## 2. Totality Contract (Class M) ### 2.1 Total Function Requirement ``` ∀ input ∈ Domain: ∃ output ∈ Codomain ``` No partial functions. No undefined branches. No implicit fallthrough. ### 2.2 Boundedness All computation MUST be statically or provably bounded. ``` ❌ unbounded recursion ❌ uncontrolled loops ❌ dynamic growth without constraint ``` ### 2.3 State Machine Closure - All transitions declared exhaustively - All transitions enforced mechanically - No undeclared state reachable ### 2.4 Fault Propagation Contract (Critical) All functions MUST accept and propagate fault context: ```c int32_t dvm_add_q16(int32_t a, int32_t b, ct_fault_flags_t *faults); ``` **Required:** ``` ✅ fault context mutation at every arithmetic operation ✅ explicit propagation at every call site ✅ fault checked at execution boundary ``` **Forbidden:** ``` ❌ errno-based error handling ❌ silent failure (returning 0 without fault flag) ❌ unchecked return values ❌ ignorable error states ``` ### 2.5 Fail-Closed Terminality (Closure Invariant) Any fault flag set MUST: - Trigger transition to `FAILED` state - Halt further state mutation - Require explicit system reset to resume No fault may be cleared implicitly. No fault may be silently ignored. > **Reset scope note:** At the SRS layer, the definition of "explicit > system reset" MUST be declared per deployment context — whether > process restart, subsystem reinitialisation, or full system-level > reset. The DVEC mandates that reset is explicit and declared; the > specific reset boundary is a deployment-level SRS requirement. > Undefined reset scope constitutes a non-conformant system. --- ## 3. Oracle Boundary Contract (Class M) ### 3.1 Entropy Admission Rule No external input may influence system state unless it has been: 1. Captured 2. Canonicalised 3. Committed (AX:OBS:v1) 4. Referenced ### 3.2 Oracle Types All of the following are oracle interactions governed by this section: - LLM inference - Time injection - Vector retrieval - Sensors / physical inputs - External APIs ### 3.3 Time Rule ``` ❌ System time forbidden in domain logic ✅ Time injected as immutable canonical input ✅ Committed as AX:OBS:v1 (oracle.type: TIME_INJECTION) ``` Within domain execution, time is immutable state data. There is no concept of "current time" inside domain execution. ### 3.4 Time Monotonicity (Closure Invariant) Time inputs MUST be strictly non-decreasing. - Any rollback = protocol violation = non-conformant system - Non-monotonic time permitted only if declared at system initialisation and committed to the ledger - A system that accepts a timestamp ≤ the prior committed timestamp without declaration constitutes a non-conformant system --- ## 4. Evidence Mandate (Class M) ### 4.1 Evidence Completeness ``` cause → evidence → state transition ``` No state transition may occur without a prior committed cause. Retroactive evidence generation is non-conformant. ### 4.2 Canonicalisation All evidence payloads MUST: - Use RFC 8785 (JCS) canonicalisation - Produce byte-identical output for identical inputs - Be canonicalised BEFORE hashing ``` ❌ hashing raw structs ❌ non-canonical JSON serialisation ❌ serialiser-dependent output ``` ### 4.3 Commitment Function ``` commit(e) = SHA-256(tag ‖ LE64(|payload|) ‖ payload) ``` No variation permitted. Domain separation via tag is mandatory. ### 4.4 Domain Separation Registry (Closure Invariant — v1.2) *Clarified in v1.2: evidence type tags and chain tags are formally separated namespaces. No cross-namespace reuse permitted.* **Evidence type tags** — typed evidence records committed to the ledger: | Tag | Type | Description | |-----|------|-------------| | `AX:STATE:v1` | State Commitment | Canonical DVM state hash | | `AX:TRANS:v1` | Transition Commitment | State change witness | | `AX:OBS:v1` | Observation Record | Oracle interaction record | | `AX:POLICY:v1` | Policy Assertion | Governance rule evaluation | | `AX:PROOF:v1` | Verification Proof | Replay or conformance proof | **Chain tags** — ledger protocol prefixes, not evidence types: | Tag | Protocol | Description | |-----|----------|-------------| | `AX:LEDGER:v1` | Axioma hash chain | Per §5.2 ledger chaining | | `DVM:LEDGER:v1` | DVM computation chain | Per DVM-SPEC-001 §7 | | `DVM:STATE:v1` | DVM state commitment | Per DVM-SPEC-001 §7.1 | | `DVM:INGRESS:v1` | DVM ingress oracle | Per DVM-SPEC-001 §7.1 | **Rules:** - Evidence type tags MAY appear as payloads in the ledger chain - Chain tags MAY NOT be used as evidence type identifiers - No tag from either namespace may be reused in the other - No ad hoc tags permitted outside this registry ### 4.5 Evidence Type Versioning The evidence type set is closed within a major version. New evidence types require: - A new major version tag (e.g. `AX:OBS:v2`) - A formal migration specification - Backward compatibility proof for existing chains - Registry update with explicit changelog entry --- ## 5. Ledger Contract (Class M) ### 5.1 Total Order Guarantee ``` ∀ events A, B: A < B XOR B < A ``` No two events share the same chain position. No concurrency ambiguity permitted. Enforced via per-organisation chain head lock (SELECT FOR UPDATE). ### 5.2 Hash Chain Integrity ``` L₀ = SHA-256("AX:LEDGER:v1" ‖ commit(e₀)) Lₙ = SHA-256("AX:LEDGER:v1" ‖ Lₙ₋₁ ‖ commit(eₙ)) ``` Any break invalidates the entire downstream chain. ### 5.3 Immutability ``` ✅ Append-only ❌ No UPDATE on committed records ❌ No DELETE on committed records ``` --- ## 6. Dependency Closure (Class M — D2 Components) All D2 components MUST declare their complete dependency set in the module header: | Dependency | Requirement | |------------|-------------| | Model version | Fully qualified identifier + version hash | | Parameters | All runtime parameters — no defaults | | Tool versions | External tool version identifiers | | Configuration | All parameters influencing behaviour | | Data snapshot | Index state hash, corpus hash | A missing dependency constitutes a non-conformant system — not a runtime surprise. --- ## 7. Cross-Platform Identity (Class M) ### 7.1 DVM Contract All D1 execution MUST be: - Integer-only arithmetic - Saturating on overflow - Defined overflow behaviour - Identical reduction topology ### 7.2 Widen-Then-Operate (Closure Invariant) All fixed-point arithmetic MUST follow: ``` 1. Widen operands (e.g. int32_t → int64_t) 2. Operate 3. Saturate to target width 4. Record fault flag if saturated ``` No raw operator arithmetic on fixed-point types. ### 7.3 Golden Reference Requirement All D1 systems MUST: - Produce a certifiable-harness compatible 368-byte golden reference - Match bit-identically across x86_64, ARM64, and (future) RISC-V - Fail CI if golden reference diverges between architectures Failure = non-conformant system. --- ## 8. No Boilerplate Rule ### 8.1 The Three-Part Test Every line of code must satisfy at least one of: 1. Enforces an invariant 2. Implements a contract 3. Contributes to a proof If none apply — delete it. ### 8.2 Prohibition ``` ❌ wrapper abstractions without invariants ❌ generic helpers without proof value ❌ duplicated patterns without formal reason ❌ defensive code masking invariant failure ``` ### 8.3 Deferred Correctness Prohibition (Critical) Forbidden in all production code: ``` ❌ TODO ❌ FIXME ❌ OPTIMIZE ❌ HACK ❌ commented-out code blocks ❌ placeholder returns (0, NULL without fault) ❌ incomplete switch arms with silent fallthrough ❌ stub implementations ``` > **A TODO is an undeclared invariant failure.** If a proof obligation cannot be satisfied now, it MUST be registered as an explicit open axiom in the registry — not hidden in a comment. --- ## 9. Proof & Traceability ### 9.1 CI Gate (Mandatory) CI MUST execute and pass ALL of the following: ``` ✅ verify-axiom-coverage (all Class M axioms dual-layer anchored) ✅ cross-platform bit-identity test (D1 components) ✅ hash stability test (commitment reproducibility) ✅ property test suite (all registered tests) ✅ static analysis — zero warnings (clang-tidy, cppcheck) ✅ forbidden pattern scan (§16) ✅ TODO/FIXME/HACK scan ✅ missing SRS anchor detection ✅ raw arithmetic on fixed-point types detection ``` A merge that fails any gate constitutes a non-conformant system regardless of review approval. ### 9.2 SRS Traceability (Critical) Every public function MUST include a requirements anchor: ```c // SRS-042-SHALL: Deterministic addition must saturate on overflow int32_t dvm_add_q16(int32_t a, int32_t b, ct_fault_flags_t *faults); ``` - 1:1 mapping: function ↔ requirement - No orphan code permitted - No orphan requirements permitted --- ## 10. Testing = Proof ### 10.1 Required Test Classes ``` ✅ Property-based tests (all inputs, not happy path) ✅ Cross-platform identity tests ✅ Replay equivalence tests ✅ Hash stability tests ✅ Fault injection tests (all fault paths exercised) ``` ### 10.2 Forbidden Test Patterns ``` ❌ Example-based happy path tests only ❌ Non-deterministic mocks (random output, time-dependent) ❌ Mocks bypassing oracle contract ❌ Unverified snapshot tests without canonicalisation ❌ Tests that pass on one platform but are not verified on others ``` --- ## 11. Performance Contract Performance optimisations MUST NOT: - Break determinism - Introduce non-deterministic ordering - Alter reduction topology - Change observable fault behaviour **Correctness > Performance. Always.** A performance optimisation that alters any of the above is a correctness regression, not an improvement. --- ## 12. Code Standards (C99) ### 12.1 Memory Totality (Critical) ``` ❌ malloc / free / realloc in runtime paths ✅ Static allocation at initialisation ✅ Caller-provided buffers ``` All buffer ownership MUST be explicit: ```c /* Correct pattern — caller owns all memory */ void dvm_matmul( int32_t *out, /* caller-allocated output */ const int32_t *a, /* caller-owned input */ const int32_t *b, /* caller-owned input */ size_t n, ct_fault_flags_t *faults ); ``` No hidden allocation. No implicit ownership transfer. ### 12.2 Arithmetic Enforcement (Critical) ``` ❌ Raw operators on fixed-point types (+, -, *, /) ✅ dvm_add_q16() ✅ dvm_mul_q16() ✅ dvm_div_q16() ✅ Saturating operations with fault propagation ``` ### 12.3 Compiler Contract ``` ✅ Strict C99 only ✅ -Wall -Wextra -Werror ✅ No implicit casts ✅ Explicit integer sizes (uint32_t, int64_t, etc.) ✅ Must compile identically: GCC, Clang, MSVC ❌ No compiler-specific extensions ❌ No UB (validated by static analysis) ❌ No uninitialised memory ❌ No pointer aliasing ambiguity ``` --- ## 13. Concurrency Contract Where parallel execution is used: ``` ✅ Fixed tree reduction topology ✅ Identical reduction order across runs ✅ Deterministic scheduling ❌ Race conditions ❌ Unordered reduction ❌ Shared mutable state without explicit control ``` A parallel implementation is conformant if and only if it produces bit-identical canonical state to sequential execution. --- ## 14. Verification Checklist (Mandatory Before Merge) ``` Determinism ☐ Determinism class declared in module header ☐ No forbidden constructs present ☐ Bit-identical across platforms (D1) Totality ☐ All inputs mapped to outputs ☐ No undefined states reachable ☐ All fault paths exercised Evidence ☐ All state transitions have prior evidence ☐ RFC 8785 canonicalisation applied ☐ Correct tag from domain separation registry (§4.4) Ledger ☐ Total order preserved ☐ No UPDATE or DELETE Oracle ☐ All external inputs committed before use ☐ Time injected via Time Oracle Memory ☐ No heap allocation in runtime paths ☐ All buffer ownership declared Proof ☐ SRS anchor present on every public function ☐ No TODO / FIXME / HACK ☐ Golden reference match (D1 systems) CI ☐ All CI gates will pass ``` --- ## 15. Code Review Contract **A review is verification, not approval.** A reviewer MUST explicitly confirm: - Determinism class declared and correct - No forbidden constructs present - Fault propagation complete at every call site - SRS traceability complete - Memory ownership declared - Domain separation tags correct (§4.4) - CI gates will pass Approval without verification constitutes a non-conformant system. A review that does not confirm the above is invalid and non-conformant. --- ## 16. Pre-Commit Guardrail Automatic rejection if any of the following are detected: **Memory violations:** ``` malloc free realloc ``` **Floating-point violations:** ``` float double ``` **Deferred correctness:** ``` TODO FIXME HACK ??? OPTIMIZE ``` **Time violations:** ``` time( clock( gettimeofday( clock_gettime( ``` **Traceability violations:** ``` public function without SRS anchor ``` **Arithmetic violations:** ``` raw + - * / on fixed-point types without dvm_* wrapper ``` > **Implementation note:** Raw arithmetic detection MUST use AST-level > analysis (clang-tidy plugin or equivalent) — not grep. Token-level > scanning cannot distinguish operator context. A grep-based scan is > insufficient and constitutes a non-conformant system. **Tag violations:** ``` evidence tag not in §4.4 registry chain tag used as evidence type ``` --- ## 17. Closure Artifacts (Required) The system MUST include and maintain: | Artifact | Purpose | |----------|---------| | Mechanised RTM | SRS ↔ code 1:1 traceability map | | Golden verifier | Cross-platform bit-identity validation | | JCS linter | RFC 8785 canonicalisation verification | | Static WCET gate | Worst-case execution time bound proof | | Domain tag linter | §4.4 registry conformance check | --- ## 18. Closing Principle > A system is not correct because it passes tests. > It is correct because it cannot be incorrect without detection. --- ## Final Statement > **This contract enforces not just correctness —** > **but the inevitability of correctness.** --- ## Ecosystem Alignment | Layer | Document | Status | |-------|----------|--------| | Computation | DVM-SPEC-001 v1.0-rc1 | Complete | | Framework | Axioma v0.4 | Complete | | Development | DVEC-001 v1.3 | Final | | Substrate | axilog.io | Registered | | Proven patterns | SpeyBooks Kernel (M1–M7) | Production Gold | | Existing assets | certifiable-* (9 repos) | Production Gold | --- *DVEC-001 v1.3 — Final* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== Layer group: L1 — Substrate ======================================================================== ======================================================================== SRS-001-DETERMINISTIC-HASH — Deterministic Hash Table ======================================================================== Spec ID: SRS-001-DETERMINISTIC-HASH Title: Deterministic Hash Table Version: v0.1 Status: Final Layer: L1 Determinism: D1 Date: 2026-01-20 Compliance: MISRA-C:2012, ISO 26262 URL: https://axilog.io/specs/srs-001-deterministic-hash/ Changelog: https://axilog.io/specs/srs-001-deterministic-hash/changelog/ Summary: The certifiable-inference hash-table contract — platform-independent hashing, deterministic collision resolution, insertion-order iteration, zero malloc. **Component:** Containers **Compliance:** MISRA-C:2012 · ISO 26262 **Applicability:** All certifiable-* components requiring key-value storage --- ## 1. Purpose The system shall provide a hash table implementation with deterministic behavior, including: 1. Platform-independent hash computation 2. Deterministic collision resolution 3. Insertion-order iteration (not hash-order) 4. Static memory allocation (no malloc/free) ## 2. Requirements ### 2.1 Hash Function **SRS-001.1:** The system shall use the FNV-1a hash algorithm for all key hashing operations. **Rationale:** FNV-1a produces identical results across all platforms using only integer arithmetic. No floating-point or platform-specific instructions are required. **Mathematical Definition:** ``` hash ← 2166136261 (FNV offset basis, 32-bit) FOR each byte c in key: hash ← hash XOR c hash ← hash × 16777619 (FNV prime) RETURN hash ``` **Verification:** Unit tests comparing hash output against known test vectors. --- **SRS-001.2:** The hash function shall produce identical output regardless of: - Target architecture (x86, ARM, RISC-V) - Compiler vendor (GCC, Clang, MSVC) - Optimization level (-O0 through -Ofast) - Endianness (little-endian, big-endian) **Rationale:** Deterministic hashing is foundational for reproducible model weight storage and lookup. **Verification:** Cross-platform testing with checksum comparison. ### 2.2 Collision Resolution **SRS-001.3:** The system shall use linear probing for collision resolution. **Mathematical Definition:** ``` probe_index(hash, attempt, capacity) = (hash + attempt) mod capacity ``` Where `attempt` increments from 0 until an empty slot is found. **Rationale:** Linear probing is deterministic (probe sequence depends only on hash value), cache-friendly, and simple to verify. **Verification:** Unit tests with keys that produce hash collisions. --- **SRS-001.4:** Duplicate key insertion shall return `D_TABLE_KEY_EXISTS` without modifying the existing entry. **Rationale:** Predictable behavior on duplicate keys prevents silent data corruption. **Verification:** Unit test `test_duplicate_key`. ### 2.3 Iteration Order **SRS-001.5:** Iteration shall occur in insertion order, not hash order. **Rationale:** Hash order varies with table capacity and load factor. Insertion order is deterministic and reproducible. **Implementation:** Maintain a separate `insertion_order[]` array tracking the order of insertions. **Verification:** Unit test `test_deterministic_iteration_order`. --- **SRS-001.6:** Two tables with identical insertion sequences shall produce identical iteration sequences. **Mathematical Definition:** ``` ∀ sequences S₁, S₂: S₁ = S₂ ⟹ iterate(table₁) = iterate(table₂) ``` **Verification:** Unit test `test_hash_consistency` with memory state comparison. ### 2.4 Memory Management **SRS-001.7:** The hash table shall use caller-provided buffers with no dynamic allocation. **Rationale:** Dynamic allocation introduces non-deterministic timing and potential fragmentation. Safety-critical systems require bounded, predictable memory usage. **API Pattern:** ```c uint8_t buffer[REQUIRED_SIZE]; d_table_t table; d_table_init(&table, buffer, sizeof(buffer)); ``` **Verification:** Static analysis confirming no malloc/free calls. --- **SRS-001.8:** Initialization shall zero all memory to prevent uninitialized data from affecting behavior. **Rationale:** Uninitialized memory can contain address-dependent garbage, breaking determinism. **Verification:** Unit test `test_hash_consistency` comparing memory states across multiple runs. ### 2.5 Capacity and Bounds **SRS-001.9:** The table shall enforce a maximum capacity specified at initialization. **Rationale:** Unbounded growth requires dynamic allocation. Fixed capacity enables static memory analysis. **Verification:** Unit test `test_capacity_limit`. --- **SRS-001.10:** Insertion into a full table shall return `D_TABLE_FULL` without modifying any state. **Rationale:** Predictable failure behavior enables proper error handling. **Verification:** Unit test `test_capacity_limit`. ## 3. Verification Criteria **V-001.1: Cross-Platform Parity** Unit tests shall verify identical hash output on at least two CPU architectures. **Test Matrix:** - x86_64 (Ubuntu 24.04, GCC 13) - ARM64 (Raspberry Pi, GCC 13) - RISC-V (QEMU, GCC 13) — optional **Pass Criteria:** Byte-identical memory states after identical insertion sequences. --- **V-001.2: Memory State Comparison** The `test_hash_consistency` suite shall: 1. Execute identical workloads N times (N ≥ 3) 2. Compare byte-for-byte memory states between runs 3. Verify all comparisons are identical **Pass Criteria:** Zero bytes differ between any pair of runs. --- **V-001.3: No Floating-Point Instructions** Static analysis or disassembly shall verify that `deterministic_hash.c` contains no floating-point instructions. **Method:** `objdump -d` inspection for FPU mnemonics. **Pass Criteria:** Zero floating-point instructions in compiled binary. --- **V-001.4: Iteration Order Stability** Unit tests shall verify that iteration order depends only on insertion order, not on: - Table capacity - Hash function output - Memory addresses **Pass Criteria:** Identical iteration sequences for identical insertion sequences. ## 4. Implementation **Files:** - `include/deterministic_hash.h` — API specification - `src/containers/deterministic_hash.c` — Implementation - `tests/unit/test_hash_basic.c` — Functional tests - `tests/unit/test_hash_consistency.c` — Determinism tests **Traceability:** - Code: `@traceability SRS-001-DETERMINISM` - Tests: Link to this document in header ## 5. Data Structures ### 5.1 Result Codes ```c typedef enum { D_TABLE_OK = 0, /* Success */ D_TABLE_KEY_EXISTS, /* Insert failed: key exists */ D_TABLE_NOT_FOUND, /* Get failed: key not found */ D_TABLE_FULL, /* Insert failed: at capacity */ D_TABLE_ERROR /* Generic error */ } d_table_res_t; ``` ### 5.2 Entry Structure ```c typedef struct { char key[D_TABLE_MAX_KEY_LEN]; /* Null-terminated key */ int32_t value; /* Associated value */ bool occupied; /* Slot contains valid data */ } d_table_entry_t; ``` ### 5.3 Table Structure ```c typedef struct { d_table_entry_t *entries; /* Hash slots (caller-owned) */ uint32_t *insertion_order; /* Iteration order tracking */ uint32_t capacity; /* Maximum entries */ uint32_t count; /* Current entry count */ } d_table_t; ``` ## 6. API Specification ### 6.1 Initialization ```c d_table_res_t d_table_init(d_table_t *table, uint8_t *buffer, size_t buffer_size); ``` **Preconditions:** - `table != NULL` - `buffer != NULL` - `buffer_size >= D_TABLE_MIN_BUFFER_SIZE` **Postconditions:** - `table->count == 0` - `table->capacity > 0` - All entries marked as unoccupied - Buffer memory zeroed ### 6.2 Insert ```c d_table_res_t d_table_insert(d_table_t *table, const char *key, int32_t value); ``` **Preconditions:** - `table` is initialized - `key != NULL` - `strlen(key) < D_TABLE_MAX_KEY_LEN` **Postconditions (on success):** - `table->count` incremented by 1 - Key-value pair stored - Insertion order recorded ### 6.3 Get ```c d_table_res_t d_table_get(const d_table_t *table, const char *key, int32_t *value); ``` **Preconditions:** - `table` is initialized - `key != NULL` - `value != NULL` **Postconditions (on success):** - `*value` contains the stored value ### 6.4 Iterate ```c void d_table_iterate(const d_table_t *table, d_table_iter_fn callback); ``` **Preconditions:** - `table` is initialized - `callback != NULL` **Postconditions:** - Callback invoked for each entry in insertion order ## 7. Design Rationale ### 7.1 Why FNV-1a? **Alternatives considered:** - Jenkins: Good distribution but more complex - MurmurHash: Uses multiplication that may vary with compiler - CRC32: Hardware acceleration varies by platform - SHA-256: Overkill for hash table indexing **Decision:** FNV-1a is simple, fast, deterministic, and has no platform-specific behavior. ### 7.2 Why Linear Probing? **Alternatives considered:** - Quadratic probing: Probe sequence depends on attempt², may skip slots - Double hashing: Requires second hash function - Chaining: Requires dynamic allocation for linked lists **Decision:** Linear probing is simplest to implement correctly and verify. ### 7.3 Why Insertion-Order Iteration? **Problem:** Standard hash table iteration visits entries in hash-bucket order, which: - Varies with table capacity - Varies with insertion order due to collision chains - Is effectively non-deterministic for verification purposes **Solution:** Track insertion order separately. O(1) space overhead per entry. ## 8. Test Mapping | Requirement | Test Function | Test File | |-------------|---------------|-----------| | SRS-001.1 | (implicit in all tests) | — | | SRS-001.2 | test_hash_consistency | test_hash_consistency.c | | SRS-001.3 | test_insert_and_get | test_hash_basic.c | | SRS-001.4 | test_duplicate_key | test_hash_basic.c | | SRS-001.5 | test_deterministic_iteration_order | test_hash_basic.c | | SRS-001.6 | test_hash_consistency | test_hash_consistency.c | | SRS-001.7 | (static analysis) | — | | SRS-001.8 | test_hash_consistency | test_hash_consistency.c | | SRS-001.9 | test_capacity_limit | test_hash_basic.c | | SRS-001.10 | test_capacity_limit | test_hash_basic.c | ## 9. References - **MISRA-C:2012** — Rule 21.3 (No dynamic memory allocation) - **ISO 26262-6:2018** — Software unit design - **Fowler-Noll-Vo Hash** — http://www.isthe.com/chongo/tech/comp/fnv/ ## 10. Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0 | 2026-01-20 | William Murray | Full specification (expanded from stub) | --- **Document Classification:** Technical Specification **Approval Status:** Approved for Implementation **Next Review:** 2026-04-20 ======================================================================== SRS-005 — DVM Arithmetic, Comparison & Mathematical Primitives ======================================================================== Spec ID: SRS-005 Title: DVM Arithmetic, Comparison & Mathematical Primitives Version: v1.1 Status: Locked Layer: L1 Determinism: D1 Date: 2026-03-27 Supersedes: SRS-005 v1.0 Depends on: SRS-001, DVEC-001, DVM-SPEC-001 URL: https://axilog.io/specs/srs-005/ Changelog: https://axilog.io/specs/srs-005/changelog/ Summary: Closes the L1 arithmetic substrate — Q16.16 representation, saturating operations with fault propagation, and the primitives every higher layer must consume. **Depends on:** SRS-001 v0.3 · DVEC-001 v1.3 · DVM-SPEC-001 v1.0-rc1 --- ## 0. GOVERNING PRINCIPLE > **L7 can certify policy and evidence only if L1 fixes the arithmetic > semantics those policies and proofs depend on.** Without mathematically closed L1 primitives: - L4 velocity comparisons are semantically undefined - L2 activation functions are implementation-dependent - L3 scoring arithmetic is not reproducible - L6 audit proofs rest on an unclosed substrate **This document closes L1.** --- ## 1. PURPOSE This document defines the **DVM Arithmetic, Comparison & Mathematical Primitives Specification** for the Axilog substrate (libaxilog). It specifies: - Q16.16 representation model - Conversion semantics (integer ↔ Q16.16) - Core arithmetic (add, sub, mul, div, negate, abs, min, max, clamp) - Comparison and ordering - Fault contract - Transcendental approximations (exp, tanh) - Lookup-table / polynomial rules - Purity and boundedness - Cross-platform identity - Forbidden dependencies **Objective:** Every arithmetic operation used by L2–L7 SHALL be mathematically total, bit-identical across platforms, and formally verifiable. --- ## 2. CONFORMANCE A software component is conformant only if: - It implements all applicable SHALL statements - Each SHALL has a declared verification method - All verification methods pass - All associated DVEC-001 v1.3 constraints are satisfied Non-conformance is a system integrity failure. --- ## 3. REQUIREMENT FORMAT Each requirement is identified as: ``` SRS-005-SHALL-NNN ``` Each requirement includes: - ID - Statement - Rationale (where applicable) - Verification method **Allowed verification methods:** | Method | Description | |--------|-------------| | `test` | Deterministic unit test | | `property test` | Property-based test over input domain | | `static analysis` | Automated static analysis tool | | `inspection` | Manual code or design review | | `cross-platform harness` | certifiable-harness compatible golden reference | | `golden vector` | Reference input/output vectors for bit-identity | | `fault injection test` | Induced fault condition verification | | `schema test` | Evidence schema conformance test | | `RTM generation` | Requirements traceability matrix tooling | --- ## 4. REPRESENTATION MODEL ### 4.1 Fixed-Point Type **SRS-005-SHALL-001** All deterministic arithmetic SHALL use Q16.16 fixed-point representation stored in `int32_t`. **Rationale:** Q16.16 provides 16 bits of integer range [-32768, 32767] and 16 bits of fractional precision (1/65536 ≈ 0.0000153), sufficient for weights, activations, and policy thresholds. **Verification:** inspection, static analysis --- ### 4.2 Unity Constant **SRS-005-SHALL-002** The value 1.0 SHALL be exactly 65536. ```c #define Q16_ONE 65536 /* 0x00010000 */ #define Q16_HALF 32768 /* 0x00008000 */ ``` **Verification:** test, inspection --- ### 4.3 Representation Bounds **SRS-005-SHALL-003** The Q16.16 representation bounds SHALL be: | Constant | Value | Hexadecimal | |----------|-------|-------------| | `Q16_MAX` | INT32_MAX | 0x7FFFFFFF | | `Q16_MIN` | INT32_MIN | 0x80000000 | | `Q16_EPS` | 1 | 0x00000001 | **Verification:** inspection, test --- ### 4.4 Two's-Complement Requirement **SRS-005-SHALL-004** The implementation SHALL assume two's-complement signed integer representation. The target compiler and platform MUST guarantee two's-complement semantics. **Verification:** inspection, static analysis, platform documentation --- ## 5. CONVERSION SEMANTICS ### 5.1 Integer to Q16.16 Conversion **SRS-005-SHALL-005** Integer-to-Q16.16 conversion SHALL use multiplication by 65536: ```c q16_16_t ax_int_to_q16(int16_t n, ct_fault_flags_t *faults) { return (int32_t)n * Q16_ONE; } ``` **Constraint:** Input SHALL be `int16_t` to guarantee no overflow. **Verification:** property test, inspection --- ### 5.2 Q16.16 to Integer Conversion **SRS-005-SHALL-006** Q16.16-to-integer conversion SHALL use division by 65536 with truncation toward zero: ```c int32_t ax_q16_to_int(q16_16_t x, ct_fault_flags_t *faults) { return x / Q16_ONE; /* C99 truncation toward zero */ } ``` **Verification:** property test, inspection --- ### 5.3 Q16.16 to Integer with Rounding **SRS-005-SHALL-007** Q16.16-to-integer conversion with rounding SHALL use round-to-nearest-even: ```c int32_t ax_q16_to_int_rne(q16_16_t x, ct_fault_flags_t *faults) { (void)faults; /* No fault possible */ int32_t base = x / Q16_ONE; /* Integer part (truncates toward zero) */ int32_t frac = x - (base * Q16_ONE); /* Fractional remainder */ /* Handle negative fractional part */ if (frac < 0) { frac = -frac; } if (frac > Q16_HALF) { /* Round away from zero */ return (x >= 0) ? base + 1 : base - 1; } else if (frac < Q16_HALF) { /* Round toward zero */ return base; } else { /* Tie: round to even */ if (base & 1) { return (x >= 0) ? base + 1 : base - 1; } return base; } } ``` **Rationale:** Uses division instead of right-shift to avoid implementation-defined behaviour for negative signed integers. **Verification:** property test, golden vector --- ### 5.4 No Floating-Point Conversion **SRS-005-SHALL-008** No L1 primitive SHALL include a floating-point conversion path. ``` ❌ (q16_16_t)(f * 65536.0f) ❌ (float)x / 65536.0f ``` **Verification:** static analysis, inspection --- ### 5.5 Decimal String Import **SRS-005-SHALL-009** Decimal string import (if provided) SHALL use deterministic fixed-point parsing with explicit rounding mode declaration and no floating-point intermediate. **Verification:** property test, inspection --- ## 6. CORE ARITHMETIC ### 6.1 Saturated Addition **SRS-005-SHALL-010** Saturated addition SHALL widen operands to `int64_t`, compute the sum, and clamp to [Q16_MIN, Q16_MAX]: ```c q16_16_t ax_add_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { int64_t sum = (int64_t)a + (int64_t)b; if (sum > INT32_MAX) { faults->overflow = 1; return INT32_MAX; } if (sum < INT32_MIN) { faults->underflow = 1; return INT32_MIN; } return (int32_t)sum; } ``` **Verification:** property test, fault injection test, cross-platform harness --- ### 6.2 Saturated Subtraction **SRS-005-SHALL-011** Saturated subtraction SHALL widen operands to `int64_t`, compute the difference, and clamp to [Q16_MIN, Q16_MAX]: ```c q16_16_t ax_sub_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { int64_t diff = (int64_t)a - (int64_t)b; if (diff > INT32_MAX) { faults->overflow = 1; return INT32_MAX; } if (diff < INT32_MIN) { faults->underflow = 1; return INT32_MIN; } return (int32_t)diff; } ``` **Verification:** property test, fault injection test, cross-platform harness --- ### 6.3 Saturated Multiplication **SRS-005-SHALL-012** Saturated multiplication SHALL compute `(a × b) / 65536` using widened intermediate arithmetic with **truncation toward zero**: ```c q16_16_t ax_mul_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { int64_t prod = (int64_t)a * (int64_t)b; int64_t result = prod / Q16_ONE; /* C99 truncation toward zero */ if (result > INT32_MAX) { faults->overflow = 1; return INT32_MAX; } if (result < INT32_MIN) { faults->underflow = 1; return INT32_MIN; } return (int32_t)result; } ``` **Verification:** property test, fault injection test, cross-platform harness --- ### 6.3.1 Multiplication Rounding Mode (Mandatory) **SRS-005-SHALL-067** All Q16.16 multiplication SHALL use truncation toward zero. No alternative rounding mode is permitted in the core multiplication primitive. Applications requiring round-to-nearest-even multiplication SHALL use `ax_mul_q16_rne()` explicitly. **Rationale:** Ensures bit-identical behaviour across all platforms and implementations. Truncation is the C99 default for integer division, eliminating any implementation-defined variance. **Verification:** cross-platform harness, golden vector, inspection --- ### 6.4 Saturated Division **SRS-005-SHALL-013** Saturated division SHALL compute `(a × 65536) / b` using widened intermediate arithmetic and SHALL set `div_zero` if `b == 0`: ```c q16_16_t ax_div_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { if (b == 0) { faults->div_zero = 1; return 0; } int64_t num = (int64_t)a * Q16_ONE; int64_t result = num / (int64_t)b; if (result > INT32_MAX) { faults->overflow = 1; return INT32_MAX; } if (result < INT32_MIN) { faults->underflow = 1; return INT32_MIN; } return (int32_t)result; } ``` **Verification:** property test, fault injection test, cross-platform harness --- ### 6.4.1 Division Overflow Edge Cases **SRS-005-SHALL-069** Division overflow cases, including `INT32_MIN / -1`, SHALL be treated as saturation with the `overflow` flag set. **Rationale:** `INT32_MIN / -1` would produce `INT32_MAX + 1` which cannot be represented. This case SHALL saturate to `INT32_MAX` with the overflow flag set. **Verification:** fault injection test, golden vector --- ### 6.4.2 No Signed Right-Shift for Division **SRS-005-SHALL-068** Right-shift operations on signed integers SHALL NOT be used to implement arithmetic division or scaling. All scaling SHALL use explicit division or multiplication. ``` ❌ int32_t base = x >> 16; ✅ int32_t base = x / Q16_ONE; ``` **Rationale:** Right-shift of negative signed integers is implementation-defined in C99 and violates cross-platform determinism (SRS-005-SHALL-054). Some compilers perform arithmetic shift (correct), others perform logical shift (incorrect for signed values). **Verification:** static analysis, inspection, pre-commit scan --- ### 6.5 Negation **SRS-005-SHALL-014** Negation SHALL handle the asymmetric two's-complement range with saturation: ```c q16_16_t ax_neg_q16(q16_16_t x, ct_fault_flags_t *faults) { if (x == INT32_MIN) { faults->overflow = 1; return INT32_MAX; } return -x; } ``` **Rationale:** `-INT32_MIN` overflows in two's-complement. **Verification:** property test, fault injection test --- ### 6.6 Absolute Value **SRS-005-SHALL-015** Absolute value SHALL handle INT32_MIN with saturation: ```c q16_16_t ax_abs_q16(q16_16_t x, ct_fault_flags_t *faults) { if (x == INT32_MIN) { faults->overflow = 1; return INT32_MAX; } return (x < 0) ? -x : x; } ``` **Verification:** property test, fault injection test --- ### 6.7 Minimum **SRS-005-SHALL-016** Minimum SHALL return the lesser of two values: ```c q16_16_t ax_min_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { (void)faults; /* No fault possible */ return (a < b) ? a : b; } ``` **Verification:** property test --- ### 6.8 Maximum **SRS-005-SHALL-017** Maximum SHALL return the greater of two values: ```c q16_16_t ax_max_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults) { (void)faults; /* No fault possible */ return (a > b) ? a : b; } ``` **Verification:** property test --- ### 6.9 Clamp **SRS-005-SHALL-018** Clamp SHALL constrain a value to [min, max]: ```c q16_16_t ax_clamp_q16(q16_16_t x, q16_16_t lo, q16_16_t hi, ct_fault_flags_t *faults) { if (lo > hi) { faults->domain = 1; return lo; } if (x < lo) return lo; if (x > hi) return hi; return x; } ``` **Verification:** property test, fault injection test --- ### 6.9.1 Clamp Invalid Bounds Behaviour **SRS-005-SHALL-070** If clamp bounds are invalid (`lo > hi`), the function SHALL: 1. Set the `domain` fault flag 2. Return `lo` 3. Perform no further evaluation **Rationale:** Defines deterministic behaviour for invalid input. Returning `lo` provides a consistent, predictable result rather than undefined behaviour. **Verification:** fault injection test, inspection --- ## 7. COMPARISON AND ORDERING ### 7.1 Signed Comparison **SRS-005-SHALL-019** All Q16.16 comparisons SHALL be signed, total, and bit-identical across platforms. **Verification:** cross-platform harness, property test --- ### 7.2 No Floating-Point Comparison **SRS-005-SHALL-020** Comparison primitives SHALL NOT use floating-point conversion or host math libraries. **Verification:** static analysis, inspection --- ### 7.3 Equality **SRS-005-SHALL-021** Equality SHALL be exact bit comparison: ```c bool ax_eq_q16(q16_16_t a, q16_16_t b) { return a == b; } ``` **Verification:** test, inspection --- ### 7.4 Less-Than **SRS-005-SHALL-022** Less-than SHALL use signed integer comparison: ```c bool ax_lt_q16(q16_16_t a, q16_16_t b) { return a < b; } ``` **Verification:** property test --- ### 7.5 Greater-Than **SRS-005-SHALL-023** Greater-than SHALL use signed integer comparison: ```c bool ax_gt_q16(q16_16_t a, q16_16_t b) { return a > b; } ``` **Verification:** property test --- ### 7.6 Less-Than-Or-Equal **SRS-005-SHALL-024** Less-than-or-equal SHALL use signed integer comparison: ```c bool ax_le_q16(q16_16_t a, q16_16_t b) { return a <= b; } ``` **Verification:** property test --- ### 7.7 Greater-Than-Or-Equal **SRS-005-SHALL-025** Greater-than-or-equal SHALL use signed integer comparison: ```c bool ax_ge_q16(q16_16_t a, q16_16_t b) { return a >= b; } ``` **Verification:** property test --- ### 7.8 Sign Classification **SRS-005-SHALL-026** Sign classification SHALL be deterministic: ```c typedef enum { AX_SIGN_NEGATIVE = -1, AX_SIGN_ZERO = 0, AX_SIGN_POSITIVE = 1 } ax_sign_t; ax_sign_t ax_sign_q16(q16_16_t x) { if (x < 0) return AX_SIGN_NEGATIVE; if (x > 0) return AX_SIGN_POSITIVE; return AX_SIGN_ZERO; } ``` **Verification:** property test --- ### 7.9 Total Ordering Guarantee **SRS-005-SHALL-027** The Q16.16 type SHALL define a total order over all 2³² values. No value is incomparable to any other. **Verification:** inspection, property test --- ### 7.10 Monotonicity Classification **SRS-005-SHALL-028** All L1 functions SHALL declare their monotonicity classification in their documentation. The allowed classifications are: | Classification | Definition | |----------------|------------| | `MONOTONE_INCREASING` | ∀ a < b: f(a) ≤ f(b) | | `MONOTONE_DECREASING` | ∀ a < b: f(a) ≥ f(b) | | `NON_MONOTONIC` | Neither of the above | **Required declarations:** | Function | Monotonicity | |----------|-------------| | `ax_add_q16(a, k)` (fixed k) | MONOTONE_INCREASING | | `ax_sub_q16(a, k)` (fixed k) | MONOTONE_INCREASING | | `ax_mul_q16(a, k)` (k > 0) | MONOTONE_INCREASING | | `ax_mul_q16(a, k)` (k < 0) | MONOTONE_DECREASING | | `ax_neg_q16` | MONOTONE_DECREASING | | `ax_abs_q16` | NON_MONOTONIC | | `ax_exp_q16` | MONOTONE_INCREASING | | `ax_tanh_q16` | MONOTONE_INCREASING | **Verification:** inspection, documentation audit --- ## 8. FAULT CONTRACT ### 8.1 Fault Context Acceptance **SRS-005-SHALL-029** Every public L1 primitive SHALL accept `ct_fault_flags_t *faults`. **Verification:** static analysis, inspection --- ### 8.2 Arithmetic Fault Types **SRS-005-SHALL-030** The fault context SHALL include at minimum: ```c typedef struct { uint8_t overflow; /* Result exceeded Q16_MAX */ uint8_t underflow; /* Result exceeded Q16_MIN */ uint8_t div_zero; /* Division by zero */ uint8_t domain; /* Input outside valid domain */ uint8_t protocol; /* Reserved: higher-layer integration (L5+) */ } ct_fault_flags_t; ``` **Note on `protocol` field:** The `protocol` flag is reserved for higher-layer integration (L5 agent state machines, L4 policy violations). L1 primitives SHALL NOT set this flag. It is included in the L1 struct definition to ensure a single fault type across all layers. **Verification:** inspection --- ### 8.3 Saturation Fault Signalling **SRS-005-SHALL-031** Any arithmetic saturation SHALL set `overflow` or `underflow` as applicable. **Verification:** fault injection test, property test --- ### 8.4 Totality Requirement **SRS-005-SHALL-032** All L1 primitives SHALL be total functions over their declared domain. No undefined output for any valid input. **Verification:** property test, inspection --- ### 8.5 Purity Requirement **SRS-005-SHALL-033** All L1 primitives SHALL be pure, reentrant, and free of global mutable state. **Verification:** static analysis, inspection --- ### 8.6 No Silent Failure **SRS-005-SHALL-034** No L1 primitive SHALL return a value without setting the appropriate fault flag if a fault condition occurred. **Verification:** fault injection test, inspection --- ### 8.7 Fault Propagation **SRS-005-SHALL-035** Fault flags SHALL propagate: once set, they SHALL remain set until explicitly cleared by the caller. **Verification:** property test --- ## 9. BOUNDEDNESS AND MEMORY ### 9.1 Bounded Time **SRS-005-SHALL-036** All L1 primitives SHALL execute in bounded time O(1). **Verification:** static analysis, WCET analysis, inspection --- ### 9.2 Bounded Space **SRS-005-SHALL-037** All L1 primitives SHALL execute in bounded stack space. No recursion. No unbounded loops. **Verification:** static analysis, `-fstack-usage`, inspection --- ### 9.3 No Dynamic Allocation **SRS-005-SHALL-038** No L1 primitive SHALL perform dynamic allocation (malloc, calloc, realloc, free). **Verification:** static analysis, pre-commit scan --- ### 9.4 No Global Mutable State **SRS-005-SHALL-039** No L1 primitive SHALL read from or write to global mutable state. **Verification:** static analysis, inspection --- ## 10. TRANSCENDENTAL APPROXIMATIONS ### 10.1 Exponential Function **SRS-005-SHALL-040** `ax_exp_q16` SHALL be implemented via a fixed polynomial approximation or CORDIC algorithm with frozen coefficients. **Verification:** golden vector, cross-platform harness --- ### 10.2 Exponential Domain **SRS-005-SHALL-041** `ax_exp_q16` SHALL declare and enforce a finite valid input domain. Inputs outside this domain SHALL set `faults->domain` and return a defined saturated value. **Suggested domain:** [-11.0, 11.0] in Q16.16 (approximately [-720896, 720896]). **Rationale:** exp(11) ≈ 59874 fits in Q16.16; exp(12) ≈ 162755 overflows the integer portion. **Verification:** property test, fault injection test, inspection --- ### 10.3 Exponential Accuracy **SRS-005-SHALL-042** `ax_exp_q16` SHALL produce results within ±2 ULP of the correctly rounded Q16.16 value over its valid domain. **Verification:** golden vector, property test --- ### 10.4 Hyperbolic Tangent **SRS-005-SHALL-043** `ax_tanh_q16` SHALL be implemented via: - The identity `tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)`, OR - A bit-perfect lookup table with linear interpolation, OR - A fixed polynomial approximation **Verification:** golden vector, cross-platform harness --- ### 10.5 Hyperbolic Tangent Domain **SRS-005-SHALL-044** `ax_tanh_q16` SHALL accept all Q16.16 values as input. **Rationale:** tanh saturates smoothly; output is always in [-1, 1]. **Verification:** property test --- ### 10.6 Hyperbolic Tangent Accuracy **SRS-005-SHALL-045** `ax_tanh_q16` SHALL produce results within ±2 ULP of the correctly rounded Q16.16 value. **Verification:** golden vector, property test --- ### 10.7 Sigmoid Function (Optional) **SRS-005-SHALL-046** If provided, `ax_sigmoid_q16` SHALL be implemented as: ``` sigmoid(x) = 1 / (1 + exp(-x)) ``` using `ax_exp_q16` internally. **Verification:** golden vector, cross-platform harness --- ### 10.8 Trigonometric Functions (Deferred) **SRS-005-SHALL-047** Trigonometric functions (`sin`, `cos`) SHALL NOT be included in L1 v1.0 unless a concrete L2 requirement justifies their inclusion. **Rationale:** Reduces surface area and proof burden. exp/tanh are immediately relevant for inference; sin/cos are not. **Verification:** inspection --- ## 11. LOOKUP-TABLE AND POLYNOMIAL RULES ### 11.1 Fixed Coefficients **SRS-005-SHALL-048** Any polynomial approximation SHALL use fixed coefficients frozen at compile time. **Verification:** inspection, static analysis --- ### 11.2 Fixed Table Contents **SRS-005-SHALL-049** Any lookup table SHALL have fixed contents frozen at compile time. **Verification:** inspection, static analysis --- ### 11.3 Compile-Time Generation **SRS-005-SHALL-050** Lookup tables and polynomial coefficients SHALL be generated at compile time or build time, not at runtime. **Verification:** inspection, build system audit --- ### 11.4 No Runtime Synthesis **SRS-005-SHALL-051** No L1 primitive SHALL synthesise tables or coefficients at runtime. **Verification:** static analysis, inspection --- ### 11.5 Endianness Neutrality **SRS-005-SHALL-052** Lookup tables stored in binary format SHALL be endianness-neutral or SHALL include compile-time byte-swapping for the target platform. **Verification:** cross-platform harness, inspection --- ### 11.6 Table Provenance **SRS-005-SHALL-053** The generation method for any lookup table SHALL be documented, reproducible, and frozen. The generation script SHALL be included in the repository. **Verification:** inspection, RTM generation --- ## 12. CROSS-PLATFORM IDENTITY ### 12.1 Platform Equivalence **SRS-005-SHALL-054** Identical inputs to any L1 primitive SHALL produce identical outputs and identical fault bits across supported architectures (x86_64, ARM64, RISC-V). **Verification:** cross-platform harness, golden vector --- ### 12.2 Golden Vector Provision **SRS-005-SHALL-055** The implementation SHALL provide golden vectors for all arithmetic primitives covering: - Normal operation - Boundary values (0, ±1, Q16_MAX, Q16_MIN, Q16_EPS) - Saturation conditions - Fault conditions **Verification:** golden vector suite --- ### 12.3 Cross-Platform Identity Tests **SRS-005-SHALL-056** The implementation SHALL provide cross-platform identity tests for all advanced primitives (exp, tanh, sigmoid). **Verification:** CI harness, certifiable-harness integration --- ### 12.4 Compiler Independence **SRS-005-SHALL-057** The implementation SHALL produce identical results when compiled with GCC, Clang, and MSVC on each supported platform. **Verification:** CI matrix, cross-platform harness --- ## 13. FORBIDDEN DEPENDENCIES ### 13.1 No libm **SRS-005-SHALL-058** No L1 primitive SHALL depend on `libm` or any host math library. **Verification:** static analysis, linker audit --- ### 13.2 No Floating-Point Hardware State **SRS-005-SHALL-059** No L1 primitive SHALL depend on floating-point hardware state (rounding mode, exception flags, MXCSR, FPCR). **Verification:** static analysis, inspection --- ### 13.3 No Locale Dependence **SRS-005-SHALL-060** No L1 primitive SHALL depend on locale settings. **Verification:** static analysis, inspection --- ### 13.4 No System Clock **SRS-005-SHALL-061** No L1 primitive SHALL depend on system clock or wall time. **Verification:** static analysis, pre-commit scan --- ### 13.5 No Randomness **SRS-005-SHALL-062** No L1 primitive SHALL depend on randomness or PRNG state. **Verification:** static analysis, inspection --- ### 13.6 No External I/O **SRS-005-SHALL-063** No L1 primitive SHALL perform external I/O (file, network, console). **Verification:** static analysis, inspection --- ## 14. HEADER TEMPLATE ### 14.1 Compliance Header **SRS-005-SHALL-064** Every L1 header SHALL declare: ```c /** * @file ax_arith.h * @brief DVM Q16.16 Arithmetic Primitives * * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * MEMORY: Zero Dynamic Allocation * SRS: SRS-005 * * Copyright © 2026 The Murray Family Innovation Trust * Patent: UK GB2521625.0 */ ``` **Verification:** static analysis, inspection --- ### 14.2 Function-Level Traceability **SRS-005-SHALL-065** Every public L1 function SHALL include SRS anchors: ```c /** * @brief Saturated Q16.16 addition. * * SRS-005-SHALL-010: Saturated addition * SRS-005-SHALL-029: Fault context acceptance * SRS-005-SHALL-031: Saturation fault signalling * SRS-005-SHALL-054: Cross-platform identity */ q16_16_t ax_add_q16(q16_16_t a, q16_16_t b, ct_fault_flags_t *faults); ``` **Verification:** RTM generation, static analysis --- ## 15. TYPE DEFINITIONS ### 15.1 Core Types Header **SRS-005-SHALL-066** The implementation SHALL provide `include/axilog/types.h`: ```c /** * @file types.h * @brief DVM Core Types * * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * MEMORY: Zero Dynamic Allocation * SRS: SRS-005 */ #ifndef AXILOG_TYPES_H #define AXILOG_TYPES_H #include #include /** * @brief Q16.16 fixed-point type. * SRS-005-SHALL-001, SRS-005-SHALL-002, SRS-005-SHALL-003 */ typedef int32_t q16_16_t; #define Q16_SHIFT 16 #define Q16_ONE (1 << Q16_SHIFT) /* 65536 = 0x00010000 */ #define Q16_HALF (1 << (Q16_SHIFT - 1)) /* 32768 = 0x00008000 */ #define Q16_MAX INT32_MAX /* 0x7FFFFFFF */ #define Q16_MIN INT32_MIN /* 0x80000000 */ #define Q16_EPS 1 /* 0x00000001 */ /** * @brief Fault flags for arithmetic operations. * SRS-005-SHALL-029, SRS-005-SHALL-030 * * Note: The 'protocol' field is reserved for higher-layer integration * (L5 agent state machines, L4 policy violations). L1 primitives SHALL * NOT set this flag. It is included here to ensure a single fault type * across all layers. */ typedef struct { uint8_t overflow; /* Result exceeded Q16_MAX */ uint8_t underflow; /* Result exceeded Q16_MIN */ uint8_t div_zero; /* Division by zero */ uint8_t domain; /* Input outside valid domain */ uint8_t protocol; /* Reserved: higher-layer integration (L5+) */ } ct_fault_flags_t; /** * @brief Check if any fault flag is set. * SRS-005-SHALL-034 */ static inline bool ct_fault_any(const ct_fault_flags_t *f) { return f->overflow || f->underflow || f->div_zero || f->domain || f->protocol; } /** * @brief Sign classification. * SRS-005-SHALL-026 */ typedef enum { AX_SIGN_NEGATIVE = -1, AX_SIGN_ZERO = 0, AX_SIGN_POSITIVE = 1 } ax_sign_t; #endif /* AXILOG_TYPES_H */ ``` **Verification:** inspection --- ## 16. VERIFICATION MATRIX | Requirement | Function(s) | Verification | |-------------|-------------|--------------| | SRS-005-SHALL-001 | All | inspection, static analysis | | SRS-005-SHALL-010 | `ax_add_q16` | property test, fault injection, golden vector | | SRS-005-SHALL-011 | `ax_sub_q16` | property test, fault injection, golden vector | | SRS-005-SHALL-012 | `ax_mul_q16` | property test, fault injection, golden vector | | SRS-005-SHALL-013 | `ax_div_q16` | property test, fault injection, golden vector | | SRS-005-SHALL-014 | `ax_neg_q16` | property test, fault injection | | SRS-005-SHALL-015 | `ax_abs_q16` | property test, fault injection | | SRS-005-SHALL-019–028 | `ax_eq/lt/gt/le/ge/sign_q16` | property test | | SRS-005-SHALL-040–042 | `ax_exp_q16` | golden vector, cross-platform harness | | SRS-005-SHALL-043–045 | `ax_tanh_q16` | golden vector, cross-platform harness | | SRS-005-SHALL-054–057 | All | cross-platform harness, CI matrix | | SRS-005-SHALL-058–063 | All | static analysis, linker audit | --- ## 17. L1 SUBSTRATE MAPPING By locking these L1 requirements, the Axioma framework achieves **Full Mathematical Closure**: | Logic Layer | Dependent Metric | L1 Requirement | |-------------|-----------------|----------------| | L4 Policy | Velocity > Threshold | SRS-005-SHALL-019 (Signed Comparison) | | L4 Policy | Value within bounds | SRS-005-SHALL-018 (Clamp) | | L3 Oracle | Temperature scaling | SRS-005-SHALL-012 (Saturated Mul) | | L2 Inference | Softmax/Activation | SRS-005-SHALL-040 (Deterministic Exp) | | L2 Inference | tanh activation | SRS-005-SHALL-043 (Deterministic Tanh) | | L6 Audit | Q16.16 in evidence | SRS-005-SHALL-001 (Representation) | | L7 Governance | Proof-carrying policy | All comparison SHALLs | --- ## 18. PUBLIC API SUMMARY | Function | SRS Coverage | |----------|-------------| | `ax_add_q16` | SRS-005-SHALL-010, 029, 031, 054 | | `ax_sub_q16` | SRS-005-SHALL-011, 029, 031, 054 | | `ax_mul_q16` | SRS-005-SHALL-012, 029, 031, 054 | | `ax_div_q16` | SRS-005-SHALL-013, 029, 031, 054 | | `ax_neg_q16` | SRS-005-SHALL-014, 029, 031 | | `ax_abs_q16` | SRS-005-SHALL-015, 029, 031 | | `ax_min_q16` | SRS-005-SHALL-016, 029 | | `ax_max_q16` | SRS-005-SHALL-017, 029 | | `ax_clamp_q16` | SRS-005-SHALL-018, 029, 031 | | `ax_eq_q16` | SRS-005-SHALL-021 | | `ax_lt_q16` | SRS-005-SHALL-022, 019 | | `ax_gt_q16` | SRS-005-SHALL-023, 019 | | `ax_le_q16` | SRS-005-SHALL-024, 019 | | `ax_ge_q16` | SRS-005-SHALL-025, 019 | | `ax_sign_q16` | SRS-005-SHALL-026 | | `ax_int_to_q16` | SRS-005-SHALL-005 | | `ax_q16_to_int` | SRS-005-SHALL-006 | | `ax_q16_to_int_rne` | SRS-005-SHALL-007 | | `ax_exp_q16` | SRS-005-SHALL-040, 041, 042, 054 | | `ax_tanh_q16` | SRS-005-SHALL-043, 044, 045, 054 | | `ax_sigmoid_q16` | SRS-005-SHALL-046 (optional) | --- ## 19. CLOSURE ASSESSMENT | Requirement Category | Status | |---------------------|--------| | Representation model | ✅ Closed | | Conversion semantics | ✅ Closed | | Core arithmetic | ✅ Closed | | Comparison and ordering | ✅ Closed | | Fault contract | ✅ Closed | | Transcendental approximations | ✅ Closed (exp, tanh) | | Lookup-table rules | ✅ Closed | | Purity and boundedness | ✅ Closed | | Cross-platform identity | ✅ Closed | | Forbidden dependencies | ✅ Closed | **Open Items (Deferred to L1 v1.1):** - Trigonometric functions (sin, cos) — pending L2 justification - Extended precision accumulator (Q32.32) — if L2 requires --- ## 20. CI GATE REQUIREMENTS The following CI gates SHALL pass before merge: ``` ☐ property-test-arith — All arithmetic property tests ☐ property-test-compare — All comparison property tests ☐ golden-vector — All golden reference vectors match ☐ fault-injection — All fault paths exercised ☐ cross-platform-x86 — x86_64 bit-identity ☐ cross-platform-arm — ARM64 bit-identity ☐ static-analysis — Zero warnings (clang-tidy, cppcheck) ☐ forbidden-pattern-scan — No float/double/malloc/time ☐ signed-shift-scan — No >> on signed integers (SRS-005-SHALL-068) ☐ rtm-coverage — All SHALLs traced to code ``` --- ## 21. FINAL STATEMENT > **The L1 substrate is not a convenience layer.** > > **It is the mathematical foundation upon which all higher-layer > proofs rest.** If L1 is not closed, L7 governance is meaningless. This document closes L1. --- ## 22. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0-Frozen | 2026-03-27 | William Murray | Initial frozen release — 66 SHALL statements. Complete mathematical closure for L1 substrate. | | 1.1-Frozen | 2026-03-27 | William Murray | Audit closure — 4 new SHALLs (067–070). Fixed multiplication rounding ambiguity, removed signed right-shift dependency, added division overflow rule, formalised clamp invalid bounds behaviour, tightened monotonicity classification. Total: 70 SHALL statements. | --- ## 23. DOCUMENT APPROVAL | Role | Name | Date | Signature | |------|------|------|-----------| | Author | William Murray | 2026-03-27 | | | Reviewer | | | | | Approver | | | | --- ## Appendix A — Golden Vector Examples ### A.1 Addition | a (Q16.16) | b (Q16.16) | Expected | Fault | |------------|------------|----------|-------| | 65536 | 65536 | 131072 | none | | INT32_MAX | 1 | INT32_MAX | overflow | | INT32_MIN | -1 | INT32_MIN | underflow | | 0 | 0 | 0 | none | | -65536 | 65536 | 0 | none | ### A.2 Multiplication | a (Q16.16) | b (Q16.16) | Expected | Fault | |------------|------------|----------|-------| | 65536 (1.0) | 65536 (1.0) | 65536 (1.0) | none | | 131072 (2.0) | 131072 (2.0) | 262144 (4.0) | none | | INT32_MAX | 2 | INT32_MAX | overflow | | 32768 (0.5) | 32768 (0.5) | 16384 (0.25) | none | ### A.3 Division | a (Q16.16) | b (Q16.16) | Expected | Fault | |------------|------------|----------|-------| | 65536 (1.0) | 65536 (1.0) | 65536 (1.0) | none | | 131072 (2.0) | 65536 (1.0) | 131072 (2.0) | none | | 65536 (1.0) | 0 | 0 | div_zero | | INT32_MIN | -1 | INT32_MAX | overflow | | INT32_MAX | 1 | INT32_MAX | overflow | ### A.4 Exponential | x (Q16.16) | Expected (approx) | Fault | |------------|-------------------|-------| | 0 | 65536 (1.0) | none | | 65536 (1.0) | 178145 (2.718) | none | | -65536 (-1.0) | 24109 (0.368) | none | | 720896 (11.0) | near Q16_MAX | none | | 786432 (12.0) | saturated | domain | --- ## Appendix B — Alignment with DVM-SPEC-001 | DVM-SPEC-001 Section | SRS-005 Coverage | |---------------------|------------------| | §3 Fixed-Point Model | SRS-005-SHALL-001–004 | | §4 Arithmetic Primitives | SRS-005-SHALL-010–018, 067–070 | | §5 Fault Model | SRS-005-SHALL-029–035 | | §6 Oracle Boundary | (L3 concern, not L1) | | §7 Commitment | (L6 concern, not L1) | --- ## Appendix C — DVEC-001 v1.3 Conformance | DVEC Mandate | SRS-005 Implementation | |--------------|----------------------| | §1.1 Bit-Identity | SRS-005-SHALL-054, 067, 068 | | §1.2 Forbidden Constructs | SRS-005-SHALL-058–063, 068 | | §2.1 Total Function | SRS-005-SHALL-032 | | §2.4 Fault Propagation | SRS-005-SHALL-029–035, 069, 070 | | §8.1 Minimal Footprint | SRS-005-SHALL-036–039 | | §12.2 Arithmetic Enforcement | All arithmetic SHALLs | --- ## Appendix D — v1.0 → v1.1 Audit Record | Finding | Severity | Resolution | |---------|----------|------------| | Multiplication rounding mode under-specified | BLOCKING | SRS-005-SHALL-067: Mandates truncation toward zero | | Signed right-shift is implementation-defined in C99 | BLOCKING | SRS-005-SHALL-068: Prohibits signed right-shift for division | | Division overflow edge case (INT32_MIN / -1) implicit | HIGH | SRS-005-SHALL-069: Explicit saturation rule | | Clamp invalid bounds behaviour ambiguous | HIGH | SRS-005-SHALL-070: Formalised domain fault behaviour | | Monotonicity requirement mathematically weak | MEDIUM | SRS-005-SHALL-028: Tightened to explicit classification | | Protocol flag in fault struct is L5+ concern | LOW | Documentation: Explicitly marked as reserved for higher layers | | RNE conversion used right-shift on negative values | BLOCKING | SRS-005-SHALL-007: Rewritten to use division | **Audit Source:** External review (GPT-4o, Gemini 2.5 Pro) **Audit Date:** 27 March 2026 **Audit Verdict:** All blocking and high-severity findings resolved. Document status elevated to **Audit-Frozen FINAL**. --- *SRS-005 v1.1-Frozen — Audit-Frozen FINAL* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== SRS-007-TIMING — Deterministic Execution Timing ======================================================================== Spec ID: SRS-007-TIMING Title: Deterministic Execution Timing Version: v0.1 Status: Draft Layer: L1 Determinism: D1 Date: 2026-01-20 Compliance: ISO 26262, DO-178C, IEC 61508 URL: https://axilog.io/specs/srs-007-timing/ Changelog: https://axilog.io/specs/srs-007-timing/changelog/ Summary: The L1 timing contract — execution time of core operations SHALL be independent of data values, with minimal jitter on identical hardware. **Component:** Core / Real-Time Systems **Compliance:** ISO 26262 · DO-178C · IEC 61508 **Applicability:** Real-Time Safety-Critical Systems --- ## 1. Purpose This module defines requirements for deterministic, bounded execution timing of inference primitives. In safety-critical real-time systems, predictable timing is as important as correctness - a late result can be as dangerous as a wrong result. **Critical Requirement:** Execution time of core operations must be independent of data values and exhibit minimal variance (jitter) across identical hardware. ## 2. The Real-Time Problem ### 2.1 Why Timing Matters **Medical Devices:** - Pacemaker: Must deliver signal within 10ms window - Surgical robot: Latency > 50ms causes unsafe tremor - **Our Requirement:** Predictable, bounded execution time **Automotive Systems:** - Emergency braking: Must complete within 100ms - Lane keeping: 50ms control loop - **Our Requirement:** Zero jitter for control loop stability **Aerospace:** - Flight control: 20ms hard deadline - DO-178C Level A: Must prove WCET - **Our Requirement:** Analyzable worst-case execution time ### 2.2 Sources of Non-Determinism (That We Avoid) **Dynamic Memory Allocation:** - `malloc()` latency varies with heap fragmentation - Garbage collection introduces unpredictable pauses - **Our Solution:** Zero dynamic allocation (SRS-001, SRS-003, SRS-006) **Data-Dependent Branching:** - `if (value > threshold) break;` creates timing variance - Different execution paths for different data - **Our Solution:** Fixed iteration counts, no early exits **Floating-Point Operations:** - IEEE-754 operations vary by value (denormals, NaN handling) - Hardware optimization units introduce timing variance - **Our Solution:** Fixed-point arithmetic only (SRS-002) **Operating System Interference:** - Context switches, interrupts, cache eviction - ASLR (Address Space Layout Randomization) - **Our Mitigation:** Documented, can be controlled by deployment ## 3. Requirements ### 3.1 Data-Independent Execution Time **SRS-007.1: Input Independence** Execution time of inference operations shall not depend on input data values. **Rationale:** - Prevents timing side-channel attacks - Enables WCET analysis - Required for DO-178C compliance - Eliminates "Heisenbugs" from timing variance **Implementation:** No data-dependent branches in inner loops. **Verification:** Timing tests with different input patterns show identical execution time. --- **SRS-007.2: Fixed Iteration Counts** All loops in inference operations shall have iteration counts determined solely by matrix dimensions, not data values. **Examples:** ```c // COMPLIANT: Loop count = rows × cols (fixed by dimensions) for (uint16_t i = 0; i < mat->rows; i++) { for (uint16_t j = 0; j < mat->cols; j++) { // Process element } } // NON-COMPLIANT: Early exit based on data for (uint16_t i = 0; i < mat->rows; i++) { if (mat->data[i] > threshold) break; // Data-dependent! } ``` **Rationale:** - Loop bounds determine execution time - Fixed bounds enable static analysis - Simplifies WCET calculation **Verification:** Code review confirms all loops have dimension-based bounds. --- **SRS-007.3: No Dynamic Dispatch** Function calls shall be statically resolved (no function pointers in hot paths unless demonstrably deterministic). **Exception:** `fx_matrix_apply()` takes function pointer but still deterministic (fixed iteration, known function). **Rationale:** - Virtual dispatch can have cache effects - Static calls enable compiler optimization - Predictable instruction cache behavior **Verification:** Static analysis confirms call graph. ### 3.2 Timing Predictability **SRS-007.4: Bounded Jitter** For identical hardware and identical dimensions, execution time variance (jitter) shall be minimal (<5% of mean execution time). **Definition:** ``` Jitter = max(execution_times) - min(execution_times) Acceptable: Jitter < 0.05 × mean ``` **Note:** This excludes OS-level interrupts (which can be controlled in real deployment). **Rationale:** - Control loops require predictable timing - Jitter causes instability in feedback systems - Required for hard real-time classification **Verification:** Run operation 10,000 times, measure jitter. --- **SRS-007.5: WCET Analyzability** Code structure shall enable worst-case execution time (WCET) analysis using static analysis tools. **Requirements:** - No recursion - All loops have statically determinable bounds - No dynamic memory allocation - Call graph is statically analyzable **Tools:** aiT, SWEET, OTAWA, or manual analysis **Rationale:** - DO-178C Level A requires WCET proof - ISO 26262 ASIL-D requires timing analysis - IEC 61508 SIL 3/4 requires bounded timing **Verification:** WCET analysis report available. ### 3.3 Performance Characteristics **SRS-007.6: Time Complexity Documentation** Each operation shall document its time complexity in Big-O notation. **Examples:** - Matrix multiplication: O(M × N × P) - Convolution: O(OH × OW × KH × KW) - ReLU: O(M × N) **Rationale:** - Enables system-level timing analysis - Helps users predict performance - Required for real-time scheduling **Verification:** Documentation reviewed and tested. ## 4. Timing Analysis ### 4.1 Matrix Multiplication (fx_matrix_mul) **Time Complexity:** O(M × N × P) - M = rows of A - N = cols of A = rows of B - P = cols of B **Iteration Count:** ``` Total iterations = M × N × P For 10×10 × 10×10: 10 × 10 × 10 = 1000 iterations ``` **Data Independence:** ✅ - Loop bounds fixed by dimensions - No early exits - No data-dependent branches **WCET:** Deterministic (M × N × P × T_MAC) - T_MAC = time for one multiply-accumulate --- ### 4.2 Convolution (fx_conv2d) **Time Complexity:** O(OH × OW × KH × KW) - OH, OW = output height, width - KH, KW = kernel height, width **Iteration Count:** ``` Total iterations = OH × OW × KH × KW For 14×14 output, 3×3 kernel: 14 × 14 × 3 × 3 = 1764 iterations ``` **Data Independence:** ✅ - Loop bounds fixed by dimensions - No early exits - No data-dependent branches **WCET:** Deterministic (OH × OW × KH × KW × T_MAC) --- ### 4.3 ReLU (fx_relu) **Time Complexity:** O(M × N) **Iteration Count:** ``` Total iterations = M × N For 10×10 matrix: 100 iterations ``` **Note:** Contains `if (data[i] < 0)` branch - Branch predictor may cause small variance - Modern CPUs: <1% timing difference - Acceptable for most real-time systems - Critical systems: Use branchless version **WCET:** Nearly deterministic (M × N × T_CMP) ## 5. Benchmark Methodology ### 5.1 Test Setup **Hardware:** Document CPU, cache configuration, frequency **Software:** Document OS, kernel version, compiler flags **Isolation:** - Disable frequency scaling - Pin process to single core - Disable interrupts if possible - Warm up caches before measurement ### 5.2 Measurement Procedure 1. **Warm-up:** Run operation 1000 times (load caches) 2. **Measurement:** Run operation 10,000 times 3. **Record:** Each individual execution time 4. **Analysis:** Calculate min, max, mean, jitter ### 5.3 Acceptance Criteria **Pass Criteria:** - Mean execution time documented - Jitter < 5% of mean (excluding OS interrupts) - Min/Max ratio < 1.05 - No outliers > 2× median **Fail Criteria:** - Jitter > 10% of mean - Bimodal distribution (indicates hidden states) - Increasing trend (memory leak) ## 6. Commercial Value ### 6.1 The Triple Threat **1. Bit-Perfect Results (Correctness)** - Same input → same output, always - Proven by SRS-001 through SRS-006 **2. Traceable Requirements (Compliance)** - Complete audit trail - Requirements → Code → Tests - Ready for regulatory submission **3. Zero-Jitter Execution (Predictability)** - Deterministic timing - No "Heisenbugs" - WCET analyzable **Value:** Companies pay $500K+ for this combination. ### 6.2 Certification Advantages **DO-178C (Aerospace):** - Level A requires WCET proof ✅ - Structural coverage easily achieved ✅ - No dynamic behavior to analyze ✅ **ISO 26262 (Automotive):** - ASIL-D requires timing predictability ✅ - Deterministic behavior proven ✅ - No timing side-channels ✅ **IEC 62304 (Medical):** - Class C requires risk analysis ✅ - Predictable timing reduces risk ✅ - Formal verification possible ✅ ### 6.3 Competitive Advantage **vs. TensorFlow Lite:** - TensorFlow: Data-dependent optimization (non-deterministic) - Us: Fixed execution path (deterministic) ✅ **vs. ONNX Runtime:** - ONNX: Dynamic memory allocation (timing variance) - Us: Pre-allocated buffers (predictable) ✅ **vs. PyTorch Mobile:** - PyTorch: Python runtime overhead (jitter) - Us: Pure C, zero overhead (zero jitter) ✅ ## 7. Timing Side-Channel Resistance ### 7.1 Security Benefit **Constant-Time Operations:** - Prevents timing attacks on sensitive data - Important for medical privacy (HIPAA) - Required for defense applications **Example Attack Prevented:** ``` // VULNERABLE: Timing reveals if tumor detected if (tumor_probability > threshold) { allocate_large_buffer(); // Takes longer! detailed_analysis(); } // SECURE: Constant time regardless of detection result = classify_region(); // Always same time ``` ### 7.2 Privacy Implications In medical AI: - Processing time should not reveal diagnosis - Constant-time prevents information leakage - Our architecture naturally constant-time ## 8. Implementation Guidelines ### 8.1 Writing Deterministic Code **DO:** - Use dimension-based loop bounds - Avoid `break` in inner loops - Use fixed-point arithmetic - Pre-allocate all buffers **DON'T:** - Use `malloc` in hot paths - Have data-dependent branches in loops - Use floating-point operations - Call functions with unknown timing ### 8.2 Testing Determinism ```c // Test pattern uint64_t times[ITERATIONS]; for (int i = 0; i < ITERATIONS; i++) { start = get_time(); operation(); end = get_time(); times[i] = end - start; } // Analyze uint64_t min = times[0]; uint64_t max = times[0]; uint64_t sum = 0; for (int i = 0; i < ITERATIONS; i++) { if (times[i] < min) min = times[i]; if (times[i] > max) max = times[i]; sum += times[i]; } uint64_t mean = sum / ITERATIONS; uint64_t jitter = max - min; // Verify assert(jitter < mean * 0.05); // Jitter < 5% ``` ## 9. Future Work **SRS-007.7:** (Planned) Branchless ReLU Implementation For ultra-critical systems, implement ReLU without branches: ```c // Branchless ReLU fixed_t relu_branchless(fixed_t x) { fixed_t mask = x >> 31; // Sign bit return x & ~mask; // Zero if negative } ``` **SRS-007.8:** (Planned) WCET Analysis Reports Generate formal WCET analysis using static analysis tools. **SRS-007.9:** (Planned) Timing Guarantees Provide documented timing guarantees per operation: - Matrix mul: X ns per MAC - Conv2D: Y ns per MAC - Platform-specific characterization ## 10. References - **DO-178C** - Software Considerations in Airborne Systems - **ISO 26262-6:2018** - Road vehicles functional safety (software) - **IEC 61508** - Functional safety of electrical/electronic systems - **MISRA-C:2012** - Guidelines for embedded C - **Liu & Layland (1973)** - "Scheduling Algorithms for Multiprogramming in a Hard-Real-Time Environment" ## 11. Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0 | 2026-01-15 | William Murray | Initial version | --- **Document Classification:** Technical Specification **Approval Status:** Approved for Implementation **Next Review:** 2026-04-15 ======================================================================== Layer group: L2 — State Machine ======================================================================== ======================================================================== CI-MATH-001 — Certifiable Inference Mathematical Specification ======================================================================== Spec ID: CI-MATH-001 Title: Certifiable Inference Mathematical Specification Version: v1.0 Status: Final Layer: L2 Determinism: D1 Date: 2026-01-20 Compliance: DO-178C, IEC 62304, ISO 26262 URL: https://axilog.io/specs/ci-math-001/ Changelog: https://axilog.io/specs/ci-math-001/changelog/ Summary: The mathematical foundation for deterministic neural network inference — Q16.16 arithmetic and layer operations, every code path bound to a named theorem. **Traceability:** All code in `src/` SHALL be a literal transcription of the mathematics herein. --- ## §1 Introduction ### §1.1 Purpose This document specifies the mathematical foundations for deterministic neural network inference. The goal is bit-identical execution across all platforms (x86, ARM, RISC-V) regardless of compiler, optimization level, or hardware implementation. ### §1.2 Scope Certifiable-inference provides: - Fixed-point arithmetic (Q16.16) - Matrix operations (multiply, add, transpose) - Convolution (2D, valid padding) - Activation functions (ReLU, Leaky ReLU) - Pooling operations (max pooling) - Deterministic hash tables ### §1.3 Notation | Symbol | Meaning | |--------|---------| | ⌊x⌋ | Floor function | | ⌈x⌉ | Ceiling function | | ≡ | Definition / equivalence | | ∧ | Logical AND | | ∀ | For all | | ∈ | Element of | | [a, b] | Closed interval | | mod | Modulo operation | | ≪ | Left bit shift | | ≫ | Arithmetic right shift | ### §1.4 Document Alignment | Topic | CI-MATH-001 | CI-STRUCT-001 | SRS | |-------|-------------|---------------|-----| | Fixed-point format | §2 | §3 | SRS-002 | | Rounding | §2.5 | §3.3 | SRS-002 | | Matrix operations | §3 | §4 | SRS-003 | | Activations | §4 | §5 | SRS-004 | | Convolution | §5 | §6 | SRS-006 | | Pooling | §6 | §7 | SRS-008 | | Hash table | §7 | §8 | SRS-001 | | Fault model | §8 | §9 | SRS-002 | --- ## §2 Fixed-Point Arithmetic ### §2.1 Format Specification **Definition:** Q16.16 fixed-point format uses a signed 32-bit integer where: - Bits [31:16]: Signed integer part (16 bits) - Bits [15:0]: Fractional part (16 bits) ``` Value = raw_integer / 2^16 raw_integer = Value × 2^16 ``` ### §2.2 Constants | Constant | Symbol | Value | Hex | |----------|--------|-------|-----| | One | FIXED_ONE | 65536 | 0x00010000 | | Half | FIXED_HALF | 32768 | 0x00008000 | | Zero | FIXED_ZERO | 0 | 0x00000000 | | Epsilon | FIXED_EPS | 1 | 0x00000001 | | Maximum | FIXED_MAX | 2147483647 | 0x7FFFFFFF | | Minimum | FIXED_MIN | -2147483648 | 0x80000000 | | Shift | FIXED_SHIFT | 16 | — | ### §2.3 Range and Precision | Property | Value | |----------|-------| | Minimum representable | -32768.0 | | Maximum representable | +32767.99998474... | | Precision (1 LSB) | 1/65536 ≈ 0.0000152588 | | Decimal digits | ~4.8 significant digits | ### §2.4 Conversion Functions **Integer to Fixed:** ``` fixed_from_int(i) ≡ i ≪ FIXED_SHIFT ``` **Fixed to Integer (truncation):** ``` fixed_to_int(f) ≡ f ≫ FIXED_SHIFT ``` **Float to Fixed (initialization only):** ``` fixed_from_float(fl) ≡ ⌊fl × FIXED_ONE + 0.5⌋ ``` **Note:** Float conversion is permitted only during model loading/initialization. Runtime inference uses integer-only operations. ### §2.5 Arithmetic Operations **Addition:** ``` fixed_add(a, b) ≡ a + b ``` Direct integer addition. Overflow behavior defined in §8. **Subtraction:** ``` fixed_sub(a, b) ≡ a - b ``` Direct integer subtraction. **Multiplication with Rounding:** ``` fixed_mul(a, b) ≡ round_shift((int64_t)a × (int64_t)b, FIXED_SHIFT) ``` Where `round_shift` implements round-to-nearest: ``` round_shift(x, shift) ≡ (x + (1 ≪ (shift - 1))) ≫ shift ``` **Rationale:** 64-bit intermediate prevents overflow. Adding FIXED_HALF before shifting implements round-to-nearest, minimizing cumulative quantization error. **Division:** ``` fixed_div(a, b) ≡ if b = 0: return 0 (with fault flag) else: ((int64_t)a ≪ FIXED_SHIFT) / b ``` **Absolute Value:** ``` fixed_abs(f) ≡ if f ≥ 0: f else: -f ``` **Note:** `fixed_abs(FIXED_MIN)` overflows; this is handled via fault flags. **Negation:** ``` fixed_neg(f) ≡ -f ``` ### §2.6 Determinism Guarantee **Theorem (Bit-Perfect Arithmetic):** For any two DVM-compliant platforms A and B: ``` ∀ a, b ∈ int32_t: fixed_mul(a, b) on A = fixed_mul(a, b) on B ``` **Proof:** All operations use: 1. Integer arithmetic only (no floating-point) 2. Explicit widening to 64-bit before overflow-prone operations 3. Deterministic rounding (round-to-nearest via addition) 4. No platform-dependent behavior (no FMA, no compiler optimization variability) --- ## §3 Linear Algebra ### §3.1 Matrix Representation A matrix M with dimensions (rows × cols) is stored in row-major order: ``` M[i][j] = data[i × cols + j] ``` Where: - i ∈ [0, rows) - j ∈ [0, cols) ### §3.2 Matrix Initialization ``` fx_matrix_init(m, buffer, rows, cols): m.data ← buffer m.rows ← rows m.cols ← cols ``` **Precondition:** `buffer` must have at least `rows × cols` elements. ### §3.3 Matrix Multiplication For matrices A (m×k) and B (k×n), compute C = A × B where C is (m×n): ``` fx_matrix_mul(A, B, C): PRECONDITION: A.cols = B.rows PRECONDITION: C.rows = A.rows ∧ C.cols = B.cols FOR i ← 0 TO A.rows - 1: FOR j ← 0 TO B.cols - 1: acc ← 0 (int64_t) FOR k ← 0 TO A.cols - 1: acc ← acc + (int64_t)A[i,k] × (int64_t)B[k,j] C[i,j] ← round_shift(acc, FIXED_SHIFT) ``` **Complexity:** O(m × n × k) time, O(1) auxiliary space. **Determinism:** 64-bit accumulator prevents intermediate overflow. Final rounding is deterministic. ### §3.4 Matrix Addition ``` fx_matrix_add(A, B, C): PRECONDITION: A.rows = B.rows = C.rows PRECONDITION: A.cols = B.cols = C.cols FOR i ← 0 TO A.rows × A.cols - 1: C.data[i] ← A.data[i] + B.data[i] ``` ### §3.5 Vector Dot Product ``` fx_dot(a, b, n): acc ← 0 (int64_t) FOR i ← 0 TO n - 1: acc ← acc + (int64_t)a[i] × (int64_t)b[i] RETURN round_shift(acc, FIXED_SHIFT) ``` ### §3.6 Address Independence **Theorem:** Matrix operations produce identical results regardless of memory addresses. **Proof:** All operations depend only on: 1. Element values (not addresses) 2. Dimension metadata 3. Index arithmetic (deterministic) No pointer comparisons or address-dependent behavior exists. --- ## §4 Activation Functions ### §4.1 ReLU ``` ReLU(x) ≡ max(0, x) ``` **Implementation:** ``` fx_relu(mat): FOR i ← 0 TO mat.rows × mat.cols - 1: IF mat.data[i] < 0: mat.data[i] ← 0 ``` **Properties:** - In-place operation (modifies input) - O(n) time, O(1) space - Deterministic (simple comparison) ### §4.2 Leaky ReLU ``` LeakyReLU(x, α) ≡ if x ≥ 0: x else: α × x ``` **Implementation:** ``` fx_leaky_relu(mat, alpha): FOR i ← 0 TO mat.rows × mat.cols - 1: IF mat.data[i] < 0: mat.data[i] ← fixed_mul(mat.data[i], alpha) ``` **Note:** α is typically 0.01 (Q16.16: 655). ### §4.3 Bias Addition ``` fx_add_bias(mat, bias): PRECONDITION: bias.cols = mat.cols FOR i ← 0 TO mat.rows - 1: FOR j ← 0 TO mat.cols - 1: mat[i,j] ← mat[i,j] + bias[0,j] ``` ### §4.4 Dense Layer Forward Pass A complete dense layer: Y = ReLU(X × W + b) ``` fx_dense_forward(X, W, b, Y): fx_matrix_mul(X, W, Y) fx_add_bias(Y, b) fx_relu(Y) ``` --- ## §5 Convolution ### §5.1 2D Convolution (Valid Padding) For input I (H_in × W_in) and kernel K (K_h × K_w), output O has dimensions: ``` H_out = H_in - K_h + 1 W_out = W_in - K_w + 1 ``` **Definition:** ``` O[i,j] = Σ_{di=0}^{K_h-1} Σ_{dj=0}^{K_w-1} I[i+di, j+dj] × K[di, dj] ``` ### §5.2 Implementation ``` fx_conv2d(input, kernel, output): PRECONDITION: output.rows = input.rows - kernel.rows + 1 PRECONDITION: output.cols = input.cols - kernel.cols + 1 FOR i ← 0 TO output.rows - 1: FOR j ← 0 TO output.cols - 1: acc ← 0 (int64_t) FOR di ← 0 TO kernel.rows - 1: FOR dj ← 0 TO kernel.cols - 1: in_val ← input[i + di, j + dj] k_val ← kernel[di, dj] acc ← acc + (int64_t)in_val × (int64_t)k_val output[i,j] ← round_shift(acc, FIXED_SHIFT) ``` ### §5.3 Complexity | Metric | Value | |--------|-------| | Time | O(H_out × W_out × K_h × K_w) | | Space | O(1) auxiliary | | Memory reads | O(H_out × W_out × K_h × K_w) | | Memory writes | O(H_out × W_out) | ### §5.4 Common Kernels **Identity (3×3):** ``` [0, 0, 0] [0, 1, 0] [0, 0, 0] ``` **Sobel Horizontal (3×3):** ``` [-1, 0, +1] [-2, 0, +2] [-1, 0, +1] ``` **Sobel Vertical (3×3):** ``` [-1, -2, -1] [ 0, 0, 0] [+1, +2, +1] ``` --- ## §6 Pooling ### §6.1 Max Pooling 2×2 For input I (H × W), output O has dimensions (H/2 × W/2): ``` O[i,j] = max(I[2i, 2j], I[2i, 2j+1], I[2i+1, 2j], I[2i+1, 2j+1]) ``` ### §6.2 Implementation ``` fx_maxpool_2x2(input, output): PRECONDITION: output.rows = input.rows / 2 PRECONDITION: output.cols = input.cols / 2 FOR i ← 0 TO output.rows - 1: FOR j ← 0 TO output.cols - 1: v00 ← input[2i, 2j] v01 ← input[2i, 2j + 1] v10 ← input[2i + 1, 2j] v11 ← input[2i + 1, 2j + 1] m1 ← max(v00, v01) m2 ← max(v10, v11) output[i,j] ← max(m1, m2) ``` ### §6.3 Properties | Property | Value | |----------|-------| | Dimension reduction | 2× in each spatial dimension | | Range preservation | output ∈ [min(input), max(input)] | | Determinism | Comparison-only (no arithmetic rounding) | ### §6.4 Boundary Handling If input dimensions are not divisible by 2, the rightmost column and/or bottom row are ignored. This is explicit in the precondition and must be handled at model design time. --- ## §7 Deterministic Hash Table ### §7.1 Purpose A hash table with deterministic iteration order, required for reproducible model weight storage and lookup. ### §7.2 Hash Function Using FNV-1a (Fowler-Noll-Vo): ``` fnv1a_hash(key): hash ← 2166136261 (FNV offset basis) FOR each byte c in key: hash ← hash XOR c hash ← hash × 16777619 (FNV prime) RETURN hash ``` **Properties:** - Deterministic across platforms - No floating-point - Good distribution for string keys ### §7.3 Collision Resolution Linear probing with insertion-order tracking: ``` probe_index(hash, i, capacity) ≡ (hash + i) mod capacity ``` ### §7.4 Iteration Order Iteration follows insertion order, not hash order. This is maintained via a separate index array: ``` FOR i ← 0 TO insert_count - 1: yield entries[insertion_order[i]] ``` ### §7.5 Operations **Insert:** ``` d_table_insert(table, key, value): IF table.count ≥ table.capacity: RETURN D_TABLE_FULL hash ← fnv1a_hash(key) FOR i ← 0 TO table.capacity - 1: idx ← probe_index(hash, i, table.capacity) IF table.entries[idx].occupied: IF table.entries[idx].key = key: RETURN D_TABLE_KEY_EXISTS ELSE: table.entries[idx] ← {key, value, occupied: true} table.insertion_order[table.count] ← idx table.count ← table.count + 1 RETURN D_TABLE_OK ``` **Get:** ``` d_table_get(table, key, out_value): hash ← fnv1a_hash(key) FOR i ← 0 TO table.capacity - 1: idx ← probe_index(hash, i, table.capacity) IF NOT table.entries[idx].occupied: RETURN D_TABLE_NOT_FOUND IF table.entries[idx].key = key: *out_value ← table.entries[idx].value RETURN D_TABLE_OK RETURN D_TABLE_NOT_FOUND ``` --- ## §8 Fault Model ### §8.1 Fault Flags ``` typedef struct { uint32_t overflow : 1; /* Result exceeded INT32_MAX */ uint32_t underflow : 1; /* Result below INT32_MIN */ uint32_t div_zero : 1; /* Division by zero attempted */ uint32_t domain : 1; /* Input outside valid range */ uint32_t precision : 1; /* Precision loss detected */ uint32_t _reserved : 27; } ci_fault_flags_t; ``` ### §8.2 Fault Behavior | Condition | Action | Fault Flag | |-----------|--------|------------| | Multiplication overflow | Saturate to FIXED_MAX/MIN | overflow/underflow | | Division by zero | Return 0 | div_zero | | Invalid dimension | Skip operation | domain | | Precision loss in conversion | Continue with rounded value | precision | ### §8.3 Fault Propagation Fault flags are **sticky**: once set, they remain set until explicitly cleared. ``` ci_has_fault(f) ≡ f.overflow ∨ f.underflow ∨ f.div_zero ∨ f.domain ∨ f.precision ``` ### §8.4 Safety Philosophy **Fail-safe behavior:** Operations continue with defined (saturated/clamped) values rather than undefined behavior. The fault flag enables the caller to detect and handle the condition. --- ## §9 Execution Timing ### §9.1 Bounded Execution All operations have bounded worst-case execution time (WCET): | Operation | Complexity | Bounded | |-----------|------------|---------| | fixed_mul | O(1) | ✓ | | fx_matrix_mul | O(m×n×k) | ✓ (dimensions known) | | fx_conv2d | O(H×W×Kh×Kw) | ✓ (dimensions known) | | fx_maxpool | O(H×W) | ✓ | | d_table_get | O(capacity) worst | ✓ (capacity bounded) | ### §9.2 No Unbounded Loops All loops have statically-known bounds derived from: - Matrix dimensions (provided at initialization) - Hash table capacity (fixed at creation) - Kernel dimensions (fixed at model load) ### §9.3 No Recursion No recursive function calls. All algorithms are iterative. ### §9.4 No Dynamic Allocation Zero calls to malloc/free/realloc during inference. All memory provided by caller. --- ## §10 Determinism Proofs ### §10.1 Platform Independence Theorem **Statement:** For any valid input state S and any two platforms A, B implementing the DVM specification: ``` inference(S) on A ≡ inference(S) on B ``` **Proof sketch:** 1. **Integer arithmetic identity:** All operations reduce to standard integer operations (+, -, ×, /, shifts) which are platform-independent for fixed-width integers. 2. **No floating-point:** All numerical computation uses int32_t or int64_t. No IEEE-754 operations. 3. **Deterministic rounding:** round_shift uses integer addition and arithmetic shift, both platform-independent. 4. **Memory layout independence:** Operations depend on values, not addresses. 5. **Iteration order determinism:** Hash table iteration follows insertion order, not hash order. ### §10.2 Reproducibility Corollary Given identical: - Model weights (Q16.16) - Input data (Q16.16) - Network topology The output is bit-identical across: - x86_64, ARM64, RISC-V - GCC, Clang, MSVC - -O0, -O2, -O3, -Ofast - Debug and release builds --- ## Appendix A: Test Vectors ### A.1 Fixed-Point Multiplication ``` Input: a = 0x00020000 (2.0), b = 0x00030000 (3.0) Expected: 0x00060000 (6.0) Input: a = 0x00018000 (1.5), b = 0x00028000 (2.5) Expected: 0x0003C000 (3.75) Input: a = 0x7FFF0000 (32767.0), b = 0x00020000 (2.0) Expected: Overflow (saturate to FIXED_MAX) ``` ### A.2 Matrix Multiplication (2×2) ``` A = [1.0 2.0] B = [5.0 6.0] Expected C = [19.0 22.0] [3.0 4.0] [7.0 8.0] [43.0 50.0] Q16.16: A.data = [0x10000, 0x20000, 0x30000, 0x40000] B.data = [0x50000, 0x60000, 0x70000, 0x80000] C.data = [0x130000, 0x160000, 0x2B0000, 0x320000] ``` ### A.3 Convolution (Identity Kernel) ``` Input (3×3): Kernel (3×3): Output (1×1): [1 2 3] [0 0 0] [5] [4 5 6] [0 1 0] [7 8 9] [0 0 0] ``` --- ## Appendix B: Compliance Mapping ### B.1 DO-178C Objectives | Objective | Section | Compliance | |-----------|---------|------------| | Requirements traceability | §1.4 | ✓ SRS mapping | | Deterministic execution | §10 | ✓ Proved | | Bounded resources | §9 | ✓ O(1) memory | | WCET analysis | §9.1 | ✓ All bounded | ### B.2 IEC 62304 Objectives | Objective | Section | Compliance | |-----------|---------|------------| | Software architecture | §1-§7 | ✓ Documented | | Risk analysis | §8 | ✓ Fault model | | Unit verification | Appendix A | ✓ Test vectors | ### B.3 ISO 26262 Objectives | Objective | Section | Compliance | |-----------|---------|------------| | ASIL capability | §8, §10 | ✓ Deterministic, fault-tolerant | | Defensive programming | §8.4 | ✓ Saturation behavior | | Traceability | §1.4 | ✓ Full chain | --- ## Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0.0 | 2026-01-20 | William Murray | Initial release | --- **Document Status:** Final **Traceability:** All code in `certifiable-inference/src/` SHALL reference this document via `@traceability CI-MATH-001 §N.N` comments. --- *Copyright © 2026 The Murray Family Innovation Trust. All rights reserved.* ======================================================================== CI-STRUCT-001 — Certifiable Inference Data Structure Specification ======================================================================== Spec ID: CI-STRUCT-001 Title: Certifiable Inference Data Structure Specification Version: v1.0 Status: Final Layer: L2 Determinism: D1 Date: 2026-01-20 URL: https://axilog.io/specs/ci-struct-001/ Changelog: https://axilog.io/specs/ci-struct-001/changelog/ Summary: The authoritative data-structure reference for certifiable-inference — every struct, field, and lifetime traced to a CI-MATH-001 definition. **Traceability:** All structures in this document are derived from CI-MATH-001 and implemented in header files under `include/`. --- ## §1 Introduction ### §1.1 Purpose This document specifies all data structures for certifiable-inference. Every structure is derived from the mathematical definitions in CI-MATH-001 and serves as the authoritative reference for implementation. ### §1.2 Scope This specification covers: - Fixed-point types and constants - Matrix structures - Convolution parameters - Pooling parameters - Activation parameters - Hash table structures - Fault flags - Result codes ### §1.3 Notation | Notation | Meaning | |----------|---------| | `uint8_t[32]` | 32-byte array (SHA-256 hash) | | `Q16.16` | Fixed-point: 16 integer bits, 16 fractional bits | | `SHALL` | Mandatory requirement | | `→` | Maps to / derived from | ### §1.4 Document Alignment | Topic | CI-MATH-001 | CI-STRUCT-001 | Implementation | |-------|-------------|---------------|----------------| | Fixed-point | §2 | §3 | `fixed_point.h` | | Matrix | §3 | §4 | `matrix.h` | | Activation | §4 | §5 | `activations.h` | | Convolution | §5 | §6 | `convolution.h` | | Pooling | §6 | §7 | `pooling.h` | | Hash table | §7 | §8 | `deterministic_hash.h` | | Fault flags | §8 | §9 | `fixed_point.h` | --- ## §2 Type Definitions ### §2.1 Standard Integer Types All implementations SHALL use `` for portable integer types: ```c #include #include /* Required types */ int8_t /* Signed 8-bit */ int16_t /* Signed 16-bit */ int32_t /* Signed 32-bit */ int64_t /* Signed 64-bit */ uint8_t /* Unsigned 8-bit */ uint16_t /* Unsigned 16-bit */ uint32_t /* Unsigned 32-bit */ uint64_t /* Unsigned 64-bit */ ``` ### §2.2 Boolean Type ```c #include /* Boolean values */ true = 1 false = 0 ``` --- ## §3 Fixed-Point Types **Traceability:** CI-MATH-001 §2 ### §3.1 Core Type Definition ```c /** * @brief Q16.16 fixed-point number. * @traceability CI-MATH-001 §2.1 * * Format: Signed 32-bit integer * - Bits [31:16]: Integer part (signed) * - Bits [15:0]: Fractional part * * Range: [-32768.0, +32767.99998] * Precision: 1/65536 ≈ 0.0000153 */ typedef int32_t fixed_t; ``` ### §3.2 Constants **Traceability:** CI-MATH-001 §2.2 ```c /** Number of fractional bits */ #define FIXED_SHIFT 16 /** 1.0 in Q16.16 */ #define FIXED_ONE (1 << FIXED_SHIFT) /* 65536 = 0x00010000 */ /** 0.5 in Q16.16 (used for rounding) */ #define FIXED_HALF (1 << (FIXED_SHIFT - 1)) /* 32768 = 0x00008000 */ /** 0.0 in Q16.16 */ #define FIXED_ZERO (0) /** Smallest positive value (1 LSB) */ #define FIXED_EPS (1) /** Maximum representable value */ #define FIXED_MAX INT32_MAX /* 0x7FFFFFFF */ /** Minimum representable value */ #define FIXED_MIN INT32_MIN /* 0x80000000 */ ``` ### §3.3 Value Table | Constant | Decimal Value | Q16.16 Hex | Q16.16 Decimal | |----------|---------------|------------|----------------| | FIXED_ONE | 1.0 | 0x00010000 | 65536 | | FIXED_HALF | 0.5 | 0x00008000 | 32768 | | FIXED_ZERO | 0.0 | 0x00000000 | 0 | | FIXED_EPS | 0.0000153 | 0x00000001 | 1 | | FIXED_MAX | 32767.99998 | 0x7FFFFFFF | 2147483647 | | FIXED_MIN | -32768.0 | 0x80000000 | -2147483648 | ### §3.4 Common Precomputed Values ```c /** π in Q16.16 (3.14159...) */ #define FIXED_PI 205887 /* 0x00032440 */ /** e in Q16.16 (2.71828...) */ #define FIXED_E 178145 /* 0x0002B7E1 */ /** 0.01 in Q16.16 (common Leaky ReLU alpha) */ #define FIXED_ALPHA_001 655 /* 0x0000028F */ ``` --- ## §4 Matrix Structures **Traceability:** CI-MATH-001 §3 ### §4.1 Matrix Structure ```c /** * @brief Fixed-point matrix with caller-provided storage. * @traceability CI-MATH-001 §3.1 * * Memory layout: Row-major order * Element access: data[i * cols + j] for M[i][j] * * IMPORTANT: This structure does NOT own the data buffer. * The caller MUST ensure the buffer outlives the matrix. */ typedef struct { fixed_t *data; /**< Pointer to caller-owned buffer */ int rows; /**< Number of rows (height) */ int cols; /**< Number of columns (width) */ } fx_matrix_t; ``` ### §4.2 Memory Layout ``` Matrix M (3×4): Row 0: [M₀₀] [M₀₁] [M₀₂] [M₀₃] Row 1: [M₁₀] [M₁₁] [M₁₂] [M₁₃] Row 2: [M₂₀] [M₂₁] [M₂₂] [M₂₃] Linear storage (row-major): data[0..3] = Row 0 data[4..7] = Row 1 data[8..11] = Row 2 Index formula: M[i][j] = data[i * cols + j] ``` ### §4.3 Size Requirements | Dimensions | Elements | Bytes (Q16.16) | |------------|----------|----------------| | 1×1 | 1 | 4 | | 3×3 | 9 | 36 | | 28×28 | 784 | 3136 | | 64×64 | 4096 | 16384 | | 784×128 | 100352 | 401408 | ### §4.4 Initialization ```c /** * @brief Initialize a matrix with caller-provided buffer. * @traceability CI-MATH-001 §3.2 * * @param m Matrix to initialize (output) * @param buffer Pre-allocated buffer (at least rows×cols elements) * @param rows Number of rows * @param cols Number of columns * * @pre buffer != NULL * @pre rows > 0 && cols > 0 * @post m->data = buffer * @post m->rows = rows * @post m->cols = cols */ void fx_matrix_init(fx_matrix_t *m, fixed_t *buffer, int rows, int cols); ``` --- ## §5 Activation Structures **Traceability:** CI-MATH-001 §4 ### §5.1 Activation Type Enumeration ```c /** * @brief Supported activation functions. * @traceability CI-MATH-001 §4 */ typedef enum { CI_ACT_NONE = 0, /**< No activation (linear) */ CI_ACT_RELU, /**< ReLU: max(0, x) */ CI_ACT_LEAKY_RELU, /**< Leaky ReLU: x if x>0 else α×x */ CI_ACT_THRESHOLD /**< Binary threshold: x > θ ? 1 : 0 */ } ci_activation_t; ``` ### §5.2 Activation Parameters ```c /** * @brief Parameters for activation functions. * @traceability CI-MATH-001 §4.2 */ typedef struct { ci_activation_t type; /**< Activation function type */ fixed_t alpha; /**< Leaky ReLU slope (default: 655 = 0.01) */ fixed_t threshold; /**< Threshold value for binary activation */ } ci_activation_params_t; ``` ### §5.3 Default Parameters | Activation | Default Parameters | |------------|-------------------| | NONE | — | | RELU | — | | LEAKY_RELU | alpha = 655 (0.01) | | THRESHOLD | threshold = 0 | --- ## §6 Convolution Structures **Traceability:** CI-MATH-001 §5 ### §6.1 Convolution Parameters ```c /** * @brief Parameters for 2D convolution. * @traceability CI-MATH-001 §5.1 * * Currently supports: * - Valid padding only (no padding) * - Stride 1 only * - Single channel only */ typedef struct { int kernel_h; /**< Kernel height (typically 3, 5, 7) */ int kernel_w; /**< Kernel width (typically 3, 5, 7) */ int stride_h; /**< Vertical stride (currently must be 1) */ int stride_w; /**< Horizontal stride (currently must be 1) */ } ci_conv_params_t; ``` ### §6.2 Output Dimension Calculation **Traceability:** CI-MATH-001 §5.1 ```c /** * Calculate convolution output dimensions. * * For valid padding: * out_h = in_h - kernel_h + 1 * out_w = in_w - kernel_w + 1 */ #define CI_CONV_OUT_H(in_h, k_h) ((in_h) - (k_h) + 1) #define CI_CONV_OUT_W(in_w, k_w) ((in_w) - (k_w) + 1) ``` ### §6.3 Common Kernel Sizes | Kernel | Input 28×28 | Output Size | Operations | |--------|-------------|-------------|------------| | 3×3 | 28×28 | 26×26 | 6084 | | 5×5 | 28×28 | 24×24 | 14400 | | 7×7 | 28×28 | 22×22 | 23716 | --- ## §7 Pooling Structures **Traceability:** CI-MATH-001 §6 ### §7.1 Pooling Type Enumeration ```c /** * @brief Supported pooling operations. * @traceability CI-MATH-001 §6 */ typedef enum { CI_POOL_MAX = 0, /**< Maximum value in window */ CI_POOL_AVG /**< Average value in window (future) */ } ci_pool_type_t; ``` ### §7.2 Pooling Parameters ```c /** * @brief Parameters for pooling operations. * @traceability CI-MATH-001 §6.1 * * Currently supports: * - 2×2 window with stride 2 only * - Max pooling only */ typedef struct { ci_pool_type_t type; /**< Pooling type */ int window_h; /**< Window height (must be 2) */ int window_w; /**< Window width (must be 2) */ int stride_h; /**< Vertical stride (must equal window_h) */ int stride_w; /**< Horizontal stride (must equal window_w) */ } ci_pool_params_t; ``` ### §7.3 Output Dimension Calculation **Traceability:** CI-MATH-001 §6.1 ```c /** * Calculate pooling output dimensions. * * For non-overlapping pooling (stride = window): * out_h = in_h / window_h * out_w = in_w / window_w */ #define CI_POOL_OUT_H(in_h, win_h) ((in_h) / (win_h)) #define CI_POOL_OUT_W(in_w, win_w) ((in_w) / (win_w)) ``` --- ## §8 Hash Table Structures **Traceability:** CI-MATH-001 §7 ### §8.1 Result Codes ```c /** * @brief Hash table operation results. * @traceability CI-MATH-001 §7.5 */ typedef enum { D_TABLE_OK = 0, /**< Operation succeeded */ D_TABLE_KEY_EXISTS, /**< Insert failed: key already exists */ D_TABLE_NOT_FOUND, /**< Get failed: key not found */ D_TABLE_FULL, /**< Insert failed: table at capacity */ D_TABLE_ERROR /**< Generic error */ } d_table_res_t; ``` ### §8.2 Entry Structure ```c /** * @brief Single hash table entry. * @traceability CI-MATH-001 §7.5 */ typedef struct { char key[D_TABLE_MAX_KEY_LEN]; /**< Null-terminated key string */ int32_t value; /**< Associated value */ bool occupied; /**< True if slot contains valid data */ } d_table_entry_t; /** Maximum key length including null terminator */ #define D_TABLE_MAX_KEY_LEN 64 ``` ### §8.3 Table Structure ```c /** * @brief Deterministic hash table with insertion-order iteration. * @traceability CI-MATH-001 §7.1, §7.4 * * Memory layout: * - entries[]: Hash table slots (linear probing) * - insertion_order[]: Indices for deterministic iteration * * The table uses caller-provided buffer for both arrays. */ typedef struct { d_table_entry_t *entries; /**< Array of hash slots */ uint32_t *insertion_order; /**< Order of insertions for iteration */ uint32_t capacity; /**< Maximum entries */ uint32_t count; /**< Current entry count */ } d_table_t; ``` ### §8.4 Memory Requirements ```c /** * Calculate buffer size for hash table. * * @param capacity Maximum number of entries * @return Required buffer size in bytes */ #define D_TABLE_BUFFER_SIZE(capacity) \ ((capacity) * sizeof(d_table_entry_t) + (capacity) * sizeof(uint32_t)) ``` | Capacity | Entry Size | Order Size | Total Bytes | |----------|------------|------------|-------------| | 8 | 576 | 32 | 608 | | 16 | 1152 | 64 | 1216 | | 32 | 2304 | 128 | 2432 | | 64 | 4608 | 256 | 4864 | | 128 | 9216 | 512 | 9728 | ### §8.5 Callback Type ```c /** * @brief Callback function for hash table iteration. * @traceability CI-MATH-001 §7.4 * * @param key Entry key (null-terminated string) * @param value Entry value */ typedef void (*d_table_iter_fn)(const char *key, int32_t value); ``` --- ## §9 Fault Flags **Traceability:** CI-MATH-001 §8 ### §9.1 Fault Flag Structure ```c /** * @brief Sticky fault flags for arithmetic operations. * @traceability CI-MATH-001 §8.1 * * Flags are STICKY: once set, they remain set until explicitly cleared. * This enables fault detection across a sequence of operations. */ typedef struct { uint32_t overflow : 1; /**< Result saturated high (> INT32_MAX) */ uint32_t underflow : 1; /**< Result saturated low (< INT32_MIN) */ uint32_t div_zero : 1; /**< Division by zero attempted */ uint32_t domain : 1; /**< Input outside valid domain */ uint32_t precision : 1; /**< Significant precision loss */ uint32_t _reserved : 27; /**< Reserved for future use */ } ci_fault_flags_t; ``` ### §9.2 Fault Flag Semantics | Flag | Set When | Value Returned | |------|----------|----------------| | `overflow` | Result > INT32_MAX | INT32_MAX | | `underflow` | Result < INT32_MIN | INT32_MIN | | `div_zero` | Divisor == 0 | 0 | | `domain` | Invalid input (e.g., negative to sqrt) | 0 | | `precision` | Significant bits lost in conversion | Rounded value | ### §9.3 Helper Functions ```c /** * @brief Check if any fault occurred. * @traceability CI-MATH-001 §8.3 */ static inline bool ci_has_fault(const ci_fault_flags_t *f) { return f->overflow || f->underflow || f->div_zero || f->domain || f->precision; } /** * @brief Clear all fault flags. * @traceability CI-MATH-001 §8.3 */ static inline void ci_clear_faults(ci_fault_flags_t *f) { f->overflow = 0; f->underflow = 0; f->div_zero = 0; f->domain = 0; f->precision = 0; } ``` --- ## §10 Layer Structures (Future) ### §10.1 Dense Layer ```c /** * @brief Dense (fully connected) layer parameters. * @traceability CI-MATH-001 §4.4 * * Computation: Y = activation(X × W + b) */ typedef struct { fx_matrix_t weights; /**< Weight matrix (in_features × out_features) */ fx_matrix_t bias; /**< Bias vector (1 × out_features) */ ci_activation_params_t act; /**< Activation function */ } ci_dense_layer_t; ``` ### §10.2 Convolutional Layer ```c /** * @brief Convolutional layer parameters. * @traceability CI-MATH-001 §5 * * Single-channel 2D convolution with optional activation. */ typedef struct { fx_matrix_t kernel; /**< Convolution kernel */ fixed_t bias; /**< Scalar bias */ ci_conv_params_t conv; /**< Convolution parameters */ ci_activation_params_t act; /**< Activation function */ } ci_conv_layer_t; ``` ### §10.3 Pooling Layer ```c /** * @brief Pooling layer parameters. * @traceability CI-MATH-001 §6 */ typedef struct { ci_pool_params_t pool; /**< Pooling parameters */ } ci_pool_layer_t; ``` --- ## §11 Memory Layout Requirements ### §11.1 Alignment All structures SHALL be naturally aligned: - 1-byte fields: no alignment requirement - 2-byte fields: 2-byte aligned - 4-byte fields: 4-byte aligned - 8-byte fields: 8-byte aligned - Pointers: platform word-aligned (4 or 8 bytes) ### §11.2 Padding Structures MAY contain compiler-inserted padding for alignment. Do NOT hash structures directly; serialize field-by-field for deterministic hashing. ### §11.3 Static Allocation All structures are designed for static allocation. No `malloc`/`free` in hot paths. ### §11.4 Buffer Ownership Structures containing pointers (e.g., `fx_matrix_t`) do NOT own their buffers. The caller is responsible for: 1. Allocating buffers of sufficient size 2. Ensuring buffers outlive structures 3. Deallocating buffers when no longer needed --- ## §12 Serialization Rules **Traceability:** CI-MATH-001 Appendix B ### §12.1 Integer Encoding All integers are serialized as **little-endian**: | Type | Bytes | Encoding | |------|-------|----------| | `int8_t` | 1 | Direct (signed) | | `uint8_t` | 1 | Direct | | `int16_t` | 2 | Little-endian | | `uint16_t` | 2 | Little-endian | | `int32_t` / `fixed_t` | 4 | Little-endian | | `uint32_t` | 4 | Little-endian | | `int64_t` | 8 | Little-endian | | `uint64_t` | 8 | Little-endian | ### §12.2 Matrix Serialization ``` serialize_matrix(m): rows[4] /* int32_t, little-endian */ cols[4] /* int32_t, little-endian */ data[rows×cols×4] /* Row-major, each element 4 bytes LE */ ``` ### §12.3 String Serialization Strings are serialized as: ``` length[4] /* uint32_t, NOT including null terminator */ chars[length] /* UTF-8 bytes, NO null terminator */ ``` ### §12.4 Boolean Serialization ```c bool → uint8_t: false = 0x00, true = 0x01 ``` --- ## §13 Implementation Checklist ### §13.1 Required Types (`fixed_point.h`) ``` ☑ fixed_t ☑ FIXED_SHIFT ☑ FIXED_ONE ☑ FIXED_HALF ☑ FIXED_ZERO ☑ FIXED_EPS ☑ FIXED_MAX ☑ FIXED_MIN ``` ### §13.2 Required Types (`matrix.h`) ``` ☑ fx_matrix_t ☑ fx_matrix_init() ☑ fx_matrix_mul() ☑ fx_matrix_add() ``` ### §13.3 Required Types (`activations.h`) ``` ☑ ci_activation_t ☑ ci_activation_params_t ☑ fx_relu() ☑ fx_leaky_relu() ☑ fx_add_bias() ``` ### §13.4 Required Types (`convolution.h`) ``` ☑ ci_conv_params_t ☑ fx_conv2d() ☑ CI_CONV_OUT_H() ☑ CI_CONV_OUT_W() ``` ### §13.5 Required Types (`pooling.h`) ``` ☑ ci_pool_type_t ☑ ci_pool_params_t ☑ fx_maxpool_2x2() ☑ CI_POOL_OUT_H() ☑ CI_POOL_OUT_W() ``` ### §13.6 Required Types (`deterministic_hash.h`) ``` ☑ d_table_res_t ☑ d_table_entry_t ☑ d_table_t ☑ d_table_iter_fn ☑ d_table_init() ☑ d_table_insert() ☑ d_table_get() ☑ d_table_iterate() ``` --- ## Appendix A: Size Summary | Structure | Size (bytes) | Notes | |-----------|--------------|-------| | `fixed_t` | 4 | int32_t alias | | `fx_matrix_t` | 12-16 | Pointer + 2 ints | | `ci_activation_params_t` | 12 | enum + 2 fixed_t | | `ci_conv_params_t` | 16 | 4 ints | | `ci_pool_params_t` | 20 | enum + 4 ints | | `d_table_entry_t` | 72 | 64-char key + value + bool + padding | | `d_table_t` | 24-32 | 2 pointers + 2 uint32_t | | `ci_fault_flags_t` | 4 | Bitfield | --- ## Appendix B: Memory Budget Example ### B.1 MNIST Inference (784→64→10) | Component | Elements | Bytes | |-----------|----------|-------| | Input (28×28) | 784 | 3,136 | | W1 (784×64) | 50,176 | 200,704 | | b1 (1×64) | 64 | 256 | | Hidden (1×64) | 64 | 256 | | W2 (64×10) | 640 | 2,560 | | b2 (1×10) | 10 | 40 | | Output (1×10) | 10 | 40 | | **Total** | **51,748** | **206,992** | All buffers can be statically allocated. Zero runtime heap usage. --- ## Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0.0 | 2026-01-20 | William Murray | Initial release | --- **Document Status:** Final **Implementation:** `include/*.h` files **Traceability:** All structures trace to CI-MATH-001 sections as noted. --- *Copyright © 2026 The Murray Family Innovation Trust. All rights reserved.* ======================================================================== SRS-005-CR-001 — Conformance & Remediation ======================================================================== Spec ID: SRS-005-CR-001 Title: Conformance & Remediation Version: v1.1 Status: Locked Layer: L2 Determinism: D1 Date: 2026-03-27 Supersedes: SRS-005-CR-001 v1.0 Depends on: SRS-005 URL: https://axilog.io/specs/srs-005-cr-001/ Changelog: https://axilog.io/specs/srs-005-cr-001/changelog/ Summary: The L2 conformance contract — certifiable-inference must consume SRS-005 arithmetic verbatim; any divergence is a system integrity failure. **Depends on:** SRS-005 v1.1-Frozen **Scope:** Arithmetic Conformance --- ## 0. GOVERNING PRINCIPLE > **All arithmetic in L2 MUST conform to SRS-005.** > > **L2 SHALL NOT define independent arithmetic semantics.** > > **L2 SHALL be a consumer of L1 arithmetic law, not a variant of it.** Any divergence from SRS-005 is a system integrity failure. --- ## 1. PURPOSE This document defines the mandatory remediation required to bring `certifiable-inference` into full conformance with SRS-005 v1.1-Frozen. It specifies: - Identified non-conformances - Required code-level corrections - Deferred compliance items - Golden reference impact - Verification requirements **This document does not redefine arithmetic.** **It enforces compliance.** --- ## 2. CONFORMANCE REQUIREMENT A `certifiable-inference` implementation is conformant only if: - All blocking and high-severity issues are remediated - No SRS-005-SHALL violations remain in arithmetic paths - Golden vectors are regenerated where semantics changed - Cross-platform identity is preserved post-remediation - Type definitions are sourced from L1 (no duplication) --- ## 3. NON-CONFORMANCE REGISTER ### CR-001-ISSUE-001 — Signed Left Shift (UB) | Field | Value | |-------|-------| | Component | `fixed_from_int` | | Violation | SRS-005-SHALL-068 | | Severity | 🔴 BLOCKING | **Description** Left-shift of signed integer invokes undefined behaviour for negative values in C99. ```c return (fixed_t)(-((-i) << FIXED_SHIFT)); ``` **Why This Is Dangerous** C99 §6.5.7: "If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined." For negative values, left-shift is undefined — not implementation-defined, but undefined. The compiler may do anything. --- ### CR-001-ISSUE-002 — Signed Right Shift (Implementation-Defined) | Field | Value | |-------|-------| | Component | `fixed_to_int` | | Violation | SRS-005-SHALL-068 | | Severity | 🔴 BLOCKING | **Description** Right-shift of signed integer is implementation-defined and violates cross-platform determinism. ```c return f >> FIXED_SHIFT; ``` **Why This Is Dangerous** C99 §6.5.7: "If E1 has a signed type and a negative value, the resulting value is implementation-defined." While most compilers perform arithmetic shift (sign-extension), the standard permits logical shift (zero-fill). This breaks bit-identity across platforms. --- ### CR-001-ISSUE-003 — Multiplication Rounding Divergence | Field | Value | |-------|-------| | Component | `fixed_mul` | | Violation | SRS-005-SHALL-067 | | Severity | 🔴 BLOCKING | **Description** Use of rounding (`+ FIXED_HALF`) violates mandated truncation semantics. ```c result += FIXED_HALF; return (fixed_t)(result >> FIXED_SHIFT); ``` **Why This Is Dangerous** SRS-005-SHALL-067 mandates truncation toward zero. The previous implementation was "better math" (rounding) but "worse for a verifiable substrate" — rounding introduces hidden dependencies on tie-handling behaviour. Truncation is simple, total, and identical everywhere. --- ### CR-001-ISSUE-004 — Signed Left Shift in Division | Field | Value | |-------|-------| | Component | `fixed_div` | | Violation | SRS-005-SHALL-068 | | Severity | 🔴 BLOCKING | **Description** Left-shift used for scaling introduces undefined behaviour. ```c int64_t numerator = (int64_t)a << FIXED_SHIFT; ``` **Remediation** Use multiplication instead of shift: ```c int64_t numerator = (int64_t)a * FIXED_ONE; ``` --- ### CR-001-ISSUE-005 — INT32_MIN Overflow (abs/neg) | Field | Value | |-------|-------| | Component | `fixed_abs`, `fixed_neg` | | Violation | SRS-005-SHALL-014, SRS-005-SHALL-015 | | Severity | 🟠 HIGH | **Description** Negation of `INT32_MIN` overflows and is not handled. ```c -INT32_MIN /* Undefined behaviour: result cannot be represented */ ``` **Required End State** - Saturate to `INT32_MAX` - Set `overflow` flag (when fault propagation is integrated) --- ### CR-001-ISSUE-006 — Duplicate Type Definition (L2 Header Leak) | Field | Value | |-------|-------| | Component | `include/fixed_point.h` | | Violation | Architectural — Source of Truth | | Severity | 🟠 HIGH | **Description** *Added in v1.1 per external audit finding.* `certifiable-inference` defines its own `fixed_point.h` with `FIXED_ONE`, `FIXED_HALF`, etc. This creates **two sources of truth** for the same constants: - `libaxilog/include/axilog/types.h` (L1 — authoritative) - `certifiable-inference/include/fixed_point.h` (L2 — duplicate) **Risk** If L1 constants ever change (e.g., for a Q16.32 variant), the L2 definitions would silently diverge, breaking the "one arithmetic law" principle. **Remediation** Replace the contents of L2's `fixed_point.h` with: ```c /** * @file fixed_point.h * @brief L2 Fixed-Point Types (L1 Delegation) * * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * SRS: SRS-005-CR-001 * * This header delegates to L1 (libaxilog) for all arithmetic * type definitions. L2 SHALL NOT define independent constants. */ #ifndef CERTIFIABLE_INFERENCE_FIXED_POINT_H #define CERTIFIABLE_INFERENCE_FIXED_POINT_H #include /* L2 legacy type aliases — delegate to L1 */ typedef q16_16_t fixed_t; #define FIXED_SHIFT Q16_SHIFT #define FIXED_ONE Q16_ONE #define FIXED_HALF Q16_HALF #define FIXED_MAX Q16_MAX #define FIXED_MIN Q16_MIN #define FIXED_ZERO 0 #endif /* CERTIFIABLE_INFERENCE_FIXED_POINT_H */ ``` **Rationale** This ensures the entire stack updates atomically if L1 constants change. L2 becomes a pure consumer of L1 arithmetic law. --- ## 4. REQUIRED REMEDIATION ### 4.1 `fixed_from_int` ```c /** * @brief Convert integer to Q16.16 fixed-point. * * SRS-005-SHALL-005: Integer-to-Q16.16 conversion * SRS-005-SHALL-068: No signed shift */ static inline fixed_t fixed_from_int(int32_t i) { return (fixed_t)(i * FIXED_ONE); } ``` --- ### 4.2 `fixed_to_int` ```c /** * @brief Convert Q16.16 fixed-point to integer (truncation). * * SRS-005-SHALL-006: Q16.16-to-integer conversion * SRS-005-SHALL-068: No signed shift */ static inline int32_t fixed_to_int(fixed_t f) { return f / FIXED_ONE; } ``` --- ### 4.3 `fixed_mul` ```c /** * @brief Saturated Q16.16 multiplication (truncation toward zero). * * SRS-005-SHALL-012: Saturated multiplication * SRS-005-SHALL-067: Truncation mandated (no rounding) * SRS-005-SHALL-068: No signed shift */ fixed_t fixed_mul(fixed_t a, fixed_t b) { int64_t result = (int64_t)a * (int64_t)b; /* Truncation toward zero — C99 division semantics */ result = result / FIXED_ONE; /* Saturation */ if (result > INT32_MAX) { return INT32_MAX; } if (result < INT32_MIN) { return INT32_MIN; } return (fixed_t)result; } ``` --- ### 4.4 `fixed_div` ```c /** * @brief Saturated Q16.16 division. * * SRS-005-SHALL-013: Saturated division * SRS-005-SHALL-068: No signed shift * SRS-005-SHALL-069: INT32_MIN/-1 handled */ fixed_t fixed_div(fixed_t a, fixed_t b) { if (b == 0) { return FIXED_ZERO; /* Temporary — see §5 (CR-001-DEFER-003) */ } /* Use multiplication instead of shift */ int64_t numerator = (int64_t)a * FIXED_ONE; int64_t result = numerator / (int64_t)b; /* Saturation */ if (result > INT32_MAX) { return INT32_MAX; } if (result < INT32_MIN) { return INT32_MIN; } return (fixed_t)result; } ``` --- ### 4.5 `fixed_abs` ```c /** * @brief Absolute value with INT32_MIN saturation. * * SRS-005-SHALL-015: Absolute value * SRS-005-SHALL-069: INT32_MIN overflow handled */ fixed_t fixed_abs(fixed_t f) { if (f == INT32_MIN) { return INT32_MAX; /* Saturate — see §5 for fault integration */ } return (f < 0) ? -f : f; } ``` --- ### 4.6 `fixed_neg` ```c /** * @brief Negation with INT32_MIN saturation. * * SRS-005-SHALL-014: Negation * SRS-005-SHALL-069: INT32_MIN overflow handled */ fixed_t fixed_neg(fixed_t f) { if (f == INT32_MIN) { return INT32_MAX; /* Saturate — see §5 for fault integration */ } return -f; } ``` --- ## 5. DEFERRED COMPLIANCE ITEMS ### CR-001-DEFER-001 — Fault Propagation Integration | Field | Value | |-------|-------| | Area | All arithmetic primitives | | Target | Phase 3 | **Description** Current implementation does not propagate `ct_fault_flags_t`. **Required End State** All functions SHALL conform to: - SRS-005-SHALL-029 (fault context acceptance) - SRS-005-SHALL-031 (fault signalling) - SRS-005-SHALL-034 (no silent failure) **Migration Path** ```c /* Current (Phase 2) */ fixed_t fixed_mul(fixed_t a, fixed_t b); /* Target (Phase 3) */ fixed_t fixed_mul(fixed_t a, fixed_t b, ct_fault_flags_t *faults); ``` --- ### CR-001-DEFER-002 — INT32_MIN Fault Signalling | Field | Value | |-------|-------| | Area | `fixed_abs`, `fixed_neg` | | Target | Phase 3 | **Current Behaviour** Saturates to `INT32_MAX` silently. **Required Behaviour** ```c if (f == INT32_MIN) { faults->overflow = 1; return INT32_MAX; } ``` --- ### CR-001-DEFER-003 — Division by Zero Fault | Field | Value | |-------|-------| | Area | `fixed_div` | | Target | Phase 3 | **Current Behaviour** ```c return FIXED_ZERO; ``` **Required Behaviour** ```c faults->div_zero = 1; return 0; ``` --- ## 6. GOLDEN REFERENCE IMPACT ### 6.1 Affected Operations | Operation | Change Type | Impact | |-----------|-------------|--------| | `fixed_mul` | **MANDATORY** | Rounding → Truncation | | Inference outputs | **CASCADE** | All dependent computations | ### 6.2 Required Actions 1. Apply all §4 remediations 2. Re-run `certifiable-harness` 3. Regenerate golden vectors 4. Freeze new reference set 5. Update cross-platform identity hashes ### 6.3 Interpretation > **Changes are corrections, not regressions.** > > **Previous outputs are non-conformant to SRS-005.** The new golden references represent the first **correct** outputs. Prior references were produced by non-conformant arithmetic. --- ## 7. VERIFICATION REQUIREMENTS The following MUST pass post-remediation: ``` ☐ property-test-arith — All arithmetic property tests ☐ golden-vector — Re-frozen reference vectors ☐ cross-platform-x86 — x86_64 bit-identity ☐ cross-platform-arm — ARM64 bit-identity ☐ static-analysis — No UB (clang-tidy, cppcheck) ☐ forbidden-pattern-scan — No << or >> on signed ints ☐ rtm-coverage — SRS-005 alignment verified ☐ header-delegation-check — L2 types delegate to L1 ``` --- ## 8. NON-SCOPE CONFIRMATION The following components are explicitly **out of scope**: ### 8.1 Jenkins Hash The Jenkins One-at-a-Time hash is: - **Deterministic** — integer-only, bit-perfect - **Platform-independent** — no signed shifts - **Internal scope** — hash table lookup, not cryptographic - **Not part of AX:OBS:v1** — no Chain of Custody role **Status: DO NOT MODIFY** **Rationale:** Changing it would introduce unnecessary "Golden Vector noise" without increasing security or determinism. --- ## 9. ARCHITECTURAL DIRECTION ### 9.1 Progressive L1 Adoption (Recommended) Future alignment path: ```c /* Preferred (L1 primitive) */ q16_16_t result = ax_mul_q16(a, b, &faults); /* Transitional (L2 wrapper) */ fixed_t result = fixed_mul(a, b); ``` ### 9.2 Header Consolidation (Mandatory) Per CR-001-ISSUE-006, L2 SHALL delegate type definitions to L1: ``` certifiable-inference/include/fixed_point.h └── #include └── typedef q16_16_t fixed_t; ``` ### 9.3 Rationale - Eliminates duplication - Prevents future drift - Reduces audit surface - Ensures atomic updates across the stack --- ## 10. BUILD SYSTEM INTEGRATION ### 10.1 CMakeLists.txt Updates ```cmake # Link against libaxilog find_package(axilog REQUIRED) target_link_libraries(certifiable-inference PRIVATE axilog::axilog) # Include L1 headers target_include_directories(certifiable-inference PRIVATE ${AXILOG_INCLUDE_DIRS} ) # Forbidden pattern scan (CI gate) add_custom_target(forbidden-pattern-scan COMMAND grep -rn "<<\\|>>" --include="*.c" --include="*.h" ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/include && exit 1 || exit 0 COMMENT "Scanning for forbidden shift operators on signed integers" ) ``` ### 10.2 Hardened Compiler Flags ```cmake add_compile_options( -Wall -Wextra -Werror -Wpedantic -fno-strict-aliasing -fwrapv -fno-tree-vectorize -fno-builtin -ffp-contract=off -fno-fast-math ) ``` --- ## 11. FINAL STATEMENT > **`certifiable-inference` SHALL NOT define arithmetic behaviour.** > > **It SHALL implement SRS-005.** Following remediation: - ✅ All undefined behaviour is eliminated - ✅ All implementation-defined behaviour is removed - ✅ Arithmetic semantics are aligned with L1 - ✅ Cross-platform determinism is preserved - ✅ Type definitions delegate to single source of truth --- ## 12. CLOSURE CONDITION This document is satisfied when: - [ ] All BLOCKING issues are remediated (001–004, 006) - [ ] All HIGH issues are remediated (005) - [ ] Golden vectors are re-frozen - [ ] CI gates pass - [ ] No SRS-005 violations remain in arithmetic paths - [ ] L2 headers delegate to L1 types --- ## 13. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0-Frozen | 2026-03-27 | William Murray | Initial conformance specification — 5 issues, full remediation defined | | 1.1-Frozen | 2026-03-27 | William Murray | Added CR-001-ISSUE-006 (L2 header leak), build system integration, hardened compiler flags. Total: 6 issues. | --- ## 14. AUDIT RECORD ### v1.0 → v1.1 | Finding | Source | Resolution | |---------|--------|------------| | Duplicate type definition in L2 header | Gemini 2.5 Pro | CR-001-ISSUE-006 added | | Build system integration missing | Internal | §10 added | | Hardened compiler flags not specified | Internal | §10.2 added | **Audit Source:** External review (Gemini 2.5 Pro) **Audit Date:** 27 March 2026 --- ## 15. AUDIT VERDICT | Category | Status | |----------|--------| | Blocking issues | ✅ Remediation defined (4) | | High issues | ✅ Remediation defined (2) | | Arithmetic alignment | ✅ Achieved post-patch | | Header consolidation | ✅ Specified | | Determinism compliance | ✅ Enforced | | Remaining risk | 🟡 Deferred (fault propagation — Phase 3) | --- ## Appendix A — Shift Operator Audit Checklist Pre-merge verification: ```bash # Must return empty (no matches) grep -rn '<<\|>>' --include='*.c' --include='*.h' \ src/ include/ | grep -v '//' # If any matches found, verify they are: # 1. On unsigned types only, OR # 2. Not in arithmetic paths (e.g., bit flags) ``` --- ## Appendix B — Cross-Reference Matrix | L2 Issue | SRS-005 SHALL | Remediation | |----------|--------------|-------------| | CR-001-ISSUE-001 | SHALL-068 | §4.1 | | CR-001-ISSUE-002 | SHALL-068 | §4.2 | | CR-001-ISSUE-003 | SHALL-067 | §4.3 | | CR-001-ISSUE-004 | SHALL-068 | §4.4 | | CR-001-ISSUE-005 | SHALL-014, 015 | §4.5, §4.6 | | CR-001-ISSUE-006 | (Architectural) | §9.2 | --- *SRS-005-CR-001 v1.1-Frozen — Audit-Frozen FINAL* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== SRS-006-CONVOLUTION — Deterministic 2D Convolution ======================================================================== Spec ID: SRS-006-CONVOLUTION Title: Deterministic 2D Convolution Version: v0.1 Status: Draft Layer: L2 Determinism: D1 Date: 2026-01-20 Compliance: ISO 26262, IEC 62304, MISRA-C:2012 URL: https://axilog.io/specs/srs-006-convolution/ Changelog: https://axilog.io/specs/srs-006-convolution/changelog/ Summary: 2D convolution for safety-critical computer vision — sliding-window dot products with bit-perfect parity and bounded execution time across all platforms. **Component:** Core / Vision **Compliance:** ISO 26262 · IEC 62304 · MISRA-C:2012 **Applicability:** Computer Vision (Medical Imaging, Autonomous Vehicles) --- ## 1. Purpose This module defines deterministic 2D convolution operations for computer vision applications. Convolution is the fundamental operation in Convolutional Neural Networks (CNNs) used for image analysis, object detection, and medical diagnostics. **Critical Requirement:** The system must perform sliding-window dot products with bit-perfect parity and bounded execution time across all platforms. ## 2. Requirements ### 2.1 Functional Requirements **SRS-006.1: Valid Padding Convolution** The system shall implement 2D convolution with "valid" padding (no zero-padding). **Mathematical Definition:** ``` For input I (H×W), kernel K (KH×KW): Output O dimensions: (H - KH + 1) × (W - KW + 1) O[r][c] = Σ(i=0 to KH-1) Σ(j=0 to KW-1) I[r+i][c+j] × K[i][j] ``` **Rationale:** - Valid padding has predictable output dimensions - No ambiguity about boundary handling - Simplest to verify for certification **Verification:** Unit tests confirm correct output dimensions and values. --- **SRS-006.2: Sliding Window Implementation** The convolution shall use explicit nested loops for the sliding window, with no data-dependent branching in inner loops. **Implementation Pattern:** ```c for each output position (r, c): accumulator = 0 for each kernel position (kr, kc): accumulator += input[r+kr][c+kc] * kernel[kr][kc] output[r][c] = quantize(accumulator) ``` **Rationale:** - Explicit loops make WCET analysis tractable - No hidden optimizations that vary by platform - Cache behavior is predictable **Verification:** Timing analysis confirms O(OH × OW × KH × KW) complexity. --- **SRS-006.3: 64-bit Accumulation** Intermediate accumulation shall use 64-bit integers to prevent overflow. **Rationale:** - Kernel sizes commonly 3×3 to 11×11 - Maximum accumulation: 11×11 = 121 products - Each product: 32-bit × 32-bit = 64-bit - Sum of 121 products requires > 32 bits **Implementation:** Same accumulator pattern as SRS-003 (matrix multiplication). **Verification:** Overflow tests with maximum-valued kernels and inputs. --- **SRS-006.4: Quantization Consistency** Output quantization shall use round-to-nearest with explicit rounding constant. **Implementation:** ```c accumulator += FIXED_HALF; output = (fixed_t)(accumulator >> FIXED_SHIFT); ``` **Rationale:** - Consistent with SRS-002 and SRS-003 - Minimizes quantization error - Deterministic across platforms **Verification:** Quantization tests verify rounding behavior. ### 2.2 Performance Requirements **SRS-006.5: Bounded Execution Time** Convolution execution time shall depend only on matrix dimensions, not on data values. **Time Complexity:** ``` T = O(OH × OW × KH × KW) Where: OH, OW = Output height, width KH, KW = Kernel height, width ``` **Rationale:** - Required for real-time systems - Enables WCET analysis - Prevents timing side-channels **Verification:** Timing tests with various data patterns show identical execution time. --- **SRS-006.6: Memory Efficiency** Convolution shall operate on caller-provided buffers with no dynamic allocation. **Memory Pattern:** ``` Input: Caller allocates H × W elements Kernel: Caller allocates KH × KW elements Output: Caller allocates (H-KH+1) × (W-KW+1) elements ``` **Rationale:** - Predictable memory footprint - No heap fragmentation - Suitable for embedded systems **Verification:** Memory profiling confirms O(1) space complexity. ## 3. Common Kernel Types ### 3.1 Edge Detection Kernels **Sobel Vertical (detects vertical edges):** ``` [-1 0 1] [-2 0 2] [-1 0 1] ``` **Sobel Horizontal (detects horizontal edges):** ``` [-1 -2 -1] [ 0 0 0] [ 1 2 1] ``` **Laplacian (detects all edges):** ``` [ 0 1 0] [ 1 -4 1] [ 0 1 0] ``` ### 3.2 Smoothing Kernels **Gaussian Blur (3×3, σ=1):** ``` [1 2 1] (divided by 16) [2 4 2] [1 2 1] ``` **Box Blur (3×3):** ``` [1 1 1] (divided by 9) [1 1 1] [1 1 1] ``` ### 3.3 Neural Network Kernels **LeNet-5 First Layer:** 5×5 kernels (learned weights) **ResNet First Layer:** 7×7 kernels (learned weights) **MobileNet Depthwise:** 3×3 kernels (efficient for mobile) ## 4. Padding Modes (Future) ### 4.1 Valid Padding (Current Implementation) - No padding added - Output smaller than input - **Status:** ✅ Implemented ### 4.2 Same Padding (Planned) - Zero-padding added to maintain size - Output same dimensions as input - **Status:** 🔄 Future extension ### 4.3 Full Padding (Planned) - Maximum padding - Output larger than input - **Status:** 🔄 Future extension ## 5. Design Decisions ### Why Start With Valid Padding? **Valid Padding Chosen:** - ✅ Simplest to implement - ✅ No ambiguity about boundaries - ✅ Easiest to verify - ✅ Common in many architectures **Same Padding Deferred:** - ⏳ Requires zero-padding logic - ⏳ More complex boundary conditions - ⏳ Can be added later without breaking API ### Row-Major vs Column-Major **Row-Major Chosen:** - ✅ Consistent with SRS-003 (matrix operations) - ✅ Better cache locality for typical access patterns - ✅ Matches standard C array layout ## 6. Verification Criteria **V-006.1: Correctness** Test convolution against known results: - Simple 3×3 kernel on 5×5 input - Sobel filters on test patterns - Compare with reference implementations **Pass Criteria:** Bit-identical results. --- **V-006.2: Determinism** Run same convolution 1000 times: - Same kernel, same input - Verify bit-identical outputs **Pass Criteria:** All outputs identical. --- **V-006.3: Platform Independence** Run on multiple architectures: - x86-64 (Intel/AMD) - ARM (Cortex-A, Cortex-M) - RISC-V **Pass Criteria:** Bit-identical results across all platforms. --- **V-006.4: Dimension Validation** Test with mismatched dimensions: - Kernel larger than input - Output buffer wrong size - NULL pointers **Pass Criteria:** Safe handling (no crash, predictable behavior). --- **V-006.5: Overflow Protection** Test with maximum values: - 11×11 kernel all FIXED_MAX - Input all FIXED_MAX - Verify no overflow **Pass Criteria:** 64-bit accumulator handles all cases. ## 7. Performance Characteristics **Time Complexity:** ``` Valid Padding: O(OH × OW × KH × KW) Example: Input: 224×224 Kernel: 3×3 Output: 222×222 Operations: 222 × 222 × 3 × 3 = 443,556 MACs ``` **Space Complexity:** ``` O(1) - all buffers caller-provided No temporary allocations Stack usage: < 100 bytes ``` **Cache Behavior:** - Row-major layout optimizes cache usage - Spatial locality in sliding window - Predictable access patterns ## 8. Medical Imaging Example ### Use Case: Tumor Detection **Input:** 512×512 grayscale CT scan slice **Layer 1:** 5×5 edge detection kernels (4 filters) - Output: 508×508×4 feature maps - Detects tumor boundaries **Layer 2:** 3×3 refinement kernels (8 filters) - Output: 506×506×8 feature maps - Classifies tissue types **Requirement:** Bit-perfect results across all hospital scanners. **Our Value:** Same CT scan → Same feature maps → Same diagnosis, regardless of hardware. ## 9. Automotive Example ### Use Case: Pedestrian Detection **Input:** 640×480 camera frame (cropped to ROI) **Layer 1:** 7×7 edge kernels (16 filters) - Detects human silhouettes **Layer 2:** 5×5 shape kernels (32 filters) - Identifies body parts **Layer 3:** 3×3 refinement kernels (64 filters) - Final classification **Requirement:** ISO 26262 ASIL-D certification requires deterministic behavior. **Our Value:** Prove car's vision system behaves identically in all conditions. ## 10. Implementation **Files:** - `include/convolution.h` - API specification - `src/core/convolution.c` - Implementation - `tests/unit/test_convolution.c` - Verification - `examples/edge_detection.c` - Demonstration **Traceability:** - Code: `@traceability SRS-006-CONVOLUTION` - Tests: Link to this document in header ## 11. Usage Example ```c /* Edge detection with Sobel filter */ // Input image (8×8 grayscale) fixed_t input_buf[64]; fx_matrix_t input; fx_matrix_init(&input, input_buf, 8, 8); // ... fill with image data // Sobel vertical kernel (3×3) fixed_t kernel_buf[9] = { fixed_from_int(-1), fixed_from_int(0), fixed_from_int(1), fixed_from_int(-2), fixed_from_int(0), fixed_from_int(2), fixed_from_int(-1), fixed_from_int(0), fixed_from_int(1) }; fx_matrix_t kernel; fx_matrix_init(&kernel, kernel_buf, 3, 3); // Output (6×6) fixed_t output_buf[36]; fx_matrix_t output; fx_matrix_init(&output, output_buf, 6, 6); // Run convolution fx_conv2d(&input, &kernel, &output); // Result: vertical edges detected in output ``` ## 12. Integration with Neural Networks **Typical CNN Layer:** ```c // Conv2D → BatchNorm → ReLU fx_conv2d(&input, &weights, &conv_out); // Convolution fx_matrix_add_bias(&conv_out, &bias); // Add bias // (BatchNorm - future) fx_relu(&conv_out); // Activation ``` **Multi-Channel Convolution (Future):** - Current: Single-channel (grayscale) - Planned: Multi-channel (RGB, feature maps) - Extension: Depth-wise separable convolutions ## 13. Future Extensions **SRS-006.7:** (Planned) Same Padding Support **SRS-006.8:** (Planned) Multi-Channel Convolution **SRS-006.9:** (Planned) Strided Convolution **SRS-006.10:** (Planned) Dilated Convolution ## 14. References - **MISRA-C:2012** - Rule 17.7 (Return value checking) - **ISO 26262-6:2018** - Software unit design - **IEC 62304:2006** - Medical device software - **LeCun et al. (1998)** - "Gradient-Based Learning Applied to Document Recognition" - **Krizhevsky et al. (2012)** - "ImageNet Classification with Deep CNNs" ## 15. Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0 | 2026-01-15 | William Murray | Initial version | --- **Document Classification:** Technical Specification **Approval Status:** Approved for Implementation **Next Review:** 2026-04-15 ======================================================================== SRS-008-POOLING — Max Pooling Layer ======================================================================== Spec ID: SRS-008-POOLING Title: Max Pooling Layer Version: v0.1 Status: Draft Layer: L2 Determinism: D1 Date: 2026-01-20 Compliance: DO-178C, ISO 26262, IEC 62304 URL: https://axilog.io/specs/srs-008-pooling/ Changelog: https://axilog.io/specs/srs-008-pooling/changelog/ Summary: Deterministic max pooling for CNNs — bit-perfect spatial reduction with zero dynamic allocation; companion to SRS-006 at the L2 inference boundary. **Component:** Core / Pooling Operations **Dependencies:** SRS-001 (Matrix) · SRS-002 (Fixed-Point) **Compliance:** DO-178C · ISO 26262 · IEC 62304 --- ## 1. Purpose This module defines requirements for deterministic max pooling operations used in convolutional neural networks (CNNs) to reduce spatial dimensions while preserving salient features. **Critical Requirement:** Max pooling must be deterministic, bit-perfect, and execute with zero dynamic memory allocation. ## 2. Background ### 2.1 Role in CNNs **Spatial Dimension Reduction:** - Reduces feature map size (typically by 2×) - Decreases computational load in deeper layers - Creates translation invariance **Feature Preservation:** - Retains maximum activation in each pool region - Preserves most salient features - Enables hierarchical feature learning ### 2.2 Max Pooling Operation **Standard 2×2 Max Pooling (Stride 2):** ``` Input: 4×4 feature map Output: 2×2 feature map (reduced by 2×) For each 2×2 window, select maximum value: ┌───────────┐ │ a b │ c d│ ┌──────┐ │ e f │ g h│ → │max(a,b,e,f) max(c,d,g,h)│ ├───────────┤ │max(i,j,m,n) max(k,l,o,p)│ │ i j │ k l│ └──────┘ │ m n │ o p│ └───────────┘ ``` **Deterministic Selection:** - No floating-point comparisons - Fixed-point max operation - Bit-perfect reproducibility ## 3. Requirements ### 3.1 Functional Requirements **SRS-008.1: 2×2 Max Pooling** Implement deterministic 2×2 max pooling with stride 2. **Signature:** ```c void fx_maxpool_2x2(const fx_matrix_t* in, fx_matrix_t* out); ``` **Preconditions:** - `in->rows` and `in->cols` must be even - `out->rows == in->rows / 2` - `out->cols == in->cols / 2` - Both matrices pre-allocated **Behavior:** - Divides input into non-overlapping 2×2 windows - Selects maximum value from each window - Writes result to output matrix **Rationale:** - Standard CNN architecture component - 2×2 pooling most common in practice - Stride 2 ensures non-overlapping windows **Verification:** Unit tests verify correct max selection. --- **SRS-008.2: Deterministic Max Selection** Max selection must be bit-perfect and independent of floating-point comparison semantics. **Implementation:** ```c // Deterministic max for fixed-point values fixed_t max = window[0]; if (window[1] > max) max = window[1]; if (window[2] > max) max = window[2]; if (window[3] > max) max = window[3]; ``` **Rationale:** - Integer comparison (no FP rounding) - Deterministic for all input values - No NaN or special value handling needed **Verification:** Bit-exact tests with boundary values. --- **SRS-008.3: Input Dimension Validation** Operations shall verify input dimensions are valid for pooling. **Validation:** ```c assert(in->rows % 2 == 0); // Even rows required assert(in->cols % 2 == 0); // Even cols required assert(out->rows == in->rows / 2); assert(out->cols == in->cols / 2); ``` **Rationale:** - Prevents undefined behavior - Ensures correct output dimensions - Catches integration errors early **Verification:** Tests with invalid dimensions should fail assertions. ### 3.2 Resource Requirements **SRS-008.4: Zero Dynamic Allocation** Max pooling shall perform no dynamic memory allocation. **Implementation:** - Input/output matrices pre-allocated by caller - No temporary buffers required - Stack usage: O(1) **Rationale:** - Consistent with SRS-001 (Matrix) and SRS-003 (Memory) - Enables static memory analysis - Required for certification **Verification:** Memory leak tests confirm zero allocations. --- **SRS-008.5: Bounded Stack Usage** Stack usage shall be constant and documented. **Expected Usage:** - Local variables: ~4 bytes (loop counters) - No recursion - No variable-length arrays **Rationale:** - Stack overflow prevention - Enables static analysis - Required for embedded systems **Verification:** Static analysis confirms O(1) stack. ### 3.3 Performance Requirements **SRS-008.6: Linear Time Complexity** Max pooling time complexity shall be O(M × N) where M×N is input size. **Expected Operations:** ``` For input: M×N Output: (M/2)×(N/2) Comparisons: M×N (one per input element) ``` **Rationale:** - Each input element examined exactly once - No repeated computations - Optimal complexity for this operation **Verification:** Benchmark confirms linear scaling. --- **SRS-008.7: Deterministic Execution Time** Execution time shall be independent of input data values. **Implementation:** - Fixed iteration count (input dimensions) - No data-dependent branches in inner loop - No early exits **Rationale:** - Required for real-time systems (SRS-007) - Prevents timing side-channels - Enables WCET analysis **Verification:** Timing tests with varied input patterns. ## 4. Mathematical Properties ### 4.1 Dimension Reduction **Input-Output Relationship:** ``` Given input I with dimensions (H, W) Output O has dimensions (H/2, W/2) For each output position (i, j): O[i][j] = max(I[2i][2j], I[2i][2j+1], I[2i+1][2j], I[2i+1][2j+1]) ``` **Spatial Preservation:** - Output preserves spatial topology - Each output corresponds to 2×2 input region - Non-overlapping windows (stride 2) ### 4.2 Value Properties **Range Preservation:** ``` min(input) ≤ output ≤ max(input) ``` **Monotonicity:** - If all input values increase, output values increase or stay same - Max operation is monotonic **Identity Property:** - If 2×2 window contains identical values, output = that value - max(x, x, x, x) = x ## 5. Integration with CNN Pipeline ### 5.1 Typical Usage Pattern **After Convolution + Activation:** ```c // Convolution layer fx_conv2d(&input, &kernel, &conv_out); // 16×16 → 14×14 // Activation (ReLU) fx_relu(&conv_out, &activated); // 14×14 → 14×14 // Max Pooling fx_maxpool_2x2(&activated, &pooled); // 14×14 → 7×7 ``` ### 5.2 Memory Planning **Buffer Allocation:** ```c // Pre-allocate all buffers fixed_t conv_buf[196]; // 14×14 after convolution fixed_t pool_buf[49]; // 7×7 after pooling fx_matrix_t conv_out, pool_out; fx_matrix_init(&conv_out, conv_buf, 14, 14); fx_matrix_init(&pool_out, pool_buf, 7, 7); ``` ### 5.3 Multi-Layer Networks **Stacking Multiple Layers:** ``` Input: 32×32 ↓ Conv3×3 Conv1: 30×30 ↓ ReLU Activated1: 30×30 ↓ MaxPool2×2 Pooled1: 15×15 ↓ Conv3×3 Conv2: 13×13 ↓ ReLU Activated2: 13×13 ↓ MaxPool2×2 Pooled2: 6×6 (odd dimension, needs padding) ``` ## 6. Handling Odd Dimensions ### 6.1 Problem Max pooling requires even dimensions. CNNs may produce odd-sized feature maps. **Example:** ``` 13×13 feature map cannot be evenly pooled with 2×2, stride 2 ``` ### 6.2 Solutions **Solution 1: Padding (Recommended)** ```c // Pad 13×13 to 14×14 with zeros fixed_t padded_buf[196]; fx_matrix_t padded; fx_matrix_init(&padded, padded_buf, 14, 14); fx_pad_zeros(&input_13x13, &padded); // Add padding fx_maxpool_2x2(&padded, &output_7x7); ``` **Solution 2: Truncation** ```c // Pool only 12×12 region, discard last row/col // Not recommended - loses information ``` **Solution 3: Design Constraint** ```c // Ensure all layer dimensions are even // Plan CNN architecture accordingly ``` **Recommendation:** Use padding for flexibility, design constraint for optimization. ## 7. Example Implementation ### 7.1 Reference Code ```c void fx_maxpool_2x2(const fx_matrix_t* in, fx_matrix_t* out) { /* Validate dimensions */ assert(in->rows % 2 == 0); assert(in->cols % 2 == 0); assert(out->rows == in->rows / 2); assert(out->cols == in->cols / 2); uint16_t out_row = 0; /* Process each 2×2 window */ for (uint16_t i = 0; i < in->rows; i += 2) { uint16_t out_col = 0; for (uint16_t j = 0; j < in->cols; j += 2) { /* Extract 2×2 window */ fixed_t a = in->data[i * in->cols + j]; fixed_t b = in->data[i * in->cols + j + 1]; fixed_t c = in->data[(i + 1) * in->cols + j]; fixed_t d = in->data[(i + 1) * in->cols + j + 1]; /* Deterministic max selection */ fixed_t max_val = a; if (b > max_val) max_val = b; if (c > max_val) max_val = c; if (d > max_val) max_val = d; /* Write to output */ out->data[out_row * out->cols + out_col] = max_val; out_col++; } out_row++; } } ``` ### 7.2 Correctness Properties **Fixed Iteration Count:** ``` Outer loop: in->rows / 2 iterations Inner loop: in->cols / 2 iterations Total: (in->rows × in->cols) / 4 window comparisons ``` **No Data-Dependent Branches:** - Loop bounds fixed by dimensions - Comparison operations deterministic - No early exits **Memory Access Pattern:** - Sequential reads from input - Sequential writes to output - Cache-friendly access ## 8. Testing Requirements ### 8.1 Unit Tests **Test 1: Basic Functionality** ```c Input: 4×4 matrix with known values Expected: 2×2 output with correct max values Verify: Bit-exact output comparison ``` **Test 2: Boundary Values** ```c Test with: Fixed-point MIN, MAX, ZERO Verify: Correct handling of extreme values ``` **Test 3: Uniform Input** ```c Input: All elements same value Expected: Output all same value ``` **Test 4: Identity Patterns** ```c Input: Diagonal matrix, checkerboard pattern Verify: Expected max selection ``` ### 8.2 Integration Tests **Test 5: Conv + Pool Pipeline** ```c Conv2D → ReLU → MaxPool Verify: End-to-end correctness ``` **Test 6: Multi-Layer Network** ```c Conv → Pool → Conv → Pool Verify: Dimension reduction chain ``` ### 8.3 Performance Tests **Test 7: Timing Consistency** ```c Run 10,000 iterations Measure: Min, max, jitter Expected: <5% variance (per SRS-007) ``` ## 9. Extensions (Future) **SRS-008.8:** (Planned) Average Pooling ```c void fx_avgpool_2x2(const fx_matrix_t* in, fx_matrix_t* out); ``` **SRS-008.9:** (Planned) Configurable Pool Size ```c void fx_maxpool_generic(const fx_matrix_t* in, fx_matrix_t* out, uint16_t pool_h, uint16_t pool_w); ``` **SRS-008.10:** (Planned) Stride Configuration ```c void fx_maxpool_stride(const fx_matrix_t* in, fx_matrix_t* out, uint16_t pool_size, uint16_t stride); ``` ## 10. Commercial Value ### 10.1 CNN Completeness With Conv2D + ReLU + MaxPool, we now support: - ✅ Feature extraction (Convolution) - ✅ Non-linearity (ReLU) - ✅ Dimension reduction (MaxPool) **This is a complete CNN building block!** ### 10.2 Real-World Applications **Medical Imaging:** - Chest X-ray classification - Tumor detection in CT scans - Retinal disease screening **Automotive:** - Lane detection - Traffic sign recognition - Pedestrian detection **Aerospace:** - Satellite image analysis - Terrain classification - Target detection ### 10.3 Certification Advantage **vs. TensorFlow Lite:** - TensorFlow: Dynamic pooling kernels - Us: Fixed, analyzable implementation ✅ **vs. ONNX Runtime:** - ONNX: Generic pooling with many branches - Us: Specialized 2×2, minimal branching ✅ ## 11. References - **LeCun et al. (1998)** - "Gradient-Based Learning Applied to Document Recognition" - **Krizhevsky et al. (2012)** - "ImageNet Classification with Deep CNNs" - **DO-178C** - Software Considerations in Airborne Systems - **ISO 26262-6:2018** - Automotive functional safety ## 12. Revision History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0 | 2026-01-15 | William Murray | Initial version | --- **Document Classification:** Technical Specification **Approval Status:** Approved for Implementation **Next Review:** 2026-04-15 ======================================================================== Layer group: L3 — Oracle Boundary ======================================================================== ======================================================================== SRS-004 — Inference Containment, Oracle Contract & L4/L5 Integration ======================================================================== Spec ID: SRS-004 Title: Inference Containment, Oracle Contract & L4/L5 Integration Version: v0.3 Status: Locked Layer: L3 Determinism: D3 Date: 2026-03-26 Depends on: SRS-001, SRS-002, SRS-003, DVEC-001, AXIOMA-FRAMEWORK URL: https://axilog.io/specs/srs-004/ Changelog: https://axilog.io/specs/srs-004/changelog/ Summary: The L3 inference containment contract — LLMs are not trusted but recorded; inference is admitted, bounded, and replayable across the Oracle Boundary. **Depends on:** SRS-001 v0.3 · SRS-002 v0.3 · SRS-003 v0.3 · DVEC-001 v1.3 · AXIOMA-FRAMEWORK v0.4 --- ## 0. GOVERNING PRINCIPLE > **LLMs are not trusted. They are recorded.** > > **Inference is not execution. Inference is evidence.** If L4/L5/L6 are about enforcing determinism, L3 is about **containing non-determinism** without letting it leak. We are not trying to make inference deterministic. We are making it: - **Admissible** — captured and committed before use - **Bounded** — constrained by schema, size, and domain - **Replayable in effect** — downstream behaviour is deterministic - **Provable in context** — every decision traceable to evidence --- ## 1. PURPOSE This document defines the **Inference Containment Contract** for the Axioma framework. It specifies how inherently non-deterministic systems (LLMs, ML models, retrieval systems, external APIs) are: - admitted into Axioma - bounded in behaviour - made observable - constrained by L4 policies - anchored to L6 evidence Additionally, this document defines: - the **L5 → L4 integration contract** for policy enforcement - the **Policy DSL specification** for deterministic rule definition - the **cross-layer ordering invariants** binding L3, L4, L5, and L6 **Objective:** Non-determinism SHALL be contained, not eliminated, and SHALL NOT violate system determinism at L4/L5/L6. --- ## 2. DEFINITIONS ### 2.1 Oracle An **oracle** is any external system producing non-deterministic output. Examples: - LLMs (GPT, Claude, Llama, etc.) - ML models (classifiers, regressors, embedders) - Retrieval systems (vector databases, search indices) - External APIs (weather, market data, etc.) ### 2.2 AX:OBS:v1 (Oracle Observation) All oracle outputs MUST be admitted as `AX:OBS:v1` records. An admitted observation is: - canonicalised input - committed to the ledger - immutable once admitted ### 2.3 Inference Event An **inference event** is: ``` Input → Oracle → Output → Admission → Policy → Behaviour ``` ### 2.4 Containment Boundary The **containment boundary** is the point at which: ``` non-determinism → becomes immutable evidence ``` ### 2.5 Policy DSL The **Policy DSL** is a static definition format for safety rules, using RFC 8785 (JCS) canonical JSON, compiled into the policy registry at build time. ### 2.6 Certified Operational Envelope (COE) The **COE** is the set of all states permitted by all active policies. Defined in SRS-003. ### 2.7 Completion State The **completion state** indicates whether oracle output was fully received: | Value | Meaning | |-------|---------| | `COMPLETE` | Full output received | | `TRUNCATED` | Output exceeded size bound | | `ERROR` | Oracle invocation failed | ### 2.8 Failure Type The **failure type** classifies oracle invocation failures: | Value | Meaning | |-------|---------| | `NULL` | No failure | | `TIMEOUT` | Oracle did not respond in time | | `INVALID_OUTPUT` | Output failed schema validation | | `TRANSPORT_ERROR` | Network or protocol failure | --- ## 3. DETERMINISM MODEL ### 3.1 Determinism Class L3 SHALL operate under: **D3 — Bounded Non-Deterministic** ### 3.2 Containment Principle **SRS-004-SHALL-001** Oracle outputs SHALL NOT influence system behaviour unless: 1. admitted as `AX:OBS:v1` 2. validated by L4 policy evaluation 3. committed to L6 ledger **Verification:** inspection, replay verification, integration test ### 3.3 Deterministic Downstream Guarantee **SRS-004-SHALL-002** Once admitted, all downstream behaviour SHALL be deterministic. Given identical `AX:OBS:v1` sequences, the system SHALL produce identical: - `AX:POLICY:v1` records - `AX:TRANS:v1` records - final state **Verification:** replay verification, cross-platform identity test --- ## 4. ORACLE ADMISSION CONTRACT ### 4.1 Mandatory Admission **SRS-004-SHALL-003** All oracle outputs MUST be: ``` captured → canonicalised → committed (AX:OBS:v1) ``` before use. **Verification:** inspection, static analysis, integration test ### 4.2 No Direct Use **SRS-004-SHALL-004** Oracle outputs SHALL NOT be used directly by: - L5 (agent state machine) - L4 (policy evaluator) All oracle influence MUST flow through the admission → policy → transition pipeline. **Verification:** static analysis, inspection ### 4.3 Admission Ordering **SRS-004-SHALL-005** Oracle admission SHALL occur in strict ledger order: ``` ORDER BY ledger_seq ASC ``` No out-of-order admission is permitted. **Verification:** property test, concurrency test ### 4.4 Observation Ordering Guard **SRS-004-SHALL-038** *Closure fix v0.2 — prevents replay/injection attacks via sequence regression.* Each new `AX:OBS:v1` SHALL satisfy: ``` ledger_seq_new > ledger_seq_last ``` **Violation Behaviour:** If `ledger_seq_new ≤ ledger_seq_last`: - violation SHALL be raised - agent SHALL transition to `STOPPED` This mirrors SRS-002-SHALL-010 (Time Oracle monotonicity) but applies to all oracle observations. **Verification:** property test, fault injection test, state machine test --- ## 5. CANONICALISATION ### 5.1 Canonical Form **SRS-004-SHALL-006** All oracle outputs MUST be: - serialised deterministically - RFC 8785 (JCS) canonical **Verification:** JCS linter, hash stability test ### 5.2 Required Fields Each `AX:OBS:v1` (oracle observation) SHALL include: | Field | Type | Description | |-------|------|-------------| | `completion_state` | enum | COMPLETE, TRUNCATED, or ERROR | | `failure_type` | enum/null | NULL, TIMEOUT, INVALID_OUTPUT, or TRANSPORT_ERROR | | `input_hash` | bytes32 | SHA-256 of canonical input/prompt | | `ledger_seq` | uint64 | Ordering anchor | | `model_id` | string | Model/version identifier | | `obs_hash` | bytes32 | SHA-256 of this canonical record (§5.7) | | `oracle_id` | string | Identity of oracle | | `output` | string | Canonicalised, normalised output | | `output_size` | uint64 | Byte length of output | | `params` | object | Sampling parameters (see §5.4) | | `schema_version` | string | Always "AX:OBS:v1" | **Field Order:** Fields MUST appear in lexicographic order per RFC 8785: ``` completion_state, failure_type, input_hash, ledger_seq, model_id, obs_hash, oracle_id, output, output_size, params, schema_version ``` ### 5.3 Forbidden Fields The following SHALL NOT appear in `AX:OBS:v1`: - wall-clock timestamps (unless separately admitted as Time Oracle) - floating-point values - non-canonical structures - memory addresses - process/thread IDs **Verification:** schema test, inspection ### 5.4 Parameter Canonicalisation **SRS-004-SHALL-036** *Closure fix v0.2 — eliminates hash divergence from parameter ordering.* The `params` object SHALL: - follow RFC 8785 (JCS) canonicalisation - use fixed field set in lexicographic order: | Field | Type | Description | |-------|------|-------------| | `max_tokens` | uint32/null | Maximum output tokens | | `seed` | uint64/null | Random seed if available | | `temperature` | Q16.16/null | Sampling temperature | | `top_p` | Q16.16/null | Nucleus sampling threshold | - include `null` for absent fields (no omission) **Canonical Format:** ```json {"max_tokens":4096,"seed":null,"temperature":45875,"top_p":58982} ``` Note: `temperature` 45875 = 0.7 in Q16.16 (0.7 × 65536 ≈ 45875). Note: `top_p` 58982 = 0.9 in Q16.16 (0.9 × 65536 ≈ 58982). **Verification:** JCS linter, hash stability test, cross-platform test ### 5.5 Encoding Canonicality **SRS-004-SHALL-042** *Closure fix v0.2 — eliminates Unicode normalisation divergence.* All oracle inputs and outputs SHALL: - be UTF-8 encoded - use NFC (Canonical Decomposition, followed by Canonical Composition) normalisation form Non-conformant encoding SHALL: - be rejected prior to admission - trigger `BREACH` **Verification:** encoding test, property test ### 5.6 Output Normalisation **SRS-004-SHALL-043** *Closure fix v0.3 — eliminates line ending and control character divergence.* Oracle output SHALL be normalised before admission: - Line endings MUST be LF (`\n`, U+000A) - CRLF (`\r\n`) MUST be converted to LF - CR (`\r`) alone MUST be converted to LF - Output MUST be valid UTF-8 (per SHALL-042) - Control characters (U+0000–U+001F excluding U+000A) MUST be rejected **Rejection Behaviour:** If output contains forbidden control characters: - `completion_state = ERROR` - `failure_type = INVALID_OUTPUT` - `BREACH` triggered **Verification:** property test, encoding test, cross-platform test ### 5.7 String Escaping Canonicality **SRS-004-SHALL-045** *Closure fix v0.3 — eliminates JSON escaping divergence.* All JSON string encoding SHALL use minimal escaping: - Escape ONLY the following characters: - `"` (U+0022) → `\"` - `\` (U+005C) → `\\` - Control characters (U+0000–U+001F) → `\uXXXX` - Direct UTF-8 encoding MUST be used for all other characters - Unicode escape sequences (`\uXXXX`) MUST NOT be used where direct UTF-8 encoding is valid **Example:** ``` CORRECT: {"output":"Héllo wörld"} FORBIDDEN: {"output":"H\u00e9llo w\u00f6rld"} ``` **Verification:** JCS linter, hash stability test, cross-platform test ### 5.8 Observation Hash **SRS-004-SHALL-046** *Closure fix v0.3 — enables tamper detection and independent verification.* Each `AX:OBS:v1` record SHALL include an `obs_hash` field computed as: ``` obs_hash = SHA-256(canonical_record_without_obs_hash) ``` **Computation Procedure:** 1. Construct the complete `AX:OBS:v1` record with `obs_hash` set to the empty string `""` 2. Canonicalise per RFC 8785 (JCS) 3. Compute SHA-256 of the canonical bytes 4. Replace `obs_hash` with the computed hash (hex-encoded, lowercase) 5. Re-canonicalise (hash position is now populated) **Verification:** hash stability test, property test ### 5.9 Schema Versioning **SRS-004-SHALL-047** *Closure fix v0.3 — enables future schema evolution.* Each `AX:OBS:v1` record SHALL include: ```json "schema_version": "AX:OBS:v1" ``` This field: - MUST be present in every observation record - MUST be validated on admission - enables forward-compatible schema evolution **Verification:** schema test, inspection --- ## 6. OBSERVATION COMPLETENESS ### 6.1 Completeness Requirement **SRS-004-SHALL-035** *Closure fix v0.2 — makes AX:OBS:v1 fully self-describing.* Every `AX:OBS:v1` SHALL include: | Field | Type | Description | |-------|------|-------------| | `completion_state` | enum | COMPLETE, TRUNCATED, or ERROR | | `failure_type` | enum/null | NULL, TIMEOUT, INVALID_OUTPUT, TRANSPORT_ERROR | | `params` | object | Canonical sampling parameters (§5.4) | **Invariant:** An auditor examining any `AX:OBS:v1` record SHALL be able to determine: - Was this output complete or truncated? - Did the oracle fail, and how? - What sampling parameters were used? Without reference to external context. **Verification:** schema test, inspection ### 6.2 Maximum Observation Size **SRS-004-SHALL-048** *Closure fix v0.3 — makes size bound explicit and verifiable.* The maximum size of an `AX:OBS:v1` record SHALL be: ```c #define AX_MAX_OBS_BYTES 65536 /* 64 KiB */ ``` Any observation exceeding this limit: - SHALL be recorded with `completion_state = TRUNCATED` - SHALL trigger policy evaluation - MAY be rejected as `BREACH` depending on policy **Verification:** property test, boundary test --- ## 7. ORACLE IDENTITY ### 7.1 Identity Requirement **SRS-004-SHALL-007** Each oracle SHALL have: - globally unique identifier (`oracle_id`) - versioned model identity (`model_id`) ### 7.2 Stability Requirement **SRS-004-SHALL-008** Oracle identity MUST be: - immutable for a given execution run - identical across replay context A mismatch between recorded `model_id` and replay environment SHALL trigger a verification failure. **Verification:** inspection, replay verification --- ## 8. INPUT REPRODUCIBILITY ### 8.1 Prompt Determinism **SRS-004-SHALL-009** The input to the oracle SHALL be: - fully specified (no implicit context) - serialised deterministically - hashed prior to execution ### 8.2 Hash Binding ``` input_hash = SHA-256(canonical_input) ``` The `input_hash` field in `AX:OBS:v1` cryptographically binds the observation to the exact input that produced it. **Verification:** hash stability test, inspection ### 8.3 Input Schema Enforcement **SRS-004-SHALL-037** *Closure fix v0.2 — closes silent replay breakage from prompt divergence.* Oracle inputs SHALL: - conform to a declared input schema - be canonicalised before hashing (RFC 8785 + NFC + line normalisation) - be rejected if schema-invalid **Rationale:** Two systems constructing slightly different prompts will produce different `input_hash` values, causing replay to fail silently. Schema enforcement ensures structural consistency. **Verification:** schema test, property test, cross-platform test --- ## 9. NON-DETERMINISM BOUNDING ### 9.1 Output Bounding **SRS-004-SHALL-010** Oracle outputs SHALL be bounded by: - maximum size (bytes) — see §6.2 - schema constraints - allowed value domain ### 9.2 Schema Enforcement **SRS-004-SHALL-011** Outputs MUST conform to a declared schema: ``` schema → validated → admitted ``` Invalid outputs → `BREACH` (L4) **Verification:** schema test, property test ### 9.3 Sampling Parameter Recording **SRS-004-SHALL-012** If the oracle uses stochastic sampling (temperature, top-p, etc.), all sampling parameters SHALL be recorded in the `AX:OBS:v1` record per §5.4. **Verification:** inspection, schema test ### 9.4 Output Size Enforcement **SRS-004-SHALL-040** *Closure fix v0.2 — prevents silent truncation from undermining replay.* If output exceeds maximum size: - output SHALL NOT be truncated silently - output SHALL be recorded with: - `completion_state = TRUNCATED` - `output_size` = actual byte length before truncation - truncation SHALL trigger `BREACH` unless explicitly permitted by policy **Verification:** property test, fault injection test ### 9.5 Atomic Output Requirement **SRS-004-SHALL-041** *Closure fix v0.2 — prevents non-deterministic chunking from streaming.* Oracle outputs SHALL: - be captured only after completion - not be processed incrementally or streamed **Rationale:** Streaming outputs produce non-deterministic chunking boundaries. Only complete outputs can be canonicalised deterministically. **Verification:** inspection, integration test --- ## 10. ORACLE ISOLATION ### 10.1 Multi-Oracle Composition **SRS-004-SHALL-039** *Closure fix v0.2 — prevents hidden coupling between oracle invocations.* Each oracle invocation SHALL: - be independently admitted - have its own `AX:OBS:v1` record - not modify inputs of other oracle calls unless explicitly recorded as a new input **Chained Oracle Pattern:** If Oracle A output influences Oracle B input: ``` Oracle A → AX:OBS:v1 (A) → commit ↓ [construct input for B using A output] ↓ input_B = f(output_A) ← this derivation MUST be deterministic ↓ Oracle B → AX:OBS:v1 (B) → commit ``` The derivation function `f` MUST be: - deterministic (D1 or D2) - traceable in evidence **Verification:** inspection, integration test --- ## 11. POLICY GATING (L4 INTEGRATION) ### 11.1 Mandatory Evaluation **SRS-004-SHALL-013** All oracle outputs MUST be evaluated by L4 policies before influencing L5 behaviour. ### 11.2 Breach Behaviour **SRS-004-SHALL-014** If policy returns `BREACH`: - output SHALL be rejected - L5 SHALL transition to `ALARM` or `STOPPED` - `AX:TRANS:v1` SHALL record the breach **Verification:** integration test, state machine test ### 11.3 L5 → L4 Integration Contract **SRS-004-SHALL-015** The L5 agent step function SHALL: 1. Extract policy-relevant values from admitted `AX:OBS:v1` 2. Evaluate all policies in `policy_id` order (SRS-003-SHALL-012) 3. If ANY policy returns `BREACH`, override intended transition 4. Commit `AX:TRANS:v1` AFTER policy evaluation completes 5. Mutate state ONLY if commit succeeds **Verification:** inspection, integration test, state machine test ### 11.4 Policy Binding **SRS-004-SHALL-044** *Closure fix v0.3 — ensures explicit trace linkage between policy and observation.* Each `AX:POLICY:v1` record SHALL be unambiguously bound to exactly one `AX:OBS:v1` via `obs_ledger_seq`. **Required Field Addition to AX:POLICY:v1:** | Field | Type | Description | |-------|------|-------------| | `obs_ledger_seq` | uint64 | Ledger sequence of the evaluated observation | **Invariant:** For any `AX:POLICY:v1` record, the binding: ``` AX:POLICY:v1.obs_ledger_seq → AX:OBS:v1.ledger_seq ``` MUST be unambiguous and verifiable. **Rationale:** Without explicit binding, batched or parallelised evaluation loses trace linkage. This field ensures every policy evaluation is traceable to the exact observation it evaluated. **Verification:** property test, integration test, RTM generation --- ## 12. EXECUTION PIPELINE ### 12.1 Required Order ``` deterministic_input → oracle_execution → AX:OBS:v1 admission → AX:POLICY:v1 evaluation (0..N) → AX:TRANS:v1 behaviour (1) ``` ### 12.2 Ordering Invariant **SRS-004-SHALL-016** For each inference event: ``` OBS → POLICY → TRANS ``` MUST hold. This is the cross-layer ordering invariant from SRS-003-SHALL-022, extended to include L3. **Verification:** property test, integration test ### 12.3 Multi-Layer Defensive Guard The integrated system enforces three guards: | Layer | Guard | Mechanism | |-------|-------|-----------| | L4 | Policy Guard | Policies evaluated in `policy_id` order using Q16.16 math | | L5 | State Guard | Any `BREACH` trapped before `AX:TRANS:v1` generation | | L6 | Ledger Guard | Transition cryptographically bound to ledger sequence | --- ## 13. REPLAY MODEL ### 13.1 Replay Definition **SRS-004-SHALL-017** Replay SHALL: - NOT re-execute oracle - reuse recorded `AX:OBS:v1` ### 13.2 Replay Guarantee **SRS-004-SHALL-018** Given identical `AX:OBS:v1` sequence, system SHALL produce identical: - policy outcomes (`AX:POLICY:v1`) - behaviour transitions (`AX:TRANS:v1`) - final state **Verification:** replay verification, cross-platform identity test ### 13.3 Oracle Isolation During replay: - oracle is NOT invoked - `AX:OBS:v1` records are read from ledger - downstream processing is bit-identical --- ## 14. SIDE-EFFECT PROHIBITION ### 14.1 No Direct Effects **SRS-004-SHALL-019** Oracle outputs SHALL NOT: - perform I/O - mutate system state directly - bypass L4/L5 **Verification:** static analysis, inspection ### 14.2 Effect Containment All effects of oracle output MUST flow through: ``` AX:OBS:v1 → AX:POLICY:v1 → AX:TRANS:v1 → state mutation ``` --- ## 15. FAILURE SEMANTICS ### 15.1 Oracle Failure **SRS-004-SHALL-020** If oracle invocation fails: - SHALL produce failure observation - SHALL be admitted as `AX:OBS:v1` with: - `completion_state = ERROR` - `failure_type` = appropriate failure classification - SHALL trigger policy evaluation ### 15.2 Invalid Output **SRS-004-SHALL-021** Invalid outputs (schema violation, bounds exceeded) SHALL: - be treated as `BREACH` - force `STOPPED` if critical ### 15.3 Timeout Handling **SRS-004-SHALL-022** Oracle timeout SHALL: - produce timeout observation - be admitted as `AX:OBS:v1` with: - `completion_state = ERROR` - `failure_type = TIMEOUT` - trigger policy evaluation (typically `BREACH`) **Verification:** fault injection test, integration test --- ## 16. PURITY RESTORATION ### 16.1 Boundary Principle **SRS-004-SHALL-023** The system SHALL restore determinism at the containment boundary: ``` Non-deterministic (oracle) → admitted (AX:OBS:v1) → deterministic (L4/L5/L6) ``` ### 16.2 Invariant Statement > Once an oracle output crosses the containment boundary, the system > is indistinguishable from a purely deterministic system processing > immutable input data. **Verification:** replay verification, property test ### 16.3 The Axioma Inference Theorem > Non-deterministic systems can be used safely > IF AND ONLY IF > they are transformed into immutable, canonical, ordered evidence > before influencing deterministic computation. --- ## 17. POLICY DSL SPECIFICATION ### 17.1 DSL Philosophy The Axioma Policy DSL is not a runtime-interpreted script; it is a **Static Definition Format**. Policies are defined in JCS-canonical JSON and compiled into the `ax_policy_registry_t` at build time. This ensures: - zero dynamic allocation - O(1) lookup - bit-identical evaluation across platforms ### 17.2 DSL Schema Requirements **SRS-004-SHALL-024** The Policy DSL SHALL use RFC 8785 (JCS) for all rule definitions to ensure bit-identical parsing across platforms. **SRS-004-SHALL-025** Every policy definition MUST strictly follow the lexicographical field order: `comparison`, `enabled`, `policy_id`, `threshold`. **SRS-004-SHALL-026** Numeric thresholds MUST be defined as signed integers, which are converted to Q16.16 at compile-time. **Verification:** JCS linter, build verification, cross-platform test ### 17.3 Canonical Policy Structure A conformant DSL entry for a single safety rule: ```json { "comparison": "GT", "enabled": true, "policy_id": "POL-001-MAX-VELOCITY", "threshold": 4587520 } ``` Note: `4587520` is the Q16.16 representation of the integer `70` (70 × 65536 = 4587520). ### 17.4 Comparison Operators **SRS-004-SHALL-027** The DSL SHALL support a closed set of comparison operators: | Operator | Meaning | |----------|---------| | `GT` | Greater than | | `LT` | Less than | | `GE` | Greater than or equal | | `LE` | Less than or equal | **SRS-004-SHALL-028** Any operator outside this closed set MUST result in a `BREACH` during evaluation (Fail-Safe). **Verification:** property test, schema test ### 17.5 Static Registry Mapping | DSL Field | C Implementation | |-----------|------------------| | `policy_id` | `const char *policy_id` | | `threshold` | `q16_16_t threshold` | | `comparison` | `ax_policy_cmp_t comparison` | | `enabled` | `uint8_t enabled` | ### 17.6 DSL Evaluation Invariants When an input is processed: 1. **Retrieve:** Fetch rule from the registry 2. **Compare:** Execute pure function `ax_policy_check_breach()` using Q16.16 math 3. **Witness:** Generate `AX:POLICY:v1` record in lexicographical field order --- ## 18. FIXED-POINT ARITHMETIC COMPLIANCE ### 18.1 Determinism Fix **SRS-004-SHALL-029** Fixed-point conversion from integer SHALL use multiplication, not left-shift, to avoid C99 undefined behaviour on negative values. ```c /* CORRECT — defined for all signed integers */ #define Q16_16_FROM_INT(x) ((q16_16_t)((x) * Q16_16_ONE)) /* FORBIDDEN — undefined for negative x in C99 */ #define Q16_16_FROM_INT(x) ((q16_16_t)((x) << 16)) ``` **Rationale:** In C99, left-shifting a negative value is undefined behaviour. Multiplication by the scale factor (2^16) is defined and deterministic across all conformant compilers. **Verification:** static analysis (Wshift-negative-value), cross-platform test ### 18.2 Arithmetic Wrapper Requirement **SRS-004-SHALL-030** All policy arithmetic SHALL use DVM arithmetic wrappers: ``` ✅ dvm_add_q16(), dvm_mul_q16(), dvm_div_q16() ❌ Raw operators (+, -, *, /) on fixed-point types ``` **Verification:** static analysis (AST-level), pre-commit guardrail --- ## 19. L5 AGENT INTEGRATION ### 19.1 Agent Step Contract **SRS-004-SHALL-031** The `ax_agent_step()` function SHALL implement the following phases: **Phase A — Policy Evaluation (L4)** - Extract policy-relevant values from input - Evaluate all policies in deterministic order - Capture aggregate result (`PERMITTED` or `BREACH`) **Phase B — Pre-Commit Invariant (L5/L6)** - Determine next state (considering policy result) - Commit `AX:TRANS:v1` before mutation **Phase C — State Mutation** - Update internal health ONLY if commit succeeds - If commit fails, transition to `STOPPED` (SRS-002-SHALL-025) ### 19.2 Policy Override Behaviour **SRS-004-SHALL-032** If policy evaluation returns `BREACH`: - intended transition SHALL be overridden - next state SHALL be `ALARM` or `STOPPED` - breach SHALL be recorded in `AX:TRANS:v1` **Verification:** integration test, state machine test ### 19.3 Terminal State Guard **SRS-004-SHALL-033** If agent is in `STOPPED` state: - step function SHALL set protocol fault - SHALL NOT proceed with evaluation - SHALL return immediately (Per SRS-002-SHALL-004) **Verification:** state machine test, inspection --- ## 20. TRACEABILITY ### 20.1 Evidence Chain Each inference event SHALL produce: ``` AX:OBS:v1 (oracle output) → AX:POLICY:v1 (0..N policy evaluations) → AX:TRANS:v1 (1 state transition) ``` ### 20.2 Audit Completeness **SRS-004-SHALL-034** Every oracle output SHALL be traceable to: - the input that triggered it (`input_hash`) - the observation itself (`obs_hash`) - the policies that evaluated it (`AX:POLICY:v1` records via `obs_ledger_seq`) - the behaviour it influenced (`AX:TRANS:v1` record) **Verification:** RTM generation, inspection --- ## 21. PHASE 4 CLOSURE CRITERIA Phase 4 is complete when: ### 21.1 Containment - [x] Oracle outputs are fully contained - [x] No direct oracle influence on behaviour ### 21.2 Replay - [x] Replay does not require oracle execution - [x] Replay produces bit-identical downstream results ### 21.3 Policy Integration - [x] Policy gating enforced for all oracle outputs - [x] `BREACH` correctly overrides L5 transitions - [x] Policy → Observation binding explicit (v0.3) ### 21.4 Evidence - [x] Evidence chain complete (OBS → POLICY → TRANS) - [x] All records JCS-canonical - [x] Observation hash included (v0.3) - [x] Schema version included (v0.3) ### 21.5 DSL - [x] Policy DSL compiles to static registry - [x] Cross-platform evaluation produces identical results ### 21.6 Arithmetic - [x] No undefined behaviour in fixed-point operations - [x] All arithmetic uses DVM wrappers ### 21.7 Observation Completeness (v0.2) - [x] AX:OBS:v1 is fully self-describing - [x] Completion state and failure type recorded - [x] Sampling parameters canonicalised ### 21.8 Boundary Closure (v0.2) - [x] Input schema enforcement - [x] Output size enforcement (no silent truncation) - [x] Observation ordering guard (monotonicity) - [x] Oracle isolation (multi-oracle composition) - [x] Atomic output requirement (no streaming) - [x] Encoding canonicality (UTF-8 + NFC) ### 21.9 Canonicalisation Closure (v0.3) - [x] Output normalisation (line endings, control chars) - [x] String escaping canonicality (minimal escaping) - [x] Policy binding explicit (obs_ledger_seq) - [x] Maximum observation size defined --- ## 22. REQUIREMENT SUMMARY | ID | Requirement | Section | |----|-------------|---------| | SRS-004-SHALL-001 | Containment principle | 3.2 | | SRS-004-SHALL-002 | Deterministic downstream | 3.3 | | SRS-004-SHALL-003 | Mandatory admission | 4.1 | | SRS-004-SHALL-004 | No direct use | 4.2 | | SRS-004-SHALL-005 | Admission ordering | 4.3 | | SRS-004-SHALL-006 | Canonicalisation | 5.1 | | SRS-004-SHALL-007 | Oracle identity | 7.1 | | SRS-004-SHALL-008 | Identity stability | 7.2 | | SRS-004-SHALL-009 | Prompt determinism | 8.1 | | SRS-004-SHALL-010 | Output bounding | 9.1 | | SRS-004-SHALL-011 | Schema enforcement | 9.2 | | SRS-004-SHALL-012 | Sampling recording | 9.3 | | SRS-004-SHALL-013 | Policy gating | 11.1 | | SRS-004-SHALL-014 | Breach behaviour | 11.2 | | SRS-004-SHALL-015 | L5 → L4 integration | 11.3 | | SRS-004-SHALL-016 | Ordering invariant | 12.2 | | SRS-004-SHALL-017 | Replay definition | 13.1 | | SRS-004-SHALL-018 | Replay guarantee | 13.2 | | SRS-004-SHALL-019 | Side-effect prohibition | 14.1 | | SRS-004-SHALL-020 | Oracle failure | 15.1 | | SRS-004-SHALL-021 | Invalid output | 15.2 | | SRS-004-SHALL-022 | Timeout handling | 15.3 | | SRS-004-SHALL-023 | Purity restoration | 16.1 | | SRS-004-SHALL-024 | DSL JCS compliance | 17.2 | | SRS-004-SHALL-025 | DSL field order | 17.2 | | SRS-004-SHALL-026 | DSL integer thresholds | 17.2 | | SRS-004-SHALL-027 | Comparison operator set | 17.4 | | SRS-004-SHALL-028 | Unknown operator breach | 17.4 | | SRS-004-SHALL-029 | Fixed-point conversion | 18.1 | | SRS-004-SHALL-030 | Arithmetic wrappers | 18.2 | | SRS-004-SHALL-031 | Agent step contract | 19.1 | | SRS-004-SHALL-032 | Policy override | 19.2 | | SRS-004-SHALL-033 | Terminal state guard | 19.3 | | SRS-004-SHALL-034 | Audit completeness | 20.2 | | SRS-004-SHALL-035 | Observation completeness | 6.1 | | SRS-004-SHALL-036 | Parameter canonicalisation | 5.4 | | SRS-004-SHALL-037 | Input schema enforcement | 8.3 | | SRS-004-SHALL-038 | Observation ordering guard | 4.4 | | SRS-004-SHALL-039 | Oracle isolation | 10.1 | | SRS-004-SHALL-040 | Output size enforcement | 9.4 | | SRS-004-SHALL-041 | Atomic output requirement | 9.5 | | SRS-004-SHALL-042 | Encoding canonicality | 5.5 | | SRS-004-SHALL-043 | Output normalisation | 5.6 | | SRS-004-SHALL-044 | Policy binding | 11.4 | | SRS-004-SHALL-045 | String escaping canonicality | 5.7 | | SRS-004-SHALL-046 | Observation hash | 5.8 | | SRS-004-SHALL-047 | Schema versioning | 5.9 | | SRS-004-SHALL-048 | Maximum observation size | 6.2 | **Total: 48 SHALL requirements** --- ## 23. LAYER INTEGRATION SUMMARY | Layer | Role | SRS | |-------|------|-----| | L6 | Truth — what happened | SRS-001 | | L5 | Behaviour — what to do | SRS-002 | | L4 | Admissibility — what is allowed | SRS-003 | | L3 | Containment — what was observed | SRS-004 | **Cross-Layer Invariant:** ``` L3 (oracle) → L6 (commit) → L4 (evaluate) → L5 (behave) → L6 (commit) ``` No layer may influence another without a corresponding evidence record. --- ## 24. SYSTEM PROPERTIES (FINAL) After v0.3 closure: | Property | Status | |----------|--------| | Oracle containment | ✔ Closed | | Input determinism | ✔ Closed | | Output determinism (post-admission) | ✔ Closed | | Replay | ✔ Closed | | Multi-oracle safety | ✔ Closed | | Encoding stability | ✔ Closed | | Evidence completeness | ✔ Closed | | Canonical JSON escaping | ✔ Closed (v0.3) | | Policy → Observation binding | ✔ Closed (v0.3) | | Output normalisation | ✔ Closed (v0.3) | --- ## 25. IMPLEMENTATION REFERENCE ### 25.1 Constants (`include/axilog/limits.h`) ```c /* include/axilog/limits.h */ /** * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * * SRS-004-SHALL-048: Maximum observation size */ #ifndef AXILOG_LIMITS_H #define AXILOG_LIMITS_H /** * @brief Maximum size of an AX:OBS:v1 record in bytes. * SRS-004-SHALL-048 */ #define AX_MAX_OBS_BYTES 65536 /* 64 KiB */ #endif /* AXILOG_LIMITS_H */ ``` ### 25.2 Types Header (`include/axilog/types.h`) ```c /* include/axilog/types.h */ /** * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * MEMORY: Zero Dynamic Allocation * * SRS-004-SHALL-029: Fixed-point conversion uses multiplication. */ #ifndef AXILOG_TYPES_H #define AXILOG_TYPES_H #include typedef int32_t q16_16_t; #define Q16_16_ONE (65536) #define Q16_16_HALF (32768) /** * @brief Convert integer to Q16.16 fixed-point. * * FIX: Use multiplication instead of left-shift for signed integers. * In C99, shifting a negative value is Undefined Behavior. * Multiplication by the scale factor (2^16) is defined and deterministic. * * SRS-004-SHALL-029 */ #define Q16_16_FROM_INT(x) ((q16_16_t)((x) * Q16_16_ONE)) #endif /* AXILOG_TYPES_H */ ``` ### 25.3 Observation Types (`include/axilog/oracle.h`) ```c /* include/axilog/oracle.h */ /** * DVEC: v1.3 * DETERMINISM: D3 — Bounded Non-Deterministic (oracle layer) * MEMORY: Zero Dynamic Allocation * * SRS-004-SHALL-035: Observation completeness * SRS-004-SHALL-036: Parameter canonicalisation * SRS-004-SHALL-046: Observation hash * SRS-004-SHALL-047: Schema versioning */ #ifndef AXILOG_ORACLE_H #define AXILOG_ORACLE_H #include #include "axilog/types.h" #include "axilog/limits.h" /** * @brief Schema version string for AX:OBS:v1 records. * SRS-004-SHALL-047 */ #define AX_OBS_SCHEMA_VERSION "AX:OBS:v1" /** * @brief Completion state for oracle observations. * SRS-004-SHALL-035 */ typedef enum { AX_COMPLETION_COMPLETE = 0, AX_COMPLETION_TRUNCATED = 1, AX_COMPLETION_ERROR = 2 } ax_completion_state_t; /** * @brief Failure type for oracle observations. * SRS-004-SHALL-035 */ typedef enum { AX_FAILURE_NULL = 0, AX_FAILURE_TIMEOUT = 1, AX_FAILURE_INVALID_OUTPUT = 2, AX_FAILURE_TRANSPORT_ERROR = 3 } ax_failure_type_t; /** * @brief Canonical sampling parameters. * SRS-004-SHALL-036 * * Field order: max_tokens, seed, temperature, top_p (lexicographic) * NULL represented by sentinel values. */ typedef struct { int32_t max_tokens; /* -1 = null */ int64_t seed; /* -1 = null */ q16_16_t temperature; /* INT32_MIN = null */ q16_16_t top_p; /* INT32_MIN = null */ } ax_oracle_params_t; #define AX_PARAMS_NULL_INT32 (-1) #define AX_PARAMS_NULL_INT64 (-1LL) #define AX_PARAMS_NULL_Q16 (INT32_MIN) #endif /* AXILOG_ORACLE_H */ ``` ### 25.4 Policy Types (`include/axilog/policy.h`) ```c /* include/axilog/policy.h */ /** * DVEC: v1.3 * DETERMINISM: D2 — Constrained Deterministic * MEMORY: Zero Dynamic Allocation * * SRS-004-SHALL-044: Policy binding via obs_ledger_seq */ #ifndef AXILOG_POLICY_H #define AXILOG_POLICY_H #include #include "axilog/types.h" /** * @brief AX:POLICY:v1 record structure. * SRS-004-SHALL-044: obs_ledger_seq binds policy to observation * * Field order (lexicographic): * actual, ledger_seq, obs_ledger_seq, policy_id, result, threshold */ typedef struct { q16_16_t actual; /* Observed value */ uint64_t ledger_seq; /* Policy record sequence */ uint64_t obs_ledger_seq; /* SRS-004-SHALL-044: bound observation */ const char *policy_id; /* Policy identifier */ uint8_t result; /* 0 = PERMITTED, 1 = BREACH */ q16_16_t threshold; /* Policy threshold */ } ax_policy_record_t; #endif /* AXILOG_POLICY_H */ ``` ### 25.5 Agent Step Function (`src/agent.c`) ```c /** * @file agent.c (L5) * @brief Integration with L4 Policy Layer * * DVEC: v1.3 * DETERMINISM: D2 — Constrained Deterministic * MEMORY: Zero Dynamic Allocation * * SRS-004-SHALL-015: L5 → L4 integration contract * SRS-004-SHALL-031: Agent step contract * SRS-004-SHALL-032: Policy override behaviour * SRS-004-SHALL-033: Terminal state guard * SRS-004-SHALL-038: Observation ordering guard * SRS-004-SHALL-044: Policy binding */ #include "axilog/agent.h" #include "axilog/policy.h" void ax_agent_step( ax_agent_ctx_t *agent_ctx, ax_policy_ctx_t *policy_ctx, const ax_input_t *input, ct_fault_flags_t *faults) { ax_health_state_t next_state; ax_policy_input_t p_input; ax_policy_result_t p_result; /* SRS-004-SHALL-033: Terminal state guard */ /* SRS-002-SHALL-004: Terminal behaviour */ if (agent_ctx->health == AX_HEALTH_STOPPED) { faults->protocol = 1; return; } /* SRS-004-SHALL-038: Observation ordering guard */ if (input->ledger_seq <= agent_ctx->last_seen_seq) { faults->protocol = 1; agent_ctx->health = AX_HEALTH_STOPPED; agent_ctx->local_failed_flag = 1; return; } /* * PHASE A: Policy Evaluation (L4) * SRS-003-SHALL-011: Map input to policy value. * SRS-004-SHALL-015: L5 → L4 integration. * SRS-004-SHALL-044: Policy binding via obs_ledger_seq. */ if (input->type == AX_INPUT_LLM_OBS || input->type == AX_INPUT_TIME_OBS) { p_input.value = ax_agent_extract_value(input); p_input.ledger_seq = input->ledger_seq; p_input.obs_ledger_seq = input->ledger_seq; /* SRS-004-SHALL-044 */ /* SRS-003-SHALL-012: Evaluate all policies in deterministic order */ p_result = ax_policy_evaluate_all(policy_ctx, &p_input, faults); if (p_result == AX_POLICY_BREACH) { /* SRS-004-SHALL-032: BREACH forces safety transition */ /* SRS-003-SHALL-007: Violation propagation */ next_state = AX_HEALTH_ALARM; } else { next_state = ax_agent_determine_next(agent_ctx->health, input->type); } } else { next_state = ax_agent_determine_next(agent_ctx->health, input->type); } /* * PHASE B: Pre-Commit Invariant (L5/L6) * SRS-002-SHALL-007: Commit transition before mutation. * SRS-004-SHALL-016: Ordering invariant (OBS → POLICY → TRANS). */ ax_agent_commit_transition(agent_ctx, input, next_state, faults); /* * PHASE C: State Mutation * Only update internal health if the ledger commit succeeded. */ if (!ct_fault_any(faults)) { agent_ctx->health = next_state; agent_ctx->last_seen_seq = input->ledger_seq; } else { /* SRS-002-SHALL-025: Fail-safe priority override */ agent_ctx->health = AX_HEALTH_STOPPED; agent_ctx->local_failed_flag = 1; } } ``` --- ## 26. FINAL STATEMENT The inference layer SHALL: > Contain non-determinism such that all observable system behaviour > remains deterministic, auditable, and replayable. **Key Insight:** Most systems: - let inference directly drive behaviour - cannot replay decisions - cannot prove what the model saw Axioma provides: - Model output → becomes immutable fact → then evaluated → then permitted to influence behaviour **System Property:** > The system cannot behave differently without producing different evidence. **The Axioma Inference Theorem:** > Non-deterministic systems can be used safely > IF AND ONLY IF > they are transformed into immutable, canonical, ordered evidence > before influencing deterministic computation. --- ## 27. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 0.1 | 2026-03-26 | William Murray | Initial draft — Inference Containment (34 SHALL), L5→L4 integration, Policy DSL, fixed-point arithmetic fix | | 0.2 | 2026-03-26 | William Murray | Audit closure — added SHALL-035 through SHALL-042. Total: 42 SHALL. | | 0.3 | 2026-03-26 | William Murray | Final closure — added SHALL-043 (output normalisation), SHALL-044 (policy binding), SHALL-045 (string escaping), SHALL-046 (observation hash), SHALL-047 (schema versioning), SHALL-048 (max observation size). Total: 48 SHALL. Status: Audit-Frozen FINAL. | --- ## 28. DOCUMENT APPROVAL | Role | Name | Date | Signature | |------|------|------|-----------| | Author | William Murray | 2026-03-26 | | | Reviewer | | | | | Approver | | | | --- ## Appendix A — Audit Record ### v0.1 → v0.2 | Finding | Resolution | |---------|------------| | AX:OBS:v1 under-specified (completion state, failure type) | §6 + SHALL-035 | | Canonical structure for params undefined | §5.4 + SHALL-036 | | No explicit input schema for oracle inputs | §8.3 + SHALL-037 | | Ledger sequence monotonicity not enforced at L3 | §4.4 + SHALL-038 | | Multi-oracle composition undefined | §10 + SHALL-039 | | Output size bound not enforced deterministically | §9.4 + SHALL-040 | | No explicit "no streaming" rule | §9.5 + SHALL-041 | | Missing UTF-8 + NFC encoding requirement | §5.5 + SHALL-042 | ### v0.2 → v0.3 | Finding | Resolution | |---------|------------| | Output encoding domain ambiguous (line endings, control chars) | §5.6 + SHALL-043 | | Policy → Observation binding implicit (no explicit trace) | §11.4 + SHALL-044 | | JSON string escaping not canonicalised | §5.7 + SHALL-045 | | No observation hash for tamper detection | §5.8 + SHALL-046 | | No schema versioning for forward compatibility | §5.9 + SHALL-047 | | Maximum observation size not explicit | §6.2 + SHALL-048 | --- ## Appendix B — Canonical AX:OBS:v1 Example ```json { "completion_state": "COMPLETE", "failure_type": null, "input_hash": "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd", "ledger_seq": 42, "model_id": "gpt-4-turbo-2024-04-09", "obs_hash": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210", "oracle_id": "azure-openai-prod-westeurope", "output": "The answer is 42.\n", "output_size": 18, "params": { "max_tokens": 4096, "seed": null, "temperature": 45875, "top_p": 58982 }, "schema_version": "AX:OBS:v1" } ``` **Notes:** - Fields in lexicographic order per RFC 8785 - Line ending normalised to LF - Direct UTF-8 encoding (no unnecessary escapes) - Q16.16 values for temperature (0.7) and top_p (0.9) - obs_hash computed over record with empty obs_hash field --- *SRS-004 v0.3 — Audit-Frozen FINAL* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== Layer group: L4 — Policy ======================================================================== ======================================================================== SRS-003 — Policy Evaluation & Operational Envelope Specification ======================================================================== Spec ID: SRS-003 Title: Policy Evaluation & Operational Envelope Specification Version: v0.3 Status: Locked Layer: L4 Determinism: D2 Date: 2026-03-26 Depends on: SRS-001, SRS-002, DVEC-001 URL: https://axilog.io/specs/srs-003/ Changelog: https://axilog.io/specs/srs-003/changelog/ Summary: The L4 policy contract — every policy decision SHALL be deterministic, replayable, and anchored to cryptographic evidence within the operational envelope. **Depends on:** SRS-001 v0.3 · SRS-002 v0.3 · DVEC-001 v1.3 --- ## 1. PURPOSE This document defines the **Policy Evaluation Contract** for the Axioma framework. It specifies: - deterministic policy evaluation - operational safety envelope enforcement - policy evidence generation - integration with L5 agent behaviour **Objective**: Every policy decision SHALL be deterministic, replayable, and anchored to cryptographic evidence. **Transition**: L5 defines "how to behave" → L4 defines "what is allowed". --- ## 2. DEFINITIONS ### 2.1 Policy A **policy** is a deterministic constraint evaluated against admitted system inputs. ### 2.2 Policy Evaluation A **policy evaluation** is a pure function: ``` P : Input → (Result × Evidence) ``` ### 2.3 AX:POLICY:v1 A canonical record representing a single policy evaluation. ### 2.4 Certified Operational Envelope (COE) The **COE** is the set of all states permitted by all active policies. ### 2.5 Policy Set The **policy set** is the finite, closed set of all policies evaluated by the system. ### 2.6 Policy Result | Value | Meaning | |-------|---------| | `PERMITTED` | Input is within operational envelope | | `BREACH` | Input violates policy constraint | --- ## 3. DETERMINISM MODEL ### 3.1 Determinism Class The policy layer SHALL operate under: **D2 — Constrained Deterministic** ### 3.2 Determinism Definition **SRS-003-SHALL-001** For identical: - admitted inputs (`AX:OBS:v1`) - policy set the system SHALL produce: - identical `AX:POLICY:v1` records - identical evaluation results ### 3.3 Oracle Boundary **SRS-003-SHALL-002** Policy evaluation MUST operate only on: - admitted `AX:OBS:v1` inputs - static configuration Direct system access is **FORBIDDEN**. --- ## 4. POLICY INPUT MODEL ### 4.1 Input Binding **SRS-003-SHALL-011** All policy evaluations SHALL operate on data derived from admitted `AX:OBS:v1`. Extraction MUST: - be deterministic - be schema-defined - produce identical values across platforms ### 4.2 Input Integrity Policy evaluation MUST NOT: - mutate input payload - access non-admitted state --- ## 5. POLICY SET CLOSURE ### 5.1 Closed Set Requirement **SRS-003-SHALL-013** The policy set SHALL be: - finite - explicitly defined at compile time - identical across all builds ### 5.2 No Dynamic Policies Runtime policy creation is **FORBIDDEN**. --- ## 5A. POLICY IDENTITY ### 5A.1 Policy Identity Stability **SRS-003-SHALL-019** `policy_id` SHALL: - be compile-time constant - be globally unique - be identical across all builds - use ASCII encoding only (no locale dependence) --- ## 6. POLICY EVALUATION ORDERING ### 6.1 Global Ordering **SRS-003-SHALL-012** Policy evaluations SHALL occur in deterministic order: ``` ORDER BY (ledger_seq ASC, policy_id ASC) ``` ### 6.2 Ordering Source - `ledger_seq` is the primary ordering axis - `policy_id` resolves intra-input ordering --- ## 7. POLICY EVALUATION CONTRACT ### 7.1 Evaluation Function **SRS-003-SHALL-003** Each policy SHALL be a pure function: ``` P(input) → (result, evidence) ``` ### 7.2 Fixed-Point Arithmetic **SRS-003-SHALL-002** (extended) All numeric evaluation MUST use: **Q16.16 fixed-point arithmetic** Floating-point operations are **FORBIDDEN**. Example: ```c if (velocity > MAX_SAFE_Q16) { /* BREACH */ } ``` A policy breach detected on an ARM64 edge device will be **exactly reproducible** on an x86_64 auditor workstation. ### 7.3 Policy Aggregation **SRS-003-SHALL-014** If **ANY** policy returns `BREACH`: - overall result SHALL be `BREACH` `PERMITTED` is valid only if **ALL** policies return `PERMITTED`. --- ## 7A. POLICY TOTALITY ### 7A.1 Totality Requirement **SRS-003-SHALL-020** Policy evaluation SHALL be total. For any admitted input: - evaluation MUST produce a result - no undefined evaluation paths are permitted If evaluation cannot be completed: - result SHALL be `BREACH` - agent SHALL transition to `STOPPED` --- ## 8. AX:POLICY:v1 RECORD ### 8.1 Canonical Requirement **SRS-003-SHALL-004** All records MUST be: - RFC 8785 (JCS) canonicalized - bit-identical for identical inputs ### 8.2 Required Fields **SRS-003-SHALL-005** Each record SHALL contain: | Field | Type | Description | |-------|------|-------------| | `actual` | Q16.16 | Observed value | | `ledger_seq` | uint64 | Input ordering source | | `policy_id` | string | Policy identifier | | `result` | enum | `PERMITTED` \| `BREACH` | | `threshold` | Q16.16 | Policy constraint | ### 8.3 Field Order **SRS-003-SHALL-018** Fields MUST appear in lexicographic order: ``` actual, ledger_seq, policy_id, result, threshold ``` ### 8.4 Canonical Format ```json {"actual":,"ledger_seq":,"policy_id":"","result":"","threshold":} ``` ### 8.5 Forbidden Fields The following SHALL NOT appear: - timestamps (unless admitted) - floating-point values - random values - memory addresses - process/thread IDs --- ## 8A. EVIDENCE MULTIPLICITY ### 8A.1 One Record Per Policy **SRS-003-SHALL-021** Each policy SHALL produce exactly one `AX:POLICY:v1` record. Aggregation SHALL NOT collapse multiple policy evaluations into a single record. ### 8A.2 Evidence Count For N policies evaluated against one input: - exactly N `AX:POLICY:v1` records SHALL be produced - each record SHALL be independently committed --- ## 9. PRE-COMMIT INVARIANT ### 9.1 Policy Commitment Requirement **SRS-003-SHALL-015** Each policy evaluation SHALL: ``` evaluate → construct AX:POLICY:v1 → commit → influence L5 ``` ### 9.2 No Silent Decisions No policy result may influence behaviour without a committed record. --- ## 9A. CROSS-LAYER ORDERING ### 9A.1 Cross-Layer Ordering Invariant **SRS-003-SHALL-022** For each input, the commit ordering SHALL be: ``` AX:OBS:v1 → AX:POLICY:v1 (0..N) → AX:TRANS:v1 (1) ``` All `AX:POLICY:v1` records MUST be committed **BEFORE** the corresponding `AX:TRANS:v1` record. ### 9A.2 Ordering Invariance This ordering SHALL be invariant across all platforms. Interleaving of policy and transition commits is **FORBIDDEN**. --- ## 10. FAILURE SEMANTICS ### 10.1 Evaluation Failure **SRS-003-SHALL-016** If evaluation fails: - result SHALL be treated as `BREACH` - agent SHALL transition to `STOPPED` ### 10.2 Commit Failure If `AX:POLICY:v1` cannot be committed: - agent SHALL transition to `STOPPED` - failure SHALL be treated as critical --- ## 11. PURITY CONSTRAINT ### 11.1 No Hidden State **SRS-003-SHALL-017** Policy evaluation SHALL be a pure function of: - admitted inputs - static configuration ### 11.2 Forbidden Dependencies Policies MUST NOT depend on: - global mutable state - system clock - randomness - IO --- ## 12. BOUNDEDNESS ### 12.1 Execution Bound **SRS-003-SHALL-010** Policy evaluation SHALL execute in: ``` O(N), where N = number of policies ``` ### 12.2 Constraint N MUST be: - fixed - bounded - compile-time constant ### 12.3 Memory **SRS-003-SHALL-009** Policy evaluation SHALL perform **zero dynamic memory allocation**. --- ## 13. L5 INTEGRATION CONTRACT ### 13.1 Enforcement Rule **SRS-003-SHALL-006** No L5 transition SHALL complete if: ``` policy_result == BREACH ``` ### 13.2 Violation Propagation **SRS-003-SHALL-007** A `BREACH` SHALL: - force L5 transition to `ALARM` or `STOPPED` - be recorded in L5 transition evidence --- ## 14. REPLAY EQUIVALENCE ### 14.1 Replay Requirement **SRS-003-SHALL-003** (extended) Given identical: - inputs - policy set the system SHALL reproduce identical: - `AX:POLICY:v1` records - policy outcomes --- ## 15. TRACEABILITY ### 15.1 Requirement Mapping **SRS-003-SHALL-008** Each policy evaluation SHALL be traceable to: - an SRS requirement - an `AX:POLICY:v1` record --- ## 16. PHASE 3 CLOSURE CRITERIA Phase 3 is complete when: ### 16.1 Determinism - identical inputs → identical outputs ### 16.2 Ordering - evaluation order deterministic ### 16.3 Closure - policy set is finite and fixed ### 16.4 Evidence - all decisions produce canonical records ### 16.5 Enforcement - L5 transitions blocked on `BREACH` ### 16.6 Replay - policy outcomes reproducible --- ## 17. REQUIREMENT SUMMARY | ID | Requirement | Section | |----|-------------|---------| | SRS-003-SHALL-001 | Determinism definition | 3.2 | | SRS-003-SHALL-002 | Oracle boundary / fixed-point | 3.3, 7.2 | | SRS-003-SHALL-003 | Deterministic evaluation | 7.1, 14.1 | | SRS-003-SHALL-004 | Canonical record | 8.1 | | SRS-003-SHALL-005 | Required fields | 8.2 | | SRS-003-SHALL-006 | L5 enforcement | 13.1 | | SRS-003-SHALL-007 | Violation propagation | 13.2 | | SRS-003-SHALL-008 | Traceability | 15.1 | | SRS-003-SHALL-009 | Zero allocation | 12.3 | | SRS-003-SHALL-010 | Bounded execution | 12.1 | | SRS-003-SHALL-011 | Input binding | 4.1 | | SRS-003-SHALL-012 | Ordering | 6.1 | | SRS-003-SHALL-013 | Policy set closure | 5.1 | | SRS-003-SHALL-014 | Aggregation rule | 7.3 | | SRS-003-SHALL-015 | Pre-commit invariant | 9.1 | | SRS-003-SHALL-016 | Failure semantics | 10.1 | | SRS-003-SHALL-017 | Purity constraint | 11.1 | | SRS-003-SHALL-018 | Canonical structure | 8.3 | | SRS-003-SHALL-019 | Policy identity stability | 5A.1 | | SRS-003-SHALL-020 | Policy totality | 7A.1 | | SRS-003-SHALL-021 | One record per policy | 8A.1 | | SRS-003-SHALL-022 | Cross-layer ordering | 9A.1 | **Total: 22 SHALL requirements** --- ## 18. FINAL STATEMENT The Axioma policy layer SHALL: > Define a deterministic, bounded, and fully observable operational envelope > whose decisions are cryptographically anchored and replayable across platforms. **System Property**: > No behaviour can occur without both evidence (L6) and permission (L4). **Layer Integration**: | Layer | Role | |-------|------| | L6 | Truth — what happened | | L5 | Behaviour — what to do | | L4 | Admissibility — what is allowed | --- ## 19. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 0.1-scaffold | 2026-03-26 | William Murray | Initial scaffold | | 0.2 | 2026-03-26 | William Murray | Full specification, 18 SHALL requirements | | 0.3 | 2026-03-26 | William Murray | Added SHALL-019 (policy identity), SHALL-020 (totality), SHALL-021 (evidence multiplicity), SHALL-022 (cross-layer ordering). Audit-frozen FINAL. | --- ## 20. DOCUMENT APPROVAL | Role | Name | Date | Signature | |------|------|------|-----------| | Author | William Murray | 2026-03-26 | | | Reviewer | | | | | Approver | | | | ======================================================================== Layer group: L5 — Agent Surface ======================================================================== ======================================================================== SRS-002 — Agent Totality & Health FSM Specification ======================================================================== Spec ID: SRS-002 Title: Agent Totality & Health FSM Specification Version: v0.3 Status: Locked Layer: L5 Determinism: D2 Date: 2026-03-26 Depends on: SRS-001, DVEC-001, AXIOMA-FRAMEWORK URL: https://axilog.io/specs/srs-002/ Changelog: https://axilog.io/specs/srs-002/changelog/ Summary: The L5 behavioural contract — every agent SHALL be a total, bounded, deterministic function over admitted inputs and state, with a fail-closed health FSM. **Depends on:** SRS-001 v0.3 · DVEC-001 v1.3 · AXIOMA-FRAMEWORK v0.4 --- ## 1. PURPOSE This document defines the **Agent Totality Contract** for the Axioma framework. It specifies the formal requirements for: - deterministic agent behaviour - health state management - oracle input admission - replay equivalence - fail-closed execution **Objective**: Every agent is a total, bounded, deterministic function over admitted inputs and internal state. --- ## 2. DEFINITIONS ### 2.1 Agent An **agent** is a deterministic state machine executing on top of the Axioma audit substrate (L6). ### 2.2 Admitted Observation (AX:OBS:v1) An **admitted observation** is: - canonicalised input - committed to the ledger - immutable once admitted ### 2.3 Transition Record (AX:TRANS:v1) A **transition record** is: - the canonical representation of a state transition - committed prior to state mutation ### 2.4 Health State The **health state** represents the operational status of the agent. ### 2.5 Terminal State A **terminal state** is a state from which no further transitions are permitted without external reset. ### 2.6 No-Op Transition A **No-Op transition** is a deterministic transition that preserves the current state while maintaining ledger continuity. ### 2.7 Fault Accumulator A **fault accumulator** is a deterministic counter tracking fault events for threshold-based state transitions. ### 2.8 Layer Terminology | Term | Layer | Meaning | |------|-------|---------| | `FAILED` | L6 (Ledger) | Substrate cannot accept commits | | `STOPPED` | L5 (Agent) | Agent terminal state | **NOTE**: `L6 FAILED ≠ L5 STOPPED`, BUT: `L6 FAILED ⇒ L5 STOPPED` (mandatory propagation). --- ## 3. DETERMINISM MODEL ### 3.1 Determinism Class The agent SHALL operate under: **D2 — Constrained Deterministic** ### 3.2 Determinism Definition **SRS-002-SHALL-001** For identical: - initial state - ordered sequence of admitted `AX:OBS:v1` inputs the agent SHALL produce: - identical sequence of `AX:TRANS:v1` records - identical resulting state ### 3.3 Oracle Boundary **SRS-002-SHALL-002** All external inputs MUST be admitted as `AX:OBS:v1` before use. Direct system calls (time, IO, randomness) are **FORBIDDEN**. --- ## 4. HEALTH STATE MACHINE ### 4.1 State Set The agent SHALL define the following states: ``` UNINIT → INIT → ENABLED → ALARM → DEGRADED → STOPPED ``` ### 4.2 Terminal State **SRS-002-SHALL-003** `AX_HEALTH_STOPPED` SHALL be a terminal state. ### 4.3 Terminal Behaviour **SRS-002-SHALL-004** If `state == STOPPED`: - no state mutation SHALL occur - all transition attempts SHALL be rejected - a violation SHALL be raised ### 4.4 Runtime Fault Coupling **SRS-002-SHALL-005** If the underlying ledger enters `FAILED`: - agent health MUST transition to `STOPPED` --- ## 4A. INITIAL STATE BINDING ### 4A.1 Genesis Binding Requirement **SRS-002-SHALL-026** An agent SHALL only transition: ``` UNINIT → INIT ``` if: - ledger context is initialised - `genesis_hash` matches system golden reference ### 4A.2 Violation Behaviour If mismatch occurs: - violation SHALL be raised - agent SHALL transition to `STOPPED` --- ## 5. TRANSITION PRE-COMMIT INVARIANT ### 5.1 Pre-Commit Requirement **SRS-002-SHALL-006** No state transition SHALL occur without a preceding `AX:TRANS:v1` commitment. ### 5.2 Ordering Constraint **SRS-002-SHALL-007** The transition sequence SHALL be: ``` determine transition → commit AX:TRANS:v1 → mutate in-memory state ``` ### 5.3 Commit Failure Behaviour **SRS-002-SHALL-008** If `AX:TRANS:v1` commitment fails: - state mutation SHALL NOT occur - agent SHALL transition to `STOPPED` --- ## 5A. SUBSTRATE FAILURE HANDLING ### 5A.1 Ledger Failure Override **SRS-002-SHALL-025** If the L6 substrate returns: - `ledger_fail` - `io_error` the agent SHALL: - immediately transition to `STOPPED` - set local terminal state - prohibit further mutation ### 5A.2 Fail-Safe Priority Rule **Safety SHALL take precedence over audit continuity.** ### 5A.3 Invariant Even if `AX:TRANS:v1` cannot be committed: - agent MUST still enter `STOPPED` --- ## 6. TIME ORACLE MONOTONICITY ### 6.1 Admission Requirement **SRS-002-SHALL-009** All timestamps MUST be admitted as `AX:OBS:v1`. ### 6.2 Monotonicity Constraint **SRS-002-SHALL-010** For timestamps: ``` T_new > T_last MUST hold ``` ### 6.3 Violation Behaviour **SRS-002-SHALL-011** If: ``` T_new ≤ T_last ``` then: - violation SHALL be raised - agent SHALL transition to `STOPPED` --- ## 7. INPUT ALPHABET ### 7.1 Admitted Input Classes The agent SHALL support the following input classes: | Input Class | Description | |-------------|-------------| | `AX_INPUT_TIME_OBS` | Admitted timestamp observation | | `AX_INPUT_LLM_OBS` | Admitted LLM response observation | | `AX_INPUT_POLICY_TRIGGER` | Policy evaluation trigger | | `AX_INPUT_FAULT_SIGNAL` | Fault condition signal | | `AX_INPUT_RESET_REQUEST` | Reset/recovery request | ### 7.2 Closure Requirement **SRS-002-SHALL-012** The input set SHALL be closed. No undeclared input types are permitted. ### 7.3 Input Ordering Guarantee **SRS-002-SHALL-028** The agent SHALL process inputs strictly in ledger order: ``` ORDER BY ledger_sequence ASC ``` No alternative ordering source is permitted. --- ## 7A. UNKNOWN INPUT HANDLING ### 7A.1 Semantic No-Op Transition **SRS-002-SHALL-023** For any admitted input that is: - syntactically valid (`AX:OBS:v1` committed) - semantically irrelevant to the current state the agent SHALL: - produce a deterministic No-Op transition - preserve current state - commit an `AX:TRANS:v1` record ### 7A.2 No-Op Invariant The No-Op transition SHALL satisfy: ``` State(t+1) = State(t) ``` while still producing: - `AX:TRANS:v1` (No-Op witness) --- ## 8. TRANSITION TOTALITY ### 8.1 Total Function Requirement **SRS-002-SHALL-013** The transition function SHALL be total: ``` F : (State × InputClass) → (NewState × Evidence) ``` ### 8.2 Completeness **SRS-002-SHALL-014** Every `(state, input_class)` pair MUST map to exactly one outcome. ### 8.3 No Hidden States **SRS-002-SHALL-015** No undeclared states SHALL exist. ### 8.4 Deterministic Outcome **SRS-002-SHALL-016** Given identical inputs and state, the transition result SHALL be identical. --- ## 8A. FAULT ACCUMULATION ### 8A.1 Fault Budget Requirement **SRS-002-SHALL-024** The agent SHALL maintain a deterministic fault accumulator. ### 8A.2 Budget Constraints The accumulator SHALL be: - fixed-width integer (uint32_t) - zero-initialised - deterministic across platforms Thresholds SHALL be: - hardcoded constants - identical across all builds ### 8A.3 Transition Rules Fault accumulation SHALL govern transitions: | Condition | Result | |-----------|--------| | `fault_count < threshold_alarm` | Remain `ENABLED` | | `fault_count >= threshold_alarm` | Transition to `ALARM` | | `fault_count >= threshold_stop` | Transition to `STOPPED` | ### 8A.4 Determinism Requirement Fault accumulation SHALL be: - order-dependent - deterministic under identical input sequence ### 8A.5 Fault Accumulator Reset **SRS-002-SHALL-029** The fault accumulator SHALL: - reset to zero on transition to `INIT` - remain unchanged across `ENABLED` / `ALARM` / `DEGRADED` - never decrease except via reset to `INIT` --- ## 9. TRANSITION TABLE (CLOSED SET) ### 9.1 Complete Transition Matrix | Current State | Input Class | New State | Evidence | |---------------|-------------|-----------|----------| | `UNINIT` | `RESET_REQ` | `INIT` | Genesis binding witness | | `UNINIT` | other | `STOPPED` | Invalid init violation | | `INIT` | `TIME_OBS` | `ENABLED` | Temporal sync witness | | `INIT` | `FAULT_SIGNAL` | `STOPPED` | Init failure witness | | `INIT` | other | `INIT` | No-Op | | `ENABLED` | `LLM_OBS` | `ENABLED` | Decision/action witness | | `ENABLED` | `FAULT_SIGNAL` | `ALARM` | Fault threshold witness | | `ENABLED` | `TIME_OBS` | `ENABLED` | Time progression witness | | `ENABLED` | `POLICY_TRIGGER` | `ENABLED` | Policy evaluation witness | | `ENABLED` | other | `ENABLED` | No-Op | | `ALARM` | `POLICY_TRIGGER` | `DEGRADED` | Mitigation witness | | `ALARM` | `FAULT_SIGNAL` | `STOPPED` | Critical failure witness | | `ALARM` | other | `ALARM` | No-Op | | `DEGRADED` | `RESET_REQ` | `INIT` | Recovery witness | | `DEGRADED` | `FAULT_SIGNAL` | `STOPPED` | Escalation witness | | `DEGRADED` | other | `DEGRADED` | No-Op | | `STOPPED` | ANY | `STOPPED` | Terminality violation witness | ### 9.2 Closure Guarantee **SRS-002-SHALL-017** Any transition not defined above SHALL: - raise violation - transition to `STOPPED` The transition table SHALL be: - complete - closed - deterministic No undefined `(state, input)` pairs SHALL exist. --- ## 10. BOUNDEDNESS ### 10.1 Execution Bound **SRS-002-SHALL-018** Each transition SHALL: - process exactly one input - execute in constant or bounded time - perform no recursion - perform no unbounded iteration - not allocate unbounded memory --- ## 11. REPLAY EQUIVALENCE ### 11.1 Replay Requirement **SRS-002-SHALL-019** Given: - identical initial state - identical ordered `AX:OBS:v1` sequence the system SHALL reproduce: - identical `AX:TRANS:v1` sequence ### 11.2 Scope Replay equivalence SHALL apply to: - state transitions - health state progression - violation behaviour --- ## 12. TRANSITION EVIDENCE ### 12.1 Evidence Canonicality **SRS-002-SHALL-027** Every `AX:TRANS:v1` record SHALL: - be canonicalised per RFC 8785 (JCS) - be bit-identical for identical transitions ### 12.2 Required Evidence Fields Each `AX:TRANS:v1` SHALL include: | Field | Type | Description | |-------|------|-------------| | `prev_state` | enum | State before transition | | `input_class` | enum | Input that triggered transition | | `next_state` | enum | State after transition | | `violation` | enum/null | Violation type if any | | `fault_count` | uint32 | Fault accumulator value | | `ledger_seq` | uint64 | Ledger sequence number | ### 12.3 Forbidden Fields The following SHALL NOT appear in `AX:TRANS:v1`: - wall-clock timestamps (unless admitted as `AX:OBS:v1`) - random values - process IDs or thread IDs - memory addresses --- ## 13. VIOLATION HANDLING ### 13.1 Violation Types The system SHALL define: | Violation | Description | |-----------|-------------| | `TIME_ROLLBACK` | Timestamp monotonicity violation | | `POLICY_BREACH` | Policy constraint violation | | `FAULT_BUDGET_EXCEEDED` | Fault threshold exceeded | | `PROTOCOL_VIOLATION` | State machine protocol error | | `GENESIS_MISMATCH` | Ledger binding failure | | `COMMIT_FAILURE` | L6 commit failed | ### 13.2 Violation Behaviour **SRS-002-SHALL-020** On violation: **If commit succeeds:** - violation SHALL be recorded in `AX:TRANS:v1` - state SHALL transition deterministically - if critical → `STOPPED` **If commit fails:** - agent SHALL still transition deterministically to `STOPPED` - violation SHALL be marked in local state (non-persistent) - `local_violation_flag` SHALL be set --- ## 14. RESET SEMANTICS ### 14.1 Reset Requirement **SRS-002-SHALL-021** Recovery from `STOPPED` SHALL require: - explicit reset input - new `AX:OBS:v1` admission ### 14.2 Reset Behaviour Reset SHALL: - reinitialise state - preserve ledger history - reset fault accumulator to zero --- ## 15. TRACEABILITY ### 15.1 Requirement Mapping **SRS-002-SHALL-022** Every transition SHALL be traceable to: - an SRS requirement - an `AX:TRANS:v1` record --- ## 16. PHASE 2 CLOSURE CRITERIA Phase 2 is complete when: ### 16.1 Replay Verification - replay produces identical transitions ### 16.2 Monotonicity Enforcement - time rollback triggers `STOPPED` ### 16.3 Totality Proof - all `(state, input)` pairs covered ### 16.4 Traceability - all transitions linked to SRS ### 16.5 Fault Budget - threshold transitions are deterministic ### 16.6 Genesis Binding - agent lifecycle bound to ledger identity ### 16.7 Evidence Canonicality - all `AX:TRANS:v1` records bit-identical for identical transitions --- ## 17. REQUIREMENT SUMMARY | ID | Requirement | Section | |----|-------------|---------| | SRS-002-SHALL-001 | Determinism definition | 3.2 | | SRS-002-SHALL-002 | Oracle boundary | 3.3 | | SRS-002-SHALL-003 | Terminal state | 4.2 | | SRS-002-SHALL-004 | Terminal behaviour | 4.3 | | SRS-002-SHALL-005 | Runtime fault coupling | 4.4 | | SRS-002-SHALL-006 | Pre-commit requirement | 5.1 | | SRS-002-SHALL-007 | Ordering constraint | 5.2 | | SRS-002-SHALL-008 | Commit failure behaviour | 5.3 | | SRS-002-SHALL-009 | Timestamp admission | 6.1 | | SRS-002-SHALL-010 | Monotonicity constraint | 6.2 | | SRS-002-SHALL-011 | Monotonicity violation | 6.3 | | SRS-002-SHALL-012 | Input closure | 7.2 | | SRS-002-SHALL-013 | Total function | 8.1 | | SRS-002-SHALL-014 | Completeness | 8.2 | | SRS-002-SHALL-015 | No hidden states | 8.3 | | SRS-002-SHALL-016 | Deterministic outcome | 8.4 | | SRS-002-SHALL-017 | Illegal transitions | 9.2 | | SRS-002-SHALL-018 | Execution bound | 10.1 | | SRS-002-SHALL-019 | Replay requirement | 11.1 | | SRS-002-SHALL-020 | Violation behaviour | 13.2 | | SRS-002-SHALL-021 | Reset requirement | 14.1 | | SRS-002-SHALL-022 | Traceability | 15.1 | | SRS-002-SHALL-023 | No-Op transition | 7A.1 | | SRS-002-SHALL-024 | Fault accumulator | 8A.1 | | SRS-002-SHALL-025 | Substrate failure | 5A.1 | | SRS-002-SHALL-026 | Genesis binding | 4A.1 | | SRS-002-SHALL-027 | Evidence canonicality | 12.1 | | SRS-002-SHALL-028 | Input ordering | 7.3 | | SRS-002-SHALL-029 | Fault accumulator reset | 8A.5 | **Total: 29 SHALL requirements** --- ## 18. FINAL STATEMENT The Axioma agent SHALL: > Operate as a total, bounded, deterministic state machine whose behaviour is > fully defined, replayable, and anchored to cryptographic evidence. **System Property**: > The agent cannot behave differently without producing different evidence. --- ## 19. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 0.1-draft | 2026-03-26 | William Murray | Initial draft | | 0.2 | 2026-03-26 | William Murray | Added SHALL-023 to SHALL-026, complete transition matrix | | 0.3 | 2026-03-26 | William Murray | Added SHALL-027 (evidence canonicality), SHALL-028 (input ordering), SHALL-029 (fault reset), tightened violation semantics, collapsed boundedness section, added layer terminology | --- ## 20. DOCUMENT APPROVAL | Role | Name | Date | Signature | |------|------|------|-----------| | Author | William Murray | 2026-03-26 | | | Reviewer | | | | | Approver | | | | ======================================================================== Layer group: L6 — Audit Ledger ======================================================================== ======================================================================== SRS-001 — Axilog Software Requirements Specification ======================================================================== Spec ID: SRS-001 Title: Axilog Software Requirements Specification Version: v0.3 Status: Production Gold Layer: L6 Determinism: D1 Date: 2026-03-15 Supersedes: SRS-001 v0.2 Depends on: DVEC-001, DVM-SPEC-001 URL: https://axilog.io/specs/srs-001/ Changelog: https://axilog.io/specs/srs-001/changelog/ Summary: The Axilog substrate-core SRS — authoritative SHALL statements for deterministic execution, evidence commitment, ledger behaviour, and the oracle boundary. **Scope:** Axilog substrate core **Alignment:** DVEC-001 v1.3 · DVM-SPEC-001 v1.0-rc1 · Axioma v0.4 --- ## Revision History | Version | Status | Notes | |---------|--------|-------| | v0.1 | Superseded | Initial draft — core substrate requirements | | v0.2 | Superseded | Genesis requirement, physical I/O fault handling, input domain validation, toolchain provenance | | v0.3 | Final | Static stack depth bound (SRS-010-SHALL-006), configuration evidence binding (SRS-001-SHALL-007) | --- ## 1. Purpose This document defines the normative software requirements for Axilog. It is the authoritative source of SHALL statements for: - Deterministic execution substrate behaviour - Evidence commitment behaviour - Ledger behaviour - Fault propagation behaviour - Oracle boundary handling - Cross-platform identity verification - Initialization determinism - Physical storage fault handling - Input domain validation - Toolchain provenance Every public Axilog function MUST trace to at least one requirement in this document. --- ## 2. Conformance A software component is conformant only if: - It implements all applicable SHALL statements - Each SHALL has a declared verification method - All verification methods pass - All associated DVEC-001 v1.3 constraints are satisfied Non-conformance is a system integrity failure. --- ## 3. Requirement Format Each requirement is identified as: ``` SRS-SECTION-SHALL-NNN ``` Example: `SRS-006-SHALL-001` Each requirement includes: - ID - Statement - Rationale (where applicable) - Verification method **Allowed verification methods:** | Method | Description | |--------|-------------| | `test` | Deterministic unit test | | `property test` | Property-based test over input domain | | `static analysis` | Automated static analysis tool | | `inspection` | Manual code or design review | | `cross-platform harness` | certifiable-harness compatible golden reference | | `replay verification` | Full execution replay with commitment comparison | | `fault injection test` | Induced fault condition verification | | `schema test` | Evidence schema conformance test | | `RTM generation` | Requirements traceability matrix tooling | --- ## 4. Global System Requirements ### SRS-001-SHALL-001 — Contract Declaration Every Axilog module SHALL declare its governing DVEC version in the module header. **Verification:** inspection, static analysis --- ### SRS-001-SHALL-002 — Determinism Class Declaration Every Axilog module SHALL declare its determinism class as D1, D2, or D3 in its primary header. **Verification:** inspection, static analysis --- ### SRS-001-SHALL-003 — SRS Traceability Every public Axilog function SHALL include one or more SRS requirement anchors in its declaration or header comment. **Verification:** static analysis, RTM generation --- ### SRS-001-SHALL-004 — No Orphan Code No public Axilog function SHALL exist without a corresponding SHALL statement. **Verification:** RTM generation, static analysis --- ### SRS-001-SHALL-005 — No Deferred Correctness Production code SHALL contain no TODO, FIXME, HACK, OPTIMIZE, placeholder, or commented-out implementation blocks. **Verification:** pre-commit scan, CI scan --- ### SRS-001-SHALL-006 — Deterministic Initialization (Genesis Requirement) *Introduced in v0.2. Closes initial state ambiguity — the system is deterministic from the first instruction.* The Axilog substrate SHALL define a deterministic initialization sequence such that: ``` Power-On-Reset (POR) → S₀ ∀ platforms P₁, P₂: S₀₍P₁₎ = S₀₍P₂₎ ``` Where `S₀` is the canonical initial state and MUST be representable as an `AX:STATE:v1` commitment. **Constraints:** Initialization SHALL NOT depend on: - Prior memory contents - Hardware timing variance - Uninitialised state All state MUST be explicitly initialised to defined values before any computation proceeds. **Verification:** replay verification from POR, cross-platform identity test, golden reference generation at initialization boundary --- ### SRS-001-SHALL-007 — Configuration Evidence Binding *Introduced in v0.3. Closes configuration spoofing — the system personality is cryptographically bound to the ledger from genesis.* The system configuration manifest SHALL be committed as the first `AX:OBS:v1` record in the ledger, prior to any state transition or evidence record. **Constraints:** - No state mutation SHALL occur before the configuration manifest is committed - The configuration manifest SHALL include all parameters that define system behaviour (determinism class declarations, oracle configurations, policy versions, platform identifiers) - A ledger whose first record is not a configuration manifest commitment SHALL be rejected as non-conformant - Configuration manifest commits SHALL be included in the genesis golden reference **Rationale:** Without this requirement, a system could replay with a different configuration while presenting valid subsequent commitments — "personality spoofing". Binding configuration to the ledger genesis makes such attacks detectable from the first record. **Verification:** inspection, replay verification from genesis, schema test confirming first record type, fault injection test for missing manifest --- ## 5. Fault Context Requirements ### SRS-005-SHALL-001 — Persistent Fault Context All runtime primitives capable of arithmetic, logical, state, or ledger failure SHALL accept a `ct_fault_flags_t *faults` parameter. **Verification:** static analysis, inspection --- ### SRS-005-SHALL-002 — Explicit Fault Propagation A function detecting a fault SHALL record that fault in the supplied fault context before returning. **Verification:** property test, inspection --- ### SRS-005-SHALL-003 — No Silent Arithmetic Failure Overflow, underflow, divide-by-zero, invalid saturation, and invalid narrowing SHALL set a fault flag. **Verification:** property test, fault injection test --- ### SRS-005-SHALL-004 — No errno Runtime fault signalling SHALL NOT use errno, global variables, or thread-local side channels. **Verification:** static analysis --- ### SRS-005-SHALL-005 — Fail-Closed Terminality Any non-zero terminal fault state SHALL cause the runtime to transition to FAILED prior to any further state mutation. **Verification:** state-machine test, fault injection test --- ### SRS-005-SHALL-006 — No Implicit Fault Clearance Fault flags SHALL NOT be cleared implicitly by any runtime primitive. **Verification:** property test, inspection --- ### SRS-005-SHALL-007 — Reset Requirement Recovery from terminal FAILED state SHALL require an explicit reset operation defined by the owning subsystem. The reset boundary (process restart, subsystem reinitialisation, or system-level reset) SHALL be declared in the subsystem SRS. **Verification:** inspection, state transition test --- ## 6. Ledger Requirements ### SRS-006-SHALL-001 — Strict Total Order The ledger SHALL define a strictly total order over all committed events. **Verification:** property test, concurrency test --- ### SRS-006-SHALL-002 — Chain Extension Function Ledger chain extension SHALL be computed as: ``` L₀ = SHA-256("AX:LEDGER:v1" ‖ commit(e₀)) Lₙ = SHA-256("AX:LEDGER:v1" ‖ Lₙ₋₁ ‖ commit(eₙ)) ``` **Verification:** hash stability test, inspection --- ### SRS-006-SHALL-003 — Chain Tag Separation The ledger SHALL use `AX:LEDGER:v1` only as a chain tag and SHALL NOT use it as an evidence type identifier. **Verification:** tag linter, static analysis --- ### SRS-006-SHALL-004 — Append-Only Behaviour Committed ledger entries SHALL be append-only. **Verification:** inspection, state test --- ### SRS-006-SHALL-005 — No In-Place Mutation Committed ledger entries SHALL NOT be updated or deleted. **Verification:** inspection, storage interface test --- ### SRS-006-SHALL-006 — Sequence Monotonicity Ledger sequence position SHALL increase monotonically by exactly one per accepted append. **Verification:** property test --- ### SRS-006-SHALL-007 — Chain Integrity Failure Any detected discontinuity, recomputation mismatch, or invalid prior hash SHALL transition the system to FAILED. **Verification:** fault injection test, replay verification --- ### SRS-006-SHALL-008 — Constant Space Append Ledger append operations SHALL execute without heap allocation in runtime paths. **Verification:** static analysis, allocator scan --- ### SRS-006-SHALL-009 — Physical Storage Fault Handling (I/O Oracle) *Introduced in v0.2. Closes the physical reality gap — hardware failure is formally part of the model.* Any hardware-level I/O failure during ledger append SHALL: 1. Be captured as an oracle failure 2. Be recorded in fault context (`ct_fault_flags_t`) 3. Prevent partial or ambiguous chain mutation 4. Transition the system to FAILED prior to returning **Includes:** - Disk write failure - fsync failure - Partial write - Timeout / device error - Corrupted read-back verification **Constraints:** - No ledger state may exist in an indeterminate state - No partial append may be considered committed **Verification:** fault injection at storage layer, replay verification after induced I/O failure, property test: no valid chain continuation after failure --- ## 7. Evidence Requirements ### SRS-007-SHALL-001 — Evidence Completeness Every state transition influencing canonical state SHALL be preceded by a committed evidence record. **Verification:** replay verification, inspection --- ### SRS-007-SHALL-002 — Canonical JSON All JSON evidence payloads SHALL be canonicalised using RFC 8785 before hashing. **Verification:** JCS linter, hash stability test --- ### SRS-007-SHALL-003 — Canonical Hash Input Evidence commitments SHALL be computed on canonical byte representation, not raw structs or serializer-dependent output. **Verification:** inspection, static analysis --- ### SRS-007-SHALL-004 — Domain-Separated Commitment Evidence commitments SHALL use the domain-separated function: ``` commit(e) = SHA-256(tag ‖ LE64(|payload|) ‖ payload) ``` **Verification:** hash test, inspection --- ### SRS-007-SHALL-005 — Closed Evidence Tag Registry Evidence type identifiers SHALL be limited to the DVEC domain separation registry. **Verification:** tag linter --- ### SRS-007-SHALL-006 — Evidence Version Closure A v1 evidence type SHALL NOT change meaning without a formal version upgrade. **Verification:** inspection, schema regression test --- ### SRS-007-SHALL-007 — Required Evidence Types The system SHALL support, at minimum: - `AX:STATE:v1` - `AX:TRANS:v1` - `AX:OBS:v1` - `AX:POLICY:v1` - `AX:PROOF:v1` **Verification:** inspection, schema presence test --- ### SRS-007-SHALL-008 — Input Domain Validation *Introduced in v0.2. Closes the undefined input space — all inputs are contractually bounded before arithmetic or state mutation proceeds.* All public APIs accepting fixed-point or domain-constrained inputs SHALL: 1. Validate that inputs lie within the declared domain 2. Reject or fault any out-of-range input BEFORE: - Arithmetic execution - State mutation - Ledger commitment **Examples:** - Q16.16 range bounds - Non-negative constraints where required - Bounded parameter domains **Constraints:** - No implicit clamping without fault signalling - No undefined behaviour from invalid inputs **Verification:** property-based testing (domain boundaries), fault injection tests, static analysis for missing guards --- ## 8. Oracle Boundary Requirements ### SRS-008-SHALL-001 — Oracle Admission No oracle-derived value SHALL influence canonical state unless captured, canonicalised, committed, and referenced. **Verification:** replay verification, inspection --- ### SRS-008-SHALL-002 — Time as Oracle Time SHALL be treated as an oracle input, not a runtime ambient value. **Verification:** static analysis, inspection --- ### SRS-008-SHALL-003 — No System Clock Access Domain execution code SHALL NOT read wall clock or monotonic clock APIs directly. **Verification:** pre-commit scan, CI scan --- ### SRS-008-SHALL-004 — Time Observation Record All accepted time injections SHALL be committed as `AX:OBS:v1` records with oracle type `TIME_INJECTION`. **Verification:** schema test, replay verification --- ### SRS-008-SHALL-005 — Monotonic Time Time injections SHALL be monotonically non-decreasing unless explicitly configured otherwise at system initialisation. **Verification:** property test, replay verification --- ### SRS-008-SHALL-006 — Rollback Rejection Undeclared time rollback SHALL be rejected and SHALL set terminal fault state. **Verification:** fault injection test --- ### SRS-008-SHALL-007 — D3 Routing Observed non-deterministic components SHALL route output through the oracle boundary before state consumption. **Verification:** inspection, architecture test --- ## 9. Arithmetic Requirements ### SRS-009-SHALL-001 — Fixed-Point Only All deterministic runtime arithmetic SHALL use fixed-point representation. **Verification:** static analysis, forbidden pattern scan --- ### SRS-009-SHALL-002 — Minimum Precision The canonical fixed-point format SHALL be Q16.16 or stricter where declared. **Verification:** inspection, type test --- ### SRS-009-SHALL-003 — Widen Before Operation All fixed-point multiplication, accumulation, or narrowing-sensitive operations SHALL widen operands before operation. **Verification:** static analysis, inspection --- ### SRS-009-SHALL-004 — Saturating Narrowing All narrowing from widened intermediate representation SHALL saturate to target width and set a fault flag on saturation. **Verification:** property test, fault injection test --- ### SRS-009-SHALL-005 — No Raw Arithmetic on Fixed-Point Types Runtime code SHALL NOT use raw `+`, `-`, `*`, `/` operators on declared fixed-point domain types outside approved primitives. **Verification:** static analysis, AST linter --- ### SRS-009-SHALL-006 — Deterministic Division All fixed-point division primitives SHALL define rounding and fault behaviour explicitly. **Verification:** property test --- ### SRS-009-SHALL-007 — Zero Divide Fault Division by zero SHALL set a terminal fault condition. **Verification:** fault injection test --- ## 10. Memory Requirements ### SRS-010-SHALL-001 — Zero Dynamic Allocation Runtime execution paths SHALL perform no dynamic allocation. **Verification:** static analysis, forbidden pattern scan --- ### SRS-010-SHALL-002 — Caller-Owned Buffers All runtime buffers SHALL be caller-provided or statically allocated at initialisation. **Verification:** inspection, API review --- ### SRS-010-SHALL-003 — Explicit Ownership Every public API with pointer parameters SHALL declare memory ownership and lifetime semantics. **Verification:** header inspection, static analysis --- ### SRS-010-SHALL-004 — No Hidden Ownership Transfer A function SHALL NOT assume ownership of caller memory unless explicitly declared in its contract. **Verification:** inspection --- ### SRS-010-SHALL-005 — Constant-Space Runtime Core runtime primitives SHALL execute in bounded space without allocator dependence. **Verification:** WCET/static resource analysis --- ### SRS-010-SHALL-006 — Static Stack Depth Bound *Introduced in v0.3. Closes the stack overflow gap — forbidden dynamic allocation is necessary but not sufficient; stack depth must also be formally bounded.* The maximum call stack depth of all D1 runtime paths SHALL be statically determinable and SHALL NOT exceed the declared stack budget for the target platform. **Constraints:** - All call graphs SHALL be acyclic (no recursion, per DVEC §2.2) - Maximum stack frame size per function SHALL be statically analysable - Total worst-case stack depth SHALL be declared in the subsystem SRS and verified against platform constraints - Stack overflow SHALL be treated as a terminal fault condition **Verification:** static call graph analysis, stack depth analysis (e.g. clang-tidy stack usage plugin, GCC `-fstack-usage`), WCET tool integration --- ## 11. Cross-Platform Identity Requirements ### SRS-011-SHALL-001 — Cross-Architecture Identity D1 components SHALL produce bit-identical outputs across all supported architectures. **Verification:** cross-platform harness --- ### SRS-011-SHALL-002 — Supported Platforms At minimum, cross-platform identity SHALL be verified across x86_64 and ARM64. RISC-V SHALL be added when supported. **Verification:** harness matrix --- ### SRS-011-SHALL-003 — Golden Reference Format D1 systems SHALL emit a certifiable-harness compatible 368-byte golden reference. **Verification:** golden verifier --- ### SRS-011-SHALL-004 — Golden Match Requirement A golden reference mismatch across supported architectures SHALL fail CI. **Verification:** CI harness --- ### SRS-011-SHALL-005 — Sequential and Parallel Equivalence Any conformant parallel implementation SHALL produce bit-identical canonical state to the sequential reference implementation. **Verification:** equivalence test --- ## 12. Concurrency Requirements ### SRS-012-SHALL-001 — Deterministic Reduction Topology Parallel reductions SHALL use a fixed tree topology. **Verification:** inspection, equivalence test --- ### SRS-012-SHALL-002 — No Shared Unsynchronised Mutation Runtime code SHALL NOT use shared mutable state without explicit synchronisation and determinism proof. **Verification:** static analysis, inspection --- ### SRS-012-SHALL-003 — No Race-Dependent Semantics Observable runtime behaviour SHALL NOT depend on race timing or scheduling coincidence. **Verification:** concurrency test, inspection --- ### SRS-012-SHALL-004 — Sequential Equivalence Parallel execution SHALL preserve the canonical result of sequential execution. **Verification:** equivalence test --- ## 13. Verification Infrastructure Requirements ### SRS-013-SHALL-001 — Mechanised RTM The system SHALL maintain a mechanised requirements traceability matrix linking SHALL statements to code anchors and verification artifacts. **Verification:** RTM generation --- ### SRS-013-SHALL-002 — Tag Linter The build SHALL include a domain tag linter enforcing DVEC registry conformance. **Verification:** CI execution --- ### SRS-013-SHALL-003 — JCS Linter The build SHALL include a JCS verification tool for all JSON evidence generation paths. **Verification:** CI execution --- ### SRS-013-SHALL-004 — Forbidden Pattern Gate The build SHALL fail if forbidden constructs defined by DVEC are detected. **Verification:** CI execution --- ### SRS-013-SHALL-005 — Static Analysis Cleanliness Static analysis SHALL pass with zero warnings for production code. **Verification:** clang-tidy, cppcheck --- ### SRS-013-SHALL-006 — Replay Verification The system SHALL provide replay verification sufficient to prove evidence-order and commitment continuity. **Verification:** replay verifier --- ### SRS-013-SHALL-007 — Toolchain Provenance (Closure Invariant) *Introduced in v0.2. Closes meta-layer trust — even verification is verifiable.* All mechanised verification tools SHALL: 1. Be version-pinned 2. Produce bit-identical outputs for identical inputs 3. Be included within the certification boundary **Applies to:** - RTM generator - JCS canonicaliser - Static analysis tools - Arithmetic linters - Tag validators - Golden verifier **Constraints:** - Tool version drift SHALL be treated as a system change - No unverified tool upgrade permitted **Verification:** toolchain hashing, reproducibility tests, cross-platform tool output comparison --- ## 14. Header Template Requirements ### SRS-014-SHALL-001 — Compliance Header Every public header SHALL declare: - File purpose - DVEC version - Determinism class - Memory model **Verification:** static analysis, inspection --- ### SRS-014-SHALL-002 — Requirement-Anchored Public API Every public function declaration SHALL carry one or more SRS anchors. **Verification:** RTM generation **Example:** ```c /** * @brief Appends a new evidence commitment to the total-ordered chain. * * DVEC: v1.3 * DETERMINISM: D1 — Strict Deterministic * MEMORY: Zero Dynamic Allocation * * SRS-006-SHALL-001: The ledger SHALL define a strictly total order. * SRS-006-SHALL-002: Chain extension SHALL use SHA-256("AX:LEDGER:v1" * || L_n-1 || commit(e_n)). * SRS-006-SHALL-009: Physical I/O failure SHALL transition to FAILED. */ void ax_ledger_append( ax_ledger_ctx_t *ctx, const uint8_t commit[32], ct_fault_flags_t *faults ); ``` --- ## 15. Initial Public API Requirement Set These are the first functions that SHALL exist only once their supporting SHALLs are frozen: | Function | Primary SRS Coverage | |----------|---------------------| | `dvm_add_q16` | SRS-009-SHALL-001..007 | | `dvm_sub_q16` | SRS-009-SHALL-001..007 | | `dvm_mul_q16` | SRS-009-SHALL-001..007 | | `dvm_div_q16` | SRS-009-SHALL-001..007 | | `ax_commit_evidence` | SRS-007-SHALL-001..008 | | `ax_ledger_append` | SRS-006-SHALL-001..009 | | `ax_verify_chain` | SRS-006-SHALL-007 | | `ax_time_observe` | SRS-008-SHALL-002..006 | | `ax_fault_reset` | SRS-005-SHALL-007 (only once reset semantics formally declared) | No additional public API SHALL be added without corresponding SHALL coverage. --- ## 16. Verification Matrix | Requirement ID | Function(s) | Verification | |----------------|-------------|--------------| | SRS-001-SHALL-006 | initialization sequence | replay, golden reference | | SRS-005-SHALL-003 | `dvm_add_q16`, `dvm_mul_q16`, `dvm_div_q16` | property test, fault injection | | SRS-005-SHALL-005 | all faulting primitives | state machine test | | SRS-006-SHALL-002 | `ax_ledger_append` | hash stability test | | SRS-006-SHALL-009 | `ax_ledger_append` | fault injection, storage layer | | SRS-007-SHALL-004 | `ax_commit_evidence` | inspection, hash test | | SRS-007-SHALL-008 | all domain-constrained APIs | property test, fault injection | | SRS-008-SHALL-005 | `ax_time_observe` | replay verification, property test | | SRS-011-SHALL-003 | harness emitter | golden verifier | | SRS-013-SHALL-007 | all verification tools | toolchain hashing | --- ## 17. Closure Assessment | Layer | Status | |-------|--------| | Execution determinism | ✅ Closed | | Fault propagation | ✅ Closed | | Ledger correctness | ✅ Closed | | Evidence system | ✅ Closed | | Oracle boundary | ✅ Closed | | Arithmetic model | ✅ Closed | | Memory model | ✅ Closed | | Cross-platform identity | ✅ Closed | | Initialization | ✅ Closed (v0.2) | | Physical I/O reality | ✅ Closed (v0.2) | | Input domain correctness | ✅ Closed (v0.2) | | Toolchain trust | ✅ Closed (v0.2) | | Stack depth bounds | ✅ Closed (v0.3) | | Configuration spoofing | ✅ Closed (v0.3) | **Certification Boundary:** | Layer | Closing Requirement | Verification Tool | |-------|--------------------|--------------------| | Meta-Layer | Toolchain Provenance (SRS-013-SHALL-007) | SHA-256 hashing of all tool binaries | | Logic-Layer | Input Domain Validation (SRS-007-SHALL-008) | Property-based boundary testing | | Physical-Layer | I/O Oracle (SRS-006-SHALL-009) | Storage layer fault injection | | Stack-Layer | Static Stack Depth Bound (SRS-010-SHALL-006) | Static call graph + `-fstack-usage` | | Genesis-Layer | Configuration Evidence Binding (SRS-001-SHALL-007) | Replay verification from genesis | **Invariants of Truth:** 1. **Temporal Invariant** — Time is an external oracle; rollback is a terminal failure 2. **Arithmetic Invariant** — Floating point is prohibited; all operations are widened and saturated with explicit fault signalling 3. **Memory Invariant** — Zero heap dependence ensures O(1) space complexity and eliminates fragmentation risks 4. **Reality Invariant** — Hardware failure is not a side effect; it is a formally modelled state transition to FAILED --- ## 18. Final Statement Axilog SHALL not be a "mostly reproducible" runtime. It SHALL be a deterministic, auditable, bounded execution substrate in which: - Faults are explicit - Evidence is canonical - Order is total - Cross-platform behaviour is identical - Correctness is mechanically enforced --- ## 19. Closing Principle > The purpose of this SRS is not to describe intentions. > It is to define the exact set of behaviours the substrate > is permitted to have. --- *SRS-001 v0.3 — Audit-Frozen* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== Layer group: L7 — Governance ======================================================================== ======================================================================== SRS-007 — Proof-Carrying Governance & Compliance ======================================================================== Spec ID: SRS-007 Title: Proof-Carrying Governance & Compliance Version: v0.3 Status: Locked Layer: L7 Determinism: D2 Date: 2026-03-27 Depends on: SRS-001, SRS-002, SRS-003, SRS-004, SRS-005, DVEC-001, AXIOMA-FRAMEWORK Compliance: DO-178C, IEC 62304, ISO 26262 URL: https://axilog.io/specs/srs-007/ Changelog: https://axilog.io/specs/srs-007/changelog/ Summary: The L7 governance contract — governance as cryptographic proof, a deterministic program over committed evidence that turns assertion into citation. **Depends on:** SRS-001 v0.3 · SRS-002 v0.3 · SRS-003 v0.3 · SRS-004 v0.3 · SRS-005 v1.1 · DVEC-001 v1.3 · AXIOMA-FRAMEWORK v0.4 --- ## 0. GOVERNING PRINCIPLE > **Governance is not a document. Governance is a proof.** > > **A regulator does not receive an assertion. They receive a > cryptographically evidenced argument.** L1–L6 produce deterministic, auditable behaviour. L7 proves it. The distinction: | Without L7 | With L7 | |------------|---------| | "The system behaved correctly" | "Here is the cryptographic proof that it did" | | Assertion | Evidence citation | | Audit log | Tamper-evident proof chain | | Policy document | Deterministic program over committed evidence | --- ## 1. PURPOSE This document defines the **Proof-Carrying Governance Contract** for the Axioma framework. It specifies: - The AX:PROOF:v1 evidence record structure - Proof construction from evidence citations - Policy soundness requirements - Cross-layer verification protocol - Compliance report generation (Track A and Track B) - External anchor publication - Integrity fault handling - Traceability requirements **Objective:** Every governance claim SHALL be a deterministic, independently verifiable proof over committed evidence — not an assertion over system state. --- ## 2. DEFINITIONS ### 2.1 Proof-Carrying Assertion A **proof-carrying assertion** is a governance claim that: - references specific committed evidence records - is independently recomputable from those records - produces identical results for identical evidence ### 2.2 AX:PROOF:v1 The canonical evidence record representing a governance proof. ### 2.3 Track A — Safety-Critical Evidence Package The evidence package for DO-178C, IEC 62304, and ISO 26262 certification. Applies to D1 components only. ### 2.4 Track B — Enterprise Governance Evidence Package The evidence package for EU AI Act Article 9, ISO/IEC 42001, FCA PS22/3, and MHRA AI/ML guidance. Applies to D2/D3 components. ### 2.5 External Anchor A periodic GPG-signed SHA-256 commitment of all ledger chain heads, published to a public append-only transparency log. ### 2.6 Governance Integrity Fault A condition where the governance layer detects an inconsistency between committed evidence and declared system behaviour. ### 2.7 Compliance Report A structured, JCS-canonical document summarising the governance state of the system over a declared period, suitable for submission to a regulatory body. ### 2.8 Mathematical Trace A structured record linking an oracle observation (L3) through policy evaluation (L4) and agent transition (L5) to a committed ledger entry (L6), with all intermediate evidence citations. ### 2.9 Evidence Closure Proof A Merkle root or equivalent cryptographic commitment proving completeness of an evidence set — that no relevant evidence has been omitted. --- ## 3. DETERMINISM MODEL ### 3.1 Determinism Class The governance layer SHALL operate under: **D2 — Constrained Deterministic** ### 3.2 Determinism Definition **SRS-007-SHALL-001** For identical: - committed evidence records - declared policy set (canonically ordered and hashed) - governance configuration (canonically ordered and hashed) the system SHALL produce: - identical `AX:PROOF:v1` records - identical compliance report content **Verification:** replay verification, cross-platform identity test --- ### 3.2.1 Configuration Canonicality **SRS-007-SHALL-044** *Added in v0.2 per F010.* The policy set and governance configuration SHALL be: - RFC 8785 (JCS) canonicalised - sorted by policy_id / config_key lexicographically - hashed (SHA-256) prior to any evaluation - committed to the ledger at initialisation **Verification:** inspection, hash stability test --- ### 3.3 Evidence Closure **SRS-007-SHALL-002** All governance evaluations SHALL operate exclusively on: - committed evidence records (`AX:STATE:v1`, `AX:TRANS:v1`, `AX:OBS:v1`, `AX:POLICY:v1`, `AX:PROOF:v1`) - static governance configuration Governance SHALL NOT depend on: - live system state - external services - system clock (unless admitted as oracle per §9.2.1) - non-committed data **Verification:** inspection, static analysis --- ## 4. AX:PROOF:v1 RECORD ### 4.1 Proof Record Requirement **SRS-007-SHALL-003** Every governance proof SHALL be committed as an `AX:PROOF:v1` record to the L6 ledger before influencing any downstream decision. --- ### 4.2 Required Fields **SRS-007-SHALL-004** *Amended in v0.3 per F014.* Each `AX:PROOF:v1` record SHALL contain: | Field | Type | Description | |-------|------|-------------| | `claim` | string | The governance claim being proven | | `commitment` | bytes32 | Domain-separated commitment per SRS-001 §4.3 | | `evidence_ordering` | enum | Ordering mode for evidence_refs (see §4.4.2) | | `evidence_refs` | array[bytes32] | Ordered list of evidence record hashes (see §4.4.1) | | `ledger_seq` | uint64 | Sequence number of this proof record | | `ordering_metadata` | object/null | Required if evidence_ordering = DECLARED | | `prev_chain_head` | bytes32 | Prior L6 chain head before this commit | | `proof_hash` | bytes32 | SHA-256 over canonical payload (preimage commitment) | | `proof_type` | enum | Classification of proof (see §4.3) | | `result` | enum | `VALID` \| `INVALID` \| `INTEGRITY_FAULT` | | `rule_id` | string | Governance rule identifier | | `schema_version` | string | Always `"AX:PROOF:v1"` | | `violation` | enum/null | Violation type if result is INVALID | **Field Order:** Fields MUST appear in lexicographic order per RFC 8785 (JCS): ``` claim, commitment, evidence_ordering, evidence_refs, ledger_seq, ordering_metadata, prev_chain_head, proof_hash, proof_type, result, rule_id, schema_version, violation ``` --- ### 4.2.1 Cryptographic Binding Fields **SRS-007-SHALL-045** *Amended in v0.3 per F011, F012.* The cryptographic binding fields SHALL be computed as: **proof_hash:** ``` proof_hash = SHA-256(canonical_payload_with_proof_hash_omitted) ``` Where `canonical_payload_with_proof_hash_omitted` is the RFC 8785 canonicalised record with the `proof_hash` field **entirely omitted** (not present as empty string, not present as null — the key itself is absent from the JSON object). **Forbidden alternatives:** ``` ❌ proof_hash set to "" (empty string) ❌ proof_hash set to null ❌ proof_hash set to zero ("000...000") ``` **Rationale:** JCS canonicalisation treats `""`, `null`, and omitted fields differently. Only field omission produces unambiguous canonical form across all implementations. --- ### 4.2.2 Commitment Payload Encoding **SRS-007-SHALL-054** *Added in v0.3 per F012.* The commitment function payload encoding SHALL be: **commitment:** ``` commitment = SHA-256("AX:PROOF:v1" ‖ LE64(byte_length) ‖ utf8_bytes) ``` Where: - `"AX:PROOF:v1"` is the ASCII domain separation tag (11 bytes) - `byte_length` is the length in **bytes** (not characters) of the UTF-8 encoded canonical JSON - `utf8_bytes` is the UTF-8 encoded RFC 8785 canonical JSON payload - `‖` denotes byte-wise concatenation **Encoding Rules:** | Component | Encoding | |-----------|----------| | Domain tag | ASCII bytes | | Length | Little-endian 64-bit unsigned integer | | Payload | UTF-8 encoded JSON (RFC 8785 canonical) | **Verification:** byte-level hash stability test, cross-platform harness --- ### 4.2.3 Chain Head Reference **SRS-007-SHALL-055** *Added in v0.3 for completeness.* **prev_chain_head:** The SHA-256 hash of the L6 chain head immediately prior to this record's commitment. **Purpose:** These fields make proofs self-authenticating and independently verifiable outside L6 context. **Verification:** hash stability test, independent verification test --- ### 4.3 Proof Types **SRS-007-SHALL-005** The proof type set SHALL be closed within a schema version: | Type | Description | |------|-------------| | `ANCHOR_PUBLICATION` | External anchor commitment | | `COMPLIANCE_SUMMARY` | Compliance report proof | | `CROSS_LAYER_VERIFY` | Cross-layer chain verification | | `POLICY_SOUNDNESS` | Policy evaluation over evidence | | `REPLAY_EQUIVALENCE` | Replay produces identical results | | `SUBSTRATE_CERT` | L1 substrate certification | | `WEIGHT_BINDING` | L2 model identity verification | Any proof type outside this closed set SHALL be rejected as non-conformant. --- ### 4.3.1 Proof Type Versioning **SRS-007-SHALL-056** *Added in v0.3 per F019.* The proof type enumeration SHALL support versioned extension: **Namespace:** `AX:PROOF:v{N}` **Extension Rules:** 1. New proof types require a new schema version (`AX:PROOF:v2`, etc.) 2. Schema version upgrade requires explicit migration specification 3. Backward compatibility: v1 proofs remain valid in v2 systems 4. Forward compatibility: v2 proofs rejected by v1 systems with `INTEGRITY_FAULT` **Migration Protocol:** ``` 1. Define new proof types in AX:PROOF:v{N+1} 2. Publish migration specification 3. Deploy systems supporting both versions 4. Deprecate old version after transition period ``` **Verification:** schema validation, version compatibility test --- ### 4.4 Evidence Reference Requirement **SRS-007-SHALL-006** Every `AX:PROOF:v1` record SHALL cite at minimum one committed evidence record in `evidence_refs`. A proof with an empty `evidence_refs` array is non-conformant. Assertions without evidence citations are not proofs. --- ### 4.4.1 Evidence Reference Encoding **SRS-007-SHALL-046** *Amended in v0.3 per F014.* The `evidence_refs` array SHALL conform to: **Hash Algorithm:** SHA-256 (32 bytes) **Encoding:** Lowercase hexadecimal (64 characters per hash) **Ordering:** Controlled by the `evidence_ordering` field (see §4.4.2) **Example:** ```json "evidence_refs": [ "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd", "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" ] ``` **Verification:** schema test, property test --- ### 4.4.2 Evidence Ordering Mode **SRS-007-SHALL-057** *Added in v0.3 per F014.* Each `AX:PROOF:v1` record SHALL include an `evidence_ordering` field: | Field | Type | Description | |-------|------|-------------| | `evidence_ordering` | enum | Ordering mode for `evidence_refs` | **Ordering Modes:** | Mode | Definition | Use Case | |------|------------|----------| | `LEX` | Lexicographic sort by hash | Default, no semantic order | | `TEMPORAL` | Ascending by `ledger_seq` | Causal chain proofs | | `DECLARED` | Order matches `ordering_metadata` | Custom semantic order | **If `DECLARED`:** The record MUST include an `ordering_metadata` field: ```json "ordering_metadata": { "description": "Cross-layer verification sequence", "key_field": "ledger_seq", "direction": "ascending" } ``` **Default:** If `evidence_ordering` is omitted, `LEX` is assumed. **Forbidden:** ``` ❌ Ordering rule declared in free-form claim field ❌ Implicit ordering without declaration ``` **Verification:** schema test, ordering verification test --- ### 4.5 Canonical Format **SRS-007-SHALL-007** All `AX:PROOF:v1` records SHALL be: - RFC 8785 (JCS) canonicalised - bit-identical for identical inputs - committed using the domain-separated commitment function (SRS-001 §4.3) **Verification:** JCS linter, hash stability test --- ## 5. POLICY SOUNDNESS REQUIREMENT ### 5.1 Soundness Definition **SRS-007-SHALL-008** All governance policies SHALL satisfy the Policy Soundness Requirement: **1. Deterministic Evaluation** Given identical evidence inputs, the policy produces identical output. **2. Evidence Closure** The policy references only committed evidence records. No external state permitted. **3. Independent Verifiability** A third party with access to the evidence set can recompute the policy and obtain the same result. **Formal model:** ``` Let P : E → R where E = evidence records, R = policy result Then: ∀ E : P(E) = deterministic ``` --- ### 5.2 Policy Violation **SRS-007-SHALL-009** A policy is non-conformant if: - It depends on external state not present in evidence records - It produces non-deterministic output - It cannot be independently recomputed from evidence Non-conformant policies SHALL be rejected at governance initialisation. **Verification:** inspection, property test --- ### 5.3 Policies as Programs **SRS-007-SHALL-010** Governance policies ARE deterministic programs over committed evidence — not configuration documents. The distinction: ``` Non-conformant: "Policy says no PII in LLM inputs" Conformant: P(AX:OBS:v1 records) → {PERMITTED, BREACH} where P is deterministic and evidence-closed ``` **Verification:** inspection, property test --- ## 6. CROSS-LAYER VERIFICATION PROTOCOL ### 6.1 Verification Chain **SRS-007-SHALL-011** The governance layer SHALL verify the complete cross-layer evidence chain. Verification SHALL proceed in layer order: ``` Step 1: L1 Substrate Certification Step 2: L2 Weight-to-Evidence Binding Step 3: L3 Observation Integrity Step 4: L4 Policy Soundness Verification Step 5: L3→L4 Observation-to-Policy Binding Step 6: L4→L5 Breach-to-Transition Enforcement Step 7: L5→L6 Pre-Commit Ordering Step 8: Full Chain Replay Verification ``` Each step SHALL produce an `AX:PROOF:v1` record. --- ### 6.1.1 Proof-Before-Execution Invariant **SRS-007-SHALL-047** *Amended in v0.3 per F017.* All cross-layer verification proofs MUST be committed before dependent layer execution proceeds. **Invariant:** ``` ∀ verification step V producing proof P: commit(P) → then dependent_action NOT: dependent_action → then commit(P) ``` **Violation Behaviour:** Any execution that proceeds before its verification proof is committed SHALL be treated as `INTEGRITY_FAULT`. **Rationale:** Prevents transient violations that could be "fixed" post-hoc. Ensures audit completeness with no gaps. **Verification:** integration test, state machine test --- ### 6.1.2 Atomicity Model **SRS-007-SHALL-058** *Added in v0.3 per F017.* The proof-before-execution invariant SHALL be enforced via one of: **Option A — Single-Threaded Sequencing:** All governance operations execute in a single thread with deterministic sequencing: ``` 1. compute_proof(V) 2. commit_to_ledger(P) 3. verify_commit_success() 4. execute_dependent_action() ``` No concurrent execution of governance operations permitted. **Option B — Atomic Commit Boundary:** Proof commit and dependent action execute within an atomic transaction boundary: ``` BEGIN ATOMIC commit_to_ledger(P) execute_dependent_action() COMMIT ``` Failure at any step rolls back all changes. **Deployment Declaration:** The atomicity model MUST be declared in the configuration manifest. **Forbidden:** ``` ❌ Race condition between commit and action ❌ Non-atomic interleaving of proof and execution ❌ Optimistic execution with deferred proof commit ``` **Verification:** concurrency test, state machine test --- ### 6.2 Step 1 — L1 Substrate Certification **SRS-007-SHALL-012** Governance SHALL verify that certifiable-inference (L2) was compiled against libaxilog (L1) with no forbidden arithmetic patterns. **Proof:** `forbidden-pattern-scan` result committed as `AX:PROOF:v1` with `proof_type = SUBSTRATE_CERT`. **Verification:** build system audit, static analysis artefact --- ### 6.3 Step 2 — L2 Weight-to-Evidence Binding **SRS-007-SHALL-013** Governance SHALL verify: ``` WeightHash(L2) ≡ ModelID(L3.AX:OBS:v1.model_id) ``` The model that produced the inference MUST match the model whose weights were quantised and certified. **Proof:** Weight hash comparison committed as `AX:PROOF:v1` with `proof_type = WEIGHT_BINDING`. **Violation:** Any `model_id` mismatch SHALL produce `result = INTEGRITY_FAULT`. **Verification:** inspection, integration test --- ### 6.3.1 Weight Hash Specification **SRS-007-SHALL-048** *Added in v0.2 per F008.* The weight hash SHALL be computed as: ``` weight_hash = SHA-256(canonical_weight_representation) ``` Where `canonical_weight_representation` is: - The quantised weight tensor in DVEC-001 canonical form - Serialised as contiguous Q16.16 values in row-major order - Little-endian byte encoding - No padding between layers - Layer order fixed by model architecture declaration **Reference:** DVEC-001 v1.3 §12.2 (quantisation canonical form) **Verification:** hash stability test, cross-platform harness --- ### 6.4 Step 3 — L3 Observation Integrity **SRS-007-SHALL-014** Governance SHALL verify the `obs_hash` in every `AX:OBS:v1` record: ``` obs_hash = SHA-256(canonical_record_without_obs_hash) ``` Any `obs_hash` mismatch SHALL produce `result = INTEGRITY_FAULT`. **Verification:** hash stability test, property test --- ### 6.5 Step 4 — L4 Policy Soundness Verification **SRS-007-SHALL-015** Governance SHALL verify that all active policies satisfy SRS-007-SHALL-008 (Policy Soundness Requirement) before certifying any compliance report. **Verification:** property test, inspection --- ### 6.6 Step 5 — L3→L4 Observation-to-Policy Binding **SRS-007-SHALL-016** Governance SHALL verify the binding: ``` AX:POLICY:v1.obs_ledger_seq → AX:OBS:v1.ledger_seq ``` (Per SRS-004-SHALL-044) Every policy evaluation MUST be unambiguously traceable to the exact observation it evaluated. Any broken binding SHALL produce `result = INTEGRITY_FAULT`. **Verification:** integration test, RTM generation --- ### 6.7 Step 6 — L4→L5 Breach-to-Transition Enforcement **SRS-007-SHALL-017** Governance SHALL verify: ``` L4:AX:POLICY:v1.result = BREACH ⟹ L5:AX:TRANS:v1.next_state ∈ {ALARM, STOPPED} ``` Any transition to a non-safety state following a policy breach SHALL produce `result = INTEGRITY_FAULT`. **Verification:** state machine test, integration test --- ### 6.8 Step 7 — L5→L6 Pre-Commit Ordering **SRS-007-SHALL-018** Governance SHALL verify the cross-layer ordering invariant: ``` AX:OBS:v1 (ledger_seq N) → AX:POLICY:v1 (ledger_seq N+1..N+k) → AX:TRANS:v1 (ledger_seq N+k+1) ``` (Per SRS-004-SHALL-016, SRS-003-SHALL-022) Any ordering violation SHALL produce `result = INTEGRITY_FAULT`. **Verification:** property test, integration test --- ### 6.9 Step 8 — Full Chain Replay Verification **SRS-007-SHALL-019** Governance SHALL provide replay verification sufficient to prove: Given: - Identical genesis state (L0) - Identical ordered AX:OBS:v1 sequence The system SHALL reproduce: - Identical AX:POLICY:v1 records - Identical AX:TRANS:v1 records - Identical final state - Identical AX:PROOF:v1 records **Verification:** replay verifier, cross-platform identity test --- ## 7. MATHEMATICAL TRACE ### 7.1 Trace Requirement **SRS-007-SHALL-020** For every inference event, governance SHALL produce a Mathematical Trace — a structured record linking the complete evidence chain from oracle input to committed transition. --- ### 7.2 Required Trace Fields **SRS-007-SHALL-021** *Amended in v0.2 per F006.* Each Mathematical Trace SHALL include: | Field | Type | Encoding | Description | |-------|------|----------|-------------| | `chain_head` | bytes32 | hex lowercase | L6 chain head after all commits | | `obs_hash` | bytes32 | hex lowercase | AX:OBS:v1 observation hash | | `obs_ledger_seq` | uint64 | decimal | L3 oracle observation sequence | | `policy_results` | array[enum] | — | PERMITTED/BREACH per policy | | `policy_seqs` | array[uint64] | ascending | L4 policy evaluation sequences | | `proof_ledger_seq` | uint64 | decimal | This proof record sequence | | `trace_hash` | bytes32 | hex lowercase | SHA-256 of canonical trace | | `trans_ledger_seq` | uint64 | decimal | L5 transition sequence | | `trans_next_state` | enum | — | Resulting agent health state | | `weight_hash` | bytes32 | hex lowercase | L2 model fingerprint | **Field Order:** Lexicographic per RFC 8785. --- ### 7.2.1 Trace Array Ordering **SRS-007-SHALL-049** *Added in v0.2 per F006.* Arrays within Mathematical Traces SHALL be ordered as: **policy_seqs:** Ascending by `ledger_seq` **policy_results:** Corresponding order to `policy_seqs` (i.e., `policy_results[i]` is the result for `policy_seqs[i]`) **Verification:** property test, inspection --- ### 7.2.2 Trace Hash Computation **SRS-007-SHALL-050** *Added in v0.2 per F006.* The `trace_hash` SHALL be computed as: ``` trace_hash = SHA-256(canonical_trace_without_trace_hash) ``` Where `canonical_trace_without_trace_hash` is the RFC 8785 canonicalised trace record with `trace_hash` set to empty string. The `trace_hash` SHALL be included in the parent `AX:PROOF:v1` record's `evidence_refs`. **Verification:** hash stability test --- ### 7.3 Trace Canonicality **SRS-007-SHALL-022** Mathematical Traces SHALL be: - RFC 8785 (JCS) canonicalised - bit-identical for identical evidence chains - committed as `AX:PROOF:v1` with `proof_type = CROSS_LAYER_VERIFY` --- ## 8. COMPLIANCE REPORT GENERATION ### 8.1 Track A — Safety-Critical Evidence Package **SRS-007-SHALL-023** The Track A evidence package SHALL be generated for systems using certifiable-inference (L2, D1) and SHALL include: | Artefact | Source | Description | |----------|--------|-------------| | Merkle provenance chains | certifiable-* | Data → training → quantisation | | 368-byte golden reference | certifiable-harness | Cross-platform bit-identity proof | | Quantisation error bounds | certifiable-quant | ε₀ = 2⁻¹⁷ per layer | | Conformance test results | certifiable-bench | Correctness-gated performance | | Substrate certification | libaxilog | No forbidden patterns | | Weight fingerprint | quantize.py | model_id binding proof | **Standards addressed:** DO-178C, IEC 62304, ISO 26262 --- ### 8.2 Track B — Enterprise Governance Evidence Package **SRS-007-SHALL-024** The Track B evidence package SHALL be generated for systems using oracle-based inference (L3, D3) and SHALL include: | Artefact | Source | Description | |----------|--------|-------------| | Typed audit ledger | axioma-audit | Complete AX:*:v1 record set | | Oracle call records | axioma-oracle | AX:OBS:v1 per LLM interaction | | Drift detection reports | certifiable-monitor | TV/JSD/PSI fixed-point results | | Policy assertion records | axioma-policy | AX:POLICY:v1 per evaluation | | Mathematical traces | axioma-governance | Cross-layer evidence chains | | External anchor log | axioma-governance | GPG-signed chain head anchors | | Evidence closure proof | axioma-governance | Merkle root of included evidence | **Standards addressed:** EU AI Act Article 9, ISO/IEC 42001, FCA PS22/3, MHRA AI/ML guidance --- ### 8.3 Report Trigger Conditions **SRS-007-SHALL-025** Compliance reports SHALL be triggered by events, not arbitrary sequence counts: | Trigger | Report Type | |---------|-------------| | Agent transitions to STOPPED | Incident report | | Policy BREACH detected | Breach report | | External anchor interval elapsed | Periodic summary | | Explicit governance request | On-demand report | | System reset from STOPPED | Recovery report | **Rationale:** Sequence-count triggers (e.g. every 1000 events) are arbitrary and may miss critical events or produce reports at semantically meaningless boundaries. --- ### 8.4 Report Canonical Format **SRS-007-SHALL-026** All compliance reports SHALL be: - RFC 8785 (JCS) canonicalised - Committed as `AX:PROOF:v1` with `proof_type = COMPLIANCE_SUMMARY` - Include the L6 chain head at time of report generation - Include the report hash in the ledger commitment --- ### 8.5 Report Independence **SRS-007-SHALL-027** A compliance report SHALL be independently verifiable by a third party holding only: - The report document - The public key for GPG anchor verification - Access to the public ledger or evidence set No additional context SHALL be required to verify the report's claims. --- ### 8.5.1 Evidence Closure Proof Requirement **SRS-007-SHALL-051** *Amended in v0.3 per F013.* Every compliance report SHALL include an **Evidence Closure Proof**: **Definition:** A Merkle root computed over all evidence records cited in the report, proving completeness of the evidence set. **Requirement:** ``` Report MUST include or commit to a complete evidence set sufficient for independent verification of all claims. ``` **Verification:** Merkle proof verification, completeness audit --- ### 8.5.2 Merkle Tree Construction Algorithm **SRS-007-SHALL-059** *Added in v0.3 per F013.* The Evidence Closure Merkle tree SHALL be constructed as follows: **Tree Structure:** Binary Merkle tree, left-balanced **Input:** Lexicographically sorted list of evidence hashes **Leaf Computation:** ``` leaf[i] = evidence_refs[i] (raw hash, no re-hash) ``` **Internal Node Computation:** ``` node = SHA-256(left_child ‖ right_child) ``` Where `‖` denotes byte-wise concatenation (64 bytes total input). **Odd Node Handling:** Duplicate the last node ``` If count(nodes) is odd: nodes.append(nodes[-1]) // duplicate last ``` **Tree Construction:** Left-to-right, bottom-up ``` Level 0: [leaf_0, leaf_1, leaf_2, leaf_3, ...] Level 1: [SHA-256(leaf_0 ‖ leaf_1), SHA-256(leaf_2 ‖ leaf_3), ...] ... Level N: [root] ``` **Empty Tree:** If `evidence_refs` is empty, root = 32 zero bytes **Example (4 leaves):** ``` root / \ H01 H23 / \ / \ L0 L1 L2 L3 ``` Where: - `L0..L3` = sorted evidence hashes - `H01 = SHA-256(L0 ‖ L1)` - `H23 = SHA-256(L2 ‖ L3)` - `root = SHA-256(H01 ‖ H23)` **Verification:** golden vector test, cross-platform harness --- ### 8.6 Golden Reference Inclusion **SRS-007-SHALL-028** All Track A compliance reports SHALL include the certifiable-harness 368-byte golden reference in the evidence package. **Purpose:** Proves the model running in production is byte-identical to the model that was audited and certified. **Verification:** certifiable-harness integration test --- ## 9. EXTERNAL ANCHOR PUBLICATION ### 9.1 Anchor Requirement **SRS-007-SHALL-029** The governance layer SHALL publish periodic cryptographic anchors to a public append-only transparency log. --- ### 9.2 Anchor Computation **SRS-007-SHALL-030** *Amended in v0.2 per F003.* The anchor hash SHALL be computed as: ``` anchor = SHA-256( "AX:ANCHOR:v1" ‖ LE64(anchor_time_seq) ‖ chain_head_hash ) ``` Where: - `anchor_time_seq` is the `ledger_seq` of the committed Time Oracle observation (`AX:OBS:v1` with `oracle.type = TIME_INJECTION`) - `chain_head_hash` is the current L6 chain head --- ### 9.2.1 Anchor Time as Oracle Input **SRS-007-SHALL-052** *Added in v0.2 per F003.* The timestamp used in anchor computation SHALL be: - Admitted as an `AX:OBS:v1` record with `oracle.type = TIME_INJECTION` - Committed to the L6 ledger before anchor computation - Referenced by `ledger_seq` in the anchor record **Rationale:** Time is an oracle input. Using raw `timestamp_ns` would introduce hidden external dependency, violating D2 determinism. **Anchor Record Extension:** | Field | Type | Description | |-------|------|-------------| | `anchor_time_seq` | uint64 | ledger_seq of Time Oracle AX:OBS:v1 | **Verification:** inspection, replay verification --- ### 9.3 Anchor Signing **SRS-007-SHALL-031** *Amended in v0.3 per F015.* Each anchor SHALL be: - GPG-signed with the published SpeyTech governance key - Published to the transparency log before the next anchor interval - Appended to `latest-anchor.txt` (append-only) --- ### 9.3.1 GPG Signature Determinism Boundary **SRS-007-SHALL-060** *Added in v0.3 per F015.* The GPG signature is an **external verification artefact** and SHALL NOT be part of the deterministic proof payload. **Determinism Boundary:** | Component | Deterministic | Role | |-----------|---------------|------| | `anchor` hash | ✅ YES | Canonical proof | | `AX:PROOF:v1` record | ✅ YES | Ledger commitment | | GPG signature | ❌ NO | External verification only | **Rationale:** GPG signatures are inherently non-deterministic due to: - Timestamp inclusion - Random nonce generation - Implementation-dependent formatting **Verification Model:** ``` 1. Deterministic anchor hash committed to L6 (reproducible) 2. GPG signature computed over anchor hash (non-reproducible) 3. Third-party verifies: signature → anchor hash → chain state ``` **The anchor hash is the canonical proof.** The signature is an external attestation of that proof. **Forbidden:** ``` ❌ GPG signature included in AX:PROOF:v1 payload ❌ GPG signature used in commitment computation ❌ Determinism claims about GPG output ``` **Verification:** inspection, replay verification (anchor hash only) --- ### 9.4 Anchor Commitment **SRS-007-SHALL-032** Each anchor publication SHALL be committed to the L6 ledger as `AX:PROOF:v1` with `proof_type = ANCHOR_PUBLICATION`. --- ### 9.5 Anchor Interval Declaration **SRS-007-SHALL-033** The anchor publication interval SHALL be: - Declared at system initialisation - Committed to the configuration manifest (SRS-001-SHALL-007) - Treated as a system change if modified **Verification:** inspection, configuration audit --- ### 9.6 Anchor Verification **SRS-007-SHALL-034** A third party holding only the public key and the transparency log SHALL be able to verify that the system state at any anchor point has not been subsequently modified. --- ## 10. INTEGRITY FAULT HANDLING ### 10.1 Integrity Fault Definition **SRS-007-SHALL-035** A Governance Integrity Fault occurs when: - Any cross-layer verification step (§6) produces `result = INTEGRITY_FAULT` - A policy is found non-conformant at initialisation - An evidence record fails hash verification - The ordering invariant (SRS-007-SHALL-018) is violated - A weight hash mismatch is detected (SRS-007-SHALL-013) --- ### 10.2 Integrity Fault Recording **SRS-007-SHALL-036** All Governance Integrity Faults SHALL be committed as `AX:PROOF:v1` records with: - `result = INTEGRITY_FAULT` - `violation` field identifying the fault type - `evidence_refs` citing the inconsistent evidence --- ### 10.3 Integrity Fault Response **SRS-007-SHALL-037** On Governance Integrity Fault: - The system SHALL transition L5 agent to `STOPPED` - No further compliance reports SHALL be generated - The fault SHALL be included in the next anchor publication - Recovery SHALL require explicit operator action --- ### 10.4 No Silent Governance Failure **SRS-007-SHALL-038** *Amended in v0.2 per F009.* No governance failure SHALL be silent. Every detected inconsistency SHALL produce a committed `AX:PROOF:v1` record. --- ### 10.4.1 Ledger Failure Mode **SRS-007-SHALL-053** *Amended in v0.3 per F018.* If the L6 ledger is in FAILED state and cannot accept commits: **Option A — Deterministic Fallback Log:** - Integrity fault SHALL be recorded to a bounded, canonical, append-only fallback log - Fallback log format SHALL be identical to `AX:PROOF:v1` - Fallback log SHALL be replayable and independently verifiable - Maximum fallback log size SHALL be declared at initialisation **Option B — System Halt:** - System SHALL halt with no further state mutation - `local_governance_fault_flag` SHALL be set - System SHALL remain in STOPPED state until explicit reset The deployment SHALL declare which option is used in the configuration manifest. **Forbidden:** ``` ❌ Non-persistent state ❌ Unverifiable fallback ❌ Silent failure ``` **Verification:** fault injection test, inspection --- ### 10.4.2 Fallback Log Overflow Behaviour **SRS-007-SHALL-061** *Added in v0.3 per F018.* If Option A (Deterministic Fallback Log) is selected, the overflow behaviour MUST be explicitly defined: **Option A.1 — Truncation with Marker:** - On overflow, stop appending new records - Write a single `OVERFLOW_MARKER` record as final entry - Set `local_governance_overflow_flag` - Transition to STOPPED state **Option A.2 — System Halt on Overflow:** - On overflow, halt immediately - No partial writes permitted - Set `local_governance_overflow_flag` - Remain in STOPPED state until explicit reset **Overflow Marker Record:** ```json { "claim": "FALLBACK_LOG_OVERFLOW", "evidence_ordering": "LEX", "evidence_refs": [], "proof_type": "INTEGRITY_FAULT", "result": "INTEGRITY_FAULT", "rule_id": "SRS-007-SHALL-061", "schema_version": "AX:PROOF:v1", "violation": "FALLBACK_OVERFLOW" } ``` **Forbidden:** ``` ❌ Undefined overflow behaviour ❌ Silent truncation without marker ❌ Wrap-around / circular buffer (loses evidence) ``` **Verification:** overflow injection test, state machine test --- ## 11. TRACEABILITY ### 11.1 Evidence Citation Requirement **SRS-007-SHALL-039** Every governance claim SHALL cite the specific committed evidence records that justify it. No governance assertion is valid without evidence citations. --- ### 11.2 Claim-to-Evidence Mapping **SRS-007-SHALL-040** The governance layer SHALL maintain a deterministic mapping: ``` Claim → Evidence Records → Verification Method → Result ``` This mapping SHALL be: - Independently recomputable - Committed as AX:PROOF:v1 - Included in compliance reports --- ### 11.3 SRS Traceability **SRS-007-SHALL-041** Every public governance function SHALL include SRS anchors per DVEC-001 v1.3 §9.2. --- ## 12. BOUNDEDNESS AND MEMORY ### 12.1 Bounded Execution **SRS-007-SHALL-042** *Amended in v0.3 per F016.* All governance operations SHALL execute in bounded time. For N evidence records: | Operation | Complexity | Notes | |-----------|------------|-------| | Cross-layer verification | O(N) | Linear scan of evidence chain | | Merkle tree construction | O(N) | Bottom-up construction | | Report generation | O(N) | Linear evidence aggregation | | Anchor computation | O(1) | Fixed-size hash computation | | Full chain replay | O(N × M) | N records, M policies per record | **Merkle Tree Complexity Clarification:** Binary Merkle tree construction over N leaves: - Tree height: ⌈log₂(N)⌉ - Total nodes: 2N - 1 - Hash operations: N - 1 (internal nodes only, leaves are raw) - Time complexity: O(N) - Space complexity: O(N) for tree storage, O(log N) for verification path **Replay Verification Complexity:** Full chain replay verification is O(N × M) where: - N = number of evidence records - M = average number of policy evaluations per record For systems with bounded M (e.g., M ≤ 10), this reduces to O(N). --- ### 12.2 Bounded Allocation Model **SRS-007-SHALL-043** *Amended in v0.2 per F004.* Governance operations SHALL use a **bounded allocation model**: **Option A — Fixed Maximum Sizes:** | Structure | Maximum Size | Declaration | |-----------|--------------|-------------| | `evidence_refs` array | 1024 entries | Compile-time constant | | Mathematical Trace | 4096 bytes | Compile-time constant | | Compliance report | 1 MiB | Configuration manifest | | Fallback log | 64 KiB | Configuration manifest | **Option B — Caller-Provided Buffers:** All governance functions accepting variable-length output SHALL: - Accept caller-provided buffer with explicit capacity - Return error if capacity exceeded - Never allocate internally **Forbidden:** ``` ❌ malloc / realloc / free in runtime paths ❌ Unbounded growth ❌ Implicit allocation ``` **Verification:** static analysis, buffer overflow test --- ## 13. PHASE 7 CLOSURE CRITERIA Phase 7 is complete when: ### 13.1 Proof Model - [ ] AX:PROOF:v1 records committed for all verification steps - [ ] Cryptographic binding fields implemented (proof_hash, commitment, prev_chain_head) - [ ] Policy soundness verified for all active policies - [ ] Evidence closure confirmed ### 13.2 Cross-Layer Verification - [ ] All 8 verification steps implemented - [ ] Proof-before-execution invariant enforced - [ ] Each step produces conformant AX:PROOF:v1 - [ ] Integrity fault detection operational ### 13.3 Compliance Reports - [ ] Track A evidence package generated - [ ] Track B evidence package generated - [ ] Evidence closure proof included - [ ] Reports independently verifiable - [ ] Golden reference included in Track A ### 13.4 External Anchoring - [ ] GPG key published - [ ] Transparency log operational - [ ] Anchor time bound to Time Oracle - [ ] Anchor computation verified - [ ] Anchor interval declared and committed ### 13.5 Mathematical Traces - [ ] Full trace produced per inference event - [ ] Trace fields complete, canonical, and properly encoded - [ ] Trace hash included in AX:PROOF:v1 - [ ] Traces committed as AX:PROOF:v1 ### 13.6 Memory Model - [ ] Bounded allocation model declared - [ ] Maximum sizes documented - [ ] No runtime malloc in governance paths --- ## 14. REQUIREMENT SUMMARY | ID | Requirement | Section | |----|-------------|---------| | SRS-007-SHALL-001 | Determinism definition | 3.2 | | SRS-007-SHALL-002 | Evidence closure | 3.3 | | SRS-007-SHALL-003 | Proof commitment | 4.1 | | SRS-007-SHALL-004 | AX:PROOF:v1 required fields | 4.2 | | SRS-007-SHALL-005 | Proof type closed set | 4.3 | | SRS-007-SHALL-006 | Evidence reference requirement | 4.4 | | SRS-007-SHALL-007 | Canonical format | 4.5 | | SRS-007-SHALL-008 | Policy soundness | 5.1 | | SRS-007-SHALL-009 | Policy violation | 5.2 | | SRS-007-SHALL-010 | Policies as programs | 5.3 | | SRS-007-SHALL-011 | Verification chain | 6.1 | | SRS-007-SHALL-012 | L1 substrate certification | 6.2 | | SRS-007-SHALL-013 | L2 weight binding | 6.3 | | SRS-007-SHALL-014 | L3 observation integrity | 6.4 | | SRS-007-SHALL-015 | L4 policy soundness | 6.5 | | SRS-007-SHALL-016 | L3→L4 obs-policy binding | 6.6 | | SRS-007-SHALL-017 | L4→L5 breach enforcement | 6.7 | | SRS-007-SHALL-018 | L5→L6 pre-commit ordering | 6.8 | | SRS-007-SHALL-019 | Full chain replay | 6.9 | | SRS-007-SHALL-020 | Mathematical trace requirement | 7.1 | | SRS-007-SHALL-021 | Trace required fields | 7.2 | | SRS-007-SHALL-022 | Trace canonicality | 7.3 | | SRS-007-SHALL-023 | Track A evidence package | 8.1 | | SRS-007-SHALL-024 | Track B evidence package | 8.2 | | SRS-007-SHALL-025 | Report trigger conditions | 8.3 | | SRS-007-SHALL-026 | Report canonical format | 8.4 | | SRS-007-SHALL-027 | Report independence | 8.5 | | SRS-007-SHALL-028 | Golden reference inclusion | 8.6 | | SRS-007-SHALL-029 | Anchor requirement | 9.1 | | SRS-007-SHALL-030 | Anchor computation | 9.2 | | SRS-007-SHALL-031 | Anchor signing | 9.3 | | SRS-007-SHALL-032 | Anchor commitment | 9.4 | | SRS-007-SHALL-033 | Anchor interval declaration | 9.5 | | SRS-007-SHALL-034 | Anchor verification | 9.6 | | SRS-007-SHALL-035 | Integrity fault definition | 10.1 | | SRS-007-SHALL-036 | Integrity fault recording | 10.2 | | SRS-007-SHALL-037 | Integrity fault response | 10.3 | | SRS-007-SHALL-038 | No silent governance failure | 10.4 | | SRS-007-SHALL-039 | Evidence citation requirement | 11.1 | | SRS-007-SHALL-040 | Claim-to-evidence mapping | 11.2 | | SRS-007-SHALL-041 | SRS traceability | 11.3 | | SRS-007-SHALL-042 | Bounded execution | 12.1 | | SRS-007-SHALL-043 | Bounded allocation model | 12.2 | | SRS-007-SHALL-044 | Configuration canonicality | 3.2.1 | | SRS-007-SHALL-045 | Cryptographic binding fields | 4.2.1 | | SRS-007-SHALL-046 | Evidence reference encoding | 4.4.1 | | SRS-007-SHALL-047 | Proof-before-execution invariant | 6.1.1 | | SRS-007-SHALL-048 | Weight hash specification | 6.3.1 | | SRS-007-SHALL-049 | Trace array ordering | 7.2.1 | | SRS-007-SHALL-050 | Trace hash computation | 7.2.2 | | SRS-007-SHALL-051 | Evidence closure proof | 8.5.1 | | SRS-007-SHALL-052 | Anchor time as oracle | 9.2.1 | | SRS-007-SHALL-053 | Ledger failure mode | 10.4.1 | **Total: 53 SHALL requirements** --- ## 15. LAYER INTEGRATION SUMMARY | Layer | Role | SRS | |-------|------|-----| | L7 | Accountability — what can be proven | SRS-007 | | L6 | Truth — what happened | SRS-001 | | L5 | Behaviour — what to do | SRS-002 | | L4 | Admissibility — what is allowed | SRS-003 | | L3 | Containment — what was observed | SRS-004 | | L2 | Identity — what the model computed | SRS-005 (via certifiable-inference) | | L1 | Mathematics — what is provable | SRS-005 | **Full Stack Invariant:** ``` L1 (arithmetic law) → L2 (deterministic inference) → L3 (contained observation) → L4 (policy gate) → L5 (bounded behaviour) → L6 (cryptographic truth) → L7 (governance proof) ``` No layer can produce an undetected lie without breaking the chain. --- ## 16. COMPLETE SRS STACK | Document | Layer | SHALL Count | Status | |----------|-------|-------------|--------| | SRS-001 | L6 Substrate | 29 | Audit-Frozen | | SRS-002 | L5 Agent | 29 | Audit-Frozen | | SRS-003 | L4 Policy | 22 | Audit-Frozen | | SRS-004 | L3 Oracle | 48 | Audit-Frozen | | SRS-005 | L1 Arithmetic | 70 | Audit-Frozen | | SRS-007 | L7 Governance | 53 | Audit-Frozen | | **Total** | | **251** | | --- ## 17. FINAL STATEMENT The governance layer SHALL: > Produce cryptographically evidenced proofs that the system > behaved correctly — not assertions that it did. **System Property:** > No layer can behave differently without producing different > evidence. No evidence can be falsified without breaking the > cryptographic chain. No chain can be broken without governance > detecting and recording the fault. **The Axioma Governance Theorem:** > A system governed by Axioma L7 cannot certify incorrect > behaviour — it can only certify correct behaviour or declare > a governance integrity fault. --- ## 18. REVISION HISTORY | Version | Date | Author | Changes | |---------|------|--------|---------| | 0.1 | 2026-03-27 | William Murray | Initial draft — 43 SHALL requirements | | 0.2 | 2026-03-27 | William Murray | Audit closure — 10 new SHALLs (044–053). Added cryptographic binding fields, evidence encoding spec, proof-before-execution invariant, weight hash spec, trace encoding/ordering, evidence closure proof, anchor time oracle binding, ledger failure mode, configuration canonicality. Total: 53 SHALL requirements. | | 0.3 | 2026-03-27 | William Murray | Final audit closure — 8 new SHALLs (054–061). Fixed proof_hash canonical treatment (field omission), payload encoding byte semantics, Merkle tree algorithm specification, evidence ordering structured field, GPG signature determinism boundary, atomicity model, complexity bounds, fallback overflow behaviour, proof type versioning. Total: 61 SHALL requirements. | --- ## 19. DOCUMENT APPROVAL | Role | Name | Date | Signature | |------|------|------|-----------| | Author | William Murray | 2026-03-27 | | | Reviewer | | | | | Approver | | | | --- ## Appendix A — Audit Record (v0.1 → v0.2) | Finding ID | Severity | Resolution | |------------|----------|------------| | F001 | 🔴 BLOCKING | SRS-007-SHALL-045: Added proof_hash, commitment, prev_chain_head | | F002 | 🔴 BLOCKING | SRS-007-SHALL-046: Evidence refs SHA-256, hex lowercase, ordered | | F003 | 🔴 BLOCKING | SRS-007-SHALL-052: Anchor time bound to Time Oracle AX:OBS:v1 | | F004 | 🔴 BLOCKING | SRS-007-SHALL-043: Replaced with bounded allocation model | | F005 | 🟠 HIGH | SRS-007-SHALL-047: Proof-before-execution invariant | | F006 | 🟠 HIGH | SRS-007-SHALL-049, 050: Trace encoding, ordering, hash | | F007 | 🟠 HIGH | SRS-007-SHALL-051: Evidence closure proof (Merkle root) | | F008 | 🟡 MEDIUM | SRS-007-SHALL-048: Weight hash canonical specification | | F009 | 🟡 MEDIUM | SRS-007-SHALL-053: Deterministic ledger failure mode | | F010 | 🔵 LOW | SRS-007-SHALL-044: Configuration canonicality | **Audit Source:** External review **Audit Date:** 27 March 2026 **Audit Verdict:** All findings resolved. Document elevated to **Audit-Frozen**. --- ## Appendix B — Cross-Reference to Audit Findings | SHALL | Audit Finding | Description | |-------|---------------|-------------| | SHALL-043 | F004 | Bounded allocation replaces zero-allocation | | SHALL-044 | F010 | Policy/config canonicalisation | | SHALL-045 | F001 | Cryptographic binding fields | | SHALL-046 | F002 | Evidence reference encoding | | SHALL-047 | F005 | Proof-before-execution | | SHALL-048 | F008 | Weight hash specification | | SHALL-049 | F006 | Trace array ordering | | SHALL-050 | F006 | Trace hash computation | | SHALL-051 | F007 | Evidence closure proof | | SHALL-052 | F003 | Anchor time as oracle | | SHALL-053 | F009 | Ledger failure mode | --- ## Appendix C — Conformance Status | Category | v0.1 | v0.2 | v0.3 | |----------|------|------|------| | Determinism | ❌ FAIL | ⚠️ PARTIAL | ✅ PASS | | Totality | ❌ FAIL | ⚠️ PARTIAL | ✅ PASS | | Cross-platform safety | ❌ FAIL | ⚠️ PARTIAL | ✅ PASS | | SRS alignment | ❌ FAIL | ✅ PASS | ✅ PASS | | Evidence closure | ❌ FAIL | ⚠️ PARTIAL | ✅ PASS | | Cryptographic binding | ❌ FAIL | ⚠️ PARTIAL | ✅ PASS | --- ## Appendix D — Audit Record (v0.2 → v0.3) | Finding ID | Severity | Resolution | |------------|----------|------------| | F011 | 🔴 BLOCKING | SRS-007-SHALL-045 amended: proof_hash field omitted (not empty/null) | | F012 | 🔴 BLOCKING | SRS-007-SHALL-054: Payload encoding byte semantics defined | | F013 | 🔴 BLOCKING | SRS-007-SHALL-059: Merkle tree algorithm fully specified | | F014 | 🟠 HIGH | SRS-007-SHALL-057: Structured evidence_ordering field | | F015 | 🟠 HIGH | SRS-007-SHALL-060: GPG signature determinism boundary | | F016 | 🟠 HIGH | SRS-007-SHALL-042 amended: Complexity bounds corrected | | F017 | 🟡 MEDIUM | SRS-007-SHALL-058: Atomicity model for proof-before-execution | | F018 | 🟡 MEDIUM | SRS-007-SHALL-061: Fallback log overflow behaviour | | F019 | 🔵 LOW | SRS-007-SHALL-056: Proof type versioning mechanism | **Audit Source:** GPT-4o external review **Audit Date:** 27 March 2026 **Audit Verdict:** All findings resolved. Document elevated to **Audit-Frozen FINAL**. --- ## Appendix E — Cross-Reference to v0.3 Audit Findings | SHALL | Audit Finding | Description | |-------|---------------|-------------| | SHALL-045 | F011 | proof_hash canonical treatment (omit field) | | SHALL-054 | F012 | Commitment payload encoding (UTF-8 bytes) | | SHALL-055 | — | Chain head reference (completeness) | | SHALL-056 | F019 | Proof type versioning mechanism | | SHALL-057 | F014 | Evidence ordering structured field | | SHALL-058 | F017 | Atomicity model | | SHALL-059 | F013 | Merkle tree construction algorithm | | SHALL-060 | F015 | GPG signature determinism boundary | | SHALL-061 | F018 | Fallback log overflow behaviour | --- *SRS-007 v0.3 — Audit-Frozen FINAL* *William Murray · SpeyTech · March 2026* *Patent GB2521625.0* ======================================================================== PART III — INSIGHTS ======================================================================== ======================================================================== Proof-carrying governance, in one paragraph ======================================================================== Document: Insight Title: Proof-carrying governance, in one paragraph Subtitle: What L7 of the Axioma framework actually does, and why a regulator gets a proof instead of an audit log. Author: William Murray Affiliation: SpeyTech Published: 2026-05-15 Topic: Governance Defines: Proof-carrying governance Related specs: SRS-007, SRS-001, DVEC-001, AXIOMA-FRAMEWORK URL: https://axilog.io/insights/proof-carrying-governance/ Q: What is Proof-carrying governance, and why does it matter? A: Proof-carrying governance is a deterministic program over cryptographically committed evidence that produces independently verifiable compliance claims, replacing the auditor-reads-the-log model with a recomputable proof a regulator can run themselves and reach the identical verdict, byte for byte, anywhere it runs, with no further trust required in the operator. Proof-carrying governance turns a compliance claim into a deterministic program a regulator can run themselves and reach the identical verdict. That sentence is short on purpose. Everything below explains why the framework's L7 is built around it and what changes the moment governance stops being a document and starts being a proof. ## The shape of the problem Most software governance pipelines end at an audit log. Logs are evidence the system *thinks* it behaved correctly. The auditor reads the log, asks for clarifications, walks through reproducibility caveats, and eventually signs something. The chain of trust is human attention plus narrative reconstruction. It works, mostly, until something is contested. Then the asymmetry shows: the operator has access to the system, the regulator has access to the document. Determinism alone does not close that gap. A bit-identical replay of L1–L6 proves what the system did. It does not prove the system did the *correct* thing under a stated policy. That step — from "this is what happened" to "this satisfies the rule we agreed on" — is what L7 specifies.
Definition: Proof-carrying governance

Proof-carrying governance is a deterministic program over committed evidence that produces a cryptographically verifiable claim about whether a stated policy was satisfied. The proof is independently recomputable: any party with the evidence and the policy reaches the identical verdict, byte for byte.

## What the layer below provides L7 is the topmost layer of the Axioma framework, and it composes on what L1 through L6 already commit. The substrate (L1) hashes deterministically. The state machine (L2) emits health events with no fault-propagation ambiguity. The Oracle Boundary (L3) marks every entry of non-determinism with a typed admission record. Policy evaluation (L4) records every admit/deny decision against the operational envelope. The agent surface (L5) gates actions. The audit ledger (L6) commits the whole sequence to a Merkle structure with bit-identical replay. By the time L7 looks at the trace, it is reading a sequence of cryptographically committed records, each one referring to the previous by hash. Nothing it sees is reconstructed; everything is cited. That changes what governance can look like. Instead of "did this system satisfy the policy", the question becomes "does this policy, evaluated as a program over these specific records, return true". Same input, same policy, same result, anywhere it runs. ## What a proof actually is The framework calls the canonical record `AX:PROOF:v1`. Its construction is mechanical: take the policy as a deterministic program, take the evidence as a set of L6 ledger citations, evaluate the program over the citations, commit the result. The output is a tamper-evident proof chain that any reader can recompute. There are two things worth highlighting about the construction. First, the policy is a program, not prose. A "must not exceed N watts during inference" policy is a function that reads the L6-committed power-trace evidence and returns a boolean. A reviewer can disagree with the policy, but they cannot disagree with whether the policy returned true or false on the evidence — that is a numerical fact, recomputable by anyone with the evidence and the policy source. Second, the proof is a citation, not a copy. The evidence is committed to L6; the proof references it by hash. The proof package is small even when the evidence is large, and it does not require trusting the operator's reproduction of the logs. The regulator pulls the L6 commitments directly, runs the policy, and confirms the verdict. ## What this replaces The behaviour replaced is the audit-log walkthrough. In the old model, the operator hands over logs and a written compliance argument; the regulator reads both and forms a judgement. The integrity of the conclusion depends on the regulator's attention and on the operator's honest reconstruction of the trace. There is no protocol for "you and I disagree on what the logs say" — only for "we disagree on what they mean". With proof-carrying governance the disagreement surface narrows. The logs are committed, so there is no question about what they say. The policy is a program, so there is no question about what it means. The verdict is the program's return value. What can still be contested — and this matters — is whether the policy was the right policy. That is a legitimate disagreement and one that audit trails have always struggled to support. The proof structure makes it the *only* available disagreement. ## Where this is hard Two places. First, policies have to be expressible as deterministic programs. "Behave reasonably" does not survive the translation. "Total inference budget per session does not exceed B" does. Some real-world regulations have wording that is genuinely ambiguous, and the work of writing them as programs is real engineering. The framework does not pretend otherwise. Second, the evidence has to be committed in a form the policy can read. If a regulator wants to check that a model never produced output in a forbidden class, the output stream has to be in L6. If the output stream is summarised before commitment, the proof loses fidelity. The discipline is to commit raw evidence and let the policy program perform any aggregation. Both problems are tractable. Neither disappears. ## Why determinism is non-negotiable here A non-deterministic governance program is not a proof. If running the same program over the same evidence can return different verdicts, the verdict is not a fact — it is a sample from a distribution. The whole construction collapses. The Axioma framework's substrate (L1) and arithmetic primitives (SRS-005) exist for exactly this reason: every operation that touches the proof has to produce the same bits on every platform that recomputes it. Fixed-point arithmetic, deterministic reduction order, canonicalised serialisation. Without those guarantees, the regulator's recomputation diverges from the operator's, and the conclusion is no longer independently verifiable. This is the link between proof-carrying governance and the rest of the framework. L7 is not a separate concern bolted on top; it is what L1–L6 were built to support. ## Frequently Asked Questions ### What is proof-carrying governance? Proof-carrying governance is a deterministic program over cryptographically committed evidence that produces an independently verifiable compliance verdict. The verdict is the program's return value. Anyone with the evidence and the policy can recompute the same result, byte for byte. Disagreement collapses onto whether the policy was correctly stated, not whether the verdict follows. ### How is a proof-carrying claim different from a signed audit log? A signed audit log proves the log was not tampered with; a proof-carrying claim proves the policy returned true on the log. Signature attests to integrity. Proof attests to satisfaction. A regulator with a signed log still has to read it and form a judgement. A regulator with a proof recomputes the verdict. ### Why doesn't a regulator just rerun the model? Rerunning the model proves reproducibility, not policy compliance. The framework's L1–L6 already give bit-identical replay; that is execution integrity. Proof-carrying governance is the additional step that says "and the policy returns true over this trace". A regulator who reruns the model and reads the output still needs a verdict step; the proof is that step. ### What kinds of policies can be expressed this way? Any policy that is a deterministic function of committed evidence. Resource budgets, output-class constraints, sequencing rules, and threshold conditions all translate cleanly. Subjective policies — "the system behaved reasonably" — do not. The forcing of policies into program form is the source of much of the value: ambiguity has to be resolved before the proof can be constructed. ### What happens when the policy is wrong? The proof still recomputes correctly; the verdict is still a fact about the policy as written. The disagreement moves upstream, to whether the policy as written captures the regulator's intent. That disagreement is real and the framework does not pretend to dissolve it. It does isolate it from every other failure mode an audit trail can host. ## Conclusion Proof-carrying governance replaces the assertion-and-document model with a deterministic verdict any reader can recompute. The constraint is real: policies have to be expressible as programs, and evidence has to be committed in a form the program can read. As with any architectural approach, suitability depends on system requirements, risk classification, and regulatory context. ======================================================================== PART IV — ROADMAP ======================================================================== The forward plan for the Axioma framework and the axilog.io substrate. Items are grouped by horizon (near, mid, long). Status values: Active (in flight), Planned (committed but not started), Researching (open question), Deferred (rationally postponed), Completed (shipped — kept as audit trail). The roadmap deliberately carries no delivery dates; calendar discipline is separate from roadmap discipline. ======================================================================== Horizon: Near horizon ======================================================================== ======================================================================== NLnet NGI Zero Commons Fund — Application & Submission ======================================================================== Document: Roadmap item Title: NLnet NGI Zero Commons Fund — Application & Submission Horizon: near Status: Active Scope: Funding Related specs: DVEC-001 URL: https://axilog.io/roadmap/#nlnet-ngi-zero-commons-fund Rationale: Independent grant funding for the Axioma stack and axilog.io substrate, targeting the June or August 2026 application windows. NGI Zero Commons Fund explicitly funds infrastructure-of-commons projects under the EU Next Generation Internet programme; ~€30-40K, no match funding requirement, UK sole trader eligible. Unlocks paid time for the verification work (Calibration axis research, traceability matrices) that currently runs at evenings-and-weekends pace. Blockers: - Completion of remaining Axioma L0/L7 elements (Phase 1 reference implementation) - axilog.io public surface at grant-review quality (M5 close cleared the document-artefact gate; M6 closes the strategic-document gate) ======================================================================== L0 Epistemic Containment Layer — Phase 1 Reference Implementation ======================================================================== Document: Roadmap item Title: L0 Epistemic Containment Layer — Phase 1 Reference Implementation Horizon: near Status: Planned Scope: L0 Related specs: SRS-EC-001, DVEC-001 URL: https://axilog.io/roadmap/#l0-phase-1-implementation Rationale: Full C99 reference implementation of L0-SPEC-001 v1.3-LOCKED, conforming to all 11 SRS-EC-SHALL requirements. Phase 0 (specification freeze + golden vectors) cleared at M5 close with 11/11 golden vectors generated. Phase 1 produces the bit-identical executable that bounds regime-classification leakage in epistemically active systems — the orthogonal axis to L1-L7 determinism. Blockers: - Independent of SRS-CAL-001 (shipped at Draft in M8). The two specs now iterate together: L0 Phase 1 implementation surfaces lived experience that may refine SRS-CAL-001 toward Final. ======================================================================== AGPL-3.0 License Migration Across the Axioma Stack ======================================================================== Document: Roadmap item Title: AGPL-3.0 License Migration Across the Axioma Stack Horizon: near Status: Active Scope: Governance URL: https://axilog.io/roadmap/#agpl-license-migration Rationale: Migrate every layer of the Axioma stack (L1-L7 plus L0) and the supporting libraries to AGPL-3.0 with CLA infrastructure for inbound contributions. Replaces the current mixed licence state with a single audit-stable governance contract aligned to NLnet funding requirements and to the project's commons commitment. Currently active across the stack; seven open PRs from Brian Shirai held pending licence and CLA finalisation. ======================================================================== Calibration Axis — Formal Specification (Draft) ======================================================================== Document: Roadmap item Title: Calibration Axis — Formal Specification (Draft) Horizon: near Status: Active Scope: Foundation Related specs: DVEC-001, SRS-EC-001, SRS-CAL-001 URL: https://axilog.io/roadmap/#calibration-axis Rationale: Introduce a Calibration axis to the framework, orthogonal to L1-L7 in the same architectural register as the L0 Epistemic Containment Layer. Where L0 bounds regime-classification leakage, the Calibration axis bounds the confidence-mismatch dimension: when a deterministic system declares a probability or a tolerance, the formal contract under which that declared figure tracks measured reality. SRS-CAL-001 ships at v1.0-DRAFT in M8; the contract shape was clear enough to formalise independently of L0 Phase 1, with the Draft status as the audit-stable midpoint between research and final. Upgrade to Final scheduled for M9 after evaluation against L0 Phase 1 in practice. Blockers: - M9: evaluation of SRS-CAL-001 v1.0-DRAFT against L0 Phase 1 reference implementation, with iteration on the contract shape if lived experience surfaces gaps ======================================================================== Horizon: Mid horizon ======================================================================== ======================================================================== Unified Compliance Traceability Matrices (DO-178C, IEC 62304, ISO 26262) ======================================================================== Document: Roadmap item Title: Unified Compliance Traceability Matrices (DO-178C, IEC 62304, ISO 26262) Horizon: mid Status: Planned Scope: Compliance Related specs: DVEC-001, SRS-EC-001 URL: https://axilog.io/roadmap/#unified-compliance-traceability Rationale: Produce auditor-grade traceability matrices mapping every SHALL across the Vault to its target standards: DO-178C objectives (aerospace), IEC 62304 software lifecycle clauses (medical), and ISO 26262 ASIL clauses (automotive). Builds on the M4 canonical compliance taxonomy and per-spec frontmatter declarations. The matrices are the gating artefact for any downstream audit and the strongest evidence a grant reviewer can ask for that the framework's compliance claims are not aspirational. Blockers: - All in-scope specs need finalised `compliance` frontmatter (currently 7 of 15 declared) ======================================================================== Archival & Cryptographic PDF Hardening (PDF/A, Digital Signatures) ======================================================================== Document: Roadmap item Title: Archival & Cryptographic PDF Hardening (PDF/A, Digital Signatures) Horizon: mid Status: Researching Scope: Infrastructure URL: https://axilog.io/roadmap/#pdf-archival-hardening Rationale: Upgrade the per-spec PDF pipeline from production-grade documentation artefact (M5 ship state) to audit-grade archival artefact: PDF/A-2b or PDF/A-3 conformance for long-term preservation, plus cryptographic signing so each PDF carries a verifiable provenance claim. PDF/A requires colour-mode and font-embedding restrictions plus ghostscript or veraPDF post-processing; signing requires key infrastructure that does not yet exist. Both target the same downstream auditor and share the build pipeline. Blockers: - PDF signing key infrastructure (HSM or equivalent — currently no key custody plan) ======================================================================== Framework Discovery & Auditing UX (Search, Changelogs, Provenance) ======================================================================== Document: Roadmap item Title: Framework Discovery & Auditing UX (Search, Changelogs, Provenance) Horizon: mid Status: Completed Scope: Infrastructure URL: https://axilog.io/roadmap/#framework-discovery-ux Rationale: Made the Vault navigable as a corpus rather than as N individual documents. Shipped at M7 (May 2026): Pagefind WASM-indexed full-text search at /search/, per-spec changelog routes at /specs//changelog/ surfacing frontmatter revision history as first-class audit-trail pages, and /provenance/ documenting the full source → artefact lineage for every published surface. Search threshold (20+ indexable documents) cleared by the per-spec changelog routes themselves; the discovery surface and the substance it indexes shipped in the same milestone. ======================================================================== Horizon: Long horizon ======================================================================== ======================================================================== mycoeco pbas7 Kernel — Open-Source Release ======================================================================== Document: Roadmap item Title: mycoeco pbas7 Kernel — Open-Source Release Horizon: long Status: Deferred Scope: Tooling URL: https://axilog.io/roadmap/#mycoeco-pbas7-release Rationale: Public release of the mycoeco pbas7 kernel — the soil-ecology inference substrate that motivated the Murray Deterministic Computing Platform's original observations on mycorrhizal-network signalling. Rationally deferred: Axioma is the priority project until the L0/L7 elements complete and the grant submission lands. The pbas7 kernel's polish budget is queued behind that work, not abandoned, and the deferral is recorded here so the project resurfaces on schedule rather than by accident. Blockers: - Axioma stack completion (L0 Phase 1, L7 final close) - NLnet submission cycle complete ======================================================================== PART V — ABOUT & PROVENANCE ======================================================================== ======================================================================== About — the framework, the maintainer, and how this is funded ======================================================================== Document: About page URL: https://axilog.io/about/ Mission ------- Axioma is the verifiable AI execution layer for regulated industries — deterministic where possible, governed where not, cryptographically provable everywhere. The framework spans seven layered contracts (L1 through L7) plus an orthogonal Epistemic Containment Layer (L0), all governed by a foundation contract (DVEC-001). The substrate, the specifications, and the reference implementations are published openly so that the system's behaviour is reviewable by any auditor, integrator, or regulator who needs to verify rather than trust. The framework targets safety-critical and regulated deployments under DO-178C, IEC 62304, ISO 26262, IEC 61508, MISRA-C:2012, and the EU AI Act. The published material on this site is the open specification; commercial integration, conformance support, and certified-build services run through Spey Systems Ltd separately. Maintainer ---------- Axioma is built and maintained by William Murray, a UNIX infrastructure engineer of thirty years' standing, founder and director of Spey Systems Ltd in Inverness, Scotland (trading as SpeyTech). The framework's origins are in the Murray Deterministic Computing Platform, covered by two UK patents (GB2521625.0 and GB2522369.4) assigned to Spey Systems Ltd — a deterministic computing stack developed over the past decade for safety-critical aerospace, medical, and automotive domains. William holds a Visiting Scholar affiliation with Heriot-Watt University (research correspondence on inter-plant signalling and structurally-deterministic analogues) and an active research relationship with a US space-systems organisation working on safety-critical kernel variants. The Axioma framework is bootstrapped entirely under Spey Systems Ltd; no external salary, institutional funding, or commercial investment supports its development at the time of writing. Licensing --------- The Axioma specifications and reference implementations are published under AGPL-3.0-or-later. The choice is deliberate: AGPL-3.0 is the strongest reciprocity copyleft in the GNU family and is the right licence for an infrastructure framework that must remain commons-bound across both source distribution and network-mediated service deployment. Documentation and specification prose are released under CC-BY-SA-4.0. The full licensing position, including the AGPL §11 patent grant covering the two MDCP patents, lives at https://axilog.io/licence/. External contributions are accepted under a Contributor Licence Agreement (CLA) ensuring contributors retain copyright while granting Spey Systems Ltd the rights necessary to relicense the corpus if the framework's commons obligations ever require it. Funding ------- Axioma is bootstrapped under Spey Systems Ltd. No commercial investment, institutional grant, or external salary supports the framework's development at the time of writing. All assets — the specifications, the reference implementations, the substrate library, the two MDCP patents, the speytech.com and axilog.io domains, the GitHub organisation — sit under Spey Systems Ltd. An application to the NLnet NGI Zero Commons Fund is in preparation for the 2026 application window. Future awards, contracts, or institutional funding will be acknowledged on the about page in the order they're received. The site itself runs on a small VM under Spey Systems Ltd; no advertising, no tracking beyond self-hosted Umami analytics (cookieless, no PII forwarded). The framework's commons commitment extends to the publishing infrastructure. Acknowledgements ---------------- Axioma carries technical and editorial debt to: - Academic correspondents at Heriot-Watt University whose inter-plant signalling research informed early thinking on structurally-deterministic analogues. - Commercial collaborators in the safety-critical kernel deployment space who reviewed early framework drafts against production constraints. - US space-systems engineers working through corporate release-review processes for space-hardened kernel variants. - The maintainers of every upstream dependency the framework and its substrate rely on, named individually in the relevant project repositories. Named individual acknowledgements are added only with explicit consent. ======================================================================== Provenance — the audit map ======================================================================== Document: Provenance page URL: https://axilog.io/provenance/ Verified at: 2026-05-15 (against build.sh) For every published artefact on axilog.io: where the source of truth lives, which build step produces it, and what verification check gates it. The Axioma framework's claim is verifiability; the provenance page is the evidence map that backs that claim. Build pipeline -------------- The deploy is orchestrated by a single shell script, build.sh, which executes the steps below in order. Each step is gated: abort-deploy (failure prevents the atomic swap), rollback (failure swaps the previous build back in), or informational (failure logged but deploy continues). 1. Compliance frontmatter lint [abort-deploy] Invokes: scripts/compliance_lint.js Produces: Verified resolution of every spec's `compliance` frontmatter array against the canonical taxonomy at src/lib/compliance-taxonomy.ts. Detail: Walks every spec markdown file, extracts the compliance array, and verifies each value resolves to a canonical entry (matching id, displayName, or any alias). Runs before any rendering so unresolved values surface as data errors rather than as silent 404s on /compliance// pages. The taxonomy module is the single source of truth; adding a new standard requires adding a canonical entry there. 2. AEO frontmatter lint [abort-deploy] Invokes: scripts/aeo_lint.js Produces: Verified `defines` and `answers` fields on every insight; Definition-block linter check for core concepts. Detail: Scoped to src/content/insights/ — specs are SHALL-bound formal prose and would fire false positives on every check. The linter enforces the AEO contract: every insight that defines a CORE_CONCEPT must include that concept verbatim in body text, and every insight must provide a 40–60-word `answers` field for llms-full.txt extraction. 3. Changelog drift check [informational] Invokes: scripts/changelog_drift_check.js Produces: Warning report comparing each spec's git mtime against its frontmatter changelog's newest entry date. Detail: Per-spec, runs `git log -1 --format=%aI` against the file and compares against the maximum date in the frontmatter `changelog` array. Drift beyond one day surfaces as a build-log warning. Skipped (with explicit warning) on shallow clones — `git rev-parse --is-shallow-repository` returning `true` means the file-mtime data would be the shallow ceiling, producing false positives across the corpus. 4. Astro static build [abort-deploy] Invokes: npx astro build --outDir ./dist.new Produces: The full static site under dist.new/: HTML for every route, the JSON-LD blocks, sitemap.xml, dynamic llms.txt and llms-full.txt, the compressed CSS and JS bundle. Detail: Output is written to dist.new/ rather than dist/ — the live build is untouched until the atomic swap step succeeds. Build into a staging directory means an Astro failure (broken schema, missing import, malformed markdown) leaves the production deploy intact. 5. Per-spec OG card generation [abort-deploy] Invokes: scripts/generate-og-cards.mjs Produces: 15 PNG images at dist.new/og/specs/.png, each ~1200×630 with the spec id, title, layer pill, and dclass pill rendered from the brand woff2 fonts via the woff2→wawoff2→TTF→resvg pipeline. Detail: Pre-decompresses Inter Variable and JetBrains Mono Variable from woff2 to TTF (resvg-js does not natively decompress woff2; see operational lesson #23). Composes SVG with inline presentation attributes per text element (resvg