File size: 23,685 Bytes
5b5a20d | 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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 | """
orchestrator.py
---------------
Session Orchestrator with file watcher.
Manages the full pipeline lifecycle for each session:
CREATED
β PARSED (transcript parsed into turns)
β SEGMENTED (Agent 1 proposed segments)
β AWAITING_R1 (coding template generated, waiting for Researcher 1)
β AWAITING_R2 (R1 received, waiting for Researcher 2)
β CALCULATING_KAPPA
β BELOW_THRESHOLD (kappa < 0.70 β researchers must review)
β DISAGREEMENT_REVIEW (kappa passed but disagreements remain)
β READY_FOR_AGENT2
β LEARNING (Agent 2 running)
β COMPLETE
The file watcher monitors the sessions directory. When a researcher
drops a completed coding file into the session folder, the orchestrator
detects it and automatically advances the session to the next state.
Usage:
# Start a new session
python orchestrator.py new <transcript_file> <session_id>
# Watch all sessions (runs continuously)
python orchestrator.py watch <sessions_root>
# Advance a specific session manually
python orchestrator.py advance <session_id> <sessions_root>
# Show status of all sessions
python orchestrator.py status <sessions_root>
# Approve a learned rule
python orchestrator.py approve-rule <rule_id> <researcher_id> <sessions_root>
"""
import json
import time
import shutil
import traceback
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional
# Import our pipeline modules
import sys
sys.path.insert(0, str(Path(__file__).parent))
from transcript_parser import parse_transcript, save_parsed
from agent1_segmenter import run_full_transcript, save_segments
from kappa_calculator import (
calculate_kappa_report,
generate_coding_template,
resolve_disagreement,
discard_disagreement,
)
from agent2_learner import (
run_learning_cycle,
add_to_tier3,
approve_rule,
reject_rule,
list_pending_rules,
)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
WATCH_INTERVAL_SECS = 10 # how often the watcher polls
LIBRARY_ROOT = Path(__file__).parent / "library"
# Expected filenames within a session directory
F_STATE = "session_state.json"
F_TURNS = "parsed_turns.json"
F_SEGMENTS = "segments_proposed.json"
F_TEMPLATE_R1 = "coding_template_R1.json"
F_TEMPLATE_R2 = "coding_template_R2.json"
F_CODING_R1 = "coding_R1.json"
F_CODING_R2 = "coding_R2.json"
F_KAPPA_REPORT = "kappa_report.json"
# ---------------------------------------------------------------------------
# State management
# ---------------------------------------------------------------------------
VALID_STATES = [
"CREATED",
"PARSED",
"SEGMENTED",
"AWAITING_R1",
"AWAITING_R2",
"CALCULATING_KAPPA",
"BELOW_THRESHOLD",
"DISAGREEMENT_REVIEW",
"READY_FOR_AGENT2",
"LEARNING",
"COMPLETE",
"ERROR",
]
def read_state(session_dir: Path) -> dict:
state_file = session_dir / F_STATE
if not state_file.exists():
return {}
return json.loads(state_file.read_text(encoding="utf-8"))
def write_state(session_dir: Path, state: str, extra: Optional[dict] = None) -> dict:
existing = read_state(session_dir)
record = {
**existing,
"state": state,
"updated_at": datetime.now(timezone.utc).isoformat(),
}
if extra:
record.update(extra)
# Append to history
history = record.get("history", [])
history.append({"state": state, "at": record["updated_at"]})
record["history"] = history
(session_dir / F_STATE).write_text(
json.dumps(record, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return record
def get_state(session_dir: Path) -> str:
return read_state(session_dir).get("state", "UNKNOWN")
# ---------------------------------------------------------------------------
# Session creation
# ---------------------------------------------------------------------------
def create_session(
transcript_path: Path,
session_id: str,
sessions_root: Path,
researcher_ids: Optional[list[str]] = None,
) -> Path:
"""
Create a new session directory and copy the transcript in.
Args:
transcript_path: Path to the raw Zoom transcript
session_id: Unique identifier for this session/dyad
sessions_root: Root directory for all sessions
researcher_ids: e.g. ["R1", "R2"] β used for template naming
Returns:
Path to the created session directory.
"""
session_dir = sessions_root / session_id
session_dir.mkdir(parents=True, exist_ok=True)
# Copy transcript in
dest = session_dir / f"transcript{transcript_path.suffix}"
shutil.copy2(transcript_path, dest)
write_state(session_dir, "CREATED", {
"session_id": session_id,
"transcript_file": dest.name,
"researcher_ids": researcher_ids or ["R1", "R2"],
"created_at": datetime.now(timezone.utc).isoformat(),
})
print(f"[Orchestrator] Session {session_id} created at {session_dir}")
return session_dir
# ---------------------------------------------------------------------------
# Pipeline steps
# ---------------------------------------------------------------------------
def step_parse(session_dir: Path) -> bool:
"""Parse the transcript into turns."""
state = read_state(session_dir)
transcript_file = session_dir / state["transcript_file"]
print(f"[Orchestrator] [{state['session_id']}] Parsing transcript...")
turns = parse_transcript(transcript_file)
save_parsed(turns, session_dir / F_TURNS)
write_state(session_dir, "PARSED", {"n_turns": len(turns)})
print(f"[Orchestrator] [{state['session_id']}] Parsed {len(turns)} turns.")
return True
def step_segment(session_dir: Path) -> bool:
"""Run Agent 1 across the full transcript."""
state = read_state(session_dir)
sid = state["session_id"]
turns = json.loads((session_dir / F_TURNS).read_text(encoding="utf-8"))
print(f"[Orchestrator] [{sid}] Running Agent 1 segmentation...")
segments = run_full_transcript(
turns=turns,
session_id=sid,
library_root=LIBRARY_ROOT,
)
save_segments(segments, session_dir / F_SEGMENTS)
write_state(session_dir, "SEGMENTED", {"n_segments": len(segments)})
print(f"[Orchestrator] [{sid}] Agent 1 produced {len(segments)} segments.")
return True
def step_generate_templates(session_dir: Path) -> bool:
"""Generate coding templates for both researchers."""
state = read_state(session_dir)
sid = state["session_id"]
researcher_ids = state.get("researcher_ids", ["R1", "R2"])
segments_path = session_dir / F_SEGMENTS
for rid in researcher_ids:
template_path = session_dir / f"coding_template_{rid}.json"
generate_coding_template(
proposed_segments_path=segments_path,
researcher_id=rid,
session_id=sid,
output_path=template_path,
)
print(f"[Orchestrator] [{sid}] Coding template generated for {rid}.")
write_state(session_dir, "AWAITING_R1")
print(f"[Orchestrator] [{sid}] Waiting for researchers to submit codings.")
print(f"[Orchestrator] [{sid}] Researchers: drop completed coding files as "
f"coding_R1.json and coding_R2.json into {session_dir}")
return True
def step_check_codings(session_dir: Path) -> Optional[str]:
"""
Check which coding files have arrived.
Returns the new state string, or None if nothing changed.
"""
state = read_state(session_dir)
sid = state["session_id"]
has_r1 = (session_dir / F_CODING_R1).exists()
has_r2 = (session_dir / F_CODING_R2).exists()
current = state.get("state")
if has_r1 and has_r2:
if current != "CALCULATING_KAPPA":
print(f"[Orchestrator] [{sid}] Both codings received. Advancing to kappa calculation.")
write_state(session_dir, "CALCULATING_KAPPA")
return "CALCULATING_KAPPA"
elif has_r1 and current == "AWAITING_R1":
print(f"[Orchestrator] [{sid}] R1 coding received. Waiting for R2.")
write_state(session_dir, "AWAITING_R2")
return "AWAITING_R2"
elif has_r2 and current == "AWAITING_R1":
print(f"[Orchestrator] [{sid}] R2 coding received first. Waiting for R1.")
write_state(session_dir, "AWAITING_R2")
return "AWAITING_R2"
return None
def step_calculate_kappa(session_dir: Path) -> bool:
"""Run the kappa calculator and route based on result."""
state = read_state(session_dir)
sid = state["session_id"]
print(f"[Orchestrator] [{sid}] Calculating Cohen's Kappa...")
report = calculate_kappa_report(
session_id=sid,
coding_r1_path=session_dir / F_CODING_R1,
coding_r2_path=session_dir / F_CODING_R2,
proposed_segments_path=session_dir / F_SEGMENTS,
output_path=session_dir / F_KAPPA_REPORT,
)
# Push resolved disagreements to Tier 3
# (at this point they're not yet resolved β just flagged)
# Tier 3 population happens after disagreement review (see resolve/discard helpers)
if not report["gate_passed"]:
write_state(session_dir, "BELOW_THRESHOLD", {
"kappa": report["overall_kappa"],
"kappa_interpretation": report["kappa_interpretation"],
})
print(f"[Orchestrator] [{sid}] Kappa {report['overall_kappa']:.4f} β "
f"BELOW THRESHOLD. Researchers must review and re-code.")
return True
if report["segments_in_disagreement"]:
write_state(session_dir, "DISAGREEMENT_REVIEW", {
"kappa": report["overall_kappa"],
"n_disagreements": len(report["segments_in_disagreement"]),
})
print(f"[Orchestrator] [{sid}] Kappa passed. "
f"{len(report['segments_in_disagreement'])} disagreements to resolve.")
return True
# Kappa passed and no disagreements
write_state(session_dir, "READY_FOR_AGENT2", {
"kappa": report["overall_kappa"],
})
print(f"[Orchestrator] [{sid}] Kappa passed with no disagreements. "
f"Ready for Agent 2.")
return True
def step_run_agent2(session_dir: Path, sessions_root: Path) -> bool:
"""Run Agent 2 learning cycle."""
state = read_state(session_dir)
sid = state["session_id"]
write_state(session_dir, "LEARNING")
print(f"[Orchestrator] [{sid}] Running Agent 2 learning cycle...")
result = run_learning_cycle(
sessions_root=sessions_root,
library_root=LIBRARY_ROOT,
)
write_state(session_dir, "COMPLETE", {
"learning_result": {
"status": result.get("status"),
"rules_proposed": len(result.get("proposed_rules", [])),
"below_safe_zone": result.get("below_safe_zone", False),
}
})
print(f"[Orchestrator] [{sid}] Session complete.")
return True
# ---------------------------------------------------------------------------
# Disagreement helpers (called by researchers after DISAGREEMENT_REVIEW)
# ---------------------------------------------------------------------------
def resolve_session_disagreement(
session_id: str,
sessions_root: Path,
segment_id: str,
resolved_dimension: str,
resolution_note: str,
) -> None:
"""
Resolve a specific disagreement and push it to Tier 3.
After all disagreements are resolved/discarded, advances the session.
"""
session_dir = sessions_root / session_id
report_path = session_dir / F_KAPPA_REPORT
state = read_state(session_dir)
segments = json.loads((session_dir / F_SEGMENTS).read_text())
seg_map = {s["segment_id"]: s for s in segments["segments"]}
# Update the kappa report
report = resolve_disagreement(
report_path=report_path,
segment_id=segment_id,
resolved_dimension=resolved_dimension,
resolution_note=resolution_note,
)
# Push to Tier 3
seg = seg_map.get(segment_id, {})
codings_r1 = json.loads((session_dir / F_CODING_R1).read_text())
codings_r2 = json.loads((session_dir / F_CODING_R2).read_text())
map_r1 = {c["segment_id"]: c for c in codings_r1["codings"]}
map_r2 = {c["segment_id"]: c for c in codings_r2["codings"]}
add_to_tier3(
session_id=session_id,
segment_id=segment_id,
agent1_dimension=seg.get("dimension_id", ""),
agent1_rationale=seg.get("rationale", ""),
r1_dimension=map_r1.get(segment_id, {}).get("dimension_id", ""),
r1_comment=map_r1.get(segment_id, {}).get("comment", ""),
r2_dimension=map_r2.get(segment_id, {}).get("dimension_id", ""),
r2_comment=map_r2.get(segment_id, {}).get("comment", ""),
resolved_dimension=resolved_dimension,
resolution_note=resolution_note,
)
# Check if all disagreements handled β advance
if report.get("status") == "ready_for_agent2":
write_state(session_dir, "READY_FOR_AGENT2", {"kappa": report["overall_kappa"]})
print(f"[Orchestrator] [{session_id}] All disagreements resolved. "
f"Ready for Agent 2.")
def discard_session_disagreement(
session_id: str,
sessions_root: Path,
segment_id: str,
discard_note: str,
) -> None:
"""Discard an unresolvable disagreement and advance if all are handled."""
session_dir = sessions_root / session_id
report_path = session_dir / F_KAPPA_REPORT
report = discard_disagreement(
report_path=report_path,
segment_id=segment_id,
discard_note=discard_note,
)
if report.get("status") == "ready_for_agent2":
write_state(session_dir, "READY_FOR_AGENT2", {"kappa": report["overall_kappa"]})
print(f"[Orchestrator] [{session_id}] All disagreements handled. "
f"Ready for Agent 2.")
# ---------------------------------------------------------------------------
# Advance β single step forward for a session
# ---------------------------------------------------------------------------
def advance_session(session_dir: Path, sessions_root: Path) -> str:
"""
Advance a session by one step based on its current state.
Returns the new state string.
"""
state_str = get_state(session_dir)
try:
if state_str == "CREATED":
step_parse(session_dir)
elif state_str == "PARSED":
step_segment(session_dir)
elif state_str == "SEGMENTED":
step_generate_templates(session_dir)
elif state_str in ("AWAITING_R1", "AWAITING_R2"):
new_state = step_check_codings(session_dir)
if new_state == "CALCULATING_KAPPA":
step_calculate_kappa(session_dir)
elif state_str == "CALCULATING_KAPPA":
step_calculate_kappa(session_dir)
elif state_str == "READY_FOR_AGENT2":
step_run_agent2(session_dir, sessions_root)
elif state_str in ("COMPLETE", "ERROR", "BELOW_THRESHOLD", "DISAGREEMENT_REVIEW"):
pass # these states require human intervention
except Exception as e:
error_msg = traceback.format_exc()
write_state(session_dir, "ERROR", {
"error": str(e),
"traceback": error_msg,
})
print(f"[Orchestrator] ERROR in session {session_dir.name}:\n{error_msg}")
return get_state(session_dir)
# ---------------------------------------------------------------------------
# File watcher
# ---------------------------------------------------------------------------
class SessionWatcher:
"""
Watches the sessions root directory for file changes.
When a coding file is detected, automatically advances the session.
"""
def __init__(self, sessions_root: Path):
self.sessions_root = sessions_root
self.sessions_root.mkdir(parents=True, exist_ok=True)
self._last_seen: dict[str, set[str]] = {} # session_id β set of filenames
def _scan_session(self, session_dir: Path) -> set[str]:
"""Return set of filenames currently in the session directory."""
return {f.name for f in session_dir.iterdir() if f.is_file()}
def _detect_new_files(self, session_id: str, current_files: set[str]) -> set[str]:
"""Return files that appeared since last scan."""
previous = self._last_seen.get(session_id, set())
return current_files - previous
def tick(self) -> None:
"""One scan cycle β check all sessions for changes."""
for session_dir in sorted(self.sessions_root.iterdir()):
if not session_dir.is_dir():
continue
session_id = session_dir.name
state_str = get_state(session_dir)
current_files = self._scan_session(session_dir)
new_files = self._detect_new_files(session_id, current_files)
self._last_seen[session_id] = current_files
# Always advance newly created sessions through automated steps
if state_str in ("CREATED", "PARSED", "SEGMENTED"):
advance_session(session_dir, self.sessions_root)
# Advance when both codings arrive
elif state_str in ("AWAITING_R1", "AWAITING_R2"):
coding_files = {F_CODING_R1, F_CODING_R2}
if new_files & coding_files:
print(f"[Watcher] New coding file(s) detected in {session_id}: "
f"{new_files & coding_files}")
advance_session(session_dir, self.sessions_root)
# Advance when ready for Agent 2
elif state_str == "READY_FOR_AGENT2":
advance_session(session_dir, self.sessions_root)
def run(self) -> None:
"""Run the watcher loop indefinitely."""
print(f"[Watcher] Watching {self.sessions_root} every {WATCH_INTERVAL_SECS}s...")
print(f"[Watcher] Press Ctrl+C to stop.\n")
# Initial scan to populate _last_seen without triggering false positives
for session_dir in self.sessions_root.iterdir():
if session_dir.is_dir():
self._last_seen[session_dir.name] = self._scan_session(session_dir)
while True:
try:
self.tick()
except KeyboardInterrupt:
print("\n[Watcher] Stopped.")
break
except Exception as e:
print(f"[Watcher] Unexpected error: {e}")
traceback.print_exc()
time.sleep(WATCH_INTERVAL_SECS)
# ---------------------------------------------------------------------------
# Status display
# ---------------------------------------------------------------------------
def print_all_status(sessions_root: Path) -> None:
"""Print a summary of all sessions and their current states."""
sessions = sorted(sessions_root.iterdir()) if sessions_root.exists() else []
if not sessions:
print("[Orchestrator] No sessions found.")
return
print(f"\n{'β' * 70}")
print(f" SESSION STATUS β {sessions_root}")
print(f"{'β' * 70}")
print(f" {'SESSION':<20} {'STATE':<25} {'KAPPA':<8} {'SEGMENTS':<10} UPDATED")
print(f" {'-'*20} {'-'*25} {'-'*8} {'-'*10} {'-'*20}")
for session_dir in sessions:
if not session_dir.is_dir():
continue
state = read_state(session_dir)
if not state:
continue
sid = state.get("session_id", session_dir.name)
s = state.get("state", "UNKNOWN")
kappa = f"{state.get('kappa', 'β'):.3f}" if isinstance(state.get("kappa"), float) else "β"
n_segs = str(state.get("n_segments", "β"))
updated = state.get("updated_at", "")[:16].replace("T", " ")
# Colour-code state
marker = {
"COMPLETE": "β",
"ERROR": "β",
"BELOW_THRESHOLD": "!",
"DISAGREEMENT_REVIEW":"?",
"READY_FOR_AGENT2": "β",
"LEARNING": "β³",
}.get(s, " ")
print(f" {sid:<20} {marker} {s:<23} {kappa:<8} {n_segs:<10} {updated}")
# Pending rules
pending = list_pending_rules()
if pending:
print(f"\n β {len(pending)} learned rule(s) pending human approval.")
print(f" Run: python orchestrator.py approve-rule <rule_id> <researcher_id>")
print(f"{'β' * 70}\n")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
command = sys.argv[1]
if command == "new":
if len(sys.argv) < 4:
print("Usage: python orchestrator.py new <transcript_file> <session_id> [sessions_root]")
sys.exit(1)
transcript = Path(sys.argv[2])
session_id = sys.argv[3]
root = Path(sys.argv[4]) if len(sys.argv) > 4 else Path("sessions")
session_dir = create_session(transcript, session_id, root)
# Immediately start automated steps
watcher = SessionWatcher(root)
watcher.tick()
elif command == "watch":
root = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("sessions")
SessionWatcher(root).run()
elif command == "advance":
if len(sys.argv) < 3:
print("Usage: python orchestrator.py advance <session_id> [sessions_root]")
sys.exit(1)
session_id = sys.argv[2]
root = Path(sys.argv[3]) if len(sys.argv) > 3 else Path("sessions")
session_dir = root / session_id
new_state = advance_session(session_dir, root)
print(f"[Orchestrator] Session {session_id} β {new_state}")
elif command == "status":
root = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("sessions")
print_all_status(root)
elif command == "resolve":
# python orchestrator.py resolve <session_id> <segment_id> <dimension> <note> [sessions_root]
session_id = sys.argv[2]
segment_id = sys.argv[3]
dimension = sys.argv[4]
note = sys.argv[5]
root = Path(sys.argv[6]) if len(sys.argv) > 6 else Path("sessions")
resolve_session_disagreement(session_id, root, segment_id, dimension, note)
elif command == "discard":
# python orchestrator.py discard <session_id> <segment_id> <note> [sessions_root]
session_id = sys.argv[2]
segment_id = sys.argv[3]
note = sys.argv[4]
root = Path(sys.argv[5]) if len(sys.argv) > 5 else Path("sessions")
discard_session_disagreement(session_id, root, segment_id, note)
elif command == "approve-rule":
rule_id = sys.argv[2]
researcher = sys.argv[3]
note = sys.argv[4] if len(sys.argv) > 4 else ""
approve_rule(rule_id, researcher, note)
elif command == "reject-rule":
rule_id = sys.argv[2]
researcher = sys.argv[3]
note = sys.argv[4] if len(sys.argv) > 4 else "No reason given"
reject_rule(rule_id, researcher, note)
else:
print(f"Unknown command: {command}")
print(__doc__)
sys.exit(1)
|