Sahek commited on
Commit
fb371ab
·
verified ·
1 Parent(s): a3a935a

v7.2: fix historical velocity tracking (repo_id), session UUID collision, read-only repo mount, SQLite pre-score, batched semgrep, real CI patch content

Browse files
README.md CHANGED
@@ -5,53 +5,62 @@ tags:
5
  - ai-governance
6
  - sandboxing
7
  - devsecops
8
- pretty_name: Adaptive Runtime Security Platform for Autonomous Agents (v7.2)
9
  ---
10
 
11
- # Adaptive Runtime Security Platform for Autonomous Agents (v7.2)
12
 
13
  A production-ready, drop-in governance layer for AI coding agents (Claude Code, Cursor, Aider).
14
- v7.2 closes out the 4 major + 3 minor issues found in the v7.1 external review.
15
 
16
- ## Changelog: v7.1 v7.2
 
 
 
 
 
17
 
18
  | # | Issue | Severity | Fix |
19
  | --- | --- | --- | --- |
20
- | 1 | Session UUID collision (`date +%s` granularity) | High | Switched to `uuid.uuid4()` for guaranteed-unique session IDs |
21
- | 2 | Historical velocity always returned 0 (queried by unique `session_id`) | **Critical** | Track a stable `repo_id` (derived from git remote) and query history by repo, not session |
22
- | 3 | Pre-score stored in fragile `/tmp/pre_score_*.txt` files | Medium-High | Moved to a `session_state` SQLite table (WAL mode), no stale files or partial writes |
23
- | 4 | Container had RW access to the real repo + `.git` | High | Repo now mounts **read-only**; agent works in a tmpfs copy; only a scoped patch file crosses back to the host, applied only after JRI evaluation |
24
- | 5 | Semgrep spawned one process per changed file | Minor | Batched into a single `semgrep ... file1 file2 file3 --json` invocation |
25
- | 6 | CI only passed changed filenames into the prompt scorer | Minor | CI now passes actual patch content (truncated) for real prompt-injection scoring |
26
- | 7 | `refactor_heavy` profile branch was unreachable dead code | Minor | Added a `refactor_heavy` profile to config + prompt-intent detection so the branch is now reachable |
 
 
 
 
 
 
27
 
28
  ## What's Included
29
 
30
  | File | Purpose |
31
  | --- | --- |
32
  | `core_engine.py` | Risk Fusion, Normalization & Policy Engine (JRI calculation) |
33
- | `config/security_profiles.json` | Context-aware weight profiles: `default`, `security_sensitive`, `refactor_heavy` |
34
  | `config/rules.semgrep.yml` | AST-aware semantic diff rules |
35
- | `scripts/secure-agent-orchestrator.sh` | Phase-driven execution wrapper — RO repo mount / RW tmpfs overlay / patch export |
36
  | `.github/workflows/agent-governance.yml` | Remote CI pipeline arbiter |
37
 
38
- ## Isolation Model (v7.2)
39
 
40
  ```
41
- Host repo (read-only mount) ──► Container tmpfs copy (agent works here)
 
 
42
 
43
 
44
- git diff → /patches/session.patch
 
45
 
46
  (only this narrow RW mount crosses back)
47
 
48
- Host: git apply --check → git apply → JRI evaluation
49
  ```
50
 
51
- The agent can never touch host git refs, history, or objects directly — it only ever
52
- produces a patch, and that patch is applied on the host **after** the container is
53
- already destroyed, then scored before it's allowed to land.
54
-
55
  ## Quick Setup
56
 
57
  ```bash
@@ -59,6 +68,14 @@ chmod +x scripts/secure-agent-orchestrator.sh
59
  ./scripts/secure-agent-orchestrator.sh aider "your prompt here"
60
  ```
61
 
 
 
 
 
 
 
 
 
62
  ## Risk Thresholds
63
 
64
  | Profile | Warn | Quarantine | Block & Isolate |
 
5
  - ai-governance
6
  - sandboxing
7
  - devsecops
8
+ pretty_name: Adaptive Runtime Security Platform for Autonomous Agents (v8.0)
9
  ---
10
 
11
+ # Adaptive Runtime Security Platform for Autonomous Agents (v8.0)
12
 
13
  A production-ready, drop-in governance layer for AI coding agents (Claude Code, Cursor, Aider).
 
14
 
15
+ It combines sandbox isolation, runtime telemetry, and weighted risk scoring to **contain**
16
+ prompt injection and malicious agent behavior before changes reach the host repository.
17
+ This is a defense-in-depth control, not a guarantee against all prompt injection — see
18
+ "Scope & Limitations" below.
19
+
20
+ ## Changelog: v7.2 → v8.0
21
 
22
  | # | Issue | Severity | Fix |
23
  | --- | --- | --- | --- |
24
+ | 1 | `cp -r` into tmpfs was slow/memory-heavy on monorepos (node_modules, build artifacts) | Medium | Sandbox now copies only git-tracked files via `git archive \| tar -x`, skipping ignored directories entirely |
25
+ | 2 | No cap on patch size before the host tried to `git apply` it | High | Patch size checked against `max_patch_size_bytes` (default 5MB) *before* any apply attempt; oversized patches are rejected outright |
26
+ | 3 | Prompt-injection regex could be bypassed by zero-width characters, bidi overrides, or whitespace fragmentation | Medium (partial mitigation) | Strip zero-width/bidi-override characters and collapse whitespace before pattern matching; messaging updated to accurately describe this as heuristic detection, not semantic analysis |
27
+ | 4 | No timeout a hung agent process could hold the sandbox open indefinitely | High | `timeout` wraps the full container run, killed and treated as a failed session if it exceeds `agent_runtime_timeout_seconds` (default 900s) |
28
+ | 5 | `session_history` / `session_state` grew unbounded | Low-Medium | Auto-prune on every engine init, controlled by `history_retention_days` (default 30) |
29
+ | 6 | If a patch failed to apply on the host, container-side activity was scored as zero — evidence lost | Medium (partial mitigation) | Orchestrator exports a small telemetry file (modified file count, apply-failure flag) that the engine folds into behavioral scoring even when the patch itself is rejected |
30
+
31
+ ## Scope & Limitations
32
+
33
+ Be precise about what this does and doesn't do:
34
+
35
+ - **Does**: sandbox agent execution (network-isolated, read-only host repo, resource-capped, timeout-enforced), detect common prompt-injection payloads and override signatures, cap the blast radius of any single agent session, and score risk across multiple independent signals before anything lands in the real repo.
36
+ - **Does not**: perform semantic/LLM-based prompt analysis. Regex + normalization catches known attack patterns (override phrases, base64-encoded payloads, zero-width smuggling) but a sufficiently novel injection technique can still get through the pre-runtime gate. Treat the runtime sandbox and post-runtime scoring as your primary defenses, and pre-runtime prompt scanning as an early tripwire, not a guarantee.
37
 
38
  ## What's Included
39
 
40
  | File | Purpose |
41
  | --- | --- |
42
  | `core_engine.py` | Risk Fusion, Normalization & Policy Engine (JRI calculation) |
43
+ | `config/security_profiles.json` | Context-aware weight profiles + system tunables (patch size cap, runtime timeout, retention) |
44
  | `config/rules.semgrep.yml` | AST-aware semantic diff rules |
45
+ | `scripts/secure-agent-orchestrator.sh` | Phase-driven execution wrapper — RO repo mount / RW tmpfs overlay / patch export / timeout enforcement |
46
  | `.github/workflows/agent-governance.yml` | Remote CI pipeline arbiter |
47
 
48
+ ## Isolation Model
49
 
50
  ```
51
+ Host repo (read-only mount) ──► Container tmpfs copy (git-tracked files only)
52
+
53
+ timeout-bounded agent run
54
 
55
 
56
+ git diff --cached → /patches/session.patch
57
+ + modified_files.txt + telemetry.json
58
 
59
  (only this narrow RW mount crosses back)
60
 
61
+ Host: patch size check → git apply --check → git apply → JRI evaluation
62
  ```
63
 
 
 
 
 
64
  ## Quick Setup
65
 
66
  ```bash
 
68
  ./scripts/secure-agent-orchestrator.sh aider "your prompt here"
69
  ```
70
 
71
+ ## System Tunables (`config/security_profiles.json`)
72
+
73
+ | Setting | Default | Purpose |
74
+ | --- | --- | --- |
75
+ | `max_patch_size_bytes` | 5242880 (5MB) | Reject oversized patches before host `git apply` ever sees them |
76
+ | `agent_runtime_timeout_seconds` | 900 | Kill hung containers instead of letting them run indefinitely |
77
+ | `history_retention_days` | 30 | Prune old `session_history` / `session_state` rows automatically |
78
+
79
  ## Risk Thresholds
80
 
81
  | Profile | Warn | Quarantine | Block & Isolate |
config/security_profiles.json CHANGED
@@ -1,6 +1,9 @@
1
  {
2
  "system_settings": {
3
  "historical_decay_half_life_days": 3.0,
 
 
 
4
  "trusted_registries": [
5
  "https://registry.npmjs.org/",
6
  "https://files.pythonhosted.org/",
 
1
  {
2
  "system_settings": {
3
  "historical_decay_half_life_days": 3.0,
4
+ "history_retention_days": 30,
5
+ "max_patch_size_bytes": 5242880,
6
+ "agent_runtime_timeout_seconds": 900,
7
  "trusted_registries": [
8
  "https://registry.npmjs.org/",
9
  "https://files.pythonhosted.org/",
core_engine.py CHANGED
@@ -9,7 +9,19 @@ import base64
9
  import subprocess
10
  import uuid
11
  import hashlib
12
- from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  class AgentSecurityEngine:
15
  def __init__(self, workspace_dir, session_id, raw_prompt=""):
@@ -19,15 +31,12 @@ class AgentSecurityEngine:
19
  self.db_path = "/tmp/agent_intel_state.db"
20
  self.explain_log = []
21
 
22
- # FIX #2 (Critical): historical velocity must be tracked per-repo, not per-session.
23
- # A session_id is unique per run by design, so filtering history on it always
24
- # returned zero prior rows. Derive a stable repo_id from the git remote (falling
25
- # back to the absolute workspace path) so history persists across sessions.
26
  self.repo_id = self._derive_repo_id()
27
 
28
  self._init_database()
29
  self.config = self._load_config()
30
  self.profile = self._determine_context_profile()
 
31
 
32
  def _derive_repo_id(self):
33
  try:
@@ -40,8 +49,6 @@ class AgentSecurityEngine:
40
  return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]
41
 
42
  def _init_database(self):
43
- """WAL mode for concurrent access, plus a session_state table replacing the
44
- fragile /tmp/pre_score_{session}.txt file (FIX #3)."""
45
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
46
  conn.execute("PRAGMA journal_mode=WAL;")
47
  conn.execute("""
@@ -66,14 +73,25 @@ class AgentSecurityEngine:
66
  with open(config_path, "r") as f:
67
  return json.load(f)
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def _determine_context_profile(self):
70
  sensitive_patterns = r"(auth|login|jwt|rbac|oauth|session|crypto|credential|privilege|permission|token)"
71
  refactor_patterns = r"(refactor|restructure|rename across|migrate|reorganize|large-scale rewrite)"
72
 
73
  if re.search(sensitive_patterns, self.raw_prompt, re.IGNORECASE):
74
  return "security_sensitive"
75
- # Makes the previously-dead "refactor_heavy" branch in evaluate_behavioral_risk
76
- # reachable via prompt intent detection, instead of being unreachable dead logic.
77
  if re.search(refactor_patterns, self.raw_prompt, re.IGNORECASE) and "refactor_heavy" in self.config.get("context_profiles", {}):
78
  return "refactor_heavy"
79
  return "default"
@@ -85,24 +103,33 @@ class AgentSecurityEngine:
85
  if not self.raw_prompt:
86
  return 0
87
 
88
- norm = unicodedata.normalize("NFKC", self.raw_prompt).lower()
 
 
 
 
 
 
89
  norm = re.sub(r"<!--.*?-->", "", norm, flags=re.DOTALL)
90
  norm = re.sub(r"```.*?```", "", norm, flags=re.DOTALL)
 
 
 
91
 
92
  b64_patterns = r"[a-zA-Z0-9+/]{40,}={0,2}"
93
  for match in re.findall(b64_patterns, norm):
94
  try:
95
  decoded = base64.b64decode(match).decode("utf-8", errors="ignore").lower()
96
- norm += " " + decoded
97
  except Exception:
98
  pass
99
 
100
  score = 0
101
- if re.search(r"(ignore previous|system override|bypass restrictions|developer mode)", norm):
102
  base_risk = 85; confidence = 0.95
103
  score += (base_risk * confidence)
104
  self.explain_log.append(f"Prompt Normalizer: Override signature detected (Contribution: +{int(base_risk * confidence)})")
105
- if re.search(r"(reveal secrets|system prompt|read \.env)", norm):
106
  base_risk = 60; confidence = 0.90
107
  score += (base_risk * confidence)
108
  self.explain_log.append(f"Prompt Normalizer: Target vector probe signature detected (Contribution: +{int(base_risk * confidence)})")
@@ -116,8 +143,6 @@ class AgentSecurityEngine:
116
  return final_score
117
 
118
  def save_pre_score(self, score):
119
- """FIX #3: persist pre-runtime score in SQLite instead of a /tmp text file,
120
- which was prone to stale leftovers, partial writes, and no cleanup path."""
121
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
122
  conn.execute(
123
  "INSERT OR REPLACE INTO session_state VALUES (?, ?, ?, ?)",
@@ -162,7 +187,21 @@ class AgentSecurityEngine:
162
  diff_stats = subprocess.check_output(["git", "diff", "--cached", "--numstat"], text=True).splitlines()
163
  lines_changed = sum(sum(int(x) for x in line.split()[:2] if x.isdigit()) for line in diff_stats)
164
  except Exception:
165
- return 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  max_files = 12 if self.profile == "refactor_heavy" else 3
168
  max_lines = 700 if self.profile == "refactor_heavy" else 150
@@ -177,9 +216,17 @@ class AgentSecurityEngine:
177
 
178
  return min(score, 100)
179
 
 
 
 
 
 
 
 
 
 
 
180
  def evaluate_historical_velocity(self):
181
- """FIX #2 (Critical): now queries by repo_id so history actually accumulates
182
- across sessions instead of always looking up a session_id with zero prior rows."""
183
  half_life = self.config["system_settings"]["historical_decay_half_life_days"]
184
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
185
  cursor = conn.cursor()
@@ -213,8 +260,6 @@ class AgentSecurityEngine:
213
  return True
214
 
215
  def run_semgrep_ast_diff(self):
216
- """FIX #5 (Minor): batch all target files into a single semgrep invocation
217
- instead of spawning one process per file, which doesn't scale on monorepos."""
218
  try:
219
  changed_files = subprocess.check_output(["git", "diff", "--cached", "--name-only"], text=True).splitlines()
220
  target_modules = [f for f in changed_files if re.search(r"\.(ts|js|py|rs|go)$", f) and os.path.exists(f)]
@@ -237,7 +282,6 @@ class AgentSecurityEngine:
237
  return 0
238
 
239
  def compute_and_route_jri(self):
240
- """Executes full mathematical matrix normalization across all signals."""
241
  pre_runtime_prompt_score = self.load_pre_score()
242
  b_score = self.evaluate_behavioral_risk()
243
  s_score = 100 if not self.verify_clean_secrets() else 0
 
9
  import subprocess
10
  import uuid
11
  import hashlib
12
+ from datetime import datetime, timedelta
13
+
14
+ # Characters commonly used to smuggle instructions past naive regex matching:
15
+ # zero-width joiners/spaces and directional override marks. Stripped before
16
+ # pattern matching so "ignore\u200bprevious" still triggers the same signature
17
+ # as "ignoreprevious". This is still a heuristic layer, not semantic analysis —
18
+ # see README for accurate scope-of-defense language.
19
+ _ZERO_WIDTH_CHARS = "".join([
20
+ "\u200b", "\u200c", "\u200d", "\u2060", "\ufeff",
21
+ "\u202a", "\u202b", "\u202c", "\u202d", "\u202e",
22
+ ])
23
+ _ZERO_WIDTH_RE = re.compile("[" + _ZERO_WIDTH_CHARS + "]")
24
+
25
 
26
  class AgentSecurityEngine:
27
  def __init__(self, workspace_dir, session_id, raw_prompt=""):
 
31
  self.db_path = "/tmp/agent_intel_state.db"
32
  self.explain_log = []
33
 
 
 
 
 
34
  self.repo_id = self._derive_repo_id()
35
 
36
  self._init_database()
37
  self.config = self._load_config()
38
  self.profile = self._determine_context_profile()
39
+ self._prune_history()
40
 
41
  def _derive_repo_id(self):
42
  try:
 
49
  return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]
50
 
51
  def _init_database(self):
 
 
52
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
53
  conn.execute("PRAGMA journal_mode=WAL;")
54
  conn.execute("""
 
73
  with open(config_path, "r") as f:
74
  return json.load(f)
75
 
76
+ def _prune_history(self):
77
+ """FIX #5 (Low-Medium): unbounded growth in session_history/session_state
78
+ slows historical scans over months of use. Prune anything older than the
79
+ configured retention window on every engine init."""
80
+ retention_days = self.config.get("system_settings", {}).get("history_retention_days", 30)
81
+ cutoff = datetime.utcnow() - timedelta(days=retention_days)
82
+ try:
83
+ with sqlite3.connect(self.db_path, timeout=30.0) as conn:
84
+ conn.execute("DELETE FROM session_history WHERE timestamp < ?", (cutoff,))
85
+ conn.execute("DELETE FROM session_state WHERE created_at < ?", (cutoff,))
86
+ except Exception:
87
+ pass
88
+
89
  def _determine_context_profile(self):
90
  sensitive_patterns = r"(auth|login|jwt|rbac|oauth|session|crypto|credential|privilege|permission|token)"
91
  refactor_patterns = r"(refactor|restructure|rename across|migrate|reorganize|large-scale rewrite)"
92
 
93
  if re.search(sensitive_patterns, self.raw_prompt, re.IGNORECASE):
94
  return "security_sensitive"
 
 
95
  if re.search(refactor_patterns, self.raw_prompt, re.IGNORECASE) and "refactor_heavy" in self.config.get("context_profiles", {}):
96
  return "refactor_heavy"
97
  return "default"
 
103
  if not self.raw_prompt:
104
  return 0
105
 
106
+ # FIX #3 (Medium, partial mitigation): strip zero-width/bidi-override
107
+ # characters and apply NFKC normalization *before* stripping markdown/
108
+ # comments, so homoglyph/invisible-character smuggling doesn't slip
109
+ # override signatures past the regex. This still does not amount to
110
+ # semantic prompt analysis — see README for accurate framing.
111
+ norm = _ZERO_WIDTH_RE.sub("", self.raw_prompt)
112
+ norm = unicodedata.normalize("NFKC", norm).lower()
113
  norm = re.sub(r"<!--.*?-->", "", norm, flags=re.DOTALL)
114
  norm = re.sub(r"```.*?```", "", norm, flags=re.DOTALL)
115
+ # Collapse repeated whitespace/newlines, another common fragmentation trick
116
+ # (e.g. "ignore\n\nprevious" split across lines to dodge a single-line regex).
117
+ norm_collapsed = re.sub(r"\s+", " ", norm)
118
 
119
  b64_patterns = r"[a-zA-Z0-9+/]{40,}={0,2}"
120
  for match in re.findall(b64_patterns, norm):
121
  try:
122
  decoded = base64.b64decode(match).decode("utf-8", errors="ignore").lower()
123
+ norm_collapsed += " " + re.sub(r"\s+", " ", decoded)
124
  except Exception:
125
  pass
126
 
127
  score = 0
128
+ if re.search(r"(ignore\s*previous|system\s*override|bypass\s*restrictions|developer\s*mode)", norm_collapsed):
129
  base_risk = 85; confidence = 0.95
130
  score += (base_risk * confidence)
131
  self.explain_log.append(f"Prompt Normalizer: Override signature detected (Contribution: +{int(base_risk * confidence)})")
132
+ if re.search(r"(reveal\s*secrets|system\s*prompt|read\s*\.env)", norm_collapsed):
133
  base_risk = 60; confidence = 0.90
134
  score += (base_risk * confidence)
135
  self.explain_log.append(f"Prompt Normalizer: Target vector probe signature detected (Contribution: +{int(base_risk * confidence)})")
 
143
  return final_score
144
 
145
  def save_pre_score(self, score):
 
 
146
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
147
  conn.execute(
148
  "INSERT OR REPLACE INTO session_state VALUES (?, ?, ?, ?)",
 
187
  diff_stats = subprocess.check_output(["git", "diff", "--cached", "--numstat"], text=True).splitlines()
188
  lines_changed = sum(sum(int(x) for x in line.split()[:2] if x.isdigit()) for line in diff_stats)
189
  except Exception:
190
+ files_changed, lines_changed = 0, 0
191
+
192
+ # FIX #6 (Medium, partial mitigation): if the patch failed to apply on the
193
+ # host, the diff above is empty and this signal would silently go to zero
194
+ # even if the agent did something risky inside the container. Fold in
195
+ # container-side telemetry (modified file count) exported by the
196
+ # orchestrator alongside the patch, so a failed-apply doesn't erase evidence.
197
+ telemetry = self._load_container_telemetry()
198
+ if telemetry:
199
+ files_changed = max(files_changed, telemetry.get("modified_file_count", 0))
200
+ if telemetry.get("patch_apply_failed"):
201
+ self.explain_log.append(
202
+ "Telemetry Bridge: Container-side patch failed to apply on host — "
203
+ f"scoring against {telemetry.get('modified_file_count', 0)} modified files reported by container instead"
204
+ )
205
 
206
  max_files = 12 if self.profile == "refactor_heavy" else 3
207
  max_lines = 700 if self.profile == "refactor_heavy" else 150
 
216
 
217
  return min(score, 100)
218
 
219
+ def _load_container_telemetry(self):
220
+ telemetry_path = os.environ.get("AGENT_TELEMETRY_PATH")
221
+ if not telemetry_path or not os.path.exists(telemetry_path):
222
+ return None
223
+ try:
224
+ with open(telemetry_path, "r") as f:
225
+ return json.load(f)
226
+ except Exception:
227
+ return None
228
+
229
  def evaluate_historical_velocity(self):
 
 
230
  half_life = self.config["system_settings"]["historical_decay_half_life_days"]
231
  with sqlite3.connect(self.db_path, timeout=30.0) as conn:
232
  cursor = conn.cursor()
 
260
  return True
261
 
262
  def run_semgrep_ast_diff(self):
 
 
263
  try:
264
  changed_files = subprocess.check_output(["git", "diff", "--cached", "--name-only"], text=True).splitlines()
265
  target_modules = [f for f in changed_files if re.search(r"\.(ts|js|py|rs|go)$", f) and os.path.exists(f)]
 
282
  return 0
283
 
284
  def compute_and_route_jri(self):
 
285
  pre_runtime_prompt_score = self.load_pre_score()
286
  b_score = self.evaluate_behavioral_risk()
287
  s_score = 100 if not self.verify_clean_secrets() else 0
scripts/secure-agent-orchestrator.sh CHANGED
@@ -1,6 +1,6 @@
1
  #!/bin/bash
2
  # ==============================================================================
3
- # Runtime Orchestrator: Enforces Split-Phase Lifecycle Topologies (v7.2)
4
  # ==============================================================================
5
  set -euo pipefail
6
 
@@ -8,11 +8,12 @@ WORKSPACE_DIR="$(pwd)"
8
  AGENT_TOOL="${1:-aider}"
9
  USER_PROMPT="${2:-""}"
10
 
11
- # FIX #1 (High): timestamp-second granularity collided on concurrent/rapid runs.
12
- # uuid4 guarantees uniqueness for /tmp/pre_score files, SQLite session rows, and
13
- # quarantine branch names.
14
  SESSION_UUID=$(python3 -c "import uuid; print(uuid.uuid4())")
15
 
 
 
 
 
16
  PATCH_DIR="/tmp/agent_patches_${SESSION_UUID}"
17
  mkdir -p "$PATCH_DIR"
18
 
@@ -22,12 +23,16 @@ python3 core_engine.py "pre" "$SESSION_UUID" "$USER_PROMPT"
22
  echo "🔒 Spawning Hardened Linux Kernel Container Space ($SESSION_UUID)..."
23
 
24
  # 2. PHASE B: Secure Sandbox Perimeter Execution
25
- # FIX #4 (High): the repo itself is now mounted READ-ONLY. The agent only gets a
26
- # writable copy inside the container's own tmpfs (never bind-mounted from host),
27
- # so it cannot tamper with git internals, refs, or history on the real repo.
28
- # On exit, the container emits a patch file into the one narrow RW mount point
29
- # (PATCH_DIR) that's the only thing that crosses back to the host filesystem.
30
- docker run -it --rm \
 
 
 
 
31
  --name "secure_agent_$SESSION_UUID" \
32
  --network none \
33
  --memory="2g" \
@@ -45,22 +50,55 @@ docker run -it --rm \
45
  --mount type=bind,source=/dev/null,target=/workspace_ro/.env \
46
  -w /workspace \
47
  coder-agent-image:latest bash -c "
48
- cp -r /workspace_ro/. /workspace/ &&
49
  cd /workspace &&
50
  $AGENT_TOOL '$USER_PROMPT' || true;
51
- git diff > /patches/session.patch 2>/dev/null || true
52
- "
 
 
 
53
 
54
  # 3. PHASE C: Post-Runtime Metric Evaluation & Active Routing
55
- # The JRI is computed against the *outside* repo state plus the pending patch,
56
- # so quarantine/block decisions never depend on code that only exists inside
57
- # the now-destroyed container.
 
 
 
 
 
 
 
 
 
58
  if [ -s "$PATCH_DIR/session.patch" ]; then
59
- git apply --check "$PATCH_DIR/session.patch" 2>/dev/null && \
60
- git apply "$PATCH_DIR/session.patch" && \
 
 
 
 
61
  git add -A
 
 
 
 
62
  fi
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  python3 core_engine.py "post" "$SESSION_UUID" "$USER_PROMPT"
65
 
66
  rm -rf "$PATCH_DIR"
 
1
  #!/bin/bash
2
  # ==============================================================================
3
+ # Runtime Orchestrator: Enforces Split-Phase Lifecycle Topologies (v8.0)
4
  # ==============================================================================
5
  set -euo pipefail
6
 
 
8
  AGENT_TOOL="${1:-aider}"
9
  USER_PROMPT="${2:-""}"
10
 
 
 
 
11
  SESSION_UUID=$(python3 -c "import uuid; print(uuid.uuid4())")
12
 
13
+ # Pull tunables from config so ops can adjust without touching this script.
14
+ MAX_PATCH_SIZE=$(python3 -c "import json; print(json.load(open('config/security_profiles.json'))['system_settings']['max_patch_size_bytes'])")
15
+ RUNTIME_TIMEOUT=$(python3 -c "import json; print(json.load(open('config/security_profiles.json'))['system_settings']['agent_runtime_timeout_seconds'])")
16
+
17
  PATCH_DIR="/tmp/agent_patches_${SESSION_UUID}"
18
  mkdir -p "$PATCH_DIR"
19
 
 
23
  echo "🔒 Spawning Hardened Linux Kernel Container Space ($SESSION_UUID)..."
24
 
25
  # 2. PHASE B: Secure Sandbox Perimeter Execution
26
+ #
27
+ # FIX (Medium): the container now copies only *git-tracked* files instead of
28
+ # `cp -r .`, which was slow and memory-heavy on monorepos and could balloon
29
+ # on untracked build artifacts / node_modules. `git archive` streams tracked
30
+ # content straight into the tmpfs copy without walking ignored directories.
31
+ #
32
+ # FIX (High): `timeout` wraps the whole docker invocation so a hung agent
33
+ # process or stuck inference call can't hold the sandbox (and its resources)
34
+ # open indefinitely — it gets killed and treated as a failed run.
35
+ timeout --signal=KILL "${RUNTIME_TIMEOUT}s" docker run --rm \
36
  --name "secure_agent_$SESSION_UUID" \
37
  --network none \
38
  --memory="2g" \
 
50
  --mount type=bind,source=/dev/null,target=/workspace_ro/.env \
51
  -w /workspace \
52
  coder-agent-image:latest bash -c "
53
+ git --git-dir=/workspace_ro/.git --work-tree=/workspace_ro archive HEAD | tar -x -C /workspace &&
54
  cd /workspace &&
55
  $AGENT_TOOL '$USER_PROMPT' || true;
56
+ git init -q &&
57
+ git add -A &&
58
+ git diff --cached > /patches/session.patch 2>/dev/null || true;
59
+ git diff --cached --name-only > /patches/modified_files.txt 2>/dev/null || true
60
+ " || echo "⚠️ Agent runtime terminated (timeout or nonzero exit) — evaluating whatever telemetry was captured."
61
 
62
  # 3. PHASE C: Post-Runtime Metric Evaluation & Active Routing
63
+ #
64
+ # FIX (High): guard against oversized patches *before* the host git process
65
+ # ever tries to parse them. A 40k-line / 500-file patch shouldn't be handed
66
+ # to `git apply` at all — reject it outright and let it fall straight into
67
+ # quarantine scoring instead.
68
+ PATCH_APPLY_FAILED=false
69
+ MODIFIED_FILE_COUNT=0
70
+
71
+ if [ -f "$PATCH_DIR/modified_files.txt" ]; then
72
+ MODIFIED_FILE_COUNT=$(wc -l < "$PATCH_DIR/modified_files.txt" | tr -d ' ')
73
+ fi
74
+
75
  if [ -s "$PATCH_DIR/session.patch" ]; then
76
+ PATCH_SIZE=$(wc -c < "$PATCH_DIR/session.patch")
77
+ if [ "$PATCH_SIZE" -gt "$MAX_PATCH_SIZE" ]; then
78
+ echo "❌ Patch rejected: ${PATCH_SIZE} bytes exceeds max_patch_size_bytes (${MAX_PATCH_SIZE}). Not applying to host repo."
79
+ PATCH_APPLY_FAILED=true
80
+ elif git apply --check "$PATCH_DIR/session.patch" 2>/dev/null; then
81
+ git apply "$PATCH_DIR/session.patch"
82
  git add -A
83
+ else
84
+ echo "⚠️ Patch failed git apply --check — not applying to host repo."
85
+ PATCH_APPLY_FAILED=true
86
+ fi
87
  fi
88
 
89
+ # FIX (Medium): even when the patch can't be applied, don't lose the evidence.
90
+ # Export a small telemetry file the engine can read to score against what the
91
+ # container reported, instead of silently defaulting every signal to zero.
92
+ TELEMETRY_PATH="$PATCH_DIR/telemetry.json"
93
+ python3 -c "
94
+ import json
95
+ json.dump({
96
+ 'modified_file_count': ${MODIFIED_FILE_COUNT},
97
+ 'patch_apply_failed': ${PATCH_APPLY_FAILED,,}
98
+ }, open('${TELEMETRY_PATH}', 'w'))
99
+ "
100
+ export AGENT_TELEMETRY_PATH="$TELEMETRY_PATH"
101
+
102
  python3 core_engine.py "post" "$SESSION_UUID" "$USER_PROMPT"
103
 
104
  rm -rf "$PATCH_DIR"