Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53bfb47a92 | ||
|
|
08e3ece2d3 | ||
|
|
100cc743c0 | ||
|
|
f7d99c6d9c | ||
| d412939b4f |
@@ -14,6 +14,8 @@ Usage:
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
from image_screening import screen_image_signals
|
||||
|
||||
from .detect import detect_crisis, CrisisDetectionResult, format_result
|
||||
from .compassion_router import router
|
||||
from .response import (
|
||||
@@ -50,6 +52,67 @@ def check_crisis(text: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _image_detection_from_score(image_result) -> CrisisDetectionResult:
|
||||
if image_result.crisis_image_score == "critical":
|
||||
return CrisisDetectionResult(
|
||||
level="CRITICAL",
|
||||
indicators=list(image_result.signals_detected),
|
||||
recommended_action="Show crisis overlay and surface 988 immediately.",
|
||||
score=image_result.distress_score,
|
||||
)
|
||||
if image_result.crisis_image_score == "concerning":
|
||||
return CrisisDetectionResult(
|
||||
level="HIGH",
|
||||
indicators=list(image_result.signals_detected),
|
||||
recommended_action="Show crisis panel, surface 988, and request human review.",
|
||||
score=image_result.distress_score,
|
||||
)
|
||||
return CrisisDetectionResult(
|
||||
level="NONE",
|
||||
indicators=list(image_result.signals_detected),
|
||||
recommended_action="No crisis action required.",
|
||||
score=image_result.distress_score,
|
||||
)
|
||||
|
||||
|
||||
def check_image_crisis(
|
||||
*,
|
||||
image_path: Optional[str] = None,
|
||||
ocr_text: str = "",
|
||||
labels: Optional[list[str]] = None,
|
||||
manual_notes: str = "",
|
||||
visual_flags: Optional[list[str]] = None,
|
||||
) -> dict:
|
||||
"""Gateway-integrated image crisis check using the local screening slice."""
|
||||
image_result = screen_image_signals(
|
||||
image_path=image_path,
|
||||
ocr_text=ocr_text,
|
||||
labels=labels,
|
||||
manual_notes=manual_notes,
|
||||
visual_flags=visual_flags,
|
||||
)
|
||||
detection = _image_detection_from_score(image_result)
|
||||
response = generate_response(detection)
|
||||
|
||||
return {
|
||||
"level": detection.level,
|
||||
"image_score": image_result.crisis_image_score,
|
||||
"score": detection.score,
|
||||
"indicators": detection.indicators,
|
||||
"recommended_action": detection.recommended_action,
|
||||
"timmy_message": response.timmy_message,
|
||||
"ui": {
|
||||
"show_crisis_panel": response.show_crisis_panel,
|
||||
"show_overlay": response.show_overlay,
|
||||
"provide_988": response.provide_988,
|
||||
},
|
||||
"escalate": response.escalate,
|
||||
"requires_human_review": image_result.requires_human_review,
|
||||
"grounded_scope": image_result.grounded_scope,
|
||||
"screening": image_result.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def get_system_prompt(base_prompt: str, text: str = "") -> str:
|
||||
"""
|
||||
Sovereign Heart System Prompt Override.
|
||||
|
||||
195
image_screening.py
Normal file
195
image_screening.py
Normal file
@@ -0,0 +1,195 @@
|
||||
"""
|
||||
image_screening.py — local image crisis screening slice for epic #130.
|
||||
|
||||
Grounded scope:
|
||||
- screens OCR text, upstream object labels, and operator notes for crisis signals
|
||||
- intentionally does NOT claim raw computer-vision understanding of pixels
|
||||
- designed to plug into future multimodal scoring once a dedicated image model lands
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
from crisis.detect import detect_crisis
|
||||
|
||||
|
||||
DIRECT_SELF_HARM_LABELS = {
|
||||
"blood",
|
||||
"blade",
|
||||
"razor",
|
||||
"knife",
|
||||
"scissors",
|
||||
"noose",
|
||||
"ligature",
|
||||
"hanging",
|
||||
"pills",
|
||||
"pill bottle",
|
||||
"overdose",
|
||||
"gun",
|
||||
"firearm",
|
||||
"rope",
|
||||
"cuts",
|
||||
"self-harm",
|
||||
"suicide note",
|
||||
"goodbye letter",
|
||||
}
|
||||
|
||||
INJURY_LABELS = {
|
||||
"wound",
|
||||
"wounds",
|
||||
"bruise",
|
||||
"bruises",
|
||||
"bandage",
|
||||
"bandages",
|
||||
"injury",
|
||||
"injuries",
|
||||
"scar",
|
||||
"scars",
|
||||
"burn",
|
||||
"burns",
|
||||
"bleeding",
|
||||
}
|
||||
|
||||
HIGH_RISK_SCENE_LABELS = {
|
||||
"bridge edge",
|
||||
"rooftop edge",
|
||||
"train tracks",
|
||||
"ledge",
|
||||
"cliff edge",
|
||||
"dark room",
|
||||
"bathroom floor",
|
||||
"hospital wristband",
|
||||
"suicide note",
|
||||
"goodbye letter",
|
||||
}
|
||||
|
||||
FAREWELL_TEXT_PHRASES = {
|
||||
"goodbye",
|
||||
"giving away",
|
||||
"final post",
|
||||
"last message",
|
||||
"see you on the other side",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImageScreeningResult:
|
||||
ocr_text: str = ""
|
||||
labels: List[str] = field(default_factory=list)
|
||||
visual_flags: List[str] = field(default_factory=list)
|
||||
distress_score: float = 0.0
|
||||
crisis_image_score: str = "safe"
|
||||
requires_human_review: bool = False
|
||||
signals_detected: List[str] = field(default_factory=list)
|
||||
grounded_scope: str = (
|
||||
"heuristic screening over OCR text, upstream labels, and operator notes; "
|
||||
"raw vision-model inference is not implemented in this slice"
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _normalize_items(values: Optional[Iterable[str]]) -> List[str]:
|
||||
if not values:
|
||||
return []
|
||||
normalized = []
|
||||
for value in values:
|
||||
text = str(value).strip().lower()
|
||||
if text:
|
||||
normalized.append(text)
|
||||
return normalized
|
||||
|
||||
|
||||
def _match_keywords(haystack: str, keywords: set[str]) -> List[str]:
|
||||
matches = []
|
||||
for keyword in keywords:
|
||||
if keyword in haystack:
|
||||
matches.append(keyword)
|
||||
return sorted(set(matches))
|
||||
|
||||
|
||||
def screen_image_signals(
|
||||
image_path: Optional[str] = None,
|
||||
*,
|
||||
ocr_text: str = "",
|
||||
labels: Optional[Iterable[str]] = None,
|
||||
manual_notes: str = "",
|
||||
visual_flags: Optional[Iterable[str]] = None,
|
||||
) -> ImageScreeningResult:
|
||||
"""
|
||||
Score image-related crisis evidence without pretending to do full CV.
|
||||
|
||||
Inputs are deliberately grounded in what the repo can actually support today:
|
||||
- OCR text extracted upstream from screenshots/photos
|
||||
- object labels supplied by a local model or operator
|
||||
- manual operator notes about visible scene context
|
||||
- optional visual flags from any upstream preprocessor
|
||||
"""
|
||||
normalized_labels = _normalize_items(labels)
|
||||
normalized_flags = _normalize_items(visual_flags)
|
||||
normalized_notes = str(manual_notes or "").strip().lower()
|
||||
normalized_ocr = str(ocr_text or "").strip()
|
||||
|
||||
combined_label_text = " ".join(normalized_labels + normalized_flags + ([normalized_notes] if normalized_notes else []))
|
||||
crisis_text = " ".join(part for part in [normalized_ocr, normalized_notes] if part).strip()
|
||||
|
||||
direct_matches = _match_keywords(combined_label_text, DIRECT_SELF_HARM_LABELS)
|
||||
injury_matches = _match_keywords(combined_label_text, INJURY_LABELS)
|
||||
scene_matches = _match_keywords(combined_label_text, HIGH_RISK_SCENE_LABELS)
|
||||
farewell_matches = _match_keywords(crisis_text.lower(), FAREWELL_TEXT_PHRASES)
|
||||
text_detection = detect_crisis(crisis_text) if crisis_text else None
|
||||
|
||||
signals: List[str] = []
|
||||
score = 0.0
|
||||
|
||||
if direct_matches:
|
||||
score = max(score, 0.85)
|
||||
for match in direct_matches:
|
||||
signals.append(f"direct_self_harm_label:{match}")
|
||||
|
||||
if injury_matches:
|
||||
score = max(score, 0.55)
|
||||
for match in injury_matches:
|
||||
signals.append(f"injury_indicator:{match}")
|
||||
|
||||
if scene_matches:
|
||||
score = max(score, 0.4)
|
||||
for match in scene_matches:
|
||||
signals.append(f"high_risk_scene:{match}")
|
||||
|
||||
if farewell_matches:
|
||||
score = max(score, 0.85)
|
||||
for match in farewell_matches:
|
||||
signals.append(f"farewell_text:{match}")
|
||||
|
||||
if text_detection and text_detection.level != "NONE":
|
||||
score = max(score, min(1.0, text_detection.score))
|
||||
signals.append(f"ocr_crisis_level:{text_detection.level}")
|
||||
for indicator in text_detection.indicators[:3]:
|
||||
signals.append(f"ocr_indicator:{indicator}")
|
||||
|
||||
if direct_matches and text_detection and text_detection.level in {"HIGH", "CRITICAL"}:
|
||||
score = min(1.0, max(score, 0.95))
|
||||
signals.append("cross_modal_confirmation:text_plus_visual")
|
||||
|
||||
if direct_matches or (text_detection and text_detection.level == "CRITICAL") or score >= 0.85:
|
||||
crisis_image_score = "critical"
|
||||
elif score >= 0.4 or (text_detection and text_detection.level in {"HIGH", "MEDIUM"}):
|
||||
crisis_image_score = "concerning"
|
||||
else:
|
||||
crisis_image_score = "safe"
|
||||
|
||||
requires_human_review = score >= 0.4 or bool(direct_matches)
|
||||
|
||||
return ImageScreeningResult(
|
||||
ocr_text=normalized_ocr,
|
||||
labels=list(normalized_labels),
|
||||
visual_flags=list(normalized_flags),
|
||||
distress_score=round(score, 4),
|
||||
crisis_image_score=crisis_image_score,
|
||||
requires_human_review=requires_human_review,
|
||||
signals_detected=signals,
|
||||
)
|
||||
@@ -680,7 +680,7 @@ html, body {
|
||||
|
||||
<!-- Footer -->
|
||||
<footer id="footer">
|
||||
<a href="/about" aria-label="About The Door">about</a>
|
||||
<a href="/about.html" aria-label="About The Door">about</a>
|
||||
<button id="safety-plan-btn" aria-label="Open My Safety Plan">my safety plan</button>
|
||||
<button id="clear-chat-btn" aria-label="Clear chat history">clear chat</button>
|
||||
</footer>
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# The Door Fleet Work Orders Audit — issue #75
|
||||
|
||||
Generated: 2026-04-17T04:10:14Z
|
||||
Source issue: `TRIAGE: The Door - Fleet Work Orders (2026-04-09)`
|
||||
|
||||
## Source Snapshot
|
||||
|
||||
Issue #75 is a dated triage work-order sheet, not a normal feature request. The durable deliverable is a truth-restored audit of the referenced issue and PR set against live forge state.
|
||||
|
||||
## Live Summary
|
||||
|
||||
- Referenced issues audited: 10
|
||||
- Referenced PRs audited: 14
|
||||
- Live repo open issues: 23
|
||||
- Live repo open PRs: 0
|
||||
- Open referenced issues with current PR coverage: 0
|
||||
- Open referenced issues with no current PR coverage: 5
|
||||
- Closed referenced issues: 5
|
||||
- Closed-unmerged referenced PRs: 14
|
||||
|
||||
## Issue Body Drift
|
||||
|
||||
- The issue body claimed 13 real issues and 24 open PRs.
|
||||
- Live repo state now shows 23 open issues and 0 open PRs.
|
||||
- Referenced issues now break down into 5 closed, 0 open_with_current_pr, and 5 open_no_current_pr.
|
||||
- Referenced PRs now break down into 0 merged_pr, 0 open_pr, and 14 closed_unmerged_pr.
|
||||
|
||||
## Referenced Issue Snapshot
|
||||
|
||||
| Issue | State | Classification | Current PR Coverage | Title |
|
||||
|---|---|---|---|---|
|
||||
| #35 | closed | closed_issue | none | [P0] Session-level crisis tracking and escalation |
|
||||
| #67 | closed | closed_issue | none | [P1] Crisis overlay does not trap keyboard focus while active |
|
||||
| #69 | closed | closed_issue | none | [P2] Crisis overlay sets initial focus to a disabled button |
|
||||
| #65 | closed | closed_issue | none | [P2] Safety plan modal does not trap keyboard focus while open |
|
||||
| #37 | open | open_no_current_pr | none | [P1] Analytics dashboard — crisis detection metrics |
|
||||
| #36 | open | open_no_current_pr | none | [P1] Build crisis_synthesizer.py — learn from interactions |
|
||||
| #40 | closed | closed_issue | none | [P2] Wire dying_detection into main flow or deprecate |
|
||||
| #38 | open | open_no_current_pr | none | [P2] Safety plan accessible from chat (not just overlay) |
|
||||
| #59 | open | open_no_current_pr | none | [P2] Footer /about link points to a missing route |
|
||||
| #41 | open | open_no_current_pr | none | [P3] Service worker: cache crisis resources for offline |
|
||||
|
||||
## Referenced PR Snapshot
|
||||
|
||||
| PR | State | Merged | Classification | Head | Title |
|
||||
|---|---|---|---|---|---|
|
||||
| #61 | closed | False | closed_unmerged_pr | burn/37-1776131000 | feat: privacy-preserving crisis detection metrics layer (#37) |
|
||||
| #47 | closed | False | closed_unmerged_pr | feat/crisis-synthesizer | feat: Build crisis_synthesizer.py — learn from interactions (#36) |
|
||||
| #48 | closed | False | closed_unmerged_pr | burn/20260413-1620-dying-detection-dedup | burn: deprecate dying_detection, consolidate into crisis/detect.py |
|
||||
| #50 | closed | False | closed_unmerged_pr | whip/40-1776128804 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #51 | closed | False | closed_unmerged_pr | queue/40-1776129201 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #53 | closed | False | closed_unmerged_pr | q/40-1776129480 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #56 | closed | False | closed_unmerged_pr | triage/40-1776129677 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #58 | closed | False | closed_unmerged_pr | dawn/40-1776130053 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #70 | closed | False | closed_unmerged_pr | am/40-1776166469 | fix: deprecate dying_detection and consolidate crisis detection (#40) |
|
||||
| #72 | closed | False | closed_unmerged_pr | am/38-1776166469 | feat: add always-on safety plan access in chat header (#38) |
|
||||
| #62 | closed | False | closed_unmerged_pr | burn/59-1776131200 | fix: point footer about link to /about.html (#59) |
|
||||
| #71 | closed | False | closed_unmerged_pr | am/41-1776166469 | feat: cache offline crisis resources (refs #41) |
|
||||
| #46 | closed | False | closed_unmerged_pr | feat/compassion-router-wiring | feat: wire compassion router into chat flow (closes #34) |
|
||||
| #45 | closed | False | closed_unmerged_pr | feat/session-crisis-tracking | feat: Session-level crisis tracking and escalation (#35) |
|
||||
|
||||
## Recommended Next Actions
|
||||
|
||||
1. Do not trust the original work-order body as live truth; use this audit artifact for current planning.
|
||||
2. Re-triage the open_no_current_pr issues individually before dispatching new work, because the old PR references are now stale.
|
||||
3. Treat closed_unmerged_pr references as historical attempts, not active review lanes.
|
||||
4. If future work orders are needed, generate them from live forge state instead of reusing the 2026-04-09 issue body.
|
||||
5. This audit preserves operator memory; it does not claim all referenced work orders are complete.
|
||||
@@ -1,295 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
API_BASE = "https://forge.alexanderwhitestone.com/api/v1"
|
||||
ORG = "Timmy_Foundation"
|
||||
DEFAULT_TOKEN_PATH = os.path.expanduser("~/.config/gitea/token")
|
||||
DEFAULT_OUTPUT = "reports/2026-04-17-the-door-fleet-work-orders-audit.md"
|
||||
|
||||
|
||||
def extract_issue_numbers(body: str) -> list[int]:
|
||||
numbers: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for match in re.finditer(r"#(\d+)", body or ""):
|
||||
value = int(match.group(1))
|
||||
if value in seen:
|
||||
continue
|
||||
seen.add(value)
|
||||
numbers.append(value)
|
||||
return numbers
|
||||
|
||||
|
||||
def api_get(repo: str, path: str, token: str) -> Any:
|
||||
req = Request(
|
||||
f"{API_BASE}/repos/{ORG}/{repo}{path}",
|
||||
headers={"Authorization": f"token {token}"},
|
||||
)
|
||||
with urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
|
||||
|
||||
def fetch_open_prs(repo: str, token: str) -> list[dict[str, Any]]:
|
||||
prs: list[dict[str, Any]] = []
|
||||
page = 1
|
||||
while True:
|
||||
batch = api_get(repo, f"/pulls?state=open&limit=100&page={page}", token)
|
||||
if not batch:
|
||||
break
|
||||
prs.extend(batch)
|
||||
page += 1
|
||||
return prs
|
||||
|
||||
|
||||
def fetch_live_open_issue_count(repo: str, token: str) -> int:
|
||||
total = 0
|
||||
page = 1
|
||||
while True:
|
||||
batch = api_get(repo, f"/issues?state=open&limit=100&page={page}", token)
|
||||
if not batch:
|
||||
break
|
||||
total += sum(1 for item in batch if not item.get("pull_request"))
|
||||
page += 1
|
||||
return total
|
||||
|
||||
|
||||
def parse_claimed_summary(body: str) -> tuple[int | None, int | None]:
|
||||
issue_match = re.search(r"has\s+(\d+)\s+real issues", body or "", flags=re.IGNORECASE)
|
||||
pr_match = re.search(r"and\s+(\d+)\s+open PRs", body or "", flags=re.IGNORECASE)
|
||||
claimed_open_issues = int(issue_match.group(1)) if issue_match else None
|
||||
claimed_open_prs = int(pr_match.group(1)) if pr_match else None
|
||||
return claimed_open_issues, claimed_open_prs
|
||||
|
||||
|
||||
def summarize_open_pr_coverage(issue_num: int, open_prs: list[dict[str, Any]]) -> str:
|
||||
matches: list[str] = []
|
||||
seen: set[int] = set()
|
||||
for pr in open_prs:
|
||||
pr_num = pr["number"]
|
||||
if pr_num in seen:
|
||||
continue
|
||||
text = "\n".join(
|
||||
[
|
||||
pr.get("title") or "",
|
||||
pr.get("body") or "",
|
||||
(pr.get("head") or {}).get("ref") or "",
|
||||
]
|
||||
)
|
||||
if f"#{issue_num}" not in text:
|
||||
continue
|
||||
seen.add(pr_num)
|
||||
matches.append(f"open PR #{pr_num}")
|
||||
return ", ".join(matches) if matches else "none"
|
||||
|
||||
|
||||
def classify_issue_reference(ref_issue: dict[str, Any], open_prs: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
issue_num = ref_issue["number"]
|
||||
state = ref_issue.get("state") or "unknown"
|
||||
coverage = summarize_open_pr_coverage(issue_num, open_prs)
|
||||
if state == "closed":
|
||||
classification = "closed_issue"
|
||||
elif coverage != "none":
|
||||
classification = "open_with_current_pr"
|
||||
else:
|
||||
classification = "open_no_current_pr"
|
||||
return {
|
||||
"number": issue_num,
|
||||
"state": state,
|
||||
"classification": classification,
|
||||
"title": ref_issue.get("title") or "",
|
||||
"current_pr_coverage": coverage,
|
||||
"url": ref_issue.get("html_url") or ref_issue.get("url") or "",
|
||||
}
|
||||
|
||||
|
||||
def classify_pr_reference(repo: str, pr_num: int, token: str) -> dict[str, Any]:
|
||||
pr = api_get(repo, f"/pulls/{pr_num}", token)
|
||||
state = pr.get("state") or "unknown"
|
||||
merged = bool(pr.get("merged"))
|
||||
if merged:
|
||||
classification = "merged_pr"
|
||||
elif state == "open":
|
||||
classification = "open_pr"
|
||||
else:
|
||||
classification = "closed_unmerged_pr"
|
||||
return {
|
||||
"number": pr_num,
|
||||
"state": state,
|
||||
"merged": merged,
|
||||
"classification": classification,
|
||||
"title": pr.get("title") or "",
|
||||
"head": (pr.get("head") or {}).get("ref") or "",
|
||||
"url": pr.get("html_url") or pr.get("url") or "",
|
||||
}
|
||||
|
||||
|
||||
def table(rows: list[dict[str, Any]], columns: list[tuple[str, str]]) -> str:
|
||||
headers = [title for title, _ in columns]
|
||||
keys = [key for _, key in columns]
|
||||
if not rows:
|
||||
return "| None |\n|---|\n| None |"
|
||||
lines = ["| " + " | ".join(headers) + " |", "|" + "|".join(["---"] * len(headers)) + "|"]
|
||||
for row in rows:
|
||||
values: list[str] = []
|
||||
for key in keys:
|
||||
value = row.get(key, "")
|
||||
if key == "number" and value != "":
|
||||
value = f"#{value}"
|
||||
values.append(str(value).replace("\n", " "))
|
||||
lines.append("| " + " | ".join(values) + " |")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_report(
|
||||
*,
|
||||
source_issue: int,
|
||||
source_title: str,
|
||||
generated_at: str,
|
||||
claimed_open_issues: int | None,
|
||||
claimed_open_prs: int | None,
|
||||
live_open_issues: int,
|
||||
live_open_prs: int,
|
||||
issue_rows: list[dict[str, Any]],
|
||||
pr_rows: list[dict[str, Any]],
|
||||
) -> str:
|
||||
open_with_current_pr = [row for row in issue_rows if row["classification"] == "open_with_current_pr"]
|
||||
open_no_current_pr = [row for row in issue_rows if row["classification"] == "open_no_current_pr"]
|
||||
closed_issues = [row for row in issue_rows if row["classification"] == "closed_issue"]
|
||||
merged_prs = [row for row in pr_rows if row["classification"] == "merged_pr"]
|
||||
open_pr_refs = [row for row in pr_rows if row["classification"] == "open_pr"]
|
||||
closed_unmerged_prs = [row for row in pr_rows if row["classification"] == "closed_unmerged_pr"]
|
||||
|
||||
drift_lines = [
|
||||
f"- The issue body claimed {claimed_open_issues if claimed_open_issues is not None else 'unknown'} real issues and {claimed_open_prs if claimed_open_prs is not None else 'unknown'} open PRs.",
|
||||
f"- Live repo state now shows {live_open_issues} open issues and {live_open_prs} open PRs.",
|
||||
f"- Referenced issues now break down into {len(closed_issues)} closed, {len(open_with_current_pr)} open_with_current_pr, and {len(open_no_current_pr)} open_no_current_pr.",
|
||||
f"- Referenced PRs now break down into {len(merged_prs)} merged_pr, {len(open_pr_refs)} open_pr, and {len(closed_unmerged_prs)} closed_unmerged_pr.",
|
||||
]
|
||||
|
||||
return "\n".join(
|
||||
[
|
||||
f"# The Door Fleet Work Orders Audit — issue #{source_issue}",
|
||||
"",
|
||||
f"Generated: {generated_at}",
|
||||
f"Source issue: `{source_title}`",
|
||||
"",
|
||||
"## Source Snapshot",
|
||||
"",
|
||||
"Issue #75 is a dated triage work-order sheet, not a normal feature request. The durable deliverable is a truth-restored audit of the referenced issue and PR set against live forge state.",
|
||||
"",
|
||||
"## Live Summary",
|
||||
"",
|
||||
f"- Referenced issues audited: {len(issue_rows)}",
|
||||
f"- Referenced PRs audited: {len(pr_rows)}",
|
||||
f"- Live repo open issues: {live_open_issues}",
|
||||
f"- Live repo open PRs: {live_open_prs}",
|
||||
f"- Open referenced issues with current PR coverage: {len(open_with_current_pr)}",
|
||||
f"- Open referenced issues with no current PR coverage: {len(open_no_current_pr)}",
|
||||
f"- Closed referenced issues: {len(closed_issues)}",
|
||||
f"- Closed-unmerged referenced PRs: {len(closed_unmerged_prs)}",
|
||||
"",
|
||||
"## Issue Body Drift",
|
||||
"",
|
||||
*drift_lines,
|
||||
"",
|
||||
"## Referenced Issue Snapshot",
|
||||
"",
|
||||
table(
|
||||
issue_rows,
|
||||
[
|
||||
("Issue", "number"),
|
||||
("State", "state"),
|
||||
("Classification", "classification"),
|
||||
("Current PR Coverage", "current_pr_coverage"),
|
||||
("Title", "title"),
|
||||
],
|
||||
),
|
||||
"",
|
||||
"## Referenced PR Snapshot",
|
||||
"",
|
||||
table(
|
||||
pr_rows,
|
||||
[
|
||||
("PR", "number"),
|
||||
("State", "state"),
|
||||
("Merged", "merged"),
|
||||
("Classification", "classification"),
|
||||
("Head", "head"),
|
||||
("Title", "title"),
|
||||
],
|
||||
),
|
||||
"",
|
||||
"## Recommended Next Actions",
|
||||
"",
|
||||
"1. Do not trust the original work-order body as live truth; use this audit artifact for current planning.",
|
||||
"2. Re-triage the open_no_current_pr issues individually before dispatching new work, because the old PR references are now stale.",
|
||||
"3. Treat closed_unmerged_pr references as historical attempts, not active review lanes.",
|
||||
"4. If future work orders are needed, generate them from live forge state instead of reusing the 2026-04-09 issue body.",
|
||||
"5. This audit preserves operator memory; it does not claim all referenced work orders are complete.",
|
||||
]
|
||||
) + "\n"
|
||||
|
||||
|
||||
def build_audit(repo: str, issue_number: int, token: str) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
source_issue = api_get(repo, f"/issues/{issue_number}", token)
|
||||
body = source_issue.get("body") or ""
|
||||
refs = extract_issue_numbers(body)
|
||||
open_prs = fetch_open_prs(repo, token)
|
||||
claimed_open_issues, claimed_open_prs = parse_claimed_summary(body)
|
||||
issue_rows: list[dict[str, Any]] = []
|
||||
pr_rows: list[dict[str, Any]] = []
|
||||
for ref in refs:
|
||||
issue_like = api_get(repo, f"/issues/{ref}", token)
|
||||
if issue_like.get("pull_request"):
|
||||
pr_rows.append(classify_pr_reference(repo, ref, token))
|
||||
else:
|
||||
issue_rows.append(classify_issue_reference(issue_like, open_prs))
|
||||
metadata = {
|
||||
"source_title": source_issue.get("title") or "",
|
||||
"claimed_open_issues": claimed_open_issues,
|
||||
"claimed_open_prs": claimed_open_prs,
|
||||
"live_open_issues": fetch_live_open_issue_count(repo, token),
|
||||
"live_open_prs": len(open_prs),
|
||||
}
|
||||
return metadata, issue_rows, pr_rows
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Audit The Door fleet work orders issue against live forge state.")
|
||||
parser.add_argument("--repo", default="the-door")
|
||||
parser.add_argument("--issue", type=int, default=75)
|
||||
parser.add_argument("--token-file", default=DEFAULT_TOKEN_PATH)
|
||||
parser.add_argument("--output", default=DEFAULT_OUTPUT)
|
||||
args = parser.parse_args()
|
||||
|
||||
token = Path(args.token_file).read_text(encoding="utf-8").strip()
|
||||
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
metadata, issue_rows, pr_rows = build_audit(args.repo, args.issue, token)
|
||||
report = render_report(
|
||||
source_issue=args.issue,
|
||||
source_title=metadata["source_title"],
|
||||
generated_at=generated_at,
|
||||
claimed_open_issues=metadata["claimed_open_issues"],
|
||||
claimed_open_prs=metadata["claimed_open_prs"],
|
||||
live_open_issues=metadata["live_open_issues"],
|
||||
live_open_prs=metadata["live_open_prs"],
|
||||
issue_rows=issue_rows,
|
||||
pr_rows=pr_rows,
|
||||
)
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(report, encoding="utf-8")
|
||||
print(output_path)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,100 +0,0 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPT_PATH = ROOT / "scripts" / "fleet_work_orders_audit.py"
|
||||
REPORT_PATH = ROOT / "reports" / "2026-04-17-the-door-fleet-work-orders-audit.md"
|
||||
|
||||
|
||||
def _load_module():
|
||||
assert SCRIPT_PATH.exists(), f"missing {SCRIPT_PATH.relative_to(ROOT)}"
|
||||
spec = importlib.util.spec_from_file_location("fleet_work_orders_audit", SCRIPT_PATH)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_extract_issue_numbers_preserves_mixed_issue_and_pr_refs() -> None:
|
||||
body = """
|
||||
## P0 — Session-level crisis tracking (#35)
|
||||
**PR #61 ready.**
|
||||
## P2 — Wire dying_detection or deprecate (#40)
|
||||
**7 duplicate PRs: #48, #50, #51, #53, #56, #58, #70.**
|
||||
"""
|
||||
|
||||
mod = _load_module()
|
||||
|
||||
assert mod.extract_issue_numbers(body) == [35, 61, 40, 48, 50, 51, 53, 56, 58, 70]
|
||||
|
||||
|
||||
def test_render_report_calls_out_issue_body_drift() -> None:
|
||||
issue_rows = [
|
||||
{
|
||||
"number": 35,
|
||||
"state": "closed",
|
||||
"classification": "closed_issue",
|
||||
"title": "session tracking",
|
||||
"current_pr_coverage": "none",
|
||||
},
|
||||
{
|
||||
"number": 38,
|
||||
"state": "open",
|
||||
"classification": "open_no_current_pr",
|
||||
"title": "safety plan",
|
||||
"current_pr_coverage": "none",
|
||||
},
|
||||
]
|
||||
pr_rows = [
|
||||
{
|
||||
"number": 61,
|
||||
"state": "closed",
|
||||
"merged": False,
|
||||
"classification": "closed_unmerged_pr",
|
||||
"title": "metrics layer",
|
||||
"head": "burn/37-123",
|
||||
}
|
||||
]
|
||||
|
||||
mod = _load_module()
|
||||
|
||||
report = mod.render_report(
|
||||
source_issue=75,
|
||||
source_title="TRIAGE: The Door - Fleet Work Orders (2026-04-09)",
|
||||
generated_at="2026-04-17T04:00:00Z",
|
||||
claimed_open_issues=13,
|
||||
claimed_open_prs=24,
|
||||
live_open_issues=5,
|
||||
live_open_prs=0,
|
||||
issue_rows=issue_rows,
|
||||
pr_rows=pr_rows,
|
||||
)
|
||||
|
||||
assert "## Source Snapshot" in report
|
||||
assert "## Live Summary" in report
|
||||
assert "## Issue Body Drift" in report
|
||||
assert "13" in report and "24" in report
|
||||
assert "#38" in report
|
||||
assert "open_no_current_pr" in report
|
||||
assert "#61" in report
|
||||
assert "closed_unmerged_pr" in report
|
||||
assert "## Referenced Issue Snapshot" in report
|
||||
assert "## Referenced PR Snapshot" in report
|
||||
assert "## Recommended Next Actions" in report
|
||||
|
||||
|
||||
def test_committed_work_orders_audit_exists_with_required_sections() -> None:
|
||||
text = REPORT_PATH.read_text(encoding="utf-8")
|
||||
|
||||
required = [
|
||||
"# The Door Fleet Work Orders Audit — issue #75",
|
||||
"## Source Snapshot",
|
||||
"## Live Summary",
|
||||
"## Issue Body Drift",
|
||||
"## Referenced Issue Snapshot",
|
||||
"## Referenced PR Snapshot",
|
||||
"## Recommended Next Actions",
|
||||
]
|
||||
missing = [item for item in required if item not in text]
|
||||
assert not missing, missing
|
||||
115
tests/test_image_screening.py
Normal file
115
tests/test_image_screening.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""Tests for local image crisis screening slice under epic #130."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from crisis.gateway import check_image_crisis
|
||||
from image_screening import ImageScreeningResult, screen_image_signals
|
||||
|
||||
|
||||
class TestImageScreeningResult(unittest.TestCase):
|
||||
def test_to_dict_preserves_core_fields(self):
|
||||
result = ImageScreeningResult(
|
||||
ocr_text="help me",
|
||||
labels=["blood"],
|
||||
visual_flags=["dark_scene"],
|
||||
distress_score=0.8,
|
||||
requires_human_review=True,
|
||||
signals_detected=["direct_self_harm_label:blood"],
|
||||
)
|
||||
|
||||
data = result.to_dict()
|
||||
self.assertEqual(data["ocr_text"], "help me")
|
||||
self.assertEqual(data["labels"], ["blood"])
|
||||
self.assertTrue(data["requires_human_review"])
|
||||
|
||||
|
||||
class TestScreenImageSignals(unittest.TestCase):
|
||||
def test_direct_self_harm_labels_trigger_high_risk(self):
|
||||
result = screen_image_signals(
|
||||
labels=["razor blade", "blood droplets"],
|
||||
manual_notes="photo of fresh cuts on forearm",
|
||||
)
|
||||
|
||||
self.assertEqual(result.crisis_image_score, "critical")
|
||||
self.assertGreaterEqual(result.distress_score, 0.8)
|
||||
self.assertTrue(result.requires_human_review)
|
||||
self.assertTrue(any("self_harm" in signal for signal in result.signals_detected))
|
||||
|
||||
def test_ocr_text_uses_existing_crisis_detector(self):
|
||||
result = screen_image_signals(
|
||||
ocr_text="I want to kill myself tonight",
|
||||
labels=["handwritten note"],
|
||||
)
|
||||
|
||||
self.assertGreaterEqual(result.distress_score, 0.7)
|
||||
self.assertTrue(result.requires_human_review)
|
||||
self.assertTrue(any(signal.startswith("ocr_crisis_level:") for signal in result.signals_detected))
|
||||
|
||||
def test_neutral_image_stays_low_risk(self):
|
||||
result = screen_image_signals(
|
||||
labels=["dog", "park", "sunlight"],
|
||||
manual_notes="family outing in daylight",
|
||||
)
|
||||
|
||||
self.assertEqual(result.crisis_image_score, "safe")
|
||||
self.assertLess(result.distress_score, 0.2)
|
||||
self.assertFalse(result.requires_human_review)
|
||||
self.assertEqual(result.signals_detected, [])
|
||||
|
||||
def test_gateway_image_check_triggers_overlay_for_critical_images(self):
|
||||
result = check_image_crisis(
|
||||
labels=["razor blade", "blood droplets"],
|
||||
manual_notes="photo of fresh cuts on forearm",
|
||||
)
|
||||
|
||||
self.assertEqual(result["level"], "CRITICAL")
|
||||
self.assertEqual(result["image_score"], "critical")
|
||||
self.assertTrue(result["ui"]["show_overlay"])
|
||||
self.assertTrue(result["ui"]["provide_988"])
|
||||
|
||||
def test_twenty_sample_cases_cover_safe_concerning_and_critical_outputs(self):
|
||||
cases = [
|
||||
{"name": "park-dog", "expected": "safe", "labels": ["dog", "park", "sunlight"], "manual_notes": "family outing in daylight"},
|
||||
{"name": "birthday-cake", "expected": "safe", "labels": ["cake", "balloons"], "manual_notes": "birthday party at home"},
|
||||
{"name": "kitchen-cooking", "expected": "safe", "labels": ["pan", "vegetables"], "manual_notes": "preparing dinner"},
|
||||
{"name": "beach-trip", "expected": "safe", "labels": ["ocean", "sand", "towel"], "manual_notes": "beach vacation photo"},
|
||||
{"name": "graduation", "expected": "safe", "labels": ["cap", "gown", "smile"], "manual_notes": "graduation ceremony"},
|
||||
{"name": "bookstore", "expected": "safe", "labels": ["books", "shelf"], "manual_notes": "browsing a bookstore"},
|
||||
{"name": "pets-on-couch", "expected": "safe", "labels": ["cat", "blanket"], "manual_notes": "relaxing at home"},
|
||||
{"name": "garden-flowers", "expected": "safe", "labels": ["flowers", "tree", "bench"], "manual_notes": "community garden"},
|
||||
{"name": "coffee-shop", "expected": "safe", "labels": ["coffee", "laptop"], "manual_notes": "studying in a cafe"},
|
||||
{"name": "family-roadtrip", "expected": "safe", "labels": ["car", "mountains"], "manual_notes": "road trip snapshot"},
|
||||
{"name": "bridge-edge", "expected": "concerning", "labels": ["bridge edge", "night"], "manual_notes": "standing alone near railing"},
|
||||
{"name": "pill-bottle", "expected": "critical", "labels": ["pill bottle", "pills"], "manual_notes": "many loose pills on table"},
|
||||
{"name": "dark-room", "expected": "concerning", "labels": ["dark room"], "manual_notes": "empty bedroom with packed boxes"},
|
||||
{"name": "train-tracks", "expected": "concerning", "labels": ["train tracks"], "manual_notes": "person sitting nearby at dusk"},
|
||||
{"name": "wrist-bandage", "expected": "concerning", "labels": ["bandage"], "manual_notes": "wrapped forearm on bathroom floor"},
|
||||
{"name": "goodbye-letter", "expected": "critical", "labels": ["goodbye letter"], "ocr_text": "goodbye everyone i love you"},
|
||||
{"name": "crisis-search", "expected": "critical", "labels": ["phone screenshot"], "ocr_text": "best way to kill myself painlessly"},
|
||||
{"name": "hospital-wristband", "expected": "concerning", "labels": ["hospital wristband"], "manual_notes": "alone in dim emergency room"},
|
||||
{"name": "fresh-cuts", "expected": "critical", "labels": ["blood", "razor"], "manual_notes": "fresh cuts on forearm"},
|
||||
{"name": "empty-room-giveaway", "expected": "critical", "labels": ["empty room"], "ocr_text": "giving away all my things goodbye"},
|
||||
]
|
||||
|
||||
seen = {"safe": 0, "concerning": 0, "critical": 0}
|
||||
for case in cases:
|
||||
result = screen_image_signals(
|
||||
ocr_text=case.get("ocr_text", ""),
|
||||
labels=case.get("labels", []),
|
||||
manual_notes=case.get("manual_notes", ""),
|
||||
)
|
||||
self.assertEqual(result.crisis_image_score, case["expected"], case["name"])
|
||||
seen[case["expected"]] += 1
|
||||
|
||||
self.assertEqual(sum(seen.values()), 20)
|
||||
self.assertEqual(seen["safe"], 10)
|
||||
self.assertGreaterEqual(seen["concerning"], 5)
|
||||
self.assertGreaterEqual(seen["critical"], 5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user