-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathapp.py
More file actions
4352 lines (3719 loc) · 158 KB
/
Copy pathapp.py
File metadata and controls
4352 lines (3719 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import time
import subprocess # nosec B404
import tempfile
import threading
import queue
import uuid
import psutil
import hashlib
import hmac
import secrets
import binascii
import urllib.request
import urllib.parse
import re
import shutil
import logging
import urllib.error
from datetime import datetime, timezone
from pathlib import Path
from flask import Flask, request, jsonify, send_from_directory, Response
from werkzeug.exceptions import BadRequest
# Setup logger for DevShell backend logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("devshell")
from utils.validators import validate_safe_path, validate_git_branch, validate_repo_name
PBKDF2_ITERATIONS = 100_000
app = Flask(__name__, static_folder="ui", static_url_path="")
@app.errorhandler(ValueError)
def handle_validation_error(e):
return jsonify({"error": str(e)}), 400
BASE_DIR = os.environ.get(
"DEV_SHELL_DATA_DIR", os.path.dirname(os.path.abspath(__file__))
)
SCRIPTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts")
FAVORITES_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "favorites.json"
)
LOCKS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "locks.json")
LOG_ROOT = os.path.join(BASE_DIR, "logs")
EXECUTION_LOG_DIR = os.path.join(LOG_ROOT, "executions")
SESSION_LOG_DIR = os.path.join(LOG_ROOT, "sessions")
HISTORY_FILE = os.path.join(LOG_ROOT, "history.jsonl")
FAILED_HISTORY_FILE = os.path.join(LOG_ROOT, "failed.jsonl")
COMMAND_HISTORY_FILE = os.path.join(LOG_ROOT, "command_history.json")
WORKSPACE_DIR = os.path.join(LOG_ROOT, "workspaces")
WORKSPACE_STATE_FILE = os.path.join(WORKSPACE_DIR, "workspace_state.json")
WORKSPACE_PROFILE_DIR = os.path.join(WORKSPACE_DIR, "profiles")
os.makedirs(WORKSPACE_DIR, exist_ok=True)
os.makedirs(WORKSPACE_PROFILE_DIR, exist_ok=True)
# Reliability intelligence infrastructure (filesystem-only, append-friendly)
RELIABILITY_DIR = os.path.join(LOG_ROOT, 'reliability')
RELIABILITY_SUMMARY_VERSION = 1
RELIABILITY_SUMMARY_FILE = os.path.join(RELIABILITY_DIR, 'summary.json')
RELIABILITY_SUMMARY_TMP = os.path.join(RELIABILITY_DIR, 'summary.json.tmp')
RELIABILITY_SUMMARY_BACKUP = os.path.join(RELIABILITY_DIR, 'summary.json.backup')
RELIABILITY_EVENTS_FILE = os.path.join(RELIABILITY_DIR, 'events.jsonl')
RELIABILITY_TREND_WINDOW = 5
RELIABILITY_FLAKY_WINDOW = 10
RELIABILITY_SLOW_STDDEV = 2
MAX_RELIABILITY_EVENTS = 5000
RELIABILITY_REGRESSION_RECENT = 5
RELIABILITY_REGRESSION_BASELINE = 10
RELIABILITY_REGRESSION_THRESHOLD = 1.5
RELIABILITY_SYNC_EVENT_LOOKBACK = 100
RELIABILITY_AGGREGATION_TAIL = 2500
RELIABILITY_DIAGNOSTICS_TTL_SEC = 45
RELIABILITY_SUMMARY_SAVE_INTERVAL_SEC = 2.0
MAX_SESSION_SCAN_FOR_DIAGNOSTICS = 200
RELIABILITY_DIAGNOSTIC_SOURCES = {
'history': 'logs/history.jsonl',
'sessions': 'logs/sessions',
'workspace': 'logs/workspaces/workspace_state.json',
'reliability': 'logs/reliability/summary.json',
'failed_history': 'logs/failed.jsonl',
}
os.makedirs(RELIABILITY_DIR, exist_ok=True)
_reliability_cache_lock = threading.Lock()
_reliability_cache = {
'records': None,
'records_signature': None,
'diagnostics': None,
'diagnostics_signature': None,
}
_last_summary_save_monotonic = 0.0
# Failure classification types
FAILURE_TYPES = {
'permission_error': 'Permission denied or insufficient privileges',
'dependency_error': 'Missing dependency or import failed',
'timeout': 'Execution timeout exceeded',
'shell_error': 'Shell error or syntax issue',
'missing_file': 'Required file not found',
'interrupted': 'Execution interrupted by user',
'unknown_failure': 'Unknown or unclassified failure',
}
SESSIONS_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "sessions.json"
)
MAX_HISTORY_ENTRIES = 1000
MAX_FAILED_HISTORY_ENTRIES = 500
MAX_EXECUTION_LOG_FILES = 250
LOG_RETENTION_DAYS = 30
MAX_HISTORY_EXCERPT_CHARS = 2000
# Thread-safe registry for running script processes (keyed by run_id)
active_processes = {}
active_processes_lock = threading.Lock()
def validate_workspace_snapshot(data):
if not isinstance(data, dict):
return False, "Workspace snapshot must be an object"
terminals = data.get("terminals")
if terminals is not None and not isinstance(terminals, list):
return False, "Invalid terminals structure"
active_terminal = data.get("activeTerminalId")
if active_terminal is not None and not isinstance(active_terminal, int):
return False, "Invalid active terminal"
version = data.get("version")
if version is not None and not isinstance(version, int):
return False, "Invalid snapshot version"
active_script = data.get("activeScript")
if active_script is not None and not isinstance(active_script, str):
return False, "Invalid active script reference"
return True, None
def _parse_workspace_time(value):
if not value:
return None
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except (TypeError, ValueError):
return None
def workspace_integrity_warnings(snapshot, saved_at=None):
warnings = []
if not isinstance(snapshot, dict):
return ["Workspace snapshot is malformed."]
terminals = snapshot.get("terminals")
if not isinstance(terminals, list) or not terminals:
warnings.append("Workspace snapshot has no terminal list.")
terminals = []
terminal_ids = {item for item in terminals if isinstance(item, int)}
if len(terminal_ids) != len(terminals):
warnings.append("Workspace snapshot contains invalid terminal ids.")
active_terminal = snapshot.get("activeTerminalId")
if active_terminal is not None and active_terminal not in terminal_ids:
warnings.append("Active terminal is missing from the terminal list.")
terminal_snapshots = snapshot.get("terminalSnapshots", [])
if terminal_snapshots is not None and not isinstance(terminal_snapshots, list):
warnings.append("Terminal snapshot payload is malformed.")
elif isinstance(terminal_snapshots, list):
for terminal_snapshot in terminal_snapshots:
if not isinstance(terminal_snapshot, dict):
warnings.append("Terminal snapshot entry is malformed.")
break
snap_id = terminal_snapshot.get("id")
if snap_id is not None and snap_id not in terminal_ids:
warnings.append("Terminal snapshot references a missing terminal.")
break
replay_state = snapshot.get("replayState") or {}
if not isinstance(replay_state, dict):
warnings.append("Replay state is malformed.")
elif replay_state.get("active"):
session_id = replay_state.get("sessionId")
if not session_id:
warnings.append("Active replay state is missing a session reference.")
else:
replay_path = os.path.join(SESSION_LOG_DIR, f"{session_id}.json")
if not os.path.exists(replay_path):
warnings.append("Replay session referenced by snapshot is missing.")
saved_dt = _parse_workspace_time(saved_at)
if saved_at and not saved_dt:
warnings.append("Snapshot timestamp is malformed.")
elif saved_dt:
if saved_dt.tzinfo is None:
saved_dt = saved_dt.replace(tzinfo=timezone.utc)
if (_utc_now() - saved_dt).days > 14:
warnings.append("Snapshot is older than 14 days.")
return warnings
def load_workspace_state():
if not os.path.exists(WORKSPACE_STATE_FILE):
return None
try:
with open(WORKSPACE_STATE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
corrupted_path = WORKSPACE_STATE_FILE + ".corrupted"
try:
shutil.move(WORKSPACE_STATE_FILE, corrupted_path)
except Exception: # nosec B110
pass
return {"corrupted": True, "error": str(e)}
def save_workspace_state(data):
valid, error = validate_workspace_snapshot(data)
if not valid:
return False, error
payload = {
"version": 2,
"saved_at": datetime.now(timezone.utc).isoformat(),
"workspace": data,
}
try:
with open(WORKSPACE_STATE_FILE, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
_invalidate_reliability_cache(keys=['diagnostics'])
return True, None
except Exception as e:
return False, str(e)
def get_workspace_profile_path(name):
safe_name = re.sub(r"[^a-zA-Z0-9_-]", "_", name)
return os.path.join(WORKSPACE_PROFILE_DIR, f"{safe_name}.json")
def list_workspace_profiles():
profiles = []
for file in os.listdir(WORKSPACE_PROFILE_DIR):
if not file.endswith(".json"):
continue
profiles.append(file[:-5])
return sorted(profiles)
def _ensure_log_dirs():
os.makedirs(EXECUTION_LOG_DIR, exist_ok=True)
os.makedirs(SESSION_LOG_DIR, exist_ok=True)
os.makedirs(RELIABILITY_DIR, exist_ok=True)
def _utc_now():
return datetime.now(timezone.utc)
def _iso_now():
return _utc_now().isoformat(timespec="seconds")
def _slugify(value, fallback="execution"):
safe = re.sub(r"[^A-Za-z0-9._-]+", "-", str(value or "")).strip("-._")
return safe[:48] or fallback
def _append_jsonl(file_path, record):
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "a", encoding="utf-8", newline="\n") as f:
json.dump(record, f, ensure_ascii=False)
f.write("\n")
def _read_jsonl(file_path, max_entries=None):
records = []
if not os.path.exists(file_path):
return records
try:
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
if max_entries:
lines = f.readlines()[-max_entries:]
else:
lines = f
for line in lines:
line = line.strip()
if not line:
continue
try:
parsed = json.loads(line)
if isinstance(parsed, dict):
records.append(parsed)
except (json.JSONDecodeError, TypeError, ValueError):
continue
except OSError:
return []
return records
def _reliability_source_signature():
"""Cheap cache key from mtimes of reliability input files."""
paths = (HISTORY_FILE, FAILED_HISTORY_FILE, RELIABILITY_SUMMARY_FILE, WORKSPACE_STATE_FILE)
signature = []
for path in paths:
try:
signature.append((path, os.path.getmtime(path)))
except OSError:
signature.append((path, None))
if os.path.isdir(SESSION_LOG_DIR):
try:
session_count = len([
name for name in os.listdir(SESSION_LOG_DIR)
if name.endswith('.json') and '.corrupted' not in name
])
session_mtime = os.path.getmtime(SESSION_LOG_DIR)
except OSError:
session_count = 0
session_mtime = None
signature.append((SESSION_LOG_DIR, session_mtime, session_count))
return tuple(signature)
def _invalidate_reliability_cache(keys=None):
with _reliability_cache_lock:
if keys:
for key in keys:
_reliability_cache[key] = None
else:
_reliability_cache['records'] = None
_reliability_cache['records_signature'] = None
_reliability_cache['diagnostics'] = None
_reliability_cache['diagnostics_signature'] = None
def _maybe_save_reliability_summary(summary, force=False):
"""Throttle summary.json writes during rapid execution bursts."""
global _last_summary_save_monotonic
now = time.perf_counter()
if not force and (now - _last_summary_save_monotonic) < RELIABILITY_SUMMARY_SAVE_INTERVAL_SEC:
return True
if _save_reliability_summary(summary):
_last_summary_save_monotonic = now
_invalidate_reliability_cache(keys=['diagnostics'])
return True
return False
def _sanitize_execution_record(entry):
"""Validate and normalize execution metadata from history/session sources."""
if not isinstance(entry, dict):
return None
execution_id = entry.get('id')
if not execution_id or not isinstance(execution_id, (str, int)):
return None
execution_id = str(execution_id).strip()[:64]
if not execution_id:
return None
success = bool(entry.get('success', entry.get('status') == 'success'))
exit_code = _normalize_exit_code(entry.get('exit_code'))
duration_seconds = _normalize_duration(entry.get('duration_seconds'))
display_name = str(entry.get('display_name') or entry.get('display') or '_unknown')[:256]
kind = str(entry.get('kind') or 'script')[:32]
if kind not in ('script', 'command'):
kind = 'script'
sanitized = {
'id': execution_id,
'kind': kind,
'display_name': display_name,
'command': str(entry.get('command', ''))[:2000],
'started_at': str(entry.get('started_at', ''))[:64],
'finished_at': str(entry.get('finished_at', ''))[:64],
'status': 'success' if success else 'failed',
'success': success,
'exit_code': exit_code,
'duration_seconds': duration_seconds if duration_seconds > 0 else None,
'log_file': str(entry.get('log_file', ''))[:256],
'session_file': str(entry.get('session_file', ''))[:128],
'output_excerpt': str(entry.get('output_excerpt', ''))[:MAX_HISTORY_EXCERPT_CHARS],
'error': str(entry.get('error', ''))[:MAX_HISTORY_EXCERPT_CHARS],
'source': str(entry.get('source', 'history'))[:32],
}
if entry.get('failure_type'):
failure_type = entry.get('failure_type')
sanitized['failure_type'] = failure_type if failure_type in FAILURE_TYPES else 'unknown_failure'
elif not success:
sanitized['failure_type'] = _classify_failure(
exit_code,
error_message=sanitized.get('error', ''),
output=sanitized.get('output_excerpt', ''),
)
return sanitized
def _index_records_by_script(records):
indexed = {}
for record in records:
name = record.get('display_name')
if not name:
continue
indexed.setdefault(name, []).append(record)
return indexed
def _trim_jsonl(file_path, max_entries):
if not os.path.exists(file_path):
return
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
if len(lines) <= max_entries:
return
with open(file_path, "w", encoding="utf-8", newline="\n") as f:
f.writelines(lines[-max_entries:])
def _cleanup_old_execution_logs():
if not os.path.exists(EXECUTION_LOG_DIR):
return
now = time.time()
cutoff = now - (LOG_RETENTION_DAYS * 24 * 60 * 60)
logs = []
for name in os.listdir(EXECUTION_LOG_DIR):
path = os.path.join(EXECUTION_LOG_DIR, name)
if not os.path.isfile(path):
continue
try:
logs.append((os.path.getmtime(path), path))
except OSError:
continue
for _, path in logs:
try:
if os.path.getmtime(path) < cutoff:
os.remove(path)
except OSError:
pass
logs = sorted(logs, key=lambda item: item[0], reverse=True)
for _, path in logs[MAX_EXECUTION_LOG_FILES:]:
try:
os.remove(path)
except OSError:
pass
def _format_duration(seconds):
if seconds < 60:
return f"{seconds:.2f}s"
minutes = int(seconds // 60)
remaining = seconds % 60
return f"{minutes}m {remaining:.1f}s"
def _start_execution_record(kind, display_name, command_text, shell_cmd="", cwd="", arguments=None):
_ensure_log_dirs()
started_at = _utc_now()
monotonic_start = time.perf_counter()
execution_id = uuid.uuid4().hex[:8]
timestamp_token = started_at.strftime("%Y%m%dT%H%M%SZ")
log_name = f"{timestamp_token}_{kind}_{_slugify(display_name)}_{execution_id}.log"
log_path = os.path.join(EXECUTION_LOG_DIR, log_name)
log_handle = open(log_path, "w", encoding="utf-8", newline="\n")
# Validate and normalize arguments
if arguments is None:
arguments = []
elif not isinstance(arguments, list):
arguments = []
else:
# Ensure all arguments are strings
arguments = [str(arg) for arg in arguments if arg is not None]
record = {
"id": execution_id,
"kind": kind,
"display_name": display_name,
"command": command_text,
"shell": shell_cmd,
"cwd": cwd,
"arguments": arguments,
"started_at": started_at.isoformat(),
"status": "running",
"exit_code": None,
"duration_seconds": None,
"log_file": log_name,
"log_path": log_path,
"output_excerpt": "",
"success": False,
"session_file": f"{execution_id}.json",
}
log_handle.write(f'[{record["started_at"]}] execution started\n')
log_handle.write(f"kind: {kind}\n")
log_handle.write(f"id: {execution_id}\n")
log_handle.write(f"display: {display_name}\n")
log_handle.write(f"command: {command_text}\n")
if shell_cmd:
log_handle.write(f"shell: {shell_cmd}\n")
if cwd:
log_handle.write(f"cwd: {cwd}\n")
if arguments:
log_handle.write(f"arguments: {json.dumps(arguments)}\n")
log_handle.write("\n")
log_handle.flush()
session_data = {
"metadata": {
"id": execution_id,
"kind": kind,
"display_name": display_name,
"command": command_text,
"shell": shell_cmd,
"cwd": cwd,
"arguments": arguments,
"started_at": started_at.isoformat(),
},
"events": [],
}
return {
"record": record,
"handle": log_handle,
"excerpt_lines": [],
"excerpt_size": 0,
"session_data": session_data,
"monotonic_start": monotonic_start,
}
def _append_execution_line(execution, stream_type, content):
if execution is None:
return
line = content.rstrip("\n")
if not line and stream_type != "system":
return
timestamp = _iso_now()
elapsed = round(time.perf_counter() - execution["monotonic_start"], 4)
execution["session_data"]["events"].append(
{"timestamp": elapsed, "stream": stream_type, "content": line}
)
execution["handle"].write(f"[{timestamp}] {stream_type}: {line}\n")
execution["handle"].flush()
excerpt_line = f"{stream_type}: {line}"
execution["excerpt_lines"].append(excerpt_line)
execution["excerpt_size"] += len(excerpt_line) + 1
while (
execution["excerpt_lines"]
and execution["excerpt_size"] > MAX_HISTORY_EXCERPT_CHARS
):
removed = execution["excerpt_lines"].pop(0)
execution["excerpt_size"] -= len(removed) + 1
def _finalize_execution(
execution,
success,
exit_code,
duration_seconds,
resource_usage=None,
error_message="",
):
if execution is None:
return None
record = execution["record"]
record["status"] = "success" if success else "failed"
record["success"] = bool(success)
record["exit_code"] = int(exit_code) if exit_code is not None else None
record["duration_seconds"] = (
round(duration_seconds, 3) if duration_seconds is not None else None
)
record["duration"] = _format_duration(duration_seconds or 0)
record["finished_at"] = _iso_now()
record["output_excerpt"] = "\n".join(execution["excerpt_lines"])[
-MAX_HISTORY_EXCERPT_CHARS:
]
if resource_usage:
record["resources"] = resource_usage
if error_message:
record["error"] = error_message
execution["handle"].write("\n")
execution["handle"].write(f'[{record["finished_at"]}] status: {record["status"]}\n')
if record["exit_code"] is not None:
execution["handle"].write(f'exit_code: {record["exit_code"]}\n')
if record["duration_seconds"] is not None:
execution["handle"].write(f'duration_seconds: {record["duration_seconds"]}\n')
if error_message:
execution["handle"].write(f"error: {error_message}\n")
if resource_usage:
execution["handle"].write(
f"resources: {json.dumps(resource_usage, ensure_ascii=False)}\n"
)
session_path = os.path.join(SESSION_LOG_DIR, record["session_file"])
execution["session_data"]["metadata"].update(
{
"finished_at": record["finished_at"],
"duration_seconds": record["duration_seconds"],
"exit_code": record["exit_code"],
"status": record["status"],
"success": record["success"],
}
)
if resource_usage:
execution["session_data"]["metadata"]["resources"] = resource_usage
with open(session_path, "w", encoding="utf-8") as sf:
json.dump(execution["session_data"], sf, indent=2, ensure_ascii=False)
execution["handle"].close()
history_record = {
"id": record["id"],
"kind": record["kind"],
"session_file": record["session_file"],
"display_name": record["display_name"],
"command": record["command"],
"shell": record["shell"],
"cwd": record["cwd"],
"arguments": record.get("arguments", []),
"started_at": record["started_at"],
"finished_at": record["finished_at"],
"status": record["status"],
"success": record["success"],
"exit_code": record["exit_code"],
"duration_seconds": record["duration_seconds"],
"duration": record["duration"],
"log_file": record["log_file"],
"output_excerpt": record["output_excerpt"],
}
if error_message:
history_record["error"] = error_message
if resource_usage:
history_record["resources"] = resource_usage
# Add failure classification for failed executions
if not success:
failure_type = _classify_failure(
record['exit_code'],
error_message=error_message,
output=record['output_excerpt']
)
history_record['failure_type'] = failure_type
_append_jsonl(HISTORY_FILE, history_record)
if not success:
_append_jsonl(FAILED_HISTORY_FILE, history_record)
_trim_jsonl(HISTORY_FILE, MAX_HISTORY_ENTRIES)
_trim_jsonl(FAILED_HISTORY_FILE, MAX_FAILED_HISTORY_ENTRIES)
_cleanup_old_execution_logs()
_invalidate_reliability_cache()
_update_reliability_after_execution(history_record)
_sync_reliability_from_session_file(record['session_file'])
return history_record
def load_command_history():
if not os.path.exists(COMMAND_HISTORY_FILE):
return []
try:
with open(COMMAND_HISTORY_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return []
def save_command_history(command):
if not command.strip():
return
history = load_command_history()
# Remove duplicates
history = [c for c in history if c != command]
history.insert(0, command)
# Keep latest 200
history = history[:200]
with open(COMMAND_HISTORY_FILE, "w", encoding="utf-8") as f:
json.dump(history, f, indent=2)
def _load_history_entries(query="", status="all", kind="all", limit=200):
entries = _read_jsonl(HISTORY_FILE)
query = (query or "").strip().lower()
status = (status or "all").strip().lower()
kind = (kind or "all").strip().lower()
def matches(entry):
if status != "all" and entry.get("status", "").lower() != status:
return False
if kind != "all" and entry.get("kind", "").lower() != kind:
return False
if not query:
return True
haystack = " ".join(
[
str(entry.get("command", "")),
str(entry.get("display_name", "")),
str(entry.get("output_excerpt", "")),
str(entry.get("status", "")),
str(entry.get("kind", "")),
str(entry.get("exit_code", "")),
]
).lower()
return query in haystack
filtered = [entry for entry in reversed(entries) if matches(entry)]
return filtered[:limit]
def _history_summary():
entries = _read_jsonl(HISTORY_FILE)
total = len(entries)
failed = sum(1 for entry in entries if entry.get("status") == "failed")
scripts = sum(1 for entry in entries if entry.get("kind") == "script")
commands = sum(1 for entry in entries if entry.get("kind") == "command")
return {
"total": total,
"failed": failed,
"successful": total - failed,
"scripts": scripts,
"commands": commands,
}
# ─── Reliability Intelligence Infrastructure ───────────────────────
def _corrupted_fallback_path(file_path):
return file_path + '.corrupted'
def _isolate_corrupted_file(file_path):
if not os.path.exists(file_path):
return
corrupted = _corrupted_fallback_path(file_path)
suffix = 1
while os.path.exists(corrupted):
corrupted = f'{file_path}.corrupted.{suffix}'
suffix += 1
try:
shutil.move(file_path, corrupted)
except OSError:
pass
def _safe_load_json(file_path, default=None, required_keys=None):
"""Load JSON with corruption isolation via .corrupted fallback files."""
default = default if default is not None else {}
required_keys = required_keys or []
if not os.path.exists(file_path):
return json.loads(json.dumps(default))
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if not isinstance(data, dict):
raise ValueError('expected object')
if required_keys and not all(key in data for key in required_keys):
raise ValueError('missing required keys')
return data
except (json.JSONDecodeError, OSError, ValueError, TypeError):
_isolate_corrupted_file(file_path)
return json.loads(json.dumps(default))
def _migrate_reliability_summary(data):
"""Upgrade on-disk summary payloads to the current schema version."""
if not isinstance(data, dict):
data = {}
version = data.get('version')
if version is None:
# Pre-version summaries: preserve scripts/global, stamp v1
data = {
'version': RELIABILITY_SUMMARY_VERSION,
'scripts': data.get('scripts') if isinstance(data.get('scripts'), dict) else {},
'global': data.get('global') if isinstance(data.get('global'), dict) else {},
'updated_at': data.get('updated_at'),
}
elif version < RELIABILITY_SUMMARY_VERSION:
data['version'] = RELIABILITY_SUMMARY_VERSION
elif version > RELIABILITY_SUMMARY_VERSION:
# Forward-compatible: normalize what we understand today
data['version'] = RELIABILITY_SUMMARY_VERSION
return data
def _cap_failure_breakdown(breakdown):
"""Keep failure_breakdown bounded to known failure types only."""
if not isinstance(breakdown, dict):
return {}
capped = {}
overflow = 0
for key, value in breakdown.items():
count = max(0, int(value or 0))
if count <= 0:
continue
if key in FAILURE_TYPES:
capped[key] = capped.get(key, 0) + count
else:
overflow += count
if overflow:
capped['unknown_failure'] = capped.get('unknown_failure', 0) + overflow
return capped
def _load_reliability_summary():
"""Load reliability summary from storage with backup and corruption recovery."""
default = {'version': RELIABILITY_SUMMARY_VERSION, 'scripts': {}, 'global': {}}
corrupted = False
data = _migrate_reliability_summary(_safe_load_json(
RELIABILITY_SUMMARY_FILE,
default=default,
required_keys=['scripts'],
))
if not data.get('scripts') and os.path.exists(RELIABILITY_SUMMARY_FILE + '.corrupted'):
corrupted = True
if data.get('scripts'):
normalized = _normalize_reliability_summary(data)
if corrupted:
normalized['corrupted'] = True
return normalized
if os.path.exists(RELIABILITY_SUMMARY_BACKUP):
backup = _migrate_reliability_summary(_safe_load_json(
RELIABILITY_SUMMARY_BACKUP,
default=default,
required_keys=['scripts'],
))
if backup.get('scripts'):
normalized = _normalize_reliability_summary(backup)
normalized['corrupted'] = True
return normalized
return _normalize_reliability_summary(default)
def _save_reliability_summary(summary):
"""Persist summary via tmp file + os.replace for crash-safe atomic writes."""
try:
payload = _normalize_reliability_summary(summary)
if os.path.exists(RELIABILITY_SUMMARY_FILE):
try:
shutil.copy2(RELIABILITY_SUMMARY_FILE, RELIABILITY_SUMMARY_BACKUP)
except OSError:
pass
payload['updated_at'] = _iso_now()
os.makedirs(RELIABILITY_DIR, exist_ok=True)
with open(RELIABILITY_SUMMARY_TMP, 'w', encoding='utf-8') as handle:
json.dump(payload, handle, indent=2, ensure_ascii=False)
handle.flush()
os.fsync(handle.fileno())
os.replace(RELIABILITY_SUMMARY_TMP, RELIABILITY_SUMMARY_FILE)
return True
except OSError:
try:
if os.path.exists(RELIABILITY_SUMMARY_TMP):
os.remove(RELIABILITY_SUMMARY_TMP)
except OSError:
pass
return False
def _normalize_duration(seconds):
"""Normalize duration to a non-negative float."""
if seconds is None:
return 0.0
try:
value = float(seconds)
except (ValueError, TypeError):
return 0.0
return max(0.0, value)
def _normalize_exit_code(exit_code):
if exit_code is None:
return None
try:
return int(exit_code)
except (ValueError, TypeError):
return None
def _normalize_reliability_summary(summary):
"""Ensure summary schema is stable for reads and API responses."""
if not isinstance(summary, dict):
summary = {}
scripts = summary.get('scripts')
if not isinstance(scripts, dict):
scripts = {}
normalized_scripts = {}
for script_name, stats in scripts.items():
if not isinstance(stats, dict):
continue
total_runs = max(0, int(stats.get('total_runs', 0) or 0))
failures = max(0, int(stats.get('failures', 0) or 0))
if failures > total_runs:
failures = total_runs
reliability_score = round(
((total_runs - failures) / total_runs * 100) if total_runs else 0,
1,
)
normalized_scripts[str(script_name)] = {
'script_name': str(script_name),
'total_runs': total_runs,
'failures': failures,
'flaky_executions': max(0, int(stats.get('flaky_executions', 0) or 0)),
'slow_executions': max(0, int(stats.get('slow_executions', 0) or 0)),
'average_duration': round(_normalize_duration(stats.get('average_duration')), 3),
'reliability_score': round(float(stats.get('reliability_score', reliability_score) or 0), 1),
'success_rate': round(float(stats.get('success_rate', reliability_score) or 0), 1),
'trend': stats.get('trend', 'stable') if stats.get('trend') in ('improving', 'degrading', 'stable') else 'stable',
'trend_summary': stats.get('trend_summary') if isinstance(stats.get('trend_summary'), dict) else {},
'failure_breakdown': _cap_failure_breakdown(stats.get('failure_breakdown')),
'duration_regression': stats.get('duration_regression') if isinstance(stats.get('duration_regression'), dict) else {},
'flaky': stats.get('flaky') if isinstance(stats.get('flaky'), dict) else {},
'recurring_failures': stats.get('recurring_failures') if isinstance(stats.get('recurring_failures'), list) else [],
'last_run': str(stats.get('last_run', '') or ''),
}
global_stats = summary.get('global')
if not isinstance(global_stats, dict):
global_stats = {}
normalized = {
'version': RELIABILITY_SUMMARY_VERSION,
'scripts': normalized_scripts,
'global': {
'total_runs': max(0, int(global_stats.get('total_runs', 0) or 0)),
'failures': max(0, int(global_stats.get('failures', 0) or 0)),
'reliability_score': round(float(global_stats.get('reliability_score', 0) or 0), 1),
'failure_breakdown': _cap_failure_breakdown(global_stats.get('failure_breakdown')),
},
'updated_at': summary.get('updated_at', _iso_now()),
}
diagnostics = summary.get('diagnostics')
if isinstance(diagnostics, dict):
normalized['diagnostics'] = diagnostics
return normalized
def _classify_failure(exit_code, error_message='', output=''):
"""Classify failure into one of the known failure types."""
code = _normalize_exit_code(exit_code)
error_msg = (error_message or '').lower()
output_lower = (output or '').lower()
combined = f'{error_msg} {output_lower}'
if code == 130 or 'interrupted' in combined or 'aborted by user' in combined:
return 'interrupted'
if code == 124 or 'timeout' in combined or 'timed out' in combined:
return 'timeout'
if code == 126 or 'permission denied' in combined or 'access is denied' in combined:
return 'permission_error'
if (
'no such file' in combined
or 'file not found' in combined
or 'cannot find the path' in combined
):
return 'missing_file'
if (
'modulenotfound' in combined
or 'importerror' in combined
or 'no module named' in combined
or 'package not found' in combined
):
return 'dependency_error'
if code == 127 and ('command not found' in combined or 'not found' in combined):
return 'dependency_error'
if (
'syntax error' in combined
or 'unexpected token' in combined
or 'parse error' in combined
or code in (2, 127)
):
return 'shell_error'
if code in (1, 2):
return 'shell_error'
return 'unknown_failure'
def _parse_execution_log_metadata(log_name):
"""Extract lightweight metadata from execution log headers."""