autopilot.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. """Autonomous action queue: what should the agent do RIGHT NOW for this subject?
  2. `next_actions` turns (dossier, broker DB, config, ledger) into an ordered queue of
  3. concrete agent actions plus a human digest. The agent's whole run becomes a loop:
  4. while True:
  5. q = pdd.py next <subject>
  6. if not q["actions"]: break
  7. execute each action, record outcomes
  8. present q["human_digest"] once; schedule cron at q["next_wake_at"]
  9. Policy (cfg["autonomy"]):
  10. full - intake consent is standing authorization; T0-T2 agent actions are
  11. executed without pausing, except actions that set confirm_first=True
  12. themselves (dnc_register). Humans appear only in the digest.
  13. assisted - same queue, but every submission action carries confirm_first=True.
  14. The queue is deterministic and side-effect free: it never mutates the ledger, it
  15. only reads. Executing + recording stays with the agent (and the record command).
  16. """
  17. from __future__ import annotations
  18. import datetime as _dt
  19. import os
  20. from pathlib import Path
  21. import brokers as brokers_mod
  22. import dossier as dossier_mod
  23. import emailer
  24. import ledger as ledger_mod
  25. import paths
  26. import registry
  27. import tiers
  28. CACHE_STALE_DAYS = 7 # refresh the live broker list after this
  29. FANOUT_THRESHOLD = 8 # above this many unscanned brokers, use delegate_task fan-out
  30. # States with nothing left to do (absent a due recheck).
  31. _TERMINAL = {"not_found", "confirmed_removed"}
  32. _IN_FLIGHT = {"submitted", "verification_pending", "awaiting_processing"}
  33. def cache_age_days(now: float | None = None) -> float | None:
  34. """Age of the live BADBOOL cache in days, or None if never pulled."""
  35. p: Path = paths.brokers_cache_path()
  36. if not p.exists():
  37. return None
  38. now = now if now is not None else _dt.datetime.now().timestamp()
  39. return max(0.0, (now - p.stat().st_mtime) / 86400.0)
  40. def _now_iso() -> str:
  41. return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
  42. def _min_future_recheck(ledger: dict, at: str, skip: set | frozenset = frozenset()) -> str | None:
  43. future = [c.get("next_recheck_at") for bid, c in ledger.items()
  44. if bid not in skip and c.get("next_recheck_at") and c["next_recheck_at"] > at]
  45. return min(future) if future else None
  46. def _digest(broker_row: dict, reason: str, steps: list[str], prep: list[str] | None = None) -> dict:
  47. return {
  48. "broker_id": broker_row.get("broker_id"),
  49. "broker_name": broker_row.get("broker_name"),
  50. "reason": reason,
  51. "agent_prep": prep or [], # commands the agent runs BEFORE handing this to the human
  52. "steps": steps, # what the human actually does
  53. "withhold": ["SSN", "full driver's-license / passport numbers"],
  54. }
  55. def request_kind(dossier: dict, allowed: list[str] | None = None) -> str:
  56. """Pick the honest legal basis for a deletion request from the subject's residency.
  57. ccpa only for California residents, gdpr only for EU/UK residents, generic otherwise.
  58. `allowed` (from the broker's deletion.kinds) can restrict DOWN to generic but never
  59. upgrades to a law the subject can't truthfully claim.
  60. """
  61. res = (dossier.get("residency_jurisdiction") or "US").upper()
  62. if res.startswith("US-CA"):
  63. kind = "ccpa"
  64. elif res.startswith(("EU", "UK", "GB")):
  65. kind = "gdpr"
  66. else:
  67. kind = "generic"
  68. if allowed and kind not in allowed and "generic" in allowed:
  69. kind = "generic"
  70. return kind
  71. _HUMAN_GATES = ("gov_id", "fax", "mail", "phone_voice", "phone_callback", "account")
  72. def _email_lane(row: dict) -> tuple[str | None, str]:
  73. """(address, why) for the autonomous email lane of this broker, if one exists.
  74. Lane rules:
  75. 1. the broker's primary opt-out method IS email;
  76. 2. the record marks its deletion lane email-preferred (deletion.via == "email");
  77. 3. RESCUE: the primary flow is human-gated (gov ID / fax / phone / account) but a
  78. right-to-delete email exists - the email lane restores full autonomy (this is the
  79. verified Whitepages pattern: privacyrequest@ accepts requests precisely so people
  80. don't have to do the phone-callback tool).
  81. """
  82. deletion = row.get("deletion") or {}
  83. req = row.get("optout_requires") or {}
  84. if row.get("method") == "email":
  85. addr = row.get("optout_email") or deletion.get("email")
  86. return (addr, "primary opt-out method is email") if addr else (None, "")
  87. if deletion.get("via") == "email" and deletion.get("email"):
  88. return deletion["email"], "record prefers the right-to-delete email lane"
  89. if (row.get("tier") == "T3" or any(req.get(k) for k in _HUMAN_GATES)) and deletion.get("email"):
  90. return deletion["email"], "rescue: primary flow is human-gated; deletion email restores autonomy"
  91. return None, ""
  92. def _email_identity_ready(dossier: dict) -> bool:
  93. """One predicate shared by every email lane: the subject has a full name AND a contact
  94. email, so a request can self-identify and carry a confirm-to address."""
  95. return bool(((dossier.get("identity") or {}).get("full_name") or "").strip()
  96. and dossier_mod.contact_email(dossier))
  97. # Open defunct cases worth closing: every state the ledger lets a defunct broker leave for
  98. # not_found, minus the pre-verdict ones (new/searching) that never hold a listing and
  99. # not_found itself (the same-state move is always allowed).
  100. _DEFUNCT_OPEN_STATES = {s for s in ledger_mod.STATES
  101. if s not in {"new", "searching", "not_found"}
  102. and ledger_mod.can_transition(s, "not_found", broker_defunct=True)}
  103. def _defunct_closeout_digest(ledger: dict, defunct_ids: set, by_id: dict, subject_id: str) -> list[dict]:
  104. """One-time digest entries closing the OPEN cases of defunct brokers as not_found.
  105. The plan and batch views exclude dead domains (never scanned, opted-out, or re-checked),
  106. so this is the only place they surface -- and not_found from an in-flight state is legal
  107. only for a broker whose record carries `defunct` (see ledger.DEFUNCT_CLOSEOUT_FROM).
  108. """
  109. out = []
  110. for bid, case in sorted(ledger.items()):
  111. if bid not in defunct_ids or case.get("state") not in _DEFUNCT_OPEN_STATES:
  112. continue
  113. out.append(_digest(
  114. {"broker_id": bid, "broker_name": (by_id.get(bid) or {}).get("name") or bid},
  115. "broker is defunct (domain dead/seized) - close the case",
  116. [f"python3 scripts/pdd.py record {subject_id} {bid} not_found "
  117. f"--reason 'broker defunct: see its broker record'"]))
  118. return out
  119. def _optout_action(row: dict, playbook: dict[str, dict], subject_id: str, dossier: dict,
  120. email_mode: str, smtp_ok: bool, confirm_first: bool) -> tuple[dict | None, dict | None]:
  121. """Map one actionable `found` row to (agent_action, human_digest_entry).
  122. Routing order maximizes autonomy: (1) the email lane (primary email method, preferred
  123. right-to-delete email, or rescue from a human-gated form) beats everything when SMTP is
  124. up; (2) genuinely human-only flows go to the digest; (3) web forms are driven with the
  125. record's own field-verified playbook steps.
  126. """
  127. bid = row["broker_id"]
  128. req = row.get("optout_requires") or {}
  129. tier = row.get("tier")
  130. deletion = row.get("deletion") or {}
  131. # 1) The autonomous EMAIL LANE (right-to-delete by email + confirm the reply).
  132. # Autonomous when SMTP is configured (programmatic/alias) OR in browser mode (agent sends via
  133. # the operator's logged-in webmail; no password needed).
  134. email_addr, lane_why = _email_lane(row)
  135. can_email = (email_mode in ("programmatic", "alias") and smtp_ok) or email_mode == "browser"
  136. if email_addr and can_email:
  137. kind = request_kind(dossier, deletion.get("kinds"))
  138. # Phase 2 identity gate: a legal email must self-identify. Intake only WARNS when
  139. # the name/contact email is missing (scans don't need them); enforce it HERE so a
  140. # nameless subject routes to the digest instead of auto-sending a request signed
  141. # "None" (or carrying an unfilled {full_name} placeholder).
  142. if not _email_identity_ready(dossier):
  143. return None, _digest(row, "email lane ready, but the subject's full name / contact email is missing",
  144. ["Collect them (intake --full-name / --contact-email, or a dossier edit), "
  145. "then re-run `next` -- the email action will surface",
  146. f"Then: python3 scripts/pdd.py send-email {subject_id} {bid} --kind {kind} "
  147. f"--to {email_addr} --listing <confirmed-url>"])
  148. via = "browser" if email_mode == "browser" else "smtp"
  149. then = ("send-email records it + returns a recipient-locked payload; compose and send it in "
  150. "the operator's webmail via browser_exec, then `verify-link` on the reply and open the link"
  151. if via == "browser" else
  152. "state auto-records as submitted; poll-verification picks up their verification reply, "
  153. "open its link, then record")
  154. return {
  155. "type": "optout_email_send",
  156. "broker_id": bid, "broker_name": row.get("broker_name"), "tier": tier,
  157. "confirm_first": confirm_first, "send_via": via,
  158. "to": email_addr, "kind": kind, "why": lane_why,
  159. "command": f"python3 scripts/pdd.py send-email {subject_id} {bid} --kind {kind} "
  160. f"--to {email_addr} --listing <confirmed-url>",
  161. "then": then,
  162. }, None
  163. if row.get("method") == "email":
  164. return None, _digest(row, "email opt-out (draft mode: a human must hit send)",
  165. ["Send the rendered draft from your own mail client",
  166. f"Then: python3 scripts/pdd.py record {subject_id} {bid} submitted "
  167. f"--disclosed contact_email --channel email"],
  168. prep=[f"python3 scripts/pdd.py render-email {subject_id} {bid} --listing <confirmed-url>"])
  169. # 2) Genuinely human-only work goes to the digest (no email lane could rescue it).
  170. if tier == "T3":
  171. return None, _digest(row, "human-only opt-out (gov ID / fax / mail / voice phone)",
  172. [f"Follow the broker's process at {row.get('optout_url') or row.get('optout_email')}",
  173. "Provide only the fields the listing already shows; cross out ID numbers on any document"])
  174. if req.get("phone_callback"):
  175. return None, _digest(row, "phone-callback verification (operator must be on the phone)",
  176. [f"Open {row.get('optout_url')} and submit with only the planned fields",
  177. "Answer the automated call and enter the 4-digit code to finish"],
  178. prep=[f"python3 scripts/pdd.py plan {subject_id} --batch # confirm fields first"])
  179. if req.get("account"):
  180. return None, _digest(row, "requires creating/holding an account with the broker",
  181. [f"Create/log in at {row.get('optout_url')} and submit the opt-out",
  182. "Use the subject's contact email; no extra PII beyond the planned fields"])
  183. # 3) web_form: drive the browser with the record's own playbook steps.
  184. steps = (playbook.get(bid) or {}).get("steps") or list(row.get("optout_playbook") or []) \
  185. or tiers.synthesize_steps(row)
  186. action = {
  187. "type": "optout_web_form",
  188. "broker_id": bid, "broker_name": row.get("broker_name"), "tier": tier,
  189. "confirm_first": confirm_first,
  190. "optout_url": row.get("optout_url"),
  191. "clears_children": row.get("clears_children") or [],
  192. "steps": steps,
  193. "after": f"python3 scripts/pdd.py record {subject_id} {bid} submitted "
  194. f"--disclosed <field>... --channel web_form",
  195. }
  196. if deletion:
  197. if deletion.get("prefer", True):
  198. action["prefer_deletion"] = ("this record has a right-to-delete lane -- complete the "
  199. "DELETION flow, not just suppression"
  200. + (f" ({deletion.get('notes')})" if deletion.get("notes") else ""))
  201. else:
  202. # Some brokers invert the usual rule: deleting the account removes suppressions and
  203. # does not stop public-records re-listing (e.g. PeopleConnect). Suppress and maintain.
  204. action["prefer_suppression"] = (deletion.get("notes")
  205. or "suppression (maintained) is what removes you here; "
  206. "deleting undoes it and does not stop re-listing")
  207. if req.get("captcha"):
  208. action["note"] = ("CAPTCHA-gated: attempt with the configured browser backend once; if it "
  209. "does not clear, record human_task_queued with the reason. Do NOT retry-loop "
  210. "or bypass -- and do NOT record blocked either: a blocked case re-scans, "
  211. "re-finds the listing and re-queues this opt-out forever, while a parked "
  212. "task stays one standing digest entry until the operator acts")
  213. return action, None
  214. def _indirect_case(row: dict, dossier: dict, email_mode: str, smtp_ok: bool,
  215. subject_id: str, confirm_first: bool) -> tuple[dict | None, dict | None]:
  216. """Map one `indirect_exposure` row to (agent_action, human_digest_entry).
  217. The subject's PII sits on a THIRD PARTY's record: drive the opt-out form with only the
  218. subject's own identifiers, or send the targeted delete-my-PII email -- which must
  219. self-identify, so a nameless/contact-less subject routes to the digest instead.
  220. """
  221. bid = row["broker_id"]
  222. has_email = bool(row.get("optout_email") or (row.get("deletion") or {}).get("email"))
  223. if not has_email and row.get("optout_url"):
  224. # No email lane (e.g. ThatsThem is web-form-only): drive the opt-out FORM, submitting
  225. # ONLY the subject's own identifiers to scrub from the third party's record.
  226. return {
  227. "type": "indirect_web_form",
  228. "broker_id": bid, "confirm_first": confirm_first,
  229. "optout_url": row.get("optout_url"),
  230. "steps": [f"browser_exec: new_tab({row.get('optout_url')!r}) + wait_for_load()",
  231. "submit ONLY the subject's own identifiers (the fields the form requires) to "
  232. "remove them from the third party's record; disclose nothing extra",
  233. "confirm the success state, screenshot into evidence/"],
  234. "after": f"python3 scripts/pdd.py record {subject_id} {bid} submitted --channel web_form",
  235. }, None
  236. if (email_mode in ("programmatic", "alias") and smtp_ok) or email_mode == "browser":
  237. # Same identity gate as the email lane: a delete-my-PII request must self-identify.
  238. if not _email_identity_ready(dossier):
  239. return None, _digest(row, "indirect-exposure request needs the subject's name + contact email first",
  240. ["Collect them (intake --full-name / --contact-email), then re-run `next`"])
  241. return {
  242. "type": "indirect_email_send",
  243. "broker_id": bid, "confirm_first": confirm_first,
  244. "send_via": "browser" if email_mode == "browser" else "smtp",
  245. "command": f"python3 scripts/pdd.py send-email {subject_id} {bid} --kind ccpa_indirect "
  246. f"--listing <third-party-listing-url>",
  247. }, None
  248. return None, _digest(row, "indirect-exposure request (draft mode: a human must hit send)",
  249. ["Send the rendered ccpa_indirect draft",
  250. f"Then: python3 scripts/pdd.py record {subject_id} {bid} submitted "
  251. f"--disclosed contact_email --channel email"],
  252. prep=[f"python3 scripts/pdd.py render-email {subject_id} {bid} "
  253. f"--kind ccpa_indirect --listing <url>"])
  254. def _registry_one_shots(dossier: dict, registry_recs: list, residency: str,
  255. subject_id: str, confirm_first: bool) -> list[dict]:
  256. """One-shot registrations beyond the per-broker casework, each surfaced once per subject
  257. until `--filed` records it: the CA DROP deletion (ONE verified request deletes from every
  258. registered data broker - the highest-leverage removal there is) and the FTC National Do
  259. Not Call Registry (US personal numbers; lawful telemarketers must stop within 31 days -
  260. complementary to broker removal, which is what cuts the lead lists scammers buy)."""
  261. prefs = dossier.get("preferences") or {}
  262. actions: list[dict] = []
  263. if registry_recs and residency.startswith("US-CA") and not prefs.get("drop_filed_at"):
  264. actions.append({
  265. "type": "drop_submit",
  266. "one_shot": True,
  267. "registry_count": len(registry_recs),
  268. "url": registry.DROP_URL,
  269. "command": f"python3 scripts/pdd.py drop {subject_id}",
  270. "why": f"CA resident: one DROP request deletes from all {len(registry_recs)} registered "
  271. "data brokers at once (superset of what commercial services cover).",
  272. "after": f"python3 scripts/pdd.py drop {subject_id} --filed",
  273. })
  274. # DNC: surfaced ONLY for phone-led runs (focus_phone set). A name-led subject's `next`
  275. # must reach done_for_now instead of offering an unrelated registry signup; `dnc` stays
  276. # available manually for any subject. confirm_first is ALWAYS true -- intake consent
  277. # authorizes broker removal, and a new registry submission is a separate disclosure
  278. # the operator confirms even in full autonomy. --declined clears it without recording
  279. # a filing that never happened.
  280. eligible = registry.dnc_eligible(dossier)
  281. if (residency.startswith("US") and prefs.get("focus_phone") and eligible
  282. and not prefs.get("dnc_filed_at") and not prefs.get("dnc_declined_at")):
  283. actions.append({
  284. "type": "dnc_register",
  285. "one_shot": True,
  286. "url": registry.DNC_URL,
  287. "confirm_first": True,
  288. "command": f"python3 scripts/pdd.py dnc {subject_id}",
  289. "why": "US personal number(s) not yet on the National Do Not Call Registry: lawful "
  290. "telemarketers must stop within 31 days; registration never expires.",
  291. "how": "drive the FTC form with browser_exec (up to 3 numbers per pass + the subject's "
  292. "contact email; the FTC emails a confirmation PER NUMBER -- open each link "
  293. "within 72 hours or that number is not registered). If the form defeats the "
  294. "configured browser, present it as a manual step in the end-of-run digest "
  295. "instead of fighting it.",
  296. "after": f"python3 scripts/pdd.py dnc {subject_id} --filed",
  297. "declined": f"python3 scripts/pdd.py dnc {subject_id} --declined",
  298. })
  299. return actions
  300. def next_actions(dossier: dict, brokers_list: list[dict], cfg: dict,
  301. ledger: dict | None = None, env: dict | None = None) -> dict:
  302. env = os.environ if env is None else env
  303. ledger = ledger or {}
  304. subject_id = dossier.get("subject_id", "")
  305. autonomy = cfg.get("autonomy", "full")
  306. confirm_first = autonomy == "assisted"
  307. email_mode = cfg.get("email_mode", "draft_only")
  308. mail = emailer.available(env)
  309. at = _now_iso()
  310. batch = tiers.batch_plan(dossier, brokers_list, cfg, ledger,
  311. browser_clears_captcha=cfg.get("browser_backend") == "browserbase"
  312. or bool(env.get("BROWSERBASE_API_KEY")))
  313. groups = batch["groups"]
  314. playbook = {p["broker_id"]: p for p in batch.get("parent_playbook") or []}
  315. by_id = {b.get("id"): b for b in brokers_list}
  316. # From the whole catalog, not just brokers_list: `next --priority` passes a filtered list
  317. # but the ledger loops below walk every case.
  318. defunct_ids = {b.get("id") for b in [*brokers_list, *brokers_mod.load_all()] if b.get("defunct")}
  319. actions: list[dict] = []
  320. digest: list[dict] = []
  321. # 0) keep the broker DB fresh (autonomously)
  322. age = cache_age_days()
  323. if age is None or age > CACHE_STALE_DAYS:
  324. actions.append({
  325. "type": "refresh_brokers",
  326. "why": "live broker cache missing" if age is None else f"cache is {age:.0f} days old",
  327. "command": "python3 scripts/pdd.py refresh-brokers",
  328. })
  329. # 0b/0c) registry-level one-shots: the CA DROP deletion (one request covers every
  330. # registered broker) and the FTC National Do Not Call Registry (US personal numbers).
  331. registry_recs = brokers_mod.load_registry_cache()
  332. residency = (dossier.get("residency_jurisdiction") or "US").upper()
  333. drop_filed = bool((dossier.get("preferences") or {}).get("drop_filed_at"))
  334. actions.extend(_registry_one_shots(dossier, registry_recs, residency, subject_id, confirm_first))
  335. # 1) Phase 1 crawl: everything unscanned (read-only, parallel-safe)
  336. unscanned = groups.get("unscanned") or []
  337. if unscanned:
  338. ids = [r["broker_id"] for r in unscanned]
  339. if len(ids) > FANOUT_THRESHOLD:
  340. actions.append({
  341. "type": "fanout_scan",
  342. "broker_ids": ids,
  343. "command": f"python3 scripts/pdd.py fanout {subject_id}",
  344. "how": "spawn ONE delegate_task subagent per batch IN PARALLEL with each batch's brief; "
  345. "parent re-verifies key `found` claims before trusting them",
  346. })
  347. else:
  348. actions.append({
  349. "type": "scan_inline",
  350. "broker_ids": ids,
  351. "command": f"python3 scripts/pdd.py plan {subject_id}",
  352. "how": "run every search_vector per broker via the methods.md ladder "
  353. "(web_extract -> site: probe -> browser), record a verdict per broker",
  354. })
  355. # 2) in-flight email verifications: poll the inbox (or hand to the human in draft mode)
  356. for st in ("submitted", "verification_pending"):
  357. for bid, case in sorted(ledger.items()):
  358. if case.get("state") != st or bid in defunct_ids:
  359. continue # defunct: a dead domain never verifies anything
  360. broker = by_id.get(bid) or {}
  361. if not ((broker.get("optout") or {}).get("requires") or {}).get("email_verification"):
  362. continue
  363. if mail["imap"]:
  364. actions.append({
  365. "type": "poll_verification", "via": "imap",
  366. "broker_id": bid,
  367. "command": f"python3 scripts/pdd.py poll-verification {subject_id} --broker {bid}",
  368. "then": "open the returned link with browser_exec IN THE SAME AGENT BROWSER (sessions are "
  369. "browser-bound), complete the flow, then record: awaiting_processing",
  370. })
  371. elif email_mode == "browser":
  372. actions.append({
  373. "type": "poll_verification", "via": "browser", "broker_id": bid,
  374. "how": "open the broker's confirmation email in the operator's logged-in webmail "
  375. f"(browser_exec), then `python3 scripts/pdd.py verify-link {subject_id} {bid} "
  376. "--text '<email body>'` to score the link, open it with browser_exec in the SAME "
  377. "browser, then record awaiting_processing",
  378. })
  379. else:
  380. digest.append(_digest(
  381. {"broker_id": bid, "broker_name": (broker.get("name") or bid)},
  382. "verification email must be opened by a human (draft mode, no inbox access)",
  383. ["Open the broker's verification email in the subject's inbox and click the link",
  384. f"Then: python3 scripts/pdd.py record {subject_id} {bid} awaiting_processing"]))
  385. # 3) due rechecks: processing windows elapsed / reappearance sweeps
  386. for case in ledger_mod.due(subject_id, at=at, ledger=ledger):
  387. bid = case.get("broker_id")
  388. st = case.get("state")
  389. if bid in defunct_ids:
  390. continue # dead domain: nothing can reappear; the case rests where it is
  391. if st in ("awaiting_processing", "confirmed_removed"):
  392. actions.append({
  393. "type": "verify_removal",
  394. "broker_id": bid,
  395. "why": "processing window elapsed" if st == "awaiting_processing" else "periodic reappearance re-scan",
  396. "how": "re-run this broker's search_vectors; if gone record confirmed_removed; "
  397. "if still listed record reappeared and requeue the opt-out",
  398. })
  399. elif st in ("submitted", "verification_pending") and not mail["imap"]:
  400. pass # already covered by the digest entry above
  401. # 3b) defunct brokers: close their open cases honestly (see _defunct_closeout_digest).
  402. digest.extend(_defunct_closeout_digest(ledger, defunct_ids, by_id, subject_id))
  403. # 4) Phase 2 opt-outs: parents first (batch_plan already ordered them)
  404. for row in groups.get("found") or []:
  405. action, task = _optout_action(row, playbook, subject_id, dossier,
  406. email_mode, mail["smtp"], confirm_first)
  407. if action:
  408. actions.append(action)
  409. if task:
  410. digest.append(task)
  411. # 5) indirect exposure: targeted delete-my-PII requests
  412. for row in groups.get("indirect_exposure") or []:
  413. action, task = _indirect_case(row, dossier, email_mode, mail["smtp"], subject_id, confirm_first)
  414. if action:
  415. actions.append(action)
  416. if task:
  417. digest.append(task)
  418. # 6) blocked sites: stealth pass if we have one, else the operator-browser path
  419. blocked = groups.get("blocked") or []
  420. if blocked:
  421. ids = [r["broker_id"] for r in blocked]
  422. if bool(env.get("BROWSERBASE_API_KEY")):
  423. actions.append({
  424. "type": "stealth_rescan",
  425. "broker_ids": ids,
  426. "how": "retry these with the cloud/stealth browser backend, then record real verdicts",
  427. })
  428. else:
  429. for r in blocked:
  430. digest.append(_digest(r, "site blocks automated access (anti-bot); a human browser gets through",
  431. ["Open the paste-ready search URL from `plan` in your everyday browser",
  432. "Report the verdict (or a screenshot) back to the agent",
  433. f"Agent records: python3 scripts/pdd.py record {subject_id} "
  434. f"{r['broker_id']} <found|not_found|indirect_exposure>"]))
  435. # 7) anything already parked as a human task
  436. for bid, case in sorted(ledger.items()):
  437. if case.get("state") == "human_task_queued" and bid not in defunct_ids: # 3b closes those
  438. broker = by_id.get(bid) or {}
  439. digest.append(_digest({"broker_id": bid, "broker_name": broker.get("name") or bid},
  440. case.get("human_task_reason") or "queued manual step",
  441. ["See `pdd.py tasks` for the exact steps recorded with this case"]))
  442. # registry coverage summary (breadth beyond the scannable people-search sites)
  443. coverage = None
  444. if registry_recs:
  445. coverage = {
  446. "people_search_sites": len(brokers_list),
  447. "registered_data_brokers": len(registry_recs),
  448. "worked_via": "CA DROP one-shot" if residency.startswith("US-CA") else "targeted CCPA/GDPR email",
  449. }
  450. if not residency.startswith("US-CA"):
  451. coverage["note"] = ("DROP is CA-only; for this subject the registry is covered by targeted "
  452. "CCPA/GDPR deletion emails (`registry --search` then `send-email`), "
  453. "not a single portal request.")
  454. elif drop_filed:
  455. coverage["note"] = "DROP already filed; registry deletions are in the brokers' hands."
  456. next_wake = _min_future_recheck(ledger, at, skip=defunct_ids) # a dead case never wakes us
  457. return {
  458. "subject": subject_id,
  459. "autonomy": autonomy,
  460. "phase": batch.get("phase"),
  461. "counts": batch.get("counts"),
  462. "actions": actions,
  463. "human_digest": digest,
  464. "coverage": coverage,
  465. "done_for_now": not actions,
  466. "fully_done": not actions and not digest and not next_wake,
  467. "next_wake_at": next_wake,
  468. "note": ("assisted mode: pause for operator confirmation on every action with confirm_first=true"
  469. if confirm_first else
  470. "full autonomy: recorded intake consent authorizes these submissions; do not pause, "
  471. "EXCEPT on an action with confirm_first=true (e.g. dnc_register), which waits for the "
  472. "operator's yes. "
  473. "Present human_digest ONCE at the end of the run, not per item."),
  474. }