commit compras5 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 19:49:19 +02:00
parent a935499d64
commit 96b30368bc
96 changed files with 3397 additions and 111 deletions
@@ -0,0 +1,127 @@
<?php
use App\Services\InventoryConversionRuntime;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
if (count($argv) !== 2 || ! in_array($argv[1], ['--preview', '--apply-authorized'], true)) {
throw new LogicException('Use --preview or --apply-authorized.');
}
$root = dirname(__DIR__);
$proposal = $root.'/docs/proofs/inventory-conversion-pilot-proposal.json';
$plan = json_decode(file_get_contents($proposal), true, 512, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/inventory-conversion-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if ($approval['state'] !== 'approved' || ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $proposal))) {
throw new LogicException('Inventory installation authorization mismatch.');
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$destination = 'C:/laragon/data/compras/runtime/inventory-8608e6551dea6448';
$resultPath = $root.'/docs/proofs/inventory-conversion-pilot-installation.json';
if ($plan['target']['settings'] !== $settingsPath || $plan['target']['inventory_directory'] !== $destination || is_file($resultPath)) {
throw new LogicException('Installation target or existing result differs.');
}
$before = file_get_contents($settingsPath);
if (! hash_equals($plan['target']['settings_before_sha256'], hash('sha256', $before))) {
throw new LogicException('Pilot settings changed since authorization.');
}
$settings = json_decode($before, true, 32, JSON_THROW_ON_ERROR);
if ($settings['DB_HOST'] !== '127.0.0.1' || (string) $settings['DB_PORT'] !== '5432'
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'], $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1] || $settings['APP_ENV'] !== 'payable-testing'
|| $settings['COMPRAS_RUNTIME_INSTALLATION_ID'] !== $plan['target']['financial_installation_id']) {
throw new LogicException('Pilot identity differs.');
}
$archive = $root.'/storage/framework/testing/compras-inventory-'.InventoryConversionRuntime::MANIFEST_SHA256.'.zip';
if (! hash_equals($plan['target']['inventory_archive_sha256'], hash_file('sha256', $archive))) {
throw new LogicException('Inventory archive differs.');
}
$changes = ['COMPRAS_INVENTORY_CONVERSION_ENABLED' => 'true', 'COMPRAS_INVENTORY_ROOT' => $destination];
if ($changes !== $plan['proposed_settings_only']) {
throw new LogicException('Unreviewed settings changes refused.');
}
$after = [...$settings, ...$changes];
$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
$preflight = new Process([PHP_BINARY, 'scripts/check-inventory-conversion-pilot.php', '--read-only'], $root, timeout: 30);
$preflight->mustRun();
$check = json_decode($preflight->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if ($check['state'] !== 'passed' || $check['active_settings_changed'] !== false) {
throw new LogicException('Read-only installation preflight failed.');
}
if ($argv[1] === '--preview') {
echo json_encode(['state' => 'preview', 'verified_archive' => true, 'read_only_preflight' => true,
'changed_keys' => array_keys($changes), 'settings_or_database_written' => false], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if (file_exists($destination)) {
throw new LogicException('Existing inventory destination refused; preserve and inspect it.');
}
$backup = 'C:/laragon/data/compras/backups/inventory-activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($backup, 0700, true) || file_put_contents($backup.'/settings.before.private.json', $before, LOCK_EX) !== strlen($before)
|| ! hash_equals(hash('sha256', $before), hash_file('sha256', $backup.'/settings.before.private.json'))) {
throw new LogicException('Verified private settings backup required.');
}
$db = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->exec('SET default_transaction_read_only=on');
$frames = static function () use ($db): array {
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$out = [];
foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
$quoted = '"'.str_replace('"', '""', $table).'"';
$rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$out[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
$db->commit();
return $out;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
};
$baseline = $frames();
file_put_contents($backup.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
$protected = ['env' => hash_file('sha256', $root.'/.env'), 'frontend' => hash_file('sha256', $root.'/public/build/manifest.json')];
$zip = new ZipArchive;
if ($zip->open($archive) !== true || $zip->numFiles !== 4) {
throw new LogicException('Reviewed archive required.');
}
InventoryConversionRuntime::assertArchiveEntries($zip);
if (! mkdir($destination, 0700) || ! $zip->extractTo($destination) || ! $zip->close()) {
throw new LogicException('Inventory extraction failed; settings not changed.');
}
InventoryConversionRuntime::verifyArtifact($destination);
$temporary = $settingsPath.'.inventory-'.bin2hex(random_bytes(6)).'.tmp';
try {
if (file_put_contents($temporary, $encoded, LOCK_EX) !== strlen($encoded)
|| ! hash_equals(hash('sha256', $before), hash_file('sha256', $settingsPath)) || ! rename($temporary, $settingsPath)) {
throw new LogicException('Atomic settings selection failed.');
}
$postcheck = new Process([PHP_BINARY, 'scripts/check-inventory-conversion-pilot.php', '--installed-read-only'], $root, timeout: 30);
$postcheck->mustRun();
$verified = json_decode($postcheck->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if ($verified['state'] !== 'passed' || ! $verified['inventory_component_installed_or_activated'] || $frames() !== $baseline
|| hash_file('sha256', $root.'/.env') !== $protected['env'] || hash_file('sha256', $root.'/public/build/manifest.json') !== $protected['frontend']
|| json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
throw new LogicException('Installed component conservation failed.');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'authorization' => 'inventory-conversion-pilot-authorization.json',
'target' => 'http://127.0.0.1:8005', 'backup_directory' => $backup, 'inventory_directory' => $destination,
'inventory_manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256,
'settings_before_sha256' => hash('sha256', $before), 'settings_after_sha256' => hash('sha256', $encoded),
'changed_keys' => array_keys($changes), 'all_database_tables_preserved' => count($baseline),
'unrelated_settings_env_frontend_and_financial_receipt_preserved' => true,
'new_permissions_users_migrations_or_business_commands' => false, 'application_complete' => false];
file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
} catch (Throwable $error) {
// No blind downgrade after possible converted effects or concurrent business edits.
file_put_contents($backup.'/failure.private.json', json_encode(['state' => 'requires_inspection_before_configuration_recovery', 'error_class' => $error::class], JSON_THROW_ON_ERROR));
throw $error;
} finally {
if (is_file($temporary)) {
unlink($temporary);
}
}
@@ -0,0 +1,111 @@
<?php
use App\Services\OrderCancellationRuntime;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (count($argv) !== 2 || ! in_array($argv[1], ['--preview', '--apply-authorized'], true)) {
throw new LogicException('Explicit pilot cancellation preview or installation required.');
}
$proposal = $root.'/docs/proofs/order-cancellation-pilot-proposal.json';
$plan = json_decode(file_get_contents($proposal), true, 32, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/order-cancellation-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$resultPath = $root.'/docs/proofs/order-cancellation-pilot-installation.json';
$sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$destination = 'C:/laragon/data/compras/runtime/order-cancellation-52df7927aa268959';
if ($approval['state'] !== 'approved' || ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $proposal))
|| is_file($resultPath) || $plan['target_root'] !== $destination || $plan['manifest_sha256'] !== OrderCancellationRuntime::MANIFEST_SHA256) {
throw new LogicException('Cancellation installation authorization or target mismatch.');
}
$before = file_get_contents($sourcePath);
$settings = json_decode($before, true, 32, JSON_THROW_ON_ERROR);
if (! hash_equals($plan['settings_before_sha256'], hash('sha256', $before))) {
throw new LogicException('Cancellation configuration changed since preparation.');
}
$changes = ['COMPRAS_ORDER_CANCELLATION_ENABLED' => 'true', 'COMPRAS_ORDER_CANCELLATION_ROOT' => $destination];
if ($changes !== $plan['proposed_settings_only']) {
throw new LogicException('Unreviewed cancellation configuration refused.');
}
$candidate = $root.'/'.$plan['candidate_root'];
OrderCancellationRuntime::verifyArtifact($candidate);
$preflight = new Process([PHP_BINARY, 'scripts/check-order-cancellation-pilot.php', '--read-only'], $root, timeout: 30);
$preflight->mustRun();
if (json_decode($preflight->getOutput(), true, 32, JSON_THROW_ON_ERROR)['state'] !== 'passed') {
throw new LogicException('Cancellation read-only preflight failed.');
}
if ($argv[1] === '--preview') {
echo json_encode(['state' => 'preview', 'changed_keys' => array_keys($changes), 'database_writes' => false], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if (file_exists($destination)) {
throw new LogicException('Preserve existing cancellation component directory.');
}
$backup = 'C:/laragon/data/compras/backups/cancellation-activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($backup, 0700, true) || file_put_contents($backup.'/settings.before.private.json', $before, LOCK_EX) !== strlen($before)
|| ! hash_equals(hash('sha256', $before), hash_file('sha256', $backup.'/settings.before.private.json'))) {
throw new LogicException('Cancellation configuration backup failed.');
}
$db = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->exec('SET default_transaction_read_only=on');
$frames = static function () use ($db): array {
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$out = [];
foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
$quoted = '"'.str_replace('"', '""', $table).'"';
$rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$out[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
$db->commit();
return $out;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
};
$baseline = $frames();
file_put_contents($backup.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
$envHash = hash_file('sha256', $root.'/.env');
$assetsHash = hash_file('sha256', $root.'/public/build/manifest.json');
if (! mkdir($destination, 0700) || ! mkdir($destination.'/src', 0700)) {
throw new LogicException('Cancellation private destination unavailable.');
}
foreach (['manifest.json', 'src/CommitmentReversal.php'] as $file) {
if (! copy($candidate.'/'.$file, $destination.'/'.$file)) {
throw new LogicException('Cancellation component copy failed before activation.');
}
}
OrderCancellationRuntime::verifyArtifact($destination);
$after = [...$settings, ...$changes];
$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
$temporary = $sourcePath.'.cancellation-'.bin2hex(random_bytes(6)).'.tmp';
try {
if (file_put_contents($temporary, $encoded, LOCK_EX) !== strlen($encoded)
|| ! hash_equals(hash('sha256', $before), hash_file('sha256', $sourcePath)) || ! rename($temporary, $sourcePath)) {
throw new LogicException('Cancellation atomic configuration selection failed.');
}
$check = new Process([PHP_BINARY, 'scripts/check-order-cancellation-pilot.php', '--installed-read-only'], $root, timeout: 30);
$check->mustRun();
if (json_decode($check->getOutput(), true, 32, JSON_THROW_ON_ERROR)['state'] !== 'passed'
|| $frames() !== $baseline || hash_file('sha256', $root.'/.env') !== $envHash
|| hash_file('sha256', $root.'/public/build/manifest.json') !== $assetsHash
|| json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
throw new LogicException('Cancellation installation conservation failed; inspect without reverting business rows.');
}
$report = ['date' => gmdate('c'), 'state' => 'passed', 'target' => 'http://127.0.0.1:8005',
'authorization' => 'order-cancellation-pilot-authorization.json', 'backup_directory' => $backup, 'component_directory' => $destination,
'manifest_sha256' => OrderCancellationRuntime::MANIFEST_SHA256, 'changed_keys' => array_keys($changes),
'settings_before_sha256' => hash('sha256', $before), 'settings_after_sha256' => hash('sha256', $encoded),
'all_database_tables_preserved' => count($baseline), 'unrelated_settings_financial_receipt_env_and_frontend_preserved' => true,
'policies_grants_migrations_or_business_commands' => false, 'application_complete' => false];
file_put_contents($resultPath, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($report, JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if (is_file($temporary)) {
unlink($temporary);
}
}
@@ -0,0 +1,45 @@
<?php
use App\Services\InventoryConversionRuntime;
require __DIR__.'/../vendor/autoload.php';
$root = dirname(__DIR__).'/packages/inventory-write/releases/0.2.0-rc.1';
InventoryConversionRuntime::verifyArtifact($root);
$manifest = json_decode(file_get_contents($root.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
$parent = dirname(__DIR__).'/storage/framework/testing';
if (! is_dir($parent) && ! mkdir($parent, 0700, true)) {
throw new LogicException('Private artifact directory unavailable.');
}
$target = $parent.'/compras-inventory-'.InventoryConversionRuntime::MANIFEST_SHA256.'.zip';
$temporary = $target.'.'.bin2hex(random_bytes(8)).'.tmp';
try {
$zip = new ZipArchive;
if ($zip->open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new LogicException('Private archive creation failed.');
}
foreach (['manifest.json', ...array_keys($manifest['files'])] as $file) {
if (! $zip->addFile($root.'/'.$file, $file) || ! $zip->setMtimeName($file, 1795910400)
|| ! $zip->setExternalAttributesName($file, ZipArchive::OPSYS_UNIX, 0100644 << 16)) {
throw new LogicException('Private archive entry failed.');
}
}
if (! $zip->close()) {
throw new LogicException('Private archive close failed.');
}
$hash = hash_file('sha256', $temporary);
if (is_file($target)) {
if (is_link($target) || ! hash_equals($hash, hash_file('sha256', $target))) {
throw new LogicException('Existing archive differs; replacement refused.');
}
} elseif (! rename($temporary, $target)) {
throw new LogicException('Private archive publication failed.');
}
echo json_encode(['state' => 'private_candidate_only', 'archive' => $target, 'entries' => 4,
'manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256, 'archive_sha256' => $hash,
'pilot_or_production_changes' => false], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT).PHP_EOL;
} finally {
if (is_file($temporary)) {
unlink($temporary);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
// Technical verification of the owned, disposable synthetic cluster; never application access.
$root = realpath($argv[1] ?? '');
$mode = $argv[2] ?? '';
if ($root === false || dirname($root) !== realpath(__DIR__.'/../storage/framework/testing')
|| ! preg_match('/^rq01-ledger-qa-([a-f0-9]{12})$/D', basename($root), $match)
|| ! in_array($mode, ['--capture', '--verify'], true)) {
throw new LogicException('Owned synthetic analytical preview required.');
}
$database = 'compras_receipts_test_'.$match[1];
$db = new PDO('pgsql:host=127.0.0.1;port=55439;dbname='.$database, 'sgf_regression_owner',
trim(file_get_contents($root.'/admin-password.txt')), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->beginTransaction();
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
if ($db->query("select current_setting('cluster_name')")->fetchColumn() !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Wrong analytical verification cluster.');
}
$frames = [];
foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
if (in_array($table, ['supply_records', 'audit_logs'], true)) {
continue;
}
// Normal authentication may rehash a synthetic password or rotate a remember token.
$query = $table === 'users' ? 'SELECT id,tenant_id,department_id,purchasing_role,name,email,created_at FROM users'
: 'SELECT * FROM "'.str_replace('"', '""', $table).'"';
$rows = $db->query('SELECT row_to_json(t)::text FROM ('.$query.') t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$frames[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
$file = $root.'/analytics-baseline.private.json';
if ($mode === '--capture') {
if (is_file($file) || (int) $db->query("SELECT count(*) FROM supply_records WHERE kind='expense_allocation'")->fetchColumn() !== 0) {
throw new LogicException('Fresh analytical baseline required.');
}
file_put_contents($file, json_encode($frames, JSON_THROW_ON_ERROR));
echo json_encode(['state' => 'captured', 'protected_tables' => count($frames), 'database_read_only' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} else {
if ($frames !== json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR)) {
throw new LogicException('Native analytical review changed protected source data.');
}
$records = $db->query("SELECT data FROM supply_records WHERE kind='expense_allocation' ORDER BY id")->fetchAll(PDO::FETCH_COLUMN);
$data = count($records) === 1 ? json_decode($records[0], true, 32, JSON_THROW_ON_ERROR) : [];
if (($data['source_type'] ?? null) !== 'common_allocation' || ($data['allocations'] ?? []) !== [
['category' => 'Material', 'amount_minor' => '1500'], ['category' => 'Serviços', 'amount_minor' => '2500']]
|| (int) $db->query("SELECT count(*) FROM audit_logs WHERE action='expense.allocation_recorded'")->fetchColumn() !== 1) {
throw new LogicException('One exact explicit analytical attribution and audit required.');
}
echo json_encode(['state' => 'passed', 'protected_tables' => count($frames), 'database_read_only' => true,
'explicit_category_total_minor' => 4000, 'one_attribution_one_audit' => true, 'no_financial_source_mutation' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
$db->commit();
@@ -0,0 +1,84 @@
<?php
use App\Services\InventoryConversionRuntime;
use App\Services\ReceiptStockMovement;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (count($argv) !== 2 || ! in_array($argv[1], ['--read-only', '--installed-read-only'], true)) {
throw new LogicException('Explicit read-only preflight required.');
}
$root = dirname(__DIR__);
$installed = $argv[1] === '--installed-read-only';
$sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$sourceBytes = file_get_contents($sourcePath);
$source = json_decode($sourceBytes, true, 32, JSON_THROW_ON_ERROR);
$sourceHash = hash('sha256', $sourceBytes);
$publicHash = hash_file('sha256', $root.'/public/build/manifest.json');
if ($source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1' || (string) $source['DB_PORT'] !== '5432'
|| realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| $source['COMPRAS_RUNTIME_INSTALLATION_ID'] !== '0602a856-0413-480f-9ef3-1a1f3238bb90'
|| $source['COMPRAS_RUNTIME_SHA256'] !== '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7'
|| ! in_array($source['COMPRAS_INVENTORY_CONVERSION_ENABLED'] ?? 'false', $installed ? ['true', true] : ['false', false], true)) {
throw new LogicException('Pilot source differs from reviewed installation.');
}
$candidate = $installed ? 'C:/laragon/data/compras/runtime/inventory-8608e6551dea6448' : $root.'/packages/inventory-write/releases/0.2.0-rc.1';
if ($installed && ($source['COMPRAS_INVENTORY_ROOT'] ?? null) !== $candidate) {
throw new LogicException('Installed inventory location differs.');
}
InventoryConversionRuntime::verifyArtifact($candidate);
$environment = [...$source, 'APP_ENV' => 'pilot-readonly', 'APP_DEBUG' => 'false',
'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
'COMPRAS_INVENTORY_CONVERSION_ENABLED' => 'true', 'COMPRAS_INVENTORY_ROOT' => $candidate,
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-inventory-readonly-config.php', 'LOG_CHANNEL' => 'stderr'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('Database read-only enforcement required.');
}
// Conservation belongs to this inspection. Installation-time conservation remains
// in the immutable installation proof; an operating application may advance its queue.
DB::beginTransaction();
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$frames = static function (): array {
$result = [];
foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
$quoted = '"'.str_replace('"', '""', $table->tablename).'"';
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM '.$quoted.' t ORDER BY row_to_json(t)::text');
$result[$table->tablename] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $result;
};
$baseline = $frames();
if (! app(InventoryConversionRuntime::class)->available()) {
throw new LogicException('Candidate unavailable with prospective configuration.');
}
app(ReceiptStockMovement::class)->load();
$converted = DB::table('goods_receipt_items')->whereNotNull('snapshot->quantity_conversion')->count();
if ($frames() !== $baseline) {
throw new LogicException('Inventory inspection changed pilot data.');
}
$preserved = count($baseline);
DB::commit();
if (! hash_equals($sourceHash, hash_file('sha256', $sourcePath))
|| ! hash_equals($publicHash, hash_file('sha256', $root.'/public/build/manifest.json'))) {
throw new LogicException('Concurrent pilot settings or frontend change.');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'mode' => $installed ? 'installed_read_only_postcheck' : 'prospective_read_only_preflight',
'database_enforced_read_only' => true, 'candidate_available_with_installed_financial_runtime' => true,
'inventory_manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256,
'active_settings_sha256' => $sourceHash, 'public_manifest_sha256' => $publicHash,
'existing_converted_receipt_lines' => $converted, 'active_settings_changed' => false,
'database_tables_preserved_during_readonly_check' => $preserved,
'inventory_component_installed_or_activated' => $installed, 'migrations_or_business_commands' => false];
file_put_contents($root.'/docs/proofs/inventory-conversion-pilot-'.($installed ? 'current-check' : 'preflight').'.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,52 @@
<?php
use App\Services\OrderCancellationRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (count($argv) !== 2 || ! in_array($argv[1], ['--read-only', '--installed-read-only'], true)) {
throw new LogicException('Explicit cancellation read-only check required.');
}
$root = dirname(__DIR__);
$installed = $argv[1] === '--installed-read-only';
$sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$before = file_get_contents($sourcePath);
$source = json_decode($before, true, 32, JSON_THROW_ON_ERROR);
$plan = json_decode(file_get_contents($root.'/docs/proofs/order-cancellation-pilot-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
if ($source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1' || (string) $source['DB_PORT'] !== '5432'
|| realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| $source['COMPRAS_RUNTIME_INSTALLATION_ID'] !== '0602a856-0413-480f-9ef3-1a1f3238bb90'
|| ($installed ? array_intersect_key($source, $plan['proposed_settings_only']) !== $plan['proposed_settings_only']
: ! hash_equals($plan['settings_before_sha256'], hash('sha256', $before)))) {
throw new LogicException('Cancellation pilot identity or settings differ.');
}
$environment = [...$source, 'APP_ENV' => 'pilot-readonly', 'APP_DEBUG' => 'false', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '',
'PGOPTIONS' => '-c default_transaction_read_only=on', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array',
'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array', 'LOG_CHANNEL' => 'stderr',
'COMPRAS_ORDER_CANCELLATION_ENABLED' => 'true',
'COMPRAS_ORDER_CANCELLATION_ROOT' => $installed ? $plan['target_root'] : $root.'/'.$plan['candidate_root'],
'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-cancellation-readonly-config.php'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('Enforced read-only database required.');
}
app(OrderCancellationRuntime::class)->assertReady();
app(OrderCancellationRuntime::class)->load(0); // Byte-checked class loading only, no reversal command.
if (! hash_equals(hash('sha256', $before), hash_file('sha256', $sourcePath))) {
throw new LogicException('Concurrent cancellation configuration edit.');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'installed' => $installed, 'database_enforced_read_only' => true,
'manifest_sha256' => OrderCancellationRuntime::MANIFEST_SHA256,
'existing_cancellation_records' => DB::table('order_cancellations')->count(),
'existing_approved_policies' => DB::table('order_cancellation_policies')->where('status', 'approved')->count(),
'new_policies_grants_business_commands_or_settings_changes' => false];
file_put_contents($root.'/docs/proofs/order-cancellation-pilot-'.($installed ? 'postcheck' : 'preflight').'.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+77
View File
@@ -0,0 +1,77 @@
<?php
use App\Services\OperationalHealth;
use App\Services\ReplenishmentTaskDefinition;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array(count($argv), [2, 3], true) || $argv[1] !== '--read-only'
|| (count($argv) === 3 && $argv[2] !== '--installation-conservation')) {
throw new LogicException('Explicit read-only operational inspection required.');
}
$root = dirname(__DIR__);
$path = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$bytes = file_get_contents($path);
$settings = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
if ($settings['APP_ENV'] !== 'payable-testing' || $settings['DB_HOST'] !== '127.0.0.1'
|| (string) $settings['DB_PORT'] !== '5432' || realpath($settings['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'], $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('Existing Compras pilot required.');
}
foreach ([...$settings, 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
'LOG_CHANNEL' => 'stderr', 'APP_DEBUG' => 'false', 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-operations-check.php'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('Enforced database read-only mode required.');
}
app(StandaloneRuntime::class)->assertLoadedPackages();
$result = app(OperationalHealth::class)->inspect();
$taskProof = $root.'/docs/proofs/replenishment-task-installation.json';
$taskVerification = null;
if (is_file($taskProof)) {
$task = json_decode(file_get_contents($taskProof), true, 32, JSON_THROW_ON_ERROR);
$directory = str_replace('\\', '/', $task['private_backup_directory']);
if (! preg_match('~^C:/laragon/data/compras/tasks/replenishment-[0-9]{8}-[0-9]{6}-[a-f0-9]{12}$~D', $directory)
|| $task['task_name'] !== 'Compras-Pilot-Replenishment') {
throw new LogicException('Owned replenishment task backup required.');
}
$native = new Process([getenv('SystemRoot').'/System32/schtasks.exe', '/Query', '/TN', $task['task_name'], '/XML'], $root, timeout: 15);
$native->run();
if (! $native->isSuccessful()) {
throw new LogicException('Native replenishment task unavailable.');
}
ReplenishmentTaskDefinition::assertMatches(file_get_contents($directory.'/task.private.xml'), $native->getOutput());
$baseline = count($argv) === 3
? json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR) : [];
$changed = [];
foreach ($baseline as $table => $before) {
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text');
$same = hash_equals($before['sha256'], hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR)));
if (! $same) {
$changed[] = $table;
if (! in_array($table, ['replenishment_work', 'supply_records', 'audit_logs'], true)) {
throw new LogicException('Protected pilot table changed during replenishment verification.');
}
}
}
$taskVerification = ['native_definition_verified' => true, 'installation_conservation_requested' => count($argv) === 3, 'baseline_tables' => count($baseline),
'unchanged_tables' => count($baseline) - count($changed), 'changed_native_replenishment_tables' => $changed,
'new_policies_or_grants' => false];
}
if (! hash_equals(hash('sha256', $bytes), hash_file('sha256', $path))) {
throw new LogicException('Pilot settings changed during inspection.');
}
$proof = ['date' => gmdate('c'), 'database_enforced_read_only' => true, 'business_commands' => false,
'replenishment_task_verification' => $taskVerification, 'result' => $result];
file_put_contents($root.'/docs/proofs/pilot-operations-current.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;
exit($result['ok'] ? 0 : 1);
+36 -5
View File
@@ -15,14 +15,45 @@ $sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$source = json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR);
$expectedSettings = $plan['active_settings_sha256'];
$expectedManifest = $plan['frontend']['previous_manifest_sha256'];
$frontend = $plan['frontend'];
if ($installed) {
$activation = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation.json'), true, 32, JSON_THROW_ON_ERROR);
$previous = json_decode(file_get_contents($activation['backup_directory'].'/settings.before.private.json'), true, 32, JSON_THROW_ON_ERROR);
if ($activation['state'] !== 'passed' || $source !== [...$previous, ...$plan['proposed_runtime_settings']]) {
$component = [];
foreach (['inventory-conversion', 'order-cancellation'] as $componentName) {
if (! is_file($root.'/docs/proofs/'.$componentName.'-pilot-installation.json')) {
continue;
}
$inventory = json_decode(file_get_contents($root.'/docs/proofs/'.$componentName.'-pilot-installation.json'), true, 32, JSON_THROW_ON_ERROR);
$inventoryPlanPath = $root.'/docs/proofs/'.$componentName.'-pilot-proposal.json';
$inventoryPlan = json_decode(file_get_contents($inventoryPlanPath), true, 32, JSON_THROW_ON_ERROR);
$inventoryApproval = json_decode(file_get_contents($root.'/docs/proofs/'.$componentName.'-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if ($inventory['state'] !== 'passed' || $inventoryApproval['state'] !== 'approved'
|| ! hash_equals($inventoryApproval['proposal_sha256'], hash_file('sha256', $inventoryPlanPath))) {
throw new LogicException('ACTIVATION_POSTCHECK_COMPONENT_AUTHORIZATION');
}
$component = [...$component, ...$inventoryPlan['proposed_settings_only']];
}
if ($activation['state'] !== 'passed' || $source !== [...$previous, ...$plan['proposed_runtime_settings'], ...$component]) {
throw new LogicException('ACTIVATION_POSTCHECK_SETTINGS_DIFFER');
}
$expectedSettings = hash_file('sha256', $sourcePath);
$expectedManifest = $plan['frontend']['manifest_sha256'];
$interfacePlanPath = $root.'/docs/proofs/analytics-print-publication-proposal.json';
if (is_file($root.'/docs/proofs/analytics-print-publication.json')) {
$interfacePlan = json_decode(file_get_contents($interfacePlanPath), true, 512, JSON_THROW_ON_ERROR);
$interfaceApproval = json_decode(file_get_contents($root.'/docs/proofs/analytics-print-publication-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$interfaceResult = json_decode(file_get_contents($root.'/docs/proofs/analytics-print-publication.json'), true, 32, JSON_THROW_ON_ERROR);
if ($interfaceApproval['state'] !== 'approved' || ($interfaceResult['pilot_state'] ?? $interfaceResult['state']) !== 'passed'
|| $interfaceApproval['scope'] !== 'analytics_print_and_attribution_menu_shared_frontend_delta'
|| ! hash_equals($interfaceApproval['proposal_sha256'], hash_file('sha256', $interfacePlanPath))
|| $interfacePlan['previous_manifest_sha256'] !== $expectedManifest
|| $interfaceResult['manifest_sha256'] !== $interfacePlan['manifest_sha256']) {
throw new LogicException('ACTIVATION_POSTCHECK_INTERFACE_AUTHORIZATION');
}
$frontend = $interfacePlan;
$expectedManifest = $interfacePlan['manifest_sha256'];
}
}
if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))
|| $source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1'
@@ -32,12 +63,12 @@ if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))
|| trim($source['PAYABLE_SOURCE_INSTANCE'] ?? '') === '') {
throw new LogicException('ACTIVATION_PREFLIGHT_SOURCE_CHANGED');
}
$assets = $root.'/'.$plan['frontend']['candidate_root'];
if (! hash_equals($plan['frontend']['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
$assets = $root.'/'.$frontend['candidate_root'];
if (! hash_equals($frontend['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
|| ! hash_equals($expectedManifest, hash_file('sha256', $root.'/public/build/manifest.json'))) {
throw new LogicException('ACTIVATION_PREFLIGHT_MANIFEST_CHANGED');
}
foreach ($plan['frontend']['files'] as $file => $hash) {
foreach ($frontend['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('ACTIVATION_PREFLIGHT_ASSET_MISMATCH');
@@ -68,7 +99,7 @@ if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))) {
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'database_enforced_read_only' => true,
'all_24_capabilities_start_with_pinned_installed_packages' => true, 'source_instance_preserved' => true,
'frontend_assets_verified' => count($plan['frontend']['files']), 'active_settings_changed' => false,
'frontend_assets_verified' => count($frontend['files']), 'active_settings_changed' => false,
'mode' => $installed ? 'installed_configuration_read_only_postcheck' : 'prospective_read_only_preflight',
'assets_published' => $installed, 'new_grants_or_business_commands' => false];
file_put_contents($root.'/docs/proofs/'.($installed ? 'compras-standalone-pilot-activation-check.json' : 'compras-standalone-pilot-activation-preflight.json'), json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+2 -1
View File
@@ -65,11 +65,12 @@ $frames = static function (): array {
$before = $frames();
app(StandaloneRuntime::class)->assertLoadedPackages();
$results = [];
$extraPaths = config('order_cancellation.enabled') === true ? ['/ordens/cancelamentos'] : [];
foreach (['admin', 'procurement', 'finance', 'warehouse'] as $role) {
$actor = User::query()->where('email', 'avaliacao-'.$role.'@example.test')->firstOrFail();
foreach (['/dashboard', '/requisicoes', '/projectos-imobilizado', '/ordens-operacionais', '/administracao/financeiro',
'/administracao/prazos-aprovacao', '/administracao/revisao-urgencias', '/requisicoes/urgencias/revisoes',
'/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa'] as $path) {
'/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa', ...$extraPaths] as $path) {
$app->forgetScopedInstances();
$request = Request::create('http://127.0.0.1:8005'.$path, 'GET', server: ['REMOTE_ADDR' => '127.0.0.1',
'HTTP_ACCEPT' => 'application/json', 'HTTP_X_INERTIA' => 'true']);
+22 -5
View File
@@ -2,7 +2,23 @@ import fs from 'node:fs/promises';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
const plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8'));
let plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8'));
let interfaceDelta = false;
try {
const result = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication.json', 'utf8'));
const bytes = await fs.readFile('docs/proofs/analytics-print-publication-proposal.json');
const proposal = JSON.parse(bytes);
const approval = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication-authorization.json', 'utf8'));
assert.equal(result.pilot_state ?? result.state, 'passed');
assert.equal(approval.state, 'approved');
assert.equal(approval.proposal_sha256, crypto.createHash('sha256').update(bytes).digest('hex'));
assert.equal(result.manifest_sha256, proposal.manifest_sha256);
assert.equal(proposal.previous_manifest_sha256, plan.frontend.manifest_sha256);
plan = { ...plan, frontend: proposal };
interfaceDelta = true;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
const activation = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation.json', 'utf8'));
assert.equal(activation.state, 'passed');
assert.equal(plan.target, 'http://127.0.0.1:8005');
@@ -29,9 +45,10 @@ const page = JSON.parse(bootstrap[1]);
assert.equal(page.props.auth.user, null);
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
const manifest = JSON.parse(await fs.readFile('public/build/manifest.json', 'utf8'));
assert.ok(html.includes(manifest['resources/js/app.tsx'].file));
const proof = { date: new Date().toISOString(), state: 'passed', pilot_asset_responses_and_hashes: verified,
public_domain_html_delivers_new_entry: true, public_anonymous_identity_preserved: true,
const publicCurrent = html.includes(manifest['resources/js/app.tsx'].file);
const proof = { date: new Date().toISOString(), state: publicCurrent ? 'passed' : 'pilot_passed_public_installation_pending', pilot_asset_responses_and_hashes: verified,
public_domain_html_delivers_new_entry: publicCurrent, public_anonymous_identity_preserved: true,
private_finance_navigation_not_exposed_publicly: true, new_grants_or_business_operations: false };
await fs.writeFile('docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n');
await fs.writeFile(interfaceDelta ? 'docs/proofs/analytics-print-publication-http.json' : 'docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n');
console.log(JSON.stringify(proof));
if (!publicCurrent) process.exitCode = 1;
+136
View File
@@ -0,0 +1,136 @@
<?php
use App\Services\ReplenishmentTaskDefinition;
use App\Services\WindowsTaskXml;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
$planPath = $root.'/docs/proofs/replenishment-task-proposal.json';
$plan = json_decode(file_get_contents($planPath), true, 32, JSON_THROW_ON_ERROR);
$apply = in_array('--apply-authorized', $argv, true);
if (realpath($root) !== realpath('C:/laragon/www/compras') || $plan['task_name'] !== 'Compras-Pilot-Replenishment'
|| str_replace('\\', '/', dirname(PHP_BINARY)) !== dirname($plan['php_executable'])) {
throw new LogicException('REPLENISHMENT_TASK_INSTALLATION_TARGET');
}
foreach ($plan['source_sha256'] as $file => $hash) {
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
throw new LogicException('REPLENISHMENT_TASK_SOURCE_CHANGED');
}
}
if (! hash_equals($plan['php_sha256'], hash_file('sha256', $plan['php_executable']))) {
throw new LogicException('REPLENISHMENT_GUI_EXECUTABLE_CHANGED');
}
$run = static function (array $command, int $timeout = 15) use ($root): string {
$process = new Process($command, $root, timeout: $timeout);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('REPLENISHMENT_TASK_NATIVE_COMMAND_FAILED');
}
return $process->getOutput();
};
$scheduler = getenv('SystemRoot').'/System32/schtasks.exe';
$tasks = $run([$scheduler, '/Query', '/FO', 'CSV', '/NH']);
foreach (preg_split('/\r?\n/', trim($tasks)) as $row) {
$name = str_getcsv($row, escape: '')[0] ?? '';
if ($name === '\\'.$plan['task_name']) {
throw new LogicException('REPLENISHMENT_TASK_ALREADY_EXISTS_NEVER_OVERWRITE');
}
}
$health = json_decode(trim($run([PHP_BINARY, 'scripts/replenishment-pilot-task.php', '--check'])), true, 32, JSON_THROW_ON_ERROR);
if ($health['state'] !== 'ready' || $health['database_enforced_read_only'] !== true) {
throw new LogicException('REPLENISHMENT_TASK_PILOT_NOT_READY');
}
$identity = str_getcsv(trim($run([getenv('SystemRoot').'/System32/whoami.exe', '/user', '/fo', 'csv', '/nh'])), escape: '');
$sid = $identity[1] ?? '';
if (! preg_match('/^S-1-\d+(?:-\d+)+$/D', $sid)) {
throw new LogicException('REPLENISHMENT_TASK_CURRENT_USER_UNAVAILABLE');
}
$escape = static fn (string $value) => htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
$start = (new DateTimeImmutable('now', new DateTimeZone('Africa/Johannesburg')))->modify('+1 minute')->format('c');
$php = $escape($plan['php_executable']);
$arguments = $escape('"'.$root.'/scripts/replenishment-pilot-task.php" --once');
$directory = 'C:/laragon/data/compras/tasks/replenishment-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($directory, 0700, true)) {
throw new LogicException('REPLENISHMENT_TASK_PRIVATE_STORAGE');
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$settings = json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR);
if ($apply) {
// Private recovery material; no settings, credentials or business rows are published.
copy($settingsPath, $directory.'/settings.private.json');
$dump = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$directory.'/before.dump',
'--dbname='.$settings['DB_DATABASE']], $root, ['PGHOST' => $settings['DB_HOST'], 'PGPORT' => $settings['DB_PORT'],
'PGUSER' => $settings['DB_USERNAME'], 'PGPASSWORD' => $settings['DB_PASSWORD']], timeout: 120);
$dump->run();
if (! $dump->isSuccessful() || ! is_file($directory.'/before.dump')) {
throw new LogicException('REPLENISHMENT_PRIVATE_BACKUP_FAILED');
}
$connection = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$connection->beginTransaction();
$connection->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$baseline = [];
foreach ($connection->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
$rows = $connection->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$baseline[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
}
$connection->commit();
file_put_contents($directory.'/baseline.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
}
$working = $escape($root);
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.
'<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'.
'<RegistrationInfo><Description>Compras pilot: native replenishment under existing approved policies only.</Description></RegistrationInfo>'.
'<Triggers><TimeTrigger><StartBoundary>'.$start.'</StartBoundary><Enabled>true</Enabled><Repetition><Interval>PT1M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger>'.
'<LogonTrigger><Enabled>true</Enabled><UserId>'.$sid.'</UserId></LogonTrigger></Triggers>'.
'<Principals><Principal id="CurrentUser"><UserId>'.$sid.'</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>'.
'<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>true</StartWhenAvailable><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT1M</ExecutionTimeLimit></Settings>'.
'<Actions Context="CurrentUser"><Exec><Command>'.$php.'</Command><Arguments>'.$arguments.'</Arguments><WorkingDirectory>'.$working.'</WorkingDirectory></Exec></Actions></Task>';
$document = WindowsTaskXml::parse($xml);
$xpath = new DOMXPath($document);
$xpath->registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
if ($xpath->query('//t:Exec')->length !== 1 || $xpath->evaluate('string(//t:LogonType)') !== 'InteractiveToken'
|| $xpath->evaluate('string(//t:RunLevel)') !== 'LeastPrivilege' || $xpath->query('//t:Triggers/*')->length !== 2) {
throw new LogicException('REPLENISHMENT_TASK_XML_SCOPE');
}
$xmlPath = $directory.'/task.private.xml';
$fileBytes = WindowsTaskXml::encode($xml);
file_put_contents($xmlPath, $fileBytes);
$record = ['date' => gmdate('c'), 'state' => 'preview', 'task_name' => $plan['task_name'], 'current_user_only' => true,
'credentials_stored' => false, 'run_level' => 'Limited', 'poll_interval' => 'PT1M', 'overlap' => 'IgnoreNew', 'time_limit' => 'PT1M',
'private_definition' => $xmlPath, 'xml_sha256' => hash('sha256', $fileBytes), 'pilot_ready' => true,
'eligible_requests' => $health['health']['work']['pending'], 'native_command' => $plan['command'],
'task_installed_or_started' => false, 'powershell_execution_policy_changed' => false];
if ($apply) {
$record['private_backup_directory'] = $directory;
$record['database_backup_sha256'] = hash_file('sha256', $directory.'/before.dump');
$record['baseline_tables'] = count($baseline);
}
if (! $apply) {
file_put_contents($root.'/docs/proofs/replenishment-task-preflight.json', json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
$approvalPath = $root.'/docs/proofs/replenishment-task-authorization.json';
$approval = is_file($approvalPath) ? json_decode(file_get_contents($approvalPath), true, 32, JSON_THROW_ON_ERROR) : [];
if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== $plan['scope']
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))) {
throw new LogicException('REPLENISHMENT_TASK_NOT_AUTHORIZED');
}
$resultPath = $root.'/docs/proofs/replenishment-task-installation.json';
if (is_file($resultPath)) {
throw new LogicException('REPLENISHMENT_TASK_PREVIOUS_RESULT');
}
$run([$scheduler, '/Create', '/TN', $plan['task_name'], '/XML', $xmlPath]); // No /F: never replace another task.
$installed = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
file_put_contents($directory.'/installed.private.xml', $installed);
ReplenishmentTaskDefinition::assertMatches($xml, $installed);
$record['state'] = 'installed';
$record['task_installed_or_started'] = true;
file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
$run([$scheduler, '/Run', '/TN', $plan['task_name']]);
$record['initial_pass_requested'] = true;
$record['state'] = 'awaiting_passage_verification';
file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
+14 -23
View File
@@ -1,23 +1,14 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
await new Function('fs', 'assert', 'return (async()=>{' + common + `
const records=[];
for(const role of ['admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role);
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
assert.equal((await viewer.request('/ordens/cancelamentos','GET',undefined,false)).status,503);
const orders=await viewer.request('/ordens'); assert.equal(orders.status,200);
let checked=0;
for(const order of orders.page.props.orders.data.slice(0,1)) {
const detail=await viewer.request('/ordens/'+order.id); assert.equal(detail.status,200);
assert.equal(detail.page.props.orderCancellation.enabled,false);
assert.equal(detail.page.props.orderCancellation.canRequest,false);
assert.equal(detail.page.props.orderCancellationAvailable,false); checked++;
}
records.push({role,disabledStatus:503,ordersChecked:checked});
}
await fs.writeFile('docs/proofs/issued-order-cancellation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,policy_commands:false,cancellation_commands:false,visual_review:false},null,2));
console.log('Circuito desligado no piloto; ordens existentes consultadas sem comandos de cancelamento.');
` + '})()')(fs, assert);
// Compatibility entry point: no evaluation login or HTTP mutation is performed.
// Historical issued-order-cancellation-http.json is deliberately preserved.
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
if (process.argv.length !== 3 || process.argv[2] !== '--read-only') {
throw new Error('Use --read-only for in-process GET checks with existing pilot actors.');
}
const root = fileURLToPath(new URL('../', import.meta.url));
const result = spawnSync('php', ['scripts/check-standalone-pilot-profiles.php', '--read-only'], {
cwd: root, stdio: 'inherit', windowsHide: true,
});
if (result.error) throw result.error;
process.exitCode = result.status ?? 1;
+4 -39
View File
@@ -1,42 +1,7 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1' || realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $matches) || $settings['DB_USERNAME'] !== 'payable_qa_'.$matches[1]) {
throw new LogicException('Wrong pilot destination.');
// Compatibility entry point. Historical disabled-pilot evidence is preserved.
if (count($argv) !== 2 || $argv[1] !== '--installed-read-only') {
throw new LogicException('Use --installed-read-only for the installed cancellation component.');
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$base = DB::connection('pgsql')->getConfig();
unset($base['name']);
config(['database.connections.cancel_pilot_read' => [...$base, 'url' => null, 'host' => $settings['DB_HOST'], 'port' => $settings['DB_PORT'],
'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']]]);
$db = DB::connection('cancel_pilot_read');
$result = $db->transaction(function () use ($db, $settings) {
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity = $db->selectOne('select current_database() as db, current_user as role');
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
throw new LogicException('Identity mismatch.');
}
$schema = Schema::connection('cancel_pilot_read');
$installed = $schema->hasTable('order_cancellations');
return ['checked_at' => gmdate('c'), 'environment' => 'http://127.0.0.1:8005', 'result' => 'passed',
'schema_installed' => $installed, 'migration_applied' => $db->table('migrations')->where('migration', '2026_11_03_000003_create_order_cancellations')->exists(),
'cancellations' => $installed ? $db->table('order_cancellations')->count() : 0,
'policies' => $schema->hasTable('order_cancellation_policies') ? $db->table('order_cancellation_policies')->count() : 0,
'mfa_accounts_enrolled' => $db->table('users')->where(fn ($q) => $q->whereNotNull('two_factor_secret')->orWhereNotNull('two_factor_recovery_codes')->orWhereNotNull('two_factor_confirmed_at'))->count(),
'audit_permission_profiles' => $db->table('organization_profiles')->whereJsonContains('permissions', 'audit_metadata_read')->count(),
'access_version' => (int) $db->table('organization_access')->where('tenant_id', 1)->value('version'), 'business_commands' => false];
});
if ($result['schema_installed'] || $result['migration_applied'] || $result['cancellations'] || $result['policies'] || $result['mfa_accounts_enrolled'] || $result['audit_permission_profiles']) {
throw new LogicException('Pilot state differs from the authorized disabled scope.');
}
file_put_contents($root.'/docs/proofs/issued-order-cancellation-pilot.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
echo 'Pilot inspected read-only: circuit uninstalled and disabled; no policies, cancellations or MFA enrollments.'.PHP_EOL;
require __DIR__.'/check-order-cancellation-pilot.php';
+62
View File
@@ -0,0 +1,62 @@
<?php
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (count($argv) !== 2 || $argv[1] !== '--apply-authorized') {
throw new LogicException('Explicit authorized interface publication required.');
}
$planPath = $root.'/docs/proofs/analytics-print-publication-proposal.json';
$plan = json_decode(file_get_contents($planPath), true, 512, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/analytics-print-publication-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$resultPath = $root.'/docs/proofs/analytics-print-publication.json';
if ($approval['state'] !== 'approved' || $approval['scope'] !== $plan['scope']
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath)) || is_file($resultPath)
|| realpath($root) !== realpath('C:/laragon/www/compras')
|| $plan['candidate_root'] !== 'storage/framework/testing/sgc-analytics-print-qa-20261129') {
throw new LogicException('Interface publication scope or previous result differs.');
}
$candidate = $root.'/'.$plan['candidate_root'];
$manifestPath = $root.'/public/build/manifest.json';
if (! hash_equals($plan['previous_manifest_sha256'], hash_file('sha256', $manifestPath))
|| ! hash_equals($plan['manifest_sha256'], hash_file('sha256', $candidate.'/manifest.json'))) {
throw new LogicException('Reviewed interface manifest changed.');
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$protected = [$root.'/.env', $settingsPath, $root.'/public/build/fonts-manifest.json'];
$hashes = array_map(static fn ($file) => hash_file('sha256', $file), $protected);
foreach ($plan['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $candidate.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('Interface candidate missing or existing immutable asset differs.');
}
}
$backup = 'C:/laragon/data/compras/backups/analytics-print-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($backup, 0700, true) || ! copy($manifestPath, $backup.'/manifest.before.json')
|| ! hash_equals($plan['previous_manifest_sha256'], hash_file('sha256', $backup.'/manifest.before.json'))) {
throw new LogicException('Interface manifest recovery copy failed.');
}
foreach ($plan['files'] as $file => $hash) {
$target = $root.'/public/build/'.$file;
if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
throw new LogicException('Interface asset copy failed before manifest selection.');
}
if (! hash_equals($hash, hash_file('sha256', $target))) {
throw new LogicException('Published asset bytes differ.');
}
}
$temporary = $manifestPath.'.analytics-'.bin2hex(random_bytes(6)).'.tmp';
if (! copy($candidate.'/manifest.json', $temporary)
|| ! hash_equals($plan['manifest_sha256'], hash_file('sha256', $temporary))
|| ! hash_equals($plan['previous_manifest_sha256'], hash_file('sha256', $manifestPath))
|| ! rename($temporary, $manifestPath)) {
throw new LogicException('Atomic interface manifest selection failed.');
}
if ($hashes !== array_map(static fn ($file) => hash_file('sha256', $file), $protected)) {
throw new LogicException('Protected configuration changed; inspect without overwriting concurrent edits.');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'authorization' => 'analytics-print-publication-authorization.json',
'manifest_sha256' => $plan['manifest_sha256'], 'previous_manifest_sha256' => $plan['previous_manifest_sha256'],
'backup_directory' => $backup, 'assets_verified' => count($plan['files']), 'old_assets_preserved' => true,
'database_commands_or_settings_changes' => false, 'public_runtime_activation' => false, 'application_complete' => false];
file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+74
View File
@@ -0,0 +1,74 @@
<?php
use App\Services\DeadlineTaskGuiAction;
use App\Services\WindowsTaskXml;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (count($argv) !== 2 || ! in_array($argv[1], ['--preview', '--apply-authorized'], true)) {
throw new LogicException('Explicit silent task preview or application required.');
}
$planPath = $root.'/docs/proofs/approval-deadlines-task-proposal.json';
$plan = json_decode(file_get_contents($planPath), true, 32, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/approval-deadlines-task-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$current = json_decode(file_get_contents($root.'/docs/proofs/inventory-conversion-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if ($approval['state'] !== 'approved' || ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))
|| $current['state'] !== 'approved' || ! hash_equals($current['proposal_sha256'], hash_file('sha256', $root.'/'.$current['proposal']))
|| ! hash_equals($plan['file_sha256'][$plan['action_script']], hash_file('sha256', $root.'/'.$plan['action_script']))) {
throw new LogicException('Existing task and necessary activity components authorization required.');
}
$resultPath = $root.'/docs/proofs/approval-deadlines-task-gui-repair.json';
if (is_file($resultPath)) {
throw new LogicException('Preserve verified task correction; do not repeat.');
}
$old = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
$new = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php-win.exe';
if (! is_file($new) || $plan['php_executable'] !== $old || $plan['task_name'] !== 'Compras-Pilot-Approval-Deadlines') {
throw new LogicException('Reviewed same-installation GUI binary required.');
}
$run = static function (array $args) use ($root): string {
$process = new Process($args, $root, timeout: 30);
$process->mustRun();
return $process->getOutput();
};
$scheduler = getenv('SystemRoot').'/System32/schtasks.exe';
$before = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
$installation = json_decode(file_get_contents($root.'/docs/proofs/approval-deadlines-task-installation.json'), true, 32, JSON_THROW_ON_ERROR);
$original = file_get_contents($installation['private_definition']);
if (! hash_equals($installation['private_installed_xml_sha256'], hash('sha256', $original))
|| DeadlineTaskGuiAction::canonical($original) !== DeadlineTaskGuiAction::canonical($before)) {
throw new LogicException('Installed task differs from its original verified definition.');
}
DeadlineTaskGuiAction::replacement($before, $old, $new);
if ($argv[1] === '--preview') {
echo json_encode(['state' => 'preview', 'same_task_script_and_policy' => true, 'task_changed' => false], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
$directory = 'C:/laragon/data/compras/tasks/deadline-gui-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($directory, 0700, true) || file_put_contents($directory.'/before.private.xml', WindowsTaskXml::encode($before)) === false) {
throw new LogicException('Private original task backup required.');
}
// Native cmdlet changes the action only; no script file or execution-policy override.
$command = <<<'POWERSHELL'
$ErrorActionPreference='Stop'
$task=Get-ScheduledTask -TaskName 'Compras-Pilot-Approval-Deadlines' -TaskPath '\'
if($task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ne 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe'){throw 'Task action changed'}
$action=New-ScheduledTaskAction -Execute 'C:/Users/macbook/.config/investmoz/php-8.5.11/php-win.exe' -Argument $task.Actions[0].Arguments -WorkingDirectory $task.Actions[0].WorkingDirectory
Set-ScheduledTask -TaskName 'Compras-Pilot-Approval-Deadlines' -TaskPath '\' -Action $action | Out-Null
POWERSHELL;
$run([getenv('SystemRoot').'/System32/WindowsPowerShell/v1.0/powershell.exe', '-NoProfile', '-NonInteractive', '-Command', $command]);
$after = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
DeadlineTaskGuiAction::assertConserved($before, $after, $old, $new);
file_put_contents($directory.'/after.private.xml', WindowsTaskXml::encode($after));
$run([$scheduler, '/Run', '/TN', $plan['task_name']]);
$result = ['date' => gmdate('c'), 'state' => 'definition_verified_awaiting_passage', 'task_name' => $plan['task_name'],
'authority' => ['approval-deadlines-task-authorization.json', 'inventory-conversion-pilot-authorization.json'],
'private_backup' => $directory, 'old_executable' => $old, 'new_executable' => $new, 'gui_binary_sha256' => hash_file('sha256', $new),
'only_executable_changed' => true, 'helper_sha256' => hash_file('sha256', $root.'/'.$plan['action_script']),
'arguments_working_directory_triggers_principal_privileges_overlap_and_limit_preserved' => true,
'powershell_execution_policy_changed' => false, 'business_policy_or_grants_changed' => false,
'reference' => 'https://www.php.net/manual/en/features.commandline.php'];
file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+58
View File
@@ -0,0 +1,58 @@
<?php
use App\Services\ReplenishmentQueue;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (count($argv) !== 2 || ! in_array($argv[1], ['--check', '--once'], true)) {
throw new LogicException('Choose read-only preflight or authorized native passage.');
}
$check = $argv[1] === '--check';
$planPath = $root.'/docs/proofs/replenishment-task-proposal.json';
$plan = json_decode(file_get_contents($planPath), true, 32, JSON_THROW_ON_ERROR);
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if ($settings['APP_ENV'] !== 'payable-testing' || $settings['DB_HOST'] !== '127.0.0.1' || (string) $settings['DB_PORT'] !== '5432'
|| realpath($settings['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'], $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| ($settings['COMPRAS_RUNTIME_ENABLED'] ?? null) !== 'true'
|| $settings['COMPRAS_RUNTIME_INSTALLATION_ID'] !== $plan['installation_id']) {
throw new LogicException('Existing standalone pilot required.');
}
foreach ($plan['source_sha256'] as $file => $hash) {
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
throw new LogicException('Reviewed replenishment task source changed.');
}
}
if (! $check) {
$approval = json_decode(file_get_contents($root.'/docs/proofs/replenishment-task-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== 'existing_pilot_replenishment_task'
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))) {
throw new LogicException('Replenishment passage not authorized.');
}
}
foreach ([...$settings, 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => $check ? '-c default_transaction_read_only=on' : '',
'CACHE_STORE' => $check ? 'array' : ($settings['CACHE_STORE'] ?? 'file'), 'LOG_CHANNEL' => 'stderr'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
app(StandaloneRuntime::class)->assertLoadedPackages();
if (! app(ReplenishmentQueue::class)->ready()) {
throw new LogicException('Native replenishment capability unavailable.');
}
if ($check) {
if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('Read-only task preflight required.');
}
echo json_encode(['state' => 'ready', 'database_enforced_read_only' => true,
'health' => app(ReplenishmentQueue::class)->health(), 'task_started' => false], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
// The native command owns process exclusion, durable recovery and bound heartbeat.
exit(Artisan::call('sgc:replenishment-tick'));
+83 -3
View File
@@ -14,9 +14,13 @@ 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 standaloneBusiness = process.argv.includes('--standalone-business-only') || standaloneUpgrade;
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 !== (standaloneUpgrade ? '--standalone-upgrade-only' : '--standalone-business-only'))) throw Error('Standalone business regression 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';
@@ -132,6 +136,18 @@ try {
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');
@@ -180,6 +196,8 @@ try {
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;
@@ -234,13 +252,75 @@ try {
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', standaloneUpgrade ? 'tests/Feature/StandaloneComponentUpgradeTest.php' : 'tests/Feature/StandaloneBusinessCompositionTest.php');
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 },
+64
View File
@@ -0,0 +1,64 @@
// Synthetic loopback preview, normal application authentication, no installed login shortcut.
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';
export async function reviewStandaloneInventory({ workspace, root, database, environment, cancellation = false, analytics = false }) {
const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
const match = /^compras_receipts_test_([a-f0-9]{12})$/.exec(database);
if (!match || path.dirname(fs.realpathSync(root)) !== parent || path.basename(root) !== `rq01-ledger-qa-${match[1]}`
|| environment.DB_USERNAME !== `payable_history_native_${match[1]}` || environment.DB_HOST !== '127.0.0.1'
|| environment.DB_PORT !== '55439' || environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned inventory preview required');
if (cancellation) environment = { ...environment, COMPRAS_ORDER_CANCELLATION_ENABLED: 'true' };
const prepared = spawnSync('php', ['tests/Concurrency/unit-conversion-worker.php', database, analytics ? 'prepare-analytics-preview' : cancellation ? 'prepare-cancellation-preview' : 'prepare-preview'], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'testing' },
});
if (prepared.status !== 0) throw Error('Synthetic inventory preview fixture failed');
const fixture = JSON.parse(prepared.stdout);
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 assets = path.join(workspace, 'storage/framework/testing', analytics ? 'sgc-analytics-print-qa-20261129' : 'sgc-standalone-finance-help-qa-20261129');
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
if (crypto.createHash('sha256').update(manifest).digest('hex') !== (analytics ? 'c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022' : '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b')) throw Error('Pinned UI build required');
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
const verifyAnalytics = (mode) => {
const check = spawnSync('php', ['scripts/check-analytics-preview.php', root, mode], { cwd: workspace, windowsHide: true, encoding: 'utf8' });
if (check.status !== 0) throw Error('Synthetic analytical conservation failed');
return JSON.parse(check.stdout);
};
if (analytics) verifyAnalytics('--capture');
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
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}`;
const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-inventory-http-router.php'], {
cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
env: { ...environment, APP_URL: url, ASSET_URL: url, SGC_STANDALONE_QA_ROOT: root, SGC_STANDALONE_QA_PORT: String(port),
SESSION_DRIVER: 'file', SESSION_COOKIE: `sgc_inventory_qa_${match[1]}`, SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false',
SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({ [fixture.tenant_id]: ['procurement.internal'] }) },
});
try {
let ready = false;
for (let attempt = 0; attempt < 30 && !ready; attempt++) {
try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
}
if (!ready) throw Error('Inventory preview did not start');
const stop = path.join(root, 'stop-inventory-review');
console.log(JSON.stringify({ inventory_preview: !cancellation && !analytics, cancellation_preview: cancellation, analytics_preview: analytics, url, stop_file: stop, ...fixture, normal_authentication_required: true }));
const until = Date.now()+20*60*1000;
while (!fs.existsSync(stop) && Date.now() < until) {
if (server.exitCode !== null) throw Error('Inventory preview stopped unexpectedly');
await new Promise(resolve => setTimeout(resolve, 200));
}
if (analytics) console.log(JSON.stringify({ analytical_conservation: verifyAnalytics('--verify') }));
} finally {
if (server.exitCode === null) {
const closed = new Promise(resolve => server.once('exit', resolve));
server.kill(); await closed;
}
}
}
@@ -0,0 +1,70 @@
<?php
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
if (count($argv) !== 2 || $argv[1] !== '--restore-private-copy') {
throw new LogicException('Explicit private restore required.');
}
$root = dirname(__DIR__);
$record = json_decode(file_get_contents($root.'/docs/proofs/replenishment-task-installation.json'), true, 32, JSON_THROW_ON_ERROR);
$directory = str_replace('\\', '/', $record['private_backup_directory']);
if (! preg_match('~^C:/laragon/data/compras/tasks/replenishment-[0-9]{8}-[0-9]{6}-[a-f0-9]{12}$~D', $directory)
|| ! hash_equals($record['database_backup_sha256'], hash_file('sha256', $directory.'/before.dump'))) {
throw new LogicException('Owned backup required.');
}
$source = json_decode(file_get_contents($directory.'/settings.private.json'), true, 32, JSON_THROW_ON_ERROR);
$settings = Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
if ($settings['DB_CONNECTION'] !== 'pgsql' || $settings['DB_HOST'] !== '127.0.0.1' || $source['DB_HOST'] !== '127.0.0.1'
|| $settings['DB_PORT'] !== $source['DB_PORT'] || $source['APP_ENV'] !== 'payable-testing'
|| realpath($source['HOST_ROOT']) !== realpath($root)) {
throw new LogicException('Own local recovery cluster required.');
}
$connect = static fn (string $database, string $user, string $password) => new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$database,
$user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$admin = $connect('postgres', $settings['DB_USERNAME'], $settings['DB_PASSWORD']);
$id = bin2hex(random_bytes(6));
$role = 'compras_replenish_app_'.$id;
$database = 'compras_replenish_restore_'.$id;
$password = bin2hex(random_bytes(32));
$createdRole = $createdDatabase = false;
$copy = null;
try {
$admin->exec('CREATE ROLE "'.$role.'" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD '.$admin->quote($password));
$createdRole = true;
$admin->exec('CREATE DATABASE "'.$database.'" OWNER "'.$role.'"');
$createdDatabase = true;
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--no-owner', '--no-acl', '--exit-on-error',
'--dbname='.$database, $directory.'/before.dump'], $root, ['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'],
'PGUSER' => $role, 'PGPASSWORD' => $password], timeout: 120);
$process->run();
if (! $process->isSuccessful()) {
throw new LogicException('Private replenishment backup restore failed.');
}
$copy = $connect($database, $role, $password);
$copy->exec('SET default_transaction_read_only=on');
$baseline = json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR);
$tables = $copy->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN);
if ($tables !== array_keys($baseline)) {
throw new LogicException('Restored table inventory differs.');
}
foreach ($baseline as $table => $before) {
$rows = $copy->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
if (count($rows) !== $before['rows'] || ! hash_equals($before['sha256'], hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)))) {
throw new LogicException('Restored replenishment backup data differs.');
}
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'restored_tables_identical' => count($baseline),
'source_database_or_settings_changed' => false, 'business_commands' => false];
} finally {
$copy = null;
if ($createdDatabase) {
$admin->exec('DROP DATABASE "'.$database.'" WITH (FORCE)');
}
if ($createdRole) {
$admin->exec('DROP ROLE "'.$role.'"');
}
}
$result['temporary_database_and_role_removed'] = true;
file_put_contents($root.'/docs/proofs/replenishment-task-recovery.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;