noqt commited on
Commit
589cd1c
·
1 Parent(s): a09dd39

Repair release correctness and operational safety gates

Browse files
.github/workflows/ci.yml CHANGED
@@ -35,12 +35,17 @@ jobs:
35
  - name: Build release artifacts
36
  run: python scripts/build_release.py --output dist/github
37
 
 
 
 
 
 
38
  - name: Verify public release
39
  run: >-
40
  python scripts/verify_release.py
41
- --artifact dist/github/lumi-eggcracker-0.1.1.pyz
42
- --source-archive dist/github/lumi-eggcracker-0.1.1-source.zip
43
- --release-bundle dist/github/lumi-eggcracker-0.1.1-linux.zip
44
 
45
  - name: Upload tag artifacts
46
  if: startsWith(github.ref, 'refs/tags/v')
@@ -48,9 +53,9 @@ jobs:
48
  with:
49
  name: lumi-eggcracker-${{ github.ref_name }}
50
  path: |
51
- dist/github/lumi-eggcracker-0.1.1.pyz
52
- dist/github/lumi-eggcracker-0.1.1-source.zip
53
- dist/github/lumi-eggcracker-0.1.1-linux.zip
54
  dist/github/release-manifest.json
55
  dist/github/SHA256SUMS
56
  if-no-files-found: error
 
35
  - name: Build release artifacts
36
  run: python scripts/build_release.py --output dist/github
37
 
38
+ - name: Determine public version
39
+ id: version
40
+ shell: bash
41
+ run: echo "version=$(PYTHONPATH=src python -c 'from lumi_eggcracker import __version__; print(__version__)')" >> "$GITHUB_OUTPUT"
42
+
43
  - name: Verify public release
44
  run: >-
45
  python scripts/verify_release.py
46
+ --artifact dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}.pyz
47
+ --source-archive dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}-source.zip
48
+ --release-bundle dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}-linux.zip
49
 
50
  - name: Upload tag artifacts
51
  if: startsWith(github.ref, 'refs/tags/v')
 
53
  with:
54
  name: lumi-eggcracker-${{ github.ref_name }}
55
  path: |
56
+ dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}.pyz
57
+ dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}-source.zip
58
+ dist/github/lumi-eggcracker-${{ steps.version.outputs.version }}-linux.zip
59
  dist/github/release-manifest.json
60
  dist/github/SHA256SUMS
61
  if-no-files-found: error
CHANGELOG.md CHANGED
@@ -5,6 +5,10 @@
5
  - Add bounded Safetensors structural validation and exact pinned CPU PyTorch/ATen build-ID-pair recognition.
6
  - Migrate content catalogue groups to `MODEL_RUNTIME` in schema v3 while preserving GGUF/llama behavior.
7
  - Contain unapproved complete Safetensors/PyTorch matches autonomously, including converters and inspectors; partial matches survive.
 
 
 
 
8
 
9
  ## 0.3.0
10
 
 
5
  - Add bounded Safetensors structural validation and exact pinned CPU PyTorch/ATen build-ID-pair recognition.
6
  - Migrate content catalogue groups to `MODEL_RUNTIME` in schema v3 while preserving GGUF/llama behavior.
7
  - Contain unapproved complete Safetensors/PyTorch matches autonomously, including converters and inspectors; partial matches survive.
8
+ - Limit the active public catalogue to the two qualified content profiles; withhold unqualified name-only runtime entries.
9
+ - Bind executable approval hashing to the live `/proc/<pid>/exe` descriptor and PID/start-time identity.
10
+ - Tie supervisor heartbeats to recent successful scan completion and bound enforcement admission.
11
+ - Preflight cgroups before uninstall and validate every published release checksum.
12
 
13
  ## 0.3.0
14
 
LIMITATIONS.md CHANGED
@@ -1,9 +1,13 @@
1
  # Limitations
2
 
3
- Lumi Eggcracker 0.4.0 autonomously acts only on a complete match from its installed deterministic AI-runtime catalogue. Its content path supports a regular GGUF v2/v3 artifact combined with a qualified llama.cpp/GGML ELF runtime, or a regular Safetensors artifact combined with the exact pinned CPU PyTorch bridge/ATen ELF build-ID pair. The two evidence groups may be observed in one process or across a bounded related workload: the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup. Unrelated same-UID or common-init processes are not joined. There is no guarantee for evidence that escaped before observation, unobserved processes, or containerised or remote workloads. It does not recognise arbitrary, custom, fully stripped, encrypted or otherwise unlisted AI/agent workloads.
 
 
4
 
5
  The observer uses bounded `/proc` polling. It has no kernel execution hook, eBPF programme or guarantee that a process which forks, daemonises or exits before discovery can be reconstructed as one complete historical tree. A successful receipt proves the exact captured quarantine cgroup is empty.
6
 
 
 
7
  The product does not kill generic Python, Node.js, Java, shell, GPU-intensive, memory-intensive or networked processes based on those generic properties. It does not require or claim proof of inference: an unapproved converter, inspector, evaluator or trainer satisfying both evidence groups is an intended kill. It does not use behavioural modelling, telemetry upload, network isolation, credential isolation, filesystem isolation, malware prevention or EDR functions.
8
 
9
  Approvals are exact: UID, resolved executable identity and complete argv digest must all match. Changing any argument requires a new approval. Revoking an approval affects future detections, not a workload already running under that approval.
 
1
  # Limitations
2
 
3
+ Lumi Eggcracker 0.4.0 autonomously acts only on a complete match from its two active, publicly qualified content profiles. Its content path supports a regular GGUF v2/v3 artifact combined with a qualified llama.cpp/GGML ELF runtime, or a regular Safetensors artifact combined with the exact pinned CPU PyTorch bridge/ATen ELF build-ID pair. The two evidence groups may be observed in one process or across a bounded related workload: the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup. Unrelated same-UID or common-init processes are not joined. There is no guarantee for evidence that escaped before observation, unobserved processes, or containerised or remote workloads. It does not recognise arbitrary, custom, fully stripped, encrypted or otherwise unlisted AI/agent workloads.
4
+
5
+ Name-only profiles for Ollama, vLLM, TGI, LocalAI, llamafile and agent CLIs are intentionally not active in this release. They require exact invocation fixtures and launcher-identity qualification before they can become destructive profiles.
6
 
7
  The observer uses bounded `/proc` polling. It has no kernel execution hook, eBPF programme or guarantee that a process which forks, daemonises or exits before discovery can be reconstructed as one complete historical tree. A successful receipt proves the exact captured quarantine cgroup is empty.
8
 
9
+ The supervisor service protects home directories. Model files held open by a workload can still be inspected through its procfs descriptor, but models discovered only by a pathname under a protected home or cache have not been qualified as a release path.
10
+
11
  The product does not kill generic Python, Node.js, Java, shell, GPU-intensive, memory-intensive or networked processes based on those generic properties. It does not require or claim proof of inference: an unapproved converter, inspector, evaluator or trainer satisfying both evidence groups is an intended kill. It does not use behavioural modelling, telemetry upload, network isolation, credential isolation, filesystem isolation, malware prevention or EDR functions.
12
 
13
  Approvals are exact: UID, resolved executable identity and complete argv digest must all match. Changing any argument requires a new approval. Revoking an approval affects future detections, not a workload already running under that approval.
QUALIFICATION.md CHANGED
@@ -1,9 +1,9 @@
1
  # Qualification
2
 
3
- The 0.4.0 candidate is releasable only when its exact commit passes the complete 0.3.1 regression, strict Safetensors and PyTorch/ATen direct tests, the existing selected-workload matrix, the native autonomous-discovery matrix, the GGUF and Safetensors content-recognition matrices, and the combined detector self-protection matrix on one Ubuntu VM.
4
 
5
  Mandatory autonomous gates are: 100/100 unapproved fixture discoveries and complete tree kills, 100/100 unrelated-canary survivals, zero surviving bounded replacement attempts, zero reused-PID signals, 50/50 exact approved survivals, zero kills in the benign and partial-match matrices, zero workload policy/socket accesses, restart recovery, p95 qualifying-snapshot-to-stop below 100 ms, p95 fixture-start-to-stop below 500 ms, and p95 trigger-to-empty below 500 ms.
6
 
7
  The self-protection gates additionally require zero workload connections to each query, operator and administrative socket; zero workload replacement launches; root-only approval administration; restart recovery; a watchdog lost-heartbeat containment; a watchdog installed-file-digest containment; bounded supervisor/watchdog resources; and clean removal of both units and runtime directories.
8
 
9
- The candidate must also run five renamed-runner, extensionless-model unapproved/approved/unapproved real llama.cpp/Qwen sequences and five real pinned PyTorch/Safetensors sequences, 100 complete-profile kills per family, 100 canary survivals, 50 exact disguised approvals and at least 300 benign or partial model-handling launches with zero kills. It must cleanly install with discovery armed and completely uninstall. Evidence is specific to the tested commit and host; it does not establish universal AI identification or inference detection.
 
1
  # Qualification
2
 
3
+ The 0.4.0 candidate is releasable only when its exact commit passes the complete 0.3.1 regression, strict Safetensors and PyTorch/ATen direct tests, the existing selected-workload matrix, the native autonomous-discovery matrix, the GGUF and Safetensors content-recognition matrices, the combined detector self-protection matrix, and the host-overhead benchmark on one Ubuntu VM.
4
 
5
  Mandatory autonomous gates are: 100/100 unapproved fixture discoveries and complete tree kills, 100/100 unrelated-canary survivals, zero surviving bounded replacement attempts, zero reused-PID signals, 50/50 exact approved survivals, zero kills in the benign and partial-match matrices, zero workload policy/socket accesses, restart recovery, p95 qualifying-snapshot-to-stop below 100 ms, p95 fixture-start-to-stop below 500 ms, and p95 trigger-to-empty below 500 ms.
6
 
7
  The self-protection gates additionally require zero workload connections to each query, operator and administrative socket; zero workload replacement launches; root-only approval administration; restart recovery; a watchdog lost-heartbeat containment; a watchdog installed-file-digest containment; bounded supervisor/watchdog resources; and clean removal of both units and runtime directories.
8
 
9
+ The candidate must also run five renamed-runner, extensionless-model unapproved/approved/unapproved real llama.cpp/Qwen sequences and five real pinned PyTorch/Safetensors sequences, 100 complete-profile kills per family, 100 canary survivals, 50 exact disguised approvals and at least 300 benign or partial model-handling launches with zero kills. It must cleanly install with discovery armed and completely uninstall. Evidence is specific to the tested commit and host; it does not establish universal AI identification or inference detection. Only the two content profiles listed in the README are active release claims; other catalogue ideas remain unqualified research work.
README.md CHANGED
@@ -1,16 +1,22 @@
1
  # Lumi Eggcracker
2
 
3
- Lumi Eggcracker is a local Linux kill switch for unapproved, supported AI and agent runtimes.
4
 
5
- > Eggcracker monitors a Linux host for supported local AI workloads. It recognises installed fast-name profiles and qualified model/runtime combinations. When a complete match has no exact root-admin approval, it automatically stops the process, captures its discovered process tree in a root-owned cgroup, and kills that cgroup.
 
 
 
 
 
 
6
 
7
  There is no alert-only phase for an unapproved catalogue match. Containment begins with a pidfd stop signal; the explanation and receipt are written only after cgroup containment completes.
8
 
9
  ## What it does
10
 
11
  - continuously scans host processes and performs a startup scan before accepting control commands;
12
- - detects published local-runtime profiles including llama.cpp, Ollama, vLLM, Text Generation Inference, LocalAI, llamafile and selected agent CLIs;
13
- - recognises the qualified `content.gguf-llama` profile without depending on executable or model filename: a structurally valid GGUF v2/v3 artifact and either two llama.cpp/GGML ELF runtime markers or the exact pinned llama.cpp launcher build ID are both required;
14
  - recognises `content.safetensors-pytorch` when a structurally valid Safetensors artifact and the exact pinned CPU PyTorch bridge/ATen ELF build-ID pair appear in one process or across a bounded related workload (the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup); unrelated same-UID or common-init processes are not joined;
15
  - lets the configured operator approve one exact executable, UID and invocation before it is run;
16
  - automatically stops, captures and kills unapproved matches with `pidfd_send_signal` and cgroup-v2 `cgroup.kill`;
@@ -23,6 +29,14 @@ Eggcracker does not identify every possible AI implementation. Content recogniti
23
 
24
  A successful receipt proves the captured quarantine cgroup is empty. It does not prove that a process which escaped before detection never existed.
25
 
 
 
 
 
 
 
 
 
26
  ## Requirements
27
 
28
  - native Linux with systemd and unified cgroup v2;
@@ -41,7 +55,7 @@ eggcracker doctor
41
  eggcracker approvals
42
  ```
43
 
44
- An unapproved complete fast-name or content profile is killed automatically when it starts; Eggcracker does not pause for confirmation. To allow a known invocation, approve it before launch. The approval stores hashes, not its raw arguments:
45
 
46
  ```sh
47
  sudo eggcracker approve --name local-qwen --uid "$(id -u)" -- \
 
1
  # Lumi Eggcracker
2
 
3
+ **Deterministic containment for unapproved local AI workloads on Linux.**
4
 
5
+ Lumi Eggcracker is a privileged Linux enforcement daemon for a narrow,
6
+ published catalogue of locally observed AI workloads.
7
+
8
+ > Engineering preview: when a complete qualified match has no exact root approval,
9
+ > Eggcracker stops the process, captures the bounded related workload, and kills
10
+ > its root-owned cgroup. Validate this exact release in a disposable Ubuntu VM
11
+ > before installing it on a workstation or server.
12
 
13
  There is no alert-only phase for an unapproved catalogue match. Containment begins with a pidfd stop signal; the explanation and receipt are written only after cgroup containment completes.
14
 
15
  ## What it does
16
 
17
  - continuously scans host processes and performs a startup scan before accepting control commands;
18
+ - detects only the two publicly qualified content/runtime profiles below; unqualified name-only catalogue entries are not active in this release;
19
+ - recognises the qualified `content.gguf-llama` profile without depending on executable or model filename: a bounded plausible GGUF v2/v3 header and either two llama.cpp/GGML ELF runtime markers or the exact pinned llama.cpp launcher build ID are both required;
20
  - recognises `content.safetensors-pytorch` when a structurally valid Safetensors artifact and the exact pinned CPU PyTorch bridge/ATen ELF build-ID pair appear in one process or across a bounded related workload (the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup); unrelated same-UID or common-init processes are not joined;
21
  - lets the configured operator approve one exact executable, UID and invocation before it is run;
22
  - automatically stops, captures and kills unapproved matches with `pidfd_send_signal` and cgroup-v2 `cgroup.kill`;
 
29
 
30
  A successful receipt proves the captured quarantine cgroup is empty. It does not prove that a process which escaped before detection never existed.
31
 
32
+ ## Publicly qualified profiles
33
+
34
+ | Profile | Exact qualification | Active in 0.4.0 |
35
+ | --- | --- | --- |
36
+ | `content.gguf-llama` | Renamed llama.cpp runner, extensionless GGUF path, bounded GGUF header, qualified ELF identity | Yes |
37
+ | `content.safetensors-pytorch` | Pinned CPU PyTorch/ATen build IDs, valid contiguous Safetensors layout, real model smoke | Yes |
38
+ | Ollama, vLLM, TGI, LocalAI, llamafile and agent CLIs | Invocation-specific fixtures and launcher identity still require qualification | No |
39
+
40
  ## Requirements
41
 
42
  - native Linux with systemd and unified cgroup v2;
 
55
  eggcracker approvals
56
  ```
57
 
58
+ An unapproved complete qualified content profile is killed automatically when it starts; Eggcracker does not pause for confirmation. To allow a known invocation, approve it before launch. The approval stores hashes, not its raw arguments:
59
 
60
  ```sh
61
  sudo eggcracker approve --name local-qwen --uid "$(id -u)" -- \
RELEASE_NOTES.md CHANGED
@@ -1,6 +1,8 @@
1
  # Lumi Eggcracker 0.4.0
2
 
3
- 0.4.0 adds aggressive `content.safetensors-pytorch` recognition to the qualified 0.3.1 control plane. A valid bounded Safetensors header and the exact pinned CPU PyTorch/ATen ELF build-ID pair may appear in one process or across a bounded related workload: the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup. Unrelated same-UID or common-init processes are not joined. There is no guarantee for evidence that escaped before observation, unobserved processes, or containerised or remote workloads. An unapproved complete match is immediately contained without requiring proof of a forward pass. The three-socket approval boundaries, watchdog and direct cgroup.kill containment remain qualified release properties.
 
 
4
 
5
  The release also applies bounded memory, CPU, I/O, task and descriptor limits to the supervisor, watchdog and selected workloads. Complete unapproved matches continue to use pidfd stop/capture and direct `cgroup.kill` as the authoritative complete-tree kill primitive.
6
 
 
1
  # Lumi Eggcracker 0.4.0
2
 
3
+ 0.4.0 adds aggressive `content.safetensors-pytorch` recognition to the qualified 0.3.1 control plane. A valid bounded, contiguous Safetensors layout and the exact pinned CPU PyTorch/ATen ELF build-ID pair may appear in one process or across a bounded related workload: the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup. Unrelated same-UID or common-init processes are not joined. There is no guarantee for evidence that escaped before observation, unobserved processes, or containerised or remote workloads. An unapproved complete match is immediately contained without requiring proof of a forward pass. The three-socket approval boundaries, watchdog and direct cgroup.kill containment remain qualified release properties.
4
+
5
+ The active catalogue contains only the two content profiles qualified by native fixtures. Name-only entries for vLLM, Ollama, TGI, LocalAI, llamafile and agent CLIs are withheld until their normal launcher invocations and approval identities are tested. Executable identity is hashed through the live `/proc/<pid>/exe` descriptor, heartbeat emission requires recent scan completion, release verification derives the public version from release metadata, and uninstall refuses before stopping protection when owned cgroups are populated.
6
 
7
  The release also applies bounded memory, CPU, I/O, task and descriptor limits to the supervisor, watchdog and selected workloads. Complete unapproved matches continue to use pidfd stop/capture and direct `cgroup.kill` as the authoritative complete-tree kill primitive.
8
 
SECURITY_MODEL.md CHANGED
@@ -2,10 +2,12 @@
2
 
3
  The root-owned `lumi-eggcracker.service` is the only enforcement component. It reads the root-owned detector catalogue and observes bounded process facts from `/proc`. The control plane has three root-owned Unix sockets: the configured operator may use query and selected-workload sockets; only root can reach the approval-administration socket. A workload account remains a dedicated no-login unprivileged user with no supplementary groups and cannot access any control socket.
4
 
5
- An independent root-owned watchdog receives a monotonic authenticated heartbeat from the supervisor and periodically verifies the installed-file manifest. On a lost heartbeat or manifest mismatch it first kills only Eggcracker-owned workload and quarantine cgroups, records a post-containment watchdog receipt, then stops the supervisor. It cannot kill arbitrary host processes during a discovery outage. The supervisor and watchdog have bounded memory, task, CPU, I/O and file-descriptor limits; selected workloads receive explicit PID, memory, CPU, I/O and descriptor limits.
6
 
7
  For an unapproved complete catalogue match, Eggcracker revalidates PID plus start-time identity, sends `SIGSTOP` through a pidfd, stops descendants, moves the discovered tree into an exact child cgroup delegated to the supervisor, and writes `1` to `cgroup.kill`. Content profiles require two independently validated groups: bounded model content and bounded runtime binary evidence may be in one process or in a bounded related workload (the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup). Unrelated same-UID or common-init processes are not joined, and there is no guarantee for escaped, unobserved, containerised or remote workloads. The Safetensors/PyTorch profile does not claim inference; a converter or inspector with both groups is intentionally contained. It proves that cgroup hierarchy is empty before writing the detection receipt. Individual pidfd signals are the initial stop/capture mechanism; direct cgroup-v2 `cgroup.kill` remains the authoritative complete-tree kill primitive.
8
 
9
- An approval is an exact root-owned record of a UID, resolved executable device/inode and digest, plus complete argv digest. Approval administration is root-only. Raw process arguments and environment values are not written to approval or detection records.
 
 
10
 
11
  This is not a general sandbox, universal AI detector, host intrusion detector, malware detector, network isolator, credential isolator or EDR replacement. An unapproved workload can evade detection by using an unsupported content/runtime combination; the qualified content path is intentionally narrow and that boundary is documented rather than hidden.
 
2
 
3
  The root-owned `lumi-eggcracker.service` is the only enforcement component. It reads the root-owned detector catalogue and observes bounded process facts from `/proc`. The control plane has three root-owned Unix sockets: the configured operator may use query and selected-workload sockets; only root can reach the approval-administration socket. A workload account remains a dedicated no-login unprivileged user with no supplementary groups and cannot access any control socket.
4
 
5
+ An independent root-owned watchdog receives a monotonic authenticated heartbeat from the supervisor and periodically verifies the installed-file manifest. On a lost heartbeat or manifest mismatch it first kills only Eggcracker-owned workload and quarantine cgroups, records a post-containment watchdog receipt, then stops the supervisor. It cannot kill arbitrary host processes during a discovery outage. The supervisor and watchdog have bounded memory, task, CPU, I/O and file-descriptor limits; selected workloads receive explicit PID, memory, CPU, I/O and descriptor limits. Discovery admission is bounded so a burst of matches cannot create an unbounded number of enforcement threads.
6
 
7
  For an unapproved complete catalogue match, Eggcracker revalidates PID plus start-time identity, sends `SIGSTOP` through a pidfd, stops descendants, moves the discovered tree into an exact child cgroup delegated to the supervisor, and writes `1` to `cgroup.kill`. Content profiles require two independently validated groups: bounded model content and bounded runtime binary evidence may be in one process or in a bounded related workload (the same unprivileged UID with a live direct parent/child or sibling relation, or one exact Eggcracker-owned workload cgroup). Unrelated same-UID or common-init processes are not joined, and there is no guarantee for escaped, unobserved, containerised or remote workloads. The Safetensors/PyTorch profile does not claim inference; a converter or inspector with both groups is intentionally contained. It proves that cgroup hierarchy is empty before writing the detection receipt. Individual pidfd signals are the initial stop/capture mechanism; direct cgroup-v2 `cgroup.kill` remains the authoritative complete-tree kill primitive.
8
 
9
+ An approval is an exact root-owned record of a UID, resolved executable device/inode and digest, plus complete argv digest. During discovery, the supervisor hashes the live `/proc/<pid>/exe` descriptor and rechecks PID/start-time and descriptor metadata before using the digest for approval. If the executable cannot be hashed, the candidate remains unapproved and is contained. Approval administration is root-only. Raw process arguments and environment values are not written to approval or detection records.
10
+
11
+ Heartbeat emission is tied to recent successful discovery completion, not merely to a live worker thread. A blocked or repeatedly failing scan therefore stops heartbeats and lets the independent watchdog apply its bounded fail-closed recovery.
12
 
13
  This is not a general sandbox, universal AI detector, host intrusion detector, malware detector, network isolator, credential isolator or EDR replacement. An unapproved workload can evade detection by using an unsupported content/runtime combination; the qualified content path is intentionally narrow and that boundary is documented rather than hidden.
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "lumi-eggcracker"
7
- version = "0.4.0"
8
  description = "A local Linux kill switch for unapproved supported AI and agent runtimes"
9
  readme = "README.md"
10
  requires-python = ">=3.11"
@@ -27,6 +27,9 @@ eggcracker = "lumi_eggcracker.cli:main"
27
  [tool.setuptools]
28
  package-dir = {"" = "src"}
29
 
 
 
 
30
  [tool.setuptools.packages.find]
31
  where = ["src"]
32
 
 
4
 
5
  [project]
6
  name = "lumi-eggcracker"
7
+ dynamic = ["version"]
8
  description = "A local Linux kill switch for unapproved supported AI and agent runtimes"
9
  readme = "README.md"
10
  requires-python = ">=3.11"
 
27
  [tool.setuptools]
28
  package-dir = {"" = "src"}
29
 
30
+ [tool.setuptools.dynamic]
31
+ version = {attr = "lumi_eggcracker.__version__"}
32
+
33
  [tool.setuptools.packages.find]
34
  where = ["src"]
35
 
scripts/build_release.py CHANGED
@@ -119,6 +119,7 @@ def main() -> int:
119
  ROOT / "scripts" / "run_content_adversarial_matrix.py": "scripts/run_content_adversarial_matrix.py",
120
  ROOT / "scripts" / "self_validate.py": "scripts/self_validate.py",
121
  ROOT / "scripts" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
 
122
  }
123
  with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
124
  for path, name in release_files.items():
 
119
  ROOT / "scripts" / "run_content_adversarial_matrix.py": "scripts/run_content_adversarial_matrix.py",
120
  ROOT / "scripts" / "self_validate.py": "scripts/self_validate.py",
121
  ROOT / "scripts" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
122
+ ROOT / "scripts" / "verify_evidence.py": "scripts/verify_evidence.py",
123
  }
124
  with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
125
  for path, name in release_files.items():
scripts/install.py CHANGED
@@ -18,7 +18,6 @@ import zipfile
18
  from pathlib import Path
19
  from typing import Any
20
 
21
- VERSION = "0.4.0"
22
  LIB = Path("/usr/local/lib/lumi-eggcracker")
23
  BIN = Path("/usr/local/bin/eggcracker")
24
  ETC = Path("/etc/lumi-eggcracker")
@@ -62,8 +61,15 @@ def manifest_for(artifact: Path) -> dict[str, Any]:
62
  expected = {"artifact", "sha256", "source_archive", "source_archive_sha256", "source_commit", "version"}
63
  if set(value) != expected or value["artifact"] != artifact.name or value["sha256"] != digest(artifact):
64
  raise RuntimeError("release artifact identity does not match manifest")
65
- if value["version"] != VERSION or len(value["source_commit"]) != 40:
 
 
 
 
66
  raise RuntimeError("release manifest version or source identity is invalid")
 
 
 
67
  return value
68
 
69
 
 
18
  from pathlib import Path
19
  from typing import Any
20
 
 
21
  LIB = Path("/usr/local/lib/lumi-eggcracker")
22
  BIN = Path("/usr/local/bin/eggcracker")
23
  ETC = Path("/etc/lumi-eggcracker")
 
61
  expected = {"artifact", "sha256", "source_archive", "source_archive_sha256", "source_commit", "version"}
62
  if set(value) != expected or value["artifact"] != artifact.name or value["sha256"] != digest(artifact):
63
  raise RuntimeError("release artifact identity does not match manifest")
64
+ if (
65
+ not isinstance(value["version"], str)
66
+ or not value["version"]
67
+ or len(value["source_commit"]) != 40
68
+ ):
69
  raise RuntimeError("release manifest version or source identity is invalid")
70
+ version_check = run(["/usr/bin/python3", str(artifact), "version"])
71
+ if version_check.returncode or version_check.stdout.strip() != value["version"]:
72
+ raise RuntimeError("release artifact version does not match manifest")
73
  return value
74
 
75
 
scripts/prepare_ai_smoke.py CHANGED
@@ -130,7 +130,7 @@ def download_model(destination: Path) -> None:
130
  temporary.unlink(missing_ok=True)
131
  value = hashlib.sha256()
132
  size = 0
133
- request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker-0.4.0"})
134
  try:
135
  with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
136
  if not response.url.startswith("https://"):
 
130
  temporary.unlink(missing_ok=True)
131
  value = hashlib.sha256()
132
  size = 0
133
+ request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker"})
134
  try:
135
  with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
136
  if not response.url.startswith("https://"):
scripts/prepare_safetensors_smoke.py CHANGED
@@ -28,7 +28,7 @@ def digest(path: Path) -> str:
28
  def download(url: str, destination: Path) -> None:
29
  if not url.startswith("https://"):
30
  raise RuntimeError("external assets must use HTTPS")
31
- request = urllib.request.Request(url, headers={"User-Agent": "Lumi-Eggcracker-0.4.0"})
32
  with urllib.request.urlopen(request, timeout=120) as response, destination.open("wb") as handle:
33
  while True:
34
  block = response.read(1024 * 1024)
 
28
  def download(url: str, destination: Path) -> None:
29
  if not url.startswith("https://"):
30
  raise RuntimeError("external assets must use HTTPS")
31
+ request = urllib.request.Request(url, headers={"User-Agent": "Lumi-Eggcracker"})
32
  with urllib.request.urlopen(request, timeout=120) as response, destination.open("wb") as handle:
33
  while True:
34
  block = response.read(1024 * 1024)
scripts/uninstall.py CHANGED
@@ -36,6 +36,12 @@ def run(argv: list[str]) -> subprocess.CompletedProcess[str]:
36
  return subprocess.run(argv, capture_output=True, text=True, check=False, timeout=60)
37
 
38
 
 
 
 
 
 
 
39
  def owned_cgroups_empty() -> bool:
40
  root = Path("/sys/fs/cgroup/system.slice")
41
  if not root.is_dir():
@@ -85,34 +91,48 @@ def main() -> int:
85
  path = Path(name)
86
  if path.is_symlink() or not path.is_file() or digest(path) != expected:
87
  raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
88
- run(["/usr/bin/systemctl", "disable", "--now", SUPERVISOR])
89
- run(["/usr/bin/systemctl", "disable", "--now", WATCHDOG])
90
  if not owned_cgroups_empty() or not quarantine_empty():
91
  raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
92
- run(["/usr/bin/systemctl", "reset-failed", SUPERVISOR])
93
- run(["/usr/bin/systemctl", "reset-failed", WATCHDOG])
94
- for path in (UNIT, WATCHDOG_UNIT, BIN, LIB, ETC, STATE, RUNTIME, WATCHDOG_RUNTIME):
95
- if path.exists() and not path.is_symlink():
96
- shutil.rmtree(path) if path.is_dir() else path.unlink()
97
- if manifest.get("created_workload_user"):
98
- try:
99
- account = pwd.getpwnam(str(manifest["workload_user"]))
100
- except KeyError:
101
- account = None
102
- if account and account.pw_uid == manifest.get("workload_uid"):
103
- result = run(["/usr/sbin/userdel", account.pw_name])
104
- if result.returncode:
105
- raise SystemExit(result.stderr.strip() or "cannot remove created workload account")
106
- if manifest.get("created_workload_group"):
107
- try:
108
- group = grp.getgrnam(str(manifest.get("workload_group", "")))
109
- except KeyError:
110
- group = None
111
- if group:
112
- result = run(["/usr/sbin/groupdel", group.gr_name])
113
- if result.returncode:
114
- raise SystemExit(result.stderr.strip() or "cannot remove created workload group")
115
- run(["/usr/bin/systemctl", "daemon-reload"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  print(json.dumps({"result": "UNINSTALLED"}, sort_keys=True))
117
  return 0
118
 
 
36
  return subprocess.run(argv, capture_output=True, text=True, check=False, timeout=60)
37
 
38
 
39
+ def require_success(argv: list[str]) -> None:
40
+ result = run(argv)
41
+ if result.returncode:
42
+ raise SystemExit(result.stderr.strip() or result.stdout.strip() or f"command failed: {argv[1]}")
43
+
44
+
45
  def owned_cgroups_empty() -> bool:
46
  root = Path("/sys/fs/cgroup/system.slice")
47
  if not root.is_dir():
 
91
  path = Path(name)
92
  if path.is_symlink() or not path.is_file() or digest(path) != expected:
93
  raise SystemExit(f"refusing uninstall because installed file drifted: {path}")
 
 
94
  if not owned_cgroups_empty() or not quarantine_empty():
95
  raise SystemExit("refusing uninstall with populated or uncertain Eggcracker cgroups")
96
+ supervisor_stopped = False
97
+ watchdog_stopped = False
98
+ try:
99
+ require_success(["/usr/bin/systemctl", "stop", SUPERVISOR])
100
+ supervisor_stopped = True
101
+ require_success(["/usr/bin/systemctl", "disable", SUPERVISOR])
102
+ require_success(["/usr/bin/systemctl", "stop", WATCHDOG])
103
+ watchdog_stopped = True
104
+ require_success(["/usr/bin/systemctl", "disable", WATCHDOG])
105
+ if not owned_cgroups_empty() or not quarantine_empty():
106
+ raise SystemExit("refusing uninstall because cgroups remained populated after stop")
107
+ require_success(["/usr/bin/systemctl", "reset-failed", SUPERVISOR])
108
+ require_success(["/usr/bin/systemctl", "reset-failed", WATCHDOG])
109
+ for path in (UNIT, WATCHDOG_UNIT, BIN, LIB, ETC, STATE, RUNTIME, WATCHDOG_RUNTIME):
110
+ if path.exists() and not path.is_symlink():
111
+ shutil.rmtree(path) if path.is_dir() else path.unlink()
112
+ if manifest.get("created_workload_user"):
113
+ try:
114
+ account = pwd.getpwnam(str(manifest["workload_user"]))
115
+ except KeyError:
116
+ account = None
117
+ if account and account.pw_uid == manifest.get("workload_uid"):
118
+ require_success(["/usr/sbin/userdel", account.pw_name])
119
+ if manifest.get("created_workload_group"):
120
+ try:
121
+ group = grp.getgrnam(str(manifest.get("workload_group", "")))
122
+ except KeyError:
123
+ group = None
124
+ if group:
125
+ require_success(["/usr/sbin/groupdel", group.gr_name])
126
+ require_success(["/usr/bin/systemctl", "daemon-reload"])
127
+ except BaseException:
128
+ # A refused or interrupted transaction must not leave protection
129
+ # disabled. Best-effort restoration is deliberately attempted for
130
+ # both units, regardless of which stop/disable operation failed.
131
+ if supervisor_stopped or watchdog_stopped:
132
+ run(["/usr/bin/systemctl", "daemon-reload"])
133
+ run(["/usr/bin/systemctl", "enable", "--now", WATCHDOG])
134
+ run(["/usr/bin/systemctl", "enable", "--now", SUPERVISOR])
135
+ raise
136
  print(json.dumps({"result": "UNINSTALLED"}, sort_keys=True))
137
  return 0
138
 
scripts/verify_evidence.py CHANGED
@@ -3,13 +3,24 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
6
  import json
 
7
  from pathlib import Path
8
 
9
  REQUIRED = {
10
- "environment.json", "catalogue.json", "autonomous-matrix.json",
11
- "real-ai-smoke.json", "benign-matrix.json", "install-cycle.json", "release-manifest.json",
12
- "SHA256SUMS", "report.md",
 
 
 
 
 
 
 
 
 
13
  }
14
 
15
 
@@ -21,20 +32,38 @@ def main() -> int:
21
  found = {item.name for item in args.evidence.iterdir()} if args.evidence.is_dir() else set()
22
  if found != REQUIRED:
23
  raise SystemExit(f"evidence pack files differ: {sorted(found)}")
24
- manifest = json.loads((args.evidence / "release-manifest.json").read_text(encoding="utf-8"))
25
- catalogue = json.loads((args.evidence / "catalogue.json").read_text(encoding="utf-8"))
26
- matrix = json.loads((args.evidence / "autonomous-matrix.json").read_text(encoding="utf-8"))
27
- smoke = json.loads((args.evidence / "real-ai-smoke.json").read_text(encoding="utf-8"))
28
- benign = json.loads((args.evidence / "benign-matrix.json").read_text(encoding="utf-8"))
 
 
29
  if (
30
- manifest.get("source_commit") != args.require_source_commit
31
- or matrix.get("result") != "PASS"
32
- or smoke.get("result") != "PASS"
33
- or not isinstance(catalogue.get("digest"), str)
34
- or benign.get("result") != "PASS"
35
- or len(smoke.get("repetitions", [])) != 5
36
  ):
37
  raise SystemExit("evidence does not meet release gate")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  print(json.dumps({"result": "PASS"}, sort_keys=True))
39
  return 0
40
 
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import hashlib
7
  import json
8
+ import re
9
  from pathlib import Path
10
 
11
  REQUIRED = {
12
+ "environment.json",
13
+ "doctor.json",
14
+ "real-ai-smoke.json",
15
+ "safetensors-ai-smoke.json",
16
+ "content-matrix.json",
17
+ "benign-model-matrix.json",
18
+ "content-adversarial-matrix.json",
19
+ "autonomous-regression.json",
20
+ "selected-workload-regression.json",
21
+ "validation.json",
22
+ "SHA256SUMS",
23
+ "report.md",
24
  }
25
 
26
 
 
32
  found = {item.name for item in args.evidence.iterdir()} if args.evidence.is_dir() else set()
33
  if found != REQUIRED:
34
  raise SystemExit(f"evidence pack files differ: {sorted(found)}")
35
+ values = {
36
+ name: json.loads((args.evidence / name).read_text(encoding="utf-8"))
37
+ for name in REQUIRED
38
+ if name.endswith(".json")
39
+ }
40
+ environment = values["environment.json"]
41
+ validation = values["validation.json"]
42
  if (
43
+ environment.get("source_commit") != args.require_source_commit
44
+ or validation.get("source_commit") != args.require_source_commit
45
+ or validation.get("result") != "PASS"
46
+ or not isinstance(environment.get("catalogue"), dict)
 
 
47
  ):
48
  raise SystemExit("evidence does not meet release gate")
49
+ for name, value in values.items():
50
+ if name in {"environment.json", "doctor.json", "validation.json"}:
51
+ continue
52
+ if value.get("result") != "PASS":
53
+ raise SystemExit(f"evidence job did not pass: {name}")
54
+ checksums: dict[str, str] = {}
55
+ for line in (args.evidence / "SHA256SUMS").read_text(encoding="ascii").splitlines():
56
+ fields = line.split(maxsplit=1)
57
+ if len(fields) != 2 or not re.fullmatch(r"[0-9a-f]{64}", fields[0]):
58
+ raise SystemExit("evidence checksum line is invalid")
59
+ checksums[fields[1].removeprefix("*")] = fields[0]
60
+ expected = {
61
+ path.name: hashlib.sha256(path.read_bytes()).hexdigest()
62
+ for path in args.evidence.iterdir()
63
+ if path.name != "SHA256SUMS"
64
+ }
65
+ if checksums != expected:
66
+ raise SystemExit("evidence checksums do not match")
67
  print(json.dumps({"result": "PASS"}, sort_keys=True))
68
  return 0
69
 
scripts/verify_release.py CHANGED
@@ -5,13 +5,12 @@ from __future__ import annotations
5
  import argparse
6
  import hashlib
7
  import json
 
8
  import subprocess
9
  import sys
10
  import zipfile
11
  from pathlib import Path
12
 
13
- VERSION = "0.4.0"
14
- PREFIX = f"lumi-eggcracker-{VERSION}/"
15
  FORBIDDEN = (
16
  "/mnt/" + "f/",
17
  "f" + ":\\",
@@ -41,6 +40,16 @@ def digest_bytes(value: bytes) -> str:
41
  return hashlib.sha256(value).hexdigest()
42
 
43
 
 
 
 
 
 
 
 
 
 
 
44
  def main() -> int:
45
  parser = argparse.ArgumentParser()
46
  parser.add_argument("--artifact", required=True, type=Path)
@@ -55,18 +64,28 @@ def main() -> int:
55
  leaks = [item for item in FORBIDDEN if item in text_from_zip(path)]
56
  if leaks:
57
  raise SystemExit(f"forbidden public artifact content in {path.name}: {leaks}")
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  result = subprocess.run(
59
  [sys.executable, str(args.artifact), "version"], capture_output=True, text=True, check=False
60
  )
61
- if result.returncode or result.stdout.strip() != VERSION:
62
  raise SystemExit("artifact version is inconsistent")
63
- manifest = json.loads(
64
- (args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8")
65
- )
66
- if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
67
  raise SystemExit("release manifest is inconsistent")
68
  expected = {
69
- PREFIX + name
70
  for name in (
71
  args.artifact.name,
72
  args.source_archive.name,
@@ -94,25 +113,27 @@ def main() -> int:
94
  "scripts/run_content_adversarial_matrix.py",
95
  "scripts/self_validate.py",
96
  "scripts/run_autonomous_matrix.py",
 
97
  )
98
  }
99
  with zipfile.ZipFile(args.release_bundle) as archive:
100
  if set(archive.namelist()) != expected:
101
  raise SystemExit("release bundle contents are inconsistent")
102
  if (
103
- digest_bytes(archive.read(PREFIX + args.artifact.name)) != manifest["sha256"]
104
- or digest_bytes(archive.read(PREFIX + args.source_archive.name))
105
  != manifest["source_archive_sha256"]
106
  ):
107
  raise SystemExit("bundled artifact digest is inconsistent")
108
- sums = (args.artifact.parent / "SHA256SUMS").read_text(encoding="utf-8")
109
- if (
110
- args.artifact.name not in sums
111
- or args.source_archive.name not in sums
112
- or args.release_bundle.name not in sums
113
- ):
114
- raise SystemExit("checksums do not cover every release asset")
115
- print(json.dumps({"result": "PASS", "version": VERSION}, sort_keys=True))
 
116
  return 0
117
 
118
 
 
5
  import argparse
6
  import hashlib
7
  import json
8
+ import re
9
  import subprocess
10
  import sys
11
  import zipfile
12
  from pathlib import Path
13
 
 
 
14
  FORBIDDEN = (
15
  "/mnt/" + "f/",
16
  "f" + ":\\",
 
40
  return hashlib.sha256(value).hexdigest()
41
 
42
 
43
+ def checksums(path: Path) -> dict[str, str]:
44
+ result: dict[str, str] = {}
45
+ for line in path.read_text(encoding="ascii").splitlines():
46
+ fields = line.split(maxsplit=1)
47
+ if len(fields) != 2 or not re.fullmatch(r"[0-9a-f]{64}", fields[0]):
48
+ raise SystemExit("checksums contain an invalid line")
49
+ result[fields[1].removeprefix("*")] = fields[0]
50
+ return result
51
+
52
+
53
  def main() -> int:
54
  parser = argparse.ArgumentParser()
55
  parser.add_argument("--artifact", required=True, type=Path)
 
64
  leaks = [item for item in FORBIDDEN if item in text_from_zip(path)]
65
  if leaks:
66
  raise SystemExit(f"forbidden public artifact content in {path.name}: {leaks}")
67
+ manifest = json.loads(
68
+ (args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8")
69
+ )
70
+ version = manifest.get("version")
71
+ if not isinstance(version, str) or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
72
+ raise SystemExit("release manifest version is invalid")
73
+ prefix = f"lumi-eggcracker-{version}/"
74
+ expected_names = {
75
+ "artifact": f"lumi-eggcracker-{version}.pyz",
76
+ "source_archive": f"lumi-eggcracker-{version}-source.zip",
77
+ }
78
+ if manifest.get("artifact") != expected_names["artifact"] or manifest.get("source_archive") != expected_names["source_archive"]:
79
+ raise SystemExit("release manifest artifact names are inconsistent")
80
  result = subprocess.run(
81
  [sys.executable, str(args.artifact), "version"], capture_output=True, text=True, check=False
82
  )
83
+ if result.returncode or result.stdout.strip() != version:
84
  raise SystemExit("artifact version is inconsistent")
85
+ if manifest.get("artifact") != args.artifact.name:
 
 
 
86
  raise SystemExit("release manifest is inconsistent")
87
  expected = {
88
+ prefix + name
89
  for name in (
90
  args.artifact.name,
91
  args.source_archive.name,
 
113
  "scripts/run_content_adversarial_matrix.py",
114
  "scripts/self_validate.py",
115
  "scripts/run_autonomous_matrix.py",
116
+ "scripts/verify_evidence.py",
117
  )
118
  }
119
  with zipfile.ZipFile(args.release_bundle) as archive:
120
  if set(archive.namelist()) != expected:
121
  raise SystemExit("release bundle contents are inconsistent")
122
  if (
123
+ digest_bytes(archive.read(prefix + args.artifact.name)) != manifest["sha256"]
124
+ or digest_bytes(archive.read(prefix + args.source_archive.name))
125
  != manifest["source_archive_sha256"]
126
  ):
127
  raise SystemExit("bundled artifact digest is inconsistent")
128
+ parsed_sums = checksums(args.artifact.parent / "SHA256SUMS")
129
+ expected_sums = {
130
+ args.artifact.name: digest_bytes(args.artifact.read_bytes()),
131
+ args.source_archive.name: digest_bytes(args.source_archive.read_bytes()),
132
+ args.release_bundle.name: digest_bytes(args.release_bundle.read_bytes()),
133
+ }
134
+ if parsed_sums != expected_sums:
135
+ raise SystemExit("checksums do not match the published release assets")
136
+ print(json.dumps({"result": "PASS", "version": version}, sort_keys=True))
137
  return 0
138
 
139
 
src/lumi_eggcracker/approvals.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  import re
6
  import time
7
  from pathlib import Path
@@ -78,13 +79,33 @@ def load_all(root: Path) -> list[dict[str, Any]]:
78
  return values
79
 
80
 
81
- def approved(snapshot: Any, digest: str, approvals: list[dict[str, Any]]) -> bool:
 
 
 
 
 
 
82
  command_hash = argv_digest(snapshot.argv)
83
- try:
84
- metadata = Path(snapshot.exe_path).stat(follow_symlinks=False)
85
- except OSError:
86
- return False
87
- return any(item["uid"] == snapshot.uid and item["executable"] == snapshot.exe_path and item["executable_device"] == metadata.st_dev and item["executable_inode"] == metadata.st_ino and item["executable_sha256"] == digest and item["argv_count"] == len(snapshot.argv) and item["argv_sha256"] == command_hash for item in approvals)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
 
90
  def revoke(root: Path, name: str) -> dict[str, Any]:
 
2
 
3
  from __future__ import annotations
4
 
5
+ import os
6
  import re
7
  import time
8
  from pathlib import Path
 
79
  return values
80
 
81
 
82
+ def approved(
83
+ snapshot: Any,
84
+ digest: str,
85
+ approvals: list[dict[str, Any]],
86
+ *,
87
+ executable_metadata: os.stat_result | tuple[int, int] | None = None,
88
+ ) -> bool:
89
  command_hash = argv_digest(snapshot.argv)
90
+ if executable_metadata is None:
91
+ try:
92
+ metadata = Path(snapshot.exe_path).stat(follow_symlinks=False)
93
+ except OSError:
94
+ return False
95
+ else:
96
+ metadata = executable_metadata
97
+ device = metadata.st_dev if hasattr(metadata, "st_dev") else metadata[0]
98
+ inode = metadata.st_ino if hasattr(metadata, "st_ino") else metadata[1]
99
+ return any(
100
+ item["uid"] == snapshot.uid
101
+ and item["executable"] == snapshot.exe_path
102
+ and item["executable_device"] == device
103
+ and item["executable_inode"] == inode
104
+ and item["executable_sha256"] == digest
105
+ and item["argv_count"] == len(snapshot.argv)
106
+ and item["argv_sha256"] == command_hash
107
+ for item in approvals
108
+ )
109
 
110
 
111
  def revoke(root: Path, name: str) -> dict[str, Any]:
src/lumi_eggcracker/artifacts.py CHANGED
@@ -146,6 +146,8 @@ def validate_safetensors_fd(descriptor: int) -> ArtifactEvidence:
146
  header = _read_exact(descriptor, header_length + 8)[8:]
147
  if len(header) != header_length:
148
  raise JsonInputError("Safetensors header is truncated")
 
 
149
  try:
150
  value = json.loads(header.decode("utf-8"), object_pairs_hook=_json_pairs)
151
  except (UnicodeDecodeError, json.JSONDecodeError, JsonInputError) as error:
@@ -165,7 +167,7 @@ def validate_safetensors_fd(descriptor: int) -> ArtifactEvidence:
165
  raise JsonInputError("Safetensors tensor count is invalid")
166
  data_start = 8 + header_length
167
  data_size = before.st_size - data_start
168
- previous_end = 0
169
  for name, tensor in value.items():
170
  if not isinstance(name, str) or not name or not isinstance(tensor, dict):
171
  raise JsonInputError("Safetensors tensor entry is invalid")
@@ -204,9 +206,19 @@ def validate_safetensors_fd(descriptor: int) -> ArtifactEvidence:
204
  ):
205
  raise JsonInputError("Safetensors data offsets are invalid")
206
  start, end = offsets
207
- if start > end or start < previous_end or end > data_size or end - start != required_bytes:
208
  raise JsonInputError("Safetensors data offsets do not match tensor shape")
 
 
 
 
 
 
 
 
209
  previous_end = end
 
 
210
  after = _regular(descriptor, minimum=8)
211
  if (before.st_dev, before.st_ino, before.st_size) != (
212
  after.st_dev,
 
146
  header = _read_exact(descriptor, header_length + 8)[8:]
147
  if len(header) != header_length:
148
  raise JsonInputError("Safetensors header is truncated")
149
+ if not header.startswith(b"{"):
150
+ raise JsonInputError("Safetensors header must begin with an object")
151
  try:
152
  value = json.loads(header.decode("utf-8"), object_pairs_hook=_json_pairs)
153
  except (UnicodeDecodeError, json.JSONDecodeError, JsonInputError) as error:
 
167
  raise JsonInputError("Safetensors tensor count is invalid")
168
  data_start = 8 + header_length
169
  data_size = before.st_size - data_start
170
+ ranges: list[tuple[int, int]] = []
171
  for name, tensor in value.items():
172
  if not isinstance(name, str) or not name or not isinstance(tensor, dict):
173
  raise JsonInputError("Safetensors tensor entry is invalid")
 
206
  ):
207
  raise JsonInputError("Safetensors data offsets are invalid")
208
  start, end = offsets
209
+ if start > end or end > data_size or end - start != required_bytes:
210
  raise JsonInputError("Safetensors data offsets do not match tensor shape")
211
+ ranges.append((start, end))
212
+ ranges.sort()
213
+ if not ranges or ranges[0][0] != 0:
214
+ raise JsonInputError("Safetensors data offsets contain a leading gap")
215
+ previous_end = 0
216
+ for start, end in ranges:
217
+ if start != previous_end:
218
+ raise JsonInputError("Safetensors data offsets contain a gap or overlap")
219
  previous_end = end
220
+ if previous_end != data_size:
221
+ raise JsonInputError("Safetensors data offsets leave trailing data")
222
  after = _regular(descriptor, minimum=8)
223
  if (before.st_dev, before.st_ino, before.st_size) != (
224
  after.st_dev,
src/lumi_eggcracker/client.py CHANGED
@@ -28,9 +28,15 @@ SOCKETS = {
28
 
29
 
30
  def _receive(connection: socket.socket) -> dict[str, Any]:
31
- header = connection.recv(4)
32
- if len(header) != 4:
33
- raise JsonInputError("truncated supervisor response")
 
 
 
 
 
 
34
  length = struct.unpack("!I", header)[0]
35
  if not 1 <= length <= MAX_FRAME:
36
  raise JsonInputError("invalid supervisor response frame")
 
28
 
29
 
30
  def _receive(connection: socket.socket) -> dict[str, Any]:
31
+ header_chunks: list[bytes] = []
32
+ remaining = 4
33
+ while remaining:
34
+ chunk = connection.recv(remaining)
35
+ if not chunk:
36
+ raise JsonInputError("truncated supervisor response")
37
+ header_chunks.append(chunk)
38
+ remaining -= len(chunk)
39
+ header = b"".join(header_chunks)
40
  length = struct.unpack("!I", header)[0]
41
  if not 1 <= length <= MAX_FRAME:
42
  raise JsonInputError("invalid supervisor response frame")
src/lumi_eggcracker/detector_catalogue.json CHANGED
@@ -1 +1 @@
1
- {"profiles":[{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llama.cpp","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"open_model_suffix","values":[".gguf"]}],"id":"llama.cpp-open-model","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["ollama"]},{"kind":"argv_token","values":["serve","runner"]}],"id":"ollama","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["vllm"]}],"id":"vllm-python","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["vllm"]}],"id":"vllm","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["text-generation-launcher","text-generation-server"]}],"id":"text-generation-inference","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["local-ai","localai"]},{"kind":"argv_token","values":["serve","run"]}],"id":"localai","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["llamafile"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llamafile","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-cli","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-python","path":"FAST_NAME"},{"id":"content.gguf-llama","path":"CONTENT","require_all_groups":[{"any":["gguf-v2","gguf-v3"],"group":"MODEL_CONTENT"},{"any":["llama-build-id","llama-elf"],"group":"MODEL_RUNTIME"}]},{"id":"content.safetensors-pytorch","path":"CONTENT","require_all_groups":[{"any":["safetensors-v1"],"group":"MODEL_CONTENT"},{"any":["pytorch-aten-pinned-cpu"],"group":"MODEL_RUNTIME"}]}],"schema_version":"lumi-eggcracker.detectors.v3"}
 
1
+ {"profiles":[{"id":"content.gguf-llama","path":"CONTENT","require_all_groups":[{"any":["gguf-v2","gguf-v3"],"group":"MODEL_CONTENT"},{"any":["llama-build-id","llama-elf"],"group":"MODEL_RUNTIME"}]},{"id":"content.safetensors-pytorch","path":"CONTENT","require_all_groups":[{"any":["safetensors-v1"],"group":"MODEL_CONTENT"},{"any":["pytorch-aten-pinned-cpu"],"group":"MODEL_RUNTIME"}]}],"schema_version":"lumi-eggcracker.detectors.v3"}
src/lumi_eggcracker/discovery.py CHANGED
@@ -83,14 +83,112 @@ def argv_digest(argv: tuple[str, ...] | list[str]) -> str:
83
 
84
 
85
  def executable_digest(path: Path) -> str:
86
- metadata = path.stat(follow_symlinks=False)
87
- if not stat.S_ISREG(metadata.st_mode):
88
- raise JsonInputError("detected executable is not a regular file")
89
- value = hashlib.sha256()
90
- with path.open("rb") as handle:
91
- for block in iter(lambda: handle.read(64 * 1024), b""):
 
 
 
 
92
  value.update(block)
93
- return value.hexdigest()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
 
96
  def _uid(raw: str) -> int:
 
83
 
84
 
85
  def executable_digest(path: Path) -> str:
86
+ """Hash a regular executable through one stable file descriptor."""
87
+ flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
88
+ descriptor = os.open(path, flags)
89
+ try:
90
+ before = os.fstat(descriptor)
91
+ if not stat.S_ISREG(before.st_mode):
92
+ raise JsonInputError("detected executable is not a regular file")
93
+ value = hashlib.sha256()
94
+ os.lseek(descriptor, 0, os.SEEK_SET)
95
+ for block in iter(lambda: os.read(descriptor, 64 * 1024), b""):
96
  value.update(block)
97
+ after = os.fstat(descriptor)
98
+ if (
99
+ before.st_dev,
100
+ before.st_ino,
101
+ before.st_size,
102
+ before.st_mtime_ns,
103
+ before.st_ctime_ns,
104
+ ) != (
105
+ after.st_dev,
106
+ after.st_ino,
107
+ after.st_size,
108
+ after.st_mtime_ns,
109
+ after.st_ctime_ns,
110
+ ):
111
+ raise JsonInputError("executable changed during hashing")
112
+ return value.hexdigest()
113
+ finally:
114
+ os.close(descriptor)
115
+
116
+
117
+ def executable_digest_for_identity(
118
+ value: ProcessIdentity, *, proc: Path = PROC
119
+ ) -> tuple[str, os.stat_result]:
120
+ """Hash the executable actually running for one PID/start-time identity.
121
+
122
+ ``/proc/<pid>/exe`` is opened directly so a renamed or replaced pathname
123
+ cannot make the supervisor hash a different file from the executing inode.
124
+ The identity and descriptor metadata are checked before and after hashing.
125
+ """
126
+ if identity(value.pid, proc=proc) != value:
127
+ raise JsonInputError("process identity changed before executable hashing")
128
+ descriptor = os.open(
129
+ proc / str(value.pid) / "exe", os.O_RDONLY | getattr(os, "O_CLOEXEC", 0)
130
+ )
131
+ try:
132
+ before = os.fstat(descriptor)
133
+ if not stat.S_ISREG(before.st_mode):
134
+ raise JsonInputError("running executable is not a regular file")
135
+ digest = hashlib.sha256()
136
+ os.lseek(descriptor, 0, os.SEEK_SET)
137
+ for block in iter(lambda: os.read(descriptor, 64 * 1024), b""):
138
+ digest.update(block)
139
+ after = os.fstat(descriptor)
140
+ if (
141
+ before.st_dev,
142
+ before.st_ino,
143
+ before.st_size,
144
+ before.st_mtime_ns,
145
+ before.st_ctime_ns,
146
+ ) != (
147
+ after.st_dev,
148
+ after.st_ino,
149
+ after.st_size,
150
+ after.st_mtime_ns,
151
+ after.st_ctime_ns,
152
+ ):
153
+ raise JsonInputError("running executable changed during hashing")
154
+ if identity(value.pid, proc=proc) != value:
155
+ raise JsonInputError("process identity changed during executable hashing")
156
+ return digest.hexdigest(), before
157
+ finally:
158
+ os.close(descriptor)
159
+
160
+
161
+ def executable_metadata_for_identity(
162
+ value: ProcessIdentity, *, proc: Path = PROC
163
+ ) -> os.stat_result:
164
+ """Return stable metadata for the live executable without hashing it."""
165
+ if identity(value.pid, proc=proc) != value:
166
+ raise JsonInputError("process identity changed before executable inspection")
167
+ descriptor = os.open(
168
+ proc / str(value.pid) / "exe", os.O_RDONLY | getattr(os, "O_CLOEXEC", 0)
169
+ )
170
+ try:
171
+ before = os.fstat(descriptor)
172
+ if not stat.S_ISREG(before.st_mode):
173
+ raise JsonInputError("running executable is not a regular file")
174
+ after = os.fstat(descriptor)
175
+ if (
176
+ before.st_dev,
177
+ before.st_ino,
178
+ before.st_size,
179
+ before.st_mtime_ns,
180
+ before.st_ctime_ns,
181
+ ) != (
182
+ after.st_dev,
183
+ after.st_ino,
184
+ after.st_size,
185
+ after.st_mtime_ns,
186
+ after.st_ctime_ns,
187
+ ) or identity(value.pid, proc=proc) != value:
188
+ raise JsonInputError("running executable changed during inspection")
189
+ return before
190
+ finally:
191
+ os.close(descriptor)
192
 
193
 
194
  def _uid(raw: str) -> int:
src/lumi_eggcracker/supervisor.py CHANGED
@@ -37,7 +37,13 @@ from .containment import (
37
  verify_empty,
38
  )
39
  from .detectors import Catalogue, DetectionMatch, load_catalogue, match, public_catalogue
40
- from .discovery import ProcessIdentity, ProcessSnapshot, executable_digest, scan
 
 
 
 
 
 
41
  from .elfmarkers import RuntimeEvidence
42
  from .elfmarkers import from_snapshot as runtime_from_snapshot
43
  from .jsonio import JsonInputError, load_regular_json
@@ -77,6 +83,9 @@ DETECTION_LIMIT = 1000
77
  RECENT_DISCOVERY_NS = 5_000_000_000
78
  CONTENT_SCAN_INTERVAL = 2
79
  MAX_CORRELATED_PROCESSES = 64
 
 
 
80
 
81
 
82
  @dataclass(frozen=True)
@@ -194,10 +203,12 @@ class Supervisor:
194
  self.discovery_active: set[ProcessIdentity] = set()
195
  self.discovery_done: dict[ProcessIdentity, int] = {}
196
  self.discovery_thread: threading.Thread | None = None
197
- self.digest_cache: dict[tuple[int, int, int, int], str] = {}
 
 
198
  self.observations = ObservationStore()
199
  self.content_scan_tick = 0
200
- self.last_scan_completed_ns = time.monotonic_ns()
201
  self.discovery_failures = 0
202
  self.heartbeat_sequence = 0
203
  self.last_heartbeat_sent = 0.0
@@ -440,13 +451,29 @@ class Supervisor:
440
  return result
441
 
442
  def _cached_executable_digest(self, snapshot: ProcessSnapshot) -> str:
443
- path = Path(snapshot.exe_path)
444
- metadata = path.stat(follow_symlinks=False)
445
- key = (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns)
 
 
 
 
 
446
  value = self.digest_cache.get(key)
447
  if value is None:
448
- value = executable_digest(path)
449
- self.digest_cache = {key: value}
 
 
 
 
 
 
 
 
 
 
 
450
  return value
451
 
452
  def _detection_path(self, event_id: str) -> Path:
@@ -462,6 +489,16 @@ class Supervisor:
462
  for path in records[DETECTION_LIMIT:]:
463
  path.unlink(missing_ok=True)
464
 
 
 
 
 
 
 
 
 
 
 
465
  def _detection_receipt(
466
  self,
467
  *,
@@ -472,7 +509,7 @@ class Supervisor:
472
  runtimes: tuple[RuntimeEvidence, ...],
473
  first_seen_ns: int,
474
  qualified_ns: int,
475
- executable_sha256: str,
476
  result: AdoptionResult | None,
477
  error: str | None,
478
  correlated: tuple[_EvidenceCandidate, ...] = (),
@@ -502,11 +539,17 @@ class Supervisor:
502
  "first_seen_monotonic_ns": first_seen_ns,
503
  "qualified_monotonic_ns": qualified_ns,
504
  }
 
 
 
 
 
 
505
  value: dict[str, Any] = {
506
  "catalogue_sha256": self.catalogue.digest,
507
  "detector": detector,
508
  "event_id": event_id,
509
- "executable": {"basename": snapshot.exe_basename, "sha256": executable_sha256},
510
  "observed": {
511
  "argv_count": len(snapshot.argv),
512
  "argv_sha256": hashlib.sha256("\0".join(snapshot.argv).encode("utf-8")).hexdigest(),
@@ -591,7 +634,7 @@ class Supervisor:
591
  runtimes: tuple[RuntimeEvidence, ...],
592
  first_seen_ns: int,
593
  qualified_ns: int,
594
- executable_sha256: str,
595
  event_id: str,
596
  pidfd: int | None = None,
597
  targets: set[ProcessIdentity] | None = None,
@@ -736,12 +779,23 @@ class Supervisor:
736
  continue
737
  qualified_ns = time.monotonic_ns()
738
  unapproved: list[_EvidenceCandidate] = []
 
739
  for candidate in group:
740
  try:
741
  executable_sha256 = self._cached_executable_digest(candidate.snapshot)
742
  except (JsonInputError, OSError):
 
 
743
  continue
744
- if not approved(candidate.snapshot, executable_sha256, approvals):
 
 
 
 
 
 
 
 
745
  unapproved.append(candidate)
746
  if not unapproved:
747
  continue
@@ -766,7 +820,7 @@ class Supervisor:
766
  with self.discovery_lock:
767
  self.discovery_active.difference_update(target_set)
768
  continue
769
- executable_sha256 = self._cached_executable_digest(snapshot)
770
  first_seen_ns = min(candidate.first_seen_ns for candidate in group)
771
  kwargs = {
772
  "targets": target_set,
@@ -787,28 +841,38 @@ class Supervisor:
787
  **kwargs,
788
  )
789
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790
  try:
791
- threading.Thread(
792
- target=self._enforce_discovery,
793
- args=(
794
- snapshot,
795
- detected,
796
- tuple(aggregate_content),
797
- tuple(aggregate_runtimes),
798
- first_seen_ns,
799
- qualified_ns,
800
- executable_sha256,
801
- event_id,
802
- pidfd,
803
- ),
804
- kwargs=kwargs,
805
- daemon=True,
806
- ).start()
807
  except RuntimeError:
808
- os.close(pidfd)
809
- with self.discovery_lock:
810
- self.discovery_active.difference_update(target_set)
811
- raise
812
 
813
  def _discovery_loop(self) -> None:
814
  while not self.stop_event.is_set():
@@ -829,6 +893,9 @@ class Supervisor:
829
  if (
830
  thread is None
831
  or not thread.is_alive()
 
 
 
832
  ):
833
  return
834
  self.heartbeat_sequence += 1
@@ -1264,7 +1331,9 @@ class Supervisor:
1264
  }
1265
  if action == "detections" and not args:
1266
  values: list[dict[str, Any]] = []
1267
- for path in sorted(self.detections.glob("*.json"), reverse=True):
 
 
1268
  try:
1269
  value = load_regular_json(path)
1270
  values.append(
 
37
  verify_empty,
38
  )
39
  from .detectors import Catalogue, DetectionMatch, load_catalogue, match, public_catalogue
40
+ from .discovery import (
41
+ ProcessIdentity,
42
+ ProcessSnapshot,
43
+ executable_digest_for_identity,
44
+ executable_metadata_for_identity,
45
+ scan,
46
+ )
47
  from .elfmarkers import RuntimeEvidence
48
  from .elfmarkers import from_snapshot as runtime_from_snapshot
49
  from .jsonio import JsonInputError, load_regular_json
 
83
  RECENT_DISCOVERY_NS = 5_000_000_000
84
  CONTENT_SCAN_INTERVAL = 2
85
  MAX_CORRELATED_PROCESSES = 64
86
+ SCAN_HEALTH_TIMEOUT_NS = 1_000_000_000
87
+ MAX_DISCOVERY_FAILURES = 3
88
+ MAX_ENFORCEMENT_TASKS = 16
89
 
90
 
91
  @dataclass(frozen=True)
 
203
  self.discovery_active: set[ProcessIdentity] = set()
204
  self.discovery_done: dict[ProcessIdentity, int] = {}
205
  self.discovery_thread: threading.Thread | None = None
206
+ self.digest_cache: dict[tuple[int, int, int, int, int], str] = {}
207
+ self.executable_metadata: dict[ProcessIdentity, tuple[int, int]] = {}
208
+ self.enforcement_slots = threading.BoundedSemaphore(MAX_ENFORCEMENT_TASKS)
209
  self.observations = ObservationStore()
210
  self.content_scan_tick = 0
211
+ self.last_scan_completed_ns = 0
212
  self.discovery_failures = 0
213
  self.heartbeat_sequence = 0
214
  self.last_heartbeat_sent = 0.0
 
451
  return result
452
 
453
  def _cached_executable_digest(self, snapshot: ProcessSnapshot) -> str:
454
+ metadata = executable_metadata_for_identity(snapshot.identity)
455
+ key = (
456
+ metadata.st_dev,
457
+ metadata.st_ino,
458
+ metadata.st_size,
459
+ metadata.st_mtime_ns,
460
+ metadata.st_ctime_ns,
461
+ )
462
  value = self.digest_cache.get(key)
463
  if value is None:
464
+ value, hashed_metadata = executable_digest_for_identity(snapshot.identity)
465
+ if (
466
+ hashed_metadata.st_dev,
467
+ hashed_metadata.st_ino,
468
+ hashed_metadata.st_size,
469
+ hashed_metadata.st_mtime_ns,
470
+ hashed_metadata.st_ctime_ns,
471
+ ) != key:
472
+ raise JsonInputError("executable changed during cached hashing")
473
+ self.digest_cache[key] = value
474
+ while len(self.digest_cache) > 256:
475
+ self.digest_cache.pop(next(iter(self.digest_cache)))
476
+ self.executable_metadata[snapshot.identity] = (metadata.st_dev, metadata.st_ino)
477
  return value
478
 
479
  def _detection_path(self, event_id: str) -> Path:
 
489
  for path in records[DETECTION_LIMIT:]:
490
  path.unlink(missing_ok=True)
491
 
492
+ def _detection_sort_key(self, path: Path) -> tuple[int, str]:
493
+ try:
494
+ value = load_regular_json(path)
495
+ observed = value.get("trigger", {}).get("observed_monotonic_ns", 0)
496
+ if isinstance(observed, int) and observed >= 0:
497
+ return observed, path.name
498
+ except (JsonInputError, OSError):
499
+ pass
500
+ return 0, path.name
501
+
502
  def _detection_receipt(
503
  self,
504
  *,
 
509
  runtimes: tuple[RuntimeEvidence, ...],
510
  first_seen_ns: int,
511
  qualified_ns: int,
512
+ executable_sha256: str | None,
513
  result: AdoptionResult | None,
514
  error: str | None,
515
  correlated: tuple[_EvidenceCandidate, ...] = (),
 
539
  "first_seen_monotonic_ns": first_seen_ns,
540
  "qualified_monotonic_ns": qualified_ns,
541
  }
542
+ executable_record: dict[str, Any] = {
543
+ "basename": snapshot.exe_basename,
544
+ "sha256": executable_sha256,
545
+ }
546
+ if executable_sha256 is None:
547
+ executable_record["digest_status"] = "UNAVAILABLE"
548
  value: dict[str, Any] = {
549
  "catalogue_sha256": self.catalogue.digest,
550
  "detector": detector,
551
  "event_id": event_id,
552
+ "executable": executable_record,
553
  "observed": {
554
  "argv_count": len(snapshot.argv),
555
  "argv_sha256": hashlib.sha256("\0".join(snapshot.argv).encode("utf-8")).hexdigest(),
 
634
  runtimes: tuple[RuntimeEvidence, ...],
635
  first_seen_ns: int,
636
  qualified_ns: int,
637
+ executable_sha256: str | None,
638
  event_id: str,
639
  pidfd: int | None = None,
640
  targets: set[ProcessIdentity] | None = None,
 
779
  continue
780
  qualified_ns = time.monotonic_ns()
781
  unapproved: list[_EvidenceCandidate] = []
782
+ executable_digests: dict[ProcessIdentity, str | None] = {}
783
  for candidate in group:
784
  try:
785
  executable_sha256 = self._cached_executable_digest(candidate.snapshot)
786
  except (JsonInputError, OSError):
787
+ executable_digests[candidate.snapshot.identity] = None
788
+ unapproved.append(candidate)
789
  continue
790
+ executable_digests[candidate.snapshot.identity] = executable_sha256
791
+ if not approved(
792
+ candidate.snapshot,
793
+ executable_sha256,
794
+ approvals,
795
+ executable_metadata=getattr(self, "executable_metadata", {}).get(
796
+ candidate.snapshot.identity
797
+ ),
798
+ ):
799
  unapproved.append(candidate)
800
  if not unapproved:
801
  continue
 
820
  with self.discovery_lock:
821
  self.discovery_active.difference_update(target_set)
822
  continue
823
+ executable_sha256 = executable_digests.get(snapshot.identity)
824
  first_seen_ns = min(candidate.first_seen_ns for candidate in group)
825
  kwargs = {
826
  "targets": target_set,
 
841
  **kwargs,
842
  )
843
  else:
844
+ task_args = (
845
+ snapshot,
846
+ detected,
847
+ tuple(aggregate_content),
848
+ tuple(aggregate_runtimes),
849
+ first_seen_ns,
850
+ qualified_ns,
851
+ executable_sha256,
852
+ event_id,
853
+ pidfd,
854
+ )
855
+ if not self.enforcement_slots.acquire(blocking=False):
856
+ # Admission is bounded. If the queue is saturated, keep
857
+ # containment decisive by running this task inline rather
858
+ # than allowing the detector to create unbounded threads.
859
+ self._enforce_discovery(*task_args, **kwargs)
860
+ continue
861
+
862
+ def enforce_bounded(
863
+ task_args: tuple[Any, ...] = task_args,
864
+ task_kwargs: dict[str, Any] = kwargs,
865
+ ) -> None:
866
+ try:
867
+ self._enforce_discovery(*task_args, **task_kwargs)
868
+ finally:
869
+ self.enforcement_slots.release()
870
+
871
  try:
872
+ threading.Thread(target=enforce_bounded, daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
873
  except RuntimeError:
874
+ self.enforcement_slots.release()
875
+ self._enforce_discovery(*task_args, **kwargs)
 
 
876
 
877
  def _discovery_loop(self) -> None:
878
  while not self.stop_event.is_set():
 
893
  if (
894
  thread is None
895
  or not thread.is_alive()
896
+ or self.last_scan_completed_ns <= 0
897
+ or time.monotonic_ns() - self.last_scan_completed_ns > SCAN_HEALTH_TIMEOUT_NS
898
+ or self.discovery_failures >= MAX_DISCOVERY_FAILURES
899
  ):
900
  return
901
  self.heartbeat_sequence += 1
 
1331
  }
1332
  if action == "detections" and not args:
1333
  values: list[dict[str, Any]] = []
1334
+ for path in sorted(
1335
+ self.detections.glob("*.json"), key=self._detection_sort_key, reverse=True
1336
+ ):
1337
  try:
1338
  value = load_regular_json(path)
1339
  values.append(
tests/test_artifacts.py CHANGED
@@ -98,3 +98,48 @@ class ArtifactTests(unittest.TestCase):
98
  zero.write_bytes(safetensors(shape=[0], offsets=(0, 0)))
99
  self.assertIsNotNone(validate_path(scalar))
100
  self.assertIsNotNone(validate_path(zero))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  zero.write_bytes(safetensors(shape=[0], offsets=(0, 0)))
99
  self.assertIsNotNone(validate_path(scalar))
100
  self.assertIsNotNone(validate_path(zero))
101
+
102
+ def test_safetensors_requires_complete_contiguous_data_layout(self) -> None:
103
+ with tempfile.TemporaryDirectory() as raw:
104
+ root = Path(raw)
105
+
106
+ def write(value: dict[str, object], body: bytes, name: str) -> Path:
107
+ header = json.dumps(value, separators=(",", ":")).encode("utf-8")
108
+ header += b" " * ((8 - len(header) % 8) % 8)
109
+ path = root / name
110
+ path.write_bytes(struct.pack("<Q", len(header)) + header + body)
111
+ return path
112
+
113
+ hole = write(
114
+ {
115
+ "left": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]},
116
+ "right": {"dtype": "F32", "shape": [1], "data_offsets": [8, 12]},
117
+ },
118
+ b"\0" * 12,
119
+ "hole",
120
+ )
121
+ trailing = write(
122
+ {"tensor": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]}},
123
+ b"\0" * 8,
124
+ "trailing",
125
+ )
126
+ overlap = write(
127
+ {
128
+ "left": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]},
129
+ "right": {"dtype": "F32", "shape": [1], "data_offsets": [2, 6]},
130
+ },
131
+ b"\0" * 6,
132
+ "overlap",
133
+ )
134
+ out_of_order = write(
135
+ {
136
+ "right": {"dtype": "F32", "shape": [1], "data_offsets": [4, 8]},
137
+ "left": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]},
138
+ },
139
+ b"\0" * 8,
140
+ "out-of-order",
141
+ )
142
+ self.assertIsNone(validate_path(hole))
143
+ self.assertIsNone(validate_path(trailing))
144
+ self.assertIsNone(validate_path(overlap))
145
+ self.assertIsNotNone(validate_path(out_of_order))
tests/test_detectors.py CHANGED
@@ -16,14 +16,10 @@ class Sample:
16
 
17
 
18
  class DetectorTests(unittest.TestCase):
19
- def test_llama_cpp_fast_path_requires_model_argument(self) -> None:
20
  catalogue = load_bundled()
21
- self.assertIsNone(match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "--help"))))
22
- value = match(
23
- catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf"))
24
- )
25
- self.assertEqual(
26
- DetectionMatch("llama.cpp", "FAST_NAME", ("exe_basename", "argv_model_suffix")), value
27
  )
28
 
29
  def test_content_profile_requires_both_independent_groups(self) -> None:
 
16
 
17
 
18
  class DetectorTests(unittest.TestCase):
19
+ def test_unqualified_fast_name_profiles_are_not_active(self) -> None:
20
  catalogue = load_bundled()
21
+ self.assertIsNone(
22
+ match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf")))
 
 
 
 
23
  )
24
 
25
  def test_content_profile_requires_both_independent_groups(self) -> None:
tests/test_discovery.py CHANGED
@@ -4,7 +4,14 @@ import tempfile
4
  import unittest
5
  from pathlib import Path
6
 
7
- from lumi_eggcracker.discovery import ProcessIdentity, _map_paths, argv_digest, identity, parse_stat
 
 
 
 
 
 
 
8
  from lumi_eggcracker.jsonio import JsonInputError
9
 
10
 
@@ -44,3 +51,18 @@ class DiscoveryTests(unittest.TestCase):
44
  values = _map_paths(path)
45
  self.assertEqual(512, len(values))
46
  self.assertTrue(values[0].startswith("/opt/runtime/"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import unittest
5
  from pathlib import Path
6
 
7
+ from lumi_eggcracker.discovery import (
8
+ ProcessIdentity,
9
+ _map_paths,
10
+ argv_digest,
11
+ executable_digest_for_identity,
12
+ identity,
13
+ parse_stat,
14
+ )
15
  from lumi_eggcracker.jsonio import JsonInputError
16
 
17
 
 
51
  values = _map_paths(path)
52
  self.assertEqual(512, len(values))
53
  self.assertTrue(values[0].startswith("/opt/runtime/"))
54
+
55
+ def test_process_executable_is_hashed_from_bound_proc_identity(self) -> None:
56
+ with tempfile.TemporaryDirectory() as raw:
57
+ proc = Path(raw)
58
+ entry = proc / "42"
59
+ entry.mkdir()
60
+ (entry / "stat").write_text(
61
+ "42 (runner) S 1 " + "0 " * 17 + "100\n", encoding="utf-8"
62
+ )
63
+ (entry / "exe").write_bytes(b"live executable")
64
+ digest, metadata = executable_digest_for_identity(
65
+ ProcessIdentity(42, 100), proc=proc
66
+ )
67
+ self.assertEqual(64, len(digest))
68
+ self.assertGreater(metadata.st_size, 0)
tests/test_supervisor.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import tempfile
4
  import threading
 
5
  import unittest
6
  from pathlib import Path
7
  from unittest.mock import patch
@@ -45,6 +46,18 @@ class SupervisorTests(unittest.TestCase):
45
  supervisor.discovery_done[identity] = 1
46
  self.assertIn(identity, supervisor.discovery_done)
47
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def test_containment_orders_direct_kill_before_receipt_state_and_cleanup(self) -> None:
49
  supervisor = self._instance()
50
  response = {"result": "TERMINATED", "cleanup": {"attempted": False}}
 
2
 
3
  import tempfile
4
  import threading
5
+ import time
6
  import unittest
7
  from pathlib import Path
8
  from unittest.mock import patch
 
46
  supervisor.discovery_done[identity] = 1
47
  self.assertIn(identity, supervisor.discovery_done)
48
 
49
+ def test_heartbeat_stops_when_no_scan_completed_within_health_bound(self) -> None:
50
+ supervisor = self._instance()
51
+ supervisor.discovery_thread = type(
52
+ "LiveThread", (), {"is_alive": lambda _self: True}
53
+ )()
54
+ supervisor.last_heartbeat_sent = 0.0
55
+ supervisor.last_scan_completed_ns = time.monotonic_ns() - 2_000_000_000
56
+ supervisor.discovery_failures = 0
57
+ with patch("lumi_eggcracker.supervisor.socket.socket") as socket_factory:
58
+ supervisor._heartbeat()
59
+ socket_factory.assert_not_called()
60
+
61
  def test_containment_orders_direct_kill_before_receipt_state_and_cleanup(self) -> None:
62
  supervisor = self._instance()
63
  response = {"result": "TERMINATED", "cleanup": {"attempted": False}}