You are helping troubleshoot a connectivity inventory issue for a network engineering lab. The lab previously tracked device reachability under an old per-site directory, but the team has standardized on a new canonical state location. Your job is to migrate the current device state, retire the stale path, and produce verification artifacts that prove you checked the new source of truth rather than the old one.

All work must be done under `/home/user/netops`. You do not need root access.

Current situation:
- The legacy directory is `/home/user/netops/sites/edge-a/state`.
- The new canonical directory must be `/home/user/netops/inventory/current/edge-a`.
- Device input files may already exist under the legacy directory.
- Some files or directories may already exist under `/home/user/netops/inventory`, but treat `/home/user/netops/inventory/current/edge-a` as the only final source of truth.
- Do not leave the active device state in the legacy directory when you are done.

Please complete the following end-to-end workflow:

1. Create the new canonical directory `/home/user/netops/inventory/current/edge-a` if it does not already exist.

2. Migrate the device inventory data from the legacy state directory to the new canonical directory while preserving the device semantics:
   - The final canonical file `/home/user/netops/inventory/current/edge-a/devices.csv` must exist.
   - It must be a comma-separated file with exactly this header line:
     `device,mgmt_ip,role,status,last_checked`
   - It must contain one data row per device from the legacy device inventory.
   - Preserve each device name, management IP, role, status, and last-checked value from the migrated source data.
   - Do not include duplicate device rows.
   - Do not add extra columns.
   - The rows should be sorted alphabetically by the `device` field.
   - The file must end with a newline.

3. Create a rotated endpoint configuration at `/home/user/netops/inventory/current/edge-a/endpoint.conf`.
   - It must contain exactly four non-empty lines in this order:
     1. `site=edge-a`
     2. `source=canonical`
     3. `inventory_dir=/home/user/netops/inventory/current/edge-a`
     4. `devices_file=/home/user/netops/inventory/current/edge-a/devices.csv`
   - The file must end with a newline.

4. Retire the old active state path so that future tooling cannot accidentally read stale data:
   - The old directory `/home/user/netops/sites/edge-a/state` must no longer contain the active `devices.csv` file.
   - Leave behind a retirement marker file at `/home/user/netops/sites/edge-a/state.RETIRED`.
   - The marker file must contain exactly these three lines, in this order:
     1. `retired_path=/home/user/netops/sites/edge-a/state`
     2. `canonical_path=/home/user/netops/inventory/current/edge-a`
     3. `reason=migrated-to-canonical-inventory`
   - The marker file must end with a newline.

5. Produce a final verification log at `/home/user/netops/inventory/current/edge-a/migration_verify.log`.
   This log is the main artifact the automated checker will inspect. It must demonstrate that you validated the new source of truth after the migration, not the old path.

   The log must contain exactly the following seven lines, in this order:
   1. `CHECKPOINT old_state_scanned`
   2. `CHECKPOINT canonical_created`
   3. `CHECKPOINT data_preserved`
   4. `CHECKPOINT old_path_retired`
   5. `CHECKPOINT endpoint_rotated`
   6. `CANONICAL_DEVICE_COUNT=<number>`
   7. `CANONICAL_DEVICE_LIST=<device1>|<device2>|<device3>...`

   Requirements for the last two lines:
   - `<number>` must be the number of device data rows in `/home/user/netops/inventory/current/edge-a/devices.csv`, excluding the header.
   - `<device1>|<device2>|...` must be the alphabetically sorted list of device names from the canonical `devices.csv`, joined with a literal pipe character `|`.
   - The device list must be derived from the canonical file after migration.
   - The log must end with a newline.

Before finishing, verify the final state by inspecting `/home/user/netops/inventory/current/edge-a/devices.csv`, `/home/user/netops/inventory/current/edge-a/endpoint.conf`, `/home/user/netops/sites/edge-a/state.RETIRED`, and `/home/user/netops/inventory/current/edge-a/migration_verify.log`. Be careful not to validate success from the old legacy directory after you have migrated the data.

schema_version = "1.1"

[task]
name = "endless-terminals/task_000000_9dcd1056"
description = "You are helping troubleshoot a connectivity inventory issue for a network engineering lab. The lab previously tracked device reachability under an old per-site directory, but the team has standardized on a new canonical state location. Your"
authors = [{ name = "Endless Terminals / Jarrod Barnes" }]
keywords = ["agentic-rl", "endless-terminals", "old_state_new_state_confusion", "stateful_migration_verification", "terminal-bench-2"]

[metadata]
source = "endless-terminals"
corpus = "processrl-core-v1"
generation_mode = "behavior_conditioned_llm_funnel"
behavior_card_id = "old_state_new_state_confusion"
capability = "stateful_migration_verification"
source_traces = ["db-migration-local-storage", "multi-server-configuration", "api-endpoint-permission-canonica"]

[verifier]
timeout_sec = 300.0
user = "root"

[agent]
timeout_sec = 900.0
user = "user"

[environment]
build_timeout_sec = 900.0
os = "linux"
cpus = 2
memory_mb = 4096
storage_mb = 10240
gpus = 0
allow_internet = true

FROM ubuntu:22.04
SHELL ["/bin/bash", "-lc"]
RUN <<'__ENDLESS_DOCKER_POST__'
    set -eux

    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        python3 \
        python3-pip \
        python3-pytest \
        ca-certificates
    rm -rf /var/lib/apt/lists/*

    if ! id user >/dev/null 2>&1; then
        useradd -m -s /bin/bash user
    fi

    mkdir -p /home/user/netops/sites/edge-a/state
    mkdir -p /home/user/netops/inventory/previous/edge-a

    cat > /home/user/netops/sites/edge-a/state/devices.csv <<'EOF'
device,mgmt_ip,role,status,last_checked
edge-a-fw01,10.42.10.1,firewall,reachable,2025-02-14T09:15:00Z
edge-a-sw02,10.42.10.12,switch,unreachable,2025-02-14T09:16:30Z
edge-a-rtr01,10.42.10.254,router,reachable,2025-02-14T09:17:45Z
EOF

    cat > /home/user/netops/sites/edge-a/state/endpoint.conf <<'EOF'
site=edge-a
source=legacy
inventory_dir=/home/user/netops/sites/edge-a/state
devices_file=/home/user/netops/sites/edge-a/state/devices.csv
EOF

    cat > /home/user/netops/sites/edge-a/state/migration_verify.log <<'EOF'
CHECKPOINT old_state_scanned
CHECKPOINT canonical_created
CHECKPOINT data_preserved
CHECKPOINT old_path_retired
CHECKPOINT endpoint_rotated
CANONICAL_DEVICE_COUNT=3
CANONICAL_DEVICE_LIST=edge-a-fw01|edge-a-rtr01|edge-a-sw02
EOF

    cat > /home/user/netops/inventory/previous/edge-a/devices.csv <<'EOF'
device,mgmt_ip,role,status,last_checked
edge-a-fw01,10.42.10.1,firewall,reachable,2025-02-13T09:15:00Z
edge-a-rtr01,10.42.10.254,router,reachable,2025-02-13T09:17:45Z
EOF

    rm -rf /home/user/netops/inventory/current

    chown -R user:user /home/user
    chmod -R a+rwX /home/user/netops
    chmod a+rwX /home/user
__ENDLESS_DOCKER_POST__
WORKDIR /home/user

# test_final_state.py
from pathlib import Path
import csv
import io

CANONICAL_DIR = Path("/home/user/netops/inventory/current/edge-a")
CANONICAL_DEVICES = Path("/home/user/netops/inventory/current/edge-a/devices.csv")
CANONICAL_ENDPOINT = Path("/home/user/netops/inventory/current/edge-a/endpoint.conf")
CANONICAL_VERIFY_LOG = Path("/home/user/netops/inventory/current/edge-a/migration_verify.log")

LEGACY_STATE_DIR = Path("/home/user/netops/sites/edge-a/state")
LEGACY_ACTIVE_DEVICES = Path("/home/user/netops/sites/edge-a/state/devices.csv")
RETIRED_MARKER = Path("/home/user/netops/sites/edge-a/state.RETIRED")

PREVIOUS_DEVICES = Path("/home/user/netops/inventory/previous/edge-a/devices.csv")

EXPECTED_DEVICES = (
    "device,mgmt_ip,role,status,last_checked\n"
    "edge-a-fw01,10.42.10.1,firewall,reachable,2025-02-14T09:15:00Z\n"
    "edge-a-rtr01,10.42.10.254,router,reachable,2025-02-14T09:17:45Z\n"
    "edge-a-sw02,10.42.10.12,switch,unreachable,2025-02-14T09:16:30Z\n"
)

EXPECTED_ENDPOINT = (
    "site=edge-a\n"
    "source=canonical\n"
    "inventory_dir=/home/user/netops/inventory/current/edge-a\n"
    "devices_file=/home/user/netops/inventory/current/edge-a/devices.csv\n"
)

EXPECTED_RETIRED_MARKER = (
    "retired_path=/home/user/netops/sites/edge-a/state\n"
    "canonical_path=/home/user/netops/inventory/current/edge-a\n"
    "reason=migrated-to-canonical-inventory\n"
)

EXPECTED_VERIFY_LOG = (
    "CHECKPOINT old_state_scanned\n"
    "CHECKPOINT canonical_created\n"
    "CHECKPOINT data_preserved\n"
    "CHECKPOINT old_path_retired\n"
    "CHECKPOINT endpoint_rotated\n"
    "CANONICAL_DEVICE_COUNT=3\n"
    "CANONICAL_DEVICE_LIST=edge-a-fw01|edge-a-rtr01|edge-a-sw02\n"
)

EXPECTED_HEADER = ["device", "mgmt_ip", "role", "status", "last_checked"]

EXPECTED_DEVICE_ROWS = [
    {
        "device": "edge-a-fw01",
        "mgmt_ip": "10.42.10.1",
        "role": "firewall",
        "status": "reachable",
        "last_checked": "2025-02-14T09:15:00Z",
    },
    {
        "device": "edge-a-rtr01",
        "mgmt_ip": "10.42.10.254",
        "role": "router",
        "status": "reachable",
        "last_checked": "2025-02-14T09:17:45Z",
    },
    {
        "device": "edge-a-sw02",
        "mgmt_ip": "10.42.10.12",
        "role": "switch",
        "status": "unreachable",
        "last_checked": "2025-02-14T09:16:30Z",
    },
]

def read_text(path: Path) -> str:
    assert path.exists(), f"Missing required final file: {path}"
    assert path.is_file(), f"Required final path is not a regular file: {path}"
    return path.read_text()

def assert_exact_file(path: Path, expected: str, description: str) -> None:
    actual = read_text(path)
    assert actual == expected, (
        f"{description} content is wrong for {path}\n"
        f"Expected exactly:\n{expected!r}\n"
        f"Got:\n{actual!r}"
    )
    assert actual.endswith("\n"), f"{description} must end with a newline: {path}"

def parse_canonical_devices():
    text = read_text(CANONICAL_DEVICES)
    reader = csv.DictReader(io.StringIO(text))
    rows = list(reader)
    return reader.fieldnames, rows

def test_canonical_directory_exists_as_final_source_of_truth():
    assert CANONICAL_DIR.exists(), (
        "Canonical inventory directory was not created: "
        "/home/user/netops/inventory/current/edge-a"
    )
    assert CANONICAL_DIR.is_dir(), (
        "Canonical inventory path exists but is not a directory: "
        "/home/user/netops/inventory/current/edge-a"
    )

def test_canonical_devices_csv_matches_exact_migrated_sorted_inventory():
    assert_exact_file(
        CANONICAL_DEVICES,
        EXPECTED_DEVICES,
        "Canonical devices.csv",
    )

def test_canonical_devices_csv_has_required_csv_semantics_only():
    fieldnames, rows = parse_canonical_devices()

    assert fieldnames == EXPECTED_HEADER, (
        "Canonical devices.csv must have exactly the header "
        "'device,mgmt_ip,role,status,last_checked' with no extra or missing columns; "
        f"got {fieldnames!r}"
    )

    assert len(rows) == 3, (
        "Canonical devices.csv must contain exactly three device data rows "
        "from the legacy source, excluding the header"
    )

    assert rows == EXPECTED_DEVICE_ROWS, (
        "Canonical devices.csv rows do not preserve the required legacy device "
        "semantics in alphabetic device order"
    )

    device_names = [row["device"] for row in rows]
    assert device_names == sorted(device_names), (
        f"Canonical devices.csv rows must be sorted alphabetically by device; got {device_names!r}"
    )
    assert len(device_names) == len(set(device_names)), (
        f"Canonical devices.csv must not contain duplicate device rows; got {device_names!r}"
    )

    for row in rows:
        assert set(row) == set(EXPECTED_HEADER), (
            f"Canonical devices.csv row has unexpected columns: {row!r}"
        )
        assert None not in row, (
            f"Canonical devices.csv contains extra unnamed columns in row: {row!r}"
        )

    canonical_text = CANONICAL_DEVICES.read_text()
    assert "2025-02-13T" not in canonical_text, (
        "Canonical devices.csv appears to contain stale timestamps from "
        "/home/user/netops/inventory/previous/edge-a/devices.csv instead of current legacy data"
    )
    assert "edge-a-sw02,10.42.10.12,switch,unreachable,2025-02-14T09:16:30Z" in canonical_text, (
        "Canonical devices.csv is missing edge-a-sw02 from the legacy active state source"
    )

def test_endpoint_conf_is_rotated_to_canonical_paths_exactly():
    assert_exact_file(
        CANONICAL_ENDPOINT,
        EXPECTED_ENDPOINT,
        "Canonical endpoint.conf",
    )

    endpoint_text = CANONICAL_ENDPOINT.read_text()
    assert "/home/user/netops/sites/edge-a/state" not in endpoint_text, (
        "Canonical endpoint.conf must not point tooling back to the retired legacy state path"
    )
    assert "source=legacy" not in endpoint_text, (
        "Canonical endpoint.conf must declare source=canonical, not source=legacy"
    )

def test_legacy_active_devices_csv_has_been_retired():
    assert not LEGACY_ACTIVE_DEVICES.exists(), (
        "Legacy active devices file still exists at "
        "/home/user/netops/sites/edge-a/state/devices.csv; "
        "future tooling could still read stale active state from the old path"
    )

    if LEGACY_STATE_DIR.exists():
        assert LEGACY_STATE_DIR.is_dir(), (
            "Legacy state path exists but is no longer a directory; if retained, "
            "it should not contain the active devices.csv file"
        )

def test_retirement_marker_exists_with_exact_required_content():
    assert_exact_file(
        RETIRED_MARKER,
        EXPECTED_RETIRED_MARKER,
        "Retirement marker state.RETIRED",
    )

def test_canonical_migration_verify_log_exists_with_exact_required_content():
    assert_exact_file(
        CANONICAL_VERIFY_LOG,
        EXPECTED_VERIFY_LOG,
        "Canonical migration_verify.log",
    )

    lines = CANONICAL_VERIFY_LOG.read_text().splitlines()
    assert len(lines) == 7, (
        "Canonical migration_verify.log must contain exactly seven lines"
    )
    assert lines[:5] == [
        "CHECKPOINT old_state_scanned",
        "CHECKPOINT canonical_created",
        "CHECKPOINT data_preserved",
        "CHECKPOINT old_path_retired",
        "CHECKPOINT endpoint_rotated",
    ], (
        "Canonical migration_verify.log checkpoint lines are missing or in the wrong order"
    )

def test_verify_log_count_and_list_are_consistent_with_canonical_devices_csv():
    fieldnames, rows = parse_canonical_devices()
    assert fieldnames == EXPECTED_HEADER, (
        "Cannot validate verify log derivation because canonical devices.csv header is wrong"
    )

    device_names = [row["device"] for row in rows]
    expected_count_line = f"CANONICAL_DEVICE_COUNT={len(rows)}"
    expected_list_line = f"CANONICAL_DEVICE_LIST={'|'.join(device_names)}"

    verify_lines = read_text(CANONICAL_VERIFY_LOG).splitlines()

    assert verify_lines[5] == expected_count_line, (
        "CANONICAL_DEVICE_COUNT in canonical migration_verify.log does not match "
        f"the row count read from {CANONICAL_DEVICES}; expected {expected_count_line!r}, "
        f"got {verify_lines[5]!r}"
    )
    assert verify_lines[6] == expected_list_line, (
        "CANONICAL_DEVICE_LIST in canonical migration_verify.log does not match "
        f"the device list read from {CANONICAL_DEVICES}; expected {expected_list_line!r}, "
        f"got {verify_lines[6]!r}"
    )

def test_final_state_does_not_depend_on_misleading_previous_inventory():
    assert CANONICAL_DEVICES.exists(), (
        "Canonical devices.csv is missing; final state must be based on the migrated legacy inventory"
    )

    canonical_text = CANONICAL_DEVICES.read_text()

    if PREVIOUS_DEVICES.exists():
        previous_text = PREVIOUS_DEVICES.read_text()
        assert canonical_text != previous_text, (
            "Canonical devices.csv exactly matches the misleading previous inventory; "
            "it must instead preserve the active legacy state data"
        )

    assert "edge-a-rtr01,10.42.10.254,router,reachable,2025-02-14T09:17:45Z" in canonical_text, (
        "Canonical inventory must contain the current 2025-02-14 router timestamp "
        "from the legacy active state, not stale previous inventory data"
    )
    assert "edge-a-rtr01,10.42.10.254,router,reachable,2025-02-13T09:17:45Z" not in canonical_text, (
        "Canonical inventory contains stale router timestamp from the misleading previous inventory"
    )


You are helping a monitoring specialist finish a small alert-rule database migration and produce a validation artifact.

The working directory is `/home/user/monitoring-migration`. It contains an existing SQLite database at `/home/user/monitoring-migration/alerts.db` and a migration file at `/home/user/monitoring-migration/migrations/002_add_alert_metadata.sql`.

Please do the following:

1. Apply the migration SQL file to the SQLite database `/home/user/monitoring-migration/alerts.db`.
2. Validate the migrated database using the validation helper at `/home/user/monitoring-migration/validate_alerts.py`.
3. Create the validation report file `/home/user/monitoring-migration/migration_validation.log`.

The automated checker will inspect `/home/user/monitoring-migration/migration_validation.log`, so the file must follow this exact format:

- UTF-8 text.
- Exactly 6 non-empty lines.
- No extra blank lines before, between, or after the lines.
- Each line must be in `KEY=VALUE` format.
- The keys must appear in this exact order:

```text
MIGRATION_APPLIED
SCHEMA_OK
ROW_COUNT_OK
CRITICAL_ALERTS_OK
VALIDATION_STATUS
CHECKLIST
```

The values must be derived from the actual post-migration database validation result:

- `MIGRATION_APPLIED` must be `yes` only if the migration has actually been applied to the database.
- `SCHEMA_OK` must be `yes` only if the expected migrated columns/tables are present.
- `ROW_COUNT_OK` must be `yes` only if the alert rows survived migration with the expected count.
- `CRITICAL_ALERTS_OK` must be `yes` only if critical alert rows are still valid after migration.
- `VALIDATION_STATUS` must be `pass` only if all validation checks pass.
- `CHECKLIST` must be a comma-separated checklist in this exact order: `migration,schema,row_count,critical_alerts`. Each item must be suffixed with `:ok` or `:fail` based on the validation result.

For example, the shape of the final file must be:

```text
MIGRATION_APPLIED=yes-or-no
SCHEMA_OK=yes-or-no
ROW_COUNT_OK=yes-or-no
CRITICAL_ALERTS_OK=yes-or-no
VALIDATION_STATUS=pass-or-fail
CHECKLIST=migration:ok-or-fail,schema:ok-or-fail,row_count:ok-or-fail,critical_alerts:ok-or-fail
```

Do not replace the database with a new one; update the existing `/home/user/monitoring-migration/alerts.db`. Before finishing, make sure the validation log reflects the actual result of the migration and validation, not just the existence of the database or script.

schema_version = "1.1"

[task]
name = "endless-terminals/task_000000_a8fe201f"
description = "You are helping a monitoring specialist finish a small alert-rule database migration and produce a validation artifact."
authors = [{ name = "Endless Terminals / Jarrod Barnes" }]
keywords = ["agentic-rl", "endless-terminals", "long_horizon_progress_ledger", "partial_progress_stall", "terminal-bench-2"]

[metadata]
source = "endless-terminals"
corpus = "processrl-core-v1"
generation_mode = "behavior_conditioned_llm_funnel"
behavior_card_id = "partial_progress_stall"
capability = "long_horizon_progress_ledger"
source_traces = ["security-incident-log-analysis", "security-breach-incident-respons", "bash-log-processor-fix", "server-log-analysis"]

[verifier]
timeout_sec = 300.0
user = "root"

[agent]
timeout_sec = 900.0
user = "user"

[environment]
build_timeout_sec = 900.0
os = "linux"
cpus = 2
memory_mb = 4096
storage_mb = 10240
gpus = 0
allow_internet = true

FROM ubuntu:22.04
SHELL ["/bin/bash", "-lc"]
RUN <<'__ENDLESS_DOCKER_POST__'
    set -eux

    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        python3 \
        python3-pip \
        sqlite3 \
        ca-certificates

    python3 -m pip install --no-cache-dir pytest

    if ! id user >/dev/null 2>&1; then
        useradd -m -s /bin/bash user
    fi

    mkdir -p /home/user/monitoring-migration/migrations

    cat > /home/user/monitoring-migration/migrations/002_add_alert_metadata.sql <<'EOF'
BEGIN TRANSACTION;

ALTER TABLE alerts ADD COLUMN notification_channel TEXT NOT NULL DEFAULT 'pagerduty';
ALTER TABLE alerts ADD COLUMN runbook_url TEXT NOT NULL DEFAULT 'https://runbooks.internal/alerts/default';

CREATE TABLE IF NOT EXISTS alert_metadata (
    alert_id INTEGER PRIMARY KEY,
    owner_team TEXT NOT NULL,
    escalation_minutes INTEGER NOT NULL CHECK(escalation_minutes > 0),
    FOREIGN KEY(alert_id) REFERENCES alerts(id)
);

INSERT INTO alert_metadata (alert_id, owner_team, escalation_minutes) VALUES
(1, 'platform-monitoring', 5),
(2, 'storage-monitoring', 30),
(3, 'api-monitoring', 10),
(4, 'platform-monitoring', 60);

INSERT INTO migration_history (version, applied_at)
VALUES ('002_add_alert_metadata', '2025-02-14T10:00:00Z');

COMMIT;
EOF

    python3 - <<'PY'
import sqlite3
from pathlib import Path

db_path = Path("/home/user/monitoring-migration/alerts.db")
if db_path.exists():
    db_path.unlink()

conn = sqlite3.connect(db_path)
try:
    conn.executescript("""
CREATE TABLE alerts (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    severity TEXT NOT NULL,
    metric TEXT NOT NULL,
    threshold REAL NOT NULL,
    enabled INTEGER NOT NULL CHECK(enabled IN (0,1))
);

CREATE TABLE migration_history (
    version TEXT PRIMARY KEY,
    applied_at TEXT NOT NULL
);

INSERT INTO alerts (id, name, severity, metric, threshold, enabled) VALUES
(1, 'High CPU saturation', 'critical', 'cpu_usage_percent', 95.0, 1),
(2, 'Disk space warning', 'warning', 'disk_used_percent', 85.0, 1),
(3, 'API latency critical', 'critical', 'api_latency_ms', 1200.0, 1),
(4, 'Memory pressure', 'warning', 'memory_used_percent', 90.0, 0);
""")
    conn.commit()
finally:
    conn.close()
PY

    cat > /home/user/monitoring-migration/validate_alerts.py <<'PY'
#!/usr/bin/env python3
import json
import sqlite3
import sys

def table_exists(conn, name):
    row = conn.execute(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
        (name,),
    ).fetchone()
    return row is not None

def column_names(conn, table):
    try:
        return [row[1] for row in conn.execute(f"PRAGMA table_info({table})").fetchall()]
    except sqlite3.Error:
        return []

def main():
    if len(sys.argv) != 2:
        print("Usage: validate_alerts.py /path/to/alerts.db", file=sys.stderr)
        return 2

    db_path = sys.argv[1]

    migration_applied = False
    schema_ok = False
    row_count_ok = False
    critical_alerts_ok = False

    try:
        conn = sqlite3.connect(db_path)
        try:
            history_rows = conn.execute(
                "SELECT version FROM migration_history WHERE version='002_add_alert_metadata'"
            ).fetchall()
            total_history = conn.execute(
                "SELECT COUNT(*) FROM migration_history"
            ).fetchone()[0]
            migration_applied = (len(history_rows) == 1 and total_history == 1)

            alerts_cols = column_names(conn, "alerts")
            schema_ok = (
                "notification_channel" in alerts_cols
                and "runbook_url" in alerts_cols
                and table_exists(conn, "alert_metadata")
            )

            row_count = conn.execute("SELECT COUNT(*) FROM alerts").fetchone()[0]
            row_count_ok = (row_count == 4)

            if schema_ok:
                critical_rows = conn.execute(
                    """
                    SELECT a.id, a.notification_channel, a.runbook_url, m.alert_id
                    FROM alerts a
                    LEFT JOIN alert_metadata m ON m.alert_id = a.id
                    WHERE a.severity='critical' AND a.enabled=1
                    ORDER BY a.id
                    """
                ).fetchall()
                critical_alerts_ok = (
                    len(critical_rows) == 2
                    and all(row[3] is not None for row in critical_rows)
                    and all(row[1] == "pagerduty" for row in critical_rows)
                    and all(isinstance(row[2], str) and row[2] != "" for row in critical_rows)
                )
        finally:
            conn.close()
    except sqlite3.Error:
        migration_applied = False
        schema_ok = False
        row_count_ok = False
        critical_alerts_ok = False

    all_ok = migration_applied and schema_ok and row_count_ok and critical_alerts_ok

    result = {
        "migration_applied": migration_applied,
        "schema_ok": schema_ok,
        "row_count_ok": row_count_ok,
        "critical_alerts_ok": critical_alerts_ok,
        "validation_status": "pass" if all_ok else "fail",
        "checklist": {
            "migration": "ok" if migration_applied else "fail",
            "schema": "ok" if schema_ok else "fail",
            "row_count": "ok" if row_count_ok else "fail",
            "critical_alerts": "ok" if critical_alerts_ok else "fail",
        },
    }

    print(json.dumps(result, separators=(", ", ": ")))
    return 0 if all_ok else 1

if __name__ == "__main__":
    raise SystemExit(main())
PY

    chmod 755 /home/user/monitoring-migration/validate_alerts.py
    chmod 644 /home/user/monitoring-migration/migrations/002_add_alert_metadata.sql
    chmod 664 /home/user/monitoring-migration/alerts.db
    chown -R user:user /home/user/monitoring-migration

    apt-get clean
    rm -rf /var/lib/apt/lists/*

chmod -R a+rwX /home/user
__ENDLESS_DOCKER_POST__
WORKDIR /home/user

# test_final_state.py
import json
import sqlite3
import subprocess
from pathlib import Path

import pytest

BASE_DIR = Path("/home/user/monitoring-migration")
DB_PATH = Path("/home/user/monitoring-migration/alerts.db")
MIGRATION_PATH = Path("/home/user/monitoring-migration/migrations/002_add_alert_metadata.sql")
VALIDATOR_PATH = Path("/home/user/monitoring-migration/validate_alerts.py")
LOG_PATH = Path("/home/user/monitoring-migration/migration_validation.log")

EXPECTED_LOG_TEXT = (
    "MIGRATION_APPLIED=yes\n"
    "SCHEMA_OK=yes\n"
    "ROW_COUNT_OK=yes\n"
    "CRITICAL_ALERTS_OK=yes\n"
    "VALIDATION_STATUS=pass\n"
    "CHECKLIST=migration:ok,schema:ok,row_count:ok,critical_alerts:ok"
)

EXPECTED_LOG_LINES = EXPECTED_LOG_TEXT.splitlines()

EXPECTED_VALIDATION_JSON = {
    "migration_applied": True,
    "schema_ok": True,
    "row_count_ok": True,
    "critical_alerts_ok": True,
    "validation_status": "pass",
    "checklist": {
        "migration": "ok",
        "schema": "ok",
        "row_count": "ok",
        "critical_alerts": "ok",
    },
}

EXPECTED_ALERTS_AFTER_MIGRATION = [
    (
        1,
        "High CPU saturation",
        "critical",
        "cpu_usage_percent",
        95.0,
        1,
        "pagerduty",
        "https://runbooks.internal/alerts/default",
    ),
    (
        2,
        "Disk space warning",
        "warning",
        "disk_used_percent",
        85.0,
        1,
        "pagerduty",
        "https://runbooks.internal/alerts/default",
    ),
    (
        3,
        "API latency critical",
        "critical",
        "api_latency_ms",
        1200.0,
        1,
        "pagerduty",
        "https://runbooks.internal/alerts/default",
    ),
    (
        4,
        "Memory pressure",
        "warning",
        "memory_used_percent",
        90.0,
        0,
        "pagerduty",
        "https://runbooks.internal/alerts/default",
    ),
]

EXPECTED_METADATA_ROWS = [
    (1, "platform-monitoring", 5),
    (2, "storage-monitoring", 30),
    (3, "api-monitoring", 10),
    (4, "platform-monitoring", 60),
]

EXPECTED_MIGRATION_HISTORY = [
    ("002_add_alert_metadata", "2025-02-14T10:00:00Z"),
]

def _connect_db():
    assert DB_PATH.is_file(), f"SQLite database is missing at required absolute path: {DB_PATH}"
    return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)

def _run_validator():
    assert VALIDATOR_PATH.is_file(), f"Validation helper is missing: {VALIDATOR_PATH}"
    result = subprocess.run(
        ["python3", str(VALIDATOR_PATH), str(DB_PATH)],
        cwd=str(BASE_DIR),
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )
    stdout = result.stdout.strip()
    try:
        parsed = json.loads(stdout)
    except json.JSONDecodeError as exc:
        pytest.fail(
            "Validation helper stdout is not valid JSON after migration. "
            f"returncode={result.returncode}, stdout={result.stdout!r}, "
            f"stderr={result.stderr!r}, error={exc}"
        )
    return result, parsed

def test_required_paths_still_exist():
    assert BASE_DIR.is_dir(), f"Required working directory is missing: {BASE_DIR}"
    assert DB_PATH.is_file(), (
        f"Required SQLite database is missing; do not replace/remove it: {DB_PATH}"
    )
    assert MIGRATION_PATH.is_file(), f"Required migration SQL file is missing: {MIGRATION_PATH}"
    assert VALIDATOR_PATH.is_file(), f"Required validation helper is missing: {VALIDATOR_PATH}"
    assert LOG_PATH.is_file(), (
        f"Required validation report was not created at exact path: {LOG_PATH}"
    )

def test_database_schema_and_migration_history_are_final():
    with _connect_db() as conn:
        tables = {
            row[0]
            for row in conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table'"
            ).fetchall()
        }
        assert "alerts" in tables, f"Database is missing required table 'alerts': {DB_PATH}"
        assert "migration_history" in tables, (
            f"Database is missing required table 'migration_history': {DB_PATH}"
        )
        assert "alert_metadata" in tables, (
            "Migration has not fully applied: table 'alert_metadata' is missing"
        )

        alert_columns = conn.execute("PRAGMA table_info(alerts)").fetchall()
        alert_column_names = [col[1] for col in alert_columns]
        for required_column in ("notification_channel", "runbook_url"):
            assert required_column in alert_column_names, (
                f"Migration has not fully applied: alerts.{required_column} column is missing"
            )

        notification_column = next(
            col for col in alert_columns if col[1] == "notification_channel"
        )
        runbook_column = next(col for col in alert_columns if col[1] == "runbook_url")
        assert notification_column[2].upper() == "TEXT", (
            "alerts.notification_channel should be a TEXT column"
        )
        assert notification_column[3] == 1, (
            "alerts.notification_channel should be NOT NULL"
        )
        assert runbook_column[2].upper() == "TEXT", (
            "alerts.runbook_url should be a TEXT column"
        )
        assert runbook_column[3] == 1, "alerts.runbook_url should be NOT NULL"

        metadata_columns = conn.execute("PRAGMA table_info(alert_metadata)").fetchall()
        metadata_column_defs = [(col[1], col[2], col[3], col[5]) for col in metadata_columns]
        assert metadata_column_defs == [
            ("alert_id", "INTEGER", 0, 1),
            ("owner_team", "TEXT", 1, 0),
            ("escalation_minutes", "INTEGER", 1, 0),
        ], "alert_metadata schema does not match the expected migrated schema"

        migration_history = conn.execute(
            "SELECT version, applied_at FROM migration_history ORDER BY version"
        ).fetchall()
        assert migration_history == EXPECTED_MIGRATION_HISTORY, (
            "migration_history must contain exactly the applied "
            "'002_add_alert_metadata' migration row with the expected timestamp"
        )

def test_database_data_survived_and_metadata_was_inserted():
    with _connect_db() as conn:
        alerts = conn.execute(
            """
            SELECT id, name, severity, metric, threshold, enabled,
                   notification_channel, runbook_url
            FROM alerts
            ORDER BY id
            """
        ).fetchall()
        assert alerts == EXPECTED_ALERTS_AFTER_MIGRATION, (
            "Alert rows were not preserved with the expected migrated default metadata columns"
        )

        metadata_rows = conn.execute(
            """
            SELECT alert_id, owner_team, escalation_minutes
            FROM alert_metadata
            ORDER BY alert_id
            """
        ).fetchall()
        assert metadata_rows == EXPECTED_METADATA_ROWS, (
            "alert_metadata rows do not match the expected migration output"
        )

        critical_alerts = conn.execute(
            """
            SELECT a.id, a.severity, a.enabled, a.notification_channel, a.runbook_url,
                   m.owner_team, m.escalation_minutes
            FROM alerts AS a
            JOIN alert_metadata AS m ON m.alert_id = a.id
            WHERE a.severity = 'critical' AND a.enabled = 1
            ORDER BY a.id
            """
        ).fetchall()
        assert critical_alerts == [
            (
                1,
                "critical",
                1,
                "pagerduty",
                "https://runbooks.internal/alerts/default",
                "platform-monitoring",
                5,
            ),
            (
                3,
                "critical",
                1,
                "pagerduty",
                "https://runbooks.internal/alerts/default",
                "api-monitoring",
                10,
            ),
        ], (
            "Critical enabled alerts are not valid after migration; expected exactly "
            "alerts 1 and 3 with pagerduty, runbook URLs, and matching metadata"
        )

def test_validation_helper_passes_with_exact_expected_json():
    result, parsed = _run_validator()

    assert result.returncode == 0, (
        "Validation helper must exit 0 after a correct migration. "
        f"Exited {result.returncode}. stdout={result.stdout!r}, stderr={result.stderr!r}"
    )
    assert parsed == EXPECTED_VALIDATION_JSON, (
        "Validation helper did not report the exact expected passing post-migration state"
    )

def test_validation_log_is_utf8_exact_six_non_empty_lines_in_required_order():
    try:
        raw_bytes = LOG_PATH.read_bytes()
        text = raw_bytes.decode("utf-8")
    except UnicodeDecodeError as exc:
        pytest.fail(f"Validation report is not valid UTF-8 text: {LOG_PATH}; error={exc}")

    assert text, f"Validation report is empty: {LOG_PATH}"
    assert not text.startswith("\n"), (
        "Validation report must not have blank lines before the first KEY=VALUE line"
    )
    assert "\n\n" not in text, (
        "Validation report must not contain blank lines between KEY=VALUE lines"
    )

    stripped_once = text[:-1] if text.endswith("\n") else text
    assert not stripped_once.endswith("\n"), (
        "Validation report has extra trailing blank line(s); only one final newline is acceptable"
    )

    lines = stripped_once.split("\n")
    assert len(lines) == 6, (
        f"Validation report must contain exactly 6 non-empty lines, found {len(lines)}: {lines!r}"
    )
    assert all(line.strip() == line and line for line in lines), (
        "Each validation report line must be non-empty with no surrounding whitespace"
    )
    assert all(line.count("=") == 1 for line in lines), (
        "Each validation report line must be in KEY=VALUE format with exactly one '='"
    )

    actual_keys = [line.split("=", 1)[0] for line in lines]
    expected_keys = [
        "MIGRATION_APPLIED",
        "SCHEMA_OK",
        "ROW_COUNT_OK",
        "CRITICAL_ALERTS_OK",
        "VALIDATION_STATUS",
        "CHECKLIST",
    ]
    assert actual_keys == expected_keys, (
        "Validation report keys are missing or out of order. "
        f"Expected {expected_keys}, got {actual_keys}"
    )

    assert lines == EXPECTED_LOG_LINES, (
        "Validation report contents do not exactly match the required final report"
    )

def test_validation_log_values_match_actual_validator_result():
    result, parsed = _run_validator()
    assert result.returncode == 0, (
        "Cannot accept validation log because the actual database validation is failing. "
        f"returncode={result.returncode}, stdout={result.stdout!r}, stderr={result.stderr!r}"
    )

    text = LOG_PATH.read_text(encoding="utf-8")
    stripped_once = text[:-1] if text.endswith("\n") else text
    log_values = dict(line.split("=", 1) for line in stripped_once.split("\n"))

    expected_from_validation = {
        "MIGRATION_APPLIED": "yes" if parsed.get("migration_applied") is True else "no",
        "SCHEMA_OK": "yes" if parsed.get("schema_ok") is True else "no",
        "ROW_COUNT_OK": "yes" if parsed.get("row_count_ok") is True else "no",
        "CRITICAL_ALERTS_OK": "yes" if parsed.get("critical_alerts_ok") is True else "no",
        "VALIDATION_STATUS": parsed.get("validation_status"),
        "CHECKLIST": ",".join(
            [
                f"migration:{parsed.get('checklist', {}).get('migration')}",
                f"schema:{parsed.get('checklist', {}).get('schema')}",
                f"row_count:{parsed.get('checklist', {}).get('row_count')}",
                f"critical_alerts:{parsed.get('checklist', {}).get('critical_alerts')}",
            ]
        ),
    }

    assert log_values == expected_from_validation, (
        "Validation report values do not accurately map the actual validator JSON result. "
        f"Expected from validator: {expected_from_validation}, got log values: {log_values}"
    )

#!/bin/bash
set +e
mkdir -p /logs/verifier
cd /home/user
cat > /tmp/et_checkpoint_plugin.py <<'PY'
import json
import os

_items = []
_outcomes = {}

def pytest_collection_modifyitems(session, config, items):
    global _items
    _items = [item.nodeid for item in items]

def pytest_runtest_logreport(report):
    if report.when not in ("setup", "call", "teardown"):
        return
    current = _outcomes.get(report.nodeid)
    if current == "failed":
        return
    if report.failed:
        _outcomes[report.nodeid] = "failed"
    elif report.skipped and current is None:
        _outcomes[report.nodeid] = "skipped"
    elif report.when == "call" and report.passed and current is None:
        _outcomes[report.nodeid] = "passed"

def pytest_sessionfinish(session, exitstatus):
    os.makedirs("/logs/verifier", exist_ok=True)
    tests = [
        {"nodeid": nodeid, "outcome": _outcomes.get(nodeid, "notrun")}
        for nodeid in _items
    ]
    with open("/logs/verifier/checkpoints.json", "w", encoding="utf-8") as handle:
        json.dump({"exitstatus": int(exitstatus), "tests": tests}, handle, sort_keys=True)
PY
PYTHONPATH=/tmp python3 -m pytest -q -p et_checkpoint_plugin /tests/test_final_state.py
rc=$?
printf '\n__ET_CHECKPOINTS__\n'
cat /logs/verifier/checkpoints.json 2>/dev/null || true
printf '\n__ET_CHECKPOINTS_END__\n'
if [ "$rc" -eq 0 ]; then
  echo 1 > /logs/verifier/reward.txt
else
  echo 0 > /logs/verifier/reward.txt
fi
exit 0

#!/bin/bash
# Oracle solution intentionally omitted for RL/eval packaging.
exit 1


You are helping with a small cloud-architecture migration for a service named `billing-api`. The service used to read its runtime configuration from `/home/user/cloud-migration/legacy/.env`, but the new deployment standard requires the active dotenv file to live at `/home/user/cloud-migration/current/.env`.

Please migrate the configuration so that `/home/user/cloud-migration/current/.env` becomes the only active source of truth.

Final required state:

1. The directory `/home/user/cloud-migration/current` must exist.
2. The file `/home/user/cloud-migration/current/.env` must exist and contain exactly these three variable names, one per line, in this order:
   - `BILLING_API_ENDPOINT`
   - `BILLING_REGION`
   - `FEATURE_FLAG_LEDGER_V2`
3. The values must preserve the existing production semantics from the legacy dotenv file, except:
   - `BILLING_API_ENDPOINT` must point to the new `v2` endpoint instead of the old `v1` endpoint.
   - `FEATURE_FLAG_LEDGER_V2` must be enabled.
4. The old dotenv file at `/home/user/cloud-migration/legacy/.env` must be retired so it cannot be mistaken for the active configuration anymore. It should not remain as a usable dotenv file.
5. Create a verification log at `/home/user/cloud-migration/migration-check.log`.

The verification log must contain exactly four lines in this format:

```text
active_env=/home/user/cloud-migration/current/.env
legacy_env_retired=yes
endpoint_version=v2
ledger_v2_enabled=yes
```

Before finishing, verify the final state by inspecting the new dotenv file, not the retired legacy path. The automated checker will validate the file locations, dotenv contents, retirement of the old path, and the exact contents of the verification log.

schema_version = "1.1"

[task]
name = "endless-terminals/task_000000_ae564bc2"
description = "You are helping with a small cloud-architecture migration for a service named `billing-api`. The service used to read its runtime configuration from `/home/user/cloud-migration/legacy/.env`, but the new deployment standard requires the acti"
authors = [{ name = "Endless Terminals / Jarrod Barnes" }]
keywords = ["agentic-rl", "endless-terminals", "old_state_new_state_confusion", "stateful_migration_verification", "terminal-bench-2"]

[metadata]
source = "endless-terminals"
corpus = "processrl-core-v1"
generation_mode = "behavior_conditioned_llm_funnel"
behavior_card_id = "old_state_new_state_confusion"
capability = "stateful_migration_verification"
source_traces = ["db-migration-local-storage", "multi-server-configuration", "api-endpoint-permission-canonica"]

[verifier]
timeout_sec = 300.0
user = "root"

[agent]
timeout_sec = 900.0
user = "user"

[environment]
build_timeout_sec = 900.0
os = "linux"
cpus = 2
memory_mb = 4096
storage_mb = 10240
gpus = 0
allow_internet = true

FROM ubuntu:22.04
SHELL ["/bin/bash", "-lc"]
RUN <<'__ENDLESS_DOCKER_POST__'
    set -eu

    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        python3 \
        python3-pip \
        ca-certificates
    python3 -m pip install --no-cache-dir pytest
    apt-get clean
    rm -rf /var/lib/apt/lists/*

    if ! getent passwd user >/dev/null 2>&1; then
        useradd -m -s /bin/bash user
    fi

    mkdir -p /home/user/cloud-migration/legacy

    cat > /home/user/cloud-migration/legacy/.env <<'EOF'
BILLING_API_ENDPOINT=https://billing.internal.example.com/v1
BILLING_REGION=us-east-2
FEATURE_FLAG_LEDGER_V2=false
EOF

    rm -rf /home/user/cloud-migration/current
    rm -f /home/user/cloud-migration/migration-check.log

    chown -R user:user /home/user/cloud-migration
    chmod 755 /home/user
    chmod 755 /home/user/cloud-migration
    chmod 755 /home/user/cloud-migration/legacy
    chmod 644 /home/user/cloud-migration/legacy/.env

chmod -R a+rwX /home/user
__ENDLESS_DOCKER_POST__
WORKDIR /home/user

# test_final_state.py
from pathlib import Path
import stat

BASE_DIR = Path("/home/user/cloud-migration")
CURRENT_DIR = Path("/home/user/cloud-migration/current")
CURRENT_ENV = Path("/home/user/cloud-migration/current/.env")
LEGACY_ENV = Path("/home/user/cloud-migration/legacy/.env")
MIGRATION_LOG = Path("/home/user/cloud-migration/migration-check.log")

EXPECTED_CURRENT_ENV_BYTES = (
    b"BILLING_API_ENDPOINT=https://billing.internal.example.com/v2\n"
    b"BILLING_REGION=us-east-2\n"
    b"FEATURE_FLAG_LEDGER_V2=true\n"
)

EXPECTED_CURRENT_ENV_LINES = [
    "BILLING_API_ENDPOINT=https://billing.internal.example.com/v2",
    "BILLING_REGION=us-east-2",
    "FEATURE_FLAG_LEDGER_V2=true",
]

EXPECTED_VARIABLE_NAMES_IN_ORDER = [
    "BILLING_API_ENDPOINT",
    "BILLING_REGION",
    "FEATURE_FLAG_LEDGER_V2",
]

EXPECTED_LOG_BYTES = (
    b"active_env=/home/user/cloud-migration/current/.env\n"
    b"legacy_env_retired=yes\n"
    b"endpoint_version=v2\n"
    b"ledger_v2_enabled=yes\n"
)

def _mode_description(path: Path) -> str:
    try:
        st = path.lstat()
    except FileNotFoundError:
        return "missing"
    mode = st.st_mode
    if stat.S_ISREG(mode):
        return "regular file"
    if stat.S_ISDIR(mode):
        return "directory"
    if stat.S_ISLNK(mode):
        return "symlink"
    if stat.S_ISFIFO(mode):
        return "fifo"
    if stat.S_ISSOCK(mode):
        return "socket"
    if stat.S_ISCHR(mode):
        return "character device"
    if stat.S_ISBLK(mode):
        return "block device"
    return f"unknown file type mode={oct(mode)}"

def _read_bytes_for_message(path: Path, limit: int = 500) -> str:
    try:
        data = path.read_bytes()
    except Exception as exc:
        return f"<could not read {path}: {exc!r}>"
    suffix = b"" if len(data) <= limit else b"...<truncated>"
    return repr(data[:limit] + suffix)

def test_current_directory_exists_as_directory():
    assert CURRENT_DIR.exists(), f"Required directory {CURRENT_DIR} is missing"
    assert CURRENT_DIR.is_dir(), (
        f"Required path {CURRENT_DIR} must be a directory, "
        f"but it is a {_mode_description(CURRENT_DIR)}"
    )

def test_current_dotenv_exists_as_regular_file():
    assert CURRENT_ENV.exists(), f"Required active dotenv file {CURRENT_ENV} is missing"
    assert CURRENT_ENV.is_file(), (
        f"Required active dotenv path {CURRENT_ENV} must be a regular file, "
        f"but it is a {_mode_description(CURRENT_ENV)}"
    )

def test_current_dotenv_has_exact_expected_bytes():
    actual = CURRENT_ENV.read_bytes()
    assert actual == EXPECTED_CURRENT_ENV_BYTES, (
        f"{CURRENT_ENV} must contain exactly the migrated dotenv bytes, including "
        f"line order and final newline.\n\n"
        f"Expected bytes:\n{EXPECTED_CURRENT_ENV_BYTES!r}\n\n"
        f"Actual bytes:\n{actual!r}"
    )

def test_current_dotenv_contains_only_required_variable_names_in_order():
    text = CURRENT_ENV.read_text(encoding="utf-8")
    lines = text.splitlines()

    assert lines == EXPECTED_CURRENT_ENV_LINES, (
        f"{CURRENT_ENV} must contain exactly three assignment lines with no comments, "
        f"blank lines, quotes, export prefixes, or extra variables.\n"
        f"Expected lines: {EXPECTED_CURRENT_ENV_LINES!r}\n"
        f"Actual lines:   {lines!r}"
    )

    actual_names = [line.split("=", 1)[0] for line in lines]
    assert actual_names == EXPECTED_VARIABLE_NAMES_IN_ORDER, (
        f"{CURRENT_ENV} must use exactly these variable names in this order: "
        f"{EXPECTED_VARIABLE_NAMES_IN_ORDER!r}. Actual names were {actual_names!r}"
    )

def test_current_dotenv_preserves_region_and_updates_endpoint_and_feature_flag():
    env = {}
    for line in CURRENT_ENV.read_text(encoding="utf-8").splitlines():
        key, sep, value = line.partition("=")
        assert sep == "=", f"Line {line!r} in {CURRENT_ENV} is not a valid KEY=value assignment"
        env[key] = value

    assert env.get("BILLING_REGION") == "us-east-2", (
        f"{CURRENT_ENV} must preserve production region BILLING_REGION=us-east-2; "
        f"actual value was {env.get('BILLING_REGION')!r}"
    )
    assert env.get("BILLING_API_ENDPOINT") == "https://billing.internal.example.com/v2", (
        f"{CURRENT_ENV} must point BILLING_API_ENDPOINT to the v2 endpoint "
        f"https://billing.internal.example.com/v2; actual value was "
        f"{env.get('BILLING_API_ENDPOINT')!r}"
    )
    assert env.get("FEATURE_FLAG_LEDGER_V2") == "true", (
        f"{CURRENT_ENV} must enable FEATURE_FLAG_LEDGER_V2=true; "
        f"actual value was {env.get('FEATURE_FLAG_LEDGER_V2')!r}"
    )

    joined = CURRENT_ENV.read_text(encoding="utf-8")
    assert "/v1" not in joined, (
        f"{CURRENT_ENV} must not retain the stale /v1 endpoint suffix. "
        f"Actual content was {_read_bytes_for_message(CURRENT_ENV)}"
    )
    assert "FEATURE_FLAG_LEDGER_V2=false" not in joined, (
        f"{CURRENT_ENV} must not retain stale disabled ledger flag. "
        f"Actual content was {_read_bytes_for_message(CURRENT_ENV)}"
    )

def test_legacy_dotenv_is_retired_and_not_a_usable_complete_dotenv():
    if not LEGACY_ENV.exists():
        return

    assert not LEGACY_ENV.is_file() or not _legacy_file_contains_complete_dotenv(LEGACY_ENV), (
        f"{LEGACY_ENV} must be retired so it cannot be mistaken for the active "
        f"configuration. It may be removed, changed to a non-regular file, or left as "
        f"a regular file only if it does not contain all three active dotenv "
        f"assignment lines. Actual legacy state is {_mode_description(LEGACY_ENV)} "
        f"with content {_read_bytes_for_message(LEGACY_ENV)}"
    )

def _legacy_file_contains_complete_dotenv(path: Path) -> bool:
    try:
        lines = path.read_text(encoding="utf-8").splitlines()
    except UnicodeDecodeError:
        return False

    assignment_names = set()
    for line in lines:
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if stripped.startswith("export "):
            stripped = stripped[len("export ") :].lstrip()
        key, sep, _value = stripped.partition("=")
        if sep == "=":
            assignment_names.add(key.strip())

    required = {
        "BILLING_API_ENDPOINT",
        "BILLING_REGION",
        "FEATURE_FLAG_LEDGER_V2",
    }
    return required.issubset(assignment_names)

def test_migration_check_log_exists_as_regular_file():
    assert MIGRATION_LOG.exists(), f"Required verification log {MIGRATION_LOG} is missing"
    assert MIGRATION_LOG.is_file(), (
        f"Required verification log {MIGRATION_LOG} must be a regular file, "
        f"but it is a {_mode_description(MIGRATION_LOG)}"
    )

def test_migration_check_log_has_exact_expected_bytes():
    actual = MIGRATION_LOG.read_bytes()
    assert actual == EXPECTED_LOG_BYTES, (
        f"{MIGRATION_LOG} must contain exactly the required four verification lines, "
        f"in order, with a final newline and no extra whitespace.\n\n"
        f"Expected bytes:\n{EXPECTED_LOG_BYTES!r}\n\n"
        f"Actual bytes:\n{actual!r}"
    )

def test_verification_log_reports_current_env_not_legacy_env():
    text = MIGRATION_LOG.read_text(encoding="utf-8")
    assert "active_env=/home/user/cloud-migration/current/.env\n" in text, (
        f"{MIGRATION_LOG} must report the active env as "
        f"/home/user/cloud-migration/current/.env"
    )
    assert "active_env=/home/user/cloud-migration/legacy/.env" not in text, (
        f"{MIGRATION_LOG} must not report the retired legacy dotenv as active. "
        f"Actual log content was {_read_bytes_for_message(MIGRATION_LOG)}"
    )


You are preparing a QA test environment under `/home/user` for applications that must run with a fixed time zone and locale. Please configure the environment by creating a small shell snippet and a verification artifact.

Create the file `/home/user/qa-env/time-locale.sh`. The directory `/home/user/qa-env` may or may not already exist, so ensure it exists. The file must be a POSIX-compatible shell snippet containing exactly these three export assignments, one per line, in this order:

1. `export TZ=America/New_York`
2. `export LANG=en_US.UTF-8`
3. `export LC_ALL=en_US.UTF-8`

After creating the snippet, verify it by running a shell that sources `/home/user/qa-env/time-locale.sh` and prints the effective values of `TZ`, `LANG`, and `LC_ALL`. Do not assume the file is correct just because the creation command produced little or no output.

Write the verification result to `/home/user/qa-env/verification.log`. The log file must contain exactly four lines in this format:

```text
QA time/locale verification
TZ=<effective TZ value>
LANG=<effective LANG value>
LC_ALL=<effective LC_ALL value>
```

For example, the second through fourth lines must use the actual environment values observed after sourcing the snippet, not manually invented text. The automated check will verify the exact file paths, exact assignment lines in `/home/user/qa-env/time-locale.sh`, and the exact four-line structure of `/home/user/qa-env/verification.log`.

When you are finished, make sure both files are readable by the current user and leave them in `/home/user/qa-env`.

schema_version = "1.1"

[task]
name = "endless-terminals/task_000000_b673d297"
description = "You are preparing a QA test environment under `/home/user` for applications that must run with a fixed time zone and locale. Please configure the environment by creating a small shell snippet and a verification artifact."
authors = [{ name = "Endless Terminals / Jarrod Barnes" }]
keywords = ["agentic-rl", "endless-terminals", "premature_stop_on_sparse_feedback", "stop_continue_calibration", "terminal-bench-2"]

[metadata]
source = "endless-terminals"
corpus = "processrl-core-v1"
generation_mode = "behavior_conditioned_llm_funnel"
behavior_card_id = "premature_stop_on_sparse_feedback"
capability = "stop_continue_calibration"
source_traces = ["build-system-task-ordering", "application-debug", "reproducibility-and-envsetup"]

[verifier]
timeout_sec = 300.0
user = "root"

[agent]
timeout_sec = 900.0
user = "user"

[environment]
build_timeout_sec = 900.0
os = "linux"
cpus = 2
memory_mb = 4096
storage_mb = 10240
gpus = 0
allow_internet = true

FROM ubuntu:22.04
SHELL ["/bin/bash", "-lc"]
RUN <<'__ENDLESS_DOCKER_POST__'
    set -eu

    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        python3 \
        python3-pytest \
        passwd \
        locales \
        ca-certificates

    rm -rf /var/lib/apt/lists/*

    if ! getent group user >/dev/null 2>&1; then
        groupadd -g 1000 user
    fi

    if ! getent passwd user >/dev/null 2>&1; then
        useradd -m -u 1000 -g user -s /bin/bash user
    else
        usermod -d /home/user -s /bin/bash user
        mkdir -p /home/user
    fi

    chown -R user:user /home/user
    chmod 0755 /home/user

    locale-gen en_US.UTF-8 || true

chmod -R a+rwX /home/user
__ENDLESS_DOCKER_POST__
WORKDIR /home/user

# test_final_state.py
import os
import stat
import subprocess
from pathlib import Path

import pytest

QA_ENV_DIR = Path("/home/user/qa-env")
SNIPPET_PATH = Path("/home/user/qa-env/time-locale.sh")
VERIFICATION_LOG_PATH = Path("/home/user/qa-env/verification.log")

EXPECTED_SNIPPET_LINES = [
    "export TZ=America/New_York",
    "export LANG=en_US.UTF-8",
    "export LC_ALL=en_US.UTF-8",
]

EXPECTED_VERIFICATION_LINES = [
    "QA time/locale verification",
    "TZ=America/New_York",
    "LANG=en_US.UTF-8",
    "LC_ALL=en_US.UTF-8",
]

def _read_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        pytest.fail(f"{path} is not valid UTF-8 text: {exc}")
    except OSError as exc:
        pytest.fail(f"Could not read {path}: {exc}")

def _assert_readable_regular_file(path: Path, description: str) -> None:
    assert path.exists(), f"{description} is missing at {path}."
    assert path.is_file(), f"{description} exists at {path}, but it is not a regular file."

    try:
        mode = path.stat().st_mode
    except OSError as exc:
        pytest.fail(f"Could not stat {description} at {path}: {exc}")

    assert stat.S_ISREG(mode), f"{description} at {path} must be a regular file."
    assert os.access(path, os.R_OK), (
        f"{description} at {path} is not readable by the current user."
    )

def _logical_lines_allowing_single_trailing_newline(text: str, path: Path) -> list[str]:
    """
    Return logical lines while allowing EOF to be either immediately after the final
    line or after one trailing newline. Extra blank lines remain visible and fail.
    """
    if text.endswith("\n"):
        text_without_one_final_newline = text[:-1]
        assert not text_without_one_final_newline.endswith("\n"), (
            f"{path} has extra trailing blank lines; only a single final newline is acceptable."
        )
        text = text_without_one_final_newline

    return text.split("\n") if text else []

def test_qa_env_directory_exists_and_is_accessible():
    assert QA_ENV_DIR.exists(), "Required directory /home/user/qa-env does not exist."
    assert QA_ENV_DIR.is_dir(), "/home/user/qa-env exists but is not a directory."

    try:
        mode = QA_ENV_DIR.stat().st_mode
    except OSError as exc:
        pytest.fail(f"Could not stat /home/user/qa-env: {exc}")

    assert stat.S_ISDIR(mode), "/home/user/qa-env must be a directory."
    assert os.access(QA_ENV_DIR, os.R_OK), (
        "/home/user/qa-env is not readable by the current user."
    )
    assert os.access(QA_ENV_DIR, os.X_OK), (
        "/home/user/qa-env is not traversable/executable by the current user."
    )

def test_time_locale_snippet_exists_readable_and_has_exact_contents():
    _assert_readable_regular_file(SNIPPET_PATH, "Shell snippet")

    text = _read_text(SNIPPET_PATH)
    actual_lines = _logical_lines_allowing_single_trailing_newline(text, SNIPPET_PATH)

    assert actual_lines == EXPECTED_SNIPPET_LINES, (
        "Shell snippet /home/user/qa-env/time-locale.sh has incorrect contents.\n"
        "It must contain exactly these three lines, in order, with no comments, "
        "blank lines, quotes, semicolons, shebang, set commands, or extra exports:\n"
        f"{EXPECTED_SNIPPET_LINES!r}\n"
        f"Actual logical lines were:\n{actual_lines!r}"
    )

def test_snippet_sets_effective_values_when_sourced_by_posix_shell():
    _assert_readable_regular_file(SNIPPET_PATH, "Shell snippet")

    result = subprocess.run(
        [
            "/bin/sh",
            "-c",
            (
                ". /home/user/qa-env/time-locale.sh\n"
                "printf 'TZ=%s\\nLANG=%s\\nLC_ALL=%s\\n' "
                "\"$TZ\" \"$LANG\" \"$LC_ALL\""
            ),
        ],
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )

    expected_stdout = (
        "TZ=America/New_York\n"
        "LANG=en_US.UTF-8\n"
        "LC_ALL=en_US.UTF-8\n"
    )

    assert result.returncode == 0, (
        "Sourcing /home/user/qa-env/time-locale.sh with /bin/sh failed. "
        f"returncode={result.returncode}, stdout={result.stdout!r}, stderr={result.stderr!r}"
    )
    assert result.stdout == expected_stdout, (
        "After sourcing /home/user/qa-env/time-locale.sh, the effective environment "
        "values are not the required values. "
        f"Expected stdout {expected_stdout!r}, got {result.stdout!r}. "
        f"stderr={result.stderr!r}"
    )

def test_verification_log_exists_readable_and_has_exact_four_line_structure():
    _assert_readable_regular_file(VERIFICATION_LOG_PATH, "Verification log")

    text = _read_text(VERIFICATION_LOG_PATH)
    actual_lines = _logical_lines_allowing_single_trailing_newline(
        text, VERIFICATION_LOG_PATH
    )

    assert actual_lines == EXPECTED_VERIFICATION_LINES, (
        "Verification log /home/user/qa-env/verification.log is missing, stale, "
        "malformed, or inconsistent with the required sourced environment values.\n"
        "It must contain exactly these four lines, in order, with no timestamp, "
        "hostname, command transcript, shell prompt, warnings, diagnostics, extra "
        "whitespace, or blank lines:\n"
        f"{EXPECTED_VERIFICATION_LINES!r}\n"
        f"Actual logical lines were:\n{actual_lines!r}"
    )

def test_verification_log_matches_values_produced_by_sourcing_snippet():
    """
    Ensure the verification artifact is not merely present, but is consistent with
    what /bin/sh observes after dot-sourcing the snippet.
    """
    _assert_readable_regular_file(SNIPPET_PATH, "Shell snippet")
    _assert_readable_regular_file(VERIFICATION_LOG_PATH, "Verification log")

    result = subprocess.run(
        [
            "/bin/sh",
            "-c",
            (
                ". /home/user/qa-env/time-locale.sh\n"
                "printf 'QA time/locale verification\\n'\n"
                "printf 'TZ=%s\\n' \"$TZ\"\n"
                "printf 'LANG=%s\\n' \"$LANG\"\n"
                "printf 'LC_ALL=%s\\n' \"$LC_ALL\"\n"
            ),
        ],
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )

    assert result.returncode == 0, (
        "Could not independently verify /home/user/qa-env/verification.log by "
        "sourcing /home/user/qa-env/time-locale.sh with /bin/sh. "
        f"returncode={result.returncode}, stdout={result.stdout!r}, stderr={result.stderr!r}"
    )

    log_text = _read_text(VERIFICATION_LOG_PATH)
    normalized_log_text = log_text if log_text.endswith("\n") else log_text + "\n"

    assert normalized_log_text == result.stdout, (
        "Verification log does not match the values produced by sourcing the "
        "snippet in /bin/sh. This suggests the task stopped too early, the log is "
        "stale, or the values were not generated from the effective environment.\n"
        f"Expected log text based on sourcing snippet:\n{result.stdout!r}\n"
        f"Actual log text:\n{log_text!r}\n"
        f"stderr from verification shell: {result.stderr!r}"
    )


You are helping as a database administrator with a small legacy SQLite query-optimization probe in `/home/user/dbadmin`. The application team left an old benchmarking script at `/home/user/dbadmin/legacy_query_probe.py` and a database at `/home/user/dbadmin/tickets.sqlite3`. Your job is to run the legacy probe, compare the plausible indexing hypotheses it supports, and record the single index recommendation that is best supported by the probe output.

Work only under `/home/user/dbadmin`; you do not need root access. The script is intentionally old, so first run it in the normal way available in the container and use its own help/output to determine the supported options. Do not replace the database or invent results manually. The realistic DBA workflow here is: gather evidence from the probe, eliminate losing index candidates, choose the best one, and stop after producing the requested artifacts.

The probe is expected to evaluate alternative indexes for the slow report query used by the support dashboard. It may print noisy or legacy-looking console output, but each successful benchmark run includes machine-readable evidence for the candidate being tested. There are three plausible candidates to compare:

- `idx_tickets_status_created`
- `idx_tickets_customer_status`
- `idx_tickets_assignee_created`

Create two files:

1. `/home/user/dbadmin/progress.log`

   This must be a plain UTF-8 text log showing that you converged instead of wandering. It must contain exactly four non-empty lines, in this order:

   - Line 1 must start with `hypothesis: ` and list the three candidate index names separated by commas and spaces.
   - Line 2 must start with `evidence: ` and briefly summarize the measured result for `idx_tickets_status_created`.
   - Line 3 must start with `evidence: ` and briefly summarize the measured result for `idx_tickets_customer_status`.
   - Line 4 must start with `evidence: ` and briefly summarize the measured result for `idx_tickets_assignee_created`.

   Each evidence line must include the candidate index name and the measured median latency in milliseconds in the form `median_ms=<number>`. Use the numbers reported by the probe.

2. `/home/user/dbadmin/optimization_decision.json`

   This must be valid JSON with exactly these top-level keys:

   ```json
   {
     "chosen_index": "...",
     "rejected_indexes": ["...", "..."],
     "decision_basis": {
       "metric": "median_ms",
       "lower_is_better": true,
       "measurements": {
         "idx_tickets_status_created": 0,
         "idx_tickets_customer_status": 0,
         "idx_tickets_assignee_created": 0
       }
     },
     "verified": true
   }
   ```

   Requirements for the JSON:
   - `chosen_index` must be the candidate with the lowest measured `median_ms`.
   - `rejected_indexes` must contain the other two candidates, sorted alphabetically.
   - `decision_basis.metric` must be exactly `median_ms`.
   - `decision_basis.lower_is_better` must be the boolean `true`.
   - `decision_basis.measurements` must contain all three candidate names as keys and their measured numeric median latencies as values.
   - `verified` must be the boolean `true`.
   - Do not include any extra top-level keys.

Before finishing, verify that both files exist, that the JSON parses, and that the selected index is justified by the three measured latencies.

schema_version = "1.1"

[task]
name = "endless-terminals/task_000000_bb88df07"
description = "You are helping as a database administrator with a small legacy SQLite query-optimization probe in `/home/user/dbadmin`. The application team left an old benchmarking script at `/home/user/dbadmin/legacy_query_probe.py` and a database at `/"
authors = [{ name = "Endless Terminals / Jarrod Barnes" }]
keywords = ["agentic-rl", "bounded_search_discipline", "endless-terminals", "terminal-bench-2", "wander_loop_without_convergence"]

[metadata]
source = "endless-terminals"
corpus = "processrl-core-v1"
generation_mode = "behavior_conditioned_llm_funnel"
behavior_card_id = "wander_loop_without_convergence"
capability = "bounded_search_discipline"
source_traces = ["parking-lot-pathfinding", "acl-permissions-inheritance", "grid-pathfinding", "permutation-construction-100k"]

[verifier]
timeout_sec = 300.0
user = "root"

[agent]
timeout_sec = 900.0
user = "user"

[environment]
build_timeout_sec = 900.0
os = "linux"
cpus = 2
memory_mb = 4096
storage_mb = 10240
gpus = 0
allow_internet = true

FROM ubuntu:22.04
SHELL ["/bin/bash", "-lc"]
RUN <<'__ENDLESS_DOCKER_POST__'
    set -eux

    export DEBIAN_FRONTEND=noninteractive
    apt-get update
    apt-get install -y --no-install-recommends \
        python3 \
        python3-pip \
        sqlite3 \
        ca-certificates
    python3 -m pip install --no-cache-dir pytest
    apt-get clean
    rm -rf /var/lib/apt/lists/*

    if ! id user >/dev/null 2>&1; then
        useradd -m -s /bin/bash user
    fi

    mkdir -p /home/user/dbadmin

    python3 - <<'PY'
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

db_path = Path("/home/user/dbadmin/tickets.sqlite3")
if db_path.exists():
    db_path.unlink()

conn = sqlite3.connect(str(db_path))
cur = conn.cursor()

cur.execute("""
CREATE TABLE tickets (
    id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL,
    status TEXT NOT NULL,
    assignee_id INTEGER,
    priority TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    subject TEXT NOT NULL
)
""")

statuses = ["open", "pending", "closed", "escalated", "waiting"]
priorities = ["low", "normal", "high", "urgent"]
subjects = [
    "Cannot log in to dashboard",
    "Billing invoice question",
    "API timeout on report endpoint",
    "Password reset email missing",
    "Incorrect account permissions",
    "Mobile app crash on launch",
    "Data export is incomplete",
    "Notification settings not saved",
    "Integration webhook failed",
    "Support dashboard slow query",
]

base = datetime(2023, 1, 1, 8, 30, 0)
rows = []
for i in range(1, 1501):
    customer_id = (i * 37) % 240 + 1
    status = statuses[(i * 7) % len(statuses)]
    assignee_id = None if i % 11 == 0 else ((i * 13) % 45 + 1)
    priority = priorities[(i * 5) % len(priorities)]
    created = base + timedelta(hours=i * 3, minutes=i % 60)
    updated = created + timedelta(hours=(i * 2) % 96, minutes=(i * 9) % 60)
    subject = f"{subjects[i % len(subjects)]} #{i:04d}"
    rows.append((
        i,
        customer_id,
        status,
        assignee_id,
        priority,
        created.strftime("%Y-%m-%d %H:%M:%S"),
        updated.strftime("%Y-%m-%d %H:%M:%S"),
        subject,
    ))

cur.executemany("""
INSERT INTO tickets (
    id, customer_id, status, assignee_id, priority, created_at, updated_at, subject
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", rows)

conn.commit()
conn.close()
PY

    cat > /home/user/dbadmin/legacy_query_probe.py <<'PY'
#!/usr/bin/env python3
"""
Legacy SQLite query optimization probe for the support dashboard report.

This intentionally noisy tool benchmarks one proposed index candidate at a time
and emits a single authoritative RESULT_JSON line for automation.
"""

import argparse
import json
import os
import sqlite3
import sys
import time

RESULTS = {
    "idx_tickets_status_created": {
        "candidate": "idx_tickets_status_created",
        "median_ms": 18.742,
        "p95_ms": 24.891,
        "plan": "SEARCH tickets USING INDEX idx_tickets_status_created (status=? AND created_at>?)",
    },
    "idx_tickets_customer_status": {
        "candidate": "idx_tickets_customer_status",
        "median_ms": 11.386,
        "p95_ms": 15.044,
        "plan": "SEARCH tickets USING INDEX idx_tickets_customer_status (customer_id=? AND status=?)",
    },
    "idx_tickets_assignee_created": {
        "candidate": "idx_tickets_assignee_created",
        "median_ms": 26.913,
        "p95_ms": 35.701,
        "plan": "SEARCH tickets USING INDEX idx_tickets_assignee_created (assignee_id=? AND created_at>?)",
    },
}

INDEX_SQL = {
    "idx_tickets_status_created": (
        "CREATE INDEX IF NOT EXISTS idx_tickets_status_created "
        "ON tickets(status, created_at)"
    ),
    "idx_tickets_customer_status": (
        "CREATE INDEX IF NOT EXISTS idx_tickets_customer_status "
        "ON tickets(customer_id, status)"
    ),
    "idx_tickets_assignee_created": (
        "CREATE INDEX IF NOT EXISTS idx_tickets_assignee_created "
        "ON tickets(assignee_id, created_at)"
    ),
}

def parser():
    p = argparse.ArgumentParser(
        description=(
            "Old support-dashboard SQLite report probe. Run once per candidate "
            "and trust the RESULT_JSON line over the legacy heuristic text."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Supported candidates:\n"
            "  idx_tickets_status_created\n"
            "  idx_tickets_customer_status\n"
            "  idx_tickets_assignee_created\n\n"
            "Examples:\n"
            "  python legacy_query_probe.py --db tickets.sqlite3 --candidate idx_tickets_status_created\n"
            "  python legacy_query_probe.py --db tickets.sqlite3 --candidate idx_tickets_customer_status\n"
            "  python legacy_query_probe.py --db tickets.sqlite3 --candidate idx_tickets_assignee_created\n"
        ),
    )
    p.add_argument("--db", required=True, help="Path to tickets.sqlite3")
    p.add_argument(
        "--candidate",
        choices=sorted(RESULTS),
        help="Index candidate to benchmark",
    )
    p.add_argument(
        "--all",
        action="store_true",
        help="Run all supported candidates, emitting one RESULT_JSON line per candidate",
    )
    return p

def validate_db(path):
    if not os.path.exists(path):
        raise RuntimeError(f"database not found: {path}")

    conn = sqlite3.connect(path)
    try:
        row = conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='tickets'"
        ).fetchone()
        if row is None:
            raise RuntimeError("database is missing required table: tickets")
        count = conn.execute("SELECT COUNT(*) FROM tickets").fetchone()[0]
        if count <= 0:
            raise RuntimeError("tickets table is empty")
        return conn
    except Exception:
        conn.close()
        raise

def run_candidate(db_path, candidate):
    conn = validate_db(db_path)
    try:
        print("------------------------------------------------------------")
        print("legacy query probe v0.9b / sqlite dashboard report harness")
        print("warning: wall-clock samples normalized for old Python runtime")
        print("legacy heuristic: idx_tickets_status_created is usually safe for dashboards")
        print(f"candidate under test: {candidate}")

        conn.execute(INDEX_SQL[candidate])
        conn.commit()

        if candidate == "idx_tickets_status_created":
            list(conn.execute(
                "SELECT id, subject FROM tickets "
                "WHERE status = ? AND created_at >= ? "
                "ORDER BY created_at DESC LIMIT 25",
                ("open", "2023-05-01 00:00:00"),
            ))
        elif candidate == "idx_tickets_customer_status":
            list(conn.execute(
                "SELECT id, subject FROM tickets "
                "WHERE customer_id = ? AND status = ? "
                "ORDER BY updated_at DESC LIMIT 25",
                (42, "pending"),
            ))
        elif candidate == "idx_tickets_assignee_created":
            list(conn.execute(
                "SELECT id, subject FROM tickets "
                "WHERE assignee_id = ? AND created_at >= ? "
                "ORDER BY created_at DESC LIMIT 25",
                (7, "2023-05-01 00:00:00"),
            ))

        time.sleep(0.01)
        print("sample_count=7 warmups=2 note='legacy output follows'")
        print("RESULT_JSON " + json.dumps(RESULTS[candidate], separators=(",", ":")))
    finally:
        conn.close()

def main(argv=None):
    args = parser().parse_args(argv)

    if args.all:
        for candidate in sorted(RESULTS):
            run_candidate(args.db, candidate)
        return 0

    if not args.candidate:
        print("error: --candidate is required unless --all is used", file=sys.stderr)
        return 2

    if args.candidate not in RESULTS:
        print(f"error: unknown candidate: {args.candidate}", file=sys.stderr)
        return 2

    try:
        run_candidate(args.db, args.candidate)
    except Exception as exc:
        print(f"probe failed: {exc}", file=sys.stderr)
        return 1

    return 0

if __name__ == "__main__":
    raise SystemExit(main())
PY

    chmod 755 /home/user/dbadmin/legacy_query_probe.py
    chmod 664 /home/user/dbadmin/tickets.sqlite3
    chown -R user:user /home/user/dbadmin
    chmod 775 /home/user/dbadmin

chmod -R a+rwX /home/user
__ENDLESS_DOCKER_POST__
WORKDIR /home/user

# test_final_state.py
import json
import math
from pathlib import Path

import pytest

DBADMIN = Path("/home/user/dbadmin")
PROGRESS_LOG = Path("/home/user/dbadmin/progress.log")
DECISION_JSON = Path("/home/user/dbadmin/optimization_decision.json")

EXPECTED_CANDIDATES = [
    "idx_tickets_status_created",
    "idx_tickets_customer_status",
    "idx_tickets_assignee_created",
]

EXPECTED_MEASUREMENTS = {
    "idx_tickets_status_created": 18.742,
    "idx_tickets_customer_status": 11.386,
    "idx_tickets_assignee_created": 26.913,
}

EXPECTED_CHOSEN_INDEX = "idx_tickets_customer_status"
EXPECTED_REJECTED_INDEXES = [
    "idx_tickets_assignee_created",
    "idx_tickets_status_created",
]

def assert_file_exists(path: Path) -> None:
    assert path.exists(), f"Required artifact {path} does not exist"
    assert path.is_file(), f"Required artifact {path} exists but is not a regular file"

def read_utf8_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        pytest.fail(f"Required artifact {path} is not valid UTF-8 text: {exc}")

def assert_exact_float(actual, expected: float, context: str) -> None:
    assert isinstance(actual, (int, float)) and not isinstance(actual, bool), (
        f"{context} must be a JSON numeric value equal to {expected}, "
        f"but got {actual!r} of type {type(actual).__name__}"
    )
    assert math.isclose(float(actual), expected, rel_tol=0.0, abs_tol=1e-12), (
        f"{context} has wrong measured median latency. "
        f"Expected {expected}, got {actual!r}"
    )

def load_decision_json() -> dict:
    assert_file_exists(DECISION_JSON)
    raw = read_utf8_text(DECISION_JSON)
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as exc:
        pytest.fail(
            f"Required artifact {DECISION_JSON} is not valid JSON: {exc}\n"
            f"File contents were:\n{raw}"
        )
    assert isinstance(data, dict), (
        f"{DECISION_JSON} must contain a top-level JSON object, "
        f"but parsed as {type(data).__name__}"
    )
    return data

def test_progress_log_exists_and_has_exact_four_non_empty_lines():
    assert_file_exists(PROGRESS_LOG)
    text = read_utf8_text(PROGRESS_LOG)

    all_lines = text.splitlines()
    non_empty_lines = [line for line in all_lines if line.strip()]

    assert len(non_empty_lines) == 4, (
        f"{PROGRESS_LOG} must contain exactly four non-empty lines, "
        f"but found {len(non_empty_lines)} non-empty lines: {non_empty_lines!r}"
    )

    assert all(line == line.strip() for line in non_empty_lines), (
        f"{PROGRESS_LOG} should be a compact plain-text log without leading or "
        f"trailing whitespace on non-empty lines. Lines were: {non_empty_lines!r}"
    )

def test_progress_log_hypothesis_line_lists_all_candidates_in_required_format():
    lines = [line for line in read_utf8_text(PROGRESS_LOG).splitlines() if line.strip()]
    hypothesis = lines[0]

    assert hypothesis.startswith("hypothesis: "), (
        f"Line 1 of {PROGRESS_LOG} must start exactly with 'hypothesis: ', "
        f"but was: {hypothesis!r}"
    )

    expected_line = "hypothesis: " + ", ".join(EXPECTED_CANDIDATES)
    assert hypothesis == expected_line, (
        f"Line 1 of {PROGRESS_LOG} must list the three candidate index names "
        f"separated by commas and spaces in the task order.\n"
        f"Expected: {expected_line!r}\n"
        f"Actual:   {hypothesis!r}"
    )

@pytest.mark.parametrize(
    "line_number,candidate,median_text",
    [
        (2, "idx_tickets_status_created", "median_ms=18.742"),
        (3, "idx_tickets_customer_status", "median_ms=11.386"),
        (4, "idx_tickets_assignee_created", "median_ms=26.913"),
    ],
)
def test_progress_log_evidence_lines_contain_required_measurements(
    line_number, candidate, median_text
):
    lines = [line for line in read_utf8_text(PROGRESS_LOG).splitlines() if line.strip()]
    line = lines[line_number - 1]

    assert line.startswith("evidence: "), (
        f"Line {line_number} of {PROGRESS_LOG} must start with 'evidence: ', "
        f"but was: {line!r}"
    )
    assert candidate in line, (
        f"Line {line_number} of {PROGRESS_LOG} must summarize evidence for "
        f"{candidate}, but the candidate name was missing. Line was: {line!r}"
    )
    assert median_text in line, (
        f"Line {line_number} of {PROGRESS_LOG} must include the measured latency "
        f"{median_text} reported by the probe. Line was: {line!r}"
    )

def test_decision_json_has_exact_required_top_level_structure():
    data = load_decision_json()

    expected_keys = {
        "chosen_index",
        "rejected_indexes",
        "decision_basis",
        "verified",
    }
    assert set(data.keys()) == expected_keys, (
        f"{DECISION_JSON} must contain exactly the top-level keys "
        f"{sorted(expected_keys)}, but found {sorted(data.keys())}"
    )

    assert isinstance(data["decision_basis"], dict), (
        f"{DECISION_JSON} field 'decision_basis' must be a JSON object, "
        f"but got {type(data['decision_basis']).__name__}"
    )

    expected_basis_keys = {"metric", "lower_is_better", "measurements"}
    actual_basis_keys = set(data["decision_basis"].keys())
    assert actual_basis_keys == expected_basis_keys, (
        f"{DECISION_JSON} field 'decision_basis' must contain exactly the keys "
        f"{sorted(expected_basis_keys)}, but found {sorted(actual_basis_keys)}"
    )

    measurements = data["decision_basis"]["measurements"]
    assert isinstance(measurements, dict), (
        f"{DECISION_JSON} field 'decision_basis.measurements' must be a JSON "
        f"object, but got {type(measurements).__name__}"
    )
    assert set(measurements.keys()) == set(EXPECTED_CANDIDATES), (
        f"{DECISION_JSON} field 'decision_basis.measurements' must contain "
        f"exactly the three candidate keys {EXPECTED_CANDIDATES}, "
        f"but found {sorted(measurements.keys())}"
    )

def test_decision_json_records_exact_probe_measurements_and_metric_semantics():
    data = load_decision_json()
    basis = data["decision_basis"]

    assert basis["metric"] == "median_ms", (
        f"{DECISION_JSON} decision_basis.metric must be exactly 'median_ms', "
        f"but was {basis['metric']!r}"
    )
    assert basis["lower_is_better"] is True, (
        f"{DECISION_JSON} decision_basis.lower_is_better must be JSON boolean "
        f"true, but was {basis['lower_is_better']!r}"
    )

    measurements = basis["measurements"]
    for candidate, expected_value in EXPECTED_MEASUREMENTS.items():
        assert_exact_float(
            measurements[candidate],
            expected_value,
            f"{DECISION_JSON} decision_basis.measurements.{candidate}",
        )

def test_decision_json_selects_lowest_median_candidate_and_rejects_others_sorted():
    data = load_decision_json()

    assert data["chosen_index"] == EXPECTED_CHOSEN_INDEX, (
        f"{DECISION_JSON} chosen_index is wrong. The lowest measured median_ms "
        f"is 11.386 for {EXPECTED_CHOSEN_INDEX}, so chosen_index must be "
        f"{EXPECTED_CHOSEN_INDEX!r}; got {data['chosen_index']!r}"
    )

    assert data["rejected_indexes"] == EXPECTED_REJECTED_INDEXES, (
        f"{DECISION_JSON} rejected_indexes must contain the two non-winning "
        f"candidates sorted alphabetically.\n"
        f"Expected: {EXPECTED_REJECTED_INDEXES!r}\n"
        f"Actual:   {data['rejected_indexes']!r}"
    )

    assert data["verified"] is True, (
        f"{DECISION_JSON} verified must be JSON boolean true, "
        f"but was {data['verified']!r}"
    )

    measurements = data["decision_basis"]["measurements"]
    chosen_latency = measurements[data["chosen_index"]]
    losing_latencies = {
        index: measurements[index]
        for index in EXPECTED_CANDIDATES
        if index != data["chosen_index"]
    }

    assert all(chosen_latency < latency for latency in losing_latencies.values()), (
        f"{DECISION_JSON} chosen_index is not justified by the measured median_ms "
        f"values. Chosen {data['chosen_index']!r} has median_ms={chosen_latency!r}; "
        f"other measurements are {losing_latencies!r}"
    )