oneshot-gtm-server 0.1.0 → 0.2.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 (68) hide show
  1. package/dist/bin.mjs +2192 -433
  2. package/dist/bin.mjs.map +1 -1
  3. package/dist/web/assets/Badge-DE7L41a6.js +2 -0
  4. package/dist/web/assets/Badge-DE7L41a6.js.map +1 -0
  5. package/dist/web/assets/Button-NJ1UVzeB.js +2 -0
  6. package/dist/web/assets/Button-NJ1UVzeB.js.map +1 -0
  7. package/dist/web/assets/EmptyNote-DkmaZWuo.js +2 -0
  8. package/dist/web/assets/{EmptyNote-C4quX2dg.js.map → EmptyNote-DkmaZWuo.js.map} +1 -1
  9. package/dist/web/assets/Field-B4mT8TGa.js +2 -0
  10. package/dist/web/assets/Field-B4mT8TGa.js.map +1 -0
  11. package/dist/web/assets/{Modal-BVbdN0gj.js → Modal-frAt7msr.js} +2 -2
  12. package/dist/web/assets/{Modal-BVbdN0gj.js.map → Modal-frAt7msr.js.map} +1 -1
  13. package/dist/web/assets/Skeleton-d2p06ghN.js +2 -0
  14. package/dist/web/assets/{Skeleton-D7Z-VTMo.js.map → Skeleton-d2p06ghN.js.map} +1 -1
  15. package/dist/web/assets/cadences-CsU8vKw2.js +2 -0
  16. package/dist/web/assets/cadences-CsU8vKw2.js.map +1 -0
  17. package/dist/web/assets/chevron-right-BXb7J1cp.js +2 -0
  18. package/dist/web/assets/chevron-right-BXb7J1cp.js.map +1 -0
  19. package/dist/web/assets/inbox-Dzd9QYT4.js +2 -0
  20. package/dist/web/assets/inbox-Dzd9QYT4.js.map +1 -0
  21. package/dist/web/assets/index-ByTPAanr.css +2 -0
  22. package/dist/web/assets/index-CzTgATNQ.js +60 -0
  23. package/dist/web/assets/index-CzTgATNQ.js.map +1 -0
  24. package/dist/web/assets/loader-circle-BylpxA-u.js +2 -0
  25. package/dist/web/assets/loader-circle-BylpxA-u.js.map +1 -0
  26. package/dist/web/assets/{measure-DLFAK1ZQ.js → measure-S3BWSb2L.js} +2 -2
  27. package/dist/web/assets/{measure-DLFAK1ZQ.js.map → measure-S3BWSb2L.js.map} +1 -1
  28. package/dist/web/assets/plays-DHIZA49D.js +2 -0
  29. package/dist/web/assets/plays-DHIZA49D.js.map +1 -0
  30. package/dist/web/assets/queue-ClVxfeJ0.js +2 -0
  31. package/dist/web/assets/queue-ClVxfeJ0.js.map +1 -0
  32. package/dist/web/assets/receipts-BgXV3-De.js +2 -0
  33. package/dist/web/assets/receipts-BgXV3-De.js.map +1 -0
  34. package/dist/web/assets/refresh-cw-BpMRSA9y.js +2 -0
  35. package/dist/web/assets/refresh-cw-BpMRSA9y.js.map +1 -0
  36. package/dist/web/assets/routes-B9L9tBMF.js +2 -0
  37. package/dist/web/assets/routes-B9L9tBMF.js.map +1 -0
  38. package/dist/web/assets/run._playName-a3eeybKs.js +5 -0
  39. package/dist/web/assets/run._playName-a3eeybKs.js.map +1 -0
  40. package/dist/web/assets/setup-fs0DMLq4.js +2 -0
  41. package/dist/web/assets/setup-fs0DMLq4.js.map +1 -0
  42. package/dist/web/assets/summarizeRun-BsPt7szF.js +2 -0
  43. package/dist/web/assets/summarizeRun-BsPt7szF.js.map +1 -0
  44. package/dist/web/index.html +3 -3
  45. package/package.json +2 -2
  46. package/dist/web/assets/Button-DPVQuma9.js +0 -2
  47. package/dist/web/assets/Button-DPVQuma9.js.map +0 -1
  48. package/dist/web/assets/EmptyNote-C4quX2dg.js +0 -2
  49. package/dist/web/assets/Field-D9WpcA8z.js +0 -2
  50. package/dist/web/assets/Field-D9WpcA8z.js.map +0 -1
  51. package/dist/web/assets/Skeleton-D7Z-VTMo.js +0 -2
  52. package/dist/web/assets/cadences-B8mwchUk.js +0 -2
  53. package/dist/web/assets/cadences-B8mwchUk.js.map +0 -1
  54. package/dist/web/assets/index-DkobhtBa.js +0 -60
  55. package/dist/web/assets/index-DkobhtBa.js.map +0 -1
  56. package/dist/web/assets/index-Dovjfyuq.css +0 -2
  57. package/dist/web/assets/plays-BUfo3QKZ.js +0 -2
  58. package/dist/web/assets/plays-BUfo3QKZ.js.map +0 -1
  59. package/dist/web/assets/queue-0mKz6GO1.js +0 -2
  60. package/dist/web/assets/queue-0mKz6GO1.js.map +0 -1
  61. package/dist/web/assets/receipts-CzIfb6zY.js +0 -2
  62. package/dist/web/assets/receipts-CzIfb6zY.js.map +0 -1
  63. package/dist/web/assets/routes-BEYqVix5.js +0 -2
  64. package/dist/web/assets/routes-BEYqVix5.js.map +0 -1
  65. package/dist/web/assets/run._playName-CJIjxoPb.js +0 -5
  66. package/dist/web/assets/run._playName-CJIjxoPb.js.map +0 -1
  67. package/dist/web/assets/setup-CFmdIoj0.js +0 -2
  68. package/dist/web/assets/setup-CFmdIoj0.js.map +0 -1
package/dist/bin.mjs CHANGED
@@ -28,7 +28,10 @@ const DEFAULTS = {
28
28
  founderName: null,
29
29
  founderEmail: null,
30
30
  productOneLiner: null,
31
+ productDomain: null,
32
+ sendingDomain: null,
31
33
  icpOneLiner: null,
34
+ cadenceOverrides: null,
32
35
  clientId: null
33
36
  };
34
37
  function configDir() {
@@ -239,6 +242,8 @@ var Ledger = class {
239
242
  sent_at TEXT,
240
243
  notes TEXT,
241
244
  prospect_id INTEGER,
245
+ last_draft_json TEXT,
246
+ last_drafted_at TEXT,
242
247
  FOREIGN KEY(prospect_id) REFERENCES prospects(id)
243
248
  );
244
249
  CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe ON target_queue(play_name, dedupe_key);
@@ -254,13 +259,22 @@ var Ledger = class {
254
259
  running_started_at TEXT
255
260
  );
256
261
 
262
+ CREATE TABLE IF NOT EXISTS enrichment_cache (
263
+ email TEXT PRIMARY KEY,
264
+ result_json TEXT NOT NULL,
265
+ fetched_at TEXT NOT NULL
266
+ );
267
+
257
268
  CREATE TABLE IF NOT EXISTS schema_version (
258
269
  version INTEGER PRIMARY KEY
259
270
  );
260
- INSERT OR IGNORE INTO schema_version(version) VALUES(5);
271
+ INSERT OR IGNORE INTO schema_version(version) VALUES(6);
261
272
  `);
262
273
  this.addColumnIfMissing("prospects", "phone", "TEXT");
263
274
  this.addColumnIfMissing("triggers", "running_started_at", "TEXT");
275
+ this.addColumnIfMissing("target_queue", "last_draft_json", "TEXT");
276
+ this.addColumnIfMissing("target_queue", "last_drafted_at", "TEXT");
277
+ this.addColumnIfMissing("target_queue", "drain_claimed_at", "TEXT");
264
278
  }
265
279
  addColumnIfMissing(table, column, type) {
266
280
  const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -312,11 +326,25 @@ var Ledger = class {
312
326
  findProspectByEmail(email) {
313
327
  return this.db.query("SELECT id FROM prospects WHERE email = ?").get(email) ?? null;
314
328
  }
329
+ /** Full prospect record by email — used to attach name/company to inbox replies. */
330
+ getProspectByEmail(email) {
331
+ return this.db.query("SELECT * FROM prospects WHERE email = ?").get(email) ?? null;
332
+ }
333
+ /** Cached enrichProfile result for an email (profiles are stable; reused with a TTL). */
334
+ getCachedEnrichment(email) {
335
+ return this.db.query("SELECT result_json, fetched_at FROM enrichment_cache WHERE email = ?").get(email) ?? null;
336
+ }
337
+ setCachedEnrichment(email, resultJson) {
338
+ this.db.prepare(`INSERT INTO enrichment_cache(email, result_json, fetched_at)
339
+ VALUES(?, ?, ?)
340
+ ON CONFLICT(email) DO UPDATE SET result_json = excluded.result_json, fetched_at = excluded.fetched_at`).run(email, resultJson, (/* @__PURE__ */ new Date()).toISOString());
341
+ }
315
342
  recordReceipt(input) {
343
+ const costUsd = typeof input.costUsd === "number" && Number.isFinite(input.costUsd) ? input.costUsd : null;
316
344
  const result = this.db.prepare(`
317
345
  INSERT INTO receipts(play_name, call_type, cost_usd, signed_receipt, oneshot_request_id)
318
346
  VALUES(?, ?, ?, ?, ?)
319
- `).run(input.playName, input.callType, input.costUsd ?? null, input.signedReceipt ? JSON.stringify(input.signedReceipt) : null, input.oneshotRequestId ?? null);
347
+ `).run(input.playName, input.callType, costUsd, input.signedReceipt ? JSON.stringify(input.signedReceipt) : null, input.oneshotRequestId ?? null);
320
348
  return Number(result.lastInsertRowid);
321
349
  }
322
350
  getReceipt(id) {
@@ -414,6 +442,12 @@ var Ledger = class {
414
442
  `).run(input.prospectId, input.playName, input.stepIndex, input.channel, input.status, input.metadata ? JSON.stringify(input.metadata) : null);
415
443
  return Number(result.lastInsertRowid);
416
444
  }
445
+ listSequenceEventsForProspectPlay(prospectId, playName) {
446
+ return this.db.query(`SELECT * FROM sequence_events
447
+ WHERE prospect_id = ? AND play_name = ?
448
+ AND status IN ('sent','delivered','replied')
449
+ ORDER BY step_index ASC, id ASC`).all(prospectId, playName);
450
+ }
417
451
  recordInterview(input) {
418
452
  const result = this.db.prepare(`
419
453
  INSERT INTO interviews(person, transcript_path, jtbd, pain_quotes_json)
@@ -496,6 +530,14 @@ var Ledger = class {
496
530
  const row = this.db.query("SELECT 1 FROM target_queue WHERE play_name = ? AND dedupe_key = ?").get(playName, dedupeKey);
497
531
  return row !== null && row !== void 0;
498
532
  }
533
+ /**
534
+ * Look up a queue row by its (play_name, dedupe_key) — the unique pair.
535
+ * Used by the SSE /run endpoint to map drafts back to the originating
536
+ * row so we can persist `last_draft_json`. Returns null when absent.
537
+ */
538
+ getQueueRowByDedupe(playName, dedupeKey) {
539
+ return this.db.query("SELECT * FROM target_queue WHERE play_name = ? AND dedupe_key = ?").get(playName, dedupeKey) ?? null;
540
+ }
499
541
  listQueue(opts = {}) {
500
542
  const where = [];
501
543
  const args = [];
@@ -555,13 +597,31 @@ var Ledger = class {
555
597
  const result = this.db.prepare(`UPDATE target_queue SET status = 'approved', reviewed_at = ? WHERE ${where.join(" AND ")}`).run(...[(/* @__PURE__ */ new Date()).toISOString(), ...args]);
556
598
  return Number(result.changes);
557
599
  }
600
+ /**
601
+ * Atomic claim-and-return. SELECTs approved rows whose lease has expired
602
+ * (or was never set) and UPDATEs their `drain_claimed_at` inside a single
603
+ * transaction so two concurrent drains can't return overlapping row sets.
604
+ * Default lease: 15 min — a crashed drain's claims self-heal after that
605
+ * without any sweeper. Held/error rows naturally back off for the lease
606
+ * duration (no LLM-burn loops on stuck-flagged content).
607
+ */
558
608
  dequeueApproved(opts) {
559
- return this.db.query(`
560
- SELECT * FROM target_queue
561
- WHERE play_name = ? AND status = 'approved'
562
- ORDER BY found_at ASC
563
- LIMIT ?
564
- `).all(opts.playName, opts.limit ?? 50);
609
+ const leaseSeconds = opts.leaseSeconds ?? 900;
610
+ const claimedAt = (/* @__PURE__ */ new Date()).toISOString();
611
+ const cutoff = (/* @__PURE__ */ new Date(Date.now() - leaseSeconds * 1e3)).toISOString();
612
+ const limit = opts.limit ?? 50;
613
+ return this.db.transaction(() => {
614
+ const rows = this.db.query(`SELECT * FROM target_queue
615
+ WHERE play_name = ? AND status = 'approved'
616
+ AND (drain_claimed_at IS NULL OR drain_claimed_at < ?)
617
+ ORDER BY found_at ASC
618
+ LIMIT ?`).all(opts.playName, cutoff, limit);
619
+ if (rows.length === 0) return [];
620
+ const ids = rows.map((r) => r.id);
621
+ const placeholders = ids.map(() => "?").join(",");
622
+ this.db.prepare(`UPDATE target_queue SET drain_claimed_at = ? WHERE id IN (${placeholders})`).run(...[claimedAt, ...ids]);
623
+ return rows;
624
+ }).immediate();
565
625
  }
566
626
  expirePendingOlderThan(days) {
567
627
  const sinceIso = (/* @__PURE__ */ new Date(Date.now() - days * 24 * 3600 * 1e3)).toISOString();
@@ -690,6 +750,25 @@ var Ledger = class {
690
750
  setQueueProspectId(id, prospectId) {
691
751
  this.db.prepare(`UPDATE target_queue SET prospect_id = ? WHERE id = ?`).run(prospectId, id);
692
752
  }
753
+ /**
754
+ * Persist the most-recent draft generated for this queue row. Called by
755
+ * the SSE /run endpoint after the play returns drafted output, so the
756
+ * founder can review subject/body/flags on /queue at any later time
757
+ * (the /run page itself is ephemeral).
758
+ *
759
+ * Most-recent-wins — re-runs overwrite without history. `last_drafted_at`
760
+ * is stored as ISO so it sorts/compares cleanly with the rest of the
761
+ * timestamp columns; the JSON envelope also embeds `draftedAt` for
762
+ * callers that already have the row payload.
763
+ */
764
+ setQueueDraft(input) {
765
+ const draftedAtIso = (/* @__PURE__ */ new Date()).toISOString();
766
+ const json = JSON.stringify({
767
+ ...input.draft,
768
+ draftedAt: draftedAtIso
769
+ });
770
+ this.db.prepare(`UPDATE target_queue SET last_draft_json = ?, last_drafted_at = ? WHERE id = ?`).run(json, draftedAtIso, input.id);
771
+ }
693
772
  close() {
694
773
  this.db.close();
695
774
  }
@@ -711,17 +790,38 @@ async function getAgent() {
711
790
  if (!agentSingleton) agentSingleton = await initAgent();
712
791
  return agentSingleton;
713
792
  }
714
- function emailRequestId(r) {
715
- return r.email?.id;
793
+ /**
794
+ * Derive the From localpart from the founder's name (first token, lowercased,
795
+ * non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back
796
+ * to `agent` when the name yields nothing usable. ("J. Nicolas" → "j".)
797
+ */
798
+ function fromLocalpart(name) {
799
+ const clean = ((name ?? "").trim().split(/\s+/)[0] ?? "").toLowerCase().replace(/[^a-z0-9]/g, "");
800
+ return clean.length > 0 ? clean : "agent";
801
+ }
802
+ /**
803
+ * OneShot renders the email `body` as HTML, so plain-text newlines collapse
804
+ * into one run-on paragraph. Escape HTML metacharacters and turn newlines into
805
+ * <br> so paragraphs + the signature lines render the way the draft intended.
806
+ */
807
+ function toHtmlBody(text) {
808
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r\n/g, "\n").replace(/\n/g, "<br>\n");
716
809
  }
717
810
  async function sendEmail(input, ctx) {
718
811
  const agent = await getAgent();
812
+ const cfg = loadConfig();
813
+ const fromDomain = input.fromDomain ?? cfg.sendingDomain ?? null;
719
814
  const opts = {
720
815
  to: input.to,
721
816
  subject: input.subject,
722
- body: input.body
817
+ body: toHtmlBody(input.body)
723
818
  };
724
- if (input.fromDomain) opts.from_domain = input.fromDomain;
819
+ if (fromDomain) {
820
+ opts.from_domain = fromDomain;
821
+ opts.from_mailbox = fromLocalpart(cfg.founderName);
822
+ const name = (cfg.founderName ?? "").trim();
823
+ if (name) opts.from_name = name;
824
+ }
725
825
  const result = await agent.email(opts);
726
826
  return {
727
827
  result,
@@ -729,7 +829,8 @@ async function sendEmail(input, ctx) {
729
829
  playName: ctx.playName,
730
830
  callType: "email.send",
731
831
  signedReceipt: result,
732
- oneshotRequestId: emailRequestId(result) ?? void 0
832
+ costUsd: result.cost,
833
+ oneshotRequestId: result.request_id
733
834
  })
734
835
  };
735
836
  }
@@ -743,7 +844,9 @@ async function deepResearch(input, ctx) {
743
844
  receiptId: getLedger().recordReceipt({
744
845
  playName: ctx.playName,
745
846
  callType: "research.deep",
746
- signedReceipt: result
847
+ signedReceipt: result,
848
+ costUsd: result.cost,
849
+ oneshotRequestId: result.request_id
747
850
  })
748
851
  };
749
852
  }
@@ -761,6 +864,7 @@ async function enrichProfile(input, ctx) {
761
864
  playName: ctx.playName,
762
865
  callType: "enrich.profile",
763
866
  signedReceipt: result,
867
+ costUsd: result.cost,
764
868
  oneshotRequestId: result.request_id
765
869
  })
766
870
  };
@@ -786,6 +890,7 @@ async function deepResearchPerson(input, ctx) {
786
890
  playName: ctx.playName,
787
891
  callType: "research.person",
788
892
  signedReceipt: result,
893
+ costUsd: result.cost,
789
894
  oneshotRequestId: result.request_id
790
895
  })
791
896
  };
@@ -803,6 +908,7 @@ async function findEmail(input, ctx) {
803
908
  playName: ctx.playName,
804
909
  callType: "email.find",
805
910
  signedReceipt: result,
911
+ costUsd: result.cost,
806
912
  oneshotRequestId: result.request_id
807
913
  })
808
914
  };
@@ -815,6 +921,7 @@ async function verifyEmail(input, ctx) {
815
921
  playName: ctx.playName,
816
922
  callType: "email.verify",
817
923
  signedReceipt: result,
924
+ costUsd: result.cost,
818
925
  oneshotRequestId: result.request_id
819
926
  })
820
927
  };
@@ -826,6 +933,13 @@ async function getBalance(tokenAddress) {
826
933
  raw
827
934
  };
828
935
  }
936
+ async function listInbox(opts) {
937
+ const agent = await getAgent();
938
+ const out = { include_body: true };
939
+ if (opts?.since) out.since = opts.since;
940
+ if (opts?.limit) out.limit = opts.limit;
941
+ return agent.inboxList(out);
942
+ }
829
943
  async function webSearch(input, ctx) {
830
944
  const agent = await getAgent();
831
945
  const opts = { query: input.query };
@@ -836,7 +950,8 @@ async function webSearch(input, ctx) {
836
950
  receiptId: getLedger().recordReceipt({
837
951
  playName: ctx.playName,
838
952
  callType: "web.search",
839
- signedReceipt: result
953
+ signedReceipt: result,
954
+ costUsd: result.cost
840
955
  })
841
956
  };
842
957
  }
@@ -847,7 +962,9 @@ async function webRead(input, ctx) {
847
962
  receiptId: getLedger().recordReceipt({
848
963
  playName: ctx.playName,
849
964
  callType: "web.read",
850
- signedReceipt: result
965
+ signedReceipt: result,
966
+ costUsd: result.cost,
967
+ oneshotRequestId: result.request_id
851
968
  })
852
969
  };
853
970
  }
@@ -1053,6 +1170,79 @@ function getReceipt(req, params) {
1053
1170
  } }, 200, req);
1054
1171
  }
1055
1172
  //#endregion
1173
+ //#region src/api/inbox.ts
1174
+ /** "Jane Doe <jane@x.com>" → "jane@x.com"; bare addresses pass through. */
1175
+ function normalizeFrom(raw) {
1176
+ const m = raw.match(/<([^>]+)>/);
1177
+ return (m ? m[1] ?? raw : raw).trim().toLowerCase();
1178
+ }
1179
+ /**
1180
+ * Read-only view of the OneShot inbox (replies to outreach). Each email is
1181
+ * matched to a known prospect by sender address, annotated with the play +
1182
+ * cadence status when available. Live fetch — no storage. The SDK exposes only
1183
+ * inboxList (no reply/markRead), so this is read-only.
1184
+ */
1185
+ async function listInboxRoute(req) {
1186
+ const ledger = getLedger();
1187
+ let emails;
1188
+ try {
1189
+ emails = (await listInbox({ limit: 50 })).emails;
1190
+ } catch (err) {
1191
+ logEvent("inbox.list_failed", { message_120: (err?.message ?? "").slice(0, 120) }, "warn");
1192
+ return jsonResponse({
1193
+ replies: [],
1194
+ hasMore: false,
1195
+ error: "couldn't reach the inbox"
1196
+ }, 200, req);
1197
+ }
1198
+ const byEmail = /* @__PURE__ */ new Map();
1199
+ for (const c of ledger.listAllCadences()) {
1200
+ if (!c.prospect_email) continue;
1201
+ const key = c.prospect_email.trim().toLowerCase();
1202
+ const existing = byEmail.get(key);
1203
+ if (!existing || c.status === "replied" || c.status === "active" && existing.status !== "replied") byEmail.set(key, {
1204
+ name: c.prospect_name,
1205
+ company: c.prospect_company,
1206
+ playName: c.play_name,
1207
+ status: c.status
1208
+ });
1209
+ }
1210
+ const replies = emails.map((e) => {
1211
+ const fromEmail = normalizeFrom(e.from);
1212
+ let matched = null;
1213
+ const cadence = byEmail.get(fromEmail);
1214
+ if (cadence) matched = {
1215
+ name: cadence.name,
1216
+ company: cadence.company,
1217
+ playName: cadence.playName,
1218
+ cadenceStatus: cadence.status
1219
+ };
1220
+ else {
1221
+ const p = ledger.getProspectByEmail(fromEmail);
1222
+ if (p) matched = {
1223
+ name: p.name,
1224
+ company: p.company,
1225
+ playName: p.source,
1226
+ cadenceStatus: null
1227
+ };
1228
+ }
1229
+ return {
1230
+ id: e.id,
1231
+ fromEmail,
1232
+ fromRaw: e.from,
1233
+ subject: e.subject,
1234
+ receivedAt: e.received_at,
1235
+ body: e.body ?? "",
1236
+ matched
1237
+ };
1238
+ });
1239
+ const selfDomain = (loadConfig().sendingDomain ?? "").trim().toLowerCase();
1240
+ return jsonResponse({
1241
+ replies: replies.filter((r) => !selfDomain || !r.fromEmail.endsWith(`@${selfDomain}`)).toSorted((a, b) => a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : 0),
1242
+ hasMore: false
1243
+ }, 200, req);
1244
+ }
1245
+ //#endregion
1056
1246
  //#region ../../packages/intel/src/prompts.ts
1057
1247
  const here = dirname(fileURLToPath(import.meta.url));
1058
1248
  const candidates = [
@@ -1060,13 +1250,28 @@ const candidates = [
1060
1250
  join(here, "..", "..", "..", "prompts"),
1061
1251
  join(process.cwd(), "packages", "prompts")
1062
1252
  ];
1063
- function loadPrompt(name) {
1064
- if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`invalid prompt name: ${JSON.stringify(name)}`);
1253
+ const HUMANIZER_REF_RE = /^\[See _humanizer\.md[^\]]*\]\s*$/gm;
1254
+ let humanizerCache = null;
1255
+ function readPromptFile(name) {
1065
1256
  for (const dir of candidates) {
1066
1257
  const path = join(dir, `${name}.md`);
1067
1258
  if (existsSync(path)) return readFileSync(path, "utf8");
1068
1259
  }
1069
- throw new Error(`prompt not found: ${name}.md (searched: ${candidates.join(", ")})`);
1260
+ return null;
1261
+ }
1262
+ function loadHumanizer() {
1263
+ if (humanizerCache != null) return humanizerCache;
1264
+ const content = readPromptFile("_humanizer");
1265
+ if (content == null) throw new Error(`_humanizer.md not found in any of: ${candidates.join(", ")}`);
1266
+ humanizerCache = content.trimEnd();
1267
+ return humanizerCache;
1268
+ }
1269
+ function loadPrompt(name) {
1270
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`invalid prompt name: ${JSON.stringify(name)}`);
1271
+ const raw = readPromptFile(name);
1272
+ if (raw == null) throw new Error(`prompt not found: ${name}.md (searched: ${candidates.join(", ")})`);
1273
+ if (HUMANIZER_REF_RE.test(raw)) return raw.replace(HUMANIZER_REF_RE, loadHumanizer());
1274
+ return raw;
1070
1275
  }
1071
1276
  //#endregion
1072
1277
  //#region ../../packages/intel/src/client.ts
@@ -1274,6 +1479,49 @@ function tryParseJsonObject(raw, fallback) {
1274
1479
  }
1275
1480
  //#endregion
1276
1481
  //#region ../../packages/plays/src/_lib.ts
1482
+ /** Profiles change slowly — reuse a cached enrichment for this long before refetching. */
1483
+ const ENRICH_CACHE_TTL_MS = 720 * 3600 * 1e3;
1484
+ /**
1485
+ * enrichProfile that (a) never throws and (b) caches by email. The dossier is a
1486
+ * nice-to-have for drafting, the SDK call is slow (~70s) and billed, and the
1487
+ * same person can recur across plays / repeated previews / re-sends — so we
1488
+ * cache the result by email (TTL) and reuse it. A cache hit returns receiptId 0
1489
+ * (no new SDK call, no spend). On failure: log a warn and return an empty
1490
+ * result so callers' `enr.result` / `enr.receiptId` usage keeps working.
1491
+ */
1492
+ async function safeEnrich(input, ctx) {
1493
+ const ledger = getLedger();
1494
+ const email = typeof input.email === "string" ? input.email.trim().toLowerCase() : null;
1495
+ if (email) {
1496
+ const cached = ledger.getCachedEnrichment(email);
1497
+ if (cached && Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS) try {
1498
+ return {
1499
+ result: JSON.parse(cached.result_json),
1500
+ receiptId: 0
1501
+ };
1502
+ } catch {}
1503
+ }
1504
+ try {
1505
+ const out = await enrichProfile(input, ctx);
1506
+ if (email) try {
1507
+ ledger.setCachedEnrichment(email, JSON.stringify(out.result));
1508
+ } catch {}
1509
+ return out;
1510
+ } catch (err) {
1511
+ logEvent("enrich.failed", {
1512
+ play: ctx.playName,
1513
+ message_120: (err?.message ?? "").slice(0, 120)
1514
+ }, "warn");
1515
+ return {
1516
+ result: {
1517
+ status: "failed",
1518
+ profile: null,
1519
+ cost: 0
1520
+ },
1521
+ receiptId: 0
1522
+ };
1523
+ }
1524
+ }
1277
1525
  const SLOP_PHRASES = [
1278
1526
  [/\bI noticed\b/i, "banned-opener:I-noticed"],
1279
1527
  [/\bI came across\b/i, "banned-opener:I-came-across"],
@@ -1310,18 +1558,66 @@ function lintEmail(subject, body, maxBodyWords = 110) {
1310
1558
  if (body.toLowerCase().includes("calendly")) flags.push("calendar-link");
1311
1559
  return flags;
1312
1560
  }
1561
+ function errorDraft(message) {
1562
+ return {
1563
+ subject: "(error)",
1564
+ body: "",
1565
+ flags: [`error: ${(message ?? "play failed").slice(0, 80)}`],
1566
+ sent: false,
1567
+ receiptIds: []
1568
+ };
1569
+ }
1570
+ /**
1571
+ * Deterministic, semantics-preserving cleanups that the LLM occasionally
1572
+ * slips through despite the humanizer rules being in its system prompt.
1573
+ * Applied silently inside `draftEmailFromPrompt` so these four flags never
1574
+ * surface in the UI.
1575
+ */
1576
+ function humanizeDraft(input) {
1577
+ return {
1578
+ subject: applyAutofixes(input.subject),
1579
+ body: applyAutofixes(input.body)
1580
+ };
1581
+ }
1582
+ function applyAutofixes(s) {
1583
+ return s.replace(/[ \t]*—[ \t]*/g, ", ").replace(/[“”]/g, "\"").replace(/[‘’]/g, "'").replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{1F1E6}-\u{1F1FF}]/gu, "").replace(/\u{FE0F}|\u{200D}/gu, "").replace(/!\s*!+/g, "!").replace(/[ \t]+\n/g, "\n").trim();
1584
+ }
1585
+ /**
1586
+ * Binding sign-off directive appended to every email system prompt. Forces
1587
+ * the founder's product domain onto its own line beneath their name, even on
1588
+ * prompts that say "no links / no tagline" (a bare domain is a signature, not
1589
+ * a hyperlink). Returns "" when no domain is configured, so founders who
1590
+ * haven't set one keep the prior name-only sign-off. Loaded fresh each call
1591
+ * so a /setup change takes effect without a process restart.
1592
+ */
1593
+ function signatureDirective() {
1594
+ const cfg = loadConfig();
1595
+ const domain = (cfg.productDomain ?? "").trim();
1596
+ if (!domain) return "";
1597
+ return [
1598
+ "",
1599
+ "",
1600
+ "## Signature (binding — overrides any sign-off rule above)",
1601
+ "End the email with the founder's name, then their domain on the very next line:",
1602
+ "",
1603
+ (cfg.founderName ?? "").trim() || "[founder name]",
1604
+ domain,
1605
+ "",
1606
+ `Always include the domain line, even if a rule above says "no links" or "no tagline" — a bare domain beneath the name is the signature, not an inline link. Write it plain: no "https://", no "www.", no hyperlink, no text after it.`
1607
+ ].join("\n");
1608
+ }
1313
1609
  async function draftEmailFromPrompt(opts) {
1314
- return parseSubjectBody((await complete({
1610
+ return humanizeDraft(parseSubjectBody((await complete({
1315
1611
  messages: [{
1316
1612
  role: "system",
1317
- content: loadPrompt(opts.promptName)
1613
+ content: loadPrompt(opts.promptName) + signatureDirective()
1318
1614
  }, {
1319
1615
  role: "user",
1320
1616
  content: opts.inputBlock
1321
1617
  }],
1322
1618
  temperature: opts.temperature ?? .65,
1323
1619
  maxTokens: opts.maxTokens ?? 500
1324
- })).content);
1620
+ })).content));
1325
1621
  }
1326
1622
  function parseSubjectBody(raw) {
1327
1623
  const parsed = tryParseJsonObject(raw, {});
@@ -1337,6 +1633,16 @@ async function sendDraftedEmail(opts) {
1337
1633
  const receiptIds = [];
1338
1634
  let sent = false;
1339
1635
  if (!opts.dryRun && opts.flags.length === 0) {
1636
+ const existing = ledger.findProspectByEmail(opts.to);
1637
+ if (existing) {
1638
+ if (ledger.listSequenceEventsForProspectPlay(existing.id, opts.playName).some((e) => e.step_index === 0)) {
1639
+ opts.flags.push("already-enrolled");
1640
+ return {
1641
+ receiptIds: [],
1642
+ sent: false
1643
+ };
1644
+ }
1645
+ }
1340
1646
  const send = await sendEmail({
1341
1647
  to: opts.to,
1342
1648
  subject: opts.draft.subject,
@@ -1352,6 +1658,7 @@ async function sendDraftedEmail(opts) {
1352
1658
  status: "sent",
1353
1659
  metadata: {
1354
1660
  subject: opts.draft.subject,
1661
+ body: opts.draft.body,
1355
1662
  ...opts.metadata
1356
1663
  }
1357
1664
  });
@@ -1362,6 +1669,107 @@ async function sendDraftedEmail(opts) {
1362
1669
  sent
1363
1670
  };
1364
1671
  }
1672
+ /**
1673
+ * Verify a batch of target emails BEFORE drafting + sending. Used by
1674
+ * direct-input entry points (CLI motion commands + dashboard /run) where
1675
+ * the founder pastes targets directly without going through a finder.
1676
+ * Drops undeliverable rows so the caller skips ~$0.005-0.02 of LLM
1677
+ * drafting cost per bad email AND avoids the send attempt itself.
1678
+ *
1679
+ * Skips on dryRun (no real spend during preview) and on empty input.
1680
+ * De-dupes the underlying verifyEmail calls so a duplicated email in
1681
+ * the input doesn't double-bill.
1682
+ *
1683
+ * Finder-sourced rows that flow through /queue → drain do NOT call this
1684
+ * — they were already verified at finder enqueue time.
1685
+ */
1686
+ async function verifyAndFilterTargets(targets, getEmail, opts) {
1687
+ if (opts.dryRun || targets.length === 0) return {
1688
+ verified: targets,
1689
+ dropped: [],
1690
+ receiptIds: [],
1691
+ costUsd: 0
1692
+ };
1693
+ const emailFor = /* @__PURE__ */ new Map();
1694
+ for (const t of targets) {
1695
+ const e = (getEmail(t) ?? "").trim().toLowerCase();
1696
+ if (e.length > 0) emailFor.set(t, e);
1697
+ }
1698
+ const uniqueEmails = [...new Set(emailFor.values())];
1699
+ const verifications = await Promise.all(uniqueEmails.map(async (email) => {
1700
+ try {
1701
+ const r = await verifyEmail({ email }, { playName: opts.playName });
1702
+ return {
1703
+ email,
1704
+ deliverable: Boolean(r.result.deliverable),
1705
+ receiptId: r.receiptId,
1706
+ costUsd: r.result.cost ?? 0,
1707
+ errored: false
1708
+ };
1709
+ } catch (err) {
1710
+ return {
1711
+ email,
1712
+ deliverable: false,
1713
+ receiptId: 0,
1714
+ costUsd: 0,
1715
+ errored: true,
1716
+ message: (err.message ?? "verify failed").slice(0, 120)
1717
+ };
1718
+ }
1719
+ }));
1720
+ const byEmail = new Map(verifications.map((v) => [v.email, v]));
1721
+ const verified = [];
1722
+ const dropped = [];
1723
+ let costUsd = 0;
1724
+ const receiptIds = [];
1725
+ for (const v of verifications) {
1726
+ costUsd += v.costUsd;
1727
+ if (v.receiptId > 0) receiptIds.push(v.receiptId);
1728
+ }
1729
+ for (const t of targets) {
1730
+ const email = emailFor.get(t);
1731
+ if (!email) {
1732
+ dropped.push({
1733
+ target: t,
1734
+ email: "",
1735
+ reason: "missing email"
1736
+ });
1737
+ continue;
1738
+ }
1739
+ const v = byEmail.get(email);
1740
+ if (!v) {
1741
+ dropped.push({
1742
+ target: t,
1743
+ email,
1744
+ reason: "undeliverable"
1745
+ });
1746
+ continue;
1747
+ }
1748
+ if (v.errored) {
1749
+ dropped.push({
1750
+ target: t,
1751
+ email,
1752
+ reason: `verify-error: ${v.message}`
1753
+ });
1754
+ continue;
1755
+ }
1756
+ if (!v.deliverable) {
1757
+ dropped.push({
1758
+ target: t,
1759
+ email,
1760
+ reason: "undeliverable"
1761
+ });
1762
+ continue;
1763
+ }
1764
+ verified.push(t);
1765
+ }
1766
+ return {
1767
+ verified,
1768
+ dropped,
1769
+ receiptIds,
1770
+ costUsd
1771
+ };
1772
+ }
1365
1773
  //#endregion
1366
1774
  //#region ../../packages/plays/src/_cadence.ts
1367
1775
  const playSequences = /* @__PURE__ */ new Map();
@@ -1369,10 +1777,38 @@ function registerSequence(seq) {
1369
1777
  playSequences.set(seq.playName, seq);
1370
1778
  }
1371
1779
  function getSequence(playName) {
1780
+ return effectiveSequence(playName);
1781
+ }
1782
+ /** The registered (code) sequence, ignoring any founder override. For "reset". */
1783
+ function defaultSequence(playName) {
1372
1784
  return playSequences.get(playName);
1373
1785
  }
1786
+ /**
1787
+ * The registered (code) sequence with the founder's per-play timing overrides
1788
+ * applied. The code sequence defines the structure (which prompts fire, where
1789
+ * the breakup sits); a matching-length `cadenceOverrides[playName]` in config
1790
+ * replaces each step's RELATIVE dayOffset. A length mismatch (e.g. after a
1791
+ * later structural change) is ignored — the code default wins, never throws.
1792
+ * Read fresh each call so a /plays edit takes effect without a restart.
1793
+ */
1794
+ function effectiveSequence(playName) {
1795
+ const base = playSequences.get(playName);
1796
+ if (!base) return void 0;
1797
+ const override = loadConfig().cadenceOverrides?.[playName];
1798
+ if (!Array.isArray(override) || override.length !== base.steps.length) return base;
1799
+ return {
1800
+ playName: base.playName,
1801
+ steps: base.steps.map((step, i) => ({
1802
+ dayOffset: override[i],
1803
+ channel: step.channel,
1804
+ breakOnReply: step.breakOnReply,
1805
+ label: step.label,
1806
+ builder: step.builder
1807
+ }))
1808
+ };
1809
+ }
1374
1810
  function enrollInCadence(input) {
1375
- const seq = playSequences.get(input.playName);
1811
+ const seq = effectiveSequence(input.playName);
1376
1812
  if (!seq || seq.steps.length === 0) return;
1377
1813
  const next = seq.steps[0];
1378
1814
  if (!next) return;
@@ -1385,14 +1821,16 @@ function enrollInCadence(input) {
1385
1821
  }
1386
1822
  function buildFollowUpEmail(opts) {
1387
1823
  return async (ctx) => {
1388
- const system = loadPrompt(opts.promptName);
1824
+ const system = loadPrompt(opts.promptName) + signatureDirective();
1825
+ const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);
1389
1826
  const user = [
1390
1827
  `FOUNDER: ${ctx.cfg.founderName}`,
1391
1828
  `PRODUCT: ${ctx.cfg.productOneLiner}`,
1392
1829
  `PROSPECT: ${ctx.prospect.name ?? "(unknown)"}`,
1393
1830
  `EMAIL: ${ctx.prospect.email ?? ""}`,
1394
1831
  `COMPANY: ${ctx.prospect.company ?? "(unknown)"}`,
1395
- ...opts.contextLines
1832
+ ...opts.contextLines,
1833
+ ...priorBlock ? ["", priorBlock] : []
1396
1834
  ].join("\n");
1397
1835
  const parsed = tryParseJsonObject((await complete({
1398
1836
  messages: [{
@@ -1413,27 +1851,53 @@ function buildFollowUpEmail(opts) {
1413
1851
  };
1414
1852
  };
1415
1853
  }
1854
+ function buildPriorEmailsBlock(prospectId, playName) {
1855
+ if (!prospectId) return null;
1856
+ let rows;
1857
+ try {
1858
+ rows = getLedger().listSequenceEventsForProspectPlay(prospectId, playName);
1859
+ } catch {
1860
+ return null;
1861
+ }
1862
+ const usable = rows.flatMap((r) => {
1863
+ const meta = tryParseJsonObject(r.metadata_json ?? "", {});
1864
+ if (!meta.body) return [];
1865
+ return [{
1866
+ step: r.step_index,
1867
+ subject: meta.subject ?? "(no subject)",
1868
+ body: meta.body,
1869
+ label: meta.label ?? (r.step_index === 0 ? "initial send" : "follow-up")
1870
+ }];
1871
+ });
1872
+ if (usable.length === 0) return null;
1873
+ const lines = ["PRIOR EMAILS (your previous touches to this prospect on this play; do not repeat their angles, hooks, openers, or closes):"];
1874
+ for (const row of usable) {
1875
+ lines.push(`--- step ${row.step} (${row.label}) ---`);
1876
+ lines.push(`Subject: ${row.subject}`);
1877
+ lines.push(row.body);
1878
+ }
1879
+ return lines.join("\n");
1880
+ }
1416
1881
  //#endregion
1417
1882
  //#region ../../packages/plays/src/show-hn.ts
1418
- const PLAY_NAME$19 = "show-hn";
1883
+ const PLAY_NAME$20 = "show-hn";
1419
1884
  async function runShowHn(opts) {
1420
1885
  const cfg = loadConfig();
1421
1886
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1422
1887
  const drafted = [];
1423
- for (const target of opts.targets) {
1888
+ for (const target of opts.targets) try {
1424
1889
  const receiptIds = [];
1425
- let dossier = "";
1890
+ const enr = await safeEnrich({
1891
+ email: target.founderEmail,
1892
+ name: target.founderName
1893
+ }, { playName: PLAY_NAME$20 });
1894
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
1895
+ let dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1426
1896
  if (!opts.dryRun) {
1427
- const enr = await enrichProfile({
1428
- email: target.founderEmail,
1429
- name: target.founderName
1430
- }, { playName: PLAY_NAME$19 });
1431
- receiptIds.push(enr.receiptId);
1432
- dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1433
1897
  const research = await deepResearch({
1434
1898
  topic: `Recent public work and engineering decisions by ${target.founderName} on ${target.postTitle}`,
1435
1899
  depth: "quick"
1436
- }, { playName: PLAY_NAME$19 });
1900
+ }, { playName: PLAY_NAME$20 });
1437
1901
  receiptIds.push(research.receiptId);
1438
1902
  dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1439
1903
  }
@@ -1450,7 +1914,7 @@ async function runShowHn(opts) {
1450
1914
  });
1451
1915
  const flags = lintEmail(draft.subject, draft.body, 90);
1452
1916
  const send = await sendDraftedEmail({
1453
- playName: PLAY_NAME$19,
1917
+ playName: PLAY_NAME$20,
1454
1918
  to: target.founderEmail,
1455
1919
  draft,
1456
1920
  flags,
@@ -1476,6 +1940,11 @@ async function runShowHn(opts) {
1476
1940
  sent: send.sent,
1477
1941
  flags
1478
1942
  });
1943
+ } catch (err) {
1944
+ drafted.push({
1945
+ target,
1946
+ ...errorDraft(err?.message)
1947
+ });
1479
1948
  }
1480
1949
  return { drafted };
1481
1950
  }
@@ -1485,26 +1954,25 @@ function extractCompany(title) {
1485
1954
  }
1486
1955
  //#endregion
1487
1956
  //#region ../../packages/plays/src/job-change.ts
1488
- const PLAY_NAME$18 = "job-change";
1957
+ const PLAY_NAME$19 = "job-change";
1489
1958
  async function runJobChange(opts) {
1490
1959
  const cfg = loadConfig();
1491
1960
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1492
1961
  const drafted = [];
1493
- for (const target of opts.targets) {
1962
+ for (const target of opts.targets) try {
1494
1963
  const receiptIds = [];
1495
- let dossier = "";
1964
+ const enr = await safeEnrich({
1965
+ ...target.email ? { email: target.email } : {},
1966
+ ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
1967
+ name: target.name
1968
+ }, { playName: PLAY_NAME$19 });
1969
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
1970
+ let dossier = JSON.stringify(enr.result, null, 2).slice(0, 4e3);
1496
1971
  if (!opts.dryRun) {
1497
- const enr = await enrichProfile({
1498
- ...target.email ? { email: target.email } : {},
1499
- ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
1500
- name: target.name
1501
- }, { playName: PLAY_NAME$18 });
1502
- receiptIds.push(enr.receiptId);
1503
- dossier = JSON.stringify(enr.result, null, 2).slice(0, 4e3);
1504
1972
  const research = await deepResearch({
1505
1973
  topic: `Public posts, talks, and recent decisions by ${target.name} (joined ${target.newCompany} as ${target.newRole}, formerly ${target.previousRole ?? "?"} at ${target.previousCompany ?? "?"})`,
1506
1974
  depth: "quick"
1507
- }, { playName: PLAY_NAME$18 });
1975
+ }, { playName: PLAY_NAME$19 });
1508
1976
  receiptIds.push(research.receiptId);
1509
1977
  dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1510
1978
  }
@@ -1521,7 +1989,7 @@ async function runJobChange(opts) {
1521
1989
  });
1522
1990
  const flags = lintEmail(draft.subject, draft.body, 100);
1523
1991
  const send = await sendDraftedEmail({
1524
- playName: PLAY_NAME$18,
1992
+ playName: PLAY_NAME$19,
1525
1993
  to: target.email,
1526
1994
  draft,
1527
1995
  flags,
@@ -1543,7 +2011,7 @@ async function runJobChange(opts) {
1543
2011
  const prospect = getLedger().findProspectByEmail(target.email);
1544
2012
  if (prospect) enrollInCadence({
1545
2013
  prospectId: prospect.id,
1546
- playName: PLAY_NAME$18
2014
+ playName: PLAY_NAME$19
1547
2015
  });
1548
2016
  }
1549
2017
  drafted.push({
@@ -1554,17 +2022,23 @@ async function runJobChange(opts) {
1554
2022
  sent: send.sent,
1555
2023
  flags
1556
2024
  });
2025
+ } catch (err) {
2026
+ drafted.push({
2027
+ target,
2028
+ ...errorDraft(err?.message)
2029
+ });
1557
2030
  }
1558
2031
  return { drafted };
1559
2032
  }
1560
2033
  registerSequence({
1561
- playName: PLAY_NAME$18,
2034
+ playName: PLAY_NAME$19,
1562
2035
  steps: [{
1563
2036
  dayOffset: 5,
1564
2037
  channel: "email",
1565
2038
  breakOnReply: true,
1566
2039
  label: "value follow-up",
1567
2040
  builder: buildFollowUpEmail({
2041
+ playName: PLAY_NAME$19,
1568
2042
  promptName: "job-change-followup",
1569
2043
  contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
1570
2044
  })
@@ -1574,6 +2048,7 @@ registerSequence({
1574
2048
  breakOnReply: true,
1575
2049
  label: "breakup",
1576
2050
  builder: buildFollowUpEmail({
2051
+ playName: PLAY_NAME$19,
1577
2052
  promptName: "breakup-email",
1578
2053
  contextLines: [`PLAY: job-change. Sender is closing the file.`]
1579
2054
  })
@@ -1581,26 +2056,25 @@ registerSequence({
1581
2056
  });
1582
2057
  //#endregion
1583
2058
  //#region ../../packages/plays/src/post-funding.ts
1584
- const PLAY_NAME$17 = "post-funding";
2059
+ const PLAY_NAME$18 = "post-funding";
1585
2060
  async function runPostFunding(opts) {
1586
2061
  const cfg = loadConfig();
1587
2062
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1588
2063
  const drafted = [];
1589
- for (const target of opts.targets) {
2064
+ for (const target of opts.targets) try {
1590
2065
  const receiptIds = [];
1591
- let dossier = "";
2066
+ const enr = await safeEnrich({
2067
+ ...target.email ? { email: target.email } : {},
2068
+ ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
2069
+ name: target.name
2070
+ }, { playName: PLAY_NAME$18 });
2071
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2072
+ let dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1592
2073
  if (!opts.dryRun) {
1593
- const enr = await enrichProfile({
1594
- ...target.email ? { email: target.email } : {},
1595
- ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
1596
- name: target.name
1597
- }, { playName: PLAY_NAME$17 });
1598
- receiptIds.push(enr.receiptId);
1599
- dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1600
2074
  const research = await deepResearch({
1601
2075
  topic: `${target.company} ${target.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${target.sourceUrl}`,
1602
2076
  depth: "quick"
1603
- }, { playName: PLAY_NAME$17 });
2077
+ }, { playName: PLAY_NAME$18 });
1604
2078
  receiptIds.push(research.receiptId);
1605
2079
  dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1606
2080
  }
@@ -1618,7 +2092,7 @@ async function runPostFunding(opts) {
1618
2092
  });
1619
2093
  const flags = lintEmail(draft.subject, draft.body, 100);
1620
2094
  const send = await sendDraftedEmail({
1621
- playName: PLAY_NAME$17,
2095
+ playName: PLAY_NAME$18,
1622
2096
  to: target.email,
1623
2097
  draft,
1624
2098
  flags,
@@ -1641,7 +2115,7 @@ async function runPostFunding(opts) {
1641
2115
  const prospect = getLedger().findProspectByEmail(target.email);
1642
2116
  if (prospect) enrollInCadence({
1643
2117
  prospectId: prospect.id,
1644
- playName: PLAY_NAME$17
2118
+ playName: PLAY_NAME$18
1645
2119
  });
1646
2120
  }
1647
2121
  drafted.push({
@@ -1652,17 +2126,23 @@ async function runPostFunding(opts) {
1652
2126
  sent: send.sent,
1653
2127
  flags
1654
2128
  });
2129
+ } catch (err) {
2130
+ drafted.push({
2131
+ target,
2132
+ ...errorDraft(err?.message)
2133
+ });
1655
2134
  }
1656
2135
  return { drafted };
1657
2136
  }
1658
2137
  registerSequence({
1659
- playName: PLAY_NAME$17,
2138
+ playName: PLAY_NAME$18,
1660
2139
  steps: [{
1661
2140
  dayOffset: 9,
1662
2141
  channel: "email",
1663
2142
  breakOnReply: true,
1664
2143
  label: "case-study follow-up",
1665
2144
  builder: buildFollowUpEmail({
2145
+ playName: PLAY_NAME$18,
1666
2146
  promptName: "post-funding-followup",
1667
2147
  contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
1668
2148
  })
@@ -1672,6 +2152,7 @@ registerSequence({
1672
2152
  breakOnReply: true,
1673
2153
  label: "breakup",
1674
2154
  builder: buildFollowUpEmail({
2155
+ playName: PLAY_NAME$18,
1675
2156
  promptName: "breakup-email",
1676
2157
  contextLines: [`PLAY: post-funding.`]
1677
2158
  })
@@ -1679,27 +2160,26 @@ registerSequence({
1679
2160
  });
1680
2161
  //#endregion
1681
2162
  //#region ../../packages/plays/src/accelerator-batch.ts
1682
- const PLAY_NAME$16 = "accelerator-batch";
2163
+ const PLAY_NAME$17 = "accelerator-batch";
1683
2164
  async function runAcceleratorBatch(opts) {
1684
2165
  const cfg = loadConfig();
1685
2166
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1686
2167
  const drafted = [];
1687
- for (const target of opts.targets) {
2168
+ for (const target of opts.targets) try {
1688
2169
  const receiptIds = [];
1689
- let dossier = "";
2170
+ const enr = await safeEnrich({
2171
+ ...target.email ? { email: target.email } : {},
2172
+ ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
2173
+ name: target.name
2174
+ }, { playName: PLAY_NAME$17 });
2175
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2176
+ let dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1690
2177
  if (!opts.dryRun) {
1691
- const enr = await enrichProfile({
1692
- ...target.email ? { email: target.email } : {},
1693
- ...target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {},
1694
- name: target.name
1695
- }, { playName: PLAY_NAME$16 });
1696
- receiptIds.push(enr.receiptId);
1697
- dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1698
2178
  if (target.launchUrl) {
1699
2179
  const research = await deepResearch({
1700
2180
  topic: `Recent public work and decisions by ${target.name} at ${target.company} (${target.cohort}). Pull launch context from ${target.launchUrl}.`,
1701
2181
  depth: "quick"
1702
- }, { playName: PLAY_NAME$16 });
2182
+ }, { playName: PLAY_NAME$17 });
1703
2183
  receiptIds.push(research.receiptId);
1704
2184
  dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1705
2185
  }
@@ -1720,7 +2200,7 @@ async function runAcceleratorBatch(opts) {
1720
2200
  });
1721
2201
  const flags = lintEmail(draft.subject, draft.body, 100);
1722
2202
  const send = await sendDraftedEmail({
1723
- playName: PLAY_NAME$16,
2203
+ playName: PLAY_NAME$17,
1724
2204
  to: target.email,
1725
2205
  draft,
1726
2206
  flags,
@@ -1742,7 +2222,7 @@ async function runAcceleratorBatch(opts) {
1742
2222
  const prospect = getLedger().findProspectByEmail(target.email);
1743
2223
  if (prospect) enrollInCadence({
1744
2224
  prospectId: prospect.id,
1745
- playName: PLAY_NAME$16
2225
+ playName: PLAY_NAME$17
1746
2226
  });
1747
2227
  }
1748
2228
  drafted.push({
@@ -1753,30 +2233,40 @@ async function runAcceleratorBatch(opts) {
1753
2233
  sent: send.sent,
1754
2234
  flags
1755
2235
  });
2236
+ } catch (err) {
2237
+ drafted.push({
2238
+ target,
2239
+ ...errorDraft(err?.message)
2240
+ });
1756
2241
  }
1757
2242
  return { drafted };
1758
2243
  }
1759
2244
  registerSequence({
1760
- playName: PLAY_NAME$16,
2245
+ playName: PLAY_NAME$17,
1761
2246
  steps: [{
1762
2247
  dayOffset: 5,
1763
2248
  channel: "email",
1764
2249
  breakOnReply: true,
1765
2250
  label: "single follow-up + breakup",
1766
2251
  builder: buildFollowUpEmail({
2252
+ playName: PLAY_NAME$17,
1767
2253
  promptName: "breakup-email",
1768
2254
  contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
1769
2255
  })
1770
2256
  }]
1771
2257
  });
2258
+ //#endregion
2259
+ //#region ../../packages/plays/src/demo-no-show.ts
2260
+ const PLAY_NAME$16 = "demo-no-show";
1772
2261
  registerSequence({
1773
- playName: "demo-no-show",
2262
+ playName: PLAY_NAME$16,
1774
2263
  steps: [{
1775
2264
  dayOffset: 3,
1776
2265
  channel: "email",
1777
2266
  breakOnReply: true,
1778
2267
  label: "day-3 follow-up",
1779
2268
  builder: buildFollowUpEmail({
2269
+ playName: PLAY_NAME$16,
1780
2270
  promptName: "demo-no-show-followup",
1781
2271
  contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`]
1782
2272
  })
@@ -1784,24 +2274,24 @@ registerSequence({
1784
2274
  });
1785
2275
  //#endregion
1786
2276
  //#region ../../packages/plays/src/competitor-switch.ts
1787
- const PLAY_NAME$14 = "competitor-switch";
2277
+ const PLAY_NAME$15 = "competitor-switch";
1788
2278
  async function runCompetitorSwitch(opts) {
1789
2279
  const cfg = loadConfig();
1790
2280
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1791
2281
  const drafted = [];
1792
- for (const t of opts.targets) {
2282
+ for (const t of opts.targets) try {
1793
2283
  const receiptIds = [];
1794
2284
  let scrapedEvidence;
1795
- let dossier = "";
2285
+ const enr = await safeEnrich({
2286
+ ...t.email ? { email: t.email } : {},
2287
+ name: t.name,
2288
+ companyDomain: extractDomain$1(t.email)
2289
+ }, { playName: PLAY_NAME$15 });
2290
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2291
+ const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1796
2292
  if (!opts.dryRun) {
1797
- const enr = await enrichProfile({
1798
- ...t.email ? { email: t.email } : {},
1799
- name: t.name,
1800
- companyDomain: extractDomain(t.email)
1801
- }, { playName: PLAY_NAME$14 });
1802
- receiptIds.push(enr.receiptId);
1803
- dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1804
- if (t.evidenceUrl && !opts.skipBrowserScrape) {
2293
+ const haveEvidenceText = typeof t.evidenceText === "string" && t.evidenceText.trim().length > 0;
2294
+ if (t.evidenceUrl && !opts.skipBrowserScrape && !haveEvidenceText) {
1805
2295
  const browse = await browserTask({
1806
2296
  task: `Read the page at ${t.evidenceUrl} and extract: (1) any specific complaints or pain points the user mentioned about ${t.competitor}, (2) any mentions of features they wished existed, (3) any context about company size or use case. Return concise structured JSON.`,
1807
2297
  startUrl: t.evidenceUrl,
@@ -1820,7 +2310,7 @@ async function runCompetitorSwitch(opts) {
1820
2310
  }
1821
2311
  },
1822
2312
  maxSteps: 12
1823
- }, { playName: PLAY_NAME$14 });
2313
+ }, { playName: PLAY_NAME$15 });
1824
2314
  receiptIds.push(browse.receiptId);
1825
2315
  scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
1826
2316
  }
@@ -1840,7 +2330,7 @@ async function runCompetitorSwitch(opts) {
1840
2330
  });
1841
2331
  const flags = lintEmail(draft.subject, draft.body, 100);
1842
2332
  const send = await sendDraftedEmail({
1843
- playName: PLAY_NAME$14,
2333
+ playName: PLAY_NAME$15,
1844
2334
  to: t.email,
1845
2335
  draft,
1846
2336
  flags,
@@ -1862,7 +2352,7 @@ async function runCompetitorSwitch(opts) {
1862
2352
  const prospect = getLedger().findProspectByEmail(t.email);
1863
2353
  if (prospect) enrollInCadence({
1864
2354
  prospectId: prospect.id,
1865
- playName: PLAY_NAME$14
2355
+ playName: PLAY_NAME$15
1866
2356
  });
1867
2357
  }
1868
2358
  drafted.push({
@@ -1874,73 +2364,73 @@ async function runCompetitorSwitch(opts) {
1874
2364
  flags,
1875
2365
  ...scrapedEvidence ? { scrapedEvidence } : {}
1876
2366
  });
2367
+ } catch (err) {
2368
+ drafted.push({
2369
+ target: t,
2370
+ ...errorDraft(err?.message)
2371
+ });
1877
2372
  }
1878
2373
  return { drafted };
1879
2374
  }
1880
- function extractDomain(email) {
2375
+ function extractDomain$1(email) {
1881
2376
  const at = email.indexOf("@");
1882
2377
  if (at < 0) return void 0;
1883
2378
  return email.slice(at + 1);
1884
2379
  }
1885
2380
  registerSequence({
1886
- playName: PLAY_NAME$14,
2381
+ playName: PLAY_NAME$15,
1887
2382
  steps: [{
1888
- dayOffset: 7,
2383
+ dayOffset: 3,
2384
+ channel: "email",
2385
+ breakOnReply: true,
2386
+ label: "value follow-up",
2387
+ builder: buildFollowUpEmail({
2388
+ playName: PLAY_NAME$15,
2389
+ promptName: "competitor-switch-followup",
2390
+ contextLines: [`PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`]
2391
+ })
2392
+ }, {
2393
+ dayOffset: 8,
1889
2394
  channel: "email",
1890
2395
  breakOnReply: true,
1891
2396
  label: "breakup",
1892
2397
  builder: buildFollowUpEmail({
2398
+ playName: PLAY_NAME$15,
1893
2399
  promptName: "breakup-email",
1894
- contextLines: [`PLAY: competitor-switch. Single follow-up after the migration-honesty pitch.`]
2400
+ contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
1895
2401
  })
1896
2402
  }]
1897
2403
  });
1898
2404
  //#endregion
1899
- //#region ../../packages/plays/src/hiring-signal.ts
1900
- const PLAY_NAME$13 = "hiring-signal";
1901
- async function runHiringSignal(opts) {
2405
+ //#region ../../packages/plays/src/stack-consolidation.ts
2406
+ const PLAY_NAME$14 = "stack-consolidation";
2407
+ async function runStackConsolidation(opts) {
1902
2408
  const cfg = loadConfig();
1903
2409
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1904
2410
  const drafted = [];
1905
- for (const t of opts.targets) {
2411
+ for (const t of opts.targets) try {
1906
2412
  const receiptIds = [];
1907
- let jobPostHook = "(no specific job post phrase scraped)";
1908
- if (!opts.dryRun) {
1909
- const enr = await enrichProfile({
1910
- email: t.email,
1911
- name: t.name
1912
- }, { playName: PLAY_NAME$13 });
1913
- receiptIds.push(enr.receiptId);
1914
- let jobUrl = t.jobPostUrl;
1915
- if (!jobUrl && !opts.skipScrape) {
1916
- const search = await webSearch({
1917
- query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
1918
- maxResults: 5
1919
- }, { playName: PLAY_NAME$13 });
1920
- receiptIds.push(search.receiptId);
1921
- jobUrl = search.result.results[0]?.url;
1922
- }
1923
- if (jobUrl) {
1924
- const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$13 });
1925
- receiptIds.push(read.receiptId);
1926
- const md = read.result.markdown ?? "";
1927
- 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();
1928
- }
1929
- }
2413
+ const enr = await safeEnrich({
2414
+ ...t.email ? { email: t.email } : {},
2415
+ name: t.name,
2416
+ companyDomain: extractDomain(t.email)
2417
+ }, { playName: PLAY_NAME$14 });
2418
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2419
+ const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
1930
2420
  const draft = await draftEmailFromPrompt({
1931
- promptName: "hiring-signal-email",
2421
+ promptName: "stack-consolidation-email",
1932
2422
  inputBlock: [
1933
2423
  `FOUNDER: ${cfg.founderName}`,
1934
2424
  `PRODUCT: ${cfg.productOneLiner}`,
1935
2425
  `PROSPECT: ${t.name} at ${t.company}`,
1936
- `JOB TITLE: ${t.jobTitle}`,
1937
- `JOB POST HOOK (real phrase from the post): ${jobPostHook}`,
1938
- `YOUR CLAIM: ${t.yourClaim}`
2426
+ `STACK: ${t.vendorStack}`,
2427
+ `YOUR EDGE: ${t.yourEdge}`,
2428
+ `DOSSIER:\n${dossier || "(dry-run)"}`
1939
2429
  ].join("\n")
1940
2430
  });
1941
2431
  const flags = lintEmail(draft.subject, draft.body, 100);
1942
2432
  const send = await sendDraftedEmail({
1943
- playName: PLAY_NAME$13,
2433
+ playName: PLAY_NAME$14,
1944
2434
  to: t.email,
1945
2435
  draft,
1946
2436
  flags,
@@ -1950,11 +2440,11 @@ async function runHiringSignal(opts) {
1950
2440
  company: t.company,
1951
2441
  linkedin_url: t.linkedinUrl ?? null,
1952
2442
  phone: t.phone ?? null,
1953
- source: "hiring-signal"
2443
+ source: "stack-consolidation"
1954
2444
  },
1955
2445
  metadata: {
1956
- jobTitle: t.jobTitle,
1957
- jobPostUrl: t.jobPostUrl ?? null
2446
+ vendorStack: t.vendorStack,
2447
+ evidenceUrl: t.evidenceUrl ?? null
1958
2448
  },
1959
2449
  dryRun: opts.dryRun
1960
2450
  });
@@ -1962,7 +2452,117 @@ async function runHiringSignal(opts) {
1962
2452
  const prospect = getLedger().findProspectByEmail(t.email);
1963
2453
  if (prospect) enrollInCadence({
1964
2454
  prospectId: prospect.id,
1965
- playName: PLAY_NAME$13
2455
+ playName: PLAY_NAME$14
2456
+ });
2457
+ }
2458
+ drafted.push({
2459
+ target: t,
2460
+ subject: draft.subject,
2461
+ body: draft.body,
2462
+ receiptIds: [...receiptIds, ...send.receiptIds],
2463
+ sent: send.sent,
2464
+ flags
2465
+ });
2466
+ } catch (err) {
2467
+ drafted.push({
2468
+ target: t,
2469
+ ...errorDraft(err?.message)
2470
+ });
2471
+ }
2472
+ return { drafted };
2473
+ }
2474
+ function extractDomain(email) {
2475
+ const at = email.indexOf("@");
2476
+ if (at < 0) return void 0;
2477
+ return email.slice(at + 1);
2478
+ }
2479
+ registerSequence({
2480
+ playName: PLAY_NAME$14,
2481
+ steps: [{
2482
+ dayOffset: 3,
2483
+ channel: "email",
2484
+ breakOnReply: true,
2485
+ label: "value follow-up",
2486
+ builder: buildFollowUpEmail({
2487
+ playName: PLAY_NAME$14,
2488
+ promptName: "stack-consolidation-followup",
2489
+ contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
2490
+ })
2491
+ }, {
2492
+ dayOffset: 8,
2493
+ channel: "email",
2494
+ breakOnReply: true,
2495
+ label: "breakup",
2496
+ builder: buildFollowUpEmail({
2497
+ playName: PLAY_NAME$14,
2498
+ promptName: "breakup-email",
2499
+ contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
2500
+ })
2501
+ }]
2502
+ });
2503
+ //#endregion
2504
+ //#region ../../packages/plays/src/hiring-signal.ts
2505
+ const PLAY_NAME$13 = "hiring-signal";
2506
+ async function runHiringSignal(opts) {
2507
+ const cfg = loadConfig();
2508
+ if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2509
+ const drafted = [];
2510
+ for (const t of opts.targets) try {
2511
+ const receiptIds = [];
2512
+ let jobPostHook = "(no specific job post phrase scraped)";
2513
+ if (!opts.dryRun) {
2514
+ let jobUrl = t.jobPostUrl;
2515
+ if (!jobUrl && !opts.skipScrape) {
2516
+ const search = await webSearch({
2517
+ query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
2518
+ maxResults: 5
2519
+ }, { playName: PLAY_NAME$13 });
2520
+ receiptIds.push(search.receiptId);
2521
+ jobUrl = search.result.results[0]?.url;
2522
+ }
2523
+ if (jobUrl) {
2524
+ const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$13 });
2525
+ receiptIds.push(read.receiptId);
2526
+ const md = read.result.markdown ?? "";
2527
+ 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();
2528
+ }
2529
+ }
2530
+ const draft = await draftEmailFromPrompt({
2531
+ promptName: "hiring-signal-email",
2532
+ inputBlock: [
2533
+ `FOUNDER: ${cfg.founderName}`,
2534
+ `PRODUCT: ${cfg.productOneLiner}`,
2535
+ `PROSPECT: ${t.name} at ${t.company}`,
2536
+ `JOB TITLE: ${t.jobTitle}`,
2537
+ `JOB POST HOOK (real phrase from the post): ${jobPostHook}`,
2538
+ `YOUR CLAIM: ${t.yourClaim}`
2539
+ ].join("\n")
2540
+ });
2541
+ const flags = lintEmail(draft.subject, draft.body, 100);
2542
+ const send = await sendDraftedEmail({
2543
+ playName: PLAY_NAME$13,
2544
+ to: t.email,
2545
+ draft,
2546
+ flags,
2547
+ prospectMeta: {
2548
+ name: t.name,
2549
+ email: t.email,
2550
+ company: t.company,
2551
+ linkedin_url: t.linkedinUrl ?? null,
2552
+ phone: t.phone ?? null,
2553
+ source: "hiring-signal"
2554
+ },
2555
+ metadata: {
2556
+ jobTitle: t.jobTitle,
2557
+ jobPostUrl: t.jobPostUrl ?? null
2558
+ },
2559
+ dryRun: opts.dryRun
2560
+ });
2561
+ if (send.sent) {
2562
+ const prospect = getLedger().findProspectByEmail(t.email);
2563
+ if (prospect) enrollInCadence({
2564
+ prospectId: prospect.id,
2565
+ playName: PLAY_NAME$13
1966
2566
  });
1967
2567
  }
1968
2568
  drafted.push({
@@ -1974,19 +2574,36 @@ async function runHiringSignal(opts) {
1974
2574
  sent: send.sent,
1975
2575
  flags
1976
2576
  });
2577
+ } catch (err) {
2578
+ drafted.push({
2579
+ target: t,
2580
+ jobPostHook: "(error)",
2581
+ ...errorDraft(err?.message)
2582
+ });
1977
2583
  }
1978
2584
  return { drafted };
1979
2585
  }
1980
2586
  registerSequence({
1981
2587
  playName: PLAY_NAME$13,
1982
2588
  steps: [{
1983
- dayOffset: 7,
2589
+ dayOffset: 3,
2590
+ channel: "email",
2591
+ breakOnReply: true,
2592
+ label: "value follow-up",
2593
+ builder: buildFollowUpEmail({
2594
+ playName: PLAY_NAME$13,
2595
+ promptName: "hiring-signal-followup",
2596
+ contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`]
2597
+ })
2598
+ }, {
2599
+ dayOffset: 8,
1984
2600
  channel: "email",
1985
2601
  breakOnReply: true,
1986
2602
  label: "breakup",
1987
2603
  builder: buildFollowUpEmail({
2604
+ playName: PLAY_NAME$13,
1988
2605
  promptName: "breakup-email",
1989
- contextLines: [`PLAY: hiring-signal. Single follow-up.`]
2606
+ contextLines: [`PLAY: hiring-signal. Final breakup.`]
1990
2607
  })
1991
2608
  }]
1992
2609
  });
@@ -1997,15 +2614,10 @@ async function runPodcastGuest(opts) {
1997
2614
  const cfg = loadConfig();
1998
2615
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1999
2616
  const drafted = [];
2000
- for (const t of opts.targets) {
2617
+ for (const t of opts.targets) try {
2001
2618
  const receiptIds = [];
2002
2619
  let extra = "";
2003
2620
  if (!opts.dryRun) {
2004
- const enr = await enrichProfile({
2005
- email: t.email,
2006
- name: t.name
2007
- }, { playName: PLAY_NAME$12 });
2008
- receiptIds.push(enr.receiptId);
2009
2621
  if (!opts.skipSearch) {
2010
2622
  const s = await webSearch({
2011
2623
  query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
@@ -2063,6 +2675,11 @@ async function runPodcastGuest(opts) {
2063
2675
  sent: send.sent,
2064
2676
  flags
2065
2677
  });
2678
+ } catch (err) {
2679
+ drafted.push({
2680
+ target: t,
2681
+ ...errorDraft(err?.message)
2682
+ });
2066
2683
  }
2067
2684
  return { drafted };
2068
2685
  }
@@ -2080,46 +2697,60 @@ async function runBreakupRevive(opts) {
2080
2697
  const drafted = [];
2081
2698
  for (const t of targets) {
2082
2699
  if (!t.email) continue;
2083
- const draft = await draftEmailFromPrompt({
2084
- promptName: "breakup-revive-email",
2085
- inputBlock: [
2086
- `FOUNDER: ${cfg.founderName}`,
2087
- `PRODUCT: ${cfg.productOneLiner}`,
2088
- `PROSPECT: ${t.name ?? "(unknown)"} at ${t.company ?? "(unknown)"}`,
2089
- `DAYS SINCE LAST ACTIVITY: ${t.daysCold}`,
2090
- `OPTIONAL VALUE DROP: ${opts.valueDrop ?? "(none — go with a probe question instead)"}`
2091
- ].join("\n")
2092
- });
2093
- const flags = lintEmail(draft.subject, draft.body, 80);
2094
- const send = await sendDraftedEmail({
2095
- playName: PLAY_NAME$11,
2096
- to: t.email,
2097
- draft,
2098
- flags,
2099
- prospectMeta: {
2100
- name: t.name,
2101
- email: t.email,
2102
- company: t.company,
2103
- linkedin_url: t.linkedinUrl ?? null,
2104
- phone: t.phone ?? null,
2105
- source: "breakup-revive"
2106
- },
2107
- metadata: {
2700
+ try {
2701
+ const draft = await draftEmailFromPrompt({
2702
+ promptName: "breakup-revive-email",
2703
+ inputBlock: [
2704
+ `FOUNDER: ${cfg.founderName}`,
2705
+ `PRODUCT: ${cfg.productOneLiner}`,
2706
+ `PROSPECT: ${t.name ?? "(unknown)"} at ${t.company ?? "(unknown)"}`,
2707
+ `DAYS SINCE LAST ACTIVITY: ${t.daysCold}`,
2708
+ `OPTIONAL VALUE DROP: ${opts.valueDrop ?? "(none — go with a probe question instead)"}`
2709
+ ].join("\n")
2710
+ });
2711
+ const flags = lintEmail(draft.subject, draft.body, 80);
2712
+ const send = await sendDraftedEmail({
2713
+ playName: PLAY_NAME$11,
2714
+ to: t.email,
2715
+ draft,
2716
+ flags,
2717
+ prospectMeta: {
2718
+ name: t.name,
2719
+ email: t.email,
2720
+ company: t.company,
2721
+ linkedin_url: t.linkedinUrl ?? null,
2722
+ phone: t.phone ?? null,
2723
+ source: "breakup-revive"
2724
+ },
2725
+ metadata: {
2726
+ daysCold: t.daysCold,
2727
+ lastEventAt: t.lastEventAt
2728
+ },
2729
+ dryRun: opts.dryRun
2730
+ });
2731
+ drafted.push({
2732
+ prospectEmail: t.email,
2733
+ prospectName: t.name,
2108
2734
  daysCold: t.daysCold,
2109
- lastEventAt: t.lastEventAt
2110
- },
2111
- dryRun: opts.dryRun
2112
- });
2113
- drafted.push({
2114
- prospectEmail: t.email,
2115
- prospectName: t.name,
2116
- daysCold: t.daysCold,
2117
- subject: draft.subject,
2118
- body: draft.body,
2119
- receiptIds: send.receiptIds,
2120
- sent: send.sent,
2121
- flags
2122
- });
2735
+ subject: draft.subject,
2736
+ body: draft.body,
2737
+ receiptIds: send.receiptIds,
2738
+ sent: send.sent,
2739
+ flags
2740
+ });
2741
+ } catch (err) {
2742
+ const stub = errorDraft(err?.message);
2743
+ drafted.push({
2744
+ prospectEmail: t.email,
2745
+ prospectName: t.name,
2746
+ daysCold: t.daysCold,
2747
+ subject: stub.subject,
2748
+ body: stub.body,
2749
+ receiptIds: stub.receiptIds,
2750
+ sent: stub.sent,
2751
+ flags: stub.flags
2752
+ });
2753
+ }
2123
2754
  }
2124
2755
  return { drafted };
2125
2756
  }
@@ -2169,6 +2800,10 @@ const PLAY_CATALOG = [
2169
2800
  name: "competitor-switch",
2170
2801
  cli: "oneshot-gtm motion competitor-switch --target ./examples/competitor-switch.json"
2171
2802
  },
2803
+ {
2804
+ name: "stack-consolidation",
2805
+ cli: "oneshot-gtm find watch # fed by the github-topics finder, drained from /queue"
2806
+ },
2172
2807
  {
2173
2808
  name: "hiring-signal",
2174
2809
  cli: "oneshot-gtm motion hiring-signal --target ./examples/hiring-signal.json"
@@ -2182,21 +2817,74 @@ const PLAY_CATALOG = [
2182
2817
  cli: "oneshot-gtm motion breakup-revive --min-days 60 --max-days 90"
2183
2818
  }
2184
2819
  ];
2820
+ /** Relative per-step dayOffsets → cumulative days from the day-0 initial send. */
2821
+ function cumulativeDays(seq) {
2822
+ if (!seq) return [];
2823
+ let acc = 0;
2824
+ return seq.steps.map((s) => acc += s.dayOffset);
2825
+ }
2185
2826
  function listPlays(req) {
2186
2827
  return jsonResponse({ plays: PLAY_CATALOG.map((p) => {
2187
2828
  const seq = getSequence(p.name);
2188
2829
  const channels = seq ? Array.from(new Set(seq.steps.map((s) => s.channel))) : ["email"];
2189
2830
  const followupCount = seq?.steps.length ?? 0;
2190
2831
  const hasBreakup = seq?.steps.some((s) => s.label?.toLowerCase().includes("breakup")) ?? false;
2832
+ const days = cumulativeDays(seq);
2833
+ const steps = (seq?.steps ?? []).map((s, i) => ({
2834
+ day: days[i] ?? 0,
2835
+ label: s.label ?? `step ${i + 1}`,
2836
+ channel: s.channel
2837
+ }));
2191
2838
  return {
2192
2839
  name: p.name,
2193
2840
  channels,
2194
2841
  followupCount,
2195
2842
  hasBreakup,
2196
- cliInvocation: p.cli
2843
+ cliInvocation: p.cli,
2844
+ steps,
2845
+ defaultDays: cumulativeDays(defaultSequence(p.name))
2197
2846
  };
2198
2847
  }) }, 200, req);
2199
2848
  }
2849
+ /**
2850
+ * Set (or clear) per-play cadence timing. Body: { days: number[] | null }.
2851
+ * `days` are CUMULATIVE days from the initial send (intuitive in the UI); we
2852
+ * convert to the engine-native relative offsets before persisting. `null`
2853
+ * clears the override (reset to code defaults). Timing only — step structure
2854
+ * is fixed in code.
2855
+ */
2856
+ async function setCadenceRoute(req, params) {
2857
+ const name = params["name"] ?? "";
2858
+ const def = defaultSequence(name);
2859
+ if (!def || def.steps.length === 0) return jsonResponse({ error: `play '${name}' has no editable cadence` }, 400, req);
2860
+ let body;
2861
+ try {
2862
+ body = await req.json();
2863
+ } catch {
2864
+ return jsonResponse({ error: "invalid JSON body" }, 400, req);
2865
+ }
2866
+ const cfg = loadConfig();
2867
+ const overrides = { ...cfg.cadenceOverrides };
2868
+ if (body.days === null || body.days === void 0) {
2869
+ delete overrides[name];
2870
+ saveConfig({
2871
+ ...cfg,
2872
+ cadenceOverrides: Object.keys(overrides).length > 0 ? overrides : null
2873
+ });
2874
+ return jsonResponse({ ok: true }, 200, req);
2875
+ }
2876
+ const days = body.days;
2877
+ const stepCount = def.steps.length;
2878
+ if (!Array.isArray(days) || days.length !== stepCount) return jsonResponse({ error: `days must be an array of ${stepCount} cumulative day value(s)` }, 400, req);
2879
+ if (!days.every((d) => Number.isInteger(d) && d >= 1 && d <= 120)) return jsonResponse({ error: "each day must be an integer between 1 and 120" }, 400, req);
2880
+ for (let i = 1; i < days.length; i++) if (days[i] <= days[i - 1]) return jsonResponse({ error: "days must be strictly increasing" }, 400, req);
2881
+ overrides[name] = days.map((d, i) => i === 0 ? d : d - days[i - 1]);
2882
+ saveConfig({
2883
+ ...cfg,
2884
+ cadenceOverrides: overrides
2885
+ });
2886
+ return jsonResponse({ ok: true }, 200, req);
2887
+ }
2200
2888
  //#endregion
2201
2889
  //#region src/api/measure.ts
2202
2890
  function readSinceDays(req) {
@@ -2312,7 +3000,10 @@ async function setup(req) {
2312
3000
  founderName: mergeString(body.founderName, current.founderName),
2313
3001
  founderEmail: mergeString(body.founderEmail, current.founderEmail),
2314
3002
  productOneLiner: mergeString(body.productOneLiner, current.productOneLiner),
3003
+ productDomain: mergeString(body.productDomain, current.productDomain),
3004
+ sendingDomain: mergeString(body.sendingDomain, current.sendingDomain),
2315
3005
  icpOneLiner: mergeString(body.icpOneLiner, current.icpOneLiner),
3006
+ cadenceOverrides: current.cadenceOverrides,
2316
3007
  clientId: current.clientId
2317
3008
  });
2318
3009
  if (body.secrets && Object.keys(body.secrets).length > 0) saveSecrets(body.secrets);
@@ -2516,6 +3207,178 @@ function urlDomain(url) {
2516
3207
  }
2517
3208
  }
2518
3209
  //#endregion
3210
+ //#region ../../packages/find/src/_findemail-prescreen.ts
3211
+ /**
3212
+ * Pre-flight guard for `findEmail` SDK calls.
3213
+ *
3214
+ * The OneShot `findEmail` SDK receives only `company_domain` + `full_name` and
3215
+ * guesses email patterns from those. Two structural causes of dud lookups we
3216
+ * can catch BEFORE spending the ~$0.05 per call:
3217
+ *
3218
+ * 1. `company_domain` points at a host where no company hosts email —
3219
+ * free-tier app subdomains (vercel.app, github.io, …), social platforms,
3220
+ * personal email providers, code hosts, link aggregators.
3221
+ * 2. `full_name` is a single-token handle (`samaralihussain`) not a real
3222
+ * person name (`Sam Jones`). Pattern-based email guessing can't
3223
+ * disambiguate a username.
3224
+ *
3225
+ * Callers do `shouldSkipFindEmail(...)` ahead of the SDK call; when it
3226
+ * returns `{ok:false}`, increment `result.droppedEnrichment` and emit a
3227
+ * `finder.skipped_findemail` event for telemetry, then move to the next
3228
+ * candidate. No new wire-protocol surface.
3229
+ */
3230
+ /**
3231
+ * Hosts where `findEmail` virtually never finds a deliverable company
3232
+ * address. Match is exact on the bare host or any subdomain of one of
3233
+ * these entries — `foo.vercel.app` and `bar.foo.vercel.app` both qualify.
3234
+ *
3235
+ * Curated, static. Adaptive/learned variants are out of scope.
3236
+ */
3237
+ const DUD_DOMAINS = new Set([
3238
+ "vercel.app",
3239
+ "netlify.app",
3240
+ "github.io",
3241
+ "pages.dev",
3242
+ "fly.dev",
3243
+ "replit.co",
3244
+ "replit.app",
3245
+ "codesandbox.io",
3246
+ "stackblitz.com",
3247
+ "glitch.me",
3248
+ "deno.dev",
3249
+ "workers.dev",
3250
+ "herokuapp.com",
3251
+ "onrender.com",
3252
+ "railway.app",
3253
+ "modal.run",
3254
+ "supabase.co",
3255
+ "firebaseapp.com",
3256
+ "appspot.com",
3257
+ "azurewebsites.net",
3258
+ "webflow.io",
3259
+ "wixsite.com",
3260
+ "googleusercontent.com",
3261
+ "gmail.com",
3262
+ "yahoo.com",
3263
+ "outlook.com",
3264
+ "hotmail.com",
3265
+ "icloud.com",
3266
+ "proton.me",
3267
+ "protonmail.com",
3268
+ "fastmail.com",
3269
+ "twitter.com",
3270
+ "x.com",
3271
+ "linkedin.com",
3272
+ "facebook.com",
3273
+ "instagram.com",
3274
+ "youtube.com",
3275
+ "youtu.be",
3276
+ "reddit.com",
3277
+ "medium.com",
3278
+ "dev.to",
3279
+ "substack.com",
3280
+ "hashnode.com",
3281
+ "hashnode.dev",
3282
+ "notion.site",
3283
+ "notion.so",
3284
+ "tiktok.com",
3285
+ "pinterest.com",
3286
+ "threads.net",
3287
+ "discord.com",
3288
+ "discord.gg",
3289
+ "slack.com",
3290
+ "news.ycombinator.com",
3291
+ "crunchbase.com",
3292
+ "producthunt.com",
3293
+ "wellfound.com",
3294
+ "pitchbook.com",
3295
+ "cbinsights.com",
3296
+ "tracxn.com",
3297
+ "github.com",
3298
+ "gitlab.com",
3299
+ "bitbucket.org",
3300
+ "gist.github.com",
3301
+ "linktr.ee",
3302
+ "bio.link",
3303
+ "carrd.co"
3304
+ ]);
3305
+ /**
3306
+ * True when the given domain is in the dud blocklist, either as an exact
3307
+ * match or as a subdomain (so `foo.vercel.app` is dud). `null`/empty
3308
+ * counts as dud — caller has no usable signal.
3309
+ *
3310
+ * Defensive normalization before matching:
3311
+ * - lowercase + trim whitespace
3312
+ * - strip `http://` / `https://` scheme
3313
+ * - strip everything from the first `/` onward (paths/queries)
3314
+ * - strip leading `www.` and trailing `.`
3315
+ *
3316
+ * Callers should pass bare hostnames (via `urlDomain` from `_dedupe.ts`),
3317
+ * but the normalization keeps an accidental full URL or trailing-dot DNS
3318
+ * form from silently slipping past the suffix match.
3319
+ *
3320
+ * Does no DNS lookup — purely suffix-based.
3321
+ */
3322
+ function isDudDomain(domain) {
3323
+ if (!domain) return true;
3324
+ const d = domain.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/[/?#].*$/, "").replace(/^www\./, "").replace(/\.+$/, "");
3325
+ if (d.length === 0) return true;
3326
+ if (DUD_DOMAINS.has(d)) return true;
3327
+ for (const dud of DUD_DOMAINS) if (d.endsWith(`.${dud}`)) return true;
3328
+ return false;
3329
+ }
3330
+ /**
3331
+ * True when the input looks like a single-token username/handle rather
3332
+ * than a real person name. Heuristics, in order:
3333
+ *
3334
+ * - Empty / null → handle (no signal).
3335
+ * - Contains whitespace → looks like a name. `"Sam Jones"`.
3336
+ * - Contains a period → looks like a name. `"Sam J. Jones"`.
3337
+ * - Single token of `[a-z0-9_-]` (case-insensitive) → handle.
3338
+ *
3339
+ * False-positive accepted: a real single-name like `Madonna` reads as a
3340
+ * handle. That's a fine tradeoff vs the volume of HN-style usernames we
3341
+ * filter out (90%+ of Show HN authors).
3342
+ */
3343
+ function looksLikeUserHandle(name) {
3344
+ if (name == null) return true;
3345
+ const trimmed = name.trim();
3346
+ if (trimmed.length === 0) return true;
3347
+ if (/\s/.test(trimmed)) return false;
3348
+ if (trimmed.includes(".")) return false;
3349
+ return /^[a-z0-9_-]+$/i.test(trimmed);
3350
+ }
3351
+ /**
3352
+ * Pre-flight guard. Returns `{ok:true}` to proceed with the SDK call, or
3353
+ * `{ok:false, reason}` to skip. The reason is human-readable and stable
3354
+ * across releases — safe to log via `finder.skipped_findemail` for later
3355
+ * blocklist tuning.
3356
+ *
3357
+ * Check order matters: a missing/dud domain dominates a handle check (no
3358
+ * point flagging "handle-not-name" when the domain alone would have
3359
+ * disqualified the row).
3360
+ */
3361
+ function shouldSkipFindEmail(input) {
3362
+ if (!input.companyDomain || input.companyDomain.trim().length === 0) return {
3363
+ ok: false,
3364
+ reason: "no-domain"
3365
+ };
3366
+ if (isDudDomain(input.companyDomain)) return {
3367
+ ok: false,
3368
+ reason: `dud-domain: ${input.companyDomain.toLowerCase()}`
3369
+ };
3370
+ const name = input.fullName?.trim() ?? "";
3371
+ if (name.length === 0) return {
3372
+ ok: false,
3373
+ reason: "no-fullname"
3374
+ };
3375
+ if (looksLikeUserHandle(name)) return {
3376
+ ok: false,
3377
+ reason: `handle-not-name: ${name}`
3378
+ };
3379
+ return { ok: true };
3380
+ }
3381
+ //#endregion
2519
3382
  //#region ../../packages/find/src/_linkedin.ts
2520
3383
  /**
2521
3384
  * Shared LinkedIn / phone capture helpers used across all finders. Centralises:
@@ -2574,7 +3437,7 @@ async function findLinkedInUrl(args) {
2574
3437
  query,
2575
3438
  maxResults: 5
2576
3439
  }, { playName: PLAY_NAME$9 });
2577
- args.accumCost(extractCost$8(search.result) ?? .01);
3440
+ args.accumCost(search.result.cost ?? 0);
2578
3441
  for (const r of search.result.results ?? []) {
2579
3442
  const url = typeof r.url === "string" ? r.url : "";
2580
3443
  if (LINKEDIN_PROFILE_RX.test(url)) {
@@ -2628,10 +3491,47 @@ function extractFirstPhone(source) {
2628
3491
  if (typeof phone === "string" && phone.trim().length > 0) return phone.trim();
2629
3492
  return null;
2630
3493
  }
2631
- function extractCost$8(r) {
2632
- if (!r || typeof r !== "object") return void 0;
2633
- const v = r["cost"];
2634
- return typeof v === "number" ? v : void 0;
3494
+ //#endregion
3495
+ //#region ../../packages/find/src/_enrich.ts
3496
+ /**
3497
+ * Always-on post-verify enrichment. Called by every enqueueing finder
3498
+ * AFTER verifyEmail succeeds + BEFORE enqueueTarget. Reads phone +
3499
+ * linkedin off PersonResult and returns them; finder merges into target.
3500
+ *
3501
+ * Why this exists: phone capture used to fire only on the narrow Path B'
3502
+ * + Path C branches in `_repo-pipeline.ts` (~10% of candidates), and the
3503
+ * other 6 finders never enriched at all. Empirical audit found 0/514
3504
+ * queue rows had a phone despite the SDK clearly returning some on
3505
+ * separate enrichProfile calls. Adding one $0.005 call per verified
3506
+ * email closes the gap uniformly across every play.
3507
+ *
3508
+ * Throws are swallowed — one transient SDK blip should never kill an
3509
+ * otherwise valid enqueue. Same try/catch pattern as the existing
3510
+ * Path B' enrichProfile call in `_repo-pipeline.ts`.
3511
+ */
3512
+ async function enrichVerifiedContact(email, opts) {
3513
+ try {
3514
+ const enriched = await enrichProfile({ email }, { playName: opts.playName });
3515
+ const profile = enriched.result.profile;
3516
+ const linkedinRaw = profile?.linkedin_url ?? null;
3517
+ return {
3518
+ phone: extractFirstPhone(profile),
3519
+ linkedinUrl: isLinkedInProfileUrl(linkedinRaw) ? linkedinRaw : null,
3520
+ costUsd: enriched.result.cost ?? 0,
3521
+ receiptId: enriched.receiptId
3522
+ };
3523
+ } catch (err) {
3524
+ logEvent("error.swallowed", {
3525
+ kind: `${opts.errKindPrefix ?? "enrich"}.post_verify`,
3526
+ message_120: (err.message ?? "").slice(0, 120)
3527
+ }, "warn");
3528
+ return {
3529
+ phone: null,
3530
+ linkedinUrl: null,
3531
+ costUsd: 0,
3532
+ receiptId: null
3533
+ };
3534
+ }
2635
3535
  }
2636
3536
  //#endregion
2637
3537
  //#region ../../packages/find/src/show-hn.ts
@@ -2721,17 +3621,29 @@ async function runShowHnFinder(opts) {
2721
3621
  continue;
2722
3622
  }
2723
3623
  const fullName = hit.author && hit.author.length > 0 ? hit.author : void 0;
3624
+ const skip = shouldSkipFindEmail({
3625
+ fullName,
3626
+ companyDomain: domain
3627
+ });
3628
+ if (!skip.ok) {
3629
+ result.droppedEnrichment++;
3630
+ logEvent("finder.skipped_findemail", {
3631
+ name: PLAY_NAME$8,
3632
+ reason: skip.reason
3633
+ }, "info");
3634
+ continue;
3635
+ }
2724
3636
  const findInput = { companyDomain: domain };
2725
3637
  if (fullName) findInput.fullName = fullName;
2726
3638
  const found = await findEmail(findInput, { playName: PLAY_NAME$8 });
2727
- result.costUsd += extractCost$7(found.result) ?? .05;
3639
+ result.costUsd += found.result.cost ?? 0;
2728
3640
  if (!found.result.found || !found.result.email) {
2729
3641
  result.droppedEnrichment++;
2730
3642
  continue;
2731
3643
  }
2732
3644
  const email = found.result.email;
2733
3645
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$8 });
2734
- result.costUsd += extractCost$7(verified.result) ?? .01;
3646
+ result.costUsd += verified.result.cost ?? 0;
2735
3647
  if (!verified.result.deliverable) {
2736
3648
  result.droppedEnrichment++;
2737
3649
  continue;
@@ -2747,7 +3659,7 @@ async function runShowHnFinder(opts) {
2747
3659
  let hookSummary = (hit.story_text ?? "").trim().slice(0, 280);
2748
3660
  if (hookSummary.length < 40 && hit.url) try {
2749
3661
  const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$8 });
2750
- result.costUsd += extractCost$7(read.result) ?? .02;
3662
+ result.costUsd += read.result.cost ?? 0;
2751
3663
  hookSummary = (read.result.markdown ?? "").trim().slice(0, 280);
2752
3664
  } catch (err) {
2753
3665
  logEvent("error.swallowed", {
@@ -2757,7 +3669,14 @@ async function runShowHnFinder(opts) {
2757
3669
  }
2758
3670
  if (!hookSummary || hookSummary.length < 20) hookSummary = `Show HN post: ${hit.title}. ${hit.points} points.`;
2759
3671
  const founderName = found.result.full_name ?? hit.author;
2760
- const linkedinUrl = await findLinkedInUrl({
3672
+ const enr = await enrichVerifiedContact(email, {
3673
+ playName: PLAY_NAME$8,
3674
+ errKindPrefix: "show-hn"
3675
+ });
3676
+ result.costUsd += enr.costUsd;
3677
+ const phone = enr.phone;
3678
+ let linkedinUrl = enr.linkedinUrl;
3679
+ if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
2761
3680
  fullName: founderName,
2762
3681
  disambiguators: ["hacker news", domain],
2763
3682
  accumCost: (c) => {
@@ -2771,7 +3690,8 @@ async function runShowHnFinder(opts) {
2771
3690
  founderName,
2772
3691
  founderEmail: email,
2773
3692
  hookSummary,
2774
- ...linkedinUrl ? { linkedinUrl } : {}
3693
+ ...linkedinUrl ? { linkedinUrl } : {},
3694
+ ...phone ? { phone } : {}
2775
3695
  };
2776
3696
  if (ledger.enqueueTarget({
2777
3697
  playName: PLAY_NAME$8,
@@ -2795,11 +3715,6 @@ async function runShowHnFinder(opts) {
2795
3715
  });
2796
3716
  return result;
2797
3717
  }
2798
- function extractCost$7(r) {
2799
- if (!r || typeof r !== "object") return void 0;
2800
- const v = r["cost"];
2801
- return typeof v === "number" ? v : void 0;
2802
- }
2803
3718
  //#endregion
2804
3719
  //#region ../../packages/find/src/post-funding.ts
2805
3720
  const PLAY_NAME$7 = "post-funding";
@@ -2854,7 +3769,7 @@ async function runPostFundingFinder(opts) {
2854
3769
  let extract;
2855
3770
  try {
2856
3771
  const read = await webRead({ url }, { playName: PLAY_NAME$7 });
2857
- result.costUsd += extractCost$6(read.result) ?? .02;
3772
+ result.costUsd += read.result.cost ?? 0;
2858
3773
  extract = parsePostFundingExtract((await complete({
2859
3774
  messages: [{
2860
3775
  role: "system",
@@ -2904,11 +3819,23 @@ async function runPostFundingFinder(opts) {
2904
3819
  });
2905
3820
  continue;
2906
3821
  }
3822
+ const skip = shouldSkipFindEmail({
3823
+ fullName: extract.founderName,
3824
+ companyDomain: extract.companyDomain
3825
+ });
3826
+ if (!skip.ok) {
3827
+ result.droppedEnrichment++;
3828
+ logEvent("finder.skipped_findemail", {
3829
+ name: PLAY_NAME$7,
3830
+ reason: skip.reason
3831
+ }, "info");
3832
+ continue;
3833
+ }
2907
3834
  const found = await findEmail({
2908
3835
  fullName: extract.founderName,
2909
3836
  companyDomain: extract.companyDomain
2910
3837
  }, { playName: PLAY_NAME$7 });
2911
- result.costUsd += extractCost$6(found.result) ?? .05;
3838
+ result.costUsd += found.result.cost ?? 0;
2912
3839
  if (!found.result.found || !found.result.email) {
2913
3840
  result.droppedEnrichment++;
2914
3841
  continue;
@@ -2923,12 +3850,19 @@ async function runPostFundingFinder(opts) {
2923
3850
  continue;
2924
3851
  }
2925
3852
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$7 });
2926
- result.costUsd += extractCost$6(verified.result) ?? .01;
3853
+ result.costUsd += verified.result.cost ?? 0;
2927
3854
  if (!verified.result.deliverable) {
2928
3855
  result.droppedEnrichment++;
2929
3856
  continue;
2930
3857
  }
3858
+ const enr = await enrichVerifiedContact(email, {
3859
+ playName: PLAY_NAME$7,
3860
+ errKindPrefix: "post-funding"
3861
+ });
3862
+ result.costUsd += enr.costUsd;
3863
+ const phone = (extract.phone || null) ?? enr.phone;
2931
3864
  let linkedinUrl = isLinkedInProfileUrl(extract.linkedinUrl) ? extract.linkedinUrl : null;
3865
+ linkedinUrl = linkedinUrl ?? enr.linkedinUrl;
2932
3866
  if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
2933
3867
  fullName: extract.founderName,
2934
3868
  disambiguators: [extract.company],
@@ -2946,7 +3880,7 @@ async function runPostFundingFinder(opts) {
2946
3880
  sourceUrl: url,
2947
3881
  ...extract.leadInvestor ? { leadInvestor: extract.leadInvestor } : {},
2948
3882
  ...linkedinUrl ? { linkedinUrl } : {},
2949
- ...extract.phone ? { phone: extract.phone } : {}
3883
+ ...phone ? { phone } : {}
2950
3884
  };
2951
3885
  if (ledger.enqueueTarget({
2952
3886
  playName: PLAY_NAME$7,
@@ -2990,11 +3924,6 @@ function parsePostFundingExtract(raw) {
2990
3924
  summary: null
2991
3925
  });
2992
3926
  }
2993
- function extractCost$6(r) {
2994
- if (!r || typeof r !== "object") return void 0;
2995
- const v = r["cost"];
2996
- return typeof v === "number" ? v : void 0;
2997
- }
2998
3927
  const FUNDING_DOMAIN_HINTS = [
2999
3928
  "techcrunch.com",
3000
3929
  "crunchbase.com",
@@ -3031,7 +3960,7 @@ async function harvestAutoUrls(args) {
3031
3960
  query,
3032
3961
  maxResults: Math.min(20, Math.max(5, args.limit - urls.length))
3033
3962
  }, { playName: PLAY_NAME$7 });
3034
- costUsd += extractCost$6(search.result) ?? .01;
3963
+ costUsd += search.result.cost ?? 0;
3035
3964
  for (const hit of search.result.results ?? []) {
3036
3965
  if (urls.length >= args.limit) break;
3037
3966
  if (!hit.url) continue;
@@ -3213,7 +4142,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
3213
4142
  query,
3214
4143
  maxResults: Math.min(15, limit)
3215
4144
  }, { playName: PLAY_NAME$6 });
3216
- costUsd += extractCost$5(search.result) ?? .01;
4145
+ costUsd += search.result.cost ?? 0;
3217
4146
  for (const raw of search.result.results ?? []) {
3218
4147
  if (!raw.url || seen.has(raw.url)) continue;
3219
4148
  if (looksLikeAcceleratorNoise(raw.url)) continue;
@@ -3242,7 +4171,7 @@ async function fetchAcceleratorSearch(_cohort, cohortLabel, limit) {
3242
4171
  let extract = null;
3243
4172
  try {
3244
4173
  const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$6 });
3245
- costUsd += extractCost$5(read.result) ?? .02;
4174
+ costUsd += read.result.cost ?? 0;
3246
4175
  extract = parseAcceleratorLaunchExtract((await complete({
3247
4176
  messages: [{
3248
4177
  role: "system",
@@ -3326,11 +4255,6 @@ function parseAcceleratorLaunchExtract(raw) {
3326
4255
  phone: null
3327
4256
  });
3328
4257
  }
3329
- function extractCost$5(r) {
3330
- if (!r || typeof r !== "object") return void 0;
3331
- const v = r["cost"];
3332
- return typeof v === "number" ? v : void 0;
3333
- }
3334
4258
  //#endregion
3335
4259
  //#region ../../packages/find/src/_parallel.ts
3336
4260
  /**
@@ -3545,12 +4469,101 @@ function mapYcOssCompany(c) {
3545
4469
  * github-topics).
3546
4470
  */
3547
4471
  const PLAY_NAME$5 = "accelerator-batch";
4472
+ /**
4473
+ * Normalize the legacy single-cohort opts shape into the new multi-cohort
4474
+ * list. Old trigger rows with `{cohort, cohortLabel}` keep working — they
4475
+ * become a one-entry list. Each entry's `cohort` is trimmed and an empty
4476
+ * `cohortLabel` is filled via `deriveCohortLabel`. Malformed entries
4477
+ * (missing or empty cohort tag) are dropped silently. Throws when zero
4478
+ * usable entries remain — readiness gate is supposed to prevent this.
4479
+ */
4480
+ function normalizeCohorts(opts) {
4481
+ if (opts.cohorts && opts.cohorts.length > 0) {
4482
+ const normalized = opts.cohorts.map((entry) => {
4483
+ if (!entry || typeof entry.cohort !== "string") return null;
4484
+ const cohort = entry.cohort.trim();
4485
+ if (cohort.length === 0) return null;
4486
+ const labelRaw = typeof entry.cohortLabel === "string" ? entry.cohortLabel.trim() : "";
4487
+ return {
4488
+ cohort,
4489
+ cohortLabel: labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort)
4490
+ };
4491
+ }).filter((e) => e !== null);
4492
+ if (normalized.length > 0) return normalized;
4493
+ }
4494
+ if (typeof opts.cohort === "string" && opts.cohort.trim().length > 0) {
4495
+ const cohort = opts.cohort.trim();
4496
+ return [{
4497
+ cohort,
4498
+ cohortLabel: typeof opts.cohortLabel === "string" && opts.cohortLabel.trim().length > 0 ? opts.cohortLabel.trim() : deriveCohortLabel(cohort)
4499
+ }];
4500
+ }
4501
+ throw new Error("accelerator-batch: at least one cohort required");
4502
+ }
4503
+ /**
4504
+ * Round-robin interleave records by their source cohort. Without this, the
4505
+ * per-company `parallelMap` would chew through every yc-w26 candidate before
4506
+ * touching Techstars — so the global `limit` enqueue cap (25 by default)
4507
+ * would be hit before any non-YC cohort got a chance. Interleaving picks
4508
+ * one record per cohort in turn until all cohort lists are exhausted, so
4509
+ * the eventual queue has a balanced cross-incubator footprint.
4510
+ *
4511
+ * Stable: ordering within a cohort matches input order. Empty input → [].
4512
+ */
4513
+ function interleaveByCohort(records) {
4514
+ if (records.length === 0) return [];
4515
+ const byCohort = /* @__PURE__ */ new Map();
4516
+ const order = [];
4517
+ for (const r of records) {
4518
+ let list = byCohort.get(r.cohort);
4519
+ if (!list) {
4520
+ list = [];
4521
+ byCohort.set(r.cohort, list);
4522
+ order.push(r.cohort);
4523
+ }
4524
+ list.push(r);
4525
+ }
4526
+ const out = [];
4527
+ let idx = 0;
4528
+ while (out.length < records.length) {
4529
+ let pushed = false;
4530
+ for (const cohort of order) {
4531
+ const list = byCohort.get(cohort);
4532
+ if (list && idx < list.length) {
4533
+ out.push(list[idx]);
4534
+ pushed = true;
4535
+ }
4536
+ }
4537
+ if (!pushed) break;
4538
+ idx++;
4539
+ }
4540
+ return out;
4541
+ }
4542
+ /**
4543
+ * Cross-cohort dedupe by company name slug. A company appearing in two
4544
+ * cohorts (e.g. a YC alum joining Techstars) is rare but possible — keep the
4545
+ * first occurrence so the per-company pipeline doesn't pay enrichment cost
4546
+ * twice. Slug = lowercase + whitespace→hyphens + non-alphanumerics stripped,
4547
+ * matching the dedupeKey shape downstream.
4548
+ */
4549
+ function dedupeRecordsBySlug(records) {
4550
+ const seen = /* @__PURE__ */ new Set();
4551
+ const out = [];
4552
+ for (const r of records) {
4553
+ const slug = r.name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
4554
+ if (seen.has(slug)) continue;
4555
+ seen.add(slug);
4556
+ out.push(r);
4557
+ }
4558
+ return out;
4559
+ }
3548
4560
  async function runAcceleratorBatchFinder(opts) {
3549
4561
  const limit = opts.limit ?? 25;
3550
4562
  const concurrency = opts.concurrency ?? 3;
3551
4563
  const icp = resolveIcp(opts.icpOverride);
3552
4564
  const ledger = getLedger();
3553
- const source = `find:accelerator-batch:${opts.cohort}`;
4565
+ const cohorts = normalizeCohorts(opts);
4566
+ const source = cohorts.length === 1 ? `find:accelerator-batch:${cohorts[0].cohort}` : `find:accelerator-batch:sweep`;
3554
4567
  const result = {
3555
4568
  source,
3556
4569
  candidates: 0,
@@ -3560,15 +4573,72 @@ async function runAcceleratorBatchFinder(opts) {
3560
4573
  enqueued: 0,
3561
4574
  costUsd: 0
3562
4575
  };
3563
- const fetched = await (pickAdapter(opts.cohort, opts.adapter) === "yc-oss" ? () => fetchYcOssBatch(opts.cohort, limit) : () => fetchAcceleratorSearch(opts.cohort, opts.cohortLabel, limit))();
3564
- result.costUsd += fetched.costUsd;
3565
- if (fetched.records.length === 0) {
3566
- result.halted = fetched.diagnostic ?? "adapter returned 0 records";
4576
+ const cohortResults = await parallelMap(cohorts, concurrency, async (entry) => {
4577
+ if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) return {
4578
+ records: [],
4579
+ summary: {
4580
+ cohort: entry.cohort,
4581
+ records: 0,
4582
+ error: "skipped: cost cap"
4583
+ }
4584
+ };
4585
+ const adapterName = pickAdapter(entry.cohort, opts.adapter);
4586
+ try {
4587
+ const fetched = adapterName === "yc-oss" ? await fetchYcOssBatch(entry.cohort, limit) : await fetchAcceleratorSearch(entry.cohort, entry.cohortLabel, limit);
4588
+ result.costUsd += fetched.costUsd;
4589
+ if (fetched.records.length === 0) return {
4590
+ records: [],
4591
+ summary: {
4592
+ cohort: entry.cohort,
4593
+ records: 0,
4594
+ error: fetched.diagnostic ?? "no records"
4595
+ }
4596
+ };
4597
+ return {
4598
+ records: fetched.records.map((r) => ({
4599
+ ...r,
4600
+ cohort: entry.cohort,
4601
+ cohortLabel: entry.cohortLabel
4602
+ })),
4603
+ summary: {
4604
+ cohort: entry.cohort,
4605
+ records: fetched.records.length
4606
+ }
4607
+ };
4608
+ } catch (err) {
4609
+ const message = (err.message ?? "").slice(0, 120);
4610
+ logEvent("error.swallowed", {
4611
+ kind: "accelerator-batch.adapter",
4612
+ cohort: entry.cohort,
4613
+ message_120: message
4614
+ }, "warn");
4615
+ return {
4616
+ records: [],
4617
+ summary: {
4618
+ cohort: entry.cohort,
4619
+ records: 0,
4620
+ error: message
4621
+ }
4622
+ };
4623
+ }
4624
+ });
4625
+ const allRecords = [];
4626
+ const perCohortOutcomes = [];
4627
+ for (const r of cohortResults) {
4628
+ allRecords.push(...r.records);
4629
+ perCohortOutcomes.push(r.summary);
4630
+ }
4631
+ result.perCohort = perCohortOutcomes;
4632
+ const deduped = dedupeRecordsBySlug(interleaveByCohort(allRecords));
4633
+ result.candidates = deduped.length;
4634
+ if (deduped.length === 0) {
4635
+ if (cohorts.length === 1) result.halted = perCohortOutcomes[0]?.error ?? "adapter returned 0 records";
4636
+ else if (opts.maxCostUsd != null && perCohortOutcomes.every((o) => o.error === "skipped: cost cap")) result.halted = `max-cost cap (${opts.maxCostUsd}) during discovery`;
4637
+ else result.halted = `all ${cohorts.length} cohorts returned 0 candidates`;
3567
4638
  return result;
3568
4639
  }
3569
- result.candidates = fetched.records.length;
3570
4640
  let halted = false;
3571
- await parallelMap(fetched.records, concurrency, async (record) => {
4641
+ await parallelMap(deduped, concurrency, async (record) => {
3572
4642
  if (halted) return;
3573
4643
  if (result.enqueued >= limit) {
3574
4644
  halted = true;
@@ -3579,7 +4649,7 @@ async function runAcceleratorBatchFinder(opts) {
3579
4649
  halted = true;
3580
4650
  return;
3581
4651
  }
3582
- const dedupeKey = makeDedupeKey(record, opts.cohort);
4652
+ const dedupeKey = makeDedupeKey(record, record.cohort);
3583
4653
  if (ledger.isQueueDuplicate(PLAY_NAME$5, dedupeKey)) {
3584
4654
  result.droppedDuplicate++;
3585
4655
  return;
@@ -3600,11 +4670,11 @@ async function runAcceleratorBatchFinder(opts) {
3600
4670
  result.droppedIcp++;
3601
4671
  ledger.enqueueTarget({
3602
4672
  playName: PLAY_NAME$5,
3603
- payload: rejectionPayload(record, opts.cohort),
4673
+ payload: rejectionPayload(record, record.cohort),
3604
4674
  dedupeKey,
3605
4675
  source,
3606
4676
  initialStatus: "rejected",
3607
- notes: `auto: ICP — ${filter.reason}`
4677
+ notes: `auto: ICP — ${record.cohortLabel} — ${filter.reason}`
3608
4678
  });
3609
4679
  return;
3610
4680
  }
@@ -3627,11 +4697,23 @@ async function runAcceleratorBatchFinder(opts) {
3627
4697
  result.droppedEnrichment++;
3628
4698
  return;
3629
4699
  }
4700
+ const skip = shouldSkipFindEmail({
4701
+ fullName: founderName,
4702
+ companyDomain: domain
4703
+ });
4704
+ if (!skip.ok) {
4705
+ result.droppedEnrichment++;
4706
+ logEvent("finder.skipped_findemail", {
4707
+ name: PLAY_NAME$5,
4708
+ reason: skip.reason
4709
+ }, "info");
4710
+ return;
4711
+ }
3630
4712
  const found = await findEmail({
3631
4713
  fullName: founderName,
3632
4714
  companyDomain: domain
3633
4715
  }, { playName: PLAY_NAME$5 });
3634
- result.costUsd += extractCost$4(found.result) ?? .05;
4716
+ result.costUsd += found.result.cost ?? 0;
3635
4717
  if (!found.result.found || !found.result.email) {
3636
4718
  result.droppedEnrichment++;
3637
4719
  return;
@@ -3647,12 +4729,18 @@ async function runAcceleratorBatchFinder(opts) {
3647
4729
  return;
3648
4730
  }
3649
4731
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$5 });
3650
- result.costUsd += extractCost$4(verified.result) ?? .01;
4732
+ result.costUsd += verified.result.cost ?? 0;
3651
4733
  if (!verified.result.deliverable) {
3652
4734
  result.droppedEnrichment++;
3653
4735
  return;
3654
4736
  }
3655
- let linkedinUrl = resolvedLinkedin;
4737
+ const enr = await enrichVerifiedContact(email, {
4738
+ playName: PLAY_NAME$5,
4739
+ errKindPrefix: "accelerator-batch"
4740
+ });
4741
+ result.costUsd += enr.costUsd;
4742
+ const phone = resolvedPhone ?? enr.phone;
4743
+ let linkedinUrl = resolvedLinkedin ?? enr.linkedinUrl;
3656
4744
  if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
3657
4745
  fullName,
3658
4746
  disambiguators: [record.name],
@@ -3665,18 +4753,18 @@ async function runAcceleratorBatchFinder(opts) {
3665
4753
  name: fullName,
3666
4754
  email,
3667
4755
  company: record.name,
3668
- cohort: opts.cohort,
4756
+ cohort: record.cohort,
3669
4757
  ...record.ycUrl ? { launchUrl: record.ycUrl } : record.website ? { launchUrl: record.website } : {},
3670
4758
  ...record.oneLiner ? { productOneLiner: record.oneLiner } : {},
3671
4759
  ...linkedinUrl ? { linkedinUrl } : {},
3672
- ...resolvedPhone ? { phone: resolvedPhone } : {}
4760
+ ...phone ? { phone } : {}
3673
4761
  };
3674
4762
  if (ledger.enqueueTarget({
3675
4763
  playName: PLAY_NAME$5,
3676
4764
  payload: target,
3677
4765
  dedupeKey,
3678
4766
  source,
3679
- notes: filter.reason
4767
+ notes: `${record.cohortLabel} — ${filter.reason}`
3680
4768
  }) != null) result.enqueued++;
3681
4769
  else result.droppedDuplicate++;
3682
4770
  });
@@ -3711,11 +4799,6 @@ function buildIcpSummary(record) {
3711
4799
  if (record.tags.length > 0) parts.push(`Tags: ${record.tags.join(", ")}`);
3712
4800
  return parts.join("\n\n");
3713
4801
  }
3714
- function extractCost$4(r) {
3715
- if (!r || typeof r !== "object") return void 0;
3716
- const v = r["cost"];
3717
- return typeof v === "number" ? v : void 0;
3718
- }
3719
4802
  /**
3720
4803
  * webRead a per-company URL (YC profile preferred, company website as
3721
4804
  * fallback) and run the `accelerator-launch-extract` prompt to grab a
@@ -3736,7 +4819,7 @@ async function resolveFounderName(record) {
3736
4819
  let costUsd = 0;
3737
4820
  try {
3738
4821
  const read = await webRead({ url }, { playName: PLAY_NAME$5 });
3739
- costUsd += extractCost$4(read.result) ?? .02;
4822
+ costUsd += read.result.cost ?? 0;
3740
4823
  const extract = parseAcceleratorLaunchExtract((await complete({
3741
4824
  messages: [{
3742
4825
  role: "system",
@@ -3810,7 +4893,7 @@ async function runJobChangeFinder(opts) {
3810
4893
  query,
3811
4894
  maxResults: Math.min(15, limit)
3812
4895
  }, { playName: PLAY_NAME$4 });
3813
- result.costUsd += extractCost$3(search.result) ?? .01;
4896
+ result.costUsd += search.result.cost ?? 0;
3814
4897
  for (const hit of search.result.results ?? []) {
3815
4898
  if (!hit.url || seenUrls.has(hit.url)) continue;
3816
4899
  seenUrls.add(hit.url);
@@ -3901,11 +4984,23 @@ async function runJobChangeFinder(opts) {
3901
4984
  result.droppedEnrichment++;
3902
4985
  continue;
3903
4986
  }
4987
+ const skip = shouldSkipFindEmail({
4988
+ fullName: extract.fullName,
4989
+ companyDomain: domain
4990
+ });
4991
+ if (!skip.ok) {
4992
+ result.droppedEnrichment++;
4993
+ logEvent("finder.skipped_findemail", {
4994
+ name: PLAY_NAME$4,
4995
+ reason: skip.reason
4996
+ }, "info");
4997
+ continue;
4998
+ }
3904
4999
  const found = await findEmail({
3905
5000
  fullName: extract.fullName,
3906
5001
  companyDomain: domain
3907
5002
  }, { playName: PLAY_NAME$4 });
3908
- result.costUsd += extractCost$3(found.result) ?? .05;
5003
+ result.costUsd += found.result.cost ?? 0;
3909
5004
  if (!found.result.found || !found.result.email) {
3910
5005
  result.droppedEnrichment++;
3911
5006
  continue;
@@ -3920,12 +5015,19 @@ async function runJobChangeFinder(opts) {
3920
5015
  continue;
3921
5016
  }
3922
5017
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$4 });
3923
- result.costUsd += extractCost$3(verified.result) ?? .01;
5018
+ result.costUsd += verified.result.cost ?? 0;
3924
5019
  if (!verified.result.deliverable) {
3925
5020
  result.droppedEnrichment++;
3926
5021
  continue;
3927
5022
  }
5023
+ const enr = await enrichVerifiedContact(email, {
5024
+ playName: PLAY_NAME$4,
5025
+ errKindPrefix: "job-change"
5026
+ });
5027
+ result.costUsd += enr.costUsd;
5028
+ const phone = (extract.phone || null) ?? enr.phone;
3928
5029
  let linkedinUrl = isLinkedInProfileUrl(extract.linkedinUrl) ? extract.linkedinUrl : null;
5030
+ linkedinUrl = linkedinUrl ?? enr.linkedinUrl;
3929
5031
  if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
3930
5032
  fullName: extract.fullName,
3931
5033
  disambiguators: [extract.newCompany],
@@ -3942,7 +5044,7 @@ async function runJobChangeFinder(opts) {
3942
5044
  ...extract.previousRole ? { previousRole: extract.previousRole } : {},
3943
5045
  ...extract.previousCompany ? { previousCompany: extract.previousCompany } : {},
3944
5046
  ...linkedinUrl ? { linkedinUrl } : {},
3945
- ...extract.phone ? { phone: extract.phone } : {}
5047
+ ...phone ? { phone } : {}
3946
5048
  };
3947
5049
  if (ledger.enqueueTarget({
3948
5050
  playName: PLAY_NAME$4,
@@ -3968,11 +5070,6 @@ function parseJobChangeExtract(raw) {
3968
5070
  summary: null
3969
5071
  });
3970
5072
  }
3971
- function extractCost$3(r) {
3972
- if (!r || typeof r !== "object") return void 0;
3973
- const v = r["cost"];
3974
- return typeof v === "number" ? v : void 0;
3975
- }
3976
5073
  //#endregion
3977
5074
  //#region ../../packages/find/src/hiring-signal.ts
3978
5075
  const PLAY_NAME$3 = "hiring-signal";
@@ -4019,7 +5116,7 @@ async function runHiringSignalFinder(opts) {
4019
5116
  query,
4020
5117
  maxResults: Math.min(15, limit)
4021
5118
  }, { playName: PLAY_NAME$3 });
4022
- result.costUsd += extractCost$2(search.result) ?? .01;
5119
+ result.costUsd += search.result.cost ?? 0;
4023
5120
  for (const hit of search.result.results ?? []) {
4024
5121
  if (!hit.url || seen.has(hit.url) || !isAtsUrl(hit.url)) continue;
4025
5122
  seen.add(hit.url);
@@ -4079,7 +5176,7 @@ async function runHiringSignalFinder(opts) {
4079
5176
  let extract;
4080
5177
  try {
4081
5178
  const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$3 });
4082
- result.costUsd += extractCost$2(read.result) ?? .02;
5179
+ result.costUsd += read.result.cost ?? 0;
4083
5180
  extract = parseHiringSignalExtract((await complete({
4084
5181
  messages: [{
4085
5182
  role: "system",
@@ -4116,11 +5213,24 @@ async function runHiringSignalFinder(opts) {
4116
5213
  result.droppedEnrichment++;
4117
5214
  continue;
4118
5215
  }
4119
- const found = await findEmail(extract.hiringManagerName && extract.hiringManagerName.length > 0 ? {
4120
- fullName: extract.hiringManagerName,
5216
+ const managerName = extract.hiringManagerName && extract.hiringManagerName.length > 0 ? extract.hiringManagerName : null;
5217
+ const skip = shouldSkipFindEmail({
5218
+ fullName: managerName,
5219
+ companyDomain: domain
5220
+ });
5221
+ if (!skip.ok) {
5222
+ result.droppedEnrichment++;
5223
+ logEvent("finder.skipped_findemail", {
5224
+ name: PLAY_NAME$3,
5225
+ reason: skip.reason
5226
+ }, "info");
5227
+ continue;
5228
+ }
5229
+ const found = await findEmail(managerName ? {
5230
+ fullName: managerName,
4121
5231
  companyDomain: domain
4122
5232
  } : { companyDomain: domain }, { playName: PLAY_NAME$3 });
4123
- result.costUsd += extractCost$2(found.result) ?? .05;
5233
+ result.costUsd += found.result.cost ?? 0;
4124
5234
  if (!found.result.found || !found.result.email) {
4125
5235
  result.droppedEnrichment++;
4126
5236
  continue;
@@ -4135,13 +5245,20 @@ async function runHiringSignalFinder(opts) {
4135
5245
  continue;
4136
5246
  }
4137
5247
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$3 });
4138
- result.costUsd += extractCost$2(verified.result) ?? .01;
5248
+ result.costUsd += verified.result.cost ?? 0;
4139
5249
  if (!verified.result.deliverable) {
4140
5250
  result.droppedEnrichment++;
4141
5251
  continue;
4142
5252
  }
4143
5253
  const recipientName = extract.hiringManagerName ?? found.result.full_name ?? null;
5254
+ const enr = await enrichVerifiedContact(email, {
5255
+ playName: PLAY_NAME$3,
5256
+ errKindPrefix: "hiring-signal"
5257
+ });
5258
+ result.costUsd += enr.costUsd;
5259
+ const phone = (extract.phone || null) ?? enr.phone;
4144
5260
  let linkedinUrl = isLinkedInProfileUrl(extract.linkedinUrl) ? extract.linkedinUrl : null;
5261
+ linkedinUrl = linkedinUrl ?? enr.linkedinUrl;
4145
5262
  if (!linkedinUrl && recipientName) linkedinUrl = await findLinkedInUrl({
4146
5263
  fullName: recipientName,
4147
5264
  disambiguators: [extract.company],
@@ -4158,7 +5275,7 @@ async function runHiringSignalFinder(opts) {
4158
5275
  jobPostUrl: extract.jobUrl ?? hit.url,
4159
5276
  yourClaim,
4160
5277
  ...linkedinUrl ? { linkedinUrl } : {},
4161
- ...extract.phone ? { phone: extract.phone } : {}
5278
+ ...phone ? { phone } : {}
4162
5279
  };
4163
5280
  if (ledger.enqueueTarget({
4164
5281
  playName: PLAY_NAME$3,
@@ -4215,7 +5332,7 @@ async function resolveCorporateDomain(company, jobUrl, cache) {
4215
5332
  query: `"${company}" official site`,
4216
5333
  maxResults: 5
4217
5334
  }, { playName: PLAY_NAME$3 });
4218
- costUsd += extractCost$2(search.result) ?? .01;
5335
+ costUsd += search.result.cost ?? 0;
4219
5336
  for (const hit of search.result.results ?? []) {
4220
5337
  const host = pickCorporateHost(hit.url);
4221
5338
  if (host) {
@@ -4264,11 +5381,6 @@ function parseHiringSignalExtract(raw) {
4264
5381
  summary: null
4265
5382
  });
4266
5383
  }
4267
- function extractCost$2(r) {
4268
- if (!r || typeof r !== "object") return void 0;
4269
- const v = r["cost"];
4270
- return typeof v === "number" ? v : void 0;
4271
- }
4272
5384
  //#endregion
4273
5385
  //#region ../../packages/find/src/podcast-guest.ts
4274
5386
  const PLAY_NAME$2 = "podcast-guest";
@@ -4307,7 +5419,7 @@ async function runPodcastGuestFinder(opts) {
4307
5419
  query,
4308
5420
  maxResults: Math.min(15, limit)
4309
5421
  }, { playName: PLAY_NAME$2 });
4310
- result.costUsd += extractCost$1(search.result) ?? .01;
5422
+ result.costUsd += search.result.cost ?? 0;
4311
5423
  for (const hit of search.result.results ?? []) {
4312
5424
  if (!hit.url || seen.has(hit.url)) continue;
4313
5425
  seen.add(hit.url);
@@ -4373,7 +5485,7 @@ async function runPodcastGuestFinder(opts) {
4373
5485
  };
4374
5486
  if (!opts.skipRead) {
4375
5487
  const read = await webRead({ url: hit.url }, { playName: PLAY_NAME$2 });
4376
- result.costUsd += extractCost$1(read.result) ?? .02;
5488
+ result.costUsd += read.result.cost ?? 0;
4377
5489
  payload = {
4378
5490
  ...payload,
4379
5491
  markdown: (read.result.markdown ?? "").slice(0, 12e3)
@@ -4402,11 +5514,23 @@ async function runPodcastGuestFinder(opts) {
4402
5514
  result.droppedEnrichment++;
4403
5515
  continue;
4404
5516
  }
5517
+ const skip = shouldSkipFindEmail({
5518
+ fullName: extract.guestName,
5519
+ companyDomain: extract.guestCompanyDomain
5520
+ });
5521
+ if (!skip.ok) {
5522
+ result.droppedEnrichment++;
5523
+ logEvent("finder.skipped_findemail", {
5524
+ name: PLAY_NAME$2,
5525
+ reason: skip.reason
5526
+ }, "info");
5527
+ continue;
5528
+ }
4405
5529
  const found = await findEmail({
4406
5530
  fullName: extract.guestName,
4407
5531
  companyDomain: extract.guestCompanyDomain
4408
5532
  }, { playName: PLAY_NAME$2 });
4409
- result.costUsd += extractCost$1(found.result) ?? .05;
5533
+ result.costUsd += found.result.cost ?? 0;
4410
5534
  if (!found.result.found || !found.result.email) {
4411
5535
  result.droppedEnrichment++;
4412
5536
  continue;
@@ -4421,12 +5545,19 @@ async function runPodcastGuestFinder(opts) {
4421
5545
  continue;
4422
5546
  }
4423
5547
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$2 });
4424
- result.costUsd += extractCost$1(verified.result) ?? .01;
5548
+ result.costUsd += verified.result.cost ?? 0;
4425
5549
  if (!verified.result.deliverable) {
4426
5550
  result.droppedEnrichment++;
4427
5551
  continue;
4428
5552
  }
5553
+ const enr = await enrichVerifiedContact(email, {
5554
+ playName: PLAY_NAME$2,
5555
+ errKindPrefix: "podcast-guest"
5556
+ });
5557
+ result.costUsd += enr.costUsd;
5558
+ const phone = (extract.phone || null) ?? enr.phone;
4429
5559
  let linkedinUrl = isLinkedInProfileUrl(extract.linkedinUrl) ? extract.linkedinUrl : null;
5560
+ linkedinUrl = linkedinUrl ?? enr.linkedinUrl;
4430
5561
  if (!linkedinUrl) linkedinUrl = await findLinkedInUrl({
4431
5562
  fullName: extract.guestName,
4432
5563
  disambiguators: [extract.podcastName],
@@ -4443,7 +5574,7 @@ async function runPodcastGuestFinder(opts) {
4443
5574
  episodeTitle: extract.episodeTitle ?? hit.title,
4444
5575
  hookQuote: (extract.summary ?? hit.description ?? "").slice(0, 240),
4445
5576
  ...linkedinUrl ? { linkedinUrl } : {},
4446
- ...extract.phone ? { phone: extract.phone } : {}
5577
+ ...phone ? { phone } : {}
4447
5578
  };
4448
5579
  if (ledger.enqueueTarget({
4449
5580
  playName: PLAY_NAME$2,
@@ -4471,11 +5602,6 @@ function parsePodcastGuestExtract(raw) {
4471
5602
  summary: null
4472
5603
  });
4473
5604
  }
4474
- function extractCost$1(r) {
4475
- if (!r || typeof r !== "object") return void 0;
4476
- const v = r["cost"];
4477
- return typeof v === "number" ? v : void 0;
4478
- }
4479
5605
  //#endregion
4480
5606
  //#region ../../packages/find/src/breakup-revive.ts
4481
5607
  const PLAY_NAME$1 = "breakup-revive";
@@ -4972,7 +6098,7 @@ function parseEnvKeys(content) {
4972
6098
  * directly from package.json / pyproject.toml / requirements.txt /
4973
6099
  * .env.example via the GitHub Contents API. Free, fast, deterministic.
4974
6100
  */
4975
- const PLAY_NAME = "competitor-switch";
6101
+ const PLAY_NAME = "stack-consolidation";
4976
6102
  /**
4977
6103
  * Process a single candidate through the full pipeline. Mutates ctx.result.
4978
6104
  * Never throws — internal exceptions become droppedEnrichment increments via
@@ -4991,7 +6117,7 @@ async function processRepoCandidate(hit, ctx) {
4991
6117
  return;
4992
6118
  }
4993
6119
  const ledger = getLedger();
4994
- if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {
6120
+ if (ledger.isQueueDuplicate("stack-consolidation", hit.url) || ledger.isQueueDuplicate("competitor-switch", hit.url)) {
4995
6121
  result.droppedDuplicate++;
4996
6122
  return;
4997
6123
  }
@@ -5059,20 +6185,24 @@ async function processRepoCandidate(hit, ctx) {
5059
6185
  stackDetected: stack.detected,
5060
6186
  summary: null
5061
6187
  };
6188
+ const directSet = new Set((ctx.directCompetitors ?? []).map((s) => s.toLowerCase()));
6189
+ const matchedCompetitor = extract.stackDetected.find((v) => directSet.has(v.toLowerCase()));
6190
+ const playName = matchedCompetitor ? "competitor-switch" : "stack-consolidation";
5062
6191
  const contact = await resolveContact({
5063
6192
  extract,
5064
6193
  repoUrl: hit.url,
5065
6194
  ghUser: ghUserInfo,
5066
6195
  accumCost,
5067
6196
  useDeepResearch: ctx.useDeepResearch,
5068
- errKindPrefix
6197
+ errKindPrefix,
6198
+ playName
5069
6199
  });
5070
6200
  if (!contact) {
5071
6201
  result.droppedEnrichment++;
5072
6202
  return;
5073
6203
  }
5074
6204
  if (isDuplicate({
5075
- playName: PLAY_NAME,
6205
+ playName,
5076
6206
  dedupeKey: hit.url,
5077
6207
  prospectEmail: contact.email
5078
6208
  })) {
@@ -5081,7 +6211,7 @@ async function processRepoCandidate(hit, ctx) {
5081
6211
  }
5082
6212
  let verified;
5083
6213
  try {
5084
- verified = await verifyEmail({ email: contact.email }, { playName: PLAY_NAME });
6214
+ verified = await verifyEmail({ email: contact.email }, { playName });
5085
6215
  } catch (err) {
5086
6216
  logEvent("error.swallowed", {
5087
6217
  kind: `${errKindPrefix}.verify_email`,
@@ -5090,30 +6220,50 @@ async function processRepoCandidate(hit, ctx) {
5090
6220
  result.droppedEnrichment++;
5091
6221
  return;
5092
6222
  }
5093
- accumCost(extractCost(verified.result) ?? .01);
6223
+ accumCost(verified.result.cost ?? 0);
5094
6224
  if (!verified.result.deliverable) {
5095
6225
  result.droppedEnrichment++;
5096
6226
  return;
5097
6227
  }
6228
+ if (!contact.phone || !contact.linkedinUrl) {
6229
+ const enr = await enrichVerifiedContact(contact.email, {
6230
+ playName,
6231
+ errKindPrefix
6232
+ });
6233
+ accumCost(enr.costUsd);
6234
+ contact.phone = contact.phone ?? enr.phone;
6235
+ contact.linkedinUrl = contact.linkedinUrl ?? enr.linkedinUrl;
6236
+ }
5098
6237
  const stackLine = extract.stackDetected.join(", ");
5099
6238
  const vendorCount = extract.stackDetected.length;
5100
- const evidenceText = `Their repo stitches together ${stackLine} — ${vendorCount} separate auth surfaces and ${vendorCount} bills to manage.`;
5101
- const competitorLabel = extract.stackDetected[0];
5102
6239
  const companyFallback = contact.domain ?? contact.email.split("@")[1] ?? "";
5103
- const target = {
5104
- name: extract.authorFullName ?? contact.fullName ?? extract.githubHandle ?? "there",
6240
+ const name = extract.authorFullName ?? contact.fullName ?? extract.githubHandle ?? "there";
6241
+ const company = extract.companyName ?? extract.githubHandle ?? companyFallback;
6242
+ const contactExtras = {
6243
+ ...contact.linkedinUrl ? { linkedinUrl: contact.linkedinUrl } : {},
6244
+ ...contact.phone ? { phone: contact.phone } : {}
6245
+ };
6246
+ const target = matchedCompetitor ? {
6247
+ name,
5105
6248
  email: contact.email,
5106
- company: extract.companyName ?? extract.githubHandle ?? companyFallback,
5107
- competitor: competitorLabel,
6249
+ company,
6250
+ competitor: matchedCompetitor,
5108
6251
  evidenceUrl: hit.url,
5109
- evidenceText,
6252
+ evidenceText: `Their public repo uses ${matchedCompetitor} (found in ${stack.manifestsFound.join(", ")}).`,
5110
6253
  yourEdge: ctx.yourEdge,
5111
- ...contact.linkedinUrl ? { linkedinUrl: contact.linkedinUrl } : {},
5112
- ...contact.phone ? { phone: contact.phone } : {}
6254
+ ...contactExtras
6255
+ } : {
6256
+ name,
6257
+ email: contact.email,
6258
+ company,
6259
+ vendorStack: stackLine,
6260
+ evidenceUrl: hit.url,
6261
+ yourEdge: ctx.yourEdge,
6262
+ ...contactExtras
5113
6263
  };
5114
6264
  const notes = truncate(`${ctx.notesPrefix}: ${stackLine} (${vendorCount} vendors) — ${snippetFilter.reason}`, 220);
5115
6265
  if (ledger.enqueueTarget({
5116
- playName: PLAY_NAME,
6266
+ playName,
5117
6267
  payload: target,
5118
6268
  dedupeKey: hit.url,
5119
6269
  source: ctx.sourceTag,
@@ -5138,10 +6288,11 @@ async function processRepoCandidate(hit, ctx) {
5138
6288
  async function resolveContact(args) {
5139
6289
  const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;
5140
6290
  const errKindPrefix = args.errKindPrefix ?? "repo-pipeline";
6291
+ const playName = args.playName ?? PLAY_NAME;
5141
6292
  const extractDomain = extract.companyDomain ?? extract.personalDomain ?? null;
5142
6293
  let discoveredLinkedinUrl = null;
5143
6294
  if (extractDomain) {
5144
- const direct = await tryFindEmail(extractDomain, extract, accumCost, errKindPrefix);
6295
+ const direct = await tryFindEmail(extractDomain, extract, accumCost, errKindPrefix, playName);
5145
6296
  if (direct) return {
5146
6297
  ...direct,
5147
6298
  domain: extractDomain,
@@ -5169,8 +6320,8 @@ async function resolveContact(args) {
5169
6320
  if (linkedinUrl) {
5170
6321
  discoveredLinkedinUrl = linkedinUrl;
5171
6322
  try {
5172
- const enriched = await enrichProfile({ linkedinUrl }, { playName: PLAY_NAME });
5173
- accumCost(extractCost(enriched.result) ?? .005);
6323
+ const enriched = await enrichProfile({ linkedinUrl }, { playName });
6324
+ accumCost(enriched.result.cost ?? 0);
5174
6325
  const profile = enriched.result.profile;
5175
6326
  const enrichedPhone = extractFirstPhone(profile);
5176
6327
  if (profile?.email) return {
@@ -5184,7 +6335,7 @@ async function resolveContact(args) {
5184
6335
  const viaEnriched = await tryFindEmail(profile.company_domain, {
5185
6336
  ...extract,
5186
6337
  authorFullName: profile.full_name ?? extract.authorFullName
5187
- }, accumCost, errKindPrefix);
6338
+ }, accumCost, errKindPrefix, playName);
5188
6339
  if (viaEnriched) return {
5189
6340
  ...viaEnriched,
5190
6341
  domain: profile.company_domain,
@@ -5211,8 +6362,8 @@ async function resolveContact(args) {
5211
6362
  socialMediaUrl: repoUrl,
5212
6363
  ...hasName ? { name: extract.authorFullName } : {},
5213
6364
  ...hasCompany ? { company: companyForGate } : {}
5214
- }, { playName: PLAY_NAME });
5215
- accumCost(extractCost(dr.result) ?? .05);
6365
+ }, { playName });
6366
+ accumCost(dr.result.cost ?? 0);
5216
6367
  const enr = dr.result.result?.enrichment;
5217
6368
  const drEmail = enr?.best_work_email ?? enr?.best_personal_email ?? enr?.altemails?.[0] ?? null;
5218
6369
  if (!drEmail) return null;
@@ -5241,14 +6392,26 @@ async function resolveContact(args) {
5241
6392
  * transient network errors. Either failure mode returns null so the caller
5242
6393
  * falls through to the next contact-resolution tier.
5243
6394
  */
5244
- async function tryFindEmail(domain, extract, accumCost, errKindPrefix) {
6395
+ async function tryFindEmail(domain, extract, accumCost, errKindPrefix, playName) {
5245
6396
  if (!extract.authorFullName || extract.authorFullName.length === 0) return null;
6397
+ const skip = shouldSkipFindEmail({
6398
+ fullName: extract.authorFullName,
6399
+ companyDomain: domain
6400
+ });
6401
+ if (!skip.ok) {
6402
+ logEvent("finder.skipped_findemail", {
6403
+ name: playName,
6404
+ reason: skip.reason,
6405
+ kind: `${errKindPrefix}.find_email`
6406
+ }, "info");
6407
+ return null;
6408
+ }
5246
6409
  let found;
5247
6410
  try {
5248
6411
  found = await findEmail({
5249
6412
  fullName: extract.authorFullName,
5250
6413
  companyDomain: domain
5251
- }, { playName: PLAY_NAME });
6414
+ }, { playName });
5252
6415
  } catch (err) {
5253
6416
  logEvent("error.swallowed", {
5254
6417
  kind: `${errKindPrefix}.find_email`,
@@ -5257,7 +6420,7 @@ async function tryFindEmail(domain, extract, accumCost, errKindPrefix) {
5257
6420
  }, "warn");
5258
6421
  return null;
5259
6422
  }
5260
- accumCost(extractCost(found.result) ?? .005);
6423
+ accumCost(found.result.cost ?? 0);
5261
6424
  if (found.result.found && found.result.email) return {
5262
6425
  email: found.result.email,
5263
6426
  fullName: found.result.full_name ?? null
@@ -5283,11 +6446,6 @@ function describeForIcp(hit) {
5283
6446
  function truncate(s, max) {
5284
6447
  return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
5285
6448
  }
5286
- function extractCost(r) {
5287
- if (!r || typeof r !== "object") return void 0;
5288
- const v = r["cost"];
5289
- return typeof v === "number" ? v : void 0;
5290
- }
5291
6449
  //#endregion
5292
6450
  //#region ../../packages/find/src/_repo-utils.ts
5293
6451
  /**
@@ -5446,6 +6604,7 @@ async function runGitHubTopicsFinder(opts) {
5446
6604
  const ctx = {
5447
6605
  icp,
5448
6606
  vocab: opts.vendors,
6607
+ directCompetitors: opts.directCompetitors ?? [],
5449
6608
  yourEdge: opts.yourEdge,
5450
6609
  minVendors,
5451
6610
  useDeepResearch,
@@ -5497,30 +6656,101 @@ const TRIGGERS = [
5497
6656
  defaultIntervalMs: 24 * ONE_HOUR,
5498
6657
  enabledByDefault: false,
5499
6658
  defaultConfig: {
5500
- cohort: "",
5501
- cohortLabel: "",
6659
+ cohorts: [
6660
+ {
6661
+ cohort: "yc-w26",
6662
+ cohortLabel: "YC W26"
6663
+ },
6664
+ {
6665
+ cohort: "yc-f25",
6666
+ cohortLabel: "YC F25"
6667
+ },
6668
+ {
6669
+ cohort: "techstars-spring-2026",
6670
+ cohortLabel: "Techstars Spring 2026"
6671
+ },
6672
+ {
6673
+ cohort: "techstars-fall-2025",
6674
+ cohortLabel: "Techstars Fall 2025"
6675
+ },
6676
+ {
6677
+ cohort: "antler-q1-2026",
6678
+ cohortLabel: "Antler Q1 2026"
6679
+ },
6680
+ {
6681
+ cohort: "antler-q4-2025",
6682
+ cohortLabel: "Antler Q4 2025"
6683
+ },
6684
+ {
6685
+ cohort: "500global-batch-38",
6686
+ cohortLabel: "500 Global Batch 38"
6687
+ },
6688
+ {
6689
+ cohort: "500global-batch-37",
6690
+ cohortLabel: "500 Global Batch 37"
6691
+ },
6692
+ {
6693
+ cohort: "ai-grant-cohort-5",
6694
+ cohortLabel: "AI Grant Cohort 5"
6695
+ },
6696
+ {
6697
+ cohort: "ai-grant-cohort-4",
6698
+ cohortLabel: "AI Grant Cohort 4"
6699
+ },
6700
+ {
6701
+ cohort: "spc-2026-1",
6702
+ cohortLabel: "South Park Commons F1 2026-1"
6703
+ },
6704
+ {
6705
+ cohort: "spc-2025-2",
6706
+ cohortLabel: "South Park Commons F1 2025-2"
6707
+ },
6708
+ {
6709
+ cohort: "neo-class-2026",
6710
+ cohortLabel: "Neo Class 2026"
6711
+ },
6712
+ {
6713
+ cohort: "neo-class-2025",
6714
+ cohortLabel: "Neo Class 2025"
6715
+ }
6716
+ ],
5502
6717
  limit: 25,
5503
- maxCostUsd: 5
6718
+ maxCostUsd: 15
5504
6719
  },
5505
- configBrief: "Pulls an accelerator cohort directory, ICP-filters companies, finds founder contact, enqueues for outreach. SHIPS EMPTY — pick a cohort that matches your ICP. Each accelerator surfaces a different founder population: YC for AI/infra-heavy startups, Techstars for vertical SaaS + corporate-partnered batches, Antler for solo founders + day-zero, AI Grant for AI-only research-product founders, SPC / Neo for senior-engineer founders, 500 Global for international + emerging markets. Config: `cohort` (tag — e.g. `yc-w26`, `techstars-toronto-2025`, `antler-nyc-q1-2026`, `ai-grant-2026`), `cohortLabel` (human label fed to email + search queries; auto-derived from cohort when not set), optional `adapter` (`yc-oss` | `websearch`; auto-picked from cohort prefix — yc-* tags use the free yc-oss/api directory, everything else falls back to web search), `limit`, `maxCostUsd`. STRATEGIST DUTY: when proposing this trigger, anchor the cohort recommendation in the founder's ICP — don't reflexively pick YC. If multiple accelerators fit, propose the top match and mention 1-2 alternatives in prose so the founder can swap.",
6720
+ configBrief: "Sweeps every known incubator (YC, Techstars, Antler, 500 Global, AI Grant, SPC, Neo) at its latest + previous-latest cohorts in one run. Config: `cohorts` (array of `{cohort, cohortLabel}` — defaults to the 14-entry curated list; edit to add/remove batches as new cohorts announce), optional `cohort` + `cohortLabel` (legacy single-cohort shape; still accepted), optional `adapter` (`yc-oss` | `websearch`; auto-picked per cohort — yc-* tags use the free yc-oss/api directory, everything else falls back to web search), `limit` (global enqueue cap across all cohorts), `maxCostUsd`. Per-cohort failures (spotty incubator, network blip) log and continue; the run only halts when EVERY cohort returns 0 candidates. ROTATION: the default list goes stale within ~3 months — edit when YC announces W27, Techstars rolls Fall 2026, etc. STRATEGIST DUTY: when the founder's ICP overlaps strongly with one incubator population, narrow the cohorts list rather than sweeping all seven — e.g. AI/infra startups → keep yc-* + ai-grant-*, drop the rest.",
5506
6721
  readiness: (cfg) => {
5507
- const cohort = cfg["cohort"];
5508
- if (typeof cohort !== "string" || cohort.trim().length === 0) return {
6722
+ const cohorts = Array.isArray(cfg["cohorts"]) ? cfg["cohorts"] : null;
6723
+ const legacyCohort = typeof cfg["cohort"] === "string" ? cfg["cohort"].trim() : "";
6724
+ if ((!cohorts || cohorts.length === 0) && legacyCohort.length === 0) return {
5509
6725
  ready: false,
5510
- reason: "set `cohort` (ask the strategist to propose one tuned to your ICP)"
6726
+ reason: "set `cohorts[]` (or legacy `cohort`)"
5511
6727
  };
5512
6728
  return { ready: true };
5513
6729
  },
5514
6730
  run: (cfg) => {
5515
- const cohort = cfg["cohort"] ?? "yc-w26";
5516
- const labelFromCfg = typeof cfg["cohortLabel"] === "string" ? cfg["cohortLabel"].trim() : "";
6731
+ const cohorts = (Array.isArray(cfg["cohorts"]) ? cfg["cohorts"] : []).map((entry) => {
6732
+ if (!entry || typeof entry !== "object") return null;
6733
+ const e = entry;
6734
+ const cohort = typeof e["cohort"] === "string" ? e["cohort"].trim() : "";
6735
+ if (cohort.length === 0) return null;
6736
+ const labelRaw = typeof e["cohortLabel"] === "string" ? e["cohortLabel"].trim() : "";
6737
+ return {
6738
+ cohort,
6739
+ cohortLabel: labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort)
6740
+ };
6741
+ }).filter((e) => e !== null);
6742
+ const legacyCohort = typeof cfg["cohort"] === "string" ? cfg["cohort"] : "";
6743
+ const legacyLabel = typeof cfg["cohortLabel"] === "string" ? cfg["cohortLabel"] : "";
5517
6744
  return runAcceleratorBatchFinder({
5518
6745
  dryRun: false,
5519
- cohort,
5520
- cohortLabel: labelFromCfg.length > 0 ? labelFromCfg : deriveCohortLabel(cohort),
6746
+ ...cohorts.length > 0 ? { cohorts } : {},
6747
+ ...cohorts.length === 0 && legacyCohort.trim().length > 0 ? {
6748
+ cohort: legacyCohort,
6749
+ cohortLabel: legacyLabel
6750
+ } : {},
5521
6751
  ...cfg["adapter"] === "yc-oss" || cfg["adapter"] === "websearch" ? { adapter: cfg["adapter"] } : {},
5522
6752
  limit: cfg["limit"] ?? 25,
5523
- maxCostUsd: cfg["maxCostUsd"] ?? 5
6753
+ maxCostUsd: cfg["maxCostUsd"] ?? 15
5524
6754
  });
5525
6755
  }
5526
6756
  },
@@ -5628,6 +6858,7 @@ const TRIGGERS = [
5628
6858
  defaultConfig: {
5629
6859
  topics: [],
5630
6860
  vendors: [],
6861
+ directCompetitors: [],
5631
6862
  yourEdge: "",
5632
6863
  minStars: 5,
5633
6864
  maxAgeDays: 90,
@@ -5637,7 +6868,7 @@ const TRIGGERS = [
5637
6868
  limit: 25,
5638
6869
  maxCostUsd: 5
5639
6870
  },
5640
- configBrief: "Discovers repos via GitHub Topic pages (`topic:<slug>` queries on the GitHub Search API), then scans each candidate's package.json / pyproject.toml / requirements.txt / .env.example via the GitHub Contents API to detect which API vendors the repo actually uses. Feeds the competitor-switch motion play. Required config: `topics` (GitHub topic slugs the founder's ICP overlaps with — lowercase, hyphenated, EXACT GitHub-canonical form; singular vs plural matters), `vendors` (the founder's competitive landscape — the API vendors they aim to replace), `yourEdge` (one-sentence pitch handed to the email). VOCAB SEMANTICS: each `vendors` string is substring-matched (case-insensitive) against manifest deps + env-var keys — so `twilio` matches `twilio`, `twilio-node`, `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is NO hardcoded vendor list; oneshot-gtm is a generic founder tool and competitive vocabularies vary entirely by founder. STRATEGIST DUTY: when you (the strategist) have enough context about the founder's product/ICP, proactively propose BOTH `topics` AND `vendors` via apply-config — topics are GitHub category slugs aligned to ICP; vendors are the API competitors the founder replaces. The founder shouldn't have to enumerate either by hand. Other config: `minStars` (filter, default 5), `maxAgeDays` (default 90), `minVendors` (gate: how many distinct vocab vendors must match in a candidate's manifests; default 1), `concurrency` (in-flight workers; default 3), `useDeepResearch` (default true), `limit`, `maxCostUsd`.",
6871
+ configBrief: "Discovers repos via GitHub Topic pages (`topic:<slug>` queries on the GitHub Search API), then scans each candidate's package.json / pyproject.toml / requirements.txt / .env.example via the GitHub Contents API to detect which API vendors the repo actually uses. Routes each candidate to one of two motion plays: stack-consolidation (default — pitch collapsing the vendor sprawl into one SDK) or competitor-switch (when a detected vendor is on `directCompetitors` — a head-on 'switch from X' pitch). Required config: `topics` (GitHub topic slugs the founder's ICP overlaps with — lowercase, hyphenated, EXACT GitHub-canonical form; singular vs plural matters), `vendors` (the founder's competitive landscape — the API vendors they aim to replace), `yourEdge` (one-sentence pitch handed to the email). Optional `directCompetitors`: a subset of `vendors` the founder competes with head-on (same canonical spelling, matched case-insensitively); a candidate using one routes to competitor-switch instead of stack-consolidation. Empty by default, so every candidate is stack-consolidation until set. VOCAB SEMANTICS: each `vendors` string is substring-matched (case-insensitive) against manifest deps + env-var keys — so `twilio` matches `twilio`, `twilio-node`, `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is NO hardcoded vendor list; oneshot-gtm is a generic founder tool and competitive vocabularies vary entirely by founder. STRATEGIST DUTY: when you (the strategist) have enough context about the founder's product/ICP, proactively propose BOTH `topics` AND `vendors` via apply-config — topics are GitHub category slugs aligned to ICP; vendors are the API competitors the founder replaces. The founder shouldn't have to enumerate either by hand. Other config: `minStars` (filter, default 5), `maxAgeDays` (default 90), `minVendors` (gate: how many distinct vocab vendors must match in a candidate's manifests; default 1), `concurrency` (in-flight workers; default 3), `useDeepResearch` (default true), `limit`, `maxCostUsd`.",
5641
6872
  readiness: (cfg) => {
5642
6873
  const topics = cfg["topics"];
5643
6874
  if (!Array.isArray(topics) || topics.length === 0) return {
@@ -5661,6 +6892,7 @@ const TRIGGERS = [
5661
6892
  dryRun: false,
5662
6893
  topics: Array.isArray(cfg["topics"]) ? cfg["topics"].filter((t) => typeof t === "string") : [],
5663
6894
  vendors: Array.isArray(cfg["vendors"]) ? cfg["vendors"].filter((v) => typeof v === "string") : [],
6895
+ directCompetitors: Array.isArray(cfg["directCompetitors"]) ? cfg["directCompetitors"].filter((v) => typeof v === "string") : [],
5664
6896
  yourEdge: typeof cfg["yourEdge"] === "string" ? cfg["yourEdge"] : "",
5665
6897
  minStars: cfg["minStars"] ?? 5,
5666
6898
  maxAgeDays: cfg["maxAgeDays"] ?? 90,
@@ -5873,24 +7105,152 @@ async function runTriggerNow(name) {
5873
7105
  at: (/* @__PURE__ */ new Date()).toISOString()
5874
7106
  }
5875
7107
  });
5876
- logEvent("trigger.run.error", {
5877
- name,
5878
- duration_ms: Date.now() - startedAt,
5879
- message_120: message.slice(0, 120)
5880
- }, "error");
5881
- return {
5882
- name,
5883
- fired: true,
5884
- error: message,
5885
- nextDueInMs: intervalMs
5886
- };
7108
+ logEvent("trigger.run.error", {
7109
+ name,
7110
+ duration_ms: Date.now() - startedAt,
7111
+ message_120: message.slice(0, 120)
7112
+ }, "error");
7113
+ return {
7114
+ name,
7115
+ fired: true,
7116
+ error: message,
7117
+ nextDueInMs: intervalMs
7118
+ };
7119
+ }
7120
+ }
7121
+ /**
7122
+ * Run every registered trigger that's due. Persists last_polled_at + last_run_summary.
7123
+ * Returns one outcome per trigger so the caller can log + decide sleep duration.
7124
+ */
7125
+ async function runDueTriggers() {
7126
+ startRun();
7127
+ const ledger = getLedger();
7128
+ const now = Date.now();
7129
+ const outcomes = [];
7130
+ logEvent("watch.tick.start", { trigger_count: TRIGGERS.length });
7131
+ for (const spec of TRIGGERS) {
7132
+ const stored = ledger.getTrigger(spec.name);
7133
+ const defaultEnabled = spec.enabledByDefault !== false;
7134
+ if (!stored) ledger.upsertTrigger({
7135
+ name: spec.name,
7136
+ configJson: JSON.stringify(spec.defaultConfig),
7137
+ enabled: defaultEnabled
7138
+ });
7139
+ const config = stored?.config_json ? JSON.parse(stored.config_json) : spec.defaultConfig;
7140
+ const intervalMs = effectiveIntervalMs(spec, config);
7141
+ if (!(stored ? Boolean(stored.enabled) : defaultEnabled)) {
7142
+ outcomes.push({
7143
+ name: spec.name,
7144
+ fired: false,
7145
+ nextDueInMs: intervalMs
7146
+ });
7147
+ continue;
7148
+ }
7149
+ const readiness = checkReadiness(spec, config);
7150
+ if (!readiness.ready) {
7151
+ outcomes.push({
7152
+ name: spec.name,
7153
+ fired: false,
7154
+ nextDueInMs: intervalMs
7155
+ });
7156
+ logEvent("trigger.run.skipped", {
7157
+ name: spec.name,
7158
+ source: "watch",
7159
+ reason: readiness.reason
7160
+ });
7161
+ continue;
7162
+ }
7163
+ const dueAt = (stored?.last_polled_at ? new Date(stored.last_polled_at).getTime() : 0) + intervalMs;
7164
+ if (now < dueAt) {
7165
+ outcomes.push({
7166
+ name: spec.name,
7167
+ fired: false,
7168
+ nextDueInMs: dueAt - now
7169
+ });
7170
+ continue;
7171
+ }
7172
+ const claimNowIso = (/* @__PURE__ */ new Date()).toISOString();
7173
+ const staleCutoffIso = new Date(Date.now() - MAX_RUN_AGE_MS).toISOString();
7174
+ if (!ledger.markTriggerRunning(spec.name, claimNowIso, staleCutoffIso)) {
7175
+ outcomes.push({
7176
+ name: spec.name,
7177
+ fired: false,
7178
+ nextDueInMs: intervalMs
7179
+ });
7180
+ logEvent("trigger.run.skipped", {
7181
+ name: spec.name,
7182
+ source: "watch",
7183
+ reason: "already-running"
7184
+ });
7185
+ continue;
7186
+ }
7187
+ const startedAt = Date.now();
7188
+ logEvent("trigger.run.start", {
7189
+ name: spec.name,
7190
+ source: "watch"
7191
+ });
7192
+ try {
7193
+ const result = await spec.run(config);
7194
+ ledger.updateTriggerLastPoll({
7195
+ name: spec.name,
7196
+ summary: result
7197
+ });
7198
+ logEvent("trigger.run.done", {
7199
+ name: spec.name,
7200
+ duration_ms: Date.now() - startedAt,
7201
+ candidates: result.candidates,
7202
+ enqueued: result.enqueued,
7203
+ dropped_icp: result.droppedIcp,
7204
+ dropped_dup: result.droppedDuplicate,
7205
+ dropped_enrich: result.droppedEnrichment,
7206
+ cost_usd: result.costUsd,
7207
+ halted: result.halted ?? null
7208
+ });
7209
+ outcomes.push({
7210
+ name: spec.name,
7211
+ fired: true,
7212
+ result,
7213
+ nextDueInMs: intervalMs
7214
+ });
7215
+ } catch (err) {
7216
+ const message = err.message ?? "unknown error";
7217
+ ledger.updateTriggerLastPoll({
7218
+ name: spec.name,
7219
+ summary: {
7220
+ error: message,
7221
+ at: (/* @__PURE__ */ new Date()).toISOString()
7222
+ }
7223
+ });
7224
+ logEvent("trigger.run.error", {
7225
+ name: spec.name,
7226
+ duration_ms: Date.now() - startedAt,
7227
+ message_120: message.slice(0, 120)
7228
+ }, "error");
7229
+ outcomes.push({
7230
+ name: spec.name,
7231
+ fired: true,
7232
+ error: message,
7233
+ nextDueInMs: intervalMs
7234
+ });
7235
+ }
5887
7236
  }
7237
+ logEvent("watch.tick.done", { fired: outcomes.filter((o) => o.fired).length });
7238
+ return outcomes;
7239
+ }
7240
+ function nextSleepMs(outcomes) {
7241
+ if (outcomes.length === 0) return 3600 * 1e3;
7242
+ const min = Math.min(...outcomes.map((o) => o.nextDueInMs));
7243
+ return Math.max(6e4, Math.min(3600 * 1e3, min));
5888
7244
  }
5889
7245
  //#endregion
5890
7246
  //#region ../../packages/find/src/drain.ts
5891
7247
  /**
5892
7248
  * Pull approved rows for a play from target_queue, run them through the
5893
- * existing motion play, and mark each as sent (or rollback on error).
7249
+ * existing motion play one target at a time, persist the draft for every row
7250
+ * (sent OR lint-held OR per-target error), then flip status to `sent` only
7251
+ * for the rows whose draft actually shipped. Per-target dispatch isolates
7252
+ * SDK throws (e.g. JobTimeoutError on agent.email()) so one bad target
7253
+ * can't kill the rest of the batch.
5894
7254
  */
5895
7255
  async function drainQueue(opts) {
5896
7256
  const ledger = getLedger();
@@ -5904,110 +7264,159 @@ async function drainQueue(opts) {
5904
7264
  errors: []
5905
7265
  };
5906
7266
  if (rows.length === 0) return outcome;
5907
- try {
5908
- const sentIds = await dispatchPlay$1(opts, rows);
5909
- if (!opts.dryRun) {
5910
- for (const id of sentIds) {
5911
- const prospectId = backfillProspectId(rows.find((r) => r.id === id) ?? null);
7267
+ if (opts.playName === "accelerator-batch" && !opts.senderCohort) {
7268
+ outcome.errors.push({
7269
+ id: -1,
7270
+ message: "--sender-cohort is required for draining accelerator-batch"
7271
+ });
7272
+ return outcome;
7273
+ }
7274
+ if (!isSupportedPlay(opts.playName)) {
7275
+ outcome.errors.push({
7276
+ id: -1,
7277
+ message: `drain: unsupported play '${opts.playName}'`
7278
+ });
7279
+ return outcome;
7280
+ }
7281
+ for (const row of rows) {
7282
+ let draft;
7283
+ try {
7284
+ draft = await dispatchOneTarget(opts, row);
7285
+ } catch (err) {
7286
+ const msg = (err.message ?? "play failed").slice(0, 200);
7287
+ draft = {
7288
+ subject: "(error)",
7289
+ body: "",
7290
+ flags: [`error: ${msg}`],
7291
+ sent: false,
7292
+ receiptIds: []
7293
+ };
7294
+ outcome.errors.push({
7295
+ id: row.id,
7296
+ message: msg
7297
+ });
7298
+ }
7299
+ try {
7300
+ ledger.setQueueDraft({
7301
+ id: row.id,
7302
+ draft: {
7303
+ subject: draft.subject,
7304
+ body: draft.body,
7305
+ flags: draft.flags,
7306
+ sent: draft.sent,
7307
+ receiptIds: draft.receiptIds,
7308
+ dryRun: opts.dryRun
7309
+ }
7310
+ });
7311
+ if (draft.sent && !opts.dryRun) {
5912
7312
  ledger.setQueueStatus({
5913
- id,
7313
+ id: row.id,
5914
7314
  status: "sent"
5915
7315
  });
7316
+ const prospectId = backfillProspectId(row);
5916
7317
  if (prospectId != null) try {
5917
- ledger.setQueueProspectId(id, prospectId);
7318
+ ledger.setQueueProspectId(row.id, prospectId);
5918
7319
  } catch {}
7320
+ outcome.sent++;
5919
7321
  }
5920
- outcome.sent = sentIds.length;
5921
- } else outcome.sent = rows.length;
5922
- } catch (err) {
5923
- outcome.errors.push({
5924
- id: -1,
5925
- message: err.message ?? "drain failed"
5926
- });
7322
+ } catch (err) {
7323
+ outcome.errors.push({
7324
+ id: row.id,
7325
+ message: (err.message ?? "persist failed").slice(0, 200)
7326
+ });
7327
+ }
5927
7328
  }
7329
+ if (opts.dryRun) outcome.sent = rows.length;
5928
7330
  return outcome;
5929
7331
  }
5930
- async function dispatchPlay$1(opts, rows) {
7332
+ const SUPPORTED_PLAYS = new Set([
7333
+ "show-hn",
7334
+ "job-change",
7335
+ "post-funding",
7336
+ "accelerator-batch",
7337
+ "hiring-signal",
7338
+ "podcast-guest",
7339
+ "breakup-revive",
7340
+ "competitor-switch",
7341
+ "stack-consolidation"
7342
+ ]);
7343
+ function isSupportedPlay(name) {
7344
+ return SUPPORTED_PLAYS.has(name);
7345
+ }
7346
+ async function dispatchOneTarget(opts, row) {
5931
7347
  switch (opts.playName) {
5932
7348
  case "show-hn": {
5933
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5934
- return idsForSentDrafts((await runShowHn({
7349
+ const target = JSON.parse(row.payload_json);
7350
+ return firstDraft((await runShowHn({
5935
7351
  dryRun: opts.dryRun,
5936
- targets
5937
- })).drafted, rows, opts.dryRun);
7352
+ targets: [target]
7353
+ })).drafted);
5938
7354
  }
5939
7355
  case "job-change": {
5940
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5941
- return idsForSentDrafts((await runJobChange({
7356
+ const target = JSON.parse(row.payload_json);
7357
+ return firstDraft((await runJobChange({
5942
7358
  dryRun: opts.dryRun,
5943
- targets
5944
- })).drafted, rows, opts.dryRun);
7359
+ targets: [target]
7360
+ })).drafted);
5945
7361
  }
5946
7362
  case "post-funding": {
5947
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5948
- return idsForSentDrafts((await runPostFunding({
7363
+ const target = JSON.parse(row.payload_json);
7364
+ return firstDraft((await runPostFunding({
5949
7365
  dryRun: opts.dryRun,
5950
- targets
5951
- })).drafted, rows, opts.dryRun);
7366
+ targets: [target]
7367
+ })).drafted);
5952
7368
  }
5953
7369
  case "accelerator-batch": {
5954
- if (!opts.senderCohort) throw new Error("--sender-cohort is required for draining accelerator-batch");
5955
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5956
- return idsForSentDrafts((await runAcceleratorBatch({
7370
+ const target = JSON.parse(row.payload_json);
7371
+ return firstDraft((await runAcceleratorBatch({
5957
7372
  dryRun: opts.dryRun,
5958
- targets,
7373
+ targets: [target],
5959
7374
  senderCohort: opts.senderCohort,
5960
7375
  ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
5961
- })).drafted, rows, opts.dryRun);
7376
+ })).drafted);
5962
7377
  }
5963
7378
  case "hiring-signal": {
5964
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5965
- return idsForSentDrafts((await runHiringSignal({
7379
+ const target = JSON.parse(row.payload_json);
7380
+ return firstDraft((await runHiringSignal({
5966
7381
  dryRun: opts.dryRun,
5967
- targets
5968
- })).drafted, rows, opts.dryRun);
7382
+ targets: [target]
7383
+ })).drafted);
5969
7384
  }
5970
7385
  case "podcast-guest": {
5971
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5972
- return idsForSentDrafts((await runPodcastGuest({
7386
+ const target = JSON.parse(row.payload_json);
7387
+ return firstDraft((await runPodcastGuest({
5973
7388
  dryRun: opts.dryRun,
5974
- targets
5975
- })).drafted, rows, opts.dryRun);
7389
+ targets: [target]
7390
+ })).drafted);
5976
7391
  }
5977
7392
  case "breakup-revive": {
5978
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5979
- return idsForSentDrafts((await runBreakupRevive({
7393
+ const target = JSON.parse(row.payload_json);
7394
+ return firstDraft((await runBreakupRevive({
5980
7395
  dryRun: opts.dryRun,
5981
- targets
5982
- })).drafted, rows, opts.dryRun);
7396
+ targets: [target]
7397
+ })).drafted);
5983
7398
  }
5984
7399
  case "competitor-switch": {
5985
- const targets = rows.map((r) => JSON.parse(r.payload_json));
5986
- return idsForSentDrafts((await runCompetitorSwitch({
7400
+ const target = JSON.parse(row.payload_json);
7401
+ return firstDraft((await runCompetitorSwitch({
7402
+ dryRun: opts.dryRun,
7403
+ targets: [target]
7404
+ })).drafted);
7405
+ }
7406
+ case "stack-consolidation": {
7407
+ const target = JSON.parse(row.payload_json);
7408
+ return firstDraft((await runStackConsolidation({
5987
7409
  dryRun: opts.dryRun,
5988
- targets
5989
- })).drafted, rows, opts.dryRun);
7410
+ targets: [target]
7411
+ })).drafted);
5990
7412
  }
5991
7413
  default: throw new Error(`drain: unsupported play '${opts.playName}'`);
5992
7414
  }
5993
7415
  }
5994
- /**
5995
- * Map drafted-results back to queue-row IDs by position. Plays return one
5996
- * draft per input target (in order), so drafted[i] always corresponds to
5997
- * rows[i]. We only flip a row to `sent` when its draft actually sent (or in
5998
- * dry-run, when we'd have sent it). The earlier `.filter().map((_, i) => rows[i])`
5999
- * pattern was wrong — after filtering, the index no longer maps to the
6000
- * original row, so partial sends marked the wrong rows as sent.
6001
- */
6002
- function idsForSentDrafts(drafted, rows, dryRun) {
6003
- const ids = [];
6004
- for (let i = 0; i < drafted.length; i++) {
6005
- const draft = drafted[i];
6006
- const row = rows[i];
6007
- if (!draft || !row) continue;
6008
- if (draft.sent || dryRun) ids.push(row.id);
6009
- }
6010
- return ids;
7416
+ function firstDraft(drafted) {
7417
+ const d = drafted[0];
7418
+ if (!d) throw new Error("play returned no draft for this target");
7419
+ return d;
6011
7420
  }
6012
7421
  function backfillProspectId(row) {
6013
7422
  if (!row) return null;
@@ -6355,6 +7764,64 @@ async function doctor(req) {
6355
7764
  }) }, 200, req);
6356
7765
  }
6357
7766
  //#endregion
7767
+ //#region src/api/_play-dispatch.ts
7768
+ function toDraftedView(d) {
7769
+ return {
7770
+ subject: d.subject,
7771
+ body: d.body,
7772
+ flags: d.flags,
7773
+ receiptIds: d.receiptIds,
7774
+ sent: d.sent
7775
+ };
7776
+ }
7777
+ /**
7778
+ * Dispatch a play by name and return one DraftedView per target (in order).
7779
+ * Shared by the SSE /api/run endpoint (multi-target) and the /queue
7780
+ * regenerate endpoint (single-target dry-run). Throws on unsupported plays
7781
+ * and on accelerator-batch without a senderCohort.
7782
+ */
7783
+ async function dispatchPlay(playName, body) {
7784
+ switch (playName) {
7785
+ case "show-hn": return (await runShowHn({
7786
+ dryRun: body.dryRun,
7787
+ targets: body.targets
7788
+ })).drafted.map(toDraftedView);
7789
+ case "job-change": return (await runJobChange({
7790
+ dryRun: body.dryRun,
7791
+ targets: body.targets
7792
+ })).drafted.map(toDraftedView);
7793
+ case "post-funding": return (await runPostFunding({
7794
+ dryRun: body.dryRun,
7795
+ targets: body.targets
7796
+ })).drafted.map(toDraftedView);
7797
+ case "accelerator-batch":
7798
+ if (!body.senderCohort || body.senderCohort.length === 0) throw new Error("accelerator-batch requires senderCohort");
7799
+ return (await runAcceleratorBatch({
7800
+ dryRun: body.dryRun,
7801
+ targets: body.targets,
7802
+ senderCohort: body.senderCohort,
7803
+ ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
7804
+ })).drafted.map(toDraftedView);
7805
+ case "hiring-signal": return (await runHiringSignal({
7806
+ dryRun: body.dryRun,
7807
+ targets: body.targets
7808
+ })).drafted.map(toDraftedView);
7809
+ case "podcast-guest": return (await runPodcastGuest({
7810
+ dryRun: body.dryRun,
7811
+ targets: body.targets
7812
+ })).drafted.map(toDraftedView);
7813
+ case "competitor-switch": return (await runCompetitorSwitch({
7814
+ dryRun: body.dryRun,
7815
+ targets: body.targets
7816
+ })).drafted.map(toDraftedView);
7817
+ case "stack-consolidation": return (await runStackConsolidation({
7818
+ dryRun: body.dryRun,
7819
+ targets: body.targets
7820
+ })).drafted.map(toDraftedView);
7821
+ default: throw new Error(`unsupported play: ${playName}`);
7822
+ }
7823
+ }
7824
+ //#endregion
6358
7825
  //#region src/api/run.ts
6359
7826
  const SUPPORTED = new Set([
6360
7827
  "show-hn",
@@ -6362,7 +7829,9 @@ const SUPPORTED = new Set([
6362
7829
  "post-funding",
6363
7830
  "accelerator-batch",
6364
7831
  "hiring-signal",
6365
- "podcast-guest"
7832
+ "podcast-guest",
7833
+ "competitor-switch",
7834
+ "stack-consolidation"
6366
7835
  ]);
6367
7836
  async function runPlay(req, params) {
6368
7837
  const playName = params["playName"] ?? "";
@@ -6377,10 +7846,63 @@ async function runPlay(req, params) {
6377
7846
  const stream = new ReadableStream({ async start(controller) {
6378
7847
  const encoder = new TextEncoder();
6379
7848
  const send = (event) => {
6380
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
7849
+ try {
7850
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
7851
+ } catch {}
6381
7852
  };
6382
7853
  try {
6383
- const drafted = await dispatchPlay(playName, body);
7854
+ const emailToDedupeKey = /* @__PURE__ */ new Map();
7855
+ if (body.dedupeKeys && body.dedupeKeys.length === body.targets.length) body.targets.forEach((t, i) => {
7856
+ const target = t;
7857
+ const email = target.email ?? target.founderEmail;
7858
+ const key = body.dedupeKeys?.[i];
7859
+ if (email && key) emailToDedupeKey.set(email, key);
7860
+ });
7861
+ const inputCount = body.targets.length;
7862
+ const fromQueue = Array.isArray(body.dedupeKeys) && body.dedupeKeys.length === body.targets.length;
7863
+ let verify;
7864
+ if (fromQueue) verify = {
7865
+ verified: body.targets,
7866
+ dropped: [],
7867
+ receiptIds: [],
7868
+ costUsd: 0
7869
+ };
7870
+ else {
7871
+ send({
7872
+ kind: "stage",
7873
+ stage: "verifying"
7874
+ });
7875
+ verify = await verifyAndFilterTargets(body.targets, (t) => t.email ?? t.founderEmail ?? null, {
7876
+ playName,
7877
+ dryRun: body.dryRun
7878
+ });
7879
+ }
7880
+ if (verify.dropped.length > 0) send({
7881
+ kind: "verify",
7882
+ total: inputCount,
7883
+ verified: verify.verified.length,
7884
+ dropped: verify.dropped.map((d) => ({
7885
+ email: d.email,
7886
+ reason: d.reason
7887
+ }))
7888
+ });
7889
+ if (verify.verified.length === 0 && inputCount > 0) {
7890
+ send({
7891
+ kind: "done",
7892
+ total: 0,
7893
+ sent: 0
7894
+ });
7895
+ return;
7896
+ }
7897
+ const filteredBody = {
7898
+ ...body,
7899
+ targets: verify.verified
7900
+ };
7901
+ send({
7902
+ kind: "stage",
7903
+ stage: body.dryRun ? "drafting" : "drafting + sending"
7904
+ });
7905
+ const drafted = await dispatchPlay(playName, filteredBody);
6384
7906
  let sentCount = 0;
6385
7907
  drafted.forEach((d, index) => {
6386
7908
  send({
@@ -6402,14 +7924,44 @@ async function runPlay(req, params) {
6402
7924
  total: drafted.length,
6403
7925
  sent: sentCount
6404
7926
  });
7927
+ if (emailToDedupeKey.size > 0) persistDraftsToQueue({
7928
+ playName,
7929
+ verifiedTargets: verify.verified,
7930
+ drafted,
7931
+ dryRun: body.dryRun,
7932
+ emailToDedupeKey
7933
+ });
6405
7934
  } catch (err) {
7935
+ const e = err;
7936
+ const causeMsg = e?.cause instanceof Error ? e.cause.message : e?.cause ? String(e.cause) : null;
7937
+ logEvent("run.pipeline_error", {
7938
+ play: playName,
7939
+ message_200: (e?.message ?? "").slice(0, 200),
7940
+ status_code: typeof e?.statusCode === "number" ? e.statusCode : null,
7941
+ response_body_400: typeof e?.responseBody === "string" ? e.responseBody.slice(0, 400) : null,
7942
+ cause_200: causeMsg ? causeMsg.slice(0, 200) : null,
7943
+ stack_300: (e?.stack ?? "").slice(0, 300)
7944
+ }, "error");
7945
+ let uiMessage = e?.message ?? "run failed";
7946
+ if (typeof e?.statusCode === "number") {
7947
+ let detail = "";
7948
+ try {
7949
+ const parsed = JSON.parse(e.responseBody ?? "");
7950
+ detail = parsed.message ?? parsed.error ?? "";
7951
+ } catch {
7952
+ detail = (e.responseBody ?? "").slice(0, 160);
7953
+ }
7954
+ uiMessage = `${uiMessage} (HTTP ${e.statusCode})${detail ? ` — ${detail}` : ""}`;
7955
+ }
6406
7956
  send({
6407
7957
  kind: "error",
6408
7958
  index: -1,
6409
- message: err.message
7959
+ message: uiMessage
6410
7960
  });
6411
7961
  } finally {
6412
- controller.close();
7962
+ try {
7963
+ controller.close();
7964
+ } catch {}
6413
7965
  }
6414
7966
  } });
6415
7967
  const origin = req.headers.get("origin") ?? "";
@@ -6428,48 +7980,50 @@ async function runPlay(req, params) {
6428
7980
  headers: sseHeaders
6429
7981
  });
6430
7982
  }
6431
- async function dispatchPlay(playName, body) {
6432
- switch (playName) {
6433
- case "show-hn": return (await runShowHn({
6434
- dryRun: body.dryRun,
6435
- targets: body.targets
6436
- })).drafted.map(toDraftedView);
6437
- case "job-change": return (await runJobChange({
6438
- dryRun: body.dryRun,
6439
- targets: body.targets
6440
- })).drafted.map(toDraftedView);
6441
- case "post-funding": return (await runPostFunding({
6442
- dryRun: body.dryRun,
6443
- targets: body.targets
6444
- })).drafted.map(toDraftedView);
6445
- case "accelerator-batch":
6446
- if (!body.senderCohort || body.senderCohort.length === 0) throw new Error("accelerator-batch requires senderCohort");
6447
- return (await runAcceleratorBatch({
6448
- dryRun: body.dryRun,
6449
- targets: body.targets,
6450
- senderCohort: body.senderCohort,
6451
- ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
6452
- })).drafted.map(toDraftedView);
6453
- case "hiring-signal": return (await runHiringSignal({
6454
- dryRun: body.dryRun,
6455
- targets: body.targets
6456
- })).drafted.map(toDraftedView);
6457
- case "podcast-guest": return (await runPodcastGuest({
6458
- dryRun: body.dryRun,
6459
- targets: body.targets
6460
- })).drafted.map(toDraftedView);
6461
- default: throw new Error(`unsupported play: ${playName}`);
7983
+ /**
7984
+ * After the SSE stream completes, write each generated draft to its
7985
+ * originating `target_queue` row. Best-effort: a SQL hiccup during
7986
+ * persistence is logged via `error.swallowed` and doesn't affect what the
7987
+ * UI already saw on the wire. Indices match because `verifiedTargets[i]`
7988
+ * corresponds to `drafted[i]` (both come from the same dispatch).
7989
+ */
7990
+ function persistDraftsToQueue(input) {
7991
+ const ledger = getLedger();
7992
+ for (let i = 0; i < input.drafted.length; i++) {
7993
+ const target = input.verifiedTargets[i];
7994
+ const draft = input.drafted[i];
7995
+ if (!target || !draft) continue;
7996
+ const email = target.email ?? target.founderEmail;
7997
+ if (!email) continue;
7998
+ const dedupeKey = input.emailToDedupeKey.get(email);
7999
+ if (!dedupeKey) continue;
8000
+ try {
8001
+ const row = ledger.getQueueRowByDedupe(input.playName, dedupeKey);
8002
+ if (!row) continue;
8003
+ ledger.setQueueDraft({
8004
+ id: row.id,
8005
+ draft: {
8006
+ subject: draft.subject,
8007
+ body: draft.body,
8008
+ flags: draft.flags,
8009
+ sent: draft.sent,
8010
+ receiptIds: draft.receiptIds,
8011
+ dryRun: input.dryRun
8012
+ }
8013
+ });
8014
+ if (draft.sent && !input.dryRun) ledger.setQueueStatus({
8015
+ id: row.id,
8016
+ status: "sent"
8017
+ });
8018
+ } catch (err) {
8019
+ logEvent("error.swallowed", {
8020
+ kind: "run.persistDraftsToQueue",
8021
+ play: input.playName,
8022
+ message_120: (err.message ?? "").slice(0, 120)
8023
+ }, "warn");
8024
+ }
6462
8025
  }
6463
8026
  }
6464
- function toDraftedView(d) {
6465
- return {
6466
- subject: d.subject,
6467
- body: d.body,
6468
- flags: d.flags,
6469
- receiptIds: d.receiptIds,
6470
- sent: d.sent
6471
- };
6472
- }
6473
8027
  //#endregion
6474
8028
  //#region src/api/queue.ts
6475
8029
  function toView$1(row) {
@@ -6479,6 +8033,21 @@ function toView$1(row) {
6479
8033
  } catch {
6480
8034
  payload = row.payload_json;
6481
8035
  }
8036
+ let lastDraft = null;
8037
+ if (row.last_draft_json) try {
8038
+ const parsed = JSON.parse(row.last_draft_json);
8039
+ if (parsed && typeof parsed.subject === "string" && typeof parsed.body === "string") lastDraft = {
8040
+ subject: parsed.subject,
8041
+ body: parsed.body,
8042
+ flags: Array.isArray(parsed.flags) ? parsed.flags : [],
8043
+ sent: parsed.sent === true,
8044
+ receiptIds: Array.isArray(parsed.receiptIds) ? parsed.receiptIds : [],
8045
+ dryRun: parsed.dryRun === true,
8046
+ draftedAt: typeof parsed.draftedAt === "string" ? parsed.draftedAt : ""
8047
+ };
8048
+ } catch {
8049
+ lastDraft = null;
8050
+ }
6482
8051
  return {
6483
8052
  id: row.id,
6484
8053
  playName: row.play_name,
@@ -6490,7 +8059,9 @@ function toView$1(row) {
6490
8059
  reviewedAt: row.reviewed_at,
6491
8060
  sentAt: row.sent_at,
6492
8061
  notes: row.notes,
6493
- prospectId: row.prospect_id
8062
+ prospectId: row.prospect_id,
8063
+ lastDraft,
8064
+ lastDraftedAt: row.last_drafted_at
6494
8065
  };
6495
8066
  }
6496
8067
  function listQueueRoute(req) {
@@ -6567,6 +8138,148 @@ async function drainQueueRoute(req) {
6567
8138
  errors: result.errors
6568
8139
  }, 200, req);
6569
8140
  }
8141
+ /**
8142
+ * Re-draft a single queue row in PREVIEW mode and overwrite its persisted
8143
+ * draft. Always dry-run: enrichment is skipped and nothing is sent, even
8144
+ * when the fresh draft is lint-clean. Lets the founder re-roll a held or
8145
+ * unsatisfying draft from /queue without leaving the page or risking a
8146
+ * send. The new draft replaces `last_draft_json` so the UI shows it on the
8147
+ * next queue refetch.
8148
+ */
8149
+ async function regenerateDraftRoute(req, params) {
8150
+ const id = Number.parseInt(params["id"] ?? "", 10);
8151
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
8152
+ const ledger = getLedger();
8153
+ const row = ledger.getQueueRow(id);
8154
+ if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);
8155
+ let target;
8156
+ try {
8157
+ target = JSON.parse(row.payload_json);
8158
+ } catch {
8159
+ return jsonResponse({ error: "row payload is not valid JSON" }, 400, req);
8160
+ }
8161
+ const payloadObj = target && typeof target === "object" ? target : {};
8162
+ const body = {
8163
+ dryRun: true,
8164
+ targets: [target],
8165
+ ...typeof payloadObj["senderCohort"] === "string" ? { senderCohort: payloadObj["senderCohort"] } : {},
8166
+ ...typeof payloadObj["freeForCohortOffer"] === "string" ? { freeForCohortOffer: payloadObj["freeForCohortOffer"] } : {}
8167
+ };
8168
+ let drafted;
8169
+ try {
8170
+ drafted = await dispatchPlay(row.play_name, body);
8171
+ } catch (err) {
8172
+ return jsonResponse({ error: err.message }, 400, req);
8173
+ }
8174
+ const draft = drafted[0];
8175
+ if (!draft) return jsonResponse({ error: "no draft produced" }, 500, req);
8176
+ ledger.setQueueDraft({
8177
+ id,
8178
+ draft: {
8179
+ subject: draft.subject,
8180
+ body: draft.body,
8181
+ flags: draft.flags,
8182
+ sent: false,
8183
+ receiptIds: [],
8184
+ dryRun: true
8185
+ }
8186
+ });
8187
+ return jsonResponse({
8188
+ subject: draft.subject,
8189
+ body: draft.body,
8190
+ flags: draft.flags,
8191
+ sent: false,
8192
+ receiptIds: [],
8193
+ dryRun: true,
8194
+ draftedAt: (/* @__PURE__ */ new Date()).toISOString()
8195
+ }, 200, req);
8196
+ }
8197
+ /**
8198
+ * Send the row's already-reviewed draft VERBATIM — the persisted
8199
+ * `last_draft_json` subject/body, no LLM re-roll. This is the review-then-send
8200
+ * model: the founder regenerates until the draft is clean, then sends exactly
8201
+ * that. Routes through `sendDraftedEmail` (the canonical send: core sendEmail
8202
+ * applies HTML + from_name formatting, records the sequence event, upserts the
8203
+ * prospect), then enrolls the cadence and flips the row to `sent`. Requires a
8204
+ * clean (lint-flag-free), not-yet-sent draft.
8205
+ */
8206
+ async function sendDraftRoute(req, params) {
8207
+ const id = Number.parseInt(params["id"] ?? "", 10);
8208
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
8209
+ const ledger = getLedger();
8210
+ const row = ledger.getQueueRow(id);
8211
+ if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);
8212
+ if (row.status === "sent") return jsonResponse({ error: "row already sent" }, 400, req);
8213
+ if (!row.last_draft_json) return jsonResponse({ error: "no draft to send — regenerate a draft first" }, 400, req);
8214
+ let parsed;
8215
+ try {
8216
+ parsed = JSON.parse(row.last_draft_json);
8217
+ } catch {
8218
+ return jsonResponse({ error: "stored draft is not valid JSON" }, 400, req);
8219
+ }
8220
+ const subject = typeof parsed.subject === "string" ? parsed.subject : "";
8221
+ const body = typeof parsed.body === "string" ? parsed.body : "";
8222
+ const flags = Array.isArray(parsed.flags) ? parsed.flags : [];
8223
+ if (!subject || !body) return jsonResponse({ error: "stored draft is empty — regenerate first" }, 400, req);
8224
+ if (flags.length > 0) return jsonResponse({ error: "draft has lint flags — regenerate to clear them before sending" }, 400, req);
8225
+ if (parsed.sent === true) return jsonResponse({ error: "draft already sent" }, 400, req);
8226
+ let payload = {};
8227
+ try {
8228
+ const p = JSON.parse(row.payload_json);
8229
+ if (p && typeof p === "object") payload = p;
8230
+ } catch {}
8231
+ const str = (k) => typeof payload[k] === "string" ? payload[k] : null;
8232
+ const email = str("email") ?? str("founderEmail");
8233
+ if (!email) return jsonResponse({ error: "row has no recipient email" }, 400, req);
8234
+ let result;
8235
+ try {
8236
+ result = await sendDraftedEmail({
8237
+ playName: row.play_name,
8238
+ to: email,
8239
+ draft: {
8240
+ subject,
8241
+ body
8242
+ },
8243
+ flags: [],
8244
+ prospectMeta: {
8245
+ name: str("name") ?? str("founderName"),
8246
+ email,
8247
+ company: str("company"),
8248
+ linkedin_url: str("linkedinUrl"),
8249
+ phone: str("phone"),
8250
+ source: row.play_name
8251
+ },
8252
+ dryRun: false
8253
+ });
8254
+ } catch (err) {
8255
+ return jsonResponse({ error: err.message ?? "send failed" }, 400, req);
8256
+ }
8257
+ if (!result.sent) return jsonResponse({ error: "send did not complete" }, 500, req);
8258
+ const prospect = ledger.findProspectByEmail(email);
8259
+ if (prospect) enrollInCadence({
8260
+ prospectId: prospect.id,
8261
+ playName: row.play_name
8262
+ });
8263
+ ledger.setQueueStatus({
8264
+ id,
8265
+ status: "sent"
8266
+ });
8267
+ ledger.setQueueDraft({
8268
+ id,
8269
+ draft: {
8270
+ subject,
8271
+ body,
8272
+ flags: [],
8273
+ sent: true,
8274
+ receiptIds: result.receiptIds,
8275
+ dryRun: false
8276
+ }
8277
+ });
8278
+ return jsonResponse({
8279
+ sent: true,
8280
+ receiptIds: result.receiptIds
8281
+ }, 200, req);
8282
+ }
6570
8283
  //#endregion
6571
8284
  //#region src/api/triggers.ts
6572
8285
  function toView(name, defaultIntervalMs, row, spec) {
@@ -6728,7 +8441,9 @@ const routes = [
6728
8441
  route("POST", "/api/cadences/:id/stop", stopCadence),
6729
8442
  route("GET", "/api/receipts", listReceipts),
6730
8443
  route("GET", "/api/receipts/:id", getReceipt),
8444
+ route("GET", "/api/inbox", listInboxRoute),
6731
8445
  route("GET", "/api/plays", listPlays),
8446
+ route("POST", "/api/plays/:name/cadence", setCadenceRoute),
6732
8447
  route("GET", "/api/measure/cac", measureCac),
6733
8448
  route("GET", "/api/measure/rocs", measureRocs),
6734
8449
  route("POST", "/api/measure/outcome", recordOutcome),
@@ -6743,6 +8458,8 @@ const routes = [
6743
8458
  route("POST", "/api/queue/drain", drainQueueRoute),
6744
8459
  route("POST", "/api/queue/:id/approve", approveQueueRoute),
6745
8460
  route("POST", "/api/queue/:id/reject", rejectQueueRoute),
8461
+ route("POST", "/api/queue/:id/regenerate", regenerateDraftRoute),
8462
+ route("POST", "/api/queue/:id/send-draft", sendDraftRoute),
6746
8463
  route("GET", "/api/triggers", listTriggersRoute),
6747
8464
  route("POST", "/api/triggers/:name/enabled", setTriggerEnabledRoute),
6748
8465
  route("POST", "/api/triggers/:name/config", setTriggerConfigRoute),
@@ -6864,6 +8581,39 @@ function jsonResponse(body, status = 200, req) {
6864
8581
  });
6865
8582
  }
6866
8583
  //#endregion
8584
+ //#region src/scheduler.ts
8585
+ const FIRST_TICK_DELAY_MS = 5e3;
8586
+ const ERROR_BACKOFF_MS = 6e4;
8587
+ function startScheduler() {
8588
+ let cancelled = false;
8589
+ let timer = null;
8590
+ const tick = async () => {
8591
+ if (cancelled) return;
8592
+ try {
8593
+ const outcomes = await runDueTriggers();
8594
+ const fired = outcomes.filter((o) => o.fired).length;
8595
+ logEvent("scheduler.tick.done", {
8596
+ fired,
8597
+ source: "server"
8598
+ });
8599
+ if (cancelled) return;
8600
+ const sleepMs = nextSleepMs(outcomes);
8601
+ timer = setTimeout(() => void tick(), sleepMs);
8602
+ } catch (err) {
8603
+ logEvent("scheduler.tick.failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
8604
+ if (!cancelled) timer = setTimeout(() => void tick(), ERROR_BACKOFF_MS);
8605
+ }
8606
+ };
8607
+ timer = setTimeout(() => void tick(), FIRST_TICK_DELAY_MS);
8608
+ return { stop() {
8609
+ cancelled = true;
8610
+ if (timer) {
8611
+ clearTimeout(timer);
8612
+ timer = null;
8613
+ }
8614
+ } };
8615
+ }
8616
+ //#endregion
6867
8617
  //#region src/bin.ts
6868
8618
  if (typeof globalThis.Bun === "undefined") {
6869
8619
  process.stderr.write("oneshot-gtm-server requires the Bun runtime.\nInstall: curl -fsSL https://bun.sh/install | bash\nRe-run: bunx oneshot-gtm-server\n");
@@ -6897,12 +8647,21 @@ if (cache.__oneshotGtmServer) {
6897
8647
  }
6898
8648
  const { url, server } = await startServer({ port });
6899
8649
  cache.__oneshotGtmServer = server;
8650
+ let scheduler = null;
8651
+ try {
8652
+ scheduler = startScheduler();
8653
+ cache.__oneshotGtmScheduler = scheduler;
8654
+ } catch (err) {
8655
+ logEvent("scheduler.start.failed", { message_120: (err.message ?? "").slice(0, 120) }, "error");
8656
+ process.stderr.write(` warn: scheduler failed to start: ${err.message}\n`);
8657
+ }
6900
8658
  process.stdout.write(`\n oneshot-gtm dashboard: ${url}\n\n`);
6901
8659
  if (!noBrowser) try {
6902
8660
  await open(url);
6903
8661
  } catch {}
6904
8662
  const shutdown = () => {
6905
8663
  process.stdout.write("\n shutting down...\n");
8664
+ if (scheduler) scheduler.stop();
6906
8665
  server.stop();
6907
8666
  process.exit(0);
6908
8667
  };