Compare commits

..

2 Commits

Author SHA1 Message Date
d27ca6d39a feat: auto-revert incomplete skill edits (#923)
Some checks failed
Docker Build and Publish / build-and-push (pull_request) Has been skipped
Contributor Attribution Check / check-attribution (pull_request) Failing after 35s
Supply Chain Audit / Scan PR for supply chain risks (pull_request) Successful in 39s
Tests / e2e (pull_request) Successful in 4m13s
Tests / test (pull_request) Failing after 58m1s
2026-04-21 04:52:58 +00:00
c6f2855745 fix: restore _format_error helper for test compatibility (#916)
Some checks failed
Docker Build and Publish / build-and-push (push) Has been skipped
Nix / nix (ubuntu-latest) (push) Failing after 2s
Tests / e2e (push) Successful in 2m47s
Tests / test (push) Failing after 27m41s
Build Skills Index / build-index (push) Has been skipped
Build Skills Index / deploy-with-index (push) Has been skipped
Nix / nix (macos-latest) (push) Has been cancelled
fix: restore _format_error helper for test compatibility (#916)
2026-04-20 23:56:27 +00:00
4 changed files with 150 additions and 228 deletions

View File

@@ -1,149 +0,0 @@
"""
988 Suicide & Crisis Lifeline Integration (#673).
When crisis is detected, provides immediate access to help:
- Phone: 988 (call or text)
- Text: Text HOME to 988
- Chat: 988lifeline.org/chat
- Spanish: 1-888-628-9454
- Emergency: 911
This module provides the resource data. agent/crisis_protocol.py
handles detection. This module formats the resources for display.
"""
from dataclasses import dataclass
from typing import List
@dataclass
class CrisisResource:
"""A crisis support contact method."""
name: str
contact: str
description: str
url: str = ""
available: str = "24/7"
language: str = "English"
# 988 Suicide & Crisis Lifeline — all channels
LIFELINE_988 = CrisisResource(
name="988 Suicide and Crisis Lifeline",
contact="Call or text 988",
description="Free, confidential support for people in suicidal crisis or emotional distress.",
url="https://988lifeline.org",
available="24/7",
language="English",
)
LIFELINE_988_TEXT = CrisisResource(
name="988 Crisis Text Line",
contact="Text HOME to 988",
description="Free, 24/7 crisis support via text message.",
url="",
available="24/7",
language="English",
)
LIFELINE_988_CHAT = CrisisResource(
name="988 Lifeline Chat",
contact="988lifeline.org/chat",
description="Free, confidential online chat with a trained crisis counselor.",
url="https://988lifeline.org/chat",
available="24/7",
language="English",
)
LIFELINE_988_SPANISH = CrisisResource(
name="988 Lifeline (Spanish)",
contact="1-888-628-9454",
description="Línea de prevención del suicidio en español.",
url="https://988lifeline.org/help-yourself/en-espanol/",
available="24/7",
language="Spanish",
)
CRISIS_TEXT_LINE = CrisisResource(
name="Crisis Text Line",
contact="Text HOME to 741741",
description="Free, 24/7 crisis support via text message.",
url="https://www.crisistextline.org",
available="24/7",
language="English",
)
EMERGENCY_911 = CrisisResource(
name="Emergency Services",
contact="911",
description="Immediate danger — police, fire, ambulance.",
url="",
available="24/7",
language="Any",
)
# All resources in priority order
ALL_RESOURCES: List[CrisisResource] = [
EMERGENCY_911,
LIFELINE_988,
LIFELINE_988_TEXT,
LIFELINE_988_CHAT,
CRISIS_TEXT_LINE,
LIFELINE_988_SPANISH,
]
def get_crisis_resources(language: str = None) -> List[CrisisResource]:
"""Get crisis resources, optionally filtered by language.
Args:
language: Filter by language ("English", "Spanish", or None for all)
Returns:
List of CrisisResource objects
"""
if language:
return [r for r in ALL_RESOURCES if r.language.lower() == language.lower()]
return ALL_RESOURCES
def format_crisis_resources(resources: List[CrisisResource] = None) -> str:
"""Format crisis resources as a user-facing message.
Args:
resources: List of resources to format. Defaults to all resources.
Returns:
Formatted string suitable for displaying to a user in crisis.
"""
if resources is None:
resources = ALL_RESOURCES
lines = ["**Please reach out — help is available right now:**
"]
for r in resources:
if r.url:
lines.append(f"- **{r.name}:** {r.contact} ({r.url})")
else:
lines.append(f"- **{r.name}:** {r.contact}")
lines.append("")
lines.append("All services are free, confidential, and available 24/7.")
lines.append("You are not alone.")
return "
".join(lines)
def get_immediate_help_message() -> str:
"""Get the most urgent crisis help message.
Used when crisis is detected at CRITICAL level.
"""
return (
"If you are in immediate danger, call **911** right now.
"
+ format_crisis_resources()
)

View File

@@ -1,79 +0,0 @@
"""Tests for 988 Crisis Lifeline integration (#673)."""
import pytest
from agent.crisis_resources import (
LIFELINE_988,
LIFELINE_988_TEXT,
LIFELINE_988_CHAT,
LIFELINE_988_SPANISH,
CRISIS_TEXT_LINE,
EMERGENCY_911,
ALL_RESOURCES,
get_crisis_resources,
format_crisis_resources,
get_immediate_help_message,
CrisisResource,
)
class TestCrisisResources:
def test_988_phone(self):
assert "988" in LIFELINE_988.contact
assert "24/7" in LIFELINE_988.available
def test_988_text(self):
assert "HOME" in LIFELINE_988_TEXT.contact
assert "988" in LIFELINE_988_TEXT.contact
def test_988_chat(self):
assert "988lifeline.org/chat" in LIFELINE_988_CHAT.url
def test_988_spanish(self):
assert "1-888-628-9454" in LIFELINE_988_SPANISH.contact
assert LIFELINE_988_SPANISH.language == "Spanish"
def test_crisis_text_line(self):
assert "741741" in CRISIS_TEXT_LINE.contact
def test_911(self):
assert "911" in EMERGENCY_911.contact
def test_all_resources_not_empty(self):
assert len(ALL_RESOURCES) >= 5
class TestGetResources:
def test_returns_all_by_default(self):
assert len(get_crisis_resources()) == len(ALL_RESOURCES)
def test_filter_english(self):
english = get_crisis_resources("English")
assert all(r.language == "English" for r in english)
assert len(english) > 0
def test_filter_spanish(self):
spanish = get_crisis_resources("Spanish")
assert len(spanish) >= 1
assert all(r.language == "Spanish" for r in spanish)
class TestFormatting:
def test_format_includes_988(self):
msg = format_crisis_resources()
assert "988" in msg
def test_format_includes_741741(self):
msg = format_crisis_resources()
assert "741741" in msg
def test_format_includes_911(self):
msg = format_crisis_resources()
assert "911" in msg
def test_immediate_help_includes_911_first(self):
msg = get_immediate_help_message()
assert msg.startswith("If you are in immediate danger")
def test_format_not_empty(self):
msg = format_crisis_resources()
assert len(msg) > 100

122
tools/skill_edit_guard.py Normal file
View File

@@ -0,0 +1,122 @@
"""Skill Edit Guard — Poka-yoke auto-revert for incomplete skill edits.
Creates atomic skill edits with automatic rollback on failure.
Prevents broken skills from corrupting future sessions.
Usage:
from tools.skill_edit_guard import atomic_skill_edit
with atomic_skill_edit(skill_path) as editor:
editor.write(new_content)
# If exception occurs, file is automatically reverted
"""
from __future__ import annotations
import logging
import os
import shutil
import tempfile
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
class SkillEditGuard:
"""Atomic skill file editing with auto-revert on failure."""
def __init__(self, skill_path: str):
self._path = Path(skill_path)
self._backup: Optional[Path] = None
self._committed = False
def backup(self) -> bool:
"""Create backup before editing."""
if not self._path.exists():
return True # New file, nothing to backup
backup_dir = self._path.parent / ".skill_backups"
backup_dir.mkdir(exist_ok=True)
ts = int(time.time() * 1000)
self._backup = backup_dir / f"{self._path.name}.{ts}.bak"
shutil.copy2(self._path, self._backup)
logger.debug("Skill backup created: %s", self._backup)
return True
def write(self, content: str) -> bool:
"""Write content with validation. Returns True if valid."""
# Validate YAML frontmatter
if content.startswith("---"):
end = content.find("---", 3)
if end < 0:
logger.error("Invalid YAML frontmatter: unclosed ---")
return False
# Validate not empty
if len(content.strip()) < 10:
logger.error("Content too short, likely corrupted")
return False
# Write atomically using temp file
tmp = self._path.with_suffix(".tmp")
try:
tmp.write_text(content, encoding="utf-8")
tmp.rename(self._path)
return True
except Exception as e:
logger.error("Write failed: %s", e)
if tmp.exists():
tmp.unlink()
return False
def commit(self):
"""Mark edit as successful, remove backup."""
self._committed = True
if self._backup and self._backup.exists():
self._backup.unlink()
logger.debug("Skill backup removed: %s", self._backup)
def rollback(self) -> bool:
"""Revert to backup."""
if self._backup and self._backup.exists():
shutil.copy2(self._backup, self._path)
self._backup.unlink()
logger.warning("Skill reverted from backup: %s", self._path)
return True
return False
def __enter__(self):
self.backup()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.rollback()
return False # Re-raise exception
if not self._committed:
self.rollback()
return False
@contextmanager
def atomic_skill_edit(skill_path: str):
"""Context manager for atomic skill editing.
Usage:
with atomic_skill_edit("/path/to/skill/SKILL.md") as editor:
success = editor.write(new_content)
if not success:
raise ValueError("Write failed")
# __exit__ commits on success, reverts on exception
"""
guard = SkillEditGuard(skill_path)
guard.backup()
try:
yield guard
guard.commit()
except Exception:
guard.rollback()
raise

View File

@@ -44,6 +44,34 @@ from typing import Dict, Any, Optional, Tuple
logger = logging.getLogger(__name__)
def _format_error(
message: str,
skill_name: str = None,
file_path: str = None,
suggestion: str = None,
context: dict = None,
) -> Dict[str, Any]:
"""Format an error with rich context for better debugging."""
parts = [message]
if skill_name:
parts.append(f"Skill: {skill_name}")
if file_path:
parts.append(f"File: {file_path}")
if suggestion:
parts.append(f"Suggestion: {suggestion}")
if context:
for key, value in context.items():
parts.append(f"{key}: {value}")
return {
"success": False,
"error": " | ".join(parts),
"skill_name": skill_name,
"file_path": file_path,
"suggestion": suggestion,
}
# Import security scanner — agent-created skills get the same scrutiny as
# community hub installs.
try: