oneshot-gtm-server 0.2.0 → 0.3.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 (67) hide show
  1. package/dist/bin.mjs +1602 -1127
  2. package/dist/bin.mjs.map +1 -1
  3. package/dist/web/assets/{Badge-DE7L41a6.js → Badge-Bl9eBoUa.js} +2 -2
  4. package/dist/web/assets/{Badge-DE7L41a6.js.map → Badge-Bl9eBoUa.js.map} +1 -1
  5. package/dist/web/assets/Button-D1rFtlez.js +2 -0
  6. package/dist/web/assets/Button-D1rFtlez.js.map +1 -0
  7. package/dist/web/assets/{EmptyNote-DkmaZWuo.js → EmptyNote-CZaRRtmD.js} +2 -2
  8. package/dist/web/assets/{EmptyNote-DkmaZWuo.js.map → EmptyNote-CZaRRtmD.js.map} +1 -1
  9. package/dist/web/assets/{Field-B4mT8TGa.js → Field-DJ9InfU_.js} +2 -2
  10. package/dist/web/assets/{Field-B4mT8TGa.js.map → Field-DJ9InfU_.js.map} +1 -1
  11. package/dist/web/assets/{Modal-frAt7msr.js → Modal-CturxR2v.js} +2 -2
  12. package/dist/web/assets/{Modal-frAt7msr.js.map → Modal-CturxR2v.js.map} +1 -1
  13. package/dist/web/assets/{Skeleton-d2p06ghN.js → Skeleton-CHzR-B21.js} +2 -2
  14. package/dist/web/assets/{Skeleton-d2p06ghN.js.map → Skeleton-CHzR-B21.js.map} +1 -1
  15. package/dist/web/assets/cadences-D9cvMlfq.js +2 -0
  16. package/dist/web/assets/cadences-D9cvMlfq.js.map +1 -0
  17. package/dist/web/assets/chevron-down-J-vUa4uQ.js +2 -0
  18. package/dist/web/assets/chevron-down-J-vUa4uQ.js.map +1 -0
  19. package/dist/web/assets/chevron-right-DAxZefV9.js +2 -0
  20. package/dist/web/assets/chevron-right-DAxZefV9.js.map +1 -0
  21. package/dist/web/assets/inbox-Dsg3_bXr.js +2 -0
  22. package/dist/web/assets/{inbox-Dzd9QYT4.js.map → inbox-Dsg3_bXr.js.map} +1 -1
  23. package/dist/web/assets/{index-CzTgATNQ.js → index-BVno9lTD.js} +4 -4
  24. package/dist/web/assets/index-BVno9lTD.js.map +1 -0
  25. package/dist/web/assets/index-Ya_svHJk.css +2 -0
  26. package/dist/web/assets/loader-circle-B_w_dqVu.js +2 -0
  27. package/dist/web/assets/{loader-circle-BylpxA-u.js.map → loader-circle-B_w_dqVu.js.map} +1 -1
  28. package/dist/web/assets/{measure-S3BWSb2L.js → measure-CV7Towgf.js} +2 -2
  29. package/dist/web/assets/{measure-S3BWSb2L.js.map → measure-CV7Towgf.js.map} +1 -1
  30. package/dist/web/assets/{plays-DHIZA49D.js → plays-BSlXDDDK.js} +2 -2
  31. package/dist/web/assets/plays-BSlXDDDK.js.map +1 -0
  32. package/dist/web/assets/queue-BHKT-qjx.js +2 -0
  33. package/dist/web/assets/queue-BHKT-qjx.js.map +1 -0
  34. package/dist/web/assets/{receipts-BgXV3-De.js → receipts-opTtY1t7.js} +2 -2
  35. package/dist/web/assets/{receipts-BgXV3-De.js.map → receipts-opTtY1t7.js.map} +1 -1
  36. package/dist/web/assets/{refresh-cw-BpMRSA9y.js → refresh-cw-BO0blIzU.js} +2 -2
  37. package/dist/web/assets/{refresh-cw-BpMRSA9y.js.map → refresh-cw-BO0blIzU.js.map} +1 -1
  38. package/dist/web/assets/routes-BgDvPuJP.js +2 -0
  39. package/dist/web/assets/{routes-B9L9tBMF.js.map → routes-BgDvPuJP.js.map} +1 -1
  40. package/dist/web/assets/run._playName-CQU-5e18.js +5 -0
  41. package/dist/web/assets/run._playName-CQU-5e18.js.map +1 -0
  42. package/dist/web/assets/send-9D8YeqmY.js +2 -0
  43. package/dist/web/assets/send-9D8YeqmY.js.map +1 -0
  44. package/dist/web/assets/setup-CqCzlBdR.js +2 -0
  45. package/dist/web/assets/setup-CqCzlBdR.js.map +1 -0
  46. package/dist/web/assets/{summarizeRun-BsPt7szF.js → summarizeRun-D5Pd2arb.js} +1 -1
  47. package/dist/web/assets/{summarizeRun-BsPt7szF.js.map → summarizeRun-D5Pd2arb.js.map} +1 -1
  48. package/dist/web/index.html +3 -3
  49. package/package.json +1 -1
  50. package/dist/web/assets/Button-NJ1UVzeB.js +0 -2
  51. package/dist/web/assets/Button-NJ1UVzeB.js.map +0 -1
  52. package/dist/web/assets/cadences-CsU8vKw2.js +0 -2
  53. package/dist/web/assets/cadences-CsU8vKw2.js.map +0 -1
  54. package/dist/web/assets/chevron-right-BXb7J1cp.js +0 -2
  55. package/dist/web/assets/chevron-right-BXb7J1cp.js.map +0 -1
  56. package/dist/web/assets/inbox-Dzd9QYT4.js +0 -2
  57. package/dist/web/assets/index-ByTPAanr.css +0 -2
  58. package/dist/web/assets/index-CzTgATNQ.js.map +0 -1
  59. package/dist/web/assets/loader-circle-BylpxA-u.js +0 -2
  60. package/dist/web/assets/plays-DHIZA49D.js.map +0 -1
  61. package/dist/web/assets/queue-ClVxfeJ0.js +0 -2
  62. package/dist/web/assets/queue-ClVxfeJ0.js.map +0 -1
  63. package/dist/web/assets/routes-B9L9tBMF.js +0 -2
  64. package/dist/web/assets/run._playName-a3eeybKs.js +0 -5
  65. package/dist/web/assets/run._playName-a3eeybKs.js.map +0 -1
  66. package/dist/web/assets/setup-fs0DMLq4.js +0 -2
  67. package/dist/web/assets/setup-fs0DMLq4.js.map +0 -1
package/dist/bin.mjs CHANGED
@@ -32,6 +32,10 @@ const DEFAULTS = {
32
32
  sendingDomain: null,
33
33
  icpOneLiner: null,
34
34
  cadenceOverrides: null,
35
+ founderCredentials: null,
36
+ productPortfolio: null,
37
+ partners: null,
38
+ mobileSignature: false,
35
39
  clientId: null
36
40
  };
37
41
  function configDir() {
@@ -147,6 +151,15 @@ function oneshotEnvReady() {
147
151
  //#endregion
148
152
  //#region ../../packages/core/src/ledger.ts
149
153
  const DEFAULT_DB_PATH = join(configDir(), "ledger.sqlite");
154
+ /**
155
+ * Canonical form for matching prospect emails — trim + lowercase. Inbound reply
156
+ * addresses (cadence inbox poll) are normalized the same way, so a prospect
157
+ * stored from a mixed-case address still matches when they reply. Applied on
158
+ * both store (upsertProspect) and every lookup so the two never diverge.
159
+ */
160
+ function canonEmail(email) {
161
+ return email.trim().toLowerCase();
162
+ }
150
163
  var Ledger = class {
151
164
  db;
152
165
  constructor(path = DEFAULT_DB_PATH) {
@@ -193,6 +206,10 @@ var Ledger = class {
193
206
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
194
207
  FOREIGN KEY(prospect_id) REFERENCES prospects(id)
195
208
  );
209
+ -- sequence_events is read by listColdProspects (MAX(created_at) per
210
+ -- prospect), per-play send counts, and cadence scans — all by
211
+ -- prospect_id and/or created_at. Without this it's a full table scan.
212
+ CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_created ON sequence_events(prospect_id, created_at);
196
213
 
197
214
  CREATE TABLE IF NOT EXISTS interviews (
198
215
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -249,6 +266,9 @@ var Ledger = class {
249
266
  CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe ON target_queue(play_name, dedupe_key);
250
267
  CREATE INDEX IF NOT EXISTS idx_queue_status ON target_queue(status);
251
268
  CREATE INDEX IF NOT EXISTS idx_queue_play ON target_queue(play_name);
269
+ -- The /queue page filters by (status, play) together; the composite
270
+ -- serves that pair without falling back to a single-column scan.
271
+ CREATE INDEX IF NOT EXISTS idx_queue_status_play ON target_queue(status, play_name);
252
272
 
253
273
  CREATE TABLE IF NOT EXISTS triggers (
254
274
  name TEXT PRIMARY KEY,
@@ -275,6 +295,8 @@ var Ledger = class {
275
295
  this.addColumnIfMissing("target_queue", "last_draft_json", "TEXT");
276
296
  this.addColumnIfMissing("target_queue", "last_drafted_at", "TEXT");
277
297
  this.addColumnIfMissing("target_queue", "drain_claimed_at", "TEXT");
298
+ this.addColumnIfMissing("cadence_state", "next_step_draft_json", "TEXT");
299
+ this.addColumnIfMissing("cadence_state", "next_step_drafted_at", "TEXT");
278
300
  }
279
301
  addColumnIfMissing(table, column, type) {
280
302
  const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -317,18 +339,48 @@ var Ledger = class {
317
339
  }
318
340
  advanceCadence(input) {
319
341
  this.db.prepare(`UPDATE cadence_state
320
- SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now')
342
+ SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now'),
343
+ next_step_draft_json = NULL, next_step_drafted_at = NULL
321
344
  WHERE prospect_id = ? AND play_name = ?`).run(input.newStep, input.nextDueAt, input.prospectId, input.playName);
322
345
  }
323
346
  setCadenceStatus(input) {
324
- this.db.prepare(`UPDATE cadence_state SET status = ? WHERE prospect_id = ? AND play_name = ?`).run(input.status, input.prospectId, input.playName);
347
+ this.db.prepare(`UPDATE cadence_state
348
+ SET status = ?,
349
+ next_step_draft_json = CASE WHEN ? = 'active' THEN next_step_draft_json ELSE NULL END,
350
+ next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END
351
+ WHERE prospect_id = ? AND play_name = ?`).run(input.status, input.status, input.status, input.prospectId, input.playName);
352
+ }
353
+ setCadenceDraft(input) {
354
+ const draftedAtIso = (/* @__PURE__ */ new Date()).toISOString();
355
+ const json = JSON.stringify({
356
+ ...input.draft,
357
+ draftedAt: draftedAtIso
358
+ });
359
+ this.db.prepare(`UPDATE cadence_state
360
+ SET next_step_draft_json = ?, next_step_drafted_at = ?
361
+ WHERE prospect_id = ? AND play_name = ?`).run(json, draftedAtIso, input.prospectId, input.playName);
362
+ }
363
+ getCadenceDraft(input) {
364
+ const row = this.db.query(`SELECT next_step_draft_json AS j FROM cadence_state
365
+ WHERE prospect_id = ? AND play_name = ?`).get(input.prospectId, input.playName);
366
+ if (!row?.j) return null;
367
+ try {
368
+ return JSON.parse(row.j);
369
+ } catch {
370
+ return null;
371
+ }
372
+ }
373
+ clearCadenceDraft(input) {
374
+ this.db.prepare(`UPDATE cadence_state
375
+ SET next_step_draft_json = NULL, next_step_drafted_at = NULL
376
+ WHERE prospect_id = ? AND play_name = ?`).run(input.prospectId, input.playName);
325
377
  }
326
378
  findProspectByEmail(email) {
327
- return this.db.query("SELECT id FROM prospects WHERE email = ?").get(email) ?? null;
379
+ return this.db.query("SELECT id FROM prospects WHERE email = ?").get(canonEmail(email)) ?? null;
328
380
  }
329
381
  /** Full prospect record by email — used to attach name/company to inbox replies. */
330
382
  getProspectByEmail(email) {
331
- return this.db.query("SELECT * FROM prospects WHERE email = ?").get(email) ?? null;
383
+ return this.db.query("SELECT * FROM prospects WHERE email = ?").get(canonEmail(email)) ?? null;
332
384
  }
333
385
  /** Cached enrichProfile result for an email (profiles are stable; reused with a TTL). */
334
386
  getCachedEnrichment(email) {
@@ -366,14 +418,15 @@ var Ledger = class {
366
418
  return this.db.query(sql).all(...args);
367
419
  }
368
420
  upsertProspect(input) {
369
- if (input.email) {
370
- const existing = this.db.query("SELECT id FROM prospects WHERE email = ?").get(input.email);
421
+ const email = input.email ? canonEmail(input.email) : null;
422
+ if (email) {
423
+ const existing = this.db.query("SELECT id FROM prospects WHERE email = ?").get(email);
371
424
  if (existing) return existing.id;
372
425
  }
373
426
  const result = this.db.prepare(`
374
427
  INSERT INTO prospects(name, email, phone, company, linkedin_url, dossier_json, source)
375
428
  VALUES(?, ?, ?, ?, ?, ?, ?)
376
- `).run(input.name ?? null, input.email ?? null, input.phone ?? null, input.company ?? null, input.linkedin_url ?? null, input.dossier_json ?? null, input.source ?? null);
429
+ `).run(input.name ?? null, email, input.phone ?? null, input.company ?? null, input.linkedin_url ?? null, input.dossier_json ?? null, input.source ?? null);
377
430
  return Number(result.lastInsertRowid);
378
431
  }
379
432
  recordOutcome(input) {
@@ -940,6 +993,46 @@ async function listInbox(opts) {
940
993
  if (opts?.limit) out.limit = opts.limit;
941
994
  return agent.inboxList(out);
942
995
  }
996
+ async function sendSms(input, ctx) {
997
+ const agent = await getAgent();
998
+ const opts = {
999
+ to_number: input.to,
1000
+ message: input.message
1001
+ };
1002
+ if (input.maxCost) opts.maxCost = input.maxCost;
1003
+ const result = await agent.sms(opts);
1004
+ return {
1005
+ result,
1006
+ receiptId: getLedger().recordReceipt({
1007
+ playName: ctx.playName,
1008
+ callType: "sms.send",
1009
+ signedReceipt: result,
1010
+ costUsd: result.cost,
1011
+ oneshotRequestId: result.details[0]?.message_sid ?? void 0
1012
+ })
1013
+ };
1014
+ }
1015
+ async function voiceCall(input, ctx) {
1016
+ const agent = await getAgent();
1017
+ const opts = {
1018
+ objective: input.objective,
1019
+ target_number: input.to
1020
+ };
1021
+ if (input.callerPersona) opts.caller_persona = input.callerPersona;
1022
+ if (input.context) opts.context = input.context;
1023
+ if (input.maxDurationMinutes) opts.max_duration_minutes = input.maxDurationMinutes;
1024
+ if (input.maxCost) opts.maxCost = input.maxCost;
1025
+ const result = await agent.voice(opts);
1026
+ return {
1027
+ result,
1028
+ receiptId: getLedger().recordReceipt({
1029
+ playName: ctx.playName,
1030
+ callType: "voice.call",
1031
+ costUsd: result.cost,
1032
+ signedReceipt: result
1033
+ })
1034
+ };
1035
+ }
943
1036
  async function webSearch(input, ctx) {
944
1037
  const agent = await getAgent();
945
1038
  const opts = { query: input.query };
@@ -1080,169 +1173,6 @@ function homeMetrics(req) {
1080
1173
  }, 200, req);
1081
1174
  }
1082
1175
  //#endregion
1083
- //#region src/api/cadences.ts
1084
- function toView$3(row) {
1085
- return {
1086
- prospectId: row.prospect_id,
1087
- prospectEmail: row.prospect_email,
1088
- prospectName: row.prospect_name,
1089
- prospectCompany: row.prospect_company,
1090
- playName: row.play_name,
1091
- status: row.status,
1092
- currentStep: row.current_step,
1093
- enrolledAt: row.enrolled_at,
1094
- nextDueAt: row.next_due_at,
1095
- lastPolledAt: row.last_polled_at
1096
- };
1097
- }
1098
- function listCadences(req) {
1099
- const all = new URL(req.url).searchParams.get("all") === "1";
1100
- const ledger = getLedger();
1101
- return jsonResponse({ cadences: (all ? ledger.listAllCadences() : ledger.listActiveCadences()).map(toView$3) }, 200, req);
1102
- }
1103
- function getCadence(req, params) {
1104
- const id = Number.parseInt(params["id"] ?? "", 10);
1105
- if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
1106
- const all = getLedger().listAllCadences().filter((c) => c.prospect_id === id);
1107
- if (all.length === 0) return jsonResponse({ error: "no cadences for prospect" }, 404, req);
1108
- return jsonResponse({ cadences: all.map(toView$3) }, 200, req);
1109
- }
1110
- function stopCadence(req, params) {
1111
- const id = Number.parseInt(params["id"] ?? "", 10);
1112
- if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
1113
- const playName = new URL(req.url).searchParams.get("play");
1114
- const ledger = getLedger();
1115
- const cadences = ledger.listAllCadences().filter((c) => {
1116
- if (c.prospect_id !== id) return false;
1117
- if (playName && c.play_name !== playName) return false;
1118
- return c.status === "active";
1119
- });
1120
- for (const cad of cadences) ledger.setCadenceStatus({
1121
- prospectId: id,
1122
- playName: cad.play_name,
1123
- status: "completed"
1124
- });
1125
- return jsonResponse({ stopped: cadences.length }, 200, req);
1126
- }
1127
- //#endregion
1128
- //#region src/api/receipts.ts
1129
- function toView$2(row) {
1130
- return {
1131
- id: row.id,
1132
- playName: row.play_name,
1133
- callType: row.call_type,
1134
- costUsd: row.cost_usd,
1135
- oneshotRequestId: row.oneshot_request_id,
1136
- createdAt: row.created_at
1137
- };
1138
- }
1139
- function listReceipts(req) {
1140
- const url = new URL(req.url);
1141
- const playName = url.searchParams.get("play") ?? void 0;
1142
- const sinceDays = Number.parseInt(url.searchParams.get("sinceDays") ?? "", 10);
1143
- const limit = Math.min(500, Number.parseInt(url.searchParams.get("limit") ?? "200", 10) || 200);
1144
- const sinceIso = Number.isFinite(sinceDays) ? (/* @__PURE__ */ new Date(Date.now() - sinceDays * 24 * 3600 * 1e3)).toISOString() : void 0;
1145
- return jsonResponse({ receipts: getLedger().listReceipts({
1146
- ...playName ? { playName } : {},
1147
- ...sinceIso ? { sinceIso } : {},
1148
- limit
1149
- }).map(toView$2) }, 200, req);
1150
- }
1151
- function getReceipt(req, params) {
1152
- const id = Number.parseInt(params["id"] ?? "", 10);
1153
- if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
1154
- const r = getLedger().getReceipt(id);
1155
- if (!r) return jsonResponse({ error: "not found" }, 404, req);
1156
- let parsed = null;
1157
- if (r.signed_receipt) try {
1158
- parsed = JSON.parse(r.signed_receipt);
1159
- } catch {
1160
- parsed = r.signed_receipt;
1161
- }
1162
- return jsonResponse({ receipt: {
1163
- id: r.id,
1164
- playName: r.play_name,
1165
- callType: r.call_type,
1166
- costUsd: r.cost_usd,
1167
- oneshotRequestId: r.oneshot_request_id,
1168
- createdAt: r.created_at,
1169
- signedReceipt: parsed
1170
- } }, 200, req);
1171
- }
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
1246
1176
  //#region ../../packages/intel/src/prompts.ts
1247
1177
  const here = dirname(fileURLToPath(import.meta.url));
1248
1178
  const candidates = [
@@ -1594,18 +1524,41 @@ function signatureDirective() {
1594
1524
  const cfg = loadConfig();
1595
1525
  const domain = (cfg.productDomain ?? "").trim();
1596
1526
  if (!domain) return "";
1527
+ const name = (cfg.founderName ?? "").trim() || "[founder name]";
1528
+ const mobile = cfg.mobileSignature === true;
1529
+ const sigLines = [name, domain];
1530
+ if (mobile) sigLines.push("Sent from my iPhone");
1597
1531
  return [
1598
1532
  "",
1599
1533
  "",
1600
1534
  "## 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:",
1535
+ mobile ? "End the email with the founder's name, then their domain, then a literal 'Sent from my iPhone' line. Three lines total, in this order:" : "End the email with the founder's name, then their domain on the very next line:",
1602
1536
  "",
1603
- (cfg.founderName ?? "").trim() || "[founder name]",
1604
- domain,
1537
+ ...sigLines,
1605
1538
  "",
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.`
1539
+ `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.`,
1540
+ ...mobile ? [`The "Sent from my iPhone" line is a literal proof-of-human artifact. Always exactly that string, no variation, no quotes.`] : []
1607
1541
  ].join("\n");
1608
1542
  }
1543
+ /**
1544
+ * Build a SOCIAL PROOF input block from the founder's three optional config
1545
+ * fields. Returns null when none are set — callers skip the line entirely
1546
+ * so the prompt's "if SOCIAL PROOF is in the inputs" conditional kicks in.
1547
+ * Each prompt should weave AT MOST ONE beat (credentials OR built-with OR
1548
+ * partners) into the email, not stack them.
1549
+ */
1550
+ function socialProofBlock() {
1551
+ const cfg = loadConfig();
1552
+ const lines = [];
1553
+ const cred = cfg.founderCredentials?.trim();
1554
+ const built = cfg.productPortfolio?.trim();
1555
+ const partners = cfg.partners?.trim();
1556
+ if (cred) lines.push(`CREDENTIALS: ${cred}`);
1557
+ if (built) lines.push(`PORTFOLIO: ${built}`);
1558
+ if (partners) lines.push(`PARTNERS: ${partners}`);
1559
+ if (lines.length === 0) return null;
1560
+ return ["SOCIAL PROOF (pick the ONE beat that best fits this play — CREDENTIALS for founder-trust, PORTFOLIO for peer-founder, PARTNERS for brand-recognition; never stack two):", ...lines].join("\n");
1561
+ }
1609
1562
  async function draftEmailFromPrompt(opts) {
1610
1563
  return humanizeDraft(parseSubjectBody((await complete({
1611
1564
  messages: [{
@@ -1669,6 +1622,12 @@ async function sendDraftedEmail(opts) {
1669
1622
  sent
1670
1623
  };
1671
1624
  }
1625
+ /** Domain portion of an email address, or undefined if it has no `@`. */
1626
+ function emailDomain(email) {
1627
+ const at = email.indexOf("@");
1628
+ if (at < 0) return void 0;
1629
+ return email.slice(at + 1);
1630
+ }
1672
1631
  /**
1673
1632
  * Verify a batch of target emails BEFORE drafting + sending. Used by
1674
1633
  * direct-input entry points (CLI motion commands + dashboard /run) where
@@ -1776,6 +1735,55 @@ const playSequences = /* @__PURE__ */ new Map();
1776
1735
  function registerSequence(seq) {
1777
1736
  playSequences.set(seq.playName, seq);
1778
1737
  }
1738
+ /**
1739
+ * "Does this label name a breakup step?" — single source of truth for the
1740
+ * label-substring check. Used by isBreakupStepAt for the cadence-final
1741
+ * semantic check AND by /plays for per-step rendering where each row is
1742
+ * already a step.
1743
+ */
1744
+ function isBreakupLabel(label) {
1745
+ return Boolean(label && label.toLowerCase().includes("breakup"));
1746
+ }
1747
+ /**
1748
+ * Centralized breakup-step detection for cadence-progress semantics. A
1749
+ * step is "the breakup" iff (a) it sits at the END of the sequence and
1750
+ * (b) its label is a breakup label. Both clauses matter: the
1751
+ * breakup-email PROMPT is also used as accelerator-batch's only
1752
+ * follow-up — at index 0 — and that one isn't semantically a breakup
1753
+ * for cadence UX purposes (no value follow-up preceded it).
1754
+ */
1755
+ function isBreakupStepAt(seq, stepEntryIndex) {
1756
+ if (stepEntryIndex !== seq.steps.length - 1) return false;
1757
+ return isBreakupLabel(seq.steps[stepEntryIndex]?.label);
1758
+ }
1759
+ /**
1760
+ * Number of follow-up steps registered for this play (excludes day-0).
1761
+ * Always returns the registered total regardless of current_step — the UI
1762
+ * uses `playFollowupCount + 1` for the StepProgress dot count which should
1763
+ * be stable for completed cadences too.
1764
+ */
1765
+ function playFollowupCount(playName) {
1766
+ return effectiveSequence(playName)?.steps.length ?? 0;
1767
+ }
1768
+ /**
1769
+ * Given a play + the cadence's current_step, describe the NEXT step
1770
+ * scheduled to fire. Returns null when the cadence is at or past the
1771
+ * last step (no more steps to send). Source of truth for both the
1772
+ * server's CadenceView and the /cadences UI — avoids hardcoded
1773
+ * play→step-count Records in the web layer.
1774
+ */
1775
+ function nextStepInfo(playName, currentStep) {
1776
+ const seq = effectiveSequence(playName);
1777
+ if (!seq) return null;
1778
+ const nextIndex = currentStep + 1;
1779
+ const stepEntryIndex = nextIndex - 1;
1780
+ if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) return null;
1781
+ return {
1782
+ label: seq.steps[stepEntryIndex]?.label ?? null,
1783
+ isBreakup: isBreakupStepAt(seq, stepEntryIndex),
1784
+ nextStepNumber: nextIndex
1785
+ };
1786
+ }
1779
1787
  function getSequence(playName) {
1780
1788
  return effectiveSequence(playName);
1781
1789
  }
@@ -1819,781 +1827,1126 @@ function enrollInCadence(input) {
1819
1827
  nextDueAt: dueAt
1820
1828
  });
1821
1829
  }
1822
- function buildFollowUpEmail(opts) {
1823
- return async (ctx) => {
1824
- const system = loadPrompt(opts.promptName) + signatureDirective();
1825
- const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);
1826
- const user = [
1827
- `FOUNDER: ${ctx.cfg.founderName}`,
1828
- `PRODUCT: ${ctx.cfg.productOneLiner}`,
1829
- `PROSPECT: ${ctx.prospect.name ?? "(unknown)"}`,
1830
- `EMAIL: ${ctx.prospect.email ?? ""}`,
1831
- `COMPANY: ${ctx.prospect.company ?? "(unknown)"}`,
1832
- ...opts.contextLines,
1833
- ...priorBlock ? ["", priorBlock] : []
1834
- ].join("\n");
1835
- const parsed = tryParseJsonObject((await complete({
1836
- messages: [{
1837
- role: "system",
1838
- content: system
1839
- }, {
1840
- role: "user",
1841
- content: user
1842
- }],
1843
- temperature: .6,
1844
- maxTokens: 500
1845
- })).content, {});
1846
- if (!parsed.subject || !parsed.body) return null;
1847
- return {
1848
- kind: "email",
1849
- subject: parsed.subject.trim(),
1850
- body: parsed.body.trim()
1830
+ /**
1831
+ * Per-prospect cadence step runner. Single source of truth for both the
1832
+ * batch `advanceCadence` (CLI) and the per-row /cadences UI (preview + send).
1833
+ * Caller decides dryRun (no send) or persistedPayload (send a previously
1834
+ * built draft verbatim). On a successful send, advances `current_step`
1835
+ * to `nextIndex` and sets `next_due_at` to the next step's offset; clears
1836
+ * any persisted preview draft via ledger.advanceCadence.
1837
+ */
1838
+ async function runCadenceStepForProspect(opts) {
1839
+ const ledger = getLedger();
1840
+ const cfg = loadConfig();
1841
+ const cadence = ledger.listAllCadences().find((c) => c.prospect_id === opts.prospectId && c.play_name === opts.playName);
1842
+ if (!cadence) return {
1843
+ action: "skipped",
1844
+ payload: null,
1845
+ receiptIds: [],
1846
+ note: "no cadence"
1847
+ };
1848
+ if (cadence.status !== "active") return {
1849
+ action: "skipped",
1850
+ payload: null,
1851
+ receiptIds: [],
1852
+ note: `cadence is ${cadence.status}`
1853
+ };
1854
+ const seq = effectiveSequence(opts.playName);
1855
+ if (!seq) return {
1856
+ action: "skipped",
1857
+ payload: null,
1858
+ receiptIds: [],
1859
+ note: "no registered sequence"
1860
+ };
1861
+ const nextIndex = cadence.current_step + 1;
1862
+ const stepEntryIndex = nextIndex - 1;
1863
+ if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {
1864
+ ledger.setCadenceStatus({
1865
+ prospectId: opts.prospectId,
1866
+ playName: opts.playName,
1867
+ status: "completed"
1868
+ });
1869
+ return {
1870
+ action: "completed",
1871
+ payload: null,
1872
+ receiptIds: []
1873
+ };
1874
+ }
1875
+ const step = seq.steps[stepEntryIndex];
1876
+ if (!step) return {
1877
+ action: "skipped",
1878
+ payload: null,
1879
+ receiptIds: []
1880
+ };
1881
+ const prospect = loadProspect(opts.prospectId);
1882
+ if (!prospect) return {
1883
+ action: "skipped",
1884
+ payload: null,
1885
+ receiptIds: [],
1886
+ note: "prospect not found"
1887
+ };
1888
+ const built = opts.persistedPayload ? opts.persistedPayload : await step.builder({
1889
+ prospect,
1890
+ cfg,
1891
+ metadata: {}
1892
+ });
1893
+ if (!built) {
1894
+ const next = seq.steps[stepEntryIndex + 1];
1895
+ ledger.advanceCadence({
1896
+ prospectId: opts.prospectId,
1897
+ playName: opts.playName,
1898
+ newStep: nextIndex,
1899
+ nextDueAt: next ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1e3).toISOString() : null
1900
+ });
1901
+ if (!next) {
1902
+ ledger.setCadenceStatus({
1903
+ prospectId: opts.prospectId,
1904
+ playName: opts.playName,
1905
+ status: "completed"
1906
+ });
1907
+ return {
1908
+ action: "completed",
1909
+ payload: null,
1910
+ receiptIds: [],
1911
+ note: step.label ?? `step ${nextIndex} builder returned null`
1912
+ };
1913
+ }
1914
+ return {
1915
+ action: "skipped",
1916
+ payload: null,
1917
+ receiptIds: [],
1918
+ note: step.label ?? `step ${nextIndex} builder returned null`
1919
+ };
1920
+ }
1921
+ const receiptIds = [];
1922
+ if (!opts.dryRun) {
1923
+ const channelOutcome = await dispatchStep({
1924
+ playName: opts.playName,
1925
+ prospectId: opts.prospectId,
1926
+ prospectEmail: cadence.prospect_email,
1927
+ stepIndex: nextIndex,
1928
+ step,
1929
+ payload: built,
1930
+ ...step.label !== void 0 ? { label: step.label } : {}
1931
+ });
1932
+ if (channelOutcome.skipReason) return {
1933
+ action: "skipped",
1934
+ payload: built,
1935
+ receiptIds: [],
1936
+ note: channelOutcome.skipReason
1937
+ };
1938
+ receiptIds.push(...channelOutcome.receiptIds);
1939
+ }
1940
+ if (isBreakupStepAt(seq, stepEntryIndex)) {
1941
+ ledger.setCadenceStatus({
1942
+ prospectId: opts.prospectId,
1943
+ playName: opts.playName,
1944
+ status: "breakup"
1945
+ });
1946
+ return {
1947
+ action: "breakup",
1948
+ payload: built,
1949
+ receiptIds,
1950
+ note: step.label ?? `step ${nextIndex}`
1851
1951
  };
1952
+ }
1953
+ const next = seq.steps[stepEntryIndex + 1];
1954
+ ledger.advanceCadence({
1955
+ prospectId: opts.prospectId,
1956
+ playName: opts.playName,
1957
+ newStep: nextIndex,
1958
+ nextDueAt: next ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1e3).toISOString() : null
1959
+ });
1960
+ if (!next) ledger.setCadenceStatus({
1961
+ prospectId: opts.prospectId,
1962
+ playName: opts.playName,
1963
+ status: "completed"
1964
+ });
1965
+ return {
1966
+ action: "step-sent",
1967
+ payload: built,
1968
+ receiptIds,
1969
+ note: step.label ?? `step ${nextIndex}`
1852
1970
  };
1853
1971
  }
1854
- function buildPriorEmailsBlock(prospectId, playName) {
1855
- if (!prospectId) return null;
1972
+ /**
1973
+ * Build the next step's draft and persist it via setCadenceDraft. Never
1974
+ * sends. Mirrors the /queue regenerate route — the founder reviews on
1975
+ * /cadences, then clicks Send next which calls sendCadenceStep.
1976
+ */
1977
+ async function previewCadenceStep(input) {
1978
+ const ledger = getLedger();
1979
+ const cfg = loadConfig();
1980
+ const cadence = ledger.listAllCadences().find((c) => c.prospect_id === input.prospectId && c.play_name === input.playName);
1981
+ if (!cadence) throw new Error("no cadence for that prospect+play");
1982
+ if (cadence.status !== "active") throw new Error(`cadence is ${cadence.status}, can only preview an active cadence`);
1983
+ const seq = effectiveSequence(input.playName);
1984
+ if (!seq) throw new Error(`no registered sequence for play '${input.playName}'`);
1985
+ const stepEntryIndex = cadence.current_step + 1 - 1;
1986
+ if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) throw new Error("no next step (cadence is at or past the last step)");
1987
+ const step = seq.steps[stepEntryIndex];
1988
+ if (!step) throw new Error("step undefined");
1989
+ const prospect = loadProspect(input.prospectId);
1990
+ if (!prospect) throw new Error("prospect not found");
1991
+ const built = await step.builder({
1992
+ prospect,
1993
+ cfg,
1994
+ metadata: {}
1995
+ });
1996
+ if (!built) throw new Error("builder returned null — nothing to preview");
1997
+ const subject = built.kind === "email" ? built.subject : "(non-email step)";
1998
+ const body = built.kind === "email" ? built.body : built.kind === "sms" ? built.message : built.kind === "voice" ? built.objective : "";
1999
+ const flags = built.kind === "email" ? lintEmail(subject, body, 100) : [];
2000
+ ledger.setCadenceDraft({
2001
+ prospectId: input.prospectId,
2002
+ playName: input.playName,
2003
+ draft: {
2004
+ subject,
2005
+ body,
2006
+ flags,
2007
+ payload: built
2008
+ }
2009
+ });
2010
+ return {
2011
+ subject,
2012
+ body,
2013
+ flags,
2014
+ payload: built,
2015
+ draftedAt: ledger.getCadenceDraft({
2016
+ prospectId: input.prospectId,
2017
+ playName: input.playName
2018
+ })?.draftedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2019
+ stepLabel: step.label ?? null,
2020
+ isBreakup: isBreakupStepAt(seq, stepEntryIndex)
2021
+ };
2022
+ }
2023
+ /**
2024
+ * Send a previously-previewed cadence step verbatim. Reads the persisted
2025
+ * draft (or 409s if none), dispatches it through runCadenceStepForProspect,
2026
+ * and advances the cadence. The advance clears the persisted draft so a
2027
+ * subsequent Preview rebuilds against the new current_step.
2028
+ */
2029
+ async function sendCadenceStep(input) {
2030
+ const draft = getLedger().getCadenceDraft(input);
2031
+ if (!draft) throw new Error("no persisted preview — click Preview first");
2032
+ return runCadenceStepForProspect({
2033
+ prospectId: input.prospectId,
2034
+ playName: input.playName,
2035
+ dryRun: false,
2036
+ persistedPayload: draft.payload
2037
+ });
2038
+ }
2039
+ /**
2040
+ * Serial preview of a list of cadence rows. Each per-prospect failure is
2041
+ * captured in the result array — the batch never throws. Sequential
2042
+ * iteration is deliberate: parallel LLM calls would risk burst rate-limits
2043
+ * and the founder is waiting on us anyway (~10s/row).
2044
+ */
2045
+ async function previewCadenceStepBatch(items) {
2046
+ const out = [];
2047
+ for (const item of items) try {
2048
+ const preview = await previewCadenceStep(item);
2049
+ out.push({
2050
+ prospectId: item.prospectId,
2051
+ playName: item.playName,
2052
+ ok: true,
2053
+ preview
2054
+ });
2055
+ } catch (err) {
2056
+ out.push({
2057
+ prospectId: item.prospectId,
2058
+ playName: item.playName,
2059
+ ok: false,
2060
+ error: (err?.message ?? "preview failed").slice(0, 120)
2061
+ });
2062
+ }
2063
+ return out;
2064
+ }
2065
+ /**
2066
+ * Serial send of a list of previewed cadence rows. Each per-prospect failure
2067
+ * is captured; the batch never throws. Used by `POST /api/cadences/send-batch`
2068
+ * as a background promise — caller returns 202 immediately and the UI sees
2069
+ * progress via subsequent `/api/cadences` refetches (the existing
2070
+ * `advanceCadence` clears `next_step_draft_json` as each row completes).
2071
+ */
2072
+ async function sendCadenceStepBatch(items, onItemSettled) {
2073
+ const out = [];
2074
+ for (const item of items) {
2075
+ let result;
2076
+ try {
2077
+ const r = await sendCadenceStep(item);
2078
+ result = {
2079
+ prospectId: item.prospectId,
2080
+ playName: item.playName,
2081
+ ok: true,
2082
+ action: r.action,
2083
+ receiptIds: r.receiptIds
2084
+ };
2085
+ } catch (err) {
2086
+ result = {
2087
+ prospectId: item.prospectId,
2088
+ playName: item.playName,
2089
+ ok: false,
2090
+ error: (err?.message ?? "send failed").slice(0, 120)
2091
+ };
2092
+ }
2093
+ out.push(result);
2094
+ onItemSettled?.(item, result);
2095
+ }
2096
+ return out;
2097
+ }
2098
+ async function dispatchStep(input) {
2099
+ const ledger = getLedger();
2100
+ const receiptIds = [];
2101
+ if (input.payload.kind === "email") {
2102
+ if (!input.prospectEmail) return {
2103
+ receiptIds,
2104
+ skipReason: "prospect has no email"
2105
+ };
2106
+ const send = await sendEmail({
2107
+ to: input.prospectEmail,
2108
+ subject: input.payload.subject,
2109
+ body: input.payload.body
2110
+ }, { playName: input.playName });
2111
+ receiptIds.push(send.receiptId);
2112
+ ledger.recordSequenceEvent({
2113
+ prospectId: input.prospectId,
2114
+ playName: input.playName,
2115
+ stepIndex: input.stepIndex,
2116
+ channel: "email",
2117
+ status: "sent",
2118
+ metadata: {
2119
+ subject: input.payload.subject,
2120
+ body: input.payload.body,
2121
+ label: input.label
2122
+ }
2123
+ });
2124
+ return { receiptIds };
2125
+ }
2126
+ if (input.payload.kind === "sms") {
2127
+ if (!input.payload.toPhone) return {
2128
+ receiptIds,
2129
+ skipReason: "prospect has no phone for SMS"
2130
+ };
2131
+ const send = await sendSms({
2132
+ to: input.payload.toPhone,
2133
+ message: input.payload.message
2134
+ }, { playName: input.playName });
2135
+ receiptIds.push(send.receiptId);
2136
+ ledger.recordSequenceEvent({
2137
+ prospectId: input.prospectId,
2138
+ playName: input.playName,
2139
+ stepIndex: input.stepIndex,
2140
+ channel: "sms",
2141
+ status: "sent",
2142
+ metadata: { label: input.label }
2143
+ });
2144
+ return { receiptIds };
2145
+ }
2146
+ if (input.payload.kind === "voice") {
2147
+ if (!input.payload.toPhone) return {
2148
+ receiptIds,
2149
+ skipReason: "prospect has no phone for voice"
2150
+ };
2151
+ const call = await voiceCall({
2152
+ objective: input.payload.objective,
2153
+ to: input.payload.toPhone,
2154
+ ...input.payload.context ? { context: input.payload.context } : {},
2155
+ ...input.payload.maxDurationMinutes ? { maxDurationMinutes: input.payload.maxDurationMinutes } : {}
2156
+ }, { playName: input.playName });
2157
+ receiptIds.push(call.receiptId);
2158
+ ledger.recordSequenceEvent({
2159
+ prospectId: input.prospectId,
2160
+ playName: input.playName,
2161
+ stepIndex: input.stepIndex,
2162
+ channel: "voice",
2163
+ status: "sent",
2164
+ metadata: {
2165
+ label: input.label,
2166
+ ended_reason: call.result.ended_reason ?? null
2167
+ }
2168
+ });
2169
+ return { receiptIds };
2170
+ }
2171
+ return {
2172
+ receiptIds,
2173
+ skipReason: "unknown step payload kind"
2174
+ };
2175
+ }
2176
+ function loadProspect(id) {
2177
+ return getLedger().db.query("SELECT * FROM prospects WHERE id = ?").get(id) ?? null;
2178
+ }
2179
+ function buildFollowUpEmail(opts) {
2180
+ return async (ctx) => {
2181
+ const system = loadPrompt(opts.promptName) + signatureDirective();
2182
+ const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);
2183
+ const proofBlock = socialProofBlock();
2184
+ const user = [
2185
+ `FOUNDER: ${ctx.cfg.founderName}`,
2186
+ `PRODUCT: ${ctx.cfg.productOneLiner}`,
2187
+ `PROSPECT: ${ctx.prospect.name ?? "(unknown)"}`,
2188
+ `EMAIL: ${ctx.prospect.email ?? ""}`,
2189
+ `COMPANY: ${ctx.prospect.company ?? "(unknown)"}`,
2190
+ ...opts.contextLines,
2191
+ ...priorBlock ? ["", priorBlock] : [],
2192
+ ...proofBlock ? ["", proofBlock] : []
2193
+ ].join("\n");
2194
+ const parsed = tryParseJsonObject((await complete({
2195
+ messages: [{
2196
+ role: "system",
2197
+ content: system
2198
+ }, {
2199
+ role: "user",
2200
+ content: user
2201
+ }],
2202
+ temperature: .6,
2203
+ maxTokens: 500
2204
+ })).content, {});
2205
+ if (!parsed.subject || !parsed.body) return null;
2206
+ const cleaned = humanizeDraft({
2207
+ subject: parsed.subject.trim(),
2208
+ body: parsed.body.trim()
2209
+ });
2210
+ return {
2211
+ kind: "email",
2212
+ subject: cleaned.subject,
2213
+ body: cleaned.body
2214
+ };
2215
+ };
2216
+ }
2217
+ /**
2218
+ * Parse a prospect's prior sends for a given play into clean per-step rows.
2219
+ * Source of truth shared by the LLM PRIOR-EMAILS injection (which filters
2220
+ * legacy rows) and the /api/cadences view (which surfaces them with a
2221
+ * "body not captured" placeholder).
2222
+ */
2223
+ function getPriorStepsForProspect(prospectId, playName) {
2224
+ if (!prospectId) return [];
1856
2225
  let rows;
1857
2226
  try {
1858
2227
  rows = getLedger().listSequenceEventsForProspectPlay(prospectId, playName);
1859
2228
  } catch {
1860
- return null;
2229
+ return [];
1861
2230
  }
1862
- const usable = rows.flatMap((r) => {
2231
+ return rows.map((r) => {
1863
2232
  const meta = tryParseJsonObject(r.metadata_json ?? "", {});
1864
- if (!meta.body) return [];
1865
- return [{
1866
- step: r.step_index,
2233
+ return {
2234
+ stepIndex: r.step_index,
2235
+ label: meta.label ?? (r.step_index === 0 ? "initial send" : "follow-up"),
1867
2236
  subject: meta.subject ?? "(no subject)",
1868
- body: meta.body,
1869
- label: meta.label ?? (r.step_index === 0 ? "initial send" : "follow-up")
1870
- }];
2237
+ body: meta.body ?? null,
2238
+ sentAt: r.created_at,
2239
+ status: r.status ?? "sent"
2240
+ };
1871
2241
  });
1872
- if (usable.length === 0) return null;
2242
+ }
2243
+ function buildPriorEmailsBlock(prospectId, playName) {
2244
+ const prior = getPriorStepsForProspect(prospectId, playName).filter((r) => r.body !== null && r.body.length > 0);
2245
+ if (prior.length === 0) return null;
1873
2246
  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}) ---`);
2247
+ for (const row of prior) {
2248
+ lines.push(`--- step ${row.stepIndex} (${row.label}) ---`);
1876
2249
  lines.push(`Subject: ${row.subject}`);
1877
2250
  lines.push(row.body);
1878
2251
  }
1879
2252
  return lines.join("\n");
1880
2253
  }
1881
2254
  //#endregion
1882
- //#region ../../packages/plays/src/show-hn.ts
1883
- const PLAY_NAME$20 = "show-hn";
1884
- async function runShowHn(opts) {
1885
- const cfg = loadConfig();
1886
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1887
- const drafted = [];
1888
- for (const target of opts.targets) try {
1889
- const receiptIds = [];
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);
1896
- if (!opts.dryRun) {
1897
- const research = await deepResearch({
1898
- topic: `Recent public work and engineering decisions by ${target.founderName} on ${target.postTitle}`,
1899
- depth: "quick"
1900
- }, { playName: PLAY_NAME$20 });
1901
- receiptIds.push(research.receiptId);
1902
- dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1903
- }
1904
- const draft = await draftEmailFromPrompt({
1905
- promptName: "show-hn-email",
1906
- inputBlock: [
1907
- `FOUNDER: ${cfg.founderName}`,
1908
- `PRODUCT: ${cfg.productOneLiner}`,
1909
- `SHOW HN: ${target.postTitle}`,
1910
- `URL: ${target.postUrl}`,
1911
- `HOOK: ${target.hookSummary}`,
1912
- `DOSSIER:\n${dossier || "(dry-run; rely on the hook only)"}`
1913
- ].join("\n")
1914
- });
1915
- const flags = lintEmail(draft.subject, draft.body, 90);
1916
- const send = await sendDraftedEmail({
1917
- playName: PLAY_NAME$20,
1918
- to: target.founderEmail,
1919
- draft,
1920
- flags,
1921
- prospectMeta: {
1922
- name: target.founderName,
1923
- email: target.founderEmail,
1924
- company: extractCompany(target.postTitle),
1925
- linkedin_url: target.linkedinUrl ?? null,
1926
- phone: target.phone ?? null,
1927
- source: "show-hn"
1928
- },
1929
- metadata: {
1930
- postUrl: target.postUrl,
1931
- postTitle: target.postTitle
1932
- },
1933
- dryRun: opts.dryRun
1934
- });
1935
- drafted.push({
1936
- target,
1937
- subject: draft.subject,
1938
- body: draft.body,
1939
- receiptIds: [...receiptIds, ...send.receiptIds],
1940
- sent: send.sent,
1941
- flags
1942
- });
1943
- } catch (err) {
1944
- drafted.push({
1945
- target,
1946
- ...errorDraft(err?.message)
1947
- });
1948
- }
1949
- return { drafted };
1950
- }
1951
- function extractCompany(title) {
1952
- const m = title.match(/Show HN:\s*([^\s—–:|-]+)/i);
1953
- return m ? m[1] ?? null : null;
1954
- }
1955
- //#endregion
1956
- //#region ../../packages/plays/src/job-change.ts
1957
- const PLAY_NAME$19 = "job-change";
1958
- async function runJobChange(opts) {
2255
+ //#region ../../packages/plays/src/_run-play.ts
2256
+ /**
2257
+ * Run an email play over its targets. Behavior-preserving extraction of the
2258
+ * per-target loop that every email play used to hand-roll: enrich/research →
2259
+ * draft → lint → send → (optional) cadence enroll, with a per-target try/catch
2260
+ * so one bad target can't kill the batch.
2261
+ */
2262
+ async function runEmailPlay(def, opts) {
1959
2263
  const cfg = loadConfig();
1960
2264
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
1961
2265
  const drafted = [];
1962
2266
  for (const target of opts.targets) try {
1963
- const receiptIds = [];
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);
1971
- if (!opts.dryRun) {
1972
- const research = await deepResearch({
1973
- topic: `Public posts, talks, and recent decisions by ${target.name} (joined ${target.newCompany} as ${target.newRole}, formerly ${target.previousRole ?? "?"} at ${target.previousCompany ?? "?"})`,
1974
- depth: "quick"
1975
- }, { playName: PLAY_NAME$19 });
1976
- receiptIds.push(research.receiptId);
1977
- dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
1978
- }
2267
+ const prep = await def.prepare(target, opts.dryRun);
2268
+ const proof = socialProofBlock();
2269
+ const inputBlock = proof ? `${def.buildInputBlock(target, prep, cfg)}\n\n${proof}` : def.buildInputBlock(target, prep, cfg);
1979
2270
  const draft = await draftEmailFromPrompt({
1980
- promptName: "job-change-email",
1981
- inputBlock: [
1982
- `FOUNDER: ${cfg.founderName}`,
1983
- `PRODUCT: ${cfg.productOneLiner}`,
1984
- `PROSPECT: ${target.name}`,
1985
- `NEW ROLE: ${target.newRole} at ${target.newCompany}`,
1986
- `PREVIOUS: ${target.previousRole ?? "unknown"} at ${target.previousCompany ?? "unknown"}`,
1987
- `DOSSIER:\n${dossier || "(dry-run; rely on the trigger only)"}`
1988
- ].join("\n")
2271
+ promptName: def.promptName,
2272
+ inputBlock
1989
2273
  });
1990
- const flags = lintEmail(draft.subject, draft.body, 100);
2274
+ const flags = lintEmail(draft.subject, draft.body, def.maxBodyWords);
1991
2275
  const send = await sendDraftedEmail({
1992
- playName: PLAY_NAME$19,
1993
- to: target.email,
2276
+ playName: def.playName,
2277
+ to: def.toEmail(target),
1994
2278
  draft,
1995
2279
  flags,
1996
- prospectMeta: {
1997
- name: target.name,
1998
- email: target.email,
1999
- company: target.newCompany,
2000
- linkedin_url: target.linkedinUrl ?? null,
2001
- phone: target.phone ?? null,
2002
- source: "job-change"
2003
- },
2004
- metadata: {
2005
- newRole: target.newRole,
2006
- newCompany: target.newCompany
2007
- },
2280
+ prospectMeta: def.prospectMeta(target),
2281
+ ...def.metadata ? { metadata: def.metadata(target) } : {},
2008
2282
  dryRun: opts.dryRun
2009
2283
  });
2010
- if (send.sent) {
2011
- const prospect = getLedger().findProspectByEmail(target.email);
2284
+ if (send.sent && def.enrollCadence) {
2285
+ const prospect = getLedger().findProspectByEmail(def.toEmail(target));
2012
2286
  if (prospect) enrollInCadence({
2013
2287
  prospectId: prospect.id,
2014
- playName: PLAY_NAME$19
2288
+ playName: def.playName
2015
2289
  });
2016
2290
  }
2017
2291
  drafted.push({
2018
2292
  target,
2019
2293
  subject: draft.subject,
2020
2294
  body: draft.body,
2021
- receiptIds: [...receiptIds, ...send.receiptIds],
2295
+ receiptIds: [...prep.receiptIds, ...send.receiptIds],
2022
2296
  sent: send.sent,
2023
- flags
2297
+ flags,
2298
+ ...prep.extra ?? {}
2024
2299
  });
2025
2300
  } catch (err) {
2026
2301
  drafted.push({
2027
2302
  target,
2028
- ...errorDraft(err?.message)
2303
+ ...errorDraft(err?.message),
2304
+ ...def.errorExtra ?? {}
2029
2305
  });
2030
2306
  }
2031
2307
  return { drafted };
2032
2308
  }
2309
+ /**
2310
+ * The common `prepare` body for plays that personalize via `safeEnrich` (cached
2311
+ * by email, never throws) and, on real sends only, a `deepResearch` dossier.
2312
+ * Pass `research` only when you want the research call to fire — callers gate it
2313
+ * on `!dryRun` (and, for accelerator-batch, on a launch URL being present).
2314
+ */
2315
+ async function standardEnrich(opts) {
2316
+ const receiptIds = [];
2317
+ const enr = await safeEnrich(opts.enrichInput, { playName: opts.playName });
2318
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2319
+ let dossier = JSON.stringify(enr.result, null, 2).slice(0, opts.enrichSlice);
2320
+ if (opts.research) {
2321
+ const research = await deepResearch({
2322
+ topic: opts.research.topic,
2323
+ depth: "quick"
2324
+ }, { playName: opts.playName });
2325
+ receiptIds.push(research.receiptId);
2326
+ dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, opts.research.slice ?? 4e3);
2327
+ }
2328
+ return {
2329
+ receiptIds,
2330
+ dossier
2331
+ };
2332
+ }
2333
+ //#endregion
2334
+ //#region ../../packages/plays/src/accelerator-batch.ts
2335
+ const PLAY_NAME$20 = "accelerator-batch";
2336
+ function runAcceleratorBatch(opts) {
2337
+ const senderCohortFor = (t) => (t.senderCohort?.trim() || opts.senderCohort || "").trim();
2338
+ const offerFor = (t) => t.freeForCohortOffer ?? opts.freeForCohortOffer;
2339
+ return runEmailPlay({
2340
+ playName: PLAY_NAME$20,
2341
+ promptName: "accelerator-batch-email",
2342
+ maxBodyWords: 100,
2343
+ enrollCadence: true,
2344
+ toEmail: (t) => t.email,
2345
+ prepare: (t, dryRun) => standardEnrich({
2346
+ playName: PLAY_NAME$20,
2347
+ enrichInput: {
2348
+ ...t.email ? { email: t.email } : {},
2349
+ ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
2350
+ name: t.name
2351
+ },
2352
+ enrichSlice: 3500,
2353
+ ...!dryRun && t.launchUrl ? { research: { topic: `Recent public work and decisions by ${t.name} at ${t.company} (${t.cohort}). Pull launch context from ${t.launchUrl}.` } } : {}
2354
+ }),
2355
+ buildInputBlock: (t, prep, cfg) => [
2356
+ `FOUNDER: ${cfg.founderName}`,
2357
+ `PRODUCT: ${cfg.productOneLiner}`,
2358
+ `SENDER COHORT: ${senderCohortFor(t) || "(unspecified)"}`,
2359
+ `PROSPECT: ${t.name} at ${t.company}`,
2360
+ `PROSPECT COHORT: ${t.cohort}`,
2361
+ `PROSPECT PRODUCT: ${t.productOneLiner ?? "(unknown)"}`,
2362
+ `LAUNCH URL: ${t.launchUrl ?? "(none)"}`,
2363
+ `FREE-FOR-COHORT OFFER: ${offerFor(t) ?? "(no active offer for this cohort)"}`,
2364
+ `DOSSIER:\n${prep.dossier || "(dry-run; rely on the cohort match only)"}`
2365
+ ].join("\n"),
2366
+ prospectMeta: (t) => ({
2367
+ name: t.name,
2368
+ email: t.email,
2369
+ company: t.company,
2370
+ linkedin_url: t.linkedinUrl ?? null,
2371
+ phone: t.phone ?? null,
2372
+ source: `accelerator-${t.cohort}`
2373
+ }),
2374
+ metadata: (t) => ({
2375
+ senderCohort: senderCohortFor(t),
2376
+ prospectCohort: t.cohort
2377
+ })
2378
+ }, opts);
2379
+ }
2033
2380
  registerSequence({
2034
- playName: PLAY_NAME$19,
2381
+ playName: PLAY_NAME$20,
2035
2382
  steps: [{
2036
2383
  dayOffset: 5,
2037
2384
  channel: "email",
2038
2385
  breakOnReply: true,
2039
- label: "value follow-up",
2040
- builder: buildFollowUpEmail({
2041
- playName: PLAY_NAME$19,
2042
- promptName: "job-change-followup",
2043
- contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
2044
- })
2045
- }, {
2046
- dayOffset: 9,
2047
- channel: "email",
2048
- breakOnReply: true,
2049
- label: "breakup",
2386
+ label: "single follow-up + breakup",
2050
2387
  builder: buildFollowUpEmail({
2051
- playName: PLAY_NAME$19,
2388
+ playName: PLAY_NAME$20,
2052
2389
  promptName: "breakup-email",
2053
- contextLines: [`PLAY: job-change. Sender is closing the file.`]
2390
+ contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
2054
2391
  })
2055
2392
  }]
2056
2393
  });
2057
2394
  //#endregion
2058
- //#region ../../packages/plays/src/post-funding.ts
2059
- const PLAY_NAME$18 = "post-funding";
2060
- async function runPostFunding(opts) {
2395
+ //#region ../../packages/plays/src/breakup-revive.ts
2396
+ const PLAY_NAME$19 = "breakup-revive";
2397
+ async function runBreakupRevive(opts) {
2061
2398
  const cfg = loadConfig();
2062
2399
  if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2400
+ const targets = opts.targets ?? ledgerScanTargets(opts);
2063
2401
  const drafted = [];
2064
- for (const target of opts.targets) try {
2065
- const receiptIds = [];
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);
2073
- if (!opts.dryRun) {
2074
- const research = await deepResearch({
2075
- topic: `${target.company} ${target.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${target.sourceUrl}`,
2076
- depth: "quick"
2077
- }, { playName: PLAY_NAME$18 });
2078
- receiptIds.push(research.receiptId);
2079
- dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
2080
- }
2081
- const draft = await draftEmailFromPrompt({
2082
- promptName: "post-funding-email",
2083
- inputBlock: [
2084
- `FOUNDER: ${cfg.founderName}`,
2085
- `PRODUCT: ${cfg.productOneLiner}`,
2086
- `PROSPECT: ${target.name} at ${target.company}`,
2087
- `ROUND: ${target.round} ($${target.amountUsd.toLocaleString()})`,
2088
- `LEAD INVESTOR: ${target.leadInvestor ?? "(unspecified)"}`,
2089
- `SOURCE: ${target.sourceUrl}`,
2090
- `DOSSIER:\n${dossier || "(dry-run; rely on the round details only)"}`
2091
- ].join("\n")
2092
- });
2093
- const flags = lintEmail(draft.subject, draft.body, 100);
2094
- const send = await sendDraftedEmail({
2095
- playName: PLAY_NAME$18,
2096
- to: target.email,
2097
- draft,
2098
- flags,
2099
- prospectMeta: {
2100
- name: target.name,
2101
- email: target.email,
2102
- company: target.company,
2103
- linkedin_url: target.linkedinUrl ?? null,
2104
- phone: target.phone ?? null,
2105
- source: "post-funding"
2106
- },
2107
- metadata: {
2108
- round: target.round,
2109
- amountUsd: target.amountUsd,
2110
- leadInvestor: target.leadInvestor
2111
- },
2112
- dryRun: opts.dryRun
2113
- });
2114
- if (send.sent) {
2115
- const prospect = getLedger().findProspectByEmail(target.email);
2116
- if (prospect) enrollInCadence({
2117
- prospectId: prospect.id,
2118
- playName: PLAY_NAME$18
2402
+ for (const t of targets) {
2403
+ if (!t.email) continue;
2404
+ try {
2405
+ const draft = await draftEmailFromPrompt({
2406
+ promptName: "breakup-revive-email",
2407
+ inputBlock: [
2408
+ `FOUNDER: ${cfg.founderName}`,
2409
+ `PRODUCT: ${cfg.productOneLiner}`,
2410
+ `PROSPECT: ${t.name ?? "(unknown)"} at ${t.company ?? "(unknown)"}`,
2411
+ `DAYS SINCE LAST ACTIVITY: ${t.daysCold}`,
2412
+ `OPTIONAL VALUE DROP: ${opts.valueDrop ?? "(none — go with a probe question instead)"}`
2413
+ ].join("\n")
2414
+ });
2415
+ const flags = lintEmail(draft.subject, draft.body, 80);
2416
+ const send = await sendDraftedEmail({
2417
+ playName: PLAY_NAME$19,
2418
+ to: t.email,
2419
+ draft,
2420
+ flags,
2421
+ prospectMeta: {
2422
+ name: t.name,
2423
+ email: t.email,
2424
+ company: t.company,
2425
+ linkedin_url: t.linkedinUrl ?? null,
2426
+ phone: t.phone ?? null,
2427
+ source: "breakup-revive"
2428
+ },
2429
+ metadata: {
2430
+ daysCold: t.daysCold,
2431
+ lastEventAt: t.lastEventAt
2432
+ },
2433
+ dryRun: opts.dryRun
2434
+ });
2435
+ drafted.push({
2436
+ prospectEmail: t.email,
2437
+ prospectName: t.name,
2438
+ daysCold: t.daysCold,
2439
+ subject: draft.subject,
2440
+ body: draft.body,
2441
+ receiptIds: send.receiptIds,
2442
+ sent: send.sent,
2443
+ flags
2444
+ });
2445
+ } catch (err) {
2446
+ const stub = errorDraft(err?.message);
2447
+ drafted.push({
2448
+ prospectEmail: t.email,
2449
+ prospectName: t.name,
2450
+ daysCold: t.daysCold,
2451
+ subject: stub.subject,
2452
+ body: stub.body,
2453
+ receiptIds: stub.receiptIds,
2454
+ sent: stub.sent,
2455
+ flags: stub.flags
2119
2456
  });
2120
2457
  }
2121
- drafted.push({
2122
- target,
2123
- subject: draft.subject,
2124
- body: draft.body,
2125
- receiptIds: [...receiptIds, ...send.receiptIds],
2126
- sent: send.sent,
2127
- flags
2128
- });
2129
- } catch (err) {
2130
- drafted.push({
2131
- target,
2132
- ...errorDraft(err?.message)
2133
- });
2134
2458
  }
2135
2459
  return { drafted };
2136
2460
  }
2461
+ function ledgerScanTargets(opts) {
2462
+ return getLedger().listColdProspects({
2463
+ minDaysSinceLastEvent: opts.minDays ?? 60,
2464
+ maxDaysSinceLastEvent: opts.maxDays ?? 90,
2465
+ ...opts.limit ? { limit: opts.limit } : {}
2466
+ }).filter((p) => p.email != null).map((p) => ({
2467
+ name: p.name,
2468
+ email: p.email,
2469
+ company: p.company,
2470
+ daysCold: p.last_event_at ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1e3)) : 0,
2471
+ lastEventAt: p.last_event_at,
2472
+ linkedinUrl: p.linkedin_url ?? null,
2473
+ phone: p.phone ?? null
2474
+ }));
2475
+ }
2476
+ //#endregion
2477
+ //#region ../../packages/plays/src/competitor-switch.ts
2478
+ const PLAY_NAME$18 = "competitor-switch";
2479
+ function runCompetitorSwitch(opts) {
2480
+ return runEmailPlay({
2481
+ playName: PLAY_NAME$18,
2482
+ promptName: "competitor-switch-email",
2483
+ maxBodyWords: 100,
2484
+ enrollCadence: true,
2485
+ toEmail: (t) => t.email,
2486
+ prepare: async (t, dryRun) => {
2487
+ const receiptIds = [];
2488
+ let scrapedEvidence;
2489
+ const enr = await safeEnrich({
2490
+ ...t.email ? { email: t.email } : {},
2491
+ name: t.name,
2492
+ companyDomain: emailDomain(t.email)
2493
+ }, { playName: PLAY_NAME$18 });
2494
+ if (enr.receiptId) receiptIds.push(enr.receiptId);
2495
+ const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
2496
+ if (!dryRun) {
2497
+ const haveEvidenceText = typeof t.evidenceText === "string" && t.evidenceText.trim().length > 0;
2498
+ if (t.evidenceUrl && !opts.skipBrowserScrape && !haveEvidenceText) {
2499
+ const browse = await browserTask({
2500
+ 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.`,
2501
+ startUrl: t.evidenceUrl,
2502
+ outputSchema: {
2503
+ type: "object",
2504
+ properties: {
2505
+ pain_points: {
2506
+ type: "array",
2507
+ items: { type: "string" }
2508
+ },
2509
+ wished_features: {
2510
+ type: "array",
2511
+ items: { type: "string" }
2512
+ },
2513
+ use_case_context: { type: "string" }
2514
+ }
2515
+ },
2516
+ maxSteps: 12
2517
+ }, { playName: PLAY_NAME$18 });
2518
+ receiptIds.push(browse.receiptId);
2519
+ scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
2520
+ }
2521
+ }
2522
+ return {
2523
+ receiptIds,
2524
+ dossier,
2525
+ ...scrapedEvidence ? { extra: { scrapedEvidence } } : {}
2526
+ };
2527
+ },
2528
+ buildInputBlock: (t, prep, cfg) => {
2529
+ const evidence = prep.extra?.scrapedEvidence ?? t.evidenceText ?? "(no evidence supplied)";
2530
+ return [
2531
+ `FOUNDER: ${cfg.founderName}`,
2532
+ `PRODUCT: ${cfg.productOneLiner}`,
2533
+ `PROSPECT: ${t.name} at ${t.company}`,
2534
+ `COMPETITOR: ${t.competitor}`,
2535
+ `EVIDENCE: ${evidence}`,
2536
+ `YOUR EDGE: ${t.yourEdge}`,
2537
+ `DOSSIER:\n${prep.dossier || "(dry-run)"}`
2538
+ ].join("\n");
2539
+ },
2540
+ prospectMeta: (t) => ({
2541
+ name: t.name,
2542
+ email: t.email,
2543
+ company: t.company,
2544
+ linkedin_url: t.linkedinUrl ?? null,
2545
+ phone: t.phone ?? null,
2546
+ source: "competitor-switch"
2547
+ }),
2548
+ metadata: (t) => ({
2549
+ competitor: t.competitor,
2550
+ evidenceUrl: t.evidenceUrl ?? null
2551
+ })
2552
+ }, opts);
2553
+ }
2137
2554
  registerSequence({
2138
2555
  playName: PLAY_NAME$18,
2139
2556
  steps: [{
2140
- dayOffset: 9,
2557
+ dayOffset: 3,
2141
2558
  channel: "email",
2142
2559
  breakOnReply: true,
2143
- label: "case-study follow-up",
2560
+ label: "value follow-up",
2144
2561
  builder: buildFollowUpEmail({
2145
2562
  playName: PLAY_NAME$18,
2146
- promptName: "post-funding-followup",
2147
- contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
2563
+ promptName: "competitor-switch-followup",
2564
+ contextLines: [`PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`]
2148
2565
  })
2149
2566
  }, {
2150
- dayOffset: 9,
2567
+ dayOffset: 8,
2151
2568
  channel: "email",
2152
2569
  breakOnReply: true,
2153
2570
  label: "breakup",
2154
2571
  builder: buildFollowUpEmail({
2155
2572
  playName: PLAY_NAME$18,
2156
2573
  promptName: "breakup-email",
2157
- contextLines: [`PLAY: post-funding.`]
2574
+ contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
2158
2575
  })
2159
2576
  }]
2160
2577
  });
2161
2578
  //#endregion
2162
- //#region ../../packages/plays/src/accelerator-batch.ts
2163
- const PLAY_NAME$17 = "accelerator-batch";
2164
- async function runAcceleratorBatch(opts) {
2165
- const cfg = loadConfig();
2166
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2167
- const drafted = [];
2168
- for (const target of opts.targets) try {
2169
- const receiptIds = [];
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);
2177
- if (!opts.dryRun) {
2178
- if (target.launchUrl) {
2179
- const research = await deepResearch({
2180
- topic: `Recent public work and decisions by ${target.name} at ${target.company} (${target.cohort}). Pull launch context from ${target.launchUrl}.`,
2181
- depth: "quick"
2182
- }, { playName: PLAY_NAME$17 });
2183
- receiptIds.push(research.receiptId);
2184
- dossier += "\n\n---\n\n" + JSON.stringify(research.result, null, 2).slice(0, 4e3);
2579
+ //#region ../../packages/plays/src/hiring-signal.ts
2580
+ const PLAY_NAME$17 = "hiring-signal";
2581
+ const NO_HOOK = "(no specific job post phrase scraped)";
2582
+ function runHiringSignal(opts) {
2583
+ return runEmailPlay({
2584
+ playName: PLAY_NAME$17,
2585
+ promptName: "hiring-signal-email",
2586
+ maxBodyWords: 100,
2587
+ enrollCadence: true,
2588
+ errorExtra: { jobPostHook: "(error)" },
2589
+ toEmail: (t) => t.email,
2590
+ prepare: async (t, dryRun) => {
2591
+ const receiptIds = [];
2592
+ let jobPostHook = NO_HOOK;
2593
+ if (!dryRun) {
2594
+ let jobUrl = t.jobPostUrl;
2595
+ if (!jobUrl && !opts.skipScrape) {
2596
+ const search = await webSearch({
2597
+ query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
2598
+ maxResults: 5
2599
+ }, { playName: PLAY_NAME$17 });
2600
+ receiptIds.push(search.receiptId);
2601
+ jobUrl = search.result.results[0]?.url;
2602
+ }
2603
+ if (jobUrl) {
2604
+ const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$17 });
2605
+ receiptIds.push(read.receiptId);
2606
+ const md = read.result.markdown ?? "";
2607
+ 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();
2608
+ }
2185
2609
  }
2186
- }
2187
- const draft = await draftEmailFromPrompt({
2188
- promptName: "accelerator-batch-email",
2189
- inputBlock: [
2190
- `FOUNDER: ${cfg.founderName}`,
2191
- `PRODUCT: ${cfg.productOneLiner}`,
2192
- `SENDER COHORT: ${opts.senderCohort}`,
2193
- `PROSPECT: ${target.name} at ${target.company}`,
2194
- `PROSPECT COHORT: ${target.cohort}`,
2195
- `PROSPECT PRODUCT: ${target.productOneLiner ?? "(unknown)"}`,
2196
- `LAUNCH URL: ${target.launchUrl ?? "(none)"}`,
2197
- `FREE-FOR-COHORT OFFER: ${opts.freeForCohortOffer ?? "(no active offer for this cohort)"}`,
2198
- `DOSSIER:\n${dossier || "(dry-run; rely on the cohort match only)"}`
2199
- ].join("\n")
2200
- });
2201
- const flags = lintEmail(draft.subject, draft.body, 100);
2202
- const send = await sendDraftedEmail({
2203
- playName: PLAY_NAME$17,
2204
- to: target.email,
2205
- draft,
2206
- flags,
2207
- prospectMeta: {
2208
- name: target.name,
2209
- email: target.email,
2210
- company: target.company,
2211
- linkedin_url: target.linkedinUrl ?? null,
2212
- phone: target.phone ?? null,
2213
- source: `accelerator-${target.cohort}`
2214
- },
2215
- metadata: {
2216
- senderCohort: opts.senderCohort,
2217
- prospectCohort: target.cohort
2218
- },
2219
- dryRun: opts.dryRun
2220
- });
2221
- if (send.sent) {
2222
- const prospect = getLedger().findProspectByEmail(target.email);
2223
- if (prospect) enrollInCadence({
2224
- prospectId: prospect.id,
2225
- playName: PLAY_NAME$17
2226
- });
2227
- }
2228
- drafted.push({
2229
- target,
2230
- subject: draft.subject,
2231
- body: draft.body,
2232
- receiptIds: [...receiptIds, ...send.receiptIds],
2233
- sent: send.sent,
2234
- flags
2235
- });
2236
- } catch (err) {
2237
- drafted.push({
2238
- target,
2239
- ...errorDraft(err?.message)
2240
- });
2241
- }
2242
- return { drafted };
2610
+ return {
2611
+ receiptIds,
2612
+ dossier: "",
2613
+ extra: { jobPostHook }
2614
+ };
2615
+ },
2616
+ buildInputBlock: (t, prep, cfg) => [
2617
+ `FOUNDER: ${cfg.founderName}`,
2618
+ `PRODUCT: ${cfg.productOneLiner}`,
2619
+ `PROSPECT: ${t.name} at ${t.company}`,
2620
+ `JOB TITLE: ${t.jobTitle}`,
2621
+ `JOB POST HOOK (real phrase from the post): ${prep.extra?.jobPostHook ?? NO_HOOK}`,
2622
+ `YOUR CLAIM: ${t.yourClaim}`
2623
+ ].join("\n"),
2624
+ prospectMeta: (t) => ({
2625
+ name: t.name,
2626
+ email: t.email,
2627
+ company: t.company,
2628
+ linkedin_url: t.linkedinUrl ?? null,
2629
+ phone: t.phone ?? null,
2630
+ source: "hiring-signal"
2631
+ }),
2632
+ metadata: (t) => ({
2633
+ jobTitle: t.jobTitle,
2634
+ jobPostUrl: t.jobPostUrl ?? null
2635
+ })
2636
+ }, opts);
2243
2637
  }
2244
2638
  registerSequence({
2245
2639
  playName: PLAY_NAME$17,
2246
2640
  steps: [{
2247
- dayOffset: 5,
2641
+ dayOffset: 3,
2248
2642
  channel: "email",
2249
2643
  breakOnReply: true,
2250
- label: "single follow-up + breakup",
2644
+ label: "value follow-up",
2251
2645
  builder: buildFollowUpEmail({
2252
2646
  playName: PLAY_NAME$17,
2253
- promptName: "breakup-email",
2254
- contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
2647
+ promptName: "hiring-signal-followup",
2648
+ contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`]
2255
2649
  })
2256
- }]
2257
- });
2258
- //#endregion
2259
- //#region ../../packages/plays/src/demo-no-show.ts
2260
- const PLAY_NAME$16 = "demo-no-show";
2261
- registerSequence({
2262
- playName: PLAY_NAME$16,
2263
- steps: [{
2264
- dayOffset: 3,
2650
+ }, {
2651
+ dayOffset: 8,
2265
2652
  channel: "email",
2266
2653
  breakOnReply: true,
2267
- label: "day-3 follow-up",
2654
+ label: "breakup",
2268
2655
  builder: buildFollowUpEmail({
2269
- playName: PLAY_NAME$16,
2270
- promptName: "demo-no-show-followup",
2271
- contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`]
2656
+ playName: PLAY_NAME$17,
2657
+ promptName: "breakup-email",
2658
+ contextLines: [`PLAY: hiring-signal. Final breakup.`]
2272
2659
  })
2273
2660
  }]
2274
2661
  });
2275
2662
  //#endregion
2276
- //#region ../../packages/plays/src/competitor-switch.ts
2277
- const PLAY_NAME$15 = "competitor-switch";
2278
- async function runCompetitorSwitch(opts) {
2279
- const cfg = loadConfig();
2280
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2281
- const drafted = [];
2282
- for (const t of opts.targets) try {
2283
- const receiptIds = [];
2284
- let scrapedEvidence;
2285
- const enr = await safeEnrich({
2663
+ //#region ../../packages/plays/src/job-change.ts
2664
+ const PLAY_NAME$16 = "job-change";
2665
+ const jobChangeDef = {
2666
+ playName: PLAY_NAME$16,
2667
+ promptName: "job-change-email",
2668
+ maxBodyWords: 100,
2669
+ enrollCadence: true,
2670
+ toEmail: (t) => t.email,
2671
+ prepare: (t, dryRun) => standardEnrich({
2672
+ playName: PLAY_NAME$16,
2673
+ enrichInput: {
2286
2674
  ...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);
2292
- if (!opts.dryRun) {
2293
- const haveEvidenceText = typeof t.evidenceText === "string" && t.evidenceText.trim().length > 0;
2294
- if (t.evidenceUrl && !opts.skipBrowserScrape && !haveEvidenceText) {
2295
- const browse = await browserTask({
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.`,
2297
- startUrl: t.evidenceUrl,
2298
- outputSchema: {
2299
- type: "object",
2300
- properties: {
2301
- pain_points: {
2302
- type: "array",
2303
- items: { type: "string" }
2304
- },
2305
- wished_features: {
2306
- type: "array",
2307
- items: { type: "string" }
2308
- },
2309
- use_case_context: { type: "string" }
2310
- }
2311
- },
2312
- maxSteps: 12
2313
- }, { playName: PLAY_NAME$15 });
2314
- receiptIds.push(browse.receiptId);
2315
- scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
2316
- }
2317
- }
2318
- const evidence = scrapedEvidence ?? t.evidenceText ?? "(no evidence supplied)";
2319
- const draft = await draftEmailFromPrompt({
2320
- promptName: "competitor-switch-email",
2321
- inputBlock: [
2322
- `FOUNDER: ${cfg.founderName}`,
2323
- `PRODUCT: ${cfg.productOneLiner}`,
2324
- `PROSPECT: ${t.name} at ${t.company}`,
2325
- `COMPETITOR: ${t.competitor}`,
2326
- `EVIDENCE: ${evidence}`,
2327
- `YOUR EDGE: ${t.yourEdge}`,
2328
- `DOSSIER:\n${dossier || "(dry-run)"}`
2329
- ].join("\n")
2330
- });
2331
- const flags = lintEmail(draft.subject, draft.body, 100);
2332
- const send = await sendDraftedEmail({
2333
- playName: PLAY_NAME$15,
2334
- to: t.email,
2335
- draft,
2336
- flags,
2337
- prospectMeta: {
2338
- name: t.name,
2339
- email: t.email,
2340
- company: t.company,
2341
- linkedin_url: t.linkedinUrl ?? null,
2342
- phone: t.phone ?? null,
2343
- source: "competitor-switch"
2344
- },
2345
- metadata: {
2346
- competitor: t.competitor,
2347
- evidenceUrl: t.evidenceUrl ?? null
2348
- },
2349
- dryRun: opts.dryRun
2350
- });
2351
- if (send.sent) {
2352
- const prospect = getLedger().findProspectByEmail(t.email);
2353
- if (prospect) enrollInCadence({
2354
- prospectId: prospect.id,
2355
- playName: PLAY_NAME$15
2356
- });
2357
- }
2358
- drafted.push({
2359
- target: t,
2360
- subject: draft.subject,
2361
- body: draft.body,
2362
- receiptIds: [...receiptIds, ...send.receiptIds],
2363
- sent: send.sent,
2364
- flags,
2365
- ...scrapedEvidence ? { scrapedEvidence } : {}
2366
- });
2367
- } catch (err) {
2368
- drafted.push({
2369
- target: t,
2370
- ...errorDraft(err?.message)
2371
- });
2372
- }
2373
- return { drafted };
2374
- }
2375
- function extractDomain$1(email) {
2376
- const at = email.indexOf("@");
2377
- if (at < 0) return void 0;
2378
- return email.slice(at + 1);
2675
+ ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
2676
+ name: t.name
2677
+ },
2678
+ enrichSlice: 4e3,
2679
+ ...dryRun ? {} : { research: { topic: `Public posts, talks, and recent decisions by ${t.name} (joined ${t.newCompany} as ${t.newRole}, formerly ${t.previousRole ?? "?"} at ${t.previousCompany ?? "?"})` } }
2680
+ }),
2681
+ buildInputBlock: (t, prep, cfg) => [
2682
+ `FOUNDER: ${cfg.founderName}`,
2683
+ `PRODUCT: ${cfg.productOneLiner}`,
2684
+ `PROSPECT: ${t.name}`,
2685
+ `NEW ROLE: ${t.newRole} at ${t.newCompany}`,
2686
+ `PREVIOUS: ${t.previousRole ?? "unknown"} at ${t.previousCompany ?? "unknown"}`,
2687
+ `DOSSIER:\n${prep.dossier || "(dry-run; rely on the trigger only)"}`
2688
+ ].join("\n"),
2689
+ prospectMeta: (t) => ({
2690
+ name: t.name,
2691
+ email: t.email,
2692
+ company: t.newCompany,
2693
+ linkedin_url: t.linkedinUrl ?? null,
2694
+ phone: t.phone ?? null,
2695
+ source: "job-change"
2696
+ }),
2697
+ metadata: (t) => ({
2698
+ newRole: t.newRole,
2699
+ newCompany: t.newCompany
2700
+ })
2701
+ };
2702
+ function runJobChange(opts) {
2703
+ return runEmailPlay(jobChangeDef, opts);
2379
2704
  }
2380
2705
  registerSequence({
2381
- playName: PLAY_NAME$15,
2706
+ playName: PLAY_NAME$16,
2382
2707
  steps: [{
2383
- dayOffset: 3,
2708
+ dayOffset: 5,
2384
2709
  channel: "email",
2385
2710
  breakOnReply: true,
2386
2711
  label: "value follow-up",
2387
2712
  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.`]
2713
+ playName: PLAY_NAME$16,
2714
+ promptName: "job-change-followup",
2715
+ contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
2391
2716
  })
2392
2717
  }, {
2393
- dayOffset: 8,
2718
+ dayOffset: 9,
2394
2719
  channel: "email",
2395
2720
  breakOnReply: true,
2396
2721
  label: "breakup",
2397
2722
  builder: buildFollowUpEmail({
2398
- playName: PLAY_NAME$15,
2723
+ playName: PLAY_NAME$16,
2399
2724
  promptName: "breakup-email",
2400
- contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
2725
+ contextLines: [`PLAY: job-change. Sender is closing the file.`]
2401
2726
  })
2402
2727
  }]
2403
2728
  });
2404
2729
  //#endregion
2405
- //#region ../../packages/plays/src/stack-consolidation.ts
2406
- const PLAY_NAME$14 = "stack-consolidation";
2407
- async function runStackConsolidation(opts) {
2408
- const cfg = loadConfig();
2409
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2410
- const drafted = [];
2411
- for (const t of opts.targets) try {
2412
- const receiptIds = [];
2413
- const enr = await safeEnrich({
2414
- ...t.email ? { email: t.email } : {},
2730
+ //#region ../../packages/plays/src/podcast-guest.ts
2731
+ const PLAY_NAME$15 = "podcast-guest";
2732
+ function runPodcastGuest(opts) {
2733
+ return runEmailPlay({
2734
+ playName: PLAY_NAME$15,
2735
+ promptName: "podcast-guest-email",
2736
+ maxBodyWords: 90,
2737
+ enrollCadence: true,
2738
+ toEmail: (t) => t.email,
2739
+ prepare: async (t, dryRun) => {
2740
+ const receiptIds = [];
2741
+ let dossier = "";
2742
+ if (!dryRun && !opts.skipSearch) {
2743
+ const s = await webSearch({
2744
+ query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
2745
+ maxResults: 3
2746
+ }, { playName: PLAY_NAME$15 });
2747
+ receiptIds.push(s.receiptId);
2748
+ dossier = s.result.results.slice(0, 2).map((r) => `- ${r.title}: ${r.description}`).join("\n");
2749
+ }
2750
+ return {
2751
+ receiptIds,
2752
+ dossier
2753
+ };
2754
+ },
2755
+ buildInputBlock: (t, prep, cfg) => [
2756
+ `FOUNDER: ${cfg.founderName}`,
2757
+ `PRODUCT: ${cfg.productOneLiner}`,
2758
+ `PROSPECT: ${t.name} at ${t.company}`,
2759
+ `PODCAST: ${t.podcast}`,
2760
+ `EPISODE: ${t.episodeTitle}`,
2761
+ `HOOK QUOTE: ${t.hookQuote}`,
2762
+ `BRIDGE TO YOUR WORK: ${t.bridge ?? "(none — keep the email purely about their point)"}`,
2763
+ `EXTRA CONTEXT FROM SEARCH:\n${prep.dossier || "(none)"}`
2764
+ ].join("\n"),
2765
+ prospectMeta: (t) => ({
2415
2766
  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);
2420
- const draft = await draftEmailFromPrompt({
2421
- promptName: "stack-consolidation-email",
2422
- inputBlock: [
2423
- `FOUNDER: ${cfg.founderName}`,
2424
- `PRODUCT: ${cfg.productOneLiner}`,
2425
- `PROSPECT: ${t.name} at ${t.company}`,
2426
- `STACK: ${t.vendorStack}`,
2427
- `YOUR EDGE: ${t.yourEdge}`,
2428
- `DOSSIER:\n${dossier || "(dry-run)"}`
2429
- ].join("\n")
2430
- });
2431
- const flags = lintEmail(draft.subject, draft.body, 100);
2432
- const send = await sendDraftedEmail({
2433
- playName: PLAY_NAME$14,
2434
- to: t.email,
2435
- draft,
2436
- flags,
2437
- prospectMeta: {
2438
- name: t.name,
2439
- email: t.email,
2440
- company: t.company,
2441
- linkedin_url: t.linkedinUrl ?? null,
2442
- phone: t.phone ?? null,
2443
- source: "stack-consolidation"
2444
- },
2445
- metadata: {
2446
- vendorStack: t.vendorStack,
2447
- evidenceUrl: t.evidenceUrl ?? null
2448
- },
2449
- dryRun: opts.dryRun
2450
- });
2451
- if (send.sent) {
2452
- const prospect = getLedger().findProspectByEmail(t.email);
2453
- if (prospect) enrollInCadence({
2454
- prospectId: prospect.id,
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 };
2767
+ email: t.email,
2768
+ company: t.company,
2769
+ linkedin_url: t.linkedinUrl ?? null,
2770
+ phone: t.phone ?? null,
2771
+ source: "podcast-guest"
2772
+ }),
2773
+ metadata: (t) => ({
2774
+ podcast: t.podcast,
2775
+ episodeTitle: t.episodeTitle
2776
+ })
2777
+ }, opts);
2473
2778
  }
2474
- function extractDomain(email) {
2475
- const at = email.indexOf("@");
2476
- if (at < 0) return void 0;
2477
- return email.slice(at + 1);
2779
+ registerSequence({
2780
+ playName: PLAY_NAME$15,
2781
+ steps: []
2782
+ });
2783
+ //#endregion
2784
+ //#region ../../packages/plays/src/post-funding.ts
2785
+ const PLAY_NAME$14 = "post-funding";
2786
+ const postFundingDef = {
2787
+ playName: PLAY_NAME$14,
2788
+ promptName: "post-funding-email",
2789
+ maxBodyWords: 100,
2790
+ enrollCadence: true,
2791
+ toEmail: (t) => t.email,
2792
+ prepare: (t, dryRun) => standardEnrich({
2793
+ playName: PLAY_NAME$14,
2794
+ enrichInput: {
2795
+ ...t.email ? { email: t.email } : {},
2796
+ ...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
2797
+ name: t.name
2798
+ },
2799
+ enrichSlice: 3500,
2800
+ ...dryRun ? {} : { research: { topic: `${t.company} ${t.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${t.sourceUrl}` } }
2801
+ }),
2802
+ buildInputBlock: (t, prep, cfg) => [
2803
+ `FOUNDER: ${cfg.founderName}`,
2804
+ `PRODUCT: ${cfg.productOneLiner}`,
2805
+ `PROSPECT: ${t.name} at ${t.company}`,
2806
+ `ROUND: ${t.round} ($${t.amountUsd.toLocaleString()})`,
2807
+ `LEAD INVESTOR: ${t.leadInvestor ?? "(unspecified)"}`,
2808
+ `SOURCE: ${t.sourceUrl}`,
2809
+ `DOSSIER:\n${prep.dossier || "(dry-run; rely on the round details only)"}`
2810
+ ].join("\n"),
2811
+ prospectMeta: (t) => ({
2812
+ name: t.name,
2813
+ email: t.email,
2814
+ company: t.company,
2815
+ linkedin_url: t.linkedinUrl ?? null,
2816
+ phone: t.phone ?? null,
2817
+ source: "post-funding"
2818
+ }),
2819
+ metadata: (t) => ({
2820
+ round: t.round,
2821
+ amountUsd: t.amountUsd,
2822
+ leadInvestor: t.leadInvestor
2823
+ })
2824
+ };
2825
+ function runPostFunding(opts) {
2826
+ return runEmailPlay(postFundingDef, opts);
2478
2827
  }
2479
2828
  registerSequence({
2480
2829
  playName: PLAY_NAME$14,
2481
2830
  steps: [{
2482
- dayOffset: 3,
2831
+ dayOffset: 9,
2483
2832
  channel: "email",
2484
2833
  breakOnReply: true,
2485
- label: "value follow-up",
2834
+ label: "case-study follow-up",
2486
2835
  builder: buildFollowUpEmail({
2487
2836
  playName: PLAY_NAME$14,
2488
- promptName: "stack-consolidation-followup",
2489
- contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
2837
+ promptName: "post-funding-followup",
2838
+ contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
2490
2839
  })
2491
2840
  }, {
2492
- dayOffset: 8,
2841
+ dayOffset: 9,
2493
2842
  channel: "email",
2494
2843
  breakOnReply: true,
2495
2844
  label: "breakup",
2496
2845
  builder: buildFollowUpEmail({
2497
2846
  playName: PLAY_NAME$14,
2498
2847
  promptName: "breakup-email",
2499
- contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
2848
+ contextLines: [`PLAY: post-funding.`]
2500
2849
  })
2501
2850
  }]
2502
2851
  });
2503
2852
  //#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
2566
- });
2567
- }
2568
- drafted.push({
2569
- target: t,
2570
- subject: draft.subject,
2571
- body: draft.body,
2572
- jobPostHook,
2573
- receiptIds: [...receiptIds, ...send.receiptIds],
2574
- sent: send.sent,
2575
- flags
2576
- });
2577
- } catch (err) {
2578
- drafted.push({
2579
- target: t,
2580
- jobPostHook: "(error)",
2581
- ...errorDraft(err?.message)
2582
- });
2583
- }
2584
- return { drafted };
2853
+ //#region ../../packages/plays/src/show-hn.ts
2854
+ const PLAY_NAME$13 = "show-hn";
2855
+ const showHnDef = {
2856
+ playName: PLAY_NAME$13,
2857
+ promptName: "show-hn-email",
2858
+ maxBodyWords: 90,
2859
+ toEmail: (t) => t.founderEmail,
2860
+ prepare: (t, dryRun) => standardEnrich({
2861
+ playName: PLAY_NAME$13,
2862
+ enrichInput: {
2863
+ email: t.founderEmail,
2864
+ name: t.founderName
2865
+ },
2866
+ enrichSlice: 3500,
2867
+ ...dryRun ? {} : { research: { topic: `Recent public work and engineering decisions by ${t.founderName} on ${t.postTitle}` } }
2868
+ }),
2869
+ buildInputBlock: (t, prep, cfg) => [
2870
+ `FOUNDER: ${cfg.founderName}`,
2871
+ `PRODUCT: ${cfg.productOneLiner}`,
2872
+ `SHOW HN: ${t.postTitle}`,
2873
+ `URL: ${t.postUrl}`,
2874
+ `HOOK: ${t.hookSummary}`,
2875
+ `DOSSIER:\n${prep.dossier || "(dry-run; rely on the hook only)"}`
2876
+ ].join("\n"),
2877
+ prospectMeta: (t) => ({
2878
+ name: t.founderName,
2879
+ email: t.founderEmail,
2880
+ company: extractCompany(t.postTitle),
2881
+ linkedin_url: t.linkedinUrl ?? null,
2882
+ phone: t.phone ?? null,
2883
+ source: "show-hn"
2884
+ }),
2885
+ metadata: (t) => ({
2886
+ postUrl: t.postUrl,
2887
+ postTitle: t.postTitle
2888
+ })
2889
+ };
2890
+ function runShowHn(opts) {
2891
+ return runEmailPlay(showHnDef, opts);
2892
+ }
2893
+ function extractCompany(title) {
2894
+ const m = title.match(/Show HN:\s*([^\s—–:|-]+)/i);
2895
+ return m ? m[1] ?? null : null;
2896
+ }
2897
+ //#endregion
2898
+ //#region ../../packages/plays/src/stack-consolidation.ts
2899
+ const PLAY_NAME$12 = "stack-consolidation";
2900
+ const stackConsolidationDef = {
2901
+ playName: PLAY_NAME$12,
2902
+ promptName: "stack-consolidation-email",
2903
+ maxBodyWords: 100,
2904
+ enrollCadence: true,
2905
+ toEmail: (t) => t.email,
2906
+ prepare: (t) => standardEnrich({
2907
+ playName: PLAY_NAME$12,
2908
+ enrichInput: {
2909
+ ...t.email ? { email: t.email } : {},
2910
+ name: t.name,
2911
+ companyDomain: emailDomain(t.email)
2912
+ },
2913
+ enrichSlice: 3500
2914
+ }),
2915
+ buildInputBlock: (t, prep, cfg) => [
2916
+ `FOUNDER: ${cfg.founderName}`,
2917
+ `PRODUCT: ${cfg.productOneLiner}`,
2918
+ `PROSPECT: ${t.name} at ${t.company}`,
2919
+ `STACK: ${t.vendorStack}`,
2920
+ `YOUR EDGE: ${t.yourEdge}`,
2921
+ `DOSSIER:\n${prep.dossier || "(dry-run)"}`
2922
+ ].join("\n"),
2923
+ prospectMeta: (t) => ({
2924
+ name: t.name,
2925
+ email: t.email,
2926
+ company: t.company,
2927
+ linkedin_url: t.linkedinUrl ?? null,
2928
+ phone: t.phone ?? null,
2929
+ source: "stack-consolidation"
2930
+ }),
2931
+ metadata: (t) => ({
2932
+ vendorStack: t.vendorStack,
2933
+ evidenceUrl: t.evidenceUrl ?? null
2934
+ })
2935
+ };
2936
+ function runStackConsolidation(opts) {
2937
+ return runEmailPlay(stackConsolidationDef, opts);
2585
2938
  }
2586
2939
  registerSequence({
2587
- playName: PLAY_NAME$13,
2940
+ playName: PLAY_NAME$12,
2588
2941
  steps: [{
2589
2942
  dayOffset: 3,
2590
2943
  channel: "email",
2591
2944
  breakOnReply: true,
2592
2945
  label: "value follow-up",
2593
2946
  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.`]
2947
+ playName: PLAY_NAME$12,
2948
+ promptName: "stack-consolidation-followup",
2949
+ contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
2597
2950
  })
2598
2951
  }, {
2599
2952
  dayOffset: 8,
@@ -2601,173 +2954,374 @@ registerSequence({
2601
2954
  breakOnReply: true,
2602
2955
  label: "breakup",
2603
2956
  builder: buildFollowUpEmail({
2604
- playName: PLAY_NAME$13,
2957
+ playName: PLAY_NAME$12,
2605
2958
  promptName: "breakup-email",
2606
- contextLines: [`PLAY: hiring-signal. Final breakup.`]
2959
+ contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
2607
2960
  })
2608
2961
  }]
2609
2962
  });
2610
2963
  //#endregion
2611
- //#region ../../packages/plays/src/podcast-guest.ts
2612
- const PLAY_NAME$12 = "podcast-guest";
2613
- async function runPodcastGuest(opts) {
2614
- const cfg = loadConfig();
2615
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2616
- const drafted = [];
2617
- for (const t of opts.targets) try {
2618
- const receiptIds = [];
2619
- let extra = "";
2620
- if (!opts.dryRun) {
2621
- if (!opts.skipSearch) {
2622
- const s = await webSearch({
2623
- query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
2624
- maxResults: 3
2625
- }, { playName: PLAY_NAME$12 });
2626
- receiptIds.push(s.receiptId);
2627
- extra = s.result.results.slice(0, 2).map((r) => `- ${r.title}: ${r.description}`).join("\n");
2628
- }
2629
- }
2630
- const draft = await draftEmailFromPrompt({
2631
- promptName: "podcast-guest-email",
2632
- inputBlock: [
2633
- `FOUNDER: ${cfg.founderName}`,
2634
- `PRODUCT: ${cfg.productOneLiner}`,
2635
- `PROSPECT: ${t.name} at ${t.company}`,
2636
- `PODCAST: ${t.podcast}`,
2637
- `EPISODE: ${t.episodeTitle}`,
2638
- `HOOK QUOTE: ${t.hookQuote}`,
2639
- `BRIDGE TO YOUR WORK: ${t.bridge ?? "(none — keep the email purely about their point)"}`,
2640
- `EXTRA CONTEXT FROM SEARCH:\n${extra || "(none)"}`
2641
- ].join("\n")
2642
- });
2643
- const flags = lintEmail(draft.subject, draft.body, 90);
2644
- const send = await sendDraftedEmail({
2645
- playName: PLAY_NAME$12,
2646
- to: t.email,
2647
- draft,
2648
- flags,
2649
- prospectMeta: {
2650
- name: t.name,
2651
- email: t.email,
2652
- company: t.company,
2653
- linkedin_url: t.linkedinUrl ?? null,
2654
- phone: t.phone ?? null,
2655
- source: "podcast-guest"
2656
- },
2657
- metadata: {
2658
- podcast: t.podcast,
2659
- episodeTitle: t.episodeTitle
2660
- },
2661
- dryRun: opts.dryRun
2662
- });
2663
- if (send.sent) {
2664
- const prospect = getLedger().findProspectByEmail(t.email);
2665
- if (prospect) enrollInCadence({
2666
- prospectId: prospect.id,
2667
- playName: PLAY_NAME$12
2668
- });
2669
- }
2670
- drafted.push({
2671
- target: t,
2672
- subject: draft.subject,
2673
- body: draft.body,
2674
- receiptIds: [...receiptIds, ...send.receiptIds],
2675
- sent: send.sent,
2676
- flags
2677
- });
2678
- } catch (err) {
2679
- drafted.push({
2680
- target: t,
2681
- ...errorDraft(err?.message)
2682
- });
2683
- }
2684
- return { drafted };
2964
+ //#region ../../packages/plays/src/registry.ts
2965
+ /**
2966
+ * Single source of truth mapping a play name → its runner. Both the server's
2967
+ * `/api/run` dispatch and the queue drainer look plays up here, so adding a
2968
+ * play means registering it once (its file + this table) instead of editing
2969
+ * two parallel switch statements that silently drifted apart.
2970
+ */
2971
+ const PLAYS = {
2972
+ "show-hn": { run: (o) => runShowHn({
2973
+ dryRun: o.dryRun,
2974
+ targets: o.targets
2975
+ }) },
2976
+ "job-change": { run: (o) => runJobChange({
2977
+ dryRun: o.dryRun,
2978
+ targets: o.targets
2979
+ }) },
2980
+ "post-funding": { run: (o) => runPostFunding({
2981
+ dryRun: o.dryRun,
2982
+ targets: o.targets
2983
+ }) },
2984
+ "accelerator-batch": { run: (o) => runAcceleratorBatch({
2985
+ dryRun: o.dryRun,
2986
+ targets: o.targets,
2987
+ ...o.senderCohort ? { senderCohort: o.senderCohort } : {},
2988
+ ...o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {}
2989
+ }) },
2990
+ "hiring-signal": { run: (o) => runHiringSignal({
2991
+ dryRun: o.dryRun,
2992
+ targets: o.targets
2993
+ }) },
2994
+ "podcast-guest": { run: (o) => runPodcastGuest({
2995
+ dryRun: o.dryRun,
2996
+ targets: o.targets
2997
+ }) },
2998
+ "competitor-switch": { run: (o) => runCompetitorSwitch({
2999
+ dryRun: o.dryRun,
3000
+ targets: o.targets
3001
+ }) },
3002
+ "stack-consolidation": { run: (o) => runStackConsolidation({
3003
+ dryRun: o.dryRun,
3004
+ targets: o.targets
3005
+ }) },
3006
+ "breakup-revive": { run: (o) => runBreakupRevive({
3007
+ dryRun: o.dryRun,
3008
+ targets: o.targets
3009
+ }) }
3010
+ };
3011
+ function isSupportedPlay(name) {
3012
+ return Object.prototype.hasOwnProperty.call(PLAYS, name);
2685
3013
  }
3014
+ //#endregion
3015
+ //#region ../../packages/plays/src/demo-no-show.ts
3016
+ const PLAY_NAME$11 = "demo-no-show";
2686
3017
  registerSequence({
2687
- playName: PLAY_NAME$12,
2688
- steps: []
3018
+ playName: PLAY_NAME$11,
3019
+ steps: [{
3020
+ dayOffset: 3,
3021
+ channel: "email",
3022
+ breakOnReply: true,
3023
+ label: "day-3 follow-up",
3024
+ builder: buildFollowUpEmail({
3025
+ playName: PLAY_NAME$11,
3026
+ promptName: "demo-no-show-followup",
3027
+ contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`]
3028
+ })
3029
+ }]
2689
3030
  });
2690
3031
  //#endregion
2691
- //#region ../../packages/plays/src/breakup-revive.ts
2692
- const PLAY_NAME$11 = "breakup-revive";
2693
- async function runBreakupRevive(opts) {
2694
- const cfg = loadConfig();
2695
- if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
2696
- const targets = opts.targets ?? ledgerScanTargets(opts);
2697
- const drafted = [];
2698
- for (const t of targets) {
2699
- if (!t.email) continue;
3032
+ //#region src/api/cadences.ts
3033
+ /**
3034
+ * In-process tracker of cadence steps that have a fire-and-forget send in
3035
+ * flight. Populated by sendCadenceStepRoute + sendCadenceBatchRoute when
3036
+ * they kick off the background SDK send (~2 min per row), cleared per-row
3037
+ * as each send settles. Used by `toView` to surface `isSending: true` so
3038
+ * /cadences can visually mark in-flight rows AND gate them out of the
3039
+ * sendable-rows count. Lost on server restart (acceptable — in-flight SDK
3040
+ * calls die with the process anyway).
3041
+ */
3042
+ const inFlightSends = /* @__PURE__ */ new Set();
3043
+ const inFlightKey = (prospectId, playName) => `${prospectId}|${playName}`;
3044
+ function toView$3(row) {
3045
+ let nextStepDraft = null;
3046
+ if (row.next_step_draft_json) try {
3047
+ const parsed = JSON.parse(row.next_step_draft_json);
3048
+ nextStepDraft = {
3049
+ subject: parsed.subject,
3050
+ body: parsed.body,
3051
+ flags: parsed.flags ?? [],
3052
+ draftedAt: parsed.draftedAt
3053
+ };
3054
+ } catch {
3055
+ nextStepDraft = null;
3056
+ }
3057
+ const next = nextStepInfo(row.play_name, row.current_step);
3058
+ const priorSteps = getPriorStepsForProspect(row.prospect_id, row.play_name).map((s) => ({
3059
+ stepIndex: s.stepIndex,
3060
+ label: s.label,
3061
+ subject: s.subject,
3062
+ body: s.body,
3063
+ sentAt: s.sentAt
3064
+ }));
3065
+ return {
3066
+ prospectId: row.prospect_id,
3067
+ prospectEmail: row.prospect_email,
3068
+ prospectName: row.prospect_name,
3069
+ prospectCompany: row.prospect_company,
3070
+ playName: row.play_name,
3071
+ status: row.status,
3072
+ currentStep: row.current_step,
3073
+ enrolledAt: row.enrolled_at,
3074
+ nextDueAt: row.next_due_at,
3075
+ lastPolledAt: row.last_polled_at,
3076
+ nextStepDraft,
3077
+ nextStepLabel: next?.label ?? null,
3078
+ nextStepIsBreakup: next?.isBreakup ?? false,
3079
+ followupCount: playFollowupCount(row.play_name),
3080
+ priorSteps,
3081
+ isSending: inFlightSends.has(inFlightKey(row.prospect_id, row.play_name))
3082
+ };
3083
+ }
3084
+ function listCadences(req) {
3085
+ const all = new URL(req.url).searchParams.get("all") === "1";
3086
+ const ledger = getLedger();
3087
+ return jsonResponse({ cadences: (all ? ledger.listAllCadences() : ledger.listActiveCadences()).map(toView$3) }, 200, req);
3088
+ }
3089
+ function getCadence(req, params) {
3090
+ const id = Number.parseInt(params["id"] ?? "", 10);
3091
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
3092
+ const all = getLedger().listAllCadences().filter((c) => c.prospect_id === id);
3093
+ if (all.length === 0) return jsonResponse({ error: "no cadences for prospect" }, 404, req);
3094
+ return jsonResponse({ cadences: all.map(toView$3) }, 200, req);
3095
+ }
3096
+ function stopCadence(req, params) {
3097
+ const id = Number.parseInt(params["id"] ?? "", 10);
3098
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
3099
+ const playName = new URL(req.url).searchParams.get("play");
3100
+ const ledger = getLedger();
3101
+ const cadences = ledger.listAllCadences().filter((c) => {
3102
+ if (c.prospect_id !== id) return false;
3103
+ if (playName && c.play_name !== playName) return false;
3104
+ return c.status === "active";
3105
+ });
3106
+ for (const cad of cadences) ledger.setCadenceStatus({
3107
+ prospectId: id,
3108
+ playName: cad.play_name,
3109
+ status: "completed"
3110
+ });
3111
+ return jsonResponse({ stopped: cadences.length }, 200, req);
3112
+ }
3113
+ function parseProspectAndPlay(req, params) {
3114
+ const prospectId = Number.parseInt(params["id"] ?? "", 10);
3115
+ if (!Number.isFinite(prospectId)) return jsonResponse({ error: "bad id" }, 400, req);
3116
+ const playName = new URL(req.url).searchParams.get("play") ?? "";
3117
+ if (!playName) return jsonResponse({ error: "play query param required" }, 400, req);
3118
+ return {
3119
+ prospectId,
3120
+ playName
3121
+ };
3122
+ }
3123
+ async function previewCadenceStepRoute(req, params) {
3124
+ const parsed = parseProspectAndPlay(req, params);
3125
+ if (parsed instanceof Response) return parsed;
3126
+ try {
3127
+ const preview = await previewCadenceStep(parsed);
3128
+ return jsonResponse({
3129
+ subject: preview.subject,
3130
+ body: preview.body,
3131
+ flags: preview.flags,
3132
+ draftedAt: preview.draftedAt,
3133
+ stepLabel: preview.stepLabel,
3134
+ isBreakup: preview.isBreakup
3135
+ }, 200, req);
3136
+ } catch (err) {
3137
+ const msg = err.message ?? "preview failed";
3138
+ const status = msg.startsWith("no cadence") || msg.startsWith("cadence is") ? 409 : 500;
3139
+ return jsonResponse({ error: msg }, status, req);
3140
+ }
3141
+ }
3142
+ async function sendCadenceStepRoute(req, params) {
3143
+ const parsed = parseProspectAndPlay(req, params);
3144
+ if (parsed instanceof Response) return parsed;
3145
+ try {
3146
+ if (!getLedger().getCadenceDraft(parsed)) return jsonResponse({ error: "no persisted preview — click Preview first" }, 409, req);
3147
+ } catch (err) {
3148
+ return jsonResponse({ error: err.message ?? "send failed" }, 500, req);
3149
+ }
3150
+ const key = inFlightKey(parsed.prospectId, parsed.playName);
3151
+ inFlightSends.add(key);
3152
+ (async () => {
2700
3153
  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,
2734
- daysCold: t.daysCold,
2735
- subject: draft.subject,
2736
- body: draft.body,
2737
- receiptIds: send.receiptIds,
2738
- sent: send.sent,
2739
- flags
3154
+ await sendCadenceStep(parsed);
3155
+ } catch (err) {
3156
+ logEvent("cadence.send.failed", {
3157
+ prospect_id: parsed.prospectId,
3158
+ play_name: parsed.playName,
3159
+ message_120: (err?.message ?? "").slice(0, 120)
3160
+ }, "error");
3161
+ } finally {
3162
+ inFlightSends.delete(key);
3163
+ }
3164
+ })();
3165
+ return jsonResponse({ accepted: true }, 202, req);
3166
+ }
3167
+ async function parseBatchItems(req) {
3168
+ let body;
3169
+ try {
3170
+ body = await req.json();
3171
+ } catch {
3172
+ return jsonResponse({ error: "invalid JSON body" }, 400, req);
3173
+ }
3174
+ if (!Array.isArray(body.items)) return jsonResponse({ error: "items: array required" }, 400, req);
3175
+ const items = [];
3176
+ for (const raw of body.items) if (raw && typeof raw === "object" && "prospectId" in raw && "playName" in raw) {
3177
+ const it = raw;
3178
+ if (typeof it.prospectId === "number" && typeof it.playName === "string") items.push({
3179
+ prospectId: it.prospectId,
3180
+ playName: it.playName
3181
+ });
3182
+ }
3183
+ if (items.length === 0) return jsonResponse({ error: "no valid items in body" }, 400, req);
3184
+ return items;
3185
+ }
3186
+ async function previewCadenceBatchRoute(req) {
3187
+ const itemsOrErr = await parseBatchItems(req);
3188
+ if (itemsOrErr instanceof Response) return itemsOrErr;
3189
+ return jsonResponse({ results: await previewCadenceStepBatch(itemsOrErr) }, 200, req);
3190
+ }
3191
+ async function sendCadenceBatchRoute(req) {
3192
+ const itemsOrErr = await parseBatchItems(req);
3193
+ if (itemsOrErr instanceof Response) return itemsOrErr;
3194
+ const items = itemsOrErr;
3195
+ for (const item of items) inFlightSends.add(inFlightKey(item.prospectId, item.playName));
3196
+ (async () => {
3197
+ try {
3198
+ await sendCadenceStepBatch(items, (item) => {
3199
+ inFlightSends.delete(inFlightKey(item.prospectId, item.playName));
2740
3200
  });
2741
3201
  } 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
- });
3202
+ for (const item of items) inFlightSends.delete(inFlightKey(item.prospectId, item.playName));
3203
+ logEvent("cadence.batch.failed", { message_120: (err?.message ?? "").slice(0, 120) }, "error");
2753
3204
  }
3205
+ })();
3206
+ return jsonResponse({ accepted: items.length }, 202, req);
3207
+ }
3208
+ //#endregion
3209
+ //#region src/api/receipts.ts
3210
+ function toView$2(row) {
3211
+ return {
3212
+ id: row.id,
3213
+ playName: row.play_name,
3214
+ callType: row.call_type,
3215
+ costUsd: row.cost_usd,
3216
+ oneshotRequestId: row.oneshot_request_id,
3217
+ createdAt: row.created_at
3218
+ };
3219
+ }
3220
+ function listReceipts(req) {
3221
+ const url = new URL(req.url);
3222
+ const playName = url.searchParams.get("play") ?? void 0;
3223
+ const sinceDays = Number.parseInt(url.searchParams.get("sinceDays") ?? "", 10);
3224
+ const limit = Math.min(500, Number.parseInt(url.searchParams.get("limit") ?? "200", 10) || 200);
3225
+ const sinceIso = Number.isFinite(sinceDays) ? (/* @__PURE__ */ new Date(Date.now() - sinceDays * 24 * 3600 * 1e3)).toISOString() : void 0;
3226
+ return jsonResponse({ receipts: getLedger().listReceipts({
3227
+ ...playName ? { playName } : {},
3228
+ ...sinceIso ? { sinceIso } : {},
3229
+ limit
3230
+ }).map(toView$2) }, 200, req);
3231
+ }
3232
+ function getReceipt(req, params) {
3233
+ const id = Number.parseInt(params["id"] ?? "", 10);
3234
+ if (!Number.isFinite(id)) return jsonResponse({ error: "bad id" }, 400, req);
3235
+ const r = getLedger().getReceipt(id);
3236
+ if (!r) return jsonResponse({ error: "not found" }, 404, req);
3237
+ let parsed = null;
3238
+ if (r.signed_receipt) try {
3239
+ parsed = JSON.parse(r.signed_receipt);
3240
+ } catch {
3241
+ parsed = r.signed_receipt;
2754
3242
  }
2755
- return { drafted };
3243
+ return jsonResponse({ receipt: {
3244
+ id: r.id,
3245
+ playName: r.play_name,
3246
+ callType: r.call_type,
3247
+ costUsd: r.cost_usd,
3248
+ oneshotRequestId: r.oneshot_request_id,
3249
+ createdAt: r.created_at,
3250
+ signedReceipt: parsed
3251
+ } }, 200, req);
2756
3252
  }
2757
- function ledgerScanTargets(opts) {
2758
- return getLedger().listColdProspects({
2759
- minDaysSinceLastEvent: opts.minDays ?? 60,
2760
- maxDaysSinceLastEvent: opts.maxDays ?? 90,
2761
- ...opts.limit ? { limit: opts.limit } : {}
2762
- }).filter((p) => p.email != null).map((p) => ({
2763
- name: p.name,
2764
- email: p.email,
2765
- company: p.company,
2766
- daysCold: p.last_event_at ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1e3)) : 0,
2767
- lastEventAt: p.last_event_at,
2768
- linkedinUrl: p.linkedin_url ?? null,
2769
- phone: p.phone ?? null
2770
- }));
3253
+ //#endregion
3254
+ //#region src/api/inbox.ts
3255
+ /** "Jane Doe <jane@x.com>" → "jane@x.com"; bare addresses pass through. */
3256
+ function normalizeFrom(raw) {
3257
+ const m = raw.match(/<([^>]+)>/);
3258
+ return (m ? m[1] ?? raw : raw).trim().toLowerCase();
3259
+ }
3260
+ /**
3261
+ * Read-only view of the OneShot inbox (replies to outreach). Each email is
3262
+ * matched to a known prospect by sender address, annotated with the play +
3263
+ * cadence status when available. Live fetch — no storage. The SDK exposes only
3264
+ * inboxList (no reply/markRead), so this is read-only.
3265
+ */
3266
+ async function listInboxRoute(req) {
3267
+ const ledger = getLedger();
3268
+ let emails;
3269
+ try {
3270
+ emails = (await listInbox({ limit: 50 })).emails;
3271
+ } catch (err) {
3272
+ logEvent("inbox.list_failed", { message_120: (err?.message ?? "").slice(0, 120) }, "warn");
3273
+ return jsonResponse({
3274
+ replies: [],
3275
+ hasMore: false,
3276
+ error: "couldn't reach the inbox"
3277
+ }, 200, req);
3278
+ }
3279
+ const byEmail = /* @__PURE__ */ new Map();
3280
+ for (const c of ledger.listAllCadences()) {
3281
+ if (!c.prospect_email) continue;
3282
+ const key = c.prospect_email.trim().toLowerCase();
3283
+ const existing = byEmail.get(key);
3284
+ if (!existing || c.status === "replied" || c.status === "active" && existing.status !== "replied") byEmail.set(key, {
3285
+ name: c.prospect_name,
3286
+ company: c.prospect_company,
3287
+ playName: c.play_name,
3288
+ status: c.status
3289
+ });
3290
+ }
3291
+ const replies = emails.map((e) => {
3292
+ const fromEmail = normalizeFrom(e.from);
3293
+ let matched = null;
3294
+ const cadence = byEmail.get(fromEmail);
3295
+ if (cadence) matched = {
3296
+ name: cadence.name,
3297
+ company: cadence.company,
3298
+ playName: cadence.playName,
3299
+ cadenceStatus: cadence.status
3300
+ };
3301
+ else {
3302
+ const p = ledger.getProspectByEmail(fromEmail);
3303
+ if (p) matched = {
3304
+ name: p.name,
3305
+ company: p.company,
3306
+ playName: p.source,
3307
+ cadenceStatus: null
3308
+ };
3309
+ }
3310
+ return {
3311
+ id: e.id,
3312
+ fromEmail,
3313
+ fromRaw: e.from,
3314
+ subject: e.subject,
3315
+ receivedAt: e.received_at,
3316
+ body: e.body ?? "",
3317
+ matched
3318
+ };
3319
+ });
3320
+ const selfDomain = (loadConfig().sendingDomain ?? "").trim().toLowerCase();
3321
+ return jsonResponse({
3322
+ replies: replies.filter((r) => !selfDomain || !r.fromEmail.endsWith(`@${selfDomain}`)).toSorted((a, b) => a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : 0),
3323
+ hasMore: false
3324
+ }, 200, req);
2771
3325
  }
2772
3326
  //#endregion
2773
3327
  //#region src/api/plays.ts
@@ -2828,12 +3382,13 @@ function listPlays(req) {
2828
3382
  const seq = getSequence(p.name);
2829
3383
  const channels = seq ? Array.from(new Set(seq.steps.map((s) => s.channel))) : ["email"];
2830
3384
  const followupCount = seq?.steps.length ?? 0;
2831
- const hasBreakup = seq?.steps.some((s) => s.label?.toLowerCase().includes("breakup")) ?? false;
3385
+ const hasBreakup = seq ? isBreakupStepAt(seq, seq.steps.length - 1) : false;
2832
3386
  const days = cumulativeDays(seq);
2833
3387
  const steps = (seq?.steps ?? []).map((s, i) => ({
2834
3388
  day: days[i] ?? 0,
2835
3389
  label: s.label ?? `step ${i + 1}`,
2836
- channel: s.channel
3390
+ channel: s.channel,
3391
+ isBreakup: isBreakupLabel(s.label)
2837
3392
  }));
2838
3393
  return {
2839
3394
  name: p.name,
@@ -3004,6 +3559,10 @@ async function setup(req) {
3004
3559
  sendingDomain: mergeString(body.sendingDomain, current.sendingDomain),
3005
3560
  icpOneLiner: mergeString(body.icpOneLiner, current.icpOneLiner),
3006
3561
  cadenceOverrides: current.cadenceOverrides,
3562
+ founderCredentials: mergeString(body.founderCredentials, current.founderCredentials),
3563
+ productPortfolio: mergeString(body.productPortfolio, current.productPortfolio),
3564
+ partners: mergeString(body.partners, current.partners),
3565
+ mobileSignature: body.mobileSignature ?? current.mobileSignature,
3007
3566
  clientId: current.clientId
3008
3567
  });
3009
3568
  if (body.secrets && Object.keys(body.secrets).length > 0) saveSecrets(body.secrets);
@@ -3534,6 +4093,32 @@ async function enrichVerifiedContact(email, opts) {
3534
4093
  }
3535
4094
  }
3536
4095
  //#endregion
4096
+ //#region ../../packages/find/src/_parallel.ts
4097
+ /**
4098
+ * Run `fn` over `items` with at most `concurrency` Promises in flight at once.
4099
+ * Preserves input order in the result array. Errors propagate via Promise.all
4100
+ * — caller is expected to catch per-item internally if partial success matters.
4101
+ *
4102
+ * Worker-pool implementation: spawn `concurrency` workers that pull from a
4103
+ * shared cursor. Cheaper than a chunked Promise.all (which stalls on the
4104
+ * slowest item per chunk) and avoids the dependency surface of p-limit.
4105
+ */
4106
+ async function parallelMap(items, concurrency, fn) {
4107
+ const out = Array.from({ length: items.length });
4108
+ if (items.length === 0) return out;
4109
+ const workers = Math.max(1, Math.min(concurrency, items.length));
4110
+ let cursor = 0;
4111
+ async function worker() {
4112
+ while (true) {
4113
+ const i = cursor++;
4114
+ if (i >= items.length) return;
4115
+ out[i] = await fn(items[i], i);
4116
+ }
4117
+ }
4118
+ await Promise.all(Array.from({ length: workers }, () => worker()));
4119
+ return out;
4120
+ }
4121
+ //#endregion
3537
4122
  //#region ../../packages/find/src/show-hn.ts
3538
4123
  const HN_ALGOLIA = "https://hn.algolia.com/api/v1/search_by_date";
3539
4124
  const PLAY_NAME$8 = "show-hn";
@@ -3572,19 +4157,26 @@ async function runShowHnFinder(opts) {
3572
4157
  name: PLAY_NAME$8,
3573
4158
  candidates: result.candidates
3574
4159
  });
3575
- for (const hit of data.hits) {
3576
- if (result.enqueued >= limit) break;
4160
+ const concurrency = opts.concurrency ?? 3;
4161
+ let halted = false;
4162
+ await parallelMap(data.hits, concurrency, async (hit) => {
4163
+ if (halted) return;
4164
+ if (result.enqueued >= limit) {
4165
+ halted = true;
4166
+ return;
4167
+ }
3577
4168
  if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {
3578
4169
  result.halted = `max-cost cap (${opts.maxCostUsd})`;
3579
- break;
4170
+ halted = true;
4171
+ return;
3580
4172
  }
3581
4173
  if (hit.points < minPoints) {
3582
4174
  result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;
3583
- continue;
4175
+ return;
3584
4176
  }
3585
4177
  if (ledger.isQueueDuplicate(PLAY_NAME$8, hit.objectID)) {
3586
4178
  result.droppedDuplicate++;
3587
- continue;
4179
+ return;
3588
4180
  }
3589
4181
  const filter = await icpFilter({
3590
4182
  icp,
@@ -3609,16 +4201,16 @@ async function runShowHnFinder(opts) {
3609
4201
  initialStatus: "rejected",
3610
4202
  notes: `auto: ICP — ${filter.reason}`
3611
4203
  });
3612
- continue;
4204
+ return;
3613
4205
  }
3614
4206
  if (opts.dryRun) {
3615
4207
  result.enqueued++;
3616
- continue;
4208
+ return;
3617
4209
  }
3618
4210
  const domain = urlDomain(hit.url);
3619
4211
  if (!domain) {
3620
4212
  result.droppedEnrichment++;
3621
- continue;
4213
+ return;
3622
4214
  }
3623
4215
  const fullName = hit.author && hit.author.length > 0 ? hit.author : void 0;
3624
4216
  const skip = shouldSkipFindEmail({
@@ -3631,7 +4223,7 @@ async function runShowHnFinder(opts) {
3631
4223
  name: PLAY_NAME$8,
3632
4224
  reason: skip.reason
3633
4225
  }, "info");
3634
- continue;
4226
+ return;
3635
4227
  }
3636
4228
  const findInput = { companyDomain: domain };
3637
4229
  if (fullName) findInput.fullName = fullName;
@@ -3639,14 +4231,14 @@ async function runShowHnFinder(opts) {
3639
4231
  result.costUsd += found.result.cost ?? 0;
3640
4232
  if (!found.result.found || !found.result.email) {
3641
4233
  result.droppedEnrichment++;
3642
- continue;
4234
+ return;
3643
4235
  }
3644
4236
  const email = found.result.email;
3645
4237
  const verified = await verifyEmail({ email }, { playName: PLAY_NAME$8 });
3646
4238
  result.costUsd += verified.result.cost ?? 0;
3647
4239
  if (!verified.result.deliverable) {
3648
4240
  result.droppedEnrichment++;
3649
- continue;
4241
+ return;
3650
4242
  }
3651
4243
  if (isDuplicate({
3652
4244
  playName: PLAY_NAME$8,
@@ -3654,7 +4246,7 @@ async function runShowHnFinder(opts) {
3654
4246
  prospectEmail: email
3655
4247
  })) {
3656
4248
  result.droppedDuplicate++;
3657
- continue;
4249
+ return;
3658
4250
  }
3659
4251
  let hookSummary = (hit.story_text ?? "").trim().slice(0, 280);
3660
4252
  if (hookSummary.length < 40 && hit.url) try {
@@ -3701,7 +4293,7 @@ async function runShowHnFinder(opts) {
3701
4293
  notes: filter.reason
3702
4294
  }) != null) result.enqueued++;
3703
4295
  else result.droppedDuplicate++;
3704
- }
4296
+ });
3705
4297
  logEvent("finder.done", {
3706
4298
  name: PLAY_NAME$8,
3707
4299
  candidates: result.candidates,
@@ -4256,32 +4848,6 @@ function parseAcceleratorLaunchExtract(raw) {
4256
4848
  });
4257
4849
  }
4258
4850
  //#endregion
4259
- //#region ../../packages/find/src/_parallel.ts
4260
- /**
4261
- * Run `fn` over `items` with at most `concurrency` Promises in flight at once.
4262
- * Preserves input order in the result array. Errors propagate via Promise.all
4263
- * — caller is expected to catch per-item internally if partial success matters.
4264
- *
4265
- * Worker-pool implementation: spawn `concurrency` workers that pull from a
4266
- * shared cursor. Cheaper than a chunked Promise.all (which stalls on the
4267
- * slowest item per chunk) and avoids the dependency surface of p-limit.
4268
- */
4269
- async function parallelMap(items, concurrency, fn) {
4270
- const out = Array.from({ length: items.length });
4271
- if (items.length === 0) return out;
4272
- const workers = Math.max(1, Math.min(concurrency, items.length));
4273
- let cursor = 0;
4274
- async function worker() {
4275
- while (true) {
4276
- const i = cursor++;
4277
- if (i >= items.length) return;
4278
- out[i] = await fn(items[i], i);
4279
- }
4280
- }
4281
- await Promise.all(Array.from({ length: workers }, () => worker()));
4282
- return out;
4283
- }
4284
- //#endregion
4285
4851
  //#region ../../packages/find/src/_yc-oss-adapter.ts
4286
4852
  /**
4287
4853
  * Adapter for the [yc-oss/api](https://github.com/yc-oss/api) public dataset.
@@ -4757,7 +5323,9 @@ async function runAcceleratorBatchFinder(opts) {
4757
5323
  ...record.ycUrl ? { launchUrl: record.ycUrl } : record.website ? { launchUrl: record.website } : {},
4758
5324
  ...record.oneLiner ? { productOneLiner: record.oneLiner } : {},
4759
5325
  ...linkedinUrl ? { linkedinUrl } : {},
4760
- ...phone ? { phone } : {}
5326
+ ...phone ? { phone } : {},
5327
+ ...opts.senderCohort ? { senderCohort: opts.senderCohort } : {},
5328
+ ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
4761
5329
  };
4762
5330
  if (ledger.enqueueTarget({
4763
5331
  playName: PLAY_NAME$5,
@@ -5086,7 +5654,6 @@ const DEFAULT_ROLES = [
5086
5654
  "ML Engineer",
5087
5655
  "Solutions Engineer"
5088
5656
  ];
5089
- const DEFAULT_CLAIM = "we cut new-hire ramp time by ~30% on the team they're hiring for — happy to share how";
5090
5657
  async function runHiringSignalFinder(opts) {
5091
5658
  const limit = opts.limit ?? 25;
5092
5659
  const sinceDays = opts.sinceDays ?? 14;
@@ -5094,7 +5661,7 @@ async function runHiringSignalFinder(opts) {
5094
5661
  const ledger = getLedger();
5095
5662
  const system = loadPrompt("hiring-signal-extract");
5096
5663
  const roles = opts.roles && opts.roles.length > 0 ? opts.roles : DEFAULT_ROLES;
5097
- const yourClaim = opts.yourClaim ?? DEFAULT_CLAIM;
5664
+ const yourClaim = (opts.yourClaim ?? "").trim();
5098
5665
  const result = {
5099
5666
  source: SOURCE$3,
5100
5667
  candidates: 0,
@@ -5104,6 +5671,10 @@ async function runHiringSignalFinder(opts) {
5104
5671
  enqueued: 0,
5105
5672
  costUsd: 0
5106
5673
  };
5674
+ if (!yourClaim) {
5675
+ result.halted = "set `yourClaim` in the hiring-signal config";
5676
+ return result;
5677
+ }
5107
5678
  const seen = /* @__PURE__ */ new Set();
5108
5679
  const hits = [];
5109
5680
  const sincePhrase = sinceDays <= 7 ? "this week" : `last ${sinceDays} days`;
@@ -6717,7 +7288,7 @@ const TRIGGERS = [
6717
7288
  limit: 25,
6718
7289
  maxCostUsd: 15
6719
7290
  },
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.",
7291
+ 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), `senderCohort` (YOUR own cohort tag, e.g. `yc-w23` — the peer angle the email is built on; REQUIRED, stamped onto every enqueued row so rows draft inline), `freeForCohortOffer` (optional time-bound offer, also stamped onto rows), `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.",
6721
7292
  readiness: (cfg) => {
6722
7293
  const cohorts = Array.isArray(cfg["cohorts"]) ? cfg["cohorts"] : null;
6723
7294
  const legacyCohort = typeof cfg["cohort"] === "string" ? cfg["cohort"].trim() : "";
@@ -6725,6 +7296,10 @@ const TRIGGERS = [
6725
7296
  ready: false,
6726
7297
  reason: "set `cohorts[]` (or legacy `cohort`)"
6727
7298
  };
7299
+ if ((typeof cfg["senderCohort"] === "string" ? cfg["senderCohort"].trim() : "").length === 0) return {
7300
+ ready: false,
7301
+ reason: "set `senderCohort` (your own cohort tag, e.g. yc-w23)"
7302
+ };
6728
7303
  return { ready: true };
6729
7304
  },
6730
7305
  run: (cfg) => {
@@ -6749,6 +7324,8 @@ const TRIGGERS = [
6749
7324
  cohortLabel: legacyLabel
6750
7325
  } : {},
6751
7326
  ...cfg["adapter"] === "yc-oss" || cfg["adapter"] === "websearch" ? { adapter: cfg["adapter"] } : {},
7327
+ ...typeof cfg["senderCohort"] === "string" && cfg["senderCohort"].trim().length > 0 ? { senderCohort: cfg["senderCohort"].trim() } : {},
7328
+ ...typeof cfg["freeForCohortOffer"] === "string" && cfg["freeForCohortOffer"].trim().length > 0 ? { freeForCohortOffer: cfg["freeForCohortOffer"].trim() } : {},
6752
7329
  limit: cfg["limit"] ?? 25,
6753
7330
  maxCostUsd: cfg["maxCostUsd"] ?? 15
6754
7331
  });
@@ -6813,7 +7390,13 @@ const TRIGGERS = [
6813
7390
  limit: 25,
6814
7391
  maxCostUsd: 5
6815
7392
  },
6816
- configBrief: "Scans Greenhouse / Lever / Workable / Ashby ATS pages for open roles that signal the company would buy THIS product. Config: `roles` (job titles whose existence implies a need for the product — e.g. 'Founding ML Engineer' for AI-infra products, 'Head of Compliance' for compliance products), `companies` (optional whitelist), `yourClaim` (one-sentence pitch about why your product makes that role's first 90 days easier — fed into the email), `sinceDays`, `limit`, `maxCostUsd`. The roles + yourClaim need to be tightly coupled to the product.",
7393
+ configBrief: "Scans Greenhouse / Lever / Workable / Ashby ATS pages for open roles that signal the company would buy THIS product. Config: `roles` (job titles whose existence implies a need for the product — e.g. 'Founding ML Engineer' for AI-infra products, 'Head of Compliance' for compliance products), `companies` (optional whitelist), `yourClaim` (one-sentence pitch about why your product makes that role's first 90 days easier — fed into the email; REQUIRED), `sinceDays`, `limit`, `maxCostUsd`. The roles + yourClaim need to be tightly coupled to the product.",
7394
+ readiness: (cfg) => {
7395
+ return (typeof cfg["yourClaim"] === "string" ? cfg["yourClaim"].trim() : "").length > 0 ? { ready: true } : {
7396
+ ready: false,
7397
+ reason: "set `yourClaim` (your one-line pitch)"
7398
+ };
7399
+ },
6817
7400
  run: (cfg) => runHiringSignalFinder({
6818
7401
  dryRun: false,
6819
7402
  ...Array.isArray(cfg["roles"]) ? { roles: cfg["roles"] } : {},
@@ -7264,13 +7847,6 @@ async function drainQueue(opts) {
7264
7847
  errors: []
7265
7848
  };
7266
7849
  if (rows.length === 0) return outcome;
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
7850
  if (!isSupportedPlay(opts.playName)) {
7275
7851
  outcome.errors.push({
7276
7852
  id: -1,
@@ -7329,89 +7905,16 @@ async function drainQueue(opts) {
7329
7905
  if (opts.dryRun) outcome.sent = rows.length;
7330
7906
  return outcome;
7331
7907
  }
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
7908
  async function dispatchOneTarget(opts, row) {
7347
- switch (opts.playName) {
7348
- case "show-hn": {
7349
- const target = JSON.parse(row.payload_json);
7350
- return firstDraft((await runShowHn({
7351
- dryRun: opts.dryRun,
7352
- targets: [target]
7353
- })).drafted);
7354
- }
7355
- case "job-change": {
7356
- const target = JSON.parse(row.payload_json);
7357
- return firstDraft((await runJobChange({
7358
- dryRun: opts.dryRun,
7359
- targets: [target]
7360
- })).drafted);
7361
- }
7362
- case "post-funding": {
7363
- const target = JSON.parse(row.payload_json);
7364
- return firstDraft((await runPostFunding({
7365
- dryRun: opts.dryRun,
7366
- targets: [target]
7367
- })).drafted);
7368
- }
7369
- case "accelerator-batch": {
7370
- const target = JSON.parse(row.payload_json);
7371
- return firstDraft((await runAcceleratorBatch({
7372
- dryRun: opts.dryRun,
7373
- targets: [target],
7374
- senderCohort: opts.senderCohort,
7375
- ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
7376
- })).drafted);
7377
- }
7378
- case "hiring-signal": {
7379
- const target = JSON.parse(row.payload_json);
7380
- return firstDraft((await runHiringSignal({
7381
- dryRun: opts.dryRun,
7382
- targets: [target]
7383
- })).drafted);
7384
- }
7385
- case "podcast-guest": {
7386
- const target = JSON.parse(row.payload_json);
7387
- return firstDraft((await runPodcastGuest({
7388
- dryRun: opts.dryRun,
7389
- targets: [target]
7390
- })).drafted);
7391
- }
7392
- case "breakup-revive": {
7393
- const target = JSON.parse(row.payload_json);
7394
- return firstDraft((await runBreakupRevive({
7395
- dryRun: opts.dryRun,
7396
- targets: [target]
7397
- })).drafted);
7398
- }
7399
- case "competitor-switch": {
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({
7409
- dryRun: opts.dryRun,
7410
- targets: [target]
7411
- })).drafted);
7412
- }
7413
- default: throw new Error(`drain: unsupported play '${opts.playName}'`);
7414
- }
7909
+ const play = PLAYS[opts.playName];
7910
+ if (!play) throw new Error(`drain: unsupported play '${opts.playName}'`);
7911
+ const target = JSON.parse(row.payload_json);
7912
+ return firstDraft((await play.run({
7913
+ dryRun: opts.dryRun,
7914
+ targets: [target],
7915
+ ...opts.senderCohort ? { senderCohort: opts.senderCohort } : {},
7916
+ ...opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}
7917
+ })).drafted);
7415
7918
  }
7416
7919
  function firstDraft(drafted) {
7417
7920
  const d = drafted[0];
@@ -7777,49 +8280,17 @@ function toDraftedView(d) {
7777
8280
  /**
7778
8281
  * Dispatch a play by name and return one DraftedView per target (in order).
7779
8282
  * 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.
8283
+ * regenerate endpoint (single-target dry-run). Throws on unsupported plays.
7782
8284
  */
7783
8285
  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
- }
8286
+ const play = PLAYS[playName];
8287
+ if (!play) throw new Error(`unsupported play: ${playName}`);
8288
+ return (await play.run({
8289
+ dryRun: body.dryRun,
8290
+ targets: body.targets,
8291
+ ...body.senderCohort ? { senderCohort: body.senderCohort } : {},
8292
+ ...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
8293
+ })).drafted.map(toDraftedView);
7823
8294
  }
7824
8295
  //#endregion
7825
8296
  //#region src/api/run.ts
@@ -8439,6 +8910,10 @@ const routes = [
8439
8910
  route("GET", "/api/cadences", listCadences),
8440
8911
  route("GET", "/api/cadences/:id", getCadence),
8441
8912
  route("POST", "/api/cadences/:id/stop", stopCadence),
8913
+ route("POST", "/api/cadences/:id/preview-next", previewCadenceStepRoute),
8914
+ route("POST", "/api/cadences/:id/send-next", sendCadenceStepRoute),
8915
+ route("POST", "/api/cadences/preview-batch", previewCadenceBatchRoute),
8916
+ route("POST", "/api/cadences/send-batch", sendCadenceBatchRoute),
8442
8917
  route("GET", "/api/receipts", listReceipts),
8443
8918
  route("GET", "/api/receipts/:id", getReceipt),
8444
8919
  route("GET", "/api/inbox", listInboxRoute),