#!/bin/sh
set -eu

# A packaged runtime is verified before each private-service launch. Embedded
# Python must not create mutable __pycache__ entries inside that trusted tree.
# This affects this application only, not the user's global Python settings.
export PYTHONDONTWRITEBYTECODE=1

# Launch only the maintained KiCad 10.0.5 fork with the compiled TraceForge
# AUI/GAL host. The old Python ActionPlugin path is intentionally not a
# fallback: it cannot satisfy native-canvas or exact-launch identity.
PREFIX=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
# KiCad's Linux install tree is self-contained but its binaries intentionally
# rely on the package launcher to resolve the sibling shared-library directory.
# Never let the dynamic loader fall through to a stock KiCad installation.
export LD_LIBRARY_PATH="$PREFIX/lib:$PREFIX/lib/kicad${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
# The compiled wxWebView hosts resolve their React bundle from this explicit
# package-owned root.  Never fall back to /usr/share: that can silently load a
# stale system bundle (or fail with a blank panel) when the TraceForge package
# is installed under a relocatable cache prefix.
export TRACEFORGE_UI_ROOT="$PREFIX/share/traceforge-kicad/ui"
TRACEFORGE_CONFIG_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}/traceforge-kicad"
appearance_settings="$TRACEFORGE_CONFIG_ROOT/traceforge/kicad.ini"
persisted_scale=0
if [ -f "$appearance_settings" ] && [ ! -L "$appearance_settings" ]; then
  persisted_scale=$(awk -F= '
    /^\[/ { in_traceforge = ($0 == "[traceforge]"); next }
    in_traceforge && $1 == "application_scale" { print $2; exit }
  ' "$appearance_settings" 2>/dev/null || printf '0')
  case "$persisted_scale" in
    ''|0|1|2|3|4) ;;
    *) echo "TraceForge startup warning: ignoring invalid persisted application scale" >&2; persisted_scale=0 ;;
  esac
fi
export TRACEFORGE_APPLICATION_SCALE_PREFERENCE="${persisted_scale:-0}"
# wxGTK runs through Xwayland on this Linux workstation.  Xwayland advertises
# a nominal 96 DPI even when the physical panel is 200+ DPI, which makes the
# entire editor (not just the compact WebView) look zoomed out. Respect a
# desktop/user GDK_SCALE first; otherwise promote only genuinely high-density
# (physical 180+ DPI) panels.
# TRACEFORGE_GDK_SCALE=1 is an explicit opt-out for users who prefer compact
# KiCad chrome. GDK_SCALE must be set before wx/GTK initializes.
if [ -z "${GDK_SCALE:-}" ]; then
  requested_scale=${TRACEFORGE_GDK_SCALE:-}
  if [ -z "$requested_scale" ] && [ "${persisted_scale:-0}" != 0 ]; then
    requested_scale=$persisted_scale
  fi
  if [ -n "$requested_scale" ]; then
    case "$requested_scale" in
      1|2|3|4) export GDK_SCALE="$requested_scale" ;;
      *) echo "TraceForge startup error: TRACEFORGE_GDK_SCALE must be 1, 2, 3, or 4" >&2; exit 78 ;;
    esac
  elif command -v xrandr >/dev/null 2>&1; then
    hidpi_metrics=$(xrandr --current 2>/dev/null | awk '
      / connected/ && !seen {
        for (i = 1; i <= NF; i++) {
          if ($i ~ /^[0-9]+x[0-9]+\+[0-9]+\+[0-9]+$/) {
            split($i, pixels, /[x+]/); width = pixels[1]; height = pixels[2]
          }
          if ($i ~ /^[0-9]+mm$/ && i + 2 <= NF && $(i + 1) == "x" && $(i + 2) ~ /^[0-9]+mm$/) {
            width_mm = substr($i, 1, length($i) - 2)
            height_mm = substr($(i + 2), 1, length($(i + 2)) - 2)
          }
        }
        if (width && height && width_mm && height_mm) print width, height, width_mm, height_mm
        seen = 1
      }')
    detected_scale=$(printf '%s\n' "$hidpi_metrics" | awk '
      NF == 4 && (($1 * 25.4 / $3) >= 180 || ($2 * 25.4 / $4) >= 180) { print 2 }')
    if [ "$detected_scale" = 2 ]; then export GDK_SCALE=2; fi
  fi
fi
export TRACEFORGE_EFFECTIVE_GDK_SCALE="${GDK_SCALE:-1}"
EDITOR_TARGET=${TRACEFORGE_KICAD_EDITOR_TARGET:-}
if [ -z "$EDITOR_TARGET" ]; then
  for argument in "$@"; do
    case "$argument" in
      *.kicad_sch) EDITOR_TARGET=eeschema; break ;;
      *.kicad_pcb) EDITOR_TARGET=pcbnew; break ;;
      *.kicad_pro)
        stem=${argument%.kicad_pro}
        if [ -f "$stem.kicad_sch" ]; then EDITOR_TARGET=eeschema; else EDITOR_TARGET=pcbnew; fi
        break ;;
    esac
  done
fi
[ -n "$EDITOR_TARGET" ] || EDITOR_TARGET=pcbnew
case "$EDITOR_TARGET" in
  eeschema|pcbnew) ;;
  *) echo "TraceForge startup error: editor target must be eeschema or pcbnew" >&2; exit 78 ;;
esac

# KiCad's editor entry points consume the schematic/board file, not the
# project-settings container.  A clean first launch must therefore translate
# a user-provided .kicad_pro path to its sibling design file before exec.  If
# we pass the .kicad_pro itself, eeschema opens an untitled document and the
# TraceForge intake pane loses the requested project identity.  Keep this
# normalization here (rather than relying on a warm KiCad profile), and only
# rewrite the single supported editor input when the sibling exists.
if [ "$#" -eq 1 ]; then
  case "$1" in
    *.kicad_pro)
      project_stem=${1%.kicad_pro}
      if [ "$EDITOR_TARGET" = eeschema ] && [ -f "$project_stem.kicad_sch" ]; then
        set -- "$project_stem.kicad_sch"
      elif [ "$EDITOR_TARGET" = pcbnew ] && [ -f "$project_stem.kicad_pcb" ]; then
        set -- "$project_stem.kicad_pcb"
      fi
      ;;
  esac
fi
if [ "$#" -eq 1 ]; then
  case "$1" in
    *.kicad_sch|*.kicad_pcb)
      # KiCad may change its process working directory before the compiled
      # host compares this identity with the loaded project.  A relative
      # launch argument would then resolve against two different directories
      # and incorrectly downgrade a real project to "Unsaved design".  Bind
      # both the editor argument and the receipt to an absolute physical path.
      if [ -f "$1" ]; then
        requested_dir=$(dirname -- "$1")
        requested_base=$(basename -- "$1")
        requested_dir=$(CDPATH= cd -- "$requested_dir" && pwd -P) || {
          echo "TraceForge startup error: requested design directory cannot be resolved" >&2
          exit 78
        }
        set -- "$requested_dir/$requested_base"
      fi
      # The native host compares this requested design identity with the file
      # actually loaded by KiCad before it enables project-scoped actions.
      export TRACEFORGE_NATIVE_REQUESTED_DESIGN_PATH="$1"
      ;;
  esac
fi
if [ "${TRACEFORGE_LAUNCH_TEST_MODE:-0}" = "1" ]; then
  # Test-only injection keeps deterministic launcher tests hermetic. Supported
  # product launches are always package-owned and never honor these paths.
  BRIDGE=${TRACEFORGE_NATIVE_BRIDGE:-"$PREFIX/bin/traceforge-kicad-native-bridge"}
  EDITOR=${TRACEFORGE_KICAD_EDITOR:-"$PREFIX/bin/$EDITOR_TARGET"}
  CLI=${TRACEFORGE_KICAD_CLI:-"$PREFIX/bin/kicad-cli"}
  MANIFEST=${TRACEFORGE_NATIVE_MANIFEST:-"$PREFIX/share/traceforge-kicad/TRACEFORGE-NATIVE-MANIFEST.json"}
  PREFLIGHT=${TRACEFORGE_NATIVE_PREFLIGHT:-"$PREFIX/bin/traceforge-kicad-preflight.py"}
  DIAGNOSTIC=${TRACEFORGE_NATIVE_RUNTIME_DIAGNOSTIC:-"$PREFIX/bin/traceforge-native-runtime-diagnostics.py"}
else
  BRIDGE="$PREFIX/bin/traceforge-kicad-native-bridge"
  EDITOR="$PREFIX/bin/$EDITOR_TARGET"
  CLI="$PREFIX/bin/kicad-cli"
  MANIFEST="$PREFIX/share/traceforge-kicad/TRACEFORGE-NATIVE-MANIFEST.json"
  PREFLIGHT="$PREFIX/bin/traceforge-kicad-preflight.py"
  DIAGNOSTIC="$PREFIX/bin/traceforge-native-runtime-diagnostics.py"
fi
SERVICE_SCRIPT="$PREFIX/bin/traceforge-kicad-native-service.py"

fail() {
  echo "TraceForge startup error: $1" >&2
  # Diagnostics inspect only this package prefix and intentionally fail closed;
  # their non-zero result must never be hidden by a stock-KiCad fallback.
  if [ -f "$DIAGNOSTIC" ]; then
    python3 "$DIAGNOSTIC" --prefix "$PREFIX" --platform linux --format summary >&2 || :
  fi
  echo "Recovery: install the exact TraceForge KiCad 10.0.5 fork package and relaunch." >&2
  exit 78
}

[ -x "$BRIDGE" ] || fail "compiled native bridge is missing: $BRIDGE"
[ -x "$EDITOR" ] || fail "compiled KiCad editor is missing: $EDITOR"
[ -x "$CLI" ] || fail "package-owned kicad-cli is missing: $CLI"
[ -f "$MANIFEST" ] || fail "native identity manifest is missing: $MANIFEST"

BRIDGE_VERSION=$($BRIDGE --version 2>&1) || fail "compiled native bridge self-identification failed"
printf '%s\n' "$BRIDGE_VERSION" | grep -Fqx 'kicad_version=10.0.5' || fail "native bridge is not bound to KiCad 10.0.5"
printf '%s\n' "$BRIDGE_VERSION" | grep -Fqx 'host_mode=compiled_kicad_aui' || fail "native bridge is not the compiled AUI host"
printf '%s\n' "$BRIDGE_VERSION" | grep -Fqx 'editors=eeschema,pcbnew' || fail "native bridge does not bind both real editors"
printf '%s\n' "$BRIDGE_VERSION" | grep -Eq '^host_payload_sha256=[0-9a-f]{64}$' || fail "native bridge payload identity is missing or malformed"
BRIDGE_PAYLOAD_SHA256=$(printf '%s\n' "$BRIDGE_VERSION" | sed -n 's/^host_payload_sha256=//p')
export TRACEFORGE_NATIVE_BRIDGE_PAYLOAD_SHA256="$BRIDGE_PAYLOAD_SHA256"

python3 - "$MANIFEST" <<'PY' || exit 78
import hashlib
import json
import hashlib
import os
import re
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    document = json.loads(path.read_text(encoding="utf-8"))
    upstream = document["upstream"]
    host = document["host_bridge"]
    identity = document["product_identity"]
    patch = path.parent / "kicad-host-source" / "0001-traceforge-native-aui-host.patch"
except (OSError, ValueError, KeyError, TypeError) as exc:
    print(f"TraceForge startup error: malformed native identity manifest: {exc}", file=sys.stderr)
    raise SystemExit(78)

if (
    document.get("schema_version") != "traceforge.native_package_manifest.v1"
    or document.get("product") != "traceforge-kicad-native"
    or document.get("platform") != "linux"
    or document.get("architecture") not in {"amd64", "arm64"}
    or not re.fullmatch(r"[0-9a-f]{40}", document.get("source_sha", ""))
    or not re.fullmatch(r"[0-9a-f]{40}", document.get("source_tree_sha", ""))
):
    print("TraceForge startup error: native manifest package identity is invalid", file=sys.stderr)
    raise SystemExit(78)
if upstream.get("project") != "kicad" or upstream.get("ref") != "10.0.5":
    print("TraceForge startup error: manifest is not bound to KiCad 10.0.5", file=sys.stderr)
    raise SystemExit(78)
if upstream.get("commit") != "18fb9289ff0efdca53c0352ed81a0973f0a6b58c":
    print("TraceForge startup error: manifest has the wrong KiCad source commit", file=sys.stderr)
    raise SystemExit(78)
if upstream.get("native_host_patch_sha256") != "987fdabbac447b872d955291dc0a6fb1ed16d5fd07c4fc68d4285ee11c061496":
    print("TraceForge startup error: manifest has the wrong native host patch digest", file=sys.stderr)
    raise SystemExit(78)
if (
    host.get("protocol") != "traceforge.native_host.v1"
    or host.get("kicad_version") != "10.0.5"
    or host.get("mode") != "compiled_kicad_aui"
    or host.get("editor_targets") != ["eeschema", "pcbnew"]
    or host.get("panes") != ["TraceForgeEeschema", "TraceForgePCB"]
    or host.get("service_protocol") != "traceforge.native_host.service.v1"
    or host.get("loaded_window_receipt") != "traceforge.native_loaded_window_receipt.v1"
    or host.get("canvas") != "kicad_gal_view_item"
    or host.get("candidate_mutation_authority") is not False
    or host.get("trusted_project_write_authority") is not False
):
    print("TraceForge startup error: manifest is not a compiled native host", file=sys.stderr)
    raise SystemExit(78)
if not patch.is_file() or hashlib.sha256(patch.read_bytes()).hexdigest() != upstream["native_host_patch_sha256"]:
    print("TraceForge startup error: packaged native host patch is missing or modified", file=sys.stderr)
    raise SystemExit(78)
payload = host.get("payload_sha256")
bridge_payload = os.environ.get("TRACEFORGE_NATIVE_BRIDGE_PAYLOAD_SHA256")
if not isinstance(payload, str) or not re.fullmatch(r"[0-9a-f]{64}", payload):
    print("TraceForge startup error: manifest native payload identity is malformed", file=sys.stderr)
    raise SystemExit(78)
if payload != bridge_payload:
    print("TraceForge startup error: manifest and native bridge payload identities differ", file=sys.stderr)
    raise SystemExit(78)
if host.get("editor_targets") != ["eeschema", "pcbnew"]:
    print("TraceForge startup error: manifest does not bind both real editors", file=sys.stderr)
    raise SystemExit(78)
    raise SystemExit(78)
if (
    identity.get("schema") != "traceforge.native_product_identity.v1"
    or identity.get("product_id") != "org.traceforge.TraceForgeKiCad"
    or identity.get("display_name") != "TraceForge — powered by KiCad 10.0.5"
    or identity.get("executable") != "traceforge-kicad"
    or identity.get("desktop_id") != "org.traceforge.TraceForgeKiCad.desktop"
    or identity.get("wm_class") != "TraceForgeKiCad"
    or identity.get("icon") != "traceforge-kicad"
):
    print("TraceForge startup error: manifest has the wrong TraceForge product identity", file=sys.stderr)
    raise SystemExit(78)
PY

[ -f "$PREFLIGHT" ] || fail "package-owned launch preflight is missing: $PREFLIGHT"

# Keep KiCad's mutable state separate from any stock KiCad installation.  The
# manifest records these user-owned roots, while the stock data root is pinned
# to this package's exact 10.0.5 resources.  Do this before the editor starts;
# a native pane cannot repair a process that has already loaded another
# profile.
TRACEFORGE_DATA_ROOT="${XDG_DATA_HOME:-$HOME/.local/share}/traceforge-kicad"
TRACEFORGE_CACHE_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/traceforge-kicad"
TRACEFORGE_STATE_ROOT="${XDG_STATE_HOME:-$HOME/.local/state}/traceforge-kicad"
mkdir -p "$TRACEFORGE_CONFIG_ROOT" "$TRACEFORGE_DATA_ROOT" "$TRACEFORGE_CACHE_ROOT" "$TRACEFORGE_STATE_ROOT" || fail "isolated TraceForge runtime roots cannot be created"
export KICAD_CONFIG_HOME="$TRACEFORGE_CONFIG_ROOT"
export KICAD_CACHE_HOME="$TRACEFORGE_CACHE_ROOT"
export KICAD_STOCK_DATA_HOME="$PREFIX/share/kicad"
# Linux's upstream EDA library fallback is compiled into the editor and does
# not follow KICAD_STOCK_DATA_HOME. Custom-prefix installations must use their
# own bundled data, while honoring explicit user library environment overrides.
export KICAD10_SYMBOL_DIR="${KICAD10_SYMBOL_DIR:-$PREFIX/share/kicad/symbols}"
export KICAD10_FOOTPRINT_DIR="${KICAD10_FOOTPRINT_DIR:-$PREFIX/share/kicad/footprints}"
export XDG_DATA_HOME="$TRACEFORGE_DATA_ROOT"
export XDG_STATE_HOME="$TRACEFORGE_STATE_ROOT"
export TRACEFORGE_NATIVE_WORKSPACE_BINDING_FILE="${TRACEFORGE_NATIVE_WORKSPACE_BINDING_FILE:-$TRACEFORGE_STATE_ROOT/workspace-binding.json}"

# Installed product launches use only the company-managed TraceForge API. A
# test process may inject a loopback server or verified message fixture, but
# ordinary launches cannot select a provider endpoint or inherit a token path.
if [ "${TRACEFORGE_LAUNCH_TEST_MODE:-0}" != "1" ] &&
   [ "${TRACEFORGE_CANDIDATE_REVIEW_ONLY:-0}" != "1" ]; then
  export TRACEFORGE_NATIVE_SERVER_URL="https://api.traceforge.space"
  unset TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE || :
  unset TRACEFORGE_NATIVE_REVIEWER_TOKEN_FILE || :
  unset TRACEFORGE_NATIVE_PROXY_SIGNING_SECRET_FILE || :
  TRACEFORGE_NATIVE_CREDENTIAL_ROOT="$TRACEFORGE_STATE_ROOT/credentials"
  python3 - "$TRACEFORGE_NATIVE_CREDENTIAL_ROOT" <<'PY' || fail "native credential directory is not private"
import os
import stat
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    info = path.lstat()
except FileNotFoundError:
    path.mkdir(mode=0o700, parents=False)
    os.chmod(path, 0o700)
    info = path.lstat()
if (
    path.is_symlink()
    or not stat.S_ISDIR(info.st_mode)
    or stat.S_IMODE(info.st_mode) != 0o700
    or info.st_uid != os.getuid()
):
    raise SystemExit(1)
PY
  TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE="$TRACEFORGE_NATIVE_CREDENTIAL_ROOT/operator-token"
  TRACEFORGE_NATIVE_LINUX_CREDENTIAL_FILE="$TRACEFORGE_NATIVE_CREDENTIAL_ROOT/device-v1.json"
  export TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE
  export TRACEFORGE_NATIVE_LINUX_CREDENTIAL_FILE
  [ -f "$SERVICE_SCRIPT" ] || fail "native service relay is missing: $SERVICE_SCRIPT"
  if python3 "$SERVICE_SCRIPT" --prepare-linux-activation \
      --credential-file "$TRACEFORGE_NATIVE_LINUX_CREDENTIAL_FILE" \
      --token-file "$TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE" >/dev/null 2>&1; then
    unset TRACEFORGE_NATIVE_ACTIVATION_REQUIRED || :
  else
    # Missing, expired, or revoked activation must not hide the application.
    # The tabless AI workbench remains available and performs the one-time
    # claim flow in process; managed requests remain fail-closed until then.
    export TRACEFORGE_NATIVE_ACTIVATION_REQUIRED=1
  fi
fi

# A clean TraceForge install owns a clean KiCad profile. Leaving that profile
# completely empty makes upstream KiCad place its stock first-run wizard over
# the TraceForge workspace, which is confusing and blocks project intake.
# Seed only upstream defaults and package-local library-table pointers; never
# overwrite an existing user profile. TraceForge's own onboarding remains in
# the native agent pane where provider and workspace state can be explained.
TRACEFORGE_KICAD_PROFILE="$TRACEFORGE_CONFIG_ROOT/10.0"
mkdir -p "$TRACEFORGE_KICAD_PROFILE" || fail "TraceForge KiCad profile cannot be created"
python3 - "$TRACEFORGE_KICAD_PROFILE" "$PREFIX" <<'PY' || exit 78
import json
import os
import sys
from pathlib import Path

profile = Path(sys.argv[1])
prefix = Path(sys.argv[2])
common = profile / "kicad_common.json"
if not common.exists():
    temporary = profile / ".kicad_common.json.traceforge-new"
    document = {
        "appearance": {"icon_theme": 2, "toolbar_icon_size": 24},
        "do_not_show_again": {
            "data_collection_prompt": True,
            "update_check_prompt": True,
        },
        "meta": {"version": 6},
        "session": {"remember_open_files": False},
    }
    temporary.write_text(
        json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    os.chmod(temporary, 0o600)
    temporary.replace(common)

tables = {
    "design-block-lib-table": "design_block_lib_table",
    "fp-lib-table": "fp_lib_table",
    "sym-lib-table": "sym_lib_table",
}
for filename, root in tables.items():
    target = profile / filename
    if target.exists():
        continue
    packaged = prefix / "share" / "kicad" / "template" / filename
    if packaged.is_file():
        body = (
            f"({root}\n"
            "\t(version 7)\n"
            f'\t(lib (name "KiCad") (type "Table") (uri "{packaged}") '
            '(options "") (descr "KiCad Default Libraries"))\n'
            ")\n"
        )
    else:
        # The relocatable package may intentionally omit the large stock
        # libraries.  KiCad considers a missing global table unfinished setup,
        # while a valid empty table is a complete explicit choice.  Seed the
        # latter so the stock wizard cannot cover TraceForge on first launch.
        body = f"({root}\n\t(version 7)\n)\n"
    temporary = profile / f".{filename}.traceforge-new"
    temporary.write_text(body, encoding="utf-8")
    os.chmod(temporary, 0o600)
    temporary.replace(target)
PY

# KiCad uses a global wx single-instance lock for each editor.  If another
# editor already owns that lock, a second invocation is delivered over IPC and
# its positional project argument is ignored; that can silently display an
# unrelated project or an untitled document.  Refuse the ambiguous handoff and
# give onboarding a truthful recovery path instead of pretending this launch
# bound the requested project.
# KiCad's singleton lock is global and the editor does not honor a custom
# instance directory.  A product launch must therefore always inspect the
# real global lock; allowing an environment override would silently forward
# the requested project into an unrelated editor and recreate the exact
# blank/untitled intake failure this guard is meant to prevent.  Hermetic
# launcher tests may inject a temporary directory, but only in explicit test
# mode and never in a packaged user launch.
if [ "${TRACEFORGE_LAUNCH_TEST_MODE:-0}" = "1" ]; then
  TRACEFORGE_KICAD_INSTANCE_DIR="${TRACEFORGE_KICAD_INSTANCE_DIR:-/tmp/org.kicad.kicad/instances}"
else
  TRACEFORGE_KICAD_INSTANCE_DIR="/tmp/org.kicad.kicad/instances"
fi
TRACEFORGE_KICAD_INSTANCE_LOCK="$TRACEFORGE_KICAD_INSTANCE_DIR/${EDITOR_TARGET}-10.0"
if [ -e "$TRACEFORGE_KICAD_INSTANCE_LOCK" ]; then
  LOCK_PID=$(tr -d '\000\r\n[:space:]' < "$TRACEFORGE_KICAD_INSTANCE_LOCK" 2>/dev/null || true)
  if ! printf '%s' "$LOCK_PID" | grep -Eq '^[0-9]+$'; then
    fail "KiCad $EDITOR_TARGET instance lock is malformed; close stale KiCad state and retry"
  fi
  if kill -0 "$LOCK_PID" 2>/dev/null; then
    fail "another KiCad $EDITOR_TARGET instance is already running (pid $LOCK_PID); close it before opening this project"
  fi
  # Preserve a dead lock before removing it. This is bounded generated state,
  # not user data, and makes stale-lock recovery auditable without forwarding
  # the requested project into an unknown editor process.
  STALE_LOCK_ARCHIVE="$TRACEFORGE_STATE_ROOT/stale-instance-locks/${EDITOR_TARGET}-10.0.$LOCK_PID.$$.lock"
  mkdir -p "$(dirname "$STALE_LOCK_ARCHIVE")" || fail "stale KiCad instance-lock archive cannot be created"
  cp -p "$TRACEFORGE_KICAD_INSTANCE_LOCK" "$STALE_LOCK_ARCHIVE" 2>/dev/null || fail "stale KiCad instance lock cannot be preserved"
  rm -f "$TRACEFORGE_KICAD_INSTANCE_LOCK" || fail "stale KiCad instance lock cannot be retired"
fi

LAUNCH_NONCE=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n') || fail "launch nonce generation failed"
printf '%s\n' "$LAUNCH_NONCE" | grep -Eq '^[0-9a-f]{32}$' || fail "launch nonce is invalid"
export TRACEFORGE_NATIVE_LAUNCH_NONCE="$LAUNCH_NONCE"
# Authenticate every editor-to-sidecar socket, including read-only requests.
# The value is per launch, non-persistent, and shared only through the child
# environment.  Windows already establishes the same boundary in launch.go.
export TRACEFORGE_NATIVE_HOST_SERVICE_NONCE="$LAUNCH_NONCE"
if [ -n "${TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT:-}" ]; then
  PREFLIGHT_JSON=$(python3 "$PREFLIGHT" \
    --manifest "$MANIFEST" --bridge "$BRIDGE" --editor "$EDITOR" --cli "$CLI" \
    --editor-target "$EDITOR_TARGET" \
    --platform linux --launch-nonce "$LAUNCH_NONCE" \
    --output "$TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT") || fail "launch preflight failed"
else
PREFLIGHT_JSON=$(python3 "$PREFLIGHT" \
    --manifest "$MANIFEST" --bridge "$BRIDGE" --editor "$EDITOR" --cli "$CLI" \
    --editor-target "$EDITOR_TARGET" \
    --platform linux --launch-nonce "$LAUNCH_NONCE" \
    --output "${TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT:-$TRACEFORGE_STATE_ROOT/preflight-$LAUNCH_NONCE.json}") || fail "launch preflight failed"
fi
PREFLIGHT_RECEIPT="${TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT:-$TRACEFORGE_STATE_ROOT/preflight-$LAUNCH_NONCE.json}"
export TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT="$PREFLIGHT_RECEIPT"
export TRACEFORGE_NATIVE_PREFLIGHT_RECEIPT_JSON="$PREFLIGHT_JSON"
export TRACEFORGE_NATIVE_LOADED_RECEIPT="${TRACEFORGE_NATIVE_LOADED_RECEIPT:-$TRACEFORGE_STATE_ROOT/loaded-window-$LAUNCH_NONCE.json}"

CLI_VERSION=$($CLI --version 2>&1 | head -n 1) || fail "package-owned kicad-cli self-identification failed"
printf '%s\n' "$CLI_VERSION" | grep -Eq '(^|[^0-9])10\.0\.5([^0-9]|$)' || fail "package-owned kicad-cli is not KiCad 10.0.5: $CLI_VERSION"

export TRACEFORGE_KICAD_VERSION=10.0.5
export TRACEFORGE_NATIVE_HOST_MODE=compiled_kicad_aui
export TRACEFORGE_NATIVE_HOST_INSTANCE_ID="$LAUNCH_NONCE"
TRACEFORGE_NATIVE_HOST_SOURCE_IDENTITY_SHA256=$(python3 - "$PREFLIGHT_RECEIPT" <<'PY'
import json
import sys

value = json.load(open(sys.argv[1], encoding="utf-8"))
digest = value.get("host_payload_sha256", "")
if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
    raise SystemExit(78)
print(digest)
PY
) || fail "native host payload identity is unavailable"
export TRACEFORGE_NATIVE_HOST_SOURCE_IDENTITY_SHA256
# The native editor and relay do not need ambient model-provider credentials.
# Leaving these variables in the process tree exposes unrelated developer
# accounts to crash reporters and child tools.  Managed service credentials
# remain server-side; the private Codex developer launcher creates its own
# independently allowlisted environment and never enters this product path.
unset OPENAI_API_KEY OPENROUTER_API_KEY ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN || :
unset CODEX_HOME CODEX_API_KEY CODEX_ACCESS_TOKEN || :
unset TRACEFORGE_CODEX_ACCOUNT TRACEFORGE_CODEX_ROUTER_HOME || :
unset TRACEFORGE_CODEX_REAL_BINARY TRACEFORGE_CODEX_ROUTER_WRAPPER || :
unset TRACEFORGE_CODEX_EXEC_WRAPPER || :
# Private journal configuration belongs to the owner-authenticated service,
# never to the GUI/relay (including an operator's own GUI).
unset TRACEFORGE_OPERATOR_WORKFLOW_FILE || :
# The native service endpoint is package-owned, not caller-configurable.  An
# inherited socket/TCP value would bypass the managed relay and let an
# unrelated local process impersonate the authenticated sidecar.  Preserve
# explicit test/candidate harness injection only.
if [ "${TRACEFORGE_LAUNCH_TEST_MODE:-0}" != "1" ] &&
   [ "${TRACEFORGE_CANDIDATE_REVIEW_ONLY:-0}" != "1" ]; then
  unset TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET TRACEFORGE_NATIVE_HOST_SERVICE_TCP || :
  # Private Codex and local-owner grants belong only to the developer runtime.
  # Never let a customer GUI/sidecar inherit them from its launching shell.
  unset TRACEFORGE_PRIVATE_CODEX_DEV TRACEFORGE_PRIVATE_CODEX_POOL_READY \
    TRACEFORGE_PRIVATE_CODEX_EXPECTED_UID TRACEFORGE_CODEX_ACCOUNT \
    TRACEFORGE_CODEX_ROUTER_HOME TRACEFORGE_OPERATOR_TOKEN \
    TRACEFORGE_OPERATOR_TOKEN_FILE TRACEFORGE_PRIVATE_REVIEWER_TOKEN_FILE \
    TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE TRACEFORGE_NATIVE_REVIEWER_TOKEN_FILE || :
  # The similarly named customer token is not a developer override. Rebind it
  # only to the protected store initialized above, never the inherited path.
  # Otherwise the sidecar cannot atomically persist a successful activation.
  if [ -n "${TRACEFORGE_NATIVE_CREDENTIAL_ROOT:-}" ] &&
     [ "${TRACEFORGE_NATIVE_LINUX_CREDENTIAL_FILE:-}" = "$TRACEFORGE_NATIVE_CREDENTIAL_ROOT/device-v1.json" ]; then
    TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE="$TRACEFORGE_NATIVE_CREDENTIAL_ROOT/operator-token"
    export TRACEFORGE_NATIVE_OPERATOR_TOKEN_FILE
  fi
fi
if [ "${TRACEFORGE_CANDIDATE_REVIEW_ONLY:-0}" != "1" ] &&
   [ -z "${TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET:-}" ] &&
   { [ -n "${TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE:-}" ] ||
     [ -n "${TRACEFORGE_NATIVE_SERVER_URL:-}" ]; }; then
  [ -f "$SERVICE_SCRIPT" ] || fail "native service relay is missing: $SERVICE_SCRIPT"
  if [ -n "${TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE:-}" ]; then
    [ -f "$TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE" ] ||
      fail "native service message file is missing: $TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE"
  fi
  # AF_UNIX paths are capped by the platform (typically 108 bytes). State
  # roots may be arbitrarily long, so keep only this ephemeral relay endpoint
  # in a fixed-length, user-owned directory. Durable receipts remain under the
  # configured state root.
  TRACEFORGE_NATIVE_SOCKET_DIR="/tmp/traceforge-kicad-$(id -u)"
  if [ -e "$TRACEFORGE_NATIVE_SOCKET_DIR" ]; then
    [ -d "$TRACEFORGE_NATIVE_SOCKET_DIR" ] && [ ! -L "$TRACEFORGE_NATIVE_SOCKET_DIR" ] ||
      fail "native service socket directory is not a real directory"
    [ "$(stat -c %u "$TRACEFORGE_NATIVE_SOCKET_DIR")" = "$(id -u)" ] ||
      fail "native service socket directory is not owned by the current user"
  else
    (umask 077 && mkdir "$TRACEFORGE_NATIVE_SOCKET_DIR") ||
      fail "native service socket directory could not be created"
  fi
  chmod 700 "$TRACEFORGE_NATIVE_SOCKET_DIR" ||
    fail "native service socket directory could not be secured"
  TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET="$TRACEFORGE_NATIVE_SOCKET_DIR/s-$LAUNCH_NONCE.sock"
  [ "${#TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET}" -lt 100 ] ||
    fail "native service socket path exceeds the safe AF_UNIX limit"
  export TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET
  : "${TRACEFORGE_NATIVE_ALLOW_MUTATIONS:=1}"
  export TRACEFORGE_NATIVE_ALLOW_MUTATIONS
  if [ -n "${TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE:-}" ]; then
    python3 "$SERVICE_SCRIPT" --socket "$TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET" \
      --message-file "$TRACEFORGE_NATIVE_HOST_SERVICE_MESSAGE_FILE" --parent-pid "$$" &
  else
    python3 "$SERVICE_SCRIPT" --socket "$TRACEFORGE_NATIVE_HOST_SERVICE_SOCKET" \
      --parent-pid "$$" &
  fi
  SERVICE_PID=$!
  # The relay is bounded to the editor PID and cannot outlive the user journey.
  export TRACEFORGE_NATIVE_SERVICE_RELAY_PID="$SERVICE_PID"
fi

exec "$EDITOR" "$@"
