"""Lambda handler shim for AlphaAgent code-interpreter sessions.

This module is the ENTRYPOINT for every environment Lambda function.
It receives a JSON event from the LambdaBackend and executes Python code
or shell commands inside the Lambda execution environment.

Every ``exec_*`` action runs in a FRESH working directory under /tmp (always
writable in Lambda; ``mkdtemp``, 0700, removed when the exec ends - see
"Fresh working directory per exec", below) that mirrors the session's
project prefix
(``users/{uid}/projects/conversations/{slug}/``): the requested project
directories are pulled down first (``sync_dirs`` — ETag-diffed against a
per-project cache, so a warm Lambda re-downloads only what changed), the code
runs with the project root as cwd, then only the files the run created or
changed (mtime/size snapshot) are uploaded and reported as ``uploaded`` so
the caller can emit one ``file_added`` per file.

Connector credentials are fetched from Secrets Manager at invocation time
and handed to the child process as environment variables - THIS invocation's
only: the child's environment is the image's own plus this invocation's
variables (`_child_env`), and nothing per-invocation is ever written to the
handler's ``os.environ``, because one warm container serves every agent
pinned to the environment (see the "Per-invocation environment" section).
Shell commands run under bash when the image has it: the variables
are named ``CONN_{connector_id}_{KEY}`` and a connector id is a UUID, so the
names carry hyphens, and Debian's ``/bin/sh`` (dash) drops such entries from
its environment at startup - see `_shell_argv`.

Dependency contract: stdlib + boto3 ONLY — this file ships inside every env
image (see environments/alphaagent-python/Dockerfile) on release.

Runtime delivery: since Studio 1.0.150 the platform does not rely on the
copy baked into the image. agent-management points every
environment function's ``ImageConfig.EntryPoint`` at an inline bootstrap that
downloads this file and ``aa_env.py`` from a release-staged S3 prefix
(``AA_HANDLER_URI``) into ``/tmp/aa_handler``, imports the handler from there
and only then starts ``awslambdaric``; when the download fails it runs the
image's own copy and records why in ``AA_HANDLER_DELIVERY``. This file
reports which copy is live (`_handler_delivery`, in ``probe_capabilities``)
and, because ``/tmp`` is writable by the sandbox uid while ``/opt`` is not,
restores ``aa_env.py`` next to itself before every exec
(`_ensure_overlay_intact`). The bootstrap never edits this file: it is the
same bytes wherever it runs from.

Private HOME per invoking scope: the image's HOME is unusable for the
runtime uid on the live env Lambda, and the fallback used to be ONE
``/tmp/home`` shared by every agent the warm container serves - a place one
agent's script could plant ``~/.local/lib/python3.X/site-packages/
usercustomize.py`` (imported by ``site`` at every interpreter start), a
``.pth`` file, a shadow module, ``~/.config/pip/pip.conf`` or rc files for
the NEXT agent's child to execute with that agent's credentials. Every child
now gets ``/tmp/home-<sha256(scope)[:16]>`` where the scope is the invoking
agent, else the owning user, else the exec itself (`_home_scope`,
`_scope_home`): the same agent's later warm turns find what it installed
(``pip install --user`` keeps working), a different agent never does.

Fresh working directory per exec: the mirror used to live at a
PREDICTABLE path - ``/tmp/users_<uid>_projects_conversations_<slug>`` -
that persisted while the container was warm, was only ever mirrored DOWN (a
file gone from S3 stayed on disk) and whose ``code/`` sits on the child's
``PYTHONPATH`` ahead of the standard library and site-packages: a hostile
child of user A could plant ``code/pandas.py`` into user B's path and B's
next turn on the same container executed it with B's credentials. Now each
exec gets ``/tmp/.aa-work-<random>`` (`_get_session_workdir`), the child runs
there and the directory is removed after the up-mirror (`_release_workdir`).
The warm ETag diff is kept through a per-project CACHE,
``/tmp/ws-<sha256(prefix)[:16]>`` (`_workspace_cache`), whose manifest is
this process's memory (`_WORKSPACE_INDEX`) - the one place a child cannot
write - and every cache hit is re-verified by sha256 before the working copy
is hard-linked from it (`_sync_dirs_down`, `_materialize_workdir`); anything
in the cache the index does not vouch for is removed (`_scrub_cache_dir`).
Since Studio 2.2.28 a hit whose stat (inode, size, mtime, ctime) is the one
this process recorded when it last copied, linked or released the file is
not hashed again (`_CACHE_TRUST`): a child can put an mtime back but never a
ctime. The same cache keeps the Folio references by key and version
(``.refs/``), prefetch entries by ETag (``.prefetch/``) and a resume's state,
each HEADed under the invocation's own credentials before it is linked; the
copies run ``sync_concurrency`` at a time; and a ``warm`` action fills it
with no program.
Bound (the same one the private HOME has): every child is one uid on one
/tmp, so a resident process a child leaves behind is not stopped by any of
this.

Credential isolation: the runtime hands this process its IAM role
credentials as environment variables and the user's code runs as a same-uid
child, so ``/proc/<ppid>/environ`` used to hand a script a role that read
every user's workspace and every agent's connector secret. The handler now
re-executes itself at import with a clean environment (credentials over a
pipe, into memory) FROM AN EXEC-ONLY COPY of the interpreter, so the serving
process is non-dumpable from its first instruction (a child gets
``PermissionError`` on ``/proc/<ppid>/environ``, ``mem`` and ``maps``;
``prctl(PR_SET_DUMPABLE)`` is refused by Lambda's seccomp, so the exec is
what carries that), and does every S3 / Secrets Manager call for the user on
STS session credentials scoped to ``users/<uid>/`` and the agent's own
secret - the "Credential isolation" section below has the four layers and
their bounds.
"""

import glob
import hashlib
import json
import mimetypes
import os
import re
import resource
import select
import shutil
import signal
import socket
import ssl
import stat
import struct
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import errno
import random
import uuid
from concurrent.futures import ThreadPoolExecutor, wait as _wait_futures
from datetime import datetime, timezone
from typing import Any, Dict, List, NamedTuple, Optional, Tuple

import boto3

#: Refused uploads reported back to the caller: entries kept, chars per entry.
_UPLOAD_ERRORS_MAX = 50
_UPLOAD_ERROR_MAX_CHARS = 300
#: The working copy's upload to S3 (2.2.27). A file up to
#: `_UPLOAD_IN_MEMORY_MAX` goes in one PutObject, whose answer carries its
#: ETag; a larger one streams from disk through the transfer manager, in
#: `_UPLOAD_PART_BYTES` parts above `_UPLOAD_MULTIPART_BYTES`,
#: `_UPLOAD_PART_CONCURRENCY` parts at a time, so no file is ever read into
#: memory whole whatever its size.
_UPLOAD_IN_MEMORY_MAX = 8 * 1024 * 1024
_UPLOAD_MULTIPART_BYTES = 64 * 1024 * 1024
_UPLOAD_PART_BYTES = 64 * 1024 * 1024
_UPLOAD_PART_CONCURRENCY = 8
#: Once the uploads' time is up the ones still running are told to stop
#: (`_UploadAborted`); the answer then waits at most this long (and never
#: more than half the save margin) for them to settle, so it can say which
#: files are in S3 and which are not.
_UPLOAD_ABORT_JOIN_S = 2.0
#: Files uploaded at once: the event's ``upload_concurrency`` (the runtime
#: limit KERNEL_UPLOAD_CONCURRENCY), held to its range; this default when
#: an older service sends none.
KERNEL_UPLOAD_CONCURRENCY_DEFAULT = 16
KERNEL_UPLOAD_CONCURRENCY_RANGE = (1, 64)
#: Paths an exec response lists in ``uploaded``: the event's
#: ``uploaded_list_max`` (the runtime limit KERNEL_UPLOADED_LIST_MAX). Past
#: it the full list is written to ``{prefix}.coder/uploads/{exec_id}.json``
#: (``uploaded_manifest``), so the response stays far under Lambda's 6 MB.
KERNEL_UPLOADED_LIST_MAX_DEFAULT = 5000
KERNEL_UPLOADED_LIST_MAX_RANGE = (500, 20000)
#: Whatever the list's limit, ``uploaded`` and ``uploads`` together stay
#: under this many bytes of JSON, so with the inline output (2 MiB at most)
#: the answer is always well under Lambda's 6 MB.
_UPLOADED_LIST_MAX_BYTES = 2 * 1024 * 1024
UPLOADED_MANIFEST_DIR = ".coder/uploads"
#: Names an exec response lists in ``not_uploaded`` and ``input_errors``.
_NOT_UPLOADED_MAX = 50
_INPUT_ERRORS_MAX = 50
#: Retries of an input copy S3 answered with SlowDown or a 5xx (or a dropped
#: connection), each after a short jittered pause.
_INPUT_COPY_RETRIES = 2
_INPUT_RETRY_BASE_S = 0.5
#: The share of free /tmp the inputs may take together (the rest is the
#: program's).
_INPUT_DISK_SHARE = 0.9
#: Connections the S3 client keeps: room for every upload worker at the
#: highest KERNEL_UPLOAD_CONCURRENCY, so none waits on another's connection.
_S3_POOL_CONNECTIONS = 64
_S3_CLIENT_CONFIG: Any = None
#: Studio 2.2.28 (PRO-2385): downloads and listings at once - the project
#: mirror's folders and files, the Folio references, the prefetch entries and
#: a resume's state: the event's ``sync_concurrency`` (the runtime limit
#: CODER_MIRROR_CONCURRENCY), held to its range; this default when an older
#: service sends none. The S3 client's pool (`_S3_POOL_CONNECTIONS`) covers
#: the highest.
SYNC_CONCURRENCY_DEFAULT = 16
SYNC_CONCURRENCY_RANGE = (1, 64)
#: aa_env's checkpoint state, relative to the project root (aa_env.py
#: ``MANIFEST_NAME`` and ``_SHARD_DIR``; a test pins that they agree). A
#: resume with ``resume_paths`` copies these and those paths only.
AA_ENV_MANIFEST_NAME = "_manifest.json"
AA_ENV_SHARD_DIR = "_aa_shards"
#: What a resume never copies down: the coder's own session, tool results,
#: spilled tool output and the read-only references (they come from ``refs``).
RESUME_EXCLUDED_PREFIXES = (".coder/", "tool-results/", "_tool_output/", "refs/")
#: Where a project's verified cache keeps Folio references (one file per key
#: and version, `_ref_cache_rel`) and prefetch entries (one per key, valid
#: while its ETag holds). Hidden names: never a project folder.
REFS_CACHE_DIR = ".refs"
PREFETCH_CACHE_DIR = ".prefetch"
#: The inline part of stdout/stderr a response carries when the caller names
#: no size (``inline_max_chars``). Since 2.2.25 (PRO-2358) this is a preview
#: size, not a cut: a longer stream is saved in full to the workspace first.
MAX_OUTPUT_BYTES = 1024 * 1024

# The project mirror: a fresh working directory per exec, fed from a
# per-project cache whose manifest lives in this process's memory.
#: Working directory name prefix under `TMP_ROOT`: ``mkdtemp``, removed per exec.
WORKDIR_PREFIX = ".aa-work-"
#: Per-project mirror cache under `TMP_ROOT`: ``ws-<sha256(prefix)[:16]>``, 0700.
WORKSPACE_CACHE_PREFIX = "ws-"
#: ``{cache_dir: {rel_path: (etag, sha256)}}`` - what `_sync_dirs_down` has
#: verified in each cache. Handler memory, never a file: a sandbox child can
#: write anything under /tmp, but not here. Same lifetime as /tmp (the warm
#: container), so nothing is lost by keeping it in memory.
_WORKSPACE_INDEX: Dict[str, Dict[str, Tuple[str, str]]] = {}
#: Project directories a coder run always mirrors (see coder_worker.run_in_env;
#: ``brand/`` since v1.0.120 so the style resolver sees the project's brand).
DEFAULT_SYNC_DIRS = ("code", "nodes", "brand")
#: Size guards for the mirror-down (env fallbacks; the event may override).
_DEFAULT_SYNC_MAX_BYTES = 500 * 1024 * 1024
_DEFAULT_SYNC_SKIP_OVER_BYTES = 100 * 1024 * 1024
#: Where an inline ``code`` script lands inside the mirrored project, so the
#: one legacy path that still accepts source text never litters the root.
INLINE_SCRIPT_DIR = "code/scratch"
#: Where an ``ephemeral`` inline script lands: a HIDDEN dir, so a service-side
#: helper run (the preview renderer) never uploads its program into the
#: user's workspace.
EPHEMERAL_SCRIPT_DIR = ".aa-scratch"
#: S3 key prefixes that mark a prefetch entry as a FULL key rather than a
#: path relative to the session prefix.
_FULL_KEY_PREFIXES = ("users/", "workspaces/", "conversations/")
#: Version stamp the document toolkit image writes (reported as
#: ``toolkit_version`` by the capability probe); absent on an image built
#: before it existed.
TOOLKIT_LOCK_PATH = "/opt/alphaagent/toolkit.lock"
#: Read to detect QEMU user-mode emulation (an amd64 image on an arm64 host):
#: x86_64 with no x86 ``flags:`` line. Chromium cannot run there, so the
#: lock's ``needs_browser`` checks are reported skipped, never pass/fail.
CPUINFO_PATH = "/proc/cpuinfo"
#: Per-command ceiling for the capability probe (seconds). soffice is the
#: slow one on a cold container; everything else answers in well under 1s.
#: The lock may override it (``check_timeout_s``).
PROBE_TIMEOUT_S = 15
#: Ceiling for the lock's ``needs_browser`` checks: a cold Chromium launch in
#: Lambda (2 GB, no /dev/shm, single-process) takes well over 15 s the first
#: time. The lock may override it (``browser_check_timeout_s``).
BROWSER_CHECK_TIMEOUT_S = 60
#: The toolkit.lock version this handler was cut with (environments/toolkit/
#: toolkit.lock). An installed lock BELOW this is ``toolkit_outdated`` — e.g. a
#: customer image built from the 1.0.0 lock has Chrome launch flags that crash
#: in Lambda and fill /tmp with core dumps (toolkit 1.1.0).
HANDLER_TOOLKIT_VERSION = "1.1.0"
#: Contract version of THIS handler: bumped when the request/response
#: contract between this file and the platform changes, so the platform can
#: tell an outdated copy from a probe. Every handler that predates the field
#: is implicitly "1" (it reports nothing). "2": runtime delivery, the
#: per-invocation child environment, budget/reserve reporting. Additive
#: under "2" (1.0.154): ``credential_isolation`` in the probe; (2.0.15)
#: ``trusted_ca`` in the probe (with ``outcome`` and ``outcome_reason``) and
#: ``untrusted_certificate`` on an exec response; (2.2.27) on an exec
#: response ``uploads`` ``[{path, size, etag}]``, ``uploaded_count``,
#: ``uploaded_truncated`` and ``uploaded_manifest``, ``not_uploaded``,
#: ``not_uploaded_count`` and ``not_uploaded_bytes``, ``upload_unsettled``
#: and ``upload_unsettled_count``, ``input_errors``, ``tmp_free_bytes``,
#: and exit 124 ``environment_timeout`` with ``reason``
#: ``inputs_took_budget``; in the event ``upload_concurrency`` and
#: ``uploaded_list_max``. Every field is optional both ways: an older
#: caller ignores the new ones and an older event gets the defaults.
#: "3" (Studio 2.2.28, PRO-2385), so the platform can tell these apart: a
#: ``warm`` action (the same envelope as an exec, no program: the mirror and
#: the references are brought into the cache, nothing is uploaded, and the
#: answer is ``{ok, action: "warm", handler_version, sync_stats}``); a resume
#: whose event carries ``resume_paths`` copies only aa_env's manifest and
#: shards plus those paths (without it the whole prefix still comes down);
#: ``sync_concurrency`` in the event; ``sync_stats`` ``{listed, fetched,
#: cached, hash_skipped, refs_cached, refs_fetched, bytes_fetched,
#: duration_ms}`` on exec and warm answers. Folio references and prefetch
#: entries are kept in the project's verified cache. All optional both ways,
#: as under "2".
HANDLER_CONTRACT_VERSION = "3"
#: Set on the FUNCTION by agent-management: the release-staged S3 prefix the
#: bootstrap downloads the handler pair from (``s3://<bucket>/.../<release>``).
HANDLER_URI_ENV = "AA_HANDLER_URI"
#: Set in the PROCESS by the bootstrap before awslambdaric starts: ``overlay``
#: when the downloaded pair is what runs, ``baked:<reason>`` when it fell back
#: to the image's copy. Absent when the function's entry point is the legacy
#: ``python -m awslambdaric`` (no bootstrap ran).
HANDLER_DELIVERY_ENV = "AA_HANDLER_DELIVERY"
#: Lambda's only writable filesystem. Core dumps land here
#: (``core_pattern=/tmp/core.%e.%p`` on the env Lambda), so they are swept
#: before every action. When the image's HOME is unusable for the runtime uid
#: (the live env Lambda runs as uid 993 while /home/agent is drwx------ uid
#: 1000: unreadable, so choreographer/kaleido, fontconfig and Chromium all
#: fail there) a child's HOME/XDG_CACHE_HOME point at a directory under here
#: that is private to the invoking scope - `_scope_home`. The old single
#: shared fallback directory is never used again.
TMP_ROOT = "/tmp"
#: ``/tmp/<HOME_DIR_PREFIX><sha256(scope)[:16]>`` is a scope's HOME.
HOME_DIR_PREFIX = "home-"
#: The scope of the handler's OWN children - the capability probes and lock
#: checks (`_probe_run`, `probe_capabilities`). Never an agent's scope: agent
#: code never runs with this HOME and these children carry no credentials.
TOOLING_HOME_SCOPE = "handler:tooling"
#: Scope prefix of a HOME that belongs to one exec only (no agent, no owner
#: in the event): removed with the exec's helper directory.
EXEC_HOME_SCOPE_PREFIX = "exec:"
#: Never handed to a child: files an earlier invocation could plant and a
#: later child's interpreter or shell would source at startup. ``BASH_ENV``
#: is the ONE file a non-interactive ``bash -c`` reads; ``PYTHONSTARTUP``
#: the interactive interpreter's. NOT ``ENV``: POSIX sh reads ``$ENV`` only
#: when interactive (never the case here), and it is a plausible name for a
#: customer's own variable on the function.
_CHILD_STARTUP_HOOK_KEYS = ("PYTHONSTARTUP", "BASH_ENV")
CORE_DUMP_GLOB = "core.*"

# Checkpoint/continuation contract (see aa_env.py). When a script checkpoints and
# asks to be re-invoked it exits with this code; the coder harness re-invokes a
# fresh Lambda with resume=true. Kept in one place so the three parties (this
# handler, aa_env, coder_worker) agree.
EXIT_CONTINUE = 75
#: coreutils ``timeout`` exit status when the command outlived the wall. The
#: handler also normalises the SIGKILL that ``timeout -k`` delivers to a
#: SIGTERM-trapping script (-9 / 137 seen at the wall) to this value.
EXIT_TIMEOUT = 124
# Seconds reserved AFTER the script exits for the workdir→S3 upload, and seconds
# of grace before the hard kill in which a cooperative script should checkpoint.
# Both are CAPS, not flat subtractions: `_compute_budget` scales them to the
# function's own remaining time (reserve = min(cap, max(5, remaining // 4))), so
# a 60 s environment gives code ~45 s rather than the 5 s floor a flat 60 s
# reserve would leave. Overridable via env (set on the function by the
# backend) or per event (``upload_reserve_s`` / ``yield_grace_s``).
_DEFAULT_UPLOAD_RESERVE_S = 60
_DEFAULT_YIELD_GRACE_S = 30
#: Floors for the scaled reserve / grace and for the script's own budget.
_MIN_UPLOAD_RESERVE_S = 5
_MIN_YIELD_GRACE_S = 5
_MIN_HARD_TIMEOUT_S = 5
#: Upper bound on ``timeout -k``: a script that traps SIGTERM is SIGKILLed this
#: many seconds after the wall (paid for out of the upload reserve).
_MAX_KILL_AFTER_S = 5

# VENDORED, not imported (stdlib + boto3 only): mirrors the service's own
# run-data tagging definition (``RUN_DATA_TAGGING`` / ``RUN_DATA_KEY_PATTERN``
# / ``TEXT_CONTENT_TYPES`` / ``put_args``), which carries the key and value
# agent-runtime puts on its own writes (``workflow_inputs.RUN_DATA_TAG_KEY`` /
# ``RUN_DATA_TAG_VALUE``). The workspaces bucket's lifecycle rule filters on
# this object tag, so every file this handler uploads under a run root
# (``users/{uid}/projects/workflows/{slug}/runs/{execution_id}/`` or a
# conversation's ``runs/{execution_id}/`` scratch) - the deliverables under
# ``outputs/``, ``outputs/result.json``, ``code/scratch/*`` - must carry it
# or it never ages out. Files outside a run root stay untagged. A test pins
# the three copies equal.
RUN_DATA_TAGGING = "aa-data-class=run-data"
_RUN_DATA_KEY_RE = re.compile(r"^users/[^/]+/projects/(?:workflows|conversations)/[^/]+/runs/[^/]+/")
#: Extension -> ``ContentType`` for the text types a run's files are made of;
#: Python's ``mimetypes`` has no ``.md``, so without this a Markdown
#: deliverable reads back as ``application/octet-stream``.
_TEXT_CONTENT_TYPES: Dict[str, str] = {
    ".md": "text/markdown",
    ".markdown": "text/markdown",
    ".txt": "text/plain",
    ".log": "text/plain",
    ".csv": "text/csv",
    ".tsv": "text/tab-separated-values",
    ".json": "application/json",
    ".jsonl": "application/x-ndjson",
    ".ndjson": "application/x-ndjson",
    ".yaml": "text/yaml",
    ".yml": "text/yaml",
    ".toml": "text/plain",
    ".ini": "text/plain",
    ".cfg": "text/plain",
    ".py": "text/x-python",
    ".sh": "text/x-shellscript",
    ".sql": "application/sql",
    ".xml": "application/xml",
    ".html": "text/html",
    ".htm": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".svg": "image/svg+xml",
}


def _s3_content_type(name: str) -> Optional[str]:
    """``ContentType`` from the extension of ``name``, or ``None`` (omit it)."""
    base = str(name or "").rsplit("/", 1)[-1]
    dot = base.rfind(".")
    if dot <= 0:
        return None
    known = _TEXT_CONTENT_TYPES.get(base[dot:].lower())
    if known:
        return known
    guessed, _ = mimetypes.guess_type(base)
    return guessed or None


def _s3_put_args(key: str, content_type: Optional[str] = None) -> Dict[str, str]:
    """Extra ``put_object`` kwargs for ``key``: ``Tagging`` when it is run
    data, ``ContentType`` = the explicit one, else the extension's when known.
    Never contains a ``None`` value (botocore rejects ``Tagging=None``)."""
    extra: Dict[str, str] = {}
    if key and _RUN_DATA_KEY_RE.match(str(key)):
        extra["Tagging"] = RUN_DATA_TAGGING
    ctype = content_type or _s3_content_type(key)
    if ctype:
        extra["ContentType"] = ctype
    return extra


#: Separates a variable's plain name from its version suffix in the agent's
#: secret (code-interpreter ``connector_creds.VERSION_SEP``).
CONNECTOR_VERSION_SEP = "#"


def _select_connector_vars(
    creds: Dict[str, Any], connector_ids: list, connector_vars: Optional[list] = None
) -> Dict[str, str]:
    """The variables of ``creds`` (the agent's secret) for this invocation.

    The secret is shared by every session of the agent, and sessions of one
    agent can hold different connectors, or one connector at different
    versions or in different shapes (a run pinned to an older agent version
    next to a conversation on the active one, a coder spec that started
    before its session moved to a new credential). It holds the union of
    their variables twice: under the plain name, one value per name (the
    last session to publish), and under ``<plain name>#<suffix>``, one copy
    per connector version.

    ``connector_vars`` are the invoking session's versioned names: each is
    injected under its plain name, so the sandbox gets one whole version of
    each connector. A version the secret does not hold in full (a secret
    written before versioned names, or one too large for them) falls back
    to the plain names. ``connector_ids`` are the plain names (what an older
    service sends): an entry that is a variable name selects exactly that
    variable; an entry that is a connector id selects every plain
    ``CONN_<connector_id>_*`` (no connector id contains another followed by
    ``_``, so one id's prefix never selects another connector's
    variables)."""
    wanted = [str(c) for c in connector_ids or [] if c]
    prefixes = tuple(f"CONN_{cid}_" for cid in wanted)
    named = set(wanted)
    out: Dict[str, str] = {}
    for key, value in creds.items():
        if CONNECTOR_VERSION_SEP in key:
            continue
        if key in named or key.startswith(prefixes):
            out[key] = str(value) if value is not None else ""
    versions: Dict[str, list] = {}
    for entry in connector_vars or []:
        entry = str(entry)
        if CONNECTOR_VERSION_SEP in entry:
            versions.setdefault(entry.rsplit(CONNECTOR_VERSION_SEP, 1)[1], []).append(entry)
    for entries in versions.values():
        if not all(e in creds for e in entries):
            continue
        for entry in entries:
            value = creds[entry]
            out[entry.rsplit(CONNECTOR_VERSION_SEP, 1)[0]] = str(value) if value is not None else ""
    return out


def _load_connector_credentials(
    agent_id: str, connector_ids: list, connector_vars: Optional[list] = None
) -> Dict[str, str]:
    """Fetch connector credentials from Secrets Manager and return the
    invocation's variables (`_select_connector_vars`) as env vars -
    through this invocation's scoped session (`_secrets_client`), whose
    session policy names this agent's secret and no other."""
    if not connector_ids:
        return {}

    try:
        sm = _secrets_client()
        secret_name = f"alphaagent-connector-creds-{agent_id}"
        print(f"[HANDLER] Fetching connector secret: {secret_name}")
        resp = sm.get_secret_value(SecretId=secret_name)
        creds = json.loads(resp["SecretString"])
        creds = creds if isinstance(creds, dict) else {}
        env_vars = _select_connector_vars(creds, connector_ids, connector_vars)
        print(f"[HANDLER] Loaded {len(env_vars)} connector creds from {len(creds)} secret entries "
              f"for {len(connector_ids)} requested names ({len(connector_vars or [])} versioned)")
        return env_vars
    except Exception as exc:
        print(f"[HANDLER] ERROR loading connector creds: {exc}")
        return {}


def _cap_output(data: bytes) -> str:
    """Decode and cut output at `MAX_OUTPUT_BYTES`. Kept for callers outside
    the exec paths; since 2.2.25 an exec's output is never cut this way
    (`_finish_run` saves a long stream in full first)."""
    text = data.decode("utf-8", errors="replace")
    if len(text) > MAX_OUTPUT_BYTES:
        return text[:MAX_OUTPUT_BYTES] + "\n[OUTPUT TRUNCATED]"
    return text


# ---------------------------------------------------------------------------
# Program output, kept in full (PRO-2358, 2.2.25 WP16).
#
# The child's stdout and stderr stream through pipes into files in a
# handler-private folder under /tmp (`_OutputCapture`) as the program runs,
# so nothing is held in memory and nothing is cut at 1 MiB any more. A stream
# longer than the caller's inline size (``inline_max_chars``, one number or
# ``{"stdout": n, "stderr": n}``) is saved in full to the session's
# workspace, in the folder the caller names (``output_save.dir``, under
# ``tool-results/``), and the response carries a head-and-tail preview that
# names the file plus ``{stream}_file`` (key, path, bytes, chars, lines, seq).
# Saves are conditional puts: a name another run holds is never overwritten,
# the next number is used. Stdout and stderr together are kept up to
# ``output_max_bytes`` (the runtime limit KERNEL_OUTPUT_MAX_BYTES); past it
# the program is stopped and the result names the ceiling. The handler's own
# role does the upload, under the session prefix; the child never sees it.
# ---------------------------------------------------------------------------

#: Largest program output kept, stdout and stderr together, in bytes
#: (runtime limit ``KERNEL_OUTPUT_MAX_BYTES``; the service passes it as
#: ``output_max_bytes``). Its range is 10 MiB to 8 GiB; it is also bounded by
#: the kernel's own disk, which the run reports when it fills.
KERNEL_OUTPUT_MAX_BYTES_DEFAULT = 1024 * 1024 * 1024
KERNEL_OUTPUT_MAX_BYTES_MIN = 10 * 1024 * 1024
KERNEL_OUTPUT_MAX_BYTES_MAX = 8 * 1024 * 1024 * 1024
#: ``/tmp/<OUTPUT_CAPTURE_PREFIX>…``: one exec's capture folder, 0700, removed after the upload.
OUTPUT_CAPTURE_PREFIX = ".aa-out-"
OUTPUT_STREAMS = ("stdout", "stderr")
#: Where a saved stream goes when the caller names no folder (or one outside these roots).
OUTPUT_SAVE_DEFAULT_DIR = "tool-results/kernel/"
_OUTPUT_SAVE_ROOTS = ("tool-results", "_tool_output")
_OUTPUT_STEM_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_OUTPUT_COPY_CHUNK = 1024 * 1024
#: The smallest inline size a caller may ask for (a preview needs room).
_OUTPUT_INLINE_MIN = 500
#: S3's single PUT limit is 5 GiB; a larger saved stream goes up in parts.
_OUTPUT_SINGLE_PUT_MAX = 5 * 1024 * 1024 * 1024
#: Taken names tried in order before a save takes a unique name instead.
#: Never decides what is kept: a save past it still lands, under that name.
_OUTPUT_NAME_TRIES = 100
#: How much of the end of stderr the certificate checks read. Never decides
#: what is kept: the whole stream is saved and previewed as it is.
_OUTPUT_TAIL_FOR_CHECKS = 256 * 1024
_UTF8_CONTINUATION = bytes(range(0x80, 0xC0))
_OUTPUT_PRECONDITION_CODES = frozenset({"PreconditionFailed", "412", "ConditionalRequestConflict"})
#: The output timing (runtime limits, sent as the event's ``output_timing``):
#: ``drain_wait_s`` (KERNEL_OUTPUT_DRAIN_WAIT_S), how long the copy threads
#: read once the program has exited, for processes it started;
#: ``save_margin_s`` (KERNEL_OUTPUT_SAVE_MARGIN_S), the time kept before the
#: invocation's end when saving output, so the response itself is never
#: lost; ``upload_mb_per_s`` (KERNEL_OUTPUT_UPLOAD_MB_PER_S), the upload
#: speed that check assumes. The defaults are the catalogue's, used only when
#: an older service sends no timing; a value is held to the catalogue range.
OUTPUT_TIMING_DEFAULTS = {"drain_wait_s": 5, "save_margin_s": 5, "upload_mb_per_s": 40}
OUTPUT_TIMING_RANGES = {"drain_wait_s": (1, 60), "save_margin_s": (1, 60), "upload_mb_per_s": (1, 1000)}

#: Monotonic time at which this invocation ends (Lambda's remaining time at
#: entry), or None off Lambda. Set by `_dispatch` for every exec.
_INVOCATION_END: Optional[float] = None
#: Monotonic time `_dispatch` started this exec, so the time its preparation
#: (mirror, inputs) took can be named.
_INVOCATION_START: Optional[float] = None
#: Free bytes on /tmp once `_make_room_on_tmp` ran at entry (exec responses
#: carry it as ``tmp_free_bytes``); None before.
_TMP_FREE_BYTES: Optional[int] = None

#: Write end of the pipe the running capture reads the child's pid from.
#: `_no_core_dumps` (every child's ``preexec_fn``) writes the pid into it; None
#: outside an exec, so the handler's own probes never write anywhere.
_CHILD_PID_FD: Optional[int] = None
#: This exec's `_OutputCapture`, set by `_exec_python` / `_exec_shell` around
#: `_run_under_wall` (which reads it), else None (the old in-memory capture).
_CURRENT_CAPTURE: Optional["_OutputCapture"] = None


def _invocation_time_left() -> Optional[float]:
    """Seconds left in this invocation, or None when there is no Lambda clock."""
    return None if _INVOCATION_END is None else _INVOCATION_END - time.monotonic()


class OutputTiming(NamedTuple):
    drain_wait_s: float
    save_margin_s: float
    upload_bytes_per_s: int


def _output_timing(event: Optional[Dict[str, Any]]) -> OutputTiming:
    """The event's ``output_timing``, each value a positive number held to
    `OUTPUT_TIMING_RANGES`, else its `OUTPUT_TIMING_DEFAULTS` entry."""
    raw = (event or {}).get("output_timing") if isinstance(event, dict) else None
    raw = raw if isinstance(raw, dict) else {}
    values: Dict[str, int] = {}
    for name, default in OUTPUT_TIMING_DEFAULTS.items():
        value = _positive_int(raw.get(name))
        low, high = OUTPUT_TIMING_RANGES[name]
        values[name] = default if value is None else max(low, min(high, value))
    return OutputTiming(float(values["drain_wait_s"]), float(values["save_margin_s"]),
                        values["upload_mb_per_s"] * 1024 * 1024)


def _output_save_fits(size: int, time_left: Optional[float], timing: Optional[OutputTiming] = None) -> bool:
    """Whether saving ``size`` bytes fits in ``time_left`` seconds with the
    margin kept, at the assumed upload speed. True without a clock."""
    if time_left is None:
        return True
    t = timing or _output_timing(None)
    return time_left - t.save_margin_s >= size / t.upload_bytes_per_s


#: Left by an exec that died before its own cleanup: never in use at entry
#: (one invocation runs at a time). Removed once they are
#: `_LEFTOVER_MIN_AGE_S` old, and at once when room is short.
_LEFTOVER_DIR_PREFIXES = (".aa-work-", ".aa-helper-")
_LEFTOVER_MIN_AGE_S = 120


def _tmp_room_wanted(event: Optional[Dict[str, Any]]) -> int:
    """Free /tmp an exec may need: the mirror's ceiling (``sync_max_bytes``),
    the output ceiling and the references it names."""
    event = event if isinstance(event, dict) else {}
    sync_max = _positive_int(event.get("sync_max_bytes")) or _int_env("AA_SYNC_MAX_BYTES", _DEFAULT_SYNC_MAX_BYTES)
    refs = event.get(REFS_EVENT_KEY) if isinstance(event.get(REFS_EVENT_KEY), list) else []
    refs_bytes = sum(_positive_int(r.get("size")) or 0 for r in refs if isinstance(r, dict))
    return int(sync_max) + _output_max_bytes(event) + refs_bytes


def _make_room_on_tmp(event: Optional[Dict[str, Any]], s3_prefix: str) -> Optional[int]:
    """At entry (SZ-05): remove what dead execs left (`_LEFTOVER_DIR_PREFIXES`),
    mark this project's mirror cache as just used, and while free space is
    under ``min(0.8 x total, sync max + output max + references)`` remove,
    oldest first, other projects' mirror caches (``ws-*``, their
    `_WORKSPACE_INDEX` entries dropped) and HOMEs (``home-*``) other than
    this invocation's and the handler's own. Returns the free bytes after,
    or None when /tmp cannot be read. Never raises."""
    try:
        names = os.listdir(TMP_ROOT)
    except OSError:
        return None

    def _remove_leftovers(min_age: float) -> None:
        now = time.time()
        for name in names:
            if not name.startswith(_LEFTOVER_DIR_PREFIXES):
                continue
            path = os.path.join(TMP_ROOT, name)
            try:
                if os.path.islink(path) or not os.path.isdir(path) or now - os.stat(path).st_mtime < min_age:
                    continue
            except OSError:
                continue
            shutil.rmtree(path, ignore_errors=True)

    _remove_leftovers(_LEFTOVER_MIN_AGE_S)
    own_ws = _workspace_cache_path(s3_prefix) if s3_prefix else None
    if own_ws and os.path.isdir(own_ws) and not os.path.islink(own_ws):
        try:
            os.utime(own_ws)
        except OSError:
            pass
    keep = {p for p in (own_ws, _scope_path(TOOLING_HOME_SCOPE),
                        _scope_path(_home_scope(event or {}, "entry"))) if p}
    try:
        usage = shutil.disk_usage(TMP_ROOT)
    except OSError:
        return None
    wanted = min(int(0.8 * usage.total), _tmp_room_wanted(event))
    free = int(usage.free)
    if free >= wanted:
        return free
    _remove_leftovers(0)
    try:
        free = int(shutil.disk_usage(TMP_ROOT).free)
    except OSError:
        return None
    candidates: List[Tuple[float, str]] = []
    for name in names:
        if not name.startswith((WORKSPACE_CACHE_PREFIX, HOME_DIR_PREFIX)):
            continue
        path = os.path.join(TMP_ROOT, name)
        if path in keep or os.path.islink(path) or not os.path.isdir(path):
            continue
        try:
            candidates.append((os.stat(path).st_mtime, path))
        except OSError:
            continue
    evicted = 0
    for _mtime, path in sorted(candidates):
        if free >= wanted:
            break
        shutil.rmtree(path, ignore_errors=True)
        _WORKSPACE_INDEX.pop(path, None)
        _CACHE_TRUST.pop(path, None)
        evicted += 1
        try:
            free = int(shutil.disk_usage(TMP_ROOT).free)
        except OSError:
            break
    if free < wanted and own_ws and os.path.isdir(own_ws) and not os.path.islink(own_ws):
        # Studio 2.2.28: the project's own cache now also keeps its Folio
        # references, prefetch entries and resume state. When the room is
        # still short it goes last: this exec copies what it needs again.
        shutil.rmtree(own_ws, ignore_errors=True)
        _WORKSPACE_INDEX.pop(own_ws, None)
        _CACHE_TRUST.pop(own_ws, None)
        evicted += 1
        try:
            free = int(shutil.disk_usage(TMP_ROOT).free)
        except OSError:
            return None
    print(f"[HANDLER] tmp room: wanted {wanted} bytes free, {free} free after removing {evicted} idle "
          f"mirror or home folder(s)")
    return free


def _sweep_output_captures() -> int:
    """Remove ``/tmp/.aa-out-*`` folders an earlier invocation left behind
    (one that hit the Lambda timeout or ran out of memory before its own
    cleanup), so a warm sandbox's disk never fills with them. One
    invocation runs at a time, so none of them is in use. Never raises."""
    removed = 0
    try:
        names = os.listdir(TMP_ROOT)
    except OSError:
        return 0
    for name in names:
        if not name.startswith(OUTPUT_CAPTURE_PREFIX):
            continue
        path = os.path.join(TMP_ROOT, name)
        if os.path.isdir(path) and not os.path.islink(path):
            shutil.rmtree(path, ignore_errors=True)
            removed += 1
    return removed


def _output_max_bytes(event: Dict[str, Any]) -> int:
    """The output ceiling for this exec: the event's ``output_max_bytes``,
    else ``KERNEL_OUTPUT_MAX_BYTES`` from the function's environment, else
    1 GiB; always within 10 MiB to 8 GiB."""
    raw = event.get("output_max_bytes") if isinstance(event, dict) else None
    value = _positive_int(raw)
    if value is None:
        value = _int_env("KERNEL_OUTPUT_MAX_BYTES", KERNEL_OUTPUT_MAX_BYTES_DEFAULT)
    return max(KERNEL_OUTPUT_MAX_BYTES_MIN, min(KERNEL_OUTPUT_MAX_BYTES_MAX, int(value)))


def _inline_max(event: Optional[Dict[str, Any]], stream: str) -> int:
    """How much of ``stream`` the response carries inline: the event's
    ``inline_max_chars`` (a number, or one per stream), at least
    `_OUTPUT_INLINE_MIN`, at most `MAX_OUTPUT_BYTES` (the default)."""
    raw = (event or {}).get("inline_max_chars")
    if isinstance(raw, dict):
        raw = raw.get(stream)
    value = _positive_int(raw)
    if value is None:
        return MAX_OUTPUT_BYTES
    return max(_OUTPUT_INLINE_MIN, min(MAX_OUTPUT_BYTES, value))


def _size_text(n: int) -> str:
    """``3 MiB``, ``1 GiB``, ``1.5 GiB``: a byte count as people read it."""
    for unit, size in (("GiB", 1024 ** 3), ("MiB", 1024 ** 2), ("KiB", 1024)):
        if n >= size:
            value = n / size
            return f"{value:.0f} {unit}" if value == int(value) else f"{value:.1f} {unit}"
    return f"{n:,} bytes"


def _write_all(fd: int, data: bytes) -> None:
    view = memoryview(data)
    while view:
        written = os.write(fd, view)
        view = view[written:]


class _OutputCapture:
    """One exec's stdout and stderr, streamed to files as the program runs.

    `start` opens a pipe per stream (the child's fd 1 and 2) and a copy thread
    per pipe that writes what arrives to ``<dir>/<stream>.out``, counting
    bytes, characters and newlines. Stdout and stderr together are kept up to
    ``max_bytes``: the copy that passes it keeps exactly the bytes that fit,
    stops the program (SIGKILL to the ``timeout`` process group, whose pid the
    child's ``preexec_fn`` wrote to a pipe) and drains the rest unkept, so the
    program can never block on a full pipe. A full disk stops it the same way.
    `finish` closes the parent's write ends once the child has exited and
    waits up to ``drain_wait_s`` for the copies to drain; a process the
    program started that still holds a pipe then is named (``still_writing``),
    since what it prints later is not kept. The handler reads the files only
    through the descriptors it opened (``O_NOFOLLOW``), so a child that swaps
    a file in the folder for a symlink changes nothing. `close` closes them
    and removes the folder."""

    def __init__(self, max_bytes: int, root: Optional[str] = None,
                 drain_wait_s: float = float(OUTPUT_TIMING_DEFAULTS["drain_wait_s"])):
        self.max_bytes = int(max_bytes)
        self.drain_wait_s = float(drain_wait_s)
        self.still_writing = False
        self.dir = tempfile.mkdtemp(prefix=OUTPUT_CAPTURE_PREFIX, dir=root or TMP_ROOT)
        self.paths = {s: os.path.join(self.dir, f"{s}.out") for s in OUTPUT_STREAMS}
        self.bytes = {s: 0 for s in OUTPUT_STREAMS}
        self.chars = {s: 0 for s in OUTPUT_STREAMS}
        self.newlines = {s: 0 for s in OUTPUT_STREAMS}
        self.last = {s: b"" for s in OUTPUT_STREAMS}
        self.over_max = False
        self.disk_full = False
        self.dropped = 0
        self.stopped = False
        self._lock = threading.Lock()
        self._fds: Dict[str, List[Optional[int]]] = {}
        self._threads: List[threading.Thread] = []
        self._pid_r: Optional[int] = None
        self._pid_w: Optional[int] = None
        self._pid: Optional[int] = None
        self._done = threading.Event()
        self._drain_until = 0.0

    # -- life cycle -----------------------------------------------------------
    def start(self) -> "_OutputCapture":
        global _CHILD_PID_FD
        for s in OUTPUT_STREAMS:
            r, w = os.pipe()
            out = os.open(self.paths[s], os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
            self._fds[s] = [r, w, out]
        self._pid_r, self._pid_w = os.pipe()
        os.set_blocking(self._pid_r, False)
        _CHILD_PID_FD = self._pid_w
        for s in OUTPUT_STREAMS:
            t = threading.Thread(target=self._copy, args=(s,), name=f"aa-output-{s}", daemon=True)
            t.start()
            self._threads.append(t)
        return self

    def child_fd(self, stream: str) -> int:
        return int(self._fds[stream][1])

    def file_fd(self, stream: str) -> Optional[int]:
        """The descriptor of ``stream``'s capture file, open until `close`."""
        return self._fds[stream][2] if stream in self._fds else None

    def finish(self) -> None:
        """After the child exited: close the parent's write ends (the copies
        then see end of file) and wait up to ``drain_wait_s`` for them;
        a grandchild still holding a pipe is not waited for, and is named
        (``still_writing``). The capture files stay open for the save."""
        global _CHILD_PID_FD
        if _CHILD_PID_FD == self._pid_w:
            _CHILD_PID_FD = None
        for fds in self._fds.values():
            self._close_slot(fds, 1)
        self._close_fd("_pid_w")
        self._drain_until = time.monotonic() + self.drain_wait_s
        self._done.set()
        for t in self._threads:
            t.join(self.drain_wait_s + 1.0)
        for fds in self._fds.values():
            self._close_slot(fds, 0)
        self._close_fd("_pid_r")

    def close(self) -> None:
        for fds in self._fds.values():
            for i in range(3):
                self._close_slot(fds, i)
        if os.path.basename(self.dir).startswith(OUTPUT_CAPTURE_PREFIX):
            shutil.rmtree(self.dir, ignore_errors=True)

    # -- facts ----------------------------------------------------------------
    @property
    def cut(self) -> bool:
        return self.over_max or self.disk_full

    def lines(self, stream: str) -> int:
        n = self.newlines[stream]
        return n + (1 if self.bytes[stream] and self.last[stream] != b"\n" else 0)

    # -- internals --------------------------------------------------------------
    @staticmethod
    def _close_slot(fds: List[Optional[int]], i: int) -> None:
        fd = fds[i]
        fds[i] = None
        if fd is not None:
            try:
                os.close(fd)
            except OSError:
                pass

    def _close_fd(self, name: str) -> None:
        fd = getattr(self, name)
        setattr(self, name, None)
        if fd is not None:
            try:
                os.close(fd)
            except OSError:
                pass

    def _child_pid(self) -> Optional[int]:
        if self._pid is None and self._pid_r is not None:
            try:
                raw = os.read(self._pid_r, 32)
                self._pid = int(raw.decode("ascii").strip() or 0) or None
            except (OSError, ValueError):
                self._pid = None
        return self._pid

    def _stop_program(self) -> None:
        """SIGKILL the child's process group (``timeout`` leads its own group,
        so the program and everything it started go too); the pid alone when
        the group is not there yet."""
        if self.stopped:
            return
        self.stopped = True
        pid = self._child_pid()
        if not pid:
            print("[HANDLER] output: the program's pid is unknown, so it runs on unread until it exits")
            return
        for kill in (os.killpg, os.kill):
            try:
                kill(pid, signal.SIGKILL)
                return
            except OSError:
                continue

    def _copy(self, stream: str) -> None:
        r, _w, out = self._fds[stream]
        poller = select.poll()      # not select(): no FD_SETSIZE limit on the descriptor
        poller.register(r, select.POLLIN | select.POLLHUP | select.POLLERR)
        try:
            while True:
                if self._done.is_set():
                    # The program has exited. A pipe still open now is held
                    # by a process it started: it is read until end of file
                    # or until the drain wait ends, pauses and all. What it
                    # prints after that is not kept, and the result says so.
                    left = self._drain_until - time.monotonic()
                    if left <= 0:
                        self.still_writing = True
                        break
                    if not poller.poll(max(1, min(200, int(left * 1000)))):
                        continue
                elif not poller.poll(200):
                    continue
                chunk = os.read(r, _OUTPUT_COPY_CHUNK)
                if not chunk:
                    break
                with self._lock:
                    if self.cut:
                        self.dropped += len(chunk)
                        continue
                    room = self.max_bytes - self.bytes["stdout"] - self.bytes["stderr"]
                    keep = chunk if len(chunk) <= room else chunk[:max(0, room)]
                    if len(keep) < len(chunk):
                        self.over_max = True
                        self.dropped += len(chunk) - len(keep)
                    self.bytes[stream] += len(keep)
                if keep:
                    try:
                        _write_all(out, keep)
                    except OSError as e:
                        with self._lock:
                            self.bytes[stream] -= len(keep)
                            self.dropped += len(keep)
                            self.disk_full = True
                        print(f"[HANDLER] output: {stream} capture stopped, {type(e).__name__}: {e}")
                        self._stop_program()
                        continue
                    with self._lock:
                        self.newlines[stream] += keep.count(b"\n")
                        self.chars[stream] += len(keep.translate(None, _UTF8_CONTINUATION))
                        self.last[stream] = keep[-1:]
                if self.over_max:
                    self._stop_program()
        except (OSError, ValueError) as e:
            print(f"[HANDLER] output: {stream} copy ended: {type(e).__name__}: {e}")


class _StreamOutput:
    """One stream's output for the response: from the capture's file, or from
    bytes a caller's own capture returned (``subprocess.run`` stand-ins)."""

    def __init__(self, data: Optional[bytes] = None, path: Optional[str] = None, size: int = 0,
                 chars: int = 0, lines: int = 0, cut: bool = False, fd: Optional[int] = None):
        self.data, self.path, self.size, self.chars, self.lines, self.cut = data, path, size, chars, lines, cut
        #: The capture file's descriptor: read through it, never by path.
        self.fd = fd

    @classmethod
    def from_bytes(cls, raw: Any) -> "_StreamOutput":
        data = raw if isinstance(raw, (bytes, bytearray)) else str(raw or "").encode("utf-8", errors="replace")
        data = bytes(data)
        lines = data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)
        return cls(data=data, size=len(data), chars=len(data.translate(None, _UTF8_CONTINUATION)), lines=lines)

    def read(self, start: int, n: int) -> bytes:
        start = max(0, min(start, self.size))
        n = max(0, min(n, self.size - start))
        if self.data is not None:
            return self.data[start:start + n]
        if self.fd is not None:
            parts: List[bytes] = []
            while n > 0:
                chunk = os.pread(self.fd, min(n, _OUTPUT_COPY_CHUNK * 16), start)
                if not chunk:
                    break
                parts.append(chunk)
                start += len(chunk)
                n -= len(chunk)
            return b"".join(parts)
        with open(self.path, "rb", opener=_open_nofollow) as fh:
            fh.seek(start)
            return fh.read(n)

    def open(self):
        import io
        if self.data is not None:
            return io.BytesIO(self.data)
        if self.fd is not None:
            fh = os.fdopen(os.dup(self.fd), "rb")
            fh.seek(0)
            return fh
        return open(self.path, "rb", opener=_open_nofollow)


def _open_nofollow(path: str, flags: int) -> int:
    return os.open(path, flags | getattr(os, "O_NOFOLLOW", 0))


def _stream_outputs(result: Any, capture: Optional[_OutputCapture]) -> Dict[str, _StreamOutput]:
    out: Dict[str, _StreamOutput] = {}
    for s in OUTPUT_STREAMS:
        raw = getattr(result, s, None)
        if raw is not None or capture is None:
            out[s] = _StreamOutput.from_bytes(raw)
        else:
            out[s] = _StreamOutput(path=capture.paths[s], size=capture.bytes[s], chars=capture.chars[s],
                                   lines=capture.lines(s), cut=capture.cut, fd=capture.file_fd(s))
    return out


def _decode(data: bytes) -> str:
    return data.decode("utf-8", errors="replace")


def _saved_preview(stream: _StreamOutput, inline: int, rel: str) -> str:
    """The first and last part of a saved stream within ``inline``
    characters, each cut back to a whole line where one ends nearby, with
    one line between them naming what is not shown and where it is."""
    probe = (f"\n[... {stream.size:,} bytes not shown. The full output, {stream.size:,} bytes in "
             f"{stream.lines:,} lines, is saved in {rel} ...]\n")
    half = max(1, (inline - len(probe) - 2) // 2)
    head_b = stream.read(0, half)
    cut = head_b.rfind(b"\n")
    if cut >= len(head_b) // 2:
        head_b = head_b[:cut + 1]
    tail_b = stream.read(stream.size - half, half)
    start = tail_b.find(b"\n")
    if 0 <= start < len(tail_b) // 2:
        tail_b = tail_b[start + 1:]
    hidden = max(0, stream.size - len(head_b) - len(tail_b))
    head, tail = _decode(head_b), _decode(tail_b)
    sep = "" if head.endswith("\n") else "\n"
    marker = (f"[... {hidden:,} bytes not shown. The full output, {stream.size:,} bytes in {stream.lines:,} "
              f"lines, is saved in {rel} ...]\n")
    return f"{head}{sep}{marker}{tail}"


def _unsaved_preview(stream: _StreamOutput, inline: int) -> str:
    """A stream too long to return that could not be saved: its start, a line
    saying so, and the old cut marker (callers read it as a cut)."""
    note = (f"\n[This output was {stream.size:,} bytes and could not be saved, so only the first part "
            "is shown.]\n[OUTPUT TRUNCATED]")
    keep = max(1, inline - len(note))
    return _decode(stream.read(0, keep)) + note


def _output_save_dir(raw: Any) -> str:
    rel = str(raw or "").strip().rstrip("/")
    if rel and _safe_workspace_rel(rel) is not None and rel.split("/", 1)[0] in _OUTPUT_SAVE_ROOTS:
        return rel + "/"
    return OUTPUT_SAVE_DEFAULT_DIR


def _name_taken(error: Exception) -> bool:
    code = str(((getattr(error, "response", None) or {}).get("Error") or {}).get("Code") or "")
    return code in _OUTPUT_PRECONDITION_CODES or "PreconditionFailed" in str(error)


def _key_exists(s3: Any, bucket: str, key: str) -> bool:
    """True only when HEAD finds ``key``. A missing key, a refused HEAD
    (a 403 without list rights) or a client without HEAD is "not known to
    exist": the conditional put then decides."""
    head = getattr(s3, "head_object", None)
    if not callable(head):
        return False
    try:
        head(Bucket=bucket, Key=key)
        return True
    except Exception:  # noqa: BLE001
        return False


def _put_if_absent(s3: Any, bucket: str, key: str, body: Any, extra: Dict[str, Any]) -> None:
    """``put_object`` with ``IfNoneMatch="*"``. A botocore older than the
    parameter (a custom image's own boto3) refuses it before sending; the
    name was already checked with HEAD, so the put is sent without it."""
    try:
        s3.put_object(Bucket=bucket, Key=key, Body=body, IfNoneMatch="*", **extra)
    except Exception as e:  # noqa: BLE001
        if type(e).__name__ != "ParamValidationError" or "IfNoneMatch" not in str(e):
            raise
        print("[HANDLER] output: this image's botocore has no IfNoneMatch; saving after the HEAD check only")
        if hasattr(body, "seek"):
            body.seek(0)
        s3.put_object(Bucket=bucket, Key=key, Body=body, **extra)


def _put_output(s3: Any, bucket: str, prefix: str, folder: str, stem: str, stream_name: str,
                stream: _StreamOutput, start: int) -> Tuple[str, str, int]:
    """Put one stream at ``{folder}{stem}-{n:03}-{stream}.txt`` for the first
    free ``n`` from ``start``. A taken name is found with HEAD, so it costs
    no upload; the put itself is conditional (``IfNoneMatch``), so a name
    another run takes meanwhile is never overwritten. Past
    `_OUTPUT_NAME_TRIES` taken names, and for a stream over S3's single-put
    limit (it goes up in parts), the name is made unique instead, so a save
    never fails for want of a name. Returns ``(rel, key, n)``."""
    n = max(1, int(start))
    big = stream.size > _OUTPUT_SINGLE_PUT_MAX
    for attempt in range(_OUTPUT_NAME_TRIES + 1):
        unique = big or attempt == _OUTPUT_NAME_TRIES
        rel = f"{folder}{stem}-{n:03}-{stream_name}.txt"
        if unique:
            rel = f"{folder}{stem}-{n:03}-{uuid.uuid4().hex[:8]}-{stream_name}.txt"
        key = f"{prefix.rstrip('/')}/{rel}"
        if not unique and _key_exists(s3, bucket, key):
            n += 1
            continue
        extra = _s3_put_args(key, "text/plain; charset=utf-8")
        try:
            with stream.open() as body:
                if big:
                    s3.upload_fileobj(body, bucket, key, ExtraArgs=extra)
                else:
                    _put_if_absent(s3, bucket, key, body, extra)
            return rel, key, n
        except Exception as e:  # noqa: BLE001
            if not _name_taken(e) or unique:
                raise
            n += 1
    raise RuntimeError(f"no free name after {_OUTPUT_NAME_TRIES} tries")


def _save_outputs(event: Dict[str, Any], s3_bucket: str, s3_prefix: str,
                  streams: Dict[str, _StreamOutput]) -> Tuple[Dict[str, Dict[str, Any]], List[Dict[str, str]]]:
    """Save every stream longer than its inline size; stderr takes the run
    number stdout got. Returns ``({stream: file}, [{stream, error}])``."""
    opts = event.get("output_save") if isinstance(event.get("output_save"), dict) else {}
    folder = _output_save_dir(opts.get("dir"))
    stem = str(opts.get("stem") or "").strip()
    if not _OUTPUT_STEM_RE.match(stem):
        stem = f"kernel-{uuid.uuid4().hex[:12]}"
    seq = _positive_int(opts.get("start")) or 1
    files: Dict[str, Dict[str, Any]] = {}
    errors: List[Dict[str, str]] = []
    for name in OUTPUT_STREAMS:
        stream = streams[name]
        if stream.size <= _inline_max(event, name):
            continue
        if not (s3_bucket and s3_prefix):
            errors.append({"stream": name, "error": "no workspace to save to"})
            continue
        if not _output_save_fits(stream.size, _invocation_time_left(), _output_timing(event)):
            print(f"[HANDLER] output: not saving {name} ({stream.size} bytes): too little time left in the invocation")
            errors.append({"stream": name, "error": "too little time left to save it before the kernel's time limit"})
            continue
        try:
            rel, key, seq = _put_output(_s3_client(), s3_bucket, s3_prefix, folder, stem, name, stream, seq)
        except Exception as e:  # noqa: BLE001
            print(f"[HANDLER] output: saving {name} ({stream.size} bytes) failed: {type(e).__name__}: {e}")
            errors.append({"stream": name, "error": f"{type(e).__name__}: {str(e)[:200]}"})
            continue
        files[name] = {"key": key, "path": rel, "bytes": stream.size, "chars": stream.chars,
                       "lines": stream.lines, "seq": seq, "cut": stream.cut}
        print(f"[HANDLER] output: {name} saved in full, {stream.size} bytes, {stream.lines} lines -> {rel}")
    return files, errors


#: Said on stderr when a process the program started still held its output
#: once the drain wait ended (``output_still_writing``).
OUTPUT_STILL_WRITING_SENTENCE = ("A process the program started was still running when the program ended. "
                                 "Output it printed after that is not kept.")


def _output_stop_sentence(capture: _OutputCapture, files: Dict[str, Dict[str, Any]]) -> str:
    where = " and ".join(f["path"] for f in files.values())
    if capture.disk_full:
        sentence = "The kernel's disk filled up while the program printed its output, so the program was stopped."
        return sentence + (f" The output so far is saved in {where}." if where else " Its output could not be saved.")
    limit = _size_text(capture.max_bytes)
    sentence = f"The program printed more than {limit} of output, so it was stopped."
    if where:
        sentence += f" The first {limit} are saved in {where}."
    else:
        sentence += " Its output could not be saved."
    return sentence + " Write large results to a file under outputs/ instead of printing them."


# ---------------------------------------------------------------------------
# Credential isolation.
#
# The Lambda runtime vends this execution environment's IAM role credentials
# as plain environment variables on the process `handler()` runs in, and the
# user's own script or shell command runs as a CHILD of that process - same
# uid, same /tmp. Two facts made that a tenant-isolation hole rather than an
# untidiness:
#
# * ``/proc/<pid>/environ`` is the environment block a process was STARTED
#   with. ``os.environ.pop`` rewrites the C ``environ`` pointers, not that
#   block, so a child that reads ``/proc/<ppid>/environ`` recovers every
#   variable the runtime set. Stripping the child's own ``env=`` (which this
#   file has done since D.1.a - `_sandboxed_env`) never closed that.
# * The role those credentials belong to (``<project>-<env>-lambda-execution-
#   role``) was granted the WHOLE workspaces bucket and EVERY agent's
#   connector secret, so the recovered credentials reached other users'
#   ``users/<uid>/`` trees and other agents' secrets directly with boto3.
#
# Four layers, each deterministic - no prompt and no model in any of them:
#
# 1. **Re-exec with a clean environment** (`_reexec_with_clean_environment`).
#    At import - the delivery bootstrap imports this module BEFORE it starts
#    ``awslambdaric`` - the handler writes the credential variables into a
#    pipe, drops them from the environment and ``execve``s itself: the same
#    interpreter, the handler directory first on ``sys.path``, then
#    ``awslambdaric`` via ``runpy`` exactly as the bootstrap would have
#    started it. The process that serves invocations was therefore STARTED
#    without credentials: its ``/proc/<pid>/environ`` has none to give. The
#    next image reads them back from the pipe into `_ROLE_CREDENTIALS` -
#    process memory, never a file, never the environment. ``awslambdaric``
#    itself never reads AWS credentials (it reads ``AWS_LAMBDA_RUNTIME_API``
#    and ``_LAMBDA_TELEMETRY_LOG_FD``, and sets ``_X_AMZN_TRACE_ID``), and the
#    runtime vends the role credentials ONCE per execution environment - no
#    per-invocation refresh - so the in-memory copy has exactly the lifetime
#    the variables had. Skipped, and reported as such, when this module is
#    imported by an already-running ``awslambdaric`` (the legacy ``python -m
#    awslambdaric`` entry point, or the bootstrap's baked fallback: its
#    telemetry fd is already consumed and an exec would lose it) - layer 2
#    stands alone there.
# 2. **Non-dumpable process** (`_nondumpable_image`, `_set_non_dumpable`,
#    `_measure_non_dumpable`). For a task whose dumpable flag is not
#    ``SUID_DUMP_USER`` the kernel's ``ptrace_may_access`` refuses a
#    same-uid, non-root process ``/proc/<pid>/environ``, ``mem``, ``maps``
#    and ``ptrace`` attach (only ``CAP_SYS_PTRACE`` gets through), whatever
#    ``kernel.yama.ptrace_scope`` says - and ``task_dump_owner`` hands those
#    /proc files to root, so plain file permissions refuse them too. Two
#    ways to get there, both taken:
#    * the clean image is started from an EXEC-ONLY COPY of the interpreter
#      (mode 0100, in the overlay directory, pre-flighted as a child first).
#      ``execve`` of a file its caller may not read sets
#      ``BINPRM_FLAGS_ENFORCE_NONDUMP`` (``would_dump``) and the new mm gets
#      ``fs.suid_dumpable`` (2 on Lambda's kernel, 0 elsewhere) instead of
#      ``SUID_DUMP_USER``: non-dumpable from its first instruction, with no
#      syscall the process has to be allowed. ``argv[0]`` stays the real
#      interpreter, so ``sys.executable`` and ``sys.prefix`` are unchanged
#      and every child still runs the installation's python.
#    * ``prctl(PR_SET_DUMPABLE, 0)`` in the serving process, where the kernel
#      lets it. Under the Lambda runtime it does NOT: the sandbox runs under
#      seccomp (``Seccomp: 2``, six filters, ``NoNewPrivs: 1``, kernel 5.10
#      amzn2) that answers EVERY prctl - PR_GET_DUMPABLE included - with
#      EPERM (measured live, inside a sandbox). The first release of this
#      layer was this call alone, so it was never in effect there; the
#      refusal is now recorded (``credential_isolation.prctl``), never
#      swallowed.
#    ``execve`` resets the flag to ``SUID_DUMP_USER`` for a readable binary,
#    which is why the copy must be the very file the clean image is exec'd
#    from. ``PR_SET_PTRACER`` adds nothing: it is a Yama hook, Yama is absent
#    from the Lambda kernel (``ptrace_scope: absent``), so EINVAL at best -
#    and EPERM under that seccomp anyway. Measured, not assumed: the owner of
#    ``/proc/self/status`` (root <=> non-dumpable, for a non-root process) at
#    import and again on every invocation (``credential_isolation.
#    non_dumpable``), plus a REAL child of this process trying
#    ``/proc/<ppid>/environ``, ``maps`` and ``mem``
#    (``child_can_read_parent_environ``, ``child_can_open_parent_mem``).
#    Bound: the baked fallback and the legacy entry point (awslambdaric
#    already running, no re-exec possible) have only the prctl half, which
#    Lambda refuses - reported as ``non_dumpable: false`` on the row and a
#    WARNING on every invocation, never silent.
# 3. **Least privilege per invocation** (`AccessScope`, `_scoped_session`).
#    Every S3 and Secrets Manager call this file makes on the user's behalf
#    - mirror down and up, prefetch, ``fetch_object``, ``read_file`` /
#    ``write_file`` / ``list_files``, the connector secret - uses STS session
#    credentials from assuming ``<project>-<env>-sandbox-scoped-role``
#    (core.yaml; trusted by the execution role alone) WITH a session policy
#    narrowed to this invocation: read on ``users/<uid>/`` plus whatever
#    ``read_prefixes`` the invoking service adds (a governed deployment passes
#    ``users/``: reads deployment-wide, writes the writer's own folder), write
#    on ``users/<uid>/`` only, and the ONE secret
#    ``alphaagent-connector-creds-<agent_id>``. The role's own policy is the
#    old bucket-wide grant; the session policy is what makes it per user,
#    and `_scoped_session` never calls AssumeRole without one. Sessions are
#    cached per (bucket, prefixes, agent) for the container's life and
#    renewed 20 minutes before expiry (an invocation can run for 15). The
#    execution role keeps only what starting the function takes: the overlay
#    read, logs, ENI, ECR, and AssumeRole. `_s3_client` and `_secrets_client`
#    are the ONLY places this file builds those clients, and they refuse to
#    build one outside an invocation (`_CURRENT_SCOPE`).
# 4. **Child hardening** (`_exec_env`). The credential variables
#    (`_LAMBDA_CREDENTIAL_ENV_KEYS`) and the variables an SDK would follow to
#    find credentials (`_CREDENTIAL_SOURCE_ENV_KEYS`) never reach a child, and
#    ``AWS_EC2_METADATA_DISABLED=true`` makes a stray ``boto3`` in the sandbox
#    raise ``NoCredentialsError`` at once instead of waiting on a metadata
#    service Lambda does not have.
#
# When the scoped role cannot be assumed - a deployment whose core stack
# predates it (STS answers AccessDenied), or STS unreachable - the handler
# falls back to the execution role's own credentials for THAT invocation
# only, never cached across invocations, logs it, and reports
# ``credential_scope`` in the probe. On a current core stack that fallback
# reaches nothing in S3 (the grant moved to the scoped role), so a failure
# is loud, never silent.
# ---------------------------------------------------------------------------
_HANDLER_DIR = os.path.dirname(os.path.abspath(__file__))

#: The runtime's own role credentials, as it vends them: plain environment
#: variables. Moved to memory at import; never in a child's environment.
_LAMBDA_CREDENTIAL_ENV_KEYS = (
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "AWS_SESSION_TOKEN",
    "AWS_SECURITY_TOKEN",  # legacy alias some SDKs still read
)
#: Not credentials, but where an SDK goes looking for some - never in a
#: child's environment either. Exact names: a connector's
#: ``CONN_<id>_AWS_PROFILE`` is a different name and survives.
_CREDENTIAL_SOURCE_ENV_KEYS = (
    "AWS_CONTAINER_CREDENTIALS_FULL_URI",
    "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
    "AWS_CONTAINER_AUTHORIZATION_TOKEN",
    "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
    "AWS_WEB_IDENTITY_TOKEN_FILE",
    "AWS_ROLE_ARN",
    "AWS_ROLE_SESSION_NAME",
    "AWS_CREDENTIAL_EXPIRATION",
    "AWS_SHARED_CREDENTIALS_FILE",
    "AWS_CONFIG_FILE",
    "AWS_PROFILE",
)
#: Set in every child: boto3 fails fast (``NoCredentialsError``) instead of
#: waiting on an instance metadata service Lambda does not have.
_CHILD_NO_METADATA_ENV = {"AWS_EC2_METADATA_DISABLED": "true"}
#: The re-exec'd image reads the role credentials (JSON) from this fd.
CREDENTIALS_FD_ENV = "AA_ROLE_CREDENTIALS_FD"
#: Function-level override for the scoped role's ARN; otherwise derived from
#: the execution role's name (`_scoped_role_arn`) - core.yaml pins both.
SANDBOX_ROLE_ARN_ENV = "AA_SANDBOX_ROLE_ARN"
EXECUTION_ROLE_SUFFIX = "-lambda-execution-role"
SANDBOX_ROLE_SUFFIX = "-sandbox-scoped-role"
#: Where the delivery bootstrap unpacks the pair (``AA_HANDLER_DIR``, default
#: as agent-management's ``OVERLAY_DIR``): the re-exec runs only for the
#: delivered overlay, mirroring the bootstrap's own shadow check.
OVERLAY_DIR_ENV = "AA_HANDLER_DIR"
DEFAULT_OVERLAY_DIR = "/tmp/aa_handler"
#: The exec-only copy of the interpreter the clean image runs from
#: (`_nondumpable_image`), next to this file in the overlay; mode 0100.
NONDUMPABLE_IMAGE_NAME = ".python-nondumpable"
#: How the previous image started this one - ``exec-only:<pre-flight
#: verdict>`` or ``plain:<why not>`` - set for the re-exec, popped at import.
EXEC_IMAGE_ENV = "AA_HANDLER_EXEC_IMAGE"
#: The exec-only copy is run once as a child before this process commits to
#: it; a cold start's init phase has 10 s in total.
IMAGE_PREFLIGHT_TIMEOUT_S = 5
#: Optional event field, trusted because only the platform's services can
#: invoke the function: extra key prefixes this invocation may READ, each
#: rooted at ``users/``. A governed deployment passes ``["users/"]``.
READ_PREFIXES_EVENT_KEY = "read_prefixes"
#: The Folio contract C7.6: event field, ``true`` only from a
#: governed deployment. It is what admits the Team folder (``team/``) as a
#: read prefix; a standard deployment never sends it and never reads there.
GOVERNED_EVENT_KEY = "governed"
#: Event field: the Folio files this run may read, ``[{key, version_id,
#: path}]``. Each is downloaded by version to ``path`` (always under
#: ``refs/``) before the program runs. Nothing under ``refs/`` is ever
#: uploaded: references are read only.
REFS_EVENT_KEY = "refs"
REFS_DIR = "refs"
#: Longest ``refs/`` path taken from an event, in bytes.
REFS_PATH_MAX_BYTES = 512
#: The tag on every object Studio wrote from a personal sign-in result. The
#: session policy denies reading one that belongs to anybody but the owner
#: of this invocation (the Folio contract C19.4).
PERSONAL_OWNER_TAG = "aa-personal-owner"
#: One secret per agent (``connector_creds.py`` creates it under this name).
#: Secrets Manager appends ``-`` and six random characters to the name in
#: the ARN, hence ``??????`` in the session policy.
CONNECTOR_SECRET_PREFIX = "alphaagent-connector-creds-"
#: The deployment's trusted certificate authorities (PEM, written by
#: Organisations; see "Trusted certificate authorities" below). Same name as
#: the services' own reader uses.
TRUSTED_CA_SECRET_NAME = "alphaagent-trusted-ca-bundle"
#: A warm container re-reads that secret on its first invocation after this
#: many seconds, so a change made on the deployment's Overview reaches every
#: warm container within five minutes.
TRUSTED_CA_REFRESH_S = 300
#: ``RoleSessionName`` of the one AssumeRole that reads the trusted CAs.
TRUST_SESSION_NAME = "aa-env-trust"
#: The shortest session STS grants; one read is all it is used for.
TRUST_SESSION_DURATION_S = 900
#: Role chaining (the execution role is itself an assumed role) caps
#: AssumeRole at one hour; renew well before an invocation could outlive it.
#: An invocation runs for up to AWS Lambda's 1,800 seconds (PRO-2371), so a
#: cached session is reused only while it has more than 35 minutes left.
_SCOPED_SESSION_DURATION_S = 3600
_SCOPED_SESSION_REFRESH_MARGIN_S = 35 * 60
_SCOPED_SESSION_CACHE_MAX = 64
_STS_CONNECT_TIMEOUT_S = 3
_STS_READ_TIMEOUT_S = 10
#: What may be embedded in a session policy: no wildcards, no ``$`` (IAM
#: policy variables), no path tricks. A uid or agent id is a single segment.
#: An owner id may carry a colon (``apikey:<key_id>``, ``service:<name>``);
#: the colon is not an IAM metacharacter and S3 keys may contain it.
_POLICY_ID_RE = re.compile(r"^[A-Za-z0-9_.@:-]{1,128}$")
_POLICY_PREFIX_RE = re.compile(r"^[A-Za-z0-9_./@:-]{1,512}$")
_USERS_PREFIX_RE = re.compile(r"^users/([^/]+)/")

#: This execution environment's role credentials - process memory only.
_ROLE_CREDENTIALS: Optional[Dict[str, str]] = None
#: What the isolation layers did at import, for the probe (`_isolation_report`).
_ISOLATION: Dict[str, Any] = {}


def _sandboxed_env(base: Dict[str, str]) -> Dict[str, str]:
    """`base`, minus this Lambda's own IAM credentials (layer 4, first half;
    `_exec_env` adds the rest). Exactly these four names and no others: every
    connector variable is ``CONN_<connector_id>_...`` (the shape the
    service's ``connector_loader.build_connector_env_vars`` produces and this
    file's own secret payload carries), so removing these cannot drop a real
    connector credential."""
    return {k: v for k, v in base.items() if k not in _LAMBDA_CREDENTIAL_ENV_KEYS}


# -- layer 1: re-exec ------------------------------------------------------

def _reexec_argv(handler_dir: str, handler_args: List[str]) -> List[str]:
    """The command the clean image runs: this interpreter with the flags it
    was started with, an inline bootstrap that puts ``handler_dir`` first on
    ``sys.path``, imports ``handler`` and starts ``awslambdaric`` the way the
    delivery bootstrap does (``runpy``), then the handler name
    ``awslambdaric`` reads as ``argv[1]``."""
    inline = (
        f"import sys;sys.path.insert(0,{handler_dir!r});import handler;"
        "import runpy;runpy.run_module('awslambdaric',run_name='__main__',alter_sys=True)"
    )
    orig = list(getattr(sys, "orig_argv", None) or [])
    flags = orig[1:orig.index("-c")] if "-c" in orig[1:] else []
    return [sys.executable, *flags, "-c", inline, *handler_args]


def _reexec_skip_reason(module_name: str) -> Optional[str]:
    """Why NOT to re-exec at this import, or None when it should happen. The
    conditions are those under which the delivery bootstrap imported us:
    real runtime, credentials in the environment, ``awslambdaric`` not yet
    started, imported as ``handler`` from the delivered overlay."""
    env = os.environ
    if env.get(CREDENTIALS_FD_ENV):
        return "done"
    if not (env.get("AWS_ACCESS_KEY_ID") and env.get("AWS_SECRET_ACCESS_KEY")):
        return "not needed: no role credentials in the environment"
    if not env.get("AWS_LAMBDA_RUNTIME_API"):
        return "skipped: not running under the Lambda runtime API"
    if "awslambdaric" in sys.modules:
        return "skipped: awslambdaric is already running (image entry point or baked fallback)"
    if module_name != "handler":
        return f"skipped: imported as {module_name!r}, not as the handler module"
    overlay = os.path.realpath(env.get(OVERLAY_DIR_ENV) or DEFAULT_OVERLAY_DIR)
    here = os.path.realpath(_HANDLER_DIR)
    if here != overlay and not here.startswith(overlay + os.sep):
        return f"skipped: not the delivered overlay ({_HANDLER_DIR})"
    return None


def _reexec_with_clean_environment(handler_args: List[str]) -> str:
    """Layer 1. Hand the role credentials to the next image of this process
    over a pipe and ``execve`` it with an environment that carries none.
    Returns only on failure, with the reason; on success this process is
    replaced and nothing after the call runs."""
    creds = {k: os.environ[k] for k in _LAMBDA_CREDENTIAL_ENV_KEYS if os.environ.get(k)}
    env = {k: v for k, v in os.environ.items() if k not in _LAMBDA_CREDENTIAL_ENV_KEYS}
    # The bootstrap records its verdict AFTER importing us; this import
    # never returns to it, so record the verdict it was about to.
    env.setdefault(HANDLER_DELIVERY_ENV, "overlay")
    # Layer 2 rides on this exec: the clean image runs from an exec-only copy
    # of the interpreter and is non-dumpable from its first instruction - the
    # kernel path Lambda's seccomp cannot refuse (`_nondumpable_image`).
    image, note = _nondumpable_image(_HANDLER_DIR, env)
    env[EXEC_IMAGE_ENV] = f"exec-only:{note}" if image else f"plain:{note}"
    read_fd, write_fd = os.pipe()
    try:
        os.set_inheritable(read_fd, True)
        payload = json.dumps(creds).encode("utf-8")
        written = 0
        while written < len(payload):
            written += os.write(write_fd, payload[written:])
        os.close(write_fd)
        write_fd = -1
        env[CREDENTIALS_FD_ENV] = str(read_fd)
        argv = _reexec_argv(_HANDLER_DIR, handler_args)
        print(f"[HANDLER] credential isolation: re-executing with a clean environment "
              f"({len(creds)} credential variable(s) moved to memory; image={env[EXEC_IMAGE_ENV]})", flush=True)
        sys.stdout.flush()
        sys.stderr.flush()
        if image:
            try:
                os.execve(image, argv, env)
            except OSError as exc:
                # Never a failed cold start: the plain interpreter, reported.
                env[EXEC_IMAGE_ENV] = f"plain:execve of the exec-only copy failed: {type(exc).__name__}: {exc}"
                print(f"[HANDLER] credential isolation: {env[EXEC_IMAGE_ENV]}", flush=True)
        os.execve(sys.executable, argv, env)
    except OSError as exc:
        for fd in (read_fd, write_fd):
            if fd >= 0:
                try:
                    os.close(fd)
                except OSError:
                    pass
        return f"failed: {type(exc).__name__}: {exc}"
    return "failed: execve returned"


def _read_fd_fully(fd: int) -> bytes:
    chunks: List[bytes] = []
    while True:
        chunk = os.read(fd, 65536)
        if not chunk:
            return b"".join(chunks)
        chunks.append(chunk)


def _capture_role_credentials(scrub_environment: bool) -> Tuple[Optional[Dict[str, str]], str, Optional[str]]:
    """Move the role credentials into memory: from the pipe the previous image
    of this process left (`_reexec_with_clean_environment`), else from the
    environment - the paths that did not re-exec - which, under the runtime,
    is then cleared of them so they are not base names for a child
    (`_BASE_ENV_KEYS`). The previous image's other hand-over, how it started
    this one (`EXEC_IMAGE_ENV`: ``exec-only:<verdict>`` | ``plain:<why>``),
    leaves the environment here too. Returns ``(credentials or None, "pipe"
    | "environment" | "none", exec_image or None)``."""
    exec_image = os.environ.pop(EXEC_IMAGE_ENV, None)
    fd_raw = os.environ.pop(CREDENTIALS_FD_ENV, None)
    if fd_raw:
        try:
            fd = int(fd_raw)
            try:
                raw = _read_fd_fully(fd)
            finally:
                os.close(fd)
            creds = {k: str(v) for k, v in json.loads(raw.decode("utf-8")).items()
                     if k in _LAMBDA_CREDENTIAL_ENV_KEYS and v}
            if creds.get("AWS_ACCESS_KEY_ID") and creds.get("AWS_SECRET_ACCESS_KEY"):
                return creds, "pipe", exec_image
            print("[HANDLER] credential isolation: the pipe carried no usable role credentials")
        except (OSError, ValueError) as exc:
            print(f"[HANDLER] credential isolation: could not read the role credentials from the pipe: {exc}")
    creds = {k: os.environ[k] for k in _LAMBDA_CREDENTIAL_ENV_KEYS if os.environ.get(k)}
    if scrub_environment:
        for k in _LAMBDA_CREDENTIAL_ENV_KEYS:
            os.environ.pop(k, None)
    if creds.get("AWS_ACCESS_KEY_ID") and creds.get("AWS_SECRET_ACCESS_KEY"):
        return creds, "environment", exec_image
    return None, "none", exec_image


# -- layer 2: non-dumpable ---------------------------------------------------

#: Runs INSIDE the exec-only copy, as a child of the pre-exec image, before
#: that image commits to it: does the copy start at all, and does this kernel
#: make a process started from it non-dumpable? One word on stdout.
_IMAGE_PREFLIGHT = (
    "import os\n"
    "print('unknown' if os.geteuid()==0 else "
    "('nondumpable' if os.stat('/proc/self/status').st_uid==0 else 'dumpable'))"
)
_PR_GET_DUMPABLE, _PR_SET_DUMPABLE = 3, 4


def _nondumpable_image(handler_dir: str, env: Dict[str, str]) -> Tuple[Optional[str], str]:
    """Layer 2, at the re-exec: an exec-only copy (mode 0100) of this
    interpreter for the clean image to run from. ``execve`` of a file its
    caller may not read makes the new process non-dumpable from its first
    instruction (``would_dump`` -> ``BINPRM_FLAGS_ENFORCE_NONDUMP`` ->
    ``set_dumpable(mm, fs.suid_dumpable)``): the kernel path that needs no
    ``prctl``, which Lambda's seccomp refuses. The copy is pre-flighted as a
    child before this process commits to it, so an interpreter that cannot
    run from a copy (an ``$ORIGIN`` rpath, a noexec /tmp) means a plain
    re-exec, never a failed cold start. Returns ``(path, verdict)`` - the
    pre-flight's ``nondumpable`` | ``dumpable`` | ``unknown`` (root) - or
    ``(None, reason)``. Linux only: a macOS framework build cannot start
    from a copy, and there is no /proc to protect there."""
    if not sys.platform.startswith("linux"):
        return None, "not linux"
    path = os.path.join(handler_dir, NONDUMPABLE_IMAGE_NAME)
    part = path + ".part"
    try:
        shutil.copyfile(os.path.realpath(sys.executable), part)
        os.chmod(part, 0o100)
        os.replace(part, path)
        # argv[0] stays the real interpreter: getpath derives sys.executable
        # and sys.prefix from it, so the clean image - and every child it
        # starts - keeps the installation's paths.
        proc = subprocess.run([sys.executable, "-c", _IMAGE_PREFLIGHT], executable=path, env=env,
                              capture_output=True, text=True, timeout=IMAGE_PREFLIGHT_TIMEOUT_S)
        lines = (proc.stdout or "").strip().splitlines()
        verdict = lines[-1].strip() if lines else ""
        if proc.returncode != 0 or verdict not in ("nondumpable", "dumpable", "unknown"):
            detail = (proc.stderr or proc.stdout or "").strip()[-200:] or "no verdict"
            raise OSError(f"pre-flight exit {proc.returncode}: {detail}")
        return path, verdict
    except (OSError, subprocess.SubprocessError) as exc:
        for stale in (part, path):
            try:
                os.remove(stale)
            except OSError:
                pass
        return None, f"{type(exc).__name__}: {exc}"


def _prctl(option: int, arg2: int = 0) -> Tuple[int, int]:
    """``prctl(option, arg2, 0, 0, 0)`` -> ``(rc, errno)``; ``(-1, ENOSYS)``
    where there is no prctl to call (macOS, no ctypes)."""
    if not sys.platform.startswith("linux"):
        return -1, errno.ENOSYS
    try:
        import ctypes
        fn = ctypes.CDLL(None, use_errno=True).prctl
        fn.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]
        fn.restype = ctypes.c_int
        rc = fn(option, arg2, 0, 0, 0)
        return rc, (ctypes.get_errno() if rc != 0 else 0)
    except (OSError, AttributeError, ValueError):
        return -1, errno.ENOSYS


def _set_non_dumpable() -> Dict[str, Any]:
    """Layer 2 by ``prctl(PR_SET_DUMPABLE, 0)``, where the kernel lets this
    process call prctl at all. Returns ``{"dumpable": <the flag afterwards,
    or None>, "prctl": "ok" | "<ERRNO>: <message>"}`` - a refusal is
    recorded, never swallowed: under Lambda's seccomp every prctl is EPERM
    and the exec-only image (`_nondumpable_image`) carries the layer."""
    rc, err = _prctl(_PR_SET_DUMPABLE, 0)
    if rc != 0:
        return {"dumpable": None, "prctl": f"{errno.errorcode.get(err, err)}: {os.strerror(err)}"}
    rc, _ = _prctl(_PR_GET_DUMPABLE)
    return {"dumpable": rc if rc >= 0 else None, "prctl": "ok"}


def _measure_non_dumpable(dumpable: Optional[int] = None) -> Dict[str, Any]:
    """What the kernel will actually do about a same-uid reader, measured
    without prctl: ``task_dump_owner`` gives a non-dumpable task's
    ``/proc/<pid>/{status,environ,maps,mem}`` to root, so ``/proc/self/
    status`` owned by root while this process is not root means the READ /
    ATTACH gate is closed. Returns ``{"non_dumpable": True | False | None,
    "proc_owner_uid": ...}``; None where there is no /proc, or the process is
    root (root owns its files either way) and prctl reported no flag."""
    out: Dict[str, Any] = {"non_dumpable": None, "proc_owner_uid": None}
    try:
        out["proc_owner_uid"] = os.stat("/proc/self/status").st_uid
    except OSError:
        pass
    if out["proc_owner_uid"] is not None and os.geteuid() != 0:
        out["non_dumpable"] = out["proc_owner_uid"] == 0
    elif dumpable is not None:
        out["non_dumpable"] = dumpable != 1
    return out


def _startup_environ_credential_names(at_import: List[str]) -> Tuple[Optional[List[str]], str]:
    """Credential variable names in THIS process's start-up environment block
    - what a child would find in ``/proc/<ppid>/environ`` if it could open
    it. Read from ``/proc/self/environ`` where the kernel lets this process
    read its own (a dumpable one); a process that STARTED non-dumpable (the
    exec-only image) is refused its own block - root owns it - and reports
    ``os.environ`` as it stood at import instead, which for a process that
    has not yet touched its environment IS that block. Returns ``(names or
    None, source)``."""
    try:
        with open("/proc/self/environ", "rb") as fh:
            block = fh.read()
    except OSError:
        if sys.platform.startswith("linux"):
            return list(at_import), "os.environ at import"
        return None, "no /proc"
    names = {entry.split(b"=", 1)[0].decode("utf-8", "replace") for entry in block.split(b"\0") if entry}
    return sorted(k for k in _LAMBDA_CREDENTIAL_ENV_KEYS if k in names), "/proc/self/environ"


def _reassert_non_dumpable() -> None:
    """Layer 2 on every invocation: re-apply prctl where it works, re-measure,
    and record. Nothing in this process resets the flag (only its own execve
    or a credential change would; it does neither), so this is the check,
    not the mechanism - and a serving process found dumpable is a WARNING in
    the log on every invocation, never silent."""
    if not sys.platform.startswith("linux"):
        return
    state = _set_non_dumpable()
    state.update(_measure_non_dumpable(state["dumpable"]))
    _ISOLATION.update(state)
    if state["non_dumpable"] is False:
        print("[HANDLER] WARNING: credential isolation: the serving process is dumpable - a same-uid child can "
              f"open its /proc/<pid>/environ, maps and mem (exec_image={_ISOLATION.get('exec_image')}, "
              f"prctl={state['prctl']})", flush=True)


def _read_ptrace_scope() -> Optional[str]:
    """``kernel.yama.ptrace_scope`` as the runtime's kernel reports it, or
    None when Yama is not there. Recorded, not relied on (layer 2)."""
    try:
        with open("/proc/sys/kernel/yama/ptrace_scope", "r", encoding="ascii") as fh:
            return fh.read().strip() or None
    except OSError:
        return None


def _isolate_at_import(module_name: str) -> None:
    """Layers 1 and 2, in import order: re-exec if this is the import the
    bootstrap made (never returns then), capture the credentials, snapshot
    what /proc would show a child, go non-dumpable."""
    global _ROLE_CREDENTIALS
    # The environment as this process was started with it, before anything
    # here pops a name (`_startup_environ_credential_names` may need it).
    at_import = sorted(k for k in _LAMBDA_CREDENTIAL_ENV_KEYS if k in os.environ)
    reason = _reexec_skip_reason(module_name)
    if reason is None:
        reason = _reexec_with_clean_environment(sys.argv[1:])
    _ISOLATION["reexec"] = reason
    under_runtime = bool(os.environ.get("AWS_LAMBDA_RUNTIME_API"))
    # ... plus how the previous image started this one: "exec-only:<verdict>"
    # or "plain:<why not>" (popped there - never a base name for a child).
    _ROLE_CREDENTIALS, _ISOLATION["credential_source"], _ISOLATION["exec_image"] = _capture_role_credentials(
        scrub_environment=under_runtime)
    leaked, source = _startup_environ_credential_names(at_import)
    _ISOLATION["proc_environ_credential_names"] = leaked
    _ISOLATION["proc_environ_clean"] = None if leaked is None else not leaked
    _ISOLATION["proc_environ_source"] = source
    state = _set_non_dumpable()
    state.update(_measure_non_dumpable(state["dumpable"]))
    _ISOLATION.update(state)
    _ISOLATION["ptrace_scope"] = _read_ptrace_scope() or "absent"
    _ISOLATION["environment_credential_names"] = sorted(k for k in _LAMBDA_CREDENTIAL_ENV_KEYS if k in os.environ)


_isolate_at_import(__name__)


# -- layer 3: per-invocation scope -------------------------------------------

class AccessScope(NamedTuple):
    """What one invocation may reach, derived from the event by
    `_scope_from_event`: the bucket, the prefix it may WRITE under
    (``users/<uid>/``; a legacy ``workspaces/sessions/...`` prefix is taken
    as itself), the prefixes it may READ (its own plus the caller's
    `READ_PREFIXES_EVENT_KEY`), and the agent whose ONE connector secret it
    may read (empty when the event names no connectors)."""
    bucket: str
    write_prefix: str
    read_prefixes: Tuple[str, ...]
    agent_id: str

    def grants_anything(self) -> bool:
        return bool(self.bucket and self.write_prefix) or bool(self.agent_id)

    def cache_key(self) -> str:
        return json.dumps(self._asdict(), sort_keys=True, separators=(",", ":"))

    def describe(self) -> str:
        s3 = f"s3://{self.bucket}/ write={self.write_prefix} read={list(self.read_prefixes)}" if self.bucket else "no S3"
        return f"{s3}; secret={CONNECTOR_SECRET_PREFIX + self.agent_id if self.agent_id else 'none'}"

    def policy(self, partition: str = "aws") -> Dict[str, Any]:
        """The STS session policy: the intersection with the scoped role's
        own grant is exactly this invocation's reach. ``ListBucket`` is
        conditioned on ``s3:prefix`` (a listing of ``users/`` alone has no
        matching prefix and is refused); objects are named by prefix."""
        statements: List[Dict[str, Any]] = []
        if self.bucket and self.write_prefix:
            bucket_arn = f"arn:{partition}:s3:::{self.bucket}"
            statements.append({
                "Sid": "ListWithinScope",
                "Effect": "Allow",
                "Action": ["s3:ListBucket"],
                "Resource": bucket_arn,
                "Condition": {"StringLike": {"s3:prefix": [f"{p}*" for p in self.read_prefixes]}},
            })
            statements.append({
                "Sid": "ReadWithinScope",
                "Effect": "Allow",
                # s3:GetObjectVersion: a Folio reference is read at its
                # pinned version (the Folio contract C7.6, C19.3).
                "Action": ["s3:GetObject", "s3:GetObjectVersion", "s3:GetObjectTagging"],
                "Resource": [f"{bucket_arn}/{p}*" for p in self.read_prefixes],
            })
            statements.append({
                "Sid": "WriteOwnPrefix",
                "Effect": "Allow",
                "Action": ["s3:PutObject", "s3:PutObjectTagging"],
                "Resource": [f"{bucket_arn}/{self.write_prefix}*"],
            })
        if self.bucket:
            # The Folio contract C19.4, always present: an object tagged as
            # fetched with somebody's personal sign-in is read by that
            # person's sandbox alone, whatever the read prefixes allow.
            owner = _USERS_PREFIX_RE.match(self.write_prefix or "")
            condition: Dict[str, Any] = {"Null": {f"s3:ExistingObjectTag/{PERSONAL_OWNER_TAG}": "false"}}
            if owner:
                condition["StringNotEquals"] = {f"s3:ExistingObjectTag/{PERSONAL_OWNER_TAG}": owner.group(1)}
            statements.append({
                "Sid": "DenyOthersPersonalFiles",
                "Effect": "Deny",
                "Action": ["s3:GetObject", "s3:GetObjectVersion"],
                "Resource": f"arn:{partition}:s3:::{self.bucket}/*",
                "Condition": condition,
            })
        if self.agent_id:
            statements.append({
                "Sid": "OwnConnectorSecret",
                "Effect": "Allow",
                "Action": ["secretsmanager:GetSecretValue"],
                "Resource": [f"arn:{partition}:secretsmanager:*:*:secret:{CONNECTOR_SECRET_PREFIX}{self.agent_id}-??????"],
            })
        return {"Version": "2012-10-17", "Statement": statements}


def _clean_prefix(raw: Any) -> Optional[str]:
    """A key prefix fit for a policy: no leading slash, a trailing one, no
    ``..`` segment, no wildcard or policy-variable characters."""
    text = str(raw or "").strip().lstrip("/")
    if not text or ".." in text.split("/") or not _POLICY_PREFIX_RE.match(text):
        return None
    return text.rstrip("/") + "/"


def _scope_from_event(event: Dict[str, Any]) -> AccessScope:
    """The invocation's reach, from what the trusted caller put in the event.
    The owner is read off ``s3_prefix`` (``users/<uid>/...``): the service
    already resolved which tree this session acts in (its own
    ``resolve_owned_project_prefix``), and a governed preview of another
    user's file legitimately acts in that user's tree. Anything that does
    not parse grants nothing, and `_s3_client` then refuses."""
    bucket = str(event.get("s3_bucket") or "").strip()
    prefix = _clean_prefix(event.get("s3_prefix"))
    write_prefix = ""
    if prefix:
        m = _USERS_PREFIX_RE.match(prefix)
        if m:
            write_prefix = f"users/{m.group(1)}/" if _POLICY_ID_RE.match(m.group(1)) else ""
        else:
            write_prefix = prefix           # legacy layout: exactly this tree
    if not _POLICY_ID_RE.match(bucket or "-"):
        bucket = ""
    reads: List[str] = [write_prefix] if write_prefix else []
    extra = event.get(READ_PREFIXES_EVENT_KEY)
    # The Team folder is admitted as exactly ``team/``, and only when the
    # event says the deployment is governed (C7.6). Anything else outside
    # ``users/`` is dropped, as before.
    governed = event.get(GOVERNED_EVENT_KEY) is True
    for item in (extra if isinstance(extra, list) else []):
        cleaned = _clean_prefix(item)
        if not cleaned or cleaned in reads:
            continue
        if cleaned.startswith("users/") or (governed and cleaned == "team/"):
            reads.append(cleaned)
    agent_id = str(event.get("agent_id") or "").strip()
    if not event.get("connector_ids") or not _POLICY_ID_RE.match(agent_id):
        agent_id = ""
    return AccessScope(
        bucket=bucket if write_prefix else "",
        write_prefix=write_prefix,
        read_prefixes=tuple(reads),
        agent_id=agent_id,
    )


def _aws_region() -> Optional[str]:
    return os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or None


def _error_code(exc: BaseException) -> str:
    response = getattr(exc, "response", None)
    if isinstance(response, dict):
        code = (response.get("Error") or {}).get("Code")
        if code:
            return str(code)
    return type(exc).__name__


def _role_session():
    """A session on the execution role's own credentials (memory), or on the
    default chain when none were captured (a local run). Used for two calls
    - ``sts:GetCallerIdentity`` and ``sts:AssumeRole`` - and for the fallback
    `_scoped_session` documents; never handed to user work directly."""
    if _ROLE_CREDENTIALS:
        return boto3.Session(
            aws_access_key_id=_ROLE_CREDENTIALS.get("AWS_ACCESS_KEY_ID"),
            aws_secret_access_key=_ROLE_CREDENTIALS.get("AWS_SECRET_ACCESS_KEY"),
            aws_session_token=(_ROLE_CREDENTIALS.get("AWS_SESSION_TOKEN")
                               or _ROLE_CREDENTIALS.get("AWS_SECURITY_TOKEN") or None),
            region_name=_aws_region(),
        )
    return boto3.Session(region_name=_aws_region())


def _sts_endpoint(region: str) -> str:
    suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com"
    return f"https://sts.{region}.{suffix}"


def _sts_client():
    """STS on the REGIONAL endpoint - core.yaml gives the VPC an STS interface
    endpoint whose private DNS covers ``sts.<region>.amazonaws.com``, not the
    global name - with short timeouts, so an unreachable STS fails in
    seconds rather than a minute."""
    kwargs: Dict[str, Any] = {}
    config_cls = getattr(boto3.session, "Config", None)
    if config_cls is not None:
        kwargs["config"] = config_cls(connect_timeout=_STS_CONNECT_TIMEOUT_S,
                                      read_timeout=_STS_READ_TIMEOUT_S,
                                      retries={"max_attempts": 2})
    region = _aws_region()
    if region:
        kwargs["endpoint_url"] = _sts_endpoint(region)
    return _role_session().client("sts", **kwargs)


def _derive_sandbox_role_arn(caller_arn: str) -> Optional[str]:
    """``arn:<partition>:sts::<account>:assumed-role/<project>-<env>-lambda-
    execution-role/<function>`` -> ``arn:<partition>:iam::<account>:role/
    <project>-<env>-sandbox-scoped-role``; None for any other shape."""
    parts = caller_arn.split(":")
    if len(parts) != 6:
        return None
    partition, account, resource = parts[1], parts[4], parts[5]
    segments = resource.split("/")
    if len(segments) < 2 or segments[0] != "assumed-role":
        return None
    role_name = segments[1]
    if not role_name.endswith(EXECUTION_ROLE_SUFFIX) or not partition or not account:
        return None
    return f"arn:{partition}:iam::{account}:role/{role_name[:-len(EXECUTION_ROLE_SUFFIX)]}{SANDBOX_ROLE_SUFFIX}"


#: The derived scoped-role ARN once known; "" when this role's name does not
#: follow the convention (a fact about the deployment, cached); None = not yet
#: resolved (an STS failure is NOT cached: the next invocation tries again).
_SCOPED_ROLE_ARN: Optional[str] = None


def _scoped_role_arn() -> Optional[str]:
    """The sandbox role to assume: `SANDBOX_ROLE_ARN_ENV` when the function
    configuration names it, else derived once per container from this
    process's own identity by the name convention core.yaml pins."""
    global _SCOPED_ROLE_ARN
    override = (os.environ.get(SANDBOX_ROLE_ARN_ENV) or "").strip()
    if override:
        return override
    if _SCOPED_ROLE_ARN is not None:
        return _SCOPED_ROLE_ARN or None
    try:
        caller_arn = str(_sts_client().get_caller_identity()["Arn"])
    except Exception as exc:
        print(f"[HANDLER] WARNING: could not resolve this function's own identity ({_error_code(exc)})")
        return None
    derived = _derive_sandbox_role_arn(caller_arn)
    if derived is None:
        print(f"[HANDLER] WARNING: no sandbox role can be derived from {caller_arn}; "
              f"set {SANDBOX_ROLE_ARN_ENV} on the function")
    _SCOPED_ROLE_ARN = derived or ""
    return derived


def _partition_of(arn: str) -> str:
    parts = arn.split(":")
    return parts[1] if len(parts) > 2 and parts[1] else "aws"


def _session_name(scope: AccessScope) -> str:
    return "aa-env-" + hashlib.sha256(scope.cache_key().encode("utf-8")).hexdigest()[:24]


#: ``{scope.cache_key(): (session, expires_epoch)}`` - scoped sessions only;
#: a fallback session is never cached here.
_SCOPED_SESSIONS: Dict[str, Tuple[Any, float]] = {}


def _scoped_session(scope: AccessScope) -> Tuple[Any, str]:
    """A boto3 session whose credentials reach exactly ``scope``: AssumeRole on
    the sandbox role with ``scope.policy()`` as the session policy, cached
    until `_SCOPED_SESSION_REFRESH_MARGIN_S` before expiry. Returns
    ``(session, "scoped")``, or ``(execution-role session,
    "execution-role-fallback:<reason>")`` when the role cannot be assumed."""
    if not scope.grants_anything():
        raise RuntimeError("this invocation's scope grants no S3 or Secrets Manager access")
    now = time.time()
    key = scope.cache_key()
    hit = _SCOPED_SESSIONS.get(key)
    if hit and hit[1] - now > _SCOPED_SESSION_REFRESH_MARGIN_S:
        return hit[0], "scoped"
    role_arn = _scoped_role_arn()
    if not role_arn:
        return _role_session(), "execution-role-fallback:no-scoped-role"
    try:
        response = _sts_client().assume_role(
            RoleArn=role_arn,
            RoleSessionName=_session_name(scope),
            Policy=json.dumps(scope.policy(_partition_of(role_arn)), separators=(",", ":")),
            DurationSeconds=_SCOPED_SESSION_DURATION_S,
        )
    except Exception as exc:
        code = _error_code(exc)
        print(f"[HANDLER] WARNING: could not assume {role_arn} ({code}); this invocation runs on the "
              f"execution role's own credentials")
        return _role_session(), f"execution-role-fallback:{code}"
    granted = response["Credentials"]
    session = boto3.Session(
        aws_access_key_id=granted["AccessKeyId"],
        aws_secret_access_key=granted["SecretAccessKey"],
        aws_session_token=granted["SessionToken"],
        region_name=_aws_region(),
    )
    expiry = granted.get("Expiration")
    expires_at = expiry.timestamp() if hasattr(expiry, "timestamp") else now + _SCOPED_SESSION_DURATION_S
    if len(_SCOPED_SESSIONS) >= _SCOPED_SESSION_CACHE_MAX:
        _SCOPED_SESSIONS.pop(min(_SCOPED_SESSIONS, key=lambda k: _SCOPED_SESSIONS[k][1]), None)
    _SCOPED_SESSIONS[key] = (session, expires_at)
    return session, "scoped"


#: Set by `handler` for the duration of one invocation; None between them.
_CURRENT_SCOPE: Optional[AccessScope] = None
#: The session this invocation resolved to (scoped or fallback), once.
_INVOCATION_SESSION: Optional[Tuple[Any, str]] = None


def _invocation_session():
    """The one session this invocation's S3/Secrets clients are built from.
    Resolved once per invocation (a fallback is therefore decided once, not
    re-tried on every client); refused outside `handler`."""
    global _INVOCATION_SESSION
    if _CURRENT_SCOPE is None:
        raise RuntimeError("S3 and Secrets Manager are reachable only inside handler(): no invocation scope is set")
    if _INVOCATION_SESSION is None:
        _INVOCATION_SESSION = _scoped_session(_CURRENT_SCOPE)
        _ISOLATION["credential_scope"] = _INVOCATION_SESSION[1]
    return _INVOCATION_SESSION[0]


def _s3_client():
    """THE S3 client for user work - built from this invocation's scoped
    session, nothing else. Its connection pool holds every upload worker
    (`_S3_POOL_CONNECTIONS`)."""
    return _invocation_session().client("s3", config=_s3_client_config())


def _s3_client_config() -> Any:
    """The S3 client's configuration (botocore's ``Config``, imported
    through boto3 on first use: the handler imports boto3 only)."""
    global _S3_CLIENT_CONFIG
    if _S3_CLIENT_CONFIG is None:
        from boto3.session import Config
        _S3_CLIENT_CONFIG = Config(max_pool_connections=_S3_POOL_CONNECTIONS)
    return _S3_CLIENT_CONFIG


def _secrets_client():
    """THE Secrets Manager client for the connector secret - same session."""
    return _invocation_session().client("secretsmanager")


# ---------------------------------------------------------------------------
# Trusted certificate authorities.
#
# An administrator can give a deployment its own certificate authorities (a
# private or corporate CA) so agent code can call internal services whose
# certificates that CA issued. Organisations writes them, as PEM, to the
# secret `TRUSTED_CA_SECRET_NAME`; no version, or a value with no
# ``-----BEGIN CERTIFICATE-----`` block, means there are none.
#
# * Read here, in handler memory only (`_trusted_cas`): on the first
#   invocation of a container and again on the first invocation after
#   `TRUSTED_CA_REFRESH_S`. Never through the function's environment
#   variables, never into this process's ``os.environ``. A failed read keeps
#   the previous copy (or none) and never blocks a run.
# * The read has its own session (`_trust_session`): the sandbox role with a
#   session policy naming that one secret and one action. It is separate from
#   the invocation's scoped session, which a probe invocation does not get,
#   and it never falls back to the execution role.
# * Applied per exec (`_apply_trust_env`), in the CHILD's environment only and
#   only when at least one of the certificates is a certificate authority
#   (`_customer_anchors`): ``ca-bundle.pem`` (the public roots botocore ships,
#   then those CAs: `_ca_bundle_text`) and ``customer-ca.pem`` (the CAs alone),
#   both from `_trust_material`, are written into that exec's own private
#   helper directory, removed with it. The customer CAs are added to the
#   public roots, never a replacement for them; agent code's own AWS SDK calls
#   keep the public roots alone (``AWS_CA_BUNDLE``). With none, the child's
#   environment is exactly what it was before and nothing is written.
# * Any CA the administrator added is a trust anchor, an issuing CA added
#   without its root included, and is still checked in full (dates, CA, key
#   usage, path length, name constraints). libpq, Node and curl have no
#   partial-chain setting: a chain must end at a self-signed certificate in
#   their file. So each added CA that is not self-signed is written
#   cross-certified (`_rooted_anchor_text`): the same certificate (subject,
#   issuer name, serial number, key, validity and every extension but the
#   authority key identifier) signed by a root made for this set of CAs, whose
#   key is discarded once it has signed; that root follows it in the file.
#   Every client's chain then ends at the CA that was added, as partial-chain
#   verification's does, and OpenSSL checks that CA as it checks any CA in a
#   chain. Self-signed CAs are written as they were added. Anchors are plain
#   certificates, never OpenSSL ``TRUSTED CERTIFICATE`` blocks, which make
#   OpenSSL skip a non-self-signed anchor's dates. The roots' key needs the
#   image's ``openssl`` command line, which the README lists as a requirement
#   for custom images: the AlphaAgent images and python:3.12-slim have it,
#   AWS's own Lambda Python base images do not. Without it, or when a build
#   fails, the CAs are written as added and Python alone gets partial chains,
#   through ``sitecustomize.py`` (`_PARTIAL_CHAIN_SITECUSTOMIZE`). A build
#   that failed for a passing reason serves that exec only; the next exec
#   builds again. The probe's ``trusted_ca.outcome`` says which form the
#   container holds (``cross_certified`` or ``partial_chain``).
# * A child that exits non-zero with a certificate-verification error on its
#   stderr whose reason is an issuer that is not trusted gets one more stderr
#   line saying how an administrator fixes it, and
#   ``untrusted_certificate: true`` on the response (`_finish_run`). When the
#   run's files carried the CAs as added and an issuing CA is in the set
#   without its root, a refusal by libpq, Node or curl (no partial chains)
#   gets a line that says the root CA is needed instead
#   (`_untrusted_certificate_line`). libpq
#   names no reason, so its failure is checked by a TLS handshake with the
#   server it names (`_libpq_reports`); an expired certificate keeps libpq's
#   text. A failure on an expired certificate also gets a line naming the
#   added CA that expired (`_expired_anchor_lines`), never one an anchor
#   valid now renews.
# ---------------------------------------------------------------------------
#: The customer's certificates as last read: ``state`` is ``none``,
#: ``loaded`` or ``unavailable`` (the read failed and there is no earlier
#: copy); ``sha256`` is of the secret's text, ``read_at`` the last successful
#: read. ``pem`` never leaves this process except as the per-exec files.
_TRUSTED_CA: Dict[str, Any] = {"state": "none", "count": 0, "sha256": None, "read_at": None, "pem": ""}
#: ``time.time()`` of the last read attempt; None = not yet tried in this container.
_TRUSTED_CA_READ_ATTEMPT: Optional[float] = None
#: One complete PEM certificate block.
_PEM_CERTIFICATE_RE = re.compile(r"-----BEGIN CERTIFICATE-----\r?\n.*?-----END CERTIFICATE-----", re.S)
#: The certificate text the last exec's files carried for the set in
#: `_TRUSTED_CA` (`_trust_material`): ``digest`` of the set it was built for,
#: ``text``, ``partial_chain`` (True only when the CAs could not be
#: cross-certified), ``retry`` (True when that failure can pass, so the next
#: exec builds again) and ``reason`` (the failure, else None). A build that
#: worked, and an image with no openssl command line, are kept for the set;
#: the libpq check after an exec reads what that exec's files carried.
_TRUST_MATERIAL: Dict[str, Any] = {}
#: Where the handler looks for the ``openssl`` command line: system
#: directories only, never the child's PATH or a directory it can write to.
_OPENSSL_DIRS = ("/usr/bin", "/bin", "/usr/local/bin")
_OPENSSL_TIMEOUT_S = 10
#: The signature algorithms of the certificates the handler makes
#: (`_set_signer`): Ed25519, else ecdsa-with-SHA256 (P-256).
_ED25519 = bytes.fromhex("300506032b6570")
_ECDSA_WITH_SHA256 = bytes.fromhex("300a06082a8648ce3d040302")
#: The cross-certifying root's validity, wide on purpose: it signs only the
#: set's cross-certified CAs, each of which keeps its own CA's dates.
_LOCAL_ROOT_VALIDITY = bytes.fromhex("3020") + b"\x17\x0d000101000000Z" + b"\x18\x0f99991231235959Z"
#: ``sitecustomize.py`` in the exec's helper directory, the first entry on the
#: child's PYTHONPATH (`_child_pythonpath`), so ``site`` imports it when any
#: Python starts in that child. It sets OpenSSL's partial-chain flag on every
#: TLS context the program creates (urllib, requests and urllib3, httpx,
#: pymysql, aiohttp, ``ssl`` itself), which makes each of the deployment's CAs
#: a trust anchor whether or not it is self-signed; OpenSSL still checks that
#: anchor's dates and CA constraints. Then the ``sitecustomize`` Python would
#: have imported without this one, if any (the image's, or one in the
#: project's ``code/``), runs as it would have. Written only when the
#: deployment's CAs could not be cross-certified (`_trust_material`), and
#: only into the exec's own directory: nothing an earlier run left can be
#: imported this way.
_PARTIAL_CHAIN_SITECUSTOMIZE = '''\
"""Written by the environment handler for this run only, because this
deployment has its own certificate authorities. Every TLS context Python
creates here accepts a chain that ends at any certificate it trusts, not only
at a self-signed root (OpenSSL's partial-chain flag, which Python 3.13 and
later set by default), so an issuing CA added without its root is trusted.
OpenSSL still checks that certificate's dates and that it is a certificate
authority. Then the sitecustomize Python would otherwise have imported, if
there is one, runs as it would have."""
import ssl as _ssl

_PARTIAL_CHAIN = getattr(_ssl, "VERIFY_X509_PARTIAL_CHAIN", 0)
if _PARTIAL_CHAIN:
    _context_new = _ssl.SSLContext.__new__

    def _new_context(cls, *args, **kwargs):
        context = _context_new(cls, *args, **kwargs)
        try:
            context.verify_flags |= _PARTIAL_CHAIN
        except (AttributeError, ValueError):
            pass
        return context

    _ssl.SSLContext.__new__ = _new_context


def _run_the_next_sitecustomize():
    import importlib.machinery
    import importlib.util
    import os
    import sys

    here = os.path.dirname(os.path.realpath(__file__))
    rest = [p for p in sys.path if os.path.realpath(p or os.curdir) != here]
    spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
    if spec is None or spec.loader is None:
        return
    module = importlib.util.module_from_spec(spec)
    sys.modules[__name__] = module
    spec.loader.exec_module(module)


_run_the_next_sitecustomize()
'''
#: DER encodings (content bytes) of the object identifiers `_certificate_facts`
#: reads: commonName, basicConstraints, keyUsage, subject and authority key
#: identifiers.
_OID_COMMON_NAME = bytes.fromhex("550403")
_OID_BASIC_CONSTRAINTS = bytes.fromhex("551d13")
_OID_KEY_USAGE = bytes.fromhex("551d0f")
_OID_SUBJECT_KEY_ID = bytes.fromhex("551d0e")
_OID_AUTHORITY_KEY_ID = bytes.fromhex("551d23")
#: Short names for a subject with no common name, written as RFC 4514 does.
_RDN_SHORT_NAMES = {
    "2.5.4.3": "CN", "2.5.4.6": "C", "2.5.4.7": "L", "2.5.4.8": "ST", "2.5.4.9": "STREET",
    "2.5.4.10": "O", "2.5.4.11": "OU", "0.9.2342.19200300.100.1.25": "DC",
    "0.9.2342.19200300.100.1.1": "UID",
}
#: OpenSSL's verify result for an expired certificate (X509_V_ERR_CERT_HAS_EXPIRED).
CERT_HAS_EXPIRED = 10
#: OpenSSL's X509_V_FLAG_NO_CHECK_TIME (1.1.0 and later). Python's ``ssl`` has
#: no name for it and passes the bit through. Used only by the handshake that
#: asks whether a server's chain hangs from an expired CA, never by a
#: connection that carries data.
_X509_V_FLAG_NO_CHECK_TIME = 0x200000
#: What a failed run's stderr shows for verify result 10 (a certificate in the
#: chain has expired): OpenSSL's reason through Python, pymysql and curl, and
#: Node's message and code. Only this reason can be an added CA that expired;
#: a host name mismatch, an untrusted issuer or a not-yet-valid certificate
#: never gets `EXPIRED_TRUSTED_CA_MESSAGE`. It does not say WHICH certificate
#: expired (the service's own, or a CA's): these clients do not name the
#: server, so the handler cannot ask it, and names each added CA that has
#: expired and that no CA valid now renews. libpq names the server, so its
#: line is settled by asking it (`_expired_anchor_behind`).
_CERT_EXPIRED_PATTERN = re.compile("certificate has expired|CERT_HAS_EXPIRED")
#: The line for an added CA that has expired: ``{subject}`` is its common
#: name, else its RFC 4514 name; ``{date}`` is YYYY-MM-DD, UTC.
EXPIRED_TRUSTED_CA_MESSAGE = (
    "The certificate authority {subject} you added expired on {date}; "
    "replace it under Trusted certificate authorities."
)
#: What the TLS stacks agent code uses print when a certificate does not chain
#: to a trusted authority: OpenSSL's reason for each of `UNTRUSTED_VERIFY_CODES`
#: through Python and curl, and Node's message or code for the same (a server
#: that sends only its leaf gives "unable to verify the first certificate").
#: Only reasons: Python's ``CERTIFICATE_VERIFY_FAILED`` is printed for every
#: verify failure, an expired certificate and a host name mismatch included,
#: and those keep the client's own text. libpq is not here: its text names no
#: reason (`_LIBPQ_VERIFY_FAILED_RE`).
UNTRUSTED_CERTIFICATE_PATTERN = re.compile("|".join(re.escape(s) for s in (
    "unable to get issuer certificate",
    "unable to get local issuer certificate",
    "unable to verify the first certificate",
    "self-signed certificate",
    "self signed certificate",
    "UNABLE_TO_GET_ISSUER_CERT",
    "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
    "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
    "SELF_SIGNED_CERT_IN_CHAIN",
    "DEPTH_ZERO_SELF_SIGNED_CERT",
)))
#: libpq (psycopg2, psycopg) prints this one bare text for EVERY certificate
#: chain failure: an issuer that is not trusted and an expired certificate
#: from a trusted one read the same. Its line names the server, so the reason
#: is settled by repeating the TLS part of that connection (`_libpq_reports`),
#: as data-connector does for the same connector. Groups: the host as libpq
#: was given it, the address it connected
#: to (only when that differs from the host), the port.
_LIBPQ_VERIFY_FAILED_RE = re.compile(
    r'connection to server at "([^"]+)"(?: \(([^()\s]+)\))?, port (\d+) failed: '
    r"SSL error: certificate verify failed"
)
#: OpenSSL verify results that mean "the issuer is not trusted": unable to get
#: the issuer (2), self-signed leaf (18), self-signed in the chain (19), unable
#: to get the local issuer (20), unable to verify the first certificate (21).
#: Equal to deployment-management trust.py's. An expired (10) or not yet valid
#: (9) certificate is not among them.
UNTRUSTED_VERIFY_CODES = frozenset({2, 18, 19, 20, 21})
#: PostgreSQL's SSLRequest: length 8, request code 80877103. A server that
#: speaks TLS answers the one byte ``S``.
_PG_SSL_REQUEST = struct.pack("!II", 8, 80877103)
#: The most servers one run's libpq lines are checked against, and the seconds
#: those checks (with any handshakes that find an expired CA) may take
#: together. They run after the run's upload, inside the upload reserve (at
#: least 5 s), and never after a run that hit its limit.
_PG_TLS_PROBE_MAX = 2
_PG_TLS_PROBE_BUDGET_S = 3.0
#: The line appended to such a run's stderr.
UNTRUSTED_CERTIFICATE_MESSAGE = (
    "A certificate in this run is not issued by a trusted authority. If it comes from your own CA, "
    "an administrator can add it under Trusted certificate authorities on the deployment's Overview "
    "in Organisations."
)
#: The line instead of `UNTRUSTED_CERTIFICATE_MESSAGE` when the run's files
#: carried the deployment's CAs as added (`_trust_material` could not
#: cross-certify them), an issuing CA is in the set without its root
#: (`_issuing_ca_without_root`) and the client that refused has no partial
#: chains: libpq (`_libpq_reports`), Node or curl
#: (`_NO_PARTIAL_CHAIN_UNTRUSTED_PATTERN`). Python has partial chains then,
#: so its refusal keeps the A5.8 sentence.
UNTRUSTED_CERTIFICATE_ROOT_NEEDED_MESSAGE = (
    "A certificate in this run is not issued by a trusted authority. In this run PostgreSQL, Node and curl "
    "trust an issuing CA only together with its root CA, so if the certificate comes from your own CA, an "
    "administrator can add your root CA certificate (and any intermediate CA between it and the issuing CA) "
    "under Trusted certificate authorities on the deployment's Overview in Organisations."
)
#: Added to that line when the reason is the image itself: it has no
#: openssl command line (`NoOpensslCommandLine`).
UNTRUSTED_CERTIFICATE_NO_OPENSSL_NOTE = (
    " This environment's image has no openssl command line; with openssl in the image they trust an issuing CA "
    "on its own."
)
#: What libpq's own text cannot say: Node's codes and curl's reasons for an
#: issuer it could not find. Those clients have no partial chains, so an
#: issuing CA written as added is not an anchor for them. A self-signed
#: service certificate (verify result 18) is not among them: a root would
#: not change it.
_NO_PARTIAL_CHAIN_UNTRUSTED_PATTERN = re.compile("|".join(re.escape(s) for s in (
    "UNABLE_TO_GET_ISSUER_CERT",
    "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
    "SELF_SIGNED_CERT_IN_CHAIN",
    "SSL certificate problem: unable to get issuer certificate",
    "SSL certificate problem: unable to get local issuer certificate",
    "SSL certificate problem: unable to verify the first certificate",
    "SSL certificate problem: self-signed certificate in certificate chain",
    "SSL certificate problem: self signed certificate in certificate chain",
)))
#: The reason code, and the response field set (``true``) alongside that line.
UNTRUSTED_CERTIFICATE_REASON = "untrusted_certificate"


def _trust_session_policy(partition: str) -> Dict[str, Any]:
    """The trust read's session policy: ``GetSecretValue`` on the one secret.
    Secrets Manager appends ``-`` and six characters to the name in the ARN."""
    return {"Version": "2012-10-17", "Statement": [{
        "Sid": "TrustedCaBundle",
        "Effect": "Allow",
        "Action": ["secretsmanager:GetSecretValue"],
        "Resource": [f"arn:{partition}:secretsmanager:*:*:secret:{TRUSTED_CA_SECRET_NAME}-??????"],
    }]}


def _trust_session():
    """A boto3 session that can read the trusted-CA secret and nothing else:
    AssumeRole on the sandbox role with `_trust_session_policy`. None when no
    sandbox role is known; never the execution role's own credentials."""
    role_arn = _scoped_role_arn()
    if not role_arn:
        return None
    response = _sts_client().assume_role(
        RoleArn=role_arn,
        RoleSessionName=TRUST_SESSION_NAME,
        Policy=json.dumps(_trust_session_policy(_partition_of(role_arn)), separators=(",", ":")),
        DurationSeconds=TRUST_SESSION_DURATION_S,
    )
    granted = response["Credentials"]
    return boto3.Session(
        aws_access_key_id=granted["AccessKeyId"],
        aws_secret_access_key=granted["SecretAccessKey"],
        aws_session_token=granted["SessionToken"],
        region_name=_aws_region(),
    )


def _trust_secrets_client():
    """The Secrets Manager client for the trusted-CA secret, from
    `_trust_session` alone; None when there is no sandbox role."""
    session = _trust_session()
    return session.client("secretsmanager") if session is not None else None


def _trusted_cas(clock=time.time) -> Dict[str, Any]:
    """Refresh `_TRUSTED_CA` when it is due and return it. Called by `handler`
    on every invocation; reads on the first one of a container and on the
    first one after `TRUSTED_CA_REFRESH_S` (wall-clock time: it keeps running
    while a warm container is frozen between invocations). Never raises. Only
    under the real runtime: a local run never reaches STS and has none."""
    global _TRUSTED_CA_READ_ATTEMPT
    if not os.environ.get("AWS_LAMBDA_RUNTIME_API"):
        return _TRUSTED_CA
    now = clock()
    if _TRUSTED_CA_READ_ATTEMPT is not None and now - _TRUSTED_CA_READ_ATTEMPT < TRUSTED_CA_REFRESH_S:
        return _TRUSTED_CA
    _TRUSTED_CA_READ_ATTEMPT = now
    try:
        client = _trust_secrets_client()
        if client is None:
            raise LookupError("no sandbox role")
        value = client.get_secret_value(SecretId=TRUSTED_CA_SECRET_NAME).get("SecretString") or ""
    except Exception as exc:
        code = "NoSandboxRole" if isinstance(exc, LookupError) else _error_code(exc)
        kept = _TRUSTED_CA["count"]
        if not kept:
            # No version yet is how a deployment without CAs starts.
            _TRUSTED_CA["state"] = "none" if code == "ResourceNotFoundException" else "unavailable"
        if code == "ResourceNotFoundException" and not kept:
            print("[HANDLER] trusted_ca: none (the secret has no value)")
        else:
            print(f"[HANDLER] WARNING: trusted_ca.unavailable ({code}); "
                  + (f"keeping the {kept} certificate(s) read at {_TRUSTED_CA['read_at']}" if kept
                     else "agent code trusts public certificate authorities only"))
        return _TRUSTED_CA
    blocks = [b.replace("\r\n", "\n").strip() for b in _PEM_CERTIFICATE_RE.findall(value)]
    _TRUSTED_CA.update(
        state="loaded" if blocks else "none",
        count=len(blocks),
        sha256=hashlib.sha256(value.encode("utf-8")).hexdigest() if blocks else None,
        read_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
        pem="".join(b + "\n" for b in blocks),
    )
    print(f"[HANDLER] trusted_ca.loaded count={len(blocks)} sha256={(_TRUSTED_CA['sha256'] or '')[:12]}")
    for note in _classify_customer_certificates(_TRUSTED_CA["pem"])[1]:
        print(f"[HANDLER] WARNING: trusted_ca: {note}; agent code does not trust it")
    return _TRUSTED_CA


def _public_ca_bundle() -> str:
    """The public roots botocore verifies AWS endpoints with (certifi's bundle
    when installed, else botocore's own). botocore is boto3's own dependency,
    imported here rather than at the top so the module's imports stay
    stdlib + boto3."""
    from botocore.httpsession import where
    return where()


def _der_tlvs(data: bytes, start: int = 0, end: Optional[int] = None) -> List[Tuple[int, int, int, int]]:
    """The DER items laid end to end in ``data[start:end]``, each as (tag,
    item start, content start, content end). Single-byte tags and definite
    lengths only, which is all an X.509 certificate uses; anything else, or an
    item that runs past ``end``, raises ValueError."""
    end = len(data) if end is None else end
    items: List[Tuple[int, int, int, int]] = []
    pos = start
    while pos < end:
        if pos + 2 > end:
            raise ValueError("truncated DER item")
        head = pos
        tag, length = data[pos], data[pos + 1]
        if tag & 0x1F == 0x1F:
            raise ValueError("multi-byte DER tag")
        pos += 2
        if length & 0x80:
            size = length & 0x7F
            if not 0 < size <= 4 or pos + size > end:
                raise ValueError("bad DER length")
            length = int.from_bytes(data[pos:pos + size], "big")
            pos += size
        if pos + length > end:
            raise ValueError("truncated DER item")
        items.append((tag, head, pos, pos + length))
        pos += length
    return items


def _der_items(data: bytes, start: int = 0, end: Optional[int] = None) -> List[Tuple[int, int, int]]:
    """`_der_tlvs` as (tag, content start, content end)."""
    return [(tag, first, last) for tag, _head, first, last in _der_tlvs(data, start, end)]


def _der(tag: int, content: bytes) -> bytes:
    """One DER item: ``tag``, the definite length, ``content``."""
    size = len(content)
    if size < 0x80:
        return bytes((tag, size)) + content
    octets = (size.bit_length() + 7) // 8
    return bytes((tag, 0x80 | octets)) + size.to_bytes(octets, "big") + content


def _der_time(data: bytes, item: Tuple[int, int, int]) -> datetime:
    """A certificate validity time: UTCTime (two-digit years 50 to 99 are
    19xx, as RFC 5280 says) or GeneralizedTime, both in UTC."""
    tag, start, end = item
    text = data[start:end].decode("ascii")
    if tag == 0x17 and len(text) == 13:
        year = int(text[:2])
        text = str(year + (1900 if year >= 50 else 2000)) + text[2:]
    elif tag != 0x18 or len(text) != 15:
        raise ValueError("not a certificate validity time")
    return datetime.strptime(text, "%Y%m%d%H%M%SZ").replace(tzinfo=timezone.utc)


def _der_text(data: bytes, item: Tuple[int, int, int]) -> str:
    """A name attribute's string value."""
    tag, start, end = item
    raw = data[start:end]
    if tag == 0x1E:                                     # BMPString
        return raw.decode("utf-16-be", errors="replace")
    if tag == 0x1C:                                     # UniversalString
        return raw.decode("utf-32-be", errors="replace")
    if tag == 0x14:                                     # TeletexString
        return raw.decode("latin-1")
    return raw.decode("utf-8", errors="replace")


def _der_oid_text(raw: bytes) -> str:
    """An object identifier's dotted form."""
    values: List[int] = []
    value = 0
    for byte in raw:
        value = (value << 7) | (byte & 0x7F)
        if not byte & 0x80:
            values.append(value)
            value = 0
    if not values:
        return ""
    first = values[0]
    head = [min(first // 40, 2), first - 40 * min(first // 40, 2)]
    return ".".join(str(v) for v in head + values[1:])


def _der_subject(data: bytes, item: Tuple[int, int, int]) -> str:
    """A certificate subject's common name, else its attributes as an RFC 4514
    string (last relative name first)."""
    rdns: List[List[Tuple[bytes, str]]] = []
    for rdn in _der_items(data, item[1], item[2]):
        attributes = []
        for attribute in _der_items(data, rdn[1], rdn[2]):
            parts = _der_items(data, attribute[1], attribute[2])
            if len(parts) < 2 or parts[0][0] != 0x06:
                raise ValueError("bad name attribute")
            attributes.append((data[parts[0][1]:parts[0][2]], _der_text(data, parts[1])))
        rdns.append(attributes)
    for attributes in rdns:
        for oid, value in attributes:
            if oid == _OID_COMMON_NAME:
                return value
    return ",".join(
        "+".join(f"{_RDN_SHORT_NAMES.get(_der_oid_text(oid), _der_oid_text(oid))}={value}"
                 for oid, value in attributes)
        for attributes in reversed(rdns))


def _certificate_facts(pem_block: str) -> Dict[str, Any]:
    """`_certificate_facts_der` of one PEM certificate block."""
    return _certificate_facts_der(ssl.PEM_cert_to_DER_cert(pem_block))


def _certificate_facts_der(der: bytes) -> Dict[str, Any]:
    """What the sandbox checks of one certificate, read from its DER (the
    handler has no X.509 library): ``subject`` (`_der_subject`),
    ``not_before`` and ``not_after`` (UTC datetimes), ``ca`` (basicConstraints
    present with cA true), ``cert_sign`` (whether keyUsage allows certificate
    signing; None when the certificate has no keyUsage), ``skid`` and
    ``akid`` (the subject and authority key identifiers, or None), and
    ``self_signed`` (issuer and subject the same name and, when both key
    identifiers are there, the same key, as OpenSSL decides it). The raw
    items `_cross_certificate` copies: ``serial_der``, ``issuer_der``,
    ``validity_der``, ``subject_der``, ``spki_der``, ``unique_ids_der`` and
    ``extensions_der`` (each extension's DER, with its OID). A certificate
    that cannot be read raises ValueError."""
    (certificate,) = _der_tlvs(der)
    if certificate[0] != 0x30:
        raise ValueError("not a certificate")
    tbs = _der_tlvs(der, certificate[2], certificate[3])[0]
    fields = _der_tlvs(der, tbs[2], tbs[3])
    if fields and fields[0][0] == 0xA0:                 # [0] version
        fields = fields[1:]
    if len(fields) < 6:
        raise ValueError("incomplete certificate")
    raw = lambda item: der[item[1]:item[3]]             # noqa: E731 - the whole item, tag and length included
    serial, issuer, validity, subject, spki = fields[0], fields[2], fields[3], fields[4], fields[5]
    times = _der_items(der, validity[2], validity[3])
    if len(times) != 2:
        raise ValueError("bad validity")
    facts: Dict[str, Any] = {
        "subject": _der_subject(der, subject[0:1] + subject[2:]),
        "not_before": _der_time(der, times[0]),
        "not_after": _der_time(der, times[1]),
        "ca": False,
        "cert_sign": None,
        "skid": None,
        "akid": None,
        "serial_der": raw(serial),
        "issuer_der": raw(issuer),
        "validity_der": raw(validity),
        "subject_der": raw(subject),
        "spki_der": raw(spki),
        "unique_ids_der": b"".join(raw(f) for f in fields[6:] if f[0] in (0x81, 0xA1, 0x82, 0xA2)),
        "extensions_der": [],
    }
    for field in fields[6:]:
        if field[0] != 0xA3:                            # [3] extensions
            continue
        (extensions,) = _der_items(der, field[2], field[3])
        for extension in _der_tlvs(der, extensions[1], extensions[2]):
            parts = _der_items(der, extension[2], extension[3])
            if len(parts) < 2 or parts[0][0] != 0x06 or parts[-1][0] != 0x04:
                raise ValueError("bad extension")
            oid, value = der[parts[0][1]:parts[0][2]], parts[-1]
            facts["extensions_der"].append((oid, raw(extension)))
            if oid == _OID_BASIC_CONSTRAINTS:
                (constraints,) = _der_items(der, value[1], value[2])
                inner = _der_items(der, constraints[1], constraints[2])
                facts["ca"] = bool(inner) and inner[0][0] == 0x01 and der[inner[0][1]:inner[0][2]] != b"\x00"
            elif oid == _OID_KEY_USAGE:
                (bits,) = _der_items(der, value[1], value[2])
                usage = der[bits[1] + 1:bits[2]]        # after the unused-bits octet
                facts["cert_sign"] = bool(usage) and bool(usage[0] & 0x04)     # keyCertSign, bit 5
            elif oid == _OID_SUBJECT_KEY_ID:
                (key_id,) = _der_items(der, value[1], value[2])
                facts["skid"] = der[key_id[1]:key_id[2]]
            elif oid == _OID_AUTHORITY_KEY_ID:
                (identifier,) = _der_items(der, value[1], value[2])
                for part in _der_items(der, identifier[1], identifier[2]):
                    if part[0] == 0x80:                 # [0] keyIdentifier
                        facts["akid"] = der[part[1]:part[2]]
    facts["self_signed"] = facts["issuer_der"] == facts["subject_der"] and (
        facts["akid"] is None or facts["skid"] is None or facts["akid"] == facts["skid"])
    return facts


def _classify_customer_certificates(pem: str) -> Tuple[List[Dict[str, Any]], List[str]]:
    """The deployment's certificates split into trust anchors and the rest.
    Anchors, in the order added, are the certificate authorities:
    basicConstraints with cA true, and a keyUsage that allows certificate
    signing when there is one; each is `_certificate_facts` plus ``pem`` (its
    block). Every other certificate gets a note naming it and why it is left
    out. Organisations refuses those when they are added; the sandbox checks
    again because, with partial chains, a service's own certificate in the
    set would be trusted on sight. A CA whose dates are out of range stays an
    anchor: OpenSSL refuses it with the dates as the reason, and
    `_expired_anchor_lines` names an expired one."""
    anchors: List[Dict[str, Any]] = []
    notes: List[str] = []
    for index, block in enumerate(_PEM_CERTIFICATE_RE.findall(pem), start=1):
        try:
            facts = _certificate_facts(block)
        except (ValueError, IndexError, UnicodeDecodeError):
            notes.append(f"certificate {index} could not be read")
            continue
        if not facts["ca"]:
            notes.append(f"certificate {index} ({facts['subject']}) is not a certificate authority")
        elif facts["cert_sign"] is False:
            notes.append(f"certificate {index} ({facts['subject']}) has a key usage that does not allow "
                         f"signing certificates")
        else:
            anchors.append({**facts, "pem": block.replace("\r\n", "\n").strip() + "\n"})
    return anchors, notes


def _customer_anchors(pem: str) -> List[Dict[str, Any]]:
    """The certificate authorities among ``pem``'s certificates
    (`_classify_customer_certificates`)."""
    return _classify_customer_certificates(pem)[0]


class NoOpensslCommandLine(LookupError):
    """The image has no ``openssl`` command line in `_OPENSSL_DIRS`. Unlike
    any other reason a set cannot be cross-certified, it holds for the
    container's whole life, so `_trust_material` does not build again."""


def _openssl_binary() -> Optional[str]:
    """The ``openssl`` command line in a system directory (`_OPENSSL_DIRS`),
    or None."""
    for directory in _OPENSSL_DIRS:
        path = os.path.join(directory, "openssl")
        if os.path.isfile(path) and os.access(path, os.X_OK):
            return path
    return None


def _openssl(binary: str, args: List[str], data: bytes = b"", key: Optional[bytes] = None,
             data_as_file: bool = False) -> bytes:
    """Run ``binary`` with ``args`` and return its stdout. ``data`` goes to
    its stdin, or (``data_as_file``, for a command that needs to know the
    input's size) to an anonymous temporary file that has no name, opened as
    ``/dev/fd/<n>`` where ``args`` says ``{data}``. ``key`` (a PEM private
    key) reaches it through a pipe, ``/dev/fd/<n>`` where ``args`` says
    ``{key}``: it is never written to a file. A minimal environment (PATH
    only). A failure, or nothing on stdout, raises RuntimeError."""
    fds: List[int] = []
    names: Dict[str, str] = {}
    data_file = None
    try:
        if key is not None:
            read_end, write_end = os.pipe()
            fds.append(read_end)
            try:
                os.write(write_end, key)        # a key of either kind is under 300 bytes, within a pipe's buffer
            finally:
                os.close(write_end)
            names["{key}"] = f"/dev/fd/{read_end}"
        if data_as_file:
            data_file = tempfile.TemporaryFile(dir=TMP_ROOT if os.path.isdir(TMP_ROOT) else None)
            data_file.write(data)
            data_file.flush()
            data_file.seek(0)
            names["{data}"] = f"/dev/fd/{data_file.fileno()}"
            data = b""
        argv = [names.get(a, a) for a in args]
        done = subprocess.run([binary, *argv], input=data, capture_output=True, timeout=_OPENSSL_TIMEOUT_S,
                              env={"PATH": os.pathsep.join(_OPENSSL_DIRS)},
                              pass_fds=tuple(fds) + ((data_file.fileno(),) if data_file else ()), check=False)
    finally:
        for fd in fds:
            os.close(fd)
        if data_file is not None:
            data_file.close()
    if done.returncode != 0 or not done.stdout:
        reason = done.stderr.decode("utf-8", errors="replace").strip().splitlines()
        raise RuntimeError(f"openssl {args[0]} exited {done.returncode}" + (f": {reason[-1][:200]}" if reason else ""))
    return done.stdout


def _der_positive_integer(value: int) -> bytes:
    return _der(0x02, value.to_bytes((value.bit_length() + 8) // 8, "big"))


def _extension(oid: bytes, value: bytes, critical: bool = False) -> bytes:
    return _der(0x30, _der(0x06, oid) + (_der(0x01, b"\xff") if critical else b"") + _der(0x04, value))


class _Signer(NamedTuple):
    """The key of one set's roots: its SubjectPublicKeyInfo, the
    AlgorithmIdentifier its signatures carry, and ``sign(tbs)``."""
    spki: bytes
    algorithm: bytes
    sign: Any


def _set_signer(binary: str) -> _Signer:
    """A new key for one set's roots, made by the ``openssl`` command line
    and held only in this call's memory. Ed25519 when that openssl can sign
    with it (``pkeyutl -rawin``, OpenSSL 3.0 and later): OpenSSL 3 never
    takes a certificate with an Ed25519 key as the issuer of one signed with
    RSA or ECDSA, so a set's root named after a real root the administrator
    added never stands in for it, even for a certificate that real root
    signed with no authority key identifier. Else P-256."""
    try:
        key = _openssl(binary, ["genpkey", "-algorithm", "ED25519"])

        def sign_ed25519(tbs: bytes) -> bytes:
            signature = _openssl(binary, ["pkeyutl", "-sign", "-rawin", "-inkey", "{key}", "-in", "{data}"],
                                 data=tbs, key=key, data_as_file=True)
            if len(signature) != 64:
                raise ValueError("not an Ed25519 signature")
            return signature

        sign_ed25519(b"\x30\x00")
        return _Signer(_openssl(binary, ["pkey", "-pubout", "-outform", "DER"], data=key), _ED25519, sign_ed25519)
    except (RuntimeError, ValueError):
        pass
    key = _openssl(binary, ["ecparam", "-name", "prime256v1", "-genkey", "-noout"])

    def sign_p256(tbs: bytes) -> bytes:
        signature = _openssl(binary, ["dgst", "-sha256", "-sign", "{key}", "-keyform", "PEM"], data=tbs, key=key)
        if _der_items(signature)[0][0] != 0x30:      # ECDSA-Sig-Value
            raise ValueError("not an ECDSA signature")
        return signature

    return _Signer(_openssl(binary, ["pkey", "-pubout", "-outform", "DER"], data=key), _ECDSA_WITH_SHA256, sign_p256)


def _signed_certificate(tbs_fields: List[Optional[bytes]], signer: _Signer) -> str:
    """The PEM certificate whose TBSCertificate holds ``tbs_fields`` in order
    (None: the signer's algorithm), signed by ``signer``."""
    tbs = _der(0x30, b"".join(signer.algorithm if f is None else f for f in tbs_fields))
    return ssl.DER_cert_to_PEM_cert(_der(0x30, tbs + signer.algorithm + _der(0x03, b"\x00" + signer.sign(tbs))))


def _cross_certificate(anchor: Dict[str, Any], key_id: bytes, signer: _Signer) -> str:
    """``anchor`` re-issued by the set's root: its own serial number, issuer
    name, validity, subject, key, unique identifiers and every extension
    (basic constraints, key usage, path length, name constraints, its
    subject key identifier) as they are, except the authority key identifier,
    which names the set's root (``key_id``) so that OpenSSL takes that root,
    never the real one, as its issuer. A service certificate whose authority
    key identifier names its CA by issuer and serial number as well as key
    still chains to it."""
    extensions = b"".join(ext for oid, ext in anchor["extensions_der"] if oid != _OID_AUTHORITY_KEY_ID)
    extensions += _extension(_OID_AUTHORITY_KEY_ID, _der(0x30, _der(0x80, key_id)))
    return _signed_certificate([
        bytes.fromhex("a003020102"),                # v3
        anchor["serial_der"], None, anchor["issuer_der"], anchor["validity_der"],
        anchor["subject_der"], anchor["spki_der"], anchor["unique_ids_der"],
        _der(0xA3, _der(0x30, extensions)),
    ], signer)


def _local_root(name_der: bytes, key_id: bytes, signer: _Signer) -> str:
    """The set's root for the CAs whose issuer is ``name_der``: self-signed,
    named after that issuer, a CA with no path length or name constraint,
    holding the set's key (``signer``, ``key_id``)."""
    serial = int.from_bytes(os.urandom(16), "big") >> 1 | 1
    extensions = (_extension(_OID_BASIC_CONSTRAINTS, _der(0x30, _der(0x01, b"\xff")), critical=True)
                  + _extension(_OID_KEY_USAGE, _der(0x03, b"\x01\x06"), critical=True)   # keyCertSign, cRLSign
                  + _extension(_OID_SUBJECT_KEY_ID, _der(0x04, key_id)))
    return _signed_certificate([
        bytes.fromhex("a003020102"), _der_positive_integer(serial), None, name_der,
        _LOCAL_ROOT_VALIDITY, name_der, signer.spki, _der(0xA3, _der(0x30, extensions)),
    ], signer)


def _rooted_anchor_text(anchors: List[Dict[str, Any]]) -> str:
    """The deployment's CAs in a form every client trusts as anchors, partial
    chains or not: each self-signed CA as added; each other CA
    cross-certified (`_cross_certificate`) in its place; then the roots that
    signed them (`_local_root`, one per issuer name), after every CA that was
    added. Their key (`_set_signer`) exists only during this call, so nothing
    else can ever be signed by them. A client's chain then ends at the CA
    that was added, and OpenSSL checks that CA's dates, CA flag, key usage,
    path length and name constraints there as for any CA in a chain. Raises
    `NoOpensslCommandLine` when there is no ``openssl``, and whatever a step
    raised when one fails; the result loads in Python's ``ssl`` or it is not
    returned."""
    others = [a for a in anchors if not a["self_signed"]]
    if not others:
        return "".join(a["pem"] for a in anchors)
    binary = _openssl_binary()
    if binary is None:
        raise NoOpensslCommandLine("this image has no openssl command line")
    signer = _set_signer(binary)
    (spki_item,) = _der_items(signer.spki)
    bit_string = _der_items(signer.spki, spki_item[1], spki_item[2])[-1]
    key_id = hashlib.sha1(signer.spki[bit_string[1] + 1:bit_string[2]]).digest()   # RFC 5280 4.2.1.2, method 1
    blocks = [a["pem"] if a["self_signed"] else _cross_certificate(a, key_id, signer) for a in anchors]
    issuers: List[bytes] = []
    for anchor in others:
        if anchor["issuer_der"] not in issuers:
            issuers.append(anchor["issuer_der"])
    blocks += [_local_root(name, key_id, signer) for name in issuers]
    text = "".join(blocks)
    ssl.create_default_context(cadata=text)         # every block loads
    return text


def _trust_material(rebuild: bool = True) -> Dict[str, Any]:
    """The certificate text the exec files carry for the CAs in
    `_TRUSTED_CA` (``text``, empty when none is a CA), kept in
    `_TRUST_MATERIAL`: `_rooted_anchor_text` when it succeeds, else the CAs
    as added with ``partial_chain`` True (Python then gets
    `_PARTIAL_CHAIN_SITECUSTOMIZE`; libpq, Node and curl need the root of an
    issuing CA, and a warning says so).

    A build that worked is kept for the set, and so is an image with no
    openssl command line (`NoOpensslCommandLine`), which no later call can
    change. Any other failure (an openssl call that failed or timed out, a
    /tmp that is full or not writable) is kept with ``retry`` True: it
    serves the exec that asked for it, and the next call with ``rebuild``
    (the next exec, or the probe) builds again, so one failure never leaves
    a warm container on partial chains. ``rebuild`` False (the libpq check
    after an exec, `_untrusted_certificate_line`) returns what that exec's
    files carried without building again."""
    pem = (_TRUSTED_CA.get("pem") or "") if _TRUSTED_CA.get("count") else ""
    digest = hashlib.sha256(pem.encode("utf-8")).hexdigest()
    if _TRUST_MATERIAL.get("digest") == digest and not (rebuild and _TRUST_MATERIAL.get("retry")):
        return _TRUST_MATERIAL
    anchors = _customer_anchors(pem) if pem else []
    partial, retry, reason = False, False, None
    try:
        text = _rooted_anchor_text(anchors)
        crossed = sum(1 for a in anchors if not a["self_signed"])
        if crossed:
            print(f"[HANDLER] trusted_ca: {crossed} issuing certificate authorit{'y' if crossed == 1 else 'ies'} "
                  f"cross-certified for clients without partial chains")
    except Exception as exc:
        text, partial = "".join(a["pem"] for a in anchors), True
        retry = not isinstance(exc, NoOpensslCommandLine)
        reason = f"{type(exc).__name__}: {exc}"[:300]
        print(f"[HANDLER] WARNING: trusted_ca: could not cross-certify the issuing certificate authorities "
              f"({reason}); Python in agent code trusts them through partial chains, and "
              f"PostgreSQL (libpq) and Node need their root certificate authority"
              + ("; this run only, the next run builds them again" if retry else ""))
    _TRUST_MATERIAL.clear()
    _TRUST_MATERIAL.update(digest=digest, text=text, partial_chain=partial, retry=retry, reason=reason)
    return _TRUST_MATERIAL


def _trust_outcome() -> Dict[str, Optional[str]]:
    """The probe's view of `_trust_material` (building it when this
    container has not yet, or when the last build failed for a passing
    reason): ``outcome`` ``cross_certified`` when every client trusts each
    added CA as an anchor (a set with no issuing CA needs nothing
    cross-certified and reads the same), ``partial_chain`` when the CAs are
    written as added and only Python trusts an issuing CA on its own, None
    when no certificate in the set is a CA; ``outcome_reason`` is why the
    CAs could not be cross-certified, else None."""
    if not _TRUSTED_CA.get("count"):
        return {"outcome": None, "outcome_reason": None}
    try:
        material = _trust_material()
    except Exception as exc:
        return {"outcome": None, "outcome_reason": f"{type(exc).__name__}: {exc}"[:300]}
    if not material["text"]:
        return {"outcome": None, "outcome_reason": None}
    return {"outcome": "partial_chain" if material["partial_chain"] else "cross_certified",
            "outcome_reason": material.get("reason")}


def _issued_by(child: Dict[str, Any], parent: Dict[str, Any]) -> bool:
    """Whether ``parent``'s name (and key identifier, when both certificates
    carry one) is ``child``'s issuer."""
    return parent["subject_der"] == child["issuer_der"] and (
        child["akid"] is None or parent["skid"] is None or child["akid"] == parent["skid"])


def _issuing_ca_without_root(anchors: List[Dict[str, Any]]) -> bool:
    """Whether an added CA that is not self-signed has no self-signed CA
    above it in the set, directly or through other added CAs: a client with
    no partial chains then cannot end its chain at it when the CAs are
    written as added."""
    reached = [a for a in anchors if a["self_signed"]]
    pending = [a for a in anchors if not a["self_signed"]]
    while pending:
        found = [a for a in pending if any(_issued_by(a, r) for r in reached)]
        if not found:
            return True
        reached += found
        pending = [a for a in pending if all(a is not f for f in found)]
    return False


def _valid_now(anchor: Dict[str, Any], now: datetime) -> bool:
    return anchor["not_before"] <= now < anchor["not_after"]


def _expired_anchor_candidates(anchors: List[Dict[str, Any]], now: datetime) -> List[Dict[str, Any]]:
    """The added CAs that have expired, leaving out any that a CA valid now
    renews (the same subject and the same key): clients take the valid one,
    so the old one is never the reason a run failed."""
    renewed = {(a["subject_der"], a["spki_der"]) for a in anchors if _valid_now(a, now)}
    return [a for a in anchors
            if a["not_after"] <= now and (a["subject_der"], a["spki_der"]) not in renewed]


def _ca_bundle_text(public: str, anchors: str) -> str:
    """The text of ``ca-bundle.pem``: the public roots as they are, then the
    deployment's certificate authorities (``anchors``, plain PEM blocks)."""
    return public.rstrip("\n") + "\n" + anchors


def _apply_trust_env(child_env: Dict[str, str], helper_dir: str) -> Dict[str, str]:
    """Point the child's TLS stacks at the public roots PLUS the deployment's
    trusted certificate authorities (`_customer_anchors`), when it has any;
    with none, ``child_env`` is returned untouched. Writes ``ca-bundle.pem``
    (`_ca_bundle_text`) and ``customer-ca.pem`` (the deployment's CAs alone),
    both with `_trust_material`'s text, into this exec's own ``helper_dir``
    (removed after the exec), plus ``sitecustomize.py``
    (`_PARTIAL_CHAIN_SITECUSTOMIZE`) only when that text needs partial chains;
    keeps ``helper_dir`` first on the child's ``PYTHONPATH``, and sets, in
    ``child_env`` only: ``SSL_CERT_FILE``, ``REQUESTS_CA_BUNDLE`` and
    ``CURL_CA_BUNDLE`` to the combined file, ``NODE_EXTRA_CA_CERTS`` (Node
    adds it to its own roots) to the customer file, and ``AWS_CA_BUNDLE`` to
    the public roots, so agent code's boto3 (which follows
    ``REQUESTS_CA_BUNDLE``) never trusts a customer CA. Never
    ``PGSSLROOTCERT``: libpq would then verify every ``sslmode=require``
    connection. Never this process's ``os.environ``. A failure leaves
    ``child_env`` as it was and removes what it wrote."""
    if not _TRUSTED_CA.get("count"):
        return child_env
    material = _trust_material()
    anchors = material["text"]
    if not anchors:
        return child_env
    bundle_path = os.path.join(helper_dir, "ca-bundle.pem")
    customer_path = os.path.join(helper_dir, "customer-ca.pem")
    site_path = os.path.join(helper_dir, "sitecustomize.py")
    try:
        public_path = _public_ca_bundle()
        with open(public_path, "r", encoding="utf-8") as fh:
            public = fh.read()
        if "-----BEGIN CERTIFICATE-----" not in public:
            raise ValueError(f"{public_path} holds no certificate")
        files = [(bundle_path, _ca_bundle_text(public, anchors)), (customer_path, anchors)]
        if material["partial_chain"]:
            files.append((site_path, _PARTIAL_CHAIN_SITECUSTOMIZE))
        for path, text in files:
            with open(path, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.chmod(path, 0o644)
    except Exception as exc:
        for path in (bundle_path, customer_path, site_path):
            try:
                os.unlink(path)
            except OSError:
                pass
        print(f"[HANDLER] WARNING: trusted_ca: could not write this run's certificate files "
              f"({type(exc).__name__}: {exc}); agent code trusts public certificate authorities only")
        return child_env
    pythonpath = child_env.get("PYTHONPATH", "")
    if pythonpath.split(os.pathsep)[0] != helper_dir:
        child_env["PYTHONPATH"] = os.pathsep.join(p for p in (helper_dir, pythonpath) if p)
    child_env["SSL_CERT_FILE"] = bundle_path
    child_env["REQUESTS_CA_BUNDLE"] = bundle_path
    child_env["CURL_CA_BUNDLE"] = bundle_path
    child_env["NODE_EXTRA_CA_CERTS"] = customer_path
    child_env["AWS_CA_BUNDLE"] = public_path
    return child_env


def _stderr_text(result: Any) -> str:
    raw = result.stderr
    return raw.decode("utf-8", errors="replace") if isinstance(raw, (bytes, bytearray)) else str(raw or "")


def _expired_anchor_lines(result: Any, libpq_reports: Optional[List[Dict[str, Any]]] = None,
                          now: Optional[datetime] = None) -> List[str]:
    """`EXPIRED_TRUSTED_CA_MESSAGE` for each added CA a failed run's
    certificate error can be laid at, in the order the CAs were added:

    * a CA `_libpq_reports` found behind a PostgreSQL server that refused
      verification as expired (``expired_anchor``);
    * when stderr shows verify result 10 from a client that does not name
      its server (`_CERT_EXPIRED_PATTERN`: Python, pymysql, curl, Node), each
      added CA that has expired and that no CA valid now renews
      (`_expired_anchor_candidates`). The text cannot say whether the
      service's own certificate or a CA expired, so a CA that expired is
      named even when the service's certificate expired too.

    Nothing for a run that succeeded, a host name mismatch, an untrusted
    issuer, a not-yet-valid certificate (the client's text names the dates)
    or a CA that a valid one renews."""
    if not result.returncode or not _TRUSTED_CA.get("count"):
        return []
    now = now or datetime.now(timezone.utc)
    anchors = _customer_anchors(_TRUSTED_CA.get("pem") or "")
    named = {report["expired_anchor"]["pem"] for report in libpq_reports or () if report.get("expired_anchor")}
    if _CERT_EXPIRED_PATTERN.search(_stderr_text(result)):
        named.update(anchor["pem"] for anchor in _expired_anchor_candidates(anchors, now))
    return [EXPIRED_TRUSTED_CA_MESSAGE.format(subject=anchor["subject"],
                                              date=anchor["not_after"].strftime("%Y-%m-%d"))
            for anchor in anchors if anchor["pem"] in named]


def _libpq_probe_context() -> ssl.SSLContext:
    """The roots a child's libpq verified against when it followed the SQL
    guide (``sslrootcert`` = ``SSL_CERT_FILE`` or ``certifi.where()``): the
    public roots, plus the deployment's certificate authorities exactly as
    ``ca-bundle.pem`` carried them (`_trust_material` without building
    again, so cross-certified CAs and their root, or the CAs as added when
    that exec's build failed), loaded from memory because the exec's own
    files are already gone. Verified as libpq verifies: no host name check (libpq
    does that after the chain, with its own text), no partial chains and no
    strict checks (Python 3.13 makes both the default, libpq sets neither)."""
    context = ssl.create_default_context(cafile=_public_ca_bundle())
    if _TRUSTED_CA.get("count"):
        anchors = _trust_material(rebuild=False)["text"]
        if anchors:
            context.load_verify_locations(cadata=anchors)
    context.check_hostname = False
    context.verify_mode = ssl.CERT_REQUIRED
    unset = int(getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0)) | int(ssl.VERIFY_X509_STRICT)
    context.verify_flags = ssl.VerifyFlags(int(context.verify_flags) & ~unset)
    return context


def _presented_certificate_context() -> ssl.SSLContext:
    """No verification: only to read the certificate a server presents."""
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    return context


def _hangs_from_context(anchor_pem: str) -> ssl.SSLContext:
    """That one CA, partial chains allowed and time checks off, no host name
    check: does a server's chain hang from it, whatever the dates?"""
    context = ssl.create_default_context(cadata=anchor_pem)
    context.check_hostname = False
    context.verify_mode = ssl.CERT_REQUIRED
    flags = (int(context.verify_flags) | int(getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0))
             | _X509_V_FLAG_NO_CHECK_TIME) & ~int(ssl.VERIFY_X509_STRICT)
    context.verify_flags = flags
    return context


def _postgres_tls(host: str, address: str, port: int, context: ssl.SSLContext, deadline: float,
                  clock=time.monotonic) -> Tuple[Optional[int], Optional[bytes]]:
    """Repeat only the TLS part of what libpq just did against the server it
    named: a connection to ``address``, the SSLRequest, then a handshake with
    ``context`` and ``host`` as the server name. Nothing is sent after the
    handshake (no startup message, no credentials), and it reaches only what
    the child just reached itself. Every step is bounded by ``deadline``
    (``clock`` time).

    Returns ``(0, the presented certificate's DER)`` when the handshake
    completed, ``(code, None)`` when verification failed with OpenSSL's
    verify ``code``, and ``(None, None)`` when there was no handshake to judge
    (a server that declines TLS, a refused or silent connection, no time
    left)."""
    def _left() -> float:
        left = deadline - clock()
        if left <= 0:
            raise TimeoutError("the check ran out of time")
        return left

    try:
        with socket.create_connection((address, port), timeout=_left()) as sock:
            sock.settimeout(_left())
            sock.sendall(_PG_SSL_REQUEST)
            if sock.recv(1) != b"S":
                return None, None
            sock.settimeout(_left())
            try:
                with context.wrap_socket(sock, server_hostname=host) as tls:
                    return 0, tls.getpeercert(binary_form=True)
            except ssl.SSLCertVerificationError as exc:
                return exc.verify_code, None
    except (OSError, ValueError):
        return None, None


def _expired_anchor_behind(host: str, address: str, port: int, anchors: List[Dict[str, Any]],
                           candidates: List[Dict[str, Any]], now: datetime, deadline: float) -> Optional[Dict[str, Any]]:
    """The added CA that expired and that a PostgreSQL server's chain stops
    at, or None. ``candidates`` are `_expired_anchor_candidates`.

    The server's certificate is read first. When added CAs issued it (its
    issuer's name, and its authority key identifier when both have one), the
    chain stops at them: one that is valid now means the expiry is the
    service's own, otherwise the expired one is named. When no added CA
    issued it, the chain goes through CAs the server sends, and a handshake
    with each expired CA alone, its dates not checked, says whether the chain
    hangs from it."""
    code, presented = _postgres_tls(host, address, port, _presented_certificate_context(), deadline)
    if code == 0 and presented:
        try:
            leaf = _certificate_facts_der(presented)
        except (ValueError, IndexError, UnicodeDecodeError):
            leaf = None
        if leaf is not None:
            issuers = [a for a in anchors if a["subject_der"] == leaf["issuer_der"]
                       and (leaf["akid"] is None or a["skid"] is None or a["skid"] == leaf["akid"])]
            if issuers:
                if any(_valid_now(a, now) for a in issuers):
                    return None
                return next((a for a in issuers if any(a["pem"] == c["pem"] for c in candidates)), None)
    for anchor in candidates:
        try:
            context = _hangs_from_context(anchor["pem"])
        except (ssl.SSLError, ValueError):
            continue
        if _postgres_tls(host, address, port, context, deadline)[0] == 0:
            return anchor
    return None


def _libpq_reports(text: str) -> List[Dict[str, Any]]:
    """libpq's bare verify failure, checked for the servers its lines name
    (at most `_PG_TLS_PROBE_MAX`, `_PG_TLS_PROBE_BUDGET_S` in all, stopping
    at the first whose issuer is not trusted) by `_postgres_tls` with
    `_libpq_probe_context`. One report per server checked: ``untrusted``
    (the verify result is in `UNTRUSTED_VERIFY_CODES`) and
    ``expired_anchor`` (for result 10, `_expired_anchor_behind`, else None).
    Empty when no line names a server."""
    targets: List[Tuple[str, str, int]] = []
    for match in _LIBPQ_VERIFY_FAILED_RE.finditer(text):
        host, port = match.group(1), int(match.group(3))
        address = match.group(2) or host
        if 0 < port < 65536 and all((address, port) != (a, p) for _, a, p in targets):
            targets.append((host, address, port))
    if not targets:
        return []
    try:
        context = _libpq_probe_context()
    except Exception as exc:
        print(f"[HANDLER] trusted_ca: could not build the roots to check libpq's certificate failure "
              f"({type(exc).__name__}: {exc}); libpq's text is kept")
        return []
    now = datetime.now(timezone.utc)
    anchors = _customer_anchors(_TRUSTED_CA.get("pem") or "") if _TRUSTED_CA.get("count") else []
    candidates = _expired_anchor_candidates(anchors, now)
    deadline = time.monotonic() + _PG_TLS_PROBE_BUDGET_S
    reports: List[Dict[str, Any]] = []
    for host, address, port in targets[:_PG_TLS_PROBE_MAX]:
        code, _presented = _postgres_tls(host, address, port, context, deadline)
        report: Dict[str, Any] = {"untrusted": code in UNTRUSTED_VERIFY_CODES, "expired_anchor": None}
        if code == CERT_HAS_EXPIRED and candidates:
            report["expired_anchor"] = _expired_anchor_behind(host, address, port, anchors, candidates, now, deadline)
        if report["untrusted"]:
            outcome = "the issuer is not trusted"
        elif report["expired_anchor"]:
            outcome = f"the certificate authority {report['expired_anchor']['subject']} you added has expired"
        else:
            outcome = "not an untrusted issuer; libpq's text is kept"
        print(f"[HANDLER] trusted_ca: libpq certificate failure for {address}:{port}: {outcome}")
        reports.append(report)
        if report["untrusted"]:
            break
    return reports


def _untrusted_certificate_line(text: str, reports: List[Dict[str, Any]]) -> str:
    """The line for a run whose certificate error is an issuer that is not
    trusted: `UNTRUSTED_CERTIFICATE_ROOT_NEEDED_MESSAGE` (plus
    `UNTRUSTED_CERTIFICATE_NO_OPENSSL_NOTE` when the image has no openssl)
    when the client that refused has no partial chains (an untrusted
    libpq report, or `_NO_PARTIAL_CHAIN_UNTRUSTED_PATTERN` for Node and
    curl), the run's files carried the deployment's CAs as added
    (`_trust_material` as that exec had it) and one of them is an issuing CA
    without its root in the set (`_issuing_ca_without_root`): adding that
    root is what lets those clients trust it. Otherwise A5.8's
    `UNTRUSTED_CERTIFICATE_MESSAGE`."""
    if not _TRUSTED_CA.get("count"):
        return UNTRUSTED_CERTIFICATE_MESSAGE
    if not (any(report["untrusted"] for report in reports) or _NO_PARTIAL_CHAIN_UNTRUSTED_PATTERN.search(text)):
        return UNTRUSTED_CERTIFICATE_MESSAGE
    material = _trust_material(rebuild=False)
    if not material["partial_chain"] or not _issuing_ca_without_root(_customer_anchors(_TRUSTED_CA.get("pem") or "")):
        return UNTRUSTED_CERTIFICATE_MESSAGE
    return UNTRUSTED_CERTIFICATE_ROOT_NEEDED_MESSAGE + ("" if material.get("retry") else
                                                        UNTRUSTED_CERTIFICATE_NO_OPENSSL_NOTE)


def _certificate_failure(result: Any, probe_libpq: bool = True) -> Tuple[Optional[str], List[str]]:
    """What a failed run's certificate error says in terms of the
    deployment's trusted CAs: when its reason is an issuer that is not
    trusted (`UNTRUSTED_CERTIFICATE_PATTERN`, or libpq's bare text when
    `_libpq_reports` finds it so), the line to add
    (`_untrusted_certificate_line`), else None; and the
    `_expired_anchor_lines`. libpq's servers are checked only when
    ``probe_libpq`` (not after a run that hit its time limit), and only when
    that can change the answer."""
    if not result.returncode:
        return None, []
    text = _stderr_text(result)
    untrusted = bool(UNTRUSTED_CERTIFICATE_PATTERN.search(text))
    reports: List[Dict[str, Any]] = []
    if probe_libpq and _LIBPQ_VERIFY_FAILED_RE.search(text):
        expired_known = bool(_TRUSTED_CA.get("count")) and bool(_expired_anchor_candidates(
            _customer_anchors(_TRUSTED_CA.get("pem") or ""), datetime.now(timezone.utc)))
        if not untrusted or expired_known:
            reports = _libpq_reports(text)
    untrusted = untrusted or any(report["untrusted"] for report in reports)
    line = _untrusted_certificate_line(text, reports) if untrusted else None
    return line, _expired_anchor_lines(result, reports)


def _no_core_dumps() -> None:
    """``preexec_fn`` for every child: RLIMIT_CORE soft=0, hard untouched.
    Lowering the soft limit is always permitted (proven for the sandbox uid;
    ``ulimit -c 0`` from sh was EPERM there). Without this one crashing Chrome
    wrote ~16 x 82 MB cores per attempt and a warm instance's 512 MB /tmp was
    full after six renders — every later action died with ENOSPC."""
    _soft, hard = resource.getrlimit(resource.RLIMIT_CORE)
    resource.setrlimit(resource.RLIMIT_CORE, (0, hard))
    # PRO-2358: during an exec's output capture, tell it this child's pid so
    # it can stop a program that prints past the output ceiling. The copy
    # threads are running at this fork: they wait in poll() or in a read or
    # write with the GIL released and hold no lock this child takes, and the
    # child only calls setrlimit and write here before it execs.
    fd = _CHILD_PID_FD
    if fd is not None:
        try:
            os.write(fd, str(os.getpid()).encode("ascii"))
        except OSError:
            pass


def _home_usable(path: Optional[str]) -> bool:
    """Readable AND writable AND searchable by this uid. ``os.access`` says no
    for a nonexistent path, for another uid's 0700 dir (unreadable — the live
    Lambda case) and for a read-only one alike."""
    return bool(path) and os.access(path, os.R_OK | os.W_OK | os.X_OK)


def _home_scope(event: Dict[str, Any], exec_token: str) -> str:
    """Whose HOME a child gets, from what the invocation already carries:
    the invoking agent (``agent:<agent_id>``), else the owning user read off
    the project prefix ``users/<uid>/...`` (``user:<uid>``), else this exec
    alone (``exec:<token>`` - the exec's private helper directory's random
    name, so two anonymous execs never meet). A legacy
    ``workspaces/sessions/...`` prefix names no owner."""
    agent_id = str(event.get("agent_id") or "").strip()
    if agent_id:
        return f"agent:{agent_id}"
    m = re.match(r"^/?users/([^/]+)/", str(event.get("s3_prefix") or ""))
    if m:
        return f"user:{m.group(1)}"
    return f"{EXEC_HOME_SCOPE_PREFIX}{exec_token}"


def _scope_path(scope: str) -> str:
    """Where `_scope_home` puts ``scope`` - without creating it."""
    digest = hashlib.sha256(scope.encode("utf-8")).hexdigest()[:16]
    return os.path.join(TMP_ROOT, f"{HOME_DIR_PREFIX}{digest}")


def _scope_home(scope: str) -> str:
    """``/tmp/home-<sha256(scope)[:16]>``, created 0700 on demand with its
    ``.cache``. Deterministic per scope, so the same agent's later warm turns
    find the same directory - a ``pip install --user`` from one turn is
    importable in the next; ``chmod`` after ``makedirs`` because the latter
    is subject to the umask and the directory may pre-exist. Never raises: a
    full /tmp is the child's problem to report, not the handler's to die on."""
    home = _scope_path(scope)
    try:
        os.makedirs(home, mode=0o700, exist_ok=True)
        os.chmod(home, 0o700)
        os.makedirs(os.path.join(home, ".cache"), exist_ok=True)
    except OSError:
        pass
    return home


def _exec_env(base: Dict[str, str], scope: str = TOOLING_HOME_SCOPE) -> Dict[str, str]:
    """The environment every child gets: `_sandboxed_env`, minus the startup
    hooks (`_CHILD_STARTUP_HOOK_KEYS`) and the variables an SDK follows to
    find credentials (`_CREDENTIAL_SOURCE_ENV_KEYS`), plus
    ``AWS_EC2_METADATA_DISABLED=true`` (credential isolation, layer 4), with
    ``PYTHONSAFEPATH=1`` when the
    interpreter knows the flag (3.11+: neither the script's directory nor the
    cwd is put on ``sys.path`` - the project's ``code/`` is, explicitly, via
    `_child_pythonpath`; ``PYTHONNOUSERSITE`` is deliberately NOT set, it
    would break ``pip install --user``), plus a HOME the runtime uid can
    actually use. When the configured HOME is not usable, HOME/XDG_CACHE_HOME
    point at ``scope``'s private directory under /tmp (`_scope_home`) and
    TMPDIR at /tmp — Chromium, puppeteer, fontconfig, soffice and
    choreographer (kaleido: its browser lookup stats ``~/.local/share/...``
    first and raises PermissionError on an unreadable HOME before it ever
    reads BROWSER_PATH) all need that."""
    env = _sandboxed_env(base)
    for key in (*_CHILD_STARTUP_HOOK_KEYS, *_CREDENTIAL_SOURCE_ENV_KEYS):
        env.pop(key, None)
    env.update(_CHILD_NO_METADATA_ENV)
    if tuple(sys.version_info[:2]) >= (3, 11):
        env["PYTHONSAFEPATH"] = "1"
    if not _home_usable(env.get("HOME")):
        home = _scope_home(scope)
        env["HOME"] = home
        env["XDG_CACHE_HOME"] = os.path.join(home, ".cache")
        env["TMPDIR"] = TMP_ROOT
    return env


# ---------------------------------------------------------------------------
# Per-invocation environment.
#
# A Lambda container is WARM across invocations and one environment function
# serves every agent - and every principal - pinned to that environment. The
# handler used to assign each injected ``CONN_*`` variable straight into its
# own ``os.environ`` and never removed the previous invocation's keys, so a warm
# container accumulated every connector it had ever been invoked with, and
# both exec paths - which built the child's environment from the process
# environment - handed the union to the next agent's sandbox, other
# principals' connector credentials included.
#
# Two independent layers, each sufficient on its own:
#
# 1. `_purge_previous_invocation_env` runs FIRST in every invocation (every
#    action, not only exec) and removes from the process environment the
#    names the previous invocation published (`_PREVIOUS_INVOCATION_KEYS`,
#    recorded by `_track_invocation_env`) and, defensively, every name that
#    is per-invocation by shape (``CONN_*``, ``AA_DEADLINE_EPOCH``) - whatever
#    wrote it, including an older handler on a container that was not
#    recycled.
# 2. `_child_env` builds every child's environment from the image's own
#    environment - the NAMES present when this module was imported
#    (`_BASE_ENV_KEYS`: the image ENV, the function configuration, the
#    runtime's init variables), values read live - plus this invocation's
#    variables only. The handler never writes a per-invocation variable into
#    ``os.environ``, and a name that reaches the process environment later by
#    any other route is not a base name, so it cannot reach a child even when
#    the purge did not run.
#
# NOT per-invocation, never purged: ``AA_UPLOAD_RESERVE_S`` /
# ``AA_YIELD_GRACE_S`` (function configuration read in-process by `_int_env`)
# and a customer's own environment variables (function configuration too) -
# both are base names. Connector variables come from the per-agent secret
# only; a ``CONN_*`` in the function configuration is not a supported shape.
# ---------------------------------------------------------------------------
#: The names the process environment had when this module was imported.
_BASE_ENV_KEYS = frozenset(os.environ)
#: Set by the Lambda runtime per invocation, after import; allowed through by name.
_RUNTIME_PASSTHROUGH_KEYS = ("_X_AMZN_TRACE_ID",)
#: Name shapes that are only ever published per invocation: the connector
#: variables (`connector_loader.build_connector_env_vars`) and the
#: cooperative deadline `aa_env` reads.
_PER_INVOCATION_PREFIXES = ("CONN_",)
_PER_INVOCATION_KEYS = ("AA_DEADLINE_EPOCH",)
#: The previous invocation's variable names (layer 1's tracked set).
_PREVIOUS_INVOCATION_KEYS: set = set()


def _is_per_invocation_name(name: str) -> bool:
    return name in _PER_INVOCATION_KEYS or name.startswith(tuple(_PER_INVOCATION_PREFIXES))


def _purge_previous_invocation_env() -> int:
    """Layer 1. Remove from ``os.environ`` every variable a previous
    invocation could have left behind: the tracked names and every
    per-invocation-shaped name. Nothing of this invocation is in the process
    environment yet (nothing ever is - see `_child_env`), so there is nothing
    to keep. Returns the number removed, for the log line."""
    stale = [k for k in os.environ if k in _PREVIOUS_INVOCATION_KEYS or _is_per_invocation_name(k)]
    for k in stale:
        os.environ.pop(k, None)
    _PREVIOUS_INVOCATION_KEYS.clear()
    return len(stale)


def _track_invocation_env(invocation_env: Dict[str, str]) -> None:
    """Record this invocation's variable names so the NEXT invocation's purge
    removes them by name, independently of the shape rule."""
    _PREVIOUS_INVOCATION_KEYS.clear()
    _PREVIOUS_INVOCATION_KEYS.update(invocation_env)


def _base_env() -> Dict[str, str]:
    """The image's own environment as it stands now: only names that were
    present at import (plus the runtime's per-invocation passthrough), with
    their current values."""
    return {k: v for k, v in os.environ.items()
            if k in _BASE_ENV_KEYS or k in _RUNTIME_PASSTHROUGH_KEYS}


def _child_env(invocation_env: Dict[str, str], scope: str = TOOLING_HOME_SCOPE) -> Dict[str, str]:
    """Layer 2. The environment a child gets: `_exec_env` over the base plus
    THIS invocation's variables - never anything an earlier invocation
    published, by construction - with ``scope``'s HOME (the exec paths pass
    `_home_scope`, the handler's own probes take the default)."""
    return _exec_env({**_base_env(), **invocation_env}, scope=scope)


def _sweep_core_dumps() -> Tuple[int, int, int]:
    """Remove ``/tmp/core.*`` left by a crashed child and return
    ``(removed, tmp_used_bytes, tmp_total_bytes)``. Never raises: a full or
    missing /tmp is reported, not fatal."""
    removed = 0
    for path in glob.glob(os.path.join(TMP_ROOT, CORE_DUMP_GLOB)):
        try:
            if os.path.isfile(path):
                os.remove(path)
                removed += 1
        except OSError:
            pass
    try:
        usage = shutil.disk_usage(TMP_ROOT)
        return removed, int(usage.used), int(usage.total)
    except OSError:
        return removed, 0, 0


#: Directories / suffixes that never leave the Lambda: hidden entries (the
#: sync manifest, .pytest_cache, editor state) plus Python bytecode caches a
#: `python -m pytest code/tests` run leaves behind.
_SKIP_DIRS = ("__pycache__",)
_SKIP_SUFFIXES = (".pyc", ".pyo")


def _walk_visible_files(workdir: str):
    """Yield ``(local_path, rel_path)`` for every uploadable file under
    ``workdir`` — not hidden, not bytecode (see ``_SKIP_DIRS`` /
    ``_SKIP_SUFFIXES``)."""
    for dirpath, dirnames, filenames in os.walk(workdir):
        dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in _SKIP_DIRS]
        if os.path.abspath(dirpath) == os.path.abspath(workdir):
            # ``refs/`` holds the Folio files the person referenced, read
            # only: nothing under it is snapshotted or uploaded, whatever
            # the program did there (the Folio contract C7.6).
            dirnames[:] = [d for d in dirnames if d != REFS_DIR]
        for filename in filenames:
            if filename.startswith(".") or filename.endswith(_SKIP_SUFFIXES):
                continue
            local_path = os.path.join(dirpath, filename)
            yield local_path, os.path.relpath(local_path, workdir).replace(os.sep, "/")


def _snapshot_workdir(workdir: str) -> Dict[str, Tuple[int, int]]:
    """``{rel_path: (mtime_ns, size)}`` of every visible file. Taken right
    before the user code runs; `_upload_workdir_files(snapshot=...)` uploads
    only what differs afterwards, so a warm Lambda's mirrored project (which
    S3 already holds) is never re-uploaded wholesale on every step."""
    snap: Dict[str, Tuple[int, int]] = {}
    for local_path, rel in _walk_visible_files(workdir):
        try:
            st = os.stat(local_path)
        except OSError:
            continue
        snap[rel] = (st.st_mtime_ns, st.st_size)
    return snap


def _sha256_file(path: str) -> Optional[str]:
    """Hex sha256 of a regular file's bytes; ``None`` when it is missing, not
    a regular file (a symlink counts as not one) or unreadable."""
    try:
        if not stat.S_ISREG(os.lstat(path).st_mode):
            return None
        digest = hashlib.sha256()
        with open(path, "rb") as fh:
            for chunk in iter(lambda: fh.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()
    except OSError:
        return None


def _unlink_quiet(path: str) -> None:
    """Remove ``path`` if it exists - a file or a symlink, never a tree."""
    try:
        if os.path.lexists(path):
            os.unlink(path)
    except OSError:
        pass


def _workspace_cache_path(prefix: str) -> str:
    """Where `_workspace_cache` keeps ``prefix``'s mirror - without creating
    it. Keyed by the PREFIX (what is mirrored), not by the invoking scope:
    two agents on one project share one verified cache, one agent on two
    projects gets two, and with the index in this process's memory the key
    is a matter of cache hits only - never of trust."""
    digest = hashlib.sha256(prefix.strip("/").encode("utf-8")).hexdigest()[:16]
    return os.path.join(TMP_ROOT, f"{WORKSPACE_CACHE_PREFIX}{digest}")


def _workspace_cache(prefix: str) -> str:
    """``/tmp/ws-<sha256(prefix)[:16]>``, created 0700 on demand (``chmod``
    after ``makedirs``: the umask, and the directory may pre-exist). A
    symlink or a plain file sitting at that path was put there by a child
    (this handler only ever makes a directory) and is removed first, so the
    cache is never another directory in disguise."""
    cache_dir = _workspace_cache_path(prefix)
    if os.path.islink(cache_dir) or (os.path.exists(cache_dir) and not os.path.isdir(cache_dir)):
        _unlink_quiet(cache_dir)
    os.makedirs(cache_dir, mode=0o700, exist_ok=True)
    try:
        os.chmod(cache_dir, 0o700)
    except OSError:
        pass
    return cache_dir


#: Studio 2.2.28 (LAT-7): ``{cache_dir: {rel: (st_ino, st_size, st_mtime_ns,
#: st_ctime_ns)}}`` - the stat of a cache file as this handler last left it,
#: right after verifying, copying or linking it. While a file's stat is still
#: exactly this, its bytes are what `_WORKSPACE_INDEX` vouches for and it is
#: not hashed again: any write, ``chmod`` or ``utime`` moves the ctime and
#: nothing lets a process set it back. Linking and unlinking move it too,
#: so `_link_from_cache` and `_release_workdir` re-record it after their own
#: changes, and only when it was untouched up to them. Handler memory, like
#: the index; an entry that is missing just means "hash it".
_CACHE_TRUST: Dict[str, Dict[str, Tuple[int, int, int, int]]] = {}
#: ``{workdir: {(cache_dir, rel): stat after the link}}``: the cache files
#: this exec's working copy is linked to (`_link_from_cache`), for
#: `_release_workdir`.
_LINKED: Dict[str, Dict[Tuple[str, str], Tuple[int, int, int, int]]] = {}
#: This invocation's ``sync_stats`` (reset at entry; `_stats_add`).
_SYNC_STATS_KEYS = ("listed", "fetched", "cached", "hash_skipped", "refs_cached", "refs_fetched",
                    "bytes_fetched", "duration_ms")
_SYNC_STATS: Dict[str, int] = {k: 0 for k in _SYNC_STATS_KEYS}
_SYNC_STATS_LOCK = threading.Lock()


def _stats_reset() -> None:
    with _SYNC_STATS_LOCK:
        for k in _SYNC_STATS_KEYS:
            _SYNC_STATS[k] = 0


def _stats_add(name: str, n: int = 1) -> None:
    with _SYNC_STATS_LOCK:
        _SYNC_STATS[name] = _SYNC_STATS.get(name, 0) + int(n)


def _sync_stats() -> Dict[str, int]:
    with _SYNC_STATS_LOCK:
        return {k: int(_SYNC_STATS.get(k, 0)) for k in _SYNC_STATS_KEYS}


def _sync_concurrency(event: Optional[Dict[str, Any]]) -> int:
    """The event's ``sync_concurrency`` (CODER_MIRROR_CONCURRENCY) held to
    `SYNC_CONCURRENCY_RANGE`, else `SYNC_CONCURRENCY_DEFAULT`."""
    value = _positive_int((event or {}).get("sync_concurrency")) if isinstance(event, dict) else None
    low, high = SYNC_CONCURRENCY_RANGE
    return SYNC_CONCURRENCY_DEFAULT if value is None else max(low, min(high, value))


def _stat_tuple(path: str) -> Optional[Tuple[int, int, int, int]]:
    """``(st_ino, st_size, st_mtime_ns, st_ctime_ns)`` of a regular file
    (never through a symlink), else None."""
    try:
        st = os.lstat(path)
    except OSError:
        return None
    if not stat.S_ISREG(st.st_mode):
        return None
    return st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns


def _trust(cache_dir: str, rel: str, path: str) -> None:
    """Record ``path``'s stat as the one this handler left it with."""
    current = _stat_tuple(path)
    if current is None:
        _distrust(cache_dir, rel)
    else:
        _CACHE_TRUST.setdefault(cache_dir, {})[rel] = current


def _distrust(cache_dir: str, rel: str) -> None:
    _CACHE_TRUST.get(cache_dir, {}).pop(rel, None)


def _index_set(cache_dir: str, rel: str, etag: str, digest: str, path: str) -> None:
    """Vouch for a cache file just copied and hashed: the index entry and its stat."""
    _WORKSPACE_INDEX.setdefault(cache_dir, {})[rel] = (etag, digest)
    _trust(cache_dir, rel, path)


def _index_drop(cache_dir: str, rel: str) -> None:
    _WORKSPACE_INDEX.setdefault(cache_dir, {}).pop(rel, None)
    _distrust(cache_dir, rel)


def _cache_file_ok(cache_dir: str, rel: str, path: str, digest: str) -> bool:
    """Whether the cache file ``path`` still holds the bytes hashed to
    ``digest``: its stat unchanged since this handler left it (no hash), else
    a sha256 of it. A pass is recorded (`_trust`), a failure forgets it."""
    trusted = _CACHE_TRUST.get(cache_dir, {}).get(rel)
    if trusted is not None and _stat_tuple(path) == trusted:
        _stats_add("hash_skipped")
        return True
    if digest and _sha256_file(path) == digest:
        _trust(cache_dir, rel, path)
        return True
    _distrust(cache_dir, rel)
    return False


def _link_from_cache(cache_dir: str, rel: str, dst: str, workdir: Optional[str]) -> None:
    """Hard-link the verified cache file ``rel`` to ``dst`` (``copy2`` when
    the filesystem refuses a link). The link moves the file's ctime, so its
    stat is recorded again - only when it was the trusted one up to here -
    and remembered for ``workdir``'s release. Raises OSError."""
    src = _safe_dest(cache_dir, rel)
    if src is None:
        raise OSError(f"not a path inside the cache: {rel!r}")
    before = _stat_tuple(src)
    trusted = _CACHE_TRUST.get(cache_dir, {}).get(rel)
    os.makedirs(os.path.dirname(dst) or (workdir or cache_dir), exist_ok=True)
    _unlink_quiet(dst)
    try:
        os.link(src, dst)
    except OSError:
        shutil.copy2(src, dst)
    if trusted is None or before != trusted:
        _distrust(cache_dir, rel)
        return
    _trust(cache_dir, rel, src)
    after = _CACHE_TRUST.get(cache_dir, {}).get(rel)
    if workdir and after is not None:
        _LINKED.setdefault(workdir, {})[(cache_dir, rel)] = after


def _scrub_cache_dir(cache_dir: str, dirs: List[str]) -> int:
    """Before a sync: under each requested project directory of the cache,
    remove every symlink (S3 objects are files; a download never makes one)
    and every file the index does not vouch for - whatever put it there, it
    was not `_sync_dirs_down`. Directories left empty go too. Returns the
    number of entries removed."""
    index = _WORKSPACE_INDEX.get(cache_dir) or {}
    removed = 0
    for d in dirs:
        top = os.path.join(cache_dir, *d.split("/"))
        if os.path.islink(top):
            _unlink_quiet(top)
            removed += 1
            continue
        if not os.path.isdir(top):
            continue
        for dirpath, dirnames, filenames in os.walk(top, topdown=False):
            for name in filenames:
                path = os.path.join(dirpath, name)
                rel = os.path.relpath(path, cache_dir).replace(os.sep, "/")
                if os.path.islink(path) or rel not in index:
                    _unlink_quiet(path)
                    removed += 1
            for name in dirnames:
                path = os.path.join(dirpath, name)
                if os.path.islink(path):
                    _unlink_quiet(path)
                    removed += 1
                else:
                    try:
                        os.rmdir(path)          # succeeds only when empty
                    except OSError:
                        pass
    return removed


def _materialize_workdir(cache_dir: str, rels: List[str], workdir: str) -> int:
    """Build this exec's working copy: hard-link every verified cache file in
    ``rels`` to the same relative path under ``workdir`` (no bytes copied, no
    extra /tmp; ``copy2`` when the filesystem refuses a link). Returns the
    number of files placed. A child's in-place write through a link reaches
    the cache inode - the next exec's sha256 check catches exactly that."""
    placed = 0
    for rel in rels:
        src = _safe_dest(cache_dir, rel)
        dst = _safe_dest(workdir, rel)
        if src is None or dst is None:
            print(f"[HANDLER] WARNING: not placing {rel!r}: not a path inside the workspace")
            continue
        try:
            _link_from_cache(cache_dir, rel, dst, workdir)
            placed += 1
        except OSError as e:
            print(f"[HANDLER] WARNING: could not place {rel} in the working directory: {e}")
    return placed


def _cache_uploaded(cache_dir: str, rel: str, local_path: str, digest: Optional[str], etag: str) -> None:
    """After a successful upload of a file under a synced directory: make the
    cache hold exactly the bytes S3 now has (link the working copy's inode
    in; nothing to do when the child wrote through the link) and record them
    with ``digest`` (the sha256 of what went up), so the next exec does not
    download what this one just wrote. No digest (the file changed while it
    was uploaded) or no ETag: the entry is dropped and the next exec
    downloads it."""
    cache_path = _safe_dest(cache_dir, rel)
    # Its stat is recorded again only once it is verified (a hash at the next
    # sync): the child wrote it.
    _distrust(cache_dir, rel)
    if cache_path is None or not digest or not etag:
        _WORKSPACE_INDEX.setdefault(cache_dir, {}).pop(rel, None)
        return
    try:
        if not (os.path.exists(cache_path) and os.path.samefile(cache_path, local_path)):
            os.makedirs(os.path.dirname(cache_path) or cache_dir, exist_ok=True)
            _unlink_quiet(cache_path)
            try:
                os.link(local_path, cache_path)
            except OSError:
                shutil.copy2(local_path, cache_path)
    except OSError as e:
        print(f"[HANDLER] WARNING: could not cache {rel}: {e}")
        _WORKSPACE_INDEX.setdefault(cache_dir, {}).pop(rel, None)
        return
    _WORKSPACE_INDEX.setdefault(cache_dir, {})[rel] = (etag, digest)


def _event_int(event: Optional[Dict[str, Any]], name: str, default: int, low: int, high: int) -> int:
    """The event's ``name``, a positive whole number held to ``[low, high]``,
    else ``default`` (an older service sends none)."""
    value = _positive_int((event or {}).get(name)) if isinstance(event, dict) else None
    return default if value is None else max(low, min(high, value))


def _upload_concurrency(event: Optional[Dict[str, Any]]) -> int:
    return _event_int(event, "upload_concurrency", KERNEL_UPLOAD_CONCURRENCY_DEFAULT, *KERNEL_UPLOAD_CONCURRENCY_RANGE)


def _uploaded_list_max(event: Optional[Dict[str, Any]]) -> int:
    return _event_int(event, "uploaded_list_max", KERNEL_UPLOADED_LIST_MAX_DEFAULT, *KERNEL_UPLOADED_LIST_MAX_RANGE)


def _transfer_config() -> Any:
    """How a file over `_UPLOAD_IN_MEMORY_MAX` streams up: multipart above
    `_UPLOAD_MULTIPART_BYTES`, in `_UPLOAD_PART_BYTES` parts,
    `_UPLOAD_PART_CONCURRENCY` at a time."""
    from boto3.s3.transfer import TransferConfig
    return TransferConfig(multipart_threshold=_UPLOAD_MULTIPART_BYTES, multipart_chunksize=_UPLOAD_PART_BYTES,
                          max_concurrency=_UPLOAD_PART_CONCURRENCY, use_threads=True)


def _multipart_upload_slots() -> int:
    """How many multipart uploads (files over `_UPLOAD_MULTIPART_BYTES`) run
    at once. Each opens up to `_UPLOAD_PART_CONCURRENCY` connections, so
    together they take at most half of the client's `_S3_POOL_CONNECTIONS`
    (4 x 8 = 32 of 64) and the other half is the single PUTs'. Memory does
    not bound them: ``upload_file`` from a file name reads each part from
    disk as it is sent. A file up to the multipart threshold takes no slot
    at all, so ``upload_concurrency`` of those go up at once whatever the
    function's memory."""
    return max(1, (_S3_POOL_CONNECTIONS // 2) // _UPLOAD_PART_CONCURRENCY)


class _UploadAborted(Exception):
    """Raised inside an upload once its batch's time is up: the transfer
    stops where it is (a multipart one is aborted by the transfer manager's
    own cleanup), so the file is known never to have been written."""


#: The S3 writes an upload batch's client refuses once the batch is stopped
#: (`_gate_upload_requests`). ``AbortMultipartUpload`` (the cleanup) and the
#: reads are never refused.
_GATED_UPLOAD_OPERATIONS = ("PutObject", "CreateMultipartUpload", "UploadPart", "CompleteMultipartUpload")


def _gate_upload_requests(s3: Any, abort: threading.Event) -> None:
    """Once ``abort`` is set, refuse every new write of ``s3`` (the batch's
    own client, `_s3_client` builds one per call) before its request is
    built. A transfer thread still alive at the answer (Lambda freezes it
    and thaws it in the next invocation, maybe another user's) can then
    start no further part, PUT or CompleteMultipartUpload with this
    invocation's scoped credentials. A client with no event system (a test
    fake) is left as it is."""
    events = getattr(getattr(s3, "meta", None), "events", None)
    if events is None:
        return

    def _refuse(**_kwargs: Any) -> None:
        if abort.is_set():
            raise _UploadAborted("the run's time to save its files ran out")

    for op in _GATED_UPLOAD_OPERATIONS:
        events.register_first(f"before-parameter-build.s3.{op}", _refuse,
                              unique_id=f"aa-upload-gate-{op}-{id(abort)}")


def _abort_callback(abort: threading.Event):
    """The transfer manager's progress ``Callback``: it is called as each
    block of the file is read to be sent, so raising there stops a transfer
    mid-body (botocore never completes a request whose body raised)."""
    def _progress(_bytes: int) -> None:
        if abort.is_set():
            raise _UploadAborted("the run's time to save its files ran out")
    return _progress


def _shutdown_quietly(pool: ThreadPoolExecutor) -> None:
    """Let go of ``pool`` without waiting, cancelling what has not started
    (``cancel_futures`` needs Python 3.9; an older interpreter just lets go,
    and `_upload_one` refuses to start once the batch is stopped)."""
    try:
        pool.shutdown(wait=False, cancel_futures=True)
    except TypeError:
        pool.shutdown(wait=False)


def _file_identity(path: str) -> Optional[Tuple[int, int, int]]:
    try:
        st = os.stat(path)
    except OSError:
        return None
    return st.st_ino, st.st_size, st.st_mtime_ns


def _upload_one(s3: Any, local_path: str, bucket: str, key: str, size: int, want_digest: bool,
                multipart_slots: threading.Semaphore,
                abort: Optional[threading.Event] = None) -> Tuple[str, Optional[str]]:
    """Upload one file; returns ``(etag, sha256 or None)``. A small file is
    read once and its hash is of exactly the bytes that went up; a larger
    one streams from disk (a single PUT up to the multipart threshold, in
    parts above it, then only while it holds one of ``multipart_slots``)
    and is hashed from disk once before; when its inode, size or mtime
    changed by the end it went up as something else and the digest is None,
    so the mirror cache never records it. Once ``abort`` is set nothing new
    starts and a running transfer stops at its next block
    (`_UploadAborted`)."""
    abort = abort or threading.Event()
    if abort.is_set():
        raise _UploadAborted("the run's time to save its files ran out")
    extra = _s3_put_args(key)
    if size <= _UPLOAD_IN_MEMORY_MAX:
        with open(local_path, "rb") as fh:
            content = fh.read()
        resp = s3.put_object(Bucket=bucket, Key=key, Body=content, **extra)
        etag = (resp.get("ETag", "") if isinstance(resp, dict) else "") or ""
        return etag, (hashlib.sha256(content).hexdigest() if want_digest else None)
    identity = _file_identity(local_path) if want_digest else None
    before = _sha256_file(local_path) if want_digest else None
    kwargs = {"ExtraArgs": extra or None, "Config": _transfer_config(), "Callback": _abort_callback(abort)}
    if size > _UPLOAD_MULTIPART_BYTES:
        while not multipart_slots.acquire(timeout=0.25):
            if abort.is_set():
                raise _UploadAborted("the run's time to save its files ran out")
        try:
            if abort.is_set():
                raise _UploadAborted("the run's time to save its files ran out")
            s3.upload_file(local_path, bucket, key, **kwargs)
        finally:
            multipart_slots.release()
    else:
        s3.upload_file(local_path, bucket, key, **kwargs)
    try:
        etag = str(s3.head_object(Bucket=bucket, Key=key).get("ETag") or "")
    except Exception as e:  # noqa: BLE001 - the upload itself succeeded
        print(f"[HANDLER] uploaded {key} but could not read its ETag: {type(e).__name__}")
        etag = ""
    digest = None
    if want_digest and before is not None and identity is not None and _file_identity(local_path) == identity:
        digest = before
    return etag, digest


def _unsettled_sentence(count: int, size: int) -> str:
    """The stderr line for files whose upload was still finishing (its last
    request already sent, so it could not be recalled) when the answer had
    to come back."""
    files = "1 file" if count == 1 else f"{count:,} files"
    verb = "was" if count == 1 else "were"
    return (f"{files} ({_size_text(size)}) {verb} still being saved when the run's time ran out and may or may "
            "not be in the workspace.")


def _not_kept_sentence(count: int, size: int) -> str:
    """The stderr line for files a run wrote that its time could not keep."""
    files = "1 file" if count == 1 else f"{count:,} files"
    verb = "was" if count == 1 else "were"
    return (f"{files} ({_size_text(size)}) {verb} written but could not be kept in this run's time. "
            "Write fewer or smaller files, or checkpoint with aa_env.")


def _upload_workdir_files(
    bucket: str,
    prefix: str,
    workdir: str,
    snapshot: Optional[Dict[str, Tuple[int, int]]] = None,
    cache_dir: Optional[str] = None,
    cache_dirs: Tuple[str, ...] = (),
    failures: Optional[List[Tuple[str, str]]] = None,
    report: Optional[Dict[str, Any]] = None,
    event: Optional[Dict[str, Any]] = None,
) -> List[str]:
    """Upload files from workdir to S3. Returns the uploaded relative paths,
    in ``os.walk`` order whatever order the uploads finished in.

    With ``snapshot`` (from `_snapshot_workdir`, taken before the run) only
    NEW or CHANGED files (different mtime or size) are uploaded — that list
    is exactly what the caller turns into ``file_added`` events. Without it
    every visible file goes up (legacy full upload; `_fetch_object` uses it).
    Only regular files go up: a pipe or a device the program left is never
    opened (a pipe would wait forever).
    With ``cache_dir`` (this project's mirror cache, `_workspace_cache`) a
    successful upload under one of ``cache_dirs`` - the directories this exec
    synced - is placed in the cache and recorded with its new ETag and sha256
    (`_cache_uploaded`), so the next `_sync_dirs_down` does not re-download a
    file this very Lambda just wrote.
    With ``failures`` (a list the caller owns) every object S3 refused is
    appended as ``(rel_path, "<error class>: <message>")`` so the caller can
    report it; each refusal is also logged, and once more as a summary.

    2.2.27: the files go up ``upload_concurrency`` at a time (the event,
    KERNEL_UPLOAD_CONCURRENCY), a large one streamed from disk in parts
    (`_upload_one`). Before each file the time left is checked
    (`_output_save_fits`, the event's ``output_timing``, counting what is
    still queued): a file that no longer fits is not started, and once the
    invocation's save margin is reached the batch is stopped: what has not
    started never starts, a running transfer stops at its next block and
    the batch's client refuses any further write (`_gate_upload_requests`),
    then the answer waits a moment (`_UPLOAD_ABORT_JOIN_S`) for them to
    settle. So no upload of this run completes after its answer, except a
    request already wholly sent, which is said as such.
    With ``report`` (a dict the caller owns) it is filled with ``uploads``
    (``[{path, size, etag}]``), ``not_kept`` (``[(path, size)]``, the
    files the time could not keep: known never written) and ``unsettled``
    (``[(path, size)]``, the ones whose last request was still in flight).
    """
    s3 = _s3_client()
    cache_top = tuple(d.strip("/") for d in cache_dirs if d.strip("/"))
    candidates: List[Tuple[str, str, int]] = []
    for local_path, rel_path in _walk_visible_files(workdir):
        try:
            st = os.stat(local_path)
        except OSError:
            continue
        if snapshot is not None and snapshot.get(rel_path) == (st.st_mtime_ns, st.st_size):
            continue
        if not stat.S_ISREG(st.st_mode):
            print(f"[HANDLER] not uploading {rel_path}: not a regular file")
            continue
        candidates.append((local_path, rel_path, int(st.st_size)))

    timing = _output_timing(event)
    done: Dict[int, Tuple[str, Optional[str]]] = {}
    errors: Dict[int, BaseException] = {}
    unsettled_idx: set = set()
    if candidates:
        lock = threading.Lock()
        queued = [0]

        def _settled(size: int) -> None:
            with lock:
                queued[0] -= size

        multipart_slots = threading.BoundedSemaphore(_multipart_upload_slots())
        abort = threading.Event()
        _gate_upload_requests(s3, abort)
        pool = ThreadPoolExecutor(max_workers=min(_upload_concurrency(event), len(candidates)),
                                  thread_name_prefix="aa-upload")
        futures: Dict[Any, int] = {}
        try:
            for idx, (local_path, rel_path, size) in enumerate(candidates):
                with lock:
                    ahead = queued[0]
                if not _output_save_fits(ahead + size, _invocation_time_left(), timing):
                    continue
                with lock:
                    queued[0] += size
                key = f"{prefix.rstrip('/')}/{rel_path}"
                want_digest = bool(cache_dir) and any(rel_path.startswith(d + "/") for d in cache_top)
                future = pool.submit(_upload_one, s3, local_path, bucket, key, size, want_digest,
                                     multipart_slots, abort)
                future.add_done_callback(lambda _f, _s=size: _settled(_s))
                futures[future] = idx
            left = _invocation_time_left()
            finished, late = _wait_futures(list(futures),
                                           timeout=None if left is None else max(0.0, left - timing.save_margin_s))
            settled: set = set()
            if late:
                # Time is up: stop the batch, then give what is running a
                # moment to settle so the answer can say what S3 has.
                abort.set()
                _shutdown_quietly(pool)
                settled, late = _wait_futures(list(late),
                                              timeout=min(_UPLOAD_ABORT_JOIN_S, timing.save_margin_s / 2))
                unsettled_idx = {futures[f] for f in late}
            for future in list(finished) + list(settled):
                idx = futures[future]
                if future.cancelled():
                    continue                    # never started: not kept
                try:
                    done[idx] = future.result()
                except Exception as e:  # noqa: BLE001 - one refusal never costs the others
                    if future in finished:
                        errors[idx] = e         # S3 refused it before the deadline
                    # else stopped by the deadline: never written, not kept
        finally:
            _shutdown_quietly(pool)

    uploaded: List[str] = []
    uploads: List[Dict[str, Any]] = []
    refused: List[Tuple[str, str]] = []
    not_kept: List[Tuple[str, int]] = []
    unsettled: List[Tuple[str, int]] = []
    for idx, (local_path, rel_path, size) in enumerate(candidates):
        if idx in done:
            etag, digest = done[idx]
            uploaded.append(rel_path)
            uploads.append({"path": rel_path, "size": size, "etag": etag})
            if cache_dir and any(rel_path.startswith(d + "/") for d in cache_top):
                _cache_uploaded(cache_dir, rel_path, local_path, digest, etag)
        elif idx in errors:
            e = errors[idx]
            print(f"[HANDLER] WARNING: failed to upload {rel_path}: {e}")
            refused.append((rel_path, f"{type(e).__name__}: {e}"[:_UPLOAD_ERROR_MAX_CHARS]))
        elif idx in unsettled_idx:
            unsettled.append((rel_path, size))
        else:
            not_kept.append((rel_path, size))

    if uploaded:
        print(f"[HANDLER] Uploaded {len(uploaded)} files to s3://{bucket}/{prefix.rstrip('/')}/")
    if refused:
        print(f"[HANDLER] WARNING: {len(refused)} file(s) could not be uploaded to "
              f"s3://{bucket}/{prefix.rstrip('/')}/ ({refused[0][0]}: {refused[0][1]})")
        if failures is not None:
            failures.extend(refused)
    if not_kept:
        print(f"[HANDLER] WARNING: {len(not_kept)} file(s) ({sum(s for _, s in not_kept)} bytes) not uploaded: "
              f"the invocation's time ran out (first: {not_kept[0][0]})")
    if unsettled:
        print(f"[HANDLER] WARNING: {len(unsettled)} file(s) still being saved at the deadline "
              f"(first: {unsettled[0][0]}); they may or may not be in S3")
    if report is not None:
        report["uploads"] = uploads
        report["not_kept"] = not_kept
        report["unsettled"] = unsettled
    return uploaded


def _sync_dirs_down(
    bucket: str,
    prefix: str,
    cache_dir: str,
    dirs: List[str],
    max_bytes: Optional[int] = None,
    skip_over_bytes: Optional[int] = None,
    concurrency: Optional[int] = None,
) -> Dict[str, Any]:
    """Bring the project's mirror CACHE (`_workspace_cache`) up to date with
    the given project directories (``code``, ``nodes``, ``inputs``…) from
    ``s3://{bucket}/{prefix}{dir}/``, preserving relative paths, and say
    which files are now present and verified.

    ETag-diffed against this process's index (`_WORKSPACE_INDEX`): an object
    whose ETag the index recorded AND whose cached bytes still hash to what
    was recorded is ``unchanged`` and not downloaded, so a warm Lambda pays
    only for what changed since its last invocation - while a cached file a
    child tampered with (the cache is writable by the sandbox uid) fails the
    hash and is fetched again. `_scrub_cache_dir` first removes what
    the index does not vouch for; a cached file S3 no longer lists is pruned
    once that directory's listing completed. Size guards: an object larger
    than ``skip_over_bytes`` is listed but not downloaded; once the running
    total would exceed ``max_bytes`` the rest is listed as skipped and
    ``truncated`` is set — never a silent partial mirror.

    Studio 2.2.28 (LAT-6, LAT-7): the folders are listed, the cached files
    checked and the copies made ``concurrency`` at a time (the event's
    ``sync_concurrency``, default 16), with every decision - unchanged, too
    large, past the total, to copy - taken in listing order before any copy
    starts, so the answer is the same whatever finishes first. A cached file
    whose stat is the one this handler left it with is not hashed again
    (`_cache_file_ok`).

    Returns ``{"downloaded": [...], "skipped": [...], "unchanged": n,
    "bytes": n, "truncated": bool, "present": [...]}`` - ``present`` is every
    rel path the working copy should carry (`_materialize_workdir`).
    Best-effort: a listing failure for a directory is logged and that
    directory's VERIFIED cache entries stand in (the run proceeds with the
    last good mirror, as before); a download failure is reported as skipped.
    """
    report: Dict[str, Any] = {"downloaded": [], "skipped": [], "unchanged": 0, "bytes": 0,
                              "truncated": False, "present": []}
    if not bucket or not prefix or not dirs:
        return report
    max_bytes = int(max_bytes if max_bytes is not None else _int_env("AA_SYNC_MAX_BYTES", _DEFAULT_SYNC_MAX_BYTES))
    skip_over_bytes = int(
        skip_over_bytes if skip_over_bytes is not None
        else _int_env("AA_SYNC_SKIP_OVER_BYTES", _DEFAULT_SYNC_SKIP_OVER_BYTES)
    )
    workers = _sync_concurrency({"sync_concurrency": concurrency})
    clean_dirs = [d for d in (str(d).strip("/") for d in dirs) if d and ".." not in d.split("/")]
    scrubbed = _scrub_cache_dir(cache_dir, clean_dirs)
    index = _WORKSPACE_INDEX.setdefault(cache_dir, {})
    s3 = _s3_client()
    base = prefix.rstrip("/") + "/"

    def _list(d_clean: str) -> List[Dict[str, Any]]:
        paginator = s3.get_paginator("list_objects_v2")
        objs: List[Dict[str, Any]] = []
        for page in paginator.paginate(Bucket=bucket, Prefix=f"{base}{d_clean}/"):
            objs.extend(page.get("Contents", []) or [])
        return objs

    # (1) Every folder listed at once.
    listings: Dict[str, Any] = {}
    with ThreadPoolExecutor(max_workers=max(1, min(workers, len(clean_dirs))),
                            thread_name_prefix="aa-list") as pool:
        futures = {d: pool.submit(_list, d) for d in clean_dirs}
        for d, future in futures.items():
            try:
                listings[d] = future.result()
            except Exception as e:  # noqa: BLE001 - that folder's verified cache stands in
                listings[d] = e

    # (2) What each listed object is, in listing order.
    entries: List[Dict[str, Any]] = []
    fallback: List[str] = []
    for d_clean in clean_dirs:
        listed = listings[d_clean]
        if isinstance(listed, Exception):
            print(f"[HANDLER] WARNING: sync-down listing failed for {d_clean}/: {listed} - "
                  "the verified cache stands in")
            fallback.append(d_clean)
            continue
        for obj in listed:
            key = obj["Key"]
            rel = key[len(base):]
            if not rel or rel.endswith("/"):
                continue
            dst = _safe_dest(cache_dir, rel)
            if dst is None:
                print(f"[HANDLER] WARNING: sync-down refused {rel!r}: not a path inside the workspace")
                continue
            entries.append({"rel": rel, "key": key, "dst": dst, "dir": d_clean,
                            "size": int(obj.get("Size", 0) or 0), "etag": obj.get("ETag", "") or ""})
    _stats_add("listed", len(entries))

    # (3) The cached ones checked at once (a stat, or a hash when the stat moved).
    known = [e for e in entries if e["etag"] and index.get(e["rel"]) and index[e["rel"]][0] == e["etag"]]
    verified: Dict[str, bool] = {}
    if known:
        with ThreadPoolExecutor(max_workers=max(1, min(workers, len(known))), thread_name_prefix="aa-verify") as pool:
            checks = {e["rel"]: pool.submit(_cache_file_ok, cache_dir, e["rel"], e["dst"], index[e["rel"]][1])
                      for e in known}
            for rel, future in checks.items():
                try:
                    verified[rel] = bool(future.result())
                except Exception:  # noqa: BLE001
                    verified[rel] = False

    # (4) Every decision in listing order, before any copy starts.
    mismatched = 0
    planned = 0
    to_copy: List[Dict[str, Any]] = []
    for e in entries:
        if e["rel"] in verified:
            if verified[e["rel"]]:
                e["status"] = "unchanged"
                continue
            mismatched += 1
        if e["size"] > skip_over_bytes:
            e["status"] = "skipped"
            continue
        if planned + e["size"] > max_bytes:
            e["status"] = "skipped"
            report["truncated"] = True
            continue
        planned += e["size"]
        _index_drop(cache_dir, e["rel"])
        e["status"] = "copy"
        to_copy.append(e)

    # (5) The copies, ``workers`` at a time; the index is written here, on this thread.
    def _copy(e: Dict[str, Any]) -> str:
        os.makedirs(os.path.dirname(e["dst"]) or cache_dir, exist_ok=True)
        _unlink_quiet(e["dst"])          # never write through a link or a symlink
        s3.download_file(bucket, e["key"], e["dst"])
        digest = _sha256_file(e["dst"])
        if digest is None:
            raise OSError(f"downloaded file is not readable: {e['dst']}")
        return digest

    if to_copy:
        with ThreadPoolExecutor(max_workers=max(1, min(workers, len(to_copy))), thread_name_prefix="aa-sync") as pool:
            copies = [(e, pool.submit(_copy, e)) for e in to_copy]
            for e, future in copies:
                try:
                    digest = future.result()
                except Exception as exc:  # noqa: BLE001 - one failure never costs the others
                    print(f"[HANDLER] WARNING: sync-down failed for {e['rel']}: {exc}")
                    _unlink_quiet(e["dst"])
                    e["status"] = "skipped"
                    continue
                _index_set(cache_dir, e["rel"], e["etag"], digest, e["dst"])
                e["status"] = "downloaded"

    present: List[str] = []
    for e in entries:
        status = e["status"]
        if status == "unchanged":
            report["unchanged"] += 1
            present.append(e["rel"])
        elif status == "downloaded":
            report["downloaded"].append(e["rel"])
            report["bytes"] += e["size"]
            present.append(e["rel"])
        else:
            report["skipped"].append(e["rel"])
    _stats_add("cached", report["unchanged"])
    _stats_add("fetched", len(report["downloaded"]))
    _stats_add("bytes_fetched", report["bytes"])

    # A folder whose listing failed: its verified cache entries stand in.
    for d_clean in fallback:
        for rel, (_etag, digest) in list(index.items()):
            if rel.startswith(d_clean + "/") and rel not in present:
                if _cache_file_ok(cache_dir, rel, os.path.join(cache_dir, *rel.split("/")), digest):
                    present.append(rel)
                else:
                    _index_drop(cache_dir, rel)
    # A folder whose listing completed: what S3 no longer holds leaves the cache.
    listed_by_dir: Dict[str, set] = {d: set() for d in clean_dirs if d not in fallback}
    for e in entries:
        listed_by_dir[e["dir"]].add(e["rel"])
    for d_clean, listed_set in listed_by_dir.items():
        for rel in [r for r in index if r.startswith(d_clean + "/") and r not in listed_set]:
            _index_drop(cache_dir, rel)
            _unlink_quiet(os.path.join(cache_dir, *rel.split("/")))
    if mismatched:
        print(f"[HANDLER] sync: {mismatched} cache entr{'y' if mismatched == 1 else 'ies'} did not match "
              f"what was downloaded - re-fetched from S3")
    report["present"] = present
    print(
        f"[HANDLER] sync: {len(report['downloaded'])} downloaded, {report['unchanged']} unchanged, "
        f"{len(report['skipped'])} skipped ({report['bytes']} bytes), {scrubbed} scrubbed from the cache, "
        f"{workers} at once, from s3://{bucket}/{base} dirs={clean_dirs}"
    )
    return report


def _event_sync_dirs(event: Dict[str, Any]) -> List[str]:
    """``event["sync_dirs"]`` — a list of project directory names to mirror
    before running. Absent/empty means "no mirror" (legacy callers), so the
    pre-existing exec paths behave exactly as before unless asked."""
    dirs = event.get("sync_dirs")
    if not isinstance(dirs, list):
        return []
    return [str(d).strip("/") for d in dirs if str(d).strip("/")]


def _child_pythonpath(workdir: str, base_env: Dict[str, str], helper_dir: str) -> str:
    """``{helper_dir}:{workdir}/code[:existing]`` — `import aa_env` resolves
    from THIS exec's private helper directory (`_helper_dir`) and the
    project's ``code/`` package root is importable from anywhere (``from
    src.x import f`` in scripts and in ``code/tests/`` alike, with cwd =
    project root).

    Never the handler's own directory: under runtime delivery that
    is ``/tmp/aa_handler`` - shared by every agent the warm container serves
    and writable by the sandbox uid, where ``/opt`` was read-only - so a file
    one invocation's script planted there (``sitecustomize.py``, a shadow
    ``pandas.py``) would be imported by the next agent's child, with that
    agent's credentials in its environment. A fresh, unpredictably named
    directory per exec cannot be pre-planted."""
    parts = [helper_dir, os.path.join(workdir, "code")]
    if base_env.get("PYTHONPATH"):
        parts.append(base_env["PYTHONPATH"])
    return os.pathsep.join(parts)


def _helper_dir() -> str:
    """A fresh private directory under /tmp holding this exec's ``aa_env.py``,
    written from the import-time copy (`_AA_ENV_BYTES`) - with the trust
    files `_apply_trust_env` adds when the deployment has its own certificate
    authorities, the only thing a child imports from outside its project and
    the image. Removed by the caller once the child has exited. ``mkdtemp``:
    mode 0700, random name."""
    directory = tempfile.mkdtemp(prefix=".aa-helper-", dir=TMP_ROOT)
    if _AA_ENV_BYTES is not None:
        with open(os.path.join(directory, "aa_env.py"), "wb") as fh:
            fh.write(_AA_ENV_BYTES)
    return directory


def _release_exec_dirs(helper_dir: str, scope: str, child_env: Dict[str, str]) -> None:
    """After the child has exited (or the wall raised): remove the exec's
    helper directory and, when the HOME was this exec's alone (no agent, no
    owner in the event - `_home_scope`), that HOME too. An agent's or owner's
    HOME is theirs to keep across warm turns; a usable configured HOME is
    never touched (it is not under `_scope_home`)."""
    shutil.rmtree(helper_dir, ignore_errors=True)
    home = child_env.get("HOME", "")
    if scope.startswith(EXEC_HOME_SCOPE_PREFIX) and home == _scope_path(scope):
        shutil.rmtree(home, ignore_errors=True)


# ---------------------------------------------------------------------------
# Runtime delivery: which handler is live, and keeping the pair intact when
# it runs from a writable directory.
# ---------------------------------------------------------------------------
_AA_ENV_PATH = os.path.join(_HANDLER_DIR, "aa_env.py")


def _read_bytes(path: str) -> Optional[bytes]:
    try:
        with open(path, "rb") as fh:
            return fh.read()
    except OSError:
        return None


#: ``aa_env.py`` as it stood next to this file at import - the delivered copy.
_AA_ENV_BYTES = _read_bytes(_AA_ENV_PATH)


def _handler_delivery() -> Dict[str, Any]:
    """The identity of the handler that is running, for ``probe_capabilities``
    (and so the row, the run's ``env_capabilities`` event and the API)::

        {handler_version, handler_delivery: "overlay" | "baked",
         handler_delivery_reason, handler_release, handler_path}

    Read lazily from the two bootstrap variables - never written here."""
    marker = os.environ.get(HANDLER_DELIVERY_ENV, "")
    uri = os.environ.get(HANDLER_URI_ENV, "").rstrip("/")
    if marker == "overlay":
        delivery, reason = "overlay", None
    elif marker.startswith("baked:"):
        delivery, reason = "baked", marker[len("baked:"):] or "the bootstrap fell back to the image's copy"
    else:
        delivery, reason = "baked", "no bootstrap ran - the function's entry point runs the image's own copy"
    return {
        "handler_version": HANDLER_CONTRACT_VERSION,
        "handler_delivery": delivery,
        "handler_delivery_reason": reason,
        "handler_release": (uri.rsplit("/", 1)[-1] or None) if (delivery == "overlay" and uri) else None,
        "handler_path": os.path.abspath(__file__),
    }


def _ensure_overlay_intact() -> bool:
    """Restore ``aa_env.py`` next to this handler from the import-time copy
    when the on-disk bytes differ. Defence in depth: children never import
    from this directory any more (`_child_pythonpath` hands each exec a
    private copy), but under runtime delivery the directory is
    ``/tmp/aa_handler``, writable by the sandbox uid, and the pair that sits
    there should stay the pair that was delivered. ``/opt`` is read-only in
    Lambda, so for a baked pair this is a no-op. Returns True when a restore
    happened."""
    if _AA_ENV_BYTES is None:
        return False
    if _read_bytes(_AA_ENV_PATH) == _AA_ENV_BYTES:
        return False
    tmp = _AA_ENV_PATH + ".restore"
    try:
        with open(tmp, "wb") as fh:
            fh.write(_AA_ENV_BYTES)
        os.replace(tmp, _AA_ENV_PATH)
    except OSError as e:
        print(f"[HANDLER] aa_env.py next to the handler was modified and could not be restored: {e}")
        return False
    print("[HANDLER] aa_env.py next to the handler had been modified since import; restored the delivered copy")
    return True


def _safe_workspace_rel(rel: Any) -> Optional[str]:
    """``rel`` unchanged when it is a safe workspace-relative key, else
    ``None``: non-empty text, no leading ``/``, no NUL, no backslash, no
    empty, ``.`` or ``..`` segment. Nothing is normalised away. The same
    rule as the service's ``destructive_guard.safe_workspace_relpath``."""
    if not isinstance(rel, str) or not rel:
        return None
    if rel.startswith("/") or "\x00" in rel or "\\" in rel:
        return None
    if any(part in ("", ".", "..") for part in rel.split("/")):
        return None
    return rel


#: git's own metadata names: a ``.git`` segment (folder or pointer file) and
#: these files, compared without case. The same names as the service's
#: ``destructive_guard.GIT_METADATA_DIR_NAMES`` / ``GIT_METADATA_FILE_NAMES``.
_GIT_METADATA_DIR_NAMES = frozenset({".git"})
_GIT_METADATA_FILE_NAMES = frozenset({".gitmodules", ".gitattributes", ".gitconfig"})


def _is_git_metadata_rel(path: Any) -> bool:
    """True when ``path`` (``/`` or ``\\`` separated) has a ``.git`` segment
    or ends in ``.gitmodules``, ``.gitattributes`` or ``.gitconfig``, in any
    case. The same rule as ``destructive_guard.is_git_metadata_path``."""
    if not isinstance(path, str) or not path:
        return False
    parts = [p.lower() for p in re.split(r"[\\/]+", path) if p]
    if not parts:
        return False
    return any(p in _GIT_METADATA_DIR_NAMES for p in parts) or parts[-1] in _GIT_METADATA_FILE_NAMES


def _safe_dest(root: str, rel: Any) -> Optional[str]:
    """Where ``rel`` lands under ``root``, or ``None``: `_safe_workspace_rel`,
    not a git metadata name (`_is_git_metadata_rel`), and the joined path
    must resolve strictly below ``root``'s resolved path (a link planted on
    the way cannot move it). Returns the joined path."""
    safe = _safe_workspace_rel(rel)
    if safe is None or not root or _is_git_metadata_rel(safe):
        return None
    root_r = os.path.realpath(root)
    dst = os.path.join(root, *safe.split("/"))
    if not os.path.realpath(dst).startswith(root_r.rstrip(os.sep) + os.sep):
        return None
    return dst


def _safe_project_relpath(path: str) -> Optional[str]:
    """Normalise a project-relative path; ``None`` if it is absolute or escapes."""
    raw = str(path or "").strip()
    if not raw or raw.startswith("/") or "\\" in raw:
        return None
    norm = os.path.normpath(raw).replace(os.sep, "/")
    if norm.startswith("../") or norm == ".." or norm.startswith("/"):
        return None
    return norm


def _sync_prefix_down(bucket: str, prefix: str, workdir: str, concurrency: Optional[int] = None) -> int:
    """Download the ENTIRE session prefix into the workdir. Used on checkpoint
    resume so a fresh Lambda's /tmp is reconstituted exactly (manifest + shards +
    prior outputs) — the durable S3 workspace is the source of truth, never /tmp.
    Best-effort: a failure here degrades to recomputing from the last checkpoint.

    Studio 2.2.28: only for an older worker's resume (an event with no
    ``resume_paths``; a current one gets `_sync_resume_state`), and the files
    come down ``concurrency`` at a time; one failure no longer stops the rest.
    """
    if not bucket or not prefix:
        return 0
    s3 = _s3_client()
    work: List[Tuple[str, str, int]] = []
    try:
        paginator = s3.get_paginator("list_objects_v2")
        for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
            for obj in page.get("Contents", []):
                key = obj["Key"]
                rel = key[len(prefix):].lstrip("/")
                if not rel or rel.endswith("/"):
                    continue
                dst = _safe_dest(workdir, rel)
                if dst is None:
                    print(f"[HANDLER] WARNING: resume sync-down refused {rel!r}: not a path inside the workspace")
                    continue
                work.append((key, dst, int(obj.get("Size", 0) or 0)))
    except Exception as e:
        print(f"[HANDLER] WARNING: resume sync-down listing failed: {e}")
    _stats_add("listed", len(work))

    def _one(item: Tuple[str, str, int]) -> int:
        key, dst, size = item
        os.makedirs(os.path.dirname(dst) or workdir, exist_ok=True)
        _unlink_quiet(dst)      # never write through a link into the mirror cache
        s3.download_file(bucket, key, dst)
        return size

    count = 0
    if work:
        workers = _sync_concurrency({"sync_concurrency": concurrency})
        with ThreadPoolExecutor(max_workers=max(1, min(workers, len(work))), thread_name_prefix="aa-resume") as pool:
            for (key, _dst, _size), future in [(item, pool.submit(_one, item)) for item in work]:
                try:
                    _stats_add("bytes_fetched", future.result())
                    count += 1
                except Exception as e:  # noqa: BLE001 - best effort, as before
                    print(f"[HANDLER] WARNING: resume sync-down failed for {key}: {e}")
    _stats_add("fetched", count)
    print(f"[HANDLER] resume: synced {count} file(s) down from s3://{bucket}/{prefix}")
    return count


def _resume_rel(rel: Any) -> Optional[str]:
    """A path a resume may copy down: a safe project-relative path outside
    `RESUME_EXCLUDED_PREFIXES`, else None."""
    safe = _safe_workspace_rel(rel)
    if safe is None or _is_git_metadata_rel(safe):
        return None
    if any(safe.startswith(p) or safe == p.rstrip("/") for p in RESUME_EXCLUDED_PREFIXES):
        return None
    return safe


def _manifest_paths(manifest_path: str) -> List[str]:
    """Every path aa_env's manifest names under ``shards`` (lists or text,
    any depth), in order. A manifest that cannot be read names none."""
    try:
        with open(manifest_path, "r", encoding="utf-8") as fh:
            manifest = json.load(fh)
    except (OSError, ValueError):
        return []
    found: List[str] = []

    def _walk(value: Any) -> None:
        if isinstance(value, str):
            found.append(value)
        elif isinstance(value, list):
            for v in value:
                _walk(v)
        elif isinstance(value, dict):
            for v in value.values():
                _walk(v)

    _walk(manifest.get("shards") if isinstance(manifest, dict) else None)
    return found


def _sync_resume_state(event: Dict[str, Any], bucket: str, prefix: str, workdir: str, cache_dir: str,
                       placed: List[str]) -> List[Dict[str, Any]]:
    """A checkpoint resume from a current worker (Studio 2.2.28, LAT-5 and
    REL-3): copy only what aa_env and the program need to carry on - aa_env's
    manifest (`AA_ENV_MANIFEST_NAME`), its shard folder (`AA_ENV_SHARD_DIR`),
    any other shard path the manifest names, and the event's
    ``resume_paths`` (the files the previous continuation uploaded) - through
    the project's verified cache, ``sync_concurrency`` at a time, each HEADed
    first and held to the free /tmp (`_copy_inputs`). Never ``.coder/``,
    ``tool-results/``, ``_tool_output/`` or ``refs/``, and nothing the mirror
    already placed (``placed``). A path that is not in S3 (a first resume
    has no manifest yet) is left out quietly; any other failure is returned
    as an input error."""
    s3 = _s3_client()
    base = prefix.rstrip("/") + "/"
    done = set(placed)
    wanted: List[str] = []

    def _want(rel: Any) -> None:
        safe = _resume_rel(rel)
        if safe is not None and safe not in done:
            done.add(safe)
            wanted.append(safe)

    _want(AA_ENV_MANIFEST_NAME)
    try:
        paginator = s3.get_paginator("list_objects_v2")
        for page in paginator.paginate(Bucket=bucket, Prefix=f"{base}{AA_ENV_SHARD_DIR}/"):
            for obj in page.get("Contents", []) or []:
                rel = obj["Key"][len(base):]
                if rel and not rel.endswith("/"):
                    _want(rel)
    except Exception as e:  # noqa: BLE001 - the shards the manifest names still come down
        print(f"[HANDLER] WARNING: resume: listing {AA_ENV_SHARD_DIR}/ failed: {e}")
    for rel in event.get("resume_paths") or []:
        _want(rel)
    _stats_add("listed", len(wanted))

    def _items(rels: List[str]) -> List[_InputCopy]:
        out = []
        for rel in rels:
            dst = _safe_dest(workdir, rel)
            if dst is not None and _safe_dest(cache_dir, rel) is not None:
                out.append(_InputCopy(rel, f"{base}{rel}", None, dst, cache_dir=cache_dir, cache_rel=rel,
                                      kind="resume"))
        return out

    copied, errors = _copy_inputs(s3, bucket, _items(wanted), event, workdir=workdir)
    # Shard paths the manifest names outside the shard folder (an older aa_env).
    extra: List[str] = []
    before = len(wanted)
    for rel in _manifest_paths(os.path.join(workdir, AA_ENV_MANIFEST_NAME)):
        _want(rel)
    extra = wanted[before:]
    if extra:
        more_copied, more_errors = _copy_inputs(s3, bucket, _items(extra), event, workdir=workdir)
        copied += more_copied
        errors += more_errors
    quiet = [e for e in errors if e.get("reason") == "not_found"]
    print(f"[HANDLER] resume: {len(copied)} state file(s) in place, {len(quiet)} not in the workspace, "
          f"{len(errors) - len(quiet)} could not be copied (resume_paths: {len(event.get('resume_paths') or [])})")
    return [e for e in errors if e.get("reason") != "not_found"]


def _int_env(name: str, default: int) -> int:
    try:
        return int(os.environ.get(name) or default)
    except (TypeError, ValueError):
        return default


class Budget(NamedTuple):
    """One exec action's time budget (see `_compute_budget`)."""
    hard_timeout: int              #: coreutils cap on the script, seconds
    deadline: float                #: epoch at which a cooperative script should yield (AA_DEADLINE_EPOCH)
    reserve: int                   #: seconds kept after the kill for the workdir → S3 upload
    grace: int                     #: seconds before the kill in which aa_env checkpoints
    bound: str                     #: "environment" (the Lambda clock decided) | "requested" (event["timeout"] decided)
    remaining: Optional[float]     #: Lambda remaining time at entry, seconds; None off-Lambda
    limit_seconds: Optional[int]   #: event["env_timeout_seconds"]: the environment's configured limit


def _positive_int(value: Any) -> Optional[int]:
    if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
        return None
    return int(value)


def _compute_budget(event: Dict[str, Any], context: Any) -> Budget:
    """Return the `Budget` for an exec action.

    The hard timeout is the coreutils cap on the script; the deadline is the
    earlier soft point (exported as ``AA_DEADLINE_EPOCH``) at which a cooperative
    checkpointing script should yield, leaving grace to flush + upload.

    Derived from the LIVE Lambda remaining time so a checkpointed chunk is as
    large as safely possible, minus an upload reserve that SCALES with the
    function's own timeout (an environment is provisioned with its
    ``resource_config.timeout_seconds`` as the Lambda ``Timeout``, 1–1,800 s)::

        reserve      = min(upload_reserve_s [60], max(5, remaining // 4))
        hard_timeout = max(5, min(remaining - reserve, event["timeout"]))
        grace        = min(yield_grace_s [30],  max(5, hard_timeout // 3))
        deadline     = now + (hard_timeout - grace)

    so a 60 s environment gives code 45 s (reserve 15), a 120 s one 90 s
    (reserve 30), a 900 s one 840 s and an 1,800 s one 1,740 s (reserve 60) — the flat 60 s reserve
    used to leave every environment under ~65 s with the 5 s floor.
    ``event["timeout"]`` (the caller's ceiling — the coder's
    ``CODER_ENV_INVOKE_TIMEOUT_SECONDS``, code-interpreter's request timeout,
    both clamped to the environment's limit) caps it further; ``bound`` records
    which of the two won so a kill can be reported as the environment's limit
    or as the caller's request. Falls back to the event timeout when no Lambda
    context is available (local/tests).
    """
    def _param(key: str, env_name: str, default: int) -> int:
        v = _positive_int(event.get(key))
        return v if v is not None else _int_env(env_name, default)

    reserve_cap = _param("upload_reserve_s", "AA_UPLOAD_RESERVE_S", _DEFAULT_UPLOAD_RESERVE_S)
    grace_cap = _param("yield_grace_s", "AA_YIELD_GRACE_S", _DEFAULT_YIELD_GRACE_S)
    requested = _positive_int(event.get("timeout"))
    limit = _positive_int(event.get("env_timeout_seconds"))
    remaining: Optional[float] = None
    try:
        if context is not None and hasattr(context, "get_remaining_time_in_millis"):
            remaining = context.get_remaining_time_in_millis() / 1000.0
    except Exception:
        remaining = None

    bound = "requested"
    if remaining is not None:
        reserve = min(reserve_cap, max(_MIN_UPLOAD_RESERVE_S, int(remaining // 4)))
        hard = remaining - reserve
        bound = "environment"
        if requested is not None and requested < hard:
            hard = float(requested)
            bound = "requested"
    elif requested is not None:
        reserve = min(reserve_cap, max(_MIN_UPLOAD_RESERVE_S, requested // 4))
        hard = float(requested)
    else:
        reserve = reserve_cap
        hard = 300.0
    hard_int = int(max(_MIN_HARD_TIMEOUT_S, hard))
    grace = min(grace_cap, max(_MIN_YIELD_GRACE_S, hard_int // 3))
    deadline = time.time() + max(1, hard_int - grace)
    return Budget(hard_int, deadline, int(reserve), int(grace), bound, remaining, limit)


def _coerce_budget(budget: Any) -> Budget:
    """`_exec_python`/`_exec_shell` take a `Budget`; a plain int (direct
    callers, tests, local harnesses) is a requested-bound budget of that many
    seconds."""
    if isinstance(budget, Budget):
        return budget
    return _compute_budget({"timeout": int(budget)}, None)


def _wall_hit(returncode: int, elapsed: float, hard_timeout: int) -> bool:
    """True when the wall stopped the child. coreutils ``timeout`` exits 124 on
    its SIGTERM; after ``-k`` it SIGKILLs the whole process group (itself
    included) and the parent sees -9 (137 through a shell) — counted as the
    wall only when the clock says so, so an early SIGKILL (OOM) stays what it
    is."""
    if returncode == EXIT_TIMEOUT:
        return True
    return returncode in (-9, 137) and elapsed >= max(0, hard_timeout - 1)


def _wall_report(budget: Budget, elapsed: float) -> Dict[str, Any]:
    """The structured fields an exec response carries when the wall was hit.
    code-interpreter (`lambda_backend._map_handler_timeout`) and the coder
    (`coder_worker.run_in_env`) turn ``error_code == "environment_timeout"``
    into the user-facing "‹environment› exceeded its N-second limit" copy;
    ``bound == "requested"`` means the caller's own ``timeout`` ceiling, not
    the environment, stopped the code."""
    hard, reserve = budget.hard_timeout, budget.reserve
    if budget.bound == "requested":
        message = f"Execution stopped after {hard} s: the {hard}-second timeout requested for this run."
    elif budget.limit_seconds:
        message = (f"Execution stopped after {hard} s: the environment's {budget.limit_seconds}-second limit "
                   f"leaves {hard} s for code ({reserve} s is reserved for saving results).")
    else:
        message = (f"Execution stopped after {hard} s: the environment's execution-time limit leaves "
                   f"{hard} s for code ({reserve} s is reserved for saving results).")
    return {
        "error_type": "infrastructure_error",
        "error_code": "environment_timeout",
        "error": message,
        "limit_seconds": budget.limit_seconds,
        "budget_seconds": hard,
        "reserve_seconds": reserve,
        "bound": budget.bound,
        "elapsed_seconds": round(elapsed, 1),
    }


def _shell_argv(login_shell: bool = False) -> List[str]:
    """The shell `_exec_shell` runs the coder's command under: ``bash`` when the
    image has it, else ``sh``. bash gets ``--noprofile --norc`` (no rc file -
    ``~/.bashrc`` is under a HOME the child can write to - is ever
    sourced; a non-interactive ``bash -c`` reads none by itself, only
    ``$BASH_ENV``, which `_exec_env` strips) unless the invocation asks for a
    login shell (``login_shell: true``), which reads its own scope's profile.
    The connector variables never depended on an rc file: they are in the
    environment the handler spawns the shell with.

    Every connector variable is named ``CONN_{connector_id}_{KEY}`` and a
    connector id is a UUID, so the name carries hyphens and is not a valid
    shell identifier. Debian's ``/bin/sh`` is dash - the base of every shipped
    image - and dash discards such entries from its environment at startup,
    so a command run under ``sh -c`` and every process it spawned (the coder's
    ``python file.py``) saw NONE of the injected credentials, while an
    ``exec_python`` child - no shell in between - saw them all (the handler
    logged the variables it had injected while ``env | grep -c ^CONN_`` under
    ``sh -c`` printed 0). bash keeps invalid-name entries in the environment
    it passes to its children (they are simply not addressable as
    ``$CONN_...``), so under bash a script run through the shell reads them
    from ``os.environ`` exactly as an ``exec_python`` script does."""
    if not shutil.which("bash"):
        # dash: a non-interactive sh reads no rc file ($ENV is interactive-only).
        return ["sh", "-l", "-c"] if login_shell else ["sh", "-c"]
    if login_shell:
        return ["bash", "-l", "-c"]
    return ["bash", "--noprofile", "--norc", "-c"]


def _kill_after(budget: Budget) -> int:
    """``timeout -k``: seconds between the wall's SIGTERM and its SIGKILL."""
    return max(1, min(_MAX_KILL_AFTER_S, budget.reserve // 3))


def _room_for_code(budget: Budget, time_left: Optional[float]) -> Optional[int]:
    """Whole seconds the program can have with ``time_left`` seconds left in
    the invocation and the upload reserve kept (the kill margin,
    `_kill_after`, is paid out of the reserve, as at the entry: an 1,800 s
    kernel still gives code 1,740 s); None without a Lambda clock. Rounded,
    so the moment spent between the entry and the start costs no second."""
    if time_left is None:
        return None
    return int(round(time_left - budget.reserve))


def _budget_now(budget: Budget, time_left: Optional[float]) -> Budget:
    """``budget`` re-derived at the program's start: the wall is
    ``min(hard_timeout, time left - reserve)`` (never below
    `_MIN_HARD_TIMEOUT_S`) and the yield deadline is recomputed from this
    moment. A wall the clock shortened is the environment's, whatever bound
    the entry chose."""
    room = _room_for_code(budget, time_left)
    if room is None:
        return budget
    hard = max(_MIN_HARD_TIMEOUT_S, min(budget.hard_timeout, room))
    bound = budget.bound if hard >= budget.hard_timeout else "environment"
    grace = min(budget.grace, max(_MIN_YIELD_GRACE_S, hard // 3))
    deadline = time.time() + max(1, hard - grace)
    return budget._replace(hard_timeout=int(hard), deadline=deadline, grace=int(grace), bound=bound)


def _inputs_took_budget(budget: Any, sync_report: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """The response when copying the mirror and the inputs left the program
    less than `_MIN_HARD_TIMEOUT_S`: exit 124, ``environment_timeout`` with
    ``reason`` ``inputs_took_budget`` and a sentence naming the time it took,
    and the program never started. None when there is room (or no clock)."""
    budget = _coerce_budget(budget)
    room = _room_for_code(budget, _invocation_time_left())
    if room is None or room >= _MIN_HARD_TIMEOUT_S:
        return None
    took = int(round(time.monotonic() - _INVOCATION_START)) if _INVOCATION_START is not None else 0
    total = budget.limit_seconds or (int(round(budget.remaining)) if budget.remaining else 0)
    of = f" of the kernel's {total:,} s" if total else ""
    message = (f"Copying the inputs took {took:,} s{of}, so the program was not started. Copy fewer or "
               "smaller inputs, or read the large ones in parts, and run it again.")
    print(f"[HANDLER] not starting the program: {message} (room for code {room}s)")
    stderr = message
    input_errors = list(sync_report.get("input_errors") or [])
    if input_errors:
        stderr += "\n" + "\n".join(_input_error_line(err) for err in input_errors[:_INPUT_ERRORS_MAX])
    out: Dict[str, Any] = {
        "exit_code": EXIT_TIMEOUT, "stdout": "", "stderr": stderr, "uploaded": [], "uploads": [],
        "uploaded_count": 0, "upload_errors": [],
        "error_type": "infrastructure_error", "error_code": "environment_timeout", "reason": "inputs_took_budget",
        "error": message, "limit_seconds": budget.limit_seconds, "budget_seconds": 0,
        "reserve_seconds": budget.reserve, "bound": "environment", "elapsed_seconds": 0.0, "inputs_seconds": took,
    }
    if input_errors:
        out["input_errors"] = input_errors[:_INPUT_ERRORS_MAX]
    if _TMP_FREE_BYTES is not None:
        out["tmp_free_bytes"] = _TMP_FREE_BYTES
    if "downloaded" in sync_report:
        out["sync"] = {"downloaded": len(sync_report.get("downloaded") or []),
                       "unchanged": sync_report.get("unchanged", 0),
                       "skipped": list(sync_report.get("skipped") or [])[:50],
                       "truncated": bool(sync_report.get("truncated"))}
    out["sync_stats"] = _sync_stats()
    return out


def _run_captured(argv: List[str], workdir: str, env: Dict[str, str], budget: Budget,
                  capture: "_OutputCapture") -> Tuple[Any, Optional[Dict[str, Any]]]:
    """`_run_under_wall` with ``capture`` taking the child's stdout and
    stderr (PRO-2358). The capture is finished (its copies drained) before
    this returns, also when the spawn itself fails."""
    global _CURRENT_CAPTURE
    capture.start()
    _CURRENT_CAPTURE = capture
    try:
        return _run_under_wall(argv, workdir, env, budget)
    finally:
        _CURRENT_CAPTURE = None
        capture.finish()


def _run_under_wall(argv: List[str], workdir: str, env: Dict[str, str], budget: Budget,
                    clock=time.monotonic) -> Tuple[Any, Optional[Dict[str, Any]]]:
    """Run ``argv`` under ``timeout -k <kill_after> <hard_timeout>`` with cwd =
    the project root, capturing stdout/stderr. Returns ``(result, wall)`` where
    ``wall`` is `_wall_report` when the wall stopped the child (its
    ``returncode`` normalised to `EXIT_TIMEOUT`) and ``None`` otherwise.

    Output the child flushed before the kill IS kept — the pipe survives
    the signal (verified on coreutils 9 / python:3.12-slim); only output
    still sitting in the child's own buffer is lost, which is why
    `_exec_python` runs with ``PYTHONUNBUFFERED=1``.

    With `_CURRENT_CAPTURE` set (the exec paths, PRO-2358) stdout and stderr
    go to its pipes and ``result.stdout`` / ``result.stderr`` are None: the
    output is in the capture's files. Without one they are captured in
    memory as before.
    """
    left = _invocation_time_left()
    if left is not None:
        # REL-2: the wall starts now, after the mirror and the inputs, so it
        # is measured from the time the invocation has left now, never from
        # the entry; the yield deadline moves with it.
        budget = _budget_now(budget, left)
        env["AA_DEADLINE_EPOCH"] = str(budget.deadline)
    kill_after = _kill_after(budget)
    capture = _CURRENT_CAPTURE
    io: Dict[str, Any] = (
        {"stdout": capture.child_fd("stdout"), "stderr": capture.child_fd("stderr")}
        if capture is not None else {"capture_output": True}
    )
    t0 = clock()
    result = subprocess.run(
        ["timeout", "-k", str(kill_after), str(budget.hard_timeout), *argv],
        cwd=workdir,
        env=env,
        preexec_fn=_no_core_dumps,
        **io,
    )
    elapsed = clock() - t0
    wall = None
    if _wall_hit(result.returncode, elapsed, budget.hard_timeout):
        wall = _wall_report(budget, elapsed)
        result.returncode = EXIT_TIMEOUT
    return result, wall


# ---------------------------------------------------------------------------
# Capability probe (v1.0.120): what document tooling this image
# actually has. Cheap version checks with short timeouts; a missing tool is
# ``False``, never an exception, so the coder's prompt can say "missing:
# node, chromium" instead of the coder discovering it mid-deliverable.
# ---------------------------------------------------------------------------

_VERSION_RE = re.compile(r"(\d+(?:\.\d+)+)")


def _probe_run(args: List[str], env: Optional[Dict[str, str]] = None,
               timeout: Optional[int] = None) -> Optional[subprocess.CompletedProcess]:
    """Run one probe command; ``None`` when the tool is absent or hangs.
    ``timeout`` defaults to `PROBE_TIMEOUT_S`; the big binaries pass the
    lock's browser ceiling instead (a cold start pages them in slowly)."""
    try:
        return subprocess.run(args, capture_output=True, text=True,
                              timeout=timeout if timeout else PROBE_TIMEOUT_S,
                              env=env if env is not None else _child_env({}),
                              preexec_fn=_no_core_dumps)
    except (FileNotFoundError, PermissionError, subprocess.TimeoutExpired, OSError):
        return None


def _probe_version(args: List[str], env: Optional[Dict[str, str]] = None, require_rc0: bool = True,
                   timeout: Optional[int] = None):
    """First dotted version number in stdout+stderr, or ``False``."""
    r = _probe_run(args, env, timeout)
    if r is None or (require_rc0 and r.returncode != 0):
        return False
    m = _VERSION_RE.search((r.stdout or "") + "\n" + (r.stderr or ""))
    return m.group(1) if m else False


#: The lock check that vouches for each probed capability when the tool's
#: own version probe came back False. On a COLD container-image
#: Lambda the first touch of soffice/pandoc/weasyprint/chromium pages in a
#: multi-hundred-MB binary and exceeds `PROBE_TIMEOUT_S`; the same probe on a
#: warm instance answers in a second. The checks run first (warming the
#: binaries) and a passing check is proof the tool is there, so the boolean
#: is derived from it rather than reported False for the whole session.
#: Lock checks that touch a big, lazily paged-in binary; they run with the
#: browser ceiling (`_run_toolkit_checks`) for the same cold-start reason.
_SLOW_CHECK_NAMES = ("soffice", "pandoc", "weasyprint")
_CHECK_FOR_CAPABILITY = {
    "libreoffice": "soffice", "poppler": "pdftoppm", "pandoc": "pandoc", "weasyprint": "weasyprint",
    "node": "node", "pptxgenjs": "pptxgenjs", "graphviz": "graphviz", "mermaid": "mmdc",
    # mermaid-render launches the toolkit's Chromium; passing means the browser runs.
    "chromium": "mermaid-render",
}
def _derive_from_checks(caps: Dict[str, Any], checks: List[Dict[str, Any]], outputs: Dict[str, str]) -> None:
    """For every capability still False whose vouching check passed
    (``ok is True`` — never a skipped or failed one), set the version parsed
    from the check's output, or True when the output carries no version."""
    by_name = {c.get("name"): c for c in checks if isinstance(c, dict)}
    for key, check_name in _CHECK_FOR_CAPABILITY.items():
        if caps.get(key) is not False:
            continue
        check = by_name.get(check_name)
        if not check or check.get("ok") is not True:
            continue
        m = _VERSION_RE.search(outputs.get(check_name) or "")
        caps[key] = m.group(1) if m else True


def _read_toolkit_lock() -> Tuple[Optional[str], Dict[str, Any]]:
    """``(toolkit_version, lock_dict)`` from `TOOLKIT_LOCK_PATH`. The lock is
    the JSON the document toolkit image ships (``toolkit_version``,
    ``check_semantics``, ``checks[]``, package lists — unknown keys ignored);
    a bare version line or ``version: x`` text is accepted for the version
    alone. ``(None, {})`` when the file is absent or empty."""
    try:
        with open(TOOLKIT_LOCK_PATH, "r", encoding="utf-8") as f:
            text = f.read().strip()
    except OSError:
        return None, {}
    if not text:
        return None, {}
    try:
        data = json.loads(text)
    except ValueError:
        data = None
    if isinstance(data, dict):
        version = data.get("toolkit_version") or data.get("version")
        return (str(version) if version else None), data
    m = re.search(r"version\s*[:=]\s*\"?([^\s\"]+)", text, re.IGNORECASE)
    if m:
        return m.group(1), {}
    return (text.splitlines()[0].strip() or None), {}


def _version_tuple(version: Optional[str]) -> Optional[Tuple[int, ...]]:
    """``"1.10.2"`` -> ``(1, 10, 2)``; None for anything non-numeric."""
    if not version:
        return None
    m = re.match(r"\s*v?(\d+(?:\.\d+)*)", str(version))
    if not m:
        return None
    return tuple(int(x) for x in m.group(1).split("."))


def _toolkit_outdated(installed: Optional[str]) -> bool:
    """True when the installed lock's version is numerically below
    `HANDLER_TOOLKIT_VERSION`. An absent lock (None) or a non-numeric version
    is not "outdated" — it is already reported as missing/odd elsewhere."""
    have, want = _version_tuple(installed), _version_tuple(HANDLER_TOOLKIT_VERSION)
    if have is None or want is None:
        return False
    return have < want


def _int_or(value: Any, default: int) -> int:
    try:
        v = int(value)
        return v if v > 0 else default
    except (TypeError, ValueError):
        return default


def _machine() -> str:
    try:
        return os.uname().machine
    except Exception:  # noqa: BLE001
        return ""


def _browser_emulated() -> Optional[str]:
    """Reason string when Chromium cannot run here (x86_64 under QEMU
    user-mode emulation: no x86 ``flags:`` line in /proc/cpuinfo), else None."""
    if _machine() != "x86_64":
        return None
    try:
        with open(CPUINFO_PATH, "r", encoding="utf-8", errors="replace") as f:
            for line in f:
                if line.startswith("flags"):
                    return None
    except OSError:
        return None
    return "needs_browser: skipped under QEMU user-mode emulation (x86_64 with no cpuinfo flags line)"


def _run_toolkit_checks(lock: Dict[str, Any], env: Dict[str, str],
                        outputs: Optional[Dict[str, str]] = None) -> List[Dict[str, Any]]:
    """The lock's ``checks[]`` exactly per its ``check_semantics``: each
    ``cmd`` via ``/bin/sh -c`` (offline, runtime user), pass = exit 0 AND
    ``re.search(expect, stdout + stderr)``; ``needs_browser`` checks are
    ``skipped`` (ok=None) with a reason under emulation. Per-check timeout:
    the lock's ``check_timeout_s`` (default `PROBE_TIMEOUT_S`), or for
    ``needs_browser`` checks its ``browser_check_timeout_s`` (default
    `BROWSER_CHECK_TIMEOUT_S` — a cold Chromium in Lambda is slow). Malformed
    entries are reported, never raised. ``outputs``, when given,
    collects each executed check's combined stdout+stderr by name so
    `_derive_from_checks` can read a version out of it; the reported entries
    keep their ``{name, ok, skipped[, reason]}`` shape."""
    results: List[Dict[str, Any]] = []
    checks = lock.get("checks")
    if not isinstance(checks, list):
        return results
    emulated = _browser_emulated()
    default_timeout = _int_or(lock.get("check_timeout_s"), PROBE_TIMEOUT_S)
    browser_timeout = _int_or(lock.get("browser_check_timeout_s"), BROWSER_CHECK_TIMEOUT_S)
    for i, check in enumerate(checks, start=1):
        if not isinstance(check, dict):
            continue
        name = str(check.get("name") or f"check-{i}")
        entry: Dict[str, Any] = {"name": name, "ok": None, "skipped": False}
        if check.get("needs_browser") and emulated:
            entry["skipped"] = True
            entry["reason"] = emulated
            results.append(entry)
            continue
        cmd = check.get("cmd")
        expect = check.get("expect")
        if not isinstance(cmd, str) or not cmd.strip() or not isinstance(expect, str):
            entry["ok"] = False
            entry["reason"] = "malformed check: cmd and expect are required strings"
            results.append(entry)
            continue
        try:
            pattern = re.compile(expect)
        except re.error as e:
            entry["ok"] = False
            entry["reason"] = f"invalid expect pattern: {e}"
            results.append(entry)
            continue
        # With the checks running first, a big binary's check IS its
        # first touch on a cold instance — the very touch that blew the 15 s
        # probe ceiling. Those checks get the browser ceiling too (deliberate
        # deviation from the lock's check_semantics prose: a longer ceiling
        # cannot turn a passing check into a failure).
        slow = check.get("needs_browser") or name in _SLOW_CHECK_NAMES
        timeout = browser_timeout if slow else default_timeout
        try:
            r = subprocess.run(["/bin/sh", "-c", cmd], capture_output=True, text=True,
                               timeout=timeout, env=env, preexec_fn=_no_core_dumps)
        except subprocess.TimeoutExpired:
            entry["ok"] = False
            entry["reason"] = f"timeout after {timeout}s"
            results.append(entry)
            continue
        except OSError as e:
            entry["ok"] = False
            entry["reason"] = f"could not run: {e}"
            results.append(entry)
            continue
        combined = (r.stdout or "") + (r.stderr or "")
        if outputs is not None:
            outputs[name] = combined[:4000]
        matched = pattern.search(combined) is not None
        if r.returncode == 0 and matched:
            entry["ok"] = True
        else:
            entry["ok"] = False
            why = []
            if r.returncode != 0:
                why.append(f"exit {r.returncode}")
            if not matched:
                why.append(f"expect {expect!r} not found")
            tail = combined.strip().splitlines()[-1][-200:] if combined.strip() else ""
            entry["reason"] = "; ".join(why) + (f" (last line: {tail})" if tail else "")
        results.append(entry)
    return results


#: Resolves the pptxgenjs package root from ``require.resolve`` (its main
#: entry, ``dist/pptxgen.cjs.js``) and reads the nearest package.json above it.
#: ``require('pptxgenjs/package.json')`` is NOT an exported subpath of that
#: package (ERR_PACKAGE_PATH_NOT_EXPORTED), which is why the probe said
#: ``pptxgenjs: false`` on our own image.
_PPTXGENJS_VERSION_JS = (
    "const fs=require('fs'),path=require('path');"
    "let d=path.dirname(require.resolve('pptxgenjs'));"
    "for(;;){const pj=path.join(d,'package.json');"
    "if(fs.existsSync(pj)){console.log(JSON.parse(fs.readFileSync(pj,'utf8')).version);break;}"
    "const up=path.dirname(d);if(up===d){process.exit(1);}d=up;}"
)


def _probe_chromium(lock: Dict[str, Any], env: Dict[str, str], timeout: Optional[int] = None):
    """The toolkit's browser is the lock's ``chromium.executable_link``
    (``/opt/alphaagent/chrome``), never a system ``chromium`` binary — probe
    that first, launched with the lock's Lambda-safe ``args`` (``--version``
    still needs a launchable configuration). System names remain a fallback
    for a customer image that installed a distro Chromium instead."""
    chromium = lock.get("chromium") if isinstance(lock.get("chromium"), dict) else {}
    link = chromium.get("executable_link")
    args = chromium.get("args") if isinstance(chromium.get("args"), list) else []
    if isinstance(link, str) and link:
        v = _probe_version([link, *[str(a) for a in args], "--version"], env, timeout=timeout)
        if v:
            return v
    for exe in ("chromium", "chromium-browser", "google-chrome"):
        v = _probe_version([exe, "--version"], env, timeout=timeout)
        if v:
            return v
    return False


#: Run as a real child of the handler process by the probe: does a same-uid
#: sibling of the sandbox still read this process's start-up environment?
_CHILD_ENVIRON_PROBE = (
    "import os,json\n"
    "p=os.getppid();r={'ppid_environ':None,'credential_names':None,'error':None,'maps':None,'mem':None}\n"
    "try:\n"
    "  d=open('/proc/%d/environ' % p,'rb').read()\n"
    "  r['ppid_environ']='readable'\n"
    "  r['credential_names']=sorted(k for k in ('AWS_ACCESS_KEY_ID','AWS_SECRET_ACCESS_KEY','AWS_SESSION_TOKEN','AWS_SECURITY_TOKEN') if any(e.startswith(k.encode()+b'=') for e in d.split(b'\\0')))\n"
    "except Exception as e:\n"
    "  r['ppid_environ']='denied' if isinstance(e,PermissionError) else 'unavailable'; r['error']=type(e).__name__\n"
    "for f in ('maps','mem'):\n"
    "  try:\n"
    "    open('/proc/%d/%s' % (p,f),'rb').close(); r[f]='opened'\n"
    "  except Exception as e:\n"
    "    r[f]='denied' if isinstance(e,PermissionError) else type(e).__name__\n"
    "print(json.dumps(r))"
)
_DENY_ALL_POLICY = json.dumps({"Version": "2012-10-17",
                               "Statement": [{"Effect": "Deny", "Action": "*", "Resource": "*"}]})


def _check_scoped_role() -> Dict[str, Any]:
    """Probe-time check that the sandbox role exists and trusts this role: one
    AssumeRole with a deny-everything session policy, credentials discarded.
    Reported as ``credential_isolation.scoped_role`` on every environment
    row, so the role's rollout is visible rather than assumed. Only under the
    real runtime - a local probe never reaches STS."""
    out: Dict[str, Any] = {"arn": None, "assumable": None, "error": None}
    if not os.environ.get("AWS_LAMBDA_RUNTIME_API"):
        out["error"] = "not checked outside the Lambda runtime"
        return out
    arn = _scoped_role_arn()
    out["arn"] = arn
    if not arn:
        out["error"] = f"no scoped role ARN: not derivable from this role's name and {SANDBOX_ROLE_ARN_ENV} unset"
        return out
    try:
        _sts_client().assume_role(RoleArn=arn, RoleSessionName="aa-env-probe",
                                  Policy=_DENY_ALL_POLICY, DurationSeconds=900)
        out["assumable"] = True
    except Exception as exc:
        out["assumable"] = False
        out["error"] = _error_code(exc)
    return out


def _isolation_report(env: Dict[str, str]) -> Dict[str, Any]:
    """`_ISOLATION` (what import did, re-measured at this invocation) plus two
    live measurements: a real child of this process trying
    ``/proc/<ppid>/environ``, ``maps`` and ``mem`` (Linux) - the READ and
    ATTACH gates a hostile child would have to pass - and whether the sandbox
    role can be assumed (`_check_scoped_role`)."""
    report: Dict[str, Any] = dict(_ISOLATION)
    report["child_can_read_parent_environ"] = None
    report["child_sees_credential_names"] = None
    report["child_can_read_parent_maps"] = None
    report["child_can_open_parent_mem"] = None
    if sys.platform.startswith("linux"):
        r = _probe_run([sys.executable, "-c", _CHILD_ENVIRON_PROBE], env)
        if r is not None and r.returncode == 0:
            try:
                data = json.loads((r.stdout or "").strip().splitlines()[-1])
                report["child_can_read_parent_environ"] = data.get("ppid_environ") == "readable"
                report["child_sees_credential_names"] = data.get("credential_names")
                report["child_probe_error"] = data.get("error")
                report["child_can_read_parent_maps"] = data.get("maps") == "opened"
                report["child_can_open_parent_mem"] = data.get("mem") == "opened"
            except (ValueError, IndexError):
                report["child_probe_error"] = "unparseable child output"
    report["scoped_role"] = _check_scoped_role()
    report.setdefault("credential_scope", None)
    return report


def probe_capabilities() -> Dict[str, Any]:
    """The capability map: ``{toolkit_version?, libreoffice, poppler, pandoc,
    weasyprint, node, pptxgenjs, chromium, graphviz, mermaid, fonts:[...],
    checked_at}`` — a version string (or True) when present, False when not.
    Plus (v1.0.120) the lock's ``checks`` / ``toolkit_ok`` and (v1.0.121)
    ``toolkit_outdated`` / ``toolkit_expected_version`` and the /tmp gauge
    ``tmp_used_bytes`` / ``tmp_total_bytes``; (1.0.154) ``credential_isolation``
    (`_isolation_report`); (2.0.15) ``trusted_ca``: ``{state, count, sha256,
    read_at}`` (`_TRUSTED_CA`) plus ``outcome`` and ``outcome_reason``
    (`_trust_outcome`): whether every client trusts an issuing CA added on
    its own (``cross_certified``) or only Python does (``partial_chain``,
    with the reason); ``java`` and ``jpype`` (the Python and Java
    environment): version strings, False where absent."""
    env = _child_env({})
    # soffice writes a profile on first run; without a writable HOME + a
    # writable UserInstallation it can exit 0 having printed nothing, or hang.
    lo_profile = os.path.join(TMP_ROOT, "lo_probe")
    try:
        os.makedirs(lo_profile, exist_ok=True)
    except OSError:
        pass
    toolkit_version, lock = _read_toolkit_lock()
    # The lock's checks run FIRST. On a cold container-image instance
    # they are what pages soffice/pandoc/weasyprint/chromium in, so the version
    # probes below meet warm binaries; their outputs are kept (by name) so a
    # probe that still misses can be derived from its passing check.
    check_outputs: Dict[str, str] = {}
    checks = _run_toolkit_checks(lock, env, outputs=check_outputs) if lock else []
    slow_timeout = _int_or(lock.get("browser_check_timeout_s"), BROWSER_CHECK_TIMEOUT_S) if lock else BROWSER_CHECK_TIMEOUT_S
    caps: Dict[str, Any] = {
        "toolkit_version": toolkit_version,
        "toolkit_expected_version": HANDLER_TOOLKIT_VERSION,
        "toolkit_outdated": _toolkit_outdated(toolkit_version),
        "libreoffice": _probe_version(
            ["soffice", "--headless", "--norestore", "--nolockcheck",
             f"-env:UserInstallation=file://{lo_profile}", "--version"], env, timeout=slow_timeout),
        # pdftoppm -v prints to stderr and exits 0 (99 on very old builds).
        "poppler": _probe_version(["pdftoppm", "-v"], env, require_rc0=False),
        "pandoc": _probe_version(["pandoc", "-v"], env, timeout=slow_timeout),
        "weasyprint": _probe_version(
            [sys.executable, "-c", "import weasyprint; print(weasyprint.__version__)"], env, timeout=slow_timeout),
        "node": _probe_version(["node", "-v"], env),
        "pptxgenjs": _probe_version(["node", "-e", _PPTXGENJS_VERSION_JS], env),
        "chromium": _probe_chromium(lock, env, timeout=slow_timeout),
        "graphviz": _probe_version(["dot", "-V"], env, require_rc0=False),
        "mermaid": _probe_version(["mmdc", "-V"], env),
        # The prebuilt Python and Java environment (and custom images built
        # on it): a Java runtime, and JPype to call it from Python. `java
        # -version` prints on stderr; both read False where they are absent.
        "java": _probe_version(["java", "-version"], env),
        "jpype": _probe_version([sys.executable, "-c", "import jpype; print(jpype.__version__)"], env),
        "fonts": [],
        "checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
    }
    r = _probe_run(["fc-list", ":", "family"], env)
    if r is not None and r.returncode == 0:
        fams = set()
        for line in (r.stdout or "").splitlines():
            fam = line.split(",", 1)[0].strip()
            if fam:
                fams.add(fam)
        caps["fonts"] = sorted(fams)
    # The toolkit's own contract: the lock's checks (run above, per its
    # check_semantics). Additive to the boolean capability map.
    caps["checks"] = checks
    caps["toolkit_ok"] = bool(lock) and all(c["ok"] is True for c in caps["checks"] if not c["skipped"])
    _derive_from_checks(caps, checks, check_outputs)
    # The credential-isolation layers as this process and a real child see
    # them (1.0.154): re-exec, /proc snapshot, dumpable flag, ptrace_scope,
    # whether a child can read /proc/<ppid>/environ, the scoped role.
    caps["credential_isolation"] = _isolation_report(env)
    # The deployment's trusted certificate authorities as this container
    # holds them (`handler` refreshed them before this action ran), and the
    # form agent code gets them in, built now if this container has not yet.
    caps["trusted_ca"] = {k: _TRUSTED_CA[k] for k in ("state", "count", "sha256", "read_at")}
    caps["trusted_ca"].update(_trust_outcome())
    # Which handler answered: contract version, delivery path, release.
    caps.update(_handler_delivery())
    try:
        usage = shutil.disk_usage(TMP_ROOT)
        caps["tmp_used_bytes"], caps["tmp_total_bytes"] = int(usage.used), int(usage.total)
    except OSError:
        caps["tmp_used_bytes"], caps["tmp_total_bytes"] = 0, 0
    return caps


def handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]:
    """Lambda entrypoint.

    Event schema::

        {
            "action": "exec_python" | "exec_shell" | "write_file" | "read_file" | "list_files" | "fetch_object"
                      | "probe_capabilities" | "warm",
            "s3_bucket": "alphaagent-workspaces-...",
            "s3_prefix": "users/{uid}/projects/conversations/{slug}/",   # (legacy: workspaces/sessions/{id}/workspace/)
            "timeout": 300,           # seconds: the caller's CEILING on one exec (the live budget can be lower)
            "env_timeout_seconds": 60, # the environment's configured limit (its Lambda Timeout); named in the timeout error
            "script_path": "...",     # project-relative script to run (exec_python; preferred)
            "code": "...",            # inline Python source (exec_python; lands in code/scratch/)
            "script_name": "...",     # filename for inline code (exec_python)
            "ephemeral": bool,        # inline code lands in a hidden dir, never uploaded
            "command": "...",         # Shell command string (exec_shell)
            "login_shell": bool,      # exec_shell: run a login shell (reads the scope's own profile);
                                      # default false: bash --noprofile --norc
            "sync_dirs": ["code", "nodes", "inputs"],   # project dirs to mirror down first
            "sync_max_bytes": N, "sync_skip_over_bytes": N,   # optional size guards
            "prefetch": [...],        # extra objects to hydrate (relative or full keys)
            "preserve_paths": bool,   # prefetch keeps relative paths (default: basename)
            "resume": bool,           # checkpoint continuation: its state is copied down first
            "resume_paths": [...],    # (3) with resume: only aa_env's manifest and shards plus these
                                      # project-relative paths (the previous continuation's uploads);
                                      # without it the whole prefix comes down, as before
            "sync_concurrency": 16,   # (3) downloads and listings at once (1 to 64; default 16)
            "path": "...",            # Relative path (file operations)
            "content": "...",         # File content (write_file)
            "agent_id": "...",        # For credential lookup
            "connector_ids": [...]    # The session's CONN_<id>_* variable names to inject
            "connector_vars": [...]   # The same names versioned (<name>#<suffix>): injected
                                      # under the plain name, one connector version each
        }

    exec responses carry ``uploaded`` (project-relative paths the run created
    or changed) and, when ``sync_dirs`` was given, a ``sync`` summary; since
    contract "3" also ``sync_stats`` (`_sync_stats`). ``warm`` (contract "3")
    takes the exec envelope with no program: it brings ``sync_dirs`` (default
    `DEFAULT_SYNC_DIRS`) and ``refs`` into the project's verified cache, runs
    nothing, uploads nothing and answers ``{ok, action: "warm",
    handler_version, sync_stats}`` (`_warm`). When the
    wall stops the script the response is ``exit_code`` 124 with the captured
    ``stdout``/``stderr`` PLUS ``error_type: "infrastructure_error"``,
    ``error_code: "environment_timeout"``, a readable ``error``,
    ``limit_seconds`` (the environment's limit), ``budget_seconds`` (what the
    code got), ``reserve_seconds`` and ``bound`` (``"environment"`` |
    ``"requested"``) — see `_compute_budget` / `_wall_report`. A failed exec
    whose stderr shows a certificate-verification error carries
    ``untrusted_certificate: true`` and one more stderr line (`_finish_run`).
    """
    action = event.get("action", "")
    s3_bucket = event.get("s3_bucket", "")
    s3_prefix = event.get("s3_prefix", "")
    timeout = event.get("timeout", 300)

    print(f"[HANDLER] entry: action={action}, bucket={s3_bucket}, prefix={s3_prefix}, "
          f"timeout={timeout}, resume={bool(event.get('resume'))}")
    delivery = _handler_delivery()
    print(f"[HANDLER] uid={os.getuid()}, gid={os.getgid()}, handler_version={delivery['handler_version']}, "
          f"delivery={delivery['handler_delivery']} ({delivery['handler_delivery_reason'] or delivery['handler_release']}) "
          f"from {delivery['handler_path']}")
    # A crashed child (Chrome under the 1.0.0 flags) leaves ~82 MB cores under
    # /tmp; on a warm instance six of those fill the disk and every later
    # action dies with ENOSPC. Sweep first, and make /tmp usage visible in
    # CloudWatch on every invocation.
    # PRO-2358: an invocation that died before its cleanup (timeout, out of
    # memory) leaves its output capture folder; remove those first too.
    global _INVOCATION_START, _TMP_FREE_BYTES
    _INVOCATION_START = time.monotonic()
    _stats_reset()
    captures = _sweep_output_captures()
    removed, tmp_used, tmp_total = _sweep_core_dumps()
    print(f"[HANDLER] tmp sweep: core dumps removed={removed}, output captures removed={captures}, "
          f"tmp_used_bytes={tmp_used}, tmp_total_bytes={tmp_total}")
    # SZ-05: a warm sandbox serves many projects and agents; their mirrors
    # and HOMEs stay on /tmp until room is needed. Make the room this exec
    # can need before anything is copied.
    _TMP_FREE_BYTES = _make_room_on_tmp(event, s3_prefix)

    # FIRST, before anything else looks at the environment, drop
    # whatever a previous invocation of this warm container could have left
    # in the process environment - every action, not only exec.
    purged = _purge_previous_invocation_env()
    print(f"[HANDLER] env: purged {purged} per-invocation variable(s) left by an earlier invocation")

    # Credential isolation, layer 2, every invocation: re-assert and
    # re-measure this process's non-dumpable state (a WARNING if it is not).
    _reassert_non_dumpable()
    print(f"[HANDLER] credential isolation: exec_image={_ISOLATION.get('exec_image')} "
          f"non_dumpable={_ISOLATION.get('non_dumpable')} prctl={_ISOLATION.get('prctl')}")

    # This invocation's reach (credential isolation, layer 3): every S3 and
    # Secrets Manager client built until this returns comes from the session
    # scoped to it - `_s3_client` / `_secrets_client` refuse otherwise.
    global _CURRENT_SCOPE, _INVOCATION_SESSION
    _CURRENT_SCOPE = _scope_from_event(event)
    _INVOCATION_SESSION = None
    print(f"[HANDLER] scope: {_CURRENT_SCOPE.describe()}")
    try:
        # The deployment's trusted certificate authorities: read on a
        # container's first invocation and every `TRUSTED_CA_REFRESH_S` after;
        # never raises.
        _trusted_cas()
        return _dispatch(event, context, action, s3_bucket, s3_prefix)
    finally:
        _CURRENT_SCOPE = None
        _INVOCATION_SESSION = None


def _dispatch(event: Dict[str, Any], context: Any, action: str, s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    """`handler`'s body once the environment is purged and the scope is set."""
    global _INVOCATION_END
    _INVOCATION_END = None
    # This invocation's variables. They reach the child through `_child_env`
    # and are never written to os.environ.
    invocation_env: Dict[str, str] = {}
    budget: Optional[Budget] = None
    if action in ("exec_python", "exec_shell"):
        # Derive the real per-invocation budget from the LIVE Lambda clock and
        # publish the soft deadline so a cooperative checkpointing script (aa_env)
        # can yield before the hard kill. A non-checkpointed script simply runs
        # under the hard timeout as before.
        budget = _compute_budget(event, context)
        _INVOCATION_END = (time.monotonic() + budget.remaining) if budget.remaining is not None else None
        invocation_env["AA_DEADLINE_EPOCH"] = str(budget.deadline)
        print(f"[HANDLER] budget: hard_timeout={budget.hard_timeout}s reserve={budget.reserve}s "
              f"grace={budget.grace}s bound={budget.bound} limit={budget.limit_seconds} "
              f"remaining={budget.remaining} deadline_epoch={budget.deadline:.0f}")
        connector_env = _load_connector_credentials(
            event.get("agent_id", ""),
            event.get("connector_ids", []),
            event.get("connector_vars") or [],
        )
        invocation_env.update(connector_env)
        print(f"[HANDLER] Injected {len(connector_env)} connector env vars")
    elif action == "warm":
        # No program: only the clock, so the copies' retries never run past it.
        try:
            remaining = context.get_remaining_time_in_millis() / 1000.0 if context is not None else None
        except Exception:  # noqa: BLE001
            remaining = None
        _INVOCATION_END = (time.monotonic() + remaining) if remaining is not None else None
    _track_invocation_env(invocation_env)

    try:
        if action == "warm":
            return _warm(event, s3_bucket, s3_prefix)
        if action == "exec_python":
            return _exec_python(event, s3_bucket, s3_prefix, budget, invocation_env)
        elif action == "exec_shell":
            return _exec_shell(event, s3_bucket, s3_prefix, budget, invocation_env)
        elif action == "write_file":
            return _write_file(event, s3_bucket, s3_prefix)
        elif action == "read_file":
            return _read_file(event, s3_bucket, s3_prefix)
        elif action == "list_files":
            return _list_files(event, s3_bucket, s3_prefix)
        elif action == "fetch_object":
            return _fetch_object(event, s3_bucket, s3_prefix)
        elif action == "probe_capabilities":
            return {"exit_code": 0, "stdout": "", "stderr": "", "capabilities": probe_capabilities()}
        else:
            return {"exit_code": 1, "stdout": "", "stderr": f"Unknown action: {action}"}
    except Exception as exc:
        print(f"[HANDLER] Unhandled exception: {traceback.format_exc()}")
        return {
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Handler error: {traceback.format_exc()}",
        }


def _warm(event: Dict[str, Any], s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    """The ``warm`` action (Studio 2.2.28, LAT-17 and EV-8): bring this
    project's mirror (``sync_dirs``, else `DEFAULT_SYNC_DIRS`) and its Folio
    references (``refs``) into the verified cache under this invocation's
    own credentials, so the next exec on this container starts with them.
    No program runs, nothing is uploaded and no connector secret is read.
    The worker sends it when an analysis starts and while it pauses
    (CODER_ENV_KEEPWARM_S), so the container stays warm too."""
    base = {"action": "warm", "handler_version": HANDLER_CONTRACT_VERSION, "stdout": "", "uploaded": []}
    if not s3_bucket or not s3_prefix:
        return {**base, "ok": False, "exit_code": 1, "stderr": "warm needs s3_bucket and s3_prefix",
                "sync_stats": _sync_stats()}
    warm_event = {k: v for k, v in event.items() if k not in ("prefetch", "resume", "resume_paths")}
    warm_event["sync_dirs"] = _event_sync_dirs(event) or list(DEFAULT_SYNC_DIRS)
    workdir = _get_session_workdir(s3_prefix)
    try:
        report = _prepare_workdir(warm_event, s3_bucket, s3_prefix, workdir)
    finally:
        _release_workdir(workdir)
    stats = _sync_stats()
    print(f"[HANDLER] warm: {stats}")
    out: Dict[str, Any] = {**base, "ok": True, "exit_code": 0, "stderr": "", "sync_stats": stats}
    if report.get("input_errors"):
        out["input_errors"] = list(report["input_errors"])[:_INPUT_ERRORS_MAX]
    if _TMP_FREE_BYTES is not None:
        out["tmp_free_bytes"] = _TMP_FREE_BYTES
    return out


def _safe_refs_path(path: Any) -> Optional[str]:
    """A ``refs/`` path taken from an event, or ``None`` when it is refused
    (the Folio contract C7.6; the payload is never trusted): relative,
    starting with ``refs/``, no empty, ``.`` or ``..`` segment, no segment
    starting with ``.``, no backslash or NUL, at most `REFS_PATH_MAX_BYTES`."""
    if not isinstance(path, str) or not path:
        return None
    if "\\" in path or "\x00" in path or path.startswith("/"):
        return None
    if len(path.encode("utf-8", errors="surrogatepass")) > REFS_PATH_MAX_BYTES:
        return None
    parts = path.split("/")
    if len(parts) < 2 or parts[0] != REFS_DIR:
        return None
    if any(p in ("", ".", "..") or p.startswith(".") for p in parts[1:]):
        return None
    return path


def _refs_destination(workdir: str, path: Any) -> Optional[str]:
    """Where a reference lands in ``workdir``: `_safe_refs_path`, and the
    resolved local path must stay under the working root (checked after
    ``os.path.realpath``, so a link planted under ``refs/`` cannot move it)."""
    safe = _safe_refs_path(path)
    if safe is None:
        return None
    root = os.path.realpath(workdir)
    dst = os.path.realpath(os.path.join(root, *safe.split("/")))
    refs_root = os.path.join(root, REFS_DIR)
    if dst != refs_root and not dst.startswith(refs_root + os.sep):
        return None
    return dst


def _download_version(s3: Any, bucket: str, key: str, version_id: str, dst: str) -> None:
    """One object version to ``dst``: GetObject with VersionId, never the
    key's current version (the Folio contract C3.6 "Versioned reads")."""
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    _unlink_quiet(dst)
    s3.download_file(bucket, key, dst, ExtraArgs={"VersionId": version_id})


def _s3_error_reason(exc: BaseException) -> Tuple[str, bool]:
    """``(reason, retry)`` for a failed S3 read: ``not_found``,
    ``access_denied``, ``slow_down`` (retried) or ``error`` (retried when S3
    answered with a 5xx or the connection dropped)."""
    response = getattr(exc, "response", None)
    code, status = "", 0
    if isinstance(response, dict):
        code = str((response.get("Error") or {}).get("Code") or "")
        try:
            status = int((response.get("ResponseMetadata") or {}).get("HTTPStatusCode") or 0)
        except (TypeError, ValueError):
            status = 0
        if code.isdigit() and not status:
            status = int(code)
    if code in ("NoSuchKey", "NoSuchVersion", "NotFound", "404") or status == 404:
        return "not_found", False
    if code in ("AccessDenied", "Forbidden", "AllAccessDisabled", "403") or status == 403:
        return "access_denied", False
    if code in ("SlowDown", "Throttling", "ThrottlingException", "RequestLimitExceeded", "TooManyRequests") \
            or status in (429, 503):
        return "slow_down", True
    if status >= 500 or code in ("InternalError", "ServiceUnavailable", "RequestTimeout"):
        return "error", True
    if response is None and type(exc).__module__.startswith(("botocore", "urllib3", "socket")) \
            or isinstance(exc, (ConnectionError, TimeoutError)):
        return "error", True        # the connection dropped or timed out: worth another try
    return "error", False


def _with_s3_retries(call, *, label: str):
    """``call()``, again after a short jittered pause when S3 answered with
    SlowDown or a 5xx (`_INPUT_COPY_RETRIES` times), never past the time
    the invocation has left."""
    attempt = 0
    while True:
        try:
            return call()
        except Exception as e:  # noqa: BLE001 - classified, re-raised when final
            reason, retry = _s3_error_reason(e)
            pause = _INPUT_RETRY_BASE_S * (2 ** attempt) * random.uniform(1.0, 1.5)
            left = _invocation_time_left()
            if not retry or attempt >= _INPUT_COPY_RETRIES or (
                    left is not None and left < pause + _MIN_HARD_TIMEOUT_S + _MIN_UPLOAD_RESERVE_S):
                raise
            attempt += 1
            print(f"[HANDLER] {label}: {reason} from S3, trying again in {pause:.1f}s ({attempt}/{_INPUT_COPY_RETRIES})")
            time.sleep(pause)


def _tmp_free() -> int:
    try:
        return int(shutil.disk_usage(TMP_ROOT).free)
    except OSError:
        return 0


class _InputCopy(NamedTuple):
    label: str                      #: what the program sees it as (a relative path, a refs/ path)
    key: str
    version_id: Optional[str]
    dst: str
    #: False for a reference that declared no size: its HEAD size is then
    #: counted against the copy limit (`_copy_inputs` ``copy_limit``).
    sized: bool = True
    #: Studio 2.2.28: kept in the project's verified cache at ``cache_rel``
    #: (under ``cache_dir``) and hard-linked to ``dst``. A version's identity
    #: is its version id; any other entry's is the ETag its HEAD reads, and
    #: an entry without one is copied as before.
    cache_dir: Optional[str] = None
    cache_rel: Optional[str] = None
    #: ``ref`` (counted as ``refs_*`` in ``sync_stats``), ``prefetch`` or ``resume``.
    kind: str = "input"


def _ref_cache_rel(key: str, version_id: str) -> str:
    """Where a Folio reference's version lives in the project's cache:
    ``.refs/<sha256(key, version)>``. A version never changes, so the bytes'
    hash is all a cached copy needs."""
    return f"{REFS_CACHE_DIR}/" + hashlib.sha256(f"{key}\n{version_id}".encode("utf-8")).hexdigest()


def _prefetch_cache_rel(key: str) -> str:
    """Where a prefetch entry lives in the project's cache, valid while its ETag holds."""
    return f"{PREFETCH_CACHE_DIR}/" + hashlib.sha256(key.encode("utf-8")).hexdigest()


def _input_error(label: str, reason: str, size: Optional[int] = None) -> Dict[str, Any]:
    out: Dict[str, Any] = {"path": label, "reason": reason}
    if size is not None:
        out["bytes"] = int(size)
    return out


def _input_error_line(err: Dict[str, Any]) -> str:
    """One stderr line per input that could not be copied, in plain words."""
    path, reason = err.get("path"), err.get("reason")
    if reason == "too_large_for_disk":
        size = _size_text(int(err.get("bytes") or 0))
        return (f"{path} could not be copied: it is {size}, more than the kernel's disk has free; "
                "read it in parts instead (aa_env or S3 range reads).")
    if reason == "refused":
        return f"{path} could not be copied: its path or its key is not one a run may read."
    if reason == "over_copy_limit":
        return f"{path} could not be copied: it is over this run's copy limit for inputs."
    if reason == "not_found":
        return f"{path} could not be copied: it was not found."
    if reason == "access_denied":
        return f"{path} could not be copied: access was refused."
    if reason == "slow_down":
        return f"{path} could not be copied: SlowDown; run again."
    return f"{path} could not be copied: {err.get('detail') or 'error'}; run again."


def _copy_inputs(s3: Any, bucket: str, items: List[_InputCopy],
                 event: Optional[Dict[str, Any]] = None,
                 copy_limit: Optional[Tuple[int, int]] = None,
                 workdir: Optional[str] = None) -> Tuple[List[str], List[Dict[str, Any]]]:
    """Copy ``items`` from S3 to their places, ``sync_concurrency`` at a
    time (CODER_MIRROR_CONCURRENCY; 2.2.27 used the upload's). Each is HEADed first, and
    one that will not fit in `_INPUT_DISK_SHARE` of the free /tmp (counting
    the ones before it) is refused as ``too_large_for_disk`` without being
    copied; SlowDown and 5xx answers are retried (`_with_s3_retries`).
    With ``copy_limit`` (``(per-file limit, bytes left of the total)``) an
    item that declared no size (``sized`` False) is held to it by its HEAD
    size, as `_fetch_refs` holds the sized ones by their declared size, and
    refused as ``over_copy_limit`` past it.
    Studio 2.2.28 (LAT-4, SZ-09): an item with a ``cache_rel`` whose cached
    copy is the same version (a reference) or the same ETag, and still
    verified (`_cache_file_ok`), is hard-linked from the cache with no
    download; the HEAD still runs first, so the read is authorised by this
    invocation's own credentials every time. A copied one lands in the cache,
    is hashed and recorded, then linked. ``workdir`` is the working copy the
    links are released with.
    Returns ``(copied labels, errors)`` in the order given; errors are
    ``{path, reason, bytes?}``. Never raises."""
    if not items:
        return [], []
    # The same place twice: the later entry wins, as when they were copied one by one.
    last = {item.dst: i for i, item in enumerate(items)}
    items = [item for i, item in enumerate(items) if last[item.dst] == i]

    def _head(item: _InputCopy) -> Tuple[int, str]:
        kwargs = {"Bucket": bucket, "Key": item.key}
        if item.version_id:
            kwargs["VersionId"] = item.version_id
        head = _with_s3_retries(lambda: s3.head_object(**kwargs), label=f"input {item.label}")
        return int(head.get("ContentLength") or 0), str(head.get("ETag") or "")

    def _identity(item: _InputCopy, etag: str) -> str:
        return f"version:{item.version_id}" if item.version_id else etag

    def _cached_path(item: _InputCopy) -> Optional[str]:
        return _safe_dest(item.cache_dir, item.cache_rel) if item.cache_dir and item.cache_rel else None

    def _download(item: _InputCopy, target: str, want_digest: bool) -> Optional[str]:
        os.makedirs(os.path.dirname(target) or TMP_ROOT, exist_ok=True)
        extra = {"VersionId": item.version_id} if item.version_id else None

        def _once() -> None:
            _unlink_quiet(target)          # never write through a link into the mirror cache
            if extra:
                s3.download_file(bucket, item.key, target, ExtraArgs=extra)
            else:
                s3.download_file(bucket, item.key, target)
        try:
            _with_s3_retries(_once, label=f"input {item.label}")
        except Exception:
            _unlink_quiet(target)
            raise
        if not want_digest:
            return None
        digest = _sha256_file(target)
        if digest is None:
            _unlink_quiet(target)
            raise OSError(f"the copy of {item.label} is not readable")
        return digest

    def _counted(item: _InputCopy, cached: bool, size: int = 0) -> None:
        if item.kind == "ref":
            _stats_add("refs_cached" if cached else "refs_fetched")
        else:
            _stats_add("cached" if cached else "fetched")
        if not cached:
            _stats_add("bytes_fetched", size)

    def _failed(item: _InputCopy, e: BaseException, size: Optional[int] = None) -> Dict[str, Any]:
        reason, _retry = _s3_error_reason(e)
        err = _input_error(item.label, reason, size)
        if reason == "error":
            err["detail"] = f"{type(e).__name__}: {e}"[:_UPLOAD_ERROR_MAX_CHARS]
        print(f"[HANDLER] WARNING: input {item.label} could not be copied: {type(e).__name__}: {e}")
        return err

    errors: Dict[int, Dict[str, Any]] = {}
    sizes: Dict[int, int] = {}
    etags: Dict[int, str] = {}
    workers = min(_sync_concurrency(event), len(items))
    with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="aa-input") as pool:
        heads = {pool.submit(_head, item): i for i, item in enumerate(items)}
        for future, i in heads.items():
            try:
                sizes[i], etags[i] = future.result()
            except Exception as e:  # noqa: BLE001
                errors[i] = _failed(items[i], e)
        room = int(_tmp_free() * _INPUT_DISK_SHARE)
        planned = 0
        unsized = 0
        downloads = {}
        hits: List[int] = []
        for i, item in enumerate(items):
            if i in errors:
                continue
            if copy_limit is not None and not item.sized:
                if sizes[i] > copy_limit[0] or unsized + sizes[i] > copy_limit[1]:
                    errors[i] = _input_error(item.label, "over_copy_limit", sizes[i])
                    print(f"[HANDLER] reference {item.label} ({sizes[i]} bytes) skipped: too large to copy")
                    continue
                unsized += sizes[i]
            cached = _cached_path(item)
            identity = _identity(item, etags.get(i, "")) if cached else ""
            if cached and identity:
                entry = _WORKSPACE_INDEX.get(item.cache_dir, {}).get(item.cache_rel)
                if entry and entry[0] == identity and _cache_file_ok(item.cache_dir, item.cache_rel, cached, entry[1]):
                    hits.append(i)          # already here: linked below, no copy and no room
                    continue
            if planned + sizes[i] > room:
                errors[i] = _input_error(item.label, "too_large_for_disk", sizes[i])
                print(f"[HANDLER] WARNING: input {item.label} ({sizes[i]} bytes) not copied: "
                      f"/tmp has {room - planned} bytes to spare")
                continue
            planned += sizes[i]
            if cached and identity:
                _index_drop(item.cache_dir, item.cache_rel)
                downloads[pool.submit(_download, item, cached, True)] = i
            else:
                downloads[pool.submit(_download, item, item.dst, False)] = i
        for i in hits:
            item = items[i]
            try:
                _link_from_cache(item.cache_dir, item.cache_rel, item.dst, workdir)
                _counted(item, True)
            except OSError as e:
                errors[i] = _failed(item, e, sizes.get(i))
        for future, i in downloads.items():
            item = items[i]
            try:
                digest = future.result()
                if digest is not None:
                    _index_set(item.cache_dir, item.cache_rel, _identity(item, etags.get(i, "")), digest,
                               _cached_path(item) or "")
                    _link_from_cache(item.cache_dir, item.cache_rel, item.dst, workdir)
                _counted(item, False, sizes.get(i, 0))
            except Exception as e:  # noqa: BLE001
                errors[i] = _failed(item, e, sizes.get(i))
    copied = [item.label for i, item in enumerate(items) if i not in errors]
    return copied, [errors[i] for i in sorted(errors)]


def _fetch_refs(event: Dict[str, Any], s3_bucket: str, workdir: str,
                cache_dir: Optional[str] = None) -> Dict[str, List[Any]]:
    """Download ``event["refs"]`` (``[{key, version_id, path}]``) to their
    ``refs/`` paths before the program runs. Each entry is checked here,
    whatever the caller checked: a refused path is logged and skipped, an
    object over the size guards is skipped, a failed download never aborts
    the run. Returns ``{"downloaded": [...], "skipped": [...], "errors":
    [...]}``; ``errors`` says why each skipped reference was not copied
    (``{path, reason, bytes?}``, `_copy_inputs`), so a missing input is never
    silent. With ``cache_dir`` (Studio 2.2.28) each version is kept in the
    project's verified cache and linked from it (`_copy_inputs`)."""
    report: Dict[str, List[Any]] = {"downloaded": [], "skipped": [], "errors": []}
    refs = event.get(REFS_EVENT_KEY)
    if not isinstance(refs, list) or not refs or not s3_bucket:
        return report
    skip_over = _positive_int(event.get("sync_skip_over_bytes")) or _DEFAULT_SYNC_SKIP_OVER_BYTES
    max_bytes = _positive_int(event.get("sync_max_bytes")) or _DEFAULT_SYNC_MAX_BYTES
    total = 0
    items: List[_InputCopy] = []
    for entry in refs:
        if not isinstance(entry, dict):
            continue
        path = entry.get("path")
        key = str(entry.get("key") or "")
        version_id = str(entry.get("version_id") or "")
        dst = _refs_destination(workdir, path)
        if dst is None or not key or not version_id or not key.startswith(("users/", "team/")):
            print(f"[HANDLER] WARNING: reference refused (path {path!r}); it could not be copied")
            report["skipped"].append(str(path))
            report["errors"].append(_input_error(str(path), "refused"))
            continue
        declared = _positive_int(entry.get("size"))
        size = declared or 0
        if size > skip_over or total + size > max_bytes:
            print(f"[HANDLER] reference {path} skipped: too large to copy")
            report["skipped"].append(str(path))
            report["errors"].append(_input_error(str(path), "over_copy_limit", size))
            continue
        total += size
        items.append(_InputCopy(str(path), key, version_id, dst, sized=declared is not None,
                                cache_dir=cache_dir, cache_rel=_ref_cache_rel(key, version_id) if cache_dir else None,
                                kind="ref"))
    # A reference that declared no size is held to what is left of the
    # limit by the size its HEAD reads.
    copied, errors = _copy_inputs(_s3_client(), s3_bucket, items, event,
                                  copy_limit=(skip_over, max(0, max_bytes - total)), workdir=workdir)
    report["downloaded"].extend(copied)
    report["skipped"].extend(e["path"] for e in errors)
    report["errors"].extend(errors)
    if report["downloaded"] or report["skipped"]:
        print(f"[HANDLER] refs: {len(report['downloaded'])} copied read only, {len(report['skipped'])} skipped")
    return report


def _prefetch_files(
    prefetch: List[str],
    s3_bucket: str,
    s3_prefix: str,
    workdir: str,
    preserve_paths: bool = False,
    event: Optional[Dict[str, Any]] = None,
    cache_dir: Optional[str] = None,
) -> List[Dict[str, Any]]:
    """Download declared inputs into the workdir before running code.

    Each entry is either a full S3 key (``users/``, ``workspaces/`` or
    ``conversations/``) or a path relative to ``s3_prefix``. With
    ``preserve_paths`` a relative entry lands at its own relative path
    (``scripts/x.py`` -> ``{workdir}/scripts/x.py``) — the coder's
    ``run_in_env`` always asks for this. The default still flattens to the
    basename because workflow's Script node executor runs ``python
    <basename>`` after prefetching ``scripts/<name>.py``; a full key always
    lands at its basename (there is no project-relative path to preserve).
    A missing or failed prefetch never aborts the run, and is never silent
    either: returns the failures (``{path, reason, bytes?}``, `_copy_inputs`:
    each entry HEADed first, refused as ``too_large_for_disk`` when it will
    not fit, SlowDown and 5xx retried), in the order given.

    The Folio contract C7.6: an entry may also be an object
    ``{key, version_id, as}``: a Folio reference, fetched by version and
    written to ``as``, which must be a ``refs/`` path (`_refs_destination`).

    With ``cache_dir`` (Studio 2.2.28) each entry is kept in the project's
    verified cache, a version by its key and version, any other by its key
    while its ETag holds, and linked from it (`_copy_inputs`).
    """
    if not prefetch or not s3_bucket:
        return []
    s3 = _s3_client()
    items: List[_InputCopy] = []
    refused: List[Dict[str, Any]] = []
    for entry in prefetch:
        if isinstance(entry, dict):
            dst = _refs_destination(workdir, entry.get("as"))
            key = str(entry.get("key") or "")
            version_id = str(entry.get("version_id") or "")
            if dst is None or not key or not version_id or not key.startswith(("users/", "team/")):
                print(f"[HANDLER] WARNING: reference refused (as {entry.get('as')!r}); it could not be copied")
                refused.append(_input_error(str(entry.get("as")), "refused"))
                continue
            items.append(_InputCopy(str(entry.get("as")), key, version_id, dst, cache_dir=cache_dir,
                                    cache_rel=_ref_cache_rel(key, version_id) if cache_dir else None, kind="ref"))
            continue
        entry = str(entry)
        if entry.startswith(_FULL_KEY_PREFIXES):
            key = entry
            dst = os.path.join(workdir, os.path.basename(key))
        else:
            rel = entry.lstrip("/")
            key = f"{s3_prefix.rstrip('/')}/{rel}"
            safe_rel = _safe_project_relpath(rel) if preserve_paths else None
            dst = (
                os.path.join(workdir, *safe_rel.split("/"))
                if safe_rel else os.path.join(workdir, os.path.basename(key))
            )
        items.append(_InputCopy(entry, key, None, dst, cache_dir=cache_dir,
                                cache_rel=_prefetch_cache_rel(key) if cache_dir else None, kind="prefetch"))
    copied, errors = _copy_inputs(s3, s3_bucket, items, event, workdir=workdir)
    for label in copied:
        print(f"[HANDLER] prefetched {label}")
    return refused + errors


def _fetch_object(event: Dict, s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    """load_artifact's hydrate step: download ONE S3 object into this
    session's live workdir. Runs in THIS handler process - the trusted
    parent, same credential context `_prefetch_files` and
    `_load_connector_credentials` already use - never as code handed to
    the sandboxed `_exec_python`/`_exec_shell` child, which no longer
    carries this Lambda's own role credentials and so has nothing
    for a `boto3.client('s3')` call there to authenticate with.
    """
    s3_key = event.get("s3_key", "")
    # basename, not the raw caller-supplied value: `target_filename` is a
    # single path segment for "where in workdir does this land", not a path
    # itself - a `../`-laden value must not be able to write outside workdir.
    target_filename = os.path.basename(event.get("target_filename") or os.path.basename(s3_key))
    if not s3_key or not target_filename:
        return {"exit_code": 1, "stdout": "", "stderr": "fetch_object requires s3_key"}

    workdir = _get_session_workdir(s3_prefix)
    try:
        dst = os.path.join(workdir, target_filename)
        try:
            _s3_client().download_file(s3_bucket, s3_key, dst)
            size = os.path.getsize(dst)
        except Exception as exc:
            print(f"[HANDLER] fetch_object failed: {exc}")
            return {"exit_code": 1, "stdout": "", "stderr": f"fetch_object failed: {exc}"}

        print(f"[HANDLER] fetch_object: {s3_key} -> {dst} ({size} bytes)")
        # Same "upload back to this session's S3 prefix" step _exec_python takes
        # after running code, so a subsequent read_workspace_file / list_files
        # sees the fetched object without requiring a run_in_env first. The
        # directory is this call's own fresh one, so exactly the fetched object
        # goes up.
        if s3_bucket and s3_prefix:
            _upload_workdir_files(s3_bucket, s3_prefix, workdir)
        return {"exit_code": 0, "stdout": f"LOADED {size} {target_filename}", "stderr": ""}
    finally:
        _release_workdir(workdir)


def _get_session_workdir(s3_prefix: str) -> str:
    """A FRESH working directory for this one exec: ``mkdtemp``
    under /tmp, mode 0700, random name (`WORKDIR_PREFIX`), removed by
    `_release_workdir` when the exec ends. It used to be a stable per-prefix
    path derived from ``s3_prefix`` - predictable to every child the warm
    container served, and persistent between execs. ``s3_prefix`` stays in
    the signature for the callers; it names nothing any more."""
    return tempfile.mkdtemp(prefix=WORKDIR_PREFIX, dir=TMP_ROOT)


def _release_workdir(workdir: str) -> None:
    """Remove an exec's working directory once the up-mirror has read it.
    Only a directory `_get_session_workdir` made - directly under `TMP_ROOT`,
    named `WORKDIR_PREFIX`… - is ever removed; anything else is left alone.
    Hard links into the mirror cache are just unlinked (the cache keeps its
    inodes); ``ignore_errors``: a stray file is not worth failing the exec.

    Studio 2.2.28 (LAT-7): removing the links moves the linked cache files'
    ctime, so first each is checked against the stat it had right after it
    was linked (`_link_from_cache`). One still exactly so was not touched by
    this exec's program, and its stat after the removal is recorded as
    trusted; any other is left to be hashed at the next sync."""
    linked = _LINKED.pop(workdir, {})
    untouched = [(cache_dir, rel) for (cache_dir, rel), after in linked.items()
                 if _CACHE_TRUST.get(cache_dir, {}).get(rel) == after
                 and _stat_tuple(os.path.join(cache_dir, *rel.split("/"))) == after]
    if os.path.dirname(workdir) == TMP_ROOT and os.path.basename(workdir).startswith(WORKDIR_PREFIX):
        shutil.rmtree(workdir, ignore_errors=True)
    keep = set(untouched)
    for cache_dir, rel in linked:
        if (cache_dir, rel) in keep:
            _trust(cache_dir, rel, os.path.join(cache_dir, *rel.split("/")))
        else:
            _distrust(cache_dir, rel)


def _prepare_workdir(event: Dict, s3_bucket: str, s3_prefix: str, workdir: str) -> Dict[str, Any]:
    """Shared pre-run step for both exec actions, into this exec's FRESH
    ``workdir``: bring the project's mirror cache up to date and link the
    requested project dirs from it, reconstitute on a checkpoint resume,
    hydrate the prefetch list. Returns the sync report (empty when no
    ``sync_dirs`` were requested) - carrying ``cache_dir`` and ``dirs`` so
    `_finish_run` can record what the run uploads back into the cache."""
    started = time.monotonic()
    sync_dirs = _event_sync_dirs(event)
    sync_report: Dict[str, Any] = {}
    concurrency = _sync_concurrency(event)
    resume = bool(event.get("resume"))
    slim_resume = resume and isinstance(event.get("resume_paths"), list)
    # Studio 2.2.28: the project's verified cache also keeps its Folio
    # references, prefetch entries and resume state.
    cache_dir: Optional[str] = None
    if s3_bucket and s3_prefix and (sync_dirs or slim_resume or event.get("prefetch") or event.get(REFS_EVENT_KEY)):
        cache_dir = _workspace_cache(s3_prefix)
        _scrub_cache_dir(cache_dir, [REFS_CACHE_DIR, PREFETCH_CACHE_DIR])
    if sync_dirs and cache_dir:
        sync_report = _sync_dirs_down(
            s3_bucket, s3_prefix, cache_dir, sync_dirs,
            max_bytes=event.get("sync_max_bytes"),
            skip_over_bytes=event.get("sync_skip_over_bytes"),
            concurrency=concurrency,
        )
        placed = _materialize_workdir(cache_dir, sync_report.get("present") or [], workdir)
        sync_report["cache_dir"] = cache_dir
        sync_report["dirs"] = list(sync_dirs)
        print(f"[HANDLER] workdir: {workdir} (fresh), {placed} file(s) linked from the verified cache {cache_dir}")
    input_errors: List[Dict[str, Any]] = []
    # On a checkpoint resume, reconstitute the workdir from the durable S3
    # workspace BEFORE prefetch, so aa_env continues from the last committed
    # cursor. /tmp is never relied upon. A current worker names what the
    # previous continuation uploaded (``resume_paths``) and only aa_env's
    # state and those come down; an older one gets the whole prefix.
    if slim_resume and cache_dir:
        input_errors += _sync_resume_state(event, s3_bucket, s3_prefix, workdir, cache_dir,
                                           list(sync_report.get("present") or []))
    elif resume:
        _sync_prefix_down(s3_bucket, s3_prefix, workdir, concurrency=concurrency)
    input_errors += _prefetch_files(
        event.get("prefetch", []), s3_bucket, s3_prefix, workdir,
        preserve_paths=bool(event.get("preserve_paths")), event=event, cache_dir=cache_dir,
    ) or []
    # The Folio files the person referenced, read only, at refs/ (C7.6).
    input_errors += (_fetch_refs(event, s3_bucket, workdir, cache_dir=cache_dir) or {}).get("errors") or []
    if input_errors:
        # Never silent (2.2.27): `_finish_run` returns them as
        # ``input_errors`` with one stderr line each.
        sync_report["input_errors"] = input_errors
    _stats_add("duration_ms", int((time.monotonic() - started) * 1000))
    return sync_report


_EXEC_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")


def _exec_id(event: Optional[Dict[str, Any]]) -> str:
    """This exec's id for the files it names: the event's ``exec_id``, else
    its output stem (``kernel-<12 hex>``), else a fresh one."""
    event = event if isinstance(event, dict) else {}
    save = event.get("output_save") if isinstance(event.get("output_save"), dict) else {}
    for candidate in (event.get("exec_id"), save.get("stem")):
        if isinstance(candidate, str) and _EXEC_ID_RE.match(candidate):
            return candidate
    return f"exec-{uuid.uuid4().hex[:12]}"


def _cap_uploaded_list(out: Dict[str, Any], event: Optional[Dict[str, Any]], bucket: str, prefix: str) -> None:
    """Keep the response far under Lambda's 6 MB (SZ-07): past
    ``uploaded_list_max`` paths, ``uploaded`` and ``uploads`` list the first
    ones, the full list is written to ``{prefix}.coder/uploads/{exec_id}.json``
    (``uploaded_manifest``; a hidden folder, never mirrored or uploaded as a
    run's file) and ``uploaded_truncated`` and ``uploaded_count`` say so."""
    uploaded = out.get("uploaded") or []
    out["uploaded_count"] = len(uploaded)
    limit = min(_uploaded_list_max(event), len(uploaded))
    listed_bytes = 0
    for i, entry in enumerate((out.get("uploads") or [{"path": p} for p in uploaded])[:limit]):
        # a path twice (uploaded, uploads) and its quotes, size and ETag
        listed_bytes += 2 * len(json.dumps(entry.get("path", ""))) + 80
        if listed_bytes > _UPLOADED_LIST_MAX_BYTES:
            limit = i
            break
    if len(uploaded) <= limit:
        return
    uploads = out.get("uploads") or [{"path": p} for p in uploaded]
    key = f"{prefix.rstrip('/')}/{UPLOADED_MANIFEST_DIR}/{_exec_id(event)}.json"
    try:
        body = json.dumps({"uploaded_count": len(uploaded), "uploads": uploads},
                          separators=(",", ":")).encode("utf-8")
        _s3_client().put_object(Bucket=bucket, Key=key, Body=body,
                                **_s3_put_args(key, content_type="application/json"))
        out["uploaded_manifest"] = key
    except Exception as e:  # noqa: BLE001 - the capped list still comes back
        print(f"[HANDLER] WARNING: the full list of {len(uploaded)} uploaded files could not be saved: {e}")
        out["uploaded_manifest_error"] = f"{type(e).__name__}: {e}"[:_UPLOAD_ERROR_MAX_CHARS]
    out["uploaded"] = uploaded[:limit]
    if "uploads" in out:
        out["uploads"] = out["uploads"][:limit]
    out["uploaded_truncated"] = True
    print(f"[HANDLER] {len(uploaded)} files uploaded; the response lists {limit}, "
          f"the full list is {out.get('uploaded_manifest') or 'not saved'}")


def _finish_run(
    result: Any,
    s3_bucket: str,
    s3_prefix: str,
    workdir: str,
    snapshot: Dict[str, Tuple[int, int]],
    sync_report: Dict[str, Any],
    wall: Optional[Dict[str, Any]] = None,
    capture: Optional[_OutputCapture] = None,
    event: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Incremental upload of what the run produced + the response envelope.
    ``uploaded`` is the list `coder_worker.run_in_env` turns into one
    ``file_added`` event per file. ``upload_errors`` names every object S3
    refused (path and error, capped at `_UPLOAD_ERRORS_MAX`); when refusals
    left nothing uploaded, stderr ends with a line saying so, where the run
    and the coder read it. ``wall`` (`_wall_report`) adds the structured
    timeout fields and appends the readable line to stderr; the captured
    stdout/stderr are kept as-is. A failed run whose stderr shows a
    certificate-verification error from an issuer that is not trusted
    (`_certificate_failure`) gets `UNTRUSTED_CERTIFICATE_MESSAGE` (or, when
    the run's CAs could not be cross-certified, the root-needed line of
    `_untrusted_certificate_line`) on stderr and
    ``untrusted_certificate: true``; one whose certificate error is an
    added CA that expired gets a line naming that CA
    (`_expired_anchor_lines`).

    PRO-2358: a stream longer than its inline size (`_inline_max`) is saved
    in full first (`_save_outputs`) and returned as a preview naming the
    file, with ``{stream}_file``; one that could not be saved is returned as
    its start with a line saying so, and ``output_save_errors``. A program
    `capture` stopped at the output ceiling (or a full disk) is a failed run
    with ``error_code`` ``output_over_max`` (``output_disk_full``) and a
    sentence naming the ceiling and the files.

    2.2.27 (always, whatever else happened): ``uploads`` (``[{path, size,
    etag}]``) and ``uploaded_count``, capped at ``uploaded_list_max`` with the
    full list in ``uploaded_manifest`` (`_cap_uploaded_list`); the files the
    time could not keep in ``not_uploaded`` (at most 50),
    ``not_uploaded_count`` and ``not_uploaded_bytes`` with a stderr sentence
    (known never written); the ones still finishing at the deadline in
    ``upload_unsettled`` (at most 50) and ``upload_unsettled_count``, with a
    sentence;
    the inputs that could not be copied in ``input_errors`` with a stderr
    line each; and ``tmp_free_bytes``."""
    event = event or {}
    streams = _stream_outputs(result, capture)
    if capture is not None:
        # The certificate checks read the end of stderr; never the whole of it.
        if result.stderr is None:
            result.stderr = streams["stderr"].read(max(0, streams["stderr"].size - _OUTPUT_TAIL_FOR_CHECKS),
                                                   _OUTPUT_TAIL_FOR_CHECKS)
        if result.stdout is None:
            result.stdout = b""
    # The working copy goes up first (outputs/ and everything the program
    # wrote): a long output's save must never cost the run its files when
    # the invocation's time runs short. `_save_outputs` checks the time left.
    uploaded: List[str] = []
    refused: List[Tuple[str, str]] = []
    upload_report: Dict[str, Any] = {}
    if s3_bucket and s3_prefix:
        try:
            uploaded = _upload_workdir_files(
                s3_bucket, s3_prefix, workdir, snapshot=snapshot,
                cache_dir=sync_report.get("cache_dir"), cache_dirs=tuple(sync_report.get("dirs") or ()),
                failures=refused, report=upload_report, event=event,
            )
        except Exception as e:  # noqa: BLE001 - the run's envelope always comes back
            print(f"[HANDLER] WARNING: the upload failed: {traceback.format_exc()}")
            refused.append(("*", f"{type(e).__name__}: {e}"[:_UPLOAD_ERROR_MAX_CHARS]))
    files, save_errors = _save_outputs(event, s3_bucket, s3_prefix, streams)
    texts: Dict[str, str] = {}
    for name, stream in streams.items():
        if name in files:
            texts[name] = _saved_preview(stream, _inline_max(event, name), files[name]["path"])
        elif stream.size > _inline_max(event, name):
            texts[name] = _unsaved_preview(stream, _inline_max(event, name))
        else:
            texts[name] = _decode(stream.read(0, stream.size))
    stopped = capture is not None and capture.cut
    stderr_text = texts["stderr"]
    stop_sentence = _output_stop_sentence(capture, files) if stopped else ""
    if stopped and not wall:
        result.returncode = 1
    untrusted_line, expired_cas = _certificate_failure(result, probe_libpq=not wall and not stopped)
    if untrusted_line:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + untrusted_line
    if expired_cas:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + "\n".join(expired_cas)
    if wall:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + wall["error"]
    if stop_sentence:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + stop_sentence
    still_writing = capture is not None and capture.still_writing
    if still_writing:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + OUTPUT_STILL_WRITING_SENTENCE
    if refused and not uploaded:
        note = (f"[HANDLER] {len(refused)} file(s) could not be uploaded to S3 "
                f"({refused[0][0]}: {refused[0][1]}); the run's outputs are incomplete.")
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + note
    not_kept = upload_report.get("not_kept") or []
    if not_kept:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + _not_kept_sentence(
            len(not_kept), sum(size for _, size in not_kept))
    unsettled = upload_report.get("unsettled") or []
    if unsettled:
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + _unsettled_sentence(
            len(unsettled), sum(size for _, size in unsettled))
    input_errors = list(sync_report.get("input_errors") or [])
    if input_errors:
        lines = "\n".join(_input_error_line(err) for err in input_errors[:_INPUT_ERRORS_MAX])
        if len(input_errors) > _INPUT_ERRORS_MAX:
            lines += f"\n{len(input_errors) - _INPUT_ERRORS_MAX:,} more inputs could not be copied."
        stderr_text = (stderr_text.rstrip("\n") + "\n" if stderr_text.strip() else "") + lines
    out: Dict[str, Any] = {
        "exit_code": result.returncode,
        "stdout": texts["stdout"],
        "stderr": stderr_text,
        "uploaded": uploaded,
        "upload_errors": [{"path": p, "error": e} for p, e in refused[:_UPLOAD_ERRORS_MAX]],
    }
    if "uploads" in upload_report:
        out["uploads"] = upload_report["uploads"]
    _cap_uploaded_list(out, event, s3_bucket, s3_prefix)
    if not_kept:
        out["not_uploaded"] = [path for path, _ in not_kept[:_NOT_UPLOADED_MAX]]
        out["not_uploaded_count"] = len(not_kept)
        out["not_uploaded_bytes"] = sum(size for _, size in not_kept)
    if unsettled:
        out["upload_unsettled"] = [path for path, _ in unsettled[:_NOT_UPLOADED_MAX]]
        out["upload_unsettled_count"] = len(unsettled)
    if input_errors:
        out["input_errors"] = input_errors[:_INPUT_ERRORS_MAX]
    if _TMP_FREE_BYTES is not None:
        out["tmp_free_bytes"] = _TMP_FREE_BYTES
    for name, saved in files.items():
        out[f"{name}_file"] = saved
    if save_errors:
        out["output_save_errors"] = save_errors
    if capture is not None:
        out["output_max_bytes"] = capture.max_bytes
    if still_writing:
        out["output_still_writing"] = True
    if stopped:
        out["output_over_max"] = True
        if capture.dropped:
            out["output_bytes_not_kept"] = capture.dropped
        if not wall:
            out["error_type"] = "script_error"
            out["error_code"] = "output_disk_full" if capture.disk_full else "output_over_max"
            out["error"] = stop_sentence
    if untrusted_line:
        out[UNTRUSTED_CERTIFICATE_REASON] = True
    if wall:
        out.update(wall)
    if "downloaded" in sync_report:
        out["sync"] = {
            "downloaded": len(sync_report.get("downloaded") or []),
            "unchanged": sync_report.get("unchanged", 0),
            "skipped": list(sync_report.get("skipped") or [])[:50],
            "truncated": bool(sync_report.get("truncated")),
        }
    out["sync_stats"] = _sync_stats()
    return out


def _sha256_regular_file(path: str) -> Optional[str]:
    """SHA-256 of the regular file at ``path``, never through a link; None
    when it is not one."""
    try:
        fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
    except OSError:
        return None
    try:
        if not stat.S_ISREG(os.fstat(fd).st_mode):
            return None
        digest = hashlib.sha256()
        while True:
            chunk = os.read(fd, 1024 * 1024)
            if not chunk:
                return digest.hexdigest()
            digest.update(chunk)
    except OSError:
        return None
    finally:
        os.close(fd)


def _verify_inspected(event: Dict, workdir: str) -> Tuple[Optional[Dict[str, Any]], int]:
    """the coder's guard read the project files a
    program runs on the coder's own disk; this exec runs the copies just
    synced from the workspace. ``verify_files`` (``{rel: sha256}``) is what
    the guard read: a synced copy with other content is refused, so nothing
    runs that was not checked. A file not synced here is not run here either.
    Returns ``(refusal or None, files checked)``."""
    wanted = event.get("verify_files")
    if not isinstance(wanted, dict) or not wanted:
        return None, 0
    differs: List[str] = []
    checked = 0
    for rel, digest in sorted(wanted.items()):
        safe = _safe_project_relpath(str(rel))
        if safe is None or not (digest is None or isinstance(digest, str)):
            differs.append(str(rel))
            continue
        local = os.path.join(workdir, *safe.split("/"))
        if not os.path.lexists(local):
            continue
        if digest is None:
            # A file the program may run that Studio looked for on the
            # coder's disk and did not find: never run here unchecked.
            differs.append(safe)
            continue
        checked += 1
        if _sha256_regular_file(local) != digest:
            differs.append(safe)
    if differs:
        names = ", ".join(differs[:5])
        return {"exit_code": 1, "stdout": "", "uploaded": [], "verify_refused": differs[:50], "stderr": (
            f"Not run: {names} in the workspace is not the version Studio checked before running it (it changed "
            "after the check). Run it again to check and run the current version.")}, checked
    return None, checked


def _exec_python(event: Dict, s3_bucket: str, s3_prefix: str, budget: Any,
                 invocation_env: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
    """Run Python inside the mirrored project under ``budget`` (a `Budget`, or
    an int number of seconds for direct callers). ``invocation_env`` is THIS
    invocation's connector variables and deadline (`handler` passes them; a
    direct caller that passes none gets a child with no connector variables -
    never the process environment's).

    Two ways to say WHAT to run, in order of preference:

    * ``script_path`` — a project-relative file (``code/src/run.py``) that the
      coder wrote with ``Write``/``Edit`` (its PostToolUse sync hook uploaded
      it) and that ``sync_dirs`` just mirrored down. Runs with cwd = project
      root and ``code/`` on PYTHONPATH.

    The project root is this exec's own fresh directory: mirrored
    in, run, mirrored up, removed - nothing on disk carries over to the next
    exec; only the workspace does.
    * ``code`` + ``script_name`` — inline source (legacy callers and quick
      probes). Written to ``code/scratch/{script_name}`` inside the mirror so
      it is uploaded with everything else instead of littering the root.
    """
    code = event.get("code", "")
    script_name = os.path.basename(event.get("script_name") or "_lambda_exec.py")
    script_path = event.get("script_path")

    workdir = _get_session_workdir(s3_prefix)
    capture: Optional[_OutputCapture] = None
    try:
        sync_report = _prepare_workdir(event, s3_bucket, s3_prefix, workdir)
        refused, verified = _verify_inspected(event, workdir)
        if refused is not None:
            return refused

        # Snapshot BEFORE the inline script is written so it counts as "new" and
        # is uploaded (under code/scratch/) along with whatever the run produces.
        snapshot = _snapshot_workdir(workdir)

        if script_path:
            rel = _safe_project_relpath(script_path)
            if rel is None:
                return {"exit_code": 1, "stdout": "", "stderr": (
                    f"script_path must be a project-relative path (got {script_path!r}); "
                    "absolute paths and '..' are refused."
                ), "uploaded": []}
            tmp_script = os.path.join(workdir, *rel.split("/"))
            if not os.path.isfile(tmp_script):
                return {"exit_code": 1, "stdout": "", "stderr": (
                    f"script_path {rel!r} not found in the project mirror after syncing "
                    f"{_event_sync_dirs(event) or list(DEFAULT_SYNC_DIRS)}. Write the file "
                    "first (Write/Edit under code/ — the sync hook uploads it), then run it."
                ), "uploaded": []}
            print(f"[HANDLER] _exec_python: script_path={rel}, workdir={workdir}")
        else:
            script_dir = EPHEMERAL_SCRIPT_DIR if event.get("ephemeral") else INLINE_SCRIPT_DIR
            rel = f"{script_dir}/{script_name}"
            tmp_script = os.path.join(workdir, *rel.split("/"))
            if code:
                os.makedirs(os.path.dirname(tmp_script), exist_ok=True)
                with open(tmp_script, "w") as f:
                    f.write(code)
                print(f"[HANDLER] Script written to {tmp_script}")
            elif not os.path.exists(tmp_script):
                return {"exit_code": 1, "stdout": "", "stderr": "No code provided and script not found",
                        "uploaded": []}
            print(f"[HANDLER] _exec_python: script={rel}, code_len={len(code)}, workdir={workdir}")

        # The user script runs with cwd = project root. PYTHONPATH carries the
        # aa_env checkpoint helper (a private per-exec copy) and the
        # project's code/ root — see _child_pythonpath. No bytecode is written
        # anywhere the child can reach later. HOME is the invoking scope's own
        # - see _home_scope.
        helper_dir = _helper_dir()
        scope = _home_scope(event, os.path.basename(helper_dir))
        child_env = _child_env({**(invocation_env or {}), "PYTHONUNBUFFERED": "1", "PYTHONDONTWRITEBYTECODE": "1"},
                               scope=scope)
        child_env["PYTHONPATH"] = _child_pythonpath(workdir, child_env, helper_dir)
        _apply_trust_env(child_env, helper_dir)
        _ensure_overlay_intact()

        late = _inputs_took_budget(budget, sync_report)
        if late is not None:
            _release_exec_dirs(helper_dir, scope, child_env)
            return late
        capture = _OutputCapture(_output_max_bytes(event), drain_wait_s=_output_timing(event).drain_wait_s)
        try:
            result, wall = _run_captured([sys.executable, tmp_script], workdir, child_env, _coerce_budget(budget),
                                         capture)
        finally:
            _release_exec_dirs(helper_dir, scope, child_env)

        streams = _stream_outputs(result, capture)
        print(f"[HANDLER] _exec_python done: exit_code={result.returncode}, stdout_len={streams['stdout'].size}, "
              f"stderr_len={streams['stderr'].size}, output_over_max={capture.cut}")
        if wall:
            print(f"[HANDLER] wall: {wall['error']} (elapsed {wall['elapsed_seconds']}s, bound={wall['bound']})")
        if result.returncode != 0:
            print(f"[HANDLER] stderr: {_decode(streams['stderr'].read(0, 500))}")

        out = _finish_run(result, s3_bucket, s3_prefix, workdir, snapshot, sync_report, wall=wall,
                          capture=capture, event=event)
        if verified and isinstance(out, dict):
            out["verified_files"] = verified
        return out
    finally:
        if capture is not None:
            capture.close()             # after the output upload has read it
        _release_workdir(workdir)       # after the up-mirror has read it


def _exec_shell(event: Dict, s3_bucket: str, s3_prefix: str, budget: Any,
                invocation_env: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
    """Run a shell command with cwd = the mirrored project root (e.g. ``python
    -m pytest code/tests -q``). Same sync / snapshot / incremental-upload /
    wall envelope - and the same ``invocation_env`` contract - as
    `_exec_python`. The command runs under bash when the
    image has it (`_shell_argv`): dash, Debian's ``sh``, drops the hyphenated
    ``CONN_<connector id>_*`` variables, so under ``sh -c`` no connector
    credential reached the command or anything it ran."""
    command = event.get("command", "")
    if not command:
        return {"exit_code": 1, "stdout": "", "stderr": "No command provided"}

    workdir = _get_session_workdir(s3_prefix)
    capture: Optional[_OutputCapture] = None
    try:
        sync_report = _prepare_workdir(event, s3_bucket, s3_prefix, workdir)
        refused, verified = _verify_inspected(event, workdir)
        if refused is not None:
            return refused
        snapshot = _snapshot_workdir(workdir)

        helper_dir = _helper_dir()
        scope = _home_scope(event, os.path.basename(helper_dir))
        child_env = _child_env({**(invocation_env or {}), "PYTHONDONTWRITEBYTECODE": "1"}, scope=scope)
        child_env["PYTHONPATH"] = _child_pythonpath(workdir, child_env, helper_dir)
        _apply_trust_env(child_env, helper_dir)
        _ensure_overlay_intact()

        shell = _shell_argv(login_shell=bool(event.get("login_shell")))
        if shell[0] == "sh":
            dropped = [k for k in child_env if k.startswith("CONN_") and not k.isidentifier()]
            if dropped:
                print(f"[HANDLER] exec_shell: bash not found in this image; sh drops {len(dropped)} connector "
                      f"variable(s) whose names are not valid shell identifiers - the command and the programs it "
                      f"runs will not see them. Install bash in the image (Debian/Ubuntu bases carry it).")

        late = _inputs_took_budget(budget, sync_report)
        if late is not None:
            _release_exec_dirs(helper_dir, scope, child_env)
            return late
        capture = _OutputCapture(_output_max_bytes(event), drain_wait_s=_output_timing(event).drain_wait_s)
        try:
            result, wall = _run_captured([*shell, command], workdir, child_env, _coerce_budget(budget), capture)
        finally:
            _release_exec_dirs(helper_dir, scope, child_env)
        if wall:
            print(f"[HANDLER] wall: {wall['error']} (elapsed {wall['elapsed_seconds']}s, bound={wall['bound']})")

        out = _finish_run(result, s3_bucket, s3_prefix, workdir, snapshot, sync_report, wall=wall,
                          capture=capture, event=event)
        if verified and isinstance(out, dict):
            out["verified_files"] = verified
        return out
    finally:
        if capture is not None:
            capture.close()             # after the output upload has read it
        _release_workdir(workdir)       # after the up-mirror has read it


def _write_file(event: Dict, s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    rel_path = event.get("path", "")
    content = event.get("content", "")
    if not rel_path:
        return {"exit_code": 1, "stdout": "", "stderr": "No path provided"}
    if _safe_workspace_rel(str(rel_path).lstrip("/")) is None:
        return {"exit_code": 1, "stdout": "", "stderr": "path must be a file path inside the workspace"}
    if _is_git_metadata_rel(str(rel_path)):
        return {"exit_code": 1, "stdout": "", "stderr": "path names git metadata (.git, .gitmodules, "
                ".gitattributes, .gitconfig), which cannot be written to the workspace"}

    s3_key = f"{s3_prefix.rstrip('/')}/{rel_path.lstrip('/')}"
    try:
        _s3_client().put_object(
            Bucket=s3_bucket,
            Key=s3_key,
            Body=content.encode("utf-8"),
            **_s3_put_args(s3_key),
        )
        return {"exit_code": 0, "stdout": f"Written {len(content)} bytes to {rel_path}", "stderr": ""}
    except Exception as e:
        return {"exit_code": 1, "stdout": "", "stderr": f"Write failed: {e}"}


def _read_file(event: Dict, s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    rel_path = event.get("path", "")
    if not rel_path:
        return {"exit_code": 1, "stdout": "", "stderr": "No path provided"}
    if _safe_workspace_rel(str(rel_path).lstrip("/")) is None:
        return {"exit_code": 1, "stdout": "", "stderr": "path must be a file path inside the workspace"}

    s3_key = f"{s3_prefix.rstrip('/')}/{rel_path.lstrip('/')}"
    try:
        resp = _s3_client().get_object(Bucket=s3_bucket, Key=s3_key)
        content = resp["Body"].read().decode("utf-8", errors="replace")
        return {"exit_code": 0, "stdout": content, "stderr": ""}
    except Exception as e:
        if "NoSuchKey" in str(e):
            return {"exit_code": 1, "stdout": "", "stderr": f"File not found: {rel_path}"}
        return {"exit_code": 1, "stdout": "", "stderr": f"Read failed: {e}"}


def _list_files(event: Dict, s3_bucket: str, s3_prefix: str) -> Dict[str, Any]:
    try:
        s3 = _s3_client()
        paginator = s3.get_paginator("list_objects_v2")
        pages = paginator.paginate(Bucket=s3_bucket, Prefix=s3_prefix)

        lines = []
        for page in pages:
            for obj in page.get("Contents", []):
                key = obj["Key"]
                rel = key[len(s3_prefix):]
                if not rel or rel.endswith("/"):
                    continue
                size = obj.get("Size", 0)
                lines.append(f"f {size} {rel}")

        return {"exit_code": 0, "stdout": "\n".join(lines), "stderr": ""}
    except Exception as e:
        return {"exit_code": 1, "stdout": "", "stderr": f"List failed: {e}"}
