tiers.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. """Automation-tier selection and per-subject action planning.
  2. Tiers:
  3. T0 fully automated, no verification loop
  4. T1 automated submit + automated verification (email mode B/C, or backend-cleared captcha)
  5. T2 automated submit, verification needs a human (hard captcha / phone callback / account)
  6. T3 human-required end-to-end (gov ID, fax, mail, voice-only phone)
  7. """
  8. from __future__ import annotations
  9. import dossier as dossier_mod
  10. import vectors as vectors_mod
  11. HARD_HUMAN = ("gov_id", "fax", "mail", "phone_voice")
  12. def select_tier(broker: dict, email_mode: str = "draft_only",
  13. browser_clears_captcha: bool = False) -> str:
  14. req = ((broker.get("optout") or {}).get("requires")) or {}
  15. if not isinstance(req, dict):
  16. req = {} # defensive: a malformed record (e.g. requires as a list) must not crash planning
  17. if any(req.get(k) for k in HARD_HUMAN):
  18. return "T3"
  19. if req.get("account"):
  20. return "T2"
  21. captcha = bool(req.get("captcha"))
  22. if (captcha and not browser_clears_captcha) or req.get("phone_callback"):
  23. return "T2"
  24. if req.get("email_verification"):
  25. return "T1" if email_mode in ("programmatic", "alias") else "T2"
  26. if captcha and browser_clears_captcha:
  27. return "T1"
  28. return "T0"
  29. def plan(subject_dossier: dict, brokers_list: list[dict], cfg: dict,
  30. browser_clears_captcha: bool = False) -> list[dict]:
  31. email_mode = (subject_dossier.get("preferences") or {}).get("email_mode") \
  32. or cfg.get("email_mode", "draft_only")
  33. actions: list[dict] = []
  34. for b in brokers_list:
  35. if b.get("defunct"):
  36. # Dead domain (seized/NXDOMAIN): excluded from every scan/act surface so it
  37. # never wedges a crawl, queues an opt-out against a corpse, or re-checks one.
  38. # batch_plan surfaces the ids so the run book can say why they are absent.
  39. continue
  40. opt = b.get("optout") or {}
  41. search = b.get("search") or {}
  42. # Defensive shape coercion: a subagent may have written a malformed record (requires as a
  43. # list, quirks as a string). Normalize here so nothing downstream crashes on a bad broker file.
  44. req = opt.get("requires") if isinstance(opt.get("requires"), dict) else {}
  45. q = opt.get("quirks")
  46. quirks = q if isinstance(q, list) else ([q] if isinstance(q, str) and q else [])
  47. tier = select_tier(b, email_mode, browser_clears_captcha)
  48. disclosure = dossier_mod.select_disclosure(subject_dossier, opt.get("inputs", []))
  49. svectors = vectors_mod.search_vectors(subject_dossier, b)
  50. # Pre-warn (don't discover mid-flow): a broker whose identity gate hard-requires DOB will
  51. # force a human touchpoint if DOB was not collected at intake (§4.1). Surface it now.
  52. prewarn: list[str] = []
  53. if req.get("dob") and not (subject_dossier.get("identity") or {}).get("date_of_birth"):
  54. prewarn.append("date_of_birth: this broker's identity gate requires DOB to match records; "
  55. "collect it up front (intake --dob) or expect a mid-flow human pause")
  56. actions.append({
  57. "broker_id": b.get("id"),
  58. "broker_name": b.get("name"),
  59. "priority": b.get("priority"),
  60. "method": opt.get("method"),
  61. "tier": tier,
  62. "human_required": tier == "T3",
  63. "search_url": search.get("url"),
  64. "fetch": search.get("fetch", "web_extract"),
  65. "antibot": search.get("antibot"),
  66. "search_by": vectors_mod.supported_by(b),
  67. "search_vectors": svectors,
  68. "search_vectors_count": len(svectors),
  69. "optout_url": opt.get("url"),
  70. "optout_email": opt.get("email"),
  71. "disclosure_fields": sorted(disclosure.keys()),
  72. "needs_operator_input": prewarn,
  73. "owns": b.get("owns") or [],
  74. "notes": opt.get("notes", ""),
  75. "optout_quirks": quirks,
  76. "optout_requires": req,
  77. # The DELETION lane (right-to-delete), distinct from listing suppression. Structured so
  78. # the autopilot can route to it: {via: email|in_flow|web_form, email?, url?, kinds?, notes?}
  79. "deletion": opt.get("deletion") or {},
  80. # Exact ordered opt-out steps maintained IN the broker record (field-verified knowledge
  81. # lives with the data, not in code).
  82. "optout_playbook": opt.get("playbook") or [],
  83. })
  84. return actions
  85. def fanout(brokers_list: list[dict], batch_size: int = 5) -> dict:
  86. """Group brokers into batches for parallel `delegate_task` scan subagents.
  87. Scanning many brokers serially is slow and burns context; above `batch_size`
  88. the agent is expected to spawn one subagent per batch (see SKILL.md).
  89. """
  90. ids = [b.get("id") for b in brokers_list if b.get("id") and not b.get("defunct")]
  91. batches = [ids[i:i + batch_size] for i in range(0, len(ids), batch_size)]
  92. return {
  93. "broker_count": len(ids),
  94. "batch_size": batch_size,
  95. "should_fanout": len(ids) > batch_size,
  96. "batches": batches,
  97. }
  98. def runnable_for(subject_dossier: dict, brokers_list: list[dict]) -> tuple[list[dict], list[dict]]:
  99. """(runnable, unsearchable) split of the broker list for THIS subject.
  100. A broker with zero runnable search vectors (e.g. a name-only site in a phone-led run
  101. with no name on file) cannot be scanned at all -- exclude it up front instead of
  102. leaving it wedged in `unscanned` forever.
  103. """
  104. runnable: list[dict] = []
  105. unsearchable: list[dict] = []
  106. for b in brokers_list:
  107. if b.get("defunct"):
  108. continue # dead domains are neither runnable nor unsearchable: they are absent
  109. (runnable if vectors_mod.search_vectors(subject_dossier, b) else unsearchable).append(b)
  110. return runnable, unsearchable
  111. # States that mean "the crawl reached a verdict for this broker".
  112. _SCANNED_STATES = {"found", "not_found", "indirect_exposure", "blocked", "submitted",
  113. "verification_pending", "awaiting_processing", "confirmed_removed", "reappeared",
  114. "action_selected", "human_task_queued"}
  115. # States that still need a deletion action taken.
  116. _ACTIONABLE_STATES = {"found", "indirect_exposure", "reappeared", "action_selected"}
  117. def batch_plan(subject_dossier: dict, brokers_list: list[dict], cfg: dict,
  118. ledger: dict | None = None, browser_clears_captcha: bool = False) -> dict:
  119. """Reduce the per-broker plan into a phase-oriented batch view.
  120. Overlays the current ledger state on each broker, groups by what the operator
  121. should DO next, and collapses ownership clusters so a parent removal that clears
  122. children is ONE action, not N. Read-only: computes, never mutates the ledger.
  123. """
  124. ledger = ledger or {}
  125. defunct = [b.get("id") for b in brokers_list if b.get("defunct")]
  126. actions = plan(subject_dossier, brokers_list, cfg, browser_clears_captcha)
  127. vcount = {a["broker_id"]: a["search_vectors_count"] for a in actions}
  128. # child id -> parent id (only for parents present in this plan set)
  129. child_to_parent: dict[str, str] = {}
  130. for a in actions:
  131. for child in a.get("owns") or []:
  132. child_to_parent[child] = a["broker_id"]
  133. def state_of(bid: str) -> str:
  134. return (ledger.get(bid) or {}).get("state", "new")
  135. groups: dict[str, list[dict]] = {
  136. "unsearchable": [], # no runnable search vector for THIS subject (e.g. a name-only
  137. # site in a phone-led run) -> excluded from the crawl, not pending
  138. "unscanned": [], # no verdict yet -> Phase 1 crawl
  139. "found": [], # direct removable listing -> Phase 2 opt-out (incl. reappeared/action_selected)
  140. "indirect_exposure": [],# PII on a third party's record -> CCPA/GDPR delete email
  141. "blocked": [], # anti-bot / needs stealth browser -> requeue
  142. "in_progress": [], # submitted / verification_pending / awaiting_processing
  143. "human": [], # human_task_queued -> the end-of-run digest, NOT re-scanning
  144. "done": [], # confirmed_removed
  145. "not_found": [],
  146. }
  147. covered_by_parent: dict[str, list[str]] = {}
  148. for a in actions:
  149. bid = a["broker_id"]
  150. st = state_of(bid)
  151. # cluster collapse: if a parent in this set is already actioned, the child is covered
  152. parent = child_to_parent.get(bid)
  153. if parent and state_of(parent) in ("found", "reappeared", "action_selected", "submitted",
  154. "verification_pending", "awaiting_processing",
  155. "confirmed_removed", "human_task_queued"):
  156. covered_by_parent.setdefault(parent, []).append(bid)
  157. continue
  158. row = {"broker_id": bid, "broker_name": a["broker_name"], "priority": a["priority"],
  159. "tier": a["tier"], "method": a["method"], "state": st,
  160. "optout_url": a["optout_url"], "optout_email": a.get("optout_email"),
  161. "clears_children": a.get("owns") or [],
  162. "optout_requires": a.get("optout_requires") or {},
  163. "optout_quirks": a.get("optout_quirks") or [],
  164. "deletion": a.get("deletion") or {},
  165. "optout_playbook": a.get("optout_playbook") or [],
  166. "notes": a.get("notes", "")}
  167. if st in ("submitted", "verification_pending", "awaiting_processing"):
  168. groups["in_progress"].append(row)
  169. elif st == "confirmed_removed":
  170. groups["done"].append(row)
  171. elif st in ("reappeared", "action_selected"):
  172. groups["found"].append(row) # still needs the opt-out action
  173. elif st == "human_task_queued":
  174. groups["human"].append(row) # parked for the digest; never re-queued as work
  175. elif st in groups:
  176. groups[st].append(row)
  177. elif st not in _SCANNED_STATES:
  178. if not vcount.get(bid):
  179. groups["unsearchable"].append(row)
  180. else:
  181. groups["unscanned"].append(row)
  182. else:
  183. groups.setdefault(st, []).append(row)
  184. # PARENTS FIRST: within the actionable 'found' group, order cluster parents (a removal
  185. # that clears children) ahead of standalone listings, most-children first. Working a
  186. # parent before its children is what makes the cluster dedup real -- do them in this order.
  187. groups["found"].sort(key=lambda r: (-len(r.get("clears_children") or []),
  188. {"T0": 0, "T1": 1, "T2": 2, "T3": 3}.get(r.get("tier") or "", 9),
  189. r["broker_id"]))
  190. return {
  191. "subject": subject_dossier.get("subject_id"),
  192. "phase": "discover" if groups["unscanned"] else "delete",
  193. "defunct": defunct,
  194. "counts": {k: len(v) for k, v in groups.items()},
  195. "groups": groups,
  196. "cluster_savings": {p: kids for p, kids in covered_by_parent.items()},
  197. "parent_playbook": _parent_playbook(groups["found"]),
  198. "next_actions": _batch_next(groups, covered_by_parent),
  199. }
  200. def synthesize_steps(r: dict) -> list[str]:
  201. """Generic ordered opt-out steps derived from an optout record's structured fields.
  202. Used for any broker without a hand-verified `optout.playbook`. Bespoke, field-verified
  203. step lists live IN the broker JSON (`optout.playbook`) - single source of truth that
  204. accrues knowledge as live runs discover mechanics (see methods.md logging rule).
  205. """
  206. steps = [f"Opt out at {r.get('optout_url') or r.get('optout_email') or '(see broker record)'}"
  207. + (f" -- clears {', '.join(r['clears_children'])}." if r.get("clears_children") else ".")]
  208. req = r.get("optout_requires") or {}
  209. if req.get("profile_url"):
  210. steps.append("Needs the confirmed profile_url (paste the listing URL you recorded).")
  211. if req.get("email_verification"):
  212. steps.append("Email verification: the same browser/inbox must open the confirmation link.")
  213. if req.get("phone_callback"):
  214. steps.append("Phone-callback code required; queue a human task if no operator is available.")
  215. if req.get("gov_id"):
  216. steps.append("Government ID demanded (T3): human task; never send SSN or a full ID number.")
  217. d = r.get("deletion") or {}
  218. if d.get("email"):
  219. steps.append(f"DELETION lane: a right-to-delete request can be emailed to {d['email']}"
  220. + (f" ({d['notes']})" if d.get("notes") else "")
  221. + " -- prefer deletion over suppression.")
  222. if r.get("notes"):
  223. steps.append(str(r["notes"]))
  224. quirks = r.get("optout_quirks") or []
  225. for q in quirks[:4]:
  226. steps.append(str(q))
  227. if len(quirks) > 4:
  228. steps.append(f"(+{len(quirks) - 4} more quirks in this broker's record -- read them "
  229. "before filing; the record is the source of truth)")
  230. return steps
  231. def _parent_playbook(found_rows: list[dict]) -> list[dict]:
  232. """Tailored, ordered opt-out instructions for each cluster PARENT in the found group.
  233. Steps come from the broker record's own `optout.playbook` (field-verified, maintained with
  234. the data) with a synthesised fallback so the guidance is never empty. Standalone listings
  235. are intentionally omitted -- the playbook exists to make the parents-first order concrete.
  236. """
  237. playbook: list[dict] = []
  238. for i, r in enumerate([x for x in found_rows if x.get("clears_children")], start=1):
  239. steps = list(r.get("optout_playbook") or []) or synthesize_steps(r)
  240. playbook.append({
  241. "order": i,
  242. "broker_id": r["broker_id"],
  243. "broker_name": r["broker_name"],
  244. "tier": r["tier"],
  245. "clears_children": r["clears_children"],
  246. "optout_url": r.get("optout_url"),
  247. "optout_email": r.get("optout_email"),
  248. "deletion": r.get("deletion") or {},
  249. "steps": steps,
  250. })
  251. return playbook
  252. def _batch_next(groups: dict, covered: dict) -> list[str]:
  253. tips: list[str] = []
  254. if groups["unscanned"]:
  255. tips.append(f"PHASE 1 (crawl): {len(groups['unscanned'])} broker(s) unscanned -- run `fanout` and "
  256. "scan read-only before any deletion.")
  257. if groups["found"]:
  258. parents = [r for r in groups["found"] if r.get("clears_children")]
  259. if parents:
  260. order = " -> ".join(r["broker_id"] for r in parents)
  261. tips.append(f"PHASE 2 (opt-out): {len(groups['found'])} direct listing(s). DO CLUSTER PARENTS "
  262. f"FIRST, in this order: {order} (see `parent_playbook` for tailored per-parent "
  263. "steps), then the standalone listings.")
  264. else:
  265. tips.append(f"PHASE 2 (opt-out): {len(groups['found'])} direct listing(s) to remove.")
  266. if groups["indirect_exposure"]:
  267. tips.append(f"{len(groups['indirect_exposure'])} indirect-exposure case(s): send a targeted "
  268. "CCPA/GDPR delete-my-PII email (render-email --kind ccpa_indirect), do NOT use the opt-out form.")
  269. if groups["blocked"]:
  270. tips.append(f"{len(groups['blocked'])} blocked (anti-bot): requeue for a stealth/cloud browser "
  271. "pass; don't burn subagent time fighting CAPTCHAs.")
  272. if covered:
  273. n = sum(len(v) for v in covered.values())
  274. tips.append(f"Cluster dedup: {n} child site(s) covered by parent removals -- skip separate opt-outs.")
  275. if groups["in_progress"]:
  276. tips.append(f"{len(groups['in_progress'])} in progress: resolve verification links, then confirm removal.")
  277. if groups.get("unsearchable"):
  278. tips.append(f"{len(groups['unsearchable'])} broker(s) have no runnable search vector for "
  279. "this subject (missing identifier, e.g. a name-only site in a phone-led "
  280. "run) -- excluded from the crawl, not pending.")
  281. if groups.get("human"):
  282. tips.append(f"{len(groups['human'])} parked human task(s): present via `tasks` at end of run "
  283. "(do not re-scan or re-queue them).")
  284. return tips