oneshot-gtm-server 0.3.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 (74) hide show
  1. package/dist/bin.mjs +2886 -623
  2. package/dist/bin.mjs.map +1 -1
  3. package/dist/web/assets/Badge-Cs_ppKNz.js +1 -0
  4. package/dist/web/assets/Button-BSvdrKMk.js +1 -0
  5. package/dist/web/assets/EmptyNote-mpJ8e7Tf.js +1 -0
  6. package/dist/web/assets/Field-CvWHFo14.js +1 -0
  7. package/dist/web/assets/Modal-Cl4CKo6q.js +1 -0
  8. package/dist/web/assets/Skeleton-BvYeiEvb.js +1 -0
  9. package/dist/web/assets/StrategistPanel-CsOILu02.js +6 -0
  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-CJdqj4WJ.js +1 -0
  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/{summarizeRun-D5Pd2arb.js → summarizeRun-CVWcweeA.js} +1 -2
  28. package/dist/web/assets/x-D_dx-pu-.js +1 -0
  29. package/dist/web/index.html +3 -3
  30. package/package.json +2 -2
  31. package/dist/web/assets/Badge-Bl9eBoUa.js +0 -2
  32. package/dist/web/assets/Badge-Bl9eBoUa.js.map +0 -1
  33. package/dist/web/assets/Button-D1rFtlez.js +0 -2
  34. package/dist/web/assets/Button-D1rFtlez.js.map +0 -1
  35. package/dist/web/assets/EmptyNote-CZaRRtmD.js +0 -2
  36. package/dist/web/assets/EmptyNote-CZaRRtmD.js.map +0 -1
  37. package/dist/web/assets/Field-DJ9InfU_.js +0 -2
  38. package/dist/web/assets/Field-DJ9InfU_.js.map +0 -1
  39. package/dist/web/assets/Modal-CturxR2v.js +0 -2
  40. package/dist/web/assets/Modal-CturxR2v.js.map +0 -1
  41. package/dist/web/assets/Skeleton-CHzR-B21.js +0 -2
  42. package/dist/web/assets/Skeleton-CHzR-B21.js.map +0 -1
  43. package/dist/web/assets/cadences-D9cvMlfq.js +0 -2
  44. package/dist/web/assets/cadences-D9cvMlfq.js.map +0 -1
  45. package/dist/web/assets/chevron-down-J-vUa4uQ.js +0 -2
  46. package/dist/web/assets/chevron-down-J-vUa4uQ.js.map +0 -1
  47. package/dist/web/assets/chevron-right-DAxZefV9.js +0 -2
  48. package/dist/web/assets/chevron-right-DAxZefV9.js.map +0 -1
  49. package/dist/web/assets/inbox-Dsg3_bXr.js +0 -2
  50. package/dist/web/assets/inbox-Dsg3_bXr.js.map +0 -1
  51. package/dist/web/assets/index-BVno9lTD.js +0 -60
  52. package/dist/web/assets/index-BVno9lTD.js.map +0 -1
  53. package/dist/web/assets/index-Ya_svHJk.css +0 -2
  54. package/dist/web/assets/loader-circle-B_w_dqVu.js +0 -2
  55. package/dist/web/assets/loader-circle-B_w_dqVu.js.map +0 -1
  56. package/dist/web/assets/measure-CV7Towgf.js +0 -2
  57. package/dist/web/assets/measure-CV7Towgf.js.map +0 -1
  58. package/dist/web/assets/plays-BSlXDDDK.js +0 -2
  59. package/dist/web/assets/plays-BSlXDDDK.js.map +0 -1
  60. package/dist/web/assets/queue-BHKT-qjx.js +0 -2
  61. package/dist/web/assets/queue-BHKT-qjx.js.map +0 -1
  62. package/dist/web/assets/receipts-opTtY1t7.js +0 -2
  63. package/dist/web/assets/receipts-opTtY1t7.js.map +0 -1
  64. package/dist/web/assets/refresh-cw-BO0blIzU.js +0 -2
  65. package/dist/web/assets/refresh-cw-BO0blIzU.js.map +0 -1
  66. package/dist/web/assets/routes-BgDvPuJP.js +0 -2
  67. package/dist/web/assets/routes-BgDvPuJP.js.map +0 -1
  68. package/dist/web/assets/run._playName-CQU-5e18.js +0 -5
  69. package/dist/web/assets/run._playName-CQU-5e18.js.map +0 -1
  70. package/dist/web/assets/send-9D8YeqmY.js +0 -2
  71. package/dist/web/assets/send-9D8YeqmY.js.map +0 -1
  72. package/dist/web/assets/setup-CqCzlBdR.js +0 -2
  73. package/dist/web/assets/setup-CqCzlBdR.js.map +0 -1
  74. package/dist/web/assets/summarizeRun-D5Pd2arb.js.map +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) {
@@ -181,6 +189,9 @@ var Ledger = class {
181
189
  );
182
190
  CREATE INDEX IF NOT EXISTS idx_receipts_play ON receipts(play_name);
183
191
  CREATE INDEX IF NOT EXISTS idx_receipts_created ON receipts(created_at);
192
+ -- listReceipts / spend rollups filter (play_name, created_at) together and
193
+ -- sort by created_at; the composite serves both without a separate sort scan.
194
+ CREATE INDEX IF NOT EXISTS idx_receipts_play_created ON receipts(play_name, created_at);
184
195
 
185
196
  CREATE TABLE IF NOT EXISTS prospects (
186
197
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -210,6 +221,11 @@ var Ledger = class {
210
221
  -- prospect), per-play send counts, and cadence scans — all by
211
222
  -- prospect_id and/or created_at. Without this it's a full table scan.
212
223
  CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_created ON sequence_events(prospect_id, created_at);
224
+ -- listSequenceEventsForProspectPlay (per-row in /api/cadences toView)
225
+ -- and listSequenceEventsForCadences (bulk variant) both filter on
226
+ -- (prospect_id, play_name) and ORDER BY step_index — composite index
227
+ -- serves both the seek and the sort, no temp B-tree.
228
+ CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_play ON sequence_events(prospect_id, play_name, step_index);
213
229
 
214
230
  CREATE TABLE IF NOT EXISTS interviews (
215
231
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -285,6 +301,24 @@ var Ledger = class {
285
301
  fetched_at TEXT NOT NULL
286
302
  );
287
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
+
288
322
  CREATE TABLE IF NOT EXISTS schema_version (
289
323
  version INTEGER PRIMARY KEY
290
324
  );
@@ -297,6 +331,45 @@ var Ledger = class {
297
331
  this.addColumnIfMissing("target_queue", "drain_claimed_at", "TEXT");
298
332
  this.addColumnIfMissing("cadence_state", "next_step_draft_json", "TEXT");
299
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}`);
300
373
  }
301
374
  addColumnIfMissing(table, column, type) {
302
375
  const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -336,19 +409,44 @@ var Ledger = class {
336
409
  JOIN prospects p ON p.id = c.prospect_id
337
410
  ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST
338
411
  `).all();
412
+ }
413
+ /**
414
+ * Single cadence (joined with its prospect) by (prospect_id, play_name) — an
415
+ * index seek on the `cadence_state` PRIMARY KEY. Replaces the O(n)
416
+ * `listAllCadences().find(...)` scan callers used to do per row.
417
+ */
418
+ getCadence(prospectId, playName) {
419
+ return this.db.query(`
420
+ SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company
421
+ FROM cadence_state c
422
+ JOIN prospects p ON p.id = c.prospect_id
423
+ WHERE c.prospect_id = ? AND c.play_name = ?
424
+ `).get(prospectId, playName) ?? null;
425
+ }
426
+ /** All cadences for one prospect — index seek on cadence_state.prospect_id (PK prefix). */
427
+ listCadencesForProspect(prospectId) {
428
+ return this.db.query(`
429
+ SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company
430
+ FROM cadence_state c
431
+ JOIN prospects p ON p.id = c.prospect_id
432
+ WHERE c.prospect_id = ?
433
+ ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST
434
+ `).all(prospectId);
339
435
  }
340
436
  advanceCadence(input) {
341
437
  this.db.prepare(`UPDATE cadence_state
342
438
  SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now'),
343
- 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
344
441
  WHERE prospect_id = ? AND play_name = ?`).run(input.newStep, input.nextDueAt, input.prospectId, input.playName);
345
442
  }
346
443
  setCadenceStatus(input) {
347
444
  this.db.prepare(`UPDATE cadence_state
348
445
  SET status = ?,
349
446
  next_step_draft_json = CASE WHEN ? = 'active' THEN next_step_draft_json ELSE NULL END,
350
- next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END
351
- 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);
352
450
  }
353
451
  setCadenceDraft(input) {
354
452
  const draftedAtIso = (/* @__PURE__ */ new Date()).toISOString();
@@ -375,6 +473,81 @@ var Ledger = class {
375
473
  SET next_step_draft_json = NULL, next_step_drafted_at = NULL
376
474
  WHERE prospect_id = ? AND play_name = ?`).run(input.prospectId, input.playName);
377
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
+ }
378
551
  findProspectByEmail(email) {
379
552
  return this.db.query("SELECT id FROM prospects WHERE email = ?").get(canonEmail(email)) ?? null;
380
553
  }
@@ -382,6 +555,10 @@ var Ledger = class {
382
555
  getProspectByEmail(email) {
383
556
  return this.db.query("SELECT * FROM prospects WHERE email = ?").get(canonEmail(email)) ?? null;
384
557
  }
558
+ /** Full prospect record by id (PK seek). Avoids loading every prospect to find one. */
559
+ getProspectById(id) {
560
+ return this.db.query("SELECT * FROM prospects WHERE id = ?").get(id) ?? null;
561
+ }
385
562
  /** Cached enrichProfile result for an email (profiles are stable; reused with a TTL). */
386
563
  getCachedEnrichment(email) {
387
564
  return this.db.query("SELECT result_json, fetched_at FROM enrichment_cache WHERE email = ?").get(email) ?? null;
@@ -501,6 +678,37 @@ var Ledger = class {
501
678
  AND status IN ('sent','delivered','replied')
502
679
  ORDER BY step_index ASC, id ASC`).all(prospectId, playName);
503
680
  }
681
+ /**
682
+ * Bulk variant of listSequenceEventsForProspectPlay: one SQL round-trip for
683
+ * many (prospect_id, play_name) pairs. Returns a Map keyed by
684
+ * `${prospect_id}|${play_name}` so callers can index in O(1). The
685
+ * per-key arrays preserve the same (step_index ASC, id ASC) ordering the
686
+ * single-row method returns. Empty input → empty map (no query).
687
+ *
688
+ * Index-served by idx_sequence_events_prospect_play; the OR-chain is
689
+ * expanded into per-pair index seeks by the query planner.
690
+ */
691
+ listSequenceEventsForCadences(pairs) {
692
+ const map = /* @__PURE__ */ new Map();
693
+ if (pairs.length === 0) return map;
694
+ const conditions = pairs.map(() => "(prospect_id = ? AND play_name = ?)").join(" OR ");
695
+ const args = [];
696
+ for (const p of pairs) args.push(p.prospectId, p.playName);
697
+ const rows = this.db.query(`SELECT * FROM sequence_events
698
+ WHERE (${conditions})
699
+ AND status IN ('sent','delivered','replied')
700
+ ORDER BY prospect_id ASC, play_name ASC, step_index ASC, id ASC`).all(...args);
701
+ for (const r of rows) {
702
+ const key = `${r.prospect_id}|${r.play_name}`;
703
+ let list = map.get(key);
704
+ if (!list) {
705
+ list = [];
706
+ map.set(key, list);
707
+ }
708
+ list.push(r);
709
+ }
710
+ return map;
711
+ }
504
712
  recordInterview(input) {
505
713
  const result = this.db.prepare(`
506
714
  INSERT INTO interviews(person, transcript_path, jtbd, pain_quotes_json)
@@ -584,6 +792,36 @@ var Ledger = class {
584
792
  return row !== null && row !== void 0;
585
793
  }
586
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
+ /**
587
825
  * Look up a queue row by its (play_name, dedupe_key) — the unique pair.
588
826
  * Used by the SSE /run endpoint to map drafts back to the originating
589
827
  * row so we can persist `last_draft_json`. Returns null when absent.
@@ -616,7 +854,7 @@ var Ledger = class {
616
854
  }
617
855
  setQueueStatus(input) {
618
856
  const now = (/* @__PURE__ */ new Date()).toISOString();
619
- 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 ? [
620
858
  input.status,
621
859
  now,
622
860
  now,
@@ -628,7 +866,7 @@ var Ledger = class {
628
866
  now,
629
867
  input.id
630
868
  ]);
631
- 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 ? [
632
870
  input.status,
633
871
  now,
634
872
  input.notes,
@@ -638,7 +876,58 @@ var Ledger = class {
638
876
  now,
639
877
  input.id
640
878
  ]);
641
- 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;
642
931
  }
643
932
  approveAllPending(opts = {}) {
644
933
  const where = ["status = 'pending'"];
@@ -693,6 +982,121 @@ var Ledger = class {
693
982
  for (const r of rows) out[r.status] = r.n;
694
983
  return out;
695
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
+ }
696
1100
  upsertTrigger(input) {
697
1101
  this.db.prepare(`INSERT INTO triggers(name, enabled, config_json)
698
1102
  VALUES(?, ?, ?)
@@ -738,12 +1142,14 @@ var Ledger = class {
738
1142
  * `sweepStaleRunningTriggers` on the next cold boot.
739
1143
  */
740
1144
  markTriggerRunning(name, startedAtIso, staleCutoffIso) {
741
- if (staleCutoffIso) return this.db.prepare(`UPDATE triggers
742
- SET running_started_at = ?
743
- WHERE name = ? AND (running_started_at IS NULL OR running_started_at < ?)`).run(startedAtIso, name, staleCutoffIso).changes > 0;
744
- return this.db.prepare(`UPDATE triggers
745
- SET running_started_at = ?
746
- 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
+ });
747
1153
  }
748
1154
  /**
749
1155
  * Sweep trigger rows whose `running_started_at` is older than `maxAgeMs`.
@@ -833,9 +1239,25 @@ function getLedger() {
833
1239
  }
834
1240
  //#endregion
835
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
+ }
836
1258
  let agentSingleton = null;
837
1259
  async function initAgent() {
838
- 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.");
839
1261
  if (process.env["AGENT_PRIVATE_KEY"]) return new OneShot({ privateKey: process.env["AGENT_PRIVATE_KEY"] });
840
1262
  return await OneShot.create({ cdp: true });
841
1263
  }
@@ -846,7 +1268,7 @@ async function getAgent() {
846
1268
  /**
847
1269
  * Derive the From localpart from the founder's name (first token, lowercased,
848
1270
  * non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back
849
- * to `agent` when the name yields nothing usable. ("J. Nicolas" → "j".)
1271
+ * to `agent` when the name yields nothing usable. ("Jane Doe" → "jane".)
850
1272
  */
851
1273
  function fromLocalpart(name) {
852
1274
  const clean = ((name ?? "").trim().split(/\s+/)[0] ?? "").toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -867,7 +1289,8 @@ async function sendEmail(input, ctx) {
867
1289
  const opts = {
868
1290
  to: input.to,
869
1291
  subject: input.subject,
870
- body: toHtmlBody(input.body)
1292
+ body: toHtmlBody(input.body),
1293
+ ...buildAuditOpts(ctx, "email.send")
871
1294
  };
872
1295
  if (fromDomain) {
873
1296
  opts.from_domain = fromDomain;
@@ -890,7 +1313,8 @@ async function sendEmail(input, ctx) {
890
1313
  async function deepResearch(input, ctx) {
891
1314
  const result = await (await getAgent()).research({
892
1315
  topic: input.topic,
893
- depth: input.depth ?? "quick"
1316
+ depth: input.depth ?? "quick",
1317
+ ...buildAuditOpts(ctx, "research.deep")
894
1318
  });
895
1319
  return {
896
1320
  result,
@@ -905,7 +1329,7 @@ async function deepResearch(input, ctx) {
905
1329
  }
906
1330
  async function enrichProfile(input, ctx) {
907
1331
  const agent = await getAgent();
908
- const opts = {};
1332
+ const opts = { ...buildAuditOpts(ctx, "enrich.profile") };
909
1333
  if (input.email) opts.email = input.email;
910
1334
  if (input.linkedinUrl) opts.linkedin_url = input.linkedinUrl;
911
1335
  if (input.name) opts.name = input.name;
@@ -931,7 +1355,7 @@ async function enrichProfile(input, ctx) {
931
1355
  */
932
1356
  async function deepResearchPerson(input, ctx) {
933
1357
  const agent = await getAgent();
934
- const opts = {};
1358
+ const opts = { ...buildAuditOpts(ctx, "research.person") };
935
1359
  if (input.email) opts.email = input.email;
936
1360
  if (input.socialMediaUrl) opts.social_media_url = input.socialMediaUrl;
937
1361
  if (input.name) opts.name = input.name;
@@ -950,7 +1374,10 @@ async function deepResearchPerson(input, ctx) {
950
1374
  }
951
1375
  async function findEmail(input, ctx) {
952
1376
  const agent = await getAgent();
953
- const opts = { company_domain: input.companyDomain };
1377
+ const opts = {
1378
+ company_domain: input.companyDomain,
1379
+ ...buildAuditOpts(ctx, "email.find")
1380
+ };
954
1381
  if (input.fullName) opts.full_name = input.fullName;
955
1382
  if (input.firstName) opts.first_name = input.firstName;
956
1383
  if (input.lastName) opts.last_name = input.lastName;
@@ -967,7 +1394,10 @@ async function findEmail(input, ctx) {
967
1394
  };
968
1395
  }
969
1396
  async function verifyEmail(input, ctx) {
970
- 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
+ });
971
1401
  return {
972
1402
  result,
973
1403
  receiptId: getLedger().recordReceipt({
@@ -997,7 +1427,8 @@ async function sendSms(input, ctx) {
997
1427
  const agent = await getAgent();
998
1428
  const opts = {
999
1429
  to_number: input.to,
1000
- message: input.message
1430
+ message: input.message,
1431
+ ...buildAuditOpts(ctx, "sms.send")
1001
1432
  };
1002
1433
  if (input.maxCost) opts.maxCost = input.maxCost;
1003
1434
  const result = await agent.sms(opts);
@@ -1016,7 +1447,8 @@ async function voiceCall(input, ctx) {
1016
1447
  const agent = await getAgent();
1017
1448
  const opts = {
1018
1449
  objective: input.objective,
1019
- target_number: input.to
1450
+ target_number: input.to,
1451
+ ...buildAuditOpts(ctx, "voice.call")
1020
1452
  };
1021
1453
  if (input.callerPersona) opts.caller_persona = input.callerPersona;
1022
1454
  if (input.context) opts.context = input.context;
@@ -1035,7 +1467,10 @@ async function voiceCall(input, ctx) {
1035
1467
  }
1036
1468
  async function webSearch(input, ctx) {
1037
1469
  const agent = await getAgent();
1038
- const opts = { query: input.query };
1470
+ const opts = {
1471
+ query: input.query,
1472
+ ...buildAuditOpts(ctx, "web.search")
1473
+ };
1039
1474
  if (input.maxResults) opts.max_results = input.maxResults;
1040
1475
  const result = await agent.webSearch(opts);
1041
1476
  return {
@@ -1049,7 +1484,10 @@ async function webSearch(input, ctx) {
1049
1484
  };
1050
1485
  }
1051
1486
  async function webRead(input, ctx) {
1052
- 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
+ });
1053
1491
  return {
1054
1492
  result,
1055
1493
  receiptId: getLedger().recordReceipt({
@@ -1063,7 +1501,10 @@ async function webRead(input, ctx) {
1063
1501
  }
1064
1502
  async function browserTask(input, ctx) {
1065
1503
  const agent = await getAgent();
1066
- const opts = { task: input.task };
1504
+ const opts = {
1505
+ task: input.task,
1506
+ ...buildAuditOpts(ctx, "browser.task")
1507
+ };
1067
1508
  if (input.startUrl) opts.start_url = input.startUrl;
1068
1509
  if (input.allowedDomains) opts.allowed_domains = input.allowedDomains;
1069
1510
  if (input.outputSchema) opts.output_schema = input.outputSchema;
@@ -1083,6 +1524,74 @@ async function browserTask(input, ctx) {
1083
1524
  };
1084
1525
  }
1085
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
1086
1595
  //#region ../../packages/core/src/events.ts
1087
1596
  const EVENTS_PATH = join(configDir(), "events.jsonl");
1088
1597
  const DEBUG_ENABLED = (process.env["DEBUG"] ?? "").includes("oneshot");
@@ -1150,6 +1659,38 @@ function resolveClientId() {
1150
1659
  return cachedClientId;
1151
1660
  }
1152
1661
  //#endregion
1662
+ //#region ../../packages/core/src/parallel.ts
1663
+ /**
1664
+ * Run `fn` over `items` with at most `concurrency` Promises in flight at once.
1665
+ * Preserves input order in the result array. Errors propagate via Promise.all
1666
+ * — caller is expected to catch per-item internally if partial success matters.
1667
+ *
1668
+ * Worker-pool implementation: spawn `concurrency` workers that pull from a
1669
+ * shared cursor. Cheaper than a chunked Promise.all (which stalls on the
1670
+ * slowest item per chunk) and avoids the dependency surface of p-limit.
1671
+ *
1672
+ * Lives in core so both `find` (candidate pipelines) and `plays` (batch send
1673
+ * loops) can share it without a cross-package dependency.
1674
+ */
1675
+ async function parallelMap(items, concurrency, fn, onItem) {
1676
+ const out = Array.from({ length: items.length });
1677
+ if (items.length === 0) return out;
1678
+ const workers = Math.max(1, Math.min(concurrency, items.length));
1679
+ let cursor = 0;
1680
+ async function worker() {
1681
+ while (true) {
1682
+ const i = cursor++;
1683
+ if (i >= items.length) return;
1684
+ const item = items[i];
1685
+ const result = await fn(item, i);
1686
+ out[i] = result;
1687
+ if (onItem) onItem(item, result, i);
1688
+ }
1689
+ }
1690
+ await Promise.all(Array.from({ length: workers }, () => worker()));
1691
+ return out;
1692
+ }
1693
+ //#endregion
1153
1694
  //#region src/api/home.ts
1154
1695
  function homeMetrics(req) {
1155
1696
  const ledger = getLedger();
@@ -1169,7 +1710,11 @@ function homeMetrics(req) {
1169
1710
  callsLast7d: recent7d.length,
1170
1711
  sentLast7d: sent7d,
1171
1712
  repliedLast7d: replied7d,
1172
- activeCadences: active.length
1713
+ activeCadences: active.length,
1714
+ currentRuns: ledger.listRuns({
1715
+ status: "running",
1716
+ limit: 5
1717
+ })
1173
1718
  }, 200, req);
1174
1719
  }
1175
1720
  //#endregion
@@ -1410,7 +1955,7 @@ function tryParseJsonObject(raw, fallback) {
1410
1955
  //#endregion
1411
1956
  //#region ../../packages/plays/src/_lib.ts
1412
1957
  /** Profiles change slowly — reuse a cached enrichment for this long before refetching. */
1413
- const ENRICH_CACHE_TTL_MS = 720 * 3600 * 1e3;
1958
+ const ENRICH_CACHE_TTL_MS$1 = 720 * 3600 * 1e3;
1414
1959
  /**
1415
1960
  * enrichProfile that (a) never throws and (b) caches by email. The dossier is a
1416
1961
  * nice-to-have for drafting, the SDK call is slow (~70s) and billed, and the
@@ -1424,7 +1969,7 @@ async function safeEnrich(input, ctx) {
1424
1969
  const email = typeof input.email === "string" ? input.email.trim().toLowerCase() : null;
1425
1970
  if (email) {
1426
1971
  const cached = ledger.getCachedEnrichment(email);
1427
- 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 {
1428
1973
  return {
1429
1974
  result: JSON.parse(cached.result_json),
1430
1975
  receiptId: 0
@@ -1432,7 +1977,16 @@ async function safeEnrich(input, ctx) {
1432
1977
  } catch {}
1433
1978
  }
1434
1979
  try {
1435
- 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
+ });
1436
1990
  if (email) try {
1437
1991
  ledger.setCachedEnrichment(email, JSON.stringify(out.result));
1438
1992
  } catch {}
@@ -1472,13 +2026,49 @@ const SLOP_PHRASES = [
1472
2026
  [/\b(?:the future looks bright|exciting times lie ahead|journey toward)\b/i, "generic-positive-ending"],
1473
2027
  [/\b(?:hope this helps|let me know if you'?d like|happy to expand)\b/i, "servile-closer"]
1474
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
+ }
1475
2065
  function lintEmail(subject, body, maxBodyWords = 110) {
1476
2066
  const flags = [];
1477
2067
  if (subject.length === 0) flags.push("empty-subject");
1478
2068
  if (subject.length > 60) flags.push("subject-too-long");
1479
2069
  if (/[A-Z]{2,}/.test(subject)) flags.push("subject-shouty");
1480
2070
  if (body.length === 0) flags.push("empty-body");
1481
- if (body.split(/\s+/).length > maxBodyWords) flags.push("body-too-long");
2071
+ if (bodyWordsForLint(body) > maxBodyWords) flags.push("body-too-long");
1482
2072
  if (body.includes("—")) flags.push("em-dash");
1483
2073
  if (/[“”‘’]/.test(body)) flags.push("curly-quotes");
1484
2074
  if (/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(body)) flags.push("emoji");
@@ -1595,26 +2185,46 @@ async function sendDraftedEmail(opts) {
1595
2185
  sent: false
1596
2186
  };
1597
2187
  }
2188
+ if (!opts.allowRecontact && ledger.prospectHasFirstTouch(existing.id)) {
2189
+ opts.flags.push("already-contacted");
2190
+ return {
2191
+ receiptIds: [],
2192
+ sent: false
2193
+ };
2194
+ }
1598
2195
  }
1599
- const send = await sendEmail({
1600
- to: opts.to,
1601
- subject: opts.draft.subject,
1602
- body: opts.draft.body
1603
- }, { playName: opts.playName });
1604
- receiptIds.push(send.receiptId);
1605
- const prospectId = ledger.upsertProspect(opts.prospectMeta);
1606
- ledger.recordSequenceEvent({
1607
- prospectId,
1608
- playName: opts.playName,
1609
- stepIndex: 0,
1610
- channel: "email",
1611
- status: "sent",
1612
- metadata: {
2196
+ const receiptId = await trackSend(async () => {
2197
+ const send = await sendEmail({
2198
+ to: opts.to,
1613
2199
  subject: opts.draft.subject,
1614
- body: opts.draft.body,
1615
- ...opts.metadata
1616
- }
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;
1617
2226
  });
2227
+ receiptIds.push(receiptId);
1618
2228
  sent = true;
1619
2229
  }
1620
2230
  return {
@@ -1628,6 +2238,45 @@ function emailDomain(email) {
1628
2238
  if (at < 0) return void 0;
1629
2239
  return email.slice(at + 1);
1630
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
+ }
1631
2280
  /**
1632
2281
  * Verify a batch of target emails BEFORE drafting + sending. Used by
1633
2282
  * direct-input entry points (CLI motion commands + dashboard /run) where
@@ -1838,7 +2487,7 @@ function enrollInCadence(input) {
1838
2487
  async function runCadenceStepForProspect(opts) {
1839
2488
  const ledger = getLedger();
1840
2489
  const cfg = loadConfig();
1841
- const cadence = ledger.listAllCadences().find((c) => c.prospect_id === opts.prospectId && c.play_name === opts.playName);
2490
+ const cadence = ledger.getCadence(opts.prospectId, opts.playName);
1842
2491
  if (!cadence) return {
1843
2492
  action: "skipped",
1844
2493
  payload: null,
@@ -1977,7 +2626,7 @@ async function runCadenceStepForProspect(opts) {
1977
2626
  async function previewCadenceStep(input) {
1978
2627
  const ledger = getLedger();
1979
2628
  const cfg = loadConfig();
1980
- const cadence = ledger.listAllCadences().find((c) => c.prospect_id === input.prospectId && c.play_name === input.playName);
2629
+ const cadence = ledger.getCadence(input.prospectId, input.playName);
1981
2630
  if (!cadence) throw new Error("no cadence for that prospect+play");
1982
2631
  if (cadence.status !== "active") throw new Error(`cadence is ${cadence.status}, can only preview an active cadence`);
1983
2632
  const seq = effectiveSequence(input.playName);
@@ -2037,30 +2686,32 @@ async function sendCadenceStep(input) {
2037
2686
  });
2038
2687
  }
2039
2688
  /**
2040
- * Serial preview of a list of cadence rows. Each per-prospect failure is
2041
- * captured in the result array — the batch never throws. Sequential
2042
- * iteration is deliberate: parallel LLM calls would risk burst rate-limits
2043
- * and the founder is waiting on us anyway (~10s/row).
2689
+ * Parallel preview of a list of cadence rows (concurrency 3). Each
2690
+ * per-prospect failure is captured in the result array — the batch never
2691
+ * throws. `parallelMap` preserves input order so the returned array matches
2692
+ * `items` 1:1. Concurrency mirrors `runEmailPlay` + `advanceCadence`; the
2693
+ * founder is waiting at the UI, so 3× speedup on a 10-row preview drops
2694
+ * wall-clock from ~100s to ~35s.
2044
2695
  */
2045
2696
  async function previewCadenceStepBatch(items) {
2046
- const out = [];
2047
- for (const item of items) try {
2048
- const preview = await previewCadenceStep(item);
2049
- out.push({
2050
- prospectId: item.prospectId,
2051
- playName: item.playName,
2052
- ok: true,
2053
- preview
2054
- });
2055
- } catch (err) {
2056
- out.push({
2057
- prospectId: item.prospectId,
2058
- playName: item.playName,
2059
- ok: false,
2060
- error: (err?.message ?? "preview failed").slice(0, 120)
2061
- });
2062
- }
2063
- return out;
2697
+ return parallelMap(items, 3, async (item) => {
2698
+ try {
2699
+ const preview = await previewCadenceStep(item);
2700
+ return {
2701
+ prospectId: item.prospectId,
2702
+ playName: item.playName,
2703
+ ok: true,
2704
+ preview
2705
+ };
2706
+ } catch (err) {
2707
+ return {
2708
+ prospectId: item.prospectId,
2709
+ playName: item.playName,
2710
+ ok: false,
2711
+ error: (err?.message ?? "preview failed").slice(0, 120)
2712
+ };
2713
+ }
2714
+ });
2064
2715
  }
2065
2716
  /**
2066
2717
  * Serial send of a list of previewed cadence rows. Each per-prospect failure
@@ -2068,6 +2719,11 @@ async function previewCadenceStepBatch(items) {
2068
2719
  * as a background promise — caller returns 202 immediately and the UI sees
2069
2720
  * progress via subsequent `/api/cadences` refetches (the existing
2070
2721
  * `advanceCadence` clears `next_step_draft_json` as each row completes).
2722
+ *
2723
+ * Sends stay serial (unlike previewCadenceStepBatch) for two reasons: the
2724
+ * `onItemSettled` callback drives the in-flight UI badge per row (parallel
2725
+ * would batch-flash all rows at once), and parallel SMTP to the same
2726
+ * domain risks soft-bounces.
2071
2727
  */
2072
2728
  async function sendCadenceStepBatch(items, onItemSettled) {
2073
2729
  const out = [];
@@ -2095,9 +2751,20 @@ async function sendCadenceStepBatch(items, onItemSettled) {
2095
2751
  }
2096
2752
  return out;
2097
2753
  }
2098
- async function dispatchStep(input) {
2754
+ function dispatchStep(input) {
2755
+ return trackSend(() => dispatchStepImpl(input));
2756
+ }
2757
+ async function dispatchStepImpl(input) {
2099
2758
  const ledger = getLedger();
2100
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}` : "";
2101
2768
  if (input.payload.kind === "email") {
2102
2769
  if (!input.prospectEmail) return {
2103
2770
  receiptIds,
@@ -2107,7 +2774,14 @@ async function dispatchStep(input) {
2107
2774
  to: input.prospectEmail,
2108
2775
  subject: input.payload.subject,
2109
2776
  body: input.payload.body
2110
- }, { 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
+ });
2111
2785
  receiptIds.push(send.receiptId);
2112
2786
  ledger.recordSequenceEvent({
2113
2787
  prospectId: input.prospectId,
@@ -2131,7 +2805,14 @@ async function dispatchStep(input) {
2131
2805
  const send = await sendSms({
2132
2806
  to: input.payload.toPhone,
2133
2807
  message: input.payload.message
2134
- }, { 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
+ });
2135
2816
  receiptIds.push(send.receiptId);
2136
2817
  ledger.recordSequenceEvent({
2137
2818
  prospectId: input.prospectId,
@@ -2153,9 +2834,17 @@ async function dispatchStep(input) {
2153
2834
  to: input.payload.toPhone,
2154
2835
  ...input.payload.context ? { context: input.payload.context } : {},
2155
2836
  ...input.payload.maxDurationMinutes ? { maxDurationMinutes: input.payload.maxDurationMinutes } : {}
2156
- }, { playName: input.playName });
2157
- receiptIds.push(call.receiptId);
2158
- ledger.recordSequenceEvent({
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
+ });
2846
+ receiptIds.push(call.receiptId);
2847
+ ledger.recordSequenceEvent({
2159
2848
  prospectId: input.prospectId,
2160
2849
  playName: input.playName,
2161
2850
  stepIndex: input.stepIndex,
@@ -2174,13 +2863,14 @@ async function dispatchStep(input) {
2174
2863
  };
2175
2864
  }
2176
2865
  function loadProspect(id) {
2177
- return getLedger().db.query("SELECT * FROM prospects WHERE id = ?").get(id) ?? null;
2866
+ return getLedger().getProspectById(id);
2178
2867
  }
2179
2868
  function buildFollowUpEmail(opts) {
2180
2869
  return async (ctx) => {
2181
2870
  const system = loadPrompt(opts.promptName) + signatureDirective();
2182
2871
  const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);
2183
2872
  const proofBlock = socialProofBlock();
2873
+ const firstName = firstNameFrom(ctx.prospect.name);
2184
2874
  const user = [
2185
2875
  `FOUNDER: ${ctx.cfg.founderName}`,
2186
2876
  `PRODUCT: ${ctx.cfg.productOneLiner}`,
@@ -2189,7 +2879,8 @@ function buildFollowUpEmail(opts) {
2189
2879
  `COMPANY: ${ctx.prospect.company ?? "(unknown)"}`,
2190
2880
  ...opts.contextLines,
2191
2881
  ...priorBlock ? ["", priorBlock] : [],
2192
- ...proofBlock ? ["", proofBlock] : []
2882
+ ...proofBlock ? ["", proofBlock] : [],
2883
+ ...firstName ? ["", `PROSPECT_FIRST_NAME: ${firstName}`] : []
2193
2884
  ].join("\n");
2194
2885
  const parsed = tryParseJsonObject((await complete({
2195
2886
  messages: [{
@@ -2228,17 +2919,37 @@ function getPriorStepsForProspect(prospectId, playName) {
2228
2919
  } catch {
2229
2920
  return [];
2230
2921
  }
2231
- return rows.map((r) => {
2232
- const meta = tryParseJsonObject(r.metadata_json ?? "", {});
2233
- return {
2234
- stepIndex: r.step_index,
2235
- label: meta.label ?? (r.step_index === 0 ? "initial send" : "follow-up"),
2236
- subject: meta.subject ?? "(no subject)",
2237
- body: meta.body ?? null,
2238
- sentAt: r.created_at,
2239
- status: r.status ?? "sent"
2240
- };
2241
- });
2922
+ return rows.map(rowToPriorStep);
2923
+ }
2924
+ function rowToPriorStep(r) {
2925
+ const meta = tryParseJsonObject(r.metadata_json ?? "", {});
2926
+ return {
2927
+ stepIndex: r.step_index,
2928
+ label: meta.label ?? (r.step_index === 0 ? "initial send" : "follow-up"),
2929
+ subject: meta.subject ?? "(no subject)",
2930
+ body: meta.body ?? null,
2931
+ sentAt: r.created_at,
2932
+ status: r.status ?? "sent"
2933
+ };
2934
+ }
2935
+ /**
2936
+ * Bulk variant of getPriorStepsForProspect: one SQL round-trip for many
2937
+ * (prospect_id, play_name) pairs. Returns a Map keyed by
2938
+ * `${prospectId}|${playName}` so /api/cadences's toView can index in O(1)
2939
+ * instead of issuing one query per row. Pairs the founder hasn't sent for
2940
+ * are absent from the map (callers should default to []).
2941
+ */
2942
+ function getPriorStepsBulk(pairs) {
2943
+ if (pairs.length === 0) return /* @__PURE__ */ new Map();
2944
+ let bulk;
2945
+ try {
2946
+ bulk = getLedger().listSequenceEventsForCadences(pairs);
2947
+ } catch {
2948
+ return /* @__PURE__ */ new Map();
2949
+ }
2950
+ const out = /* @__PURE__ */ new Map();
2951
+ for (const [key, rows] of bulk) out.set(key, rows.map(rowToPriorStep));
2952
+ return out;
2242
2953
  }
2243
2954
  function buildPriorEmailsBlock(prospectId, playName) {
2244
2955
  const prior = getPriorStepsForProspect(prospectId, playName).filter((r) => r.body !== null && r.body.length > 0);
@@ -2262,49 +2973,53 @@ function buildPriorEmailsBlock(prospectId, playName) {
2262
2973
  async function runEmailPlay(def, opts) {
2263
2974
  const cfg = loadConfig();
2264
2975
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2265
- const drafted = [];
2266
- for (const target of opts.targets) try {
2267
- const prep = await def.prepare(target, opts.dryRun);
2268
- const proof = socialProofBlock();
2269
- const inputBlock = proof ? `${def.buildInputBlock(target, prep, cfg)}\n\n${proof}` : def.buildInputBlock(target, prep, cfg);
2270
- const draft = await draftEmailFromPrompt({
2271
- promptName: def.promptName,
2272
- inputBlock
2273
- });
2274
- const flags = lintEmail(draft.subject, draft.body, def.maxBodyWords);
2275
- const send = await sendDraftedEmail({
2276
- playName: def.playName,
2277
- to: def.toEmail(target),
2278
- draft,
2279
- flags,
2280
- prospectMeta: def.prospectMeta(target),
2281
- ...def.metadata ? { metadata: def.metadata(target) } : {},
2282
- dryRun: opts.dryRun
2283
- });
2284
- if (send.sent && def.enrollCadence) {
2285
- const prospect = getLedger().findProspectByEmail(def.toEmail(target));
2286
- if (prospect) enrollInCadence({
2287
- prospectId: prospect.id,
2288
- playName: def.playName
2976
+ const emails = opts.targets.map((t) => def.toEmail(t).trim().toLowerCase());
2977
+ const concurrency = new Set(emails).size !== emails.length ? 1 : 6;
2978
+ return { drafted: await parallelMap(opts.targets, concurrency, async (target) => {
2979
+ try {
2980
+ const prep = await def.prepare(target, opts.dryRun);
2981
+ const proof = socialProofBlock();
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}`;
2985
+ const draft = await draftEmailFromPrompt({
2986
+ promptName: def.promptName,
2987
+ inputBlock
2988
+ });
2989
+ const flags = lintEmail(draft.subject, draft.body, def.maxBodyWords);
2990
+ const send = await sendDraftedEmail({
2991
+ playName: def.playName,
2992
+ to: def.toEmail(target),
2993
+ draft,
2994
+ flags,
2995
+ prospectMeta: def.prospectMeta(target),
2996
+ ...def.metadata ? { metadata: def.metadata(target) } : {},
2997
+ dryRun: opts.dryRun
2289
2998
  });
2999
+ if (send.sent && def.enrollCadence) {
3000
+ const prospect = getLedger().findProspectByEmail(def.toEmail(target));
3001
+ if (prospect) enrollInCadence({
3002
+ prospectId: prospect.id,
3003
+ playName: def.playName
3004
+ });
3005
+ }
3006
+ return {
3007
+ target,
3008
+ subject: draft.subject,
3009
+ body: draft.body,
3010
+ receiptIds: [...prep.receiptIds, ...send.receiptIds],
3011
+ sent: send.sent,
3012
+ flags,
3013
+ ...prep.extra ?? {}
3014
+ };
3015
+ } catch (err) {
3016
+ return {
3017
+ target,
3018
+ ...errorDraft(err?.message),
3019
+ ...def.errorExtra ?? {}
3020
+ };
2290
3021
  }
2291
- drafted.push({
2292
- target,
2293
- subject: draft.subject,
2294
- body: draft.body,
2295
- receiptIds: [...prep.receiptIds, ...send.receiptIds],
2296
- sent: send.sent,
2297
- flags,
2298
- ...prep.extra ?? {}
2299
- });
2300
- } catch (err) {
2301
- drafted.push({
2302
- target,
2303
- ...errorDraft(err?.message),
2304
- ...def.errorExtra ?? {}
2305
- });
2306
- }
2307
- return { drafted };
3022
+ }, opts.onProgress ? (_target, result, index) => opts.onProgress?.(index, result) : void 0) };
2308
3023
  }
2309
3024
  /**
2310
3025
  * The common `prepare` body for plays that personalize via `safeEnrich` (cached
@@ -2332,18 +3047,18 @@ async function standardEnrich(opts) {
2332
3047
  }
2333
3048
  //#endregion
2334
3049
  //#region ../../packages/plays/src/accelerator-batch.ts
2335
- const PLAY_NAME$20 = "accelerator-batch";
3050
+ const PLAY_NAME$24 = "accelerator-batch";
2336
3051
  function runAcceleratorBatch(opts) {
2337
3052
  const senderCohortFor = (t) => (t.senderCohort?.trim() || opts.senderCohort || "").trim();
2338
3053
  const offerFor = (t) => t.freeForCohortOffer ?? opts.freeForCohortOffer;
2339
3054
  return runEmailPlay({
2340
- playName: PLAY_NAME$20,
3055
+ playName: PLAY_NAME$24,
2341
3056
  promptName: "accelerator-batch-email",
2342
- maxBodyWords: 100,
3057
+ maxBodyWords: 150,
2343
3058
  enrollCadence: true,
2344
3059
  toEmail: (t) => t.email,
2345
3060
  prepare: (t, dryRun) => standardEnrich({
2346
- playName: PLAY_NAME$20,
3061
+ playName: PLAY_NAME$24,
2347
3062
  enrichInput: {
2348
3063
  ...t.email ? { email: t.email } : {},
2349
3064
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2378,14 +3093,14 @@ function runAcceleratorBatch(opts) {
2378
3093
  }, opts);
2379
3094
  }
2380
3095
  registerSequence({
2381
- playName: PLAY_NAME$20,
3096
+ playName: PLAY_NAME$24,
2382
3097
  steps: [{
2383
3098
  dayOffset: 5,
2384
3099
  channel: "email",
2385
3100
  breakOnReply: true,
2386
3101
  label: "single follow-up + breakup",
2387
3102
  builder: buildFollowUpEmail({
2388
- playName: PLAY_NAME$20,
3103
+ playName: PLAY_NAME$24,
2389
3104
  promptName: "breakup-email",
2390
3105
  contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
2391
3106
  })
@@ -2393,7 +3108,7 @@ registerSequence({
2393
3108
  });
2394
3109
  //#endregion
2395
3110
  //#region ../../packages/plays/src/breakup-revive.ts
2396
- const PLAY_NAME$19 = "breakup-revive";
3111
+ const PLAY_NAME$23 = "breakup-revive";
2397
3112
  async function runBreakupRevive(opts) {
2398
3113
  const cfg = loadConfig();
2399
3114
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
@@ -2414,7 +3129,7 @@ async function runBreakupRevive(opts) {
2414
3129
  });
2415
3130
  const flags = lintEmail(draft.subject, draft.body, 80);
2416
3131
  const send = await sendDraftedEmail({
2417
- playName: PLAY_NAME$19,
3132
+ playName: PLAY_NAME$23,
2418
3133
  to: t.email,
2419
3134
  draft,
2420
3135
  flags,
@@ -2430,7 +3145,8 @@ async function runBreakupRevive(opts) {
2430
3145
  daysCold: t.daysCold,
2431
3146
  lastEventAt: t.lastEventAt
2432
3147
  },
2433
- dryRun: opts.dryRun
3148
+ dryRun: opts.dryRun,
3149
+ allowRecontact: true
2434
3150
  });
2435
3151
  drafted.push({
2436
3152
  prospectEmail: t.email,
@@ -2475,12 +3191,12 @@ function ledgerScanTargets(opts) {
2475
3191
  }
2476
3192
  //#endregion
2477
3193
  //#region ../../packages/plays/src/competitor-switch.ts
2478
- const PLAY_NAME$18 = "competitor-switch";
3194
+ const PLAY_NAME$22 = "competitor-switch";
2479
3195
  function runCompetitorSwitch(opts) {
2480
3196
  return runEmailPlay({
2481
- playName: PLAY_NAME$18,
3197
+ playName: PLAY_NAME$22,
2482
3198
  promptName: "competitor-switch-email",
2483
- maxBodyWords: 100,
3199
+ maxBodyWords: 150,
2484
3200
  enrollCadence: true,
2485
3201
  toEmail: (t) => t.email,
2486
3202
  prepare: async (t, dryRun) => {
@@ -2490,7 +3206,7 @@ function runCompetitorSwitch(opts) {
2490
3206
  ...t.email ? { email: t.email } : {},
2491
3207
  name: t.name,
2492
3208
  companyDomain: emailDomain(t.email)
2493
- }, { playName: PLAY_NAME$18 });
3209
+ }, { playName: PLAY_NAME$22 });
2494
3210
  if (enr.receiptId) receiptIds.push(enr.receiptId);
2495
3211
  const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
2496
3212
  if (!dryRun) {
@@ -2514,7 +3230,7 @@ function runCompetitorSwitch(opts) {
2514
3230
  }
2515
3231
  },
2516
3232
  maxSteps: 12
2517
- }, { playName: PLAY_NAME$18 });
3233
+ }, { playName: PLAY_NAME$22 });
2518
3234
  receiptIds.push(browse.receiptId);
2519
3235
  scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
2520
3236
  }
@@ -2552,14 +3268,14 @@ function runCompetitorSwitch(opts) {
2552
3268
  }, opts);
2553
3269
  }
2554
3270
  registerSequence({
2555
- playName: PLAY_NAME$18,
3271
+ playName: PLAY_NAME$22,
2556
3272
  steps: [{
2557
3273
  dayOffset: 3,
2558
3274
  channel: "email",
2559
3275
  breakOnReply: true,
2560
3276
  label: "value follow-up",
2561
3277
  builder: buildFollowUpEmail({
2562
- playName: PLAY_NAME$18,
3278
+ playName: PLAY_NAME$22,
2563
3279
  promptName: "competitor-switch-followup",
2564
3280
  contextLines: [`PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`]
2565
3281
  })
@@ -2569,7 +3285,7 @@ registerSequence({
2569
3285
  breakOnReply: true,
2570
3286
  label: "breakup",
2571
3287
  builder: buildFollowUpEmail({
2572
- playName: PLAY_NAME$18,
3288
+ playName: PLAY_NAME$22,
2573
3289
  promptName: "breakup-email",
2574
3290
  contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
2575
3291
  })
@@ -2577,13 +3293,13 @@ registerSequence({
2577
3293
  });
2578
3294
  //#endregion
2579
3295
  //#region ../../packages/plays/src/hiring-signal.ts
2580
- const PLAY_NAME$17 = "hiring-signal";
3296
+ const PLAY_NAME$21 = "hiring-signal";
2581
3297
  const NO_HOOK = "(no specific job post phrase scraped)";
2582
3298
  function runHiringSignal(opts) {
2583
3299
  return runEmailPlay({
2584
- playName: PLAY_NAME$17,
3300
+ playName: PLAY_NAME$21,
2585
3301
  promptName: "hiring-signal-email",
2586
- maxBodyWords: 100,
3302
+ maxBodyWords: 150,
2587
3303
  enrollCadence: true,
2588
3304
  errorExtra: { jobPostHook: "(error)" },
2589
3305
  toEmail: (t) => t.email,
@@ -2596,12 +3312,12 @@ function runHiringSignal(opts) {
2596
3312
  const search = await webSearch({
2597
3313
  query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
2598
3314
  maxResults: 5
2599
- }, { playName: PLAY_NAME$17 });
3315
+ }, { playName: PLAY_NAME$21 });
2600
3316
  receiptIds.push(search.receiptId);
2601
3317
  jobUrl = search.result.results[0]?.url;
2602
3318
  }
2603
3319
  if (jobUrl) {
2604
- const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$17 });
3320
+ const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$21 });
2605
3321
  receiptIds.push(read.receiptId);
2606
3322
  const md = read.result.markdown ?? "";
2607
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();
@@ -2636,14 +3352,14 @@ function runHiringSignal(opts) {
2636
3352
  }, opts);
2637
3353
  }
2638
3354
  registerSequence({
2639
- playName: PLAY_NAME$17,
3355
+ playName: PLAY_NAME$21,
2640
3356
  steps: [{
2641
3357
  dayOffset: 3,
2642
3358
  channel: "email",
2643
3359
  breakOnReply: true,
2644
3360
  label: "value follow-up",
2645
3361
  builder: buildFollowUpEmail({
2646
- playName: PLAY_NAME$17,
3362
+ playName: PLAY_NAME$21,
2647
3363
  promptName: "hiring-signal-followup",
2648
3364
  contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`]
2649
3365
  })
@@ -2653,7 +3369,7 @@ registerSequence({
2653
3369
  breakOnReply: true,
2654
3370
  label: "breakup",
2655
3371
  builder: buildFollowUpEmail({
2656
- playName: PLAY_NAME$17,
3372
+ playName: PLAY_NAME$21,
2657
3373
  promptName: "breakup-email",
2658
3374
  contextLines: [`PLAY: hiring-signal. Final breakup.`]
2659
3375
  })
@@ -2661,15 +3377,15 @@ registerSequence({
2661
3377
  });
2662
3378
  //#endregion
2663
3379
  //#region ../../packages/plays/src/job-change.ts
2664
- const PLAY_NAME$16 = "job-change";
3380
+ const PLAY_NAME$20 = "job-change";
2665
3381
  const jobChangeDef = {
2666
- playName: PLAY_NAME$16,
3382
+ playName: PLAY_NAME$20,
2667
3383
  promptName: "job-change-email",
2668
- maxBodyWords: 100,
3384
+ maxBodyWords: 150,
2669
3385
  enrollCadence: true,
2670
3386
  toEmail: (t) => t.email,
2671
3387
  prepare: (t, dryRun) => standardEnrich({
2672
- playName: PLAY_NAME$16,
3388
+ playName: PLAY_NAME$20,
2673
3389
  enrichInput: {
2674
3390
  ...t.email ? { email: t.email } : {},
2675
3391
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2703,14 +3419,14 @@ function runJobChange(opts) {
2703
3419
  return runEmailPlay(jobChangeDef, opts);
2704
3420
  }
2705
3421
  registerSequence({
2706
- playName: PLAY_NAME$16,
3422
+ playName: PLAY_NAME$20,
2707
3423
  steps: [{
2708
3424
  dayOffset: 5,
2709
3425
  channel: "email",
2710
3426
  breakOnReply: true,
2711
3427
  label: "value follow-up",
2712
3428
  builder: buildFollowUpEmail({
2713
- playName: PLAY_NAME$16,
3429
+ playName: PLAY_NAME$20,
2714
3430
  promptName: "job-change-followup",
2715
3431
  contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
2716
3432
  })
@@ -2720,20 +3436,88 @@ registerSequence({
2720
3436
  breakOnReply: true,
2721
3437
  label: "breakup",
2722
3438
  builder: buildFollowUpEmail({
2723
- playName: PLAY_NAME$16,
3439
+ playName: PLAY_NAME$20,
2724
3440
  promptName: "breakup-email",
2725
3441
  contextLines: [`PLAY: job-change. Sender is closing the file.`]
2726
3442
  })
2727
3443
  }]
2728
3444
  });
2729
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
2730
3514
  //#region ../../packages/plays/src/podcast-guest.ts
2731
- const PLAY_NAME$15 = "podcast-guest";
3515
+ const PLAY_NAME$18 = "podcast-guest";
2732
3516
  function runPodcastGuest(opts) {
2733
3517
  return runEmailPlay({
2734
- playName: PLAY_NAME$15,
3518
+ playName: PLAY_NAME$18,
2735
3519
  promptName: "podcast-guest-email",
2736
- maxBodyWords: 90,
3520
+ maxBodyWords: 150,
2737
3521
  enrollCadence: true,
2738
3522
  toEmail: (t) => t.email,
2739
3523
  prepare: async (t, dryRun) => {
@@ -2743,7 +3527,7 @@ function runPodcastGuest(opts) {
2743
3527
  const s = await webSearch({
2744
3528
  query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
2745
3529
  maxResults: 3
2746
- }, { playName: PLAY_NAME$15 });
3530
+ }, { playName: PLAY_NAME$18 });
2747
3531
  receiptIds.push(s.receiptId);
2748
3532
  dossier = s.result.results.slice(0, 2).map((r) => `- ${r.title}: ${r.description}`).join("\n");
2749
3533
  }
@@ -2777,20 +3561,20 @@ function runPodcastGuest(opts) {
2777
3561
  }, opts);
2778
3562
  }
2779
3563
  registerSequence({
2780
- playName: PLAY_NAME$15,
3564
+ playName: PLAY_NAME$18,
2781
3565
  steps: []
2782
3566
  });
2783
3567
  //#endregion
2784
3568
  //#region ../../packages/plays/src/post-funding.ts
2785
- const PLAY_NAME$14 = "post-funding";
3569
+ const PLAY_NAME$17 = "post-funding";
2786
3570
  const postFundingDef = {
2787
- playName: PLAY_NAME$14,
3571
+ playName: PLAY_NAME$17,
2788
3572
  promptName: "post-funding-email",
2789
- maxBodyWords: 100,
3573
+ maxBodyWords: 150,
2790
3574
  enrollCadence: true,
2791
3575
  toEmail: (t) => t.email,
2792
3576
  prepare: (t, dryRun) => standardEnrich({
2793
- playName: PLAY_NAME$14,
3577
+ playName: PLAY_NAME$17,
2794
3578
  enrichInput: {
2795
3579
  ...t.email ? { email: t.email } : {},
2796
3580
  ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
@@ -2826,14 +3610,14 @@ function runPostFunding(opts) {
2826
3610
  return runEmailPlay(postFundingDef, opts);
2827
3611
  }
2828
3612
  registerSequence({
2829
- playName: PLAY_NAME$14,
3613
+ playName: PLAY_NAME$17,
2830
3614
  steps: [{
2831
3615
  dayOffset: 9,
2832
3616
  channel: "email",
2833
3617
  breakOnReply: true,
2834
3618
  label: "case-study follow-up",
2835
3619
  builder: buildFollowUpEmail({
2836
- playName: PLAY_NAME$14,
3620
+ playName: PLAY_NAME$17,
2837
3621
  promptName: "post-funding-followup",
2838
3622
  contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
2839
3623
  })
@@ -2843,22 +3627,77 @@ registerSequence({
2843
3627
  breakOnReply: true,
2844
3628
  label: "breakup",
2845
3629
  builder: buildFollowUpEmail({
2846
- playName: PLAY_NAME$14,
3630
+ playName: PLAY_NAME$17,
2847
3631
  promptName: "breakup-email",
2848
3632
  contextLines: [`PLAY: post-funding.`]
2849
3633
  })
2850
3634
  }]
2851
3635
  });
2852
3636
  //#endregion
3637
+ //#region ../../packages/plays/src/repo-interest.ts
3638
+ const PLAY_NAME$16 = "repo-interest";
3639
+ const repoInterestDef = {
3640
+ playName: PLAY_NAME$16,
3641
+ promptName: "repo-interest-email",
3642
+ maxBodyWords: 150,
3643
+ enrollCadence: true,
3644
+ toEmail: (t) => t.email,
3645
+ prepare: (t) => standardEnrich({
3646
+ playName: PLAY_NAME$16,
3647
+ enrichInput: {
3648
+ ...t.email ? { email: t.email } : {},
3649
+ name: t.name,
3650
+ companyDomain: emailDomain(t.email)
3651
+ },
3652
+ enrichSlice: 3500
3653
+ }),
3654
+ buildInputBlock: (t, prep, cfg) => [
3655
+ `FOUNDER: ${cfg.founderName}`,
3656
+ `PRODUCT: ${cfg.productOneLiner}`,
3657
+ `PROSPECT: ${t.name} at ${t.company}`,
3658
+ `STARRED REPO: ${t.repoLabel ?? t.repo}`,
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)"}`)] : [],
3662
+ `DOSSIER:\n${prep.dossier || "(dry-run)"}`
3663
+ ].join("\n"),
3664
+ prospectMeta: (t) => ({
3665
+ name: t.name,
3666
+ email: t.email,
3667
+ company: t.company,
3668
+ linkedin_url: t.linkedinUrl ?? null,
3669
+ phone: t.phone ?? null,
3670
+ source: "repo-interest"
3671
+ }),
3672
+ metadata: (t) => ({ repo: t.repo })
3673
+ };
3674
+ function runRepoInterest(opts) {
3675
+ return runEmailPlay(repoInterestDef, opts);
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
+ });
3691
+ //#endregion
2853
3692
  //#region ../../packages/plays/src/show-hn.ts
2854
- const PLAY_NAME$13 = "show-hn";
3693
+ const PLAY_NAME$15 = "show-hn";
2855
3694
  const showHnDef = {
2856
- playName: PLAY_NAME$13,
3695
+ playName: PLAY_NAME$15,
2857
3696
  promptName: "show-hn-email",
2858
- maxBodyWords: 90,
3697
+ maxBodyWords: 150,
2859
3698
  toEmail: (t) => t.founderEmail,
2860
3699
  prepare: (t, dryRun) => standardEnrich({
2861
- playName: PLAY_NAME$13,
3700
+ playName: PLAY_NAME$15,
2862
3701
  enrichInput: {
2863
3702
  email: t.founderEmail,
2864
3703
  name: t.founderName
@@ -2896,15 +3735,15 @@ function extractCompany(title) {
2896
3735
  }
2897
3736
  //#endregion
2898
3737
  //#region ../../packages/plays/src/stack-consolidation.ts
2899
- const PLAY_NAME$12 = "stack-consolidation";
3738
+ const PLAY_NAME$14 = "stack-consolidation";
2900
3739
  const stackConsolidationDef = {
2901
- playName: PLAY_NAME$12,
3740
+ playName: PLAY_NAME$14,
2902
3741
  promptName: "stack-consolidation-email",
2903
- maxBodyWords: 100,
3742
+ maxBodyWords: 150,
2904
3743
  enrollCadence: true,
2905
3744
  toEmail: (t) => t.email,
2906
3745
  prepare: (t) => standardEnrich({
2907
- playName: PLAY_NAME$12,
3746
+ playName: PLAY_NAME$14,
2908
3747
  enrichInput: {
2909
3748
  ...t.email ? { email: t.email } : {},
2910
3749
  name: t.name,
@@ -2937,14 +3776,14 @@ function runStackConsolidation(opts) {
2937
3776
  return runEmailPlay(stackConsolidationDef, opts);
2938
3777
  }
2939
3778
  registerSequence({
2940
- playName: PLAY_NAME$12,
3779
+ playName: PLAY_NAME$14,
2941
3780
  steps: [{
2942
3781
  dayOffset: 3,
2943
3782
  channel: "email",
2944
3783
  breakOnReply: true,
2945
3784
  label: "value follow-up",
2946
3785
  builder: buildFollowUpEmail({
2947
- playName: PLAY_NAME$12,
3786
+ playName: PLAY_NAME$14,
2948
3787
  promptName: "stack-consolidation-followup",
2949
3788
  contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
2950
3789
  })
@@ -2954,7 +3793,7 @@ registerSequence({
2954
3793
  breakOnReply: true,
2955
3794
  label: "breakup",
2956
3795
  builder: buildFollowUpEmail({
2957
- playName: PLAY_NAME$12,
3796
+ playName: PLAY_NAME$14,
2958
3797
  promptName: "breakup-email",
2959
3798
  contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
2960
3799
  })
@@ -2962,46 +3801,59 @@ registerSequence({
2962
3801
  });
2963
3802
  //#endregion
2964
3803
  //#region ../../packages/plays/src/registry.ts
2965
- /**
2966
- * Single source of truth mapping a play name → its runner. Both the server's
2967
- * `/api/run` dispatch and the queue drainer look plays up here, so adding a
2968
- * play means registering it once (its file + this table) instead of editing
2969
- * two parallel switch statements that silently drifted apart.
2970
- */
3804
+ const progressOpt = (o) => o.onProgress ? { onProgress: o.onProgress } : {};
2971
3805
  const PLAYS = {
2972
3806
  "show-hn": { run: (o) => runShowHn({
2973
3807
  dryRun: o.dryRun,
2974
- targets: o.targets
3808
+ targets: o.targets,
3809
+ ...progressOpt(o)
2975
3810
  }) },
2976
3811
  "job-change": { run: (o) => runJobChange({
2977
3812
  dryRun: o.dryRun,
2978
- targets: o.targets
3813
+ targets: o.targets,
3814
+ ...progressOpt(o)
2979
3815
  }) },
2980
3816
  "post-funding": { run: (o) => runPostFunding({
2981
3817
  dryRun: o.dryRun,
2982
- targets: o.targets
3818
+ targets: o.targets,
3819
+ ...progressOpt(o)
2983
3820
  }) },
2984
3821
  "accelerator-batch": { run: (o) => runAcceleratorBatch({
2985
3822
  dryRun: o.dryRun,
2986
3823
  targets: o.targets,
2987
3824
  ...o.senderCohort ? { senderCohort: o.senderCohort } : {},
2988
- ...o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {}
3825
+ ...o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {},
3826
+ ...progressOpt(o)
2989
3827
  }) },
2990
3828
  "hiring-signal": { run: (o) => runHiringSignal({
2991
3829
  dryRun: o.dryRun,
2992
- targets: o.targets
3830
+ targets: o.targets,
3831
+ ...progressOpt(o)
2993
3832
  }) },
2994
3833
  "podcast-guest": { run: (o) => runPodcastGuest({
2995
3834
  dryRun: o.dryRun,
2996
- targets: o.targets
3835
+ targets: o.targets,
3836
+ ...progressOpt(o)
2997
3837
  }) },
2998
3838
  "competitor-switch": { run: (o) => runCompetitorSwitch({
2999
3839
  dryRun: o.dryRun,
3000
- targets: o.targets
3840
+ targets: o.targets,
3841
+ ...progressOpt(o)
3001
3842
  }) },
3002
3843
  "stack-consolidation": { run: (o) => runStackConsolidation({
3003
3844
  dryRun: o.dryRun,
3004
- targets: o.targets
3845
+ targets: o.targets,
3846
+ ...progressOpt(o)
3847
+ }) },
3848
+ "repo-interest": { run: (o) => runRepoInterest({
3849
+ dryRun: o.dryRun,
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)
3005
3857
  }) },
3006
3858
  "breakup-revive": { run: (o) => runBreakupRevive({
3007
3859
  dryRun: o.dryRun,
@@ -3013,16 +3865,16 @@ function isSupportedPlay(name) {
3013
3865
  }
3014
3866
  //#endregion
3015
3867
  //#region ../../packages/plays/src/demo-no-show.ts
3016
- const PLAY_NAME$11 = "demo-no-show";
3868
+ const PLAY_NAME$13 = "demo-no-show";
3017
3869
  registerSequence({
3018
- playName: PLAY_NAME$11,
3870
+ playName: PLAY_NAME$13,
3019
3871
  steps: [{
3020
3872
  dayOffset: 3,
3021
3873
  channel: "email",
3022
3874
  breakOnReply: true,
3023
3875
  label: "day-3 follow-up",
3024
3876
  builder: buildFollowUpEmail({
3025
- playName: PLAY_NAME$11,
3877
+ playName: PLAY_NAME$13,
3026
3878
  promptName: "demo-no-show-followup",
3027
3879
  contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`]
3028
3880
  })
@@ -3031,17 +3883,43 @@ registerSequence({
3031
3883
  //#endregion
3032
3884
  //#region src/api/cadences.ts
3033
3885
  /**
3034
- * In-process tracker of cadence steps that have a fire-and-forget send in
3035
- * flight. Populated by sendCadenceStepRoute + sendCadenceBatchRoute when
3036
- * they kick off the background SDK send (~2 min per row), cleared per-row
3037
- * as each send settles. Used by `toView` to surface `isSending: true` so
3038
- * /cadences can visually mark in-flight rows AND gate them out of the
3039
- * sendable-rows count. Lost on server restart (acceptable — in-flight SDK
3040
- * 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.
3041
3899
  */
3042
- const inFlightSends = /* @__PURE__ */ new Set();
3043
- const inFlightKey = (prospectId, playName) => `${prospectId}|${playName}`;
3044
- function toView$3(row) {
3900
+ const MAX_SEND_AGE_MS = 300 * 1e3;
3901
+ function buildPlayInfoMap(rows) {
3902
+ const map = /* @__PURE__ */ new Map();
3903
+ for (const row of rows) {
3904
+ let info = map.get(row.play_name);
3905
+ if (!info) {
3906
+ info = {
3907
+ nextLabelByStep: /* @__PURE__ */ new Map(),
3908
+ followupCount: playFollowupCount(row.play_name)
3909
+ };
3910
+ map.set(row.play_name, info);
3911
+ }
3912
+ if (!info.nextLabelByStep.has(row.current_step)) {
3913
+ const next = nextStepInfo(row.play_name, row.current_step);
3914
+ info.nextLabelByStep.set(row.current_step, {
3915
+ label: next?.label ?? null,
3916
+ isBreakup: next?.isBreakup ?? false
3917
+ });
3918
+ }
3919
+ }
3920
+ return map;
3921
+ }
3922
+ function toView$3(row, priorByKey, playInfo) {
3045
3923
  let nextStepDraft = null;
3046
3924
  if (row.next_step_draft_json) try {
3047
3925
  const parsed = JSON.parse(row.next_step_draft_json);
@@ -3054,8 +3932,10 @@ function toView$3(row) {
3054
3932
  } catch {
3055
3933
  nextStepDraft = null;
3056
3934
  }
3057
- const next = nextStepInfo(row.play_name, row.current_step);
3058
- const priorSteps = getPriorStepsForProspect(row.prospect_id, row.play_name).map((s) => ({
3935
+ const info = playInfo.get(row.play_name);
3936
+ const next = info?.nextLabelByStep.get(row.current_step) ?? null;
3937
+ const followupCount = info?.followupCount ?? 0;
3938
+ const priorSteps = (priorByKey.get(`${row.prospect_id}|${row.play_name}`) ?? []).map((s) => ({
3059
3939
  stepIndex: s.stepIndex,
3060
3940
  label: s.label,
3061
3941
  subject: s.subject,
@@ -3076,30 +3956,49 @@ function toView$3(row) {
3076
3956
  nextStepDraft,
3077
3957
  nextStepLabel: next?.label ?? null,
3078
3958
  nextStepIsBreakup: next?.isBreakup ?? false,
3079
- followupCount: playFollowupCount(row.play_name),
3959
+ followupCount,
3080
3960
  priorSteps,
3081
- isSending: inFlightSends.has(inFlightKey(row.prospect_id, row.play_name))
3961
+ isSending: row.sending_started_at != null
3082
3962
  };
3083
3963
  }
3964
+ function viewsForRows(rows) {
3965
+ const priorByKey = getPriorStepsBulk(rows.map((r) => ({
3966
+ prospectId: r.prospect_id,
3967
+ playName: r.play_name
3968
+ })));
3969
+ const playInfo = buildPlayInfoMap(rows);
3970
+ return rows.map((r) => toView$3(r, priorByKey, playInfo));
3971
+ }
3084
3972
  function listCadences(req) {
3085
- 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;
3086
3977
  const ledger = getLedger();
3087
- return jsonResponse({ cadences: (all ? ledger.listAllCadences() : ledger.listActiveCadences()).map(toView$3) }, 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);
3088
3988
  }
3089
3989
  function getCadence(req, params) {
3090
3990
  const id = Number.parseInt(params["id"] ?? "", 10);
3091
3991
  if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
3092
- const all = getLedger().listAllCadences().filter((c) => c.prospect_id === id);
3992
+ const all = getLedger().listCadencesForProspect(id);
3093
3993
  if (all.length === 0) return jsonResponse({ error: "no cadences for prospect" }, 404, req);
3094
- return jsonResponse({ cadences: all.map(toView$3) }, 200, req);
3994
+ return jsonResponse({ cadences: viewsForRows(all) }, 200, req);
3095
3995
  }
3096
3996
  function stopCadence(req, params) {
3097
3997
  const id = Number.parseInt(params["id"] ?? "", 10);
3098
3998
  if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
3099
3999
  const playName = new URL(req.url).searchParams.get("play");
3100
4000
  const ledger = getLedger();
3101
- const cadences = ledger.listAllCadences().filter((c) => {
3102
- if (c.prospect_id !== id) return false;
4001
+ const cadences = ledger.listCadencesForProspect(id).filter((c) => {
3103
4002
  if (playName && c.play_name !== playName) return false;
3104
4003
  return c.status === "active";
3105
4004
  });
@@ -3140,15 +4039,23 @@ async function previewCadenceStepRoute(req, params) {
3140
4039
  }
3141
4040
  }
3142
4041
  async function sendCadenceStepRoute(req, params) {
4042
+ if (isDraining()) return jsonResponse({ error: "server restarting — retry in a moment" }, 503, req);
3143
4043
  const parsed = parseProspectAndPlay(req, params);
3144
4044
  if (parsed instanceof Response) return parsed;
4045
+ const ledger = getLedger();
3145
4046
  try {
3146
- 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);
3147
4048
  } catch (err) {
3148
4049
  return jsonResponse({ error: err.message ?? "send failed" }, 500, req);
3149
4050
  }
3150
- const key = inFlightKey(parsed.prospectId, parsed.playName);
3151
- 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);
3152
4059
  (async () => {
3153
4060
  try {
3154
4061
  await sendCadenceStep(parsed);
@@ -3158,8 +4065,9 @@ async function sendCadenceStepRoute(req, params) {
3158
4065
  play_name: parsed.playName,
3159
4066
  message_120: (err?.message ?? "").slice(0, 120)
3160
4067
  }, "error");
3161
- } finally {
3162
- inFlightSends.delete(key);
4068
+ try {
4069
+ ledger.clearCadenceSendingMarker(parsed);
4070
+ } catch {}
3163
4071
  }
3164
4072
  })();
3165
4073
  return jsonResponse({ accepted: true }, 202, req);
@@ -3189,21 +4097,36 @@ async function previewCadenceBatchRoute(req) {
3189
4097
  return jsonResponse({ results: await previewCadenceStepBatch(itemsOrErr) }, 200, req);
3190
4098
  }
3191
4099
  async function sendCadenceBatchRoute(req) {
4100
+ if (isDraining()) return jsonResponse({ error: "server restarting — retry in a moment" }, 503, req);
3192
4101
  const itemsOrErr = await parseBatchItems(req);
3193
4102
  if (itemsOrErr instanceof Response) return itemsOrErr;
3194
4103
  const items = itemsOrErr;
3195
- 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);
3196
4115
  (async () => {
3197
4116
  try {
3198
- await sendCadenceStepBatch(items, (item) => {
3199
- inFlightSends.delete(inFlightKey(item.prospectId, item.playName));
4117
+ await sendCadenceStepBatch(claimed, (item) => {
4118
+ try {
4119
+ ledger.clearCadenceSendingMarker(item);
4120
+ } catch {}
3200
4121
  });
3201
4122
  } catch (err) {
3202
- 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 {}
3203
4126
  logEvent("cadence.batch.failed", { message_120: (err?.message ?? "").slice(0, 120) }, "error");
3204
4127
  }
3205
4128
  })();
3206
- return jsonResponse({ accepted: items.length }, 202, req);
4129
+ return jsonResponse({ accepted: claimed.length }, 202, req);
3207
4130
  }
3208
4131
  //#endregion
3209
4132
  //#region src/api/receipts.ts
@@ -3358,6 +4281,14 @@ const PLAY_CATALOG = [
3358
4281
  name: "stack-consolidation",
3359
4282
  cli: "oneshot-gtm find watch # fed by the github-topics finder, drained from /queue"
3360
4283
  },
4284
+ {
4285
+ name: "repo-interest",
4286
+ cli: "oneshot-gtm find watch # fed by the github-stars finder (adjacent repos), drained from /queue"
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
+ },
3361
4292
  {
3362
4293
  name: "hiring-signal",
3363
4294
  cli: "oneshot-gtm motion hiring-signal --target ./examples/hiring-signal.json"
@@ -3581,7 +4512,7 @@ function mergeString(incoming, current) {
3581
4512
  }
3582
4513
  //#endregion
3583
4514
  //#region src/api/derive-icp.ts
3584
- const PLAY_NAME$10 = "config:icp";
4515
+ const PLAY_NAME$12 = "config:icp";
3585
4516
  async function deriveIcpRoute(req) {
3586
4517
  startRun();
3587
4518
  let body = {};
@@ -3600,7 +4531,7 @@ async function deriveIcpRoute(req) {
3600
4531
  const readStartedAt = Date.now();
3601
4532
  logEvent("derive_icp.read.start", { host });
3602
4533
  try {
3603
- const read = await webRead({ url }, { playName: PLAY_NAME$10 });
4534
+ const read = await webRead({ url }, { playName: PLAY_NAME$12 });
3604
4535
  markdown = (read.result.markdown ?? "").trim();
3605
4536
  const c = read.result.cost;
3606
4537
  if (typeof c === "number") costUsd += c;
@@ -3717,17 +4648,29 @@ async function icpFilter(input) {
3717
4648
  icp: input.icp,
3718
4649
  candidate: input.candidate
3719
4650
  });
3720
- const decision = parseIcpJson((await complete({
3721
- messages: [{
3722
- role: "system",
3723
- content: system
3724
- }, {
3725
- role: "user",
3726
- content: user
3727
- }],
3728
- temperature: .1,
3729
- maxTokens: 200
3730
- })).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
+ }
3731
4674
  logEvent("icp.decision", {
3732
4675
  match: decision.match,
3733
4676
  reason_120: decision.reason.slice(0, 120),
@@ -3737,22 +4680,33 @@ async function icpFilter(input) {
3737
4680
  }
3738
4681
  function parseIcpJson(raw) {
3739
4682
  const parsed = tryParseJsonObject(raw, {});
4683
+ if (typeof parsed.match !== "boolean") return {
4684
+ match: null,
4685
+ reason: "icp classifier malformed response"
4686
+ };
3740
4687
  return {
3741
- match: parsed.match === true,
4688
+ match: parsed.match,
3742
4689
  reason: typeof parsed.reason === "string" ? parsed.reason : "no reason given"
3743
4690
  };
3744
4691
  }
3745
4692
  //#endregion
3746
4693
  //#region ../../packages/find/src/_dedupe.ts
3747
4694
  /**
3748
- * True if this (play, dedupe-key) pair is already in the queue
3749
- * 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.
3750
4703
  */
3751
4704
  function isDuplicate(opts) {
3752
4705
  const ledger = getLedger();
3753
4706
  if (ledger.isQueueDuplicate(opts.playName, opts.dedupeKey)) return true;
3754
4707
  if (opts.prospectEmail) {
3755
4708
  if (ledger.findProspectByEmail(opts.prospectEmail)) return true;
4709
+ if (ledger.isEmailPendingInQueue(opts.prospectEmail)) return true;
3756
4710
  }
3757
4711
  return false;
3758
4712
  }
@@ -3938,27 +4892,165 @@ function shouldSkipFindEmail(input) {
3938
4892
  return { ok: true };
3939
4893
  }
3940
4894
  //#endregion
3941
- //#region ../../packages/find/src/_linkedin.ts
4895
+ //#region ../../packages/find/src/_sdk-safe.ts
3942
4896
  /**
3943
- * Shared LinkedIn / phone capture helpers used across all finders. Centralises:
3944
- * - `findLinkedInUrl`: webSearch-based LinkedIn-URL discovery (active lookup)
3945
- * - `extractFirstPhone`: passive read of phone fields from enrichment SDK results
4897
+ * Per-candidate-safe wrappers for the two job-based contact-resolution SDK calls.
3946
4898
  *
3947
- * Both feed the same goal — populate `target.linkedinUrl` and `target.phone` so
3948
- * the founder sees these signals in /queue review and the prospect row carries
3949
- * them after drain.
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.
3950
4908
  */
3951
- const PLAY_NAME$9 = "linkedin-lookup";
3952
- /** Match `linkedin.com/in/<slug>` profile URLs. The slug class is permissive
3953
- * enough to cover URL-encoded unicode slugs (e.g. `%E7%8E%8B`) which LinkedIn
3954
- * does serve for non-Latin display names. */
3955
- const LINKEDIN_PROFILE_RX = /^https?:\/\/(?:[a-z0-9-]+\.)*linkedin\.com\/in\/[a-z0-9-_.%]+/i;
3956
- /** Per-process cache so the same `(fullName, disambiguators)` doesn't re-search
3957
- * within a run. `null` is a real cached value (means "we tried and missed"). */
3958
- const cache$2 = /* @__PURE__ */ new Map();
3959
- /**
3960
- * Returns true when `url` looks like a LinkedIn profile URL (`linkedin.com/in/<slug>`).
3961
- * Use to validate LLM-extracted `linkedinUrl` strings before persisting them —
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
5033
+ //#region ../../packages/find/src/_linkedin.ts
5034
+ /**
5035
+ * Shared LinkedIn / phone capture helpers used across all finders. Centralises:
5036
+ * - `findLinkedInUrl`: webSearch-based LinkedIn-URL discovery (active lookup)
5037
+ * - `extractFirstPhone`: passive read of phone fields from enrichment SDK results
5038
+ *
5039
+ * Both feed the same goal — populate `target.linkedinUrl` and `target.phone` so
5040
+ * the founder sees these signals in /queue review and the prospect row carries
5041
+ * them after drain.
5042
+ */
5043
+ const PLAY_NAME$11 = "linkedin-lookup";
5044
+ /** Match `linkedin.com/in/<slug>` profile URLs. The slug class is permissive
5045
+ * enough to cover URL-encoded unicode slugs (e.g. `%E7%8E%8B`) which LinkedIn
5046
+ * does serve for non-Latin display names. */
5047
+ const LINKEDIN_PROFILE_RX = /^https?:\/\/(?:[a-z0-9-]+\.)*linkedin\.com\/in\/[a-z0-9-_.%]+/i;
5048
+ /** Per-process cache so the same `(fullName, disambiguators)` doesn't re-search
5049
+ * within a run. `null` is a real cached value (means "we tried and missed"). */
5050
+ const cache$2 = /* @__PURE__ */ new Map();
5051
+ /**
5052
+ * Returns true when `url` looks like a LinkedIn profile URL (`linkedin.com/in/<slug>`).
5053
+ * Use to validate LLM-extracted `linkedinUrl` strings before persisting them —
3962
5054
  * the prompt instructs the LLM to emit only profile URLs but real outputs drift
3963
5055
  * (sometimes a `/posts/` URL, sometimes free-form prose).
3964
5056
  */
@@ -3995,7 +5087,7 @@ async function findLinkedInUrl(args) {
3995
5087
  const search = await webSearch({
3996
5088
  query,
3997
5089
  maxResults: 5
3998
- }, { playName: PLAY_NAME$9 });
5090
+ }, { playName: PLAY_NAME$11 });
3999
5091
  args.accumCost(search.result.cost ?? 0);
4000
5092
  for (const r of search.result.results ?? []) {
4001
5093
  const url = typeof r.url === "string" ? r.url : "";
@@ -4052,6 +5144,7 @@ function extractFirstPhone(source) {
4052
5144
  }
4053
5145
  //#endregion
4054
5146
  //#region ../../packages/find/src/_enrich.ts
5147
+ const ENRICH_CACHE_TTL_MS = 720 * 3600 * 1e3;
4055
5148
  /**
4056
5149
  * Always-on post-verify enrichment. Called by every enqueueing finder
4057
5150
  * AFTER verifyEmail succeeds + BEFORE enqueueTarget. Reads phone +
@@ -4069,8 +5162,32 @@ function extractFirstPhone(source) {
4069
5162
  * Path B' enrichProfile call in `_repo-pipeline.ts`.
4070
5163
  */
4071
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 {}
4072
5180
  try {
4073
- 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 {}
4074
5191
  const profile = enriched.result.profile;
4075
5192
  const linkedinRaw = profile?.linkedin_url ?? null;
4076
5193
  return {
@@ -4093,36 +5210,10 @@ async function enrichVerifiedContact(email, opts) {
4093
5210
  }
4094
5211
  }
4095
5212
  //#endregion
4096
- //#region ../../packages/find/src/_parallel.ts
4097
- /**
4098
- * Run `fn` over `items` with at most `concurrency` Promises in flight at once.
4099
- * Preserves input order in the result array. Errors propagate via Promise.all
4100
- * — caller is expected to catch per-item internally if partial success matters.
4101
- *
4102
- * Worker-pool implementation: spawn `concurrency` workers that pull from a
4103
- * shared cursor. Cheaper than a chunked Promise.all (which stalls on the
4104
- * slowest item per chunk) and avoids the dependency surface of p-limit.
4105
- */
4106
- async function parallelMap(items, concurrency, fn) {
4107
- const out = Array.from({ length: items.length });
4108
- if (items.length === 0) return out;
4109
- const workers = Math.max(1, Math.min(concurrency, items.length));
4110
- let cursor = 0;
4111
- async function worker() {
4112
- while (true) {
4113
- const i = cursor++;
4114
- if (i >= items.length) return;
4115
- out[i] = await fn(items[i], i);
4116
- }
4117
- }
4118
- await Promise.all(Array.from({ length: workers }, () => worker()));
4119
- return out;
4120
- }
4121
- //#endregion
4122
5213
  //#region ../../packages/find/src/show-hn.ts
4123
5214
  const HN_ALGOLIA = "https://hn.algolia.com/api/v1/search_by_date";
4124
- const PLAY_NAME$8 = "show-hn";
4125
- const SOURCE$6 = "find:show-hn";
5215
+ const PLAY_NAME$10 = "show-hn";
5216
+ const SOURCE$7 = "find:show-hn";
4126
5217
  /**
4127
5218
  * Pulls Show HN posts from HN Algolia, ICP-filters them, enriches founder
4128
5219
  * contact via OneShot, dedupes against the ledger, and enqueues into target_queue.
@@ -4134,7 +5225,7 @@ async function runShowHnFinder(opts) {
4134
5225
  const icp = resolveIcp(opts.icpOverride);
4135
5226
  const ledger = getLedger();
4136
5227
  const result = {
4137
- source: SOURCE$6,
5228
+ source: SOURCE$7,
4138
5229
  candidates: 0,
4139
5230
  droppedIcp: 0,
4140
5231
  droppedDuplicate: 0,
@@ -4144,7 +5235,7 @@ async function runShowHnFinder(opts) {
4144
5235
  costUsd: 0
4145
5236
  };
4146
5237
  logEvent("finder.start", {
4147
- name: PLAY_NAME$8,
5238
+ name: PLAY_NAME$10,
4148
5239
  since_days: sinceDays,
4149
5240
  limit
4150
5241
  });
@@ -4154,7 +5245,7 @@ async function runShowHnFinder(opts) {
4154
5245
  const data = await res.json();
4155
5246
  result.candidates = data.hits.length;
4156
5247
  logEvent("finder.fetched", {
4157
- name: PLAY_NAME$8,
5248
+ name: PLAY_NAME$10,
4158
5249
  candidates: result.candidates
4159
5250
  });
4160
5251
  const concurrency = opts.concurrency ?? 3;
@@ -4174,7 +5265,7 @@ async function runShowHnFinder(opts) {
4174
5265
  result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;
4175
5266
  return;
4176
5267
  }
4177
- if (ledger.isQueueDuplicate(PLAY_NAME$8, hit.objectID)) {
5268
+ if (ledger.isQueueDuplicate(PLAY_NAME$10, hit.objectID)) {
4178
5269
  result.droppedDuplicate++;
4179
5270
  return;
4180
5271
  }
@@ -4187,17 +5278,21 @@ async function runShowHnFinder(opts) {
4187
5278
  author: hit.author
4188
5279
  }
4189
5280
  });
5281
+ if (filter.match === null) {
5282
+ result.droppedEnrichment++;
5283
+ return;
5284
+ }
4190
5285
  if (!filter.match) {
4191
5286
  result.droppedIcp++;
4192
5287
  if (!opts.dryRun) ledger.enqueueTarget({
4193
- playName: PLAY_NAME$8,
5288
+ playName: PLAY_NAME$10,
4194
5289
  payload: {
4195
5290
  postTitle: hit.title,
4196
5291
  postUrl: hit.url,
4197
5292
  founderName: hit.author
4198
5293
  },
4199
5294
  dedupeKey: hit.objectID,
4200
- source: SOURCE$6,
5295
+ source: SOURCE$7,
4201
5296
  initialStatus: "rejected",
4202
5297
  notes: `auto: ICP — ${filter.reason}`
4203
5298
  });
@@ -4212,45 +5307,26 @@ async function runShowHnFinder(opts) {
4212
5307
  result.droppedEnrichment++;
4213
5308
  return;
4214
5309
  }
4215
- const fullName = hit.author && hit.author.length > 0 ? hit.author : void 0;
4216
- const skip = shouldSkipFindEmail({
4217
- fullName,
4218
- 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
+ })
4219
5319
  });
4220
- if (!skip.ok) {
4221
- result.droppedEnrichment++;
4222
- logEvent("finder.skipped_findemail", {
4223
- name: PLAY_NAME$8,
4224
- reason: skip.reason
4225
- }, "info");
4226
- return;
4227
- }
4228
- const findInput = { companyDomain: domain };
4229
- if (fullName) findInput.fullName = fullName;
4230
- const found = await findEmail(findInput, { playName: PLAY_NAME$8 });
4231
- result.costUsd += found.result.cost ?? 0;
4232
- if (!found.result.found || !found.result.email) {
4233
- result.droppedEnrichment++;
4234
- return;
4235
- }
4236
- const email = found.result.email;
4237
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$8 });
4238
- result.costUsd += verified.result.cost ?? 0;
4239
- if (!verified.result.deliverable) {
4240
- result.droppedEnrichment++;
4241
- return;
4242
- }
4243
- if (isDuplicate({
4244
- playName: PLAY_NAME$8,
4245
- dedupeKey: hit.objectID,
4246
- prospectEmail: email
4247
- })) {
4248
- result.droppedDuplicate++;
5320
+ result.costUsd += contact.costUsd;
5321
+ if (!contact.ok) {
5322
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
5323
+ else result.droppedEnrichment++;
4249
5324
  return;
4250
5325
  }
5326
+ const email = contact.email;
4251
5327
  let hookSummary = (hit.story_text ?? "").trim().slice(0, 280);
4252
5328
  if (hookSummary.length < 40 && hit.url) try {
4253
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$8 });
5329
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$10 });
4254
5330
  result.costUsd += read.result.cost ?? 0;
4255
5331
  hookSummary = (read.result.markdown ?? "").trim().slice(0, 280);
4256
5332
  } catch (err) {
@@ -4260,9 +5336,9 @@ async function runShowHnFinder(opts) {
4260
5336
  }, "warn");
4261
5337
  }
4262
5338
  if (!hookSummary || hookSummary.length < 20) hookSummary = `Show HN post: ${hit.title}. ${hit.points} points.`;
4263
- const founderName = found.result.full_name ?? hit.author;
5339
+ const founderName = contact.fullName ?? hit.author;
4264
5340
  const enr = await enrichVerifiedContact(email, {
4265
- playName: PLAY_NAME$8,
5341
+ playName: PLAY_NAME$10,
4266
5342
  errKindPrefix: "show-hn"
4267
5343
  });
4268
5344
  result.costUsd += enr.costUsd;
@@ -4286,16 +5362,16 @@ async function runShowHnFinder(opts) {
4286
5362
  ...phone ? { phone } : {}
4287
5363
  };
4288
5364
  if (ledger.enqueueTarget({
4289
- playName: PLAY_NAME$8,
5365
+ playName: PLAY_NAME$10,
4290
5366
  payload: target,
4291
5367
  dedupeKey: hit.objectID,
4292
- source: SOURCE$6,
5368
+ source: SOURCE$7,
4293
5369
  notes: filter.reason
4294
5370
  }) != null) result.enqueued++;
4295
5371
  else result.droppedDuplicate++;
4296
5372
  });
4297
5373
  logEvent("finder.done", {
4298
- name: PLAY_NAME$8,
5374
+ name: PLAY_NAME$10,
4299
5375
  candidates: result.candidates,
4300
5376
  enqueued: result.enqueued,
4301
5377
  dropped_icp: result.droppedIcp,
@@ -4309,8 +5385,8 @@ async function runShowHnFinder(opts) {
4309
5385
  }
4310
5386
  //#endregion
4311
5387
  //#region ../../packages/find/src/post-funding.ts
4312
- const PLAY_NAME$7 = "post-funding";
4313
- const SOURCE$5 = "find:post-funding";
5388
+ const PLAY_NAME$9 = "post-funding";
5389
+ const SOURCE$6 = "find:post-funding";
4314
5390
  const ROUND_MAP = {
4315
5391
  "Pre-Seed": "Pre-Seed",
4316
5392
  Seed: "Seed",
@@ -4337,7 +5413,7 @@ async function runPostFundingFinder(opts) {
4337
5413
  autoCost = harvested.costUsd;
4338
5414
  }
4339
5415
  const result = {
4340
- source: opts.auto ? `${SOURCE$5}:auto` : SOURCE$5,
5416
+ source: opts.auto ? `${SOURCE$6}:auto` : SOURCE$6,
4341
5417
  candidates: urls.length,
4342
5418
  droppedIcp: 0,
4343
5419
  droppedDuplicate: 0,
@@ -4350,7 +5426,7 @@ async function runPostFundingFinder(opts) {
4350
5426
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
4351
5427
  break;
4352
5428
  }
4353
- if (ledger.isQueueDuplicate(PLAY_NAME$7, url)) {
5429
+ if (ledger.isQueueDuplicate(PLAY_NAME$9, url)) {
4354
5430
  result.droppedDuplicate++;
4355
5431
  continue;
4356
5432
  }
@@ -4360,7 +5436,7 @@ async function runPostFundingFinder(opts) {
4360
5436
  }
4361
5437
  let extract;
4362
5438
  try {
4363
- const read = await webRead({ url }, { playName: PLAY_NAME$7 });
5439
+ const read = await webRead({ url }, { playName: PLAY_NAME$9 });
4364
5440
  result.costUsd += read.result.cost ?? 0;
4365
5441
  extract = parsePostFundingExtract((await complete({
4366
5442
  messages: [{
@@ -4393,10 +5469,14 @@ async function runPostFundingFinder(opts) {
4393
5469
  summary: extract.summary
4394
5470
  }
4395
5471
  });
5472
+ if (filter.match === null) {
5473
+ result.droppedEnrichment++;
5474
+ continue;
5475
+ }
4396
5476
  if (!filter.match) {
4397
5477
  result.droppedIcp++;
4398
5478
  ledger.enqueueTarget({
4399
- playName: PLAY_NAME$7,
5479
+ playName: PLAY_NAME$9,
4400
5480
  payload: {
4401
5481
  company: extract.company,
4402
5482
  round: extract.round,
@@ -4405,50 +5485,31 @@ async function runPostFundingFinder(opts) {
4405
5485
  sourceUrl: url
4406
5486
  },
4407
5487
  dedupeKey: url,
4408
- source: SOURCE$5,
5488
+ source: SOURCE$6,
4409
5489
  initialStatus: "rejected",
4410
5490
  notes: `auto: ICP — ${filter.reason}`
4411
5491
  });
4412
5492
  continue;
4413
5493
  }
4414
- const skip = shouldSkipFindEmail({
5494
+ const contact = await resolveAndVerifyContact({
5495
+ playName: PLAY_NAME$9,
4415
5496
  fullName: extract.founderName,
4416
- companyDomain: extract.companyDomain
5497
+ companyDomain: extract.companyDomain,
5498
+ isDuplicate: (email) => isDuplicate({
5499
+ playName: PLAY_NAME$9,
5500
+ dedupeKey: url,
5501
+ prospectEmail: email
5502
+ })
4417
5503
  });
4418
- if (!skip.ok) {
4419
- result.droppedEnrichment++;
4420
- logEvent("finder.skipped_findemail", {
4421
- name: PLAY_NAME$7,
4422
- reason: skip.reason
4423
- }, "info");
4424
- continue;
4425
- }
4426
- const found = await findEmail({
4427
- fullName: extract.founderName,
4428
- companyDomain: extract.companyDomain
4429
- }, { playName: PLAY_NAME$7 });
4430
- result.costUsd += found.result.cost ?? 0;
4431
- if (!found.result.found || !found.result.email) {
4432
- result.droppedEnrichment++;
4433
- continue;
4434
- }
4435
- const email = found.result.email;
4436
- if (isDuplicate({
4437
- playName: PLAY_NAME$7,
4438
- dedupeKey: url,
4439
- prospectEmail: email
4440
- })) {
4441
- result.droppedDuplicate++;
4442
- continue;
4443
- }
4444
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$7 });
4445
- result.costUsd += verified.result.cost ?? 0;
4446
- if (!verified.result.deliverable) {
4447
- result.droppedEnrichment++;
5504
+ result.costUsd += contact.costUsd;
5505
+ if (!contact.ok) {
5506
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
5507
+ else result.droppedEnrichment++;
4448
5508
  continue;
4449
5509
  }
5510
+ const email = contact.email;
4450
5511
  const enr = await enrichVerifiedContact(email, {
4451
- playName: PLAY_NAME$7,
5512
+ playName: PLAY_NAME$9,
4452
5513
  errKindPrefix: "post-funding"
4453
5514
  });
4454
5515
  result.costUsd += enr.costUsd;
@@ -4475,10 +5536,10 @@ async function runPostFundingFinder(opts) {
4475
5536
  ...phone ? { phone } : {}
4476
5537
  };
4477
5538
  if (ledger.enqueueTarget({
4478
- playName: PLAY_NAME$7,
5539
+ playName: PLAY_NAME$9,
4479
5540
  payload: target,
4480
5541
  dedupeKey: url,
4481
- source: SOURCE$5,
5542
+ source: SOURCE$6,
4482
5543
  notes: `${extract.round ?? "?"} ${extract.amountUsd ? `$${extract.amountUsd.toLocaleString()}` : ""} — ${filter.reason}`
4483
5544
  }) != null) result.enqueued++;
4484
5545
  else result.droppedDuplicate++;
@@ -4551,7 +5612,7 @@ async function harvestAutoUrls(args) {
4551
5612
  const search = await webSearch({
4552
5613
  query,
4553
5614
  maxResults: Math.min(20, Math.max(5, args.limit - urls.length))
4554
- }, { playName: PLAY_NAME$7 });
5615
+ }, { playName: PLAY_NAME$9 });
4555
5616
  costUsd += search.result.cost ?? 0;
4556
5617
  for (const hit of search.result.results ?? []) {
4557
5618
  if (urls.length >= args.limit) break;
@@ -4664,7 +5725,7 @@ function deriveIndustryHint(icp) {
4664
5725
  * Less reliable than the yc-oss adapter (search recall depends on the
4665
5726
  * accelerator's web presence) but works without per-accelerator scrapers.
4666
5727
  */
4667
- const PLAY_NAME$6 = "accelerator-batch";
5728
+ const PLAY_NAME$8 = "accelerator-batch";
4668
5729
  /**
4669
5730
  * Build the three search queries from a human-readable cohort label.
4670
5731
  * Founders supply `cohortLabel: "YC W26"` or `"Techstars Toronto Spring 2025"`
@@ -4733,7 +5794,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
4733
5794
  const search = await webSearch({
4734
5795
  query,
4735
5796
  maxResults: Math.min(15, limit)
4736
- }, { playName: PLAY_NAME$6 });
5797
+ }, { playName: PLAY_NAME$8 });
4737
5798
  costUsd += search.result.cost ?? 0;
4738
5799
  for (const raw of search.result.results ?? []) {
4739
5800
  if (!raw.url || seen.has(raw.url)) continue;
@@ -4762,7 +5823,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
4762
5823
  for (const hit of hits.slice(0, limit)) {
4763
5824
  let extract = null;
4764
5825
  try {
4765
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$6 });
5826
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$8 });
4766
5827
  costUsd += read.result.cost ?? 0;
4767
5828
  extract = parseAcceleratorLaunchExtract((await complete({
4768
5829
  messages: [{
@@ -5034,7 +6095,7 @@ function mapYcOssCompany(c) {
5034
6095
  * verifyEmail → enqueue, all under `parallelMap` (concurrency 3, mirrors
5035
6096
  * github-topics).
5036
6097
  */
5037
- const PLAY_NAME$5 = "accelerator-batch";
6098
+ const PLAY_NAME$7 = "accelerator-batch";
5038
6099
  /**
5039
6100
  * Normalize the legacy single-cohort opts shape into the new multi-cohort
5040
6101
  * list. Old trigger rows with `{cohort, cohortLabel}` keep working — they
@@ -5216,7 +6277,7 @@ async function runAcceleratorBatchFinder(opts) {
5216
6277
  return;
5217
6278
  }
5218
6279
  const dedupeKey = makeDedupeKey(record, record.cohort);
5219
- if (ledger.isQueueDuplicate(PLAY_NAME$5, dedupeKey)) {
6280
+ if (ledger.isQueueDuplicate(PLAY_NAME$7, dedupeKey)) {
5220
6281
  result.droppedDuplicate++;
5221
6282
  return;
5222
6283
  }
@@ -5232,10 +6293,14 @@ async function runAcceleratorBatchFinder(opts) {
5232
6293
  summary: buildIcpSummary(record)
5233
6294
  }
5234
6295
  });
6296
+ if (filter.match === null) {
6297
+ result.droppedEnrichment++;
6298
+ return;
6299
+ }
5235
6300
  if (!filter.match) {
5236
6301
  result.droppedIcp++;
5237
6302
  ledger.enqueueTarget({
5238
- playName: PLAY_NAME$5,
6303
+ playName: PLAY_NAME$7,
5239
6304
  payload: rejectionPayload(record, record.cohort),
5240
6305
  dedupeKey,
5241
6306
  source,
@@ -5263,45 +6328,26 @@ async function runAcceleratorBatchFinder(opts) {
5263
6328
  result.droppedEnrichment++;
5264
6329
  return;
5265
6330
  }
5266
- const skip = shouldSkipFindEmail({
6331
+ const contact = await resolveAndVerifyContact({
6332
+ playName: PLAY_NAME$7,
5267
6333
  fullName: founderName,
5268
- companyDomain: domain
6334
+ companyDomain: domain,
6335
+ isDuplicate: (email) => isDuplicate({
6336
+ playName: PLAY_NAME$7,
6337
+ dedupeKey,
6338
+ prospectEmail: email
6339
+ })
5269
6340
  });
5270
- if (!skip.ok) {
5271
- result.droppedEnrichment++;
5272
- logEvent("finder.skipped_findemail", {
5273
- name: PLAY_NAME$5,
5274
- reason: skip.reason
5275
- }, "info");
5276
- return;
5277
- }
5278
- const found = await findEmail({
5279
- fullName: founderName,
5280
- companyDomain: domain
5281
- }, { playName: PLAY_NAME$5 });
5282
- result.costUsd += found.result.cost ?? 0;
5283
- if (!found.result.found || !found.result.email) {
5284
- result.droppedEnrichment++;
5285
- return;
5286
- }
5287
- const email = found.result.email;
5288
- const fullName = found.result.full_name?.trim() || founderName;
5289
- if (isDuplicate({
5290
- playName: PLAY_NAME$5,
5291
- dedupeKey,
5292
- prospectEmail: email
5293
- })) {
5294
- result.droppedDuplicate++;
5295
- return;
5296
- }
5297
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$5 });
5298
- result.costUsd += verified.result.cost ?? 0;
5299
- if (!verified.result.deliverable) {
5300
- result.droppedEnrichment++;
6341
+ result.costUsd += contact.costUsd;
6342
+ if (!contact.ok) {
6343
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6344
+ else result.droppedEnrichment++;
5301
6345
  return;
5302
6346
  }
6347
+ const email = contact.email;
6348
+ const fullName = contact.fullName?.trim() || founderName;
5303
6349
  const enr = await enrichVerifiedContact(email, {
5304
- playName: PLAY_NAME$5,
6350
+ playName: PLAY_NAME$7,
5305
6351
  errKindPrefix: "accelerator-batch"
5306
6352
  });
5307
6353
  result.costUsd += enr.costUsd;
@@ -5328,7 +6374,7 @@ async function runAcceleratorBatchFinder(opts) {
5328
6374
  ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
5329
6375
  };
5330
6376
  if (ledger.enqueueTarget({
5331
- playName: PLAY_NAME$5,
6377
+ playName: PLAY_NAME$7,
5332
6378
  payload: target,
5333
6379
  dedupeKey,
5334
6380
  source,
@@ -5386,7 +6432,7 @@ async function resolveFounderName(record) {
5386
6432
  };
5387
6433
  let costUsd = 0;
5388
6434
  try {
5389
- const read = await webRead({ url }, { playName: PLAY_NAME$5 });
6435
+ const read = await webRead({ url }, { playName: PLAY_NAME$7 });
5390
6436
  costUsd += read.result.cost ?? 0;
5391
6437
  const extract = parseAcceleratorLaunchExtract((await complete({
5392
6438
  messages: [{
@@ -5426,8 +6472,8 @@ async function resolveFounderName(record) {
5426
6472
  }
5427
6473
  //#endregion
5428
6474
  //#region ../../packages/find/src/job-change.ts
5429
- const PLAY_NAME$4 = "job-change";
5430
- const SOURCE$4 = "find:job-change";
6475
+ const PLAY_NAME$6 = "job-change";
6476
+ const SOURCE$5 = "find:job-change";
5431
6477
  const DEFAULT_PERSONAS = [
5432
6478
  "VP Engineering",
5433
6479
  "Head of Growth",
@@ -5442,7 +6488,7 @@ async function runJobChangeFinder(opts) {
5442
6488
  const system = loadPrompt("job-change-extract");
5443
6489
  const personas = opts.personas && opts.personas.length > 0 ? opts.personas : DEFAULT_PERSONAS;
5444
6490
  const result = {
5445
- source: SOURCE$4,
6491
+ source: SOURCE$5,
5446
6492
  candidates: 0,
5447
6493
  droppedIcp: 0,
5448
6494
  droppedDuplicate: 0,
@@ -5460,7 +6506,7 @@ async function runJobChangeFinder(opts) {
5460
6506
  const search = await webSearch({
5461
6507
  query,
5462
6508
  maxResults: Math.min(15, limit)
5463
- }, { playName: PLAY_NAME$4 });
6509
+ }, { playName: PLAY_NAME$6 });
5464
6510
  result.costUsd += search.result.cost ?? 0;
5465
6511
  for (const hit of search.result.results ?? []) {
5466
6512
  if (!hit.url || seenUrls.has(hit.url)) continue;
@@ -5486,7 +6532,7 @@ async function runJobChangeFinder(opts) {
5486
6532
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
5487
6533
  break;
5488
6534
  }
5489
- if (ledger.isQueueDuplicate(PLAY_NAME$4, hit.url)) {
6535
+ if (ledger.isQueueDuplicate(PLAY_NAME$6, hit.url)) {
5490
6536
  result.droppedDuplicate++;
5491
6537
  continue;
5492
6538
  }
@@ -5502,17 +6548,21 @@ async function runJobChangeFinder(opts) {
5502
6548
  summary: hit.description
5503
6549
  }
5504
6550
  });
6551
+ if (filter.match === null) {
6552
+ result.droppedEnrichment++;
6553
+ continue;
6554
+ }
5505
6555
  if (!filter.match) {
5506
6556
  result.droppedIcp++;
5507
6557
  ledger.enqueueTarget({
5508
- playName: PLAY_NAME$4,
6558
+ playName: PLAY_NAME$6,
5509
6559
  payload: {
5510
6560
  title: hit.title,
5511
6561
  url: hit.url,
5512
6562
  description: hit.description
5513
6563
  },
5514
6564
  dedupeKey: hit.url,
5515
- source: SOURCE$4,
6565
+ source: SOURCE$5,
5516
6566
  initialStatus: "rejected",
5517
6567
  notes: `auto: ICP — ${filter.reason}`
5518
6568
  });
@@ -5552,44 +6602,25 @@ async function runJobChangeFinder(opts) {
5552
6602
  result.droppedEnrichment++;
5553
6603
  continue;
5554
6604
  }
5555
- const skip = shouldSkipFindEmail({
6605
+ const contact = await resolveAndVerifyContact({
6606
+ playName: PLAY_NAME$6,
5556
6607
  fullName: extract.fullName,
5557
- companyDomain: domain
6608
+ companyDomain: domain,
6609
+ isDuplicate: (email) => isDuplicate({
6610
+ playName: PLAY_NAME$6,
6611
+ dedupeKey: hit.url,
6612
+ prospectEmail: email
6613
+ })
5558
6614
  });
5559
- if (!skip.ok) {
5560
- result.droppedEnrichment++;
5561
- logEvent("finder.skipped_findemail", {
5562
- name: PLAY_NAME$4,
5563
- reason: skip.reason
5564
- }, "info");
5565
- continue;
5566
- }
5567
- const found = await findEmail({
5568
- fullName: extract.fullName,
5569
- companyDomain: domain
5570
- }, { playName: PLAY_NAME$4 });
5571
- result.costUsd += found.result.cost ?? 0;
5572
- if (!found.result.found || !found.result.email) {
5573
- result.droppedEnrichment++;
5574
- continue;
5575
- }
5576
- const email = found.result.email;
5577
- if (isDuplicate({
5578
- playName: PLAY_NAME$4,
5579
- dedupeKey: hit.url,
5580
- prospectEmail: email
5581
- })) {
5582
- result.droppedDuplicate++;
5583
- continue;
5584
- }
5585
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$4 });
5586
- result.costUsd += verified.result.cost ?? 0;
5587
- if (!verified.result.deliverable) {
5588
- result.droppedEnrichment++;
6615
+ result.costUsd += contact.costUsd;
6616
+ if (!contact.ok) {
6617
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6618
+ else result.droppedEnrichment++;
5589
6619
  continue;
5590
6620
  }
6621
+ const email = contact.email;
5591
6622
  const enr = await enrichVerifiedContact(email, {
5592
- playName: PLAY_NAME$4,
6623
+ playName: PLAY_NAME$6,
5593
6624
  errKindPrefix: "job-change"
5594
6625
  });
5595
6626
  result.costUsd += enr.costUsd;
@@ -5615,10 +6646,10 @@ async function runJobChangeFinder(opts) {
5615
6646
  ...phone ? { phone } : {}
5616
6647
  };
5617
6648
  if (ledger.enqueueTarget({
5618
- playName: PLAY_NAME$4,
6649
+ playName: PLAY_NAME$6,
5619
6650
  payload: target,
5620
6651
  dedupeKey: hit.url,
5621
- source: SOURCE$4,
6652
+ source: SOURCE$5,
5622
6653
  notes: `${extract.fullName} → ${extract.newRole} @ ${extract.newCompany} — ${filter.reason}`
5623
6654
  }) != null) result.enqueued++;
5624
6655
  else result.droppedDuplicate++;
@@ -5640,8 +6671,8 @@ function parseJobChangeExtract(raw) {
5640
6671
  }
5641
6672
  //#endregion
5642
6673
  //#region ../../packages/find/src/hiring-signal.ts
5643
- const PLAY_NAME$3 = "hiring-signal";
5644
- const SOURCE$3 = "find:hiring-signal";
6674
+ const PLAY_NAME$5 = "hiring-signal";
6675
+ const SOURCE$4 = "find:hiring-signal";
5645
6676
  const ATS_DOMAIN_HINTS = [
5646
6677
  "boards.greenhouse.io",
5647
6678
  "jobs.lever.co",
@@ -5663,7 +6694,7 @@ async function runHiringSignalFinder(opts) {
5663
6694
  const roles = opts.roles && opts.roles.length > 0 ? opts.roles : DEFAULT_ROLES;
5664
6695
  const yourClaim = (opts.yourClaim ?? "").trim();
5665
6696
  const result = {
5666
- source: SOURCE$3,
6697
+ source: SOURCE$4,
5667
6698
  candidates: 0,
5668
6699
  droppedIcp: 0,
5669
6700
  droppedDuplicate: 0,
@@ -5686,7 +6717,7 @@ async function runHiringSignalFinder(opts) {
5686
6717
  const search = await webSearch({
5687
6718
  query,
5688
6719
  maxResults: Math.min(15, limit)
5689
- }, { playName: PLAY_NAME$3 });
6720
+ }, { playName: PLAY_NAME$5 });
5690
6721
  result.costUsd += search.result.cost ?? 0;
5691
6722
  for (const hit of search.result.results ?? []) {
5692
6723
  if (!hit.url || seen.has(hit.url) || !isAtsUrl(hit.url)) continue;
@@ -5712,7 +6743,7 @@ async function runHiringSignalFinder(opts) {
5712
6743
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
5713
6744
  break;
5714
6745
  }
5715
- if (ledger.isQueueDuplicate(PLAY_NAME$3, hit.url)) {
6746
+ if (ledger.isQueueDuplicate(PLAY_NAME$5, hit.url)) {
5716
6747
  result.droppedDuplicate++;
5717
6748
  continue;
5718
6749
  }
@@ -5728,17 +6759,21 @@ async function runHiringSignalFinder(opts) {
5728
6759
  summary: hit.description
5729
6760
  }
5730
6761
  });
6762
+ if (filter.match === null) {
6763
+ result.droppedEnrichment++;
6764
+ continue;
6765
+ }
5731
6766
  if (!filter.match) {
5732
6767
  result.droppedIcp++;
5733
6768
  ledger.enqueueTarget({
5734
- playName: PLAY_NAME$3,
6769
+ playName: PLAY_NAME$5,
5735
6770
  payload: {
5736
6771
  title: hit.title,
5737
6772
  url: hit.url,
5738
6773
  description: hit.description
5739
6774
  },
5740
6775
  dedupeKey: hit.url,
5741
- source: SOURCE$3,
6776
+ source: SOURCE$4,
5742
6777
  initialStatus: "rejected",
5743
6778
  notes: `auto: ICP — ${filter.reason}`
5744
6779
  });
@@ -5746,7 +6781,7 @@ async function runHiringSignalFinder(opts) {
5746
6781
  }
5747
6782
  let extract;
5748
6783
  try {
5749
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$3 });
6784
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$5 });
5750
6785
  result.costUsd += read.result.cost ?? 0;
5751
6786
  extract = parseHiringSignalExtract((await complete({
5752
6787
  messages: [{
@@ -5784,46 +6819,26 @@ async function runHiringSignalFinder(opts) {
5784
6819
  result.droppedEnrichment++;
5785
6820
  continue;
5786
6821
  }
5787
- const managerName = extract.hiringManagerName && extract.hiringManagerName.length > 0 ? extract.hiringManagerName : null;
5788
- const skip = shouldSkipFindEmail({
5789
- fullName: managerName,
5790
- 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
+ })
5791
6831
  });
5792
- if (!skip.ok) {
5793
- result.droppedEnrichment++;
5794
- logEvent("finder.skipped_findemail", {
5795
- name: PLAY_NAME$3,
5796
- reason: skip.reason
5797
- }, "info");
6832
+ result.costUsd += contact.costUsd;
6833
+ if (!contact.ok) {
6834
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
6835
+ else result.droppedEnrichment++;
5798
6836
  continue;
5799
6837
  }
5800
- const found = await findEmail(managerName ? {
5801
- fullName: managerName,
5802
- companyDomain: domain
5803
- } : { companyDomain: domain }, { playName: PLAY_NAME$3 });
5804
- result.costUsd += found.result.cost ?? 0;
5805
- if (!found.result.found || !found.result.email) {
5806
- result.droppedEnrichment++;
5807
- continue;
5808
- }
5809
- const email = found.result.email;
5810
- if (isDuplicate({
5811
- playName: PLAY_NAME$3,
5812
- dedupeKey: hit.url,
5813
- prospectEmail: email
5814
- })) {
5815
- result.droppedDuplicate++;
5816
- continue;
5817
- }
5818
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$3 });
5819
- result.costUsd += verified.result.cost ?? 0;
5820
- if (!verified.result.deliverable) {
5821
- result.droppedEnrichment++;
5822
- continue;
5823
- }
5824
- const recipientName = extract.hiringManagerName ?? found.result.full_name ?? null;
6838
+ const email = contact.email;
6839
+ const recipientName = extract.hiringManagerName ?? contact.fullName;
5825
6840
  const enr = await enrichVerifiedContact(email, {
5826
- playName: PLAY_NAME$3,
6841
+ playName: PLAY_NAME$5,
5827
6842
  errKindPrefix: "hiring-signal"
5828
6843
  });
5829
6844
  result.costUsd += enr.costUsd;
@@ -5849,10 +6864,10 @@ async function runHiringSignalFinder(opts) {
5849
6864
  ...phone ? { phone } : {}
5850
6865
  };
5851
6866
  if (ledger.enqueueTarget({
5852
- playName: PLAY_NAME$3,
6867
+ playName: PLAY_NAME$5,
5853
6868
  payload: target,
5854
6869
  dedupeKey: hit.url,
5855
- source: SOURCE$3,
6870
+ source: SOURCE$4,
5856
6871
  notes: `${extract.company} hiring "${extract.jobTitle}"${extract.team ? ` (${extract.team})` : ""} — ${filter.reason}`
5857
6872
  }) != null) result.enqueued++;
5858
6873
  else result.droppedDuplicate++;
@@ -5902,7 +6917,7 @@ async function resolveCorporateDomain(company, jobUrl, cache) {
5902
6917
  const search = await webSearch({
5903
6918
  query: `"${company}" official site`,
5904
6919
  maxResults: 5
5905
- }, { playName: PLAY_NAME$3 });
6920
+ }, { playName: PLAY_NAME$5 });
5906
6921
  costUsd += search.result.cost ?? 0;
5907
6922
  for (const hit of search.result.results ?? []) {
5908
6923
  const host = pickCorporateHost(hit.url);
@@ -5954,8 +6969,8 @@ function parseHiringSignalExtract(raw) {
5954
6969
  }
5955
6970
  //#endregion
5956
6971
  //#region ../../packages/find/src/podcast-guest.ts
5957
- const PLAY_NAME$2 = "podcast-guest";
5958
- const SOURCE$2 = "find:podcast-guest";
6972
+ const PLAY_NAME$4 = "podcast-guest";
6973
+ const SOURCE$3 = "find:podcast-guest";
5959
6974
  const DEFAULT_PODCASTS = [
5960
6975
  "Latent Space",
5961
6976
  "Lenny's Podcast",
@@ -5971,7 +6986,7 @@ async function runPodcastGuestFinder(opts) {
5971
6986
  const system = loadPrompt("podcast-guest-extract");
5972
6987
  const podcasts = opts.podcasts && opts.podcasts.length > 0 ? opts.podcasts : DEFAULT_PODCASTS;
5973
6988
  const result = {
5974
- source: SOURCE$2,
6989
+ source: SOURCE$3,
5975
6990
  candidates: 0,
5976
6991
  droppedIcp: 0,
5977
6992
  droppedDuplicate: 0,
@@ -5989,7 +7004,7 @@ async function runPodcastGuestFinder(opts) {
5989
7004
  const search = await webSearch({
5990
7005
  query,
5991
7006
  maxResults: Math.min(15, limit)
5992
- }, { playName: PLAY_NAME$2 });
7007
+ }, { playName: PLAY_NAME$4 });
5993
7008
  result.costUsd += search.result.cost ?? 0;
5994
7009
  for (const hit of search.result.results ?? []) {
5995
7010
  if (!hit.url || seen.has(hit.url)) continue;
@@ -6015,7 +7030,7 @@ async function runPodcastGuestFinder(opts) {
6015
7030
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
6016
7031
  break;
6017
7032
  }
6018
- if (ledger.isQueueDuplicate(PLAY_NAME$2, hit.url)) {
7033
+ if (ledger.isQueueDuplicate(PLAY_NAME$4, hit.url)) {
6019
7034
  result.droppedDuplicate++;
6020
7035
  continue;
6021
7036
  }
@@ -6031,17 +7046,21 @@ async function runPodcastGuestFinder(opts) {
6031
7046
  summary: hit.description
6032
7047
  }
6033
7048
  });
7049
+ if (filter.match === null) {
7050
+ result.droppedEnrichment++;
7051
+ continue;
7052
+ }
6034
7053
  if (!filter.match) {
6035
7054
  result.droppedIcp++;
6036
7055
  ledger.enqueueTarget({
6037
- playName: PLAY_NAME$2,
7056
+ playName: PLAY_NAME$4,
6038
7057
  payload: {
6039
7058
  title: hit.title,
6040
7059
  url: hit.url,
6041
7060
  description: hit.description
6042
7061
  },
6043
7062
  dedupeKey: hit.url,
6044
- source: SOURCE$2,
7063
+ source: SOURCE$3,
6045
7064
  initialStatus: "rejected",
6046
7065
  notes: `auto: ICP — ${filter.reason}`
6047
7066
  });
@@ -6055,7 +7074,7 @@ async function runPodcastGuestFinder(opts) {
6055
7074
  description: hit.description
6056
7075
  };
6057
7076
  if (!opts.skipRead) {
6058
- const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$2 });
7077
+ const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$4 });
6059
7078
  result.costUsd += read.result.cost ?? 0;
6060
7079
  payload = {
6061
7080
  ...payload,
@@ -6085,44 +7104,25 @@ async function runPodcastGuestFinder(opts) {
6085
7104
  result.droppedEnrichment++;
6086
7105
  continue;
6087
7106
  }
6088
- const skip = shouldSkipFindEmail({
7107
+ const contact = await resolveAndVerifyContact({
7108
+ playName: PLAY_NAME$4,
6089
7109
  fullName: extract.guestName,
6090
- companyDomain: extract.guestCompanyDomain
7110
+ companyDomain: extract.guestCompanyDomain,
7111
+ isDuplicate: (email) => isDuplicate({
7112
+ playName: PLAY_NAME$4,
7113
+ dedupeKey: hit.url,
7114
+ prospectEmail: email
7115
+ })
6091
7116
  });
6092
- if (!skip.ok) {
6093
- result.droppedEnrichment++;
6094
- logEvent("finder.skipped_findemail", {
6095
- name: PLAY_NAME$2,
6096
- reason: skip.reason
6097
- }, "info");
6098
- continue;
6099
- }
6100
- const found = await findEmail({
6101
- fullName: extract.guestName,
6102
- companyDomain: extract.guestCompanyDomain
6103
- }, { playName: PLAY_NAME$2 });
6104
- result.costUsd += found.result.cost ?? 0;
6105
- if (!found.result.found || !found.result.email) {
6106
- result.droppedEnrichment++;
6107
- continue;
6108
- }
6109
- const email = found.result.email;
6110
- if (isDuplicate({
6111
- playName: PLAY_NAME$2,
6112
- dedupeKey: hit.url,
6113
- prospectEmail: email
6114
- })) {
6115
- result.droppedDuplicate++;
6116
- continue;
6117
- }
6118
- const verified = await verifyEmail({ email }, { playName: PLAY_NAME$2 });
6119
- result.costUsd += verified.result.cost ?? 0;
6120
- if (!verified.result.deliverable) {
6121
- result.droppedEnrichment++;
7117
+ result.costUsd += contact.costUsd;
7118
+ if (!contact.ok) {
7119
+ if (contact.reason === "duplicate") result.droppedDuplicate++;
7120
+ else result.droppedEnrichment++;
6122
7121
  continue;
6123
7122
  }
7123
+ const email = contact.email;
6124
7124
  const enr = await enrichVerifiedContact(email, {
6125
- playName: PLAY_NAME$2,
7125
+ playName: PLAY_NAME$4,
6126
7126
  errKindPrefix: "podcast-guest"
6127
7127
  });
6128
7128
  result.costUsd += enr.costUsd;
@@ -6148,10 +7148,10 @@ async function runPodcastGuestFinder(opts) {
6148
7148
  ...phone ? { phone } : {}
6149
7149
  };
6150
7150
  if (ledger.enqueueTarget({
6151
- playName: PLAY_NAME$2,
7151
+ playName: PLAY_NAME$4,
6152
7152
  payload: target,
6153
7153
  dedupeKey: hit.url,
6154
- source: SOURCE$2,
7154
+ source: SOURCE$3,
6155
7155
  notes: `${extract.guestName} on ${extract.podcastName} — ${filter.reason}`
6156
7156
  }) != null) result.enqueued++;
6157
7157
  else result.droppedDuplicate++;
@@ -6175,8 +7175,8 @@ function parsePodcastGuestExtract(raw) {
6175
7175
  }
6176
7176
  //#endregion
6177
7177
  //#region ../../packages/find/src/breakup-revive.ts
6178
- const PLAY_NAME$1 = "breakup-revive";
6179
- const SOURCE$1 = "find:breakup-revive";
7178
+ const PLAY_NAME$3 = "breakup-revive";
7179
+ const SOURCE$2 = "find:breakup-revive";
6180
7180
  /**
6181
7181
  * Scan the local ledger for cold prospects (no activity in the last
6182
7182
  * min/maxDays window) and enqueue them into target_queue. No LLM calls,
@@ -6189,7 +7189,7 @@ function runBreakupReviveFinder(opts) {
6189
7189
  const maxDays = opts.maxDays ?? 90;
6190
7190
  const ledger = getLedger();
6191
7191
  const result = {
6192
- source: SOURCE$1,
7192
+ source: SOURCE$2,
6193
7193
  candidates: 0,
6194
7194
  droppedIcp: 0,
6195
7195
  droppedDuplicate: 0,
@@ -6211,7 +7211,7 @@ function runBreakupReviveFinder(opts) {
6211
7211
  }
6212
7212
  const dedupeKey = `prospect:${p.id}`;
6213
7213
  if (isDuplicate({
6214
- playName: PLAY_NAME$1,
7214
+ playName: PLAY_NAME$3,
6215
7215
  dedupeKey,
6216
7216
  prospectEmail: void 0
6217
7217
  })) {
@@ -6233,10 +7233,10 @@ function runBreakupReviveFinder(opts) {
6233
7233
  continue;
6234
7234
  }
6235
7235
  const id = ledger.enqueueTarget({
6236
- playName: PLAY_NAME$1,
7236
+ playName: PLAY_NAME$3,
6237
7237
  payload: target,
6238
7238
  dedupeKey,
6239
- source: SOURCE$1,
7239
+ source: SOURCE$2,
6240
7240
  notes: `${daysCold}d cold${p.company ? ` — ${p.company}` : ""}`
6241
7241
  });
6242
7242
  if (id != null) {
@@ -6423,6 +7423,100 @@ async function fetchGitHubUser(login) {
6423
7423
  }
6424
7424
  }
6425
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
+ /**
6426
7520
  * Normalize a profile `blog` field to a bare hostname.
6427
7521
  *
6428
7522
  * GitHub stores whatever the user typed, so this needs to handle:
@@ -6669,7 +7763,7 @@ function parseEnvKeys(content) {
6669
7763
  * directly from package.json / pyproject.toml / requirements.txt /
6670
7764
  * .env.example via the GitHub Contents API. Free, fast, deterministic.
6671
7765
  */
6672
- const PLAY_NAME = "stack-consolidation";
7766
+ const PLAY_NAME$2 = "stack-consolidation";
6673
7767
  /**
6674
7768
  * Process a single candidate through the full pipeline. Mutates ctx.result.
6675
7769
  * Never throws — internal exceptions become droppedEnrichment increments via
@@ -6708,10 +7802,14 @@ async function processRepoCandidate(hit, ctx) {
6708
7802
  summary: describeForIcp(hit)
6709
7803
  }
6710
7804
  });
7805
+ if (snippetFilter.match === null) {
7806
+ result.droppedEnrichment++;
7807
+ return;
7808
+ }
6711
7809
  if (!snippetFilter.match) {
6712
7810
  result.droppedIcp++;
6713
7811
  ledger.enqueueTarget({
6714
- playName: PLAY_NAME,
7812
+ playName: PLAY_NAME$2,
6715
7813
  payload: {
6716
7814
  repoUrl: hit.url,
6717
7815
  title: hit.title,
@@ -6859,7 +7957,7 @@ async function processRepoCandidate(hit, ctx) {
6859
7957
  async function resolveContact(args) {
6860
7958
  const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;
6861
7959
  const errKindPrefix = args.errKindPrefix ?? "repo-pipeline";
6862
- const playName = args.playName ?? PLAY_NAME;
7960
+ const playName = args.playName ?? PLAY_NAME$2;
6863
7961
  const extractDomain = extract.companyDomain ?? extract.personalDomain ?? null;
6864
7962
  let discoveredLinkedinUrl = null;
6865
7963
  if (extractDomain) {
@@ -6895,6 +7993,9 @@ async function resolveContact(args) {
6895
7993
  accumCost(enriched.result.cost ?? 0);
6896
7994
  const profile = enriched.result.profile;
6897
7995
  const enrichedPhone = extractFirstPhone(profile);
7996
+ if (profile?.email) try {
7997
+ getLedger().setCachedEnrichment(profile.email.trim().toLowerCase(), JSON.stringify(enriched.result));
7998
+ } catch {}
6898
7999
  if (profile?.email) return {
6899
8000
  email: profile.email,
6900
8001
  fullName: profile.full_name ?? extract.authorFullName,
@@ -7116,7 +8217,7 @@ function normalizeRepoUrl(url) {
7116
8217
  * misleading issue/PR snippets that judged the parent repo on text it didn't
7117
8218
  * own. And discovery is free (no webSearch spend per query).
7118
8219
  */
7119
- const SOURCE = "find:github-topics";
8220
+ const SOURCE$1 = "find:github-topics";
7120
8221
  async function runGitHubTopicsFinder(opts) {
7121
8222
  const limit = opts.limit ?? 25;
7122
8223
  const minStars = Math.max(0, opts.minStars ?? 5);
@@ -7126,7 +8227,7 @@ async function runGitHubTopicsFinder(opts) {
7126
8227
  const useDeepResearch = opts.useDeepResearch !== false;
7127
8228
  const icp = resolveIcp(opts.icpOverride);
7128
8229
  const result = {
7129
- source: SOURCE,
8230
+ source: SOURCE$1,
7130
8231
  candidates: 0,
7131
8232
  droppedIcp: 0,
7132
8233
  droppedDuplicate: 0,
@@ -7146,50 +8247,941 @@ async function runGitHubTopicsFinder(opts) {
7146
8247
  result.halted = "unconfigured: set `yourEdge` in /queue → github-topics → edit config";
7147
8248
  return result;
7148
8249
  }
7149
- const pushedSinceIso = isoDateNDaysAgo(maxAgeDays);
7150
- const seen = /* @__PURE__ */ new Set();
7151
- const hits = [];
7152
- for (const topic of opts.topics) {
7153
- if (hits.length >= limit * 2) break;
7154
- const repos = await searchTopicRepos({
7155
- topic,
7156
- minStars,
7157
- pushedSinceIso,
7158
- perPage: 50
8250
+ const pushedSinceIso = isoDateNDaysAgo(maxAgeDays);
8251
+ const seen = /* @__PURE__ */ new Set();
8252
+ const hits = [];
8253
+ for (const topic of opts.topics) {
8254
+ if (hits.length >= limit * 2) break;
8255
+ const repos = await searchTopicRepos({
8256
+ topic,
8257
+ minStars,
8258
+ pushedSinceIso,
8259
+ perPage: 50
8260
+ });
8261
+ for (const repo of repos) {
8262
+ const url = normalizeRepoUrl(repo.url);
8263
+ if (!url || seen.has(url)) continue;
8264
+ if (looksLikeNoiseRepo(url)) continue;
8265
+ seen.add(url);
8266
+ hits.push({
8267
+ url,
8268
+ title: repo.fullName,
8269
+ description: repo.description ?? "",
8270
+ vendors: [],
8271
+ topics: repo.topics
8272
+ });
8273
+ }
8274
+ }
8275
+ result.candidates = hits.length;
8276
+ const ctx = {
8277
+ icp,
8278
+ vocab: opts.vendors,
8279
+ directCompetitors: opts.directCompetitors ?? [],
8280
+ yourEdge: opts.yourEdge,
8281
+ minVendors,
8282
+ useDeepResearch,
8283
+ result,
8284
+ halted: { value: false },
8285
+ limit,
8286
+ maxCostUsd: opts.maxCostUsd,
8287
+ sourceTag: SOURCE$1,
8288
+ notesPrefix: "github-topic",
8289
+ dryRun: opts.dryRun
8290
+ };
8291
+ await parallelMap(hits, concurrency, (hit) => processRepoCandidate(hit, ctx));
8292
+ return result;
8293
+ }
8294
+ //#endregion
8295
+ //#region ../../packages/find/src/_stargazers.ts
8296
+ /** Parse one `application/vnd.github.star+json` stargazer row. */
8297
+ function parseStarRow(raw) {
8298
+ if (!raw || typeof raw !== "object") return null;
8299
+ const r = raw;
8300
+ const starredAt = typeof r["starred_at"] === "string" ? r["starred_at"] : null;
8301
+ const user = r["user"];
8302
+ if (!starredAt || !user || typeof user !== "object") return null;
8303
+ const u = user;
8304
+ const login = typeof u["login"] === "string" ? u["login"] : null;
8305
+ if (!login) return null;
8306
+ return {
8307
+ login,
8308
+ userUrl: (typeof u["html_url"] === "string" ? u["html_url"] : null) ?? `https://github.com/${login}`,
8309
+ starredAt
8310
+ };
8311
+ }
8312
+ /** Read the `page=N>; rel="last"` page number from a GitHub `Link` header. */
8313
+ function parseLastPage(link) {
8314
+ if (!link) return 1;
8315
+ const m = link.match(/[?&]page=(\d+)>;\s*rel="last"/);
8316
+ return m ? Math.max(1, Number.parseInt(m[1] ?? "1", 10)) : 1;
8317
+ }
8318
+ /**
8319
+ * Recent stargazers of a public repo. GitHub returns stargazers oldest-first,
8320
+ * so the newest stars live on the LAST page — we read the `Link: rel="last"`
8321
+ * page number, then page backward (newest → older), collecting stars with
8322
+ * `starredAt >= sinceIso` and stopping as soon as a page has none fresh (every
8323
+ * earlier page is older still) or `maxPages` is hit. Fault-tolerant like
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".
8328
+ *
8329
+ * Requires `GITHUB_TOKEN` for any real volume (5,000 req/hr core); without it
8330
+ * GitHub rate-limits hard at 60/hr — which a backward walk through a big repo
8331
+ * hits fast.
8332
+ */
8333
+ async function recentStargazers(repo, opts) {
8334
+ const maxPages = Math.max(1, opts.maxPages ?? 20);
8335
+ const headers = {
8336
+ ...githubHeaders(),
8337
+ Accept: "application/vnd.github.star+json"
8338
+ };
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
+ };
8351
+ try {
8352
+ const firstRes = await fetch(`${base}&page=1`, { headers });
8353
+ if (!firstRes.ok) {
8354
+ logEvent("github.stargazers", {
8355
+ repo,
8356
+ ok: false,
8357
+ status: firstRes.status
8358
+ }, "warn");
8359
+ return {
8360
+ stargazers: [],
8361
+ newestSeen: null,
8362
+ error: `status ${firstRes.status}`
8363
+ };
8364
+ }
8365
+ const lastPage = parseLastPage(firstRes.headers.get("link"));
8366
+ const page1Rows = await firstRes.json() ?? [];
8367
+ let pagesFetched = 1;
8368
+ for (let page = lastPage; page >= 1 && pagesFetched <= maxPages; page--) {
8369
+ let rows;
8370
+ if (page === 1) rows = page1Rows;
8371
+ else {
8372
+ const res = await fetch(`${base}&page=${page}`, { headers });
8373
+ pagesFetched++;
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
+ }
8387
+ rows = await res.json() ?? [];
8388
+ }
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;
8394
+ }
8395
+ const stargazers = dedupe();
8396
+ logEvent("github.stargazers", {
8397
+ repo,
8398
+ ok: true,
8399
+ fresh: stargazers.length,
8400
+ last_page: lastPage,
8401
+ pages_fetched: pagesFetched
8402
+ });
8403
+ return {
8404
+ stargazers,
8405
+ newestSeen
8406
+ };
8407
+ } catch (err) {
8408
+ const message = (err.message ?? "").slice(0, 120);
8409
+ logEvent("github.stargazers", {
8410
+ repo,
8411
+ ok: false,
8412
+ message_120: message
8413
+ }, "warn");
8414
+ return {
8415
+ stargazers: dedupe(),
8416
+ newestSeen,
8417
+ error: message
8418
+ };
8419
+ }
8420
+ }
8421
+ //#endregion
8422
+ //#region ../../packages/find/src/github-stars.ts
8423
+ const PLAY_NAME$1 = "github-stars";
8424
+ function deriveLabel(repo) {
8425
+ return repo.split("/")[1]?.trim() || repo;
8426
+ }
8427
+ function sourceFor(repo) {
8428
+ return `find:${PLAY_NAME$1}:${repo}`;
8429
+ }
8430
+ /**
8431
+ * github-stars finder: recent stargazers of watched repos → prospects, routed
8432
+ * by each repo's founder-tagged `rel`. A `competitor` repo's stargazers become
8433
+ * `competitor-switch` rows ("why teams switch from X"); an `adjacent` repo's
8434
+ * become `repo-interest` rows ("you're into X — my product helps"). Reuses the
8435
+ * shared finder stack (ICP filter, findEmail/verify/enrich, dedupe, prescreen)
8436
+ * and the soft-cap loop pattern from show-hn / accelerator-batch.
8437
+ */
8438
+ async function runGitHubStarsFinder(opts) {
8439
+ const limit = opts.limit ?? 25;
8440
+ const concurrency = Math.max(1, opts.concurrency ?? 3);
8441
+ const sinceDays = opts.sinceDays ?? 30;
8442
+ const sinceIso = (/* @__PURE__ */ new Date(Date.now() - sinceDays * 24 * 3600 * 1e3)).toISOString();
8443
+ const icp = resolveIcp(opts.icpOverride);
8444
+ const ledger = getLedger();
8445
+ const result = {
8446
+ source: `find:${PLAY_NAME$1}`,
8447
+ candidates: 0,
8448
+ droppedIcp: 0,
8449
+ droppedDuplicate: 0,
8450
+ droppedEnrichment: 0,
8451
+ enqueued: 0,
8452
+ costUsd: 0
8453
+ };
8454
+ logEvent("finder.start", {
8455
+ name: PLAY_NAME$1,
8456
+ repos: opts.repos.length,
8457
+ since_days: sinceDays,
8458
+ limit
8459
+ });
8460
+ const tagged = [];
8461
+ let firstError = null;
8462
+ let newestSeen = null;
8463
+ for (const w of opts.repos) {
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;
8467
+ const label = w.label?.trim() || deriveLabel(w.repo);
8468
+ const repoEdge = w.repoEdge?.trim();
8469
+ for (const s of stargazers) tagged.push({
8470
+ ...s,
8471
+ repo: w.repo,
8472
+ rel: w.rel,
8473
+ label,
8474
+ ...repoEdge ? { repoEdge } : {}
8475
+ });
8476
+ }
8477
+ const seen = /* @__PURE__ */ new Set();
8478
+ const candidates = tagged.filter((c) => {
8479
+ const k = c.login.toLowerCase();
8480
+ if (seen.has(k)) return false;
8481
+ seen.add(k);
8482
+ return true;
8483
+ });
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
+ });
9029
+ }
9030
+ }
9031
+ for (const work of attendeesWork) {
9032
+ if (result.enqueued >= limit) break;
9033
+ if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {
9034
+ result.halted = `max-cost cap (${opts.maxCostUsd})`;
9035
+ break;
9036
+ }
9037
+ const dedupeKey = `${work.event.url}#${work.attendee.name.toLowerCase()}`;
9038
+ if (ledger.isQueueDuplicate(PLAY_NAME, dedupeKey)) {
9039
+ result.droppedDuplicate++;
9040
+ continue;
9041
+ }
9042
+ if (opts.dryRun) {
9043
+ result.enqueued++;
9044
+ continue;
9045
+ }
9046
+ const filter = await icpFilter({
9047
+ icp,
9048
+ candidate: {
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 ?? ""}`
9052
+ }
7159
9053
  });
7160
- for (const repo of repos) {
7161
- const url = normalizeRepoUrl(repo.url);
7162
- if (!url || seen.has(url)) continue;
7163
- if (looksLikeNoiseRepo(url)) continue;
7164
- seen.add(url);
7165
- hits.push({
7166
- url,
7167
- title: repo.fullName,
7168
- description: repo.description ?? "",
7169
- vendors: [],
7170
- topics: repo.topics
9054
+ if (filter.match === null) {
9055
+ result.droppedEnrichment++;
9056
+ continue;
9057
+ }
9058
+ if (!filter.match) {
9059
+ result.droppedIcp++;
9060
+ ledger.enqueueTarget({
9061
+ playName: PLAY_NAME,
9062
+ payload: {
9063
+ ...work.attendee,
9064
+ event: work.event
9065
+ },
9066
+ dedupeKey,
9067
+ source: SOURCE,
9068
+ initialStatus: "rejected",
9069
+ notes: `auto: ICP — ${filter.reason}`
9070
+ });
9071
+ continue;
9072
+ }
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
+ }
7171
9087
  });
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");
9101
+ }
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;
7172
9130
  }
9131
+ const email = contact.email;
9132
+ const enr = await enrichVerifiedContact(email, {
9133
+ playName: PLAY_NAME,
9134
+ errKindPrefix: "luma-events"
9135
+ });
9136
+ result.costUsd += enr.costUsd;
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,
9149
+ email,
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 } : {}
9159
+ };
9160
+ if (ledger.enqueueTarget({
9161
+ playName: PLAY_NAME,
9162
+ payload: target,
9163
+ dedupeKey,
9164
+ source: SOURCE,
9165
+ notes: `${work.attendee.name} going to ${work.event.title} — ${filter.reason}`
9166
+ }) != null) result.enqueued++;
9167
+ else result.droppedDuplicate++;
7173
9168
  }
7174
- result.candidates = hits.length;
7175
- const ctx = {
7176
- icp,
7177
- vocab: opts.vendors,
7178
- directCompetitors: opts.directCompetitors ?? [],
7179
- yourEdge: opts.yourEdge,
7180
- minVendors,
7181
- useDeepResearch,
7182
- result,
7183
- halted: { value: false },
7184
- limit,
7185
- maxCostUsd: opts.maxCostUsd,
7186
- sourceTag: SOURCE,
7187
- notesPrefix: "github-topic",
7188
- dryRun: opts.dryRun
7189
- };
7190
- await parallelMap(hits, concurrency, (hit) => processRepoCandidate(hit, ctx));
7191
9169
  return result;
7192
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
+ }
7193
9185
  //#endregion
7194
9186
  //#region ../../packages/find/src/registry.ts
7195
9187
  /** Evaluate a spec's readiness fn (defaulting to ready when absent). */
@@ -7434,6 +9426,47 @@ const TRIGGERS = [
7434
9426
  maxCostUsd: cfg["maxCostUsd"] ?? 5
7435
9427
  })
7436
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
+ },
7437
9470
  {
7438
9471
  name: "github-topics",
7439
9472
  defaultIntervalMs: 12 * ONE_HOUR,
@@ -7487,6 +9520,62 @@ const TRIGGERS = [
7487
9520
  });
7488
9521
  }
7489
9522
  },
9523
+ {
9524
+ name: "github-stars",
9525
+ defaultIntervalMs: 12 * ONE_HOUR,
9526
+ enabledByDefault: false,
9527
+ defaultConfig: {
9528
+ repos: [],
9529
+ yourEdge: "",
9530
+ sinceDays: 30,
9531
+ concurrency: 3,
9532
+ limit: 25,
9533
+ maxCostUsd: 5
9534
+ },
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.",
9536
+ readiness: (cfg) => {
9537
+ if ((Array.isArray(cfg["repos"]) ? cfg["repos"] : []).filter((r) => {
9538
+ if (!r || typeof r !== "object") return false;
9539
+ const e = r;
9540
+ return typeof e["repo"] === "string" && e["repo"].trim().length > 0 && (e["rel"] === "competitor" || e["rel"] === "adjacent");
9541
+ }).length === 0) return {
9542
+ ready: false,
9543
+ reason: "set `repos` (each `{repo, rel:'competitor'|'adjacent'}`)"
9544
+ };
9545
+ const edge = cfg["yourEdge"];
9546
+ if (typeof edge !== "string" || edge.trim().length === 0) return {
9547
+ ready: false,
9548
+ reason: "set `yourEdge` — your one-line pitch"
9549
+ };
9550
+ return { ready: true };
9551
+ },
9552
+ run: (cfg) => {
9553
+ return runGitHubStarsFinder({
9554
+ dryRun: false,
9555
+ repos: (Array.isArray(cfg["repos"]) ? cfg["repos"] : []).map((r) => {
9556
+ if (!r || typeof r !== "object") return null;
9557
+ const e = r;
9558
+ const repo = typeof e["repo"] === "string" ? e["repo"].trim() : "";
9559
+ const rel = e["rel"];
9560
+ if (repo.length === 0 || rel !== "competitor" && rel !== "adjacent") return null;
9561
+ const label = typeof e["label"] === "string" ? e["label"].trim() : "";
9562
+ const repoEdge = typeof e["repoEdge"] === "string" ? e["repoEdge"].trim() : "";
9563
+ const watch = {
9564
+ repo,
9565
+ rel
9566
+ };
9567
+ if (label) watch.label = label;
9568
+ if (repoEdge) watch.repoEdge = repoEdge;
9569
+ return watch;
9570
+ }).filter((r) => r !== null),
9571
+ yourEdge: typeof cfg["yourEdge"] === "string" ? cfg["yourEdge"] : "",
9572
+ sinceDays: cfg["sinceDays"] ?? 30,
9573
+ concurrency: cfg["concurrency"] ?? 3,
9574
+ limit: cfg["limit"] ?? 25,
9575
+ maxCostUsd: cfg["maxCostUsd"] ?? 5
9576
+ });
9577
+ }
9578
+ },
7490
9579
  {
7491
9580
  name: "breakup-revive",
7492
9581
  defaultIntervalMs: 168 * ONE_HOUR,
@@ -7496,7 +9585,7 @@ const TRIGGERS = [
7496
9585
  maxDays: 90,
7497
9586
  limit: 25
7498
9587
  },
7499
- 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.",
7500
9589
  run: async (cfg) => runBreakupReviveFinder({
7501
9590
  dryRun: false,
7502
9591
  minDays: cfg["minDays"] ?? 60,
@@ -8218,7 +10307,7 @@ async function runDoctor() {
8218
10307
  const pkSrc = secretSource("AGENT_PRIVATE_KEY");
8219
10308
  const walletSrc = process.env.AGENT_PRIVATE_KEY ? pkSrc : cdpSrc;
8220
10309
  results.push({
8221
- name: "oneshot wallet env",
10310
+ name: "wallet env",
8222
10311
  severity: oneshotEnvReady() ? "ok" : "fail",
8223
10312
  message: oneshotEnvReady() ? `${process.env.AGENT_PRIVATE_KEY ? "AGENT_PRIVATE_KEY" : "CDP wallet"} set (${walletSrc ?? "?"})` : "no wallet credentials",
8224
10313
  ...oneshotEnvReady() ? {} : { hint: "oneshot-gtm config keys" }
@@ -8281,15 +10370,22 @@ function toDraftedView(d) {
8281
10370
  * Dispatch a play by name and return one DraftedView per target (in order).
8282
10371
  * Shared by the SSE /api/run endpoint (multi-target) and the /queue
8283
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.
8284
10379
  */
8285
- async function dispatchPlay(playName, body) {
10380
+ async function dispatchPlay(playName, body, onProgress) {
8286
10381
  const play = PLAYS[playName];
8287
10382
  if (!play) throw new Error(`unsupported play: ${playName}`);
8288
10383
  return (await play.run({
8289
10384
  dryRun: body.dryRun,
8290
10385
  targets: body.targets,
8291
10386
  ...body.senderCohort ? { senderCohort: body.senderCohort } : {},
8292
- ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
10387
+ ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {},
10388
+ ...onProgress ? { onProgress: (index, draft) => onProgress(index, toDraftedView(draft)) } : {}
8293
10389
  })).drafted.map(toDraftedView);
8294
10390
  }
8295
10391
  //#endregion
@@ -8302,7 +10398,9 @@ const SUPPORTED = new Set([
8302
10398
  "hiring-signal",
8303
10399
  "podcast-guest",
8304
10400
  "competitor-switch",
8305
- "stack-consolidation"
10401
+ "stack-consolidation",
10402
+ "repo-interest",
10403
+ "luma-events"
8306
10404
  ]);
8307
10405
  async function runPlay(req, params) {
8308
10406
  const playName = params["playName"] ?? "";
@@ -8314,13 +10412,31 @@ async function runPlay(req, params) {
8314
10412
  return jsonResponse({ error: "invalid JSON body" }, 400, req);
8315
10413
  }
8316
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 = [];
8317
10421
  const stream = new ReadableStream({ async start(controller) {
8318
10422
  const encoder = new TextEncoder();
10423
+ const ledger = getLedger();
8319
10424
  const send = (event) => {
10425
+ try {
10426
+ ledger.appendRunEvent({
10427
+ runId,
10428
+ event
10429
+ });
10430
+ } catch {}
8320
10431
  try {
8321
10432
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
8322
10433
  } catch {}
8323
10434
  };
10435
+ send({
10436
+ kind: "runStarted",
10437
+ runId,
10438
+ startedAt
10439
+ });
8324
10440
  try {
8325
10441
  const emailToDedupeKey = /* @__PURE__ */ new Map();
8326
10442
  if (body.dedupeKeys && body.dedupeKeys.length === body.targets.length) body.targets.forEach((t, i) => {
@@ -8373,9 +10489,8 @@ async function runPlay(req, params) {
8373
10489
  kind: "stage",
8374
10490
  stage: body.dryRun ? "drafting" : "drafting + sending"
8375
10491
  });
8376
- const drafted = await dispatchPlay(playName, filteredBody);
8377
10492
  let sentCount = 0;
8378
- drafted.forEach((d, index) => {
10493
+ const drafted = await dispatchPlay(playName, filteredBody, (index, d) => {
8379
10494
  send({
8380
10495
  kind: "draft",
8381
10496
  index,
@@ -8388,7 +10503,12 @@ async function runPlay(req, params) {
8388
10503
  index,
8389
10504
  receiptIds: d.receiptIds
8390
10505
  });
8391
- 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
+ }
8392
10512
  });
8393
10513
  send({
8394
10514
  kind: "done",
@@ -8430,6 +10550,13 @@ async function runPlay(req, params) {
8430
10550
  message: uiMessage
8431
10551
  });
8432
10552
  } finally {
10553
+ try {
10554
+ getLedger().markRunComplete({
10555
+ runId,
10556
+ status: "done",
10557
+ sentEmails
10558
+ });
10559
+ } catch {}
8433
10560
  try {
8434
10561
  controller.close();
8435
10562
  } catch {}
@@ -8496,6 +10623,35 @@ function persistDraftsToQueue(input) {
8496
10623
  }
8497
10624
  }
8498
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
8499
10655
  //#region src/api/queue.ts
8500
10656
  function toView$1(row) {
8501
10657
  let payload = null;
@@ -8532,7 +10688,8 @@ function toView$1(row) {
8532
10688
  notes: row.notes,
8533
10689
  prospectId: row.prospect_id,
8534
10690
  lastDraft,
8535
- lastDraftedAt: row.last_drafted_at
10691
+ lastDraftedAt: row.last_drafted_at,
10692
+ isSending: row.send_started_at != null
8536
10693
  };
8537
10694
  }
8538
10695
  function listQueueRoute(req) {
@@ -8623,6 +10780,8 @@ async function regenerateDraftRoute(req, params) {
8623
10780
  const ledger = getLedger();
8624
10781
  const row = ledger.getQueueRow(id);
8625
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);
8626
10785
  let target;
8627
10786
  try {
8628
10787
  target = JSON.parse(row.payload_json);
@@ -8644,6 +10803,8 @@ async function regenerateDraftRoute(req, params) {
8644
10803
  }
8645
10804
  const draft = drafted[0];
8646
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);
8647
10808
  ledger.setQueueDraft({
8648
10809
  id,
8649
10810
  draft: {
@@ -8677,6 +10838,7 @@ async function regenerateDraftRoute(req, params) {
8677
10838
  async function sendDraftRoute(req, params) {
8678
10839
  const id = Number.parseInt(params["id"] ?? "", 10);
8679
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);
8680
10842
  const ledger = getLedger();
8681
10843
  const row = ledger.getQueueRow(id);
8682
10844
  if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);
@@ -8694,6 +10856,11 @@ async function sendDraftRoute(req, params) {
8694
10856
  if (!subject || !body) return jsonResponse({ error: "stored draft is empty — regenerate first" }, 400, req);
8695
10857
  if (flags.length > 0) return jsonResponse({ error: "draft has lint flags — regenerate to clear them before sending" }, 400, req);
8696
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);
8697
10864
  let payload = {};
8698
10865
  try {
8699
10866
  const p = JSON.parse(row.payload_json);
@@ -8702,6 +10869,7 @@ async function sendDraftRoute(req, params) {
8702
10869
  const str = (k) => typeof payload[k] === "string" ? payload[k] : null;
8703
10870
  const email = str("email") ?? str("founderEmail");
8704
10871
  if (!email) return jsonResponse({ error: "row has no recipient email" }, 400, req);
10872
+ const sendFlags = [];
8705
10873
  let result;
8706
10874
  try {
8707
10875
  result = await sendDraftedEmail({
@@ -8711,7 +10879,7 @@ async function sendDraftRoute(req, params) {
8711
10879
  subject,
8712
10880
  body
8713
10881
  },
8714
- flags: [],
10882
+ flags: sendFlags,
8715
10883
  prospectMeta: {
8716
10884
  name: str("name") ?? str("founderName"),
8717
10885
  email,
@@ -8723,9 +10891,31 @@ async function sendDraftRoute(req, params) {
8723
10891
  dryRun: false
8724
10892
  });
8725
10893
  } catch (err) {
10894
+ try {
10895
+ ledger.clearQueueSendingMarker(id);
10896
+ } catch {}
8726
10897
  return jsonResponse({ error: err.message ?? "send failed" }, 400, req);
8727
10898
  }
8728
- 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
+ }
8729
10919
  const prospect = ledger.findProspectByEmail(email);
8730
10920
  if (prospect) enrollInCadence({
8731
10921
  prospectId: prospect.id,
@@ -8928,6 +11118,7 @@ const routes = [
8928
11118
  route("POST", "/api/strategist/stream", strategistRoute),
8929
11119
  route("GET", "/api/doctor", doctor),
8930
11120
  route("POST", "/api/run/:playName", runPlay),
11121
+ route("GET", "/api/runs/:id", getRunRoute),
8931
11122
  route("GET", "/api/queue", listQueueRoute),
8932
11123
  route("POST", "/api/queue/approve-all", approveAllRoute),
8933
11124
  route("POST", "/api/queue/drain", drainQueueRoute),
@@ -9120,6 +11311,58 @@ if (cache.__oneshotGtmServer) {
9120
11311
  logEvent("trigger.sweep.failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
9121
11312
  process.stderr.write(` warn: stale-run sweep failed: ${err.message}\n`);
9122
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
+ }
9123
11366
  const { url, server } = await startServer({ port });
9124
11367
  cache.__oneshotGtmServer = server;
9125
11368
  let scheduler = null;
@@ -9134,14 +11377,34 @@ if (cache.__oneshotGtmServer) {
9134
11377
  if (!noBrowser) try {
9135
11378
  await open(url);
9136
11379
  } catch {}
9137
- const shutdown = () => {
9138
- 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();
9139
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");
9140
11403
  server.stop();
9141
11404
  process.exit(0);
9142
11405
  };
9143
- process.on("SIGINT", shutdown);
9144
- process.on("SIGTERM", shutdown);
11406
+ process.on("SIGINT", () => void shutdown("SIGINT"));
11407
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
9145
11408
  }
9146
11409
  //#endregion
9147
11410
  export {};