"""Append one subagent_run row per agent after the fan-out completes. The orchestrator calls this once after all subagents return. It scans /findings-.json for each agent listed in the --usage-json payload, counts findings, and writes a subagent_run row to runs.jsonl using token / duration metadata supplied by the orchestrator. Usage: python scripts/log-run.py \\ --output-dir --run-id --repo --mode \\ --usage-json - < int: if not path.exists(): return 0 try: data = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: return 0 if isinstance(data, dict): findings = data.get("findings") if isinstance(findings, list): return len(findings) elif isinstance(data, list): return len(data) return 0 def main(argv: list[str]) -> int: p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--output-dir", required=True, type=Path) p.add_argument("--run-id", required=True) p.add_argument("--repo", required=True) p.add_argument("--mode", required=True, choices=["local", "ref"]) p.add_argument("--log-path", type=Path, default=_DEFAULT_LOG) p.add_argument("--usage-json", required=True, help="Path to JSON file, or '-' for stdin.") args = p.parse_args(argv) raw = sys.stdin.read() if args.usage_json == "-" else Path(args.usage_json).read_text(encoding="utf-8") usage = json.loads(raw) if not isinstance(usage, dict): print("usage-json must be a JSON object keyed by agent name", file=sys.stderr) return 2 for agent, meta in usage.items(): if not isinstance(meta, dict): print(f"skipping {agent}: usage entry not an object", file=sys.stderr) continue findings_path = args.output_dir / f"findings-{agent}.json" append_subagent_run( args.log_path, run_id=args.run_id, repo=args.repo, mode=args.mode, agent=agent, model=str(meta.get("model", "?")), input_tokens=int(meta.get("input_tokens", 0)), output_tokens=int(meta.get("output_tokens", 0)), duration_ms=int(meta.get("duration_ms", 0)), finding_count=_count_findings(findings_path), ) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))