pdd.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. #!/usr/bin/env python3
  2. """unbroker - deterministic CLI helper.
  3. The Hermes agent orchestrates scanning and opt-out submission with native tools
  4. (`web_extract`, `browser_exec`, email mechanisms). THIS CLI owns the
  5. deterministic state: config, dossiers + consent, the broker DB, tier planning,
  6. the ledger + audit log, draft/template rendering, and reports.
  7. Run it through the `terminal` tool (it can read PII files under HERMES_HOME);
  8. do NOT run it through `execute_code` (that sandbox scrubs env and redacts output).
  9. Examples:
  10. python pdd.py setup
  11. python pdd.py intake --full-name "Jane Q. Public" --email jane@example.com \
  12. --city Oakland --state CA --residency US-CA --consent --consent-method self
  13. python pdd.py plan sub_xxxx --priority crucial
  14. python pdd.py record sub_xxxx spokeo found --found true \
  15. --evidence '{"listing_urls":["https://www.spokeo.com/..."]}'
  16. python pdd.py render-email sub_xxxx spokeo --listing https://www.spokeo.com/...
  17. python pdd.py status sub_xxxx
  18. """
  19. from __future__ import annotations
  20. import argparse
  21. import json
  22. import os
  23. import sys
  24. from pathlib import Path
  25. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  26. import autopilot
  27. import badbool
  28. import cdp
  29. import brokers as brokers_mod
  30. import config as config_mod
  31. import crypto
  32. import dossier as dossier_mod
  33. import email_modes
  34. import emailer
  35. import ledger as ledger_mod
  36. import legal
  37. import paths as paths_mod
  38. import registry
  39. import report as report_mod
  40. import tiers
  41. def _out(obj) -> None:
  42. print(json.dumps(obj, indent=2, ensure_ascii=False))
  43. def _require_subject(subject_id: str) -> dict:
  44. d = dossier_mod.load(subject_id)
  45. if not d:
  46. sys.exit(f"error: unknown subject {subject_id!r} (run `intake` first)")
  47. return d
  48. def cmd_setup(args) -> None:
  49. if getattr(args, "auto", False):
  50. # Autonomous path: detect capabilities and pick the most autonomous valid config without
  51. # asking anyone. Read creds from $HERMES_HOME/.env too (the terminal shell doesn't export
  52. # them). Explicit flags still win below.
  53. cfg = config_mod.auto_configure(env=config_mod.dotenv_env())
  54. else:
  55. cfg = config_mod.load_config()
  56. for key in ("autonomy", "email_mode", "browser_backend", "tracker_backend", "encryption"):
  57. val = getattr(args, key)
  58. if val:
  59. cfg[key] = val
  60. if cfg.get("encryption") == "age":
  61. if not crypto.age_available():
  62. sys.exit("error: encryption=age requested but `age`/`age-keygen` not found. "
  63. "Install age (e.g. `brew install age`) or use `--encryption none`.")
  64. crypto.ensure_identity() # generate the key now so encryption is actually engaged
  65. path = config_mod.save_config(cfg)
  66. migrated = _migrate_subjects() # rewrite existing dossiers/ledgers into the new at-rest format
  67. out = {
  68. "config_path": str(path),
  69. "config": cfg,
  70. "encryption_engaged": crypto.is_engaged(),
  71. "detected_upgrades": config_mod.detect_capabilities(),
  72. "migrated_subjects": migrated,
  73. "note": "Defaults are easiest-first (draft email, auto browser, local tracker, no encryption). "
  74. "Pass flags to opt into upgrades, then run `doctor` for a readiness summary.",
  75. }
  76. if cfg.get("encryption") == "age":
  77. out["age_identity"] = str(crypto.identity_path())
  78. _out(out)
  79. def _migrate_subjects() -> int:
  80. """Re-save each subject's dossier + ledger so they match the current at-rest format."""
  81. sd = paths_mod.subjects_dir()
  82. if not sd.exists():
  83. return 0
  84. n = 0
  85. for child in sorted(sd.iterdir()):
  86. if not child.is_dir():
  87. continue
  88. sid = child.name
  89. d = dossier_mod.load(sid)
  90. if d is not None:
  91. dossier_mod.save(d)
  92. n += 1
  93. led = ledger_mod.load(sid)
  94. if led:
  95. ledger_mod.save(sid, led)
  96. return n
  97. def _check_writable(path) -> bool:
  98. try:
  99. path.mkdir(parents=True, exist_ok=True)
  100. probe = path / ".write_test"
  101. probe.write_text("x", encoding="utf-8")
  102. probe.unlink()
  103. return True
  104. except OSError:
  105. return False
  106. def cmd_doctor(args) -> None:
  107. import platform
  108. cfg = config_mod.load_config()
  109. caps = config_mod.detect_capabilities(config_mod.dotenv_env()) # see creds in $HERMES_HOME/.env too
  110. data = paths_mod.data_dir()
  111. writable = _check_writable(data)
  112. curated = len(brokers_mod._load_curated())
  113. live = len(brokers_mod.load_live_cache())
  114. total = len(brokers_mod.load_all())
  115. L = ["unbroker - readiness check", "=" * 42,
  116. f"Python : {platform.python_version()}",
  117. f"Data dir : {data} ({'writable' if writable else 'NOT writable'})",
  118. f"Config : autonomy={cfg.get('autonomy', 'full')} email={cfg['email_mode']} "
  119. f"browser={cfg['browser_backend']} "
  120. f"tracker={cfg['tracker_backend']} encryption={cfg['encryption']}",
  121. f"Brokers : {total} available ({curated} curated + {live} live"
  122. + ("" if live else ", run `refresh-brokers` to expand to ~50") + ")",
  123. "", "Opt-in upgrades:"]
  124. rows = [
  125. ("Cloud browser (Browserbase) *RECOMMENDED*", caps["browserbase"],
  126. "default backend: clears soft CAPTCHAs (Turnstile/hCaptcha) -> more T1", "set BROWSERBASE_API_KEY"),
  127. ("Email auto (AgentMail)", caps["agentmail"],
  128. "send + auto-verify, per-broker aliases (Mode B/C)", "install agentmail skill / set AGENTMAIL_API_KEY"),
  129. ("Email send (CLI SMTP)", caps["smtp_send"],
  130. "`send-email` delivers opt-outs itself (Mode B)", "set EMAIL_ADDRESS / EMAIL_PASSWORD (+ EMAIL_SMTP_HOST)"),
  131. ("Verify-link poll (CLI IMAP)", caps["imap_read"],
  132. "`poll-verification` reads confirmation links itself", "set EMAIL_ADDRESS / EMAIL_PASSWORD (+ EMAIL_IMAP_HOST)"),
  133. ("Google Sheets tracker", caps["google_workspace"],
  134. "shared status dashboard", "set up the google-workspace skill"),
  135. ]
  136. for name, ok, enables, how in rows:
  137. L.append(f" [{'ON ' if ok else 'off'}] {name:<28} {enables}")
  138. if not ok:
  139. L.append(f" enable: {how}")
  140. # At-rest encryption: report TRUE engagement (configured + key present), not just binary presence.
  141. engaged = crypto.is_engaged()
  142. L.append(f" [{'ON ' if engaged else 'off'}] {'At-rest encryption (age)':<28} "
  143. "encrypts dossiers + ledgers on disk")
  144. if engaged:
  145. L.append(f" key: {crypto.identity_path()} (0600) - guards casual/backup/commit "
  146. "exposure, NOT a full-HERMES_HOME read")
  147. elif cfg["encryption"] == "age":
  148. L.append(" WARNING: encryption=age is SET but NOT engaged (age binary or key missing);"
  149. " dossiers would be PLAINTEXT")
  150. elif caps["age"]:
  151. L.append(" off - dossiers are plaintext (0600). enable: `setup --encryption age`")
  152. else:
  153. L.append(" off - dossiers are plaintext (0600). install `age` first to enable")
  154. L += ["", "Verdict:", " Ready now in DRAFT mode (no setup needed): scan brokers, draft opt-out",
  155. " emails for you to send, and track everything in the ledger."]
  156. if caps["browserbase"]:
  157. L.append(" Cloud browser ON (recommended default): soft/managed CAPTCHAs "
  158. "(Turnstile/hCaptcha) clear automatically -> those brokers stay T1.")
  159. else:
  160. L.append(" No cloud browser: set BROWSERBASE_API_KEY (the recommended default) so soft "
  161. "CAPTCHAs clear automatically; without it those brokers drop to T2 (human tasks).")
  162. if cfg["email_mode"] == "draft_only":
  163. L.append(" Email is draft-only: you send drafts + click verify links. For hands-off email "
  164. "WITHOUT storing a password, run `setup --email-mode browser` (agent sends + opens "
  165. "verify links via your logged-in webmail); or set EMAIL_* for SMTP/IMAP.")
  166. elif cfg["email_mode"] == "browser":
  167. L.append(" Email mode: browser (no password) - the agent sends opt-outs and opens verify "
  168. "links via the operator's logged-in webmail. This needs Hermes pointed at the "
  169. "operator's OWN Chrome over CDP (launch with --remote-debugging-port=9222 "
  170. "--user-data-dir=~/.hermes/chrome-debug, signed into the webmail once); else it falls "
  171. "back to drafts. Run `pdd.py cdp` to launch it (or `pdd.py cdp --print` for the command). "
  172. "See methods.md 'Browser backends'.")
  173. cloud_scan = cfg.get("browser_backend") == "browserbase" or (
  174. cfg.get("browser_backend") == "auto" and caps.get("browserbase"))
  175. if cloud_scan:
  176. L.append(" NOTE: your scan backend is a cloud browser (Browserbase). It is great for "
  177. "Phase-1 scanning but CANNOT be the browser that sends webmail (no inbox session) "
  178. "and is itself Cloudflare/DataDome-gated on session-bound gates (e.g. PeopleConnect). "
  179. "For Phase-2 email/verify, launch the operator's Chrome over CDP: `pdd.py cdp`.")
  180. if not crypto.is_engaged():
  181. L.append(" Storage: dossiers are PLAINTEXT JSON (0600 under HERMES_HOME). "
  182. "Run `setup --encryption age` for at-rest encryption.")
  183. if not live:
  184. L.append(" Next: run `refresh-brokers` to load the full broker list.")
  185. # Freshness: warn when cached lists / curated mechanics are going stale (silent broker rot).
  186. import time as _time
  187. STALE_CACHE_DAYS, STALE_VERIFY_DAYS = 30, 180
  188. def _age_days(p) -> float | None:
  189. try:
  190. return (_time.time() - p.stat().st_mtime) / 86400.0
  191. except OSError:
  192. return None
  193. fresh = []
  194. for label, p in [("BADBOOL", paths_mod.brokers_cache_path()),
  195. ("CA registry", paths_mod.registry_cache_path())]:
  196. age = _age_days(p)
  197. if age is None:
  198. fresh.append(f"{label}: not pulled")
  199. elif age > STALE_CACHE_DAYS:
  200. fresh.append(f"{label}: {age:.0f}d old (stale, re-pull)")
  201. stale_curated = documented = 0
  202. for b in brokers_mod._load_curated():
  203. conf = b.get("confidence")
  204. lv = b.get("last_verified")
  205. if conf == "documented" or not lv:
  206. documented += 1
  207. continue
  208. try:
  209. if (_time.time() - _time.mktime(_time.strptime(lv, "%Y-%m-%d"))) / 86400.0 > STALE_VERIFY_DAYS:
  210. stale_curated += 1
  211. except (ValueError, TypeError):
  212. pass
  213. if fresh:
  214. L.append(" Freshness: " + "; ".join(fresh) + " (run `refresh-brokers`).")
  215. if stale_curated or documented:
  216. L.append(f" Freshness: {stale_curated} curated broker(s) last-verified >{STALE_VERIFY_DAYS}d ago; "
  217. f"{documented} documented broker(s) awaiting first-use verification.")
  218. print("\n".join(L))
  219. def cmd_cdp(args) -> None:
  220. """Launch (or detect) the operator's Chrome over CDP for Phase-2 browser + webmail work.
  221. A cloud browser cannot send the operator's webmail or clear session-bound gates; this points
  222. Hermes at the operator's real Chrome on a dedicated debug profile (see methods.md).
  223. """
  224. import shlex
  225. import time
  226. port = args.port
  227. profile = Path(args.profile).expanduser() if args.profile else cdp.default_profile()
  228. live = cdp.endpoint_status(port)
  229. if live:
  230. _out({"running": True, "endpoint": f"127.0.0.1:{port}",
  231. "browser": live.get("Browser"),
  232. "webSocketDebuggerUrl": live.get("webSocketDebuggerUrl"),
  233. "note": "a debuggable browser is already listening; attach Hermes's browser (`/browser connect`) to "
  234. f"127.0.0.1:{port} and make sure the operator's webmail is signed in in THAT browser."})
  235. return
  236. if getattr(args, "check", False):
  237. _out({"running": False, "endpoint": f"127.0.0.1:{port}",
  238. "note": f"no debuggable browser here yet; run `pdd.py cdp --port {port}` (no --check) to launch one."})
  239. return
  240. browser = cdp.find_browser(args.browser)
  241. if not browser:
  242. _out({"running": False, "error": "no Chrome/Chromium-family browser found",
  243. "fix": "install Google Chrome, or pass --browser /path/to/chrome (or a command on PATH)"})
  244. return
  245. cmd = cdp.launch_command(browser, port, profile)
  246. if getattr(args, "print_only", False):
  247. _out({"running": False, "browser": browser, "profile": str(profile), "command": cmd,
  248. "shell": " ".join(shlex.quote(c) for c in cmd),
  249. "note": "run this yourself to launch the debug browser, then sign into your webmail once."})
  250. return
  251. pid = cdp.launch(browser, port, profile)
  252. live = None
  253. for _ in range(20): # give Chrome a few seconds to open the debug port
  254. live = cdp.endpoint_status(port)
  255. if live:
  256. break
  257. time.sleep(0.5)
  258. _out({"running": bool(live), "launched_pid": pid, "browser": browser,
  259. "profile": str(profile), "endpoint": f"127.0.0.1:{port}",
  260. "webSocketDebuggerUrl": (live or {}).get("webSocketDebuggerUrl"),
  261. "next": ([f"attach Hermes's browser (browser_exec) with `/browser connect` to 127.0.0.1:{port} (CDP)",
  262. "in the launched browser, sign into the operator's webmail ONCE (dedicated debug profile)",
  263. "then run email/verify flows in browser mode -- they use this logged-in session"]
  264. if live else
  265. ["browser launched but the debug port has not answered yet; give it a few seconds, then "
  266. f"re-run `pdd.py cdp --check --port {port}`"])})
  267. def cmd_intake(args) -> None:
  268. if args.json:
  269. data = json.loads(Path(args.json).read_text(encoding="utf-8"))
  270. identity = data["identity"]
  271. consent = data.get("consent", {})
  272. residency = data.get("residency_jurisdiction", "US")
  273. prefs = data.get("preferences") or {}
  274. if getattr(args, "focus_phone", None):
  275. # --focus-phone applies to --json intake too (it was silently ignored before):
  276. # same normalized-digits dedupe as the CLI path, same preferences marker.
  277. if registry.phone_digits(args.focus_phone) not in {
  278. registry.phone_digits(p) for p in identity.get("phones") or []}:
  279. identity.setdefault("phones", []).append(args.focus_phone)
  280. prefs["focus_phone"] = args.focus_phone
  281. else:
  282. # Phone-led intake: a spam-call run starts from the number. At least ONE identifier
  283. # is required (name, phone, or email). The full name is not required to SCAN
  284. # (phone/email/address vectors run; name-only brokers group as `unsearchable`), but
  285. # every opt-out form and legal request needs it -- warned below, not refused.
  286. if not (args.full_name or args.phone or args.email or getattr(args, "focus_phone", None)):
  287. sys.exit("error: intake needs at least one identifier: --full-name, --phone, or --email")
  288. identity = {"full_name": args.full_name, "emails": args.email or [], "phones": args.phone or []}
  289. if args.alias:
  290. identity["also_known_as"] = args.alias
  291. if args.dob:
  292. identity["date_of_birth"] = args.dob
  293. addr = {k: v for k, v in {"line1": args.street, "city": args.city,
  294. "state": args.state, "postal": args.postal}.items() if v}
  295. if addr:
  296. identity["current_address"] = addr
  297. priors = []
  298. for loc in args.prior_location or []:
  299. parts = [p.strip() for p in loc.split(",") if p.strip()]
  300. if not parts:
  301. continue
  302. entry = {"city": parts[0]}
  303. if len(parts) > 1:
  304. entry["state"] = parts[1]
  305. if len(parts) > 2:
  306. entry["postal"] = parts[2]
  307. priors.append(entry)
  308. if priors:
  309. identity["prior_addresses"] = priors
  310. cfg = config_mod.load_config()
  311. consent = {"authorized": bool(args.consent), "method": args.consent_method, "recorded_at": dossier_mod.now()}
  312. residency = args.residency or "US"
  313. prefs = {
  314. "email_mode": args.email_mode or cfg["email_mode"],
  315. "rescan_interval_days": cfg["default_rescan_interval_days"],
  316. }
  317. if args.contact_email:
  318. prefs["contact_email_for_optouts"] = args.contact_email
  319. if getattr(args, "focus_phone", None):
  320. # Phone-led (spam-call) run: the number being scrubbed. Add it to the dossier
  321. # phones so search vectors cover it even when it was not listed separately.
  322. # Compare on normalized digits: "--phone 555-123-4567 --focus-phone 5551234567"
  323. # is ONE number, and a duplicate would double the phone vectors and the DNC list.
  324. if registry.phone_digits(args.focus_phone) not in {
  325. registry.phone_digits(p) for p in identity["phones"]}:
  326. identity["phones"].append(args.focus_phone)
  327. prefs["focus_phone"] = args.focus_phone
  328. d = dossier_mod.create(identity, consent, residency, prefs)
  329. warnings: list[str] = []
  330. if not (d["identity"].get("full_name") or "").strip():
  331. warnings.append("no full_name on file: scans run (phone/email/address vectors) but most "
  332. "opt-out forms and every legal request need the subject's legal name -- "
  333. "collect it before Phase 2")
  334. if not dossier_mod.contact_email(d):
  335. warnings.append("no email on file: opt-out correspondence needs a contact email -- "
  336. "collect one before Phase 2")
  337. _out({"subject_id": d["subject_id"], "authorized": dossier_mod.is_authorized(d),
  338. "residency": residency, "email_mode": (prefs or {}).get("email_mode"),
  339. "focus_phone": (prefs or {}).get("focus_phone"),
  340. "names": dossier_mod.all_names(d),
  341. "emails": len(d["identity"].get("emails") or []),
  342. "phones": len(d["identity"].get("phones") or []),
  343. "addresses": len(dossier_mod.all_addresses(d)),
  344. "warnings": warnings})
  345. def cmd_brokers(args) -> None:
  346. bl = brokers_mod.by_priority(*(args.priority or [])) if args.priority else brokers_mod.load_all()
  347. _out([
  348. {"id": b.get("id"), "name": b.get("name"), "priority": b.get("priority"),
  349. "method": (b.get("optout") or {}).get("method"), "owns": b.get("owns") or [],
  350. "source": b.get("source"), "confidence": b.get("confidence", "curated")}
  351. for b in bl
  352. ])
  353. def cmd_refresh_brokers(args) -> None:
  354. res = badbool.refresh(paths_mod.brokers_cache_path())
  355. curated_ids = {b["id"] for b in brokers_mod._load_curated()}
  356. new = [b["id"] for b in brokers_mod.load_live_cache() if b["id"] not in curated_ids]
  357. out = {**res, "curated": len(curated_ids), "new_from_live": len(new),
  358. "people_search_total": len(brokers_mod.load_all()),
  359. "note": "Live records have confidence=auto; verify their opt-out URL before acting."}
  360. if not getattr(args, "no_registry", False):
  361. try:
  362. reg = registry.refresh_all(paths_mod.registry_cache_path())
  363. out["registry"] = {"total": reg["total"], "sources": reg["sources"],
  364. "portals": reg["portals"],
  365. "note": "Coverage lane worked via the CA DROP one-shot + CCPA email, "
  366. "not the people-search scan. VT/OR/TX are search portals (no "
  367. "bulk export); CA is the superset. See `drop` and `registry`."}
  368. except Exception as exc:
  369. out["registry_error"] = str(exc)
  370. _out(out)
  371. def cmd_registry(args) -> None:
  372. recs = brokers_mod.load_registry_cache()
  373. if not recs:
  374. _out({"registered_brokers": 0,
  375. "note": "registry empty - run `refresh-brokers` (pulls the CA Data Broker Registry)"})
  376. return
  377. fcra = sum(1 for r in recs if (r.get("optout") or {}).get("fcra"))
  378. out = {"registered_brokers": len(recs), "fcra_regulated": fcra,
  379. "source": "CA Data Broker Registry (CPPA, 2025)", "drop_url": registry.DROP_URL,
  380. "other_state_portals": registry.portals()}
  381. if args.search:
  382. q = args.search.lower()
  383. hits = [r for r in recs if q in (r.get("name") or "").lower()
  384. or q in (r.get("id") or "") or q in ((r.get("optout") or {}).get("email") or "").lower()]
  385. out["matches"] = [{"id": r["id"], "name": r["name"],
  386. "email": (r.get("optout") or {}).get("email"),
  387. "url": (r.get("optout") or {}).get("url"),
  388. "fcra": (r.get("optout") or {}).get("fcra")} for r in hits[:args.limit]]
  389. out["match_count"] = len(hits)
  390. _out(out)
  391. def _mark_one_shot(d: dict, subject: str, key: str, label: str) -> dict:
  392. """Record a registry one-shot marker (drop_filed_at / dnc_filed_at / dnc_declined_at)."""
  393. prefs = d.setdefault("preferences", {})
  394. prefs[key] = dossier_mod.now()
  395. dossier_mod.save(d)
  396. return {"subject": subject, key: prefs[key],
  397. "note": f"recorded; `next` will stop surfacing the {label} one-shot"}
  398. def cmd_drop(args) -> None:
  399. """The one-shot legal lever: CA DROP deletes from ALL registered brokers at once."""
  400. d = _require_subject(args.subject)
  401. dossier_mod.require_authorized(d)
  402. reg = brokers_mod.load_registry_cache()
  403. res = (d.get("residency_jurisdiction") or "US").upper()
  404. eligible = res.startswith("US-CA")
  405. if args.filed:
  406. _out(_mark_one_shot(d, args.subject, "drop_filed_at", "DROP"))
  407. return
  408. _out({
  409. "subject": args.subject,
  410. "eligible": eligible,
  411. "residency": res,
  412. "drop_url": registry.DROP_URL,
  413. "covers_registered_brokers": len(reg),
  414. "steps": ([
  415. "Go to privacy.ca.gov/drop and create/verify a DROP account (CA resident).",
  416. "Submit ONE deletion request; it applies to EVERY registered data broker "
  417. f"({len(reg)} in the current registry). Brokers must process starting 2026-08-01.",
  418. "After filing, run `drop <subject> --filed` so the loop stops re-surfacing it.",
  419. ] if eligible else [
  420. "DROP is a California mechanism; this subject's residency is not US-CA.",
  421. "Parity path for non-CA: work the people-search sites via `next`, and send targeted "
  422. "CCPA/GDPR deletion emails to registry brokers that hold this person's data "
  423. "(`registry --search`, then `send-email`).",
  424. ]),
  425. "note": "DROP is the highest-leverage removal: one request covers the whole registry.",
  426. })
  427. def cmd_dnc(args) -> None:
  428. """The spam-call one-shot: the FTC National Do Not Call Registry (US personal numbers).
  429. Complementary to broker removal -- the registry is what lawful telemarketers must honor
  430. (within 31 days); the people-search listings are where lead lists come from. Mirrors
  431. `drop`: surfaced by `next` once per subject until `--filed` records it.
  432. """
  433. d = _require_subject(args.subject)
  434. dossier_mod.require_authorized(d)
  435. res = (d.get("residency_jurisdiction") or "US").upper()
  436. numbers = registry.dnc_eligible(d)
  437. eligible = res.startswith("US") and bool(numbers)
  438. if args.filed:
  439. _out(_mark_one_shot(d, args.subject, "dnc_filed_at", "DNC"))
  440. return
  441. if getattr(args, "declined", False):
  442. _out(_mark_one_shot(d, args.subject, "dnc_declined_at", "DNC (declined)"))
  443. return
  444. _out({
  445. "subject": args.subject,
  446. "eligible": eligible,
  447. "residency": res,
  448. "numbers": numbers,
  449. "dnc_url": registry.DNC_URL,
  450. "steps": ([
  451. f"Open {registry.DNC_URL} and enter the subject's personal number(s) -- up to "
  452. f"three per pass ({len(numbers)} eligible here) -- with the subject's contact email.",
  453. "The FTC sends a confirmation email PER NUMBER; open each link within 72 hours "
  454. "or that number is not registered.",
  455. "Sales calls stop within 31 days; registration never expires (personal numbers "
  456. "only -- business/fax lines are not covered).",
  457. f"After submitting, run `dnc {args.subject} --filed` so the loop stops "
  458. f"re-surfacing it (or `dnc {args.subject} --declined` if the subject opts out).",
  459. ] if eligible else [
  460. "The National Do Not Call Registry covers US (NANP) personal numbers only; this "
  461. "subject has no US residency or no eligible US number on file.",
  462. "The broker-removal lane (`next`) is what cuts the lead lists scammers buy, in "
  463. "any jurisdiction.",
  464. ]),
  465. "note": "DNC stops lawful telemarketers, not scammers; broker removal is the other "
  466. "half. It is not a call blocker -- carriers' call-blocking/labeling handles "
  467. "the rest.",
  468. })
  469. def cmd_plan(args) -> None:
  470. d = _require_subject(args.subject)
  471. dossier_mod.require_authorized(d)
  472. cfg = config_mod.load_config()
  473. bl = brokers_mod.by_priority(*(args.priority or [])) if args.priority else brokers_mod.load_all()
  474. bcc = config_mod.browser_clears_captcha(cfg)
  475. if getattr(args, "batch", False):
  476. _out(tiers.batch_plan(d, bl, cfg, ledger_mod.load(args.subject), bcc))
  477. else:
  478. _out(tiers.plan(d, bl, cfg, bcc))
  479. def cmd_fanout(args) -> None:
  480. d = _require_subject(args.subject)
  481. dossier_mod.require_authorized(d)
  482. bl = brokers_mod.by_priority(*(args.priority or [])) if args.priority else brokers_mod.load_all()
  483. runnable, unsearchable = tiers.runnable_for(d, bl) # zero-vector brokers can't be scanned at all
  484. grouping = tiers.fanout(runnable, batch_size=args.size)
  485. mode = "scan AND opt-out (operator authorized submissions)" if args.optout \
  486. else "READ-ONLY scan (submit nothing; reconnaissance only)"
  487. batches = []
  488. for i, ids in enumerate(grouping["batches"], 1):
  489. brief = (
  490. f"You are scan worker {i} of {len(grouping['batches'])} for the `unbroker` skill. First "
  491. f"load the `unbroker` skill and read its references/methods.md. Use the `web` toolset "
  492. f"(web_search `site:` + web_extract), NOT `browser` (browser navigation is heavy and times "
  493. f"out). Subject id: {args.subject}. Handle ONLY these brokers: {', '.join(ids)}. "
  494. f"For EACH broker: read references/brokers/<id>.json; run EVERY search vector from "
  495. f"`pdd.py plan {args.subject}` (filtered to your brokers); build URLs from search.url_patterns "
  496. f"and heed url_format_quirks; a 404 is INCONCLUSIVE (rebuild/try the on-site search box), not "
  497. f"not_found. ECONOMY: at most ~3 web calls per broker; the moment a page shows antibot "
  498. f"(Cloudflare 'just a moment'/DataDome) or hangs, record `blocked` and move on -- do NOT "
  499. f"retry-loop. Confirm the SUBJECT vs namesakes/relatives by ADDRESS/DOB before recording "
  500. f"`found` (ignore SEO-templated page titles/intro that just echo the query -- require a real "
  501. f"result card; a public property/address record with no displayed personal NAME is "
  502. f"not_found, not found). Record each outcome via `pdd.py record {args.subject} <broker> "
  503. f"<found|not_found|indirect_exposure|blocked> --found <bool> --evidence '{{\"listing_urls\":[...]}}'`. "
  504. f"Mode: {mode}. Broker JSON files are READ-ONLY for you -- do NOT edit them; if you discover "
  505. f"a URL/quirk, put it in your report for the parent to fold in. Return a concise structured "
  506. f"per-broker report."
  507. )
  508. batches.append({"batch": i, "brokers": ids, "brief": brief})
  509. _out({
  510. "subject": args.subject,
  511. "broker_count": grouping["broker_count"],
  512. "skipped_unsearchable": len(unsearchable),
  513. "batch_size": grouping["batch_size"],
  514. "should_fanout": grouping["should_fanout"],
  515. "batch_count": len(batches),
  516. "batches": batches,
  517. "instruction": (
  518. "If should_fanout is true you MUST spawn ONE delegate_task subagent per batch IN PARALLEL, "
  519. "passing each batch's `brief`; do not scan all brokers yourself sequentially. Wait for every "
  520. "report, consolidate, then proceed to opt-outs. If false, just scan the brokers inline."
  521. ),
  522. })
  523. def cmd_record(args) -> None:
  524. d = _require_subject(args.subject)
  525. dossier_mod.require_authorized(d)
  526. broker = brokers_mod.get(args.broker)
  527. # Auto-stamp follow-up scheduling (next_recheck_at / removal_confirmed_at) so the
  528. # autonomous loop knows when to come back without anyone remembering to set it.
  529. fields = ledger_mod.followup_fields(args.state, broker, d)
  530. if args.found is not None:
  531. fields["found"] = args.found
  532. if args.evidence:
  533. fields["evidence"] = json.loads(args.evidence)
  534. if args.reason:
  535. fields["human_task_reason"] = args.reason
  536. case = ledger_mod.transition(args.subject, args.broker, args.state,
  537. broker_defunct=bool((broker or {}).get("defunct")), **fields)
  538. if args.disclosed:
  539. ledger_mod.log_disclosure(args.subject, args.broker, args.disclosed, args.channel or "unknown")
  540. _out({"broker": args.broker, "state": case["state"],
  541. "next_recheck_at": case.get("next_recheck_at")})
  542. def _email_request(d: dict, b: dict, kind: str, listings, identifiers) -> tuple[dict, list[str]]:
  543. """Least-disclosure (fields, disclosed_names) for an opt-out/legal email of KIND.
  544. A removal letter must self-identify. Name + a contact email are already known to the
  545. broker (the name is displayed on the very listing being removed), so not extra exposure.
  546. """
  547. fields = dossier_mod.select_disclosure(d, (b.get("optout") or {}).get("inputs", []))
  548. ident = d.get("identity", {})
  549. if ident.get("full_name"):
  550. fields.setdefault("full_name", ident["full_name"])
  551. else:
  552. # Never render the literal None. Generic drafts are operator-edited, so an explicit
  553. # placeholder is the honest stand-in; the legal kinds are refused upstream when the
  554. # subject is nameless (see _require_email_identity).
  555. fields.setdefault("full_name", "[your full name]")
  556. fields.setdefault("contact_email", dossier_mod.contact_email(d) or "")
  557. if listings:
  558. fields["listing_urls"] = listings
  559. if kind == "ccpa_indirect":
  560. # Indirect exposure: name ONLY the subject's own identifiers to scrub from a third party's
  561. # record. Default to the contact email + the subject's name-as-relative if none specified.
  562. # The indirect template renders ONLY these placeholders; do not over-report disclosure with
  563. # unrelated dossier fields (phone/street/postal) that select_disclosure happened to populate.
  564. ids = list(identifiers or [])
  565. if not ids:
  566. ids = [contact for contact in [dossier_mod.contact_email(d)] if contact]
  567. # Only when a name exists -- a nameless subject must never emit the literal
  568. # None into a legal email.
  569. if ident.get("full_name"):
  570. ids.append(f'the name "{ident["full_name"]}" where it appears as a relative/associated person')
  571. fields = {
  572. "full_name": fields.get("full_name"),
  573. "contact_email": fields.get("contact_email"),
  574. "listing_urls": fields.get("listing_urls"),
  575. "my_identifiers": ids,
  576. }
  577. return fields, ["contact_email", "full_name", "my_identifiers"]
  578. return fields, sorted(fields.keys())
  579. def _require_email_identity(d: dict, kind: str, sending: bool) -> None:
  580. """Enforce the intake warning at the send boundary: a removal request must self-identify.
  581. Intake only WARNS when the name/contact email is missing (scans run fine without them);
  582. this is where it turns fatal. `generic` drafts are operator-edited ([your name]), so
  583. rendering one without a name is allowed -- but SENDING any request without a name is
  584. not, and the contact email (the confirm-to address) is required in every mode.
  585. """
  586. missing = []
  587. if (sending or kind != "generic") and not ((d.get("identity") or {}).get("full_name") or "").strip():
  588. missing.append("full name")
  589. if not dossier_mod.contact_email(d):
  590. missing.append("contact email")
  591. if missing:
  592. sys.exit("error: a removal request must self-identify, and the subject's "
  593. + " and ".join(missing) + " is missing. Collect it first "
  594. "(intake --full-name / --contact-email, or a dossier edit), then re-run; "
  595. "scans do not need it, sending does.")
  596. def cmd_render_email(args) -> None:
  597. d = _require_subject(args.subject)
  598. dossier_mod.require_authorized(d)
  599. b = brokers_mod.get(args.broker)
  600. if not b:
  601. sys.exit(f"error: unknown broker {args.broker!r}")
  602. kind = getattr(args, "kind", "generic") or "generic"
  603. _require_email_identity(d, kind, sending=False)
  604. fields, disclosed = _email_request(d, b, kind, args.listing, getattr(args, "identifier", None))
  605. if kind == "generic":
  606. draft = email_modes.render_draft(b, fields)
  607. else:
  608. draft = email_modes.render_request_draft(b, fields, kind=kind)
  609. ledger_mod.log_disclosure(args.subject, args.broker, list(disclosed), f"email_draft:{kind}")
  610. _out({"draft": str(draft), "kind": kind, "disclosed_fields": disclosed})
  611. def cmd_send_email(args) -> None:
  612. """Mode B: render AND deliver the opt-out/legal request - no human in the loop.
  613. Sends ONLY to an address the broker record itself declares (emailer enforces it),
  614. then records the ledger transition + disclosure and auto-stamps the recheck date.
  615. """
  616. d = _require_subject(args.subject)
  617. dossier_mod.require_authorized(d)
  618. b = brokers_mod.get(args.broker)
  619. if not b:
  620. sys.exit(f"error: unknown broker {args.broker!r}")
  621. cfg = config_mod.load_config()
  622. mode = cfg.get("email_mode")
  623. if mode not in ("programmatic", "alias", "browser"):
  624. sys.exit("error: email_mode is draft_only; run `setup --email-mode browser` (no password; "
  625. "sends via your logged-in webmail) or `--email-mode programmatic`, or use "
  626. "`render-email` and send it yourself")
  627. if not args.listing:
  628. sys.exit("error: --listing <confirmed-url> is required (verify-before-disclose: never "
  629. "email a broker about an unconfirmed listing)")
  630. # Idempotency: don't re-send if this case is already submitted/beyond (prevents duplicate
  631. # requests when an action is retried). --force overrides.
  632. _POST_SUBMIT = {"submitted", "verification_pending", "awaiting_processing", "confirmed_removed"}
  633. current = ledger_mod.get_case(args.subject, args.broker).get("state")
  634. if current in _POST_SUBMIT and not getattr(args, "force", False):
  635. _out({"skipped": True, "broker": args.broker, "state": current,
  636. "note": "already submitted; not re-sending (idempotent). Use --force to re-send."})
  637. return
  638. kind = getattr(args, "kind", "generic") or "generic"
  639. _require_email_identity(d, kind, sending=True)
  640. fields, disclosed = _email_request(d, b, kind, args.listing, getattr(args, "identifier", None))
  641. body = legal.render_optout_email(b, fields) if kind == "generic" else legal.render_request(kind, b, fields)
  642. if mode == "browser":
  643. # No network / no credentials: hand the agent a recipient-locked payload to send in the
  644. # operator's webmail via browser_exec. State still records deterministically here.
  645. payload = emailer.browser_send_payload(b, body, to=args.to)
  646. ledger_mod.log_disclosure(args.subject, args.broker, list(disclosed), f"email_browser:{kind}")
  647. case = ledger_mod.transition(args.subject, args.broker, "submitted",
  648. **ledger_mod.followup_fields("submitted", b, d))
  649. _out({"send_via": "browser", "compose": payload, "kind": kind, "disclosed_fields": disclosed,
  650. "state": case["state"], "next_recheck_at": case.get("next_recheck_at"),
  651. "instruction": "In the operator's logged-in webmail, compose a NEW email to compose.to "
  652. "with compose.subject/body EXACTLY (disclose nothing beyond it) and send "
  653. "it via browser_exec. Then use `verify-link` on any confirmation reply.",
  654. "note": "recipient is locked to the broker's declared address"})
  655. return
  656. result = emailer.send(b, body, to=args.to,
  657. min_interval=float(cfg.get("email_min_interval_seconds", 0) or 0))
  658. ledger_mod.log_disclosure(args.subject, args.broker, list(disclosed), f"email_sent:{kind}")
  659. case = ledger_mod.transition(args.subject, args.broker, "submitted",
  660. **ledger_mod.followup_fields("submitted", b, d))
  661. _out({"sent": result, "send_via": "smtp", "kind": kind, "disclosed_fields": disclosed,
  662. "state": case["state"], "next_recheck_at": case.get("next_recheck_at"),
  663. "note": "if this broker verifies by email, `poll-verification` will pick up the link"})
  664. def cmd_verify_link(args) -> None:
  665. """Extract a broker's verification link from email text the agent read in webmail (browser mode).
  666. IMAP-free counterpart to `poll-verification`: the agent opens the broker's confirmation email
  667. in the operator's webmail, pastes the body here, and gets the anti-phishing-scored link back.
  668. """
  669. _require_subject(args.subject)
  670. b = brokers_mod.get(args.broker)
  671. if not b:
  672. sys.exit(f"error: unknown broker {args.broker!r}")
  673. text = args.text
  674. if args.file:
  675. text = Path(args.file).read_text(encoding="utf-8", errors="replace")
  676. if not text:
  677. sys.exit("error: provide --text '<email body>' (or --file) from the broker's confirmation email")
  678. link = email_modes.extract_verification_link(text, b)
  679. _out({"broker": args.broker, "verification_link": link,
  680. "next": ("open the link with browser_exec IN THE SAME browser (sessions are browser-bound), "
  681. f"complete the flow, then `record {args.subject} {args.broker} awaiting_processing`"
  682. if link else
  683. "no broker/opt-out-scoped link found in that text; confirm you opened the right email")})
  684. def cmd_poll_verification(args) -> None:
  685. """Poll the inbox for brokers' verification links (Mode B) - replaces the human click-chase.
  686. For each in-flight case (submitted / verification_pending with email_verification),
  687. extract the broker's link (anti-phishing scored). A found link auto-advances
  688. submitted -> verification_pending (the email HAS arrived); the agent must then OPEN
  689. the link in its own browser (sessions are browser-bound) and record the next state.
  690. """
  691. d = _require_subject(args.subject)
  692. dossier_mod.require_authorized(d)
  693. led = ledger_mod.load(args.subject)
  694. targets = []
  695. for bid, case in sorted(led.items()):
  696. if args.broker and bid != args.broker:
  697. continue
  698. if case.get("state") not in ("submitted", "verification_pending"):
  699. continue
  700. b = brokers_mod.get(bid)
  701. if b and (((b.get("optout") or {}).get("requires")) or {}).get("email_verification"):
  702. targets.append((bid, case, b))
  703. if not targets:
  704. _out({"subject": args.subject, "results": [],
  705. "note": "no in-flight cases awaiting email verification"})
  706. return
  707. results = []
  708. for bid, case, b in targets:
  709. hit = emailer.find_verification_link(b, since_days=args.since_days)
  710. if hit:
  711. if case.get("state") == "submitted":
  712. ledger_mod.transition(args.subject, bid, "verification_pending",
  713. **ledger_mod.followup_fields("verification_pending", b, d))
  714. results.append({"broker": bid, "verification_link": hit["link"],
  715. "email_from": hit.get("from"), "email_subject": hit.get("subject"),
  716. "next": f"open the link with browser_exec IN THE AGENT'S OWN BROWSER, complete "
  717. f"the flow, then `record {args.subject} {bid} awaiting_processing` "
  718. f"(or confirmed_removed only after a verifying re-scan)"})
  719. else:
  720. results.append({"broker": bid, "verification_link": None,
  721. "next": "no matching email yet; poll again later (next_recheck_at is set)"})
  722. _out({"subject": args.subject, "results": results})
  723. def cmd_next(args) -> None:
  724. d = _require_subject(args.subject)
  725. dossier_mod.require_authorized(d)
  726. cfg = config_mod.load_config()
  727. bl = brokers_mod.by_priority(*(args.priority or [])) if args.priority else brokers_mod.load_all()
  728. _out(autopilot.next_actions(d, bl, cfg, ledger_mod.load(args.subject)))
  729. def cmd_tasks(args) -> None:
  730. _require_subject(args.subject)
  731. print(report_mod.human_tasks_markdown(args.subject))
  732. def cmd_due(args) -> None:
  733. _require_subject(args.subject)
  734. cases = ledger_mod.due(args.subject)
  735. _out({"subject": args.subject, "due_count": len(cases),
  736. "cases": [{"broker_id": c.get("broker_id"), "state": c.get("state"),
  737. "next_recheck_at": c.get("next_recheck_at")} for c in cases],
  738. "note": "run `next` for the concrete follow-up action per case"})
  739. def cmd_show(args) -> None:
  740. """Read a case's recorded state + evidence (so the parent can re-verify a subagent's `found`
  741. without re-deriving listing URLs)."""
  742. _require_subject(args.subject)
  743. case = ledger_mod.get_case(args.subject, args.broker)
  744. _out({"broker": args.broker, "state": case.get("state"), "found": case.get("found"),
  745. "evidence": case.get("evidence") or {},
  746. "disclosure_log": case.get("disclosure_log") or [],
  747. "next_recheck_at": case.get("next_recheck_at"),
  748. "human_task_reason": case.get("human_task_reason"),
  749. "history": case.get("history") or []})
  750. def cmd_status(args) -> None:
  751. _require_subject(args.subject)
  752. print(report_mod.render_markdown(args.subject))
  753. def cmd_report(args) -> None:
  754. _require_subject(args.subject)
  755. if args.sheets:
  756. _out(report_mod.sheets_rows(args.subject))
  757. else:
  758. print(report_mod.render_markdown(args.subject))
  759. def build_parser() -> argparse.ArgumentParser:
  760. p = argparse.ArgumentParser(prog="pdd", description="unbroker helper CLI")
  761. sub = p.add_subparsers(dest="cmd", required=True)
  762. s = sub.add_parser("setup", help="write install config (easiest-first defaults; --auto = most autonomous)")
  763. s.add_argument("--auto", action="store_true",
  764. help="detect capabilities and pick the most autonomous valid config (no questions)")
  765. s.add_argument("--autonomy", dest="autonomy", choices=sorted(config_mod.VALID["autonomy"]))
  766. s.add_argument("--email-mode", dest="email_mode", choices=sorted(config_mod.VALID["email_mode"]))
  767. s.add_argument("--browser-backend", dest="browser_backend", choices=sorted(config_mod.VALID["browser_backend"]))
  768. s.add_argument("--tracker-backend", dest="tracker_backend", choices=sorted(config_mod.VALID["tracker_backend"]))
  769. s.add_argument("--encryption", dest="encryption", choices=sorted(config_mod.VALID["encryption"]))
  770. s.set_defaults(func=cmd_setup)
  771. s = sub.add_parser("doctor", help="readiness check: config, brokers, available upgrades")
  772. s.set_defaults(func=cmd_doctor)
  773. s = sub.add_parser("cdp",
  774. help="launch/detect the operator's Chrome over CDP (Phase-2 browser + webmail)")
  775. s.add_argument("--port", type=int, default=cdp.DEFAULT_PORT, help="remote debugging port (default 9222)")
  776. s.add_argument("--profile",
  777. help="user-data-dir (default: $HERMES_HOME/chrome-debug, a dedicated debug profile)")
  778. s.add_argument("--browser", help="path to (or PATH name of) a Chrome/Chromium/Brave/Edge binary")
  779. s.add_argument("--check", action="store_true",
  780. help="only report whether a debug browser is live; do not launch")
  781. s.add_argument("--print", dest="print_only", action="store_true",
  782. help="print the launch command instead of launching it (run it yourself)")
  783. s.set_defaults(func=cmd_cdp)
  784. s = sub.add_parser("intake", help="create a subject dossier (records consent)")
  785. s.add_argument("--json", help="path to a dossier JSON file (overrides flags)")
  786. s.add_argument("--full-name")
  787. s.add_argument("--alias", action="append", metavar="NAME",
  788. help="other name the subject is listed under (maiden/married/nickname); repeatable")
  789. s.add_argument("--email", action="append", metavar="EMAIL", help="repeatable")
  790. s.add_argument("--phone", action="append", metavar="PHONE", help="repeatable")
  791. s.add_argument("--street", help="current street line1 (enables reverse-address search)")
  792. s.add_argument("--city")
  793. s.add_argument("--state")
  794. s.add_argument("--postal")
  795. s.add_argument("--prior-location", dest="prior_location", action="append", metavar="City,ST",
  796. help="a past city/state (or City,ST,ZIP); repeatable")
  797. s.add_argument("--dob", help="date of birth YYYY-MM-DD (only used if a broker requires it)")
  798. s.add_argument("--contact-email", dest="contact_email",
  799. help="which email to use for opt-out correspondence (default: first)")
  800. s.add_argument("--focus-phone", dest="focus_phone", metavar="PHONE",
  801. help="phone-led (spam-call) run: the number being scrubbed -- added to the "
  802. "search vectors and used as the `phone` field opt-out forms disclose")
  803. s.add_argument("--residency", help="e.g. US, US-CA")
  804. s.add_argument("--consent", action="store_true", help="subject authorizes removal on their behalf")
  805. s.add_argument("--consent-method", default="self", choices=["self", "written_authorization", "poa"])
  806. s.add_argument("--email-mode", dest="email_mode", choices=sorted(config_mod.VALID["email_mode"]))
  807. s.set_defaults(func=cmd_intake)
  808. s = sub.add_parser("brokers", help="list the broker database (curated + live)")
  809. s.add_argument("--priority", action="append", choices=["crucial", "high", "standard", "long_tail"])
  810. s.set_defaults(func=cmd_brokers)
  811. s = sub.add_parser("refresh-brokers",
  812. help="pull the latest BADBOOL people-search list + the CA data broker registry")
  813. s.add_argument("--no-registry", dest="no_registry", action="store_true",
  814. help="skip the CA registry pull (BADBOOL people-search only)")
  815. s.set_defaults(func=cmd_refresh_brokers)
  816. s = sub.add_parser("registry",
  817. help="CA Data Broker Registry coverage (hundreds of brokers; DROP/email lane)")
  818. s.add_argument("--search", help="find registered brokers by name / id / email substring")
  819. s.add_argument("--limit", type=int, default=25, help="max matches to print (default 25)")
  820. s.set_defaults(func=cmd_registry)
  821. s = sub.add_parser("drop",
  822. help="CA DROP one-shot: delete from ALL registered brokers in one request")
  823. s.add_argument("subject")
  824. s.add_argument("--filed", action="store_true", help="mark DROP as filed (stops `next` surfacing it)")
  825. s.set_defaults(func=cmd_drop)
  826. s = sub.add_parser("dnc",
  827. help="spam-call one-shot: register the subject's US numbers on the FTC "
  828. "National Do Not Call Registry (lawful telemarketers stop within 31 days)")
  829. s.add_argument("subject")
  830. s.add_argument("--filed", action="store_true",
  831. help="mark the DNC registration as filed (stops `next` surfacing it)")
  832. s.add_argument("--declined", action="store_true",
  833. help="record that the subject declines DNC registration (stops `next` "
  834. "surfacing it WITHOUT recording a filing that never happened)")
  835. s.set_defaults(func=cmd_dnc)
  836. s = sub.add_parser("plan", help="compute per-broker tier + next action for a subject")
  837. s.add_argument("subject")
  838. s.add_argument("--priority", action="append", choices=["crucial", "high", "standard", "long_tail"])
  839. s.add_argument("--batch", action="store_true",
  840. help="phase-oriented batch view: overlays ledger state, groups by next action "
  841. "(unscanned/found/indirect/blocked/in_progress/done), collapses ownership clusters")
  842. s.set_defaults(func=cmd_plan)
  843. s = sub.add_parser("fanout", help="batch brokers into parallel delegate_task subagents (large runs)")
  844. s.add_argument("subject")
  845. s.add_argument("--priority", action="append", choices=["crucial", "high", "standard", "long_tail"])
  846. s.add_argument("--size", type=int, default=5, help="brokers per subagent batch (default 5; 8+ times out)")
  847. s.add_argument("--optout", action="store_true",
  848. help="brief authorizes opt-out submission (default: read-only scan)")
  849. s.set_defaults(func=cmd_fanout)
  850. s = sub.add_parser("record", help="record a ledger state transition after an agent action")
  851. s.add_argument("subject")
  852. s.add_argument("broker")
  853. s.add_argument("state", choices=ledger_mod.STATES)
  854. s.add_argument("--found", type=lambda v: v.strip().lower() in ("1", "true", "yes", "y"))
  855. s.add_argument("--evidence", help="JSON object stored as case.evidence")
  856. s.add_argument("--disclosed", action="append", metavar="FIELD", help="field name disclosed")
  857. s.add_argument("--channel", help="disclosure channel, e.g. web_form / email")
  858. s.add_argument("--reason", help="for human_task_queued: why a human is needed (shown in `tasks`)")
  859. s.set_defaults(func=cmd_record)
  860. s = sub.add_parser("next", help="autonomous action queue: exactly what to do right now")
  861. s.add_argument("subject")
  862. s.add_argument("--priority", action="append", choices=["crucial", "high", "standard", "long_tail"])
  863. s.set_defaults(func=cmd_next)
  864. s = sub.add_parser("send-email", help="Mode B: render AND send the opt-out/legal request (records it)")
  865. s.add_argument("subject")
  866. s.add_argument("broker")
  867. s.add_argument("--listing", action="append", metavar="URL", required=False,
  868. help="confirmed listing URL (required: verify-before-disclose)")
  869. s.add_argument("--kind", choices=["generic", "ccpa", "ccpa_agent", "ccpa_indirect", "gdpr"],
  870. default="generic")
  871. s.add_argument("--identifier", action="append", metavar="ID",
  872. help="(ccpa_indirect only) a specific own-identifier to remove; repeatable")
  873. s.add_argument("--to", help="override recipient (must be an address the broker record declares)")
  874. s.add_argument("--force", action="store_true", help="re-send even if already submitted (default: idempotent skip)")
  875. s.set_defaults(func=cmd_send_email)
  876. s = sub.add_parser("poll-verification",
  877. help="Mode B (IMAP): poll the inbox for brokers' verification links (anti-phishing scored)")
  878. s.add_argument("subject")
  879. s.add_argument("--broker", help="only this broker (default: every in-flight verification case)")
  880. s.add_argument("--since-days", dest="since_days", type=int, default=3)
  881. s.set_defaults(func=cmd_poll_verification)
  882. s = sub.add_parser("verify-link",
  883. help="browser mode: extract a broker's verification link from pasted webmail text")
  884. s.add_argument("subject")
  885. s.add_argument("broker")
  886. s.add_argument("--text", help="the confirmation email body (read from the operator's webmail)")
  887. s.add_argument("--file", help="path to a file with the email body (alternative to --text)")
  888. s.set_defaults(func=cmd_verify_link)
  889. s = sub.add_parser("tasks", help="ONE consolidated human-task digest (present at end of run)")
  890. s.add_argument("subject")
  891. s.set_defaults(func=cmd_tasks)
  892. s = sub.add_parser("show", help="read a case's state + evidence (for parent re-verification)")
  893. s.add_argument("subject")
  894. s.add_argument("broker")
  895. s.set_defaults(func=cmd_show)
  896. s = sub.add_parser("due", help="cases whose recheck window has arrived (cron re-scan queue)")
  897. s.add_argument("subject")
  898. s.set_defaults(func=cmd_due)
  899. s = sub.add_parser("render-email", help="render a Mode-A opt-out / legal-request draft (least-disclosure)")
  900. s.add_argument("subject")
  901. s.add_argument("broker")
  902. s.add_argument("--listing", action="append", metavar="URL", help="confirmed listing URL")
  903. s.add_argument("--kind", choices=["generic", "ccpa", "ccpa_agent", "ccpa_indirect", "gdpr"],
  904. default="generic",
  905. help="request type. 'ccpa_indirect' = delete MY identifiers from a third party's "
  906. "record (indirect exposure); default 'generic' opt-out.")
  907. s.add_argument("--identifier", action="append", metavar="ID",
  908. help="(ccpa_indirect only) a specific own-identifier to request removal of "
  909. "(e.g. an email or phone). Repeatable. Defaults to the contact email + "
  910. "name-as-relative if omitted.")
  911. s.set_defaults(func=cmd_render_email)
  912. s = sub.add_parser("status", help="print a Markdown status report")
  913. s.add_argument("subject")
  914. s.set_defaults(func=cmd_status)
  915. s = sub.add_parser("report", help="status report (default) or --sheets rows")
  916. s.add_argument("subject")
  917. s.add_argument("--sheets", action="store_true", help="emit Google Sheets rows as JSON")
  918. s.set_defaults(func=cmd_report)
  919. return p
  920. def main(argv=None) -> None:
  921. args = build_parser().parse_args(argv)
  922. try:
  923. args.func(args)
  924. except (PermissionError, ValueError, RuntimeError, FileNotFoundError) as exc:
  925. sys.exit(f"error: {exc}")
  926. if __name__ == "__main__":
  927. main()