$path && $base && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $base)).'/'); if (! $host || ! $inside($review, realpath($host.'/storage/framework/testing/merchandise-invoices-20261130/review')) || ! $inside($compat, realpath($root.'/storage/app/private/candidates')) || ! preg_match('/^[a-f0-9]{40}$/D', $commit) || ! preg_match('/^[a-f0-9]{64}$/D', $reviewHash) || ! preg_match('/^[a-f0-9]{64}$/D', $compatHash)) { throw new LogicException('Explicit private sources and baseline required.'); } $git = function (array $arguments) use ($host): array { $process = proc_open(['git', '-C', $host, ...$arguments], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); if (! is_resource($process)) { throw new RuntimeException('Cannot read Git baseline.'); } fclose($pipes[0]); $out = stream_get_contents($pipes[1]); $error = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); return [proc_close($process), $out, $error]; }; [$status, $resolved] = $git(['rev-parse', $commit.'^{commit}']); if ($status !== 0 || trim($resolved) !== $commit) { throw new LogicException('Baseline commit does not exist.'); } $blob = function (string $path) use ($git, $commit): ?string { [$status, $text] = $git(['cat-file', 'blob', $commit.':'.$path]); if ($status === 128) { return null; } if ($status !== 0) { throw new RuntimeException('Cannot resolve baseline file: '.$path); } return $text; }; $read = function (string $directory, string $hash): array { $text = file_get_contents($directory.'/manifest.json'); if (! hash_equals($hash, hash('sha256', $text))) { throw new LogicException('Source manifest changed.'); } return json_decode($text, true, 64, JSON_THROW_ON_ERROR); }; $reviewManifest = $read($review, $reviewHash); $compatManifest = $read($compat, $compatHash); if ($reviewManifest['format'] !== 'tempo.integration-review.v1' || $reviewManifest['installable'] !== false || $compatManifest['format'] !== 'tempo.operational-review.v1') { throw new LogicException('Unexpected preparation source.'); } (new ReflectionMethod(CodeDeployment::class, 'manifest'))->invoke(new CodeDeployment($host), $compat, $compatHash); $bodies = []; $runtime = []; foreach ($compatManifest['support_files'] as $file => $hash) { $bodies[$file] = file_get_contents($compat.'/'.$file); } if (! isset($bodies['integrations/sgf/operational/CodeDeployment.php']) || ! hash_equals(hash('sha256', $bodies['integrations/sgf/operational/CodeDeployment.php']), hash_file('sha256', $root.'/integrations/sgf/operational/CodeDeployment.php'))) { throw new LogicException('Refresh compatibility preparation with the tested deployment contract.'); } foreach ($reviewManifest['files'] as $file => $hash) { if (str_contains($file, '..') || ! preg_match('~^[A-Za-z0-9_./-]+$~D', $file) || is_link($review.'/'.$file) || ! $inside(realpath($review.'/'.$file), $review) || ! hash_equals($hash, hash_file('sha256', $review.'/'.$file))) { throw new LogicException('Review source changed.'); } $body = file_get_contents($review.'/'.$file); if (str_starts_with($file, 'sgf/')) { $runtime[substr($file, 4)] = $body; } elseif (str_starts_with($file, 'shared/general-ledger/')) { $runtime['packages/general-ledger/'.substr($file, strlen('shared/general-ledger/'))] = $body; } elseif (str_starts_with($file, 'shared/purchasing/src/')) { $destination = 'packages/purchasing/src/'.substr($file, strlen('shared/purchasing/src/')); if (! isset($bodies[$destination]) || ! hash_equals(hash('sha256', $body), hash('sha256', $bodies[$destination]))) { throw new LogicException('Common calculation sources disagree.'); } } } // The compiled frontend may contain only the baseline plus explicitly reviewed changes. foreach (['diff', 'ls-files'] as $mode) { $arguments = $mode === 'diff' ? ['diff', '--name-only', $commit, '--', 'resources', 'package.json', 'vite.config.js'] : ['ls-files', '--others', '--exclude-standard', '--', 'resources']; [$status, $paths] = $git($arguments); if ($status !== 0) { throw new RuntimeException('Cannot freeze frontend sources.'); } foreach (array_filter(explode("\n", trim($paths))) as $file) { if (! isset($runtime[$file]) || ! hash_equals(hash('sha256', $runtime[$file]), hash_file('sha256', $host.'/'.$file))) { throw new LogicException('Unreviewed frontend change: '.$file); } } } $overlays = []; $beforeBodies = []; $developmentBuild = []; foreach ($runtime as $file => $body) { if (! isset($compatManifest['host_overlays'][$file])) { $bodies[$file] = $body; } elseif ($compatManifest['host_overlays'][$file]['before_sha256'] !== hash('sha256', $body)) { throw new LogicException('Merged overlay used another source: '.$file); } } foreach (array_unique([...array_keys($runtime), ...array_keys($compatManifest['host_overlays'])]) as $file) { $before = $blob($file); if ($file === 'public/build/manifest.json' && $before === null) { $before = file_get_contents($host.'/'.$file); $developmentBuild[$file] = hash('sha256', $before); } if (isset($compatManifest['host_overlays'][$file]) && ! isset($runtime[$file])) { $checkout = file_get_contents($host.'/'.$file); if ($before === null || hash('sha256', $checkout) !== $compatManifest['host_overlays'][$file]['before_sha256'] || str_replace("\r\n", "\n", $before) !== str_replace("\r\n", "\n", $checkout)) { throw new LogicException('Compatibility overlay contains an unreviewed baseline change: '.$file); } } $beforeBodies[$file] = $before; $overlays[$file] = ['before_sha256' => $before === null ? null : hash('sha256', $before), 'after_sha256' => hash('sha256', $bodies[$file])]; } $bodies['scripts/merchandise-delivery-metadata.json'] = json_encode(['baseline_git_commit' => $commit, 'baseline_bytes' => 'canonical_git_blobs_and_explicit_development_build_manifest', 'development_build_baseline' => $developmentBuild, 'operational_destination_verified' => false, 'source_review_manifest_sha256' => $reviewHash, 'source_compatibility_manifest_sha256' => $compatHash, 'installed' => false, 'activated' => false, 'schema_installed' => false, 'core_pointer_preserved' => '0.1.1', 'operational_schema_receipt_required' => true], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); ksort($bodies); ksort($overlays); $files = array_map(fn ($body) => hash('sha256', $body), $bodies); $added = []; $schema = []; foreach ($overlays as $file => $entry) { $added[$file] = $entry['before_sha256']; } foreach ($files as $file => $hash) { if (str_starts_with($file, 'database/') || preg_match('~Schema\.php$~D', $file) || in_array($file, ['integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json'], true)) { $schema[$file] = ['before' => null, 'after' => $hash]; } } $manifest = ['format' => 'tempo.operational-review.v2', 'support_files' => $files, 'host_overlays' => $overlays, 'composition_transition' => ['from_manifest_sha256' => null, 'added_files' => $added, 'schema_files' => $schema]]; $manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n"; $hash = hash('sha256', $manifestText); $directory = $root.'/storage/app/private/candidates/MERCHANDISE-V2-'.substr($hash, 0, 16); $write = function (string $path, string $body): void { if (is_file($path) && ! hash_equals(hash('sha256', $body), hash_file('sha256', $path))) { throw new LogicException('Preserve immutable preparation.'); } if (! is_dir(dirname($path))) { mkdir(dirname($path), 0700, true); } if (! is_file($path) && file_put_contents($path, $body) !== strlen($body)) { throw new RuntimeException('Incomplete file.'); } }; foreach ($bodies + ['manifest.json' => $manifestText] as $file => $body) { $write($directory.'/'.$file, $body); } // File-only recovery rehearsal. This synthetic receipt is never included in the candidate. $copy = $root.'/storage/framework/testing/merchandise-v2-'.bin2hex(random_bytes(6)); foreach ($beforeBodies as $file => $body) { if ($body !== null) { $write($copy.'/'.$file, $body); } } $pointer = file_get_contents($host.'/packages/purchasing/current.json'); if (json_decode($pointer, true, 16, JSON_THROW_ON_ERROR)['version'] !== '0.1.1') { throw new LogicException('Preserve the known module version.'); } $write($copy.'/packages/purchasing/current.json', $pointer); $write($copy.'/storage/framework/down', '{}'); if (! is_dir($copy.'/bootstrap/cache')) { mkdir($copy.'/bootstrap/cache', 0700, true); } $copy = str_replace('\\', '/', realpath($copy)); $receipt = ['from_manifest_sha256' => null, 'to_manifest_sha256' => $hash, 'host' => $copy, 'schema_verified' => true, 'changes' => $schema, 'synthetic_code_only_test' => true]; $write($copy.'/storage/app/private/module-deployments/schema-transition-'.$hash.'.json', json_encode($receipt, JSON_THROW_ON_ERROR)); $deploy = new CodeDeployment($copy); $plan = $deploy->plan($directory, $hash); $result = $deploy->apply($directory, $hash, $plan['target_sha256'], 'Synthetic file-copy rehearsal', true); $checks = 0; foreach ($overlays as $file => $entry) { if (hash_file('sha256', $copy.'/'.$file) !== $entry['after_sha256']) { throw new LogicException('Applied bytes differ.'); } $checks++; } if (! $deploy->apply($directory, $hash, $plan['target_sha256'], 'Synthetic replay', true)['replayed']) { throw new LogicException('Replay failed.'); } $checks++; $deploy->rollback($result['deployment_id'], 'Synthetic file recovery', true); foreach ($overlays as $file => $entry) { $actual = is_file($copy.'/'.$file) ? hash_file('sha256', $copy.'/'.$file) : null; if ($actual !== $entry['before_sha256']) { throw new LogicException('Original bytes or absence not restored.'); } $checks++; } if (file_get_contents($host.'/packages/purchasing/current.json') !== $pointer || file_get_contents($copy.'/packages/purchasing/current.json') !== $pointer) { throw new LogicException('Module pointer changed.'); } $checks++; $runPhp = function (string $script): string { $process = proc_open([PHP_BINARY, '-r', $script], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); if (! is_resource($process)) { throw new RuntimeException('Cannot qualify the delivered code.'); } fclose($pipes[0]); $out = stream_get_contents($pipes[1]); $error = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); if (proc_close($process) !== 0) { throw new RuntimeException('Delivered code qualification failed: '.$error); } return $out; }; $script = 'require '.var_export($directory.'/integrations/sgf/operational/CodeDeployment.php', true).';' .'$deploy=new Tempo\\Purchasing\\Delivery\\CodeDeployment('.var_export($copy, true).');' .'$plan=$deploy->plan('.var_export($directory, true).','.var_export($hash, true).'); echo json_encode($plan["writes"]);'; if ($runPhp($script) !== 'false') { throw new LogicException('Bundled updater does not accept its own candidate.'); } $checks++; $script = 'require '.var_export($host.'/vendor/autoload.php', true).';' .'Illuminate\\Container\\Container::getInstance()->instance("config",new Illuminate\\Config\\Repository(["merchandise_invoices"=>["costs_enabled"=>true],"purchasing-internal"=>["candidate_enabled"=>false]]));' .'require '.var_export($directory.'/bootstrap.php', true).';' .'if(config("purchasing-internal.candidate_enabled")!==false)throw new RuntimeException("Code activated requisitions");' .'$result=Tempo\\Purchasing\\Inventory\\StockCosting::project("fifo",["reference"=>"synthetic-opening","quantity_milli"=>3000,"value_minor"=>100,"layers"=>[["quantity_milli"=>3000,"value_minor"=>100]]],' .'[["id"=>1,"reference"=>"synthetic-issue","kind"=>"issue","quantity_milli"=>1000],["id"=>2,"reference"=>"synthetic-final","kind"=>"issue","quantity_milli"=>2000]],"half_up_final_balance");' .'if($result["movements"][0]["value"]["amount_minor"]!=="33"||$result["movements"][1]["value"]["amount_minor"]!=="67")throw new RuntimeException("Calculation mismatch");echo "BOOT_AND_COST_OK";'; if ($runPhp($script) !== 'BOOT_AND_COST_OK') { throw new LogicException('Incomplete candidate bootstrap.'); } $checks++; $archive = $root.'/storage/app/private/candidate-archives/'.basename($directory).'.zip'; $zip = new ZipArchive; if (! is_file($archive)) { $temporary = $archive.'.'.bin2hex(random_bytes(4)).'.next'; if ($zip->open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) !== true) { throw new RuntimeException('Cannot prepare archive.'); } foreach (array_keys($bodies + ['manifest.json' => $manifestText]) as $file) { $zip->addFile($directory.'/'.$file, $file); $zip->setMtimeName($file, 946684800); } if (! $zip->close() || ! rename($temporary, $archive)) { throw new RuntimeException('Cannot finish archive.'); } } if ($zip->open($archive, ZipArchive::RDONLY) !== true || $zip->numFiles !== count($bodies) + 1) { throw new LogicException('Unexpected archive.'); } foreach ($bodies + ['manifest.json' => $manifestText] as $file => $body) { if (! hash_equals(hash('sha256', $body), hash('sha256', $zip->getFromName($file)))) { throw new LogicException('Archive bytes differ.'); } } $zip->close(); $proof = ['passed' => true, 'checks' => $checks, 'candidate' => basename($directory), 'manifest_sha256' => $hash, 'archive_sha256' => hash_file('sha256', $archive), 'bundled_updater_qualified' => true, 'bundled_bootstrap_and_cost_qualified' => true, 'bootstrap_did_not_enable_requisitions' => true, 'baseline_git_commit' => $commit, 'code_copy' => $copy, 'schema_or_data_recovery_qualified' => false, 'synthetic_schema_receipt_only' => true, 'database_connected' => false, 'destination_installed' => false, 'pointer_preserved' => '0.1.1', 'published' => false]; $write($copy.'/recovery-result.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)); echo json_encode(['directory' => $directory, 'archive' => $archive, 'manifest_sha256' => $hash, 'archive_sha256' => $proof['archive_sha256'], 'files' => count($files), 'host_overlays' => count($overlays), 'schema_sources_requiring_receipt' => count($schema), 'checks' => $checks, 'proof' => $copy.'/recovery-result.json', 'installed' => false], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";