apodictic-sdk 0.0.0-stage → 3.9.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * @apodictic/sdk — Odoo 18–20 JSON-2, /doc-bearer/ OpenAPI Schema & MCP Scope Firewall
3
+ * Encodes Odoo 19/20 breaking transitions:
4
+ * - Deprecation of XML-RPC / legacy /jsonrpc and removal of remote `db` RPC service
5
+ * - POST /json/2/<model>/<method> Bearer API + X-Odoo-Database header
6
+ * - Mandatory bearer_scope gating ('mcp' read/staging vs 'rpc' privileged ledger ops)
7
+ * - hard_lock_date / fiscalyear_lock_date / inalterable_hash immutability invariants
8
+ * - Multi-row account.move.line integer-cent balance, multi-currency sign parity & analytic_distribution
9
+ * - Immutable field_diff journal compensating for Odoo 20's removal of stored chatter tracking values
10
+ */
11
+
12
+ export const DESTRUCTIVE_ODOO_METHODS = new Set([
13
+ 'unlink',
14
+ 'button_draft',
15
+ 'button_cancel',
16
+ 'action_cancel',
17
+ 'reset_to_draft',
18
+ ]);
19
+
20
+ export const PROTECTED_ACCOUNTING_MODELS = new Set([
21
+ 'account.move',
22
+ 'account.move.line',
23
+ 'account.payment',
24
+ 'account.journal',
25
+ 'res.company',
26
+ 'ir.rule',
27
+ 'ir.model.access',
28
+ ]);
29
+
30
+ const VALID_X2M_CMD_CODES = new Set([0, 1, 2, 3, 4, 5, 6]);
31
+
32
+ export function toCents(val) {
33
+ const n = Number(val ?? 0);
34
+ if (!Number.isFinite(n)) throw new Error('Non-finite monetary value rejected');
35
+ return Math.round(n * 100);
36
+ }
37
+
38
+ /**
39
+ * Normalize an Odoo 20 /json/2/<model>/<method> URL or MCP tool payload into a structured call descriptor.
40
+ */
41
+ export function extractOdoo20Call(input = {}) {
42
+ const raw = typeof input === 'string' ? input : String(input.sql || input.payload || '');
43
+ const odoo = input.odoo && typeof input.odoo === 'object' ? input.odoo : {};
44
+
45
+ let urlPath = String(odoo.endpointPath || input.endpointPath || '');
46
+ let model = String(odoo.model || input.model || '').trim();
47
+ let method = String(odoo.method || input.method || '').trim();
48
+
49
+ if (!model || !method) {
50
+ const pathMatch = (urlPath || raw).match(/\/json\/2\/([a-z0-9_.]+)\/([a-z0-9_]+)/i);
51
+ if (pathMatch) {
52
+ model = model || pathMatch[1];
53
+ method = method || pathMatch[2];
54
+ }
55
+ }
56
+
57
+ // Detect deprecated /xmlrpc/2/ or removed /json/2/db/ RPC usage
58
+ const lowerCombined = `${urlPath} ${raw}`.toLowerCase();
59
+ const usesLegacyXmlRpc = /\/xmlrpc(?:\/2)?\/(?:common|object|db)/.test(lowerCombined);
60
+ const usesRemovedDbService = /\/(?:json\/2|xmlrpc(?:\/2)?|jsonrpc)\/db\b|\bservice\s*[:=]\s*['"]?db['"]?/.test(lowerCombined)
61
+ || model === 'db';
62
+
63
+ const valsList = Array.isArray(odoo.valsList)
64
+ ? odoo.valsList
65
+ : Array.isArray(odoo.vals_list)
66
+ ? odoo.vals_list
67
+ : odoo.vals && typeof odoo.vals === 'object'
68
+ ? [odoo.vals]
69
+ : [];
70
+
71
+ return {
72
+ isOdooCall: Boolean(model || method || usesLegacyXmlRpc || usesRemovedDbService || odoo.bearerScope || odoo.lineItems || odoo.lines),
73
+ model,
74
+ method,
75
+ urlPath,
76
+ usesLegacyXmlRpc,
77
+ usesRemovedDbService,
78
+ bearerScope: odoo.bearerScope || odoo.bearer_scope || input.bearerScope || null,
79
+ dbName: odoo.database || odoo.xOdooDatabase || input.odooDatabase || null,
80
+ moveDate: odoo.moveDate || odoo.date || null,
81
+ hardLockDate: odoo.hardLockDate || odoo.hard_lock_date || null,
82
+ fiscalyearLockDate: odoo.fiscalyearLockDate || odoo.fiscalyear_lock_date || null,
83
+ taxLockDate: odoo.taxLockDate || odoo.tax_lock_date || null,
84
+ postedBefore: Boolean(odoo.postedBefore ?? odoo.posted_before),
85
+ inalterableHash: odoo.inalterableHash || odoo.inalterable_hash || null,
86
+ companyCurrencyId: odoo.companyCurrencyId || odoo.company_currency_id || 'EGP',
87
+ cfoSigned: Boolean(input.cfoSigned ?? odoo.cfoSigned),
88
+ openApiSchema: odoo.openApiSchema || odoo.docBearerSchema || null,
89
+ ids: Array.isArray(odoo.ids) ? odoo.ids : [],
90
+ valsList,
91
+ lineItems: Array.isArray(odoo.lineItems)
92
+ ? odoo.lineItems
93
+ : Array.isArray(odoo.lines)
94
+ ? odoo.lines
95
+ : extractLinesFromVals(valsList),
96
+ beforeRecord: odoo.beforeRecord || null,
97
+ };
98
+ }
99
+
100
+ function extractLinesFromVals(valsList) {
101
+ const lines = [];
102
+ for (const vals of valsList) {
103
+ if (!vals || typeof vals !== 'object') continue;
104
+ const cmds = vals.line_ids || vals.invoice_line_ids;
105
+ if (Array.isArray(cmds)) {
106
+ for (const cmd of cmds) {
107
+ if (Array.isArray(cmd) && (cmd[0] === 0 || cmd[0] === 1) && cmd[2] && typeof cmd[2] === 'object') {
108
+ lines.push(cmd[2]);
109
+ }
110
+ }
111
+ } else if ('debit' in vals || 'credit' in vals || 'balance' in vals || 'amount_currency' in vals || 'analytic_distribution' in vals) {
112
+ lines.push(vals);
113
+ }
114
+ }
115
+ return lines;
116
+ }
117
+
118
+ /**
119
+ * Evaluate Odoo 18-20 structural, scope, fiscal-lock, OpenAPI schema, multi-currency,
120
+ * and analytic_distribution invariants. Returns exact minor-unit facts for Z3/OxiZ proof.
121
+ */
122
+ export function evaluateOdoo20Call(input = {}) {
123
+ const call = extractOdoo20Call(input);
124
+ if (!call.isOdooCall) {
125
+ return {
126
+ isOdooCall: false,
127
+ violations: [],
128
+ lineChecks: null,
129
+ reversalHint: null,
130
+ fieldDiff: null,
131
+ };
132
+ }
133
+
134
+ const violations = [];
135
+ const warnings = [];
136
+
137
+ if (call.usesRemovedDbService) {
138
+ violations.push('ODOO20_REMOVED_DB_RPC_BLOCKED');
139
+ }
140
+ if (call.usesLegacyXmlRpc) {
141
+ warnings.push('ODOO_LEGACY_XMLRPC_DEPRECATED_USE_JSON2');
142
+ }
143
+
144
+ // 1. Odoo 20 mandatory bearer_scope gate for AI / MCP agents
145
+ const scope = call.bearerScope ? String(call.bearerScope).toLowerCase() : null;
146
+ if (scope === 'mcp') {
147
+ const isProtectedModel = PROTECTED_ACCOUNTING_MODELS.has(call.model);
148
+ const isDestructiveMethod = DESTRUCTIVE_ODOO_METHODS.has(call.method);
149
+ const isPrivilegedLockWrite =
150
+ call.model === 'res.company' &&
151
+ call.valsList.some((v) =>
152
+ v && Object.keys(v).some((k) => k.endsWith('_lock_date') || k === 'restrict_mode_hash_table')
153
+ );
154
+
155
+ if ((isProtectedModel && isDestructiveMethod) || isPrivilegedLockWrite || call.model === 'ir.rule' || call.model === 'ir.model.access') {
156
+ if (!call.cfoSigned) {
157
+ violations.push('INV_ODOO20_MCP_SCOPE_ESCALATION');
158
+ }
159
+ }
160
+ }
161
+
162
+ // 2. Fiscal lock dates (hard_lock_date / fiscalyear_lock_date / tax_lock_date) & inalterable_hash
163
+ const lockCandidates = [call.hardLockDate, call.fiscalyearLockDate, call.taxLockDate].filter(Boolean).sort();
164
+ const effectiveLockDate = lockCandidates.length > 0 ? lockCandidates[lockCandidates.length - 1] : null;
165
+ if (call.moveDate && effectiveLockDate && String(call.moveDate) <= String(effectiveLockDate)) {
166
+ violations.push('INV_ODOO_FISCAL_LOCK_VIOLATION');
167
+ }
168
+
169
+ if (
170
+ call.inalterableHash &&
171
+ ['write', 'unlink', 'button_draft'].includes(call.method)
172
+ ) {
173
+ violations.push('INV_ODOO_INALTERABLE_HASH_IMMUTABLE');
174
+ } else if (call.postedBefore && (call.method === 'unlink' || call.valsList.some((v) => v && 'name' in v))) {
175
+ violations.push('INV_ODOO_POSTED_BEFORE_SEQUENCE_IMMUTABLE');
176
+ }
177
+
178
+ // 3. OpenAPI /doc-bearer/<model>.json schema + X2many relational tuple validation
179
+ const allowedFields = call.openApiSchema?.properties
180
+ ? new Set(Object.keys(call.openApiSchema.properties))
181
+ : call.openApiSchema?.fields
182
+ ? new Set(Object.keys(call.openApiSchema.fields))
183
+ : null;
184
+
185
+ for (const vals of call.valsList) {
186
+ if (!vals || typeof vals !== 'object') continue;
187
+ for (const [k, v] of Object.entries(vals)) {
188
+ if (allowedFields && !allowedFields.has(k)) {
189
+ violations.push(`ODOO20_SCHEMA_UNKNOWN_FIELD:${k}`);
190
+ }
191
+ if ((k === 'line_ids' || k === 'invoice_line_ids' || k.endsWith('_ids')) && Array.isArray(v)) {
192
+ for (const cmd of v) {
193
+ if (Array.isArray(cmd)) {
194
+ if (!VALID_X2M_CMD_CODES.has(Number(cmd[0]))) {
195
+ violations.push(`ODOO_INVALID_X2M_COMMAND:${cmd[0]}`);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ // 4. Multi-row account.move.line accounting, multi-currency & analytic_distribution checks
204
+ let debitCentsTotal = 0;
205
+ let creditCentsTotal = 0;
206
+ let mutuallyExclusiveViolation = false;
207
+ let currencyParityViolation = false;
208
+ let analyticDistributionViolation = false;
209
+ let analyticPercentSum = null;
210
+
211
+ if (call.lineItems.length > 0) {
212
+ for (const line of call.lineItems) {
213
+ const dCents = toCents(line.debit ?? 0);
214
+ const cCents = toCents(line.credit ?? 0);
215
+ if (dCents < 0 || cCents < 0 || (dCents > 0 && cCents > 0)) {
216
+ mutuallyExclusiveViolation = true;
217
+ }
218
+ debitCentsTotal += dCents;
219
+ creditCentsTotal += cCents;
220
+
221
+ const balanceCents = line.balance !== undefined ? toCents(line.balance) : dCents - cCents;
222
+ if (line.amount_currency !== undefined) {
223
+ const acCents = toCents(line.amount_currency);
224
+ const lineCurr = line.currency_id || call.companyCurrencyId;
225
+ if (lineCurr === call.companyCurrencyId && acCents !== balanceCents) {
226
+ currencyParityViolation = true;
227
+ } else if ((acCents > 0 && balanceCents < 0) || (acCents < 0 && balanceCents > 0)) {
228
+ currencyParityViolation = true;
229
+ }
230
+ }
231
+
232
+ if (line.analytic_distribution && typeof line.analytic_distribution === 'object') {
233
+ const weights = Object.values(line.analytic_distribution).map(Number);
234
+ if (weights.some((w) => !Number.isFinite(w) || w < 0 || w > 100)) {
235
+ analyticDistributionViolation = true;
236
+ } else if (weights.length > 0) {
237
+ analyticPercentSum = Number(weights.reduce((a, b) => a + b, 0).toFixed(4));
238
+ if (Math.abs(analyticPercentSum - 100.0) > 0.01) {
239
+ analyticDistributionViolation = true;
240
+ }
241
+ }
242
+ }
243
+ }
244
+
245
+ if (mutuallyExclusiveViolation) {
246
+ violations.push('INV_ODOO_LINE_DEBIT_CREDIT_MUTEX');
247
+ }
248
+ if (currencyParityViolation) {
249
+ violations.push('INV_ODOO_MULTICURRENCY_SIGN_PARITY');
250
+ }
251
+ if (analyticDistributionViolation) {
252
+ violations.push('INV_ODOO_ANALYTIC_DISTRIBUTION_100PCT');
253
+ }
254
+ }
255
+
256
+ // Build non-destructive compensating credit-note reversal payload for Odoo 18-20
257
+ const targetMoveId = call.ids[0] ?? null;
258
+ const reversalHint = {
259
+ protocol: 'ODOO_JSON2_POST',
260
+ endpoint: '/json/2/account.move.reversal/create',
261
+ followUpEndpoint: '/json/2/account.move.reversal/reverse_moves',
262
+ headers: {
263
+ Authorization: 'Bearer <ODOO_API_KEY>',
264
+ 'X-Odoo-Database': call.dbName || '<ODOO_DB>',
265
+ 'Content-Type': 'application/json',
266
+ },
267
+ body: {
268
+ vals_list: [
269
+ {
270
+ reason: 'Apodictic Z3/OxiZ compensating reversal (inalterable audit preservation)',
271
+ ...(call.moveDate ? { date: call.moveDate } : {}),
272
+ },
273
+ ],
274
+ context: {
275
+ active_model: call.model || 'account.move',
276
+ active_ids: targetMoveId ? [targetMoveId] : [],
277
+ },
278
+ },
279
+ };
280
+
281
+ // Capture immutable field diff to replace removed Odoo 20 stored chatter tracking values
282
+ const fieldDiff = {
283
+ model: call.model,
284
+ method: call.method,
285
+ ids: call.ids,
286
+ before: call.beforeRecord,
287
+ proposed: call.valsList[0] ?? null,
288
+ preservedReason: 'Odoo 20 removed stored chatter tracking values; sealed in Apodictic WORM vault',
289
+ };
290
+
291
+ return {
292
+ isOdooCall: true,
293
+ model: call.model,
294
+ method: call.method,
295
+ bearerScope: scope,
296
+ violations,
297
+ warnings,
298
+ lineChecks: call.lineItems.length > 0
299
+ ? {
300
+ lineCount: call.lineItems.length,
301
+ debitCentsTotal,
302
+ creditCentsTotal,
303
+ debitTotal: Number((debitCentsTotal / 100).toFixed(2)),
304
+ creditTotal: Number((creditCentsTotal / 100).toFixed(2)),
305
+ mutuallyExclusiveViolation,
306
+ currencyParityViolation,
307
+ analyticDistributionViolation,
308
+ analyticPercentSum,
309
+ }
310
+ : null,
311
+ reversalHint,
312
+ fieldDiff,
313
+ };
314
+ }
315
+
316
+ export default {
317
+ extractOdoo20Call,
318
+ evaluateOdoo20Call,
319
+ DESTRUCTIVE_ODOO_METHODS,
320
+ PROTECTED_ACCOUNTING_MODELS,
321
+ };
@@ -0,0 +1,36 @@
1
+ import type { SymbolicGateway, VerifyMutationInput, VerifyMutationResult } from './index.d.ts';
2
+
3
+ export interface CounterfactualPatch {
4
+ max_safe_amount: number;
5
+ reduction_delta: number;
6
+ patched_sql: string | null;
7
+ solver: string;
8
+ }
9
+
10
+ export interface ShadowExecuteInput extends VerifyMutationInput {
11
+ schemaSql?: string;
12
+ seedSql?: string;
13
+ }
14
+
15
+ export interface ShadowExecuteResult {
16
+ verdict: 'SAT' | 'UNSAT';
17
+ verified: boolean;
18
+ engine: 'apodictic-pglite-shadow-z3';
19
+ rowsAffected: number;
20
+ observedDebit: number;
21
+ observedDeltas: Record<string, { before: number; after: number; delta: number }>;
22
+ postBalances: Record<string, number>;
23
+ z3Proof: VerifyMutationResult;
24
+ counterfactualPatch: CounterfactualPatch | null;
25
+ reason?: string | null;
26
+ executionError?: string | null;
27
+ latencyMs: number;
28
+ }
29
+
30
+ export declare class ShadowPostgresVerifier {
31
+ constructor(gatewayOrOptions?: SymbolicGateway | Record<string, unknown>, options?: Record<string, unknown>);
32
+ shadowExecuteAndProve(input?: ShadowExecuteInput): Promise<ShadowExecuteResult>;
33
+ close(): Promise<void>;
34
+ }
35
+
36
+ export default ShadowPostgresVerifier;
@@ -0,0 +1,286 @@
1
+ /**
2
+ * @apodictic/sdk — PGlite WASM Shadow Postgres Firewall ("Execute-Then-Prove")
3
+ * Executes candidate SQL inside a rolled-back in-memory Postgres 17 WASM transaction,
4
+ * observes actual post-execution state diffs (triggers, subqueries, CASE WHEN, CTEs,
5
+ * cascading deletes), unconditionally rolls back, and proves solvency/cap invariants via Z3 5.4.1.
6
+ */
7
+ import { PGlite } from '@electric-sql/pglite';
8
+
9
+ const DEFAULT_SCHEMA_SQL = `
10
+ CREATE TABLE IF NOT EXISTS accounts (
11
+ id TEXT PRIMARY KEY,
12
+ balance DOUBLE PRECISION NOT NULL
13
+ );
14
+ CREATE TABLE IF NOT EXISTS vendor_disbursements (
15
+ id INT PRIMARY KEY,
16
+ account_id TEXT NOT NULL,
17
+ amount DOUBLE PRECISION NOT NULL DEFAULT 0,
18
+ status TEXT NOT NULL DEFAULT 'PENDING',
19
+ vendor_iban TEXT NOT NULL DEFAULT ''
20
+ );
21
+ CREATE TABLE IF NOT EXISTS ledger_entries (
22
+ id SERIAL PRIMARY KEY,
23
+ account_id TEXT NOT NULL,
24
+ delta DOUBLE PRECISION NOT NULL,
25
+ memo TEXT NOT NULL DEFAULT '',
26
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
27
+ );
28
+ `;
29
+
30
+ export class ShadowPostgresVerifier {
31
+ constructor(gatewayOrOptions = null, maybeOptions = {}) {
32
+ if (gatewayOrOptions && typeof gatewayOrOptions.verifyMutation === 'function') {
33
+ this._gateway = gatewayOrOptions;
34
+ this._ownGateway = null;
35
+ this.options = maybeOptions || {};
36
+ } else {
37
+ this.options = (gatewayOrOptions && typeof gatewayOrOptions === 'object') ? gatewayOrOptions : {};
38
+ this._gateway = this.options.gateway && typeof this.options.gateway.verifyMutation === 'function'
39
+ ? this.options.gateway
40
+ : null;
41
+ this._ownGateway = null;
42
+ }
43
+ this._db = null;
44
+ }
45
+
46
+ async _getGateway() {
47
+ if (this._gateway) return this._gateway;
48
+ if (!this._ownGateway) {
49
+ const { SymbolicGateway } = await import('./index.mjs');
50
+ this._ownGateway = new SymbolicGateway(this.options);
51
+ }
52
+ return this._ownGateway;
53
+ }
54
+
55
+ async _ensureDefaultDb(accountId, currentBalance) {
56
+ if (!this._db) {
57
+ this._db = new PGlite();
58
+ await this._db.exec(DEFAULT_SCHEMA_SQL);
59
+ }
60
+ await this._db.query(
61
+ 'INSERT INTO accounts (id, balance) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET balance = EXCLUDED.balance',
62
+ [accountId, currentBalance]
63
+ );
64
+ await this._db.query(
65
+ `INSERT INTO vendor_disbursements (id, account_id, amount, status, vendor_iban)
66
+ VALUES (1, $1, 0, 'PENDING', ''), (4092, $1, 0, 'PENDING', '')
67
+ ON CONFLICT (id) DO NOTHING`,
68
+ [accountId]
69
+ );
70
+ return this._db;
71
+ }
72
+
73
+ async shadowExecuteAndProve(input = {}) {
74
+ const t0 = performance.now();
75
+ const sql = String(input.sql || '');
76
+ const accountId = String(input.accountId || 'sdk_default');
77
+ const hasExplicitBal = input.currentBalance !== undefined && input.currentBalance !== null;
78
+ const explicitAmount =
79
+ input.amount !== undefined && input.amount !== null ? Number(input.amount) : undefined;
80
+ const minReserve = Number(input.minReserve ?? 50000);
81
+ const maxAutonomousLimit = Number(input.maxAutonomousLimit ?? 50000);
82
+ const cfoSigned = Boolean(input.cfoSigned);
83
+ const schemaSql = typeof input.schemaSql === 'string' ? input.schemaSql.trim() : '';
84
+ const seedSql = typeof input.seedSql === 'string' ? input.seedSql.trim() : '';
85
+ const useFreshTemp = Boolean(schemaSql || seedSql);
86
+
87
+ let tempDb = null;
88
+ let db;
89
+ if (useFreshTemp) {
90
+ tempDb = new PGlite();
91
+ db = tempDb;
92
+ await db.exec(schemaSql || DEFAULT_SCHEMA_SQL);
93
+ if (seedSql) {
94
+ await db.exec(seedSql);
95
+ } else {
96
+ await db.query(
97
+ 'INSERT INTO accounts (id, balance) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET balance = EXCLUDED.balance',
98
+ [accountId, hasExplicitBal ? Number(input.currentBalance) : 250000]
99
+ );
100
+ }
101
+ } else {
102
+ db = await this._ensureDefaultDb(accountId, hasExplicitBal ? Number(input.currentBalance) : 250000);
103
+ }
104
+
105
+ let hasAccountsTable = false;
106
+ let preBalances = {};
107
+ let totalBefore = 0;
108
+ let postBalances = {};
109
+ let totalAfter = 0;
110
+ let rowsAffected = 0;
111
+ let executionError = null;
112
+ let ddlOrTableDropped = false;
113
+ let inTx = false;
114
+ let observedDebitTotal = input.debitTotal !== undefined ? Number(input.debitTotal) : undefined;
115
+ let observedCreditTotal = input.creditTotal !== undefined ? Number(input.creditTotal) : undefined;
116
+
117
+ // Strip comments and string literals before rejecting transaction-control escape statements
118
+ const txControlProbe = sql
119
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
120
+ .replace(/--[^\n]*/g, ' ')
121
+ .replace(/'(?:''|[^'])*'/g, " '' ");
122
+ const hasTxControlEscape = /\b(?:COMMIT|END\s+(?:TRANSACTION|WORK)|ROLLBACK\s+TO|ROLLBACK\b|BEGIN\b|START\s+TRANSACTION|SAVEPOINT|RELEASE\s+SAVEPOINT)\b/i.test(
123
+ txControlProbe
124
+ );
125
+
126
+ try {
127
+ const regPre = await db.query("SELECT to_regclass('public.accounts') AS tbl");
128
+ hasAccountsTable = Boolean(regPre.rows?.[0]?.tbl);
129
+ if (hasAccountsTable) {
130
+ const preRes = await db.query('SELECT id, balance FROM accounts ORDER BY id ASC');
131
+ for (const r of preRes.rows) {
132
+ const bal = Number(r.balance);
133
+ preBalances[String(r.id)] = bal;
134
+ totalBefore += bal;
135
+ }
136
+ }
137
+ postBalances = { ...preBalances };
138
+ totalAfter = totalBefore;
139
+
140
+ if (hasTxControlEscape) {
141
+ ddlOrTableDropped = true;
142
+ executionError = 'TRANSACTION_CONTROL_ESCAPE_BLOCKED: COMMIT/BEGIN/ROLLBACK forbidden inside shadow probe';
143
+ } else {
144
+ await db.exec('BEGIN;');
145
+ inTx = true;
146
+ const execResults = await db.exec(sql);
147
+ for (const r of execResults) {
148
+ rowsAffected += Number(r.affectedRows ?? r.rowCount ?? 0);
149
+ const cmd = String(r.command || '').toUpperCase();
150
+ if (cmd === 'DROP' || cmd === 'TRUNCATE' || cmd === 'ALTER' || cmd === 'CREATE' || cmd === 'COPY') {
151
+ ddlOrTableDropped = true;
152
+ }
153
+ }
154
+
155
+ if (hasAccountsTable) {
156
+ const regPost = await db.query("SELECT to_regclass('public.accounts') AS tbl");
157
+ if (!regPost.rows?.[0]?.tbl) {
158
+ ddlOrTableDropped = true;
159
+ postBalances = {};
160
+ totalAfter = 0;
161
+ } else {
162
+ const postRes = await db.query('SELECT id, balance FROM accounts ORDER BY id ASC');
163
+ postBalances = {};
164
+ totalAfter = 0;
165
+ for (const r of postRes.rows) {
166
+ const bal = Number(r.balance);
167
+ postBalances[String(r.id)] = bal;
168
+ totalAfter += bal;
169
+ }
170
+ }
171
+ }
172
+
173
+ const regMove = await db.query("SELECT to_regclass('public.account_move_line') AS tbl");
174
+ if (regMove.rows?.[0]?.tbl && observedDebitTotal === undefined && observedCreditTotal === undefined) {
175
+ const deRes = await db.query('SELECT COALESCE(SUM(debit), 0) AS d, COALESCE(SUM(credit), 0) AS c FROM account_move_line');
176
+ if (deRes.rows?.[0]) {
177
+ observedDebitTotal = Number(deRes.rows[0].d);
178
+ observedCreditTotal = Number(deRes.rows[0].c);
179
+ }
180
+ }
181
+ }
182
+ } catch (err) {
183
+ executionError = err instanceof Error ? err.message : String(err);
184
+ } finally {
185
+ if (inTx) {
186
+ try {
187
+ await db.exec('ROLLBACK;');
188
+ } catch {
189
+ // ignore rollback error on aborted cleanup
190
+ }
191
+ }
192
+ if (tempDb) {
193
+ try {
194
+ await tempDb.close();
195
+ } catch {
196
+ // ignore temp close error
197
+ }
198
+ }
199
+ }
200
+
201
+ const observedDeltas = {};
202
+ let grossOutflow = 0;
203
+ for (const id of new Set([...Object.keys(preBalances), ...Object.keys(postBalances)])) {
204
+ const before = preBalances[id] ?? 0;
205
+ const after = postBalances[id] ?? 0;
206
+ if (before !== after || !(id in postBalances) || !(id in preBalances)) {
207
+ const delta = Number((after - before).toFixed(4));
208
+ if (before > after) grossOutflow += before - after;
209
+ observedDeltas[id] = {
210
+ before,
211
+ after,
212
+ delta,
213
+ };
214
+ }
215
+ }
216
+
217
+ const observedDebit = executionError
218
+ ? 0
219
+ : Number(Math.max(grossOutflow, Math.max(0, totalBefore - totalAfter)).toFixed(4));
220
+
221
+ const currentBalance = hasExplicitBal
222
+ ? Number(input.currentBalance)
223
+ : (preBalances[accountId] ?? (Object.keys(preBalances).length > 0 ? totalBefore : 250000));
224
+
225
+ const effectiveAmount =
226
+ explicitAmount !== undefined || observedDebit > 0
227
+ ? Math.max(explicitAmount || 0, observedDebit)
228
+ : undefined;
229
+
230
+ const gw = await this._getGateway();
231
+ const z3Proof = await gw.verifyMutation({
232
+ sql,
233
+ action: input.action,
234
+ accountId,
235
+ amount: effectiveAmount,
236
+ currentBalance,
237
+ minReserve,
238
+ maxAutonomousLimit,
239
+ cfoSigned,
240
+ debitTotal: observedDebitTotal,
241
+ creditTotal: observedCreditTotal,
242
+ statutoryVat: input.statutoryVat,
243
+ expectedVat: input.expectedVat,
244
+ targetSystem: input.targetSystem,
245
+ odoo: input.odoo,
246
+ });
247
+
248
+ const failClosed = Boolean(executionError) || ddlOrTableDropped;
249
+ const verified = !failClosed && Boolean(z3Proof.verified);
250
+ const verdict = verified ? 'SAT' : 'UNSAT';
251
+ const reason = executionError
252
+ ? `EXECUTION_ERROR: ${executionError}`
253
+ : ddlOrTableDropped
254
+ ? (z3Proof.reason || 'DDL_OR_DESTRUCTIVE_MUTATION_BLOCKED')
255
+ : (z3Proof.reason ?? null);
256
+
257
+ return {
258
+ verdict,
259
+ verified,
260
+ engine: 'apodictic-pglite-shadow-z3',
261
+ rowsAffected,
262
+ observedDebit,
263
+ observedDeltas,
264
+ postBalances,
265
+ z3Proof,
266
+ counterfactualPatch: verified ? null : (z3Proof.counterfactualPatch ?? null),
267
+ reason,
268
+ executionError,
269
+ latencyMs: Number((performance.now() - t0).toFixed(3)),
270
+ };
271
+ }
272
+
273
+ async close() {
274
+ if (this._db) {
275
+ await this._db.close();
276
+ this._db = null;
277
+ }
278
+ if (this._ownGateway) {
279
+ await this._ownGateway.close();
280
+ this._ownGateway = null;
281
+ }
282
+ }
283
+ }
284
+
285
+ export { PGlite };
286
+ export default ShadowPostgresVerifier;