$hash) { if (hash_file('sha256', $root.'/'.$file) !== $hash) { throw new LogicException('Reviewed installation file changed:'.$file); } } } $settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'; $settingsBytes = file_get_contents($settingsPath); $settings = json_decode($settingsBytes, 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'] ?? '', $match) || $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1] || filter_var($settings['SGC_BUDGET_DISTRIBUTIONS_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN)) { throw new LogicException('Original named pilot with distributions disabled required.'); } $artifactPath = $root.'/docs/proofs/rq01-distribution-artifact.json'; $artifact = json_decode(file_get_contents($artifactPath), true, 32, JSON_THROW_ON_ERROR); BudgetDistributionArtifact::verify($root.'/'.$artifact['path'], $artifactPath, hash_file('sha256', $artifactPath)); $app = require $root.'/bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); $owner = DB::connection('pgsql')->getConfig(); unset($owner['name']); if ($owner['host'] !== '127.0.0.1') { throw new LogicException('Local administrative connection required.'); } $pilotConfig = [...$owner, 'url' => null, 'host' => $settings['DB_HOST'], 'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']]; config(['database.connections.distribution_pilot_read' => $pilotConfig, 'database.connections.distribution_prepare_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]); $pilot = DB::connection('distribution_pilot_read'); $admin = DB::connection('distribution_prepare_owner'); $restoreName = 'compras_distribution_restore_'.bin2hex(random_bytes(6)); $directory = 'C:/laragon/data/sgf-tempo/backups/compras-distribution-preparation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3)); if (! mkdir($directory, 0700, true)) { throw new RuntimeException('Could not create private recovery directory.'); } $dump = $directory.'/before.dump'; $originalManifest = hash_file('sha256', $root.'/public/build/manifest.json'); if ($apply && $originalManifest !== $proposal['previous_manifest_sha256']) { throw new LogicException('Pilot assets changed after the reviewed proposal.'); } $previous = DB::getDefaultConnection(); $created = false; $fingerprint = static function ($connection, array $columns): array { $out = []; foreach ($columns as $table => $names) { $selected = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names)); $rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text'); $out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR)); } return $out; }; $pg = static function (string $binary, array $arguments) use ($pilotConfig): void { $process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null, ['PGHOST' => $pilotConfig['host'], 'PGPORT' => (string) $pilotConfig['port'], 'PGUSER' => $pilotConfig['username'], 'PGPASSWORD' => $pilotConfig['password']], timeout: 120); $process->run(); if (! $process->isSuccessful()) { throw new RuntimeException('Private backup or restore failed; pilot untouched.'); } }; try { $pilot->beginTransaction(); $pilot->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); $identity = $pilot->selectOne('select current_database() as db, current_user as role'); if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) { throw new LogicException('Effective pilot identity mismatch.'); } $schema = $pilot->getSchemaBuilder(); if ($schema->hasTable('budget_distributions') || $schema->hasColumn('requisitions', 'budget_distribution_preparation')) { throw new LogicException('Optional schema already exists; inspect without reapplying.'); } $tables = array_column($pilot->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename'); $columns = $keys = []; foreach ($tables as $table) { $columns[$table] = $schema->getColumnListing($table); $keys[$table] = $schema->getForeignKeys($table); } $baseline = $fingerprint($pilot, $columns); $migrationCount = $pilot->table('migrations')->count(); $snapshot = $pilot->selectOne('select pg_export_snapshot() as snapshot')->snapshot; $pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$pilotConfig['database']]); $pilot->commit(); $admin->statement('CREATE DATABASE "'.$restoreName.'" OWNER "'.$settings['DB_USERNAME'].'"'); $created = true; $pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restoreName, $dump]); config(['database.connections.distribution_rehearsal' => [...$pilotConfig, 'database' => $restoreName]]); $restored = DB::connection('distribution_rehearsal'); if ($fingerprint($restored, $columns) !== $baseline) { throw new LogicException('Same-role restore differs from original snapshot.'); } DB::setDefaultConnection('distribution_rehearsal'); config(['budget-distributions.schema_installation' => ['database' => $restoreName, 'username' => $settings['DB_USERNAME']]]); $migration = 'database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php'; if (Artisan::call('migrate', ['--database' => 'distribution_rehearsal', '--path' => [$migration], '--force' => true]) !== 0) { throw new RuntimeException('Exact restored migration failed.'); } $after = $fingerprint($restored, $columns); unset($after['migrations'], $baseline['migrations']); if ($after !== $baseline || $restored->table('migrations')->count() !== $migrationCount + 1 || $restored->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) { throw new LogicException('Previous records changed or new values are not empty.'); } foreach ($keys as $table => $expected) { if ($restored->getSchemaBuilder()->getForeignKeys($table) !== $expected) { throw new LogicException('Previous foreign keys changed.'); } } foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) { if ($restored->table($table)->exists()) { throw new LogicException('Optional schema must remain empty.'); } } if (hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes) || hash_file('sha256', $root.'/public/build/manifest.json') !== $originalManifest) { throw new LogicException('Deployment changed during preparation; reassess the destination.'); } $proof = ['date' => gmdate('Y-m-d'), 'status' => 'restored_pilot_rehearsal_passed_not_installed', 'environment' => 'http://127.0.0.1:8005', 'pilot_read_only' => true, 'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'same_restore_role' => true, 'restored_tables_checked' => count($tables), 'previous_business_tables_preserved' => count($tables) - 1, 'previous_foreign_keys_preserved' => true, 'new_values_empty' => true, 'optional_tables' => 4, 'deployment_settings_unchanged' => true, 'pilot_manifest_sha256' => $originalManifest, 'migration' => $migration, 'migration_sha256' => hash_file('sha256', $root.'/'.$migration), 'schema_definition_sha256' => hash_file('sha256', $root.'/app/Services/BudgetDistributionSchema.php'), 'artifact_manifest_sha256' => hash_file('sha256', $artifactPath), 'pilot_schema_or_activation_changed' => false]; if ($apply) { // Preserve deployment state before copying immutable, separately selected release files. if (file_put_contents($directory.'/settings.before.json', $settingsBytes) !== strlen($settingsBytes) || ! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) { throw new RuntimeException('Could not preserve deployment state.'); } $release = $root.'/'.$proposal['release_path']; if (! is_dir($release.'/src') && ! mkdir($release.'/src', 0700, true)) { throw new RuntimeException('Could not create the private release directory.'); } foreach ($artifact['files'] as $file => $hash) { if (is_file($release.'/'.$file) && hash_file('sha256', $release.'/'.$file) !== $hash) { throw new LogicException('Existing release differs; it was not overwritten.'); } if (! is_file($release.'/'.$file)) { copy($root.'/'.$artifact['path'].'/'.$file, $release.'/'.$file); } } $releaseManifest = $release.'/artifact-manifest.json'; if (is_file($releaseManifest) && hash_file('sha256', $releaseManifest) !== hash_file('sha256', $artifactPath)) { throw new LogicException('Existing release manifest differs.'); } if (! is_file($releaseManifest)) { copy($artifactPath, $releaseManifest); } BudgetDistributionArtifact::verify($release, $releaseManifest, $proposal['artifact_manifest_sha256']); foreach ($proposal['assets'] as $file => $hash) { $target = $root.'/public/build/'.$file; if (! preg_match('~^assets/[A-Za-z0-9_.-]+$~D', $file) || hash_file('sha256', $root.'/'.$proposal['candidate_path'].'/'.$file) !== $hash || (is_file($target) && hash_file('sha256', $target) !== $hash)) { throw new LogicException('Candidate asset changed or collides with an existing asset.'); } if (! is_file($target)) { copy($root.'/'.$proposal['candidate_path'].'/'.$file, $target); } if (hash_file('sha256', $target) !== $hash) { throw new RuntimeException('Copied asset verification failed.'); } } DB::setDefaultConnection('distribution_pilot_read'); config(['budget-distributions.schema_installation' => ['database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME']]]); $pilot->transaction(function () use ($pilot, $tables, $fingerprint, $columns, $keys, $baseline, $migration, $migrationCount, $settingsPath, $settingsBytes): void { $pilot->statement("SET LOCAL lock_timeout = '5s'"); foreach ($tables as $table) { $pilot->statement('LOCK TABLE "'.$table.'" IN SHARE MODE'); } $current = $fingerprint($pilot, $columns); unset($current['migrations']); if ($current !== $baseline || hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) { throw new LogicException('Pilot changed after backup; installation refused.'); } foreach ($keys as $table => $expected) { if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) { throw new LogicException('Pilot foreign keys changed after backup.'); } } if (Artisan::call('migrate', ['--database' => 'distribution_pilot_read', '--path' => [$migration], '--force' => true]) !== 0 || $pilot->table('migrations')->count() !== $migrationCount + 1) { throw new RuntimeException('Exact pilot migration failed.'); } $after = $fingerprint($pilot, $columns); unset($after['migrations']); if ($after !== $baseline || $pilot->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) { throw new LogicException('Previous data changed; installation rolled back.'); } foreach ($keys as $table => $expected) { if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) { throw new LogicException('Previous foreign keys changed; installation rolled back.'); } } }); $proof['status'] = 'schema_installed_activation_pending'; $proof['pilot_read_only'] = false; $proof['pilot_schema_or_activation_changed'] = true; file_put_contents($installationProof, json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL); // All copied chunks are verified before the manifest is atomically switched. $manifestBytes = file_get_contents($root.'/'.$proposal['candidate_path'].'/manifest.json'); if (hash('sha256', $manifestBytes) !== $proposal['candidate_manifest_sha256'] || hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) { throw new LogicException('Activation inputs changed; new empty schema retained, activation refused.'); } $nextSettings = [...$settings, 'COMMON_BUDGET_PATH' => str_replace('\\', '/', $release), 'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => str_replace('\\', '/', $releaseManifest), 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => $proposal['artifact_manifest_sha256']]; $settingsNextBytes = json_encode($nextSettings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL; $manifestNext = $root.'/public/build/manifest.distribution-next.json'; $settingsNext = $settingsPath.'.distribution-next'; if (file_put_contents($manifestNext, $manifestBytes) !== strlen($manifestBytes) || file_put_contents($settingsNext, $settingsNextBytes) !== strlen($settingsNextBytes) || ! rename($manifestNext, $root.'/public/build/manifest.json')) { throw new RuntimeException('Could not switch reviewed assets; deployment state preserved in backup.'); } if (! rename($settingsNext, $settingsPath)) { copy($directory.'/manifest.before.json', $root.'/public/build/manifest.json'); throw new RuntimeException('Capability switch failed; previous assets restored, schema retained.'); } $proof['status'] = 'installed_and_capability_enabled_no_business_operations'; $proof['pilot_read_only'] = false; $proof['deployment_settings_unchanged'] = false; $proof['unrelated_deployment_settings_preserved'] = true; $proof['manifest_sha256'] = hash_file('sha256', $root.'/public/build/manifest.json'); $proof['release_path'] = $proposal['release_path']; $proof['business_operations'] = false; $proof['grants_changed'] = false; $proof['pinned_packages_changed'] = false; } } finally { if ($pilot->transactionLevel() > 0) { $pilot->rollBack(); } DB::setDefaultConnection($previous); config(['budget-distributions.schema_installation' => null]); DB::purge('distribution_rehearsal'); if ($created) { $admin->statement('DROP DATABASE "'.$restoreName.'" WITH (FORCE)'); } } $proof['restored_database_removed'] = true; file_put_contents($apply ? $installationProof : $root.'/docs/proofs/rq01-distribution-pilot-preparation.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL); echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;