AI is changing how we develop software. Coding agents can analyse unfamiliar codebases, generate implementations, construct tests, investigate bugs and write technical reports. But increasing the speed of software development raises a more fundamental question: how can we establish that the software produced is correct?
In my recent work on Cardano networking, I have been exploring how AI and mechanised formal methods can complement one another. Rather than using AI only as a coding assistant, I have used it to drive code analysis, modelling, implementation, investigation and reporting, with a mechanised CSP library in Agda as part of its working context.
This experience motivates a broader idea: a reusable engineering workflow in which AI accelerates development while formal models, proofs, executable tests and runtime evidence establish the grounds for trusting the software.
AI proposes; formal methods verify; execution provides evidence; humans govern.
I will call this approach AI-driven formal software engineering (AI-FSE). It is a proposed methodology, not a claim that the complete framework already exists or that the software discussed here has been fully verified.
1. Starting from practical engineering work
My current exploration is centred on three branches of the agda-cardano-common repository:
| Branch | Focus in the wider workflow |
|---|---|
| Cardano network CSP model | Formalise the behaviour of networking protocols. |
| Trace replay checker | Relate observed executions to formal models. |
| Connection Manager | Understand and model a complex concurrent implementation. |
These efforts build on csp-ptree-agda, a mechanised CSP foundation based on process trees in Agda. By bringing this library into the AI agent's context, I can work with a shared mathematical vocabulary instead of asking the agent to invent a new modelling formalism for every task.
The interesting question is no longer simply whether AI can write Agda or Haskell code. It is whether these activities can be organised into a reliable workflow that other developers can reproduce and reuse on different systems.
2. Beyond AI-assisted coding
A conventional AI-assisted workflow starts with a requirement, generates code, runs tests and iterates until the tests pass. This can be highly productive. However, the code, the tests and even the explanation may have been generated from the same incorrect interpretation of the requirement.
Formal methods introduce an explicit mathematical contract. The contract becomes an asset that persists beyond any individual AI session and can be reused throughout the lifetime of the software.
The distinction is not that conventional testing becomes unnecessary. Rather, proofs and tests answer different questions. A proof can establish a property of a formal model for all behaviours covered by its assumptions. A test can provide evidence about the actual implementation. Neither automatically establishes that the model faithfully describes the executable software.
The goal is to connect these forms of evidence instead of confusing them.
3. A continuous engineering workflow
I envisage AI-FSE as an iterative engineering process, not a separate verification exercise performed after the implementation is complete.
Every stage should produce version-controlled artifacts and have an explicit acceptance criterion.
| Stage | AI-assisted activity | Evidence or acceptance criterion |
|---|---|---|
| Understand | Analyse requirements, source code and assumptions | Reviewed behavioural description with source references |
| Specify | Construct models and formalise properties | Approved specification and explicit abstraction choices |
| Verify | Develop proofs or explore state spaces | Machine-checked proofs or reproducible exploration results |
| Develop | Generate implementations, patches and instrumentation | Build, static analysis and reviewed code changes |
| Test | Generate scenarios, including difficult interleavings | Reproducible executions and regression tests |
| Check conformance | Replay observations against the model | Independently computed verdicts and witnesses |
| Investigate | Explain discrepancies and propose repairs | Reproducer, diagnosis and regression evidence |
| Deliver | Summarise the assurance evidence | CI gates and human approval |
| Monitor | Check operational traces and investigate anomalies | Runtime observations and their documented limitations |
The important rule is that AI's own assessment is not the acceptance criterion. An agent can say that a theorem has been proved, but the Agda checker must establish that the proof type-checks. It can propose a bug fix, but a reproducible execution and regression checks must support the claim that the defect has been repaired.
4. Two routes: existing software and software developed from scratch
The same workflow should support both reverse and forward engineering.
For an existing system such as Cardano's Connection Manager, AI can analyse state transitions, STM transactions, exception handling, concurrency and resource management. It can help extract an implementation model in CSP. But this model must be distinguished from an independently reviewed requirements model. Translating a buggy implementation into a formal language can reproduce the bug in the model; proving a property of that model is not necessarily evidence that the intended requirement holds.
For new systems, including future components of consensus protocols such as Praos or Leios, the direction can be reversed. Start with the intended behaviour, prove critical properties, and use the specification to guide implementation, instrumentation and testing. For suitable pure components, verified executable definitions in Agda may also offer a route towards correctness by construction, provided the compilation and integration boundary is accounted for.
The level of verification should be chosen according to the criticality, complexity and cost of the component.
5. A mathematical contract between model and implementation
Let denote the intended specification, an implementation model, the executable implementation, and an abstraction that maps concrete execution events into the vocabulary of the specification.
For trace-level correctness, the desired relationship is:
Here the abstraction is lifted from individual events to traces. The goal is that every observable implementation behaviour is permitted by the specification, under the stated environmental and observation assumptions.
For complex software, proving this relationship directly may be difficult. Instead, we can establish complementary obligations:
- Specification validity: the intended model satisfies the selected requirements.
- Model refinement: the implementation model permits no traces forbidden by the intended specification, i.e. .
- Implementation correspondence: the executable implementation behaves according to its model, at the chosen abstraction level.
- Observed conformance: for a particular recorded execution , check whether .
If implementation correspondence is proved, it can be composed with model refinement to establish the desired trace inclusion. If it is only tested, the result is evidence about the tested executions, not a universal correctness theorem.
CSP offers more than trace semantics. Stable failures and failures-divergences semantics can express stronger behavioural requirements, including refusal and divergence properties. Bisimulation can justify behavioural equivalences and abstractions. Temporal properties can express safety and liveness, subject to the relevant semantic and fairness assumptions.
For protocols such as Leios, extending the mechanised foundation with discrete time and probability is another research direction. This could support reasoning about deadlines, timeouts and probabilistic guarantees. Ordinary untimed trace replay alone cannot establish these guarantees.
Verify the verifier
A particularly valuable step is to establish the correctness of reusable verification tools themselves. For example, a trace replay checker should ideally have machine-checked soundness theorems of the following form:
-- Schematic signatures, not an existing repository API.
replay-sound :
∀ P t →
replay P t ≡ accepted →
IsTrace P t
replay-reject-sound :
∀ P t →
replay P t ≡ rejected →
¬ IsTrace P t
These two obligations are not identical to completeness. For a coinductive and nondeterministic model, search may be bounded or may encounter arbitrarily many internal transitions. A checker that exhausts its search budget must not simply conclude that a trace is impossible.
A practical verifier therefore needs at least three outcomes:
| Verdict | Meaning |
|---|---|
| Accepted | A valid model witness explains the observed behaviour. |
| Rejected | The behaviour is incompatible with the model under the defined semantics and observation assumptions. |
| Inconclusive | The available data, search budget or supported semantics are insufficient to decide. |
For partially observed or concurrent executions, the relation may need to quantify over possible completions or causally consistent event orderings. Rejecting one arbitrarily chosen ordering does not establish that every compatible execution is forbidden. Acceptance likewise shows compatibility, not necessarily that the reconstructed behaviour is the one that occurred.
This is an example of where formal methods make AI-assisted engineering more dependable: they force the meaning of a result to be explicit.
6. From a formal property to a real bug report
Consider a hypothetical safety property for the Connection Manager:
For a connection identity and generation, at most one active owner exists at any given time.
This is an illustrative requirement to demonstrate the workflow, not a verified statement of Cardano's actual ownership contract or a claim that an existing bug has been found.
An AI agent could identify relevant Haskell code, including acquireOutboundConnectionImpl, and map connection allocation, reservation, handshake, failure and cleanup into abstract events. A reviewed specification would describe which sequences and interleavings are permitted.
For example, a trace containing two active ownership reservations without an intervening release might violate the illustrative property. The next step is to determine whether such a trace can actually occur in the implementation.
Cardano already has useful infrastructure for this. io-sim provides simulated execution for concurrent Haskell programs, with IOSimPOR supporting schedule discovery. It has been used in the development and testing of the Ouroboros networking stack. Instead of building another simulator, we can explore integrating a CSP-based verification oracle with this infrastructure.
A useful AI-assisted investigation should produce the failing execution, the smallest practical reproducer, a mapping to the corresponding formal property, commit-pinned source locations, an explanation of the discrepancy, and a regression test. Ideally, it should also distinguish an implementation defect from an incorrect specification, a faulty abstraction, missing instrumentation or an inconclusive search.
For real testnet logs, the observation problem becomes even more important. Timestamps from multiple nodes do not necessarily establish a total causal order. Logs may omit events, contain duplicates, or start midway through an execution. Connection identifiers, transaction boundaries, node identities and causal dependencies may need to be captured in the instrumentation.
A good report should explain these assumptions rather than hiding them behind a binary pass/fail result.
7. Reusable AI workflows, not a single enormous prompt
To make the approach transferable, I would separate the engineering methodology from the formal backend and the application domain.
An initial implementation does not need a complex multi-agent platform. Specialised workflows in Codex CLI or Claude Code could perform distinct tasks, each with an input/output contract.
| Workflow | Input | Output |
|---|---|---|
analyse-source |
Repository, commit and module | Source-grounded behavioural description |
formalise |
Reviewed requirements and source analysis | Model, properties and assumptions |
prove |
Model and fixed theorem statement | Checked proof or unresolved obligation |
implement |
Specification and development task | Implementation patch |
generate-tests |
Model and target property | Executable test scenarios |
replay-trace |
Model and normalised observations | Verdict, witness or diagnostic |
investigate-bug |
Counterexample and source | Reproducer, diagnosis and candidate repair |
audit |
Current artifacts | Assurance report and outstanding obligations |
The agents should share versioned artifacts rather than depend on a single conversation history. The core verification commands should remain executable without an LLM, so that the same results can be reproduced in CI, by another developer, or by a different AI agent.
The mathematical foundation, generic checker and evidence schemas should be kept separate from Cardano-specific event schemas, source mappings and protocol models. That separation is what makes the methodology reusable. Agda/CSP is my starting backend; the same engineering contracts could eventually accommodate other formal tools where appropriate.
8. Explainability through persistent assurance evidence
AI can generate a plausible narrative about almost any piece of software. But genuine engineering explainability requires a connection between the explanation and the evidence.
I propose maintaining a lightweight assurance evidence graph. Each requirement, property, proof, implementation location, test case, trace and bug report receives a stable identifier. Their relationships are represented as structured, version-controlled data.
A property record might look like this:
id: CM-SAFETY-001
requirement: CM-REQ-001
description: At most one active owner per connection identity and generation.
kind: safety
formalisation:
backend: agda-csp
module: ConnectionManager.Properties
theorem: uniqueActiveOwner
assumptions:
- connection-identity-mapping-is-valid
- ownership-events-are-observable
implementation:
repository: ouroboros-network
commit: "<pinned-commit>"
symbol: acquireOutboundConnectionImpl
evidence:
proof: pending
simulation: pending
trace-conformance: pending
status: proposed
This is a proposed schema, not an existing theorem or completed assurance record. In practice, evidence entries should link to artifact hashes, tool versions, model and implementation revisions, exact commands and the assumptions under which the result was obtained.
With such a structure, AI can answer more useful engineering questions: Why is a component implemented this way? Which requirements justify this function? What has been mathematically established? Which executions have been tested? What needs rechecking if this code changes? Why did a test fail?
The answer can point to the original evidence instead of being merely a generated explanation. Markdown reports, diagrams and searchable documentation can then be derived from these artifacts.
9. Trust boundaries and safeguards
The formal verifier is not a substitute for engineering judgement. A theorem can be true and still be irrelevant because the formal statement is too weak or the assumptions exclude the failure that matters. Likewise, a trace checker can be sound while a log parser incorrectly maps implementation events into formal events.
The framework should make these risks explicit.
| Failure mode | Safeguard |
|---|---|
| AI invents source behaviour | Pin the source revision and cite exact definitions or locations. |
| AI misunderstands the intended behaviour | Review requirements independently of the implementation. |
| A theorem is weakened to make it provable | Protect reviewed specifications and require approval for changes. |
| A proof introduces unjustified assumptions | Check the trusted core with appropriate Agda safety settings and track assumptions explicitly. |
| The model and generated tests share the same mistake | Independently review properties and test the oracle with negative cases. |
| A mismatch is hidden by changing the log abstraction | Version and review the abstraction separately. |
| Bounded search is reported as an exhaustive proof | Record bounds and preserve an inconclusive verdict. |
| A report claims checks that did not run | Generate evidence status from actual tool executions. |
| Previously valid evidence becomes stale | Tie each result to its relevant input revisions and dependencies. |
For Agda, --safe is a useful policy for the trusted core wherever the chosen semantics and dependencies are compatible with it. Arbitrary postulates, disabled checks or changes to the theorem should not be used as shortcuts to satisfy an AI task. Necessary environmental assumptions should be stated explicitly, for example as parameters to theorems, and their relevance reviewed.
The trusted computing base also includes the proof checker, any admitted assumptions, and the components used to obtain and interpret execution evidence. A verified model does not magically make the Haskell compiler, logger, operating system or network correct.
10. Integrating assurance into everyday delivery
Formal methods become more valuable when they participate in ordinary pull requests, rather than appearing only in a report at the end of a project.
A possible first implementation is a small CLI, with commands such as fse prove, fse test, fse replay, fse audit and fse report. These names are proposals. The commands should invoke actual verification tools and generate structured evidence, with AI assisting analysis and repair rather than deciding whether a check passes.
For a pull request, the workflow would identify affected properties, invalidate stale evidence, check proofs, run selected model-based tests, replay traces and produce an assurance summary for reviewers. Expensive concurrency exploration or larger devnet experiments could run in separate CI jobs.
The merge policy should be determined by the risk of the change. Some components may require documented behaviour and targeted tests, while critical components require checked model properties and stronger implementation-level evidence. For selected components, a proof of implementation correspondence may be achievable. These are different kinds of assurance, not interchangeable percentages of correctness.
A report should distinguish at least the following: proved, tested, failed, inconclusive, stale and not checked. The fact that a required check is inconclusive must never silently become a successful CI result. Exceptions to the policy should be explicit, justified and reviewed.
11. How to establish that the workflow works
The proposed methodology itself needs to be evaluated. Faster code generation alone is not enough, nor is the number of proof scripts produced.
I would compare ordinary development, AI-assisted development with conventional tests, human-led formal methods and the combined approach using comparable tasks and bug corpora. The evaluation should account for differences in experience, task difficulty, AI/tool versions, search budgets and review effort.
| Objective | Possible measurement |
|---|---|
| Productivity | Engineering time, including review and verification effort |
| Bug detection | Fraction of seeded faults detected, plus independently confirmed real defects |
| Reliability | False-positive and false-negative rates on a labelled test corpus |
| Assurance | Coverage of required properties, proof scope and implementation evidence |
| Explainability | Findings with source mappings, witnesses and reproducible explanations |
| Reproducibility | Independent reruns using pinned tools and artifact versions |
| Reusability | Effort to apply the workflow to a different system |
| Maintainability | Effort to restore valid assurance evidence after a software change |
Mutation testing could provide a useful first experiment. Introduce controlled faults into a test version of Connection Manager or a mini-protocol, and measure whether the workflow detects and explains them. Keep a separate set of held-out faults for evaluation, and do not equate performance on artificial mutations with real-world defect coverage.
This turns the idea into an empirical research programme rather than an assertion that AI and formal methods must work well together.
12. A practical path forward
I would begin with a small but complete vertical case study instead of immediately building a general-purpose AI platform.
- Consolidate the existing work. Document how AI was used in the three branches, including the artifact dependencies and verification steps.
- Establish a trusted replay core. Define trace semantics, checker verdicts, assumptions, bounds and soundness obligations. Make the build and checking process reproducible.
- Pilot the Connection Manager. Select a few important, reviewed concurrency or lifecycle properties. Connect formal models to IOSim scenarios, trace replay, controlled faults and regression tests.
- Extract reusable workflows. Package the agent instructions, verification commands, evidence schemas and reporting templates separately from the Cardano models.
- Integrate with CI. Establish property-level gates and evidence reports for normal software changes.
- Apply to Linear Leios. Connect the framework to protocol development and testnet observations, exploring timed and probabilistic semantics as the mathematical foundations mature.
- Generalise beyond Cardano. Apply the same artifact contracts to an unrelated concurrent or distributed system, and measure the cost of adaptation.
Each phase should produce working artifacts and an independently reproducible example before the next phase introduces more complexity.
Conclusion
Formal methods and AI address different limitations in software engineering. Formal methods offer precise definitions and independently checkable reasoning, but constructing specifications, proofs and implementation mappings can be expensive. AI can accelerate those activities, but its generated answers do not constitute correctness evidence.
Combining them offers a promising direction: AI can make formal methods more accessible and productive, while formal methods can make AI-driven development more disciplined, reliable and explainable.
My work on Cardano networking, trace replay and Connection Manager provides a practical starting point. The longer-term objective is a continuous software assurance framework, where specifications, proofs, model-based tests, runtime observations and engineering decisions remain connected throughout the life of the software.
The ambition is not to remove humans from software development or to claim that all software will be fully verified. It is to make software delivery increasingly evidence-driven: every important claim about correctness should have a clear scope, explicit assumptions and a reproducible means of checking it.
Further reading
- Ongoing work, including the projects below.
- Mechanising CSP in Agda with Process Trees — the mathematical foundation for this exploration.
- The three motivating branches linked above: Modelling and Verifying the Cardano Peer-to-Peer Network, Trace Verifier for Cardano Mini-Protocols and Verifying the Cardano Connection Manager.
Diagram convention: all figures use the same SVG design language. Grey denotes engineering activities and artifacts, blue denotes formal specifications and mappings, teal denotes verification and evidence, amber denotes review or unresolved obligations, and muted red denotes discrepancies and repair. Solid arrows represent dependencies or workflow progression; dashed arrows represent feedback, separate specification or property inputs, or future extensions.