File size: 5,294 Bytes
94da461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Join every C3 result row to its confuser story and the EXACT text C3 judged.



For each caught row we emit: item_id, tool, real_id, confidence, the judge's

reasoning, the query, a compact history view, the rendered C3 conversation, and

tell tags (keyword-derived from the reasoning). Also emits an uncaught set so we

can study what already fools C3.



Run from repo root:  python -u temp/story_remediation/build_join.py

"""
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from datasetreview import judge_prompts as J  # noqa: E402

OUT = Path(__file__).resolve().parent / "out"
C3 = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
TRAJ = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"


def _rows(p: Path):
    return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]


TELLS = {
    "bundled_checklist": ("bundl", "packs", "checklist", "enumerat", "multiple distinct",
                          "multi-task", "one turn", "one message", "exercise many",
                          "exercise multiple", "one-to-one", "stack", "all at once",
                          "everything at once", "comprehensive", "front-load"),
    "no_verification": ("verificat", "authenticat", "identity", "without verif",
                        "skips ident", "glossed", "no auth"),
    "over_precise_ids": ("precise", "exact order", "exact item", "id-laden", "unprompted",
                         "conveniently", "verbatim", "recite", "specific order number"),
    "agent_burst_no_confirm": ("fires", "burst", "no confirmation", "no intermediate",
                               "without confirm", "batch of tool", "silently", "no clarif",
                               "many tool call", "rapid sequence"),
    "terse_closer": ("taken care of", "all set", "that's handled", "done.", "what else",
                     "formulaic", "terse"),
    "duplicate_request": ("redundant", "restate", "re-asks", "re-state", "twice",
                          "double-statement", "identical repeated", "repeats the"),
    "invented_capability": ("unusual", "atypical", "don't typically", "invent",
                            "doesn't typically", "not typically", "uncommon", "rarely"),
    "sequential_orders": ("sequential", "conveniently formatted", "clean order number"),
    "scripted_flavor": ("scripted", "staged", "stagey", "stilted", "canned", "test prompt",
                        "task prompt", "flavor text", "persona"),
}


def tag(reason: str) -> list[str]:
    r = reason.lower()
    return [k for k, ws in TELLS.items() if any(w in r for w in ws)]


def hist_view(story: dict):
    out = []
    for m in story.get("history") or []:
        if m.get("role") == "tool":
            continue
        out.append({"role": m.get("role"),
                    "content": (m.get("content") or "").strip(),
                    "n_tool_calls": len(m.get("tool_calls") or [])})
    return out


def main() -> int:
    c3 = _rows(C3)
    traj = {t["example_id"]: t for t in _rows(TRAJ)}
    caught, fooled = [], []
    missing = 0
    for r in c3:
        iid = r["item_id"]
        story = traj.get(iid)
        if story is None:
            missing += 1
            continue
        parts = iid.split("-")
        tool = parts[1] if len(parts) >= 3 else "?"
        rec = {
            "item_id": iid,
            "tool": tool,
            "real_id": r.get("real_id"),
            "caught": bool(r.get("caught")),
            "confidence": (r.get("result") or {}).get("confidence"),
            "reasoning": (r.get("result") or {}).get("reasoning") or "",
            "tells": tag((r.get("result") or {}).get("reasoning") or ""),
            "n_calls": len(story.get("calls") or []),
            "n_hist_turns": len(hist_view(story)),
            "query": (story.get("query") or story.get("retrieval_text") or "").strip(),
            "history": hist_view(story),
            "c3_view": J.render_trajectory(story, blind_tools=True,
                                           include_metadata=False, conversation_only=True),
        }
        (caught if rec["caught"] else fooled).append(rec)

    (OUT / "caught_rows.jsonl").write_text(
        "\n".join(json.dumps(r, ensure_ascii=False) for r in caught) + "\n", encoding="utf-8")
    (OUT / "fooled_rows.jsonl").write_text(
        "\n".join(json.dumps(r, ensure_ascii=False) for r in fooled) + "\n", encoding="utf-8")

    from collections import Counter
    tally = Counter(t for r in caught for t in r["tells"])
    notag = sum(1 for r in caught if not r["tells"])
    print(f"caught={len(caught)} fooled={len(fooled)} missing_story={missing}")
    print(f"caught rows with NO tell tag: {notag}")
    print("tell frequency among caught:")
    for k, v in tally.most_common():
        print(f"  {v:4d}  {k}")
    # history presence
    openers = sum(1 for r in caught if r["n_hist_turns"] == 0)
    print(f"caught openers (no history): {openers} | caught with history: {len(caught)-openers}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())