// Own disposable Compras database/role/cluster for the real common-ledger schema. // Never starts, configures or connects to an operational SGF/Compras database. import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import { spawn, spawnSync } from 'node:child_process'; import { createServer } from 'node:net'; const id = crypto.randomBytes(6).toString('hex'); const workspace = path.resolve('C:/laragon/www/compras'); const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes=')); const reviewDurationMinutes = reviewDurationArgs.length === 0 ? 20 : Number(reviewDurationArgs[0].slice('--review-minutes='.length)); if (reviewDurationArgs.length > 1 || !Number.isInteger(reviewDurationMinutes) || reviewDurationMinutes < 1 || reviewDurationMinutes > 60 || (reviewDurationArgs.length > 0 && !process.argv.includes('--native-review'))) throw Error('Native review duration must be one explicit value from1to60minutes'); if (process.argv.includes('--legal-reference-preview') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || !process.argv.some(flag => ['--native-review', '--native-review-http-only'].includes(flag)))) throw Error('Legal preview requires the owned native review with complete pinned private composition'); if (process.argv.includes('--vat-reference-preview') && (!process.argv.includes('--legal-reference-preview') || !process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('VAT preview requires the guarded native legal composition'); if (process.argv.includes('--private-audit-recovery') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.some(flag => ['--recovery-only', '--race-only', '--native-review', '--native-review-http-only'].includes(flag)))) throw Error('Private audit recovery requires its own complete pinned isolated composition'); if (process.argv.includes('--print-pagination-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Print pagination requires the owned native preview and complete pinned composition'); if (process.argv.includes('--native-office-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.some(flag => ['--print-pagination-preview', '--legal-reference-preview'].includes(flag)))) throw Error('Office preview requires its own complete pinned native QA composition'); if (process.argv.includes('--specific-rate-preview') && (!process.argv.includes('--legal-reference-preview') || !process.argv.includes('--native-review'))) throw Error('Specific coefficient preview requires the owned legal native review'); if (process.argv.includes('--ice-reference-preview') && (!process.argv.includes('--legal-reference-preview') || !process.argv.includes('--native-review'))) throw Error('ICE reference preview requires the owned legal native review'); if (process.argv.includes('--capital-search-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Capital search preview requires the owned native review and pinned isolated composition'); if (process.argv.includes('--import-documentary-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Documentary import preview requires the owned native review and pinned isolated composition'); if (process.argv.includes('--supplier-review-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Supplier review requires the owned native preview and pinned isolated composition'); if (process.argv.includes('--conflict-release-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.includes('--native-office-preview'))) throw Error('Conflict release requires its own guarded native QA composition'); if (process.argv.includes('--urgent-stock-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.includes('--native-office-preview'))) throw Error('Urgent stock review requires its own guarded native QA composition'); if (process.argv.includes('--order-cancellation-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.includes('--native-office-preview'))) throw Error('Cancellation review requires its own guarded native QA composition'); if (process.argv.includes('--operational-search-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Operational search preview requires the owned native review and pinned isolated composition'); if (path.resolve(process.cwd()) !== workspace) throw Error('Compras workspace required'); if (process.argv.includes('--integrated-cycles-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated cycles require the complete isolated schema composition'); if (process.argv.includes('--integrated-orders-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated orders require the complete isolated schema composition'); if (process.argv.includes('--integrated-import-costs-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated import costs require the complete isolated schema composition'); if (process.argv.includes('--integrated-release-journeys') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Release journeys require the complete pinned private composition'); if (process.argv.includes('--native-review-http-only') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Native HTTP review requires the complete pinned private composition'); if (process.argv.includes('--native-office-http-only') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Native office HTTP journey requires the complete pinned private composition'); if (process.argv.some(flag => ['--independent-procurement-only', '--privacy-controllers-only'].includes(flag)) && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Focused release regressions require the complete pinned private composition'); const privateParent = path.join(workspace, 'storage/framework/testing'); const frozenRuntime = process.argv.includes('--frozen-runtime'); if (frozenRuntime && !process.argv.includes('--integrated-schema')) throw Error('Frozen runtime requires the complete isolated schema composition'); const financeRoot = path.join(privateParent, 'requisition-ledger-runtime-qa-182e10ceec556e12'); const financePin = '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df'; const budgetRoot = path.join(privateParent, 'requisition-cycles-qa-35701ec1614f871e'); function verifyPrivateRuntime(root, pin, count) { const manifestFile = path.join(root, 'manifest.json'); if (fs.lstatSync(root).isSymbolicLink() || fs.lstatSync(manifestFile).isSymbolicLink()) throw Error('Private runtime links refused'); const bytes = fs.readFileSync(manifestFile); if (crypto.createHash('sha256').update(bytes).digest('hex') !== pin) throw Error('Pinned runtime manifest differs'); const manifest = JSON.parse(bytes); const entries = Array.isArray(manifest.files) ? manifest.files.map(e => [e.file, e.sha256]) : Object.entries(manifest.files); if (entries.length !== count) throw Error('Private runtime file count differs'); const expected = new Set(['manifest.json']); const boundary = fs.realpathSync(root) + path.sep; for (const [file, hash] of entries) { if (typeof file !== 'string' || !/^[A-Za-z0-9_./-]+$/.test(file) || file.split('/').includes('..') || expected.has(file)) throw Error('Private runtime path refused'); const target = path.join(root, file); if (!fs.realpathSync(target).startsWith(boundary) || fs.lstatSync(target).isSymbolicLink() || !fs.lstatSync(target).isFile() || crypto.createHash('sha256').update(fs.readFileSync(target)).digest('hex') !== hash) throw Error('Private runtime byte mismatch'); expected.add(file); } const walk = directory => { for (const name of fs.readdirSync(directory)) { const target = path.join(directory, name); const stat = fs.lstatSync(target); if (stat.isSymbolicLink()) throw Error('Private runtime links refused'); if (stat.isDirectory()) walk(target); else if (!stat.isFile() || !expected.delete(path.relative(root, target).replaceAll('\\', '/'))) throw Error('Unexpected private runtime file'); } }; walk(root); if (expected.size !== 0) throw Error('Private runtime file missing'); } if (frozenRuntime) { verifyPrivateRuntime(financeRoot, financePin, 44); verifyPrivateRuntime(budgetRoot, 'fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a', 24); console.log(JSON.stringify({ private_frozen_runtime: true, finance_manifest_sha256: financePin, budget_manifest_sha256: 'fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a', finance_files: 44, budget_files: 24 })); } const root = path.join(privateParent, `rq01-ledger-qa-${id}`); const cluster = path.join(root, 'postgres'); if (path.dirname(root) !== privateParent || !/^rq01-ledger-qa-[a-f0-9]{12}$/.test(path.basename(root))) throw Error('Private QA root refused'); fs.mkdirSync(root); const database = `compras_receipts_test_${id}`; const role = `payable_history_native_${id}`; const password = crypto.randomBytes(30).toString('hex'); const adminPassword = crypto.randomBytes(30).toString('hex'); const passwordFile = path.join(root, 'admin-password.txt'); fs.writeFileSync(passwordFile, adminPassword); const pg = 'C:/Program Files/PostgreSQL/17/bin'; const psql = path.join(pg, 'psql.exe'); function pgRun(binary, args) { const result = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8', // Detached PostgreSQL Windows children must not inherit a captured pipe. ...(binary === 'pg_ctl.exe' ? { stdio: 'ignore' } : {}), }); if (result.status !== 0) throw Error('Private QA cluster operation failed: ' + (result.stderr || '')); } function sql(input) { const result = spawnSync(psql, ['-h', '127.0.0.1', '-p', '55439', '-U', 'sgf_regression_owner', '-d', 'postgres', '-X', '-v', 'ON_ERROR_STOP=1', '-At'], { windowsHide: true, encoding: 'utf8', input, env: { ...process.env, PGPASSWORD: adminPassword }, }); if (result.status !== 0) throw Error('Isolated ledger SQL failed: ' + (result.stderr || '').replaceAll(password, '[private]').replaceAll(adminPassword, '[private]')); return result.stdout.trim(); } let createdRole = false; let createdDatabase = false; let started = false; let restoreRole = null; let restoreDatabase = null; let reviewServer = null; try { // The ledger contract fixes this QA port; an occupied port is refused, never stopped. pgRun('initdb.exe', ['-D', cluster, '-U', 'sgf_regression_owner', '-A', 'scram-sha-256', '--pwfile='+passwordFile, '-E', 'UTF8', '--locale=C']); fs.appendFileSync(path.join(cluster, 'postgresql.conf'), `\nlisten_addresses='127.0.0.1'\nport=55439\ncluster_name='sgf_modular_regression_${id}'\n`); pgRun('pg_ctl.exe', ['-D', cluster, '-l', path.join(root, 'postgres.log'), '-w', 'start']); started = true; if (sql("SELECT current_setting('cluster_name')") !== `sgf_modular_regression_${id}`) throw Error('Unexpected cluster'); sql(`CREATE ROLE ${role} LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`); createdRole = true; sql(`CREATE DATABASE ${database} OWNER ${role};`); createdDatabase = true; sql(`REVOKE ALL ON DATABASE ${database} FROM PUBLIC;`); const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', APP_KEY: 'base64:'+crypto.randomBytes(32).toString('base64'), DB_CONNECTION: 'pgsql', DB_URL: '', DB_HOST: '127.0.0.1', DB_PORT: '55439', DB_DATABASE: database, DB_USERNAME: role, DB_PASSWORD: password, CACHE_STORE: 'array', SESSION_DRIVER: 'array', MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null', COMMON_BUDGET_PATH: frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control', RQ01_LEDGER_QA_SOURCE: frozenRuntime ? path.join(financeRoot, 'general-ledger') : 'C:/laragon/www/sgf-tempo/packages/general-ledger', RQ01_LEDGER_INTEGRATED_SCHEMA: process.argv.includes('--integrated-schema') ? '1' : '0', RQ01_NATIVE_OFFICE_JOURNEY: process.argv.some(flag => ['--native-office-http-only', '--native-office-preview'].includes(flag)) ? '1' : '0', RQ01_QA_LEGAL_REFERENCE: process.argv.includes('--legal-reference-preview') ? '1' : '0', RQ01_QA_VAT_REFERENCE: process.argv.includes('--vat-reference-preview') ? '1' : '0', RQ01_QA_SPECIFIC_RATE: process.argv.includes('--specific-rate-preview') ? '1' : '0', RQ01_QA_ICE_REFERENCE: process.argv.includes('--ice-reference-preview') ? '1' : '0', RQ01_QA_CAPITAL_SEARCH: process.argv.includes('--capital-search-preview') ? '1' : '0', RQ01_QA_IMPORT_DOCUMENTARY: process.argv.includes('--import-documentary-preview') ? '1' : '0', RQ01_QA_SUPPLIER_REVIEW: process.argv.includes('--supplier-review-preview') ? '1' : '0', RQ01_QA_CONFLICT_RELEASE: process.argv.includes('--conflict-release-preview') ? '1' : '0', RQ01_QA_URGENT_STOCK: process.argv.includes('--urgent-stock-preview') ? '1' : '0', RQ01_QA_ORDER_CANCELLATION: process.argv.includes('--order-cancellation-preview') ? '1' : '0', RQ01_QA_OPERATIONAL_SEARCH: process.argv.includes('--operational-search-preview') ? '1' : '0', RQ01_QA_PRINT_PAGINATION: process.argv.includes('--print-pagination-preview') ? '1' : '0' }; delete environment.COMMON_FINANCE_BUNDLE_ROOT; delete environment.COMMON_FINANCE_BUNDLE_SHA256; if (frozenRuntime) { environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot; environment.COMMON_FINANCE_BUNDLE_SHA256 = financePin; } const raceOnly = process.argv.includes('--race-only'); const auditRecovery = process.argv.includes('--private-audit-recovery'); const recoveryOnly = process.argv.includes('--recovery-only') || auditRecovery; const nativeAuditSchemaOnly = process.argv.includes('--audit-schema-only'); const nativeFixtureOnly = process.argv.includes('--native-review-fixture-only'); const nativeHttpOnly = process.argv.includes('--native-review-http-only'); const nativeOfficePreview = process.argv.includes('--native-office-preview'); const nativeOfficeOnly = process.argv.includes('--native-office-http-only') || nativeOfficePreview; const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly || nativeAuditSchemaOnly; const setupOnly = raceOnly || recoveryOnly || nativeReview; const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=minimal purchasing catalogue|chart references reject|native line account assignment|classified line requires|native submission requires account|zero monetary line retains|native order preserves common ledger|native office purchase']; if (process.argv.includes('--runtime-guard-only')) { if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Runtime guard requires only the frozen isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=pinned private runtime refuses'); } if (process.argv.includes('--order-document-only')) { if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Order document regression requires only the frozen isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/OrderDocumentNavigationTest.php', '--filter=ordinary controlled order|distributed approved synthetic|award starts a new approval cycle|order and receipt consultations|context links do not grant|print navigation leaves'); } if (process.argv.includes('--supplier-evaluation-only')) { if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Supplier evaluation regression requires the frozen isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierEvaluationTest.php'); } if (process.argv.includes('--legal-reference-only')) { if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Legal reference regression requires the frozen isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalReferenceDraftsTest.php', 'tests/Feature/ImportLegalRulesTest.php'); } if (process.argv.includes('--conflict-only')) { if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Conflict regression requires the complete pinned isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/ConflictDeclarationTest.php'); } if (process.argv.includes('--private-audit-only')) { if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Private audit regression requires the complete pinned isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PrivateAuditSourcesTest.php', 'tests/Feature/PrivateAuditAccessTest.php', 'tests/Feature/PrivateAuditExporterTest.php'); } if (process.argv.includes('--independent-procurement-only')) { if (setupOnly) throw Error('Independent procurement is a focused native Pest regression'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=office_with_independent_procurement'); } if (process.argv.includes('--privacy-controllers-only')) { if (setupOnly) throw Error('Private controllers are focused native Pest regressions'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=budget consultations|purchase control preparations'); } if (process.argv.includes('--expiry-history-only')) { if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition'); args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=native expiry returns the same request'); } const result = spawnSync('php', args, { cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment, }); if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]')); process.stderr.write((result.stderr || '').replaceAll(password, '[private]')); process.exitCode = result.status === 0 ? 0 : 1; if (result.status === 0 && raceOnly) { const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], { cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment, }); process.stdout.write((race.stdout || '').replaceAll(password, '[private]')); process.stderr.write((race.stderr || '').replaceAll(password, '[private]')); process.exitCode = race.status === 0 ? 0 : 1; } if (result.status === 0 && recoveryOnly) { const worker = (mode, env, payload = null) => { const args = [auditRecovery ? 'tests/Concurrency/private-audit-recovery-worker.php' : 'tests/Concurrency/requisition-account-worker.php', env.DB_DATABASE, mode]; if (payload !== null) args.push(JSON.stringify(payload)); const result = spawnSync('php', args, { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env }); if (result.status !== 0) throw Error('Account recovery worker failed: ' + (result.stderr || result.stdout || '').replaceAll(password, '[private]')); return JSON.parse(result.stdout); }; const recoveryEnvironment = auditRecovery ? { ...environment, SGC_REQUISITION_QA_ROOT: root } : environment; const fixture = worker(auditRecovery ? 'prepare' : 'prepare-recovery', recoveryEnvironment); if (auditRecovery) fs.cpSync(path.join(root, 'audit-source-files'), path.join(root, 'audit-backup-files'), { recursive: true, errorOnExist: true, force: false }); const pgCommand = (binary, args, env) => { const result = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8', env: { ...process.env, PGHOST: '127.0.0.1', PGPORT: '55439', PGUSER: env.DB_USERNAME, PGPASSWORD: env.DB_PASSWORD } }); if (result.status !== 0) throw Error('Private account backup/restore failed'); }; const dump = path.join(root, 'accounts.dump'); pgCommand('pg_dump.exe', ['--format=custom', '--no-owner', '--no-acl', '--file='+dump, '--dbname='+database], environment); const restoredId = crypto.randomBytes(6).toString('hex'); const restoredPassword = crypto.randomBytes(30).toString('hex'); const targetRole = `payable_history_native_${restoredId}`; const targetDatabase = `compras_receipts_test_${restoredId}`; sql(`CREATE ROLE ${targetRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`); restoreRole = targetRole; sql(`CREATE DATABASE ${targetDatabase} OWNER ${targetRole};`); restoreDatabase = targetDatabase; sql(`REVOKE ALL ON DATABASE ${targetDatabase} FROM PUBLIC;`); const restoredEnvironment = { ...recoveryEnvironment, DB_DATABASE: targetDatabase, DB_USERNAME: targetRole, DB_PASSWORD: restoredPassword }; pgCommand('pg_restore.exe', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='+targetDatabase, dump], restoredEnvironment); if (auditRecovery) { // All paths are literal children of the guarded newly-created task root. if (path.dirname(path.resolve(root)) !== privateParent || path.basename(root) !== `rq01-ledger-qa-${id}`) throw Error('Audit recovery root refused'); fs.renameSync(path.join(root, 'audit-source-files'), path.join(root, 'audit-source-unavailable')); fs.cpSync(path.join(root, 'audit-backup-files'), path.join(root, 'audit-restored-files'), { recursive: true, errorOnExist: true, force: false }); } console.log(JSON.stringify({ source_database: database, restored_database: targetDatabase, ...worker(auditRecovery ? 'verify' : 'verify-recovery', restoredEnvironment, fixture) })); } if (result.status === 0 && nativeReview) { for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) { fs.mkdirSync(path.join(root, relative), { recursive: true }); } const seed = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'prepare-native-review'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (seed.status !== 0) throw Error('Native review fixture failed: '+(seed.stderr || seed.stdout || '').replaceAll(password, '[private]')); const fixture = JSON.parse(seed.stdout); fs.writeFileSync(path.join(root, 'native-review.json'), JSON.stringify(fixture)); const assets = path.join(privateParent, 'sgc-legacy-cancellation-qa-20261129'); const manifest = fs.readFileSync(path.join(assets, 'manifest.json')); const manifestHash = crypto.createHash('sha256').update(manifest).digest('hex'); if (manifestHash !== '99b072435a0b9eccb83d98ab36faceb23f98e510509d2175691269d1958083be') throw Error('Unexpected private review manifest'); for (const entry of Object.values(JSON.parse(manifest))) { if (!fs.existsSync(path.join(assets, entry.file))) throw Error('Private review asset missing'); } fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true }); const staticReviewAssets = ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png'].map(file => { const source = path.join(workspace, 'public', file); if (fs.lstatSync(source).isSymbolicLink()) throw Error('Private review static links refused'); const bytes = fs.readFileSync(source); fs.copyFileSync(source, path.join(root, 'public', file)); return { file, sha256: crypto.createHash('sha256').update(bytes).digest('hex') }; }); if (nativeAuditSchemaOnly) { if (!frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Audit schema inventory requires the pinned private composition'); const schema = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'describe-private-audit-schema'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (schema.status !== 0) throw Error('Private audit schema inventory failed'); const inventory = JSON.parse(schema.stdout); if (inventory.schema_only !== true || inventory.no_business_values !== true) throw Error('Schema-only contract refused'); const target = path.join(privateParent, 'private-audit-source-schema-20261128.json'); const bytes = JSON.stringify(inventory, null, 2)+'\n'; if (fs.existsSync(target) && fs.readFileSync(target, 'utf8') !== bytes) throw Error('Preserve the previous private schema inventory before replacing it'); fs.writeFileSync(target, bytes); console.log(JSON.stringify({ private_audit_schema_inventory: true, tables: Object.keys(inventory.tables).length, business_values_exported: false, target })); } else if (nativeFixtureOnly) { console.log(JSON.stringify({ private_native_fixture_verified: true, ...fixture, private_manifest_sha256: manifestHash })); } else { const port = await new Promise((resolve, reject) => { const socket = createServer(); socket.on('error', reject); socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); }); }); const url = `http://localhost:${port}`; reviewServer = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/requisition-qa-http-router.php'], { cwd: workspace, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...environment, APP_URL: url, ASSET_URL: url, SESSION_DRIVER: 'file', SESSION_COOKIE: `sgc_req_qa_${id}`, SGC_REQUISITION_QA_ROOT: root, SGC_REQUISITION_QA_PORT: String(port), SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({ [fixture.tenant_id]: ['procurement.internal'] }) }, }); let diagnostic = ''; reviewServer.stdout.on('data', data => { diagnostic = (diagnostic + data).slice(-4000); }); reviewServer.stderr.on('data', data => { diagnostic = (diagnostic + data).slice(-4000); }); let ready = false; for (let attempt = 0; attempt < 40; attempt++) { try { ready = true; for (const route of ['/up', '/login']) { const response = await fetch(url + route); await response.arrayBuffer(); ready = ready && response.status === 200; } } catch { ready = false; /* startup only */ } if (ready) break; if (reviewServer.exitCode !== null) break; await new Promise(resolve => setTimeout(resolve, 250)); } if (!ready) throw Error('Native review server unavailable: '+diagnostic.replaceAll(password, '[private]')); const staticChecks = await Promise.allSettled(staticReviewAssets.map(async asset => { const response = await fetch(`${url}/${asset.file}`, { redirect: 'manual' }); const bytes = Buffer.from(await response.arrayBuffer()); if (response.status !== 200 || crypto.createHash('sha256').update(bytes).digest('hex') !== asset.sha256) throw Error('Private review static asset differs: '+asset.file); return asset; })); for (const check of staticChecks) if (check.status === 'rejected') throw check.reason; console.log(JSON.stringify({ private_native_static_assets_verified: true, files: staticChecks.map(check => check.value), operational_changes: false })); if (nativeOfficeOnly) { const { verifyOfficePurchaseHttp } = await import('./requisition-office-http-check.mjs'); const result = await verifyOfficePurchaseHttp(url, fixture, async () => { const state = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-office-purchase'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (state.status !== 0) throw Error('Native office assertion worker failed: ' + (state.stderr || state.stdout || '').replaceAll(password, '[private]').replaceAll(environment.APP_KEY, '[private]')); return JSON.parse(state.stdout); }, value => console.log(JSON.stringify(value))); console.log(JSON.stringify({ private_native_office_http_verified: true, ...result, private_manifest_sha256: manifestHash })); } if (nativeHttpOnly) { const { verifyNativeReviewHttp } = await import('./requisition-native-http-check.mjs'); const pageAssets = ['resources/js/pages/audit/private.tsx', 'resources/js/pages/supply/index.tsx', 'resources/js/pages/purchase-controls/index.tsx', 'resources/js/pages/purchase-controls/orders.tsx', 'resources/js/pages/budgets/index.tsx', 'resources/js/pages/conflicts/index.tsx', 'resources/js/pages/conflicts/show.tsx', 'resources/js/pages/payments/index.tsx', 'resources/js/pages/stock/index.tsx', 'resources/js/pages/stock/operations.tsx', 'resources/js/pages/stock/lots.tsx', 'resources/js/pages/stock/reversals.tsx', 'resources/js/pages/stock/dispositions.tsx', 'resources/js/pages/equipment/index.tsx', 'resources/js/pages/investment/index.tsx', 'resources/js/pages/company/parameters.tsx', 'resources/js/pages/company/index.tsx', 'resources/js/pages/company/setup.tsx', 'resources/js/pages/requisitions/operational-orders.tsx', 'resources/js/pages/requisitions/urgent-stock.tsx'] .map(key => JSON.parse(manifest)[key]); const result = await verifyNativeReviewHttp(url, fixture, { assets: pageAssets.map(entry => ({ file: entry.file, sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(assets, entry.file))).digest('hex') })), snapshot: async () => { const result = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-native-sources'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment, }); if (result.status !== 0) throw Error('Native HTTP read snapshot failed'); return JSON.parse(result.stdout).snapshot; }, }); console.log(JSON.stringify({ private_native_http_verified: true, ...result, private_manifest_sha256: manifestHash })); } else if (!nativeOfficeOnly || nativeOfficePreview) { const stopFile = path.join(root, 'stop-review'); console.log(JSON.stringify({ private_native_review_running: true, url, stop_file: stopFile, review_minutes: reviewDurationMinutes, ...fixture, private_manifest_sha256: manifestHash })); const until = Date.now() + reviewDurationMinutes * 60 * 1000; while (!fs.existsSync(stopFile) && Date.now() < until) { if (reviewServer.exitCode !== null) throw Error('Private native review stopped unexpectedly'); await new Promise(resolve => setTimeout(resolve, 200)); } if (process.argv.includes('--conflict-release-preview')) { const state = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-native-conflict-release'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (state.status !== 0) throw Error('Native conflict conservation failed: '+(state.stderr || state.stdout || '').replaceAll(password, '[private]')); console.log(JSON.stringify({ private_native_conflict_release_verified: true, ...JSON.parse(state.stdout), private_manifest_sha256: manifestHash })); } if (process.argv.includes('--urgent-stock-preview')) { const state = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-native-urgent-stock'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (state.status !== 0 || !state.stdout.trim().startsWith('{')) throw Error('Native urgent stock conservation failed: '+(state.stderr || state.stdout || '').replaceAll(password, '[private]')); console.log(JSON.stringify({ private_native_urgent_stock_verified: true, ...JSON.parse(state.stdout), private_manifest_sha256: manifestHash })); } if (process.argv.includes('--order-cancellation-preview')) { const state = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'read-native-cancellation'], { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: { ...environment, SGC_REQUISITION_QA_ROOT: root }, }); if (state.status !== 0 || !state.stdout.trim().startsWith('{')) throw Error('Native cancellation conservation failed: '+(state.stderr || state.stdout || '').replaceAll(password, '[private]')); console.log(JSON.stringify({ private_native_cancellation_verified: true, ...JSON.parse(state.stdout), private_manifest_sha256: manifestHash })); } } } } } finally { if (reviewServer && reviewServer.exitCode === null) { const closed = new Promise(resolve => reviewServer.once('exit', resolve)); reviewServer.kill(); await closed; } if (restoreDatabase) { sql(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${restoreDatabase}' AND pid<>pg_backend_pid();`); sql(`DROP DATABASE ${restoreDatabase};`); } if (restoreRole) sql(`DROP ROLE ${restoreRole};`); if (createdDatabase) { sql(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid();`); sql(`DROP DATABASE ${database};`); } if (createdRole) sql(`DROP ROLE ${role};`); if (started) pgRun('pg_ctl.exe', ['-D', cluster, '-m', 'fast', '-w', 'stop']); // Verified absolute task root, containing only this newly-created cluster and secrets. if (path.dirname(path.resolve(root)) !== privateParent || path.basename(root) !== `rq01-ledger-qa-${id}`) throw Error('Cleanup root refused'); fs.rmSync(root, { recursive: true }); console.log(JSON.stringify({ isolated_database_removed: createdDatabase, isolated_role_removed: createdRole, restored_database_removed: restoreDatabase !== null, restored_role_removed: restoreRole !== null, operational_changes: false })); }