Engineering Level 3 Counterfactuals — deterministic ‘what-if’ simulations in SWI-Prolog
Operationalizing Judea Pearl’s Abduction–Action–Prediction (AAP) cycle with SBRM hypercubes and Logical English — without latent vector leakage.
In our companion post, Mind the Causal Ladder, we examined Paolo Di Prodi’s October 2026 TMLR paper (Mind the Ladder: A Benchmark for Level 1–3 Causal Reasoning in World Models) and why flat-latent neural networks fail at Pearl’s Level 3 (Counterfactual Reasoning).
Understanding why neural world models fail at counterfactuals is only half the battle. The real engineering challenge is building an engine that succeeds.
In a standard compliance run, a deterministic tax and accounting engine operates forward and deductively:
$$\text{SBRM Facts} + \text{Logical English Rules} \implies \text{Statutory Outcome}$$
In a “What-If” advisory, restructuring, or audit defense scenario, we already know the factual outcome—often an undesirable tax consequence we want to mitigate or verify—and we need the engine to answer Pearl’s Level 3 query:
“Given that we observed ledger state $X$ and statutory outcome $Y$, what would $Y$ have been if we had intervened on $X^*$—and what is the minimal valid intervention required to change $Y$ without corrupting the rest of the financial report?”
To build a true Level 3 Counterfactual Engine in the LodgeiT Labs stack, we take Pearl’s Abduction–Action–Prediction (AAP) cycle from Di Prodi’s paper and invert how our SWI-Prolog and Logical English engine is queried.
1. Partitioning the SBRM fact base: immutable vs. intervenable (do-able)
In Section 3.5 of Mind the Ladder, Di Prodi demonstrates why neural world models fail at counterfactuals: when you intervene in a continuous 192-dimensional latent space via vector translation ($z_{cf} = z_{fact} + \delta v$), the model suffers from Single-Factor Leakage. Shifting the vector to alter one variable (room hue) inadvertently mutates unrelated variables (the agent’s episode step index and physical distance to the goal) by nearly a full standard deviation.
In financial terms, Single-Factor Leakage is catastrophic: it is the equivalent of testing a counterfactual tax election and having the model silently alter historical bank balances or fixed-asset cost bases in the background.
To prevent this in Standard Business Report Modeling (SBRM), our Markdown + YAML frontmatter contracts partition facts into three strict Pearlian buckets before SWI-Prolog ever executes a “What-If” branch:
sbrm_contract: "counterfactual_partition_schema"
version: "1.0.0"
rounding_policy: "half_away_from_zero"
balance_convention: "signed_numbers_sum_to_zero" # Positive = Debit, Negative = Credit
fact_partitions:
# 1. Exogenous & Immutable (U_settled)
settled_historical_facts:
mutable_by_do_operator: false
examples:
- bank_statement_movement
- asic_incorporation_date
- locked_prior_period_closing_balance
# 2. Abducible Unknowns (U_abduced)
abducible_context_facts:
mutable_by_do_operator: true
requires_evidence_anchor: true
examples:
- s109n_written_agreement_executed
- cgt_a1_contract_execution_date
- market_valuation_at_transfer
# 3. Actionable Levers (X_controllable)
controllable_intervention_levers:
mutable_by_do_operator: true
examples:
- dividend_declaration_resolution
- trust_income_streaming_election
- cgt_small_business_rollover_choice
- Historical / Settled Facts ($U_{settled}$): Past bank transactions, settled trial balance movements after period lock, or statutory registration dates. No $do()$ operator is permitted to mutate these unless explicitly simulating a retrospective prior-year amendment.
- Abducible Unknowns ($U_{abduced}$): Facts missing from the raw trial balance that govern which statutory branch fires—for example, whether a complying written loan agreement under s 109N ITAA 1936 exists, whether a disposal contract date for CGT Event A1 preceded settlement across a 30 June boundary, or whether an entity satisfies the maximum net asset value test.
- Actionable Levers ($X_{controllable}$): Pre-lodgment or pre-year-end elections, dividend declarations, minimum yearly repayments (MYR) via journal set-offs, or choice of capital gains concessions.
2. The symbolic AAP cycle in SWI-Prolog + Logical English
Instead of shifting an entangled neural embedding vector, ClawDog and our FOL_solvers substrate execute Pearl’s Abduction–Action–Prediction cycle via abductive meta-interpretation and isolated transactional snapshots in SWI-Prolog.
Step 1: Abduction (generating the proof tree & missing assumptions)
When a client’s ledger is loaded, the engine evaluates the factual baseline ($z_{fact}$). If an undesirable tax outcome fires—such as a $120,000 Division 7A deemed dividend or a spiked CGT Event A1 net capital gain—the engine captures the exact deductive proof tree: every ground atom and negated condition (\+) that caused the rule to succeed.
Conversely, if a draft filing claims no tax liability applies despite a debit shareholder loan balance, Prolog uses Abductive Logic Programming (ALP) to abduce the minimal set of unobserved facts $\Delta \subseteq U_{abduced}$ required to make that claim hold:
$$\text{Logical English Rules} \cup \text{SBRM Facts}_{fact} \cup \Delta \models \neg\,\text{deemed\_dividend}(T)$$
For example, Prolog abduces:
% Abduced Evidentiary Requirement (Delta):
abduced_hypothesis([
converted_to_complying_s109N_loan(tx_42, 2026),
agreement_in_writing_before_lodgment_day(tx_42, '2027-05-15')
]).
Under our Proof-of-Control and Brain Pattern discipline, any abduced fact $\Delta$ automatically generates an evidentiary checklist item that must be anchored by a verifiable document before lodgment.
Step 2: Action (the do() meta-predicate via isolated snapshots)
To evaluate a counterfactual “What-If” scenario, we never mutate the Git-backed Markdown source of truth in place. Instead, we pass an explicit intervention do(AddFacts, RetractFacts) into a sandboxed SWI-Prolog transactional snapshot (snapshot/1):
% Deterministic Level 3 Counterfactual Evaluator in SWI-Prolog
evaluate_what_if(DoAdd, DoRetract, TargetGoal, FactualOut, CounterfactualOut, InvErr) :-
% 1. Guardrail: Reject any intervention that touches immutable historical facts
validate_intervention_permissions(DoAdd, DoRetract),
% 2. Compute Factual Baseline & Orthogonal Trial Balance Invariant
findall(TargetGoal, call(TargetGoal), FactualOut),
immutable_cash_and_equity_invariant(Invariant_Fact),
% 3. Execute Pearl's do() operator inside an isolated memory snapshot
snapshot((
forall(member(R, DoRetract), retractall(R)),
forall(member(A, DoAdd), assertz(A)),
findall(TargetGoal, call(TargetGoal), CounterfactualOut),
immutable_cash_and_equity_invariant(Invariant_CF)
)),
% 4. Verify Di Prodi's Structural Invariance Error (InvErr == 0.0)
InvErr is abs(Invariant_Fact - Invariant_CF),
InvErr =:= 0.
Because snapshot/1 isolates all asserted and retracted clauses in thread-local memory and rolls them back automatically upon completion, the engine can evaluate hundreds of counterfactual “What-If” branches in parallel in milliseconds with zero risk of state pollution.
Step 3: Prediction & causal delta diffing
The engine compares FactualOut against CounterfactualOut across the entire SBRM hypercube. Because the rules are written in Logical English over explicit parent nodes:
- True Causal Dependents Propagate Cleanly: If we assert
do(declare_franked_dividend(company_A, trust_B, 45000))to satisfy a Division 7A Minimum Yearly Repayment (MYR), the counterfactual branch doesn’t just clear the s 109D shortfall—it deterministically updatesdistributable_surplus, debits thefranking_account_balance, and flows the grossed-up franked distribution intotrust_B’s counterfactual net income. - Zero Orthogonal Leakage ($InvErr = 0.0$): Unrelated SBRM structures—such as fixed-asset depreciation pools, GST control accounts, or settled bank movements—remain mathematically invariant.
3. Two high-leverage “What-If” workflows in production
Wiring Pearl’s AAP cycle into SWI-Prolog unlocks two distinct operational modes for practitioners and autonomous agents.
Mode A: Forward “What-If” simulation (stress testing)
An operator or agent asks:
“What if the disposal contract for Commercial Property X was executed on 29 June 2026 instead of 2 July 2026, even though settlement occurred in August 2026?”
- The
do()Intervention: Under s 104-10(3) ITAA 1997, CGT Event A1 happens when the disposal contract is entered into, not at settlement. The engine runs:do(Add: [contract_execution_date(asset_x, '2026-06-29')], Retract: [contract_execution_date(asset_x, '2026-07-02')]) - Multi-Period Evaluation: Both the 2025–26 and 2026–27 SBRM hypercubes are re-evaluated inside the snapshot.
- SBRM Counterfactual Diff: The engine returns a structured diff table showing not only that the capital gain shifted tax years, but whether pulling the event forward to 29 June 2026 breached the 12-month holding threshold for the 50% CGT discount or absorbed carried-forward capital losses a year earlier.
Mode B: Inverse counterfactual search (“minimum intervention advisory”)
This is where declarative logic programming leaves neural world models completely behind. Instead of the practitioner manually guessing which “What-If” parameters to tweak, the practitioner specifies the Target Counterfactual Outcome as a constraint:
“Find all valid interventions in $X_{controllable}$ prior to Lodgment Day that reduce s109D_deemed_dividend to $0 while keeping total group tax delta under $15,000.”
Using SWI-Prolog’s backtracking and constraint solvers (library(clpq) for exact rational arithmetic alongside half-away-from-zero statutory rounding), the engine searches backwards through the Logical English rule graph to synthesize every compliant option:
| Synthesized branch | Required do() intervention ($X_{controllable}$) |
Primary statutory effect | Secondary ripple effects (SBRM diff) | InvErr |
|---|---|---|---|---|
| Branch 1: s 109N complying loan | assert(s109n_agreement(tx_42, '7_year_unsecured')) before lodgment day |
2026 Deemed Dividend: $0.00 (down from $100,000) | Triggers mandatory MYR + benchmark interest starting in 2027 tax year | 0.000 |
| Branch 2: Dividend set-off | assert(declare_franked_dividend(entity_a, assoc_b, 100000)) |
Offset balances loan to $0.00 | Consumes $42,857 in franking credits; increases assoc_b taxable income |
0.000 |
| Branch 3: s 109RB discretion | abduce(honest_mistake_or_inadvertent_omission(tx_42)) |
Flags potential relief subject to Commissioner ruling | Requires external statutory declaration attachment | 0.000 |
4. Guarding the boundary: the “counterfactual compiler” pattern
Where does the Large Language Model (LLM) sit in this workflow?
Neither a human practitioner nor a DIY business operator wants to write raw Prolog snapshot/1 predicates by hand. They want to ask a natural-language question:
“What happens if Richtide Holdings streams the capital gain to the family trust instead of retaining it in the corporate beneficiary?”
In the ClawDog architecture, the LLM acts strictly as a Counterfactual Compiler:
- Natural Language → Candidate
do()Spec: The LLM translates the user’s question into a proposed YAML/Logical English intervention (do(Add, Retract)). - The Operator-Approval Firewall: Before execution, the UI surfaces the exact symbolic intervention for human or policy-gate approval:
“Proposing Counterfactual Branch #1: Modifying
trust_distribution_resolutionfrom 0% to 100%. All historical bank movements and immutable facts locked.” - Deterministic Execution & Proof Receipt: SWI-Prolog executes the snapshot, verifies that all SBRM trial-balance sums equal zero (under our positive-debit / negative-credit convention) and that Structural Invariance Error ($InvErr$) is strictly zero, and returns the exact dollar delta backed by a cryptographic proof receipt.
Neural networks are extraordinary translators, but they cannot be trusted to hold the causal graph of a financial report inside a flat vector of floating-point weights. By compiling natural-language “What-If” questions into SBRM and Logical English interventions executed by SWI-Prolog, we turn Pearl’s Level 3 Counterfactual Ladder from an AI research benchmark into deterministic financial infrastructure.
This is the engineering half of a pair. For the conceptual case — why financial truth requires a deterministic firewall in the first place — read the companion post, Mind the Causal Ladder.
References
- Di Prodi, P. (2026). Mind the Ladder: A Benchmark for Level 1–3 Causal Reasoning in World Models. Transactions on Machine Learning Research (10/2026). OpenReview.
- Pearl, J. (2009). Causality: Models, Reasoning, and Inference. Cambridge University Press.
- Kowalski, R., & Datoo, A. (2022). Logical English meets Legal English for Swaps and Derivatives. Artificial Intelligence and Law.
The methodology behind this programme is public in brain-pattern. The statutory calculators underneath it are verified in the open through the bounty programme, where practitioner reviewers are paid to break our reasoning against statute.