oneshot-gtm-server 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/bin.mjs +2329 -612
  2. package/dist/bin.mjs.map +1 -1
  3. package/dist/web/assets/{Badge-B2tW85qr.js → Badge-Cs_ppKNz.js} +1 -1
  4. package/dist/web/assets/{Button-C-XcKplu.js → Button-BSvdrKMk.js} +1 -1
  5. package/dist/web/assets/{EmptyNote-zvLnRLPo.js → EmptyNote-mpJ8e7Tf.js} +1 -1
  6. package/dist/web/assets/{Field-BxSk5tbg.js → Field-CvWHFo14.js} +1 -1
  7. package/dist/web/assets/{Modal-CU0ZPvE2.js → Modal-Cl4CKo6q.js} +1 -1
  8. package/dist/web/assets/{Skeleton-DNAfO8PV.js → Skeleton-BvYeiEvb.js} +1 -1
  9. package/dist/web/assets/{StrategistPanel-DMjQbPlQ.js → StrategistPanel-CsOILu02.js} +3 -3
  10. package/dist/web/assets/cadences-JqBgr46D.js +1 -0
  11. package/dist/web/assets/chevron-down-BeWVWGdo.js +1 -0
  12. package/dist/web/assets/chevron-right-Du3_kGKl.js +1 -0
  13. package/dist/web/assets/cn-BKgCwmv1.js +1 -0
  14. package/dist/web/assets/inbox-DtLjDnYD.js +1 -0
  15. package/dist/web/assets/index-7d3nMOw-.js +54 -0
  16. package/dist/web/assets/index-CKtlVfUg.css +2 -0
  17. package/dist/web/assets/loader-circle-gVZnVzju.js +1 -0
  18. package/dist/web/assets/measure-Bmh0UUK6.js +1 -0
  19. package/dist/web/assets/plays-DhdcqdAa.js +1 -0
  20. package/dist/web/assets/queue-wHngnLmn.js +1 -0
  21. package/dist/web/assets/receipts-CDfQR8nI.js +1 -0
  22. package/dist/web/assets/{refresh-cw-Bz4Kdt55.js → refresh-cw-CJdqj4WJ.js} +1 -1
  23. package/dist/web/assets/routes-Brb_5Gng.js +1 -0
  24. package/dist/web/assets/run._playName-C243_Zbw.js +4 -0
  25. package/dist/web/assets/send-CwiJ-XyF.js +1 -0
  26. package/dist/web/assets/setup-CcO6C_TU.js +1 -0
  27. package/dist/web/assets/x-D_dx-pu-.js +1 -0
  28. package/dist/web/index.html +3 -3
  29. package/package.json +2 -2
  30. package/dist/web/assets/cadences-CvBPoULf.js +0 -1
  31. package/dist/web/assets/chevron-down-CDjJN-YY.js +0 -1
  32. package/dist/web/assets/chevron-right-BTFaTdbr.js +0 -1
  33. package/dist/web/assets/cn-CS0Arupu.js +0 -1
  34. package/dist/web/assets/inbox-CzzgtWQf.js +0 -1
  35. package/dist/web/assets/index-B_nrqLlS.js +0 -54
  36. package/dist/web/assets/index-Ya_svHJk.css +0 -2
  37. package/dist/web/assets/loader-circle-CKkt6cSn.js +0 -1
  38. package/dist/web/assets/measure-CEgySDdR.js +0 -1
  39. package/dist/web/assets/plays-CuudkOHb.js +0 -1
  40. package/dist/web/assets/queue-C7vGtsQ5.js +0 -1
  41. package/dist/web/assets/receipts-B5u3oLpw.js +0 -1
  42. package/dist/web/assets/routes-DHC_we4Z.js +0 -1
  43. package/dist/web/assets/run._playName-B9sG9Msq.js +0 -4
  44. package/dist/web/assets/send-Bv2Dd-HU.js +0 -1
  45. package/dist/web/assets/setup-BRVBiCEX.js +0 -1
  46. package/dist/web/assets/x-CPdidoxn.js +0 -1
package/dist/bin.mjs CHANGED
@@ -160,6 +160,14 @@ const DEFAULT_DB_PATH = join(configDir(), "ledger.sqlite");
160
160
  function canonEmail(email) {
161
161
  return email.trim().toLowerCase();
162
162
  }
163
+ function safeParseJsonArray(raw) {
164
+ try {
165
+ const parsed = JSON.parse(raw);
166
+ return Array.isArray(parsed) ? parsed : [];
167
+ } catch {
168
+ return [];
169
+ }
170
+ }
163
171
  var Ledger = class {
164
172
  db;
165
173
  constructor(path = DEFAULT_DB_PATH) {
@@ -293,6 +301,24 @@ var Ledger = class {
293
301
  fetched_at TEXT NOT NULL
294
302
  );
295
303
 
304
+ CREATE TABLE IF NOT EXISTS runs (
305
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
306
+ play_name TEXT NOT NULL,
307
+ dry_run INTEGER NOT NULL,
308
+ status TEXT NOT NULL CHECK(status IN ('running','done','interrupted')),
309
+ started_at TEXT NOT NULL,
310
+ completed_at TEXT,
311
+ target_count INTEGER NOT NULL,
312
+ drafted_count INTEGER NOT NULL DEFAULT 0,
313
+ sent_count INTEGER NOT NULL DEFAULT 0,
314
+ error_count INTEGER NOT NULL DEFAULT 0,
315
+ targets_json TEXT NOT NULL,
316
+ events_json TEXT NOT NULL DEFAULT '[]',
317
+ prospect_emails_json TEXT NOT NULL DEFAULT '[]'
318
+ );
319
+ CREATE INDEX IF NOT EXISTS idx_runs_started ON runs(started_at DESC);
320
+ CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status);
321
+
296
322
  CREATE TABLE IF NOT EXISTS schema_version (
297
323
  version INTEGER PRIMARY KEY
298
324
  );
@@ -305,6 +331,45 @@ var Ledger = class {
305
331
  this.addColumnIfMissing("target_queue", "drain_claimed_at", "TEXT");
306
332
  this.addColumnIfMissing("cadence_state", "next_step_draft_json", "TEXT");
307
333
  this.addColumnIfMissing("cadence_state", "next_step_drafted_at", "TEXT");
334
+ this.addColumnIfMissing("cadence_state", "sending_started_at", "TEXT");
335
+ this.addColumnIfMissing("target_queue", "send_started_at", "TEXT");
336
+ }
337
+ /**
338
+ * CAS-claim a timestamp marker on a single row. Returns true when the row's
339
+ * marker was NULL (or older than `staleCutoffIso` when provided) and we set
340
+ * it to `startedAtIso`; false when another caller already holds the claim.
341
+ *
342
+ * Shared by every in-flight marker in the ledger: triggers.running_started_at,
343
+ * cadence_state.sending_started_at, target_queue.send_started_at. Each domain
344
+ * just supplies its own table + primary-key WHERE fragment.
345
+ *
346
+ * Identifier validation (table + column) mirrors `addColumnIfMissing` —
347
+ * SQLite has no parameter binding for table/column names, so we whitelist
348
+ * to bare ASCII to slam the door on any injection vector.
349
+ */
350
+ claimMarker(opts) {
351
+ this.assertSafeIdentifiers(opts.table, opts.column);
352
+ const staleClause = opts.staleCutoffIso ? ` AND (${opts.column} IS NULL OR ${opts.column} < ?)` : ` AND ${opts.column} IS NULL`;
353
+ const args = opts.staleCutoffIso ? [
354
+ opts.startedAtIso,
355
+ ...opts.pkeyValues,
356
+ opts.staleCutoffIso
357
+ ] : [opts.startedAtIso, ...opts.pkeyValues];
358
+ return this.db.prepare(`UPDATE ${opts.table}
359
+ SET ${opts.column} = ?
360
+ WHERE ${opts.pkeyWhere}${staleClause}`).run(...args).changes > 0;
361
+ }
362
+ /**
363
+ * Release a timestamp marker (set to NULL). Idempotent — no-op if the row
364
+ * doesn't exist or the column is already NULL.
365
+ */
366
+ clearMarker(opts) {
367
+ this.assertSafeIdentifiers(opts.table, opts.column);
368
+ this.db.prepare(`UPDATE ${opts.table} SET ${opts.column} = NULL WHERE ${opts.pkeyWhere}`).run(...opts.pkeyValues);
369
+ }
370
+ assertSafeIdentifiers(table, column) {
371
+ const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
372
+ if (!ident.test(table) || !ident.test(column)) throw new Error(`unsafe identifier in marker helper: ${table}.${column}`);
308
373
  }
309
374
  addColumnIfMissing(table, column, type) {
310
375
  const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -371,15 +436,17 @@ var Ledger = class {
371
436
  advanceCadence(input) {
372
437
  this.db.prepare(`UPDATE cadence_state
373
438
  SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now'),
374
- next_step_draft_json = NULL, next_step_drafted_at = NULL
439
+ next_step_draft_json = NULL, next_step_drafted_at = NULL,
440
+ sending_started_at = NULL
375
441
  WHERE prospect_id = ? AND play_name = ?`).run(input.newStep, input.nextDueAt, input.prospectId, input.playName);
376
442
  }
377
443
  setCadenceStatus(input) {
378
444
  this.db.prepare(`UPDATE cadence_state
379
445
  SET status = ?,
380
446
  next_step_draft_json = CASE WHEN ? = 'active' THEN next_step_draft_json ELSE NULL END,
381
- next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END
382
- WHERE prospect_id = ? AND play_name = ?`).run(input.status, input.status, input.status, input.prospectId, input.playName);
447
+ next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END,
448
+ sending_started_at = CASE WHEN ? = 'active' THEN sending_started_at ELSE NULL END
449
+ WHERE prospect_id = ? AND play_name = ?`).run(input.status, input.status, input.status, input.status, input.prospectId, input.playName);
383
450
  }
384
451
  setCadenceDraft(input) {
385
452
  const draftedAtIso = (/* @__PURE__ */ new Date()).toISOString();
@@ -406,6 +473,81 @@ var Ledger = class {
406
473
  SET next_step_draft_json = NULL, next_step_drafted_at = NULL
407
474
  WHERE prospect_id = ? AND play_name = ?`).run(input.prospectId, input.playName);
408
475
  }
476
+ /**
477
+ * Atomic claim of the sending marker. Returns `true` when the row had a
478
+ * NULL `sending_started_at` and the marker was set; `false` if another
479
+ * caller already holds the claim. Mirrors triggers' `markTriggerRunning`
480
+ * CAS pattern so two concurrent Send clicks can't double-fire.
481
+ *
482
+ * `staleCutoffIso` (optional): allows a fresh click to reclaim a marker
483
+ * whose `sending_started_at` is older than the cutoff — for the case where
484
+ * a previous send was stranded by a server restart and the cold-boot
485
+ * sweeper hasn't cleared it yet. Without this, the row would 409 every
486
+ * retry until the next boot sweep.
487
+ */
488
+ claimCadenceSendingMarker(input) {
489
+ return this.claimMarker({
490
+ table: "cadence_state",
491
+ pkeyWhere: "prospect_id = ? AND play_name = ?",
492
+ column: "sending_started_at",
493
+ pkeyValues: [input.prospectId, input.playName],
494
+ startedAtIso: input.startedAtIso,
495
+ ...input.staleCutoffIso ? { staleCutoffIso: input.staleCutoffIso } : {}
496
+ });
497
+ }
498
+ /** Release the sending marker for this cadence (sets sending_started_at = NULL). */
499
+ clearCadenceSendingMarker(input) {
500
+ this.clearMarker({
501
+ table: "cadence_state",
502
+ pkeyWhere: "prospect_id = ? AND play_name = ?",
503
+ column: "sending_started_at",
504
+ pkeyValues: [input.prospectId, input.playName]
505
+ });
506
+ }
507
+ /**
508
+ * Sweep cadence rows whose `sending_started_at` is older than the cutoff
509
+ * (or any non-null value when `staleAgeMs` is 0 — cold-boot semantics).
510
+ * For each match, classify by whether a `sequence_events` row for the
511
+ * (prospect, play, current_step) already exists:
512
+ * - event present → the send actually went out; clear the marker only.
513
+ * - event absent → the send was stranded (server died mid-call); clear
514
+ * the marker but leave the draft so the founder can re-click Send.
515
+ * Returns the swept rows so the caller can log them.
516
+ *
517
+ * Pure-ish (takes `now` + `maxAgeMs` as args) — tests can drive both
518
+ * "fresh markers spared" and "stale markers swept" without faking the clock.
519
+ */
520
+ sweepStaleCadenceSends(input) {
521
+ const cutoffMs = input.now.getTime() - input.maxAgeMs;
522
+ const rows = this.db.query(`SELECT prospect_id, play_name, current_step, sending_started_at
523
+ FROM cadence_state
524
+ WHERE sending_started_at IS NOT NULL`).all();
525
+ const swept = [];
526
+ const checkEvent = this.db.prepare(`SELECT 1 FROM sequence_events
527
+ WHERE prospect_id = ? AND play_name = ? AND step_index = ?
528
+ AND status IN ('sent','delivered','replied')
529
+ LIMIT 1`);
530
+ const clear = this.db.prepare(`UPDATE cadence_state
531
+ SET sending_started_at = NULL
532
+ WHERE prospect_id = ? AND play_name = ?`);
533
+ for (const row of rows) {
534
+ const startedMs = new Date(row.sending_started_at).getTime();
535
+ if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue;
536
+ const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;
537
+ const sentNow = checkEvent.get(row.prospect_id, row.play_name, row.current_step);
538
+ const sentPrev = checkEvent.get(row.prospect_id, row.play_name, row.current_step - 1);
539
+ const actuallySent = sentNow != null || sentPrev != null;
540
+ clear.run(row.prospect_id, row.play_name);
541
+ swept.push({
542
+ prospectId: row.prospect_id,
543
+ playName: row.play_name,
544
+ startedAt: row.sending_started_at,
545
+ ageMs,
546
+ actuallySent
547
+ });
548
+ }
549
+ return swept;
550
+ }
409
551
  findProspectByEmail(email) {
410
552
  return this.db.query("SELECT id FROM prospects WHERE email = ?").get(canonEmail(email)) ?? null;
411
553
  }
@@ -650,6 +792,36 @@ var Ledger = class {
650
792
  return row !== null && row !== void 0;
651
793
  }
652
794
  /**
795
+ * Cross-play dedup (finder side): is this email already sitting in a
796
+ * non-terminal queue row under ANY play? Catches the window where the same
797
+ * person is queued under two plays before either has sent (so no prospect row
798
+ * exists yet for findProspectByEmail to catch). Terminal rows
799
+ * (sent/rejected/expired) are excluded so they never block future work.
800
+ * Matches both `email` (most plays) and `founderEmail` (show-hn-style).
801
+ */
802
+ isEmailPendingInQueue(email) {
803
+ const row = this.db.query(`SELECT 1 FROM target_queue
804
+ WHERE status IN ('pending','approved')
805
+ AND (LOWER(json_extract(payload_json, '$.email')) = ?1
806
+ OR LOWER(json_extract(payload_json, '$.founderEmail')) = ?1)
807
+ LIMIT 1`).get(canonEmail(email));
808
+ return row !== null && row !== void 0;
809
+ }
810
+ /**
811
+ * Cross-play dedup (send side): has this prospect already received an initial
812
+ * (step-0) touch under ANY play? The authoritative guard against first-touching
813
+ * the same person twice. Mirrors the step-0 existence check in
814
+ * sweepStaleCadenceSends. Note: deliberate re-engagement (breakup-revive)
815
+ * bypasses this via sendDraftedEmail's `allowRecontact`.
816
+ */
817
+ prospectHasFirstTouch(prospectId) {
818
+ const row = this.db.query(`SELECT 1 FROM sequence_events
819
+ WHERE prospect_id = ? AND step_index = 0
820
+ AND status IN ('sent','delivered','replied')
821
+ LIMIT 1`).get(prospectId);
822
+ return row !== null && row !== void 0;
823
+ }
824
+ /**
653
825
  * Look up a queue row by its (play_name, dedupe_key) — the unique pair.
654
826
  * Used by the SSE /run endpoint to map drafts back to the originating
655
827
  * row so we can persist `last_draft_json`. Returns null when absent.
@@ -682,7 +854,7 @@ var Ledger = class {
682
854
  }
683
855
  setQueueStatus(input) {
684
856
  const now = (/* @__PURE__ */ new Date()).toISOString();
685
- if (input.status === "sent") this.db.prepare(`UPDATE target_queue SET status = ?, sent_at = ?, reviewed_at = COALESCE(reviewed_at, ?) ${input.notes ? ", notes = ?" : ""} WHERE id = ?`).run(...input.notes ? [
857
+ if (input.status === "sent") this.db.prepare(`UPDATE target_queue SET status = ?, sent_at = ?, reviewed_at = COALESCE(reviewed_at, ?), send_started_at = NULL ${input.notes ? ", notes = ?" : ""} WHERE id = ?`).run(...input.notes ? [
686
858
  input.status,
687
859
  now,
688
860
  now,
@@ -694,7 +866,7 @@ var Ledger = class {
694
866
  now,
695
867
  input.id
696
868
  ]);
697
- else if (input.status === "approved" || input.status === "rejected") this.db.prepare(`UPDATE target_queue SET status = ?, reviewed_at = ? ${input.notes ? ", notes = ?" : ""} WHERE id = ?`).run(...input.notes ? [
869
+ else if (input.status === "approved" || input.status === "rejected") this.db.prepare(`UPDATE target_queue SET status = ?, reviewed_at = ?, send_started_at = NULL ${input.notes ? ", notes = ?" : ""} WHERE id = ?`).run(...input.notes ? [
698
870
  input.status,
699
871
  now,
700
872
  input.notes,
@@ -704,7 +876,58 @@ var Ledger = class {
704
876
  now,
705
877
  input.id
706
878
  ]);
707
- else this.db.prepare(`UPDATE target_queue SET status = ? WHERE id = ?`).run(input.status, input.id);
879
+ else this.db.prepare(`UPDATE target_queue SET status = ?, send_started_at = NULL WHERE id = ?`).run(input.status, input.id);
880
+ }
881
+ /**
882
+ * Atomic claim of the queue-send marker on `target_queue.send_started_at`.
883
+ * Mirrors `claimCadenceSendingMarker` semantics — survives server restart so
884
+ * `/queue` Send-draft UI doesn't lose its spinner on `bun --watch` reloads.
885
+ * Cleared on success via `setQueueStatus('sent', …)`, on failure via
886
+ * `clearQueueSendingMarker`, on cold boot via `sweepStaleQueueSends`.
887
+ */
888
+ claimQueueSendingMarker(input) {
889
+ return this.claimMarker({
890
+ table: "target_queue",
891
+ pkeyWhere: "id = ?",
892
+ column: "send_started_at",
893
+ pkeyValues: [input.id],
894
+ startedAtIso: input.startedAtIso,
895
+ ...input.staleCutoffIso ? { staleCutoffIso: input.staleCutoffIso } : {}
896
+ });
897
+ }
898
+ clearQueueSendingMarker(id) {
899
+ this.clearMarker({
900
+ table: "target_queue",
901
+ pkeyWhere: "id = ?",
902
+ column: "send_started_at",
903
+ pkeyValues: [id]
904
+ });
905
+ }
906
+ /**
907
+ * Sweep queue rows whose `send_started_at` is older than `maxAgeMs` (or any
908
+ * non-null when 0 — cold-boot semantics). For each: classify by current
909
+ * status. status='sent' means the SDK call landed before the kill (clear
910
+ * the marker only); otherwise the send was stranded (clear the marker,
911
+ * draft is still on the row for retry).
912
+ */
913
+ sweepStaleQueueSends(input) {
914
+ const cutoffMs = input.now.getTime() - input.maxAgeMs;
915
+ const rows = this.db.query(`SELECT id, status, send_started_at FROM target_queue WHERE send_started_at IS NOT NULL`).all();
916
+ const swept = [];
917
+ const clear = this.db.prepare(`UPDATE target_queue SET send_started_at = NULL WHERE id = ?`);
918
+ for (const row of rows) {
919
+ const startedMs = new Date(row.send_started_at).getTime();
920
+ if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue;
921
+ const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;
922
+ clear.run(row.id);
923
+ swept.push({
924
+ id: row.id,
925
+ startedAt: row.send_started_at,
926
+ ageMs,
927
+ actuallySent: row.status === "sent"
928
+ });
929
+ }
930
+ return swept;
708
931
  }
709
932
  approveAllPending(opts = {}) {
710
933
  const where = ["status = 'pending'"];
@@ -759,6 +982,121 @@ var Ledger = class {
759
982
  for (const r of rows) out[r.status] = r.n;
760
983
  return out;
761
984
  }
985
+ createRun(input) {
986
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
987
+ const result = this.db.prepare(`INSERT INTO runs(play_name, dry_run, status, started_at, target_count, targets_json)
988
+ VALUES(?, ?, 'running', ?, ?, ?)`).run(input.playName, input.dryRun ? 1 : 0, startedAt, input.targets.length, JSON.stringify(input.targets));
989
+ return {
990
+ runId: Number(result.lastInsertRowid),
991
+ startedAt
992
+ };
993
+ }
994
+ /**
995
+ * Append a single event to a run's events_json and bump the matching
996
+ * counter. Cheap re-serialize is fine — events_json fits in a single row;
997
+ * runs are bounded at ~25 targets typically.
998
+ */
999
+ appendRunEvent(input) {
1000
+ const row = this.db.query(`SELECT events_json, drafted_count, sent_count, error_count
1001
+ FROM runs WHERE id = ?`).get(input.runId);
1002
+ if (!row) return;
1003
+ let events;
1004
+ try {
1005
+ events = JSON.parse(row.events_json);
1006
+ if (!Array.isArray(events)) events = [];
1007
+ } catch {
1008
+ events = [];
1009
+ }
1010
+ events.push(input.event);
1011
+ const kind = input.event && typeof input.event === "object" ? input.event.kind ?? null : null;
1012
+ let drafted = row.drafted_count;
1013
+ let sent = row.sent_count;
1014
+ let errors = row.error_count;
1015
+ if (kind === "draft") drafted++;
1016
+ else if (kind === "send") sent++;
1017
+ else if (kind === "error") errors++;
1018
+ this.db.prepare(`UPDATE runs
1019
+ SET events_json = ?, drafted_count = ?, sent_count = ?, error_count = ?
1020
+ WHERE id = ?`).run(JSON.stringify(events), drafted, sent, errors, input.runId);
1021
+ }
1022
+ markRunComplete(input) {
1023
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
1024
+ this.db.prepare(`UPDATE runs
1025
+ SET status = ?, completed_at = ?, prospect_emails_json = ?
1026
+ WHERE id = ? AND status = 'running'`).run(input.status, completedAt, JSON.stringify(input.sentEmails ?? []), input.runId);
1027
+ }
1028
+ getRun(runId) {
1029
+ const row = this.db.query(`SELECT * FROM runs WHERE id = ?`).get(runId);
1030
+ if (!row) return null;
1031
+ return {
1032
+ id: row.id,
1033
+ playName: row.play_name,
1034
+ dryRun: row.dry_run === 1,
1035
+ status: row.status,
1036
+ startedAt: row.started_at,
1037
+ completedAt: row.completed_at,
1038
+ targetCount: row.target_count,
1039
+ draftedCount: row.drafted_count,
1040
+ sentCount: row.sent_count,
1041
+ errorCount: row.error_count,
1042
+ targets: safeParseJsonArray(row.targets_json),
1043
+ events: safeParseJsonArray(row.events_json),
1044
+ prospectEmails: safeParseJsonArray(row.prospect_emails_json)
1045
+ };
1046
+ }
1047
+ /**
1048
+ * Compact run listing for dashboards. Returns lightweight columns only —
1049
+ * `events_json` + `targets_json` stay on the row but aren't read here so
1050
+ * `/api/home` doesn't pay to ship them on every 30s poll. Default order:
1051
+ * newest started_at first; capped at `limit` rows (default 5). When
1052
+ * `status` is set, filters via the existing `idx_runs_status` index.
1053
+ */
1054
+ listRuns(opts = {}) {
1055
+ const limit = Math.max(1, Math.min(50, opts.limit ?? 5));
1056
+ const where = opts.status ? "WHERE status = ?" : "";
1057
+ const args = opts.status ? [opts.status, limit] : [limit];
1058
+ return this.db.query(`SELECT id, play_name, status, started_at, completed_at,
1059
+ target_count, drafted_count, sent_count, error_count
1060
+ FROM runs
1061
+ ${where}
1062
+ ORDER BY started_at DESC
1063
+ LIMIT ?`).all(...args).map((r) => ({
1064
+ id: r.id,
1065
+ playName: r.play_name,
1066
+ status: r.status,
1067
+ startedAt: r.started_at,
1068
+ completedAt: r.completed_at,
1069
+ targetCount: r.target_count,
1070
+ draftedCount: r.drafted_count,
1071
+ sentCount: r.sent_count,
1072
+ errorCount: r.error_count
1073
+ }));
1074
+ }
1075
+ /**
1076
+ * Sweep run rows whose status is still 'running' but predate the cutoff
1077
+ * (or any non-null when 0 — cold-boot semantics). Marks them as
1078
+ * 'interrupted' so the UI shows a truthful banner instead of an eternal
1079
+ * spinner. Returns the swept rows so the caller can log them.
1080
+ */
1081
+ sweepStaleRuns(input) {
1082
+ const cutoffMs = input.now.getTime() - input.maxAgeMs;
1083
+ const rows = this.db.query(`SELECT id, play_name, started_at FROM runs WHERE status = 'running'`).all();
1084
+ const swept = [];
1085
+ const update = this.db.prepare(`UPDATE runs SET status = 'interrupted', completed_at = ? WHERE id = ?`);
1086
+ for (const row of rows) {
1087
+ const startedMs = new Date(row.started_at).getTime();
1088
+ if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue;
1089
+ const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;
1090
+ update.run(input.now.toISOString(), row.id);
1091
+ swept.push({
1092
+ id: row.id,
1093
+ playName: row.play_name,
1094
+ startedAt: row.started_at,
1095
+ ageMs
1096
+ });
1097
+ }
1098
+ return swept;
1099
+ }
762
1100
  upsertTrigger(input) {
763
1101
  this.db.prepare(`INSERT INTO triggers(name, enabled, config_json)
764
1102
  VALUES(?, ?, ?)
@@ -804,12 +1142,14 @@ var Ledger = class {
804
1142
  * `sweepStaleRunningTriggers` on the next cold boot.
805
1143
  */
806
1144
  markTriggerRunning(name, startedAtIso, staleCutoffIso) {
807
- if (staleCutoffIso) return this.db.prepare(`UPDATE triggers
808
- SET running_started_at = ?
809
- WHERE name = ? AND (running_started_at IS NULL OR running_started_at < ?)`).run(startedAtIso, name, staleCutoffIso).changes > 0;
810
- return this.db.prepare(`UPDATE triggers
811
- SET running_started_at = ?
812
- WHERE name = ? AND running_started_at IS NULL`).run(startedAtIso, name).changes > 0;
1145
+ return this.claimMarker({
1146
+ table: "triggers",
1147
+ pkeyWhere: "name = ?",
1148
+ column: "running_started_at",
1149
+ pkeyValues: [name],
1150
+ startedAtIso,
1151
+ ...staleCutoffIso ? { staleCutoffIso } : {}
1152
+ });
813
1153
  }
814
1154
  /**
815
1155
  * Sweep trigger rows whose `running_started_at` is older than `maxAgeMs`.
@@ -899,9 +1239,25 @@ function getLedger() {
899
1239
  }
900
1240
  //#endregion
901
1241
  //#region ../../packages/core/src/oneshot.ts
1242
+ /**
1243
+ * Build the `{memo, decisionContext}` audit blob the SDK 0.16.2+ accepts as
1244
+ * top-level fields on every paid tool's option bag. Sensible defaults (playName
1245
+ * + callType) so even call sites that don't enrich still emit a usable audit
1246
+ * trail; callers that DO enrich override / extend via `ctx.decisionContext`.
1247
+ */
1248
+ function buildAuditOpts(ctx, callType) {
1249
+ return {
1250
+ memo: ctx.memo ?? `${ctx.playName} ${callType}`,
1251
+ decisionContext: {
1252
+ playName: ctx.playName,
1253
+ callType,
1254
+ ...ctx.decisionContext
1255
+ }
1256
+ };
1257
+ }
902
1258
  let agentSingleton = null;
903
1259
  async function initAgent() {
904
- if (!oneshotEnvReady()) throw new Error("OneShot credentials missing. Set CDP_API_KEY_ID + CDP_API_KEY_SECRET + CDP_WALLET_SECRET, or AGENT_PRIVATE_KEY. Run `oneshot-gtm doctor` for details.");
1260
+ if (!oneshotEnvReady()) throw new Error("Agent wallet credentials missing. Set CDP_API_KEY_ID + CDP_API_KEY_SECRET + CDP_WALLET_SECRET, or AGENT_PRIVATE_KEY. Run `oneshot-gtm doctor` for details.");
905
1261
  if (process.env["AGENT_PRIVATE_KEY"]) return new OneShot({ privateKey: process.env["AGENT_PRIVATE_KEY"] });
906
1262
  return await OneShot.create({ cdp: true });
907
1263
  }
@@ -912,7 +1268,7 @@ async function getAgent() {
912
1268
  /**
913
1269
  * Derive the From localpart from the founder's name (first token, lowercased,
914
1270
  * non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back
915
- * to `agent` when the name yields nothing usable. ("J. Nicolas" → "j".)
1271
+ * to `agent` when the name yields nothing usable. ("Jane Doe" → "jane".)
916
1272
  */
917
1273
  function fromLocalpart(name) {
918
1274
  const clean = ((name ?? "").trim().split(/\s+/)[0] ?? "").toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -933,7 +1289,8 @@ async function sendEmail(input, ctx) {
933
1289
  const opts = {
934
1290
  to: input.to,
935
1291
  subject: input.subject,
936
- body: toHtmlBody(input.body)
1292
+ body: toHtmlBody(input.body),
1293
+ ...buildAuditOpts(ctx, "email.send")
937
1294
  };
938
1295
  if (fromDomain) {
939
1296
  opts.from_domain = fromDomain;
@@ -956,7 +1313,8 @@ async function sendEmail(input, ctx) {
956
1313
  async function deepResearch(input, ctx) {
957
1314
  const result = await (await getAgent()).research({
958
1315
  topic: input.topic,
959
- depth: input.depth ?? "quick"
1316
+ depth: input.depth ?? "quick",
1317
+ ...buildAuditOpts(ctx, "research.deep")
960
1318
  });
961
1319
  return {
962
1320
  result,
@@ -971,7 +1329,7 @@ async function deepResearch(input, ctx) {
971
1329
  }
972
1330
  async function enrichProfile(input, ctx) {
973
1331
  const agent = await getAgent();
974
- const opts = {};
1332
+ const opts = { ...buildAuditOpts(ctx, "enrich.profile") };
975
1333
  if (input.email) opts.email = input.email;
976
1334
  if (input.linkedinUrl) opts.linkedin_url = input.linkedinUrl;
977
1335
  if (input.name) opts.name = input.name;
@@ -997,7 +1355,7 @@ async function enrichProfile(input, ctx) {
997
1355
  */
998
1356
  async function deepResearchPerson(input, ctx) {
999
1357
  const agent = await getAgent();
1000
- const opts = {};
1358
+ const opts = { ...buildAuditOpts(ctx, "research.person") };
1001
1359
  if (input.email) opts.email = input.email;
1002
1360
  if (input.socialMediaUrl) opts.social_media_url = input.socialMediaUrl;
1003
1361
  if (input.name) opts.name = input.name;
@@ -1016,7 +1374,10 @@ async function deepResearchPerson(input, ctx) {
1016
1374
  }
1017
1375
  async function findEmail(input, ctx) {
1018
1376
  const agent = await getAgent();
1019
- const opts = { company_domain: input.companyDomain };
1377
+ const opts = {
1378
+ company_domain: input.companyDomain,
1379
+ ...buildAuditOpts(ctx, "email.find")
1380
+ };
1020
1381
  if (input.fullName) opts.full_name = input.fullName;
1021
1382
  if (input.firstName) opts.first_name = input.firstName;
1022
1383
  if (input.lastName) opts.last_name = input.lastName;
@@ -1033,7 +1394,10 @@ async function findEmail(input, ctx) {
1033
1394
  };
1034
1395
  }
1035
1396
  async function verifyEmail(input, ctx) {
1036
- const result = await (await getAgent()).verifyEmail({ email: input.email });
1397
+ const result = await (await getAgent()).verifyEmail({
1398
+ email: input.email,
1399
+ ...buildAuditOpts(ctx, "email.verify")
1400
+ });
1037
1401
  return {
1038
1402
  result,
1039
1403
  receiptId: getLedger().recordReceipt({
@@ -1063,7 +1427,8 @@ async function sendSms(input, ctx) {
1063
1427
  const agent = await getAgent();
1064
1428
  const opts = {
1065
1429
  to_number: input.to,
1066
- message: input.message
1430
+ message: input.message,
1431
+ ...buildAuditOpts(ctx, "sms.send")
1067
1432
  };
1068
1433
  if (input.maxCost) opts.maxCost = input.maxCost;
1069
1434
  const result = await agent.sms(opts);
@@ -1082,7 +1447,8 @@ async function voiceCall(input, ctx) {
1082
1447
  const agent = await getAgent();
1083
1448
  const opts = {
1084
1449
  objective: input.objective,
1085
- target_number: input.to
1450
+ target_number: input.to,
1451
+ ...buildAuditOpts(ctx, "voice.call")
1086
1452
  };
1087
1453
  if (input.callerPersona) opts.caller_persona = input.callerPersona;
1088
1454
  if (input.context) opts.context = input.context;
@@ -1101,7 +1467,10 @@ async function voiceCall(input, ctx) {
1101
1467
  }
1102
1468
  async function webSearch(input, ctx) {
1103
1469
  const agent = await getAgent();
1104
- const opts = { query: input.query };
1470
+ const opts = {
1471
+ query: input.query,
1472
+ ...buildAuditOpts(ctx, "web.search")
1473
+ };
1105
1474
  if (input.maxResults) opts.max_results = input.maxResults;
1106
1475
  const result = await agent.webSearch(opts);
1107
1476
  return {
@@ -1115,7 +1484,10 @@ async function webSearch(input, ctx) {
1115
1484
  };
1116
1485
  }
1117
1486
  async function webRead(input, ctx) {
1118
- const result = await (await getAgent()).webRead({ url: input.url });
1487
+ const result = await (await getAgent()).webRead({
1488
+ url: input.url,
1489
+ ...buildAuditOpts(ctx, "web.read")
1490
+ });
1119
1491
  return {
1120
1492
  result,
1121
1493
  receiptId: getLedger().recordReceipt({
@@ -1129,7 +1501,10 @@ async function webRead(input, ctx) {
1129
1501
  }
1130
1502
  async function browserTask(input, ctx) {
1131
1503
  const agent = await getAgent();
1132
- const opts = { task: input.task };
1504
+ const opts = {
1505
+ task: input.task,
1506
+ ...buildAuditOpts(ctx, "browser.task")
1507
+ };
1133
1508
  if (input.startUrl) opts.start_url = input.startUrl;
1134
1509
  if (input.allowedDomains) opts.allowed_domains = input.allowedDomains;
1135
1510
  if (input.outputSchema) opts.output_schema = input.outputSchema;
@@ -1149,6 +1524,74 @@ async function browserTask(input, ctx) {
1149
1524
  };
1150
1525
  }
1151
1526
  //#endregion
1527
+ //#region ../../packages/core/src/inflight.ts
1528
+ /**
1529
+ * Process-wide in-flight SEND tracker, used to drain gracefully on shutdown.
1530
+ *
1531
+ * The risk this guards: a `kill`/Ctrl-C lands between "OneShot accepted the
1532
+ * send" and "we wrote the local `sequence_events` row". The dedup keys off that
1533
+ * row, so a send lost in that gap can be re-sent (a duplicate) on retry. The
1534
+ * server's shutdown handler waits for `activeSendCount()` to reach 0 before
1535
+ * exiting, so every in-flight send finishes recording first.
1536
+ *
1537
+ * In-memory by design: it complements the PERSISTED `send_started_at` /
1538
+ * `sending_started_at` markers (which survive a hard kill and are reconciled by
1539
+ * the cold-boot sweep). This counter only exists within a live process and only
1540
+ * matters for the graceful (signal) path. A hard SIGKILL skips it — the boot
1541
+ * sweep is the backstop there.
1542
+ */
1543
+ let active = 0;
1544
+ let draining = false;
1545
+ /** Mark a send as started. Pair with exactly one `endSend()`. Prefer `trackSend`. */
1546
+ function beginSend() {
1547
+ active++;
1548
+ }
1549
+ /** Mark a send as finished. Never drops below 0 even if mis-paired. */
1550
+ function endSend() {
1551
+ active = Math.max(0, active - 1);
1552
+ }
1553
+ /**
1554
+ * Wrap a send-and-persist span so it's counted as in-flight for its whole
1555
+ * duration — including the local record write that follows the SDK call. The
1556
+ * counter decrements even if `fn` throws.
1557
+ */
1558
+ async function trackSend(fn) {
1559
+ beginSend();
1560
+ try {
1561
+ return await fn();
1562
+ } finally {
1563
+ endSend();
1564
+ }
1565
+ }
1566
+ /** How many sends are currently in-flight. */
1567
+ function activeSendCount() {
1568
+ return active;
1569
+ }
1570
+ /** Flip the draining flag — send routes should start refusing new work (503). */
1571
+ function beginDraining() {
1572
+ draining = true;
1573
+ }
1574
+ /** True once shutdown has begun draining; new sends should be refused. */
1575
+ function isDraining() {
1576
+ return draining;
1577
+ }
1578
+ /**
1579
+ * Poll until no sends are in-flight or `timeoutMs` elapses. Resolves
1580
+ * immediately when already idle. On timeout, returns `{ drained: false }` with
1581
+ * the count still outstanding so the caller can log it and exit anyway (the
1582
+ * boot sweep reconciles whatever was left).
1583
+ */
1584
+ async function waitForSendsToDrain(opts) {
1585
+ const poll = opts.pollMs ?? 200;
1586
+ const deadline = Date.now() + opts.timeoutMs;
1587
+ while (activeSendCount() > 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, poll));
1588
+ const remaining = activeSendCount();
1589
+ return {
1590
+ drained: remaining === 0,
1591
+ remaining
1592
+ };
1593
+ }
1594
+ //#endregion
1152
1595
  //#region ../../packages/core/src/events.ts
1153
1596
  const EVENTS_PATH = join(configDir(), "events.jsonl");
1154
1597
  const DEBUG_ENABLED = (process.env["DEBUG"] ?? "").includes("oneshot");
@@ -1229,7 +1672,7 @@ function resolveClientId() {
1229
1672
  * Lives in core so both `find` (candidate pipelines) and `plays` (batch send
1230
1673
  * loops) can share it without a cross-package dependency.
1231
1674
  */
1232
- async function parallelMap(items, concurrency, fn) {
1675
+ async function parallelMap(items, concurrency, fn, onItem) {
1233
1676
  const out = Array.from({ length: items.length });
1234
1677
  if (items.length === 0) return out;
1235
1678
  const workers = Math.max(1, Math.min(concurrency, items.length));
@@ -1238,7 +1681,10 @@ async function parallelMap(items, concurrency, fn) {
1238
1681
  while (true) {
1239
1682
  const i = cursor++;
1240
1683
  if (i >= items.length) return;
1241
- out[i] = await fn(items[i], i);
1684
+ const item = items[i];
1685
+ const result = await fn(item, i);
1686
+ out[i] = result;
1687
+ if (onItem) onItem(item, result, i);
1242
1688
  }
1243
1689
  }
1244
1690
  await Promise.all(Array.from({ length: workers }, () => worker()));
@@ -1264,7 +1710,11 @@ function homeMetrics(req) {
1264
1710
  callsLast7d: recent7d.length,
1265
1711
  sentLast7d: sent7d,
1266
1712
  repliedLast7d: replied7d,
1267
- activeCadences: active.length
1713
+ activeCadences: active.length,
1714
+ currentRuns: ledger.listRuns({
1715
+ status: "running",
1716
+ limit: 5
1717
+ })
1268
1718
  }, 200, req);
1269
1719
  }
1270
1720
  //#endregion
@@ -1505,7 +1955,7 @@ function tryParseJsonObject(raw, fallback) {
1505
1955
  //#endregion
1506
1956
  //#region ../../packages/plays/src/_lib.ts
1507
1957
  /** Profiles change slowly — reuse a cached enrichment for this long before refetching. */
1508
- const ENRICH_CACHE_TTL_MS = 720 * 3600 * 1e3;
1958
+ const ENRICH_CACHE_TTL_MS$1 = 720 * 3600 * 1e3;
1509
1959
  /**
1510
1960
  * enrichProfile that (a) never throws and (b) caches by email. The dossier is a
1511
1961
  * nice-to-have for drafting, the SDK call is slow (~70s) and billed, and the
@@ -1519,7 +1969,7 @@ async function safeEnrich(input, ctx) {
1519
1969
  const email = typeof input.email === "string" ? input.email.trim().toLowerCase() : null;
1520
1970
  if (email) {
1521
1971
  const cached = ledger.getCachedEnrichment(email);
1522
- if (cached && Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS) try {
1972
+ if (cached && Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS$1) try {
1523
1973
  return {
1524
1974
  result: JSON.parse(cached.result_json),
1525
1975
  receiptId: 0
@@ -1527,7 +1977,16 @@ async function safeEnrich(input, ctx) {
1527
1977
  } catch {}
1528
1978
  }
1529
1979
  try {
1530
- const out = await enrichProfile(input, ctx);
1980
+ const out = await enrichProfile(input, {
1981
+ ...ctx,
1982
+ decisionContext: {
1983
+ source: "play.enrich",
1984
+ ...email ? { prospectEmail: email } : {},
1985
+ ...input.linkedinUrl ? { linkedinUrl: input.linkedinUrl } : {},
1986
+ ...input.companyDomain ? { companyDomain: input.companyDomain } : {},
1987
+ ...ctx.decisionContext
1988
+ }
1989
+ });
1531
1990
  if (email) try {
1532
1991
  ledger.setCachedEnrichment(email, JSON.stringify(out.result));
1533
1992
  } catch {}
@@ -1567,13 +2026,49 @@ const SLOP_PHRASES = [
1567
2026
  [/\b(?:the future looks bright|exciting times lie ahead|journey toward)\b/i, "generic-positive-ending"],
1568
2027
  [/\b(?:hope this helps|let me know if you'?d like|happy to expand)\b/i, "servile-closer"]
1569
2028
  ];
2029
+ /**
2030
+ * Trailing signature lines that the signatureDirective forces the LLM to
2031
+ * append (founder name, then product domain, then optional "Sent from my
2032
+ * iPhone"). Returned in last-line-first order so callers can peel from the
2033
+ * end. Empty when neither name nor domain is configured (no sig to strip).
2034
+ */
2035
+ function configuredSigLines() {
2036
+ const cfg = loadConfig();
2037
+ const out = [];
2038
+ if (cfg.mobileSignature === true) out.push("Sent from my iPhone");
2039
+ const domain = (cfg.productDomain ?? "").trim();
2040
+ if (domain) out.push(domain);
2041
+ const name = (cfg.founderName ?? "").trim();
2042
+ if (name) out.push(name);
2043
+ return out;
2044
+ }
2045
+ /**
2046
+ * Word count for body-too-long lint. Strips the trailing signature lines so
2047
+ * the LLM isn't penalized for the 2-3 deterministic words the
2048
+ * signatureDirective forces it to append. Otherwise a prompt that says "≤110
2049
+ * words" only really gives the LLM ~107 for content, and borderline drafts
2050
+ * trip body-too-long even when they're inside the contract.
2051
+ *
2052
+ * `sigLines` (last-line-first order) is exposed for tests so they don't have
2053
+ * to mock loadConfig — production passes nothing and reads config.
2054
+ */
2055
+ function bodyWordsForLint(body, sigLines) {
2056
+ const lines = sigLines ?? configuredSigLines();
2057
+ let trimmed = body.replace(/\s+$/, "");
2058
+ for (const line of lines) {
2059
+ const i = trimmed.lastIndexOf("\n");
2060
+ if ((i < 0 ? trimmed : trimmed.slice(i + 1)).trim() !== line) break;
2061
+ trimmed = trimmed.slice(0, i < 0 ? 0 : i).replace(/\s+$/, "");
2062
+ }
2063
+ return trimmed.split(/\s+/).filter(Boolean).length;
2064
+ }
1570
2065
  function lintEmail(subject, body, maxBodyWords = 110) {
1571
2066
  const flags = [];
1572
2067
  if (subject.length === 0) flags.push("empty-subject");
1573
2068
  if (subject.length > 60) flags.push("subject-too-long");
1574
2069
  if (/[A-Z]{2,}/.test(subject)) flags.push("subject-shouty");
1575
2070
  if (body.length === 0) flags.push("empty-body");
1576
- if (body.split(/\s+/).length > maxBodyWords) flags.push("body-too-long");
2071
+ if (bodyWordsForLint(body) > maxBodyWords) flags.push("body-too-long");
1577
2072
  if (body.includes("—")) flags.push("em-dash");
1578
2073
  if (/[“”‘’]/.test(body)) flags.push("curly-quotes");
1579
2074
  if (/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(body)) flags.push("emoji");
@@ -1690,26 +2185,46 @@ async function sendDraftedEmail(opts) {
1690
2185
  sent: false
1691
2186
  };
1692
2187
  }
2188
+ if (!opts.allowRecontact && ledger.prospectHasFirstTouch(existing.id)) {
2189
+ opts.flags.push("already-contacted");
2190
+ return {
2191
+ receiptIds: [],
2192
+ sent: false
2193
+ };
2194
+ }
1693
2195
  }
1694
- const send = await sendEmail({
1695
- to: opts.to,
1696
- subject: opts.draft.subject,
1697
- body: opts.draft.body
1698
- }, { playName: opts.playName });
1699
- receiptIds.push(send.receiptId);
1700
- const prospectId = ledger.upsertProspect(opts.prospectMeta);
1701
- ledger.recordSequenceEvent({
1702
- prospectId,
1703
- playName: opts.playName,
1704
- stepIndex: 0,
1705
- channel: "email",
1706
- status: "sent",
1707
- metadata: {
2196
+ const receiptId = await trackSend(async () => {
2197
+ const send = await sendEmail({
2198
+ to: opts.to,
1708
2199
  subject: opts.draft.subject,
1709
- body: opts.draft.body,
1710
- ...opts.metadata
1711
- }
2200
+ body: opts.draft.body
2201
+ }, {
2202
+ playName: opts.playName,
2203
+ memo: `${opts.playName} step 0 → ${opts.to}`,
2204
+ decisionContext: {
2205
+ source: "play.initial",
2206
+ prospectEmail: opts.to,
2207
+ prospectName: opts.prospectMeta.name ?? null,
2208
+ company: opts.prospectMeta.company ?? null,
2209
+ subject: opts.draft.subject
2210
+ }
2211
+ });
2212
+ const prospectId = ledger.upsertProspect(opts.prospectMeta);
2213
+ ledger.recordSequenceEvent({
2214
+ prospectId,
2215
+ playName: opts.playName,
2216
+ stepIndex: 0,
2217
+ channel: "email",
2218
+ status: "sent",
2219
+ metadata: {
2220
+ subject: opts.draft.subject,
2221
+ body: opts.draft.body,
2222
+ ...opts.metadata
2223
+ }
2224
+ });
2225
+ return send.receiptId;
1712
2226
  });
2227
+ receiptIds.push(receiptId);
1713
2228
  sent = true;
1714
2229
  }
1715
2230
  return {
@@ -1723,6 +2238,45 @@ function emailDomain(email) {
1723
2238
  if (at < 0) return void 0;
1724
2239
  return email.slice(at + 1);
1725
2240
  }
2241
+ const HONORIFIC_TOKENS = new Set([
2242
+ "dr.",
2243
+ "dr",
2244
+ "mr.",
2245
+ "mr",
2246
+ "mrs.",
2247
+ "mrs",
2248
+ "ms.",
2249
+ "ms",
2250
+ "prof.",
2251
+ "prof",
2252
+ "sr.",
2253
+ "sr",
2254
+ "jr.",
2255
+ "jr"
2256
+ ]);
2257
+ /**
2258
+ * Best-effort first-name extraction from a prospect's `name` field. Returns
2259
+ * `null` when we shouldn't use a greeting at all: missing data, the placeholder
2260
+ * "(unknown)", a username-looking handle, or a non-capitalized opening token
2261
+ * (which usually signals a handle fragment rather than a real first name).
2262
+ *
2263
+ * Used to optionally surface `PROSPECT_FIRST_NAME` to the LLM input block so
2264
+ * prompts can occasionally open with `Hey {firstName},`. The LLM owns the
2265
+ * decision to actually greet — this helper just gates whether the field is
2266
+ * present.
2267
+ */
2268
+ function firstNameFrom(name) {
2269
+ if (!name) return null;
2270
+ const trimmed = name.trim();
2271
+ if (trimmed.length === 0 || trimmed === "(unknown)") return null;
2272
+ const tokens = trimmed.split(/\s+/);
2273
+ let i = 0;
2274
+ while (i < tokens.length && HONORIFIC_TOKENS.has(tokens[i].toLowerCase())) i++;
2275
+ const first = tokens[i];
2276
+ if (!first) return null;
2277
+ if (!/^[A-Z]/.test(first)) return null;
2278
+ return first.replace(/,$/, "");
2279
+ }
1726
2280
  /**
1727
2281
  * Verify a batch of target emails BEFORE drafting + sending. Used by
1728
2282
  * direct-input entry points (CLI motion commands + dashboard /run) where
@@ -2197,9 +2751,20 @@ async function sendCadenceStepBatch(items, onItemSettled) {
2197
2751
  }
2198
2752
  return out;
2199
2753
  }
2200
- async function dispatchStep(input) {
2754
+ function dispatchStep(input) {
2755
+ return trackSend(() => dispatchStepImpl(input));
2756
+ }
2757
+ async function dispatchStepImpl(input) {
2201
2758
  const ledger = getLedger();
2202
2759
  const receiptIds = [];
2760
+ const cadenceAudit = {
2761
+ source: "cadence",
2762
+ prospectId: input.prospectId,
2763
+ prospectEmail: input.prospectEmail,
2764
+ stepIndex: input.stepIndex,
2765
+ label: input.label ?? null
2766
+ };
2767
+ const labelTail = input.label ? ` ${input.label}` : "";
2203
2768
  if (input.payload.kind === "email") {
2204
2769
  if (!input.prospectEmail) return {
2205
2770
  receiptIds,
@@ -2209,7 +2774,14 @@ async function dispatchStep(input) {
2209
2774
  to: input.prospectEmail,
2210
2775
  subject: input.payload.subject,
2211
2776
  body: input.payload.body
2212
- }, { playName: input.playName });
2777
+ }, {
2778
+ playName: input.playName,
2779
+ memo: `${input.playName} step ${input.stepIndex}${labelTail} → ${input.prospectEmail}`,
2780
+ decisionContext: {
2781
+ ...cadenceAudit,
2782
+ subject: input.payload.subject
2783
+ }
2784
+ });
2213
2785
  receiptIds.push(send.receiptId);
2214
2786
  ledger.recordSequenceEvent({
2215
2787
  prospectId: input.prospectId,
@@ -2233,7 +2805,14 @@ async function dispatchStep(input) {
2233
2805
  const send = await sendSms({
2234
2806
  to: input.payload.toPhone,
2235
2807
  message: input.payload.message
2236
- }, { playName: input.playName });
2808
+ }, {
2809
+ playName: input.playName,
2810
+ memo: `${input.playName} step ${input.stepIndex}${labelTail} SMS → ${input.payload.toPhone}`,
2811
+ decisionContext: {
2812
+ ...cadenceAudit,
2813
+ toPhone: input.payload.toPhone
2814
+ }
2815
+ });
2237
2816
  receiptIds.push(send.receiptId);
2238
2817
  ledger.recordSequenceEvent({
2239
2818
  prospectId: input.prospectId,
@@ -2255,7 +2834,15 @@ async function dispatchStep(input) {
2255
2834
  to: input.payload.toPhone,
2256
2835
  ...input.payload.context ? { context: input.payload.context } : {},
2257
2836
  ...input.payload.maxDurationMinutes ? { maxDurationMinutes: input.payload.maxDurationMinutes } : {}
2258
- }, { playName: input.playName });
2837
+ }, {
2838
+ playName: input.playName,
2839
+ memo: `${input.playName} step ${input.stepIndex}${labelTail} voice → ${input.payload.toPhone}`,
2840
+ decisionContext: {
2841
+ ...cadenceAudit,
2842
+ toPhone: input.payload.toPhone,
2843
+ objective: input.payload.objective.slice(0, 120)
2844
+ }
2845
+ });
2259
2846
  receiptIds.push(call.receiptId);
2260
2847
  ledger.recordSequenceEvent({
2261
2848
  prospectId: input.prospectId,
@@ -2283,6 +2870,7 @@ function buildFollowUpEmail(opts) {
2283
2870
  const system = loadPrompt(opts.promptName) + signatureDirective();
2284
2871
  const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);
2285
2872
  const proofBlock = socialProofBlock();
2873
+ const firstName = firstNameFrom(ctx.prospect.name);
2286
2874
  const user = [
2287
2875
  `FOUNDER: ${ctx.cfg.founderName}`,
2288
2876
  `PRODUCT: ${ctx.cfg.productOneLiner}`,
@@ -2291,7 +2879,8 @@ function buildFollowUpEmail(opts) {
2291
2879
  `COMPANY: ${ctx.prospect.company ?? "(unknown)"}`,
2292
2880
  ...opts.contextLines,
2293
2881
  ...priorBlock ? ["", priorBlock] : [],
2294
- ...proofBlock ? ["", proofBlock] : []
2882
+ ...proofBlock ? ["", proofBlock] : [],
2883
+ ...firstName ? ["", `PROSPECT_FIRST_NAME: ${firstName}`] : []
2295
2884
  ].join("\n");
2296
2885
  const parsed = tryParseJsonObject((await complete({
2297
2886
  messages: [{
@@ -2385,12 +2974,14 @@ async function runEmailPlay(def, opts) {
2385
2974
  const cfg = loadConfig();
2386
2975
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2387
2976
  const emails = opts.targets.map((t) => def.toEmail(t).trim().toLowerCase());
2388
- const concurrency = new Set(emails).size !== emails.length ? 1 : 3;
2977
+ const concurrency = new Set(emails).size !== emails.length ? 1 : 6;
2389
2978
  return { drafted: await parallelMap(opts.targets, concurrency, async (target) => {
2390
2979
  try {
2391
2980
  const prep = await def.prepare(target, opts.dryRun);
2392
2981
  const proof = socialProofBlock();
2393
- const inputBlock = proof ? `${def.buildInputBlock(target, prep, cfg)}\n\n${proof}` : def.buildInputBlock(target, prep, cfg);
2982
+ let inputBlock = proof ? `${def.buildInputBlock(target, prep, cfg)}\n\n${proof}` : def.buildInputBlock(target, prep, cfg);
2983
+ const firstName = firstNameFrom(def.prospectMeta(target).name ?? null);
2984
+ if (firstName) inputBlock = `${inputBlock}\n\nPROSPECT_FIRST_NAME: ${firstName}`;
2394
2985
  const draft = await draftEmailFromPrompt({
2395
2986
  promptName: def.promptName,
2396
2987
  inputBlock
@@ -2428,7 +3019,7 @@ async function runEmailPlay(def, opts) {
2428
3019
  ...def.errorExtra ?? {}
2429
3020
  };
2430
3021
  }
2431
- }) };
3022
+ }, opts.onProgress ? (_target, result, index) => opts.onProgress?.(index, result) : void 0) };
2432
3023
  }
2433
3024
  /**
2434
3025
  * The common `prepare` body for plays that personalize via `safeEnrich` (cached
@@ -2456,18 +3047,18 @@ async function standardEnrich(opts) {
2456
3047
  }
2457
3048
  //#endregion
2458
3049
  //#region ../../packages/plays/src/accelerator-batch.ts
2459
- const PLAY_NAME$22 = "accelerator-batch";
3050
+ const PLAY_NAME$24 = "accelerator-batch";
2460
3051
  function runAcceleratorBatch(opts) {
2461
3052
  const senderCohortFor = (t) => (t.senderCohort?.trim() || opts.senderCohort || "").trim();
2462
3053
  const offerFor = (t) => t.freeForCohortOffer ?? opts.freeForCohortOffer;
2463
3054
  return runEmailPlay({
2464
- playName: PLAY_NAME$22,
3055
+ playName: PLAY_NAME$24,
2465
3056
  promptName: "accelerator-batch-email",
2466
- maxBodyWords: 100,
3057
+ maxBodyWords: 150,
2467
3058
  enrollCadence: true,
2468
3059
  toEmail: (t) => t.email,
2469
3060
  prepare: (t, dryRun) => standardEnrich({
2470
- playName: PLAY_NAME$22,
3061
+ playName: PLAY_NAME$24,
2471
3062
  enrichInput: {
2472
3063
  ...t.email ? { email: t.email } : {},
2473
3064
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2502,14 +3093,14 @@ function runAcceleratorBatch(opts) {
2502
3093
  }, opts);
2503
3094
  }
2504
3095
  registerSequence({
2505
- playName: PLAY_NAME$22,
3096
+ playName: PLAY_NAME$24,
2506
3097
  steps: [{
2507
3098
  dayOffset: 5,
2508
3099
  channel: "email",
2509
3100
  breakOnReply: true,
2510
3101
  label: "single follow-up + breakup",
2511
3102
  builder: buildFollowUpEmail({
2512
- playName: PLAY_NAME$22,
3103
+ playName: PLAY_NAME$24,
2513
3104
  promptName: "breakup-email",
2514
3105
  contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
2515
3106
  })
@@ -2517,7 +3108,7 @@ registerSequence({
2517
3108
  });
2518
3109
  //#endregion
2519
3110
  //#region ../../packages/plays/src/breakup-revive.ts
2520
- const PLAY_NAME$21 = "breakup-revive";
3111
+ const PLAY_NAME$23 = "breakup-revive";
2521
3112
  async function runBreakupRevive(opts) {
2522
3113
  const cfg = loadConfig();
2523
3114
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
@@ -2538,7 +3129,7 @@ async function runBreakupRevive(opts) {
2538
3129
  });
2539
3130
  const flags = lintEmail(draft.subject, draft.body, 80);
2540
3131
  const send = await sendDraftedEmail({
2541
- playName: PLAY_NAME$21,
3132
+ playName: PLAY_NAME$23,
2542
3133
  to: t.email,
2543
3134
  draft,
2544
3135
  flags,
@@ -2554,7 +3145,8 @@ async function runBreakupRevive(opts) {
2554
3145
  daysCold: t.daysCold,
2555
3146
  lastEventAt: t.lastEventAt
2556
3147
  },
2557
- dryRun: opts.dryRun
3148
+ dryRun: opts.dryRun,
3149
+ allowRecontact: true
2558
3150
  });
2559
3151
  drafted.push({
2560
3152
  prospectEmail: t.email,
@@ -2599,12 +3191,12 @@ function ledgerScanTargets(opts) {
2599
3191
  }
2600
3192
  //#endregion
2601
3193
  //#region ../../packages/plays/src/competitor-switch.ts
2602
- const PLAY_NAME$20 = "competitor-switch";
3194
+ const PLAY_NAME$22 = "competitor-switch";
2603
3195
  function runCompetitorSwitch(opts) {
2604
3196
  return runEmailPlay({
2605
- playName: PLAY_NAME$20,
3197
+ playName: PLAY_NAME$22,
2606
3198
  promptName: "competitor-switch-email",
2607
- maxBodyWords: 100,
3199
+ maxBodyWords: 150,
2608
3200
  enrollCadence: true,
2609
3201
  toEmail: (t) => t.email,
2610
3202
  prepare: async (t, dryRun) => {
@@ -2614,7 +3206,7 @@ function runCompetitorSwitch(opts) {
2614
3206
  ...t.email ? { email: t.email } : {},
2615
3207
  name: t.name,
2616
3208
  companyDomain: emailDomain(t.email)
2617
- }, { playName: PLAY_NAME$20 });
3209
+ }, { playName: PLAY_NAME$22 });
2618
3210
  if (enr.receiptId) receiptIds.push(enr.receiptId);
2619
3211
  const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
2620
3212
  if (!dryRun) {
@@ -2638,7 +3230,7 @@ function runCompetitorSwitch(opts) {
2638
3230
  }
2639
3231
  },
2640
3232
  maxSteps: 12
2641
- }, { playName: PLAY_NAME$20 });
3233
+ }, { playName: PLAY_NAME$22 });
2642
3234
  receiptIds.push(browse.receiptId);
2643
3235
  scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
2644
3236
  }
@@ -2676,14 +3268,14 @@ function runCompetitorSwitch(opts) {
2676
3268
  }, opts);
2677
3269
  }
2678
3270
  registerSequence({
2679
- playName: PLAY_NAME$20,
3271
+ playName: PLAY_NAME$22,
2680
3272
  steps: [{
2681
3273
  dayOffset: 3,
2682
3274
  channel: "email",
2683
3275
  breakOnReply: true,
2684
3276
  label: "value follow-up",
2685
3277
  builder: buildFollowUpEmail({
2686
- playName: PLAY_NAME$20,
3278
+ playName: PLAY_NAME$22,
2687
3279
  promptName: "competitor-switch-followup",
2688
3280
  contextLines: [`PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`]
2689
3281
  })
@@ -2693,7 +3285,7 @@ registerSequence({
2693
3285
  breakOnReply: true,
2694
3286
  label: "breakup",
2695
3287
  builder: buildFollowUpEmail({
2696
- playName: PLAY_NAME$20,
3288
+ playName: PLAY_NAME$22,
2697
3289
  promptName: "breakup-email",
2698
3290
  contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
2699
3291
  })
@@ -2701,13 +3293,13 @@ registerSequence({
2701
3293
  });
2702
3294
  //#endregion
2703
3295
  //#region ../../packages/plays/src/hiring-signal.ts
2704
- const PLAY_NAME$19 = "hiring-signal";
3296
+ const PLAY_NAME$21 = "hiring-signal";
2705
3297
  const NO_HOOK = "(no specific job post phrase scraped)";
2706
3298
  function runHiringSignal(opts) {
2707
3299
  return runEmailPlay({
2708
- playName: PLAY_NAME$19,
3300
+ playName: PLAY_NAME$21,
2709
3301
  promptName: "hiring-signal-email",
2710
- maxBodyWords: 100,
3302
+ maxBodyWords: 150,
2711
3303
  enrollCadence: true,
2712
3304
  errorExtra: { jobPostHook: "(error)" },
2713
3305
  toEmail: (t) => t.email,
@@ -2720,12 +3312,12 @@ function runHiringSignal(opts) {
2720
3312
  const search = await webSearch({
2721
3313
  query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
2722
3314
  maxResults: 5
2723
- }, { playName: PLAY_NAME$19 });
3315
+ }, { playName: PLAY_NAME$21 });
2724
3316
  receiptIds.push(search.receiptId);
2725
3317
  jobUrl = search.result.results[0]?.url;
2726
3318
  }
2727
3319
  if (jobUrl) {
2728
- const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$19 });
3320
+ const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$21 });
2729
3321
  receiptIds.push(read.receiptId);
2730
3322
  const md = read.result.markdown ?? "";
2731
3323
  jobPostHook = (md.match(/(?:About the role|Responsibilities|Requirements|What you[' ]?ll do)[^\n]*\n+([\s\S]{40,300})/i)?.[1] ?? md.slice(0, 400)).replace(/\s+/g, " ").trim();
@@ -2760,14 +3352,14 @@ function runHiringSignal(opts) {
2760
3352
  }, opts);
2761
3353
  }
2762
3354
  registerSequence({
2763
- playName: PLAY_NAME$19,
3355
+ playName: PLAY_NAME$21,
2764
3356
  steps: [{
2765
3357
  dayOffset: 3,
2766
3358
  channel: "email",
2767
3359
  breakOnReply: true,
2768
3360
  label: "value follow-up",
2769
3361
  builder: buildFollowUpEmail({
2770
- playName: PLAY_NAME$19,
3362
+ playName: PLAY_NAME$21,
2771
3363
  promptName: "hiring-signal-followup",
2772
3364
  contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`]
2773
3365
  })
@@ -2777,7 +3369,7 @@ registerSequence({
2777
3369
  breakOnReply: true,
2778
3370
  label: "breakup",
2779
3371
  builder: buildFollowUpEmail({
2780
- playName: PLAY_NAME$19,
3372
+ playName: PLAY_NAME$21,
2781
3373
  promptName: "breakup-email",
2782
3374
  contextLines: [`PLAY: hiring-signal. Final breakup.`]
2783
3375
  })
@@ -2785,15 +3377,15 @@ registerSequence({
2785
3377
  });
2786
3378
  //#endregion
2787
3379
  //#region ../../packages/plays/src/job-change.ts
2788
- const PLAY_NAME$18 = "job-change";
3380
+ const PLAY_NAME$20 = "job-change";
2789
3381
  const jobChangeDef = {
2790
- playName: PLAY_NAME$18,
3382
+ playName: PLAY_NAME$20,
2791
3383
  promptName: "job-change-email",
2792
- maxBodyWords: 100,
3384
+ maxBodyWords: 150,
2793
3385
  enrollCadence: true,
2794
3386
  toEmail: (t) => t.email,
2795
3387
  prepare: (t, dryRun) => standardEnrich({
2796
- playName: PLAY_NAME$18,
3388
+ playName: PLAY_NAME$20,
2797
3389
  enrichInput: {
2798
3390
  ...t.email ? { email: t.email } : {},
2799
3391
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2827,14 +3419,14 @@ function runJobChange(opts) {
2827
3419
  return runEmailPlay(jobChangeDef, opts);
2828
3420
  }
2829
3421
  registerSequence({
2830
- playName: PLAY_NAME$18,
3422
+ playName: PLAY_NAME$20,
2831
3423
  steps: [{
2832
3424
  dayOffset: 5,
2833
3425
  channel: "email",
2834
3426
  breakOnReply: true,
2835
3427
  label: "value follow-up",
2836
3428
  builder: buildFollowUpEmail({
2837
- playName: PLAY_NAME$18,
3429
+ playName: PLAY_NAME$20,
2838
3430
  promptName: "job-change-followup",
2839
3431
  contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
2840
3432
  })
@@ -2844,20 +3436,88 @@ registerSequence({
2844
3436
  breakOnReply: true,
2845
3437
  label: "breakup",
2846
3438
  builder: buildFollowUpEmail({
2847
- playName: PLAY_NAME$18,
3439
+ playName: PLAY_NAME$20,
2848
3440
  promptName: "breakup-email",
2849
3441
  contextLines: [`PLAY: job-change. Sender is closing the file.`]
2850
3442
  })
2851
3443
  }]
2852
3444
  });
2853
3445
  //#endregion
3446
+ //#region ../../packages/plays/src/luma-events.ts
3447
+ const PLAY_NAME$19 = "luma-events";
3448
+ /**
3449
+ * Humanize an ISO date to "tomorrow", "this Tuesday", "next Tuesday", or a
3450
+ * date like "Tue Jun 10". Keeps the prompt input concrete so the LLM doesn't
3451
+ * have to do calendar math (and can't accidentally say "next year").
3452
+ */
3453
+ function humanizeEventDate(iso) {
3454
+ const d = new Date(iso);
3455
+ if (Number.isNaN(d.getTime())) return iso;
3456
+ const now = /* @__PURE__ */ new Date();
3457
+ const days = Math.round((d.getTime() - now.getTime()) / (24 * 3600 * 1e3));
3458
+ if (days < 0) return d.toISOString().slice(0, 10);
3459
+ if (days === 0) return "today";
3460
+ if (days === 1) return "tomorrow";
3461
+ const weekday = d.toLocaleDateString("en-US", { weekday: "long" });
3462
+ if (days <= 6) return `this ${weekday}`;
3463
+ if (days <= 13) return `next ${weekday}`;
3464
+ return d.toLocaleDateString("en-US", {
3465
+ weekday: "short",
3466
+ month: "short",
3467
+ day: "numeric"
3468
+ });
3469
+ }
3470
+ const lumaEventsDef = {
3471
+ playName: PLAY_NAME$19,
3472
+ promptName: "luma-events-email",
3473
+ maxBodyWords: 150,
3474
+ toEmail: (t) => t.email,
3475
+ prepare: (t) => standardEnrich({
3476
+ playName: PLAY_NAME$19,
3477
+ enrichInput: {
3478
+ ...t.email ? { email: t.email } : {},
3479
+ name: t.name,
3480
+ companyDomain: emailDomain(t.email)
3481
+ },
3482
+ enrichSlice: 3500
3483
+ }),
3484
+ buildInputBlock: (t, prep, cfg) => [
3485
+ `FOUNDER: ${cfg.founderName}`,
3486
+ `PRODUCT: ${cfg.productOneLiner}`,
3487
+ `PROSPECT: ${t.name}${t.company ? ` at ${t.company}` : ""}`,
3488
+ `ATTENDEE BIO/ROLE: ${t.attendeeBio ?? "(none)"}`,
3489
+ `EVENT TITLE: ${t.eventTitle}`,
3490
+ `EVENT CITY: ${t.eventCity}`,
3491
+ `EVENT DATE: ${humanizeEventDate(t.eventDate)} (${t.eventDate})`,
3492
+ `EVENT URL: ${t.eventUrl}`,
3493
+ `YOUR EDGE: ${t.yourEdge}`,
3494
+ `DOSSIER:\n${prep.dossier || "(dry-run)"}`
3495
+ ].join("\n"),
3496
+ prospectMeta: (t) => ({
3497
+ name: t.name,
3498
+ email: t.email,
3499
+ company: t.company ?? null,
3500
+ linkedin_url: t.linkedinUrl ?? null,
3501
+ phone: t.phone ?? null,
3502
+ source: "luma-events"
3503
+ }),
3504
+ metadata: (t) => ({
3505
+ eventTitle: t.eventTitle,
3506
+ eventUrl: t.eventUrl,
3507
+ eventDate: t.eventDate
3508
+ })
3509
+ };
3510
+ function runLumaEvents(opts) {
3511
+ return runEmailPlay(lumaEventsDef, opts);
3512
+ }
3513
+ //#endregion
2854
3514
  //#region ../../packages/plays/src/podcast-guest.ts
2855
- const PLAY_NAME$17 = "podcast-guest";
3515
+ const PLAY_NAME$18 = "podcast-guest";
2856
3516
  function runPodcastGuest(opts) {
2857
3517
  return runEmailPlay({
2858
- playName: PLAY_NAME$17,
3518
+ playName: PLAY_NAME$18,
2859
3519
  promptName: "podcast-guest-email",
2860
- maxBodyWords: 90,
3520
+ maxBodyWords: 150,
2861
3521
  enrollCadence: true,
2862
3522
  toEmail: (t) => t.email,
2863
3523
  prepare: async (t, dryRun) => {
@@ -2867,7 +3527,7 @@ function runPodcastGuest(opts) {
2867
3527
  const s = await webSearch({
2868
3528
  query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
2869
3529
  maxResults: 3
2870
- }, { playName: PLAY_NAME$17 });
3530
+ }, { playName: PLAY_NAME$18 });
2871
3531
  receiptIds.push(s.receiptId);
2872
3532
  dossier = s.result.results.slice(0, 2).map((r) => `- ${r.title}: ${r.description}`).join("\n");
2873
3533
  }
@@ -2901,20 +3561,20 @@ function runPodcastGuest(opts) {
2901
3561
  }, opts);
2902
3562
  }
2903
3563
  registerSequence({
2904
- playName: PLAY_NAME$17,
3564
+ playName: PLAY_NAME$18,
2905
3565
  steps: []
2906
3566
  });
2907
3567
  //#endregion
2908
3568
  //#region ../../packages/plays/src/post-funding.ts
2909
- const PLAY_NAME$16 = "post-funding";
3569
+ const PLAY_NAME$17 = "post-funding";
2910
3570
  const postFundingDef = {
2911
- playName: PLAY_NAME$16,
3571
+ playName: PLAY_NAME$17,
2912
3572
  promptName: "post-funding-email",
2913
- maxBodyWords: 100,
3573
+ maxBodyWords: 150,
2914
3574
  enrollCadence: true,
2915
3575
  toEmail: (t) => t.email,
2916
3576
  prepare: (t, dryRun) => standardEnrich({
2917
- playName: PLAY_NAME$16,
3577
+ playName: PLAY_NAME$17,
2918
3578
  enrichInput: {
2919
3579
  ...t.email ? { email: t.email } : {},
2920
3580
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2950,14 +3610,14 @@ function runPostFunding(opts) {
2950
3610
  return runEmailPlay(postFundingDef, opts);
2951
3611
  }
2952
3612
  registerSequence({
2953
- playName: PLAY_NAME$16,
3613
+ playName: PLAY_NAME$17,
2954
3614
  steps: [{
2955
3615
  dayOffset: 9,
2956
3616
  channel: "email",
2957
3617
  breakOnReply: true,
2958
3618
  label: "case-study follow-up",
2959
3619
  builder: buildFollowUpEmail({
2960
- playName: PLAY_NAME$16,
3620
+ playName: PLAY_NAME$17,
2961
3621
  promptName: "post-funding-followup",
2962
3622
  contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
2963
3623
  })
@@ -2967,7 +3627,7 @@ registerSequence({
2967
3627
  breakOnReply: true,
2968
3628
  label: "breakup",
2969
3629
  builder: buildFollowUpEmail({
2970
- playName: PLAY_NAME$16,
3630
+ playName: PLAY_NAME$17,
2971
3631
  promptName: "breakup-email",
2972
3632
  contextLines: [`PLAY: post-funding.`]
2973
3633
  })
@@ -2975,14 +3635,15 @@ registerSequence({
2975
3635
  });
2976
3636
  //#endregion
2977
3637
  //#region ../../packages/plays/src/repo-interest.ts
2978
- const PLAY_NAME$15 = "repo-interest";
3638
+ const PLAY_NAME$16 = "repo-interest";
2979
3639
  const repoInterestDef = {
2980
- playName: PLAY_NAME$15,
3640
+ playName: PLAY_NAME$16,
2981
3641
  promptName: "repo-interest-email",
2982
- maxBodyWords: 90,
3642
+ maxBodyWords: 150,
3643
+ enrollCadence: true,
2983
3644
  toEmail: (t) => t.email,
2984
3645
  prepare: (t) => standardEnrich({
2985
- playName: PLAY_NAME$15,
3646
+ playName: PLAY_NAME$16,
2986
3647
  enrichInput: {
2987
3648
  ...t.email ? { email: t.email } : {},
2988
3649
  name: t.name,
@@ -2996,6 +3657,8 @@ const repoInterestDef = {
2996
3657
  `PROSPECT: ${t.name} at ${t.company}`,
2997
3658
  `STARRED REPO: ${t.repoLabel ?? t.repo}`,
2998
3659
  `YOUR EDGE: ${t.yourEdge}`,
3660
+ ...t.repoEdge ? [`WHY THIS REPO IS NOTABLE (peer nod + how your offer fits — see prompt): ${t.repoEdge}`] : [],
3661
+ ...t.candidateRepos && t.candidateRepos.length > 0 ? [`CANDIDATE REPOS (their public work, sorted by recent push):`, ...t.candidateRepos.map((r) => `- ${r.name}${r.language ? ` [${r.language}]` : ""}: ${r.description ?? "(no description)"}`)] : [],
2999
3662
  `DOSSIER:\n${prep.dossier || "(dry-run)"}`
3000
3663
  ].join("\n"),
3001
3664
  prospectMeta: (t) => ({
@@ -3011,16 +3674,30 @@ const repoInterestDef = {
3011
3674
  function runRepoInterest(opts) {
3012
3675
  return runEmailPlay(repoInterestDef, opts);
3013
3676
  }
3677
+ registerSequence({
3678
+ playName: PLAY_NAME$16,
3679
+ steps: [{
3680
+ dayOffset: 3,
3681
+ channel: "email",
3682
+ breakOnReply: true,
3683
+ label: "value follow-up",
3684
+ builder: buildFollowUpEmail({
3685
+ playName: PLAY_NAME$16,
3686
+ promptName: "repo-interest-followup",
3687
+ contextLines: [`PLAY: repo-interest. Day-3 soft nudge after the peer-to-peer intro about a repo they starred.`]
3688
+ })
3689
+ }]
3690
+ });
3014
3691
  //#endregion
3015
3692
  //#region ../../packages/plays/src/show-hn.ts
3016
- const PLAY_NAME$14 = "show-hn";
3693
+ const PLAY_NAME$15 = "show-hn";
3017
3694
  const showHnDef = {
3018
- playName: PLAY_NAME$14,
3695
+ playName: PLAY_NAME$15,
3019
3696
  promptName: "show-hn-email",
3020
- maxBodyWords: 90,
3697
+ maxBodyWords: 150,
3021
3698
  toEmail: (t) => t.founderEmail,
3022
3699
  prepare: (t, dryRun) => standardEnrich({
3023
- playName: PLAY_NAME$14,
3700
+ playName: PLAY_NAME$15,
3024
3701
  enrichInput: {
3025
3702
  email: t.founderEmail,
3026
3703
  name: t.founderName
@@ -3058,15 +3735,15 @@ function extractCompany(title) {
3058
3735
  }
3059
3736
  //#endregion
3060
3737
  //#region ../../packages/plays/src/stack-consolidation.ts
3061
- const PLAY_NAME$13 = "stack-consolidation";
3738
+ const PLAY_NAME$14 = "stack-consolidation";
3062
3739
  const stackConsolidationDef = {
3063
- playName: PLAY_NAME$13,
3740
+ playName: PLAY_NAME$14,
3064
3741
  promptName: "stack-consolidation-email",
3065
- maxBodyWords: 100,
3742
+ maxBodyWords: 150,
3066
3743
  enrollCadence: true,
3067
3744
  toEmail: (t) => t.email,
3068
3745
  prepare: (t) => standardEnrich({
3069
- playName: PLAY_NAME$13,
3746
+ playName: PLAY_NAME$14,
3070
3747
  enrichInput: {
3071
3748
  ...t.email ? { email: t.email } : {},
3072
3749
  name: t.name,
@@ -3099,14 +3776,14 @@ function runStackConsolidation(opts) {
3099
3776
  return runEmailPlay(stackConsolidationDef, opts);
3100
3777
  }
3101
3778
  registerSequence({
3102
- playName: PLAY_NAME$13,
3779
+ playName: PLAY_NAME$14,
3103
3780
  steps: [{
3104
3781
  dayOffset: 3,
3105
3782
  channel: "email",
3106
3783
  breakOnReply: true,
3107
3784
  label: "value follow-up",
3108
3785
  builder: buildFollowUpEmail({
3109
- playName: PLAY_NAME$13,
3786
+ playName: PLAY_NAME$14,
3110
3787
  promptName: "stack-consolidation-followup",
3111
3788
  contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
3112
3789
  })
@@ -3116,7 +3793,7 @@ registerSequence({
3116
3793
  breakOnReply: true,
3117
3794
  label: "breakup",
3118
3795
  builder: buildFollowUpEmail({
3119
- playName: PLAY_NAME$13,
3796
+ playName: PLAY_NAME$14,
3120
3797
  promptName: "breakup-email",
3121
3798
  contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
3122
3799
  })
@@ -3124,50 +3801,59 @@ registerSequence({
3124
3801
  });
3125
3802
  //#endregion
3126
3803
  //#region ../../packages/plays/src/registry.ts
3127
- /**
3128
- * Single source of truth mapping a play name → its runner. Both the server's
3129
- * `/api/run` dispatch and the queue drainer look plays up here, so adding a
3130
- * play means registering it once (its file + this table) instead of editing
3131
- * two parallel switch statements that silently drifted apart.
3132
- */
3804
+ const progressOpt = (o) => o.onProgress ? { onProgress: o.onProgress } : {};
3133
3805
  const PLAYS = {
3134
3806
  "show-hn": { run: (o) => runShowHn({
3135
3807
  dryRun: o.dryRun,
3136
- targets: o.targets
3808
+ targets: o.targets,
3809
+ ...progressOpt(o)
3137
3810
  }) },
3138
3811
  "job-change": { run: (o) => runJobChange({
3139
3812
  dryRun: o.dryRun,
3140
- targets: o.targets
3813
+ targets: o.targets,
3814
+ ...progressOpt(o)
3141
3815
  }) },
3142
3816
  "post-funding": { run: (o) => runPostFunding({
3143
3817
  dryRun: o.dryRun,
3144
- targets: o.targets
3818
+ targets: o.targets,
3819
+ ...progressOpt(o)
3145
3820
  }) },
3146
3821
  "accelerator-batch": { run: (o) => runAcceleratorBatch({
3147
3822
  dryRun: o.dryRun,
3148
3823
  targets: o.targets,
3149
3824
  ...o.senderCohort ? { senderCohort: o.senderCohort } : {},
3150
- ...o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {}
3825
+ ...o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {},
3826
+ ...progressOpt(o)
3151
3827
  }) },
3152
3828
  "hiring-signal": { run: (o) => runHiringSignal({
3153
3829
  dryRun: o.dryRun,
3154
- targets: o.targets
3830
+ targets: o.targets,
3831
+ ...progressOpt(o)
3155
3832
  }) },
3156
3833
  "podcast-guest": { run: (o) => runPodcastGuest({
3157
3834
  dryRun: o.dryRun,
3158
- targets: o.targets
3835
+ targets: o.targets,
3836
+ ...progressOpt(o)
3159
3837
  }) },
3160
3838
  "competitor-switch": { run: (o) => runCompetitorSwitch({
3161
3839
  dryRun: o.dryRun,
3162
- targets: o.targets
3840
+ targets: o.targets,
3841
+ ...progressOpt(o)
3163
3842
  }) },
3164
3843
  "stack-consolidation": { run: (o) => runStackConsolidation({
3165
3844
  dryRun: o.dryRun,
3166
- targets: o.targets
3845
+ targets: o.targets,
3846
+ ...progressOpt(o)
3167
3847
  }) },
3168
3848
  "repo-interest": { run: (o) => runRepoInterest({
3169
3849
  dryRun: o.dryRun,
3170
- targets: o.targets
3850
+ targets: o.targets,
3851
+ ...progressOpt(o)
3852
+ }) },
3853
+ "luma-events": { run: (o) => runLumaEvents({
3854
+ dryRun: o.dryRun,
3855
+ targets: o.targets,
3856
+ ...progressOpt(o)
3171
3857
  }) },
3172
3858
  "breakup-revive": { run: (o) => runBreakupRevive({
3173
3859
  dryRun: o.dryRun,
@@ -3179,16 +3865,16 @@ function isSupportedPlay(name) {
3179
3865
  }
3180
3866
  //#endregion
3181
3867
  //#region ../../packages/plays/src/demo-no-show.ts
3182
- const PLAY_NAME$12 = "demo-no-show";
3868
+ const PLAY_NAME$13 = "demo-no-show";
3183
3869
  registerSequence({
3184
- playName: PLAY_NAME$12,
3870
+ playName: PLAY_NAME$13,
3185
3871
  steps: [{
3186
3872
  dayOffset: 3,
3187
3873
  channel: "email",
3188
3874
  breakOnReply: true,
3189
3875
  label: "day-3 follow-up",
3190
3876
  builder: buildFollowUpEmail({
3191
- playName: PLAY_NAME$12,
3877
+ playName: PLAY_NAME$13,
3192
3878
  promptName: "demo-no-show-followup",
3193
3879
  contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`]
3194
3880
  })
@@ -3197,16 +3883,21 @@ registerSequence({
3197
3883
  //#endregion
3198
3884
  //#region src/api/cadences.ts
3199
3885
  /**
3200
- * In-process tracker of cadence steps that have a fire-and-forget send in
3201
- * flight. Populated by sendCadenceStepRoute + sendCadenceBatchRoute when
3202
- * they kick off the background SDK send (~2 min per row), cleared per-row
3203
- * as each send settles. Used by `toView` to surface `isSending: true` so
3204
- * /cadences can visually mark in-flight rows AND gate them out of the
3205
- * sendable-rows count. Lost on server restart (acceptable — in-flight SDK
3206
- * calls die with the process anyway).
3886
+ * In-flight cadence sends are tracked on the cadence_state row's
3887
+ * `sending_started_at` column (claimed atomically by
3888
+ * `ledger.claimCadenceSendingMarker` before the background SDK send fires,
3889
+ * cleared on success via `advanceCadence` and on failure in the catch).
3890
+ *
3891
+ * History: this used to be an in-memory Set. Under `bun --watch` a file save
3892
+ * killed the background promise mid-SDK-call, leaving the founder with no
3893
+ * "sending" UI signal AND no email delivered. The DB-backed marker survives
3894
+ * restarts; the cold-boot sweeper recovers stranded rows.
3895
+ *
3896
+ * Stale-cutoff window: a fresh Send click can reclaim a marker older than
3897
+ * this. Set to MAX_SEND_AGE_MS to match the cold-boot sweeper threshold —
3898
+ * the only way the marker is older is if a previous send was killed.
3207
3899
  */
3208
- const inFlightSends = /* @__PURE__ */ new Set();
3209
- const inFlightKey = (prospectId, playName) => `${prospectId}|${playName}`;
3900
+ const MAX_SEND_AGE_MS = 300 * 1e3;
3210
3901
  function buildPlayInfoMap(rows) {
3211
3902
  const map = /* @__PURE__ */ new Map();
3212
3903
  for (const row of rows) {
@@ -3267,7 +3958,7 @@ function toView$3(row, priorByKey, playInfo) {
3267
3958
  nextStepIsBreakup: next?.isBreakup ?? false,
3268
3959
  followupCount,
3269
3960
  priorSteps,
3270
- isSending: inFlightSends.has(inFlightKey(row.prospect_id, row.play_name))
3961
+ isSending: row.sending_started_at != null
3271
3962
  };
3272
3963
  }
3273
3964
  function viewsForRows(rows) {
@@ -3279,9 +3970,21 @@ function viewsForRows(rows) {
3279
3970
  return rows.map((r) => toView$3(r, priorByKey, playInfo));
3280
3971
  }
3281
3972
  function listCadences(req) {
3282
- const all = new URL(req.url).searchParams.get("all") === "1";
3973
+ const url = new URL(req.url);
3974
+ const all = url.searchParams.get("all") === "1";
3975
+ const sinceRunRaw = url.searchParams.get("sinceRun");
3976
+ const sinceRunId = sinceRunRaw && Number.isFinite(Number.parseInt(sinceRunRaw, 10)) ? Number.parseInt(sinceRunRaw, 10) : null;
3283
3977
  const ledger = getLedger();
3284
- return jsonResponse({ cadences: viewsForRows(all ? ledger.listAllCadences() : ledger.listActiveCadences()) }, 200, req);
3978
+ let rows = all ? ledger.listAllCadences() : ledger.listActiveCadences();
3979
+ if (sinceRunId != null) {
3980
+ const run = ledger.getRun(sinceRunId);
3981
+ const wantedEmails = new Set((run?.prospectEmails ?? []).map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0));
3982
+ rows = rows.filter((r) => {
3983
+ const email = r.prospect_email?.trim().toLowerCase();
3984
+ return email != null && wantedEmails.has(email);
3985
+ });
3986
+ }
3987
+ return jsonResponse({ cadences: viewsForRows(rows) }, 200, req);
3285
3988
  }
3286
3989
  function getCadence(req, params) {
3287
3990
  const id = Number.parseInt(params["id"] ?? "", 10);
@@ -3336,15 +4039,23 @@ async function previewCadenceStepRoute(req, params) {
3336
4039
  }
3337
4040
  }
3338
4041
  async function sendCadenceStepRoute(req, params) {
4042
+ if (isDraining()) return jsonResponse({ error: "server restarting — retry in a moment" }, 503, req);
3339
4043
  const parsed = parseProspectAndPlay(req, params);
3340
4044
  if (parsed instanceof Response) return parsed;
4045
+ const ledger = getLedger();
3341
4046
  try {
3342
- if (!getLedger().getCadenceDraft(parsed)) return jsonResponse({ error: "no persisted preview — click Preview first" }, 409, req);
4047
+ if (!ledger.getCadenceDraft(parsed)) return jsonResponse({ error: "no persisted preview — click Preview first" }, 409, req);
3343
4048
  } catch (err) {
3344
4049
  return jsonResponse({ error: err.message ?? "send failed" }, 500, req);
3345
4050
  }
3346
- const key = inFlightKey(parsed.prospectId, parsed.playName);
3347
- inFlightSends.add(key);
4051
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
4052
+ const staleCutoffIso = new Date(Date.now() - MAX_SEND_AGE_MS).toISOString();
4053
+ if (!ledger.claimCadenceSendingMarker({
4054
+ prospectId: parsed.prospectId,
4055
+ playName: parsed.playName,
4056
+ startedAtIso: nowIso,
4057
+ staleCutoffIso
4058
+ })) return jsonResponse({ error: "already sending — wait for the in-flight send to complete" }, 409, req);
3348
4059
  (async () => {
3349
4060
  try {
3350
4061
  await sendCadenceStep(parsed);
@@ -3354,8 +4065,9 @@ async function sendCadenceStepRoute(req, params) {
3354
4065
  play_name: parsed.playName,
3355
4066
  message_120: (err?.message ?? "").slice(0, 120)
3356
4067
  }, "error");
3357
- } finally {
3358
- inFlightSends.delete(key);
4068
+ try {
4069
+ ledger.clearCadenceSendingMarker(parsed);
4070
+ } catch {}
3359
4071
  }
3360
4072
  })();
3361
4073
  return jsonResponse({ accepted: true }, 202, req);
@@ -3385,21 +4097,36 @@ async function previewCadenceBatchRoute(req) {
3385
4097
  return jsonResponse({ results: await previewCadenceStepBatch(itemsOrErr) }, 200, req);
3386
4098
  }
3387
4099
  async function sendCadenceBatchRoute(req) {
4100
+ if (isDraining()) return jsonResponse({ error: "server restarting — retry in a moment" }, 503, req);
3388
4101
  const itemsOrErr = await parseBatchItems(req);
3389
4102
  if (itemsOrErr instanceof Response) return itemsOrErr;
3390
4103
  const items = itemsOrErr;
3391
- for (const item of items) inFlightSends.add(inFlightKey(item.prospectId, item.playName));
4104
+ const ledger = getLedger();
4105
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
4106
+ const staleCutoffIso = new Date(Date.now() - MAX_SEND_AGE_MS).toISOString();
4107
+ const claimed = [];
4108
+ for (const item of items) if (ledger.claimCadenceSendingMarker({
4109
+ prospectId: item.prospectId,
4110
+ playName: item.playName,
4111
+ startedAtIso: nowIso,
4112
+ staleCutoffIso
4113
+ })) claimed.push(item);
4114
+ if (claimed.length === 0) return jsonResponse({ error: "no claimable rows — all selected are already sending" }, 409, req);
3392
4115
  (async () => {
3393
4116
  try {
3394
- await sendCadenceStepBatch(items, (item) => {
3395
- inFlightSends.delete(inFlightKey(item.prospectId, item.playName));
4117
+ await sendCadenceStepBatch(claimed, (item) => {
4118
+ try {
4119
+ ledger.clearCadenceSendingMarker(item);
4120
+ } catch {}
3396
4121
  });
3397
4122
  } catch (err) {
3398
- for (const item of items) inFlightSends.delete(inFlightKey(item.prospectId, item.playName));
4123
+ for (const item of claimed) try {
4124
+ ledger.clearCadenceSendingMarker(item);
4125
+ } catch {}
3399
4126
  logEvent("cadence.batch.failed", { message_120: (err?.message ?? "").slice(0, 120) }, "error");
3400
4127
  }
3401
4128
  })();
3402
- return jsonResponse({ accepted: items.length }, 202, req);
4129
+ return jsonResponse({ accepted: claimed.length }, 202, req);
3403
4130
  }
3404
4131
  //#endregion
3405
4132
  //#region src/api/receipts.ts
@@ -3558,6 +4285,10 @@ const PLAY_CATALOG = [
3558
4285
  name: "repo-interest",
3559
4286
  cli: "oneshot-gtm find watch # fed by the github-stars finder (adjacent repos), drained from /queue"
3560
4287
  },
4288
+ {
4289
+ name: "luma-events",
4290
+ cli: "oneshot-gtm find watch # fed by the luma-events finder (publicly-visible attendees), drained from /queue"
4291
+ },
3561
4292
  {
3562
4293
  name: "hiring-signal",
3563
4294
  cli: "oneshot-gtm motion hiring-signal --target ./examples/hiring-signal.json"
@@ -3781,7 +4512,7 @@ function mergeString(incoming, current) {
3781
4512
  }
3782
4513
  //#endregion
3783
4514
  //#region src/api/derive-icp.ts
3784
- const PLAY_NAME$11 = "config:icp";
4515
+ const PLAY_NAME$12 = "config:icp";
3785
4516
  async function deriveIcpRoute(req) {
3786
4517
  startRun();
3787
4518
  let body = {};
@@ -3800,7 +4531,7 @@ async function deriveIcpRoute(req) {
3800
4531
  const readStartedAt = Date.now();
3801
4532
  logEvent("derive_icp.read.start", { host });
3802
4533
  try {
3803
- const read = await webRead({ url }, { playName: PLAY_NAME$11 });
4534
+ const read = await webRead({ url }, { playName: PLAY_NAME$12 });
3804
4535
  markdown = (read.result.markdown ?? "").trim();
3805
4536
  const c = read.result.cost;
3806
4537
  if (typeof c === "number") costUsd += c;
@@ -3917,17 +4648,29 @@ async function icpFilter(input) {
3917
4648
  icp: input.icp,
3918
4649
  candidate: input.candidate
3919
4650
  });
3920
- const decision = parseIcpJson((await complete({
3921
- messages: [{
3922
- role: "system",
3923
- content: system
3924
- }, {
3925
- role: "user",
3926
- content: user
3927
- }],
3928
- temperature: .1,
3929
- maxTokens: 200
3930
- })).content);
4651
+ let decision;
4652
+ try {
4653
+ decision = parseIcpJson((await complete({
4654
+ messages: [{
4655
+ role: "system",
4656
+ content: system
4657
+ }, {
4658
+ role: "user",
4659
+ content: user
4660
+ }],
4661
+ temperature: .1,
4662
+ maxTokens: 200
4663
+ })).content);
4664
+ } catch (err) {
4665
+ logEvent("error.swallowed", {
4666
+ kind: "icp-filter",
4667
+ message_120: (err.message ?? "").slice(0, 120)
4668
+ }, "warn");
4669
+ return {
4670
+ match: null,
4671
+ reason: "icp classifier unavailable"
4672
+ };
4673
+ }
3931
4674
  logEvent("icp.decision", {
3932
4675
  match: decision.match,
3933
4676
  reason_120: decision.reason.slice(0, 120),
@@ -3937,22 +4680,33 @@ async function icpFilter(input) {
3937
4680
  }
3938
4681
  function parseIcpJson(raw) {
3939
4682
  const parsed = tryParseJsonObject(raw, {});
4683
+ if (typeof parsed.match !== "boolean") return {
4684
+ match: null,
4685
+ reason: "icp classifier malformed response"
4686
+ };
3940
4687
  return {
3941
- match: parsed.match === true,
4688
+ match: parsed.match,
3942
4689
  reason: typeof parsed.reason === "string" ? parsed.reason : "no reason given"
3943
4690
  };
3944
4691
  }
3945
4692
  //#endregion
3946
4693
  //#region ../../packages/find/src/_dedupe.ts
3947
4694
  /**
3948
- * True if this (play, dedupe-key) pair is already in the queue
3949
- * OR a prospect with the same email is already known.
4695
+ * True if this (play, dedupe-key) pair is already in the queue,
4696
+ * OR a prospect with the same email is already known,
4697
+ * OR the same email is already pending in the queue under ANOTHER play
4698
+ * (cross-play dedup — don't queue + enrich someone a different play already
4699
+ * surfaced and is about to email).
4700
+ *
4701
+ * The email-based checks are gated on `prospectEmail`, so callers that pass
4702
+ * `undefined` (breakup-revive, by design) still bypass them to re-engage.
3950
4703
  */
3951
4704
  function isDuplicate(opts) {
3952
4705
  const ledger = getLedger();
3953
4706
  if (ledger.isQueueDuplicate(opts.playName, opts.dedupeKey)) return true;
3954
4707
  if (opts.prospectEmail) {
3955
4708
  if (ledger.findProspectByEmail(opts.prospectEmail)) return true;
4709
+ if (ledger.isEmailPendingInQueue(opts.prospectEmail)) return true;
3956
4710
  }
3957
4711
  return false;
3958
4712
  }
@@ -4138,6 +4892,144 @@ function shouldSkipFindEmail(input) {
4138
4892
  return { ok: true };
4139
4893
  }
4140
4894
  //#endregion
4895
+ //#region ../../packages/find/src/_sdk-safe.ts
4896
+ /**
4897
+ * Per-candidate-safe wrappers for the two job-based contact-resolution SDK calls.
4898
+ *
4899
+ * Finders process candidates concurrently via `parallelMap` (errors propagate
4900
+ * through Promise.all) or in sequential loops. An unguarded throw from one
4901
+ * candidate's `findEmail`/`verifyEmail` — e.g. a OneShot backend job timeout —
4902
+ * rejects the whole batch and aborts the entire trigger run. These wrappers
4903
+ * swallow the throw, log `error.swallowed`, and return a graceful "not found /
4904
+ * not deliverable" sentinel so the caller's existing drop branch handles just
4905
+ * that candidate and the run continues. Same pattern as `enrichVerifiedContact`
4906
+ * (_enrich.ts) and `findLinkedInUrl` (_linkedin.ts). The full `CallContext` is
4907
+ * forwarded unchanged, so audit/decisionContext metadata is preserved.
4908
+ */
4909
+ function swallow(ctx, call, err) {
4910
+ logEvent("error.swallowed", {
4911
+ kind: `${ctx.playName}.${call}`,
4912
+ message_120: (err.message ?? "").slice(0, 120)
4913
+ }, "warn");
4914
+ }
4915
+ /** findEmail that never throws — a failure resolves to `found: false` (drop). */
4916
+ async function safeFindEmail(input, ctx) {
4917
+ try {
4918
+ return await findEmail(input, ctx);
4919
+ } catch (err) {
4920
+ swallow(ctx, "find_email", err);
4921
+ return {
4922
+ result: {
4923
+ status: "error",
4924
+ email: null,
4925
+ found: false,
4926
+ cost: 0
4927
+ },
4928
+ receiptId: 0
4929
+ };
4930
+ }
4931
+ }
4932
+ /** verifyEmail that never throws — a failure resolves to `deliverable: false` (drop). */
4933
+ async function safeVerifyEmail(input, ctx) {
4934
+ try {
4935
+ return await verifyEmail(input, ctx);
4936
+ } catch (err) {
4937
+ swallow(ctx, "verify_email", err);
4938
+ return {
4939
+ result: {
4940
+ status: "error",
4941
+ email: input.email,
4942
+ valid: false,
4943
+ deliverable: false,
4944
+ catch_all: false,
4945
+ disposable: false,
4946
+ cost: 0
4947
+ },
4948
+ receiptId: 0
4949
+ };
4950
+ }
4951
+ }
4952
+ //#endregion
4953
+ //#region ../../packages/find/src/_contact.ts
4954
+ /**
4955
+ * The prescreen → findEmail → dedupe → verify spine shared by every enqueueing
4956
+ * finder. Extracted so the per-candidate isolation (safeFindEmail/safeVerifyEmail
4957
+ * never throw) and the dedupe-before-verify ordering live in one place instead
4958
+ * of being re-implemented (and drifting) in each finder.
4959
+ *
4960
+ * Boundary: this owns email resolution + verification only. Downstream steps
4961
+ * (enrichVerifiedContact, findLinkedInUrl, webRead, enqueue) stay in the caller
4962
+ * because they vary too much between finders.
4963
+ *
4964
+ * - `knownEmail`: when the caller already has a usable email (a public profile
4965
+ * email, or one surfaced by LinkedIn enrichment), pass it to skip the
4966
+ * prescreen + findEmail entirely.
4967
+ * - `companyDomain`: required when `knownEmail` is absent (the findEmail input).
4968
+ * - `isDuplicate`: called with the resolved email BEFORE verify, so a
4969
+ * cross-table duplicate is dropped without paying for a verify call. Dedupe
4970
+ * stays caller-owned (each finder has its own `dedupeKey`).
4971
+ * - `decisionContext`: threaded to both findEmail and verify as audit metadata.
4972
+ */
4973
+ async function resolveAndVerifyContact(args) {
4974
+ const ctx = { playName: args.playName };
4975
+ if (args.decisionContext) ctx.decisionContext = args.decisionContext;
4976
+ let costUsd = 0;
4977
+ let email;
4978
+ let fullName = args.fullName;
4979
+ if (args.knownEmail) email = args.knownEmail;
4980
+ else {
4981
+ if (!args.companyDomain) return {
4982
+ ok: false,
4983
+ reason: "no-domain",
4984
+ costUsd
4985
+ };
4986
+ const skip = shouldSkipFindEmail({
4987
+ fullName: args.fullName,
4988
+ companyDomain: args.companyDomain
4989
+ });
4990
+ if (!skip.ok) {
4991
+ logEvent("finder.skipped_findemail", {
4992
+ name: args.playName,
4993
+ reason: skip.reason
4994
+ }, "info");
4995
+ return {
4996
+ ok: false,
4997
+ reason: "prescreen",
4998
+ costUsd
4999
+ };
5000
+ }
5001
+ const findInput = { companyDomain: args.companyDomain };
5002
+ if (args.fullName) findInput.fullName = args.fullName;
5003
+ const found = await safeFindEmail(findInput, ctx);
5004
+ costUsd += found.result.cost ?? 0;
5005
+ if (!found.result.found || !found.result.email) return {
5006
+ ok: false,
5007
+ reason: "not-found",
5008
+ costUsd
5009
+ };
5010
+ email = found.result.email;
5011
+ fullName = found.result.full_name ?? args.fullName;
5012
+ }
5013
+ if (args.isDuplicate?.(email)) return {
5014
+ ok: false,
5015
+ reason: "duplicate",
5016
+ costUsd
5017
+ };
5018
+ const verified = await safeVerifyEmail({ email }, ctx);
5019
+ costUsd += verified.result.cost ?? 0;
5020
+ if (!verified.result.deliverable) return {
5021
+ ok: false,
5022
+ reason: "undeliverable",
5023
+ costUsd
5024
+ };
5025
+ return {
5026
+ ok: true,
5027
+ email,
5028
+ fullName,
5029
+ costUsd
5030
+ };
5031
+ }
5032
+ //#endregion
4141
5033
  //#region ../../packages/find/src/_linkedin.ts
4142
5034
  /**
4143
5035
  * Shared LinkedIn / phone capture helpers used across all finders. Centralises:
@@ -4148,7 +5040,7 @@ function shouldSkipFindEmail(input) {
4148
5040
  * the founder sees these signals in /queue review and the prospect row carries
4149
5041
  * them after drain.
4150
5042
  */
4151
- const PLAY_NAME$10 = "linkedin-lookup";
5043
+ const PLAY_NAME$11 = "linkedin-lookup";
4152
5044
  /** Match `linkedin.com/in/<slug>` profile URLs. The slug class is permissive
4153
5045
  * enough to cover URL-encoded unicode slugs (e.g. `%E7%8E%8B`) which LinkedIn
4154
5046
  * does serve for non-Latin display names. */
@@ -4195,7 +5087,7 @@ async function findLinkedInUrl(args) {
4195
5087
  const search = await webSearch({
4196
5088
  query,
4197
5089
  maxResults: 5
4198
- }, { playName: PLAY_NAME$10 });
5090
+ }, { playName: PLAY_NAME$11 });
4199
5091
  args.accumCost(search.result.cost ?? 0);
4200
5092
  for (const r of search.result.results ?? []) {
4201
5093
  const url = typeof r.url === "string" ? r.url : "";
@@ -4252,6 +5144,7 @@ function extractFirstPhone(source) {
4252
5144
  }
4253
5145
  //#endregion
4254
5146
  //#region ../../packages/find/src/_enrich.ts
5147
+ const ENRICH_CACHE_TTL_MS = 720 * 3600 * 1e3;
4255
5148
  /**
4256
5149
  * Always-on post-verify enrichment. Called by every enqueueing finder
4257
5150
  * AFTER verifyEmail succeeds + BEFORE enqueueTarget. Reads phone +
@@ -4269,8 +5162,32 @@ function extractFirstPhone(source) {
4269
5162
  * Path B' enrichProfile call in `_repo-pipeline.ts`.
4270
5163
  */
4271
5164
  async function enrichVerifiedContact(email, opts) {
5165
+ const ledger = getLedger();
5166
+ const key = email.trim().toLowerCase();
5167
+ try {
5168
+ const cached = ledger.getCachedEnrichment(key);
5169
+ if (cached && Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS) try {
5170
+ const profile = JSON.parse(cached.result_json).profile ?? null;
5171
+ const linkedinRaw = profile?.linkedin_url ?? null;
5172
+ return {
5173
+ phone: extractFirstPhone(profile),
5174
+ linkedinUrl: isLinkedInProfileUrl(linkedinRaw) ? linkedinRaw : null,
5175
+ costUsd: 0,
5176
+ receiptId: null
5177
+ };
5178
+ } catch {}
5179
+ } catch {}
4272
5180
  try {
4273
- const enriched = await enrichProfile({ email }, { playName: opts.playName });
5181
+ const enriched = await enrichProfile({ email }, {
5182
+ playName: opts.playName,
5183
+ decisionContext: {
5184
+ source: "finder.post_verify",
5185
+ prospectEmail: email
5186
+ }
5187
+ });
5188
+ try {
5189
+ ledger.setCachedEnrichment(key, JSON.stringify(enriched.result));
5190
+ } catch {}
4274
5191
  const profile = enriched.result.profile;
4275
5192
  const linkedinRaw = profile?.linkedin_url ?? null;
4276
5193
  return {
@@ -4295,8 +5212,8 @@ async function enrichVerifiedContact(email, opts) {
4295
5212
  //#endregion
4296
5213
  //#region ../../packages/find/src/show-hn.ts
4297
5214
  const HN_ALGOLIA = "https://hn.algolia.com/api/v1/search_by_date";
4298
- const PLAY_NAME$9 = "show-hn";
4299
- const SOURCE$6 = "find:show-hn";
5215
+ const PLAY_NAME$10 = "show-hn";
5216
+ const SOURCE$7 = "find:show-hn";
4300
5217
  /**
4301
5218
  * Pulls Show HN posts from HN Algolia, ICP-filters them, enriches founder
4302
5219
  * contact via OneShot, dedupes against the ledger, and enqueues into target_queue.
@@ -4308,7 +5225,7 @@ async function runShowHnFinder(opts) {
4308
5225
  const icp = resolveIcp(opts.icpOverride);
4309
5226
  const ledger = getLedger();
4310
5227
  const result = {
4311
- source: SOURCE$6,
5228
+ source: SOURCE$7,
4312
5229
  candidates: 0,
4313
5230
  droppedIcp: 0,
4314
5231
  droppedDuplicate: 0,
@@ -4318,7 +5235,7 @@ async function runShowHnFinder(opts) {
4318
5235
  costUsd: 0
4319
5236
  };
4320
5237
  logEvent("finder.start", {
4321
- name: PLAY_NAME$9,
5238
+ name: PLAY_NAME$10,
4322
5239
  since_days: sinceDays,
4323
5240
  limit
4324
5241
  });
@@ -4328,7 +5245,7 @@ async function runShowHnFinder(opts) {
4328
5245
  const data = await res.json();
4329
5246
  result.candidates = data.hits.length;
4330
5247
  logEvent("finder.fetched", {
4331
- name: PLAY_NAME$9,
5248
+ name: PLAY_NAME$10,
4332
5249
  candidates: result.candidates
4333
5250
  });
4334
5251
  const concurrency = opts.concurrency ?? 3;
@@ -4348,7 +5265,7 @@ async function runShowHnFinder(opts) {
4348
5265
  result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;
4349
5266
  return;
4350
5267
  }
4351
- if (ledger.isQueueDuplicate(PLAY_NAME$9, hit.objectID)) {
5268
+ if (ledger.isQueueDuplicate(PLAY_NAME$10, hit.objectID)) {
4352
5269
  result.droppedDuplicate++;
4353
5270
  return;
4354
5271
  }
@@ -4361,17 +5278,21 @@ async function runShowHnFinder(opts) {
4361
5278
  author: hit.author
4362
5279
  }
4363
5280
  });
5281
+ if (filter.match === null) {
5282
+ result.droppedEnrichment++;
5283
+ return;
5284
+ }
4364
5285
  if (!filter.match) {
4365
5286
  result.droppedIcp++;
4366
5287
  if (!opts.dryRun) ledger.enqueueTarget({
4367
- playName: PLAY_NAME$9,
5288
+ playName: PLAY_NAME$10,
4368
5289
  payload: {
4369
5290
  postTitle: hit.title,
4370
5291
  postUrl: hit.url,
4371
5292
  founderName: hit.author
4372
5293
  },
4373
5294
  dedupeKey: hit.objectID,
4374
- source: SOURCE$6,
5295
+ source: SOURCE$7,
4375
5296
  initialStatus: "rejected",
4376
5297
  notes: `auto: ICP — ${filter.reason}`
4377
5298
  });
@@ -4386,45 +5307,26 @@ async function runShowHnFinder(opts) {
4386
5307
  result.droppedEnrichment++;
4387
5308
  return;
4388
5309
  }
4389
- const fullName = hit.author && hit.author.length > 0 ? hit.author : void 0;
4390
- const skip = shouldSkipFindEmail({
4391
- fullName,
4392
- companyDomain: domain
5310
+ const contact = await resolveAndVerifyContact({
5311
+ playName: PLAY_NAME$10,
5312
+ fullName: hit.author && hit.author.length > 0 ? hit.author : null,
5313
+ companyDomain: domain,
5314
+ isDuplicate: (email) => isDuplicate({
5315
+ playName: PLAY_NAME$10,
5316
+ dedupeKey: hit.objectID,
5317
+ prospectEmail: email
5318
+ })
4393
5319
  });
4394
- if (!skip.ok) {
4395
- result.droppedEnrichment++;
4396
- logEvent("finder.skipped_findemail", {
4397
- name: PLAY_NAME$9,
4398
- reason: skip.reason
4399
- }, "info");
4400
- return;
4401
- }
4402
- const findInput = { companyDomain: domain };
4403
- if (fullName) findInput.fullName = fullName;
4404
- const found = await findEmail(findInput, { playName: PLAY_NAME$9 });
4405
- result.costUsd += found.result.cost ?? 0;
4406
- if (!found.result.found || !found.result.email) {
4407
- result.droppedEnrichment++;
4408
- return;
4409
- }
4410
- const email = found.result.email;
4411
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$9 });
4412
- result.costUsd += verified.result.cost ?? 0;
4413
- if (!verified.result.deliverable) {
4414
- result.droppedEnrichment++;
4415
- return;
4416
- }
4417
- if (isDuplicate({
4418
- playName: PLAY_NAME$9,
4419
- dedupeKey: hit.objectID,
4420
- prospectEmail: email
4421
- })) {
4422
- result.droppedDuplicate++;
5320
+ result.costUsd += contact.costUsd;
5321
+ if (!contact.ok) {
5322
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
5323
+ else result.droppedEnrichment++;
4423
5324
  return;
4424
5325
  }
5326
+ const email = contact.email;
4425
5327
  let hookSummary = (hit.story_text ?? "").trim().slice(0, 280);
4426
5328
  if (hookSummary.length < 40 && hit.url) try {
4427
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$9 });
5329
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$10 });
4428
5330
  result.costUsd += read.result.cost ?? 0;
4429
5331
  hookSummary = (read.result.markdown ?? "").trim().slice(0, 280);
4430
5332
  } catch (err) {
@@ -4434,9 +5336,9 @@ async function runShowHnFinder(opts) {
4434
5336
  }, "warn");
4435
5337
  }
4436
5338
  if (!hookSummary || hookSummary.length < 20) hookSummary = `Show HN post: ${hit.title}. ${hit.points} points.`;
4437
- const founderName = found.result.full_name ?? hit.author;
5339
+ const founderName = contact.fullName ?? hit.author;
4438
5340
  const enr = await enrichVerifiedContact(email, {
4439
- playName: PLAY_NAME$9,
5341
+ playName: PLAY_NAME$10,
4440
5342
  errKindPrefix: "show-hn"
4441
5343
  });
4442
5344
  result.costUsd += enr.costUsd;
@@ -4460,16 +5362,16 @@ async function runShowHnFinder(opts) {
4460
5362
  ...phone ? { phone } : {}
4461
5363
  };
4462
5364
  if (ledger.enqueueTarget({
4463
- playName: PLAY_NAME$9,
5365
+ playName: PLAY_NAME$10,
4464
5366
  payload: target,
4465
5367
  dedupeKey: hit.objectID,
4466
- source: SOURCE$6,
5368
+ source: SOURCE$7,
4467
5369
  notes: filter.reason
4468
5370
  }) != null) result.enqueued++;
4469
5371
  else result.droppedDuplicate++;
4470
5372
  });
4471
5373
  logEvent("finder.done", {
4472
- name: PLAY_NAME$9,
5374
+ name: PLAY_NAME$10,
4473
5375
  candidates: result.candidates,
4474
5376
  enqueued: result.enqueued,
4475
5377
  dropped_icp: result.droppedIcp,
@@ -4483,8 +5385,8 @@ async function runShowHnFinder(opts) {
4483
5385
  }
4484
5386
  //#endregion
4485
5387
  //#region ../../packages/find/src/post-funding.ts
4486
- const PLAY_NAME$8 = "post-funding";
4487
- const SOURCE$5 = "find:post-funding";
5388
+ const PLAY_NAME$9 = "post-funding";
5389
+ const SOURCE$6 = "find:post-funding";
4488
5390
  const ROUND_MAP = {
4489
5391
  "Pre-Seed": "Pre-Seed",
4490
5392
  Seed: "Seed",
@@ -4511,7 +5413,7 @@ async function runPostFundingFinder(opts) {
4511
5413
  autoCost = harvested.costUsd;
4512
5414
  }
4513
5415
  const result = {
4514
- source: opts.auto ? `${SOURCE$5}:auto` : SOURCE$5,
5416
+ source: opts.auto ? `${SOURCE$6}:auto` : SOURCE$6,
4515
5417
  candidates: urls.length,
4516
5418
  droppedIcp: 0,
4517
5419
  droppedDuplicate: 0,
@@ -4524,7 +5426,7 @@ async function runPostFundingFinder(opts) {
4524
5426
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
4525
5427
  break;
4526
5428
  }
4527
- if (ledger.isQueueDuplicate(PLAY_NAME$8, url)) {
5429
+ if (ledger.isQueueDuplicate(PLAY_NAME$9, url)) {
4528
5430
  result.droppedDuplicate++;
4529
5431
  continue;
4530
5432
  }
@@ -4534,7 +5436,7 @@ async function runPostFundingFinder(opts) {
4534
5436
  }
4535
5437
  let extract;
4536
5438
  try {
4537
- const read = await webRead({ url }, { playName: PLAY_NAME$8 });
5439
+ const read = await webRead({ url }, { playName: PLAY_NAME$9 });
4538
5440
  result.costUsd += read.result.cost ?? 0;
4539
5441
  extract = parsePostFundingExtract((await complete({
4540
5442
  messages: [{
@@ -4567,10 +5469,14 @@ async function runPostFundingFinder(opts) {
4567
5469
  summary: extract.summary
4568
5470
  }
4569
5471
  });
5472
+ if (filter.match === null) {
5473
+ result.droppedEnrichment++;
5474
+ continue;
5475
+ }
4570
5476
  if (!filter.match) {
4571
5477
  result.droppedIcp++;
4572
5478
  ledger.enqueueTarget({
4573
- playName: PLAY_NAME$8,
5479
+ playName: PLAY_NAME$9,
4574
5480
  payload: {
4575
5481
  company: extract.company,
4576
5482
  round: extract.round,
@@ -4579,50 +5485,31 @@ async function runPostFundingFinder(opts) {
4579
5485
  sourceUrl: url
4580
5486
  },
4581
5487
  dedupeKey: url,
4582
- source: SOURCE$5,
5488
+ source: SOURCE$6,
4583
5489
  initialStatus: "rejected",
4584
5490
  notes: `auto: ICP — ${filter.reason}`
4585
5491
  });
4586
5492
  continue;
4587
5493
  }
4588
- const skip = shouldSkipFindEmail({
5494
+ const contact = await resolveAndVerifyContact({
5495
+ playName: PLAY_NAME$9,
4589
5496
  fullName: extract.founderName,
4590
- companyDomain: extract.companyDomain
5497
+ companyDomain: extract.companyDomain,
5498
+ isDuplicate: (email) => isDuplicate({
5499
+ playName: PLAY_NAME$9,
5500
+ dedupeKey: url,
5501
+ prospectEmail: email
5502
+ })
4591
5503
  });
4592
- if (!skip.ok) {
4593
- result.droppedEnrichment++;
4594
- logEvent("finder.skipped_findemail", {
4595
- name: PLAY_NAME$8,
4596
- reason: skip.reason
4597
- }, "info");
4598
- continue;
4599
- }
4600
- const found = await findEmail({
4601
- fullName: extract.founderName,
4602
- companyDomain: extract.companyDomain
4603
- }, { playName: PLAY_NAME$8 });
4604
- result.costUsd += found.result.cost ?? 0;
4605
- if (!found.result.found || !found.result.email) {
4606
- result.droppedEnrichment++;
4607
- continue;
4608
- }
4609
- const email = found.result.email;
4610
- if (isDuplicate({
4611
- playName: PLAY_NAME$8,
4612
- dedupeKey: url,
4613
- prospectEmail: email
4614
- })) {
4615
- result.droppedDuplicate++;
4616
- continue;
4617
- }
4618
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$8 });
4619
- result.costUsd += verified.result.cost ?? 0;
4620
- if (!verified.result.deliverable) {
4621
- result.droppedEnrichment++;
5504
+ result.costUsd += contact.costUsd;
5505
+ if (!contact.ok) {
5506
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
5507
+ else result.droppedEnrichment++;
4622
5508
  continue;
4623
5509
  }
5510
+ const email = contact.email;
4624
5511
  const enr = await enrichVerifiedContact(email, {
4625
- playName: PLAY_NAME$8,
5512
+ playName: PLAY_NAME$9,
4626
5513
  errKindPrefix: "post-funding"
4627
5514
  });
4628
5515
  result.costUsd += enr.costUsd;
@@ -4649,10 +5536,10 @@ async function runPostFundingFinder(opts) {
4649
5536
  ...phone ? { phone } : {}
4650
5537
  };
4651
5538
  if (ledger.enqueueTarget({
4652
- playName: PLAY_NAME$8,
5539
+ playName: PLAY_NAME$9,
4653
5540
  payload: target,
4654
5541
  dedupeKey: url,
4655
- source: SOURCE$5,
5542
+ source: SOURCE$6,
4656
5543
  notes: `${extract.round ?? "?"} ${extract.amountUsd ? `$${extract.amountUsd.toLocaleString()}` : ""} — ${filter.reason}`
4657
5544
  }) != null) result.enqueued++;
4658
5545
  else result.droppedDuplicate++;
@@ -4725,7 +5612,7 @@ async function harvestAutoUrls(args) {
4725
5612
  const search = await webSearch({
4726
5613
  query,
4727
5614
  maxResults: Math.min(20, Math.max(5, args.limit - urls.length))
4728
- }, { playName: PLAY_NAME$8 });
5615
+ }, { playName: PLAY_NAME$9 });
4729
5616
  costUsd += search.result.cost ?? 0;
4730
5617
  for (const hit of search.result.results ?? []) {
4731
5618
  if (urls.length >= args.limit) break;
@@ -4838,7 +5725,7 @@ function deriveIndustryHint(icp) {
4838
5725
  * Less reliable than the yc-oss adapter (search recall depends on the
4839
5726
  * accelerator's web presence) but works without per-accelerator scrapers.
4840
5727
  */
4841
- const PLAY_NAME$7 = "accelerator-batch";
5728
+ const PLAY_NAME$8 = "accelerator-batch";
4842
5729
  /**
4843
5730
  * Build the three search queries from a human-readable cohort label.
4844
5731
  * Founders supply `cohortLabel: "YC W26"` or `"Techstars Toronto Spring 2025"`
@@ -4907,7 +5794,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
4907
5794
  const search = await webSearch({
4908
5795
  query,
4909
5796
  maxResults: Math.min(15, limit)
4910
- }, { playName: PLAY_NAME$7 });
5797
+ }, { playName: PLAY_NAME$8 });
4911
5798
  costUsd += search.result.cost ?? 0;
4912
5799
  for (const raw of search.result.results ?? []) {
4913
5800
  if (!raw.url || seen.has(raw.url)) continue;
@@ -4936,7 +5823,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
4936
5823
  for (const hit of hits.slice(0, limit)) {
4937
5824
  let extract = null;
4938
5825
  try {
4939
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$7 });
5826
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$8 });
4940
5827
  costUsd += read.result.cost ?? 0;
4941
5828
  extract = parseAcceleratorLaunchExtract((await complete({
4942
5829
  messages: [{
@@ -5208,7 +6095,7 @@ function mapYcOssCompany(c) {
5208
6095
  * verifyEmail → enqueue, all under `parallelMap` (concurrency 3, mirrors
5209
6096
  * github-topics).
5210
6097
  */
5211
- const PLAY_NAME$6 = "accelerator-batch";
6098
+ const PLAY_NAME$7 = "accelerator-batch";
5212
6099
  /**
5213
6100
  * Normalize the legacy single-cohort opts shape into the new multi-cohort
5214
6101
  * list. Old trigger rows with `{cohort, cohortLabel}` keep working — they
@@ -5390,7 +6277,7 @@ async function runAcceleratorBatchFinder(opts) {
5390
6277
  return;
5391
6278
  }
5392
6279
  const dedupeKey = makeDedupeKey(record, record.cohort);
5393
- if (ledger.isQueueDuplicate(PLAY_NAME$6, dedupeKey)) {
6280
+ if (ledger.isQueueDuplicate(PLAY_NAME$7, dedupeKey)) {
5394
6281
  result.droppedDuplicate++;
5395
6282
  return;
5396
6283
  }
@@ -5406,10 +6293,14 @@ async function runAcceleratorBatchFinder(opts) {
5406
6293
  summary: buildIcpSummary(record)
5407
6294
  }
5408
6295
  });
6296
+ if (filter.match === null) {
6297
+ result.droppedEnrichment++;
6298
+ return;
6299
+ }
5409
6300
  if (!filter.match) {
5410
6301
  result.droppedIcp++;
5411
6302
  ledger.enqueueTarget({
5412
- playName: PLAY_NAME$6,
6303
+ playName: PLAY_NAME$7,
5413
6304
  payload: rejectionPayload(record, record.cohort),
5414
6305
  dedupeKey,
5415
6306
  source,
@@ -5437,45 +6328,26 @@ async function runAcceleratorBatchFinder(opts) {
5437
6328
  result.droppedEnrichment++;
5438
6329
  return;
5439
6330
  }
5440
- const skip = shouldSkipFindEmail({
6331
+ const contact = await resolveAndVerifyContact({
6332
+ playName: PLAY_NAME$7,
5441
6333
  fullName: founderName,
5442
- companyDomain: domain
6334
+ companyDomain: domain,
6335
+ isDuplicate: (email) => isDuplicate({
6336
+ playName: PLAY_NAME$7,
6337
+ dedupeKey,
6338
+ prospectEmail: email
6339
+ })
5443
6340
  });
5444
- if (!skip.ok) {
5445
- result.droppedEnrichment++;
5446
- logEvent("finder.skipped_findemail", {
5447
- name: PLAY_NAME$6,
5448
- reason: skip.reason
5449
- }, "info");
5450
- return;
5451
- }
5452
- const found = await findEmail({
5453
- fullName: founderName,
5454
- companyDomain: domain
5455
- }, { playName: PLAY_NAME$6 });
5456
- result.costUsd += found.result.cost ?? 0;
5457
- if (!found.result.found || !found.result.email) {
5458
- result.droppedEnrichment++;
5459
- return;
5460
- }
5461
- const email = found.result.email;
5462
- const fullName = found.result.full_name?.trim() || founderName;
5463
- if (isDuplicate({
5464
- playName: PLAY_NAME$6,
5465
- dedupeKey,
5466
- prospectEmail: email
5467
- })) {
5468
- result.droppedDuplicate++;
5469
- return;
5470
- }
5471
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$6 });
5472
- result.costUsd += verified.result.cost ?? 0;
5473
- if (!verified.result.deliverable) {
5474
- result.droppedEnrichment++;
6341
+ result.costUsd += contact.costUsd;
6342
+ if (!contact.ok) {
6343
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6344
+ else result.droppedEnrichment++;
5475
6345
  return;
5476
6346
  }
6347
+ const email = contact.email;
6348
+ const fullName = contact.fullName?.trim() || founderName;
5477
6349
  const enr = await enrichVerifiedContact(email, {
5478
- playName: PLAY_NAME$6,
6350
+ playName: PLAY_NAME$7,
5479
6351
  errKindPrefix: "accelerator-batch"
5480
6352
  });
5481
6353
  result.costUsd += enr.costUsd;
@@ -5502,7 +6374,7 @@ async function runAcceleratorBatchFinder(opts) {
5502
6374
  ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
5503
6375
  };
5504
6376
  if (ledger.enqueueTarget({
5505
- playName: PLAY_NAME$6,
6377
+ playName: PLAY_NAME$7,
5506
6378
  payload: target,
5507
6379
  dedupeKey,
5508
6380
  source,
@@ -5560,7 +6432,7 @@ async function resolveFounderName(record) {
5560
6432
  };
5561
6433
  let costUsd = 0;
5562
6434
  try {
5563
- const read = await webRead({ url }, { playName: PLAY_NAME$6 });
6435
+ const read = await webRead({ url }, { playName: PLAY_NAME$7 });
5564
6436
  costUsd += read.result.cost ?? 0;
5565
6437
  const extract = parseAcceleratorLaunchExtract((await complete({
5566
6438
  messages: [{
@@ -5600,8 +6472,8 @@ async function resolveFounderName(record) {
5600
6472
  }
5601
6473
  //#endregion
5602
6474
  //#region ../../packages/find/src/job-change.ts
5603
- const PLAY_NAME$5 = "job-change";
5604
- const SOURCE$4 = "find:job-change";
6475
+ const PLAY_NAME$6 = "job-change";
6476
+ const SOURCE$5 = "find:job-change";
5605
6477
  const DEFAULT_PERSONAS = [
5606
6478
  "VP Engineering",
5607
6479
  "Head of Growth",
@@ -5616,7 +6488,7 @@ async function runJobChangeFinder(opts) {
5616
6488
  const system = loadPrompt("job-change-extract");
5617
6489
  const personas = opts.personas && opts.personas.length > 0 ? opts.personas : DEFAULT_PERSONAS;
5618
6490
  const result = {
5619
- source: SOURCE$4,
6491
+ source: SOURCE$5,
5620
6492
  candidates: 0,
5621
6493
  droppedIcp: 0,
5622
6494
  droppedDuplicate: 0,
@@ -5634,7 +6506,7 @@ async function runJobChangeFinder(opts) {
5634
6506
  const search = await webSearch({
5635
6507
  query,
5636
6508
  maxResults: Math.min(15, limit)
5637
- }, { playName: PLAY_NAME$5 });
6509
+ }, { playName: PLAY_NAME$6 });
5638
6510
  result.costUsd += search.result.cost ?? 0;
5639
6511
  for (const hit of search.result.results ?? []) {
5640
6512
  if (!hit.url || seenUrls.has(hit.url)) continue;
@@ -5660,7 +6532,7 @@ async function runJobChangeFinder(opts) {
5660
6532
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
5661
6533
  break;
5662
6534
  }
5663
- if (ledger.isQueueDuplicate(PLAY_NAME$5, hit.url)) {
6535
+ if (ledger.isQueueDuplicate(PLAY_NAME$6, hit.url)) {
5664
6536
  result.droppedDuplicate++;
5665
6537
  continue;
5666
6538
  }
@@ -5676,17 +6548,21 @@ async function runJobChangeFinder(opts) {
5676
6548
  summary: hit.description
5677
6549
  }
5678
6550
  });
6551
+ if (filter.match === null) {
6552
+ result.droppedEnrichment++;
6553
+ continue;
6554
+ }
5679
6555
  if (!filter.match) {
5680
6556
  result.droppedIcp++;
5681
6557
  ledger.enqueueTarget({
5682
- playName: PLAY_NAME$5,
6558
+ playName: PLAY_NAME$6,
5683
6559
  payload: {
5684
6560
  title: hit.title,
5685
6561
  url: hit.url,
5686
6562
  description: hit.description
5687
6563
  },
5688
6564
  dedupeKey: hit.url,
5689
- source: SOURCE$4,
6565
+ source: SOURCE$5,
5690
6566
  initialStatus: "rejected",
5691
6567
  notes: `auto: ICP — ${filter.reason}`
5692
6568
  });
@@ -5726,44 +6602,25 @@ async function runJobChangeFinder(opts) {
5726
6602
  result.droppedEnrichment++;
5727
6603
  continue;
5728
6604
  }
5729
- const skip = shouldSkipFindEmail({
6605
+ const contact = await resolveAndVerifyContact({
6606
+ playName: PLAY_NAME$6,
5730
6607
  fullName: extract.fullName,
5731
- companyDomain: domain
6608
+ companyDomain: domain,
6609
+ isDuplicate: (email) => isDuplicate({
6610
+ playName: PLAY_NAME$6,
6611
+ dedupeKey: hit.url,
6612
+ prospectEmail: email
6613
+ })
5732
6614
  });
5733
- if (!skip.ok) {
5734
- result.droppedEnrichment++;
5735
- logEvent("finder.skipped_findemail", {
5736
- name: PLAY_NAME$5,
5737
- reason: skip.reason
5738
- }, "info");
5739
- continue;
5740
- }
5741
- const found = await findEmail({
5742
- fullName: extract.fullName,
5743
- companyDomain: domain
5744
- }, { playName: PLAY_NAME$5 });
5745
- result.costUsd += found.result.cost ?? 0;
5746
- if (!found.result.found || !found.result.email) {
5747
- result.droppedEnrichment++;
5748
- continue;
5749
- }
5750
- const email = found.result.email;
5751
- if (isDuplicate({
5752
- playName: PLAY_NAME$5,
5753
- dedupeKey: hit.url,
5754
- prospectEmail: email
5755
- })) {
5756
- result.droppedDuplicate++;
5757
- continue;
5758
- }
5759
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$5 });
5760
- result.costUsd += verified.result.cost ?? 0;
5761
- if (!verified.result.deliverable) {
5762
- result.droppedEnrichment++;
6615
+ result.costUsd += contact.costUsd;
6616
+ if (!contact.ok) {
6617
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6618
+ else result.droppedEnrichment++;
5763
6619
  continue;
5764
6620
  }
6621
+ const email = contact.email;
5765
6622
  const enr = await enrichVerifiedContact(email, {
5766
- playName: PLAY_NAME$5,
6623
+ playName: PLAY_NAME$6,
5767
6624
  errKindPrefix: "job-change"
5768
6625
  });
5769
6626
  result.costUsd += enr.costUsd;
@@ -5789,10 +6646,10 @@ async function runJobChangeFinder(opts) {
5789
6646
  ...phone ? { phone } : {}
5790
6647
  };
5791
6648
  if (ledger.enqueueTarget({
5792
- playName: PLAY_NAME$5,
6649
+ playName: PLAY_NAME$6,
5793
6650
  payload: target,
5794
6651
  dedupeKey: hit.url,
5795
- source: SOURCE$4,
6652
+ source: SOURCE$5,
5796
6653
  notes: `${extract.fullName} → ${extract.newRole} @ ${extract.newCompany} — ${filter.reason}`
5797
6654
  }) != null) result.enqueued++;
5798
6655
  else result.droppedDuplicate++;
@@ -5814,8 +6671,8 @@ function parseJobChangeExtract(raw) {
5814
6671
  }
5815
6672
  //#endregion
5816
6673
  //#region ../../packages/find/src/hiring-signal.ts
5817
- const PLAY_NAME$4 = "hiring-signal";
5818
- const SOURCE$3 = "find:hiring-signal";
6674
+ const PLAY_NAME$5 = "hiring-signal";
6675
+ const SOURCE$4 = "find:hiring-signal";
5819
6676
  const ATS_DOMAIN_HINTS = [
5820
6677
  "boards.greenhouse.io",
5821
6678
  "jobs.lever.co",
@@ -5837,7 +6694,7 @@ async function runHiringSignalFinder(opts) {
5837
6694
  const roles = opts.roles && opts.roles.length > 0 ? opts.roles : DEFAULT_ROLES;
5838
6695
  const yourClaim = (opts.yourClaim ?? "").trim();
5839
6696
  const result = {
5840
- source: SOURCE$3,
6697
+ source: SOURCE$4,
5841
6698
  candidates: 0,
5842
6699
  droppedIcp: 0,
5843
6700
  droppedDuplicate: 0,
@@ -5860,7 +6717,7 @@ async function runHiringSignalFinder(opts) {
5860
6717
  const search = await webSearch({
5861
6718
  query,
5862
6719
  maxResults: Math.min(15, limit)
5863
- }, { playName: PLAY_NAME$4 });
6720
+ }, { playName: PLAY_NAME$5 });
5864
6721
  result.costUsd += search.result.cost ?? 0;
5865
6722
  for (const hit of search.result.results ?? []) {
5866
6723
  if (!hit.url || seen.has(hit.url) || !isAtsUrl(hit.url)) continue;
@@ -5886,7 +6743,7 @@ async function runHiringSignalFinder(opts) {
5886
6743
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
5887
6744
  break;
5888
6745
  }
5889
- if (ledger.isQueueDuplicate(PLAY_NAME$4, hit.url)) {
6746
+ if (ledger.isQueueDuplicate(PLAY_NAME$5, hit.url)) {
5890
6747
  result.droppedDuplicate++;
5891
6748
  continue;
5892
6749
  }
@@ -5902,17 +6759,21 @@ async function runHiringSignalFinder(opts) {
5902
6759
  summary: hit.description
5903
6760
  }
5904
6761
  });
6762
+ if (filter.match === null) {
6763
+ result.droppedEnrichment++;
6764
+ continue;
6765
+ }
5905
6766
  if (!filter.match) {
5906
6767
  result.droppedIcp++;
5907
6768
  ledger.enqueueTarget({
5908
- playName: PLAY_NAME$4,
6769
+ playName: PLAY_NAME$5,
5909
6770
  payload: {
5910
6771
  title: hit.title,
5911
6772
  url: hit.url,
5912
6773
  description: hit.description
5913
6774
  },
5914
6775
  dedupeKey: hit.url,
5915
- source: SOURCE$3,
6776
+ source: SOURCE$4,
5916
6777
  initialStatus: "rejected",
5917
6778
  notes: `auto: ICP — ${filter.reason}`
5918
6779
  });
@@ -5920,7 +6781,7 @@ async function runHiringSignalFinder(opts) {
5920
6781
  }
5921
6782
  let extract;
5922
6783
  try {
5923
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$4 });
6784
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$5 });
5924
6785
  result.costUsd += read.result.cost ?? 0;
5925
6786
  extract = parseHiringSignalExtract((await complete({
5926
6787
  messages: [{
@@ -5958,46 +6819,26 @@ async function runHiringSignalFinder(opts) {
5958
6819
  result.droppedEnrichment++;
5959
6820
  continue;
5960
6821
  }
5961
- const managerName = extract.hiringManagerName && extract.hiringManagerName.length > 0 ? extract.hiringManagerName : null;
5962
- const skip = shouldSkipFindEmail({
5963
- fullName: managerName,
5964
- companyDomain: domain
6822
+ const contact = await resolveAndVerifyContact({
6823
+ playName: PLAY_NAME$5,
6824
+ fullName: extract.hiringManagerName && extract.hiringManagerName.length > 0 ? extract.hiringManagerName : null,
6825
+ companyDomain: domain,
6826
+ isDuplicate: (email) => isDuplicate({
6827
+ playName: PLAY_NAME$5,
6828
+ dedupeKey: hit.url,
6829
+ prospectEmail: email
6830
+ })
5965
6831
  });
5966
- if (!skip.ok) {
5967
- result.droppedEnrichment++;
5968
- logEvent("finder.skipped_findemail", {
5969
- name: PLAY_NAME$4,
5970
- reason: skip.reason
5971
- }, "info");
6832
+ result.costUsd += contact.costUsd;
6833
+ if (!contact.ok) {
6834
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6835
+ else result.droppedEnrichment++;
5972
6836
  continue;
5973
6837
  }
5974
- const found = await findEmail(managerName ? {
5975
- fullName: managerName,
5976
- companyDomain: domain
5977
- } : { companyDomain: domain }, { playName: PLAY_NAME$4 });
5978
- result.costUsd += found.result.cost ?? 0;
5979
- if (!found.result.found || !found.result.email) {
5980
- result.droppedEnrichment++;
5981
- continue;
5982
- }
5983
- const email = found.result.email;
5984
- if (isDuplicate({
5985
- playName: PLAY_NAME$4,
5986
- dedupeKey: hit.url,
5987
- prospectEmail: email
5988
- })) {
5989
- result.droppedDuplicate++;
5990
- continue;
5991
- }
5992
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$4 });
5993
- result.costUsd += verified.result.cost ?? 0;
5994
- if (!verified.result.deliverable) {
5995
- result.droppedEnrichment++;
5996
- continue;
5997
- }
5998
- const recipientName = extract.hiringManagerName ?? found.result.full_name ?? null;
6838
+ const email = contact.email;
6839
+ const recipientName = extract.hiringManagerName ?? contact.fullName;
5999
6840
  const enr = await enrichVerifiedContact(email, {
6000
- playName: PLAY_NAME$4,
6841
+ playName: PLAY_NAME$5,
6001
6842
  errKindPrefix: "hiring-signal"
6002
6843
  });
6003
6844
  result.costUsd += enr.costUsd;
@@ -6023,10 +6864,10 @@ async function runHiringSignalFinder(opts) {
6023
6864
  ...phone ? { phone } : {}
6024
6865
  };
6025
6866
  if (ledger.enqueueTarget({
6026
- playName: PLAY_NAME$4,
6867
+ playName: PLAY_NAME$5,
6027
6868
  payload: target,
6028
6869
  dedupeKey: hit.url,
6029
- source: SOURCE$3,
6870
+ source: SOURCE$4,
6030
6871
  notes: `${extract.company} hiring "${extract.jobTitle}"${extract.team ? ` (${extract.team})` : ""} — ${filter.reason}`
6031
6872
  }) != null) result.enqueued++;
6032
6873
  else result.droppedDuplicate++;
@@ -6076,7 +6917,7 @@ async function resolveCorporateDomain(company, jobUrl, cache) {
6076
6917
  const search = await webSearch({
6077
6918
  query: `"${company}" official site`,
6078
6919
  maxResults: 5
6079
- }, { playName: PLAY_NAME$4 });
6920
+ }, { playName: PLAY_NAME$5 });
6080
6921
  costUsd += search.result.cost ?? 0;
6081
6922
  for (const hit of search.result.results ?? []) {
6082
6923
  const host = pickCorporateHost(hit.url);
@@ -6128,8 +6969,8 @@ function parseHiringSignalExtract(raw) {
6128
6969
  }
6129
6970
  //#endregion
6130
6971
  //#region ../../packages/find/src/podcast-guest.ts
6131
- const PLAY_NAME$3 = "podcast-guest";
6132
- const SOURCE$2 = "find:podcast-guest";
6972
+ const PLAY_NAME$4 = "podcast-guest";
6973
+ const SOURCE$3 = "find:podcast-guest";
6133
6974
  const DEFAULT_PODCASTS = [
6134
6975
  "Latent Space",
6135
6976
  "Lenny's Podcast",
@@ -6145,7 +6986,7 @@ async function runPodcastGuestFinder(opts) {
6145
6986
  const system = loadPrompt("podcast-guest-extract");
6146
6987
  const podcasts = opts.podcasts && opts.podcasts.length > 0 ? opts.podcasts : DEFAULT_PODCASTS;
6147
6988
  const result = {
6148
- source: SOURCE$2,
6989
+ source: SOURCE$3,
6149
6990
  candidates: 0,
6150
6991
  droppedIcp: 0,
6151
6992
  droppedDuplicate: 0,
@@ -6163,7 +7004,7 @@ async function runPodcastGuestFinder(opts) {
6163
7004
  const search = await webSearch({
6164
7005
  query,
6165
7006
  maxResults: Math.min(15, limit)
6166
- }, { playName: PLAY_NAME$3 });
7007
+ }, { playName: PLAY_NAME$4 });
6167
7008
  result.costUsd += search.result.cost ?? 0;
6168
7009
  for (const hit of search.result.results ?? []) {
6169
7010
  if (!hit.url || seen.has(hit.url)) continue;
@@ -6189,7 +7030,7 @@ async function runPodcastGuestFinder(opts) {
6189
7030
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
6190
7031
  break;
6191
7032
  }
6192
- if (ledger.isQueueDuplicate(PLAY_NAME$3, hit.url)) {
7033
+ if (ledger.isQueueDuplicate(PLAY_NAME$4, hit.url)) {
6193
7034
  result.droppedDuplicate++;
6194
7035
  continue;
6195
7036
  }
@@ -6205,17 +7046,21 @@ async function runPodcastGuestFinder(opts) {
6205
7046
  summary: hit.description
6206
7047
  }
6207
7048
  });
7049
+ if (filter.match === null) {
7050
+ result.droppedEnrichment++;
7051
+ continue;
7052
+ }
6208
7053
  if (!filter.match) {
6209
7054
  result.droppedIcp++;
6210
7055
  ledger.enqueueTarget({
6211
- playName: PLAY_NAME$3,
7056
+ playName: PLAY_NAME$4,
6212
7057
  payload: {
6213
7058
  title: hit.title,
6214
7059
  url: hit.url,
6215
7060
  description: hit.description
6216
7061
  },
6217
7062
  dedupeKey: hit.url,
6218
- source: SOURCE$2,
7063
+ source: SOURCE$3,
6219
7064
  initialStatus: "rejected",
6220
7065
  notes: `auto: ICP — ${filter.reason}`
6221
7066
  });
@@ -6229,7 +7074,7 @@ async function runPodcastGuestFinder(opts) {
6229
7074
  description: hit.description
6230
7075
  };
6231
7076
  if (!opts.skipRead) {
6232
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$3 });
7077
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$4 });
6233
7078
  result.costUsd += read.result.cost ?? 0;
6234
7079
  payload = {
6235
7080
  ...payload,
@@ -6259,44 +7104,25 @@ async function runPodcastGuestFinder(opts) {
6259
7104
  result.droppedEnrichment++;
6260
7105
  continue;
6261
7106
  }
6262
- const skip = shouldSkipFindEmail({
7107
+ const contact = await resolveAndVerifyContact({
7108
+ playName: PLAY_NAME$4,
6263
7109
  fullName: extract.guestName,
6264
- companyDomain: extract.guestCompanyDomain
7110
+ companyDomain: extract.guestCompanyDomain,
7111
+ isDuplicate: (email) => isDuplicate({
7112
+ playName: PLAY_NAME$4,
7113
+ dedupeKey: hit.url,
7114
+ prospectEmail: email
7115
+ })
6265
7116
  });
6266
- if (!skip.ok) {
6267
- result.droppedEnrichment++;
6268
- logEvent("finder.skipped_findemail", {
6269
- name: PLAY_NAME$3,
6270
- reason: skip.reason
6271
- }, "info");
6272
- continue;
6273
- }
6274
- const found = await findEmail({
6275
- fullName: extract.guestName,
6276
- companyDomain: extract.guestCompanyDomain
6277
- }, { playName: PLAY_NAME$3 });
6278
- result.costUsd += found.result.cost ?? 0;
6279
- if (!found.result.found || !found.result.email) {
6280
- result.droppedEnrichment++;
6281
- continue;
6282
- }
6283
- const email = found.result.email;
6284
- if (isDuplicate({
6285
- playName: PLAY_NAME$3,
6286
- dedupeKey: hit.url,
6287
- prospectEmail: email
6288
- })) {
6289
- result.droppedDuplicate++;
6290
- continue;
6291
- }
6292
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$3 });
6293
- result.costUsd += verified.result.cost ?? 0;
6294
- if (!verified.result.deliverable) {
6295
- result.droppedEnrichment++;
7117
+ result.costUsd += contact.costUsd;
7118
+ if (!contact.ok) {
7119
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
7120
+ else result.droppedEnrichment++;
6296
7121
  continue;
6297
7122
  }
7123
+ const email = contact.email;
6298
7124
  const enr = await enrichVerifiedContact(email, {
6299
- playName: PLAY_NAME$3,
7125
+ playName: PLAY_NAME$4,
6300
7126
  errKindPrefix: "podcast-guest"
6301
7127
  });
6302
7128
  result.costUsd += enr.costUsd;
@@ -6322,10 +7148,10 @@ async function runPodcastGuestFinder(opts) {
6322
7148
  ...phone ? { phone } : {}
6323
7149
  };
6324
7150
  if (ledger.enqueueTarget({
6325
- playName: PLAY_NAME$3,
7151
+ playName: PLAY_NAME$4,
6326
7152
  payload: target,
6327
7153
  dedupeKey: hit.url,
6328
- source: SOURCE$2,
7154
+ source: SOURCE$3,
6329
7155
  notes: `${extract.guestName} on ${extract.podcastName} — ${filter.reason}`
6330
7156
  }) != null) result.enqueued++;
6331
7157
  else result.droppedDuplicate++;
@@ -6349,8 +7175,8 @@ function parsePodcastGuestExtract(raw) {
6349
7175
  }
6350
7176
  //#endregion
6351
7177
  //#region ../../packages/find/src/breakup-revive.ts
6352
- const PLAY_NAME$2 = "breakup-revive";
6353
- const SOURCE$1 = "find:breakup-revive";
7178
+ const PLAY_NAME$3 = "breakup-revive";
7179
+ const SOURCE$2 = "find:breakup-revive";
6354
7180
  /**
6355
7181
  * Scan the local ledger for cold prospects (no activity in the last
6356
7182
  * min/maxDays window) and enqueue them into target_queue. No LLM calls,
@@ -6363,7 +7189,7 @@ function runBreakupReviveFinder(opts) {
6363
7189
  const maxDays = opts.maxDays ?? 90;
6364
7190
  const ledger = getLedger();
6365
7191
  const result = {
6366
- source: SOURCE$1,
7192
+ source: SOURCE$2,
6367
7193
  candidates: 0,
6368
7194
  droppedIcp: 0,
6369
7195
  droppedDuplicate: 0,
@@ -6385,7 +7211,7 @@ function runBreakupReviveFinder(opts) {
6385
7211
  }
6386
7212
  const dedupeKey = `prospect:${p.id}`;
6387
7213
  if (isDuplicate({
6388
- playName: PLAY_NAME$2,
7214
+ playName: PLAY_NAME$3,
6389
7215
  dedupeKey,
6390
7216
  prospectEmail: void 0
6391
7217
  })) {
@@ -6407,10 +7233,10 @@ function runBreakupReviveFinder(opts) {
6407
7233
  continue;
6408
7234
  }
6409
7235
  const id = ledger.enqueueTarget({
6410
- playName: PLAY_NAME$2,
7236
+ playName: PLAY_NAME$3,
6411
7237
  payload: target,
6412
7238
  dedupeKey,
6413
- source: SOURCE$1,
7239
+ source: SOURCE$2,
6414
7240
  notes: `${daysCold}d cold${p.company ? ` — ${p.company}` : ""}`
6415
7241
  });
6416
7242
  if (id != null) {
@@ -6597,6 +7423,100 @@ async function fetchGitHubUser(login) {
6597
7423
  }
6598
7424
  }
6599
7425
  /**
7426
+ * Per-process cache of `/users/{login}/repos` lookups. Same shape + semantics
7427
+ * as the user-profile cache above: `null` is a real value meaning "we tried
7428
+ * and got 404 / 429 / network error, don't retry within the run."
7429
+ */
7430
+ const reposCache = /* @__PURE__ */ new Map();
7431
+ /**
7432
+ * Fetch the candidate's top 10 OWN public repos, sorted by most-recent push
7433
+ * — i.e. "what they actively ship." No star filter (a one-star repo can still
7434
+ * be the most-telling signal of what they care about right now). Forks are
7435
+ * dropped client-side in the filter chain below — they're a weak signal of
7436
+ * authorship AND with `sort=pushed` a fork tracking a busy upstream
7437
+ * (kubernetes, next.js) would float to the top and get framed to the LLM as
7438
+ * shipping evidence.
7439
+ *
7440
+ * Note: GitHub's `type=owner` URL param filters by OWNERSHIP relation (owner
7441
+ * vs collaborator-via-member), NOT by fork status. The endpoint has no
7442
+ * `fork=false` param; client-side filtering on the response is the only way.
7443
+ *
7444
+ * Returns null on any non-2xx / network error / parse failure — caller treats
7445
+ * an absent enrichment as "skip the repos block in the prompt," never fatal.
7446
+ * Empty array (user has no public repos / all private) stays `[]`, distinct
7447
+ * from null, so callers can tell "no data" from "no repos."
7448
+ */
7449
+ async function fetchTopRepos(login) {
7450
+ const key = login.toLowerCase();
7451
+ if (reposCache.has(key)) return reposCache.get(key) ?? null;
7452
+ try {
7453
+ const url = `https://api.github.com/users/${encodeURIComponent(login)}/repos?per_page=10&sort=pushed&type=owner`;
7454
+ const res = await fetch(url, { headers: githubHeaders() });
7455
+ if (res.status === 404) {
7456
+ reposCache.set(key, null);
7457
+ logEvent("github.repos.fetch", {
7458
+ login,
7459
+ ok: false,
7460
+ status: 404
7461
+ });
7462
+ return null;
7463
+ }
7464
+ if (res.status === 429 || res.status === 403) {
7465
+ reposCache.set(key, null);
7466
+ logEvent("github.repos.fetch", {
7467
+ login,
7468
+ ok: false,
7469
+ status: res.status,
7470
+ rate_limited: true
7471
+ });
7472
+ return null;
7473
+ }
7474
+ if (!res.ok) {
7475
+ reposCache.set(key, null);
7476
+ logEvent("github.repos.fetch", {
7477
+ login,
7478
+ ok: false,
7479
+ status: res.status
7480
+ });
7481
+ return null;
7482
+ }
7483
+ const json = await res.json();
7484
+ if (!Array.isArray(json)) {
7485
+ reposCache.set(key, null);
7486
+ logEvent("github.repos.fetch", {
7487
+ login,
7488
+ ok: false,
7489
+ status: res.status,
7490
+ malformed: true
7491
+ });
7492
+ return null;
7493
+ }
7494
+ const repos = json.filter((r) => r["archived"] !== true && r["fork"] !== true && typeof r["name"] === "string" && r["name"] !== "").map((r) => {
7495
+ const rawDesc = typeof r["description"] === "string" && r["description"] !== "" ? r["description"] : null;
7496
+ return {
7497
+ name: r["name"],
7498
+ description: rawDesc && rawDesc.length > 160 ? `${rawDesc.slice(0, 159)}…` : rawDesc,
7499
+ language: typeof r["language"] === "string" ? r["language"] : null
7500
+ };
7501
+ });
7502
+ reposCache.set(key, repos);
7503
+ logEvent("github.repos.fetch", {
7504
+ login,
7505
+ ok: true,
7506
+ count: repos.length
7507
+ });
7508
+ return repos;
7509
+ } catch (err) {
7510
+ reposCache.set(key, null);
7511
+ logEvent("github.repos.fetch", {
7512
+ login,
7513
+ ok: false,
7514
+ message_120: (err.message ?? "").slice(0, 120)
7515
+ }, "warn");
7516
+ return null;
7517
+ }
7518
+ }
7519
+ /**
6600
7520
  * Normalize a profile `blog` field to a bare hostname.
6601
7521
  *
6602
7522
  * GitHub stores whatever the user typed, so this needs to handle:
@@ -6843,7 +7763,7 @@ function parseEnvKeys(content) {
6843
7763
  * directly from package.json / pyproject.toml / requirements.txt /
6844
7764
  * .env.example via the GitHub Contents API. Free, fast, deterministic.
6845
7765
  */
6846
- const PLAY_NAME$1 = "stack-consolidation";
7766
+ const PLAY_NAME$2 = "stack-consolidation";
6847
7767
  /**
6848
7768
  * Process a single candidate through the full pipeline. Mutates ctx.result.
6849
7769
  * Never throws — internal exceptions become droppedEnrichment increments via
@@ -6882,10 +7802,14 @@ async function processRepoCandidate(hit, ctx) {
6882
7802
  summary: describeForIcp(hit)
6883
7803
  }
6884
7804
  });
7805
+ if (snippetFilter.match === null) {
7806
+ result.droppedEnrichment++;
7807
+ return;
7808
+ }
6885
7809
  if (!snippetFilter.match) {
6886
7810
  result.droppedIcp++;
6887
7811
  ledger.enqueueTarget({
6888
- playName: PLAY_NAME$1,
7812
+ playName: PLAY_NAME$2,
6889
7813
  payload: {
6890
7814
  repoUrl: hit.url,
6891
7815
  title: hit.title,
@@ -7033,7 +7957,7 @@ async function processRepoCandidate(hit, ctx) {
7033
7957
  async function resolveContact(args) {
7034
7958
  const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;
7035
7959
  const errKindPrefix = args.errKindPrefix ?? "repo-pipeline";
7036
- const playName = args.playName ?? PLAY_NAME$1;
7960
+ const playName = args.playName ?? PLAY_NAME$2;
7037
7961
  const extractDomain = extract.companyDomain ?? extract.personalDomain ?? null;
7038
7962
  let discoveredLinkedinUrl = null;
7039
7963
  if (extractDomain) {
@@ -7069,6 +7993,9 @@ async function resolveContact(args) {
7069
7993
  accumCost(enriched.result.cost ?? 0);
7070
7994
  const profile = enriched.result.profile;
7071
7995
  const enrichedPhone = extractFirstPhone(profile);
7996
+ if (profile?.email) try {
7997
+ getLedger().setCachedEnrichment(profile.email.trim().toLowerCase(), JSON.stringify(enriched.result));
7998
+ } catch {}
7072
7999
  if (profile?.email) return {
7073
8000
  email: profile.email,
7074
8001
  fullName: profile.full_name ?? extract.authorFullName,
@@ -7290,7 +8217,7 @@ function normalizeRepoUrl(url) {
7290
8217
  * misleading issue/PR snippets that judged the parent repo on text it didn't
7291
8218
  * own. And discovery is free (no webSearch spend per query).
7292
8219
  */
7293
- const SOURCE = "find:github-topics";
8220
+ const SOURCE$1 = "find:github-topics";
7294
8221
  async function runGitHubTopicsFinder(opts) {
7295
8222
  const limit = opts.limit ?? 25;
7296
8223
  const minStars = Math.max(0, opts.minStars ?? 5);
@@ -7300,7 +8227,7 @@ async function runGitHubTopicsFinder(opts) {
7300
8227
  const useDeepResearch = opts.useDeepResearch !== false;
7301
8228
  const icp = resolveIcp(opts.icpOverride);
7302
8229
  const result = {
7303
- source: SOURCE,
8230
+ source: SOURCE$1,
7304
8231
  candidates: 0,
7305
8232
  droppedIcp: 0,
7306
8233
  droppedDuplicate: 0,
@@ -7357,7 +8284,7 @@ async function runGitHubTopicsFinder(opts) {
7357
8284
  halted: { value: false },
7358
8285
  limit,
7359
8286
  maxCostUsd: opts.maxCostUsd,
7360
- sourceTag: SOURCE,
8287
+ sourceTag: SOURCE$1,
7361
8288
  notesPrefix: "github-topic",
7362
8289
  dryRun: opts.dryRun
7363
8290
  };
@@ -7394,11 +8321,14 @@ function parseLastPage(link) {
7394
8321
  * page number, then page backward (newest → older), collecting stars with
7395
8322
  * `starredAt >= sinceIso` and stopping as soon as a page has none fresh (every
7396
8323
  * earlier page is older still) or `maxPages` is hit. Fault-tolerant like
7397
- * `searchTopicRepos`: returns `{ stargazers: [], error }` on any non-2xx /
7398
- * network / parse failure so the caller logs + continues to the next repo.
8324
+ * `searchTopicRepos`: returns `{ stargazers, error }` on any non-2xx / network
8325
+ * / parse failure so the caller logs + continues. A non-2xx on a BACKWARD page
8326
+ * surfaces as `error` (it usually means a rate-limit mid-walk) rather than
8327
+ * silently masquerading as "no recent stars".
7399
8328
  *
7400
8329
  * Requires `GITHUB_TOKEN` for any real volume (5,000 req/hr core); without it
7401
- * GitHub rate-limits hard at 60/hr.
8330
+ * GitHub rate-limits hard at 60/hr — which a backward walk through a big repo
8331
+ * hits fast.
7402
8332
  */
7403
8333
  async function recentStargazers(repo, opts) {
7404
8334
  const maxPages = Math.max(1, opts.maxPages ?? 20);
@@ -7407,6 +8337,17 @@ async function recentStargazers(repo, opts) {
7407
8337
  Accept: "application/vnd.github.star+json"
7408
8338
  };
7409
8339
  const base = `https://api.github.com/repos/${repo}/stargazers?per_page=100`;
8340
+ const out = [];
8341
+ let newestSeen = null;
8342
+ const dedupe = () => {
8343
+ const seen = /* @__PURE__ */ new Set();
8344
+ return out.filter((s) => {
8345
+ const key = s.login.toLowerCase();
8346
+ if (seen.has(key)) return false;
8347
+ seen.add(key);
8348
+ return true;
8349
+ });
8350
+ };
7410
8351
  try {
7411
8352
  const firstRes = await fetch(`${base}&page=1`, { headers });
7412
8353
  if (!firstRes.ok) {
@@ -7417,12 +8358,12 @@ async function recentStargazers(repo, opts) {
7417
8358
  }, "warn");
7418
8359
  return {
7419
8360
  stargazers: [],
8361
+ newestSeen: null,
7420
8362
  error: `status ${firstRes.status}`
7421
8363
  };
7422
8364
  }
7423
8365
  const lastPage = parseLastPage(firstRes.headers.get("link"));
7424
8366
  const page1Rows = await firstRes.json() ?? [];
7425
- const out = [];
7426
8367
  let pagesFetched = 1;
7427
8368
  for (let page = lastPage; page >= 1 && pagesFetched <= maxPages; page--) {
7428
8369
  let rows;
@@ -7430,20 +8371,28 @@ async function recentStargazers(repo, opts) {
7430
8371
  else {
7431
8372
  const res = await fetch(`${base}&page=${page}`, { headers });
7432
8373
  pagesFetched++;
7433
- if (!res.ok) break;
8374
+ if (!res.ok) {
8375
+ logEvent("github.stargazers", {
8376
+ repo,
8377
+ ok: false,
8378
+ status: res.status,
8379
+ page
8380
+ }, "warn");
8381
+ return {
8382
+ stargazers: dedupe(),
8383
+ newestSeen,
8384
+ error: `status ${res.status} on page ${page}`
8385
+ };
8386
+ }
7434
8387
  rows = await res.json() ?? [];
7435
8388
  }
7436
- const parsed = rows.map(parseStarRow).filter((s) => s !== null && s.starredAt >= opts.sinceIso);
7437
- out.push(...parsed);
7438
- if (parsed.length === 0) break;
8389
+ const parsed = rows.map(parseStarRow).filter((s) => s !== null);
8390
+ for (const s of parsed) if (!newestSeen || s.starredAt > newestSeen) newestSeen = s.starredAt;
8391
+ const fresh = parsed.filter((s) => s.starredAt >= opts.sinceIso);
8392
+ out.push(...fresh);
8393
+ if (fresh.length === 0) break;
7439
8394
  }
7440
- const seen = /* @__PURE__ */ new Set();
7441
- const stargazers = out.filter((s) => {
7442
- const key = s.login.toLowerCase();
7443
- if (seen.has(key)) return false;
7444
- seen.add(key);
7445
- return true;
7446
- });
8395
+ const stargazers = dedupe();
7447
8396
  logEvent("github.stargazers", {
7448
8397
  repo,
7449
8398
  ok: true,
@@ -7451,7 +8400,10 @@ async function recentStargazers(repo, opts) {
7451
8400
  last_page: lastPage,
7452
8401
  pages_fetched: pagesFetched
7453
8402
  });
7454
- return { stargazers };
8403
+ return {
8404
+ stargazers,
8405
+ newestSeen
8406
+ };
7455
8407
  } catch (err) {
7456
8408
  const message = (err.message ?? "").slice(0, 120);
7457
8409
  logEvent("github.stargazers", {
@@ -7460,19 +8412,20 @@ async function recentStargazers(repo, opts) {
7460
8412
  message_120: message
7461
8413
  }, "warn");
7462
8414
  return {
7463
- stargazers: [],
8415
+ stargazers: dedupe(),
8416
+ newestSeen,
7464
8417
  error: message
7465
8418
  };
7466
8419
  }
7467
8420
  }
7468
8421
  //#endregion
7469
8422
  //#region ../../packages/find/src/github-stars.ts
7470
- const PLAY_NAME = "github-stars";
8423
+ const PLAY_NAME$1 = "github-stars";
7471
8424
  function deriveLabel(repo) {
7472
8425
  return repo.split("/")[1]?.trim() || repo;
7473
8426
  }
7474
8427
  function sourceFor(repo) {
7475
- return `find:${PLAY_NAME}:${repo}`;
8428
+ return `find:${PLAY_NAME$1}:${repo}`;
7476
8429
  }
7477
8430
  /**
7478
8431
  * github-stars finder: recent stargazers of watched repos → prospects, routed
@@ -7490,7 +8443,7 @@ async function runGitHubStarsFinder(opts) {
7490
8443
  const icp = resolveIcp(opts.icpOverride);
7491
8444
  const ledger = getLedger();
7492
8445
  const result = {
7493
- source: `find:${PLAY_NAME}`,
8446
+ source: `find:${PLAY_NAME$1}`,
7494
8447
  candidates: 0,
7495
8448
  droppedIcp: 0,
7496
8449
  droppedDuplicate: 0,
@@ -7499,22 +8452,26 @@ async function runGitHubStarsFinder(opts) {
7499
8452
  costUsd: 0
7500
8453
  };
7501
8454
  logEvent("finder.start", {
7502
- name: PLAY_NAME,
8455
+ name: PLAY_NAME$1,
7503
8456
  repos: opts.repos.length,
7504
8457
  since_days: sinceDays,
7505
8458
  limit
7506
8459
  });
7507
8460
  const tagged = [];
7508
- let anyRepoOk = false;
8461
+ let firstError = null;
8462
+ let newestSeen = null;
7509
8463
  for (const w of opts.repos) {
7510
- const { stargazers, error } = await recentStargazers(w.repo, { sinceIso });
7511
- if (!error) anyRepoOk = true;
8464
+ const { stargazers, error, newestSeen: repoNewest } = await recentStargazers(w.repo, { sinceIso });
8465
+ if (error && !firstError) firstError = `${w.repo}: ${error}`;
8466
+ if (repoNewest && (!newestSeen || repoNewest > newestSeen)) newestSeen = repoNewest;
7512
8467
  const label = w.label?.trim() || deriveLabel(w.repo);
8468
+ const repoEdge = w.repoEdge?.trim();
7513
8469
  for (const s of stargazers) tagged.push({
7514
8470
  ...s,
7515
8471
  repo: w.repo,
7516
8472
  rel: w.rel,
7517
- label
8473
+ label,
8474
+ ...repoEdge ? { repoEdge } : {}
7518
8475
  });
7519
8476
  }
7520
8477
  const seen = /* @__PURE__ */ new Set();
@@ -7524,163 +8481,707 @@ async function runGitHubStarsFinder(opts) {
7524
8481
  seen.add(k);
7525
8482
  return true;
7526
8483
  });
7527
- result.candidates = candidates.length;
7528
- if (candidates.length === 0) {
7529
- result.halted = anyRepoOk ? "no recent stargazers in the window" : "all repos failed (check GITHUB_TOKEN / repo names)";
7530
- logEvent("finder.done", {
7531
- name: PLAY_NAME,
7532
- candidates: 0,
7533
- halted: result.halted
7534
- });
7535
- return result;
7536
- }
7537
- let halted = false;
7538
- await parallelMap(candidates, concurrency, async (c) => {
7539
- if (halted) return;
7540
- if (result.enqueued >= limit) {
7541
- halted = true;
7542
- return;
8484
+ result.candidates = candidates.length;
8485
+ if (candidates.length === 0) {
8486
+ if (firstError) result.halted = `github fetch failed (${firstError}) — set GITHUB_TOKEN for higher rate limits`;
8487
+ else if (newestSeen) result.halted = `no stars in last ${sinceDays}d — newest was ${Math.floor((Date.now() - new Date(newestSeen).getTime()) / 864e5)}d ago; widen sinceDays`;
8488
+ else result.halted = "no stargazers found (check repo names / GITHUB_TOKEN)";
8489
+ logEvent("finder.done", {
8490
+ name: PLAY_NAME$1,
8491
+ candidates: 0,
8492
+ halted: result.halted
8493
+ });
8494
+ return result;
8495
+ }
8496
+ let halted = false;
8497
+ await parallelMap(candidates, concurrency, async (c) => {
8498
+ if (halted) return;
8499
+ if (result.enqueued >= limit) {
8500
+ halted = true;
8501
+ return;
8502
+ }
8503
+ if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {
8504
+ result.halted = `max-cost cap (${opts.maxCostUsd})`;
8505
+ halted = true;
8506
+ return;
8507
+ }
8508
+ const playName = c.rel === "competitor" ? "competitor-switch" : "repo-interest";
8509
+ const dedupeKey = `${PLAY_NAME$1}:${c.repo}:${c.login}`;
8510
+ if (ledger.isQueueDuplicate(playName, dedupeKey)) {
8511
+ result.droppedDuplicate++;
8512
+ return;
8513
+ }
8514
+ const user = await fetchGitHubUser(c.login);
8515
+ if (!user) {
8516
+ result.droppedEnrichment++;
8517
+ return;
8518
+ }
8519
+ const fullName = user.name ?? c.login;
8520
+ const filter = await icpFilter({
8521
+ icp,
8522
+ candidate: {
8523
+ title: fullName,
8524
+ url: c.userUrl,
8525
+ summary: [user.company, `starred ${c.repo}`].filter(Boolean).join(" · ")
8526
+ }
8527
+ });
8528
+ if (filter.match === null) {
8529
+ result.droppedEnrichment++;
8530
+ return;
8531
+ }
8532
+ if (!filter.match) {
8533
+ result.droppedIcp++;
8534
+ if (!opts.dryRun) ledger.enqueueTarget({
8535
+ playName,
8536
+ payload: {
8537
+ name: fullName,
8538
+ company: user.company ?? "",
8539
+ repo: c.repo
8540
+ },
8541
+ dedupeKey,
8542
+ source: sourceFor(c.repo),
8543
+ initialStatus: "rejected",
8544
+ notes: `auto: ICP — ${filter.reason}`
8545
+ });
8546
+ return;
8547
+ }
8548
+ if (opts.dryRun) {
8549
+ result.enqueued++;
8550
+ return;
8551
+ }
8552
+ const contact = await resolveAndVerifyContact({
8553
+ playName: PLAY_NAME$1,
8554
+ fullName,
8555
+ knownEmail: user.email,
8556
+ companyDomain: user.blogDomain,
8557
+ isDuplicate: (email) => isDuplicate({
8558
+ playName,
8559
+ dedupeKey,
8560
+ prospectEmail: email
8561
+ })
8562
+ });
8563
+ result.costUsd += contact.costUsd;
8564
+ if (!contact.ok) {
8565
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
8566
+ else result.droppedEnrichment++;
8567
+ return;
8568
+ }
8569
+ const email = contact.email;
8570
+ const enr = await enrichVerifiedContact(email, {
8571
+ playName: PLAY_NAME$1,
8572
+ errKindPrefix: PLAY_NAME$1
8573
+ });
8574
+ result.costUsd += enr.costUsd;
8575
+ const company = user.company?.trim() || "(unknown)";
8576
+ const repoUrl = `https://github.com/${c.repo}`;
8577
+ const contactExtras = {
8578
+ ...enr.linkedinUrl ? { linkedinUrl: enr.linkedinUrl } : {},
8579
+ ...enr.phone ? { phone: enr.phone } : {}
8580
+ };
8581
+ const candidateRepos = c.rel === "competitor" ? void 0 : await fetchTopRepos(c.login) ?? void 0;
8582
+ const target = c.rel === "competitor" ? {
8583
+ name: fullName,
8584
+ email,
8585
+ company,
8586
+ competitor: c.label,
8587
+ evidenceUrl: repoUrl,
8588
+ evidenceText: `Starred ${c.label}'s repo (${c.repo}) on ${c.starredAt.slice(0, 10)} — actively evaluating tools in this space.`,
8589
+ yourEdge: opts.yourEdge,
8590
+ ...contactExtras
8591
+ } : {
8592
+ name: fullName,
8593
+ email,
8594
+ company,
8595
+ repo: c.repo,
8596
+ repoLabel: c.label,
8597
+ yourEdge: opts.yourEdge,
8598
+ ...c.repoEdge ? { repoEdge: c.repoEdge } : {},
8599
+ evidenceUrl: repoUrl,
8600
+ candidateLogin: c.login,
8601
+ ...candidateRepos ? { candidateRepos } : {},
8602
+ ...contactExtras
8603
+ };
8604
+ if (ledger.enqueueTarget({
8605
+ playName,
8606
+ payload: target,
8607
+ dedupeKey,
8608
+ source: sourceFor(c.repo),
8609
+ notes: filter.reason
8610
+ }) != null) result.enqueued++;
8611
+ else result.droppedDuplicate++;
8612
+ });
8613
+ logEvent("finder.done", {
8614
+ name: PLAY_NAME$1,
8615
+ candidates: result.candidates,
8616
+ enqueued: result.enqueued,
8617
+ dropped_icp: result.droppedIcp,
8618
+ dropped_dup: result.droppedDuplicate,
8619
+ dropped_enrich: result.droppedEnrichment,
8620
+ cost_usd: result.costUsd,
8621
+ halted: result.halted ?? null
8622
+ });
8623
+ return result;
8624
+ }
8625
+ //#endregion
8626
+ //#region ../../packages/find/src/_luma-auth.ts
8627
+ /**
8628
+ * Optional v2 path for the luma-events finder. When the founder has pasted
8629
+ * their `luma.auth-session-key` cookie into `LUMA_SESSION_COOKIE`, this helper
8630
+ * fetches the FULL guest list from Luma's internal API — the same call the
8631
+ * logged-in dashboard makes. Public-only mode (no cookie) caps coverage at
8632
+ * the 5-30 attendees Luma chose to surface; auth'd mode unlocks everyone
8633
+ * the founder could see by clicking the event in their browser.
8634
+ *
8635
+ * The endpoint is undocumented and may change. We try two URL shapes (the
8636
+ * `/admin/` and the bare variant) and fall back gracefully to null on any
8637
+ * 4xx / shape drift / network blip. The caller (luma.ts) treats null as
8638
+ * "stay in public-only mode for this event" — no crash.
8639
+ *
8640
+ * TOS posture: this is the founder's own cookie hitting pages they could
8641
+ * read in a browser. The cookie value is never logged (only its presence is)
8642
+ * and never persisted by this codebase beyond the `~/.oneshot-gtm/.env` file
8643
+ * the founder owns.
8644
+ */
8645
+ const ENDPOINTS = ["https://api.lu.ma/event/admin/get-guest-list", "https://api.lu.ma/event/get-guest-list"];
8646
+ const COOKIE_NAME = "luma.auth-session-key";
8647
+ const REQUEST_TIMEOUT_MS = 1e4;
8648
+ const USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 oneshot-gtm/luma-events";
8649
+ const MAX_AUTHED_ATTENDEES = 30;
8650
+ function buildLinkedinUrl(input) {
8651
+ if (!input) return null;
8652
+ const v = String(input).trim();
8653
+ if (v.length === 0) return null;
8654
+ if (/^https?:\/\//i.test(v)) return v;
8655
+ return `https://www.linkedin.com/in/${v.replace(/^(?:www\.)?linkedin\.com\/in\//i, "").replace(/^@/, "")}`;
8656
+ }
8657
+ function buildTwitterUrl(input) {
8658
+ if (!input) return null;
8659
+ const v = String(input).trim();
8660
+ if (v.length === 0) return null;
8661
+ if (/^https?:\/\//i.test(v)) return v;
8662
+ return `https://x.com/${v.replace(/^(?:www\.)?(?:twitter\.com|x\.com)\//i, "").replace(/^@/, "")}`;
8663
+ }
8664
+ function projectRawGuest(raw) {
8665
+ const u = raw.user ?? null;
8666
+ const name = (u?.name ?? raw.name ?? "").trim();
8667
+ if (!name) return null;
8668
+ return {
8669
+ name,
8670
+ profileUrl: u?.url ?? null,
8671
+ websiteUrl: u?.website ?? null,
8672
+ linkedinUrl: buildLinkedinUrl(u?.linkedin_handle),
8673
+ twitterUrl: buildTwitterUrl(u?.twitter_handle),
8674
+ bio: u?.bio_short ?? u?.bio ?? null,
8675
+ role: raw.role ?? raw.registration_status ?? null
8676
+ };
8677
+ }
8678
+ /**
8679
+ * Fetch a Luma event's full guest list using the founder's session cookie.
8680
+ * Returns null on any failure mode (no cookie, expired cookie, 4xx, shape
8681
+ * drift, network blip) — the caller falls back to public-only mode.
8682
+ */
8683
+ async function fetchAuthedGuestList(eventSlug, cookie) {
8684
+ if (!cookie || !eventSlug) return null;
8685
+ const cookieHeader = `${COOKIE_NAME}=${cookie}`;
8686
+ let lastStatus = null;
8687
+ for (const base of ENDPOINTS) {
8688
+ const url = `${base}?event_api_id=${encodeURIComponent(eventSlug)}`;
8689
+ let res;
8690
+ try {
8691
+ res = await fetch(url, {
8692
+ method: "GET",
8693
+ headers: {
8694
+ Accept: "application/json",
8695
+ Cookie: cookieHeader,
8696
+ "User-Agent": USER_AGENT
8697
+ },
8698
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
8699
+ });
8700
+ } catch (err) {
8701
+ logEvent("error.swallowed", {
8702
+ kind: "luma-events.auth_fetch",
8703
+ slug: eventSlug,
8704
+ message_120: (err.message ?? "").slice(0, 120)
8705
+ }, "warn");
8706
+ lastStatus = null;
8707
+ continue;
8708
+ }
8709
+ lastStatus = res.status;
8710
+ if (res.status === 404) continue;
8711
+ if (res.status === 401 || res.status === 403) {
8712
+ logEvent("luma-events.auth_unauthorized", {
8713
+ slug: eventSlug,
8714
+ status: res.status
8715
+ }, "warn");
8716
+ return null;
8717
+ }
8718
+ if (!res.ok) {
8719
+ logEvent("error.swallowed", {
8720
+ kind: "luma-events.auth_status",
8721
+ slug: eventSlug,
8722
+ status: res.status
8723
+ }, "warn");
8724
+ return null;
8725
+ }
8726
+ let body;
8727
+ try {
8728
+ body = await res.json();
8729
+ } catch {
8730
+ logEvent("error.swallowed", {
8731
+ kind: "luma-events.auth_parse",
8732
+ slug: eventSlug
8733
+ }, "warn");
8734
+ return null;
8735
+ }
8736
+ const parsed = body;
8737
+ const raws = parsed?.entries ?? parsed?.guests ?? null;
8738
+ if (!Array.isArray(raws)) {
8739
+ logEvent("error.swallowed", {
8740
+ kind: "luma-events.auth_shape",
8741
+ slug: eventSlug
8742
+ }, "warn");
8743
+ return null;
8744
+ }
8745
+ const projected = [];
8746
+ for (const raw of raws) {
8747
+ const a = projectRawGuest(raw);
8748
+ if (a) projected.push(a);
8749
+ if (projected.length >= MAX_AUTHED_ATTENDEES) break;
8750
+ }
8751
+ return projected;
8752
+ }
8753
+ if (lastStatus === 404) logEvent("error.swallowed", {
8754
+ kind: "luma-events.auth_404_all_endpoints",
8755
+ slug: eventSlug
8756
+ }, "warn");
8757
+ return null;
8758
+ }
8759
+ /**
8760
+ * Merge public (LLM-extracted) attendees with auth'd attendees. Dedupe key is
8761
+ * the lowercased trimmed name; matches the per-event dedupe key used downstream.
8762
+ *
8763
+ * Per-field union: when both sides have an entry for the same name, the auth
8764
+ * value wins on conflict, but public values fill in any nulls. This handles
8765
+ * the realistic case where the auth API doesn't surface a field (`linkedinUrl`
8766
+ * = null) that the LLM caught from a visible attendee card.
8767
+ */
8768
+ function mergeAttendees(publicList, authedList) {
8769
+ const byName = /* @__PURE__ */ new Map();
8770
+ for (const a of publicList) {
8771
+ const key = a.name.trim().toLowerCase();
8772
+ if (key.length === 0) continue;
8773
+ byName.set(key, a);
8774
+ }
8775
+ for (const auth of authedList) {
8776
+ const key = auth.name.trim().toLowerCase();
8777
+ if (key.length === 0) continue;
8778
+ const pub = byName.get(key);
8779
+ if (!pub) {
8780
+ byName.set(key, auth);
8781
+ continue;
8782
+ }
8783
+ byName.set(key, {
8784
+ name: auth.name,
8785
+ profileUrl: auth.profileUrl ?? pub.profileUrl,
8786
+ websiteUrl: auth.websiteUrl ?? pub.websiteUrl,
8787
+ linkedinUrl: auth.linkedinUrl ?? pub.linkedinUrl,
8788
+ twitterUrl: auth.twitterUrl ?? pub.twitterUrl,
8789
+ bio: auth.bio ?? pub.bio,
8790
+ role: auth.role ?? pub.role
8791
+ });
8792
+ }
8793
+ return [...byName.values()];
8794
+ }
8795
+ //#endregion
8796
+ //#region ../../packages/find/src/luma.ts
8797
+ const PLAY_NAME = "luma-events";
8798
+ const SOURCE = "find:luma-events";
8799
+ /** Cap per-event LLM extract input — Luma event pages are usually under 8k chars. */
8800
+ const READ_MARKDOWN_SLICE = 12e3;
8801
+ /** Sane upper bound — no event we care about has >30 public attendees. */
8802
+ const MAX_ATTENDEES_PER_EVENT = 30;
8803
+ /**
8804
+ * Extract the single-segment slug from a Luma event URL. Returns null when
8805
+ * the URL isn't a single-event page. Used to address Luma's internal API
8806
+ * (`api.lu.ma/event/get-guest-list?event_api_id=<slug>`) when the founder
8807
+ * has set `LUMA_SESSION_COOKIE`.
8808
+ */
8809
+ function lumaEventSlug(url) {
8810
+ try {
8811
+ const u = new URL(url);
8812
+ if (!/^(www\.)?(luma\.com|lu\.ma)$/.test(u.hostname)) return null;
8813
+ const segments = u.pathname.split("/").filter((s) => s.length > 0);
8814
+ if (segments.length !== 1) return null;
8815
+ return segments[0] ?? null;
8816
+ } catch {
8817
+ return null;
8818
+ }
8819
+ }
8820
+ function looksLikeLumaEventUrl(url) {
8821
+ try {
8822
+ const u = new URL(url);
8823
+ if (!/^(www\.)?(luma\.com|lu\.ma)$/.test(u.hostname)) return false;
8824
+ if (u.searchParams.has("k")) return false;
8825
+ const segments = u.pathname.split("/").filter((s) => s.length > 0);
8826
+ if (segments.length !== 1) return false;
8827
+ return !new Set([
8828
+ "discover",
8829
+ "home",
8830
+ "events",
8831
+ "calendars",
8832
+ "create",
8833
+ "login",
8834
+ "signup",
8835
+ "user"
8836
+ ]).has(segments[0].toLowerCase());
8837
+ } catch {
8838
+ return false;
8839
+ }
8840
+ }
8841
+ async function runLumaFinder(opts) {
8842
+ const limit = opts.limit ?? 25;
8843
+ const sinceDays = opts.sinceDays ?? 14;
8844
+ const topics = (opts.topics ?? []).filter((t) => t.trim().length > 0);
8845
+ const cities = (opts.cities ?? []).filter((c) => c.trim().length > 0);
8846
+ const yourEdge = (opts.yourEdge ?? "").trim();
8847
+ const icp = resolveIcp(opts.icpOverride);
8848
+ const ledger = getLedger();
8849
+ const extractSystem = loadPrompt("luma-event-extract");
8850
+ const sessionCookie = (process.env["LUMA_SESSION_COOKIE"] ?? "").trim();
8851
+ if (!sessionCookie) logEvent("luma-events.cookie_unset", { hint: "set LUMA_SESSION_COOKIE in ~/.oneshot-gtm/.env to unlock the full guest list" }, "info");
8852
+ const result = {
8853
+ source: SOURCE,
8854
+ candidates: 0,
8855
+ droppedIcp: 0,
8856
+ droppedDuplicate: 0,
8857
+ droppedEnrichment: 0,
8858
+ enqueued: 0,
8859
+ costUsd: 0,
8860
+ halted: void 0
8861
+ };
8862
+ const seenUrls = /* @__PURE__ */ new Set();
8863
+ const hits = [];
8864
+ outer: for (const topic of topics) for (const city of cities) {
8865
+ if (hits.length >= limit * 3) break outer;
8866
+ const query = `site:luma.com "${topic}" "${city}" event`;
8867
+ try {
8868
+ const search = await webSearch({
8869
+ query,
8870
+ maxResults: Math.min(10, limit)
8871
+ }, {
8872
+ playName: PLAY_NAME,
8873
+ decisionContext: {
8874
+ source: "finder",
8875
+ topic,
8876
+ city
8877
+ }
8878
+ });
8879
+ result.costUsd += search.result.cost ?? 0;
8880
+ for (const hit of search.result.results ?? []) {
8881
+ if (!hit.url) continue;
8882
+ if (!looksLikeLumaEventUrl(hit.url)) continue;
8883
+ const canonical = hit.url.split("?")[0].replace(/\/$/, "");
8884
+ if (seenUrls.has(canonical)) continue;
8885
+ seenUrls.add(canonical);
8886
+ hits.push({
8887
+ url: canonical,
8888
+ title: hit.title,
8889
+ description: hit.description
8890
+ });
8891
+ }
8892
+ } catch (err) {
8893
+ logEvent("error.swallowed", {
8894
+ kind: "luma-events.webSearch",
8895
+ topic,
8896
+ city,
8897
+ message_120: (err.message ?? "").slice(0, 120)
8898
+ }, "warn");
8899
+ }
8900
+ }
8901
+ result.candidates = hits.length;
8902
+ const eventExtracts = await parallelMap(hits.slice(0, limit * 2), 3, async (hit) => {
8903
+ if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) return null;
8904
+ try {
8905
+ const read = await webRead({ url: hit.url }, {
8906
+ playName: PLAY_NAME,
8907
+ decisionContext: {
8908
+ source: "finder",
8909
+ eventUrl: hit.url
8910
+ }
8911
+ });
8912
+ result.costUsd += read.result.cost ?? 0;
8913
+ const payload = {
8914
+ url: hit.url,
8915
+ title: hit.title,
8916
+ description: hit.description,
8917
+ markdown: (read.result.markdown ?? "").slice(0, READ_MARKDOWN_SLICE)
8918
+ };
8919
+ const extract = parseLumaEventExtract((await complete({
8920
+ messages: [{
8921
+ role: "system",
8922
+ content: extractSystem
8923
+ }, {
8924
+ role: "user",
8925
+ content: JSON.stringify(payload)
8926
+ }],
8927
+ temperature: .1,
8928
+ maxTokens: 1500
8929
+ })).content);
8930
+ if (!extract.eventTitle) {
8931
+ logEvent("finder.skipped_non_event", {
8932
+ name: PLAY_NAME,
8933
+ url: hit.url
8934
+ }, "info");
8935
+ return null;
8936
+ }
8937
+ if (extract.eventHasPassed) {
8938
+ logEvent("finder.skipped_past_event", {
8939
+ name: PLAY_NAME,
8940
+ url: hit.url,
8941
+ eventTitle: extract.eventTitle
8942
+ }, "info");
8943
+ return null;
8944
+ }
8945
+ if (!extract.eventDateIso) {
8946
+ logEvent("finder.skipped_no_event_date", {
8947
+ name: PLAY_NAME,
8948
+ url: hit.url,
8949
+ eventTitle: extract.eventTitle
8950
+ }, "info");
8951
+ return null;
8952
+ }
8953
+ const eventMs = new Date(extract.eventDateIso).getTime();
8954
+ if (!Number.isFinite(eventMs) || eventMs < Date.now() - 24 * 3600 * 1e3) {
8955
+ logEvent("finder.skipped_past_event", {
8956
+ name: PLAY_NAME,
8957
+ url: hit.url,
8958
+ eventTitle: extract.eventTitle,
8959
+ eventDateIso: extract.eventDateIso,
8960
+ reason: "date defense"
8961
+ }, "info");
8962
+ return null;
8963
+ }
8964
+ if (eventMs > Date.now() + sinceDays * 24 * 3600 * 1e3) {
8965
+ logEvent("finder.skipped_too_far_out", {
8966
+ name: PLAY_NAME,
8967
+ url: hit.url,
8968
+ eventTitle: extract.eventTitle,
8969
+ eventDateIso: extract.eventDateIso,
8970
+ sinceDays
8971
+ }, "info");
8972
+ return null;
8973
+ }
8974
+ if (sessionCookie) {
8975
+ const slug = lumaEventSlug(hit.url);
8976
+ if (slug) {
8977
+ const authed = await fetchAuthedGuestList(slug, sessionCookie);
8978
+ if (authed) {
8979
+ const before = extract.publicAttendees.length;
8980
+ const merged = mergeAttendees(extract.publicAttendees, authed);
8981
+ extract.publicAttendees = merged;
8982
+ logEvent("finder.luma_auth.success", {
8983
+ name: PLAY_NAME,
8984
+ slug,
8985
+ public_count: before,
8986
+ authed_count: authed.length,
8987
+ merged_count: merged.length
8988
+ }, "info");
8989
+ }
8990
+ }
8991
+ }
8992
+ if (extract.publicAttendees.length < 2) {
8993
+ logEvent("finder.skipped_no_public_guests", {
8994
+ name: PLAY_NAME,
8995
+ url: hit.url,
8996
+ eventTitle: extract.eventTitle
8997
+ }, "info");
8998
+ return null;
8999
+ }
9000
+ return {
9001
+ hit,
9002
+ extract
9003
+ };
9004
+ } catch (err) {
9005
+ logEvent("error.swallowed", {
9006
+ kind: "luma-events.extract",
9007
+ url: hit.url,
9008
+ message_120: (err.message ?? "").slice(0, 120)
9009
+ }, "warn");
9010
+ return null;
9011
+ }
9012
+ });
9013
+ const attendeesWork = [];
9014
+ for (const item of eventExtracts) {
9015
+ if (!item) continue;
9016
+ const { hit, extract } = item;
9017
+ const eventCtx = {
9018
+ url: hit.url,
9019
+ title: extract.eventTitle ?? hit.title,
9020
+ dateIso: extract.eventDateIso ?? "",
9021
+ city: extract.eventCity ?? ""
9022
+ };
9023
+ for (const attendee of extract.publicAttendees.slice(0, MAX_ATTENDEES_PER_EVENT)) {
9024
+ if (!attendee.name || attendee.name.trim().length === 0) continue;
9025
+ attendeesWork.push({
9026
+ attendee,
9027
+ event: eventCtx
9028
+ });
7543
9029
  }
9030
+ }
9031
+ for (const work of attendeesWork) {
9032
+ if (result.enqueued >= limit) break;
7544
9033
  if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {
7545
9034
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
7546
- halted = true;
7547
- return;
9035
+ break;
7548
9036
  }
7549
- const playName = c.rel === "competitor" ? "competitor-switch" : "repo-interest";
7550
- const dedupeKey = `${PLAY_NAME}:${c.repo}:${c.login}`;
7551
- if (ledger.isQueueDuplicate(playName, dedupeKey)) {
9037
+ const dedupeKey = `${work.event.url}#${work.attendee.name.toLowerCase()}`;
9038
+ if (ledger.isQueueDuplicate(PLAY_NAME, dedupeKey)) {
7552
9039
  result.droppedDuplicate++;
7553
- return;
9040
+ continue;
7554
9041
  }
7555
- const user = await fetchGitHubUser(c.login);
7556
- if (!user) {
7557
- result.droppedEnrichment++;
7558
- return;
9042
+ if (opts.dryRun) {
9043
+ result.enqueued++;
9044
+ continue;
7559
9045
  }
7560
- const fullName = user.name ?? c.login;
7561
9046
  const filter = await icpFilter({
7562
9047
  icp,
7563
9048
  candidate: {
7564
- title: fullName,
7565
- url: c.userUrl,
7566
- summary: [user.company, `starred ${c.repo}`].filter(Boolean).join(" · ")
9049
+ title: `${work.attendee.name} — ${work.attendee.bio ?? work.attendee.role ?? ""}`,
9050
+ url: work.attendee.profileUrl ?? work.event.url,
9051
+ summary: `Going to: ${work.event.title} in ${work.event.city}. ${work.attendee.bio ?? ""}`
7567
9052
  }
7568
9053
  });
9054
+ if (filter.match === null) {
9055
+ result.droppedEnrichment++;
9056
+ continue;
9057
+ }
7569
9058
  if (!filter.match) {
7570
9059
  result.droppedIcp++;
7571
- if (!opts.dryRun) ledger.enqueueTarget({
7572
- playName,
9060
+ ledger.enqueueTarget({
9061
+ playName: PLAY_NAME,
7573
9062
  payload: {
7574
- name: fullName,
7575
- company: user.company ?? "",
7576
- repo: c.repo
9063
+ ...work.attendee,
9064
+ event: work.event
7577
9065
  },
7578
9066
  dedupeKey,
7579
- source: sourceFor(c.repo),
9067
+ source: SOURCE,
7580
9068
  initialStatus: "rejected",
7581
9069
  notes: `auto: ICP — ${filter.reason}`
7582
9070
  });
7583
- return;
7584
- }
7585
- if (opts.dryRun) {
7586
- result.enqueued++;
7587
- return;
9071
+ continue;
7588
9072
  }
7589
- let email = user.email;
7590
- if (!email) {
7591
- const domain = user.blogDomain;
7592
- if (!domain) {
7593
- result.droppedEnrichment++;
7594
- return;
7595
- }
7596
- const skip = shouldSkipFindEmail({
7597
- fullName,
7598
- companyDomain: domain
9073
+ let companyDomain = null;
9074
+ let resolvedLinkedinUrl = isLinkedInProfileUrl(work.attendee.linkedinUrl) ? work.attendee.linkedinUrl : null;
9075
+ let resolvedCompany = null;
9076
+ let surfacedEmail = null;
9077
+ if (resolvedLinkedinUrl) try {
9078
+ const enr = await enrichProfile({
9079
+ linkedinUrl: resolvedLinkedinUrl,
9080
+ name: work.attendee.name
9081
+ }, {
9082
+ playName: PLAY_NAME,
9083
+ decisionContext: {
9084
+ source: "finder",
9085
+ linkedinUrl: resolvedLinkedinUrl
9086
+ }
7599
9087
  });
7600
- if (!skip.ok) {
7601
- result.droppedEnrichment++;
7602
- logEvent("finder.skipped_findemail", {
7603
- name: PLAY_NAME,
7604
- reason: skip.reason
7605
- }, "info");
7606
- return;
7607
- }
7608
- const found = await findEmail({
7609
- companyDomain: domain,
7610
- fullName
7611
- }, { playName: PLAY_NAME });
7612
- result.costUsd += found.result.cost ?? 0;
7613
- if (!found.result.found || !found.result.email) {
7614
- result.droppedEnrichment++;
7615
- return;
7616
- }
7617
- email = found.result.email;
7618
- }
7619
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME });
7620
- result.costUsd += verified.result.cost ?? 0;
7621
- if (!verified.result.deliverable) {
7622
- result.droppedEnrichment++;
7623
- return;
9088
+ result.costUsd += enr.result.cost ?? 0;
9089
+ const profile = enr.result.profile;
9090
+ companyDomain = profile?.company_domain ?? null;
9091
+ resolvedCompany = profile?.company ?? null;
9092
+ surfacedEmail = profile?.best_work_email ?? profile?.email ?? null;
9093
+ if (surfacedEmail) try {
9094
+ getLedger().setCachedEnrichment(surfacedEmail.trim().toLowerCase(), JSON.stringify(enr.result));
9095
+ } catch {}
9096
+ } catch (err) {
9097
+ logEvent("error.swallowed", {
9098
+ kind: "luma-events.enrichProfile",
9099
+ message_120: (err.message ?? "").slice(0, 120)
9100
+ }, "warn");
7624
9101
  }
7625
- if (isDuplicate({
7626
- playName,
7627
- dedupeKey,
7628
- prospectEmail: email
7629
- })) {
7630
- result.droppedDuplicate++;
7631
- return;
9102
+ if (!companyDomain && work.attendee.websiteUrl) companyDomain = urlDomain(work.attendee.websiteUrl);
9103
+ const contact = await resolveAndVerifyContact({
9104
+ playName: PLAY_NAME,
9105
+ fullName: work.attendee.name,
9106
+ knownEmail: surfacedEmail,
9107
+ companyDomain,
9108
+ isDuplicate: (email) => isDuplicate({
9109
+ playName: PLAY_NAME,
9110
+ dedupeKey,
9111
+ prospectEmail: email
9112
+ }),
9113
+ decisionContext: {
9114
+ source: "finder",
9115
+ attendeeName: work.attendee.name,
9116
+ companyDomain,
9117
+ eventUrl: work.event.url
9118
+ }
9119
+ });
9120
+ result.costUsd += contact.costUsd;
9121
+ if (!contact.ok) {
9122
+ if (contact.reason === "no-domain") logEvent("finder.skipped_no_contact_domain", {
9123
+ name: PLAY_NAME,
9124
+ attendeeName: work.attendee.name,
9125
+ eventUrl: work.event.url
9126
+ }, "info");
9127
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
9128
+ else result.droppedEnrichment++;
9129
+ continue;
7632
9130
  }
9131
+ const email = contact.email;
7633
9132
  const enr = await enrichVerifiedContact(email, {
7634
9133
  playName: PLAY_NAME,
7635
- errKindPrefix: PLAY_NAME
9134
+ errKindPrefix: "luma-events"
7636
9135
  });
7637
9136
  result.costUsd += enr.costUsd;
7638
- const company = user.company?.trim() || "(unknown)";
7639
- const repoUrl = `https://github.com/${c.repo}`;
7640
- const contactExtras = {
7641
- ...enr.linkedinUrl ? { linkedinUrl: enr.linkedinUrl } : {},
7642
- ...enr.phone ? { phone: enr.phone } : {}
7643
- };
7644
- const target = c.rel === "competitor" ? {
7645
- name: fullName,
7646
- email,
7647
- company,
7648
- competitor: c.label,
7649
- evidenceUrl: repoUrl,
7650
- evidenceText: `Starred ${c.label}'s repo (${c.repo}) on ${c.starredAt.slice(0, 10)} — actively evaluating tools in this space.`,
7651
- yourEdge: opts.yourEdge,
7652
- ...contactExtras
7653
- } : {
7654
- name: fullName,
9137
+ const phone = enr.phone;
9138
+ let linkedinUrl = resolvedLinkedinUrl ?? enr.linkedinUrl;
9139
+ if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
9140
+ fullName: work.attendee.name,
9141
+ disambiguators: [work.event.title, work.event.city].filter((s) => s.length > 0),
9142
+ accumCost: (c) => {
9143
+ result.costUsd += c ?? 0;
9144
+ },
9145
+ errKindPrefix: "luma-events"
9146
+ });
9147
+ const target = {
9148
+ name: work.attendee.name,
7655
9149
  email,
7656
- company,
7657
- repo: c.repo,
7658
- repoLabel: c.label,
7659
- yourEdge: opts.yourEdge,
7660
- evidenceUrl: repoUrl,
7661
- ...contactExtras
9150
+ ...resolvedCompany ? { company: resolvedCompany } : {},
9151
+ ...work.attendee.bio || work.attendee.role ? { attendeeBio: work.attendee.bio ?? work.attendee.role ?? "" } : {},
9152
+ eventTitle: work.event.title,
9153
+ eventDate: work.event.dateIso,
9154
+ eventCity: work.event.city,
9155
+ eventUrl: work.event.url,
9156
+ yourEdge,
9157
+ ...linkedinUrl ? { linkedinUrl } : {},
9158
+ ...phone ? { phone } : {}
7662
9159
  };
7663
9160
  if (ledger.enqueueTarget({
7664
- playName,
9161
+ playName: PLAY_NAME,
7665
9162
  payload: target,
7666
9163
  dedupeKey,
7667
- source: sourceFor(c.repo),
7668
- notes: filter.reason
9164
+ source: SOURCE,
9165
+ notes: `${work.attendee.name} going to ${work.event.title} — ${filter.reason}`
7669
9166
  }) != null) result.enqueued++;
7670
9167
  else result.droppedDuplicate++;
7671
- });
7672
- logEvent("finder.done", {
7673
- name: PLAY_NAME,
7674
- candidates: result.candidates,
7675
- enqueued: result.enqueued,
7676
- dropped_icp: result.droppedIcp,
7677
- dropped_dup: result.droppedDuplicate,
7678
- dropped_enrich: result.droppedEnrichment,
7679
- cost_usd: result.costUsd,
7680
- halted: result.halted ?? null
7681
- });
9168
+ }
7682
9169
  return result;
7683
9170
  }
9171
+ function parseLumaEventExtract(raw) {
9172
+ const parsed = tryParseJsonObject(raw, {
9173
+ eventTitle: null,
9174
+ eventDateIso: null,
9175
+ eventCity: null,
9176
+ eventHasPassed: false,
9177
+ publicAttendees: []
9178
+ });
9179
+ if (!Array.isArray(parsed.publicAttendees)) return {
9180
+ ...parsed,
9181
+ publicAttendees: []
9182
+ };
9183
+ return parsed;
9184
+ }
7684
9185
  //#endregion
7685
9186
  //#region ../../packages/find/src/registry.ts
7686
9187
  /** Evaluate a spec's readiness fn (defaulting to ready when absent). */
@@ -7925,6 +9426,47 @@ const TRIGGERS = [
7925
9426
  maxCostUsd: cfg["maxCostUsd"] ?? 5
7926
9427
  })
7927
9428
  },
9429
+ {
9430
+ name: "luma-events",
9431
+ defaultIntervalMs: 24 * ONE_HOUR,
9432
+ enabledByDefault: false,
9433
+ defaultConfig: {
9434
+ topics: ["AI", "founders"],
9435
+ cities: ["San Francisco", "New York"],
9436
+ sinceDays: 14,
9437
+ yourEdge: "",
9438
+ limit: 25,
9439
+ maxCostUsd: 5
9440
+ },
9441
+ configBrief: "Discovers upcoming Luma events whose topic + city overlap with the founder's ICP, then pitches the publicly-visible attendees — speakers, sponsors, featured guests, and whoever the organizer surfaced via 'Show Who's Coming'. Coverage per event is 5-30 attendees (the highest-signal subset Luma exposes without login). Config: `topics` (phrases combined with cities into webSearch queries — e.g. ['AI', 'founders', 'product']), `cities` (e.g. ['San Francisco', 'New York']), `yourEdge` (one-line angle on why your product helps event-going people, REQUIRED), `sinceDays` (forward-looking window in days — events further out than this are dropped), `limit`, `maxCostUsd`. STRATEGIST DUTY: align topics to your ICP's actual gathering spots (AI hackers ≠ growth marketers); city list narrows search recall.",
9442
+ readiness: (cfg) => {
9443
+ const topics = Array.isArray(cfg["topics"]) ? cfg["topics"] : null;
9444
+ if (!topics || topics.filter((t) => typeof t === "string" && t.trim()).length === 0) return {
9445
+ ready: false,
9446
+ reason: "set `topics` (e.g. ['AI','founders'])"
9447
+ };
9448
+ const cities = Array.isArray(cfg["cities"]) ? cfg["cities"] : null;
9449
+ if (!cities || cities.filter((c) => typeof c === "string" && c.trim()).length === 0) return {
9450
+ ready: false,
9451
+ reason: "set `cities` (e.g. ['San Francisco'])"
9452
+ };
9453
+ const edge = cfg["yourEdge"];
9454
+ if (typeof edge !== "string" || edge.trim().length === 0) return {
9455
+ ready: false,
9456
+ reason: "set `yourEdge` — one-line pitch for event attendees"
9457
+ };
9458
+ return { ready: true };
9459
+ },
9460
+ run: (cfg) => runLumaFinder({
9461
+ dryRun: false,
9462
+ ...Array.isArray(cfg["topics"]) ? { topics: cfg["topics"].filter((t) => typeof t === "string") } : {},
9463
+ ...Array.isArray(cfg["cities"]) ? { cities: cfg["cities"].filter((c) => typeof c === "string") } : {},
9464
+ ...typeof cfg["yourEdge"] === "string" ? { yourEdge: cfg["yourEdge"] } : {},
9465
+ sinceDays: cfg["sinceDays"] ?? 14,
9466
+ limit: cfg["limit"] ?? 25,
9467
+ maxCostUsd: cfg["maxCostUsd"] ?? 5
9468
+ })
9469
+ },
7928
9470
  {
7929
9471
  name: "github-topics",
7930
9472
  defaultIntervalMs: 12 * ONE_HOUR,
@@ -7990,7 +9532,7 @@ const TRIGGERS = [
7990
9532
  limit: 25,
7991
9533
  maxCostUsd: 5
7992
9534
  },
7993
- configBrief: "Finds recent stargazers of repos you watch and turns them into prospects. Config: `repos` (array of `{repo:\"owner/name\", rel:\"competitor\"|\"adjacent\", label?}` — tag a repo `competitor` to pitch a switch (→ competitor-switch) or `adjacent` for a complementary intro (→ repo-interest); `label` is the human name, else derived from the repo), `yourEdge` (one-line pitch fed to whichever play, REQUIRED), `sinceDays` (recency window, default 30), `limit`, `maxCostUsd`. Needs `GITHUB_TOKEN` for any volume. STRATEGIST DUTY: pick repos your buyers' current tools live in; tag the ones you replace as `competitor`, the rest `adjacent`.",
9535
+ configBrief: "Finds recent stargazers of repos you watch and turns them into prospects. Config: `repos` (array of `{repo:\"owner/name\", rel:\"competitor\"|\"adjacent\", label?, repoEdge?}` — tag a repo `competitor` to pitch a switch (→ competitor-switch) or `adjacent` for a complementary intro (→ repo-interest); `label` is the human name, else derived from the repo; `repoEdge` is an OPTIONAL per-repo line on why THAT repo is notable + the respectful bridge to your offer, used by repo-interest as a shared-taste nod that also shapes the pitch — e.g. a privacy-first repo leads with control/auditability, not \"we do it for you\"), `yourEdge` (one-line pitch fed to whichever play, REQUIRED), `sinceDays` (recency window, default 30), `limit`, `maxCostUsd`. Needs `GITHUB_TOKEN` for any volume. STRATEGIST DUTY: pick repos your buyers' current tools live in; tag the ones you replace as `competitor`, the rest `adjacent`; give each adjacent repo a `repoEdge` so the intro nods to why they chose THAT tool.",
7994
9536
  readiness: (cfg) => {
7995
9537
  if ((Array.isArray(cfg["repos"]) ? cfg["repos"] : []).filter((r) => {
7996
9538
  if (!r || typeof r !== "object") return false;
@@ -8017,11 +9559,13 @@ const TRIGGERS = [
8017
9559
  const rel = e["rel"];
8018
9560
  if (repo.length === 0 || rel !== "competitor" && rel !== "adjacent") return null;
8019
9561
  const label = typeof e["label"] === "string" ? e["label"].trim() : "";
9562
+ const repoEdge = typeof e["repoEdge"] === "string" ? e["repoEdge"].trim() : "";
8020
9563
  const watch = {
8021
9564
  repo,
8022
9565
  rel
8023
9566
  };
8024
9567
  if (label) watch.label = label;
9568
+ if (repoEdge) watch.repoEdge = repoEdge;
8025
9569
  return watch;
8026
9570
  }).filter((r) => r !== null),
8027
9571
  yourEdge: typeof cfg["yourEdge"] === "string" ? cfg["yourEdge"] : "",
@@ -8041,7 +9585,7 @@ const TRIGGERS = [
8041
9585
  maxDays: 90,
8042
9586
  limit: 25
8043
9587
  },
8044
- configBrief: "Scans the founder's local prospect ledger for cold leads (no reply, marketable) within the day window and re-enqueues them for a pattern-interrupt revive. No OneShot/LLM spend (ledger-only). Config: `minDays` / `maxDays` (the cold-window — defaults 60-90), `limit`. Only enable when the founder has been sending for ≥2 months — empty ledger = no revives.",
9588
+ configBrief: "Scans the founder's local prospect ledger for cold leads (no reply, marketable) within the day window and re-enqueues them for a pattern-interrupt revive. No agent/LLM spend (ledger-only). Config: `minDays` / `maxDays` (the cold-window — defaults 60-90), `limit`. Only enable when the founder has been sending for ≥2 months — empty ledger = no revives.",
8045
9589
  run: async (cfg) => runBreakupReviveFinder({
8046
9590
  dryRun: false,
8047
9591
  minDays: cfg["minDays"] ?? 60,
@@ -8763,7 +10307,7 @@ async function runDoctor() {
8763
10307
  const pkSrc = secretSource("AGENT_PRIVATE_KEY");
8764
10308
  const walletSrc = process.env.AGENT_PRIVATE_KEY ? pkSrc : cdpSrc;
8765
10309
  results.push({
8766
- name: "oneshot wallet env",
10310
+ name: "wallet env",
8767
10311
  severity: oneshotEnvReady() ? "ok" : "fail",
8768
10312
  message: oneshotEnvReady() ? `${process.env.AGENT_PRIVATE_KEY ? "AGENT_PRIVATE_KEY" : "CDP wallet"} set (${walletSrc ?? "?"})` : "no wallet credentials",
8769
10313
  ...oneshotEnvReady() ? {} : { hint: "oneshot-gtm config keys" }
@@ -8826,15 +10370,22 @@ function toDraftedView(d) {
8826
10370
  * Dispatch a play by name and return one DraftedView per target (in order).
8827
10371
  * Shared by the SSE /api/run endpoint (multi-target) and the /queue
8828
10372
  * regenerate endpoint (single-target dry-run). Throws on unsupported plays.
10373
+ *
10374
+ * `onProgress`: optional per-target hook fired AFTER each target completes.
10375
+ * The SSE handler uses this to emit `draft` + `send` events live as they
10376
+ * happen instead of batching at the end. The PlayDraft → DraftedView
10377
+ * projection is applied inside the wrapper so the callback gets the same
10378
+ * shape downstream code expects.
8829
10379
  */
8830
- async function dispatchPlay(playName, body) {
10380
+ async function dispatchPlay(playName, body, onProgress) {
8831
10381
  const play = PLAYS[playName];
8832
10382
  if (!play) throw new Error(`unsupported play: ${playName}`);
8833
10383
  return (await play.run({
8834
10384
  dryRun: body.dryRun,
8835
10385
  targets: body.targets,
8836
10386
  ...body.senderCohort ? { senderCohort: body.senderCohort } : {},
8837
- ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
10387
+ ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {},
10388
+ ...onProgress ? { onProgress: (index, draft) => onProgress(index, toDraftedView(draft)) } : {}
8838
10389
  })).drafted.map(toDraftedView);
8839
10390
  }
8840
10391
  //#endregion
@@ -8848,7 +10399,8 @@ const SUPPORTED = new Set([
8848
10399
  "podcast-guest",
8849
10400
  "competitor-switch",
8850
10401
  "stack-consolidation",
8851
- "repo-interest"
10402
+ "repo-interest",
10403
+ "luma-events"
8852
10404
  ]);
8853
10405
  async function runPlay(req, params) {
8854
10406
  const playName = params["playName"] ?? "";
@@ -8860,13 +10412,31 @@ async function runPlay(req, params) {
8860
10412
  return jsonResponse({ error: "invalid JSON body" }, 400, req);
8861
10413
  }
8862
10414
  if (!Array.isArray(body.targets) || body.targets.length === 0) return jsonResponse({ error: "targets must be a non-empty array" }, 400, req);
10415
+ const { runId, startedAt } = getLedger().createRun({
10416
+ playName,
10417
+ dryRun: body.dryRun,
10418
+ targets: body.targets
10419
+ });
10420
+ const sentEmails = [];
8863
10421
  const stream = new ReadableStream({ async start(controller) {
8864
10422
  const encoder = new TextEncoder();
10423
+ const ledger = getLedger();
8865
10424
  const send = (event) => {
10425
+ try {
10426
+ ledger.appendRunEvent({
10427
+ runId,
10428
+ event
10429
+ });
10430
+ } catch {}
8866
10431
  try {
8867
10432
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
8868
10433
  } catch {}
8869
10434
  };
10435
+ send({
10436
+ kind: "runStarted",
10437
+ runId,
10438
+ startedAt
10439
+ });
8870
10440
  try {
8871
10441
  const emailToDedupeKey = /* @__PURE__ */ new Map();
8872
10442
  if (body.dedupeKeys && body.dedupeKeys.length === body.targets.length) body.targets.forEach((t, i) => {
@@ -8919,9 +10489,8 @@ async function runPlay(req, params) {
8919
10489
  kind: "stage",
8920
10490
  stage: body.dryRun ? "drafting" : "drafting + sending"
8921
10491
  });
8922
- const drafted = await dispatchPlay(playName, filteredBody);
8923
10492
  let sentCount = 0;
8924
- drafted.forEach((d, index) => {
10493
+ const drafted = await dispatchPlay(playName, filteredBody, (index, d) => {
8925
10494
  send({
8926
10495
  kind: "draft",
8927
10496
  index,
@@ -8934,7 +10503,12 @@ async function runPlay(req, params) {
8934
10503
  index,
8935
10504
  receiptIds: d.receiptIds
8936
10505
  });
8937
- if (d.sent) sentCount++;
10506
+ if (d.sent) {
10507
+ sentCount++;
10508
+ const t = verify.verified[index];
10509
+ const email = t?.email ?? t?.founderEmail;
10510
+ if (email) sentEmails.push(email);
10511
+ }
8938
10512
  });
8939
10513
  send({
8940
10514
  kind: "done",
@@ -8976,6 +10550,13 @@ async function runPlay(req, params) {
8976
10550
  message: uiMessage
8977
10551
  });
8978
10552
  } finally {
10553
+ try {
10554
+ getLedger().markRunComplete({
10555
+ runId,
10556
+ status: "done",
10557
+ sentEmails
10558
+ });
10559
+ } catch {}
8979
10560
  try {
8980
10561
  controller.close();
8981
10562
  } catch {}
@@ -9042,6 +10623,35 @@ function persistDraftsToQueue(input) {
9042
10623
  }
9043
10624
  }
9044
10625
  //#endregion
10626
+ //#region src/api/runs.ts
10627
+ /**
10628
+ * `GET /api/runs/:id` — snapshot of one /run-page dispatch. The UI polls this
10629
+ * every 2s while `status === 'running'`, then stops once `status` flips to
10630
+ * `done` or `interrupted`. The full events array is returned so the resume
10631
+ * view can rebuild per-target rows identically to a live SSE consumer.
10632
+ */
10633
+ function getRunRoute(req, params) {
10634
+ const id = Number.parseInt(params["id"] ?? "", 10);
10635
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
10636
+ const run = getLedger().getRun(id);
10637
+ if (!run) return jsonResponse({ error: `run #${id} not found` }, 404, req);
10638
+ return jsonResponse({
10639
+ id: run.id,
10640
+ playName: run.playName,
10641
+ dryRun: run.dryRun,
10642
+ status: run.status,
10643
+ startedAt: run.startedAt,
10644
+ completedAt: run.completedAt,
10645
+ targetCount: run.targetCount,
10646
+ draftedCount: run.draftedCount,
10647
+ sentCount: run.sentCount,
10648
+ errorCount: run.errorCount,
10649
+ targets: run.targets,
10650
+ events: run.events,
10651
+ prospectEmails: run.prospectEmails
10652
+ }, 200, req);
10653
+ }
10654
+ //#endregion
9045
10655
  //#region src/api/queue.ts
9046
10656
  function toView$1(row) {
9047
10657
  let payload = null;
@@ -9078,7 +10688,8 @@ function toView$1(row) {
9078
10688
  notes: row.notes,
9079
10689
  prospectId: row.prospect_id,
9080
10690
  lastDraft,
9081
- lastDraftedAt: row.last_drafted_at
10691
+ lastDraftedAt: row.last_drafted_at,
10692
+ isSending: row.send_started_at != null
9082
10693
  };
9083
10694
  }
9084
10695
  function listQueueRoute(req) {
@@ -9169,6 +10780,8 @@ async function regenerateDraftRoute(req, params) {
9169
10780
  const ledger = getLedger();
9170
10781
  const row = ledger.getQueueRow(id);
9171
10782
  if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);
10783
+ if (row.status === "sent") return jsonResponse({ error: "row already sent" }, 400, req);
10784
+ if (row.send_started_at != null) return jsonResponse({ error: "send in flight, can't regenerate" }, 409, req);
9172
10785
  let target;
9173
10786
  try {
9174
10787
  target = JSON.parse(row.payload_json);
@@ -9190,6 +10803,8 @@ async function regenerateDraftRoute(req, params) {
9190
10803
  }
9191
10804
  const draft = drafted[0];
9192
10805
  if (!draft) return jsonResponse({ error: "no draft produced" }, 500, req);
10806
+ const fresh = ledger.getQueueRow(id);
10807
+ if (!fresh || fresh.status === "sent" || fresh.send_started_at != null) return jsonResponse({ error: "send completed (or started) during regenerate" }, 409, req);
9193
10808
  ledger.setQueueDraft({
9194
10809
  id,
9195
10810
  draft: {
@@ -9223,6 +10838,7 @@ async function regenerateDraftRoute(req, params) {
9223
10838
  async function sendDraftRoute(req, params) {
9224
10839
  const id = Number.parseInt(params["id"] ?? "", 10);
9225
10840
  if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
10841
+ if (isDraining()) return jsonResponse({ error: "server restarting — retry in a moment" }, 503, req);
9226
10842
  const ledger = getLedger();
9227
10843
  const row = ledger.getQueueRow(id);
9228
10844
  if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);
@@ -9240,6 +10856,11 @@ async function sendDraftRoute(req, params) {
9240
10856
  if (!subject || !body) return jsonResponse({ error: "stored draft is empty — regenerate first" }, 400, req);
9241
10857
  if (flags.length > 0) return jsonResponse({ error: "draft has lint flags — regenerate to clear them before sending" }, 400, req);
9242
10858
  if (parsed.sent === true) return jsonResponse({ error: "draft already sent" }, 400, req);
10859
+ if (!ledger.claimQueueSendingMarker({
10860
+ id,
10861
+ startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
10862
+ staleCutoffIso: (/* @__PURE__ */ new Date(Date.now() - 300 * 1e3)).toISOString()
10863
+ })) return jsonResponse({ error: "already sending — wait for the in-flight send to complete" }, 409, req);
9243
10864
  let payload = {};
9244
10865
  try {
9245
10866
  const p = JSON.parse(row.payload_json);
@@ -9248,6 +10869,7 @@ async function sendDraftRoute(req, params) {
9248
10869
  const str = (k) => typeof payload[k] === "string" ? payload[k] : null;
9249
10870
  const email = str("email") ?? str("founderEmail");
9250
10871
  if (!email) return jsonResponse({ error: "row has no recipient email" }, 400, req);
10872
+ const sendFlags = [];
9251
10873
  let result;
9252
10874
  try {
9253
10875
  result = await sendDraftedEmail({
@@ -9257,7 +10879,7 @@ async function sendDraftRoute(req, params) {
9257
10879
  subject,
9258
10880
  body
9259
10881
  },
9260
- flags: [],
10882
+ flags: sendFlags,
9261
10883
  prospectMeta: {
9262
10884
  name: str("name") ?? str("founderName"),
9263
10885
  email,
@@ -9269,9 +10891,31 @@ async function sendDraftRoute(req, params) {
9269
10891
  dryRun: false
9270
10892
  });
9271
10893
  } catch (err) {
10894
+ try {
10895
+ ledger.clearQueueSendingMarker(id);
10896
+ } catch {}
9272
10897
  return jsonResponse({ error: err.message ?? "send failed" }, 400, req);
9273
10898
  }
9274
- if (!result.sent) return jsonResponse({ error: "send did not complete" }, 500, req);
10899
+ if (!result.sent) {
10900
+ try {
10901
+ ledger.clearQueueSendingMarker(id);
10902
+ } catch {}
10903
+ const dedup = sendFlags.find((f) => f === "already-contacted" || f === "already-enrolled");
10904
+ if (dedup) {
10905
+ const reason = dedup === "already-contacted" ? "already contacted via another play" : "already sent this play";
10906
+ ledger.setQueueStatus({
10907
+ id,
10908
+ status: "rejected",
10909
+ notes: `auto: ${reason} — not re-sent`
10910
+ });
10911
+ return jsonResponse({
10912
+ error: `${reason} — not re-sent`,
10913
+ skipped: true,
10914
+ reason: dedup
10915
+ }, 409, req);
10916
+ }
10917
+ return jsonResponse({ error: "send did not complete" }, 500, req);
10918
+ }
9275
10919
  const prospect = ledger.findProspectByEmail(email);
9276
10920
  if (prospect) enrollInCadence({
9277
10921
  prospectId: prospect.id,
@@ -9474,6 +11118,7 @@ const routes = [
9474
11118
  route("POST", "/api/strategist/stream", strategistRoute),
9475
11119
  route("GET", "/api/doctor", doctor),
9476
11120
  route("POST", "/api/run/:playName", runPlay),
11121
+ route("GET", "/api/runs/:id", getRunRoute),
9477
11122
  route("GET", "/api/queue", listQueueRoute),
9478
11123
  route("POST", "/api/queue/approve-all", approveAllRoute),
9479
11124
  route("POST", "/api/queue/drain", drainQueueRoute),
@@ -9666,6 +11311,58 @@ if (cache.__oneshotGtmServer) {
9666
11311
  logEvent("trigger.sweep.failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
9667
11312
  process.stderr.write(` warn: stale-run sweep failed: ${err.message}\n`);
9668
11313
  }
11314
+ try {
11315
+ const swept = getLedger().sweepStaleCadenceSends({
11316
+ now: /* @__PURE__ */ new Date(),
11317
+ maxAgeMs: 0
11318
+ });
11319
+ for (const s of swept) {
11320
+ logEvent(s.actuallySent ? "cadence.send.cleared_marker" : "cadence.send.killed_by_restart", {
11321
+ prospect_id: s.prospectId,
11322
+ play_name: s.playName,
11323
+ age_ms: s.ageMs,
11324
+ actually_sent: s.actuallySent
11325
+ }, s.actuallySent ? "info" : "warn");
11326
+ if (!s.actuallySent) process.stdout.write(` swept stale cadence send: ${s.playName} (prospect ${s.prospectId}, ${Math.round(s.ageMs / 1e3)}s old) — re-click Send to retry\n`);
11327
+ }
11328
+ } catch (err) {
11329
+ logEvent("cadence.send.sweep_failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
11330
+ process.stderr.write(` warn: stale-send sweep failed: ${err.message}\n`);
11331
+ }
11332
+ try {
11333
+ const swept = getLedger().sweepStaleQueueSends({
11334
+ now: /* @__PURE__ */ new Date(),
11335
+ maxAgeMs: 0
11336
+ });
11337
+ for (const s of swept) {
11338
+ logEvent(s.actuallySent ? "queue.send.cleared_marker" : "queue.send.killed_by_restart", {
11339
+ queue_id: s.id,
11340
+ age_ms: s.ageMs,
11341
+ actually_sent: s.actuallySent
11342
+ }, s.actuallySent ? "info" : "warn");
11343
+ if (!s.actuallySent) process.stdout.write(` swept stale queue send: row ${s.id} (${Math.round(s.ageMs / 1e3)}s old) — re-click Send to retry\n`);
11344
+ }
11345
+ } catch (err) {
11346
+ logEvent("queue.send.sweep_failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
11347
+ process.stderr.write(` warn: stale queue-send sweep failed: ${err.message}\n`);
11348
+ }
11349
+ try {
11350
+ const swept = getLedger().sweepStaleRuns({
11351
+ now: /* @__PURE__ */ new Date(),
11352
+ maxAgeMs: 0
11353
+ });
11354
+ for (const s of swept) {
11355
+ logEvent("run.killed_by_restart", {
11356
+ run_id: s.id,
11357
+ play_name: s.playName,
11358
+ age_ms: s.ageMs
11359
+ }, "warn");
11360
+ process.stdout.write(` swept stale run: #${s.id} ${s.playName} (${Math.round(s.ageMs / 1e3)}s old)\n`);
11361
+ }
11362
+ } catch (err) {
11363
+ logEvent("run.sweep_failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
11364
+ process.stderr.write(` warn: stale-run sweep failed: ${err.message}\n`);
11365
+ }
9669
11366
  const { url, server } = await startServer({ port });
9670
11367
  cache.__oneshotGtmServer = server;
9671
11368
  let scheduler = null;
@@ -9680,14 +11377,34 @@ if (cache.__oneshotGtmServer) {
9680
11377
  if (!noBrowser) try {
9681
11378
  await open(url);
9682
11379
  } catch {}
9683
- const shutdown = () => {
9684
- process.stdout.write("\n shutting down...\n");
11380
+ const drainTimeoutMs = Number.parseInt(process.env["ONESHOT_GTM_DRAIN_TIMEOUT_MS"] ?? "30000", 10);
11381
+ let shuttingDown = false;
11382
+ const shutdown = async (signal) => {
11383
+ if (shuttingDown) {
11384
+ process.stdout.write("\n forced exit.\n");
11385
+ process.exit(1);
11386
+ }
11387
+ shuttingDown = true;
11388
+ beginDraining();
9685
11389
  if (scheduler) scheduler.stop();
11390
+ const inflight = activeSendCount();
11391
+ if (inflight > 0) {
11392
+ process.stdout.write(`\n ${signal} — draining ${inflight} in-flight send(s)... (Ctrl-C again to force)\n`);
11393
+ const { drained, remaining } = await waitForSendsToDrain({ timeoutMs: drainTimeoutMs });
11394
+ if (drained) process.stdout.write(" drained — all sends recorded.\n");
11395
+ else {
11396
+ logEvent("server.drain.timeout", {
11397
+ remaining,
11398
+ timeout_ms: drainTimeoutMs
11399
+ }, "warn");
11400
+ process.stdout.write(` WARN: ${remaining} send(s) still in-flight after ${drainTimeoutMs}ms — exiting; boot sweep will reconcile.\n`);
11401
+ }
11402
+ } else process.stdout.write("\n shutting down...\n");
9686
11403
  server.stop();
9687
11404
  process.exit(0);
9688
11405
  };
9689
- process.on("SIGINT", shutdown);
9690
- process.on("SIGTERM", shutdown);
11406
+ process.on("SIGINT", () => void shutdown("SIGINT"));
11407
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
9691
11408
  }
9692
11409
  //#endregion
9693
11410
  export {};