Files
compras/scripts/requisition-ledger-qa-check.mjs
T
nalaandClaude Opus 5.5 ec934455e7 Aplicar Pint e formatação de frontend; delimitar o âmbito do lint
Só formatação automática (pint, vp check --fix), sem alterar comportamento.
Excluídos da formatação os registos e artefactos com bytes fixos: docs/,
integrations/, storage/, tmp/, output/, resources/data/, tests/Fixtures/,
compras-release.json e AGENTS*.md. Scripts operacionais, integrations e
auxiliares de teste ficam fora do lint (usam new Function; limpeza na fase 2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:01:42 +02:00

2164 lines
82 KiB
JavaScript

// 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 standaloneOnly = process.argv.includes('--standalone-runtime-only');
const financePreview = process.argv.includes('--standalone-finance-preview');
const componentProfile = process.argv.includes(
'--standalone-component-profile',
);
if (componentProfile && (!standaloneOnly || financePreview))
throw Error('Component profile requires its own standalone invocation');
if (financePreview && !standaloneOnly)
throw Error('Finance preview requires the isolated standalone runtime');
const standaloneUpgrade = process.argv.includes('--standalone-upgrade-only');
const standaloneAnalyticsPreview = process.argv.includes(
'--standalone-analytics-preview',
);
const standaloneCancellationPreview = process.argv.includes(
'--standalone-cancellation-preview',
);
const standaloneConversionPreview =
process.argv.includes('--standalone-conversion-preview') ||
standaloneCancellationPreview ||
standaloneAnalyticsPreview;
const standaloneConversion =
process.argv.includes('--standalone-conversion-only') ||
standaloneConversionPreview;
const standaloneBusiness =
process.argv.includes('--standalone-business-only') ||
standaloneUpgrade ||
standaloneConversion;
if (
standaloneOnly &&
process.argv
.slice(2)
.some(
(flag) =>
![
'--standalone-runtime-only',
'--standalone-finance-preview',
'--standalone-component-profile',
].includes(flag),
)
)
throw Error('Standalone composition requires its own isolated invocation');
if (
standaloneBusiness &&
process.argv
.slice(2)
.some(
(flag) =>
flag !==
(standaloneAnalyticsPreview
? '--standalone-analytics-preview'
: standaloneCancellationPreview
? '--standalone-cancellation-preview'
: standaloneConversionPreview
? '--standalone-conversion-preview'
: standaloneConversion
? '--standalone-conversion-only'
: standaloneUpgrade
? '--standalone-upgrade-only'
: '--standalone-business-only'),
)
)
throw Error(
'Standalone business regression requires its own isolated invocation',
);
const standaloneRoot = path.join(
workspace,
'storage/framework/testing/compras-standalone-80483320a54af6f1',
);
const standalonePin =
'80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7';
const standaloneArchivePin =
'bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76';
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 = standaloneOnly
? `compras_standalone_qa_${id}`
: `compras_receipts_test_${id}`;
const role = standaloneOnly
? `compras_standalone_app_${id}`
: `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;`);
let activeStandaloneRoot = standaloneRoot;
let inventoryRoot = null;
if (standaloneConversion) {
const pin =
'8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd';
const archive = path.join(
privateParent,
`compras-inventory-${pin}.zip`,
);
if (
fs.lstatSync(archive).isSymbolicLink() ||
crypto
.createHash('sha256')
.update(fs.readFileSync(archive))
.digest('hex') !==
'dbb7e3d172f2ce5168f678993b96d9d94ce2e0c1737b581743cf2bbb6d4d00b8'
)
throw Error('Pinned inventory archive mismatch');
inventoryRoot = path.join(root, 'inventory-runtime');
fs.mkdirSync(inventoryRoot);
const code =
'$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==4||!$z->extractTo($argv[2]))throw new LogicException("Owned inventory extraction failed");$z->close();';
const extracted = spawnSync(
'php',
['-r', code, archive, inventoryRoot],
{ windowsHide: true, encoding: 'utf8' },
);
if (extracted.status !== 0)
throw Error('Owned inventory extraction failed');
verifyPrivateRuntime(inventoryRoot, pin, 3);
}
if (standaloneOnly) {
const archive = standaloneRoot + '.zip';
if (
fs.lstatSync(archive).isSymbolicLink() ||
crypto
.createHash('sha256')
.update(fs.readFileSync(archive))
.digest('hex') !== standaloneArchivePin
)
throw Error('Pinned standalone archive mismatch');
activeStandaloneRoot = path.join(root, 'runtime');
fs.mkdirSync(activeStandaloneRoot);
const code =
'$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==68||!$z->extractTo($argv[2]))throw new LogicException("Owned candidate extraction failed");$z->close();echo "extracted";';
const extracted = spawnSync(
'php',
['-r', code, archive, activeStandaloneRoot],
{ windowsHide: true, encoding: 'utf8' },
);
if (extracted.status !== 0 || extracted.stdout !== 'extracted')
throw Error('Owned standalone extraction failed');
verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 67);
const uiTest = spawnSync(
process.execPath,
['--test', 'tests/Support/financial-preparation.test.mjs'],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
env: {
...process.env,
COMPRAS_FINANCE_UI_PACKAGE_ROOT: activeStandaloneRoot,
},
},
);
if (uiTest.status !== 0)
throw Error(
'Pinned financial preparation UI regression failed: ' +
(uiTest.stdout || uiTest.stderr || ''),
);
console.log(
JSON.stringify({
pinned_financial_preparation_tests: 10,
result: 'passed',
extracted_runtime: true,
}),
);
}
const environment = {
...process.env,
APP_ENV: 'testing',
APP_DEBUG: 'false',
COMPRAS_RUNTIME_ENABLED: 'false',
COMPRAS_RUNTIME_PREPARE_ONLY: 'false',
COMPRAS_RUNTIME_SYNTHETIC_ONLY: 'true',
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:
standaloneOnly || standaloneBusiness
? path.join(activeStandaloneRoot, 'budget-control')
: 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 (standaloneOnly || standaloneBusiness) {
environment.COMPRAS_RUNTIME_ENABLED = 'false';
environment.COMPRAS_RUNTIME_PREPARE_ONLY = 'true';
environment.COMMON_PAYABLES_PATH = path.join(
activeStandaloneRoot,
'payables',
);
environment.COMMON_PURCHASING_PATH = path.join(
activeStandaloneRoot,
'purchasing',
);
environment.COMPRAS_RUNTIME_ROOT = activeStandaloneRoot;
environment.COMPRAS_RUNTIME_SHA256 = standalonePin;
environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness
? '1'
: '0';
environment.COMPRAS_STANDALONE_UPGRADE_QA = standaloneUpgrade
? '1'
: '0';
environment.COMPRAS_STANDALONE_CONVERSION_QA = standaloneConversion
? '1'
: '0';
if (inventoryRoot !== null)
environment.COMPRAS_INVENTORY_ROOT = inventoryRoot;
}
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 =
standaloneOnly || 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('--work-context-only')) {
args.splice(
0,
args.length,
'vendor/bin/pest',
'--compact',
'tests/Feature/WorkContextTest.php',
'tests/Feature/OrganizationConfigurationTest.php',
'tests/Feature/OrganizationActivationPreviewTest.php',
'tests/Feature/PrivateAuditExporterTest.php',
'tests/Feature/PrivateAuditAccessTest.php',
);
}
if (process.argv.includes('--third-party-hiring-only')) {
args.splice(
0,
args.length,
'vendor/bin/pest',
'--compact',
'tests/Feature/BusinessClientsTest.php',
'tests/Feature/PeopleHiringTest.php',
'tests/Feature/WorkContextTest.php',
);
}
if (process.argv.includes('--configured-sales-ledger-only')) {
args.splice(
0,
args.length,
'vendor/bin/pest',
'--compact',
'tests/Feature/ConfiguredSalesLedgerTest.php',
'tests/Feature/CustomerReceivablesTest.php',
'tests/Feature/CustomerSalesNativeTest.php',
);
}
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',
);
}
if (standaloneBusiness)
args.splice(
0,
args.length,
'vendor/bin/pest',
'--compact',
standaloneConversion
? 'tests/Conversion/ReceiptQuantityConversionTest.php'
: standaloneUpgrade
? 'tests/Feature/StandaloneComponentUpgradeTest.php'
: 'tests/Feature/StandaloneBusinessCompositionTest.php',
);
if (standaloneConversionPreview)
args.splice(
0,
args.length,
'artisan',
'migrate',
'--force',
'--no-interaction',
'--quiet',
);
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 && standaloneConversion) {
const prepared = spawnSync(
'php',
[
'tests/Concurrency/unit-conversion-worker.php',
database,
'prepare-runtime',
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
env: environment,
},
);
if (
prepared.status !== 0 ||
prepared.stdout !== 'synthetic_standalone_inventory_prepared'
)
throw Error(
'Inventory runtime preparation failed: ' +
(prepared.stderr || prepared.stdout || ''),
);
const operationalEnvironment = {
...environment,
APP_ENV: 'standalone-qa',
COMPRAS_RUNTIME_ENABLED: 'true',
COMPRAS_RUNTIME_PREPARE_ONLY: 'false',
COMPRAS_INVENTORY_CONVERSION_ENABLED: 'true',
};
for (const match of fs
.readFileSync(
path.join(workspace, 'config/standalone-runtime.php'),
'utf8',
)
.matchAll(/env\('(COMPRAS_[A-Z_]+_ENABLED)'/g))
operationalEnvironment[match[1]] = 'true';
if (standaloneConversionPreview) {
if (standaloneCancellationPreview)
operationalEnvironment.COMPRAS_ORDER_CANCELLATION_ENABLED =
'true';
const { reviewStandaloneInventory } =
await import('./standalone-inventory-preview.mjs');
await reviewStandaloneInventory({
workspace,
root,
database,
environment: operationalEnvironment,
cancellation: standaloneCancellationPreview,
analytics: standaloneAnalyticsPreview,
});
} else {
const raced = spawnSync(
'php',
[
'tests/Concurrency/unit-conversion-worker.php',
database,
'race',
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
maxBuffer: 1024 * 1024,
env: operationalEnvironment,
},
);
process.stdout.write(
(raced.stdout || '').replaceAll(password, '[private]'),
);
process.stderr.write(
(raced.stderr || '').replaceAll(password, '[private]'),
);
if (raced.status !== 0)
throw Error('Operational inventory contention failed');
console.log(
JSON.stringify({
inventory_archive_extracted: true,
operational_environment: 'standalone-qa',
qa_conversion_disabled: true,
operational_changes: false,
}),
);
}
if (!standaloneConversionPreview || standaloneCancellationPreview) {
operationalEnvironment.SGC_STANDALONE_QA_ROOT = root;
operationalEnvironment.COMPRAS_QA_ORIGINAL_INSTALLATION_ID =
environment.COMPRAS_RUNTIME_INSTALLATION_ID;
const inspectInventory = (mode, env) => {
const check = spawnSync(
'php',
[
'tests/Support/standalone-inventory-recovery-worker.php',
env.DB_DATABASE,
mode,
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
maxBuffer: 1024 * 1024,
env,
},
);
if (check.status !== 0)
throw Error(
'Isolated inventory recovery check failed: ' +
(check.stderr || check.stdout || '').replaceAll(
env.DB_PASSWORD,
'[private]',
),
);
try {
return JSON.parse(check.stdout);
} catch {
throw Error(
'Inventory recovery returned an invalid receipt: ' +
(check.stdout || '')
.replaceAll(env.DB_PASSWORD, '[private]')
.slice(0, 2000),
);
}
};
const readMode = standaloneCancellationPreview
? 'read-cancellation'
: 'read';
const original = inspectInventory(readMode, operationalEnvironment);
const pgInventory = (binary, args, env) => {
const check = 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 (check.status !== 0)
throw Error('Synthetic inventory backup/restore failed');
};
const dump = path.join(root, 'inventory-recovery.dump');
pgInventory(
'pg_dump.exe',
[
'--format=custom',
'--no-owner',
'--no-acl',
'--file=' + dump,
'--dbname=' + database,
],
operationalEnvironment,
);
const restoredPassword = crypto.randomBytes(30).toString('hex');
restoreRole = role + '_restored';
sql(
`CREATE ROLE ${restoreRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`,
);
restoreDatabase = database + '_restored';
sql(
`CREATE DATABASE ${restoreDatabase} OWNER ${restoreRole}; REVOKE ALL ON DATABASE ${restoreDatabase} FROM PUBLIC;`,
);
const restored = {
...operationalEnvironment,
DB_DATABASE: restoreDatabase,
DB_USERNAME: restoreRole,
DB_PASSWORD: restoredPassword,
};
pgInventory(
'pg_restore.exe',
[
'--no-owner',
'--no-acl',
'--exit-on-error',
'--dbname=' + restoreDatabase,
dump,
],
restored,
);
const rejected = inspectInventory('reject-restore', restored);
if (rejected.rejected !== true)
throw Error('Restored inventory binding was not refused');
restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
const rebound = inspectInventory('rebind', {
...restored,
COMPRAS_RUNTIME_ENABLED: 'false',
COMPRAS_RUNTIME_PREPARE_ONLY: 'true',
});
if (rebound.state !== 'rebound')
throw Error('Inventory recovery binding not recorded');
const recovered = inspectInventory(readMode, restored);
if (JSON.stringify(original) !== JSON.stringify(recovered))
throw Error(
'Recovered inventory business data or legacy installation changed',
);
console.log(
JSON.stringify({
inventory_backup_restored: !standaloneCancellationPreview,
cancellation_backup_restored: standaloneCancellationPreview,
incompatible_binding_rejected: true,
explicit_rebind: true,
preserved_business_tables: recovered.business_tables,
recovered_converted_movements:
recovered.converted_movements,
recovered_cancellations: recovered.approved_cancellations,
source_cycle: recovered.source_cycle,
exact_replays: recovered.exact_replays,
}),
);
}
}
if (result.status === 0 && componentProfile) {
const profile = spawnSync(
'php',
[
'tests/Support/standalone-runtime-worker.php',
database,
'prepare-component-profile',
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
env: {
...environment,
APP_ENV: 'standalone-qa',
SGC_STANDALONE_QA_ROOT: root,
},
},
);
process.stdout.write(profile.stdout || '');
process.stderr.write(profile.stderr || '');
if (
profile.status !== 0 ||
!(profile.stdout || '').includes(
'synthetic_canonical_component_profiles',
)
)
throw Error('Canonical component profile fixture failed');
}
if (result.status === 0 && standaloneOnly && !componentProfile) {
const standaloneEnvironment = {
...environment,
APP_ENV: 'standalone-qa',
COMPRAS_RUNTIME_PREPARE_ONLY: 'false',
COMPRAS_RUNTIME_ROOT: activeStandaloneRoot,
COMPRAS_RUNTIME_SHA256: standalonePin,
COMPRAS_RUNTIME_INSTALLATION_ID: crypto.randomUUID(),
SGC_STANDALONE_QA_ROOT: root,
PAYABLE_SOURCE_INSTANCE: `standalone-synthetic-${id}`,
COMPRAS_CAPITAL_REGISTER_ENABLED: 'true',
COMPRAS_OPERATIONAL_ORDERS_ENABLED: 'true',
COMPRAS_PRIVATE_AUDIT_ENABLED: 'true',
COMPRAS_CONFLICT_RELEASES_ENABLED: 'true',
COMPRAS_URGENT_REVIEWS_ENABLED: 'true',
COMPRAS_URGENT_QUOTATIONS_ENABLED: 'true',
};
for (const feature of [
'BUDGET_DISTRIBUTIONS',
'REQUISITION_ACCOUNTS',
'REQUISITION_EXPIRY',
'EXPENSE_ALLOCATIONS',
'AGREEMENT_LIMITS',
'ORDER_PARTS',
'IMPORT_TARIFFS',
'IMPORT_LEGAL',
'IMPORT_DOSSIER',
'IMPORT_BANK_SUPPORT',
'IMPORT_READINESS',
'IMPORT_ESTIMATES',
'IMPORT_LANDED_COSTS',
'SUPPLIER_PAYABLES',
'GENERAL_LEDGER',
'SUPPLIER_SETTLEMENTS',
'GENERAL_LEDGER_CYCLE',
'FINANCE_CONFIGURATION',
])
standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true';
for (const mode of ['prepare', 'verify']) {
const check = spawnSync(
'php',
['tests/Support/standalone-runtime-worker.php', database, mode],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
maxBuffer: 1024 * 1024,
env: {
...standaloneEnvironment,
COMPRAS_RUNTIME_ENABLED:
mode === 'verify' ? 'true' : 'false',
COMPRAS_RUNTIME_PREPARE_ONLY:
mode === 'prepare' ? 'true' : 'false',
},
},
);
process.stdout.write(
(check.stdout || '').replaceAll(password, '[private]'),
);
process.stderr.write(
(check.stderr || '').replaceAll(password, '[private]'),
);
const expected = mode === 'prepare' ? 'prepared' : 'verified';
let receipt = null;
try {
receipt = JSON.parse((check.stdout || '').trim());
} catch {}
if (check.status !== 0 || receipt?.[expected] !== true) {
process.exitCode = 1;
break;
}
}
if (process.exitCode === 0) {
for (const mode of [
'reject-foreign',
'reject-pin',
'reject-prepare-pin',
'reject-dependency',
'reject-old',
]) {
const invalid = {
...standaloneEnvironment,
COMPRAS_RUNTIME_ENABLED: 'true',
};
if (mode === 'reject-prepare-pin') {
invalid.COMPRAS_RUNTIME_ENABLED = 'false';
invalid.COMPRAS_RUNTIME_PREPARE_ONLY = 'true';
}
if (mode === 'reject-pin' || mode === 'reject-prepare-pin')
invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64);
if (mode === 'reject-dependency')
invalid.COMPRAS_IMPORT_DOSSIER_ENABLED = 'false';
if (mode === 'reject-old') {
invalid.COMPRAS_RUNTIME_ROOT = path.join(
workspace,
'storage/framework/testing/compras-standalone-730845de0bddd000',
);
invalid.COMPRAS_RUNTIME_SHA256 =
'730845de0bddd0007845dd57599c084c4002f3c0672d05e89c582d8e0346fc7b';
}
const check = spawnSync(
'php',
[
'tests/Support/standalone-runtime-worker.php',
database,
mode,
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
maxBuffer: 1024 * 1024,
env: invalid,
},
);
process.stdout.write(
(check.stdout || '').replaceAll(password, '[private]'),
);
process.stderr.write(
(check.stderr || '').replaceAll(password, '[private]'),
);
let receipt = null;
try {
receipt = JSON.parse((check.stdout || '').trim());
} catch {}
if (check.status !== 0 || receipt?.rejected !== true) {
process.exitCode = 1;
break;
}
}
}
if (process.exitCode === 0) {
const pgCommand = (binary, args, env) => {
const check = 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 (check.status !== 0)
throw Error('Standalone private backup/restore failed');
};
const dump = path.join(root, 'standalone.dump');
pgCommand(
'pg_dump.exe',
[
'--format=custom',
'--no-owner',
'--no-acl',
'--file=' + dump,
'--dbname=' + database,
],
environment,
);
const restoredPassword = crypto.randomBytes(30).toString('hex');
restoreRole = role + '_restored';
restoreDatabase = database + '_restored';
sql(
`CREATE ROLE ${restoreRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`,
);
sql(
`CREATE DATABASE ${restoreDatabase} OWNER ${restoreRole}; REVOKE ALL ON DATABASE ${restoreDatabase} FROM PUBLIC;`,
);
const restored = {
...standaloneEnvironment,
DB_DATABASE: restoreDatabase,
DB_USERNAME: restoreRole,
DB_PASSWORD: restoredPassword,
};
pgCommand(
'pg_restore.exe',
[
'--no-owner',
'--no-acl',
'--exit-on-error',
'--dbname=' + restoreDatabase,
dump,
],
restored,
);
for (const mode of ['reject-restore', 'rebind', 'verify']) {
if (mode === 'rebind')
restored.COMPRAS_RUNTIME_INSTALLATION_ID =
crypto.randomUUID();
const check = spawnSync(
'php',
[
'tests/Support/standalone-runtime-worker.php',
restoreDatabase,
mode,
],
{
cwd: workspace,
windowsHide: true,
encoding: 'utf8',
maxBuffer: 1024 * 1024,
env: {
...restored,
COMPRAS_RUNTIME_ENABLED:
mode === 'rebind' ? 'false' : 'true',
COMPRAS_RUNTIME_PREPARE_ONLY:
mode === 'rebind' ? 'true' : 'false',
},
},
);
process.stdout.write(
(check.stdout || '').replaceAll(
restoredPassword,
'[private]',
),
);
process.stderr.write(
(check.stderr || '').replaceAll(
restoredPassword,
'[private]',
),
);
let receipt = null;
try {
receipt = JSON.parse((check.stdout || '').trim());
} catch {}
const expected =
mode === 'reject-restore'
? 'rejected'
: mode === 'rebind'
? 'prepared'
: 'verified';
if (check.status !== 0 || receipt?.[expected] !== true) {
process.exitCode = 1;
break;
}
}
}
if (process.exitCode === 0) {
const { verifyConfigurationConcurrency } =
await import('./standalone-configuration-race.mjs');
await verifyConfigurationConcurrency(workspace, root, database, {
...standaloneEnvironment,
COMPRAS_RUNTIME_ENABLED: 'true',
});
}
if (process.exitCode === 0 && financePreview) {
const { reviewStandaloneFinance } =
await import('./standalone-finance-preview.mjs');
await reviewStandaloneFinance({
workspace,
root,
database,
environment: {
...standaloneEnvironment,
COMPRAS_RUNTIME_ENABLED: 'true',
},
assets: path.join(
privateParent,
'sgc-standalone-finance-help-qa-20261129',
),
manifestPin:
'8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b',
});
}
}
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,
}),
);
}