report.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Status dashboards, Markdown reports, human-task digest, and Google Sheets row export."""
  2. from __future__ import annotations
  3. import brokers as brokers_mod
  4. import ledger as ledger_mod
  5. STATE_LABELS = {
  6. "new": "Not started",
  7. "searching": "Searching",
  8. "not_found": "Not found",
  9. "found": "Found (action needed)",
  10. "indirect_exposure": "Indirect exposure (PII on a relative's record)",
  11. "action_selected": "Action selected",
  12. "submitted": "Submitted",
  13. "verification_pending": "Awaiting verification",
  14. "awaiting_processing": "Processing",
  15. "confirmed_removed": "Removed",
  16. "reappeared": "Reappeared",
  17. "human_task_queued": "Human task",
  18. "blocked": "Blocked",
  19. }
  20. def status_counts(subject_id: str) -> dict:
  21. counts: dict[str, int] = {}
  22. for case in ledger_mod.load(subject_id).values():
  23. state = case.get("state", "new")
  24. counts[state] = counts.get(state, 0) + 1
  25. return counts
  26. def metrics(subject_id: str) -> dict:
  27. """Outcome metrics: what's actually confirmed vs merely claimed, and what's overdue.
  28. removal_rate is confirmed_removed over cases we actually acted on (found/submitted/... ),
  29. NOT over the whole broker DB, so it reflects real progress on real exposure. `in_flight`
  30. is 'claimed' (submitted/verifying/processing) but not yet re-scan-confirmed. `overdue`
  31. counts cases whose recheck window has already passed (the cron backlog).
  32. """
  33. c = status_counts(subject_id)
  34. removed = c.get("confirmed_removed", 0)
  35. in_flight = c.get("submitted", 0) + c.get("verification_pending", 0) + c.get("awaiting_processing", 0)
  36. open_found = c.get("found", 0) + c.get("reappeared", 0) + c.get("action_selected", 0) \
  37. + c.get("indirect_exposure", 0)
  38. acted = removed + in_flight + open_found + c.get("human_task_queued", 0) + c.get("blocked", 0)
  39. return {
  40. "confirmed_removed": removed,
  41. "in_flight_claimed": in_flight, # submitted but NOT yet verified gone
  42. "open_needs_action": open_found,
  43. "blocked": c.get("blocked", 0),
  44. "human_tasks": c.get("human_task_queued", 0),
  45. "acted_total": acted,
  46. "removal_rate": round(removed / acted, 3) if acted else 0.0,
  47. "overdue_rechecks": len(ledger_mod.due(subject_id)),
  48. }
  49. def render_markdown(subject_id: str) -> str:
  50. ledger = ledger_mod.load(subject_id)
  51. counts = status_counts(subject_id)
  52. total = sum(counts.values())
  53. removed = counts.get("confirmed_removed", 0)
  54. m = metrics(subject_id)
  55. lines = [
  56. f"# unbroker - status for `{subject_id}`",
  57. "",
  58. f"**{removed} / {total} confirmed removed** · removal rate (of acted-on cases): "
  59. f"{int(m['removal_rate'] * 100)}%",
  60. "",
  61. f"- Confirmed removed: {m['confirmed_removed']}",
  62. f"- In flight (submitted, not yet re-scan-confirmed): {m['in_flight_claimed']}",
  63. f"- Open / needs action: {m['open_needs_action']}",
  64. f"- Blocked (anti-bot): {m['blocked']} · Human tasks: {m['human_tasks']}",
  65. f"- Overdue rechecks (cron backlog): {m['overdue_rechecks']}",
  66. "",
  67. "| State | Count |",
  68. "|---|---|",
  69. ]
  70. for state in ledger_mod.STATES:
  71. if counts.get(state):
  72. lines.append(f"| {STATE_LABELS.get(state, state)} | {counts[state]} |")
  73. tasks = [c for c in ledger.values() if c.get("state") == "human_task_queued"]
  74. if tasks:
  75. lines += ["", "## Outstanding human tasks"]
  76. for c in tasks:
  77. reason = c.get("human_task_reason", "manual step required")
  78. lines.append(f"- **{c.get('broker_id')}** - {reason}")
  79. indirect = [c for c in ledger.values() if c.get("state") == "indirect_exposure"]
  80. if indirect:
  81. lines += ["", "## Indirect exposure (your PII on third-party records)",
  82. "Not removable via the broker's self-service opt-out (the record is about someone "
  83. "else). Lever: a targeted CCPA/GDPR delete-my-PII request naming only your own "
  84. "identifiers."]
  85. for c in indirect:
  86. ev = c.get("evidence") or {}
  87. note = ev.get("summary") or "subject's identifiers appear on another person's listing"
  88. lines.append(f"- **{c.get('broker_id')}** - {note}")
  89. return "\n".join(lines) + "\n"
  90. def human_tasks_markdown(subject_id: str) -> str:
  91. """ONE consolidated digest of everything that genuinely needs a human.
  92. The autonomous run accumulates human-only work silently (never interrupting);
  93. this digest is presented once, at the end, so the operator clears it in a
  94. single sitting. Includes queued tasks and blocked-site operator-browser checks.
  95. """
  96. ledger = ledger_mod.load(subject_id)
  97. tasks = [(bid, c) for bid, c in sorted(ledger.items()) if c.get("state") == "human_task_queued"]
  98. blocked = [(bid, c) for bid, c in sorted(ledger.items()) if c.get("state") == "blocked"]
  99. lines = [f"# Human tasks for `{subject_id}`", ""]
  100. if not tasks and not blocked:
  101. lines.append("Nothing needs a human right now.")
  102. return "\n".join(lines) + "\n"
  103. lines.append(f"{len(tasks)} manual step(s) + {len(blocked)} blocked site(s). "
  104. "Everything else ran (or will run) autonomously.")
  105. if tasks:
  106. lines += ["", "## Manual steps"]
  107. for bid, c in tasks:
  108. b = brokers_mod.get(bid) or {}
  109. opt = b.get("optout") or {}
  110. lines.append(f"### {b.get('name', bid)}")
  111. lines.append(f"- Why: {c.get('human_task_reason', 'manual step required')}")
  112. where = opt.get("url") or opt.get("email") or "(see broker record)"
  113. lines.append(f"- Where: {where}")
  114. for q in (opt.get("quirks") or [])[:2]:
  115. lines.append(f"- Note: {q}")
  116. lines.append("- Withhold: SSN and full ID numbers - always.")
  117. lines.append(f"- When done, tell the agent so it records the outcome for `{bid}`.")
  118. if blocked:
  119. lines += ["", "## Blocked sites (open in YOUR browser - it gets through where bots don't)"]
  120. for bid, c in blocked:
  121. b = brokers_mod.get(bid) or {}
  122. url = ((b.get("search") or {}).get("url")) or "(see broker record)"
  123. lines.append(f"- **{b.get('name', bid)}** - open {url}, search the subject, and report "
  124. "the verdict (or a screenshot) back to the agent.")
  125. return "\n".join(lines) + "\n"
  126. def sheets_rows(subject_id: str) -> list[list[str]]:
  127. """Header + one row per case for the optional Google Sheets tracker.
  128. The agent appends these via the `google-workspace` skill, e.g.:
  129. google_api.py sheets append <SHEET_ID> "Sheet1!A:F" --values <json-rows>
  130. """
  131. rows = [["broker_id", "state", "found", "tier", "removed_at", "next_recheck"]]
  132. for bid, c in sorted(ledger_mod.load(subject_id).items()):
  133. rows.append([
  134. bid,
  135. c.get("state", ""),
  136. str(c.get("found", "")),
  137. (c.get("automation") or {}).get("tier_used", ""),
  138. c.get("removal_confirmed_at") or "",
  139. c.get("next_recheck_at") or "",
  140. ])
  141. return rows