Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

84.3 KB
Raw Blame
#!/usr/bin/env python3
"""Snapshot and serve bounded sites or single documents from the owner workspace.

The control socket accepts one relative site directory or document file. Every
regular file is reopened without symlink traversal, bounded, hashed, and copied
create-only into a private state directory. A separate loopback HTTP listener
serves only those immutable snapshots with browser-hardening headers.
"""

from __future__ import annotations

import hashlib
import io
import zipfile
import errno
from contextlib import contextmanager
import fcntl
import importlib.util
import itertools
import difflib
import http.client
import http.server
import json
import mimetypes
import os
import pathlib
import pwd
import re
import shutil
import socket
import socketserver
import stat
import sys
import tempfile
import threading
import urllib.parse
from typing import Any

_peer_spec = importlib.util.spec_from_file_location("ods_unix_peer", pathlib.Path(__file__).with_name("unix_peer.py"))
_peer_module = importlib.util.module_from_spec(_peer_spec)
_peer_spec.loader.exec_module(_peer_module)
peer_ids = _peer_module.peer_ids

SCHEMA_VERSION = 1
KIND = "ods-pixel-workspace-preview"
SOCKET_PATH = pathlib.Path("/run/ods-pixel-preview/control.sock")
HTTP_SOCKET_PATH = pathlib.Path("/run/ods-pixel-preview/http.sock")
PROFILE_ID: str | None = None
PATH_COMPONENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
ASSET_COMPONENT = re.compile(r"(?!__ods_)(?!__pycache__$)[A-Za-z0-9_\[][A-Za-z0-9._\[\]-]{0,127}\Z")
SITE_ID = re.compile(r"site-[a-f0-9]{24}")
DOWNLOAD_ONLY_SUFFIXES = frozenset({".pdf", ".zip", ".rar"})
ALLOWED_SUFFIXES = frozenset(
    {
        ".html", ".htm", ".css", ".js", ".mjs", ".json", ".svg",
        ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico",
        ".woff", ".woff2", ".ttf", ".txt", ".map", ".csv", ".tsv",
        ".md", ".markdown",
    }
) | DOWNLOAD_ONLY_SUFFIXES
ARTIFACT_SUFFIXES = frozenset({'.md', '.markdown', '.txt', '.csv', '.tsv', '.json', '.pdf', '.zip', '.rar', '.docx', '.xlsx', '.pptx'})
ARTIFACT_KIND = 'ods-pixel-workspace-artifact'
ARTIFACT_BOUNDARY = 'Create-only single-file snapshot from the configured Pixel workspace; byte integrity only, no execution or document-quality claim.'
MAX_REQUEST_BYTES = 2048
MAX_RESPONSE_BYTES = 8192
MAX_FILES = 128
MAX_FILE_BYTES = 4 * 1024 * 1024
MAX_TOTAL_BYTES = 16 * 1024 * 1024
# Hidden entries (any directory or file whose name starts with '.') are never
# site content: version-control metadata (.git/, .gitignore, a worktree's .git
# file), tool and editor state (.harness/, .vscode/, .idea/, .pytest_cache/),
# OS files (.DS_Store) and private files (.env). _source_files prunes hidden
# directories before os.walk descends, so nothing inside them is listed,
# stat'ed or read, and skips hidden files by name. Neither counts toward the
# file limits, the digest or the manifest, and neither is ever copied or
# published: an index.html that references one gets a 404 rather than its
# bytes (the HTTP handler's ASSET_COMPONENT check refuses a leading '.' too).
#
# Bytecode caches appear whenever project code or its tests run in the
# directory. They are never site content either, so prune them by exact
# directory name. A file with this name is still validated normally.
GENERATED_CACHE_DIRECTORY_NAMES = frozenset({"__pycache__"})

SOURCE_ID = re.compile(r"source-[a-f0-9]{24}")
SOURCE_SUFFIXES = frozenset({'.html', '.css', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx',
                             '.vue', '.svelte', '.json', '.md', '.txt', '.py'})
SOURCE_EXCLUDED_DIRECTORIES = frozenset({'node_modules', 'dist', 'build', 'out', 'coverage',
                                         '__pycache__', 'venv', 'env', 'ods-builds'})
SOURCE_SECRET_NAME = re.compile(r'(?:^|[._-])(?:credentials?|secrets?|tokens?|passwords?)(?:[._-]|$)', re.I)
SOURCE_SECRET_CONTENT = re.compile(r'authorization\s*[:=]|bearer\s+[A-Za-z0-9._-]+|'
                                   r'(?:api[_-]?key|access[_-]?token|password|secret)\s*[:=]\s*[\"\']?\S|'
                                   r'BEGIN .*PRIVATE KEY', re.I)
SOURCE_FILE_BYTES = 256 * 1024
SOURCE_TOTAL_BYTES = 1024 * 1024

BOUNDARY = (
    "Create-only static-site snapshot from the configured Pixel workspace to a "
    "dedicated loopback preview origin; no arbitrary host path, network "
    "destination, server process, overwrite, or execution authority."
)
CSP = (
    "default-src 'self' data: blob:; connect-src 'self'; img-src 'self' data: blob:; "
    "media-src 'self'; font-src 'self'; script-src 'self' 'unsafe-inline'; "
    "style-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'; "
    "form-action 'none'; frame-ancestors http://localhost:* http://127.0.0.1:*"
)


class PreviewError(Exception):
    """A generic fail-closed preview error."""


STARTUP_STAGES = frozenset(('configuration', 'owner', 'workspace-root', 'previews-root', 'control-socket-cleanup',
                            'http-socket-cleanup', 'http-listener', 'unix-http-listener', 'control-listener'))
STARTUP_REASONS = {
    'unsafe preview root': 'unsafe-root',
    'unsafe existing preview socket': 'unsafe-control-socket',
    'unsafe existing preview HTTP socket': 'unsafe-http-socket',
    'preview must run as its configured owner': 'owner-mismatch',
    'invalid preview service configuration': 'invalid-configuration',
    'container preview requires numeric non-root owner': 'invalid-owner',
}


class PreviewStartupError(PreviewError):
    def __init__(self, stage, error):
        super().__init__('preview startup failed')
        self.stage = stage if stage in STARTUP_STAGES else 'unknown'
        if isinstance(error, OSError):
            self.reason = errno.errorcode.get(error.errno, 'OS_ERROR')
        elif isinstance(error, PreviewError):
            self.reason = STARTUP_REASONS.get(str(error), 'validation-failed')
        else:
            self.reason = 'invalid-configuration'


@contextmanager
def _startup_phase(stage):
    try:
        yield
    except (PreviewError, OSError, ValueError, KeyError) as error:
        # OS exception text can include paths, and arbitrary validation errors
        # can contain configuration values. Export only static stage/categories.
        raise PreviewStartupError(stage, error) from None


class JsonArtifactError(PreviewError):
    def __init__(self, relative: str, line: int | None, column: int | None):
        super().__init__("invalid preview JSON artifact")
        self.diagnostic = {"path": relative, "line": line, "column": column}


def configure_portal(profile_id: str) -> None:
    """Bind this broker process to one supervisor-selected Hermes profile.

    Called once before opening listeners. The legacy standalone entry point does
    not call this, so existing Pixel wire contracts and installs stay unchanged.
    The same audited snapshot/HTTP engine is packaged for both entry points.
    """
    global KIND, BOUNDARY, SOCKET_PATH, HTTP_SOCKET_PATH, PROFILE_ID
    if PROFILE_ID is not None or not isinstance(profile_id, str) or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}", profile_id) is None:
        raise PreviewError("invalid or already bound preview profile")
    PROFILE_ID = profile_id
    KIND = "ods-portal-workspace-preview"
    BOUNDARY = BOUNDARY.replace("Pixel workspace", "Portal workspace")
    SOCKET_PATH = pathlib.Path("/run/ods-portal/preview/control.sock")
    HTTP_SOCKET_PATH = pathlib.Path("/run/ods-portal/preview/http.sock")


def _profile_fields() -> dict[str, str]:
    return {} if PROFILE_ID is None else {"profileId": PROFILE_ID}


PREVIEW_FAILURE_CODES = {
    "archive exceeds limit": "archive_limit",
    "archive source changed": "archive_changed",
    "archive is empty": "archive_empty",
    "archive contains secret content": "archive_private_source",
    "archive contains secret-named path": "archive_private_source",
    "archive contains secret-named file": "archive_private_source",
    "unsafe archive path": "archive_unsafe_source",
    "unsafe archive directory": "archive_unsafe_source",
    "unsafe archive file": "archive_unsafe_source",
    "archive has duplicate paths": "archive_unsafe_source",
    "source review exceeds limit": "source_capture_limit",
    "source review store quota exceeded": "source_store_full",
    "source review changed": "source_capture_changed",
    "source review has no eligible files": "no_eligible_source",
    "writable preview file": "writable_file",
    "invalid preview JSON artifact": "invalid_json_artifact",
    "unsupported preview file type": "unsupported_file_type",
    "preview requires index.html": "missing_entry",
    "preview contains too many files": "too_many_files",
    "preview is too large": "snapshot_too_large",
    "unsafe preview file": "unsafe_file",
    "unsafe preview directory": "unsafe_directory",
}


def _parts(value: object) -> tuple[str, ...]:
    if (
        not isinstance(value, str)
        or not 1 <= len(value) <= 512
        or value.startswith("/")
        or "\\" in value
        or any(ord(character) < 32 or ord(character) == 127 for character in value)
    ):
        raise PreviewError("invalid preview directory")
    parts = tuple(value.split("/"))
    if (
        not 1 <= len(parts) <= 12
        or any(
            part in {"", ".", ".."} or PATH_COMPONENT.fullmatch(part) is None
            for part in parts
        )
    ):
        raise PreviewError("invalid preview directory")
    return parts


def _json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise PreviewError("duplicate preview JSON member")
        result[key] = value
    return result


def parse_request(payload: bytes) -> dict[str, Any]:
    try:
        value = json.loads(payload.decode("utf-8"), object_pairs_hook=_json_object)
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise PreviewError("invalid preview request") from exc
    if isinstance(value, dict) and value.get('action') == 'publish-artifact':
        fields = {'schemaVersion', 'action', 'relativePath'}
        if 'sourcePath' in value:
            fields.add('sourcePath')
        if (set(value) != fields or PROFILE_ID is not None
                or type(value.get('schemaVersion')) is not int or value['schemaVersion'] != 1):
            raise PreviewError('invalid artifact request')
        parts = _parts(value.get('relativePath'))
        if pathlib.PurePosixPath(parts[-1]).suffix.lower() not in ARTIFACT_SUFFIXES:
            raise PreviewError('unsupported preview file type')
        if 'sourcePath' in value:
            _parts(value['sourcePath'])
            if pathlib.PurePosixPath(parts[-1]).suffix.lower() != '.zip':
                raise PreviewError('archive output must be a ZIP')
        return value
    if (
        not isinstance(value, dict)
        or not isinstance(value.get("action"), str)
        or set(value) != {"schemaVersion", "action", "relativeDirectory", *_profile_fields(),
                           *({"siteId", "sha256"} if value.get("action") == "verify-current" else set()),
                           *({'sourceDirectory'} if value.get('action') == 'publish' and 'sourceDirectory' in value else set())}
        or type(value.get("schemaVersion")) is not int or value.get("schemaVersion") != SCHEMA_VERSION
        or value.get("action") not in {"publish", "verify-current"}
        or (PROFILE_ID is not None and value.get("profileId") != PROFILE_ID)
    ):
        raise PreviewError("invalid preview request")
    _parts(value.get("relativeDirectory"))
    if 'sourceDirectory' in value:
        _parts(value['sourceDirectory'])
        if PROFILE_ID is not None or not (value['relativeDirectory'] == value['sourceDirectory']
                or value['relativeDirectory'].startswith(value['sourceDirectory'] + '/')):
            raise PreviewError('invalid preview request')
    if value["action"] == "verify-current" and (
        not isinstance(value.get("siteId"), str) or SITE_ID.fullmatch(value["siteId"]) is None
        or not isinstance(value.get("sha256"), str) or re.fullmatch(r"[a-f0-9]{64}", value["sha256"]) is None
        or value["siteId"] != "site-" + value["sha256"][:24]
    ):
        raise PreviewError("invalid preview request")
    return value


def _safe_root(path: pathlib.Path, owner_uid: int) -> None:
    info = path.lstat()
    if (
        not stat.S_ISDIR(info.st_mode)
        or stat.S_ISLNK(info.st_mode)
        or info.st_mode & 0o022
        or path.resolve(strict=True) != path
    ):
        raise PreviewError("unsafe preview root")
    if info.st_uid != owner_uid:
        # Colima's VirtioFS can report a bind mount point as root-owned while
        # the directory reached through it retains its real host-owner UID.
        # Only admit that exact mount-point discrepancy, never a symlink,
        # different inode, or permissive directory.
        actual = os.stat(os.fspath(path) + "/.")
        if (info.st_uid != 0 or actual.st_uid != owner_uid
                or (actual.st_dev, actual.st_ino) != (info.st_dev, info.st_ino)
                or not stat.S_ISDIR(actual.st_mode) or actual.st_mode & 0o022):
            raise PreviewError("unsafe preview root")


def _directory_walk_failed(error: OSError) -> None:
    # os.walk otherwise silently skips unreadable/disappeared directories and
    # can publish an index whose referenced assets were never captured.
    raise PreviewError("unsafe preview directory") from error


def _source_files(
    workspace: pathlib.Path, relative_directory: str, owner_uid: int
) -> list[tuple[str, pathlib.Path, os.stat_result]]:
    _safe_root(workspace, owner_uid)
    current = workspace
    for component in _parts(relative_directory):
        current = current / component
        info = current.lstat()
        if (
            not stat.S_ISDIR(info.st_mode)
            or stat.S_ISLNK(info.st_mode)
            or info.st_uid != owner_uid
            or info.st_mode & 0o022
        ):
            raise PreviewError("unsafe preview directory")
    if current.resolve(strict=True) != current:
        raise PreviewError("unsafe preview directory")

    files: list[tuple[str, pathlib.Path, os.stat_result]] = []
    for root, directories, names in os.walk(current, topdown=True, followlinks=False, onerror=_directory_walk_failed):
        root_path = pathlib.Path(root)
        root_info = root_path.lstat()
        if (
            not stat.S_ISDIR(root_info.st_mode)
            or stat.S_ISLNK(root_info.st_mode)
            or root_info.st_uid != owner_uid
            or root_info.st_mode & 0o022
        ):
            raise PreviewError("unsafe preview directory")
        # Exclude hidden and cache directories by their own name before
        # descending; every other directory, symlink or not, is validated.
        pruned = [d for d in directories
                  if not d.startswith(".") and d not in GENERATED_CACHE_DIRECTORY_NAMES]
        for directory in pruned:
            info = (root_path / directory).lstat()
            if (
                not stat.S_ISDIR(info.st_mode)
                or stat.S_ISLNK(info.st_mode)
                or info.st_uid != owner_uid
                or info.st_mode & 0o022
                or ASSET_COMPONENT.fullmatch(directory) is None
            ):
                raise PreviewError("unsafe preview directory")
        directories[:] = pruned
        for name in names:
            # Hidden files (.DS_Store, .env, a worktree's .git pointer file)
            # are skipped by name before any lstat, size or count check.
            if name.startswith("."):
                continue
            source = root_path / name
            info = source.lstat()
            relative = source.relative_to(current).as_posix()
            if (
                not stat.S_ISREG(info.st_mode)
                or name in GENERATED_CACHE_DIRECTORY_NAMES
                or stat.S_ISLNK(info.st_mode)
                or info.st_nlink != 1
                or info.st_uid != owner_uid
                or not (1 if relative == "index.html" else 0) <= info.st_size <= MAX_FILE_BYTES
                or any(ASSET_COMPONENT.fullmatch(part) is None for part in relative.split("/"))
            ):
                raise PreviewError("unsafe preview file")
            if info.st_mode & 0o022:
                raise PreviewError("writable preview file")
            if pathlib.PurePosixPath(relative).suffix.lower() not in ALLOWED_SUFFIXES:
                raise PreviewError("unsupported preview file type")
            files.append((relative, source, info))
            if len(files) > MAX_FILES:
                raise PreviewError("preview contains too many files")
    files.sort(key=lambda item: item[0])
    if not files or not any(relative == "index.html" for relative, _, _ in files):
        raise PreviewError("preview requires index.html")
    if sum(info.st_size for _, _, info in files) > MAX_TOTAL_BYTES:
        raise PreviewError("preview is too large")
    return files


def _read_stable(source: pathlib.Path, expected: os.stat_result) -> bytes:
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
    descriptor = os.open(source, flags)
    try:
        before = os.fstat(descriptor)
        if (
            not stat.S_ISREG(before.st_mode)
            or before.st_nlink != 1
            or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
            != (expected.st_dev, expected.st_ino, expected.st_size, expected.st_mtime_ns)
        ):
            raise PreviewError("preview source changed")
        data = bytearray()
        while len(data) <= MAX_FILE_BYTES:
            chunk = os.read(descriptor, min(65536, MAX_FILE_BYTES + 1 - len(data)))
            if not chunk:
                break
            data.extend(chunk)
        after = os.fstat(descriptor)
        if (
            len(data) != expected.st_size
            or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)
            != (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)
        ):
            raise PreviewError("preview source changed")
        return bytes(data)
    finally:
        os.close(descriptor)


def _validate_json_artifact(data: bytes, relative: str) -> None:
    """Validate captured JSON bytes without rewriting the owner's artifact."""
    def invalid_constant(_value):
        raise ValueError("non-JSON numeric constant")

    try:
        json.loads(data.decode("utf-8"), object_pairs_hook=_json_object,
                   parse_constant=invalid_constant)
    except json.JSONDecodeError as error:
        raise JsonArtifactError(relative, error.lineno, error.colno) from error
    except UnicodeDecodeError as error:
        prefix = data[:error.start].decode("utf-8")
        raise JsonArtifactError(relative, prefix.count("\n") + 1,
                                len(prefix.rsplit("\n", 1)[-1]) + 1) from error
    except (ValueError, RecursionError, PreviewError) as error:
        # The decoder does not supply offsets for duplicate keys, nonstandard
        # constants or excessive nesting. Do not invent a source location.
        raise JsonArtifactError(relative, None, None) from error


def _source_directory_fd(path, owner_uid):
    fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    info = os.fstat(fd)
    if info.st_uid != owner_uid or info.st_mode & 0o022:
        os.close(fd)
        raise PreviewError('unsafe source review directory')
    return fd


def _capture_review_source(workspace, relative_directory, owner_uid, output_directory=None):
    """Bounded UTF-8 source, distinct from runnable output. Never follow links."""
    _safe_root(workspace, owner_uid)
    root = _source_directory_fd(workspace, owner_uid)
    files, identities, omitted = [], [], {'directories': 0, 'files': 0, 'sensitiveFiles': 0}
    total = 0
    visited = 0
    output = output_directory[len(relative_directory)+1:] if output_directory and output_directory.startswith(relative_directory + '/') else None
    try:
        for component in _parts(relative_directory):
            child = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root)
            os.close(root)
            root = child
            info = os.fstat(root)
            if info.st_uid != owner_uid or info.st_mode & 0o022:
                raise PreviewError('unsafe source review directory')
        def scan(directory, prefix='', capture=True):
            nonlocal total, visited
            observed = []
            with os.scandir(directory) as entries:
                names = sorted(entry.name for entry in itertools.islice(entries, 1025))
            if len(names) > 1024:
                raise PreviewError('source review exceeds limit')
            for name in names:
                visited += 1
                if visited > 4096:
                    raise PreviewError('source review exceeds limit')
                if name.startswith('.'):
                    if capture:
                        omitted['files'] += 1
                    continue
                if ASSET_COMPONENT.fullmatch(name) is None:
                    raise PreviewError('unsafe source review path')
                info = os.stat(name, dir_fd=directory, follow_symlinks=False)
                path = prefix + name
                if stat.S_ISDIR(info.st_mode) and (path == output or name.lower() in SOURCE_EXCLUDED_DIRECTORIES or SOURCE_SECRET_NAME.search(name)):
                    if capture:
                        omitted['directories'] += 1
                    continue
                if (info.st_uid != owner_uid or info.st_mode & 0o022 or stat.S_ISLNK(info.st_mode)):
                    raise PreviewError('unsafe source review path')
                identity = (path, info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_mode)
                observed.append(identity)
                if len(observed) > 1024 or path.count('/') > 12:
                    raise PreviewError('source review exceeds limit')
                if stat.S_ISDIR(info.st_mode):
                    child = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory)
                    try:
                        current = os.fstat(child)
                        if (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino):
                            raise PreviewError('source review changed')
                        observed.extend(scan(child, path + '/', capture))
                    finally:
                        os.close(child)
                    if len(observed) > 1024:
                        raise PreviewError('source review exceeds limit')
                    continue
                if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
                    raise PreviewError('unsafe source review file')
                if SOURCE_SECRET_NAME.search(name) or pathlib.PurePosixPath(name).suffix.lower() not in SOURCE_SUFFIXES:
                    if capture:
                        omitted['files'] += 1
                    continue
                if info.st_size > SOURCE_FILE_BYTES:
                    raise PreviewError('source review exceeds limit')
                if not capture:
                    continue
                descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
                try:
                    before = os.fstat(descriptor)
                    if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_mode, before.st_nlink) != (
                            info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_mode, 1):
                        raise PreviewError('source review changed')
                    with os.fdopen(os.dup(descriptor), 'rb') as stream:
                        data = stream.read(SOURCE_FILE_BYTES + 1)
                    after = os.fstat(descriptor)
                    if (after.st_size, after.st_mtime_ns, after.st_mode, after.st_nlink) != (
                            before.st_size, before.st_mtime_ns, before.st_mode, 1) or len(data) != info.st_size:
                        raise PreviewError('source review changed')
                finally:
                    os.close(descriptor)
                try:
                    text = data.decode('utf-8')
                except UnicodeDecodeError:
                    omitted['files'] += 1
                    continue
                if '\x00' in text or SOURCE_SECRET_CONTENT.search(text):
                    omitted['sensitiveFiles'] += 1
                    continue
                total += len(data)
                if total > SOURCE_TOTAL_BYTES or len(files) >= MAX_FILES:
                    raise PreviewError('source review exceeds limit')
                files.append({'path': path, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'text': text})
            return observed
        identities = scan(root)
        visited = 0
        if identities != scan(root, capture=False):
            raise PreviewError('source review changed')
    finally:
        os.close(root)
    if not files:
        raise PreviewError('source review has no eligible files')
    return {'relativeDirectory': relative_directory, 'files': files, 'bytes': total, 'omitted': omitted}


def _source_review_store(previews, owner_uid):
    _safe_root(previews, owner_uid)
    root = previews / '.review-sources'
    root.mkdir(mode=0o700, exist_ok=True)
    fd = _source_directory_fd(root, owner_uid)
    if stat.S_IMODE(os.fstat(fd).st_mode) != 0o700:
        os.close(fd)
        raise PreviewError('unsafe source review store')
    return root, fd


SOURCE_STORE_FILES = 128
SOURCE_STORE_BYTES = 64 * 1024 * 1024


def _source_store_usage(directory, owner_uid):
    count = total = 0
    with os.scandir(directory) as entries:
        for entry in entries:
            if entry.name == ".quota.lock":
                continue
            if not re.fullmatch(r"(?:site-[a-f0-9]{24}-source-[a-f0-9]{24}\.json|\.capture-[a-f0-9]{32})", entry.name):
                raise PreviewError("unsafe source review store")
            info = entry.stat(follow_symlinks=False)
            if (not stat.S_ISREG(info.st_mode) or info.st_uid != owner_uid or info.st_nlink != 1
                    or stat.S_IMODE(info.st_mode) != 0o400):
                raise PreviewError("unsafe source review store")
            count += 1
            total += info.st_size
            if count > SOURCE_STORE_FILES or total > SOURCE_STORE_BYTES:
                raise PreviewError("source review store quota exceeded")
    return count, total


def _publish_review_source(previews, site_id, captured, owner_uid, before_commit=None):
    document = {'schemaVersion': 1, 'scope': 'captured-project-source', 'siteId': site_id, **captured}
    body = json.dumps(document, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
    if len(body) > MAX_FILE_BYTES:
        raise PreviewError('source review exceeds limit')
    digest = hashlib.sha256(body).hexdigest()
    identity = 'source-' + digest[:24]
    _root, directory = _source_review_store(previews, owner_uid)
    temporary = '.capture-' + os.urandom(16).hex()
    name = site_id + '-' + identity + '.json'
    lock = None
    try:
        lock = os.open('.quota.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600, dir_fd=directory)
        lock_info = os.fstat(lock)
        if (not stat.S_ISREG(lock_info.st_mode) or lock_info.st_uid != owner_uid
                or lock_info.st_nlink != 1 or stat.S_IMODE(lock_info.st_mode) != 0o600):
            raise PreviewError('unsafe source review store')
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            existing = os.stat(name, dir_fd=directory, follow_symlinks=False)
        except FileNotFoundError:
            existing = None
        if existing is None:
            count, size = _source_store_usage(directory, owner_uid)
            if count >= SOURCE_STORE_FILES or size + len(body) > SOURCE_STORE_BYTES:
                raise PreviewError('source review store quota exceeded')
        else:
            if _review_source_bytes(previews, site_id, identity, owner_uid) != body:
                raise PreviewError('source review verification failed')
            if before_commit is not None:
                before_commit()
            return {'schemaVersion': 1, 'sourceId': identity, 'sha256': digest,
                    'relativeDirectory': captured['relativeDirectory'], 'files': len(captured['files']),
                    'bytes': captured['bytes'], 'omitted': captured['omitted']}
        descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o400, dir_fd=directory)
        with os.fdopen(descriptor, 'wb') as target:
            target.write(body)
            target.flush()
            os.fsync(target.fileno())
        # The source quota is reserved under this lock before output mutation.
        # A failed output publication leaves no new source capture.
        if before_commit is not None:
            before_commit()
        try:
            os.link(temporary, name, src_dir_fd=directory, dst_dir_fd=directory, follow_symlinks=False)
        except FileExistsError:
            pass
        os.unlink(temporary, dir_fd=directory)
        os.fsync(directory)
    finally:
        try:
            os.unlink(temporary, dir_fd=directory)
        except FileNotFoundError:
            pass
        if lock is not None:
            os.close(lock)
        os.close(directory)
    if _review_source_bytes(previews, site_id, identity, owner_uid) != body:
        raise PreviewError('source review verification failed')
    return {'schemaVersion': 1, 'sourceId': identity, 'sha256': digest,
            'relativeDirectory': captured['relativeDirectory'], 'files': len(captured['files']),
            'bytes': captured['bytes'], 'omitted': captured['omitted']}


def _review_source_bytes(previews, site_id, source_id, owner_uid):
    if not SITE_ID.fullmatch(site_id) or not SOURCE_ID.fullmatch(source_id):
        raise PreviewError('invalid source review identity')
    root = previews / '.review-sources'
    directory = _source_directory_fd(root, owner_uid)
    try:
        descriptor = os.open(site_id + '-' + source_id + '.json', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
        with os.fdopen(descriptor, 'rb') as stream:
            info = os.fstat(stream.fileno())
            if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != owner_uid
                    or stat.S_IMODE(info.st_mode) != 0o400 or info.st_size > MAX_FILE_BYTES):
                raise PreviewError('unsafe source review snapshot')
            body = stream.read(MAX_FILE_BYTES + 1)
        if len(body) != info.st_size or 'source-' + hashlib.sha256(body).hexdigest()[:24] != source_id:
            raise PreviewError('source review verification failed')
        document = json.loads(body)
        if document.get('siteId') != site_id or document.get('scope') != 'captured-project-source':
            raise PreviewError('source review verification failed')
        return body
    finally:
        os.close(directory)


def publish_snapshot(
    workspace: pathlib.Path,
    previews: pathlib.Path,
    relative_directory: str,
    owner_uid: int,
    source_directory: str | None = None,
) -> dict[str, Any]:
    _safe_root(previews, owner_uid)
    if source_directory is not None and not (relative_directory == source_directory or relative_directory.startswith(source_directory + '/')):
        raise PreviewError('invalid preview request')
    captured_source = _capture_review_source(workspace, source_directory, owner_uid, relative_directory) if source_directory is not None else None
    sources = _source_files(workspace, relative_directory, owner_uid)
    captured: list[tuple[str, bytes]] = []
    digest = hashlib.sha256()
    total = 0
    for relative, source, info in sources:
        data = _read_stable(source, info)
        if pathlib.PurePosixPath(relative).suffix.lower() == ".json":
            _validate_json_artifact(data, relative)
        total += len(data)
        if total > MAX_TOTAL_BYTES:
            raise PreviewError("preview is too large")
        encoded_name = relative.encode("utf-8")
        digest.update(len(encoded_name).to_bytes(4, "big"))
        digest.update(encoded_name)
        digest.update(len(data).to_bytes(8, "big"))
        digest.update(data)
        captured.append((relative, data))
    full_digest = digest.hexdigest()
    site_id = f"site-{full_digest[:24]}"
    if captured_source is None:
        return _publish_captured_snapshot(previews, site_id, captured, full_digest, total, relative_directory, owner_uid)
    result = {}
    def publish_output():
        result.update(_publish_captured_snapshot(previews, site_id, captured, full_digest, total, relative_directory, owner_uid))
    source_receipt = _publish_review_source(previews, site_id, captured_source, owner_uid, before_commit=publish_output)
    return {**result, 'source': source_receipt}


def _publish_captured_snapshot(previews, site_id, captured, full_digest, total, relative_directory, owner_uid):
    destination = previews / site_id
    overwritten = False
    if not destination.exists():
        temporary = pathlib.Path(tempfile.mkdtemp(prefix=".publish-", dir=previews))
        try:
            os.chmod(temporary, 0o700)
            for relative, data in captured:
                target = temporary / relative
                parent = temporary
                for component in pathlib.PurePosixPath(relative).parts[:-1]:
                    parent = parent / component
                    parent.mkdir(mode=0o700, exist_ok=True)
                descriptor = os.open(
                    target,
                    os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
                    0o400,
                )
                try:
                    view = memoryview(data)
                    while view:
                        written = os.write(descriptor, view)
                        if written <= 0:
                            raise PreviewError("incomplete preview write")
                        view = view[written:]
                    os.fsync(descriptor)
                finally:
                    os.close(descriptor)
            os.rename(temporary, destination)
        except Exception:
            shutil.rmtree(temporary, ignore_errors=True)
            raise
    destination_info = destination.lstat()
    if (
        not stat.S_ISDIR(destination_info.st_mode)
        or stat.S_ISLNK(destination_info.st_mode)
        or destination_info.st_uid != owner_uid
        or stat.S_IMODE(destination_info.st_mode) != 0o700
    ):
        raise PreviewError("unsafe preview snapshot")
    expected = {relative: data for relative, data in captured}
    observed: set[str] = set()
    for root, directories, names in os.walk(destination, topdown=True, followlinks=False, onerror=_directory_walk_failed):
        root_path = pathlib.Path(root)
        root_info = root_path.lstat()
        if (
            not stat.S_ISDIR(root_info.st_mode)
            or stat.S_ISLNK(root_info.st_mode)
            or root_info.st_uid != owner_uid
            or stat.S_IMODE(root_info.st_mode) != 0o700
        ):
            raise PreviewError("unsafe preview snapshot")
        for directory in directories:
            directory_info = (root_path / directory).lstat()
            if (
                not stat.S_ISDIR(directory_info.st_mode)
                or stat.S_ISLNK(directory_info.st_mode)
                or directory_info.st_uid != owner_uid
                or stat.S_IMODE(directory_info.st_mode) != 0o700
            ):
                raise PreviewError("unsafe preview snapshot")
        for name in names:
            target = root_path / name
            relative = target.relative_to(destination).as_posix()
            target_info = target.lstat()
            if (
                relative not in expected
                or not stat.S_ISREG(target_info.st_mode)
                or stat.S_ISLNK(target_info.st_mode)
                or target_info.st_nlink != 1
                or target_info.st_uid != owner_uid
                or stat.S_IMODE(target_info.st_mode) != 0o400
                or _read_stable(target, target_info) != expected[relative]
            ):
                raise PreviewError("preview snapshot verification failed")
            observed.add(relative)
    if observed != set(expected):
        raise PreviewError("preview snapshot verification failed")
    entry_data = expected["index.html"]
    entry_sha256 = hashlib.sha256(entry_data).hexdigest()
    return {
        "schemaVersion": SCHEMA_VERSION,
        "kind": KIND,
        "status": "succeeded",
        **_profile_fields(),
        "relativeDirectory": relative_directory,
        "siteId": site_id,
        "files": len(captured),
        **(_published_path_feedback(observed, [relative for relative, data in captured if not data])
           if PROFILE_ID is None else {}),
        "bytes": total,
        "sha256": full_digest,
        "entryFile": "index.html",
        "entrySha256": entry_sha256,
        "executable": False,
        "overwritten": overwritten,
        "boundary": BOUNDARY,
    }


ARCHIVE_CACHE_DIRS = frozenset({'__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.git', 'node_modules'})
ARCHIVE_SKIP_SUFFIXES = frozenset({'.pyc', '.pyo'})
ARCHIVE_SKIP_NAMES = frozenset({'.DS_Store'})
ARCHIVE_ALLOWED_DOTFILES = frozenset({'.gitignore', '.gitattributes', '.editorconfig'})
ARCHIVE_MAX_FILES = 128
ARCHIVE_MAX_FILE_BYTES = 4 * 1024 * 1024
ARCHIVE_MAX_TOTAL_BYTES = 16 * 1024 * 1024
ARCHIVE_MAX_DEPTH = 12
ARCHIVE_MAX_PATH = 512
ARCHIVE_MAX_VISITED = 4096
ARCHIVE_MAX_OUTPUT = 4 * 1024 * 1024
ARCHIVE_BOUNDARY = 'Create-only deterministic ZIP snapshot from the configured Pixel workspace; byte integrity only, no execution or document-quality claim.'


def _archive_identity(info):
    return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns,
            info.st_mode, info.st_uid, info.st_nlink)


def _archive_open_dir(parent_fd, name, owner_uid):
    fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent_fd)
    try:
        info = os.fstat(fd)
        if (not stat.S_ISDIR(info.st_mode) or info.st_uid != owner_uid
                or info.st_mode & 0o022):
            raise PreviewError('unsafe archive directory')
        return fd, info
    except Exception:
        os.close(fd)
        raise


def _archive_read_file(parent_fd, name, owner_uid):
    fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, dir_fd=parent_fd)
    try:
        before = os.fstat(fd)
        if (not stat.S_ISREG(before.st_mode) or before.st_uid != owner_uid
                or before.st_nlink != 1 or before.st_mode & 0o022
                or not 0 <= before.st_size <= ARCHIVE_MAX_FILE_BYTES):
            raise PreviewError('unsafe archive file')
        data = bytearray()
        while len(data) <= ARCHIVE_MAX_FILE_BYTES:
            chunk = os.read(fd, min(65536, ARCHIVE_MAX_FILE_BYTES + 1 - len(data)))
            if not chunk:
                break
            data.extend(chunk)
        after = os.fstat(fd)
        if len(data) != before.st_size or _archive_identity(before) != _archive_identity(after):
            raise PreviewError('archive source changed')
        os.lseek(fd, 0, os.SEEK_SET)
        with os.fdopen(os.dup(fd), 'rb') as stream:
            repeated = stream.read(ARCHIVE_MAX_FILE_BYTES + 1)
        if repeated != bytes(data) or _archive_identity(before) != _archive_identity(os.fstat(fd)):
            raise PreviewError('archive source changed')
        return bytes(data), before
    finally:
        os.close(fd)


def _archive_manifest_walk(fd, prefix, depth, state, manifest):
    if depth > ARCHIVE_MAX_DEPTH:
        raise PreviewError('archive exceeds limit')
    directory_before = _archive_identity(os.fstat(fd))
    with os.scandir(fd) as entries:
        names = sorted(entry.name for entry in itertools.islice(entries, ARCHIVE_MAX_VISITED + 1))
    if len(names) > ARCHIVE_MAX_VISITED:
        raise PreviewError('archive exceeds limit')
    for name in names:
        state['visited'] += 1
        if state['visited'] > ARCHIVE_MAX_VISITED:
            raise PreviewError('archive exceeds limit')
        info = os.stat(name, dir_fd=fd, follow_symlinks=False)
        relative = prefix + name
        if len(relative) > ARCHIVE_MAX_PATH:
            raise PreviewError('archive exceeds limit')
        manifest[relative] = _archive_identity(info)
        if relative in state['expectedBytes']:
            repeated, observed = _archive_read_file(fd, name, state['owner_uid'])
            if (_archive_identity(observed) != _archive_identity(info)
                    or repeated != state['expectedBytes'][relative]):
                raise PreviewError('archive source changed')
        if stat.S_ISDIR(info.st_mode):
            if name in ARCHIVE_CACHE_DIRS:
                continue
            child_fd, child_info = _archive_open_dir(fd, name, state['owner_uid'])
            try:
                if (child_info.st_dev, child_info.st_ino) != (info.st_dev, info.st_ino):
                    raise PreviewError('archive source changed')
                _archive_manifest_walk(child_fd, relative + '/', depth + 1, state, manifest)
            finally:
                os.close(child_fd)

    if directory_before != _archive_identity(os.fstat(fd)):
        raise PreviewError('archive source changed')


def _archive_walk(root_fd, owner_uid, prefix, depth, state, out, manifest):
    if depth > ARCHIVE_MAX_DEPTH:
        raise PreviewError('archive exceeds limit')
    directory_before = _archive_identity(os.fstat(root_fd))
    with os.scandir(root_fd) as entries:
        names = sorted(entry.name for entry in itertools.islice(entries, ARCHIVE_MAX_VISITED + 1))
    if len(names) > ARCHIVE_MAX_VISITED:
        raise PreviewError('archive exceeds limit')
    folded = set()
    for name in names:
        state['visited'] += 1
        if state['visited'] > ARCHIVE_MAX_VISITED:
            raise PreviewError('archive exceeds limit')
        key = name.casefold()
        if key in folded:
            raise PreviewError('archive has duplicate paths')
        folded.add(key)
        info = os.stat(name, dir_fd=root_fd, follow_symlinks=False)
        if stat.S_ISLNK(info.st_mode):
            raise PreviewError('unsafe archive path')
        if info.st_uid != owner_uid or info.st_mode & 0o022:
            raise PreviewError('unsafe archive path')
        relative = prefix + name
        if len(relative) > ARCHIVE_MAX_PATH:
            raise PreviewError('archive exceeds limit')
        if stat.S_ISDIR(info.st_mode):
            if name in ARCHIVE_CACHE_DIRS:
                state['omittedCacheEntries'] += 1
                manifest[relative] = _archive_identity(info)
                continue
            if SOURCE_SECRET_NAME.search(name):
                raise PreviewError('archive contains secret-named path')
            if ASSET_COMPONENT.fullmatch(name) is None:
                raise PreviewError('unsafe archive path')
            child_fd, child_info = _archive_open_dir(root_fd, name, owner_uid)
            try:
                if (child_info.st_dev, child_info.st_ino) != (info.st_dev, info.st_ino):
                    raise PreviewError('archive source changed')
                manifest[relative] = _archive_identity(child_info)
                _archive_walk(child_fd, owner_uid, relative + '/', depth + 1, state, out, manifest)
            finally:
                os.close(child_fd)
            continue
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise PreviewError('unsafe archive file')
        if name == '.git' or name in ARCHIVE_SKIP_NAMES or pathlib.PurePosixPath(name).suffix.lower() in ARCHIVE_SKIP_SUFFIXES:
            state['omittedCacheEntries'] += 1
            manifest[relative] = _archive_identity(info)
            continue
        if name.startswith('.'):
            if name not in ARCHIVE_ALLOWED_DOTFILES:
                raise PreviewError('unsafe archive path')
        else:
            if ASSET_COMPONENT.fullmatch(name) is None:
                raise PreviewError('unsafe archive path')
        if SOURCE_SECRET_NAME.search(name):
            raise PreviewError('archive contains secret-named file')
        data, before = _archive_read_file(root_fd, name, owner_uid)
        if _archive_identity(before) != _archive_identity(info):
            raise PreviewError('archive source changed')
        try:
            text = data.decode('utf-8')
        except UnicodeDecodeError:
            text = None
        if text is not None and SOURCE_SECRET_CONTENT.search(text):
            raise PreviewError('archive contains secret content')
        state['total'] += len(data)
        if state['total'] > ARCHIVE_MAX_TOTAL_BYTES:
            raise PreviewError('archive exceeds limit')
        state['files'] += 1
        if state['files'] > ARCHIVE_MAX_FILES:
            raise PreviewError('archive exceeds limit')
        manifest[relative] = _archive_identity(before)
        out.append((relative, data))

    if directory_before != _archive_identity(os.fstat(root_fd)):
        raise PreviewError('archive source changed')


def _archive_capture(workspace, source_path, owner_uid):
    _safe_root(workspace, owner_uid)
    parts = _parts(source_path)
    if not parts:
        raise PreviewError('unsafe archive path')
    root_fd = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
    current = root_fd
    try:
        root_info = os.fstat(root_fd)
        if root_info.st_uid != owner_uid or root_info.st_mode & 0o022:
            raise PreviewError('unsafe archive directory')
        for component in parts[:-1]:
            if component in ARCHIVE_CACHE_DIRS or SOURCE_SECRET_NAME.search(component):
                raise PreviewError('unsafe archive path')
            if ASSET_COMPONENT.fullmatch(component) is None:
                raise PreviewError('unsafe archive path')
            child, _info = _archive_open_dir(current, component, owner_uid)
            if current != root_fd:
                os.close(current)
            current = child
        leaf = parts[-1]
        if (leaf in ARCHIVE_CACHE_DIRS or leaf in ARCHIVE_SKIP_NAMES
                or pathlib.PurePosixPath(leaf).suffix.lower() in ARCHIVE_SKIP_SUFFIXES
                or SOURCE_SECRET_NAME.search(leaf)):
            raise PreviewError('unsafe archive path')
        if ASSET_COMPONENT.fullmatch(leaf) is None:
            raise PreviewError('unsafe archive path')
        leaf_info = os.stat(leaf, dir_fd=current, follow_symlinks=False)
        if stat.S_ISLNK(leaf_info.st_mode) or leaf_info.st_uid != owner_uid or leaf_info.st_mode & 0o022:
            raise PreviewError('unsafe archive path')
        state = {'visited': 0, 'files': 0, 'total': 0, 'omittedCacheEntries': 0, 'owner_uid': owner_uid}
        out = []
        manifest = {}
        if stat.S_ISDIR(leaf_info.st_mode):
            child_fd, child_info = _archive_open_dir(current, leaf, owner_uid)
            try:
                if (child_info.st_dev, child_info.st_ino) != (leaf_info.st_dev, leaf_info.st_ino):
                    raise PreviewError('archive source changed')
                manifest[leaf] = _archive_identity(child_info)
                _archive_walk(child_fd, owner_uid, leaf + '/', 1, state, out, manifest)
            finally:
                os.close(child_fd)
        elif stat.S_ISREG(leaf_info.st_mode):
            if leaf_info.st_nlink != 1:
                raise PreviewError('unsafe archive file')
            data, before = _archive_read_file(current, leaf, owner_uid)
            if _archive_identity(before) != _archive_identity(leaf_info):
                raise PreviewError('archive source changed')
            try:
                text = data.decode('utf-8')
            except UnicodeDecodeError:
                text = None
            if text is not None and SOURCE_SECRET_CONTENT.search(text):
                raise PreviewError('archive contains secret content')
            state['files'] = 1
            state['total'] = len(data)
            manifest[leaf] = _archive_identity(before)
            out.append((leaf, data))
        else:
            raise PreviewError('unsafe archive path')
        if not out:
            raise PreviewError('archive is empty')
        out.sort(key=lambda item: item[0])
        folded = set()
        for name, _data in out:
            key = name.casefold()
            if key in folded:
                raise PreviewError('archive has duplicate paths')
            folded.add(key)
        final_manifest = {}
        # Timestamps can be coarser than rapid same-size writes. Verify bytes
        # again after capturing the whole tree, not just its metadata.
        final_state = {'visited': 0, 'owner_uid': owner_uid, 'expectedBytes': dict(out)}
        if stat.S_ISDIR(leaf_info.st_mode):
            child_fd, child_info = _archive_open_dir(current, leaf, owner_uid)
            try:
                if (child_info.st_dev, child_info.st_ino) != (leaf_info.st_dev, leaf_info.st_ino):
                    raise PreviewError('archive source changed')
                final_manifest[leaf] = _archive_identity(child_info)
                _archive_manifest_walk(child_fd, leaf + '/', 1, final_state, final_manifest)
            finally:
                os.close(child_fd)
        else:
            repeated, observed = _archive_read_file(current, leaf, owner_uid)
            final_manifest[leaf] = _archive_identity(observed)
            if repeated != out[0][1]:
                raise PreviewError('archive source changed')
        if final_manifest != manifest:
            raise PreviewError('archive source changed')
        return out, state
    finally:
        if current != root_fd:
            os.close(current)
        os.close(root_fd)


def _archive_build(entries):
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=False) as archive:
        for name, data in entries:
            info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
            info.compress_type = zipfile.ZIP_DEFLATED
            info.external_attr = (stat.S_IFREG | 0o644) << 16
            info.create_system = 3
            archive.writestr(info, data)
    body = buffer.getvalue()
    if len(body) > ARCHIVE_MAX_OUTPUT:
        raise PreviewError('archive exceeds limit')
    with zipfile.ZipFile(io.BytesIO(body), 'r') as archive:
        names = archive.namelist()
        if names != [name for name, _data in entries]:
            raise PreviewError('archive verification failed')
        for name, data in entries:
            if archive.read(name) != data:
                raise PreviewError('archive verification failed')
        if archive.testzip() is not None:
            raise PreviewError('archive verification failed')
    return body


def publish_artifact_archive(workspace, previews, relative_path, source_path, owner_uid):
    _parts(relative_path)
    if pathlib.PurePosixPath(relative_path).suffix.lower() != '.zip':
        raise PreviewError('unsupported preview file type')
    entries, state = _archive_capture(workspace, source_path, owner_uid)
    body = _archive_build(entries)
    receipt = _publish_artifact_bytes(previews, relative_path, body, owner_uid)
    receipt['archive'] = {
        'sourcePath': source_path,
        'fileCount': state['files'],
        'sourceBytes': state['total'],
        'omittedCacheEntries': state['omittedCacheEntries'],
    }
    receipt['boundary'] = ARCHIVE_BOUNDARY
    return receipt


def publish_artifact(workspace, previews, relative_path, owner_uid):
    """Capture exactly one owner file through descriptor-relative no-link opens."""
    _safe_root(workspace, owner_uid)
    _safe_root(previews, owner_uid)
    parts = _parts(relative_path)
    filename = parts[-1]
    if pathlib.PurePosixPath(filename).suffix.lower() not in ARTIFACT_SUFFIXES:
        raise PreviewError('unsupported preview file type')
    directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
    current = os.open(workspace, directory_flags)
    try:
        root_info = os.fstat(current)
        if root_info.st_uid != owner_uid or root_info.st_mode & 0o022:
            raise PreviewError('unsafe preview directory')
        for component in parts[:-1]:
            child = os.open(component, directory_flags, dir_fd=current)
            os.close(current)
            current = child
            info = os.fstat(current)
            if info.st_uid != owner_uid or info.st_mode & 0o022:
                raise PreviewError('unsafe preview directory')
        descriptor = os.open(filename, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, dir_fd=current)
        try:
            before = os.fstat(descriptor)
            if (not stat.S_ISREG(before.st_mode) or before.st_uid != owner_uid or before.st_nlink != 1
                    or before.st_mode & 0o022 or not 0 <= before.st_size <= MAX_FILE_BYTES):
                raise PreviewError('unsafe preview file')
            chunks = bytearray()
            while len(chunks) <= MAX_FILE_BYTES:
                chunk = os.read(descriptor, min(65536, MAX_FILE_BYTES + 1 - len(chunks)))
                if not chunk:
                    break
                chunks.extend(chunk)
            after = os.fstat(descriptor)
            def identity(info):
                return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_mode, info.st_uid, info.st_nlink)
            if len(chunks) != before.st_size or identity(before) != identity(after):
                raise PreviewError('preview source changed')
            data = bytes(chunks)
            # Some filesystems can retain timestamps across rapid same-size writes.
            # Re-read the held descriptor rather than accepting a torn first read.
            os.lseek(descriptor, 0, os.SEEK_SET)
            with os.fdopen(os.dup(descriptor), 'rb') as stream:
                repeated = stream.read(MAX_FILE_BYTES + 1)
            if repeated != data or identity(before) != identity(os.fstat(descriptor)):
                raise PreviewError('preview source changed')
        finally:
            os.close(descriptor)
    finally:
        os.close(current)
    return _publish_artifact_bytes(previews, relative_path, data, owner_uid)


def _publish_artifact_bytes(previews, relative_path, data, owner_uid):
    _safe_root(previews, owner_uid)
    filename = _parts(relative_path)[-1]
    if pathlib.PurePosixPath(filename).suffix.lower() not in ARTIFACT_SUFFIXES or len(data) > MAX_FILE_BYTES:
        raise PreviewError('unsupported or oversized artifact')
    directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
    digest = hashlib.sha256()
    encoded_name = filename.encode('utf-8')
    digest.update(len(encoded_name).to_bytes(4, 'big'))
    digest.update(encoded_name)
    digest.update(len(data).to_bytes(8, 'big'))
    digest.update(data)
    full_digest = digest.hexdigest()
    site_id = 'site-' + full_digest[:24]
    destination = previews / site_id
    if not destination.exists():
        temporary = pathlib.Path(tempfile.mkdtemp(prefix='.artifact-', dir=previews))
        try:
            os.chmod(temporary, 0o700)
            fd = os.open(temporary / filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o400)
            try:
                view = memoryview(data)
                while view:
                    written = os.write(fd, view)
                    if written <= 0:
                        raise PreviewError('incomplete preview write')
                    view = view[written:]
                os.fsync(fd)
            finally:
                os.close(fd)
            os.rename(temporary, destination)
        except Exception:
            shutil.rmtree(temporary, ignore_errors=True)
            raise
    root = os.open(destination, directory_flags)
    try:
        root_info = os.fstat(root)
        if root_info.st_uid != owner_uid or stat.S_IMODE(root_info.st_mode) != 0o700 or os.listdir(root) != [filename]:
            raise PreviewError('unsafe preview snapshot')
        fd = os.open(filename, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK, dir_fd=root)
        try:
            info = os.fstat(fd)
            if (not stat.S_ISREG(info.st_mode) or info.st_uid != owner_uid or info.st_nlink != 1
                    or stat.S_IMODE(info.st_mode) != 0o400 or info.st_size != len(data)):
                raise PreviewError('unsafe preview snapshot')
            with os.fdopen(os.dup(fd), 'rb') as stream:
                if stream.read(MAX_FILE_BYTES + 1) != data:
                    raise PreviewError('preview snapshot verification failed')
        finally:
            os.close(fd)
    finally:
        os.close(root)
    return {'schemaVersion': 1, 'kind': ARTIFACT_KIND, 'status': 'succeeded', 'relativePath': relative_path,
            'siteId': site_id, 'sha256': full_digest,
            'file': {'path': filename, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()},
            'executable': False, 'overwritten': False, 'boundary': ARTIFACT_BOUNDARY}


def verify_current_snapshot(workspace, previews, request, owner_uid):
    """Read-only point-in-time equality, never a new publication or execution."""
    manifest = json.loads(snapshot_manifest(previews, request["siteId"]))
    if manifest["sha256"] != request["sha256"]:
        raise PreviewError("preview snapshot verification failed")
    sources = _source_files(workspace, request["relativeDirectory"], owner_uid)
    def identities(rows):
        return [(name, info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns,
                 info.st_ctime_ns, info.st_mode, info.st_uid, info.st_nlink)
                for name, _, info in rows]
    entries = []
    digest = hashlib.sha256()
    total = 0
    for name, source, info in sources:
        data = _read_stable(source, info)
        total += len(data)
        if total > MAX_TOTAL_BYTES:
            raise PreviewError("preview is too large")
        encoded = name.encode("utf-8")
        digest.update(len(encoded).to_bytes(4, "big"))
        digest.update(encoded)
        digest.update(len(data).to_bytes(8, "big"))
        digest.update(data)
        entries.append({"path": name, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})
    if identities(sources) != identities(_source_files(workspace, request["relativeDirectory"], owner_uid)):
        raise PreviewError("preview source changed")
    matched = entries == manifest["files"] and total == manifest["bytes"] and digest.hexdigest() == manifest["sha256"]
    return {"schemaVersion": 1, "kind": "ods-pixel-workspace-preview-verification",
            "status": "matched" if matched else "mismatched", "relativeDirectory": request["relativeDirectory"],
            "siteId": request["siteId"], "sha256": request["sha256"], "files": len(entries), "bytes": total,
            "entrySha256": next((entry["sha256"] for entry in entries if entry["path"] == "index.html"), None),
            "boundary": BOUNDARY, **_profile_fields()}


def _bounded_paths(paths):
    ordered = sorted(paths)
    shown = []
    total = 0
    for relative in ordered:
        if len(shown) >= 32 or total + len(relative) > 2048:
            break
        shown.append(relative)
        total += len(relative)
    return shown, len(ordered) - len(shown)


def _published_path_feedback(paths, empty_paths=()):
    """Bounded names from the verified snapshot; never infer requested files.

    Zero-byte files are listed separately. They are legitimate (for example an
    empty stylesheet), so this is information for the model, not a failure.
    """
    shown, omitted = _bounded_paths(paths)
    empty, empty_omitted = _bounded_paths(empty_paths)
    return {"publishedPaths": shown, "publishedPathsOmitted": omitted,
            "publishedEmptyPaths": empty, "publishedEmptyPathsOmitted": empty_omitted}


def snapshot_manifest(previews: pathlib.Path, site_id: str) -> bytes:
    """Describe only a rehashed published snapshot, never the live workspace.

    The reserved HTTP filename cannot be supplied by a generated site (its
    reserved __ods_ prefix is excluded by ASSET_COMPONENT). Old snapshots work
    without migration or adding metadata files to their content hash. Hidden
    names are skipped here as in publication: publication verifies that a
    snapshot holds exactly its captured files, none hidden, and the HTTP
    handler never serves a hidden name.
    """
    if SITE_ID.fullmatch(site_id) is None:
        raise PreviewError("invalid preview snapshot")
    files = _source_files(previews, site_id, os.getuid())
    digest = hashlib.sha256()
    entries = []
    total = 0
    for relative, source, info in files:
        if stat.S_IMODE(info.st_mode) != 0o400:
            raise PreviewError("unsafe preview snapshot")
        data = _read_stable(source, info)
        total += len(data)
        if total > MAX_TOTAL_BYTES:
            raise PreviewError("preview is too large")
        name = relative.encode("utf-8")
        digest.update(len(name).to_bytes(4, "big"))
        digest.update(name)
        digest.update(len(data).to_bytes(8, "big"))
        digest.update(data)
        entries.append({"path": relative, "bytes": len(data),
                        "sha256": hashlib.sha256(data).hexdigest()})
    if site_id != f"site-{digest.hexdigest()[:24]}":
        raise PreviewError("preview snapshot verification failed")
    return json.dumps({"schemaVersion": 1, "siteId": site_id,
                       "sha256": digest.hexdigest(), "bytes": total,
                       "files": entries}, separators=(",", ":")).encode("utf-8")


# Presentation-only chrome for the embedded viewer. Original artifact bytes and
# their hashes remain available at index.html and in the manifest unchanged.
PREVIEW_SCROLLBAR_STYLE = b'''<style data-ods-preview-scrollbars>
:root,body,*{scrollbar-color:#3d3f43 #131415!important;scrollbar-width:thin!important}
::-webkit-scrollbar{width:8px;height:8px;background:#131415}
::-webkit-scrollbar-track,::-webkit-scrollbar-corner{background:#131415}
::-webkit-scrollbar-thumb{background:#3d3f43;border-radius:6px;border:2px solid #131415}
::-webkit-scrollbar-thumb:hover{background:#55585e}
</style>'''


def _diff_row(kind: str, old_line: int | None, new_line: int | None, text: str) -> dict[str, Any]:
    row = {"type": kind, "oldLine": old_line, "newLine": new_line, "text": text.rstrip("\r\n")}
    if not text.endswith(("\r", "\n")):
        row["noFinalNewline"] = True
    return row


def snapshot_changes(previews: pathlib.Path, site_id: str, before_id: str | None) -> bytes:
    """Compare verified publications, never infer edits from assistant prose.

    The bounded line comparison follows Pixel control/chat_artifacts.py.
    First publication is labelled published, not a claimed new workspace file.
    """
    def contents(identity):
        if identity is None:
            return None, {}
        manifest = json.loads(snapshot_manifest(previews, identity))
        files = {}
        for entry in manifest["files"]:
            path = previews / identity / entry["path"]
            data = _read_stable(path, path.lstat())
            if hashlib.sha256(data).hexdigest() != entry["sha256"]:
                raise PreviewError("preview snapshot verification failed")
            files[entry["path"]] = data
        return manifest["sha256"], files
    before_hash, before = contents(before_id)
    after_hash, after = contents(site_id)
    changes = []
    remaining = 256 * 1024
    for path in sorted(set(before) | set(after)):
        old, new = before.get(path), after.get(path)
        if old == new:
            continue
        change = "published" if before_id is None else "deleted" if new is None else "created" if old is None else "modified"
        entry = {"path": path, "change": change, "additions": None, "deletions": None, "diff": [], "truncated": False}
        try:
            # Match the source viewer/excerpt's LF boundaries. str.splitlines
            # also splits Unicode separators that are retained inside a source line.
            a = [] if old is None else re.findall(r"[^\n]*\n|[^\n]+$", old.decode("utf-8"))
            b = [] if new is None else re.findall(r"[^\n]*\n|[^\n]+$", new.decode("utf-8"))
            if any(any(ord(c) < 32 and c != '\t' for c in line.rstrip("\r\n")) for line in a + b) or len(a) + len(b) > 4000:
                raise ValueError()
            additions = deletions = 0
            for kind, i, j, k, l in difflib.SequenceMatcher(None, a, b).get_opcodes():
                if kind in {"replace", "delete"}: deletions += j - i
                if kind in {"replace", "insert"}: additions += l - k
                rows = []
                if kind == "equal": rows = [_diff_row("context", x+1, k+x-i+1, a[x]) for x in range(i,j)]
                else:
                    rows += [_diff_row("remove", x+1, None, a[x]) for x in range(i,j)]
                    rows += [_diff_row("add", None, x+1, b[x]) for x in range(k,l)]
                for row in rows:
                    size = len(json.dumps(row, ensure_ascii=True).encode()) + 1
                    if size > remaining:
                        entry["truncated"] = True
                        continue
                    remaining -= size
                    entry["diff"].append(row)
            entry.update(additions=additions, deletions=deletions)
        except (UnicodeError, ValueError):
            entry["truncated"] = True
        changes.append(entry)
    return json.dumps({"schemaVersion":1, "scope":"published-snapshots", "siteId":site_id,
                       "beforeSiteId":before_id, "sha256":after_hash, "beforeSha256":before_hash,
                       "changes":changes}, separators=(",", ":")).encode()


def _preview_content_type(target: pathlib.Path, body: bytes) -> str:
    content_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
    if target.suffix.lower() in {".md", ".markdown"}:
        content_type = "text/plain"
    if content_type.startswith("text/") or content_type == "application/javascript":
        try:
            body.decode("utf-8")
        except UnicodeDecodeError:
            # Preserve browser encoding detection for non-UTF-8 publications.
            return content_type
        return content_type + "; charset=utf-8"
    return content_type


class PreviewHandler(http.server.BaseHTTPRequestHandler):
    server_version = "ODSPreview"
    sys_version = ""

    def _target(self) -> tuple[pathlib.Path, bytes] | None:
        parsed = urllib.parse.urlsplit(self.path)
        # Static snapshot queries (for example style.css?v=2) do not select
        # different bytes or authority. Match the private relay's path-only
        # lookup; never interpret a query as a source or filesystem path.
        if parsed.fragment:
            return None
        try:
            decoded = urllib.parse.unquote(parsed.path, errors="strict")
        except UnicodeDecodeError:
            return None
        parts = decoded.lstrip("/").split("/")
        # Framework exports request /_next/... and /games/... from the origin
        # root. Only a dedicated public snapshot host can bind those requests;
        # the authenticated internal proxy still requires an explicit site ID.
        if (parts and SITE_ID.fullmatch(parts[0]) is None and not self.server.internal_proxy):
            host = self.headers.get('Host', '')
            suffix = f'.localhost:{self.server.preview_port}'
            host_site = host[:-len(suffix)] if host.endswith(suffix) else ''
            if SITE_ID.fullmatch(host_site):
                parts.insert(0, host_site)
        if len(parts) < 1 or SITE_ID.fullmatch(parts[0]) is None:
            return None
        site_id = parts[0]
        if parsed.query and len(parts) > 1 and parts[1].startswith("__ods_"):
            return None
        if self.server.internal_proxy:  # type: ignore[attr-defined]
            expected_host = "portal-preview.internal" if PROFILE_ID is not None else "pixel-preview.internal"
        else:
            expected_host = (
                f"{site_id}.localhost:{self.server.preview_port}"  # type: ignore[attr-defined]
            )
        if self.headers.get("Host", "").lower() != expected_host:
            return None
        if parts[1:] == ["__ods_manifest__.json"]:
            try:
                return pathlib.Path("manifest.json"), snapshot_manifest(
                    self.server.preview_root, site_id  # type: ignore[attr-defined]
                )
            except (PreviewError, OSError, ValueError):
                return None
        if len(parts) == 3 and parts[1] == '__ods_source__' and parts[2].endswith('.json'):
            # Source text never enters the public, executable preview origin.
            # Only the authenticated Dashboard -> edge -> private Unix relay.
            if not self.server.internal_proxy or PROFILE_ID is not None:
                return None
            try:
                return pathlib.Path('source.json'), _review_source_bytes(
                    self.server.preview_root, site_id, parts[2][:-5], os.getuid())
            except (PreviewError, OSError, ValueError):
                return None
        if len(parts) == 3 and parts[1] == "__ods_changes__" and parts[2].endswith(".json"):
            baseline = parts[2][:-5]
            if baseline != "initial" and SITE_ID.fullmatch(baseline) is None:
                return None
            try:
                return pathlib.Path("changes.json"), snapshot_changes(
                    self.server.preview_root, site_id, None if baseline == "initial" else baseline)
            except (PreviewError, OSError, ValueError):
                return None
        if parts[-1] == "":
            parts[-1] = "index.html"
        styled_view = parts[1:] == ["__ods_view__.html"]
        if styled_view:
            parts[-1] = "index.html"
        if any(ASSET_COMPONENT.fullmatch(part) is None for part in parts[1:]):
            return None
        target = self.server.preview_root.joinpath(*parts)  # type: ignore[attr-defined]
        try:
            info = target.lstat()
            root = self.server.preview_root.resolve(strict=True)  # type: ignore[attr-defined]
            if (
                not stat.S_ISREG(info.st_mode)
                or stat.S_ISLNK(info.st_mode)
                or info.st_nlink != 1
                or info.st_size > MAX_FILE_BYTES
                or target.resolve(strict=True).is_relative_to(root) is False
            ):
                return None
            body = target.read_bytes()
            if styled_view:
                # Append instead of prepending so the original doctype and
                # document parsing mode remain intact. No script is injected.
                body += PREVIEW_SCROLLBAR_STYLE
            return target, body
        except (FileNotFoundError, OSError, ValueError):
            return None

    def _send(self, include_body: bool) -> None:
        result = self._target()
        if result is None:
            self.send_error(404)
            return
        target, body = result
        download_only = target.suffix.lower() in (DOWNLOAD_ONLY_SUFFIXES | {".docx", ".xlsx", ".pptx"})
        content_type = "application/octet-stream" if download_only else _preview_content_type(target, body)
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        if download_only:
            # Validated snapshot filenames cannot inject header bytes.
            # Documents/archives are opaque downloads, never rendered or unpacked.
            self.send_header("Content-Disposition", f'attachment; filename="{target.name}"')
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Security-Policy", CSP)
        self.send_header("Cross-Origin-Opener-Policy", "same-origin")
        # The ODS dashboard and preview service intentionally use separate
        # loopback ports. CSP restricts which local parents may frame a site;
        # CORP must therefore permit that cross-origin iframe navigation.
        self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
        # Module scripts, fonts and fetch() use CORS from the opaque preview
        # frame. Only published snapshot bytes are served here; never grant
        # credentials or carry this policy onto ODS control endpoints.
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
        self.send_header("Referrer-Policy", "no-referrer")
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("X-Preview-SHA256", hashlib.sha256(body).hexdigest())
        self.end_headers()
        if include_body:
            self.wfile.write(body)

    def do_GET(self) -> None:  # noqa: N802
        self._send(True)

    def do_HEAD(self) -> None:  # noqa: N802
        self._send(False)

    def log_message(self, _format: str, *_args: object) -> None:
        return


class PreviewHTTPServer(http.server.ThreadingHTTPServer):
    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, address: tuple[str, int], preview_root: pathlib.Path):
        self.preview_root = preview_root
        self.internal_proxy = False
        super().__init__(address, PreviewHandler)
        self.preview_port = self.server_address[1]


class PreviewUnixHTTPServer(socketserver.ThreadingUnixStreamServer):
    daemon_threads = True

    def __init__(
        self, address: str, preview_root: pathlib.Path, preview_port: int
    ):
        self.preview_root = preview_root
        self.preview_port = preview_port
        self.internal_proxy = True
        super().__init__(address, PreviewHandler)


def _verify_http(port: int, site_id: str, entry_sha256: str, filename: str = "") -> None:
    connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
    try:
        connection.request(
            "GET",
            f"/{site_id}/{filename}",
            headers={"Host": f"{site_id}.localhost:{port}"},
        )
        response = connection.getresponse()
        body = response.read(MAX_FILE_BYTES + 1)
        if (
            response.status != 200
            or len(body) > MAX_FILE_BYTES
            or hashlib.sha256(body).hexdigest() != entry_sha256
            or response.getheader("X-Preview-SHA256") != entry_sha256
        ):
            raise PreviewError("preview HTTP readback failed")
    finally:
        connection.close()


def _error_result(code: str = "unavailable", diagnostic=None) -> dict[str, Any]:
    return {
        "schemaVersion": SCHEMA_VERSION,
        "kind": KIND,
        "status": "failed",
        **_profile_fields(),
        "error": "ODS workspace preview publication failed",
        "errorCode": code if code in PREVIEW_FAILURE_CODES.values() else "unavailable",
        "boundary": BOUNDARY,
        **({"artifactError": diagnostic} if code == "invalid_json_artifact" and diagnostic else {}),
    }


def _serve_connection(
    connection: socket.socket,
    *,
    workspace: pathlib.Path,
    previews: pathlib.Path,
    owner_uid: int,
    port: int,
) -> None:
    response: dict[str, Any]
    try:
        uid, _gid = peer_ids(connection)
        if uid != owner_uid:
            raise PreviewError("unauthorized preview peer")
        connection.settimeout(10)
        payload = bytearray()
        while len(payload) <= MAX_REQUEST_BYTES:
            piece = connection.recv(min(1024, MAX_REQUEST_BYTES + 1 - len(payload)))
            if not piece:
                break
            payload.extend(piece)
            if b"\n" in piece:
                break
        if b"\n" not in payload or payload.count(b"\n") != 1 or not payload.endswith(b"\n"):
            raise PreviewError("invalid preview framing")
        raw = bytes(payload[:-1])
        if raw == b'{"schemaVersion":1,"action":"health"}':
            response = {
                "schemaVersion": SCHEMA_VERSION,
                "kind": KIND,
                "status": "ok",
                **_profile_fields(),
                "port": port,
                "boundary": BOUNDARY,
            }
        else:
            request = parse_request(raw)
            if request['action'] == 'publish-artifact':
                if 'sourcePath' in request:
                    response = publish_artifact_archive(workspace, previews, request['relativePath'], request['sourcePath'], owner_uid)
                else:
                    response = publish_artifact(workspace, previews, request['relativePath'], owner_uid)
                _verify_http(port, response['siteId'], response['file']['sha256'], response['file']['path'])
                response.update({'httpStatus': 200, 'readbackVerified': True})
            elif request["action"] == "verify-current":
                response = verify_current_snapshot(workspace, previews, request, owner_uid)
            else:
                response = publish_snapshot(
                    workspace,
                    previews,
                    request["relativeDirectory"],
                    owner_uid,
                    source_directory=request.get('sourceDirectory'),
                )
                _verify_http(port, response["siteId"], response["entrySha256"])
                response.update(
                    {
                        "port": port,
                        "url": (
                            f"http://{response['siteId']}.localhost:{port}/"
                            f"{response['siteId']}/"
                        ),
                        "httpStatus": 200,
                        "readbackVerified": True,
                    }
                )
    except PreviewError as error:
        # Only fixed categories and captured JSON artifact-relative locations
        # cross the socket; no source excerpts, absolute paths or OS details.
        response = _error_result(PREVIEW_FAILURE_CODES.get(str(error), "unavailable"),
                                 error.diagnostic if isinstance(error, JsonArtifactError) else None)
    except (OSError, ValueError, TypeError, KeyError):
        response = _error_result()
    encoded = (json.dumps(response, sort_keys=True, separators=(",", ":")) + "\n").encode()
    if len(encoded) > MAX_RESPONSE_BYTES:
        encoded = (json.dumps(_error_result(), sort_keys=True, separators=(",", ":")) + "\n").encode()
    try:
        connection.sendall(encoded)
    except OSError:
        return


def preview_owner_uid(owner: str) -> int:
    """Numeric container identities must name this unprivileged process only."""
    if not isinstance(owner, str):
        raise PreviewError("invalid preview service configuration")
    if re.fullmatch(r"[1-9][0-9]{0,9}", owner):
        uid = int(owner)
        if uid != os.getuid() or uid != os.geteuid():
            raise PreviewError("preview must run as its configured owner")
        return uid
    if re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", owner) is None:
        raise PreviewError("invalid preview service configuration")
    uid = pwd.getpwnam(owner).pw_uid
    if PROFILE_ID is not None and uid != os.getuid():
        raise PreviewError("preview must run as its configured owner")
    return uid


def serve(
    socket_path: pathlib.Path,
    workspace: pathlib.Path,
    previews: pathlib.Path,
    owner: str,
    port: int,
    *,
    listen_host: str = "127.0.0.1",
) -> int:
    if (
        socket_path != SOCKET_PATH
        or not workspace.is_absolute()
        or workspace == pathlib.Path("/")
        or not previews.is_absolute()
        or previews == pathlib.Path("/")
        or type(port) is not int or not 1 <= port <= 65535
        or listen_host not in ("127.0.0.1", "0.0.0.0")
    ):
        raise PreviewStartupError('configuration', PreviewError("invalid preview service configuration"))
    with _startup_phase('owner'):
        owner_uid = preview_owner_uid(owner)
    with _startup_phase('workspace-root'):
        _safe_root(workspace, owner_uid)
    with _startup_phase('previews-root'):
        previews.mkdir(mode=0o700, parents=True, exist_ok=True)
        _safe_root(previews, owner_uid)
    with _startup_phase('control-socket-cleanup'):
        if socket_path.exists() or socket_path.is_symlink():
            info = socket_path.lstat()
            if not stat.S_ISSOCK(info.st_mode) or info.st_uid != owner_uid:
                raise PreviewError("unsafe existing preview socket")
            socket_path.unlink()
    with _startup_phase('http-socket-cleanup'):
        if HTTP_SOCKET_PATH.exists() or HTTP_SOCKET_PATH.is_symlink():
            info = HTTP_SOCKET_PATH.lstat()
            if not stat.S_ISSOCK(info.st_mode) or info.st_uid != owner_uid:
                raise PreviewError("unsafe existing preview HTTP socket")
            HTTP_SOCKET_PATH.unlink()

    with _startup_phase('http-listener'):
        httpd = PreviewHTTPServer((listen_host, port), previews)
    http_thread = threading.Thread(target=httpd.serve_forever, daemon=True)
    http_thread.start()
    with _startup_phase('unix-http-listener'):
        unix_httpd = PreviewUnixHTTPServer(str(HTTP_SOCKET_PATH), previews, port)
        os.chmod(HTTP_SOCKET_PATH, 0o660)
    unix_http_thread = threading.Thread(target=unix_httpd.serve_forever, daemon=True)
    unix_http_thread.start()
    listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        with _startup_phase('control-listener'):
            listener.bind(str(socket_path))
            os.chmod(socket_path, 0o600)
            listener.listen(4)
        while True:
            connection, _address = listener.accept()
            with connection:
                _serve_connection(
                    connection,
                    workspace=workspace,
                    previews=previews,
                    owner_uid=owner_uid,
                    port=port,
                )
    finally:
        listener.close()
        httpd.shutdown()
        httpd.server_close()
        unix_httpd.shutdown()
        unix_httpd.server_close()
        try:
            socket_path.unlink()
        except FileNotFoundError:
            pass
        try:
            HTTP_SOCKET_PATH.unlink()
        except FileNotFoundError:
            pass


def client(socket_path: pathlib.Path, payload: dict[str, Any]) -> dict[str, Any]:
    connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    connection.settimeout(15)
    try:
        connection.connect(str(socket_path))
        connection.sendall((json.dumps(payload, separators=(",", ":")) + "\n").encode())
        chunks = bytearray()
        while len(chunks) <= MAX_RESPONSE_BYTES:
            piece = connection.recv(min(4096, MAX_RESPONSE_BYTES + 1 - len(chunks)))
            if not piece:
                break
            chunks.extend(piece)
    finally:
        connection.close()
    if len(chunks) > MAX_RESPONSE_BYTES or chunks.count(b"\n") != 1 or not chunks.endswith(b"\n"):
        raise PreviewError("invalid preview response")
    value = json.loads(bytes(chunks[:-1]).decode("utf-8"))
    if not isinstance(value, dict) or value.get("schemaVersion") != SCHEMA_VERSION:
        raise PreviewError("invalid preview response")
    return value


def main(argv: list[str]) -> int:
    try:
        if len(argv) == 7 and argv[1] in ("serve", "serve-container"):
            container = argv[1] == "serve-container"
            with _startup_phase('owner'):
                if container and (not argv[5].isdecimal() or preview_owner_uid(argv[5]) == 0):
                    raise PreviewError("container preview requires numeric non-root owner")
            with _startup_phase('configuration'):
                port = int(argv[6])
            return serve(
                pathlib.Path(argv[2]),
                pathlib.Path(argv[3]),
                pathlib.Path(argv[4]),
                argv[5],
                port,
                listen_host="0.0.0.0" if container else "127.0.0.1",
            )
        if len(argv) == 2 and argv[1] == "request":
            raw = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
            if len(raw) > MAX_REQUEST_BYTES:
                raise PreviewError("invalid preview request")
            request = parse_request(raw)
            value = client(SOCKET_PATH, request)
            sys.stdout.write(json.dumps(value, separators=(",", ":")) + "\n")
            return 0
        if len(argv) == 3 and argv[1] == "health":
            value = client(
                pathlib.Path(argv[2]),
                {"schemaVersion": SCHEMA_VERSION, "action": "health"},
            )
            if (
                value.get("kind") != KIND
                or value.get("status") != "ok"
                or value.get("boundary") != BOUNDARY
            ):
                raise PreviewError("invalid preview health response")
            sys.stdout.write(json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n")
            return 0
        raise PreviewError("invalid preview command")
    except PreviewStartupError as error:
        sys.stderr.write(f"ODS workspace preview failed [stage={error.stage}, reason={error.reason}]\n")
        return 1
    except (PreviewError, OSError, ValueError, KeyError, json.JSONDecodeError):
        sys.stderr.write("ODS workspace preview failed\n")
        return 1


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))