File size: 4,057 Bytes
8f74b6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import hashlib
from datetime import datetime
from pathlib import Path
from filelock import FileLock

DATA_DIR = Path("data")
CARDS_DIR = DATA_DIR / "cards"
DECISIONS_FILE = DATA_DIR / "decisions.json"
LOCK_FILE = DATA_DIR / ".decisions.lock"


def ensure_dirs():
    DATA_DIR.mkdir(exist_ok=True)
    CARDS_DIR.mkdir(exist_ok=True)


def generate_commit_hash(timestamp: str, raw_input: str) -> str:
    content = f"{timestamp}:{raw_input}"
    return hashlib.sha256(content.encode()).hexdigest()[:7]


def generate_id() -> str:
    now = datetime.now()
    decisions = load_decisions()
    today_count = sum(
        1 for d in decisions
        if d["timestamp"].startswith(now.strftime("%Y-%m-%d"))
    )
    return f"dec_{now.strftime('%Y%m%d')}_{today_count + 1:03d}"


def load_decisions() -> list[dict]:
    ensure_dirs()
    if not DECISIONS_FILE.exists():
        return []
    try:
        with open(DECISIONS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return []


def _write_decisions(decisions: list[dict]):
    ensure_dirs()
    with open(DECISIONS_FILE, "w", encoding="utf-8") as f:
        json.dump(decisions, f, indent=2, default=str)


def save_decision(record: dict):
    lock = FileLock(str(LOCK_FILE))
    with lock:
        decisions = load_decisions()
        decisions.append(record)
        _write_decisions(decisions)


def update_decision(decision_id: str, updates: dict):
    lock = FileLock(str(LOCK_FILE))
    with lock:
        decisions = load_decisions()
        for d in decisions:
            if d["id"] == decision_id:
                d.update(updates)
                break
        _write_decisions(decisions)


def get_open_decisions() -> list[dict]:
    return [d for d in load_decisions() if d.get("status") == "open"]


def get_decision_by_id(decision_id: str) -> dict | None:
    for d in load_decisions():
        if d["id"] == decision_id:
            return d
    return None


def resolve_decision(decision_id: str, description: str, valence: str):
    decision = get_decision_by_id(decision_id)
    if not decision:
        return

    predictions = decision.get("consequence_predictions", [])
    high_preds = [p for p in predictions if p.get("probability") == "high"]
    if high_preds:
        matching = sum(1 for p in high_preds if p.get("valence") == valence)
        accuracy = matching / len(high_preds)
    else:
        accuracy = 0.5

    outcome = {
        "timestamp": datetime.now().isoformat(),
        "description": description,
        "actual_valence": valence,
        "prediction_accuracy": round(accuracy, 2),
    }
    update_decision(decision_id, {"status": "resolved", "outcome": outcome})


def export_decisions() -> str:
    return json.dumps(load_decisions(), indent=2, default=str)


def create_decision_record(
    raw_input: str,
    input_type: str,
    follow_up_qa: list[dict],
    category: str,
    subcategory: str,
    severity: int,
    status_emoji: str,
    consequence_predictions: list[dict],
    moment_card_prompt: str,
    moment_card_path: str | None = None,
    image_description: str | None = None,
) -> dict:
    now = datetime.now()
    decision_id = generate_id()
    commit_hash = generate_commit_hash(now.isoformat(), raw_input)

    record = {
        "id": decision_id,
        "timestamp": now.isoformat(),
        "input_type": input_type,
        "raw_input": raw_input,
        "image_description": image_description,
        "follow_up_qa": follow_up_qa,
        "category": category,
        "subcategory": subcategory,
        "severity": severity,
        "consequence_predictions": consequence_predictions,
        "moment_card_prompt": moment_card_prompt,
        "moment_card_path": moment_card_path,
        "status": "open",
        "outcome": None,
        "debug_metadata": {
            "commit_hash": commit_hash,
            "branch": category,
            "status_emoji": status_emoji,
        },
    }
    save_decision(record)
    return record