nexo-brain 5.7.0 → 5.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,6 +38,56 @@ except Exception:
38
38
  # still leaving enough headroom for legitimate long per-session extractions.
39
39
  CLAUDE_TIMEOUT = AUTOMATION_SUBPROCESS_TIMEOUT
40
40
 
41
+ # Poison detection: a session checkpoint records the number of failed attempts
42
+ # across runs. Once it reaches this limit we stop trying to extract findings
43
+ # from that session — repeated failures on the same session (deterministic
44
+ # JSON parse errors, unreadable transcripts) only burn API credits and stall
45
+ # the whole deep-sleep cycle behind the poisoned session. The session is still
46
+ # kept in the output (with the error) so synthesize.py can account for it.
47
+ MAX_POISON_ATTEMPTS = 3
48
+
49
+ # Transient error types worth retrying on the next deep-sleep run instead of
50
+ # being counted as a poisoned attempt. `overloaded_error` comes from the
51
+ # Anthropic API when it is under load and is the cause of the stuck
52
+ # deep-sleep between 2026-04-14 and 2026-04-17 — the first attempt hit it,
53
+ # the checkpoint flagged it as permanent failure, and later runs kept
54
+ # re-processing the same session forever.
55
+ TRANSIENT_ERROR_KINDS = {
56
+ "overloaded_error",
57
+ "rate_limit_error",
58
+ "api_error",
59
+ "timeout",
60
+ "signal",
61
+ }
62
+
63
+
64
+ def _classify_cli_result(result) -> tuple[str, str]:
65
+ """Return (kind, short_message) describing a failed automation backend call.
66
+
67
+ Kinds:
68
+ - "overloaded_error" / "rate_limit_error" / "api_error"
69
+ Anthropic API transient failure — do not poison the checkpoint.
70
+ - "signal" Claude CLI killed by external signal (SIGTERM / SIGKILL / exit>=128).
71
+ - "timeout" Subprocess hit CLAUDE_TIMEOUT — extremely long session.
72
+ - "json_parse" Claude responded, but output wasn't parseable JSON.
73
+ - "unknown" Fallback.
74
+ """
75
+ rc = getattr(result, "returncode", -1)
76
+ stderr = (getattr(result, "stderr", "") or "")[:800]
77
+ stdout = (getattr(result, "stdout", "") or "")[:800]
78
+ blob = f"{stderr}\n{stdout}".lower()
79
+ if "overloaded" in blob:
80
+ return "overloaded_error", "Anthropic API overloaded"
81
+ if "rate_limit" in blob or "rate-limit" in blob or "429" in blob:
82
+ return "rate_limit_error", "Anthropic rate-limit hit"
83
+ if '"type":"error"' in blob and '"api_error"' in blob:
84
+ return "api_error", "Anthropic API error"
85
+ if rc >= 128:
86
+ return "signal", f"killed by signal (exit {rc})"
87
+ if rc < 0:
88
+ return "signal", f"subprocess terminated (exit {rc})"
89
+ return "unknown", f"exit {rc}"
90
+
41
91
 
42
92
  def extract_json_from_response(text: str) -> dict | None:
43
93
  """Parse JSON from Claude's response, handling markdown fences."""
@@ -104,20 +154,23 @@ def analyze_session(
104
154
  date_dir: Path,
105
155
  shared_context_file: Path | None,
106
156
  session_txt_map: dict[str, str] | None = None,
107
- ) -> dict | None:
157
+ ) -> tuple[dict | None, str | None]:
108
158
  """Send a session to the automation backend for extraction analysis.
109
159
 
110
- The backend reads the small per-session file + shared context file.
111
- Prompt is short the heavy lifting is in the Read tool calls.
160
+ Returns (parsed_result, error_kind). `error_kind` is only set on failure.
161
+ See `_classify_cli_result` for possible values.
112
162
  """
113
163
  session_file = find_session_file(session_id, date_dir, session_txt_map=session_txt_map)
114
164
  if not session_file:
115
165
  print(f" No session file found for {session_id}", file=sys.stderr)
116
- return None
166
+ return None, "missing_session_file"
117
167
 
118
168
  print(f" File: {session_file.name} ({session_file.stat().st_size / 1024:.0f} KB)")
119
169
 
120
- # Build a short prompt — Claude reads the files itself
170
+ # Build a short prompt — Claude reads the files itself. We point at the
171
+ # slim shared context rather than the full 400+KB dump so the Claude CLI
172
+ # process doesn't have to stream hundreds of kilobytes of followups /
173
+ # learnings into its context window on every per-session extraction.
121
174
  shared_ctx_instruction = ""
122
175
  if shared_context_file and shared_context_file.exists():
123
176
  shared_ctx_instruction = f"\n\nAlso read the shared context (followups, learnings, DB state) at: {shared_context_file}"
@@ -148,8 +201,9 @@ def analyze_session(
148
201
  )
149
202
 
150
203
  if result.returncode != 0:
151
- print(f" Automation backend error (exit {result.returncode}): {result.stderr[:300]}", file=sys.stderr)
152
- return None
204
+ kind, message = _classify_cli_result(result)
205
+ print(f" Automation backend {kind} (exit {result.returncode}): {message}", file=sys.stderr)
206
+ return None, kind
153
207
 
154
208
  # Filter out stop hook contamination (e.g. "Post-mortem completo.")
155
209
  output = "\n".join(
@@ -185,18 +239,65 @@ def analyze_session(
185
239
  debug_file = DEEP_SLEEP_DIR / f"debug-extract-{session_id[:20]}.txt"
186
240
  debug_file.write_text(result.stdout[:5000])
187
241
  print(f" Failed to parse JSON. Raw output saved to {debug_file}", file=sys.stderr)
188
- return None
242
+ return None, "json_parse"
189
243
 
190
- return parsed
244
+ return parsed, None
191
245
 
192
246
  except AutomationBackendUnavailableError as exc:
193
247
  print(f" Automation backend unavailable: {exc}", file=sys.stderr)
194
- return None
248
+ return None, "backend_unavailable"
195
249
  except subprocess.TimeoutExpired:
196
250
  print(f" Automation backend timeout ({CLAUDE_TIMEOUT}s)", file=sys.stderr)
251
+ return None, "timeout"
252
+
253
+
254
+ def _write_slim_shared_context(full_path: Path) -> Path:
255
+ """Generate (once per run) a slim version of shared-context.txt.
256
+
257
+ The full shared context can exceed 400KB — feeding that to every
258
+ per-session extraction means the Claude CLI subprocess spends most of its
259
+ context window on repeated DB metadata instead of the session transcript.
260
+ The slim version keeps the top-level structure + the first ~200 lines so
261
+ the model still has a summary of followups/learnings/diary samples.
262
+ """
263
+ slim_path = full_path.with_suffix(".slim.txt")
264
+ try:
265
+ raw = full_path.read_text(errors="replace")
266
+ except OSError:
267
+ return full_path
268
+ lines = raw.splitlines()
269
+ head = lines[:200]
270
+ header = [
271
+ "# Shared context (slim) — " + full_path.name,
272
+ f"# original_bytes={full_path.stat().st_size} original_lines={len(lines)}",
273
+ f"# trimmed_to=first_{len(head)}_lines",
274
+ "",
275
+ ]
276
+ try:
277
+ slim_path.write_text("\n".join(header + head), encoding="utf-8")
278
+ except OSError:
279
+ return full_path
280
+ return slim_path
281
+
282
+
283
+ def _load_checkpoint(path: Path) -> dict | None:
284
+ if not path.exists():
285
+ return None
286
+ try:
287
+ with path.open() as fh:
288
+ return json.load(fh)
289
+ except (json.JSONDecodeError, OSError):
197
290
  return None
198
291
 
199
292
 
293
+ def _save_checkpoint(path: Path, payload: dict) -> None:
294
+ try:
295
+ with path.open("w") as fh:
296
+ json.dump(payload, fh, indent=2, ensure_ascii=False)
297
+ except OSError as exc:
298
+ print(f" Warning: could not persist checkpoint {path}: {exc}", file=sys.stderr)
299
+
300
+
200
301
  def main():
201
302
  target_date = sys.argv[1] if len(sys.argv) > 1 else datetime.now().strftime("%Y-%m-%d")
202
303
 
@@ -237,12 +338,17 @@ def main():
237
338
  print(f"[extract] Output: {output_file}")
238
339
  return
239
340
 
240
- # Shared context file (followups, learnings, DB state)
241
- shared_context_file = date_dir / "shared-context.txt" if date_dir.exists() else None
242
- if shared_context_file and shared_context_file.exists():
243
- print(f"[extract] Shared context: {shared_context_file} ({shared_context_file.stat().st_size / 1024:.0f} KB)")
341
+ # Shared context file (followups, learnings, DB state).
342
+ # Use a slim copy for the per-session prompts so the Claude CLI doesn't
343
+ # re-read the full 400+KB dump for every single session.
344
+ full_shared_context = date_dir / "shared-context.txt" if date_dir.exists() else None
345
+ shared_context_file: Path | None = None
346
+ if full_shared_context and full_shared_context.exists():
347
+ shared_context_file = _write_slim_shared_context(full_shared_context)
348
+ full_kb = full_shared_context.stat().st_size / 1024
349
+ slim_kb = shared_context_file.stat().st_size / 1024
350
+ print(f"[extract] Shared context: {shared_context_file} ({slim_kb:.0f} KB slim, {full_kb:.0f} KB full)")
244
351
  else:
245
- shared_context_file = None
246
352
  print("[extract] No shared context file")
247
353
 
248
354
  print(f"[extract] Phase 2: Analyzing {len(session_files)} sessions for {target_date}")
@@ -255,6 +361,7 @@ def main():
255
361
  all_extractions = []
256
362
  total_findings = 0
257
363
  skipped = 0
364
+ poisoned = 0
258
365
  # Two attempts is enough: if a session's extraction fails twice, the cause is
259
366
  # almost always deterministic (JSON parse, schema violation) rather than transient,
260
367
  # so further retries just burn time. Skip and continue instead.
@@ -264,26 +371,42 @@ def main():
264
371
  sid_safe = _safe_session_slug(session_id)[:40]
265
372
  checkpoint_file = checkpoint_dir / f"{sid_safe}.json"
266
373
 
267
- # Resume: skip already-processed sessions
268
- if checkpoint_file.exists():
269
- try:
270
- with open(checkpoint_file) as f:
271
- cached = json.load(f)
272
- findings_count = len(cached.get("findings", []))
273
- total_findings += findings_count
274
- all_extractions.append(cached)
275
- skipped += 1
276
- print(f"[extract] Session {i + 1}/{len(session_files)}: {session_id} (cached, {findings_count} findings)")
277
- continue
278
- except (json.JSONDecodeError, KeyError):
279
- pass # Corrupted checkpoint, re-process
374
+ cached = _load_checkpoint(checkpoint_file)
375
+ cached_error_count = int((cached or {}).get("error_count", 0))
376
+ cached_last_error_kind = (cached or {}).get("last_error_kind", "")
377
+
378
+ # Successful prior checkpoint → reuse as-is
379
+ if cached and not cached.get("error") and cached.get("findings") is not None:
380
+ findings_count = len(cached.get("findings", []))
381
+ total_findings += findings_count
382
+ all_extractions.append(cached)
383
+ skipped += 1
384
+ print(f"[extract] Session {i + 1}/{len(session_files)}: {session_id} (cached, {findings_count} findings)")
385
+ continue
386
+
387
+ # Poisoned checkpoint → skip without burning API calls
388
+ if cached_error_count >= MAX_POISON_ATTEMPTS:
389
+ poisoned += 1
390
+ all_extractions.append(cached or {
391
+ "session_id": session_id,
392
+ "findings": [],
393
+ "error": "poisoned",
394
+ "error_count": cached_error_count,
395
+ "last_error_kind": cached_last_error_kind,
396
+ })
397
+ print(
398
+ f"[extract] Session {i + 1}/{len(session_files)}: {session_id} "
399
+ f"(poisoned, {cached_error_count} prior failures — skip)"
400
+ )
401
+ continue
280
402
 
281
403
  print(f"[extract] Session {i + 1}/{len(session_files)}: {session_id}")
282
404
 
283
- # Retry loop
405
+ # Retry loop within this run
284
406
  result = None
407
+ last_error_kind = ""
285
408
  for attempt in range(1, MAX_RETRIES + 1):
286
- result = analyze_session(
409
+ result, error_kind = analyze_session(
287
410
  session_id,
288
411
  date_dir,
289
412
  shared_context_file,
@@ -291,47 +414,77 @@ def main():
291
414
  )
292
415
  if result:
293
416
  break
417
+ last_error_kind = error_kind or "unknown"
294
418
  if attempt < MAX_RETRIES:
295
- print(f" -> Attempt {attempt}/{MAX_RETRIES} failed, retrying...")
419
+ print(f" -> Attempt {attempt}/{MAX_RETRIES} failed ({last_error_kind}), retrying...")
296
420
 
297
421
  if result:
298
422
  findings_count = len(result.get("findings", []))
299
423
  total_findings += findings_count
424
+ # Persist success and reset error_count so transient past failures
425
+ # don't keep counting against the session.
426
+ result.setdefault("session_id", session_id)
427
+ result["error_count"] = 0
428
+ result["last_error_kind"] = ""
300
429
  all_extractions.append(result)
301
- # Save checkpoint
302
- with open(checkpoint_file, "w") as f:
303
- json.dump(result, f, indent=2, ensure_ascii=False)
430
+ _save_checkpoint(checkpoint_file, result)
304
431
  print(f" -> {findings_count} findings extracted (checkpointed)")
305
432
  else:
306
- print(f" -> Failed after {MAX_RETRIES} attempts, marking as failed")
433
+ # Transient errors (API overloaded, rate-limit, timeout, killed
434
+ # by signal) should NOT increment the poison counter — they're
435
+ # not the session's fault. They also don't persist a fresh
436
+ # checkpoint, so the next deep-sleep run will retry cleanly.
437
+ transient = last_error_kind in TRANSIENT_ERROR_KINDS
438
+ if transient:
439
+ print(f" -> Transient failure ({last_error_kind}), will retry on next run.")
440
+ all_extractions.append({
441
+ "session_id": session_id,
442
+ "findings": [],
443
+ "error": "transient",
444
+ "error_count": cached_error_count,
445
+ "last_error_kind": last_error_kind,
446
+ })
447
+ # Do not touch the checkpoint — the next run gets a clean retry.
448
+ continue
449
+
450
+ new_count = cached_error_count + 1
451
+ state = "poisoned" if new_count >= MAX_POISON_ATTEMPTS else "failed"
452
+ print(
453
+ f" -> Deterministic failure #{new_count}/{MAX_POISON_ATTEMPTS} "
454
+ f"({last_error_kind}); marked as {state}."
455
+ )
307
456
  failed_entry = {
308
457
  "session_id": session_id,
309
458
  "findings": [],
310
- "error": f"Extraction failed after {MAX_RETRIES} attempts"
459
+ "error": state,
460
+ "error_count": new_count,
461
+ "last_error_kind": last_error_kind,
311
462
  }
312
463
  all_extractions.append(failed_entry)
313
- # Save failed checkpoint too (so we don't retry forever)
314
- with open(checkpoint_file, "w") as f:
315
- json.dump(failed_entry, f, indent=2, ensure_ascii=False)
464
+ _save_checkpoint(checkpoint_file, failed_entry)
465
+ if state == "poisoned":
466
+ poisoned += 1
316
467
 
317
468
  # Merge into output
318
469
  output = {
319
470
  "date": target_date,
320
471
  "sessions_analyzed": len(session_files),
321
- "sessions_succeeded": len([e for e in all_extractions if "error" not in e]),
472
+ "sessions_succeeded": len([e for e in all_extractions if not e.get("error")]),
322
473
  "sessions_cached": skipped,
474
+ "sessions_poisoned": poisoned,
323
475
  "total_findings": total_findings,
324
- "extractions": all_extractions
476
+ "extractions": all_extractions,
325
477
  }
326
478
 
327
479
  output_file = DEEP_SLEEP_DIR / f"{target_date}-extractions.json"
328
480
  with open(output_file, "w") as f:
329
481
  json.dump(output, f, indent=2, ensure_ascii=False)
330
482
 
331
- if skipped:
332
- print(f"\n[extract] Done. {total_findings} findings from {len(session_files)} sessions ({skipped} cached, {len(session_files) - skipped} new).")
333
- else:
334
- print(f"\n[extract] Done. {total_findings} findings from {len(session_files)} sessions.")
483
+ fresh_runs = len(session_files) - skipped - poisoned
484
+ print(
485
+ f"\n[extract] Done. {total_findings} findings from {len(session_files)} sessions "
486
+ f"({skipped} cached, {fresh_runs} fresh, {poisoned} poisoned)."
487
+ )
335
488
  print(f"[extract] Output: {output_file}")
336
489
 
337
490
 
@@ -5,6 +5,16 @@
5
5
  #
6
6
  # Wraps any cron command to automatically record start/end/exit_code/summary.
7
7
  # Used by sync.py when generating LaunchAgents from manifest.json.
8
+ #
9
+ # Two-phase recording (start → end):
10
+ # 1. INSERT cron_runs row at start with ended_at=NULL so the watchdog can
11
+ # distinguish "currently running" from "missed / stuck". Without this,
12
+ # any job that exceeds the next watchdog tick (interval_seconds=1800 by
13
+ # default) looks stale and the watchdog may kickstart -k over it — which
14
+ # is exactly the loop that broke deep-sleep between 2026-04-14 and 2026-04-17.
15
+ # 2. UPDATE the row at end with ended_at + exit_code + summary.
16
+ # 3. Trap SIGTERM / SIGINT so wrappers killed mid-flight still close their
17
+ # row (exit_code=143 or 130) instead of leaving it NULL forever.
8
18
 
9
19
  set -uo pipefail
10
20
 
@@ -33,84 +43,159 @@ print(datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
33
43
  PY
34
44
  )
35
45
 
36
- # Run the actual command, capture output
46
+ # Phase 1: INSERT row at start (ended_at NULL = "running").
47
+ # ROW_ID empty on DB failure; spool-fallback at the end handles that.
48
+ ROW_ID=""
49
+ ROW_ID=$(python3 - "$DB" "$CRON_ID" "$STARTED_AT" <<'PY' 2>/dev/null
50
+ from __future__ import annotations
51
+ import sqlite3
52
+ import sys
53
+ db_path, cron_id, started_at = sys.argv[1:]
54
+ conn = sqlite3.connect(db_path)
55
+ try:
56
+ cur = conn.execute(
57
+ "INSERT INTO cron_runs (cron_id, started_at, ended_at) VALUES (?, ?, NULL)",
58
+ (cron_id, started_at),
59
+ )
60
+ conn.commit()
61
+ print(cur.lastrowid)
62
+ finally:
63
+ conn.close()
64
+ PY
65
+ )
66
+
37
67
  OUTPUT_FILE=$(mktemp)
38
- trap 'rm -f "$OUTPUT_FILE"' EXIT
39
- "$@" > "$OUTPUT_FILE" 2>&1
40
- EXIT_CODE=$?
41
- ENDED_AT=$(python3 - <<'PY'
68
+ EXIT_CODE=0
69
+ SIGNAL_NAME=""
70
+
71
+ # finalize_row DB writer — also used by signal traps.
72
+ # Reads $EXIT_CODE / $SIGNAL_NAME / $OUTPUT_FILE from the outer scope.
73
+ finalize_row() {
74
+ local ended_at duration summary error
75
+ ended_at=$(python3 - <<'PY'
42
76
  from datetime import datetime, timezone
43
77
  print(datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
44
78
  PY
45
79
  )
46
- DURATION_SECS=$(python3 - <<PY
80
+ duration=$(python3 - <<PY
47
81
  start = float("$START_EPOCH")
48
82
  import time
49
83
  print(round(time.time() - start, 1))
50
84
  PY
51
85
  )
86
+ summary=$(tail -5 "$OUTPUT_FILE" 2>/dev/null | grep -v "^$" | tail -1 | head -c 500)
87
+ error=""
88
+ if [ "$EXIT_CODE" -ne 0 ]; then
89
+ if [ -n "$SIGNAL_NAME" ]; then
90
+ error="Killed by $SIGNAL_NAME (exit $EXIT_CODE)"
91
+ else
92
+ error=$(grep -i "error\|exception\|fail\|traceback" "$OUTPUT_FILE" 2>/dev/null | tail -1 | head -c 500)
93
+ fi
94
+ fi
52
95
 
53
- # Extract summary (last meaningful line, max 500 chars)
54
- SUMMARY=$(tail -5 "$OUTPUT_FILE" | grep -v "^$" | tail -1 | head -c 500)
55
-
56
- # Extract error if failed
57
- ERROR=""
58
- if [ $EXIT_CODE -ne 0 ]; then
59
- ERROR=$(grep -i "error\|exception\|fail\|traceback" "$OUTPUT_FILE" | tail -1 | head -c 500)
60
- fi
61
-
62
- if ! python3 - "$DB" "$CRON_ID" "$STARTED_AT" "$ENDED_AT" "$EXIT_CODE" "$SUMMARY" "$ERROR" "$DURATION_SECS" <<'PY'
96
+ # Update the row we inserted at start — or INSERT fresh if the start write failed.
97
+ if ! python3 - "$DB" "$ROW_ID" "$CRON_ID" "$STARTED_AT" "$ended_at" "$EXIT_CODE" "$summary" "$error" "$duration" <<'PY' 2>/dev/null
63
98
  from __future__ import annotations
64
-
65
99
  import sqlite3
66
100
  import sys
67
-
68
- db_path, cron_id, started_at, ended_at, exit_code, summary, error, duration_secs = sys.argv[1:]
101
+ db_path, row_id, cron_id, started_at, ended_at, exit_code, summary, error, duration_secs = sys.argv[1:]
69
102
  conn = sqlite3.connect(db_path)
70
103
  try:
71
- conn.execute(
72
- """
73
- INSERT INTO cron_runs (
74
- cron_id, started_at, ended_at, exit_code, summary, error, duration_secs
75
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
76
- """,
77
- (
78
- cron_id,
79
- started_at,
80
- ended_at,
81
- int(exit_code),
82
- summary,
83
- error,
84
- float(duration_secs),
85
- ),
86
- )
104
+ if row_id:
105
+ conn.execute(
106
+ """
107
+ UPDATE cron_runs
108
+ SET ended_at=?, exit_code=?, summary=?, error=?, duration_secs=?
109
+ WHERE id=?
110
+ """,
111
+ (ended_at, int(exit_code), summary, error, float(duration_secs), int(row_id)),
112
+ )
113
+ else:
114
+ conn.execute(
115
+ """
116
+ INSERT INTO cron_runs (cron_id, started_at, ended_at, exit_code, summary, error, duration_secs)
117
+ VALUES (?, ?, ?, ?, ?, ?, ?)
118
+ """,
119
+ (cron_id, started_at, ended_at, int(exit_code), summary, error, float(duration_secs)),
120
+ )
87
121
  conn.commit()
88
122
  finally:
89
123
  conn.close()
90
124
  PY
91
- then
92
- mkdir -p "$SPOOL_DIR"
93
- SPOOL_FILE="$SPOOL_DIR/${CRON_ID}-$(date +%Y%m%d-%H%M%S)-$$.json"
94
- python3 - "$SPOOL_FILE" "$CRON_ID" "$STARTED_AT" "$ENDED_AT" "$EXIT_CODE" "$SUMMARY" "$ERROR" "$DURATION_SECS" <<'PY'
125
+ then
126
+ mkdir -p "$SPOOL_DIR"
127
+ local spool_file="$SPOOL_DIR/${CRON_ID}-$(date +%Y%m%d-%H%M%S)-$$.json"
128
+ python3 - "$spool_file" "$CRON_ID" "$STARTED_AT" "$ended_at" "$EXIT_CODE" "$summary" "$error" "$duration" <<'PY'
95
129
  from __future__ import annotations
96
-
97
130
  import json
98
131
  import sys
99
132
  from pathlib import Path
100
-
101
133
  spool_file, cron_id, started_at, ended_at, exit_code, summary, error, duration_secs = sys.argv[1:]
102
- payload = {
103
- "cron_id": cron_id,
104
- "started_at": started_at,
105
- "ended_at": ended_at,
106
- "exit_code": int(exit_code),
107
- "summary": summary,
108
- "error": error,
109
- "duration_secs": float(duration_secs),
110
- }
111
- Path(spool_file).write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
134
+ Path(spool_file).write_text(
135
+ json.dumps({
136
+ "cron_id": cron_id,
137
+ "started_at": started_at,
138
+ "ended_at": ended_at,
139
+ "exit_code": int(exit_code),
140
+ "summary": summary,
141
+ "error": error,
142
+ "duration_secs": float(duration_secs),
143
+ }, indent=2, ensure_ascii=False) + "\n",
144
+ encoding="utf-8",
145
+ )
112
146
  PY
113
- echo "[nexo-cron-wrapper] DB write failed; spooled run to $SPOOL_FILE" >&2
114
- fi
147
+ echo "[nexo-cron-wrapper] DB write failed; spooled run to $spool_file" >&2
148
+ fi
149
+ }
150
+
151
+ cleanup() {
152
+ rm -f "$OUTPUT_FILE"
153
+ }
154
+
155
+ CHILD_PID=""
156
+
157
+ on_signal() {
158
+ local sig="$1"
159
+ local code="$2"
160
+ SIGNAL_NAME="$sig"
161
+ EXIT_CODE="$code"
162
+ # Forward the signal to the child. Bash traps run AFTER the foreground
163
+ # command completes, which is why we launch the command in background
164
+ # and wait on its PID — otherwise a SIGTERM to the wrapper would be
165
+ # delivered only when the child finishes naturally, defeating the
166
+ # purpose of closing the cron_runs row on kill.
167
+ if [ -n "$CHILD_PID" ] && kill -0 "$CHILD_PID" 2>/dev/null; then
168
+ kill -TERM "$CHILD_PID" 2>/dev/null
169
+ # Brief grace period before escalating to SIGKILL so the child gets
170
+ # a chance to clean up on its own.
171
+ local waited=0
172
+ while [ $waited -lt 5 ] && kill -0 "$CHILD_PID" 2>/dev/null; do
173
+ sleep 1
174
+ waited=$((waited + 1))
175
+ done
176
+ kill -KILL "$CHILD_PID" 2>/dev/null
177
+ fi
178
+ finalize_row
179
+ cleanup
180
+ exit "$code"
181
+ }
182
+
183
+ trap cleanup EXIT
184
+ trap 'on_signal SIGTERM 143' TERM
185
+ trap 'on_signal SIGINT 130' INT
186
+ trap 'on_signal SIGHUP 129' HUP
187
+
188
+ "$@" > "$OUTPUT_FILE" 2>&1 &
189
+ CHILD_PID=$!
190
+
191
+ # `wait` is interruptible by signals — when the trap fires, wait returns
192
+ # immediately and on_signal() takes over. When the child finishes
193
+ # normally, wait yields its exit code and we fall through to finalize_row
194
+ # for the happy path.
195
+ wait "$CHILD_PID"
196
+ EXIT_CODE=$?
197
+ CHILD_PID=""
198
+
199
+ finalize_row
115
200
 
116
- exit $EXIT_CODE
201
+ exit "$EXIT_CODE"