File size: 23,908 Bytes
c8d30bc | 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 | """
checkpoint.py โ Pipeline ๅท่กๆชขๆฅ้ป่จ้ๅจ
===========================================
่จญ่จๅๅ๏ผ
- ้ถ้ปๅก๏ผI/O ๆไฝ็กๅฏ่ฝ่ผ้๏ผappend-only JSONL๏ผ
- ้ถๅคฑๆ๏ผไปปไฝ่จ้้ฏ่ชค้ฝ่ขซ้้ปๅๅฌ๏ผ็ตไธๅฝฑ้ฟ Pipeline
- ็ตๆงๅ๏ผๆฏๆข่จ้้ฝๆฏๅฏๆฅ่ฉข็ JSON
- ๅท่ก็ทๅฎๅ
จ๏ผ
Phase 4A: ๅชๅ
ไฝฟ็จ Rust threathunter_checkpoint_writer
๏ผparking_lot::Mutex + BufWriter<File>๏ผ้ซ้ ป SSE ไธ็ซถ็ญ๏ผ
Fallback: Python threading.Lock + TextIO๏ผๅๆๅฏฆไฝ๏ผ
่ผธๅบๆ ผๅผ๏ผJSONL๏ผ๏ผ
logs/checkpoints/scan_{id}_{timestamp}.jsonl
ไบไปถ้กๅ๏ผ
SCAN_START / SCAN_END
STAGE_ENTER / STAGE_EXIT
LLM_CALL / LLM_RESULT / LLM_RETRY / LLM_ERROR
TOOL_CALL / HARNESS_CHECK / DEGRADATION
้ตๅฎ๏ผAGENTS.md + project_CONSTITUTION.md
"""
import hashlib
import json
import logging
import os
import re
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, TextIO
logger = logging.getLogger("ThreatHunter.checkpoint")
# โโ Phase 4A๏ผRust BufWriter ๆดๅ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅชๅ
่ผๅ
ฅ Rust crate๏ผไธๅฏ็จๆ๏ผๆช็ทจ่ญฏใ้ Windows ็ญ๏ผ่ชๅ้็ด
try:
import threathunter_checkpoint_writer as _cw
_RUST_WRITER_AVAILABLE = True
logger.info("[CHECKPOINT] Phase 4A: Rust BufWriter ๅ็จ โ")
except ImportError:
_cw = None # type: ignore[assignment]
_RUST_WRITER_AVAILABLE = False
logger.debug("[CHECKPOINT] Phase 4A: Rust BufWriter ไธๅฏ็จ๏ผไฝฟ็จ Python fallback")
# โโ ็ฐๅข่ฎๆธ้้๏ผๅๆปพ็ญ็ฅ็ฌฌไธ็ด๏ผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ENABLED = os.getenv("CHECKPOINT_ENABLED", "true").lower() != "false"
# โโ ๆๆ่ณๆ้ฎ็ฝฉๆจกๅผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_SENSITIVE_PATTERNS = [
re.compile(r"(sk(?:-proj)?-[a-zA-Z0-9\-_]{10,})", re.IGNORECASE), # OpenAI-style keys
re.compile(r"(ghp_[a-zA-Z0-9]{36,})", re.IGNORECASE), # GitHub Token
re.compile(r"(api[_-]?key\s*[:=]\s*['\"]?)([^'\"\s,]{8,})", re.IGNORECASE),
re.compile(r"(password\s*[:=]\s*['\"]?)([^'\"\s,]{4,})", re.IGNORECASE),
re.compile(r"(secret\s*[:=]\s*['\"]?)([^'\"\s,]{8,})", re.IGNORECASE),
]
# โโ ๆชๆทไธ้ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
MAX_DATA_LENGTH = 2000 # ๅฎไธๆฌไฝๅผๆๅคง้ทๅบฆ
MAX_THINKING_LENGTH = 1000 # ๆ่้็จๆ่ฆๆๅคง้ทๅบฆ
def _redact(text: str) -> str:
"""้ฎ็ฝฉๆๆ่ณๆ๏ผAPI Keyใๅฏ็ขผ็ญ๏ผ"""
if not isinstance(text, str):
return str(text)
result = text
for pattern in _SENSITIVE_PATTERNS:
result = pattern.sub(lambda m: m.group(0)[:4] + "***REDACTED***", result)
return result
def _truncate(value: Any, max_len: int = MAX_DATA_LENGTH) -> str:
"""ๆชๆท้้ท็ๅผ"""
s = str(value) if not isinstance(value, str) else value
if len(s) > max_len:
return s[:max_len] + f"...[truncated, total={len(s)}]"
return s
def _safe_hash(text: str) -> str:
"""่จ็ฎ่ผธๅ
ฅ็็ญ hash๏ผ็จๆผ่ฟฝ่นคๅไธ่ผธๅ
ฅ็ๅคๆฌกๅท่ก๏ผ"""
return hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()[:12]
class CheckpointRecorder:
"""
Pipeline ๅท่กๆชขๆฅ้ป่จ้ๅจใ
ๆฏๆฌกๆๆๅผๅซ start_scan() ๅๅงๅไธๅ JSONL ๆชๆก๏ผ
ๅพ็บๆๆ checkpoint() ๅผๅซ่ฟฝๅ ไธ่ก JSONใ
ๆๆ็ตๆๅผๅซ end_scan() ้้ๆชๆกใ
ๆๆๅ
ฌ้ๆนๆณ้ฝๆฏใ้้ปๆจกๅผใ๏ผ
- ไปปไฝๅ
ง้จ้ฏ่ชค่ขซ try-except ๆๆ
- ๅ
่จ้ๅฐ logger.debug๏ผไธๆๅบไพๅค
- Pipeline ไธปๆต็จๅฎๅ
จไธๅๅฝฑ้ฟ
"""
def __init__(self, logs_dir: Path | str | None = None):
if logs_dir is None:
logs_dir = Path(__file__).parent / "logs"
self._logs_dir = Path(logs_dir)
self._checkpoints_dir = self._logs_dir / "checkpoints"
self._errors_dir = self._logs_dir / "errors"
self._scan_id: str = "unknown"
self._seq: int = 0
self._file: TextIO | None = None # Python fallback writer
self._lock = threading.Lock() # Python fallback lock
self._event_counts: dict[str, int] = {}
self._scan_start_time: float = 0.0
self._current_filename: str = "" # v3.6: Thinking Path API ไฝฟ็จ
# Phase 4A๏ผ่ฟฝ่นค Rust writer ๆฏๅฆๅฐๆฌๆฌกๆๆ้ๅ
self._rust_writer_active: bool = False
@property
def current_filename(self) -> str:
"""ๅๅณๆฌๆฌกๆๆ็ JSONL ๆชๅ๏ผไพ server.py Thinking Path API ไฝฟ็จ๏ผ"""
return self._current_filename
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๆๆ็ๅฝ้ฑๆ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def start_scan(self, scan_id: str) -> None:
"""ๅๅงๅๆฐๆๆ็ checkpoint ๆชๆก"""
if not ENABLED:
return
try:
self._checkpoints_dir.mkdir(parents=True, exist_ok=True)
self._errors_dir.mkdir(parents=True, exist_ok=True)
self._scan_id = scan_id
self._seq = 0
self._event_counts = {}
self._scan_start_time = time.time()
self._rust_writer_active = False
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"scan_{scan_id[:8]}_{ts}.jsonl"
filepath = self._checkpoints_dir / filename
self._current_filename = filename # v3.6: ไพ Thinking Path API ๆฅ่ฉข
# โโ Phase 4A๏ผๅชๅ
ๅ่ฉฆ Rust BufWriter โโโโโโโโโโโโโโโโโโ
if _RUST_WRITER_AVAILABLE:
try:
_cw.open_writer(str(filepath))
self._rust_writer_active = True
logger.info(
"[CHECKPOINT] Phase 4A: Rust BufWriter ้ๅ: %s", filepath.name
)
except Exception as rust_err:
logger.warning(
"[CHECKPOINT] Phase 4A: Rust BufWriter ้ๅๅคฑๆ๏ผๅ้ Python: %s", rust_err
)
self._rust_writer_active = False
# โโ Fallback๏ผPython TextIO โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if not self._rust_writer_active:
if self._file and not self._file.closed:
try:
self._file.close()
except Exception:
pass
self._file = open(filepath, "a", encoding="utf-8")
self.checkpoint("SCAN_START", "pipeline", {
"scan_id": scan_id,
"writer_backend": "rust_bufwriter" if self._rust_writer_active else "python_lock",
})
logger.info("[CHECKPOINT] ๆๆ่จ้้ๅง: %s", filepath.name)
except Exception as e:
logger.debug("[CHECKPOINT] start_scan failed: %s", e)
def end_scan(self, final_status: str, total_duration: float) -> None:
"""ๆๆ็ตๆ๏ผๅฏซๅ
ฅๆ่ฆไธฆ้้ๆชๆก"""
if not ENABLED:
return
try:
self.checkpoint("SCAN_END", "pipeline", {
"final_status": final_status,
"total_duration_seconds": round(total_duration, 2),
"total_checkpoints": self._seq,
"event_summary": dict(self._event_counts),
"writer_backend": "rust_bufwriter" if self._rust_writer_active else "python_lock",
})
# โโ Phase 4A๏ผ้้ Rust writer โโโโโโโโโโโโโโโโโโโโโโโโโโ
if self._rust_writer_active and _RUST_WRITER_AVAILABLE:
try:
_cw.flush_writer()
_cw.close_writer()
logger.debug(
"[CHECKPOINT] Phase 4A: Rust BufWriter ๅทฒ้้๏ผๅ
ฑๅฏซๅ
ฅ %d ่ก",
_cw.get_lines_written(),
)
except Exception as e:
logger.debug("[CHECKPOINT] Phase 4A: Rust close ๅคฑๆ: %s", e)
finally:
self._rust_writer_active = False
# โโ Fallback๏ผPython TextIO ้้ โโโโโโโโโโโโโโโโโโโโโโโโ
if self._file and not self._file.closed:
self._file.close()
self._file = None
logger.info(
"[CHECKPOINT] ๆๆ่จ้็ตๆ: %d ๆข checkpoint | %.1fs",
self._seq, total_duration,
)
except Exception as e:
logger.debug("[CHECKPOINT] end_scan failed: %s", e)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๆ ธๅฟๅฏซๅ
ฅ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def checkpoint(self, event: str, agent: str, data: dict | None = None) -> None:
"""
ๅฏซๅ
ฅไธๆข checkpoint ่จ้๏ผๅท่ก็ทๅฎๅ
จ๏ผใ
Phase 4A๏ผๅชๅ
ไฝฟ็จ Rust BufWriter๏ผparking_lot::Mutex๏ผ็ก GIL ็ซถ็ญ๏ผใ
Fallback๏ผPython threading.Lock + TextIO๏ผๅๆๅฏฆไฝ๏ผๅฎๅ
จ็ญๆ๏ผใ
Args:
event: ไบไปถ้กๅ๏ผๅฆ STAGE_ENTER, LLM_CALL ็ญ๏ผ
agent: Agent ๅ็จฑ๏ผๅฆ scout, security_guard๏ผ
data: ้ๅ ่ณๆๅญๅ
ธ
"""
if not ENABLED:
return
try:
with self._lock:
self._seq += 1
self._event_counts[event] = self._event_counts.get(event, 0) + 1
record = {
"seq": self._seq,
"ts": datetime.now(timezone.utc).isoformat(),
"scan_id": self._scan_id,
"event": event,
"agent": agent,
"data": self._sanitize_data(data or {}),
}
line = json.dumps(record, ensure_ascii=False, default=str)
# โโ Phase 4A๏ผRust BufWriter ๅฏซๅ
ฅ่ทฏๅพ โโโโโโโโโโโโโโ
if self._rust_writer_active and _RUST_WRITER_AVAILABLE:
try:
_cw.write_line(line)
# ้ซๅชๅ
็ดไบไปถ๏ผLLM ้ฏ่ชค / ๆๆ้็๏ผ็ซๅณ flush
if event in (
"SCAN_START",
"SCAN_END",
"STAGE_ENTER",
"STAGE_EXIT",
"LLM_ERROR",
"DEGRADATION",
):
_cw.flush_writer()
return
except Exception as rust_err:
# Rust ๅฏซๅ
ฅๅคฑๆ โ ๅ้๏ผไธฆ็ฆ็จ Rust writer ้ฟๅ
ๅพ็บ้่ฉฆ
logger.warning(
"[CHECKPOINT] Phase 4A Rust write ๅคฑๆ๏ผๅๆ Python: %s", rust_err
)
self._rust_writer_active = False
# โโ Fallback๏ผPython TextIO โโโโโโโโโโโโโโโโโโโโโโโโโ
if self._file and not self._file.closed:
self._file.write(line + "\n")
self._file.flush() # ๅณๆๅฏซๅ
ฅ๏ผdebug ๆๆดๆ่ฟฝ่นค
except Exception as e:
logger.debug("[CHECKPOINT] write failed: %s", e)
def _sanitize_data(self, data: dict) -> dict:
"""ๆธ
ๆด่ณๆ๏ผๆชๆท + ้ฎ็ฝฉๆๆ่ณ่จ"""
sanitized = {}
for key, value in data.items():
if isinstance(value, dict):
sanitized[key] = self._sanitize_data(value)
elif isinstance(value, (list, tuple)):
sanitized[key] = _truncate(str(value))
elif isinstance(value, str):
sanitized[key] = _redact(_truncate(value))
elif isinstance(value, (int, float, bool)):
sanitized[key] = value
else:
sanitized[key] = _truncate(str(value))
return sanitized
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Stage ๅฑคไพฟๆทๆนๆณ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def stage_enter(
self,
agent: str,
input_data: Any = None,
skill_file: str = "",
input_type: str = "",
) -> None:
"""Stage ้ฒๅ
ฅ้ป checkpoint โ v3.7: ๅ ๅ
ฅ skill_file / input_type ๆฌไฝไพ Thinking Path UI ไฝฟ็จ"""
try:
data: dict[str, Any] = {}
# v3.7: Path-Aware Skills ่ฟฝ่นค่ณๆ
if skill_file:
data["skill_file"] = skill_file
if input_type:
data["input_type"] = input_type
# ่ผธๅ
ฅๆ่ฆ
if isinstance(input_data, dict):
data["input_keys"] = list(input_data.keys())[:20]
if "tech_stack" in input_data:
data["tech_stack_preview"] = _truncate(
str(input_data["tech_stack"]), 200
)
if "vulnerabilities" in input_data:
data["vuln_count"] = len(input_data.get("vulnerabilities", []))
data["input_hash"] = _safe_hash(json.dumps(input_data, default=str))
elif isinstance(input_data, str):
data["input_preview"] = _truncate(input_data, 200)
data["input_hash"] = _safe_hash(input_data)
data["input_length"] = len(input_data)
self.checkpoint("STAGE_ENTER", agent, data)
except Exception:
pass
def stage_exit(
self,
agent: str,
status: str,
output_data: Any = None,
duration_ms: int = 0,
) -> None:
"""Stage ้ข้้ป checkpoint"""
try:
data: dict[str, Any] = {
"status": status,
"duration_ms": duration_ms,
}
if isinstance(output_data, dict):
data["output_keys"] = list(output_data.keys())[:20]
if "vulnerabilities" in output_data:
data["vuln_count"] = len(output_data.get("vulnerabilities", []))
if "risk_score" in output_data:
data["risk_score"] = output_data["risk_score"]
if "verdict" in output_data:
data["verdict"] = output_data["verdict"]
if output_data.get("_degraded"):
data["degraded"] = True
if "scan_path" in output_data:
data["scan_path"] = output_data["scan_path"]
self.checkpoint("STAGE_EXIT", agent, data)
# โโ ่ชๅๆณจๅ
ฅ DEGRADATION checkpoint โโโโโโโโโโโโโโโโโโโโโโโโโโ
# ็ถ stage ่ผธๅบๅ
ๅซ _degraded=True ๆ๏ผ็ซๅณ่ฃๅฏซไธๆข DEGRADATION
# ไบไปถ๏ผ่ฎ Thinking Path ้ขๆฟ่ฝๆญฃ็ขบ้กฏ็คบ้็ดๅๅ ๏ผไธ่ฎ้็ผ่
็็
if isinstance(output_data, dict) and output_data.get("_degraded"):
error_msg = str(output_data.get("_error", "Unknown degradation reason"))
strategy = f"status={status}, duration={duration_ms}ms"
self.checkpoint("DEGRADATION", agent, {
"reason": _truncate(error_msg, 400),
"fallback_strategy": strategy,
"error": _truncate(error_msg, 400), # ไพๅ็ซฏ tp-error-text ไฝฟ็จ
"source": "stage_exit_auto",
})
except Exception:
pass
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# LLM ๅฑคไพฟๆทๆนๆณ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def llm_call(
self,
agent: str,
model: str,
provider: str = "openrouter",
task_preview: str = "",
) -> None:
"""LLM ๅผๅซๅ checkpoint"""
try:
self.checkpoint("LLM_CALL", agent, {
"model": model,
"provider": provider,
"task_preview": _truncate(task_preview, 300),
})
except Exception:
pass
def llm_result(
self,
agent: str,
model: str,
status: str,
output_len: int,
duration_ms: int,
thinking: str = "",
) -> None:
"""LLM ๅผๅซๅพ checkpoint๏ผๅซๆ่้็จๆ่ฆ๏ผ"""
try:
data: dict[str, Any] = {
"model": model,
"status": status,
"output_length": output_len,
"duration_ms": duration_ms,
}
if thinking:
data["thinking_preview"] = _redact(
_truncate(thinking, MAX_THINKING_LENGTH)
)
self.checkpoint("LLM_RESULT", agent, data)
except Exception:
pass
def llm_retry(
self,
agent: str,
model: str,
error: str,
retry_count: int,
next_model: str,
) -> None:
"""LLM ้่ฉฆ checkpoint"""
try:
self.checkpoint("LLM_RETRY", agent, {
"failed_model": model,
"error": _truncate(error, 300),
"retry_count": retry_count,
"next_model": next_model,
})
except Exception:
pass
def llm_error(self, agent: str, model: str, error: str) -> None:
"""LLM ๅคฑๆ checkpoint๏ผๅๆๅฏซๅ
ฅ error log๏ผ"""
try:
self.checkpoint("LLM_ERROR", agent, {
"model": model,
"error": _truncate(error, 500),
})
# ๅๆญฅๅฏซๅ
ฅ error log
self._write_error_log(agent, model, error)
except Exception:
pass
def _write_error_log(self, agent: str, model: str, error: str) -> None:
"""ๅฐ LLM ้ฏ่ชคๅฏซๅ
ฅ็จ็ซ็ error log ๆชๆก"""
try:
self._errors_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d")
error_file = self._errors_dir / f"errors_{ts}.log"
with open(error_file, "a", encoding="utf-8") as f:
now = datetime.now(timezone.utc).isoformat()
f.write(
f"[{now}] scan={self._scan_id} agent={agent} "
f"model={model} error={error[:300]}\n"
)
except Exception:
pass
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅทฅๅ
ท / Harness ๅฑคไพฟๆทๆนๆณ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def tool_call(
self,
agent: str,
tool_name: str,
tool_input: str,
tool_output: str,
status: str = "SUCCESS",
) -> None:
"""ๅทฅๅ
ทๅผๅซ checkpoint"""
try:
self.checkpoint("TOOL_CALL", agent, {
"tool_name": tool_name,
"input": _truncate(tool_input, 500),
"output_preview": _truncate(tool_output, 500),
"status": status,
})
except Exception:
pass
def harness_check(
self,
agent: str,
layer: str,
check_name: str,
result: str,
action: str = "",
details: dict | None = None,
) -> None:
"""Harness ไฟ้ๅฑค่งธ็ผ checkpoint"""
try:
data: dict[str, Any] = {
"layer": layer,
"check_name": check_name,
"result": result,
}
if action:
data["corrective_action"] = action
if details:
data.update(details)
self.checkpoint("HARNESS_CHECK", agent, data)
except Exception:
pass
def degradation(
self,
agent: str,
reason: str,
fallback_strategy: str = "",
) -> None:
"""้็ด่งธ็ผ checkpoint"""
try:
self.checkpoint("DEGRADATION", agent, {
"reason": _truncate(reason, 300),
"fallback_strategy": fallback_strategy,
})
except Exception:
pass
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ็ตฑ่จ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def get_summary(self) -> dict:
"""ๅๅณ็ถๅๆๆ็็ตฑ่จๆ่ฆ"""
try:
elapsed = time.time() - self._scan_start_time if self._scan_start_time else 0
return {
"scan_id": self._scan_id,
"total_checkpoints": self._seq,
"event_counts": dict(self._event_counts),
"elapsed_seconds": round(elapsed, 2),
"enabled": ENABLED,
}
except Exception:
return {"error": "summary unavailable"}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅ
จๅๅฏฆไพ๏ผๅฎไพๆจกๅผ๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_project_root = Path(__file__).parent
recorder = CheckpointRecorder(logs_dir=_project_root / "logs")
def get_checkpoint_writer_status() -> dict[str, Any]:
"""ๅๅณ checkpoint writer ๅพ็ซฏ็ๆ
๏ผไพ UI diagnostics ไฝฟ็จใ"""
rust_active = bool(getattr(recorder, "_rust_writer_active", False))
return {
"available": _RUST_WRITER_AVAILABLE,
"active": rust_active,
"preferred_backend": "rust_bufwriter",
"current_backend": "rust_bufwriter" if rust_active else "python_lock",
"fallback_backend": "python_lock",
}
|