<?php

declare(strict_types=1);

// Five Stageanalyze PC reads. Formal HTTP/actor DML is default-denied.
$requestedMode = (string)($argv[1] ?? '');
$requestedLane = (string)getenv('CDX_NEXT5_LANE');
if (!in_array($requestedMode, ['--preflight', '--execute'], true)
    || !in_array($requestedLane, ['A', 'B', 'C'], true)
    || ($requestedMode === '--execute'
        && ((string)getenv('CDX_TEAM5_EXECUTE') !== 'ROOT_APPROVED_TEAM5_V1'
            || (string)getenv('CDX_TEAM5_RUNNER_SHA') !== hash_file('sha256', __FILE__)))) {
    fwrite(STDERR, "TEAM5 formal HTTP and DML disabled\n");
    exit(78);
}
$preflight = $requestedLane === 'C'
    ? '/tmp/zhct-team5-readonly-20261004/preflight_team5.php'
    : '/workspace/zhct/zhctprompt/work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-store-team-monitor-read5/preflight_team5.php';
if (!is_file($preflight) || is_link($preflight)
    || hash_file('sha256', $preflight)
        !== '8de63a11b20a4d19ee39139180051e5bc90fcfbf6dfcad9fe4399e5052614444') {
    throw new RuntimeException('Frozen team5 preflight drift');
}
$argv[1] = '--preflight';
require $preflight;
$mode = $requestedMode; // Required: include preflight assigns its own mode.
$argv[1] = $requestedMode;
if ($mode === '--execute'
    && ((string)getenv('CDX_TEAM5_DB_SHA') !== $approvedDbSha
        || ($dialect === 'dm' && (string)getenv('CDX_TEAM5_HOST_SHA')
            !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9'))) {
    throw new RuntimeException('Explicit team5 target approval absent');
}
$authSources = [
    'application/p/logic/Login.php' => 'd56c1c6f8e99e6819fa7695ef9397e8d2e33e62e6ee0278fb4cbfe7d1fdabba0',
    'application/base/Security.php' => 'b82e5ed982e6084a2b2942c033d4767428fb6f1012ba628f609477a7563eb4c3',
    'application/base/AdminController.php' => '7565b36fa4dda2c21cc4fa3b37753dbffb7c3a464bb8c11ea0f17ca00bececa5',
    'application/model/Department.php' => $lane === 'A'
        ? 'a0910fe7209b7da3e6a43a1697ea7a049bbd6e94d2c08225cdefe90f368efce8'
        : '9cd5a91f10f238d932d062e1fe8fae74208496b65d639314c545ecec49cc0e1f',
    'application/model/StaffDepartment.php' => 'c450c5b72f6e5f1a9f0c0736922b1ccdc1f160b9637970857cf6b794d6becf29',
    'application/common.php' => $lane === 'A'
        ? '5f0bc855dc205360896f7a08a5d66f3904a39a607cc463f6a70a6add04a55e7e'
        : '1ff0e49451950d671498ad5e1f7380f60448d2f7a39041d4b53370abd6e6d78f',
    'application/route.php' => '081b0186b7f40f0bdd237cecb3e2d678fc9344c656932c0d3b3052404e4f1510',
];
foreach ($authSources as $relative => $sha) {
    $path = $root . '/' . $relative;
    if (!is_file($path) || is_link($path) || hash_file('sha256', $path) !== $sha) {
        throw new RuntimeException('Auth/route source drift: ' . $relative);
    }
}
$connect = static function () use ($dsn, $runtime): PDO {
    return new PDO($dsn, (string)$runtime['username'], (string)$runtime['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
};
$sameIdentity = static function (PDO $pdo) use ($dialect, $approvedDbSha): bool {
    $actual = $dialect === 'dm'
        ? 'ZHCT_APP|5237|' . (string)$pdo->query(
            "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn()
        : (string)$pdo->query(
            "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
            ->fetchColumn();
    return hash_equals($approvedDbSha, hash('sha256', $actual));
};
$read = static function (PDO $pdo, string $sql, array $args = [], int $cap = 6000): array {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    $out = [];
    while (($raw = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
        if (count($out) >= $cap) throw new RuntimeException('Bounded team source cap exceeded');
        $row = [];
        foreach (array_change_key_case($raw, CASE_LOWER) as $key => $value) {
            $row[$key] = is_resource($value) ? stream_get_contents($value) : $value;
        }
        ksort($row, SORT_STRING);
        $out[] = $row;
    }
    return $out;
};
$scalar = static function (PDO $pdo, string $sql, array $args = []) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    return $stmt->fetchColumn();
};
$in = implode(',', array_fill(0, count($staffUuids), '?'));
$source = static function (PDO $pdo) use ($read, $table, $dept, $staffUuids,
    $in, $range): array {
    $sets = [
        'department' => $read($pdo, 'SELECT * FROM ' . $table('department')
            . ' WHERE UUID=?', [$dept], 2),
        'staff' => $read($pdo, 'SELECT * FROM ' . $table('staff')
            . ' WHERE UUID IN (' . $in . ')', $staffUuids, 9),
        'staff_department' => $read($pdo, 'SELECT * FROM '
            . $table('staff_department') . ' WHERE STAFF_UUID IN (' . $in . ')',
            $staffUuids, 100),
        'menu_recommend' => $read($pdo, 'SELECT * FROM '
            . $table('menu_recommend') . ' WHERE STAFF_UUID IN (' . $in . ')',
            $staffUuids, 6000),
        'date_menu_3days' => $read($pdo, 'SELECT * FROM ' . $table('date_menu')
            . ' WHERE STAFF_UUID IN (' . $in . ') AND MENU_DATE BETWEEN ? AND ?',
            array_merge($staffUuids, $range), 301),
    ];
    $dishUuids = [];
    foreach ($sets['date_menu_3days'] as $item) {
        if (!empty($item['dishes_uuid'])) $dishUuids[(string)$item['dishes_uuid']] = true;
    }
    $dishValues = array_keys($dishUuids);
    if (count($dishValues) < 1 || count($dishValues) > 100) {
        throw new RuntimeException('Actual dish source absent/unbounded');
    }
    $dishBind = implode(',', array_fill(0, count($dishValues), '?'));
    $sets['dishes'] = $read($pdo, 'SELECT UUID,ENERGY FROM ' . $table('dishes')
        . ' WHERE UUID IN (' . $dishBind . ')', $dishValues, 101);
    $counts = [];
    $hashes = [];
    foreach ($sets as $name => $items) {
        $canonical = [];
        foreach ($items as $item) $canonical[] = serialize($item);
        sort($canonical, SORT_STRING);
        $counts[$name] = count($items);
        $hashes[$name] = hash('sha256', implode("\n", $canonical));
    }
    return [$sets, $counts, $hashes];
};
[$sourceRows, $sourceCounts, $sourceHashes] = $source($db);
if ($sourceCounts['department'] !== 1
    || $sourceCounts['staff'] !== count($staffUuids)
    || $sourceCounts['date_menu_3days'] < count($actualRows)
    || $sourceCounts['dishes'] < 1) {
    throw new RuntimeException('Team5 source count mismatch');
}
$queueState = static function (PDO $pdo) use ($table): array {
    $row = array_change_key_case($pdo->query('SELECT COUNT(*) AS TOTAL,'
        . ' SUM(CASE WHEN STATUS=0 THEN 1 ELSE 0 END) AS PENDING FROM '
        . $table('export_log'))->fetch(PDO::FETCH_ASSOC) ?: [], CASE_LOWER);
    return [(int)($row['total'] ?? -1), (int)($row['pending'] ?? -1)];
};
$queueBefore = $queueState($db);
if ($queueBefore[0] < 0 || $queueBefore[1] !== 0) {
    throw new RuntimeException('Team5 queue pending/unavailable');
}
$oldActorCount = (int)$scalar($db, 'SELECT COUNT(*) FROM ' . $table('user')
    . " WHERE ACCOUNT LIKE 'CDXTM5%'");
if ($oldActorCount !== 0) throw new RuntimeException('Old team5 actor residue');
if ($dialect === 'dm') {
    $ddlStmt = $db->prepare('CALL SP_TABLEDEF(?, ?)');
    $ddlStmt->execute(['ZHCT_APP', 'YDY_USER']);
    $ddl = $ddlStmt->fetchColumn();
    if (is_resource($ddl)) $ddl = stream_get_contents($ddl);
    $autoId = preg_match('/"ID"\s+[A-Z0-9]+\s+AUTO_INCREMENT\s+NOT\s+NULL/i',
        (string)$ddl) === 1;
    $trigger = (int)$scalar($db, 'SELECT COUNT(*) FROM USER_TRIGGERS WHERE TABLE_NAME=?',
        ['YDY_USER']);
    $fk = (int)$scalar($db, "SELECT COUNT(*) FROM USER_CONSTRAINTS"
        . " WHERE TABLE_NAME=? AND CONSTRAINT_TYPE='R'", ['YDY_USER'])
        + (int)$scalar($db, 'SELECT COUNT(*) FROM ALL_CONSTRAINTS c'
            . ' JOIN ALL_CONSTRAINTS parent ON c.R_OWNER=parent.OWNER'
            . ' AND c.R_CONSTRAINT_NAME=parent.CONSTRAINT_NAME'
            . " WHERE c.CONSTRAINT_TYPE='R' AND parent.OWNER='ZHCT_APP'"
            . ' AND parent.TABLE_NAME=?', ['YDY_USER']);
} else {
    $autoId = (int)$scalar($db, 'SELECT COUNT(*) FROM information_schema.COLUMNS'
        . ' WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?'
        . " AND EXTRA LIKE '%auto_increment%'", ['ydy_user', 'id']) === 1;
    $trigger = (int)$scalar($db, 'SELECT COUNT(*) FROM information_schema.TRIGGERS'
        . ' WHERE TRIGGER_SCHEMA=DATABASE() AND EVENT_OBJECT_TABLE=?', ['ydy_user']);
    $fk = (int)$scalar($db, 'SELECT COUNT(*) FROM information_schema.KEY_COLUMN_USAGE'
        . ' WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?'
        . ' AND REFERENCED_TABLE_NAME IS NOT NULL', ['ydy_user'])
        + (int)$scalar($db, 'SELECT COUNT(*) FROM information_schema.KEY_COLUMN_USAGE'
            . ' WHERE REFERENCED_TABLE_SCHEMA=DATABASE() AND REFERENCED_TABLE_NAME=?',
            ['ydy_user']);
}
if (!$autoId || $trigger !== 0 || $fk !== 0) {
    throw new RuntimeException('Team5 actor ID/FK/trigger drift');
}
$pre = ['lane' => $lane, 'mode' => 'select-only-preflight',
    'day' => $day, 'range' => $range,
    'leaf_department_sha12' => substr(hash('sha256', $dept), 0, 12),
    'staff_count' => count($staffUuids), 'source_counts' => $sourceCounts,
    'source_hashes' => $sourceHashes, 'queue_before' => $queueBefore,
    'actor_auto_id_fk0_trigger0' => true, 'prior_actor_rows' => $oldActorCount,
    'business_http' => 0, 'dml' => 0];
if ($mode === '--preflight') {
    echo json_encode($pre, JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(0);
}
$time = date('H:i');
if ($time >= '23:58' || $time <= '00:02') {
    throw new RuntimeException('Near-midnight isolated temp cleanup window');
}
$baseline = null;
if ($lane !== 'A') {
    $baselineFile = (string)getenv('CDX_TEAM5_A_CONTRACT_FILE');
    $baselineSha = (string)getenv('CDX_TEAM5_A_CONTRACT_SHA');
    if ($baselineFile === '' || !is_file($baselineFile) || is_link($baselineFile)
        || !preg_match('/^[a-f0-9]{64}$/D', $baselineSha)
        || !hash_equals($baselineSha, (string)hash_file('sha256', $baselineFile))) {
        throw new RuntimeException('A baseline contract and SHA required');
    }
    $baselineJson = (string)file_get_contents($baselineFile);
    $baseline = json_decode($baselineJson, true);
    if (!is_array($baseline) || ($baseline['lane'] ?? '') !== 'A'
        || ($baseline['db_sha'] ?? '')
            !== '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401'
        || !isset($baseline['routes'], $baseline['auth_negative'])) {
        throw new RuntimeException('A baseline contract invalid');
    }
}
$staffMap = [];
$staffNameToUuid = [];
foreach ($sourceRows['staff'] as $row) {
    $staffMap[(string)$row['uuid']] = $row;
    $staffNameToUuid[(string)$row['name']] = (string)$row['uuid'];
}
if (count($staffMap) !== count($staffUuids)
    || count($staffNameToUuid) !== count($staffUuids)) {
    throw new RuntimeException('Team5 staff map ambiguous');
}
$uuidCsv = implode(',', $staffUuids);
$uuidSet = static function (string $csv): array {
    $parts = array_values(array_filter(array_map('trim', explode(',', $csv)),
        static function (string $value): bool { return $value !== ''; }));
    if (count($parts) !== count(array_unique($parts))) {
        throw new RuntimeException('Duplicate UUID in response');
    }
    sort($parts, SORT_STRING);
    return $parts;
};
$expectedUuids = $uuidSet($uuidCsv);
$stageGrade = 1;
foreach ($staffMap as $staff) {
    if ((int)$staff['grade'] !== 1) { $stageGrade = 2; break; }
}
$actualTimes = [];
foreach ($rangeRows as $row) {
    $uuid = (string)$row['staff_uuid'];
    $mealDay = substr((string)$row['menu_date'], 0, 10);
    if (isset($staffMap[$uuid])) $actualTimes[$uuid][$mealDay][(int)$row['meal_times']] = true;
}
$expectedSingle = [];
$actualStaffCount = 0;
$mealNames = [1 => '缺早餐', 2 => '缺午餐', 3 => '缺晚餐'];
foreach ($staffMap as $uuid => $staff) {
    $times = $actualTimes[$uuid][$day] ?? [];
    $missing = [];
    if ($times) {
        $actualStaffCount++;
        foreach ($mealNames as $mealNo => $label) {
            if (!isset($times[$mealNo])) $missing[] = $label;
        }
    } else {
        $missing[] = '未就餐';
    }
    $expectedSingle[(string)$staff['name']] = $missing;
}
ksort($expectedSingle, SORT_STRING);
$days = [];
for ($stamp = strtotime($range[0]); $stamp <= strtotime($range[1]); $stamp += 86400) {
    $days[] = date('Y-m-d', $stamp);
}
if (count($days) !== 3) throw new RuntimeException('Three-day status range drift');
$expectedMulti = [];
foreach ($staffMap as $uuid => $staff) {
    $lack = [1 => 0, 2 => 0, 3 => 0];
    $noMealDays = 0;
    foreach ($days as $oneDay) {
        $times = $actualTimes[$uuid][$oneDay] ?? [];
        if (!$times) { $noMealDays++; continue; }
        foreach ([1, 2, 3] as $mealNo) {
            if (!isset($times[$mealNo])) $lack[$mealNo]++;
        }
    }
    $labels = [];
    foreach ($mealNames as $mealNo => $name) {
        if ($lack[$mealNo] > 0) $labels[] = $name . $lack[$mealNo] . '天';
    }
    $labels[] = '未就餐' . $noMealDays . '天';
    $expectedMulti[(string)$staff['name']] = $labels;
}
ksort($expectedMulti, SORT_STRING);
$runtimeReady = static function () use ($root, $base, $pid): bool {
    $cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
    $environment = (string)@file_get_contents('/proc/' . $pid . '/environ');
    $children = (string)@file_get_contents('/proc/' . $pid . '/task/' . $pid . '/children');
    $boundary = json_decode((string)@file_get_contents($base . '/__poc_boundary',
        false, stream_context_create(['http' => ['timeout' => 5]])), true);
    $port = (int)parse_url($base, PHP_URL_PORT);
    $hex = strtoupper(str_pad(dechex($port), 4, '0', STR_PAD_LEFT));
    $inode = '';
    foreach (@file('/proc/net/tcp', FILE_IGNORE_NEW_LINES) ?: [] as $line) {
        $part = preg_split('/\s+/', trim($line));
        if (($part[1] ?? '') === '0100007F:' . $hex && ($part[3] ?? '') === '0A') {
            $inode = (string)($part[9] ?? '');
            break;
        }
    }
    $owns = false;
    if ($inode !== '') foreach (@scandir('/proc/' . $pid . '/fd') ?: [] as $fd) {
        if ($fd !== '.' && $fd !== '..'
            && @readlink('/proc/' . $pid . '/fd/' . $fd) === 'socket:[' . $inode . ']') {
            $owns = true;
            break;
        }
    }
    return $owns && $environment !== '' && trim($children) === ''
        && strpos($cmdline, '127.0.0.1:' . $port) !== false
        && strpos($cmdline, $root . '/public') !== false
        && !(preg_match('/(?:^|\x00)PHP_CLI_SERVER_WORKERS=(\d+)(?:\x00|$)/', $environment, $m)
            && (int)$m[1] > 1)
        && is_array($boundary) && !empty($boundary['external_stubs'])
        && !empty($boundary['redis_isolated']) && empty($boundary['real_queue']);
};
$profile = static function (array $json, string $kind): array {
    $types = ['code' => gettype($json['code']),
        'message' => gettype($json['message']),
        'data' => gettype($json['data'] ?? null)];
    if (isset($json['grade'])) $types['grade'] = gettype($json['grade']);
    if (isset($json['nums'])) $types['nums'] = gettype($json['nums']);
    if ($kind === 'staff_rows') {
        $rowTypes = [];
        foreach ($json['data'] as $row) {
            foreach ($row as $name => $value) $rowTypes[$name][gettype($value)] = true;
        }
        foreach ($rowTypes as $name => $values) {
            $types['row.' . $name] = array_keys($values);
            sort($types['row.' . $name], SORT_STRING);
        }
    } elseif ($kind === 'status') {
        $types['data_values'] = [];
        foreach ($json['data'] as $value) {
            $types['data_values'][gettype($value)] = true;
            if (is_array($value)) foreach ($value as $element) {
                $types['element.' . gettype($element)] = true;
            }
        }
        $types['data_values'] = array_keys($types['data_values']);
        sort($types['data_values'], SORT_STRING);
    }
    ksort($types, SORT_STRING);
    return $types;
};
$assertBaseline = static function (string $key, string $sha, array $typeProfile)
    use ($lane, $baseline): void {
    if ($lane === 'A') return;
    $previous = $baseline['routes'][$key] ?? null;
    if (!is_array($previous) || !isset($previous['response_sha'], $previous['type_profile'])) {
        throw new RuntimeException('A baseline route missing');
    }
    if ($lane === 'B' && !hash_equals((string)$previous['response_sha'], $sha)) {
        throw new RuntimeException('A/B full JSON response differs');
    }
    if ($lane === 'C' && $previous['type_profile'] !== $typeProfile) {
        throw new RuntimeException('C JSON type profile differs from A');
    }
};
$marker = 'CDXTM5' . strtoupper(bin2hex(random_bytes(6)));
if ((int)$scalar($db, 'SELECT COUNT(*) FROM ' . $table('user')
    . ' WHERE UUID=? OR ACCOUNT=?', [$marker, $marker]) !== 0) {
    throw new RuntimeException('Team5 random marker collision');
}
$privateDir = sys_get_temp_dir() . '/zhct-team5-' . $marker;
if (file_exists($privateDir) || !mkdir($privateDir, 0700)) {
    throw new RuntimeException('Team5 private recovery directory unavailable');
}
chmod($privateDir, 0700);
$journalPath = $privateDir . '/recovery.json';
$journal = ['lane' => $lane, 'marker' => $marker,
    'source_hashes' => $sourceHashes, 'queue_before' => $queueBefore,
    'state' => 'prepared'];
$saveJournal = static function () use (&$journal, $privateDir, $journalPath): void {
    $next = $privateDir . '/recovery.next';
    if (file_put_contents($next, json_encode($journal, JSON_UNESCAPED_SLASHES)) === false) {
        throw new RuntimeException('Team5 journal write failed');
    }
    chmod($next, 0600);
    if (!rename($next, $journalPath)) throw new RuntimeException('Team5 journal rename failed');
};
$saveJournal();
$actorId = 0;
$httpSent = false;
$httpConfirmed = true;
$sourceUnchanged = false;
$queueUnchanged = false;
$cleaned = false;
$privateCleared = false;
$failure = '';
$routeResults = [];
$negativeResults = [];
$http = static function (string $path, array $form, string $token)
    use ($base, $runtimeReady, &$httpSent, &$httpConfirmed): array {
    if (!$runtimeReady()) throw new RuntimeException('Team5 HTTP runtime boundary drift');
    $headers = "Content-Type: application/x-www-form-urlencoded\r\n";
    if ($token !== '') $headers .= 'token: ' . $token . "\r\n";
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'header' => $headers,
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'timeout' => 15, 'ignore_errors' => true]]);
    $httpConfirmed = false;
    $httpSent = true;
    $stream = @fopen($base . $path, 'rb', false, $context);
    $body = is_resource($stream) ? stream_get_contents($stream, 524289) : false;
    $meta = is_resource($stream) ? stream_get_meta_data($stream) : [];
    if (is_resource($stream)) fclose($stream);
    if (!is_string($body) || !empty($meta['timed_out']) || strlen($body) > 524288) {
        throw new RuntimeException('Team5 HTTP incomplete or body cap exceeded');
    }
    $httpConfirmed = true;
    $headers = $http_response_header ?? [];
    if (strpos((string)($headers[0] ?? ''), ' 200 ') === false) {
        throw new RuntimeException('Team5 HTTP status mismatch');
    }
    $json = json_decode($body, true);
    if (!is_array($json) || !isset($json['code'], $json['message'])) {
        throw new RuntimeException('Team5 response envelope invalid');
    }
    return [$json, hash('sha256', $body)];
};
try {
    // Independent connection confirms this exact six-table window, not global menu totals.
    $fresh = $connect();
    if (!$sameIdentity($fresh) || $source($fresh)[2] !== $sourceHashes
        || $queueState($fresh) !== $queueBefore) {
        throw new RuntimeException('Team5 source/queue drift before actor');
    }
    $stmt = $db->prepare('INSERT INTO ' . $table('user')
        . ' (UUID,ACCOUNT,PWD,SALT,NAME,TYPE,CREATE_TIME,CREATE_BY,IS_DELETE)'
        . ' VALUES (?,?,?,?,?,?,?,?,?)');
    $stmt->execute([$marker, $marker, 'DISABLED', strtoupper(bin2hex(random_bytes(8))),
        $marker, 0, date('Y-m-d H:i:s'), 'CODEX', 0]);
    if ($stmt->rowCount() !== 1) throw new RuntimeException('Team5 actor insert row count mismatch');
    $actorId = (int)$scalar($db, 'SELECT ID FROM ' . $table('user')
        . ' WHERE UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?',
        [$marker, $marker, 'CODEX']);
    if ($actorId <= 0) throw new RuntimeException('Team5 actor ID missing');
    $journal['actor_id'] = $actorId;
    $journal['state'] = 'actor_committed';
    $saveJournal();
    require_once $root . '/application/base/Security.php';
    $token = \app\base\Security::encrypt(implode("\t",
        [(string)$actorId, $marker, $marker, '0', '', '', $marker]));
    if (!is_string($token) || $token === '') {
        throw new RuntimeException('Team5 synthetic token unavailable');
    }
    $calls = [
        'team_list' => ['/p/Stageanalyze/team_list',
            ['department_uuid' => $dept, 'menu_data' => $day], 'staff_rows'],
        'eligibility_dept' => ['/p/Stageanalyze/eligibility_uuid',
            ['uuid' => $dept, 'department_uuid' => $dept,
                'menu_data' => $day, 'type' => '1'], 'eligibility_day'],
        'eligibility_staff' => ['/p/Stageanalyze/eligibility_uuid',
            ['uuid' => $uuidCsv, 'department_uuid' => $dept,
                'menu_data' => $day, 'type' => '2'], 'eligibility_day'],
        'stage_eligibility_dept' => ['/p/Stageanalyze/stage_eligibility_uuid',
            ['uuid' => $dept, 'type' => '1'], 'eligibility_stage'],
        'stage_eligibility_staff' => ['/p/Stageanalyze/stage_eligibility_uuid',
            ['uuid' => $uuidCsv, 'type' => '2'], 'eligibility_stage'],
        'eat_single_status' => ['/p/stageanalyze/eatSingleStatus',
            ['uuid' => $uuidCsv, 'menu_date' => $day], 'status_single'],
        'eat_multi_status' => ['/p/stageanalyze/eatMultiStatus',
            ['uuid' => $uuidCsv, 'start_time' => $range[0],
                'end_time' => $range[1]], 'status_multi'],
    ];
    $checked = [];
    foreach ($calls as $call) {
        $path = $call[0];
        if (isset($checked[$path])) continue;
        $checked[$path] = true;
        [$negative] = $http($path, $call[1], '');
        if ((int)$negative['code'] === 0) {
            throw new RuntimeException('Team5 unauthenticated route accepted');
        }
        $negativeResults[$path] = ['code' => $negative['code'],
            'code_type' => gettype($negative['code']),
            'message_sha' => hash('sha256', (string)$negative['message']),
            'message_type' => gettype($negative['message'])];
    }
    if ($lane !== 'A' && $negativeResults !== $baseline['auth_negative']) {
        throw new RuntimeException('Team5 unauthenticated contract differs from A');
    }
    foreach ($calls as $key => $call) {
        [$path, $form, $kind] = $call;
        [$json, $sha] = $http($path, $form, $token);
        if ((int)$json['code'] !== 0 || !array_key_exists('data', $json)) {
            throw new RuntimeException('Team5 positive business response failed');
        }
        $data = $json['data'];
        if ($kind === 'staff_rows') {
            if (!is_array($data) || count($data) !== count($staffUuids)) {
                throw new RuntimeException('Team list row count differs from source');
            }
            $seen = [];
            foreach ($data as $row) {
                if (!is_array($row) || !isset($row['uuid'], $row['name'])) {
                    throw new RuntimeException('Team list row shape mismatch');
                }
                $uuid = (string)$row['uuid'];
                if (!isset($staffMap[$uuid]) || isset($seen[$uuid])
                    || (string)$row['name'] !== (string)$staffMap[$uuid]['name']) {
                    throw new RuntimeException('Team list staff source mismatch');
                }
                $seen[$uuid] = true;
            }
        } elseif ($kind === 'eligibility_day' || $kind === 'eligibility_stage') {
            if (!is_string($data) || $uuidSet($data) !== $expectedUuids
                || !isset($json['grade'])
                || (int)$json['grade'] !== ($kind === 'eligibility_day' ? 1 : $stageGrade)) {
                throw new RuntimeException('Team eligibility UUID/grade source mismatch');
            }
        } elseif ($kind === 'status_single' || $kind === 'status_multi') {
            if (!is_array($data)) throw new RuntimeException('Team status data type mismatch');
            ksort($data, SORT_STRING);
            $expect = $kind === 'status_single' ? $expectedSingle : $expectedMulti;
            if ($data !== $expect) {
                throw new RuntimeException('Team meal-status source calculation mismatch');
            }
            if ($kind === 'status_single'
                && (!isset($json['nums']) || (int)$json['nums'] !== $actualStaffCount)) {
                throw new RuntimeException('Team single-day nums source mismatch');
            }
        }
        $types = $profile($json, $kind === 'staff_rows' ? 'staff_rows'
            : (strpos($kind, 'status_') === 0 ? 'status' : 'eligibility'));
        $assertBaseline($key, $sha, $types);
        $routeResults[$key] = ['response_sha' => $sha,
            'type_profile' => $types,
            'business_rows' => is_array($data) ? count($data) : count($uuidSet((string)$data))];
        $journal['state'] = 'route_' . $key . '_confirmed';
        $saveJournal();
    }
    $after = $connect();
    if (!$sameIdentity($after)) throw new RuntimeException('Team5 post-HTTP DB identity drift');
    $afterSource = $source($after);
    $sourceUnchanged = $afterSource[1] === $sourceCounts
        && $afterSource[2] === $sourceHashes;
    $queueUnchanged = $queueState($after) === $queueBefore;
    if (!$sourceUnchanged || !$queueUnchanged) {
        throw new RuntimeException('Team5 windowed source or queue changed');
    }
} catch (Throwable $e) {
    $failure = get_class($e) . ':' . hash('sha256', $e->getMessage());
} finally {
    $workerStopped = !is_dir('/proc/' . $pid);
    $cleanupSafe = ($workerStopped || $runtimeReady())
        && ($workerStopped || !$httpSent || $httpConfirmed);
    if ($cleanupSafe) {
        try {
            $cleanupDb = $connect();
            if (!$sameIdentity($cleanupDb)) throw new RuntimeException('Team5 cleanup DB identity drift');
            $owner = $read($cleanupDb, 'SELECT ID,UUID,ACCOUNT,NAME,TYPE,CREATE_BY'
                . ' FROM ' . $table('user') . ' WHERE UUID=? OR ACCOUNT=?',
                [$marker, $marker], 2);
            if (count($owner) > 1) throw new RuntimeException('Team5 actor ownership ambiguous');
            foreach ($owner as $record) {
                if ((string)$record['uuid'] !== $marker
                    || (string)$record['account'] !== $marker
                    || (string)$record['name'] !== $marker
                    || (int)$record['type'] !== 0
                    || (string)$record['create_by'] !== 'CODEX'
                    || ($actorId > 0 && (int)$record['id'] !== $actorId)) {
                    throw new RuntimeException('Team5 actor ownership drift');
                }
                foreach (['user_role', 'user_data'] as $relation) {
                    if ((int)$scalar($cleanupDb, 'SELECT COUNT(*) FROM '
                        . $table($relation) . ' WHERE USER_UUID=?', [$marker]) !== 0) {
                        throw new RuntimeException('Team5 unexpected actor association');
                    }
                }
                $cleanupDb->beginTransaction();
                try {
                    $stmt = $cleanupDb->prepare('DELETE FROM ' . $table('user')
                        . ' WHERE ID=? AND UUID=? AND ACCOUNT=? AND NAME=?'
                        . ' AND TYPE=0 AND CREATE_BY=?');
                    $stmt->execute([(int)$record['id'], $marker, $marker, $marker, 'CODEX']);
                    if ($stmt->rowCount() !== 1) {
                        throw new RuntimeException('Team5 exact actor cleanup mismatch');
                    }
                    $cleanupDb->commit();
                } catch (Throwable $e) {
                    if ($cleanupDb->inTransaction()) $cleanupDb->rollBack();
                    throw $e;
                }
            }
            $zero = $connect();
            if (!$sameIdentity($zero)
                || (int)$scalar($zero, 'SELECT COUNT(*) FROM ' . $table('user')
                    . ' WHERE UUID=? OR ACCOUNT=?', [$marker, $marker]) !== 0) {
                throw new RuntimeException('Team5 independent actor-zero failed');
            }
            $cleaned = true;
        } catch (Throwable $e) {
            $failure .= ($failure === '' ? '' : ';') . 'cleanup:'
                . get_class($e) . ':' . hash('sha256', $e->getMessage());
        }
    } else {
        $failure .= ($failure === '' ? '' : ';')
            . ($httpSent && !$httpConfirmed && !$workerStopped
                ? 'cleanup:unknown_http_outcome' : 'cleanup:runtime_drift');
    }
    if ($cleaned) {
        if (is_file($journalPath)) @unlink($journalPath);
        if (is_file($privateDir . '/recovery.next')) @unlink($privateDir . '/recovery.next');
        $privateCleared = @rmdir($privateDir);
        if (!$privateCleared) $failure .= ';private_journal_not_removed';
    } else {
        $journal['state'] = 'requires_manual_recovery';
        try { $saveJournal(); } catch (Throwable $e) { /* Retain prior journal. */ }
    }
}
$contract = ['lane' => $lane, 'db_sha' => $approvedDbSha,
    'routes' => $routeResults, 'auth_negative' => $negativeResults];
$result = ['lane' => $lane,
    'leaf_department_sha12' => substr(hash('sha256', $dept), 0, 12),
    'day' => $day, 'range' => $range, 'contract' => $contract,
    'source_counts' => $sourceCounts, 'source_hashes_before' => $sourceHashes,
    'source_unchanged' => $sourceUnchanged, 'queue_unchanged' => $queueUnchanged,
    'actor_independent_zero' => $cleaned, 'private_journal_removed' => $privateCleared,
    'private_recovery_pointer' => $cleaned ? null : $privateDir,
    'failure' => $failure];
echo json_encode($result, JSON_UNESCAPED_SLASHES), PHP_EOL;
if ($failure !== '' || count($routeResults) !== 7 || !$sourceUnchanged
    || !$queueUnchanged || !$cleaned || !$privateCleared) exit(1);
