@mudraforge/statutory 2.13.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +6 -0
  3. package/package.json +1 -4
  4. package/src/calculators.js +139 -3
  5. package/src/constants.js +1 -1
  6. package/types/index.d.ts +95 -0
  7. package/conformance/README.md +0 -54
  8. package/conformance/fixtures/invalid_malformed_temporal_dates.json +0 -10
  9. package/conformance/fixtures/invalid_missing_effective_period.json +0 -6
  10. package/conformance/fixtures/invalid_missing_section_code.json +0 -9
  11. package/conformance/fixtures/valid_circular_frontmatter.md +0 -16
  12. package/conformance/fixtures/valid_full_section.json +0 -35
  13. package/conformance/fixtures/valid_minimal_section.json +0 -11
  14. package/conformance/test_conformance.js +0 -129
  15. package/docs/ACCOUNTING_ASSURANCE_AUDIT_DOSSIER.md +0 -276
  16. package/docs/ADESHA_ASSURANCE_OVERVIEW.md +0 -166
  17. package/docs/ARCHITECTURE.md +0 -773
  18. package/docs/ARCHITECTURE_DECISIONS.md +0 -158
  19. package/docs/CASE_01_FORM_TEXT.txt +0 -48
  20. package/docs/CATALOG.md +0 -1901
  21. package/docs/CA_PILOT_BENCHMARK_CASES.md +0 -282
  22. package/docs/CORPUS_QUALITY.md +0 -106
  23. package/docs/DATA_LICENSING.md +0 -73
  24. package/docs/DOMAIN_BREADTH_AND_DEPTH_COMPARISON.md +0 -209
  25. package/docs/ENTERPRISE_GOVERNANCE.md +0 -160
  26. package/docs/OKF_MAINTENANCE_SOP.md +0 -286
  27. package/docs/PILOT_EVALUATION_GUIDE.md +0 -215
  28. package/docs/PROVENANCE.md +0 -33
  29. package/docs/VERIFICATION.md +0 -106
  30. package/examples/README.md +0 -56
  31. package/examples/invoice_deduction_trace.json +0 -149
  32. package/examples/simulate_end_to_end_trace.js +0 -106
@@ -1,773 +0,0 @@
1
- # MudraForge Statutory Architecture
2
- ## Grounding Financial AI in Deterministic Law & Open Knowledge
3
-
4
- > **MudraForge Statutory Bundle**: `v2.13.0`
5
- > **Knowledge Specification**: Google Open Knowledge Format (OKF) specification (upstream v0.2)
6
- > **License**: MIT (Public Knowledge Commons)
7
- > **Status**: Public Beta
8
-
9
- ---
10
-
11
- ## 1. Executive Thesis: The Payment Instruction Boundary
12
-
13
- > **The Dangerous Moment in Finance AI**:
14
- > *The dangerous moment in finance AI isn't when the model is wrong. It's when its output becomes a payment instruction.*
15
- >
16
- > In marketing, an AI hallucination is a typo. In accounts payable, an unhandled bank timeout can trigger a retry that double-pays a vendor.
17
- >
18
- > Hardening the financial runtime for **Adesha, MudraForge's organizational AI**, our principle is simple:
19
- > **Reasoning can be probabilistic, but financial execution needs deterministic boundaries.**
20
-
21
- ---
22
-
23
- ## 2. The Four Pillars of Autonomous Finance Execution
24
-
25
- To ensure financial workflows remain resilient against model confabulation, concurrent API races, and network failures, the MudraForge architecture is grounded in four operational pillars:
26
-
27
- ### Pillar 1: Retrieval is Not Verification
28
- Early on, prototype compliance validators relied on pre-populated test files holding expected answers. We scrapped that crutch. Real-world accounting cannot trust static assumptions.
29
-
30
- Our tests now exercise live retrieval from connected systems of record (including live Zoho Books / SAP ERP readback) and authenticated tenant statutory vaults. Finding a document or matching keywords is not legal verification; the system must verify what evidence legally supports before any downstream calculation runs or any payment lease is minted.
31
-
32
- ### Pillar 2: Safe Tools Do Not Guarantee Safe Workflows
33
- An AI agent can call individually safe API tools and still coordinate an unauthorized or illegal transaction (e.g., deducting tax on an exempt unit or paying an altered beneficiary account).
34
-
35
- We enforce an absolute separation between reasoning and execution:
36
- - **Generative AI Layer**: Coordinates investigations, clarifies unstructured context, and extracts messy invoice narratives.
37
- - **Deterministic Execution Engine**: Evaluates statutory tax thresholds, computes paisa-level withholding, and enforces ledger invariants.
38
- - **Statutory Provenance**: Human oversight must not mean accountants re-auditing arithmetic; the runtime provides verifiable statutory provenance so human officers can focus on the actual business decision.
39
-
40
- > **Rule 11**: *Agreement with the Engine ≠ Agreement with the Law.*
41
- > Never confuse an agent adhering to tool output with true statutory correctness. If the underlying statutory baseline is flawed, 100% agent adherence merely guarantees that the agent faithfully repeats a flawed calculation. Statutory thresholds and effective dates must be enforced by deterministic calculator functions, never left to ungrounded LLM text generation.
42
-
43
- ### Pillar 3: Preventing Silent Financial Drift
44
- Deterministic code computes numbers. RFC 8785 JSON Canonicalization Scheme (JCS) and SHA-256 bind the calculation result to a verifiable, immutable fingerprint:
45
- ```
46
- Calculation Result ──► RFC 8785 Canonicalization ──► SHA-256 Fingerprint
47
- ```
48
- The cryptographic hash does not perform math—it detects any alteration between calculation, human authorization, and banking execution. If an invoice total, vendor account, or tax deduction is altered anywhere in the workflow, the fingerprint mismatch immediately halts execution before payment dispatch.
49
-
50
- ### Pillar 4: Testing Payment Boundaries Against Failure
51
- - **Duplicate-Payment Prevention**: Single-use Compare-and-Swap (CAS) leases are tested under concurrent races using MongoDB-compatible atomic operations (`findAndModify`): exactly one consumer consumes the lease successfully; all concurrent races are rejected with `LEASE_ALREADY_CONSUMED`.
52
- - **Formal TLA+ State Machine Modeling**: The TLC Model Checker explored all 361 reachable states in our configured distributed model (covering two concurrent leases, retries, and network timeouts) with zero invariant violations, and caught four deliberate defects injected into the formal specification.
53
- - **Edge Execution**: Built on Cloudflare Workers V8 isolates, eliminating container cold starts and sandbox vulnerabilities.
54
- - **Accounting Integrity**: Adversarial test suites target unbalanced journals, duplicate credits, and amount mismatches, enforcing paisa-level equilibrium before ERP writeback.
55
-
56
- ---
57
-
58
- ## 3. End-to-End AP Architecture: From Statutory Law to Bank Settlement
59
-
60
- The journey of an accounts payable transaction from incoming PDF invoice to general ledger reconciliation traverses seven strict governance stages (`npm run example:trace`):
61
-
62
- ```
63
- ┌────────────────────────────────────────────────────────────────────────┐
64
- │ STAGE 1: INVOICE INGESTION │
65
- │ Incoming PDF / IRN e-Invoice QR code parsed and verified. │
66
- │ (Basic: INR 60,00,000 | GST 18%: INR 10,80,000 | Gross: INR 70,80,000) │
67
- └───────────────────────────────────┬────────────────────────────────────┘
68
- ▼
69
- ┌────────────────────────────────────────────────────────────────────────┐
70
- │ STAGE 2: OKF RULE RESOLUTION (This Package - Zero Network Calls) │
71
- │ Offline local lookup identifies Section 194Q & successor Act 2025. │
72
- │ Threshold: INR 50,00,000 | Standard Rate: 0.1% | Excess Base Only │
73
- └───────────────────────────────────┬────────────────────────────────────┘
74
- ▼
75
- ┌────────────────────────────────────────────────────────────────────────┐
76
- │ STAGE 3: USVM DECLARATIVE AST EXECUTION (Rational BigInt Kernel) │
77
- │ Prior FY Purchases: INR 45,00,000 | Cumulative: INR 1,05,00,000 │
78
- │ Taxable Excess: INR 55,00,000 | GST Unbundled (Circular 13/2021) │
79
- │ TDS Deducted: INR 5,500 | Net Payable to Vendor: INR 70,74,500 │
80
- └───────────────────────────────────┬────────────────────────────────────┘
81
- ▼
82
- ┌────────────────────────────────────────────────────────────────────────┐
83
- │ STAGE 4: CRYPTOGRAPHIC PAYMENT AUTHORIZATION LEASE (Adesha CAS Gate) │
84
- │ Single-Use Token: sha256-4f9e8a71... | Max Authorized: INR 70,74,500 │
85
- │ State: LEASE_ISSUED_UNCONSUMED (Atomic lock prevents re-execution) │
86
- └───────────────────────────────────┬────────────────────────────────────┘
87
- ▼
88
- ┌────────────────────────────────────────────────────────────────────────┐
89
- │ STAGE 5: HUMAN-IN-THE-LOOP AUTHORITY HARNESS (Mobile / Biometric) │
90
- │ CFO reviews verifiable statutory provenance on mobile authority app. │
91
- │ Decision: APPROVED | Transition: AUTHORIZED_FOR_SETTLEMENT │
92
- └───────────────────────────────────┬────────────────────────────────────┘
93
- ▼
94
- ┌────────────────────────────────────────────────────────────────────────┐
95
- │ STAGE 6: BANK RAIL DISBURSEMENT (Host-to-Host Corporate RTGS) │
96
- │ Payout dispatched via banking gateway. HTTP 200 settled confirmed. │
97
- │ Bank UTR: SIMULATED-RTGS-UTR-2026-891 | Disbursed: INR 70,74,500 │
98
- └───────────────────────────────────┬────────────────────────────────────┘
99
- ▼
100
- ┌────────────────────────────────────────────────────────────────────────┐
101
- │ STAGE 7: GENERAL LEDGER BALANCED DOUBLE-ENTRY WRITEBACK (ERP) │
102
- │ Balanced Journal Entry (JV-2026-04-0042) posted to ERP (SAP / Zoho): │
103
- │ [DEBIT ] Purchases / Cost of Goods Sold INR 60,00,000.00 │
104
- │ [DEBIT ] Input CGST Receivable (9%) INR 5,40,000.00 │
105
- │ [DEBIT ] Input SGST Receivable (9%) INR 5,40,000.00 │
106
- │ [CREDIT] TDS Payable under Section 194Q INR 5,500.00 │
107
- │ [CREDIT] Bank Operating Account INR 70,74,500.00 │
108
- │ Equilibrium: PAISA_LEVEL_PERFECT_BALANCE (Discrepancy: INR 0.00) │
109
- └────────────────────────────────────────────────────────────────────────┘
110
- ```
111
-
112
- > **Reproduce This Execution Trace Locally**:
113
- > You can run the audited 7-stage execution simulation locally in your terminal:
114
- > ```bash
115
- > npm run example:trace
116
- > ```
117
-
118
- ### 3.1 Stage 1: Invoice Ingestion & Cryptographic Ingestion Gate
119
- - **Operational Purpose**: Ingests, normalizes, and cryptographically validates incoming vendor billing payloads from heterogeneous channels (PDF documents, scanned paper, structured EDI feeds, and B2B GST e-Invoices).
120
- - **Inbound Data Contract**:
121
- - `invoicePayload`: Raw image/PDF bytes or structured JSON payload.
122
- - `irnQrPayload`: Base64-encoded CBIC/NIC e-invoice QR code string (for B2B invoices exceeding mandatory e-invoicing thresholds).
123
- - `metadata`: Source channel, ingest timestamp, and receiving tenant ID.
124
- - **Cryptographic Gate & Ingestion Mechanics**:
125
- 1. *QR Code Public Key Verification*: Extracts the signed JWT embedded within the 500-character QR code. The digital signature is validated against the National Informatics Centre (NIC) public certificate, certifying that the Invoice Reference Number (IRN), GSTIN of supplier/buyer, invoice date, and item totals were registered on the government portal.
126
- 2. *Line-Item Decomposition & Arithmetic Balancing*: Normalizes itemized line items, verifying strict paisa-level equality:
127
- $$\text{Gross Total} \equiv \sum \text{Line Taxable Values} + \sum \text{CGST} + \sum \text{SGST/UTGST} + \sum \text{IGST} + \sum \text{Cess} \pm \text{INR } 0.00$$
128
- 3. *Replay Protection Check*: Queries historical transaction ledger for existing IRN hash or `(supplier_gstin, invoice_number, fiscal_year)` tuple.
129
- - **Outbound Payload**: Normalized `IngestedInvoice` structure pinned with an immutable `invoiceDigest` (SHA-256).
130
- - **Failure Modes & Degradation Handling**:
131
- - `ERR_INVALID_QR_SIGNATURE`: Cryptographic signature mismatch. Invoice is rejected; processing halts with security alert.
132
- - `ERR_ARITHMETIC_MISMATCH`: Line item sums diverge from header gross amount. Execution suspended for human accounting review.
133
- - `ERR_DUPLICATE_IRN_DETECTED`: Invoice replay detected. Aborts immediately to prevent duplicate bill processing.
134
-
135
- ### 3.2 Stage 2: OKF Rule Resolution Substrate (Zero-Network Subsystem)
136
- - **Operational Purpose**: Resolves the applicable legal provisions, circular guidelines, and compliance schemas directly from the local Open Knowledge Format (OKF) filesystem with zero network calls and sub-millisecond deterministic latency.
137
- - **Inbound Data Contract**:
138
- - `transactionContext`: Supplier type, buyer corporate turnover, goods vs. services classification, and line item HSN/SAC codes.
139
- - `transactionDate`: ISO 8601 execution timestamp (e.g., `2026-04-23T10:00:00Z`).
140
- - **Resolution Pipeline & Temporal Mechanics**:
141
- 1. *Statute Routing*: Maps transaction context to the authoritative regulatory domain (e.g., `direct_tax/tds_goods_194q`).
142
- 2. *Zero-Network Local Traversal*: Reads `./okf/direct_tax/tds_goods_194q/section.json` from the local filesystem or isolated edge memory.
143
- 3. *Temporal State Machine Evaluation*:
144
- - Verifies `transactionDate >= section.effectiveFrom`.
145
- - Evaluates `section.sunsetDate`. If $\text{transactionDate} \ge \text{sunsetDate}$ (as with Section 206C(1H) on 1 April 2025), transitions status to `SUNSET_SUPERSEDED` and halts execution.
146
- - Evaluates `section.successorAct2025Mapping`. If $\text{transactionDate} \ge \text{2026-04-01}$, cross-compiles citation to the *Income-tax Act, 2025* codification (e.g. Section 194Q $\rightarrow$ Section 393(1), Table 1, Sl. No. 8(ii)).
147
- - **Outbound Payload**: Immutable `StatutoryRuleSnapshot` containing thresholds, rates, circular provisos, and successor mapping.
148
- - **Failure Modes & Degradation Handling**:
149
- - `ERR_SECTION_NOT_FOUND`: Specified statutory provision not indexed in active OKF manifest.
150
- - `ERR_STATUTE_SUNSET_EXPIRED`: Transaction attempted against an expired or omitted legal section.
151
- - `ERR_UNMAPPED_SUCCESSOR`: Transaction date falls into the 2025 Act era without an explicit statutory cross-reference.
152
-
153
- ### 3.3 Stage 3: Universal Statutory Virtual Machine (USVM) Declarative Execution Engine
154
- - **Operational Purpose**: Executes statutory rules through the stateless Universal Statutory Virtual Machine (`@mudraforge/statutory/usvm`), evaluating declarative Abstract Syntax Tree (AST) representations with 5-stage rational BigInt arithmetic. Generative LLMs are barred from performing this arithmetic (Rule 11).
155
- - **Inbound Data Contract**:
156
- - `ingestedInvoice`: Verified invoice amounts, item breakdown, and vendor PAN.
157
- - `statutorySnapshot`: Applicable OKF declarative AST package (`ast.json` or pre-cached USVM rule).
158
- - `ledgerHistory`: Verified historical purchases from the same vendor within the active financial year.
159
- - **Deterministic Computation Algorithms**:
160
- 1. *Declarative AST Rule Traversal*: The USVM kernel (`evaluation_vm.js`, 355 lines) evaluates statutory expressions over facts in <15 microseconds without relying on hardcoded procedural conditionals.
161
- 2. *Cumulative Threshold Evaluation (Section 194Q)*:
162
- - Retrieves cumulative prior FY purchases from the verified ERP ledger: $\text{Prior Purchases} = \text{INR } 45,00,000$.
163
- - Computes cumulative aggregate: $\text{Cumulative} = 45,00,000 + 60,00,000 = \text{INR } 1,05,00,000$.
164
- 3. *GST Unbundling & Taxable Base Netting*:
165
- - Strictly enforces CBDT Circular 13/2021 and Circular 23/2017: GST components (CGST/SGST/IGST) are excluded from the withholding base when charged separately.
166
- - Computes marginal taxable excess:
167
- $$\text{Taxable Excess} = \max(0, \min(\text{Basic Value}, \text{Cumulative} - 50,00,000)) = \text{INR } 55,00,000$$
168
- 4. *PAN Compliance & Penalty Rate Interception*:
169
- - Inspects vendor PAN validity and Section 206AB compliance. If PAN is valid and active, standard rate ($0.1\%$) applies:
170
- $$\text{TDS Deducted} = \lfloor 55,00,000 \times 0.001 \rfloor = \text{INR } 5,500$$
171
- - If PAN is inoperative or specified non-filer, automatically elevates rate to 5% u/s 206AA/206AB.
172
- 5. *Net Payable Allocation & Rational BigInt Precision*:
173
- - Computed via 5-stage rational fractions (`math_rational.js`) eliminating IEEE 754 float drift:
174
- $$\text{Net Payable to Vendor} = \text{Gross Invoice Total} - \text{TDS Deducted} = 70,80,000 - 5,500 = \text{INR } 70,74,500$$
175
- - **Outbound Payload**: Canonical `StatutoryCalculationResult` detailing basic value, unbundled taxes, taxable excess, deduction, net payable, and mandatory fiduciary invariant `isAuthorizedToDisburse: false`.
176
- - **Failure Modes & Degradation Handling**:
177
- - `ERR_NEGATIVE_TAXABLE_BASE`: Negative purchase value or invalid credit note netting.
178
- - `ERR_PAN_INOPERATIVE_MANDATORY_ELEVATION`: Vendor PAN inoperative, requiring mandatory 5% withholding rate escalation.
179
- - `ERR_MISSING_FY_PURCHASE_HISTORY`: Ledger purchase history unretrievable, preventing deterministic threshold calculation.
180
-
181
- ### 3.4 Stage 4: Cryptographic Payment Authorization Lease (Adesha CAS Gate)
182
- - **Operational Purpose**: Converts the computed financial calculation into a single-use, cryptographically sealed authorization lease. Enforces the payment instruction boundary and guarantees single-execution semantics under concurrent distributed races.
183
- - **Inbound Data Contract**:
184
- - `calculationResult`: Deterministic statutory calculation numbers.
185
- - `disbursementTarget`: Verified vendor beneficiary account, IFSC code, and legal entity identifier.
186
- - **Cryptographic Binding & Atomic CAS Mechanics**:
187
- 1. *RFC 8785 JSON Canonicalization Scheme (JCS)*: Normalizes the calculation payload to remove whitespace and key ordering variance:
188
- $$\text{Canonical JSON} = \text{JCS}(\text{CalculationPayload})$$
189
- 2. *SHA-256 Fingerprint Binding*: Mints a unique transaction fingerprint:
190
- $$\text{transactionFingerprint} = \text{SHA-256}(\text{Canonical JSON})$$
191
- 3. *Atomic Single-Use Compare-and-Swap (CAS) Minting*: Inserts lease into distributed state storage (MongoDB/KV) under status `LEASE_ISSUED_UNCONSUMED`:
192
- ```javascript
193
- const lease = {
194
- leaseId: "lease_sec194q_2026_04_9921",
195
- transactionFingerprint: "sha256-4f9e8a71...",
196
- vendorAccountHash: "sha256-992a...",
197
- maxAuthorizedAmountPaisa: 707450000,
198
- status: "LEASE_ISSUED_UNCONSUMED",
199
- expiresAt: "2026-04-23T12:00:00Z"
200
- };
201
- ```
202
- 4. *Concurrency Defense*: When a disbursement process claims the lease, it executes an atomic `findOneAndUpdate` matching `status: LEASE_ISSUED_UNCONSUMED`. Exactly one consumer succeeds; any concurrent thread, worker retry, or duplicate webhook fails with `LEASE_ALREADY_CONSUMED`.
203
- - **Outbound Payload**: Cryptographic `PaymentAuthorizationLease` ready for human officer review.
204
- - **Failure Modes & Degradation Handling**:
205
- - `ERR_FINGERPRINT_TAMPER_DETECTED`: Invoice payload or vendor account modified after computation.
206
- - `ERR_LEASE_ALREADY_CONSUMED`: Replay or concurrent payment attempt detected.
207
- - `ERR_LEASE_TTL_EXPIRED`: Lease expired before human authorization and settlement.
208
-
209
- ### 3.5 Stage 5: Human-in-the-Loop Authority Harness
210
- - **Operational Purpose**: Presents verifiable statutory provenance and financial breakdowns to authorized corporate officers (CFO, Controller), ensuring human oversight without requiring manual arithmetic recalculation.
211
- - **Inbound Data Contract**:
212
- - `paymentLease`: Cryptographic lease token with `transactionFingerprint`.
213
- - `statutoryProvenance`: Full execution trace linking statutory section, circular citations, and threshold math.
214
- - **Presentation Consistency Lock & Cryptographic Verification**:
215
- 1. *Presentation Consistency Lock*: Any narrative or explanatory text generated by AI agents to summarize the invoice is verified against the canonical calculation. If the text description misstates a single number, the approval UI locks out.
216
- 2. *Biometric & Cryptographic Co-Signing*: The authorizing officer approves the lease using WebAuthn / FIDO2 hardware enclaves on mobile or desktop devices.
217
- 3. *Dual-Control Risk Escalation*: Transactions exceeding enterprise policy thresholds (e.g., > INR 50,00,000) mandate two independent authorized signatures (e.g., Finance Controller + CFO).
218
- - **Outbound Payload**: Cryptographically signed `ApprovedPaymentLease` transitioning to `AUTHORIZED_FOR_SETTLEMENT`.
219
- - **Failure Modes & Degradation Handling**:
220
- - `ERR_PRESENTATION_LOCK_VIOLATION`: AI explanatory prose conflicts with canonical lease numbers.
221
- - `ERR_DUAL_KEY_SIGNATURE_MISSING`: Second authorized signature absent for transactions above risk threshold.
222
- - `ERR_BIOMETRIC_TOKEN_INVALID`: WebAuthn / FIDO2 cryptographic assertion failed verification.
223
-
224
- ### 3.6 Stage 6: Bank Rail Disbursement & Two-Generals Recovery
225
- - **Operational Purpose**: Dispatches the payout instruction to host-to-host corporate banking rails (RTGS/NEFT/IMPS) and idempotently recovers from network partitions, timeouts, and unacknowledged API states.
226
- - **Inbound Data Contract**:
227
- - `approvedLease`: Verified lease with valid officer signatures.
228
- - `bankCredentials`: Corporate host-to-host banking gateway tokens with mutual TLS 1.3 certificates.
229
- - **Disbursement Protocol & Two-Generals Recovery**:
230
- 1. *Deterministic Idempotency Key*: Bank payout request headers inject:
231
- $$\text{X-Idempotency-Key} = \text{lease.transactionFingerprint}$$
232
- 2. *Execution & Settlement*: Dispatches wire transfer via banking gateway. Upon receiving HTTP 200 with bank settlement acknowledgment, records the official Bank Reference / UTR number (`SIMULATED-RTGS-UTR-2026-891`).
233
- 3. *The Two-Generals Network Partition Recovery*: If the banking call returns HTTP 504 Gateway Timeout or the TCP connection drops mid-flight:
234
- - The runtime *strictly forbids blind retries* to prevent double-disbursement.
235
- - Transitions lease to `SETTLEMENT_SUSPENDED`.
236
- - Initiates an asynchronous out-of-band inquiry protocol (`GET /v1/payouts/{idempotencyKey}`) to poll the core banking system until settlement status is definitively resolved (`SETTLED` vs `FAILED`).
237
- - **Outbound Payload**: Immutable `SettlementReceipt` containing Bank UTR, settlement timestamp, disbursed amount, and fee split.
238
- - **Failure Modes & Degradation Handling**:
239
- - `ERR_SETTLEMENT_TIMEOUT_PENDING_RECONCILIATION`: Bank rail timed out; entered out-of-band UTR verification queue.
240
- - `ERR_BENEFICIARY_ACCOUNT_BLOCKED`: Bank rejected beneficiary account.
241
- - `ERR_TREASURY_INSUFFICIENT_FUNDS`: Corporate treasury operating account has insufficient balance.
242
-
243
- ### 3.7 Stage 7: General Ledger Balanced Double-Entry Writeback
244
- - **Operational Purpose**: Posts the completed transaction to the corporate ERP (SAP S/4HANA, Zoho Books, Oracle NetSuite) as an immutable, balanced double-entry journal entry bound to verified statutory provenance.
245
- - **Inbound Data Contract**:
246
- - `ingestedInvoice`: Line item asset/expense accounts.
247
- - `calculationResult`: Tax withholding accounts and net payable figures.
248
- - `settlementReceipt`: Bank disbursement UTR and bank operating account.
249
- - **Double-Entry Equilibrium & Provenance Invariants**:
250
- 1. *Paisa-Level Equilibrium Invariant*: Enforces mathematical zero-imbalance across integer debits and credits:
251
- $$\sum \text{Debits} - \sum \text{Credits} \equiv \text{INR } 0.00$$
252
- If discrepancy $\neq 0$, writeback is blocked with `ERR_JOURNAL_EQUILIBRIUM_VIOLATION`.
253
- 2. *Source-Bound Line Structure*:
254
- - `DEBIT` Purchases / Cost of Goods Sold (INR 60,00,000.00) — Bound to Invoice Line Items
255
- - `DEBIT` Input CGST Receivable (INR 5,40,000.00) — Bound to CGST Section 16 eligibility
256
- - `DEBIT` Input SGST Receivable (INR 5,40,000.00) — Bound to SGST Section 16 eligibility
257
- - `CREDIT` TDS Payable under Section 194Q (INR 5,500.00) — Bound to Section 194Q / Challan 281
258
- - `CREDIT` Bank Operating Account (INR 70,74,500.00) — Bound to Bank UTR
259
- 3. *Atomic ERP Commit*: Journal posted via ERP REST API with transactional rollback on partial write failure.
260
- - **Outbound Payload**: Final `ReconciledJournalVoucher` (`JV-2026-04-0042`) permanently registered in ERP.
261
- - **Failure Modes & Degradation Handling**:
262
- - `ERR_JOURNAL_EQUILIBRIUM_VIOLATION`: Debits do not equal credits to the exact paisa.
263
- - `ERR_ERP_PERIOD_CLOSED`: Target accounting period is locked in ERP.
264
- - `ERR_ERP_CONNECTION_FAILED`: ERP API unavailable; journal queued in write-ahead log (WAL) for transactional replay.
265
-
266
- ---
267
-
268
- ## 4. The Failure Boundaries of LLMs in Tax Law
269
-
270
- Large Language Models (LLMs) are stochastic token predictors. In corporate accounting, accounts payable automation, and ERP reconciliation, applying generative models directly to statutory compliance introduces a critical failure mode: **the conflation of generative reasoning with transactional and statutory authority**.
271
-
272
- 1. **Non-Linear Cumulative Thresholds**:
273
- Statutory tax provisions in India are non-linear and cumulative across financial years.
274
- *Example*: Under **Section 194Q** of the Income-tax Act, 1961, tax is deductible at 0.1% strictly on the *excess* purchase value over ₹50 Lakhs in a financial year. An LLM presented with an ₹80 Lakh invoice and ₹40 Lakhs of prior purchases frequently computes 0.1% on the full ₹80 Lakhs (₹8,000) instead of the statutory ₹70 Lakh taxable excess (₹7,000)—generating a persistent ₹1,000 tax over-deduction on a single transaction.
275
-
276
- 2. **Temporal Decay & Legislative Sunsets**:
277
- Statutory laws expire or are omitted by annual Finance Acts.
278
- *Example*: **Section 206C(1H)** was omitted by the Finance Act, 2025 effective 1 April 2025. Standard model weights continue citing and enforcing sunset sections long after their legal expiration date because pre-training data lacks temporal enforcement boundaries.
279
-
280
- 3. **Dual-Act Legislative Transition**:
281
- India transitioned to the **Income-tax Act, 2025** (which took effect 1 April 2026), replacing familiar 1961 section numbers with new codifications (e.g., Section 194Q transitions to Section 393(1), Table 1, Sl. No. 8(ii)). Agents without a dual-act mapping layer hallucinate cross-statutory citations.
282
-
283
- 4. **The Failure of Messy Web Searches (Web RAG)**:
284
- When autonomous agents attempt to retrieve tax laws using automated search queries, they ingest conflicting third-party summaries: outdated SEO-optimized accounting blogs from 2018–2022, promotional vendor writeups, and unstructured discussion forums. These sources consistently miss crucial statutory provisos—such as CBDT Circular 13/2021 unbundling GST from TDS, or Ministry of MSME OM 2/1(5)/2021 excluding wholesale/retail traders. Web RAG introduces high latency, burns thousands of context tokens, and injects contradictory noise into agent reasoning.
285
-
286
- 5. **Having the Law ≠ Correct Interpretation (The Computation Boundary)**:
287
- Simply injecting the raw text of a statute into an LLM's context window does **not** ensure statutory compliance. LLMs are probabilistic token sequence predictors, not deterministic arithmetic engines. When an LLM reads Section 194Q or MSMED Section 16, it frequently miscalculates multi-invoice cumulative threshold tracking or monthly compound interest, and defends its erroneous math when challenged (**The Epistemic Confirmation Loop**). Statutory law requires a strict boundary between legal knowledge and mathematical execution.
288
-
289
- ---
290
-
291
- ## 5. Architectural Principle: Sovereign Separation of Powers
292
-
293
- To resolve these vulnerabilities, MudraForge enforces a strict **Separation of Powers**:
294
-
295
- ```
296
- ┌────────────────────────────────────────────────────────────────────────┐
297
- │ 1. Generative Layer (AI Agents / LLMs) │
298
- │ • Assists, extracts messy invoice narrative, and explains context │
299
- │ • Strictly prohibited from authoritative financial computation │
300
- └──────────────────────────────────▲─────────────────────────────────────┘
301
- │ Queries local disk / edge
302
- ┌──────────────────────────────────┴─────────────────────────────────────┐
303
- │ 2. Statutory Knowledge & USVM Substrate (OKF Layer - This Package) │
304
- │ • Authoritative, versioned reference law under Google's OKF standard│
305
- │ • Universal Statutory Virtual Machine (USVM Declarative ASTs) │
306
- │ • Temporal validity state machines (detects sunsets & transitions) │
307
- │ • Zero dependencies, 100% offline-capable, <15µs local evaluation │
308
- └──────────────────────────────────▲─────────────────────────────────────┘
309
- │ Feeds verified ground truth
310
- ┌──────────────────────────────────┴─────────────────────────────────────┐
311
- │ 3. Deterministic Governance & Execution (Adesha Sovereign Runtime) │
312
- │ • 5-stage rational BigInt arithmetic (194Q excess, MSMED 3x RBI) │
313
- │ • Single-use payment leases, CAS gates & Two-Generals recovery │
314
- │ • Double-entry general ledger writeback with source-bound lines │
315
- └────────────────────────────────────────────────────────────────────────┘
316
- ```
317
-
318
- > **Core Postulate**: *The Generative AI assists, analyzes, and explains; the Deterministic Runtime computes, gates, authorizes, executes, and reconciles.*
319
-
320
- ### 5.1 The Inherent Conflict: Reasoning vs. Execution Authority
321
- In traditional software engineering, business logic is explicitly coded into deterministic control-flow graphs. In generative AI, business logic is approximated via probabilistic token probabilities.
322
-
323
- Attempting to grant Large Language Models direct execution authority over financial transactions introduces catastrophic failure modes:
324
- 1. *Soft Constraints Cannot Enforce Hard Law*: System prompts such as *"Always deduct 0.1% on the excess over 50 Lakhs"* are probabilistic guidelines, not hardware or compiler constraints. Adversarial prompt injections, long-context attention degradation, or edge-case invoice phrasing can cause the model to bypass the instruction entirely.
325
- 2. *The Epistemic Confirmation Loop*: When a generative model miscalculates a statutory base (e.g. deducting tax on gross turnover rather than taxable excess), challenging the model frequently causes it to defend its erroneous math with plausible-sounding legal confabulations.
326
- 3. *Lack of Transactional Idempotency*: LLMs lack atomic state tracking. A retried prompt generation can output subtly different financial amounts, different account routing numbers, or altered tax rates for the exact same transaction.
327
-
328
- To ensure safety, MudraForge enforces an absolute **Separation of Powers** across three isolated architectural layers:
329
-
330
- ```
331
- ┌────────────────────────────────────────────────────────────────────────┐
332
- │ 1. GENERATIVE LAYER (AI Agents / Reasoning Engines) │
333
- │ • Ingests messy, unstructured vendor PDF invoices & email trails │
334
- │ • Explains complex multi-statute reasoning to human officers │
335
- │ • STRICTLY READ-ONLY: Prohibited from computing tax or wiring funds │
336
- └──────────────────────────────────┬─────────────────────────────────────┘
337
- │ Dispatches structured queries
338
- ▼
339
- ┌────────────────────────────────────────────────────────────────────────┐
340
- │ 2. STATUTORY KNOWLEDGE & USVM SUBSTRATE (OKF Layer - This Package) │
341
- │ • Declarative legal ground truth under Google OKF specification │
342
- │ • Universal Statutory Virtual Machine (USVM Declarative ASTs) │
343
- │ • Deterministic temporal state machine (sunsets & Act 2025 mappings)│
344
- │ • 100% offline filesystem lookup (<15µs local traversal) │
345
- └──────────────────────────────────┬─────────────────────────────────────┘
346
- │ Feeds verified statutory AST & parameters
347
- ▼
348
- ┌────────────────────────────────────────────────────────────────────────┐
349
- │ 3. DETERMINISTIC GOVERNANCE & SETTLEMENT RUNTIME (Adesha Runtime) │
350
- │ • 5-stage rational BigInt arithmetic (194Q excess, MSMED 3x RBI) │
351
- │ • Single-use cryptographic CAS leases (RFC 8785 + SHA-256) │
352
- │ • Two-Generals idempotent banking recovery (Host-to-Host RTGS) │
353
- │ • Balanced double-entry writeback to core ERP (SAP / Zoho Books) │
354
- └────────────────────────────────────────────────────────────────────────┘
355
- ```
356
-
357
- ### 5.2 Layer 1: Generative Reasoning & Context Extraction (AI Agents)
358
- - **Operational Sandbox**:
359
- - The Generative Layer operates within an unprivileged, read-only security boundary.
360
- - Generative agents (such as LLM workflows, conversational assistants, and triage bots) are provided tools to extract invoice headers, classify line items into probable HSN/SAC codes, and synthesize audit explanations.
361
- - *Hard Enforcement Gate*: The Generative Layer cannot issue API calls to banking rails, payment gateways, or ERP general ledger writeback endpoints. Any attempt by an LLM to invoke execution tools without a valid cryptographic lease is rejected at the API dispatcher gate (`lib/tool_dispatch.js`).
362
-
363
- ### 5.3 Layer 2: Statutory Knowledge Substrate (Google OKF Layer)
364
- - **Declarative Ground Truth**:
365
- - Encapsulates legal provisions, circulars, and forms as versioned, declarative filesystem artifacts.
366
- - Operates completely independent of model weights. When Parliament passes a new Finance Act or the CBDT issues a circular, the knowledge substrate is updated declaratively in `./okf/` without requiring model fine-tuning or prompt re-engineering.
367
- - Implements deterministic temporal routing: evaluates the exact transaction timestamp against statutory effective dates, sunset deadlines, and the *Income-tax Act, 2025* migration matrix.
368
-
369
- ### 5.4 Layer 3: Deterministic Governance & Execution Engine (Adesha Runtime)
370
- - **Authoritative Execution**:
371
- - Holds sole authority to perform mathematical calculations, issue payment instructions, and modify general ledger records.
372
- - Enforces integer-paisa math, eliminating floating-point rounding errors across cumulative calculations.
373
- - Mints single-use Compare-and-Swap (CAS) authorization leases bound to the RFC 8785 canonical hash of the calculation.
374
- - Manages banking settlement state machines, enforcing idempotent recovery protocols to eliminate double-payment risks during network partitions.
375
-
376
- ### 5.5 Threat Model & Invariant Defense Matrix
377
-
378
- | Threat Vector | LLM Failure Mode | MudraForge Architectural Defense |
379
- | :--- | :--- | :--- |
380
- | **Prompt Injection / Jailbreak** | Malicious invoice text tricks LLM into routing funds to hacker's account | Generative layer has zero bank rail access; vendor accounts are resolved against verified vendor master ERP tables by deterministic runtime |
381
- | **Arithmetic Confabulation** | LLM computes 0.1% on ₹80L instead of ₹70L excess, over-deducting tax | Arithmetic execution is completely stripped from LLM and computed by deterministic pure functions in integer paisa |
382
- | **Outdated Statutory Law** | LLM cites expired Section 206C(1H) post-1 April 2025 | OKF Temporal State Machine intercepts expired sections and forces rejection with `ERR_STATUTE_SUNSET_EXPIRED` |
383
- | **Dual-Act Migration Collision** | LLM confuses Section 194Q with Section 393(1) of Act 2025 | Cross-compilation matrix deterministically maps sections based on `transactionDate >= 2026-04-01` |
384
- | **Concurrent Double-Disbursement** | Parallel webhook retries trigger duplicate bank transfers | Single-use Compare-and-Swap (CAS) lease in MongoDB/KV ensures exactly one execution; concurrent calls fail with `LEASE_ALREADY_CONSUMED` |
385
- | **Unbalanced Ledger Writeback** | Out-of-sync API writes unbalanced debit/credit entries to ERP | Zero Paisa Equilibrium Invariant ($\sum \text{Debits} - \sum \text{Credits} \equiv 0.00$) enforced before ERP dispatch |
386
-
387
- ---
388
-
389
- ## 6. The Open Knowledge Format (OKF) Implementation
390
-
391
- The foundation of the statutory knowledge layer is the **Open Knowledge Format (OKF)**, an open specification introduced by Google Cloud as the "OpenAPI for Knowledge" (upstream specification: v0.2).
392
-
393
- Rather than forcing developers and AI agents to query external vector databases or inject large RAG prompts, the OKF represents legal ground truth as a versioned, portable filesystem of human- and agent-readable files.
394
-
395
- ### Domain-Structured Filesystem Architecture
396
-
397
- Statutes in `./okf/` are structured by **regulatory domain** with dedicated sub-directories containing the core statute schema, official executive circulars in Google OKF Markdown, and statutory compliance forms:
398
-
399
- ```
400
- okf/
401
- ├── manifest.json # Cryptographic SHA-256 root hash & domain manifest
402
- │
403
- ├── direct_tax/
404
- │ ├── tds_goods_194q/
405
- │ │ ├── section.json # 0.1% TDS on purchase excess over ₹50L
406
- │ │ ├── circulars/
407
- │ │ │ ├── cbdt_circular_13_2021_guidelines.md # CBDT Q&A on threshold math & advance netting
408
- │ │ │ └── cbdt_circular_23_2017_gst_unbundling.md# Exclusion of GST from TDS base
409
- │ │ └── forms/
410
- │ │ ├── form_26q_quarterly_return.json # Form 26Q quarterly TDS reporting schema
411
- │ │ └── vendor_pan_declaration.md # Vendor PAN & Section 206AB declaration template
412
- │ ├── tds_services_194j/
413
- │ │ ├── section.json # 2% FTS vs 10% Professional fees
414
- │ │ ├── circulars/
415
- │ │ │ └── cbdt_circular_03_2020_fts_rate_cut.md # FTS 2% rate reduction guidelines
416
- │ │ └── forms/
417
- │ │ └── form_16a_tds_certificate.json # Form 16A quarterly TDS certificate schema
418
- │ └── tcs_goods_206c_1h/
419
- │ ├── section.json # Section 206C(1H) sunset on 1 April 2025
420
- │ └── circulars/
421
- │ └── finance_act_2025_sunset_memo.md # Finance Act 2025 omission memo
422
- │
423
- ├── indirect_tax_gst/
424
- │ └── blocked_itc_17_5/
425
- │ ├── section.json # CGST 17(5) blocked credit negative list
426
- │ ├── circulars/
427
- │ │ └── cbic_circular_172_2022_employer_obligations.md # Statutory employer obligation exception
428
- │ └── forms/
429
- │ └── gstr_2b_ineligible_reconciliation.json # GSTR-2B vs 3B Table 4(B) reporting schema
430
- │
431
- ├── msme_commercial/
432
- │ └── delayed_payments_15_16/
433
- │ ├── section.json # 45-day clock, 3x RBI interest & 43B(h)
434
- │ ├── circulars/
435
- │ │ └── msme_om_2021_trader_exclusion.md # Retail/wholesale trader exclusion rule
436
- │ └── forms/
437
- │ ├── udyam_registration_verification.json # UDYAM portal certificate validation schema
438
- │ └── schedule_iii_msme_disclosure.md # Balance Sheet Schedule III disclosure format
439
- │
440
- ├── international_tax/
441
- │ └── foreign_tax_credit_irc_901_904/
442
- │ ├── section.json # US Foreign Tax Credit limitation baskets
443
- │ └── forms/
444
- │ ├── form_67_statement_of_foreign_tax.json # Indian Income Tax Form 67 (Rule 128)
445
- │ └── irs_schedule_k3_reporting.json # US IRS Schedule K-3 dual-reporting schema
446
- │
447
- └── corporate_ma_restructuring/
448
- └── slump_sale_50b/
449
- ├── section.json # Section 50B slump sale & net worth rules
450
- ├── circulars/
451
- │ ├── cbdt_notification_68_2021_rule_11uae_fmv.md # Rule 11UAE Fair Market Value formula
452
- │ └── cbic_notification_12_2017_going_concern_exemption.md # 0% GST going concern exemption
453
- └── forms/
454
- ├── form_3cea_chartered_accountant_report.json # Form 3CEA CA slump sale report schema
455
- └── section_281_tax_clearance_checklist.md # Section 281 & 313 due diligence checklist
456
- ```
457
-
458
- ### Zero-Token Agent Discovery
459
- When an autonomous agent (Antigravity, Cursor, Claude Code) receives a compliance task:
460
- 1. The agent reads the directory listing of `./okf/` (organized by regulatory domains).
461
- 2. The combination of section code and plain-text description allows the agent to identify the applicable statute at **0 token cost** without RAG hallucinations.
462
- 3. The agent loads only the targeted JSON statute into context.
463
-
464
- ### Dual-Act Legislative Migration Matrix
465
- The OKF embeds a cross-compilation matrix forward-mapping the *Income-tax Act, 1961* to the *Income-tax Act, 2025*:
466
- - `194Q` $\rightarrow$ Section 393(1), Table 1, Sl. No. 8(ii)
467
- - `194J` $\rightarrow$ Section 393(1), Table 1, Sl. No. 6(iii)
468
- - `194C` $\rightarrow$ Section 393(1), Table 1, Sl. No. 8(i)
469
-
470
- Transactions dated before 1 April 2026 resolve under the 1961 Act; transactions on or after 1 April 2026 automatically compile under the 2025 Act codification.
471
-
472
- ---
473
-
474
- ## 7. Financial Regulatory Domains Currently Supported
475
-
476
- The OKF statutory substrate is purpose-built for **corporate finance departments, enterprise accounts payable (AP), treasury controllers, and tax compliance teams**.
477
-
478
- Currently, the substrate indexes and provides deterministic ground truth across five vital financial domains:
479
-
480
- ### 1. Direct Tax & Corporate Withholdings (TDS / TCS)
481
- - **Section 194Q**: 0.1% TDS on purchase of goods exceeding ₹50 Lakhs cumulative annual threshold (calculating strictly on the excess over ₹50L).
482
- - **Section 206C(1H)**: TCS on sale of goods, with automated temporal interception of its **1 April 2025 sunset** under the Finance Act, 2025.
483
- - **Section 194J**: Fees for Technical Services (2% FTS) vs. Professional Fees (10%), enforcing standard 20% non-PAN penalty rates under Section 206AA(1)(iii) / Section 397(2)(a).
484
- - **Dual-Act Forward Mapping**: Complete cross-compilation matrix from *Income-tax Act, 1961* to the *Income-tax Act, 2025* (which took effect 1 April 2026), mapping sections seamlessly (e.g., Section 194Q → Section 393(1), Table 1, Sl. No. 8(ii)).
485
-
486
- ### 2. Indirect Tax & Procurement Compliance (GST)
487
- - **CGST Section 17(5)**: Comprehensive statutory negative list for Blocked Input Tax Credit (ITC)—including motor vehicles, corporate food & beverages, personal consumption, club memberships, and statutory exceptions/provisos.
488
-
489
- ### 3. Micro, Small & Medium Enterprises (MSME Working Capital & Section 43B(h))
490
- - **MSMED Act, 2006 (Sections 15 & 16)**: Strict statutory payment clock (15 days without agreement, max 45 days with written agreement) and non-negotiable compound penal interest at **3 times the RBI Bank Rate** (compounded monthly).
491
- - **Trader Exclusion Rule**: Automated enforcement of Ministry of MSME OM No. 2/1(5)/2021-P&G/Policy, strictly excluding wholesale and retail traders (NIC 45, 46, 47) from delayed payment protection.
492
- - **Income Tax Linkage**: Cross-statutory disallowance rules under Section 43B(h) for overdue vendor payables.
493
-
494
- ### 4. Cross-Border Remittances & Dual-Reporting
495
- - **US Internal Revenue Code (IRC §§ 901 & 904)**: Foreign Tax Credit (FTC) limitation baskets (General Category vs. Passive Category), Pass-Through Entity (PTE) tax pass-throughs, and Schedule K-3 dual-reporting compliance for Indo-US cross-border ventures.
496
-
497
- ### 5. Corporate M&A, Restructuring & Successor Liability
498
- - **Section 50B**: Special provision for computation of capital gains in case of slump sale (organic undertaking test, book value net worth minus liabilities, WDV for depreciable assets u/s 43(6), revaluations ignored, indexation unavailable u/s 50B(2)).
499
- - **Rule 11UAE Fair Market Value**: CBDT Notification 68/2021 deemed full value of consideration formula: $\max(\text{FMV}_1, \text{FMV}_2)$.
500
- - **CBIC Notification 12/2017 Entry 2**: 0% GST going concern exemption verification for business transfers.
501
- - **Section 281 & Section 313**: Pre-closing tax clearance NOC and joint/several successor tax liability enforcement under direct and indirect tax law.
502
-
503
- ---
504
-
505
- ## 8. Requesting New Statutes & Expanding Legal Domains
506
-
507
- Enterprise finance operations are broad, and finance teams frequently encounter specialized regulatory frameworks beyond the initial core set.
508
-
509
- **Do you need support for an additional tax domain or statutory provision?**
510
- Examples of sections and domains we are actively indexing or can prioritize on request:
511
- - **International & Transfer Pricing**: Section 92E / Master File / Local File compliance.
512
- - **Digital Economy Taxes**: Equalisation Levy (Section 165) and Section 194S (Crypto/VDA TDS).
513
- - **Lower Deduction Certificates**: Section 197 / Section 195 certificate exhaustion monitoring.
514
- - **State-Specific Compliance**: State Stamp Duty acts, Professional Tax, and State GST variations.
515
- - **Cross-Border Jurisdictions**: UK Corporation Tax (HMRC), Singapore IRAS GST, or US State Apportionment / Sales Tax Nexus.
516
-
517
- ### How to Request a Statute or Legal Domain:
518
- 1. **GitHub Issues**: Open an issue on [`github.com/mondeep0123/mudraforge-statutory`](https://github.com/mondeep0123/mudraforge-statutory/issues) using the `statute-request` or `domain-support` label. Include the governing statute, section number, and primary CBDT/CBIC/regulatory citations.
519
- 2. **Direct Contact**: Email our engineering and tax research team at [hello@mudraforge.in](mailto:hello@mudraforge.in) or [support@mudraforge.in](mailto:support@mudraforge.in).
520
- 3. **CA & Legal Practitioner Empanelment**: If you are a Chartered Accountant (CA), CPA, or tax attorney and want to co-author, audit, or review statutory packs with official attribution and review records, reach out directly to Mondeep Engti at [mondeepe@gmail.com](mailto:mondeepe@gmail.com).
521
-
522
- ---
523
-
524
- ## 9. How the Knowledge Layer Connects to Adesha
525
-
526
- The statutory substrate published in this repository (`@mudraforge/statutory`) acts as the declarative knowledge layer for the broader **MudraForge Adesha Governance Platform**:
527
-
528
- ```mermaid
529
- flowchart TD
530
- AP["Corporate AP Stream:<br/>PDF Invoices / IRN e-Invoices"] --> Triage["Statutory Domain Classifier<br/>& Context Builder"]
531
-
532
- subgraph Tier1["Tier 1: Open Substrate & USVM (This Repository)"]
533
- Triage --> Substrate{"Local OKF Filesystem<br/>(Zero Network Calls)"}
534
- Substrate --> S1["194Q Thresholds & Excess AST"]
535
- Substrate --> S2["206C(1H) Sunset Evaluation AST"]
536
- Substrate --> S3["MSMED 15/16 Payment Rules AST"]
537
- Substrate --> S4["194J FTS vs Professional AST"]
538
- S1 & S2 & S3 & S4 --> USVMKernel["USVM Declarative Kernel<br/>(<15µs Latency, Rational BigInt)"]
539
- end
540
-
541
- subgraph Tier2["Tier 2: Hosted Edge Sync API (api.mudraforge.in)"]
542
- Substrate -.-> EdgeSync["Remote Manifest Check & Sync<br/>(Cloudflare 300+ PoPs)"]
543
- EdgeSync --> RemoteCatalog["11-Domain Roadmap Catalog"]
544
- end
545
-
546
- subgraph Tier3["Tier 3: Commercial Adesha Governance Runtime"]
547
- USVMKernel --> USVMRuntime["Enterprise USVM Pipeline<br/>(Ledger Accumulator & 3x RBI)"]
548
- USVMRuntime --> CanonResult["Canonical Financial Result<br/>(RFC 8785 JCS + SHA-256 Seal)"]
549
- CanonResult --> PresLock["Presentation Consistency Lock<br/>(Automated Prose Auditor)"]
550
- PresLock --> Lease["Single-Use Payment Lease<br/>(Atomic CAS Gate)"]
551
- Lease --> Bank["Banking Outflow Rails<br/>(RazorpayX / Host-to-Host)"]
552
- Bank --> GL["Double-Entry General Ledger<br/>(Zoho Books / SAP Writeback)"]
553
- end
554
- ```
555
-
556
- ### Subsystem Boundary Delineation
557
-
558
- | Capability | Tier 1: Free Open-Source Commons (`@mudraforge/statutory`) | Tier 2: Paid Hosted API (`api.mudraforge.in`) | Tier 3: Full Vertical Enterprise Deployment (Adesha Runtime) |
559
- | :--- | :--- | :--- | :--- |
560
- | **Deployment Model** | Local NPM Package / CLI | Globally Distributed Cloudflare Edge API | Enterprise Private VPC / On-Premise Cluster |
561
- | **Statutory Text & Schemas** | Included (OKF v0.2 / MIT) | Remote edge catalog | Included & Maintained |
562
- | **Offline Filesystem Traversal** | Supported (Sub-1ms local lookup, 0 network calls) | N/A (Edge API requires network) | Local caching within VPC |
563
- | **Edge Synchronization** | **Included** (Free best-effort sync: `npx @mudraforge/statutory sync`) | Priority SLA edge sync & expanded catalog | Automated continuous gazette synchronization |
564
- | **Agent Skill Interface** | Included (`init-skill` CLI) | Supported | Included |
565
- | **Deterministic Tax Math & USVM** | Included via USVM (`@mudraforge/statutory/usvm`) | Gated Edge USVM API (`POST /calculate`) | Built-in native USVM execution with live ledger hooks |
566
- | **Systems of Record (SoR) Access** | None (Stateless) | None (Stateless) | **Direct Live Integration** (SAP, Zoho, Oracle, Bank Rails) |
567
- | **Statutory Claim Validator** | Excluded | Excluded | **Included Exclusively** *(Strictly requires live access to enterprise Systems of Record)* |
568
- | **Payment Authorization Leases**| Excluded | Excluded | Single-use cryptographic CAS leases |
569
- | **Bank Rail Settlement Recovery**| Excluded | Excluded | Two-Generals idempotent recovery |
570
- | **General Ledger Writeback** | Excluded | Excluded | Source-bound balanced double-entry |
571
-
572
- ### 9.1 Multi-Tier Architectural Topology & Topology Mapping
573
-
574
- The interaction between the open statutory substrate, the hosted edge services, and the full enterprise runtime operates across three distinct operational tiers:
575
-
576
- 1. **Tier 1: Free Open-Source Commons (`@mudraforge/statutory`)**
577
- - *Deployment Target*: Deployed directly inside developer applications, CI/CD runners, local development environments, and agent contexts.
578
- - *Execution Model*: Pure synchronous local filesystem traversal (`./okf/`).
579
- - *Synchronization*: **Includes free edge synchronization** via Cloudflare Anycast (`npx @mudraforge/statutory sync`) on a best-effort beta basis.
580
- - *Dependencies & Isolation*: Zero external npm dependencies, zero mandatory network connections, zero runtime telemetries. Provides sub-millisecond lookup latency (< 0.8ms), completely immune to external outages.
581
-
582
- 2. **Tier 2: Paid Hosted API (`api.mudraforge.in`)**
583
- - *Deployment Target*: Globally distributed edge network running on Cloudflare Workers V8 isolates across 300+ global Points of Presence (PoPs).
584
- - *Execution Model*: Stateless, metered HTTP API endpoints (`POST /v1/statutory/calculate`, `POST /v1/statutory/sync`).
585
- - *State Layer*: Cloudflare Workers KV using the Immutable Release Key Pattern.
586
- - *Function*: Provides priority SLA gazette synchronization, real-time regulatory alerts, and cloud-hosted deterministic tax calculation without requiring local infrastructure management.
587
-
588
- 3. **Tier 3: Full Vertical Enterprise Deployment (Commercial Adesha Runtime)**
589
- - *Deployment Target*: Dedicated enterprise VPCs (AWS, GCP, Azure, or on-premise Kubernetes clusters).
590
- - *Execution Model*: Stateful orchestration, atomic CAS lease management, and direct integration with **Systems of Record (SoRs)**.
591
- - *Systems of Record (SoR) Integration*: Deep, authenticated read/write access to corporate ERPs (SAP S/4HANA, Zoho Books, Oracle NetSuite), verified vendor master databases, and corporate host-to-host banking gateways.
592
- - *Exclusive Capabilities*: Holds the **Statutory Claim Validator**, single-use payment leases, Two-Generals banking recovery, and source-bound general ledger writebacks.
593
-
594
- ### 9.2 Cryptographic Verification Envelope Across Tiers
595
-
596
- Data traveling between tiers is encapsulated within a deterministic verification envelope:
597
-
598
- ```json
599
- {
600
- "protocolVersion": "okf/2.10.0",
601
- "domain": "direct_tax",
602
- "sectionCode": "194Q",
603
- "manifestDigest": "sha256-4bbe36c3db841b833dd2bebbd6c1c5ed735498e7b20d1221c323ceb211529fe0",
604
- "effectiveTemporalStatus": "ACTIVE",
605
- "canonicalParameters": {
606
- "standardRatePercent": 0.1,
607
- "annualThresholdPaisa": 500000000,
608
- "taxableBaseRule": "EXCESS_OVER_THRESHOLD_ONLY",
609
- "gstUnbundlingMandatory": true,
610
- "inoperativePanRatePercent": 5.0
611
- },
612
- "verificationSignature": "sha256-4c8a2b..."
613
- }
614
- ```
615
-
616
- - When Tier 3 (Adesha Runtime) ingests statutory parameters from Tier 1 or Tier 2, it computes the SHA-256 Merkle root hash of the payload and asserts equivalence against the versioned manifest.
617
- - If a single character, threshold number, or circular interpretation is altered or corrupted in transit, the Merkle root mismatch aborts execution before the deterministic calculator runs.
618
-
619
- ### 9.3 Edge Consistency & Eventual Consistency Resolution (Cloudflare KV)
620
-
621
- Cloudflare Workers KV provides global low-latency reads via eventual consistency across edge nodes. To prevent release skew during regulatory updates:
622
- 1. *Immutable Version Tagging*: All statutory releases are written under unique semver namespaces (`statutory:releases:v2.13.0:...`).
623
- 2. *Atomic Manifest Flip*: The global pointer `statutory:active_release` is updated only after all 191 files across all domains are fully confirmed across edge replicas.
624
- 3. *Cache-Control Invalidation*: Manifest responses carry strict validation headers (`ETag: "v2.13.0"`, `stale-while-revalidate=600`).
625
- 4. *Local Fallback*: If Tier 2 returns HTTP 5xx or fails DNS resolution, Tier 1 and Tier 3 automatically fall back to the bundled local filesystem snapshot without failing the active business transaction.
626
-
627
- ### 9.4 Architectural Boundaries: The Autonomous Coprocessor vs. Stateless Subsystems
628
-
629
- A common misconception in enterprise AI is viewing statutory compliance as a post-facto "accounting script" that merely posts journal entries at the end of a transaction.
630
-
631
- Within the MudraForge Adesha platform, this architecture operates as a **Comprehensive Statutory Governance Coprocessor for Enterprise AI Agents**. Whenever an autonomous agent performs any legal, tax, or regulatory task—whether answering an executive tax query, evaluating procurement contract terms, drafting vendor compliance notices, or calculating statutory deductions—this coprocessor intercepts the workflow to ground agent reasoning in deterministic law and live enterprise truth.
632
-
633
- To balance open developer accessibility with enterprise security, the architecture establishes a clear boundary between **stateless modular subsystems** and the **full vertical deployment**:
634
-
635
- ```
636
- ┌────────────────────────────────────────────────────────────────────────┐
637
- │ STATELESS REFERENCE & USVM ENGINE (Tiers 1 & 2) │
638
- │ ~50% Functional Scope (Decoupled Reference Law, ASTs & USVM) │
639
- │ • Normalized OKF v0.2 schemas, rates, thresholds, and sunset timelines │
640
- │ • Universal Statutory Virtual Machine (USVM) declarative AST kernel │
641
- │ • 5-stage rational BigInt arithmetic eliminating IEEE 754 float drift │
642
- │ • Synchronous offline filesystem lookup (Tier 1 Free Package & CLI) │
643
- │ • Best-effort edge gazette synchronization (Tier 1 & Tier 2) │
644
- │ • Metered stateless cloud USVM API (Tier 2 POST /calculate) │
645
- │ • Scope: Stateless reference & USVM math; ZERO enterprise SoR access │
646
- └──────────────────────────────────┬─────────────────────────────────────┘
647
- │ Integrated into
648
- ▼
649
- ┌────────────────────────────────────────────────────────────────────────┐
650
- │ FULL VERTICAL SOVEREIGN ENTERPRISE COPROCESSOR (Tier 3 Adesha Runtime) │
651
- │ 100% Functional Scope (Full Governance, Validation & Execution) │
652
- │ • Direct, authenticated connectivity to Systems of Record (SoRs): │
653
- │ - Live ERP General Ledgers (SAP S/4HANA, Zoho Books, Oracle) │
654
- │ - Enterprise Chart of Accounts & Historical Vendor Spend │
655
- │ - Verified Vendor Master & Tax Compliance Directories │
656
- │ • Activated Subsystems (Exclusive to Full Vertical Deployment): │
657
- │ 1. Statutory Claim Validator (Verifies AI/vendor claims vs SoR data) │
658
- │ 2. Presentation Consistency Lock (Audits LLM text against math) │
659
- │ 3. Single-Use Cryptographic Payment Leases (Atomic CAS gates) │
660
- │ 4. Two-Generals Host-to-Host Banking Rail Settlement Recovery │
661
- │ 5. Source-Bound Balanced Double-Entry ERP Writeback │
662
- └────────────────────────────────────────────────────────────────────────┘
663
- ```
664
-
665
- 1. **The Stateless Modular Subsystem (Tiers 1 & 2)**:
666
- The open-source `@mudraforge/statutory` package and the hosted edge API represent a decoupled, stateless core providing approximately half of the functional capability of the complete coprocessor. They supply the declarative legal schemas, temporal validity graphs, and stateless arithmetic calculators. They operate in complete isolation from internal company databases, providing sub-millisecond reference lookups and cloud tax calculations without requiring access to private enterprise data.
667
-
668
- 2. **The Full Sovereign Coprocessor (Tier 3 Vertical Deployment)**:
669
- The full vertical deployment embeds this stateless engine into the enterprise's private security perimeter, granting it live read/write integration with core Systems of Record (SoRs). This transforms the stateless engine into an authoritative governance coprocessor: whenever an AI agent reasons about or acts on a financial transaction, the coprocessor verifies the agent's assertions against actual ledger history, enforces single-use payment leases, and writes balanced double-entries to the corporate ERP.
670
-
671
- ### 9.5 The Statutory Claim Validator Subsystem (Tier 3 Exclusive)
672
-
673
- The **Statutory Claim Validator** is deployed exclusively within the **Tier 3 Full Vertical Deployment**. It is architecturally decoupled from the public edge API because validating statutory assertions—whether made by a vendor on an invoice or generated by an LLM in natural language—**strictly requires authenticated, stateful access to enterprise Systems of Record (SoRs)**:
674
-
675
- 1. **Why SoR Access is Architecturally Mandatory**:
676
- - *Cumulative Spend History*: To validate an assertion under Section 194Q, the validator must inspect the corporate general ledger across all historical fiscal-year purchases for that specific vendor. A stateless public API without access to private ERP ledgers cannot determine if an annual threshold has been crossed.
677
- - *Line-Item & Chart-of-Accounts Context*: To evaluate whether an Input Tax Credit (ITC) claim is blocked under CGST Section 17(5), the validator must inspect the expenditure classification against the enterprise chart of accounts (e.g. differentiating passenger vehicle leases from commercial logistics transport).
678
- - *Vendor Master & Tax Compliance Filing Records*: Validating vendor standing for Section 206AB/206AA penalty tiers requires cross-referencing internal vendor master tax declarations.
679
- - *Zero Financial Data Leakage*: Enterprise accounting drafts, line-item pricing, and vendor accounts never leave the private enterprise VPC perimeter.
680
-
681
- 2. **Core Claim Validation Gates**:
682
- - **Input Tax Credit (ITC) Eligibility Verification**: Evaluates line-item HSN/SAC classifications against statutory blocked lists under CGST Section 17(5). Non-creditable expenses (personal transport, outdoor catering, club memberships) are automatically reclassified as uncreditable business costs rather than claimable input tax.
683
- - **Enterprise Entity & MSME Status Verification**: Cross-references supplier registration records under the MSMED Act, 2006, enforcing administrative exclusions (such as the exclusion of retail/wholesale traders under NIC 45/46/47 per Ministry of MSME OM No. 2/1(5)/2021-P&G/Policy).
684
- - **Vendor Compliance Standing & Penalty Rate Interception**: Inspects vendor compliance metrics to evaluate higher deduction rates under Section 206AB (non-filers of income tax returns) and Section 206AA (inoperative PAN status), elevating standard rates to mandatory statutory penalty tiers (5% or 20%) when non-compliance is verified.
685
- - **AI Assertion & Presentation Lock Verification**: Validates narrative claims generated by LLM assistants against verified SoR ground truth, ensuring no hallucinated tax rate, threshold, or section reference reaches human approving officers.
686
-
687
- ### 9.6 The Universal Statutory Virtual Machine (USVM) & Edge Calculation
688
-
689
- The **Universal Statutory Virtual Machine (USVM)** (`@mudraforge/statutory/usvm`) provides a stateless, declarative AST execution kernel that eliminates hardcoded procedural calculation logic:
690
-
691
- 1. **Declarative Abstract Syntax Tree (AST) Rules**:
692
- Statutes are compiled into declarative AST expressions (e.g. `okf/*/ast.json` and `src/usvm/rules/*.json`). The virtual machine evaluates logical and arithmetic operations without embedding hardcoded procedural branching in application code.
693
- 2. **Multi-Invoice Cumulative Spend Tracking**:
694
- Statutory provisions requiring cumulative threshold evaluations (such as Section 194Q) evaluate prior purchases against financial-year limits, withholding strictly on the marginal excess exceeding the statutory limit (e.g. INR 50,00,000) rather than the aggregate invoice gross.
695
- 3. **Tax Component Unbundling**:
696
- Implements administrative guidelines (including CBDT Circular 13/2021) requiring the exclusion of separately billed GST components from the tax deduction base, preventing compounding tax-on-tax withholding errors.
697
- 4. **5-Stage Rational BigInt Arithmetic (`math_rational.js`)**:
698
- Calculations are executed with rational fractions (`[numerator, denominator]` BigInt pairs) to eliminate IEEE 754 floating-point drift before rounding to the nearest paisa (`roundToPaisa`).
699
- 5. **Cryptographic CAS Lease Minting**:
700
- The resulting payment authorization is sealed via RFC 8785 JSON Canonicalization Scheme (JCS) and SHA-256 into a single-use Compare-and-Swap (CAS) lease. Any subsequent alteration to the transaction payload, beneficiary details, or tax allocation invalidates the lease prior to banking dispatch.
701
- 6. **Distributed Edge Synchronization & Lightweight Tree-Shaking**:
702
- Exposed via tree-shakable subpath `@mudraforge/statutory/usvm` (~12 kB GZIP vs 92.9 kB full library), enabling microsecond edge evaluation on Cloudflare Workers V8 isolates without cold start latency.
703
-
704
- ---
705
-
706
- ## 10. Working Example: Offline Traversal & USVM Execution
707
-
708
- The public package allows developers and agents to traverse statutory law and evaluate rules with zero external network requests:
709
-
710
- ```javascript
711
- import { lookupLocalStatute, isStatuteActive } from '@mudraforge/statutory';
712
- import { evaluateStatutoryAst, getStatutoryAst } from '@mudraforge/statutory/usvm';
713
-
714
- // 1. Look up Section 194Q offline (sub-1ms)
715
- const statute = lookupLocalStatute('194Q');
716
- console.log(statute.title);
717
- console.log(statute.keyStatutoryThresholds.taxableBaseScope);
718
- // => "Tax is deductible strictly on the excess over ₹50 Lakhs, NOT on the aggregate gross turnover."
719
-
720
- // 2. Check temporal status against effective dates
721
- const isActive2024 = await isStatuteActive('206C(1H)', '2024-05-01'); // true
722
- const isActive2025 = await isStatuteActive('206C(1H)', '2025-06-01'); // false (sunset effective 1 April 2025)
723
-
724
- // 3. Evaluate Section 194Q via USVM Declarative AST (<15µs latency)
725
- const ast194Q = getStatutoryAst('194Q');
726
- const voucher = evaluateStatutoryAst(ast194Q, {
727
- invoiceAmount: 6000000,
728
- priorFyPurchases: 4500000,
729
- hasPan: true,
730
- transactionDate: '2026-03-15'
731
- });
732
- console.log(voucher.calculatedTdsInr); // 5500 (0.1% on excess over ₹50L)
733
- console.log(voucher.isAuthorizedToDisburse); // false (Fiduciary invariant)
734
- ```
735
-
736
- ---
737
-
738
- ## 11. Public Commons vs. Commercial Lifecycle & Sustainability Policy
739
-
740
- ### 11.1 Free Edge Sync and Maintenance Policy
741
- The MudraForge Statutory project publishes an open, locally usable statutory knowledge package under the MIT License. The hosted free sync service (`npx @mudraforge/statutory sync`) is provided on a best-effort basis and is not a guarantee of perpetual availability, comprehensive statutory coverage, or continuous updates.
742
-
743
- 1. **Maintainer Capacity & Community Updates**: Future updates to the hosted free dataset depend on maintainer capacity, community contributions, infrastructure costs, and project priorities. The free service may experience limited coverage, delayed updates, or periods without new releases.
744
- 2. **Deterministic Versioning**: Each published bundle explicitly identifies its release version, source provenance, and applicable verification or effective-date information. Users are responsible for checking whether a statutory snapshot is current and suitable for their intended use.
745
- 3. **Perpetual MIT License Guarantee**: Every statutory file and manifest downloaded or cloned under the MIT license remains permanently free for offline traversal, local agent skills, and internal experimentation. Organizations are free to inspect, fork, and maintain their local `./okf/` directories indefinitely.
746
- 4. **Commercial Services**: Additional hosted services, comprehensive domain suites (all 11 enterprise domains), and maintained deterministic calculation engines are offered separately under commercial subscriptions.
747
-
748
- ---
749
-
750
- ### 11.2 Edge Consistency & Immutable Release Strategy (Cloudflare KV)
751
-
752
- Cloudflare Workers KV is a globally distributed, eventually consistent storage layer across 300+ points of presence (PoPs). In statutory finance, serving inconsistent states during an active release rollout (e.g. one edge PoP serving an amended 0.1% TDS rate while another serves an outdated 1% rate) introduces compliance risk.
753
-
754
- To prevent version skew across regions, the edge runtime employs an **Immutable Release Key Pattern**:
755
-
756
- 1. **Immutable Artifact Keys**: Every section schema, circular, and form is stored under an immutable, version-tagged key:
757
- ```
758
- statutory:releases:<semver>:<domain>:<section_code>
759
- # Example: statutory:releases:v2.13.0:direct_tax:194Q
760
- ```
761
- Once written to KV, the bytes for a specific semver key are permanently immutable.
762
- 2. **Atomic Manifest Pointers**: Releases are indexed by a versioned root manifest (`statutory:manifests:v2.13.0`). The active pointer is switched only after all constituent keys are fully populated.
763
- 3. **Cache Invalidation & ETag Gates**: The manifest endpoint serves HTTP `ETag` validators with short edge TTLs (`Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=600`). This ensures edge caches converge globally within minutes while allowing clients to detect release changes via deterministic SHA-256 root hash comparisons.
764
- - **Commercial Boundary**: Only the automated, continuously maintained edge update stream, neural discovery search, and deep deterministic calculator engines require an Enterprise API subscription post-beta.
765
-
766
- ---
767
-
768
- ## 12. Related Documents
769
-
770
- - [`DOMAIN_BREADTH_AND_DEPTH_COMPARISON.md`](./DOMAIN_BREADTH_AND_DEPTH_COMPARISON.md) — Authoritative matrix comparing the 5 starter domains against the full 11-domain sovereign roadmap.
771
- - [`VERIFICATION.md`](./VERIFICATION.md) — Formal verification report, TLA+ state machine model, mutation tests, and documented limitations.
772
- - [`ENTERPRISE_GOVERNANCE.md`](./ENTERPRISE_GOVERNANCE.md) — The Adesha governance architecture: single-use payment leases, Two-Generals banking recovery, and ERP writebacks.
773
- - [`README.md`](../README.md) — Quickstart, CLI commands, and installation guide.