oneshot-gtm-server 0.4.0 → 0.6.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.
- package/dist/bin.mjs +10657 -6021
- package/dist/bin.mjs.map +1 -1
- package/dist/web/assets/Badge-i7nNYr-O.js +1 -0
- package/dist/web/assets/Button-CwgZt1tQ.js +1 -0
- package/dist/web/assets/EmptyNote-uIusooGk.js +1 -0
- package/dist/web/assets/Field-Lu8BfWg7.js +1 -0
- package/dist/web/assets/Modal-CDPz1CPv.js +1 -0
- package/dist/web/assets/Pii-CybNyYoN.js +1 -0
- package/dist/web/assets/Skeleton-BnehflEF.js +1 -0
- package/dist/web/assets/{StrategistPanel-DMjQbPlQ.js → StrategistPanel-BT7pkEha.js} +3 -3
- package/dist/web/assets/cadences-L6OtcR2U.js +1 -0
- package/dist/web/assets/chevron-down-Fqh8xk_J.js +1 -0
- package/dist/web/assets/chevron-right-Ct1AtbHw.js +1 -0
- package/dist/web/assets/dist-yPYNbuB_.js +1 -0
- package/dist/web/assets/inbox-D6vK3Uh_.js +1 -0
- package/dist/web/assets/index-C7_9mwYD.js +54 -0
- package/dist/web/assets/index-c7S5-cnw.css +2 -0
- package/dist/web/assets/loader-circle-Bg1u7Pc8.js +1 -0
- package/dist/web/assets/measure-DICeV6u0.js +1 -0
- package/dist/web/assets/plays-FzKWoHW7.js +1 -0
- package/dist/web/assets/queue-BUHMLlyN.js +1 -0
- package/dist/web/assets/receipts-jmGYoC8d.js +1 -0
- package/dist/web/assets/refresh-cw-BAYQiC3W.js +1 -0
- package/dist/web/assets/rotate-cw-BZauKIGY.js +1 -0
- package/dist/web/assets/routes-D9btIJMO.js +1 -0
- package/dist/web/assets/run._playName-BEHDsQ6-.js +4 -0
- package/dist/web/assets/setup-BaujTJR0.js +1 -0
- package/dist/web/assets/src-DDEaweyX.js +1 -0
- package/dist/web/assets/x-C-34Mo7s.js +1 -0
- package/dist/web/index.html +3 -3
- package/package.json +3 -3
- package/dist/web/assets/Badge-B2tW85qr.js +0 -1
- package/dist/web/assets/Button-C-XcKplu.js +0 -1
- package/dist/web/assets/EmptyNote-zvLnRLPo.js +0 -1
- package/dist/web/assets/Field-BxSk5tbg.js +0 -1
- package/dist/web/assets/Modal-CU0ZPvE2.js +0 -1
- package/dist/web/assets/Skeleton-DNAfO8PV.js +0 -1
- package/dist/web/assets/cadences-CvBPoULf.js +0 -1
- package/dist/web/assets/chevron-down-CDjJN-YY.js +0 -1
- package/dist/web/assets/chevron-right-BTFaTdbr.js +0 -1
- package/dist/web/assets/cn-CS0Arupu.js +0 -1
- package/dist/web/assets/inbox-CzzgtWQf.js +0 -1
- package/dist/web/assets/index-B_nrqLlS.js +0 -54
- package/dist/web/assets/index-Ya_svHJk.css +0 -2
- package/dist/web/assets/loader-circle-CKkt6cSn.js +0 -1
- package/dist/web/assets/measure-CEgySDdR.js +0 -1
- package/dist/web/assets/plays-CuudkOHb.js +0 -1
- package/dist/web/assets/queue-C7vGtsQ5.js +0 -1
- package/dist/web/assets/receipts-B5u3oLpw.js +0 -1
- package/dist/web/assets/refresh-cw-Bz4Kdt55.js +0 -1
- package/dist/web/assets/routes-DHC_we4Z.js +0 -1
- package/dist/web/assets/run._playName-B9sG9Msq.js +0 -4
- package/dist/web/assets/send-Bv2Dd-HU.js +0 -1
- package/dist/web/assets/setup-BRVBiCEX.js +0 -1
- package/dist/web/assets/x-CPdidoxn.js +0 -1
- /package/dist/web/assets/{summarizeRun-CVWcweeA.js → summarizeRun-J5570T9r.js} +0 -0
package/dist/bin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.mjs","names":["PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","toView","toView","PLAY_NAME","PLAY_NAME","cache","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","PLAY_NAME","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","cache","PLAY_NAME","toView"],"sources":["../../../packages/core/src/config.ts","../../../packages/core/src/ledger.ts","../../../packages/core/src/oneshot.ts","../../../packages/core/src/events.ts","../../../packages/core/src/parallel.ts","../src/api/home.ts","../../../packages/intel/src/prompts.ts","../../../packages/intel/src/client.ts","../../../packages/intel/src/_parse.ts","../../../packages/plays/src/_lib.ts","../../../packages/plays/src/_cadence.ts","../../../packages/plays/src/_run-play.ts","../../../packages/plays/src/accelerator-batch.ts","../../../packages/plays/src/breakup-revive.ts","../../../packages/plays/src/competitor-switch.ts","../../../packages/plays/src/hiring-signal.ts","../../../packages/plays/src/job-change.ts","../../../packages/plays/src/podcast-guest.ts","../../../packages/plays/src/post-funding.ts","../../../packages/plays/src/repo-interest.ts","../../../packages/plays/src/show-hn.ts","../../../packages/plays/src/stack-consolidation.ts","../../../packages/plays/src/registry.ts","../../../packages/plays/src/demo-no-show.ts","../src/api/cadences.ts","../src/api/receipts.ts","../src/api/inbox.ts","../src/api/plays.ts","../src/api/measure.ts","../src/api/setup.ts","../src/api/derive-icp.ts","../../../packages/find/src/_filter.ts","../../../packages/find/src/_dedupe.ts","../../../packages/find/src/_findemail-prescreen.ts","../../../packages/find/src/_linkedin.ts","../../../packages/find/src/_enrich.ts","../../../packages/find/src/show-hn.ts","../../../packages/find/src/post-funding.ts","../../../packages/find/src/_accelerator-search-adapter.ts","../../../packages/find/src/_yc-oss-adapter.ts","../../../packages/find/src/accelerator-batch.ts","../../../packages/find/src/job-change.ts","../../../packages/find/src/hiring-signal.ts","../../../packages/find/src/podcast-guest.ts","../../../packages/find/src/breakup-revive.ts","../../../packages/find/src/_github-search.ts","../../../packages/find/src/_github-user.ts","../../../packages/find/src/_repo-stack.ts","../../../packages/find/src/_repo-pipeline.ts","../../../packages/find/src/_repo-utils.ts","../../../packages/find/src/github-topics.ts","../../../packages/find/src/_stargazers.ts","../../../packages/find/src/github-stars.ts","../../../packages/find/src/registry.ts","../../../packages/find/src/drain.ts","../src/api/strategist.ts","../../../packages/doctor/src/check.ts","../src/api/doctor.ts","../src/api/_play-dispatch.ts","../src/api/run.ts","../src/api/queue.ts","../src/api/triggers.ts","../src/server.ts","../src/scheduler.ts","../src/bin.ts"],"sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport type { OneShotConfig } from \"./types.ts\";\n\nconst CONFIG_DIR = join(homedir(), \".oneshot-gtm\");\nconst CONFIG_PATH = join(CONFIG_DIR, \"config.json\");\nconst SECRETS_PATH = join(CONFIG_DIR, \".env\");\n\nexport const SECRET_KEYS = [\n \"OPENROUTER_API_KEY\",\n \"OPENAI_API_KEY\",\n \"ANTHROPIC_API_KEY\",\n \"CDP_API_KEY_ID\",\n \"CDP_API_KEY_SECRET\",\n \"CDP_WALLET_SECRET\",\n \"AGENT_PRIVATE_KEY\",\n] as const;\nexport type SecretKey = (typeof SECRET_KEYS)[number];\n\nconst DEFAULTS: OneShotConfig = {\n walletMode: \"cdp\",\n llmProvider: \"openrouter\",\n llmModel: \"anthropic/claude-sonnet-4.6\",\n telemetryEnabled: true,\n founderName: null,\n founderEmail: null,\n productOneLiner: null,\n productDomain: null,\n sendingDomain: null,\n icpOneLiner: null,\n cadenceOverrides: null,\n founderCredentials: null,\n productPortfolio: null,\n partners: null,\n mobileSignature: false,\n clientId: null,\n};\n\nexport function configDir(): string {\n return CONFIG_DIR;\n}\n\nexport function ensureConfigDir(): void {\n if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });\n}\n\nexport function loadConfig(): OneShotConfig {\n const raw = readConfigOrDefault();\n const { cfg, minted } = bootstrapClientId(raw);\n // First-sight bootstrap of the anonymous install id. Persisted immediately\n // so subsequent reads (and any future telemetry sink) see a stable value.\n // Failures are non-fatal: returning the in-memory id still works for this\n // process, we just won't have it on disk yet — next call will retry.\n if (minted) {\n try {\n saveConfig(cfg);\n } catch {\n // ignore — read-only fs, permission denied, etc. Caller still gets the id.\n }\n }\n return cfg;\n}\n\n/**\n * Pure helper for the clientId bootstrap path — extracted so it can be\n * unit-tested without touching the user's real config file. Mints a fresh\n * UUID when `cfg.clientId` is null/empty, otherwise returns the input\n * unchanged. `minted: true` signals the caller to persist.\n */\nexport function bootstrapClientId(cfg: OneShotConfig): {\n cfg: OneShotConfig;\n minted: boolean;\n} {\n if (cfg.clientId && cfg.clientId.length > 0) return { cfg, minted: false };\n return { cfg: { ...cfg, clientId: randomUUID() }, minted: true };\n}\n\nfunction readConfigOrDefault(): OneShotConfig {\n if (!existsSync(CONFIG_PATH)) return { ...DEFAULTS };\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf8\");\n return { ...DEFAULTS, ...JSON.parse(raw) };\n } catch {\n return { ...DEFAULTS };\n }\n}\n\nexport function saveConfig(cfg: OneShotConfig): void {\n ensureConfigDir();\n if (!existsSync(dirname(CONFIG_PATH))) mkdirSync(dirname(CONFIG_PATH), { recursive: true });\n writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));\n}\n\nexport function secretsPath(): string {\n return SECRETS_PATH;\n}\n\nexport function loadSecretsFile(): Record<string, string> {\n if (!existsSync(SECRETS_PATH)) return {};\n const out: Record<string, string> = {};\n for (const raw of readFileSync(SECRETS_PATH, \"utf8\").split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const eq = line.indexOf(\"=\");\n if (eq < 0) continue;\n const k = line.slice(0, eq).trim();\n let v = line.slice(eq + 1).trim();\n if ((v.startsWith('\"') && v.endsWith('\"')) || (v.startsWith(\"'\") && v.endsWith(\"'\"))) {\n v = v.slice(1, -1);\n }\n out[k] = v;\n }\n return out;\n}\n\nexport function applySecretsToEnv(): void {\n const stored = loadSecretsFile();\n for (const [k, v] of Object.entries(stored)) {\n if (process.env[k] === undefined || process.env[k] === \"\") {\n process.env[k] = v;\n }\n }\n}\n\nexport function saveSecrets(updates: Partial<Record<SecretKey, string>>): void {\n ensureConfigDir();\n const existing = loadSecretsFile();\n for (const [k, v] of Object.entries(updates)) {\n if (v === undefined || v === \"\") continue;\n existing[k] = v;\n }\n const lines = [\n \"# oneshot-gtm secrets — do not commit\",\n \"# this file is read on every CLI invocation; values here override blank process.env\",\n \"\",\n ...Object.entries(existing)\n .filter(([k]) => SECRET_KEYS.includes(k as SecretKey))\n .map(([k, v]) => `${k}=${v}`),\n \"\",\n ];\n writeFileSync(SECRETS_PATH, lines.join(\"\\n\"));\n try {\n chmodSync(SECRETS_PATH, 0o600);\n } catch {\n // chmod may fail on Windows; the file is still in $HOME so reasonably scoped.\n }\n // reflect new values into the running process so `doctor` etc see them immediately\n for (const [k, v] of Object.entries(updates)) {\n if (v) process.env[k] = v;\n }\n}\n\nexport function secretSource(key: SecretKey): \"env\" | \"file\" | null {\n // process.env was populated either by the shell (env) or by applySecretsToEnv (file).\n // We can distinguish by checking the file directly.\n const fromFile = loadSecretsFile();\n if (fromFile[key]) {\n // If the shell ALSO has it AND it differs from the file, the shell value wins (we only fill blanks).\n if (process.env[key] && process.env[key] !== fromFile[key]) return \"env\";\n return \"file\";\n }\n if (process.env[key]) return \"env\";\n return null;\n}\n\n// Auto-apply on first import so downstream code sees keys in process.env without ceremony.\napplySecretsToEnv();\n\nexport function llmApiKey(provider: OneShotConfig[\"llmProvider\"]): string | null {\n switch (provider) {\n case \"openrouter\":\n return process.env.OPENROUTER_API_KEY ?? null;\n case \"openai\":\n return process.env.OPENAI_API_KEY ?? null;\n case \"anthropic\":\n return process.env.ANTHROPIC_API_KEY ?? null;\n }\n}\n\nexport function oneshotEnvReady(): boolean {\n return Boolean(\n (process.env.CDP_API_KEY_ID &&\n process.env.CDP_API_KEY_SECRET &&\n process.env.CDP_WALLET_SECRET) ||\n process.env.AGENT_PRIVATE_KEY,\n );\n}\n","import { Database } from \"bun:sqlite\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { configDir } from \"./config.ts\";\nimport type {\n InterviewRecord,\n ProspectRecord,\n QueueRow,\n QueueStatus,\n ReceiptRecord,\n SequenceEventRecord,\n TriggerRow,\n} from \"./types.ts\";\n\nconst DEFAULT_DB_PATH = join(configDir(), \"ledger.sqlite\");\n\n/**\n * Canonical form for matching prospect emails — trim + lowercase. Inbound reply\n * addresses (cadence inbox poll) are normalized the same way, so a prospect\n * stored from a mixed-case address still matches when they reply. Applied on\n * both store (upsertProspect) and every lookup so the two never diverge.\n */\nfunction canonEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\n/** A `cadence_state` row joined with its prospect's email/name/company. */\nexport interface CadenceWithProspect {\n prospect_id: number;\n play_name: string;\n current_step: number;\n status: string;\n enrolled_at: string;\n next_due_at: string | null;\n last_polled_at: string | null;\n next_step_draft_json: string | null;\n next_step_drafted_at: string | null;\n prospect_email: string | null;\n prospect_name: string | null;\n prospect_company: string | null;\n}\n\nexport class Ledger {\n private db: Database;\n\n constructor(path: string = DEFAULT_DB_PATH) {\n if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true });\n this.db = new Database(path);\n this.db.exec(\"PRAGMA journal_mode = WAL\");\n this.migrate();\n }\n\n private migrate(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n play_name TEXT NOT NULL,\n call_type TEXT NOT NULL,\n cost_usd REAL,\n signed_receipt TEXT,\n oneshot_request_id TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_play ON receipts(play_name);\n CREATE INDEX IF NOT EXISTS idx_receipts_created ON receipts(created_at);\n -- listReceipts / spend rollups filter (play_name, created_at) together and\n -- sort by created_at; the composite serves both without a separate sort scan.\n CREATE INDEX IF NOT EXISTS idx_receipts_play_created ON receipts(play_name, created_at);\n\n CREATE TABLE IF NOT EXISTS prospects (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n email TEXT,\n phone TEXT,\n company TEXT,\n linkedin_url TEXT,\n dossier_json TEXT,\n source TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_prospects_email ON prospects(email) WHERE email IS NOT NULL;\n\n CREATE TABLE IF NOT EXISTS sequence_events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n prospect_id INTEGER NOT NULL,\n play_name TEXT NOT NULL,\n step_index INTEGER NOT NULL,\n channel TEXT NOT NULL,\n status TEXT NOT NULL,\n metadata_json TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n -- sequence_events is read by listColdProspects (MAX(created_at) per\n -- prospect), per-play send counts, and cadence scans — all by\n -- prospect_id and/or created_at. Without this it's a full table scan.\n CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_created ON sequence_events(prospect_id, created_at);\n -- listSequenceEventsForProspectPlay (per-row in /api/cadences toView)\n -- and listSequenceEventsForCadences (bulk variant) both filter on\n -- (prospect_id, play_name) and ORDER BY step_index — composite index\n -- serves both the seek and the sort, no temp B-tree.\n CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_play ON sequence_events(prospect_id, play_name, step_index);\n\n CREATE TABLE IF NOT EXISTS interviews (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n person TEXT NOT NULL,\n transcript_path TEXT,\n jtbd TEXT,\n pain_quotes_json TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n\n CREATE TABLE IF NOT EXISTS cadence_state (\n prospect_id INTEGER NOT NULL,\n play_name TEXT NOT NULL,\n current_step INTEGER NOT NULL DEFAULT 0,\n status TEXT NOT NULL DEFAULT 'active',\n enrolled_at TEXT NOT NULL DEFAULT (datetime('now')),\n next_due_at TEXT,\n last_polled_at TEXT,\n PRIMARY KEY (prospect_id, play_name)\n );\n CREATE INDEX IF NOT EXISTS idx_cadence_status ON cadence_state(status);\n CREATE INDEX IF NOT EXISTS idx_cadence_next_due ON cadence_state(next_due_at);\n\n CREATE TABLE IF NOT EXISTS deal_outcomes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n prospect_id INTEGER NOT NULL,\n play_name TEXT,\n outcome TEXT NOT NULL,\n amount_usd REAL,\n notes TEXT,\n recorded_at TEXT NOT NULL DEFAULT (datetime('now')),\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n CREATE INDEX IF NOT EXISTS idx_outcomes_prospect ON deal_outcomes(prospect_id);\n CREATE INDEX IF NOT EXISTS idx_outcomes_outcome ON deal_outcomes(outcome);\n CREATE INDEX IF NOT EXISTS idx_outcomes_play ON deal_outcomes(play_name);\n\n CREATE TABLE IF NOT EXISTS target_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n play_name TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n dedupe_key TEXT NOT NULL,\n source TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n found_at TEXT NOT NULL DEFAULT (datetime('now')),\n reviewed_at TEXT,\n sent_at TEXT,\n notes TEXT,\n prospect_id INTEGER,\n last_draft_json TEXT,\n last_drafted_at TEXT,\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe ON target_queue(play_name, dedupe_key);\n CREATE INDEX IF NOT EXISTS idx_queue_status ON target_queue(status);\n CREATE INDEX IF NOT EXISTS idx_queue_play ON target_queue(play_name);\n -- The /queue page filters by (status, play) together; the composite\n -- serves that pair without falling back to a single-column scan.\n CREATE INDEX IF NOT EXISTS idx_queue_status_play ON target_queue(status, play_name);\n\n CREATE TABLE IF NOT EXISTS triggers (\n name TEXT PRIMARY KEY,\n last_polled_at TEXT,\n last_run_summary TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n config_json TEXT,\n running_started_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS enrichment_cache (\n email TEXT PRIMARY KEY,\n result_json TEXT NOT NULL,\n fetched_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS schema_version (\n version INTEGER PRIMARY KEY\n );\n INSERT OR IGNORE INTO schema_version(version) VALUES(6);\n `);\n\n // Lightweight migrations for installs that pre-date a column.\n this.addColumnIfMissing(\"prospects\", \"phone\", \"TEXT\");\n // v5 (2026-04): persist trigger run-state so a server restart doesn't\n // strand fire-and-forget runs as silent stale rows. See\n // sweepStaleRunningTriggers + fireTriggerNow.\n this.addColumnIfMissing(\"triggers\", \"running_started_at\", \"TEXT\");\n // v6 (2026-05): persist drafts per target_queue row so the founder can\n // review subject/body/flags after the SSE stream finishes (the /run\n // page itself is ephemeral). See `setQueueDraft` + the persist hook in\n // `apps/server/src/api/run.ts`.\n this.addColumnIfMissing(\"target_queue\", \"last_draft_json\", \"TEXT\");\n this.addColumnIfMissing(\"target_queue\", \"last_drafted_at\", \"TEXT\");\n // v7 (2026-05): lease column for atomic drain claiming. Two concurrent\n // /api/queue/drain calls used to see the same `approved` rows and both\n // start sending; dequeueApproved now atomically flips this column inside\n // a transaction so each drain sees a disjoint slice. Lease defaults to\n // 15 min — long enough for a slow per-target SDK send, short enough that\n // a crashed drain self-heals without a sweeper.\n this.addColumnIfMissing(\"target_queue\", \"drain_claimed_at\", \"TEXT\");\n // v8 (2026-05): persist per-cadence next-step draft so /cadences can\n // preview the 2nd/3rd email before firing (mirrors /queue's\n // last_draft_json). JSON envelope = {subject, body, flags, payload,\n // draftedAt}; cleared on cadence advance.\n this.addColumnIfMissing(\"cadence_state\", \"next_step_draft_json\", \"TEXT\");\n this.addColumnIfMissing(\"cadence_state\", \"next_step_drafted_at\", \"TEXT\");\n }\n\n private addColumnIfMissing(table: string, column: string, type: string): void {\n // Defense-in-depth: SQLite has no parameter binding for table/column/type\n // names, so we must validate. Whitelist to bare ASCII identifiers only.\n const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;\n if (!ident.test(table) || !ident.test(column)) {\n throw new Error(`unsafe identifier in addColumnIfMissing: ${table}.${column}`);\n }\n if (!/^[A-Z][A-Z0-9_ ]*$/.test(type)) {\n throw new Error(`unsafe column type in addColumnIfMissing: ${type}`);\n }\n const cols = this.db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n if (cols.some((c) => c.name === column)) return;\n this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);\n }\n\n enrollCadence(input: { prospectId: number; playName: string; nextDueAt: string }): void {\n this.db\n .prepare(\n `INSERT INTO cadence_state(prospect_id, play_name, current_step, status, next_due_at)\n VALUES(?, ?, 0, 'active', ?)\n ON CONFLICT(prospect_id, play_name) DO UPDATE SET\n status = 'active',\n next_due_at = excluded.next_due_at,\n last_polled_at = NULL`,\n )\n .run(input.prospectId, input.playName, input.nextDueAt);\n }\n\n listActiveCadences(opts: { dueByIso?: string } = {}): Array<{\n prospect_id: number;\n play_name: string;\n current_step: number;\n status: string;\n enrolled_at: string;\n next_due_at: string | null;\n last_polled_at: string | null;\n next_step_draft_json: string | null;\n next_step_drafted_at: string | null;\n prospect_email: string | null;\n prospect_name: string | null;\n prospect_company: string | null;\n }> {\n const where: string[] = [\"c.status = 'active'\"];\n const args: unknown[] = [];\n if (opts.dueByIso) {\n where.push(\"(c.next_due_at IS NULL OR c.next_due_at <= ?)\");\n args.push(opts.dueByIso);\n }\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE ${where.join(\" AND \")}\n ORDER BY c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all(...(args as never[])) as never;\n }\n\n listAllCadences(): CadenceWithProspect[] {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all() as never;\n }\n\n /**\n * Single cadence (joined with its prospect) by (prospect_id, play_name) — an\n * index seek on the `cadence_state` PRIMARY KEY. Replaces the O(n)\n * `listAllCadences().find(...)` scan callers used to do per row.\n */\n getCadence(prospectId: number, playName: string): CadenceWithProspect | null {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE c.prospect_id = ? AND c.play_name = ?\n `;\n return (this.db.query(sql).get(prospectId, playName) as CadenceWithProspect) ?? null;\n }\n\n /** All cadences for one prospect — index seek on cadence_state.prospect_id (PK prefix). */\n listCadencesForProspect(prospectId: number): CadenceWithProspect[] {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE c.prospect_id = ?\n ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all(prospectId) as never;\n }\n\n advanceCadence(input: {\n prospectId: number;\n playName: string;\n newStep: number;\n nextDueAt: string | null;\n }): void {\n // Also clear any persisted next-step draft — it was for the OLD next\n // step; advancing makes it stale and unsafe to send against the new\n // step. /cadences will surface a fresh \"no preview yet\" state.\n this.db\n .prepare(\n `UPDATE cadence_state\n SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now'),\n next_step_draft_json = NULL, next_step_drafted_at = NULL\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.newStep, input.nextDueAt, input.prospectId, input.playName);\n }\n\n setCadenceStatus(input: {\n prospectId: number;\n playName: string;\n status: \"active\" | \"replied\" | \"breakup\" | \"completed\";\n }): void {\n // Non-active terminal states clear the persisted draft too — a replied /\n // breakup / completed cadence shouldn't have a sendable preview hanging\n // around (the founder might click Send by accident, but the send route\n // also re-checks status='active', so this is defense in depth).\n this.db\n .prepare(\n `UPDATE cadence_state\n SET status = ?,\n next_step_draft_json = CASE WHEN ? = 'active' THEN next_step_draft_json ELSE NULL END,\n next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.status, input.status, input.status, input.prospectId, input.playName);\n }\n\n setCadenceDraft(input: {\n prospectId: number;\n playName: string;\n draft: {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n };\n }): void {\n const draftedAtIso = new Date().toISOString();\n const json = JSON.stringify({ ...input.draft, draftedAt: draftedAtIso });\n this.db\n .prepare(\n `UPDATE cadence_state\n SET next_step_draft_json = ?, next_step_drafted_at = ?\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(json, draftedAtIso, input.prospectId, input.playName);\n }\n\n getCadenceDraft(input: { prospectId: number; playName: string }): {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n draftedAt: string;\n } | null {\n const row = this.db\n .query(\n `SELECT next_step_draft_json AS j FROM cadence_state\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .get(input.prospectId, input.playName) as { j: string | null } | null;\n if (!row?.j) return null;\n try {\n return JSON.parse(row.j) as {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n draftedAt: string;\n };\n } catch {\n return null;\n }\n }\n\n clearCadenceDraft(input: { prospectId: number; playName: string }): void {\n this.db\n .prepare(\n `UPDATE cadence_state\n SET next_step_draft_json = NULL, next_step_drafted_at = NULL\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.prospectId, input.playName);\n }\n\n findProspectByEmail(email: string): { id: number } | null {\n return (\n (this.db.query(\"SELECT id FROM prospects WHERE email = ?\").get(canonEmail(email)) as {\n id: number;\n }) ?? null\n );\n }\n\n /** Full prospect record by email — used to attach name/company to inbox replies. */\n getProspectByEmail(email: string): ProspectRecord | null {\n return (\n (this.db\n .query(\"SELECT * FROM prospects WHERE email = ?\")\n .get(canonEmail(email)) as ProspectRecord) ?? null\n );\n }\n\n /** Full prospect record by id (PK seek). Avoids loading every prospect to find one. */\n getProspectById(id: number): ProspectRecord | null {\n return (\n (this.db.query(\"SELECT * FROM prospects WHERE id = ?\").get(id) as ProspectRecord) ?? null\n );\n }\n\n /** Cached enrichProfile result for an email (profiles are stable; reused with a TTL). */\n getCachedEnrichment(email: string): { result_json: string; fetched_at: string } | null {\n return (\n (this.db\n .query(\"SELECT result_json, fetched_at FROM enrichment_cache WHERE email = ?\")\n .get(email) as { result_json: string; fetched_at: string }) ?? null\n );\n }\n\n setCachedEnrichment(email: string, resultJson: string): void {\n this.db\n .prepare(\n `INSERT INTO enrichment_cache(email, result_json, fetched_at)\n VALUES(?, ?, ?)\n ON CONFLICT(email) DO UPDATE SET result_json = excluded.result_json, fetched_at = excluded.fetched_at`,\n )\n .run(email, resultJson, new Date().toISOString());\n }\n\n recordReceipt(input: {\n playName: string;\n callType: string;\n /** Per-call USD cost. Every wrapper in `oneshot.ts` reads `result.cost`\n * from the SDK response (declared on every result type in\n * `@oneshot-agent/sdk@0.15.2+`) and forwards it here. NULL in the\n * column when undefined — visible signal that the SDK omitted cost. */\n costUsd?: number;\n signedReceipt?: unknown;\n oneshotRequestId?: string;\n }): number {\n // Number.isFinite guard rejects undefined / Infinity / NaN — those land\n // as NULL in the column, NOT silently distorted into a number.\n const costUsd =\n typeof input.costUsd === \"number\" && Number.isFinite(input.costUsd) ? input.costUsd : null;\n const stmt = this.db.prepare(`\n INSERT INTO receipts(play_name, call_type, cost_usd, signed_receipt, oneshot_request_id)\n VALUES(?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.playName,\n input.callType,\n costUsd,\n input.signedReceipt ? JSON.stringify(input.signedReceipt) : null,\n input.oneshotRequestId ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n getReceipt(id: number): ReceiptRecord | null {\n return (this.db.query(\"SELECT * FROM receipts WHERE id = ?\").get(id) as ReceiptRecord) ?? null;\n }\n\n listReceipts(\n opts: { playName?: string; sinceIso?: string; limit?: number } = {},\n ): ReceiptRecord[] {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `SELECT * FROM receipts ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"} ORDER BY created_at DESC LIMIT ?`;\n args.push(opts.limit ?? 200);\n return this.db.query(sql).all(...(args as never[])) as ReceiptRecord[];\n }\n\n upsertProspect(input: Partial<ProspectRecord> & { email?: string | null }): number {\n // Store the canonical (lowercased) email so reply matching — which\n // normalizes the inbound from-address the same way — always lands.\n const email = input.email ? canonEmail(input.email) : null;\n if (email) {\n const existing = this.db.query(\"SELECT id FROM prospects WHERE email = ?\").get(email) as\n | { id: number }\n | undefined;\n if (existing) return existing.id;\n }\n const stmt = this.db.prepare(`\n INSERT INTO prospects(name, email, phone, company, linkedin_url, dossier_json, source)\n VALUES(?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.name ?? null,\n email,\n (input as { phone?: string | null }).phone ?? null,\n input.company ?? null,\n input.linkedin_url ?? null,\n input.dossier_json ?? null,\n input.source ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n recordOutcome(input: {\n prospectId: number;\n playName?: string;\n outcome: \"meeting_booked\" | \"sql_qualified\" | \"deal_won\" | \"deal_lost\" | \"ghosted\";\n amountUsd?: number;\n notes?: string;\n }): number {\n const stmt = this.db.prepare(`\n INSERT INTO deal_outcomes(prospect_id, play_name, outcome, amount_usd, notes)\n VALUES(?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.prospectId,\n input.playName ?? null,\n input.outcome,\n input.amountUsd ?? null,\n input.notes ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n countOutcomes(\n opts: {\n sinceIso?: string;\n playName?: string;\n outcome?: string;\n } = {},\n ): number {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"recorded_at >= ?\");\n args.push(opts.sinceIso);\n }\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.outcome) {\n where.push(\"outcome = ?\");\n args.push(opts.outcome);\n }\n const sql = `SELECT COUNT(*) AS n FROM deal_outcomes ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}`;\n return (this.db.query(sql).get(...(args as never[])) as { n: number } | null)?.n ?? 0;\n }\n\n outcomesByPlay(opts: { sinceIso?: string } = {}): Array<{\n play_name: string | null;\n meetings: number;\n sqls: number;\n won: number;\n lost: number;\n ghosted: number;\n }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"recorded_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT\n play_name,\n SUM(CASE WHEN outcome = 'meeting_booked' THEN 1 ELSE 0 END) AS meetings,\n SUM(CASE WHEN outcome = 'sql_qualified' THEN 1 ELSE 0 END) AS sqls,\n SUM(CASE WHEN outcome = 'deal_won' THEN 1 ELSE 0 END) AS won,\n SUM(CASE WHEN outcome = 'deal_lost' THEN 1 ELSE 0 END) AS lost,\n SUM(CASE WHEN outcome = 'ghosted' THEN 1 ELSE 0 END) AS ghosted\n FROM deal_outcomes\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n ORDER BY play_name ASC NULLS LAST\n `;\n return this.db.query(sql).all(...(args as never[])) as never;\n }\n\n listColdProspects(opts: {\n minDaysSinceLastEvent: number;\n maxDaysSinceLastEvent: number;\n limit?: number;\n }): Array<{\n id: number;\n name: string | null;\n email: string | null;\n company: string | null;\n linkedin_url: string | null;\n phone: string | null;\n last_event_at: string | null;\n }> {\n const sql = `\n SELECT p.id, p.name, p.email, p.company, p.linkedin_url, p.phone, MAX(s.created_at) AS last_event_at\n FROM prospects p\n LEFT JOIN sequence_events s ON s.prospect_id = p.id\n GROUP BY p.id\n HAVING last_event_at IS NOT NULL\n AND julianday('now') - julianday(last_event_at) BETWEEN ? AND ?\n ORDER BY last_event_at ASC\n LIMIT ?\n `;\n return this.db\n .query(sql)\n .all(opts.minDaysSinceLastEvent, opts.maxDaysSinceLastEvent, opts.limit ?? 50) as never;\n }\n\n recordSequenceEvent(input: {\n prospectId: number;\n playName: string;\n stepIndex: number;\n channel: SequenceEventRecord[\"channel\"];\n status: SequenceEventRecord[\"status\"];\n metadata?: unknown;\n }): number {\n const stmt = this.db.prepare(`\n INSERT INTO sequence_events(prospect_id, play_name, step_index, channel, status, metadata_json)\n VALUES(?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.prospectId,\n input.playName,\n input.stepIndex,\n input.channel,\n input.status,\n input.metadata ? JSON.stringify(input.metadata) : null,\n );\n return Number(result.lastInsertRowid);\n }\n\n listSequenceEventsForProspectPlay(prospectId: number, playName: string): SequenceEventRecord[] {\n return this.db\n .query(\n `SELECT * FROM sequence_events\n WHERE prospect_id = ? AND play_name = ?\n AND status IN ('sent','delivered','replied')\n ORDER BY step_index ASC, id ASC`,\n )\n .all(prospectId, playName) as SequenceEventRecord[];\n }\n\n /**\n * Bulk variant of listSequenceEventsForProspectPlay: one SQL round-trip for\n * many (prospect_id, play_name) pairs. Returns a Map keyed by\n * `${prospect_id}|${play_name}` so callers can index in O(1). The\n * per-key arrays preserve the same (step_index ASC, id ASC) ordering the\n * single-row method returns. Empty input → empty map (no query).\n *\n * Index-served by idx_sequence_events_prospect_play; the OR-chain is\n * expanded into per-pair index seeks by the query planner.\n */\n listSequenceEventsForCadences(\n pairs: ReadonlyArray<{ prospectId: number; playName: string }>,\n ): Map<string, SequenceEventRecord[]> {\n const map = new Map<string, SequenceEventRecord[]>();\n if (pairs.length === 0) return map;\n const conditions = pairs.map(() => \"(prospect_id = ? AND play_name = ?)\").join(\" OR \");\n const args: unknown[] = [];\n for (const p of pairs) {\n args.push(p.prospectId, p.playName);\n }\n const rows = this.db\n .query(\n `SELECT * FROM sequence_events\n WHERE (${conditions})\n AND status IN ('sent','delivered','replied')\n ORDER BY prospect_id ASC, play_name ASC, step_index ASC, id ASC`,\n )\n .all(...(args as never[])) as SequenceEventRecord[];\n for (const r of rows) {\n const key = `${r.prospect_id}|${r.play_name}`;\n let list = map.get(key);\n if (!list) {\n list = [];\n map.set(key, list);\n }\n list.push(r);\n }\n return map;\n }\n\n recordInterview(input: Omit<InterviewRecord, \"id\" | \"created_at\">): number {\n const stmt = this.db.prepare(`\n INSERT INTO interviews(person, transcript_path, jtbd, pain_quotes_json)\n VALUES(?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.person,\n input.transcript_path,\n input.jtbd,\n input.pain_quotes_json,\n );\n return Number(result.lastInsertRowid);\n }\n\n countSends(opts: { playName?: string } = {}): number {\n const sql = opts.playName\n ? \"SELECT COUNT(*) AS n FROM sequence_events WHERE play_name = ? AND status IN ('sent', 'delivered', 'replied')\"\n : \"SELECT COUNT(*) AS n FROM sequence_events WHERE status IN ('sent', 'delivered', 'replied')\";\n const args = opts.playName ? [opts.playName] : [];\n return (this.db.query(sql).get(...(args as never[])) as { n: number } | null)?.n ?? 0;\n }\n\n spendByPlay(\n opts: { sinceIso?: string } = {},\n ): Array<{ play_name: string; calls: number; total_usd: number }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT play_name, COUNT(*) AS calls, COALESCE(SUM(cost_usd), 0) AS total_usd\n FROM receipts\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n ORDER BY total_usd DESC, calls DESC\n `;\n return this.db.query(sql).all(...(args as never[])) as Array<{\n play_name: string;\n calls: number;\n total_usd: number;\n }>;\n }\n\n eventsByPlay(opts: { sinceIso?: string } = {}): Array<{\n play_name: string;\n sent: number;\n delivered: number;\n replied: number;\n bounced: number;\n }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT\n play_name,\n SUM(CASE WHEN status IN ('sent', 'delivered', 'replied') THEN 1 ELSE 0 END) AS sent,\n SUM(CASE WHEN status IN ('delivered', 'replied') THEN 1 ELSE 0 END) AS delivered,\n SUM(CASE WHEN status = 'replied' THEN 1 ELSE 0 END) AS replied,\n SUM(CASE WHEN status = 'bounced' THEN 1 ELSE 0 END) AS bounced\n FROM sequence_events\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n `;\n return this.db.query(sql).all(...(args as never[])) as Array<{\n play_name: string;\n sent: number;\n delivered: number;\n replied: number;\n bounced: number;\n }>;\n }\n\n totalSpendUsd(opts: { sinceIso?: string; playName?: string } = {}): number {\n const where: string[] = [\"cost_usd IS NOT NULL\"];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `SELECT COALESCE(SUM(cost_usd), 0) AS total FROM receipts WHERE ${where.join(\" AND \")}`;\n return (this.db.query(sql).get(...(args as never[])) as { total: number } | null)?.total ?? 0;\n }\n\n // ── target_queue ────────────────────────────────────────────────────────────\n\n /**\n * Insert a row into target_queue. Returns the new id, or null if a row with\n * the same (play_name, dedupe_key) already exists.\n */\n enqueueTarget(input: {\n playName: string;\n payload: unknown;\n dedupeKey: string;\n source: string;\n notes?: string;\n /**\n * Status to insert with. Defaults to \"pending\" (the normal review path).\n * Pass \"rejected\" to record an auto-drop (e.g. ICP filter said no) so the\n * founder can see what was filtered out and override if needed.\n */\n initialStatus?: QueueStatus;\n }): number | null {\n try {\n const status = input.initialStatus ?? \"pending\";\n const reviewedAt = status === \"pending\" ? null : new Date().toISOString();\n const result = this.db\n .prepare(\n `INSERT INTO target_queue(play_name, payload_json, dedupe_key, source, status, reviewed_at, notes)\n VALUES(?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.playName,\n JSON.stringify(input.payload),\n input.dedupeKey,\n input.source,\n status,\n reviewedAt,\n input.notes ?? null,\n );\n return Number(result.lastInsertRowid);\n } catch (err) {\n // Unique constraint violation = already queued; return null to signal dedupe.\n const msg = (err as Error).message ?? \"\";\n if (msg.includes(\"UNIQUE constraint failed\")) return null;\n throw err;\n }\n }\n\n isQueueDuplicate(playName: string, dedupeKey: string): boolean {\n const row = this.db\n .query(\"SELECT 1 FROM target_queue WHERE play_name = ? AND dedupe_key = ?\")\n .get(playName, dedupeKey);\n return row !== null && row !== undefined;\n }\n\n /**\n * Look up a queue row by its (play_name, dedupe_key) — the unique pair.\n * Used by the SSE /run endpoint to map drafts back to the originating\n * row so we can persist `last_draft_json`. Returns null when absent.\n */\n getQueueRowByDedupe(playName: string, dedupeKey: string): QueueRow | null {\n return (\n (this.db\n .query(\"SELECT * FROM target_queue WHERE play_name = ? AND dedupe_key = ?\")\n .get(playName, dedupeKey) as QueueRow) ?? null\n );\n }\n\n listQueue(opts: { playName?: string; status?: QueueStatus; limit?: number } = {}): QueueRow[] {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.status) {\n where.push(\"status = ?\");\n args.push(opts.status);\n }\n const sql = `\n SELECT * FROM target_queue\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n ORDER BY found_at DESC\n LIMIT ?\n `;\n args.push(opts.limit ?? 200);\n return this.db.query(sql).all(...(args as never[])) as QueueRow[];\n }\n\n getQueueRow(id: number): QueueRow | null {\n return (this.db.query(\"SELECT * FROM target_queue WHERE id = ?\").get(id) as QueueRow) ?? null;\n }\n\n setQueueStatus(input: { id: number; status: QueueStatus; notes?: string }): void {\n const now = new Date().toISOString();\n if (input.status === \"sent\") {\n this.db\n .prepare(\n `UPDATE target_queue SET status = ?, sent_at = ?, reviewed_at = COALESCE(reviewed_at, ?) ${input.notes ? \", notes = ?\" : \"\"} WHERE id = ?`,\n )\n .run(\n ...(input.notes\n ? [input.status, now, now, input.notes, input.id]\n : [input.status, now, now, input.id]),\n );\n } else if (input.status === \"approved\" || input.status === \"rejected\") {\n this.db\n .prepare(\n `UPDATE target_queue SET status = ?, reviewed_at = ? ${input.notes ? \", notes = ?\" : \"\"} WHERE id = ?`,\n )\n .run(\n ...(input.notes\n ? [input.status, now, input.notes, input.id]\n : [input.status, now, input.id]),\n );\n } else {\n this.db\n .prepare(`UPDATE target_queue SET status = ? WHERE id = ?`)\n .run(input.status, input.id);\n }\n }\n\n approveAllPending(opts: { playName?: string } = {}): number {\n const where: string[] = [\"status = 'pending'\"];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n const result = this.db\n .prepare(\n `UPDATE target_queue SET status = 'approved', reviewed_at = ? WHERE ${where.join(\" AND \")}`,\n )\n .run(...([new Date().toISOString(), ...args] as never[]));\n return Number(result.changes);\n }\n\n /**\n * Atomic claim-and-return. SELECTs approved rows whose lease has expired\n * (or was never set) and UPDATEs their `drain_claimed_at` inside a single\n * transaction so two concurrent drains can't return overlapping row sets.\n * Default lease: 15 min — a crashed drain's claims self-heal after that\n * without any sweeper. Held/error rows naturally back off for the lease\n * duration (no LLM-burn loops on stuck-flagged content).\n */\n dequeueApproved(opts: { playName: string; limit?: number; leaseSeconds?: number }): QueueRow[] {\n const leaseSeconds = opts.leaseSeconds ?? 900;\n const claimedAt = new Date().toISOString();\n const cutoff = new Date(Date.now() - leaseSeconds * 1000).toISOString();\n const limit = opts.limit ?? 50;\n const txn = this.db.transaction((): QueueRow[] => {\n const rows = this.db\n .query(\n `SELECT * FROM target_queue\n WHERE play_name = ? AND status = 'approved'\n AND (drain_claimed_at IS NULL OR drain_claimed_at < ?)\n ORDER BY found_at ASC\n LIMIT ?`,\n )\n .all(opts.playName, cutoff, limit) as QueueRow[];\n if (rows.length === 0) return [];\n const ids = rows.map((r) => r.id);\n const placeholders = ids.map(() => \"?\").join(\",\");\n this.db\n .prepare(`UPDATE target_queue SET drain_claimed_at = ? WHERE id IN (${placeholders})`)\n .run(...([claimedAt, ...ids] as never[]));\n return rows;\n });\n // BEGIN IMMEDIATE takes a RESERVED lock at the start of the transaction\n // instead of the default DEFERRED (which only locks on the first write).\n // In WAL mode with two processes, DEFERRED lets both transactions pass\n // the SELECT before either holds the write lock, then the second UPDATE\n // silently overwrites the first's claim — both drains would consider the\n // rows theirs. IMMEDIATE serializes the whole thing across connections.\n return txn.immediate();\n }\n\n expirePendingOlderThan(days: number): number {\n const sinceIso = new Date(Date.now() - days * 24 * 3600 * 1000).toISOString();\n const result = this.db\n .prepare(\n `UPDATE target_queue SET status = 'expired' WHERE status = 'pending' AND found_at < ?`,\n )\n .run(sinceIso);\n return Number(result.changes);\n }\n\n queueCounts(): Record<QueueStatus, number> {\n const rows = this.db\n .query(\"SELECT status, COUNT(*) AS n FROM target_queue GROUP BY status\")\n .all() as Array<{ status: QueueStatus; n: number }>;\n const out: Record<QueueStatus, number> = {\n pending: 0,\n approved: 0,\n rejected: 0,\n sent: 0,\n expired: 0,\n };\n for (const r of rows) out[r.status] = r.n;\n return out;\n }\n\n // ── triggers (find watch state) ────────────────────────────────────────────\n\n upsertTrigger(input: { name: string; configJson: string; enabled?: boolean }): void {\n this.db\n .prepare(\n `INSERT INTO triggers(name, enabled, config_json)\n VALUES(?, ?, ?)\n ON CONFLICT(name) DO UPDATE SET\n enabled = excluded.enabled,\n config_json = excluded.config_json`,\n )\n .run(input.name, input.enabled === false ? 0 : 1, input.configJson);\n }\n\n getTrigger(name: string): TriggerRow | null {\n return (this.db.query(\"SELECT * FROM triggers WHERE name = ?\").get(name) as TriggerRow) ?? null;\n }\n\n listTriggers(): TriggerRow[] {\n return this.db.query(\"SELECT * FROM triggers ORDER BY name ASC\").all() as TriggerRow[];\n }\n\n /**\n * Records the result of a finished run AND clears `running_started_at` in\n * the same statement. This is the only \"completed\" path — both success and\n * caught-finder-throw funnel through here, so clearing the in-flight flag\n * here is the right semantic.\n */\n updateTriggerLastPoll(input: { name: string; summary: unknown }): void {\n this.db\n .prepare(\n `UPDATE triggers\n SET last_polled_at = ?, last_run_summary = ?, running_started_at = NULL\n WHERE name = ?`,\n )\n .run(new Date().toISOString(), JSON.stringify(input.summary), input.name);\n }\n\n /**\n * Atomic claim: marks a trigger as in-flight ONLY if it's not already\n * running. Returns true when the claim succeeded (caller may proceed to\n * fire), false when another caller already holds the slot.\n *\n * The conditional UPDATE closes the TOCTOU race that would otherwise let\n * two concurrent `fireTriggerNow` calls both pass an `isTriggerRunning()`\n * check, both write, both fire — burning real $ on duplicate API spend.\n * SQLite serializes writes per process, so the second UPDATE's `changes`\n * count is 0.\n *\n * `staleCutoffIso` (optional): when provided, the claim ALSO succeeds if\n * the existing `running_started_at` is older than the cutoff — a stale\n * marker (process killed, never cleared, freshness gate already says \"not\n * running\"). Without this, a 4h-stale row would 409 every retry until\n * the next cold-boot sweep, leaving the founder stuck.\n *\n * Cleared by `updateTriggerLastPoll` on completion or by\n * `sweepStaleRunningTriggers` on the next cold boot.\n */\n markTriggerRunning(name: string, startedAtIso: string, staleCutoffIso?: string): boolean {\n if (staleCutoffIso) {\n const result = this.db\n .prepare(\n `UPDATE triggers\n SET running_started_at = ?\n WHERE name = ? AND (running_started_at IS NULL OR running_started_at < ?)`,\n )\n .run(startedAtIso, name, staleCutoffIso);\n return result.changes > 0;\n }\n const result = this.db\n .prepare(\n `UPDATE triggers\n SET running_started_at = ?\n WHERE name = ? AND running_started_at IS NULL`,\n )\n .run(startedAtIso, name);\n return result.changes > 0;\n }\n\n /**\n * Sweep trigger rows whose `running_started_at` is older than `maxAgeMs`.\n * For each match, write a `last_run_summary = { error: \"killed_by_restart\",\n * at }` and clear the in-flight flag. Returns the swept rows so the caller\n * can log them.\n *\n * Pure-ish (takes `now` + `maxAgeMs` as args) so tests can drive both\n * \"fresh entries are spared\" and \"stale entries are swept\" without\n * faking the system clock.\n */\n sweepStaleRunningTriggers(input: {\n now: Date;\n maxAgeMs: number;\n }): Array<{ name: string; startedAt: string; ageMs: number }> {\n const cutoffMs = input.now.getTime() - input.maxAgeMs;\n const rows = this.db\n .query(`SELECT name, running_started_at FROM triggers WHERE running_started_at IS NOT NULL`)\n .all() as Array<{ name: string; running_started_at: string }>;\n const swept: Array<{ name: string; startedAt: string; ageMs: number }> = [];\n const update = this.db.prepare(\n `UPDATE triggers\n SET last_polled_at = ?, last_run_summary = ?, running_started_at = NULL\n WHERE name = ?`,\n );\n for (const row of rows) {\n const startedMs = new Date(row.running_started_at).getTime();\n if (!Number.isFinite(startedMs)) {\n // Garbage timestamp — clear it so it doesn't perpetually re-trip.\n update.run(\n input.now.toISOString(),\n JSON.stringify({\n error: \"killed_by_restart\",\n reason: \"running_started_at unparseable\",\n at: input.now.toISOString(),\n }),\n row.name,\n );\n continue;\n }\n if (startedMs > cutoffMs) continue; // still fresh\n const ageMs = input.now.getTime() - startedMs;\n update.run(\n input.now.toISOString(),\n JSON.stringify({\n error: \"killed_by_restart\",\n startedAt: row.running_started_at,\n ageMs,\n at: input.now.toISOString(),\n }),\n row.name,\n );\n swept.push({ name: row.name, startedAt: row.running_started_at, ageMs });\n }\n return swept;\n }\n\n setTriggerEnabled(name: string, enabled: boolean): void {\n this.db.prepare(`UPDATE triggers SET enabled = ? WHERE name = ?`).run(enabled ? 1 : 0, name);\n }\n\n setTriggerConfig(name: string, configJson: string): void {\n this.db.prepare(`UPDATE triggers SET config_json = ? WHERE name = ?`).run(configJson, name);\n }\n\n /**\n * Associate a queued target with a known prospect (so the queue page can\n * link back to the prospect record). Best-effort — the caller is expected\n * to swallow failures since the link is a convenience, not a correctness\n * invariant.\n */\n setQueueProspectId(id: number, prospectId: number): void {\n this.db.prepare(`UPDATE target_queue SET prospect_id = ? WHERE id = ?`).run(prospectId, id);\n }\n\n /**\n * Persist the most-recent draft generated for this queue row. Called by\n * the SSE /run endpoint after the play returns drafted output, so the\n * founder can review subject/body/flags on /queue at any later time\n * (the /run page itself is ephemeral).\n *\n * Most-recent-wins — re-runs overwrite without history. `last_drafted_at`\n * is stored as ISO so it sorts/compares cleanly with the rest of the\n * timestamp columns; the JSON envelope also embeds `draftedAt` for\n * callers that already have the row payload.\n */\n setQueueDraft(input: {\n id: number;\n draft: {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n dryRun: boolean;\n };\n }): void {\n const draftedAtIso = new Date().toISOString();\n const json = JSON.stringify({ ...input.draft, draftedAt: draftedAtIso });\n this.db\n .prepare(`UPDATE target_queue SET last_draft_json = ?, last_drafted_at = ? WHERE id = ?`)\n .run(json, draftedAtIso, input.id);\n }\n\n close(): void {\n this.db.close();\n }\n}\n\nlet singleton: Ledger | null = null;\n\nexport function getLedger(): Ledger {\n if (!singleton) singleton = new Ledger();\n return singleton;\n}\n","import {\n OneShot,\n type BrowserResult,\n type DeepResearchPersonResult,\n type EnrichProfileResult,\n type FindEmailResult,\n type InboxEmail,\n type InboxListResult,\n type ResearchResult,\n type SmsSendResult,\n type VerifyEmailResult,\n type VoiceCallResult,\n type WebReadResult,\n type WebSearchResult,\n} from \"@oneshot-agent/sdk\";\nimport { getLedger } from \"./ledger.ts\";\nimport { loadConfig, oneshotEnvReady } from \"./config.ts\";\n\nexport interface SendEmailInput {\n to: string;\n subject: string;\n body: string;\n fromDomain?: string;\n}\n\nexport interface ResearchInput {\n topic: string;\n depth?: \"quick\" | \"deep\";\n}\n\nexport interface EnrichInput {\n email?: string;\n linkedinUrl?: string;\n name?: string;\n companyDomain?: string;\n}\n\nexport interface CallContext {\n playName: string;\n}\n\nlet agentSingleton: OneShot | null = null;\n\nasync function initAgent(): Promise<OneShot> {\n if (!oneshotEnvReady()) {\n throw new Error(\n \"OneShot credentials missing. Set CDP_API_KEY_ID + CDP_API_KEY_SECRET + CDP_WALLET_SECRET, or AGENT_PRIVATE_KEY. Run `oneshot-gtm doctor` for details.\",\n );\n }\n if (process.env[\"AGENT_PRIVATE_KEY\"]) {\n return new OneShot({ privateKey: process.env[\"AGENT_PRIVATE_KEY\"] });\n }\n return await OneShot.create({ cdp: true });\n}\n\nasync function getAgent(): Promise<OneShot> {\n if (!agentSingleton) agentSingleton = await initAgent();\n return agentSingleton;\n}\n\n/**\n * Derive the From localpart from the founder's name (first token, lowercased,\n * non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back\n * to `agent` when the name yields nothing usable. (\"J. Nicolas\" → \"j\".)\n */\nfunction fromLocalpart(name: string | null): string {\n const first = (name ?? \"\").trim().split(/\\s+/)[0] ?? \"\";\n const clean = first.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return clean.length > 0 ? clean : \"agent\";\n}\n\n/**\n * OneShot renders the email `body` as HTML, so plain-text newlines collapse\n * into one run-on paragraph. Escape HTML metacharacters and turn newlines into\n * <br> so paragraphs + the signature lines render the way the draft intended.\n */\nfunction toHtmlBody(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n/g, \"<br>\\n\");\n}\n\nexport async function sendEmail(input: SendEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const cfg = loadConfig();\n // The send domain MUST be one the wallet owns, or OneShot 403s\n // (`domain_not_owned`). The SDK's typed email() defaults from_domain to its\n // own demo domain — so an unset sendingDomain is the current broken state.\n const fromDomain = input.fromDomain ?? cfg.sendingDomain ?? null;\n\n const opts: Parameters<OneShot[\"email\"]>[0] = {\n to: input.to,\n subject: input.subject,\n body: toHtmlBody(input.body),\n };\n if (fromDomain) {\n // sendingDomain must be wallet-owned (else OneShot 403s `domain_not_owned`,\n // since the SDK otherwise defaults to its demo domain). Send from\n // <first-name>@<domain> with the founder's name as the display name.\n // from_mailbox (localpart) + from_name (display name) are native fields in\n // SDK ≥0.16.2 — from_name ships as a separate field, so the bare\n // from_address still passes the server's strict email validation.\n opts.from_domain = fromDomain;\n opts.from_mailbox = fromLocalpart(cfg.founderName);\n const name = (cfg.founderName ?? \"\").trim();\n if (name) opts.from_name = name;\n }\n const result = await agent.email(opts);\n\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"email.send\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport async function deepResearch(input: ResearchInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: ResearchResult = await agent.research({\n topic: input.topic,\n depth: input.depth ?? \"quick\",\n });\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"research.deep\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport async function enrichProfile(input: EnrichInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"enrichProfile\"]>[0] = {};\n if (input.email) opts.email = input.email;\n if (input.linkedinUrl) opts.linkedin_url = input.linkedinUrl;\n if (input.name) opts.name = input.name;\n if (input.companyDomain) opts.company_domain = input.companyDomain;\n\n const result: EnrichProfileResult = await agent.enrichProfile(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"enrich.profile\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface DeepResearchPersonInput {\n /** A known email address — feeds dossier lookup. */\n email?: string;\n /** Any social URL (LinkedIn, Twitter, GitHub) the engine can chase. */\n socialMediaUrl?: string;\n /** Best-guess full name. */\n name?: string;\n /** Best-guess company name (free text — can be a domain or a brand). */\n company?: string;\n}\n\n/**\n * Multi-source person dossier: emails (work + personal + alts), phones,\n * org history, social profiles. Higher cost (~$0.05) and 2–5 min async vs.\n * findEmail's seconds-and-half-a-cent — use when you don't have a\n * `companyDomain` to feed findEmail (e.g. GitHub repo owners with no\n * resolvable company), not as a default first-pass.\n */\nexport async function deepResearchPerson(input: DeepResearchPersonInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"deepResearchPerson\"]>[0] = {};\n if (input.email) opts.email = input.email;\n if (input.socialMediaUrl) opts.social_media_url = input.socialMediaUrl;\n if (input.name) opts.name = input.name;\n if (input.company) opts.company = input.company;\n\n const result: DeepResearchPersonResult = await agent.deepResearchPerson(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"research.person\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface FindEmailInput {\n /** Pass either fullName, OR firstName + lastName. companyDomain is required. */\n fullName?: string;\n firstName?: string;\n lastName?: string;\n companyDomain: string;\n}\n\nexport async function findEmail(input: FindEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"findEmail\"]>[0] = {\n company_domain: input.companyDomain,\n };\n if (input.fullName) opts.full_name = input.fullName;\n if (input.firstName) opts.first_name = input.firstName;\n if (input.lastName) opts.last_name = input.lastName;\n const result: FindEmailResult = await agent.findEmail(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"email.find\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface VerifyEmailInput {\n email: string;\n}\n\nexport async function verifyEmail(input: VerifyEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: VerifyEmailResult = await agent.verifyEmail({ email: input.email });\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"email.verify\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport async function getBalance(\n tokenAddress?: string,\n): Promise<{ balance: string; raw: unknown }> {\n const agent = await getAgent();\n const raw = await agent.getBalance(tokenAddress);\n return { balance: raw, raw };\n}\n\nexport async function listInbox(opts?: {\n since?: string;\n limit?: number;\n}): Promise<InboxListResult> {\n const agent = await getAgent();\n const out: { since?: string; limit?: number; include_body?: boolean } = { include_body: true };\n if (opts?.since) out.since = opts.since;\n if (opts?.limit) out.limit = opts.limit;\n return agent.inboxList(out);\n}\n\nexport interface BuildSiteInput {\n name: string;\n description: string;\n type?:\n | \"saas\"\n | \"portfolio\"\n | \"agency\"\n | \"personal\"\n | \"product\"\n | \"funnel\"\n | \"restaurant\"\n | \"event\";\n sections?: string[];\n leadCaptureEmail?: string;\n primaryColor?: string;\n tone?: \"professional\" | \"playful\" | \"bold\" | \"minimal\";\n domain?: string;\n}\n\nexport async function buildSite(input: BuildSiteInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"build\"]>[0] = {\n product: { name: input.name, description: input.description },\n };\n if (input.type) opts.type = input.type;\n if (input.sections) opts.sections = input.sections;\n if (input.leadCaptureEmail) {\n opts.lead_capture = { enabled: true, inbox_email: input.leadCaptureEmail };\n }\n if (input.primaryColor || input.tone) {\n opts.brand = {};\n if (input.primaryColor) opts.brand.primary_color = input.primaryColor;\n if (input.tone) opts.brand.tone = input.tone;\n }\n if (input.domain) opts.domain = input.domain;\n\n const result = await agent.build(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"build.website\",\n signedReceipt: result,\n costUsd: result.cost,\n });\n return { result, receiptId };\n}\n\nexport interface SendSmsInput {\n to: string | string[];\n message: string;\n maxCost?: number;\n}\n\nexport async function sendSms(input: SendSmsInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"sms\"]>[0] = {\n to_number: input.to,\n message: input.message,\n };\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: SmsSendResult = await agent.sms(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"sms.send\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.details[0]?.message_sid ?? undefined,\n });\n return { result, receiptId };\n}\n\nexport interface VoiceCallInput {\n objective: string;\n to: string | string[];\n callerPersona?: string;\n context?: string;\n maxDurationMinutes?: number;\n maxCost?: number;\n}\n\nexport async function voiceCall(input: VoiceCallInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"voice\"]>[0] = {\n objective: input.objective,\n target_number: input.to,\n };\n if (input.callerPersona) opts.caller_persona = input.callerPersona;\n if (input.context) opts.context = input.context;\n if (input.maxDurationMinutes) opts.max_duration_minutes = input.maxDurationMinutes;\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: VoiceCallResult = await agent.voice(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"voice.call\",\n costUsd: result.cost,\n signedReceipt: result,\n });\n return { result, receiptId };\n}\n\nexport interface WebSearchInput {\n query: string;\n maxResults?: number;\n}\n\nexport async function webSearch(input: WebSearchInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"webSearch\"]>[0] = { query: input.query };\n if (input.maxResults) opts.max_results = input.maxResults;\n const result: WebSearchResult = await agent.webSearch(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"web.search\",\n signedReceipt: result,\n costUsd: result.cost,\n });\n return { result, receiptId };\n}\n\nexport interface WebReadInput {\n url: string;\n}\n\nexport async function webRead(input: WebReadInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: WebReadResult = await agent.webRead({ url: input.url });\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"web.read\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface BrowserTaskInput {\n task: string;\n startUrl?: string;\n allowedDomains?: string[];\n outputSchema?: Record<string, unknown>;\n profileId?: string;\n maxSteps?: number;\n maxCost?: number;\n}\n\nexport async function browserTask(input: BrowserTaskInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"browser\"]>[0] = { task: input.task };\n if (input.startUrl) opts.start_url = input.startUrl;\n if (input.allowedDomains) opts.allowed_domains = input.allowedDomains;\n if (input.outputSchema) opts.output_schema = input.outputSchema;\n if (input.profileId) opts.profile_id = input.profileId;\n if (input.maxSteps) opts.max_steps = input.maxSteps;\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: BrowserResult = await agent.browser(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"browser.task\",\n costUsd: result.cost,\n signedReceipt: result,\n oneshotRequestId: result.browser_task_id ?? undefined,\n });\n return { result, receiptId };\n}\n\nexport type {\n BrowserResult,\n DeepResearchPersonResult,\n InboxEmail,\n InboxListResult,\n SmsSendResult,\n VoiceCallResult,\n WebReadResult,\n WebSearchResult,\n};\n\nexport function receiptUrlForId(receiptId: number): string {\n return `local://receipt/${receiptId}`;\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { configDir } from \"./config.ts\";\n\n/**\n * Local-only structured event log.\n *\n * Every interesting moment (LLM call, ICP filter decision, finder lifecycle,\n * swallowed errors) appends one JSON line to ~/.oneshot-gtm/events.jsonl.\n * Tail it with `tail -f ~/.oneshot-gtm/events.jsonl | jq` while iterating.\n *\n * ## Privacy boundary\n *\n * `ctx` may contain primitives, counters, durations, category labels, error\n * class names, hostname/domain. It must NEVER contain user-typed values like\n * email addresses or ICP one-liner text, prospect data, or LLM completions\n * verbatim. This is the same boundary that will apply when an opt-in HTTP\n * sink is added later — keeping the rule tight today means schema reuse\n * tomorrow.\n *\n * Not enforced programmatically. Code-review discipline at the call sites.\n *\n * ## Failure mode\n *\n * Logging never throws. A logging bug must not break the caller. If the\n * filesystem is read-only or the config dir doesn't exist, the event is\n * dropped silently.\n */\n\nexport type EventLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface DevEvent {\n ts: string;\n kind: string;\n level: EventLevel;\n ctx?: Record<string, unknown>;\n /** Anonymous per-install id; resolved lazily so tests can mock it. */\n client_id?: string;\n /** Groups all events emitted within one \"run\" (one watch tick, one HTTP request, one CLI invocation). */\n run_id?: string;\n}\n\nconst EVENTS_PATH = join(configDir(), \"events.jsonl\");\nconst DEBUG_ENABLED = (process.env[\"DEBUG\"] ?? \"\").includes(\"oneshot\");\n\nlet runId: string | null = null;\nlet cachedClientId: string | null = null;\nlet clientIdResolved = false;\nlet configDirEnsured = false;\n\n/**\n * Begin a new \"run\" — subsequent events emitted from this process will share\n * the returned run_id until the next call. Useful for grouping with jq:\n * jq 'select(.run_id == \"abc-…\")'\n */\nexport function startRun(): string {\n runId = randomUUID();\n return runId;\n}\n\nexport function logEvent(\n kind: string,\n ctx?: Record<string, unknown>,\n level: EventLevel = \"info\",\n): void {\n // Whole body is best-effort; a logging bug must not break the caller.\n // buildEventLine can throw on BigInt / circular refs (JSON.stringify), so\n // it goes inside the try block alongside the filesystem work.\n try {\n const line = buildEventLine(kind, ctx, level, runId, resolveClientId(), new Date());\n\n if (!configDirEnsured) {\n if (!existsSync(configDir())) mkdirSync(configDir(), { recursive: true });\n configDirEnsured = true;\n }\n appendFileSync(EVENTS_PATH, line);\n\n if (DEBUG_ENABLED) {\n // Mirror to stderr so it doesn't interleave with command output on stdout.\n process.stderr.write(line);\n }\n } catch {\n // dropped silently — see file header\n }\n}\n\n/**\n * Pure builder for a single JSONL line. Extracted for testability — the\n * call site supplies `now`, `runId`, `clientId` so tests can pin them\n * without touching the module-level singletons or the filesystem.\n *\n * Includes the trailing newline so the caller can append in a single\n * fs syscall.\n */\nexport function buildEventLine(\n kind: string,\n ctx: Record<string, unknown> | undefined,\n level: EventLevel,\n runId: string | null,\n clientId: string | null,\n now: Date,\n): string {\n const event: DevEvent = {\n ts: now.toISOString(),\n kind,\n level,\n };\n if (ctx) event.ctx = ctx;\n if (clientId) event.client_id = clientId;\n if (runId) event.run_id = runId;\n return JSON.stringify(event) + \"\\n\";\n}\n\n/**\n * Read the clientId straight from config.json instead of going through\n * loadConfig() — that would create a circular import (config doesn't depend\n * on events today; we keep it that way). Survives the case where the file\n * doesn't exist yet: returns null and the event ships without a client_id.\n * Cached for the process lifetime once non-null.\n */\nfunction resolveClientId(): string | null {\n // First call resolves and caches, subsequent calls return the cached value\n // even if it's null. The previous `clientIdResolved && cachedClientId` check\n // re-read the config file on every event when bootstrap hadn't finished\n // yet — turning the once-per-process cost into a per-event syscall.\n if (clientIdResolved) return cachedClientId;\n clientIdResolved = true;\n try {\n const path = join(configDir(), \"config.json\");\n if (!existsSync(path)) return null;\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as { clientId?: string };\n cachedClientId = typeof parsed.clientId === \"string\" ? parsed.clientId : null;\n } catch {\n cachedClientId = null;\n }\n return cachedClientId;\n}\n\n/**\n * Test-only escape hatch. Lets vitest reset the cached id between cases when\n * it manipulates the underlying config file. Not exported via the package\n * barrel — import directly if you really need it.\n */\nexport function _resetClientIdCacheForTests(): void {\n cachedClientId = null;\n clientIdResolved = false;\n configDirEnsured = false;\n runId = null;\n}\n\n/** Path the JSONL log lives at — exposed so docs/CLI hints can reference it. */\nexport function eventsLogPath(): string {\n return EVENTS_PATH;\n}\n","/**\n * Run `fn` over `items` with at most `concurrency` Promises in flight at once.\n * Preserves input order in the result array. Errors propagate via Promise.all\n * — caller is expected to catch per-item internally if partial success matters.\n *\n * Worker-pool implementation: spawn `concurrency` workers that pull from a\n * shared cursor. Cheaper than a chunked Promise.all (which stalls on the\n * slowest item per chunk) and avoids the dependency surface of p-limit.\n *\n * Lives in core so both `find` (candidate pipelines) and `plays` (batch send\n * loops) can share it without a cross-package dependency.\n */\nexport async function parallelMap<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const out: R[] = Array.from({ length: items.length });\n if (items.length === 0) return out;\n const workers = Math.max(1, Math.min(concurrency, items.length));\n let cursor = 0;\n async function worker(): Promise<void> {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n out[i] = await fn(items[i] as T, i);\n }\n }\n await Promise.all(Array.from({ length: workers }, () => worker()));\n return out;\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { HomeMetrics } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport function homeMetrics(req: Request): Response {\n const ledger = getLedger();\n const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000).toISOString();\n const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 3600 * 1000).toISOString();\n\n const recent7d = ledger.listReceipts({ sinceIso: sevenDaysAgo, limit: 1000 });\n const events7d = ledger.eventsByPlay({ sinceIso: sevenDaysAgo });\n const sent7d = events7d.reduce((acc, e) => acc + e.sent, 0);\n const replied7d = events7d.reduce((acc, e) => acc + e.replied, 0);\n const active = ledger.listActiveCadences();\n\n const metrics: HomeMetrics = {\n spendUsd7d: ledger.totalSpendUsd({ sinceIso: sevenDaysAgo }),\n spendUsd30d: ledger.totalSpendUsd({ sinceIso: thirtyDaysAgo }),\n callsLast7d: recent7d.length,\n sentLast7d: sent7d,\n repliedLast7d: replied7d,\n activeCadences: active.length,\n };\n\n return jsonResponse(metrics, 200, req);\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\nconst candidates = [\n join(here, \"..\", \"..\", \"prompts\"),\n join(here, \"..\", \"..\", \"..\", \"prompts\"),\n join(process.cwd(), \"packages\", \"prompts\"),\n];\n\n// Matches the bracketed reference line prompt files use to point at the\n// humanizer doc: `[See _humanizer.md — every rule binding...]`. The `[^\\]]*`\n// (non-greedy through the close-bracket) avoids any chance of consuming a\n// downstream `]` if a prompt accidentally has another bracket on the line.\nconst HUMANIZER_REF_RE = /^\\[See _humanizer\\.md[^\\]]*\\]\\s*$/gm;\n\nlet humanizerCache: string | null = null;\n\nfunction readPromptFile(name: string): string | null {\n for (const dir of candidates) {\n const path = join(dir, `${name}.md`);\n if (existsSync(path)) return readFileSync(path, \"utf8\");\n }\n return null;\n}\n\nfunction loadHumanizer(): string {\n if (humanizerCache != null) return humanizerCache;\n const content = readPromptFile(\"_humanizer\");\n if (content == null) {\n throw new Error(`_humanizer.md not found in any of: ${candidates.join(\", \")}`);\n }\n humanizerCache = content.trimEnd();\n return humanizerCache;\n}\n\nexport function loadPrompt(name: string): string {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new Error(`invalid prompt name: ${JSON.stringify(name)}`);\n }\n const raw = readPromptFile(name);\n if (raw == null) {\n throw new Error(`prompt not found: ${name}.md (searched: ${candidates.join(\", \")})`);\n }\n // The textual `[See _humanizer.md ...]` reference in many prompts was a\n // false promise: the LLM read \"see X\" but the content was never attached.\n // Inline it here so every prompt that opts in (by including the reference)\n // actually receives the humanizer rules.\n if (HUMANIZER_REF_RE.test(raw)) {\n return raw.replace(HUMANIZER_REF_RE, loadHumanizer());\n }\n return raw;\n}\n\n/** Test-only: clears the memoized humanizer read. Not used in production. */\nexport function _resetPromptCache(): void {\n humanizerCache = null;\n}\n","import { llmApiKey, loadConfig, logEvent } from \"@oneshot-gtm/core\";\nimport { loadPrompt } from \"./prompts.ts\";\n\nexport interface LlmMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface LlmCompleteInput {\n messages: LlmMessage[];\n temperature?: number;\n maxTokens?: number;\n}\n\nexport interface LlmCompleteOutput {\n content: string;\n provider: string;\n model: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\nexport class LlmError extends Error {\n constructor(\n message: string,\n public readonly status?: number,\n ) {\n super(message);\n this.name = \"LlmError\";\n }\n}\n\nlet humanizerPrologueCache: string | null = null;\nfunction humanizerPrologue(): string {\n if (humanizerPrologueCache !== null) return humanizerPrologueCache;\n try {\n humanizerPrologueCache = loadPrompt(\"_humanizer\");\n } catch {\n humanizerPrologueCache = \"\";\n }\n return humanizerPrologueCache;\n}\n\nfunction injectHumanizer(messages: LlmMessage[]): LlmMessage[] {\n const prologue = humanizerPrologue();\n if (!prologue) return messages;\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx < 0) {\n return [{ role: \"system\", content: prologue }, ...messages];\n }\n const sys = messages[sysIdx];\n if (!sys) return messages;\n if (sys.content.includes(\"_humanizer.md\") || sys.content.includes(\"Anti-AI-slop rules\")) {\n const out: LlmMessage[] = messages.slice();\n out[sysIdx] = { role: \"system\", content: `${prologue}\\n\\n---\\n\\n${sys.content}` };\n return out;\n }\n return messages;\n}\n\nexport async function complete(input: LlmCompleteInput): Promise<LlmCompleteOutput> {\n const cfg = loadConfig();\n const key = llmApiKey(cfg.llmProvider);\n if (!key) {\n const envName = {\n openrouter: \"OPENROUTER_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n }[cfg.llmProvider];\n throw new LlmError(`No ${envName} set. Run: oneshot-gtm config llm`);\n }\n\n const expanded: LlmCompleteInput = { ...input, messages: injectHumanizer(input.messages) };\n\n const startedAt = Date.now();\n logEvent(\"llm.start\", {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n message_count: expanded.messages.length,\n max_tokens: expanded.maxTokens ?? null,\n });\n try {\n let result: LlmCompleteOutput;\n switch (cfg.llmProvider) {\n case \"openrouter\":\n result = await openaiCompatibleComplete({\n key,\n model: cfg.llmModel,\n baseUrl: \"https://openrouter.ai/api/v1\",\n provider: \"openrouter\",\n input: expanded,\n extraHeaders: {\n \"HTTP-Referer\": \"https://github.com/oneshot-agent/oneshot-gtm\",\n \"X-Title\": \"oneshot-gtm\",\n },\n });\n break;\n case \"openai\":\n result = await openaiCompatibleComplete({\n key,\n model: cfg.llmModel,\n baseUrl: \"https://api.openai.com/v1\",\n provider: \"openai\",\n input: expanded,\n });\n break;\n case \"anthropic\":\n result = await anthropicComplete({ key, model: cfg.llmModel, input: expanded });\n break;\n }\n logEvent(\"llm.done\", {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n duration_ms: Date.now() - startedAt,\n response_chars: result.content.length,\n });\n return result;\n } catch (err) {\n logEvent(\n \"llm.error\",\n {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n duration_ms: Date.now() - startedAt,\n error_class: (err as Error).constructor.name,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n throw err;\n }\n}\n\ninterface OpenAIArgs {\n key: string;\n model: string;\n baseUrl: string;\n provider: string;\n input: LlmCompleteInput;\n extraHeaders?: Record<string, string>;\n}\n\nasync function openaiCompatibleComplete(args: OpenAIArgs): Promise<LlmCompleteOutput> {\n const res = await fetch(`${args.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${args.key}`,\n ...args.extraHeaders,\n },\n body: JSON.stringify({\n model: args.model,\n messages: args.input.messages,\n temperature: args.input.temperature ?? 0.7,\n max_tokens: args.input.maxTokens ?? 1024,\n }),\n });\n\n if (!res.ok) {\n const body = await res.text();\n throw new LlmError(`${args.provider} ${res.status}: ${body.slice(0, 400)}`, res.status);\n }\n\n const data = (await res.json()) as {\n choices: Array<{ message: { content: string } }>;\n usage?: { prompt_tokens?: number; completion_tokens?: number };\n };\n\n const choice = data.choices[0];\n if (!choice) throw new LlmError(`${args.provider} returned no choices`);\n\n return {\n content: choice.message.content,\n provider: args.provider,\n model: args.model,\n inputTokens: data.usage?.prompt_tokens,\n outputTokens: data.usage?.completion_tokens,\n };\n}\n\ninterface AnthropicArgs {\n key: string;\n model: string;\n input: LlmCompleteInput;\n}\n\nasync function anthropicComplete(args: AnthropicArgs): Promise<LlmCompleteOutput> {\n const system = args.input.messages.find((m) => m.role === \"system\")?.content;\n const messages = args.input.messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({ role: m.role, content: m.content }));\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": args.key,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: args.model,\n max_tokens: args.input.maxTokens ?? 1024,\n temperature: args.input.temperature ?? 0.7,\n ...(system ? { system } : {}),\n messages,\n }),\n });\n\n if (!res.ok) {\n const body = await res.text();\n throw new LlmError(`anthropic ${res.status}: ${body.slice(0, 400)}`, res.status);\n }\n\n const data = (await res.json()) as {\n content: Array<{ type: string; text?: string }>;\n usage?: { input_tokens?: number; output_tokens?: number };\n };\n\n const text = data.content.map((b) => b.text ?? \"\").join(\"\");\n return {\n content: text,\n provider: \"anthropic\",\n model: args.model,\n inputTokens: data.usage?.input_tokens,\n outputTokens: data.usage?.output_tokens,\n };\n}\n","/**\n * Parse a JSON object out of an LLM response. Handles three shapes in order:\n * 1. A fenced ```json ... ``` block.\n * 2. A raw JSON document (with optional surrounding whitespace).\n * 3. A response with prose before/after — slice between the outer braces.\n *\n * Returns `fallback` when all three attempts fail. The helper exists so every\n * finder/play that asks the LLM for structured JSON doesn't re-implement the\n * same four-step recovery ceremony (there were seven copies of it before).\n */\nexport function tryParseJsonObject<T>(raw: string, fallback: T): T {\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const candidate = (fenced ? fenced[1] : raw) ?? \"\";\n const trimmed = candidate.trim();\n if (trimmed.length > 0) {\n try {\n return JSON.parse(trimmed) as T;\n } catch {\n // fall through to brace-slice\n }\n const start = candidate.indexOf(\"{\");\n const end = candidate.lastIndexOf(\"}\");\n if (start >= 0 && end > start) {\n try {\n return JSON.parse(candidate.slice(start, end + 1)) as T;\n } catch {\n // fall through to fallback\n }\n }\n }\n return fallback;\n}\n","import {\n enrichProfile,\n getLedger,\n loadConfig,\n logEvent,\n receiptUrlForId,\n sendEmail,\n verifyEmail,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\n\n/** Profiles change slowly — reuse a cached enrichment for this long before refetching. */\nconst ENRICH_CACHE_TTL_MS = 30 * 24 * 3600 * 1000;\n\n/**\n * enrichProfile that (a) never throws and (b) caches by email. The dossier is a\n * nice-to-have for drafting, the SDK call is slow (~70s) and billed, and the\n * same person can recur across plays / repeated previews / re-sends — so we\n * cache the result by email (TTL) and reuse it. A cache hit returns receiptId 0\n * (no new SDK call, no spend). On failure: log a warn and return an empty\n * result so callers' `enr.result` / `enr.receiptId` usage keeps working.\n */\nexport async function safeEnrich(\n input: Parameters<typeof enrichProfile>[0],\n ctx: Parameters<typeof enrichProfile>[1],\n): Promise<Awaited<ReturnType<typeof enrichProfile>>> {\n const ledger = getLedger();\n const email = typeof input.email === \"string\" ? input.email.trim().toLowerCase() : null;\n\n if (email) {\n const cached = ledger.getCachedEnrichment(email);\n if (cached && Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS) {\n try {\n return { result: JSON.parse(cached.result_json), receiptId: 0 } as Awaited<\n ReturnType<typeof enrichProfile>\n >;\n } catch {\n // corrupt cache row — fall through and refetch\n }\n }\n }\n\n try {\n const out = await enrichProfile(input, ctx);\n if (email) {\n try {\n ledger.setCachedEnrichment(email, JSON.stringify(out.result));\n } catch {\n // cache write is best-effort\n }\n }\n return out;\n } catch (err) {\n logEvent(\n \"enrich.failed\",\n { play: ctx.playName, message_120: ((err as Error)?.message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return {\n result: { status: \"failed\", profile: null, cost: 0 },\n receiptId: 0,\n } as unknown as Awaited<ReturnType<typeof enrichProfile>>;\n }\n}\n\nexport const SLOP_PHRASES: Array<[RegExp, string]> = [\n [/\\bI noticed\\b/i, \"banned-opener:I-noticed\"],\n [/\\bI came across\\b/i, \"banned-opener:I-came-across\"],\n [/\\bHope this (?:email )?finds you well\\b/i, \"banned-opener:hope-this-finds\"],\n [/\\bQuick question\\b/i, \"banned-opener:quick-question\"],\n [/\\bLoved your launch\\b/i, \"banned-opener:loved-your-launch\"],\n [/\\bReaching out because\\b/i, \"banned-opener:reaching-out\"],\n [/\\bI'd love to (?:chat|connect|jump on a call|hear)\\b/i, \"banned-cta:love-to-chat\"],\n [/\\bWorth a 15.?min\\b/i, \"banned-cta:worth-15-min\"],\n [/\\bMind if I\\b/i, \"banned-cta:mind-if-i\"],\n [/\\bJust wanted to\\b/i, \"banned-filler:just-wanted-to\"],\n [/\\bcurious to (?:learn|hear)\\b/i, \"banned-filler:curious-to\"],\n [\n /\\b(?:additionally|crucial|delve|enduring|enhance|fostering|garner|highlight|interplay|intricate|pivotal|showcase|tapestry|testament|underscore|leverage|navigate|elevate|empower|seamless|robust|comprehensive|vibrant|profound|groundbreaking|revolutionary)\\b/i,\n \"ai-vocab\",\n ],\n [\n /\\b(?:serves as|stands as|represents a|marks a|functions as|boasts a|features a)\\b/i,\n \"copula-avoidance\",\n ],\n [/^(?:Great question|Certainly|Of course|Absolutely)[!,]/i, \"sycophantic-opener\"],\n [\n /\\b(?:as of my last training|based on available information|while specific details are limited)\\b/i,\n \"knowledge-cutoff-hedge\",\n ],\n [/\\bIt'?s not (?:just|merely) [^.]+, it'?s\\b/i, \"negative-parallelism\"],\n [\n /\\b(?:the future looks bright|exciting times lie ahead|journey toward)\\b/i,\n \"generic-positive-ending\",\n ],\n [/\\b(?:hope this helps|let me know if you'?d like|happy to expand)\\b/i, \"servile-closer\"],\n];\n\nexport function lintEmail(subject: string, body: string, maxBodyWords = 110): string[] {\n const flags: string[] = [];\n if (subject.length === 0) flags.push(\"empty-subject\");\n if (subject.length > 60) flags.push(\"subject-too-long\");\n if (/[A-Z]{2,}/.test(subject)) flags.push(\"subject-shouty\");\n if (body.length === 0) flags.push(\"empty-body\");\n if (body.split(/\\s+/).length > maxBodyWords) flags.push(\"body-too-long\");\n if (body.includes(\"—\")) flags.push(\"em-dash\");\n if (/[“”‘’]/.test(body)) flags.push(\"curly-quotes\");\n if (/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}]/u.test(body)) flags.push(\"emoji\");\n for (const [re, label] of SLOP_PHRASES) {\n if (re.test(body)) flags.push(label);\n }\n if (/(\\b\\w+\\b),\\s+(\\b\\w+\\b),\\s+and\\s+\\b\\w+\\b/.test(body)) flags.push(\"rule-of-three\");\n if ((body.match(/!/g) ?? []).length > 1) flags.push(\"excess-exclamations\");\n if (body.toLowerCase().includes(\"calendly\")) flags.push(\"calendar-link\");\n return flags;\n}\n\nexport interface DraftedEmail {\n subject: string;\n body: string;\n}\n\n/**\n * Stub drafted-row for a target whose per-target processing threw (LLM API\n * error, SDK JobTimeoutError, ledger write failure, etc.). Plays wrap their\n * per-target body in try/catch and push this on failure so the rest of the\n * batch can keep going. Same shape `drain.ts` synthesizes when its outer\n * `dispatchOneTarget` catches — one source of truth for the error envelope.\n */\nexport interface ErrorDraft {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n}\nexport function errorDraft(message: string | null | undefined): ErrorDraft {\n const msg = (message ?? \"play failed\").slice(0, 80);\n return {\n subject: \"(error)\",\n body: \"\",\n flags: [`error: ${msg}`],\n sent: false,\n receiptIds: [],\n };\n}\n\n/**\n * Deterministic, semantics-preserving cleanups that the LLM occasionally\n * slips through despite the humanizer rules being in its system prompt.\n * Applied silently inside `draftEmailFromPrompt` so these four flags never\n * surface in the UI.\n */\nexport function humanizeDraft(input: DraftedEmail): DraftedEmail {\n return {\n subject: applyAutofixes(input.subject),\n body: applyAutofixes(input.body),\n };\n}\n\nfunction applyAutofixes(s: string): string {\n return (\n s\n // Collapse only horizontal whitespace around the em-dash. Using `\\s*`\n // here would eat a trailing newline when an em-dash ends a paragraph,\n // silently merging paragraphs.\n .replace(/[ \\t]*—[ \\t]*/g, \", \")\n .replace(/[“”]/g, '\"')\n .replace(/[‘’]/g, \"'\")\n // Emoji ranges: main BMP+SMP block, dingbats, and the regional-\n // indicator pair used for country flags (🇺🇸 = 1F1FA + 1F1F8).\n .replace(/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}\\u{1F1E6}-\\u{1F1FF}]/gu, \"\")\n // Variation-selector + ZWJ stripped in a second pass — leaving them\n // would produce a dangling glyph after the emoji itself is gone\n // (e.g. `☀️` → `️`).\n .replace(/\\u{FE0F}|\\u{200D}/gu, \"\")\n .replace(/!\\s*!+/g, \"!\")\n // Strip trailing horizontal whitespace before a newline. Catches the\n // `paragraph,_\\n` artifact left by an em-dash at end-of-line, plus\n // any stray trailing space from emoji removal.\n .replace(/[ \\t]+\\n/g, \"\\n\")\n .trim()\n );\n}\n\n/**\n * Binding sign-off directive appended to every email system prompt. Forces\n * the founder's product domain onto its own line beneath their name, even on\n * prompts that say \"no links / no tagline\" (a bare domain is a signature, not\n * a hyperlink). Returns \"\" when no domain is configured, so founders who\n * haven't set one keep the prior name-only sign-off. Loaded fresh each call\n * so a /setup change takes effect without a process restart.\n */\nexport function signatureDirective(): string {\n const cfg = loadConfig();\n const domain = (cfg.productDomain ?? \"\").trim();\n if (!domain) return \"\";\n const name = (cfg.founderName ?? \"\").trim() || \"[founder name]\";\n const mobile = cfg.mobileSignature === true;\n const sigLines = [name, domain];\n if (mobile) sigLines.push(\"Sent from my iPhone\");\n return [\n \"\",\n \"\",\n \"## Signature (binding — overrides any sign-off rule above)\",\n mobile\n ? \"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:\"\n : \"End the email with the founder's name, then their domain on the very next line:\",\n \"\",\n ...sigLines,\n \"\",\n `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.`,\n ...(mobile\n ? [\n `The \"Sent from my iPhone\" line is a literal proof-of-human artifact. Always exactly that string, no variation, no quotes.`,\n ]\n : []),\n ].join(\"\\n\");\n}\n\n/**\n * Build a SOCIAL PROOF input block from the founder's three optional config\n * fields. Returns null when none are set — callers skip the line entirely\n * so the prompt's \"if SOCIAL PROOF is in the inputs\" conditional kicks in.\n * Each prompt should weave AT MOST ONE beat (credentials OR built-with OR\n * partners) into the email, not stack them.\n */\nexport function socialProofBlock(): string | null {\n const cfg = loadConfig();\n const lines: string[] = [];\n const cred = cfg.founderCredentials?.trim();\n const built = cfg.productPortfolio?.trim();\n const partners = cfg.partners?.trim();\n if (cred) lines.push(`CREDENTIALS: ${cred}`);\n if (built) lines.push(`PORTFOLIO: ${built}`);\n if (partners) lines.push(`PARTNERS: ${partners}`);\n if (lines.length === 0) return null;\n return [\n \"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):\",\n ...lines,\n ].join(\"\\n\");\n}\n\nexport async function draftEmailFromPrompt(opts: {\n promptName: string;\n inputBlock: string;\n temperature?: number;\n maxTokens?: number;\n}): Promise<DraftedEmail> {\n const system = loadPrompt(opts.promptName) + signatureDirective();\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: opts.inputBlock },\n ],\n temperature: opts.temperature ?? 0.65,\n maxTokens: opts.maxTokens ?? 500,\n });\n return humanizeDraft(parseSubjectBody(res.content));\n}\n\nfunction parseSubjectBody(raw: string): DraftedEmail {\n const parsed = tryParseJsonObject<{ subject?: string; body?: string }>(raw, {});\n return {\n subject: (parsed.subject ?? \"\").trim(),\n body: (parsed.body ?? \"\").trim(),\n };\n}\n\nexport interface SendDraftedOpts {\n playName: string;\n to: string;\n draft: DraftedEmail;\n flags: string[];\n prospectMeta: {\n name?: string | null;\n email?: string | null;\n company?: string | null;\n linkedin_url?: string | null;\n phone?: string | null;\n source?: string | null;\n };\n metadata?: Record<string, unknown>;\n dryRun: boolean;\n}\n\nexport interface SendDraftedResult {\n receiptIds: number[];\n sent: boolean;\n}\n\nexport async function sendDraftedEmail(opts: SendDraftedOpts): Promise<SendDraftedResult> {\n const ledger = getLedger();\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n const receiptIds: number[] = [];\n let sent = false;\n if (!opts.dryRun && opts.flags.length === 0) {\n // Pre-send dedupe: refuse to send step-0 a second time to the same\n // (prospect, play). Catches double-fire from drain-after-drain, /run\n // resubmits, two-tab races, etc. Residual race window is microseconds\n // between this read and recordSequenceEvent; documented as acceptable.\n const existing = ledger.findProspectByEmail(opts.to);\n if (existing) {\n const prior = ledger.listSequenceEventsForProspectPlay(existing.id, opts.playName);\n if (prior.some((e) => e.step_index === 0)) {\n opts.flags.push(\"already-enrolled\");\n return { receiptIds: [], sent: false };\n }\n }\n const send = await sendEmail(\n { to: opts.to, subject: opts.draft.subject, body: opts.draft.body },\n { playName: opts.playName },\n );\n receiptIds.push(send.receiptId);\n const prospectId = ledger.upsertProspect(opts.prospectMeta);\n ledger.recordSequenceEvent({\n prospectId,\n playName: opts.playName,\n stepIndex: 0,\n channel: \"email\",\n status: \"sent\",\n metadata: { subject: opts.draft.subject, body: opts.draft.body, ...opts.metadata },\n });\n sent = true;\n }\n return { receiptIds, sent };\n}\n\nexport function receiptUrls(receiptIds: number[]): string[] {\n return receiptIds.map(receiptUrlForId);\n}\n\n/** Domain portion of an email address, or undefined if it has no `@`. */\nexport function emailDomain(email: string): string | undefined {\n const at = email.indexOf(\"@\");\n if (at < 0) return undefined;\n return email.slice(at + 1);\n}\n\nexport interface VerifyAndFilterResult<T> {\n verified: T[];\n dropped: Array<{ target: T; email: string; reason: string }>;\n receiptIds: number[];\n costUsd: number;\n}\n\n/**\n * Verify a batch of target emails BEFORE drafting + sending. Used by\n * direct-input entry points (CLI motion commands + dashboard /run) where\n * the founder pastes targets directly without going through a finder.\n * Drops undeliverable rows so the caller skips ~$0.005-0.02 of LLM\n * drafting cost per bad email AND avoids the send attempt itself.\n *\n * Skips on dryRun (no real spend during preview) and on empty input.\n * De-dupes the underlying verifyEmail calls so a duplicated email in\n * the input doesn't double-bill.\n *\n * Finder-sourced rows that flow through /queue → drain do NOT call this\n * — they were already verified at finder enqueue time.\n */\nexport async function verifyAndFilterTargets<T>(\n targets: T[],\n getEmail: (target: T) => string | null | undefined,\n opts: { playName: string; dryRun: boolean },\n): Promise<VerifyAndFilterResult<T>> {\n if (opts.dryRun || targets.length === 0) {\n return { verified: targets, dropped: [], receiptIds: [], costUsd: 0 };\n }\n\n const emailFor = new Map<T, string>();\n for (const t of targets) {\n const e = (getEmail(t) ?? \"\").trim().toLowerCase();\n if (e.length > 0) emailFor.set(t, e);\n }\n\n const uniqueEmails = [...new Set(emailFor.values())];\n // Catch SDK throws (transient network / rate-limit / invalid-format errors)\n // and treat the affected target as dropped rather than aborting the whole\n // run. Mirrors the per-candidate handling finders already do — one bad\n // verify call shouldn't kill a 25-target batch.\n const verifications = await Promise.all(\n uniqueEmails.map(async (email) => {\n try {\n const r = await verifyEmail({ email }, { playName: opts.playName });\n return {\n email,\n deliverable: Boolean(r.result.deliverable),\n receiptId: r.receiptId,\n costUsd: r.result.cost ?? 0,\n errored: false as const,\n };\n } catch (err) {\n return {\n email,\n deliverable: false,\n receiptId: 0,\n costUsd: 0,\n errored: true as const,\n message: ((err as Error).message ?? \"verify failed\").slice(0, 120),\n };\n }\n }),\n );\n const byEmail = new Map(verifications.map((v) => [v.email, v]));\n\n const verified: T[] = [];\n const dropped: VerifyAndFilterResult<T>[\"dropped\"] = [];\n let costUsd = 0;\n const receiptIds: number[] = [];\n for (const v of verifications) {\n costUsd += v.costUsd;\n if (v.receiptId > 0) receiptIds.push(v.receiptId);\n }\n\n for (const t of targets) {\n const email = emailFor.get(t);\n if (!email) {\n dropped.push({ target: t, email: \"\", reason: \"missing email\" });\n continue;\n }\n const v = byEmail.get(email);\n if (!v) {\n dropped.push({ target: t, email, reason: \"undeliverable\" });\n continue;\n }\n if (v.errored) {\n dropped.push({ target: t, email, reason: `verify-error: ${v.message}` });\n continue;\n }\n if (!v.deliverable) {\n dropped.push({ target: t, email, reason: \"undeliverable\" });\n continue;\n }\n verified.push(t);\n }\n\n return { verified, dropped, receiptIds, costUsd };\n}\n","import {\n getLedger,\n listInbox,\n loadConfig,\n parallelMap,\n receiptUrlForId,\n sendEmail,\n sendSms,\n voiceCall,\n type ProspectRecord,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { humanizeDraft, lintEmail, signatureDirective, socialProofBlock } from \"./_lib.ts\";\n\nexport interface CadenceContext {\n prospect: ProspectRecord;\n cfg: ReturnType<typeof loadConfig>;\n metadata: Record<string, unknown>;\n}\n\nexport type StepPayload =\n | { kind: \"email\"; subject: string; body: string }\n | { kind: \"sms\"; message: string; toPhone?: string }\n | {\n kind: \"voice\";\n objective: string;\n toPhone?: string;\n context?: string;\n maxDurationMinutes?: number;\n };\n\nexport interface SequenceStep {\n /** Days after enrollment (step 0 was the original send). step 1 is the first follow-up. */\n dayOffset: number;\n channel: \"email\" | \"sms\" | \"voice\";\n /** When true, an inbound reply at any time stops the cadence. */\n breakOnReply: boolean;\n /** Builder returns null to skip this step gracefully. */\n builder: (ctx: CadenceContext) => Promise<StepPayload | null>;\n /** Optional label for logs. */\n label?: string;\n}\n\nexport interface Sequence {\n playName: string;\n steps: SequenceStep[];\n}\n\nconst playSequences = new Map<string, Sequence>();\n\nexport function registerSequence(seq: Sequence): void {\n playSequences.set(seq.playName, seq);\n}\n\n/**\n * \"Does this label name a breakup step?\" — single source of truth for the\n * label-substring check. Used by isBreakupStepAt for the cadence-final\n * semantic check AND by /plays for per-step rendering where each row is\n * already a step.\n */\nexport function isBreakupLabel(label: string | null | undefined): boolean {\n return Boolean(label && label.toLowerCase().includes(\"breakup\"));\n}\n\n/**\n * Centralized breakup-step detection for cadence-progress semantics. A\n * step is \"the breakup\" iff (a) it sits at the END of the sequence and\n * (b) its label is a breakup label. Both clauses matter: the\n * breakup-email PROMPT is also used as accelerator-batch's only\n * follow-up — at index 0 — and that one isn't semantically a breakup\n * for cadence UX purposes (no value follow-up preceded it).\n */\nexport function isBreakupStepAt(seq: Sequence, stepEntryIndex: number): boolean {\n if (stepEntryIndex !== seq.steps.length - 1) return false;\n return isBreakupLabel(seq.steps[stepEntryIndex]?.label);\n}\n\nexport interface NextStepInfo {\n /** Label of the next step (e.g. \"value follow-up\", \"breakup\"). */\n label: string | null;\n /** True when the next step is the final breakup. */\n isBreakup: boolean;\n /** 1-based index of the next step within the follow-up steps array. */\n nextStepNumber: number;\n}\n\n/**\n * Number of follow-up steps registered for this play (excludes day-0).\n * Always returns the registered total regardless of current_step — the UI\n * uses `playFollowupCount + 1` for the StepProgress dot count which should\n * be stable for completed cadences too.\n */\nexport function playFollowupCount(playName: string): number {\n return effectiveSequence(playName)?.steps.length ?? 0;\n}\n\n/**\n * Given a play + the cadence's current_step, describe the NEXT step\n * scheduled to fire. Returns null when the cadence is at or past the\n * last step (no more steps to send). Source of truth for both the\n * server's CadenceView and the /cadences UI — avoids hardcoded\n * play→step-count Records in the web layer.\n */\nexport function nextStepInfo(playName: string, currentStep: number): NextStepInfo | null {\n const seq = effectiveSequence(playName);\n if (!seq) return null;\n const nextIndex = currentStep + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) return null;\n const step = seq.steps[stepEntryIndex];\n return {\n label: step?.label ?? null,\n isBreakup: isBreakupStepAt(seq, stepEntryIndex),\n nextStepNumber: nextIndex,\n };\n}\n\nexport function getSequence(playName: string): Sequence | undefined {\n return effectiveSequence(playName);\n}\n\n/** The registered (code) sequence, ignoring any founder override. For \"reset\". */\nexport function defaultSequence(playName: string): Sequence | undefined {\n return playSequences.get(playName);\n}\n\n/**\n * The registered (code) sequence with the founder's per-play timing overrides\n * applied. The code sequence defines the structure (which prompts fire, where\n * the breakup sits); a matching-length `cadenceOverrides[playName]` in config\n * replaces each step's RELATIVE dayOffset. A length mismatch (e.g. after a\n * later structural change) is ignored — the code default wins, never throws.\n * Read fresh each call so a /plays edit takes effect without a restart.\n */\nexport function effectiveSequence(playName: string): Sequence | undefined {\n const base = playSequences.get(playName);\n if (!base) return undefined;\n const override = loadConfig().cadenceOverrides?.[playName];\n if (!Array.isArray(override) || override.length !== base.steps.length) return base;\n return {\n playName: base.playName,\n steps: base.steps.map((step, i) => ({\n dayOffset: override[i] as number,\n channel: step.channel,\n breakOnReply: step.breakOnReply,\n label: step.label,\n builder: step.builder,\n })),\n };\n}\n\nexport function enrollInCadence(input: { prospectId: number; playName: string }): void {\n const seq = effectiveSequence(input.playName);\n if (!seq || seq.steps.length === 0) return;\n const next = seq.steps[0];\n if (!next) return;\n const dueAt = new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString();\n getLedger().enrollCadence({\n prospectId: input.prospectId,\n playName: input.playName,\n nextDueAt: dueAt,\n });\n}\n\nexport interface AdvanceResult {\n polled: number;\n repliesDetected: number;\n stepsExecuted: number;\n breakups: number;\n completed: number;\n details: Array<{\n prospectEmail: string | null;\n playName: string;\n action: \"step-sent\" | \"marked-replied\" | \"breakup\" | \"completed\" | \"waiting\" | \"skipped\";\n note?: string;\n receiptIds: number[];\n }>;\n}\n\nexport async function advanceCadence(\n opts: { dryRun: boolean } = { dryRun: false },\n): Promise<AdvanceResult> {\n const ledger = getLedger();\n const result: AdvanceResult = {\n polled: 0,\n repliesDetected: 0,\n stepsExecuted: 0,\n breakups: 0,\n completed: 0,\n details: [],\n };\n\n // 1. Poll inbox for new replies, mark cadences as replied where we recognize the from-address.\n if (!opts.dryRun) {\n try {\n const inbox = await listInbox({ limit: 50 });\n result.polled = inbox.emails.length;\n for (const e of inbox.emails) {\n const from = normalizeEmail(e.from);\n const prospect = ledger.findProspectByEmail(from);\n if (!prospect) continue;\n // Index seek per matched sender, not a full-table scan per inbox email.\n const activeForProspect = ledger\n .listCadencesForProspect(prospect.id)\n .filter((c) => c.status === \"active\");\n for (const cad of activeForProspect) {\n ledger.setCadenceStatus({\n prospectId: prospect.id,\n playName: cad.play_name,\n status: \"replied\",\n });\n result.repliesDetected++;\n result.details.push({\n prospectEmail: from,\n playName: cad.play_name,\n action: \"marked-replied\",\n note: `inbound: ${e.subject}`,\n receiptIds: [],\n });\n }\n }\n } catch (err) {\n result.details.push({\n prospectEmail: null,\n playName: \"(poll)\",\n action: \"skipped\",\n note: `inbox poll failed: ${(err as Error).message}`,\n receiptIds: [],\n });\n }\n }\n\n // 2. For each active cadence with next_due_at <= now, execute the next step.\n // Parallelized (concurrency 3): each step is an LLM draft + send (~5-90s), and\n // `due` rows are distinct (prospect, play) pairs, so there's no shared-write\n // contention. Results are collected in input order before counting.\n const nowIso = new Date().toISOString();\n const due = ledger.listActiveCadences({ dueByIso: nowIso });\n\n const outs = await parallelMap(due, 3, (cad) =>\n runCadenceStepForProspect({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\n dryRun: opts.dryRun,\n }),\n );\n\n for (let i = 0; i < due.length; i++) {\n const cad = due[i]!;\n const out = outs[i]!;\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: out.action,\n ...(out.note ? { note: out.note } : {}),\n receiptIds: out.receiptIds,\n });\n if (out.action === \"step-sent\") result.stepsExecuted++;\n else if (out.action === \"breakup\") result.breakups++;\n else if (out.action === \"completed\") result.completed++;\n }\n\n return result;\n}\n\nexport interface RunCadenceStepOptions {\n prospectId: number;\n playName: string;\n dryRun: boolean;\n /** Skip the step's builder and send this verbatim (mirrors /queue's\n send-this-one — used by the /cadences UI after a Preview round-trip). */\n persistedPayload?: StepPayload;\n}\n\nexport interface RunCadenceStepResult {\n action: AdvanceResult[\"details\"][number][\"action\"];\n payload: StepPayload | null;\n receiptIds: number[];\n note?: string;\n}\n\n/**\n * Per-prospect cadence step runner. Single source of truth for both the\n * batch `advanceCadence` (CLI) and the per-row /cadences UI (preview + send).\n * Caller decides dryRun (no send) or persistedPayload (send a previously\n * built draft verbatim). On a successful send, advances `current_step`\n * to `nextIndex` and sets `next_due_at` to the next step's offset; clears\n * any persisted preview draft via ledger.advanceCadence.\n */\nexport async function runCadenceStepForProspect(\n opts: RunCadenceStepOptions,\n): Promise<RunCadenceStepResult> {\n const ledger = getLedger();\n const cfg = loadConfig();\n const cadence = ledger.getCadence(opts.prospectId, opts.playName);\n if (!cadence) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"no cadence\" };\n }\n if (cadence.status !== \"active\") {\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: `cadence is ${cadence.status}`,\n };\n }\n const seq = effectiveSequence(opts.playName);\n if (!seq) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"no registered sequence\" };\n }\n const nextIndex = cadence.current_step + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n return { action: \"completed\", payload: null, receiptIds: [] };\n }\n const step = seq.steps[stepEntryIndex];\n if (!step) return { action: \"skipped\", payload: null, receiptIds: [] };\n\n const prospect = loadProspect(opts.prospectId);\n if (!prospect) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"prospect not found\" };\n }\n\n const built: StepPayload | null = opts.persistedPayload\n ? opts.persistedPayload\n : await step.builder({ prospect, cfg, metadata: {} });\n\n if (!built) {\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: opts.prospectId,\n playName: opts.playName,\n newStep: nextIndex,\n nextDueAt: next\n ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString()\n : null,\n });\n if (!next) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n return {\n action: \"completed\",\n payload: null,\n receiptIds: [],\n note: step.label ?? `step ${nextIndex} builder returned null`,\n };\n }\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: step.label ?? `step ${nextIndex} builder returned null`,\n };\n }\n\n const receiptIds: number[] = [];\n if (!opts.dryRun) {\n const channelOutcome = await dispatchStep({\n playName: opts.playName,\n prospectId: opts.prospectId,\n prospectEmail: cadence.prospect_email,\n stepIndex: nextIndex,\n step,\n payload: built,\n ...(step.label !== undefined ? { label: step.label } : {}),\n });\n if (channelOutcome.skipReason) {\n return {\n action: \"skipped\",\n payload: built,\n receiptIds: [],\n note: channelOutcome.skipReason,\n };\n }\n receiptIds.push(...channelOutcome.receiptIds);\n }\n\n if (isBreakupStepAt(seq, stepEntryIndex)) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"breakup\",\n });\n return {\n action: \"breakup\",\n payload: built,\n receiptIds,\n note: step.label ?? `step ${nextIndex}`,\n };\n }\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: opts.prospectId,\n playName: opts.playName,\n newStep: nextIndex,\n nextDueAt: next ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString() : null,\n });\n if (!next) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n }\n return {\n action: \"step-sent\",\n payload: built,\n receiptIds,\n note: step.label ?? `step ${nextIndex}`,\n };\n}\n\nexport interface CadenceStepPreview {\n subject: string;\n body: string;\n flags: string[];\n payload: StepPayload;\n draftedAt: string;\n stepLabel: string | null;\n isBreakup: boolean;\n}\n\n/**\n * Build the next step's draft and persist it via setCadenceDraft. Never\n * sends. Mirrors the /queue regenerate route — the founder reviews on\n * /cadences, then clicks Send next which calls sendCadenceStep.\n */\nexport async function previewCadenceStep(input: {\n prospectId: number;\n playName: string;\n}): Promise<CadenceStepPreview> {\n const ledger = getLedger();\n const cfg = loadConfig();\n const cadence = ledger.getCadence(input.prospectId, input.playName);\n if (!cadence) throw new Error(\"no cadence for that prospect+play\");\n if (cadence.status !== \"active\") {\n throw new Error(`cadence is ${cadence.status}, can only preview an active cadence`);\n }\n const seq = effectiveSequence(input.playName);\n if (!seq) throw new Error(`no registered sequence for play '${input.playName}'`);\n const nextIndex = cadence.current_step + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {\n throw new Error(\"no next step (cadence is at or past the last step)\");\n }\n const step = seq.steps[stepEntryIndex];\n if (!step) throw new Error(\"step undefined\");\n const prospect = loadProspect(input.prospectId);\n if (!prospect) throw new Error(\"prospect not found\");\n const built = await step.builder({ prospect, cfg, metadata: {} });\n if (!built) throw new Error(\"builder returned null — nothing to preview\");\n\n const subject = built.kind === \"email\" ? built.subject : \"(non-email step)\";\n const body =\n built.kind === \"email\"\n ? built.body\n : built.kind === \"sms\"\n ? built.message\n : built.kind === \"voice\"\n ? built.objective\n : \"\";\n const flags = built.kind === \"email\" ? lintEmail(subject, body, 100) : [];\n ledger.setCadenceDraft({\n prospectId: input.prospectId,\n playName: input.playName,\n draft: { subject, body, flags, payload: built },\n });\n const draft = ledger.getCadenceDraft({\n prospectId: input.prospectId,\n playName: input.playName,\n });\n const draftedAt = draft?.draftedAt ?? new Date().toISOString();\n return {\n subject,\n body,\n flags,\n payload: built,\n draftedAt,\n stepLabel: step.label ?? null,\n isBreakup: isBreakupStepAt(seq, stepEntryIndex),\n };\n}\n\n/**\n * Send a previously-previewed cadence step verbatim. Reads the persisted\n * draft (or 409s if none), dispatches it through runCadenceStepForProspect,\n * and advances the cadence. The advance clears the persisted draft so a\n * subsequent Preview rebuilds against the new current_step.\n */\nexport async function sendCadenceStep(input: {\n prospectId: number;\n playName: string;\n}): Promise<RunCadenceStepResult> {\n const ledger = getLedger();\n const draft = ledger.getCadenceDraft(input);\n if (!draft) throw new Error(\"no persisted preview — click Preview first\");\n return runCadenceStepForProspect({\n prospectId: input.prospectId,\n playName: input.playName,\n dryRun: false,\n persistedPayload: draft.payload as StepPayload,\n });\n}\n\nexport interface BatchItem {\n prospectId: number;\n playName: string;\n}\n\nexport interface BatchPreviewResult {\n prospectId: number;\n playName: string;\n ok: boolean;\n preview?: CadenceStepPreview;\n error?: string;\n}\n\nexport interface BatchSendResult {\n prospectId: number;\n playName: string;\n ok: boolean;\n action?: RunCadenceStepResult[\"action\"];\n receiptIds?: number[];\n error?: string;\n}\n\n/**\n * Parallel preview of a list of cadence rows (concurrency 3). Each\n * per-prospect failure is captured in the result array — the batch never\n * throws. `parallelMap` preserves input order so the returned array matches\n * `items` 1:1. Concurrency mirrors `runEmailPlay` + `advanceCadence`; the\n * founder is waiting at the UI, so 3× speedup on a 10-row preview drops\n * wall-clock from ~100s to ~35s.\n */\nexport async function previewCadenceStepBatch(items: BatchItem[]): Promise<BatchPreviewResult[]> {\n return parallelMap(items, 3, async (item) => {\n try {\n const preview = await previewCadenceStep(item);\n return { prospectId: item.prospectId, playName: item.playName, ok: true, preview };\n } catch (err) {\n return {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: false,\n error: ((err as Error)?.message ?? \"preview failed\").slice(0, 120),\n };\n }\n });\n}\n\n/**\n * Serial send of a list of previewed cadence rows. Each per-prospect failure\n * is captured; the batch never throws. Used by `POST /api/cadences/send-batch`\n * as a background promise — caller returns 202 immediately and the UI sees\n * progress via subsequent `/api/cadences` refetches (the existing\n * `advanceCadence` clears `next_step_draft_json` as each row completes).\n *\n * Sends stay serial (unlike previewCadenceStepBatch) for two reasons: the\n * `onItemSettled` callback drives the in-flight UI badge per row (parallel\n * would batch-flash all rows at once), and parallel SMTP to the same\n * domain risks soft-bounces.\n */\nexport async function sendCadenceStepBatch(\n items: BatchItem[],\n /** Fires after each item resolves (ok OR error) — lets the API layer\n * track per-row in-flight state without splitting the iteration. */\n onItemSettled?: (item: BatchItem, result: BatchSendResult) => void,\n): Promise<BatchSendResult[]> {\n const out: BatchSendResult[] = [];\n for (const item of items) {\n let result: BatchSendResult;\n try {\n const r = await sendCadenceStep(item);\n result = {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: true,\n action: r.action,\n receiptIds: r.receiptIds,\n };\n } catch (err) {\n result = {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: false,\n error: ((err as Error)?.message ?? \"send failed\").slice(0, 120),\n };\n }\n out.push(result);\n onItemSettled?.(item, result);\n }\n return out;\n}\n\nasync function dispatchStep(input: {\n playName: string;\n prospectId: number;\n prospectEmail: string | null;\n stepIndex: number;\n step: SequenceStep;\n payload: StepPayload;\n label?: string | undefined;\n}): Promise<{ receiptIds: number[]; skipReason?: string }> {\n const ledger = getLedger();\n const receiptIds: number[] = [];\n\n if (input.payload.kind === \"email\") {\n if (!input.prospectEmail) return { receiptIds, skipReason: \"prospect has no email\" };\n const send = await sendEmail(\n { to: input.prospectEmail, subject: input.payload.subject, body: input.payload.body },\n { playName: input.playName },\n );\n receiptIds.push(send.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"email\",\n status: \"sent\",\n metadata: {\n subject: input.payload.subject,\n body: input.payload.body,\n label: input.label,\n },\n });\n return { receiptIds };\n }\n\n if (input.payload.kind === \"sms\") {\n if (!input.payload.toPhone) {\n return { receiptIds, skipReason: \"prospect has no phone for SMS\" };\n }\n const send = await sendSms(\n { to: input.payload.toPhone, message: input.payload.message },\n { playName: input.playName },\n );\n receiptIds.push(send.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"sms\",\n status: \"sent\",\n metadata: { label: input.label },\n });\n return { receiptIds };\n }\n\n if (input.payload.kind === \"voice\") {\n if (!input.payload.toPhone) {\n return { receiptIds, skipReason: \"prospect has no phone for voice\" };\n }\n const call = await voiceCall(\n {\n objective: input.payload.objective,\n to: input.payload.toPhone,\n ...(input.payload.context ? { context: input.payload.context } : {}),\n ...(input.payload.maxDurationMinutes\n ? { maxDurationMinutes: input.payload.maxDurationMinutes }\n : {}),\n },\n { playName: input.playName },\n );\n receiptIds.push(call.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"voice\",\n status: \"sent\",\n metadata: { label: input.label, ended_reason: call.result.ended_reason ?? null },\n });\n return { receiptIds };\n }\n\n return { receiptIds, skipReason: \"unknown step payload kind\" };\n}\n\nfunction normalizeEmail(raw: string): string {\n const m = raw.match(/<([^>]+)>/);\n return (m ? m[1]! : raw).trim().toLowerCase();\n}\n\nfunction loadProspect(id: number): ProspectRecord | null {\n return getLedger().getProspectById(id);\n}\n\nexport function buildFollowUpEmail(opts: {\n playName: string;\n promptName: string;\n contextLines: string[];\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const system = loadPrompt(opts.promptName) + signatureDirective();\n const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);\n const proofBlock = socialProofBlock();\n const user = [\n `FOUNDER: ${ctx.cfg.founderName}`,\n `PRODUCT: ${ctx.cfg.productOneLiner}`,\n `PROSPECT: ${ctx.prospect.name ?? \"(unknown)\"}`,\n `EMAIL: ${ctx.prospect.email ?? \"\"}`,\n `COMPANY: ${ctx.prospect.company ?? \"(unknown)\"}`,\n ...opts.contextLines,\n ...(priorBlock ? [\"\", priorBlock] : []),\n ...(proofBlock ? [\"\", proofBlock] : []),\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.6,\n maxTokens: 500,\n });\n const parsed = tryParseJsonObject<{ subject?: string; body?: string }>(res.content, {});\n if (!parsed.subject || !parsed.body) return null;\n // Apply the deterministic autofixer (em-dash → \", \", curly quotes → ASCII,\n // emoji strip, etc.) — same humanization the initial-send plays get via\n // draftEmailFromPrompt. Without this, cadence follow-ups ship em-dashes\n // raw even though lintEmail flags them.\n const cleaned = humanizeDraft({\n subject: parsed.subject.trim(),\n body: parsed.body.trim(),\n });\n return { kind: \"email\", subject: cleaned.subject, body: cleaned.body };\n };\n}\n\nexport interface PriorStepRow {\n stepIndex: number;\n /** \"initial send\" for step 0; the registered step label for 1+; \"follow-up\" if missing. */\n label: string;\n subject: string;\n /** Null for legacy pre-v8 rows whose metadata_json didn't include the body. */\n body: string | null;\n /** sequence_events.created_at (UTC ISO). */\n sentAt: string;\n status: \"sent\" | \"delivered\" | \"replied\";\n}\n\n/**\n * Parse a prospect's prior sends for a given play into clean per-step rows.\n * Source of truth shared by the LLM PRIOR-EMAILS injection (which filters\n * legacy rows) and the /api/cadences view (which surfaces them with a\n * \"body not captured\" placeholder).\n */\nexport function getPriorStepsForProspect(prospectId: number, playName: string): PriorStepRow[] {\n if (!prospectId) return [];\n let rows: Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>;\n try {\n rows = getLedger().listSequenceEventsForProspectPlay(prospectId, playName) as Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>;\n } catch {\n return [];\n }\n return rows.map(rowToPriorStep);\n}\n\nfunction rowToPriorStep(r: {\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n}): PriorStepRow {\n const meta = tryParseJsonObject<{ subject?: string; body?: string; label?: string }>(\n r.metadata_json ?? \"\",\n {},\n );\n return {\n stepIndex: r.step_index,\n label: meta.label ?? (r.step_index === 0 ? \"initial send\" : \"follow-up\"),\n subject: meta.subject ?? \"(no subject)\",\n body: meta.body ?? null,\n sentAt: r.created_at,\n status: (r.status as PriorStepRow[\"status\"]) ?? \"sent\",\n };\n}\n\n/**\n * Bulk variant of getPriorStepsForProspect: one SQL round-trip for many\n * (prospect_id, play_name) pairs. Returns a Map keyed by\n * `${prospectId}|${playName}` so /api/cadences's toView can index in O(1)\n * instead of issuing one query per row. Pairs the founder hasn't sent for\n * are absent from the map (callers should default to []).\n */\nexport function getPriorStepsBulk(\n pairs: ReadonlyArray<{ prospectId: number; playName: string }>,\n): Map<string, PriorStepRow[]> {\n if (pairs.length === 0) return new Map();\n let bulk: Map<\n string,\n Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>\n >;\n try {\n bulk = getLedger().listSequenceEventsForCadences(pairs) as Map<\n string,\n Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>\n >;\n } catch {\n return new Map();\n }\n const out = new Map<string, PriorStepRow[]>();\n for (const [key, rows] of bulk) {\n out.set(key, rows.map(rowToPriorStep));\n }\n return out;\n}\n\nfunction buildPriorEmailsBlock(prospectId: number, playName: string): string | null {\n const prior = getPriorStepsForProspect(prospectId, playName).filter(\n (r): r is PriorStepRow & { body: string } => r.body !== null && r.body.length > 0,\n );\n if (prior.length === 0) return null;\n const lines = [\n \"PRIOR EMAILS (your previous touches to this prospect on this play; do not repeat their angles, hooks, openers, or closes):\",\n ];\n for (const row of prior) {\n lines.push(`--- step ${row.stepIndex} (${row.label}) ---`);\n lines.push(`Subject: ${row.subject}`);\n lines.push(row.body);\n }\n return lines.join(\"\\n\");\n}\n\nexport function buildSmsStep(opts: {\n promptName: string;\n contextLines: string[];\n toPhone: (ctx: CadenceContext) => string | null;\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const phone = opts.toPhone(ctx);\n if (!phone) return null;\n const system = loadPrompt(opts.promptName);\n const user = [\n `FOUNDER: ${ctx.cfg.founderName}`,\n `PRODUCT: ${ctx.cfg.productOneLiner}`,\n `PROSPECT: ${ctx.prospect.name ?? \"(unknown)\"}`,\n ...opts.contextLines,\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.5,\n maxTokens: 250,\n });\n const parsed = tryParseJsonObject<{ message?: string }>(res.content, {});\n if (!parsed.message) return null;\n return { kind: \"sms\", message: parsed.message.trim(), toPhone: phone };\n };\n}\n\nexport function buildVoiceStep(opts: {\n toPhone: (ctx: CadenceContext) => string | null;\n objective: (ctx: CadenceContext) => string;\n context?: (ctx: CadenceContext) => string;\n maxDurationMinutes?: number;\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const phone = opts.toPhone(ctx);\n if (!phone) return null;\n return {\n kind: \"voice\",\n objective: opts.objective(ctx),\n toPhone: phone,\n ...(opts.context ? { context: opts.context(ctx) } : {}),\n ...(opts.maxDurationMinutes ? { maxDurationMinutes: opts.maxDurationMinutes } : {}),\n };\n };\n}\n\nexport function receiptUrlsForCadence(receiptIds: number[]): string[] {\n return receiptIds.map(receiptUrlForId);\n}\n","import { deepResearch, getLedger, loadConfig, parallelMap } from \"@oneshot-gtm/core\";\nimport {\n draftEmailFromPrompt,\n errorDraft,\n lintEmail,\n safeEnrich,\n sendDraftedEmail,\n socialProofBlock,\n type SendDraftedOpts,\n} from \"./_lib.ts\";\nimport { enrollInCadence } from \"./_cadence.ts\";\n\ntype AppConfig = ReturnType<typeof loadConfig>;\n\n/**\n * What a play's per-target `prepare` step hands back to the executor: the\n * receipts it billed, the dossier string it assembled (may be empty), and an\n * optional `extra` bag of play-specific fields that get merged onto the\n * drafted row verbatim (e.g. competitor-switch's `scrapedEvidence`,\n * hiring-signal's `jobPostHook`). `X` defaults to no extra fields.\n */\nexport interface Prepared<X = Record<string, never>> {\n receiptIds: number[];\n dossier: string;\n extra?: X;\n}\n\n/** Drafted row every email play returns: the standard six fields plus `X`. */\nexport type PlayDraft<T, X = Record<string, never>> = {\n target: T;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n} & X;\n\n/**\n * Declarative definition of an email play. The shared executor (`runEmailPlay`)\n * walks the targets, runs `prepare` → draft → lint → send → optional cadence\n * enroll, and wraps each per-target body in the same try/catch error envelope.\n * Everything that varies between plays is a field or a closure here.\n */\nexport interface EmailPlayDef<T, X = Record<string, never>> {\n playName: string;\n promptName: string;\n /** Per-play word budget passed to `lintEmail`. */\n maxBodyWords: number;\n toEmail: (t: T) => string;\n /**\n * Enrichment / research / scrape phase. Owns all SDK calls that build\n * context for the draft. Use `standardEnrich` for the safeEnrich(+deepResearch)\n * shape; plays with browser/websearch context supply their own.\n */\n prepare: (t: T, dryRun: boolean) => Promise<Prepared<X>>;\n buildInputBlock: (t: T, prep: Prepared<X>, cfg: AppConfig) => string;\n prospectMeta: (t: T) => SendDraftedOpts[\"prospectMeta\"];\n metadata?: (t: T) => Record<string, unknown>;\n /** Enroll the prospect in this play's cadence after a real send. */\n enrollCadence?: boolean;\n /** Extra fields merged onto the row when a target throws (e.g. jobPostHook). */\n errorExtra?: X;\n}\n\n/**\n * Run an email play over its targets. Behavior-preserving extraction of the\n * per-target loop that every email play used to hand-roll: enrich/research →\n * draft → lint → send → (optional) cadence enroll, with a per-target try/catch\n * so one bad target can't kill the batch.\n */\nexport async function runEmailPlay<T, X = Record<string, never>>(\n def: EmailPlayDef<T, X>,\n opts: { dryRun: boolean; targets: T[] },\n): Promise<{ drafted: Array<PlayDraft<T, X>> }> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n\n // Process targets in parallel (each is an LLM draft + send, ~5-90s). Drop to\n // serial when the batch has duplicate emails: sendDraftedEmail's per-(prospect,\n // play) step-0 dedupe is read-then-write, and only the serial order guarantees\n // a duplicate doesn't slip a second send through the window. Finder-drained\n // batches are already unique, so they get the full concurrency.\n const emails = opts.targets.map((t) => def.toEmail(t).trim().toLowerCase());\n const hasDupeEmails = new Set(emails).size !== emails.length;\n const concurrency = hasDupeEmails ? 1 : 3;\n\n const drafted = await parallelMap(opts.targets, concurrency, async (target) => {\n try {\n const prep = await def.prepare(target, opts.dryRun);\n\n // Append SOCIAL PROOF block when any of the three optional fields is\n // set. Prompts treat it as conditional input — present only when set,\n // and the prompt picks ONE beat per email (never stacks).\n const proof = socialProofBlock();\n const inputBlock = proof\n ? `${def.buildInputBlock(target, prep, cfg)}\\n\\n${proof}`\n : def.buildInputBlock(target, prep, cfg);\n const draft = await draftEmailFromPrompt({\n promptName: def.promptName,\n inputBlock,\n });\n\n const flags = lintEmail(draft.subject, draft.body, def.maxBodyWords);\n\n const send = await sendDraftedEmail({\n playName: def.playName,\n to: def.toEmail(target),\n draft,\n flags,\n prospectMeta: def.prospectMeta(target),\n ...(def.metadata ? { metadata: def.metadata(target) } : {}),\n dryRun: opts.dryRun,\n });\n\n if (send.sent && def.enrollCadence) {\n const prospect = getLedger().findProspectByEmail(def.toEmail(target));\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: def.playName });\n }\n\n return {\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...prep.receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n ...(prep.extra ?? ({} as X)),\n } as PlayDraft<T, X>;\n } catch (err) {\n return {\n target,\n ...errorDraft((err as Error)?.message),\n ...(def.errorExtra ?? ({} as X)),\n } as PlayDraft<T, X>;\n }\n });\n\n return { drafted };\n}\n\n/**\n * The common `prepare` body for plays that personalize via `safeEnrich` (cached\n * by email, never throws) and, on real sends only, a `deepResearch` dossier.\n * Pass `research` only when you want the research call to fire — callers gate it\n * on `!dryRun` (and, for accelerator-batch, on a launch URL being present).\n */\nexport async function standardEnrich(opts: {\n playName: string;\n enrichInput: Parameters<typeof safeEnrich>[0];\n enrichSlice: number;\n research?: { topic: string; slice?: number };\n}): Promise<Prepared> {\n const receiptIds: number[] = [];\n\n const enr = await safeEnrich(opts.enrichInput, { playName: opts.playName });\n if (enr.receiptId) receiptIds.push(enr.receiptId);\n let dossier = JSON.stringify(enr.result, null, 2).slice(0, opts.enrichSlice);\n\n if (opts.research) {\n const research = await deepResearch(\n { topic: opts.research.topic, depth: \"quick\" },\n { playName: opts.playName },\n );\n receiptIds.push(research.receiptId);\n dossier +=\n \"\\n\\n---\\n\\n\" +\n JSON.stringify(research.result, null, 2).slice(0, opts.research.slice ?? 4000);\n }\n\n return { receiptIds, dossier };\n}\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport type AcceleratorCohort =\n | \"yc-w26\"\n | \"yc-s26\"\n | \"yc-w25\"\n | \"yc-s25\"\n | \"od\"\n | \"spc\"\n | \"antler\"\n | \"techstars\"\n | \"neo\"\n | \"soma\"\n | \"other\";\n\nexport interface AcceleratorBatchTarget {\n name: string;\n email: string;\n company: string;\n cohort: string;\n launchUrl?: string;\n productOneLiner?: string;\n linkedinUrl?: string;\n phone?: string;\n /** The SENDER's own cohort (peer angle). Stamped onto finder rows from the\n * trigger config so the row is self-contained; falls back to the run-level\n * option for manually-entered /run targets. */\n senderCohort?: string;\n /** Optional time-bound offer for the sender's cohort. Same fallback rules. */\n freeForCohortOffer?: string;\n}\n\nexport interface AcceleratorBatchRunOptions {\n dryRun: boolean;\n targets: AcceleratorBatchTarget[];\n /** Run-level fallback applied to any target that doesn't carry its own. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\nexport interface AcceleratorBatchDraft {\n target: AcceleratorBatchTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"accelerator-batch\";\n\nexport function runAcceleratorBatch(\n opts: AcceleratorBatchRunOptions,\n): Promise<{ drafted: AcceleratorBatchDraft[] }> {\n // senderCohort / freeForCohortOffer are read target-first (finder rows carry\n // their own, stamped from trigger config) with the run-level option as a\n // fallback for manually-entered /run targets. Built per-call to close over\n // that fallback.\n const senderCohortFor = (t: AcceleratorBatchTarget): string =>\n (t.senderCohort?.trim() || opts.senderCohort || \"\").trim();\n const offerFor = (t: AcceleratorBatchTarget): string | undefined =>\n t.freeForCohortOffer ?? opts.freeForCohortOffer;\n const def: EmailPlayDef<AcceleratorBatchTarget> = {\n playName: PLAY_NAME,\n promptName: \"accelerator-batch-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email); deepResearch is\n // real-send only AND only when a launch URL is present to anchor it.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 3500,\n ...(!dryRun && t.launchUrl\n ? {\n research: {\n topic: `Recent public work and decisions by ${t.name} at ${t.company} (${t.cohort}). Pull launch context from ${t.launchUrl}.`,\n },\n }\n : {}),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SENDER COHORT: ${senderCohortFor(t) || \"(unspecified)\"}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `PROSPECT COHORT: ${t.cohort}`,\n `PROSPECT PRODUCT: ${t.productOneLiner ?? \"(unknown)\"}`,\n `LAUNCH URL: ${t.launchUrl ?? \"(none)\"}`,\n `FREE-FOR-COHORT OFFER: ${offerFor(t) ?? \"(no active offer for this cohort)\"}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the cohort match only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: `accelerator-${t.cohort}`,\n }),\n metadata: (t) => ({\n senderCohort: senderCohortFor(t),\n prospectCohort: t.cohort,\n }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 5,\n channel: \"email\",\n breakOnReply: true,\n label: \"single follow-up + breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [\n `PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`,\n ],\n }),\n },\n ],\n});\n","import { getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, errorDraft, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\n\nconst PLAY_NAME = \"breakup-revive\";\n\nexport interface BreakupReviveTarget {\n name: string | null;\n email: string;\n company: string | null;\n daysCold: number;\n lastEventAt: string | null;\n linkedinUrl?: string | null;\n phone?: string | null;\n}\n\nexport interface BreakupReviveOptions {\n dryRun: boolean;\n /**\n * When provided, skip the ledger scan and use these prospects directly.\n * The queue-based flow (`find breakup-revive` → `find drain breakup-revive`)\n * goes through this path. When omitted, fall back to scanning the ledger.\n */\n targets?: BreakupReviveTarget[];\n /** Min days since last activity to consider cold. Default 60. (Ledger-scan mode only.) */\n minDays?: number;\n /** Max days since last activity to consider revivable. Default 90. (Ledger-scan mode only.) */\n maxDays?: number;\n /** Hard cap on prospects to revive in one run. Default 25. */\n limit?: number;\n /** Optional value drop to lead with (a new feature, a benchmark, a case study you can offer). */\n valueDrop?: string;\n}\n\nexport interface BreakupReviveDraft {\n prospectEmail: string | null;\n prospectName: string | null;\n daysCold: number;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nexport async function runBreakupRevive(\n opts: BreakupReviveOptions,\n): Promise<{ drafted: BreakupReviveDraft[] }> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n\n const targets = opts.targets ?? ledgerScanTargets(opts);\n const drafted: BreakupReviveDraft[] = [];\n\n for (const t of targets) {\n if (!t.email) continue;\n try {\n const draft = await draftEmailFromPrompt({\n promptName: \"breakup-revive-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name ?? \"(unknown)\"} at ${t.company ?? \"(unknown)\"}`,\n `DAYS SINCE LAST ACTIVITY: ${t.daysCold}`,\n `OPTIONAL VALUE DROP: ${opts.valueDrop ?? \"(none — go with a probe question instead)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 80);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: t.email,\n draft,\n flags,\n prospectMeta: {\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"breakup-revive\",\n },\n metadata: { daysCold: t.daysCold, lastEventAt: t.lastEventAt },\n dryRun: opts.dryRun,\n });\n\n drafted.push({\n prospectEmail: t.email,\n prospectName: t.name,\n daysCold: t.daysCold,\n subject: draft.subject,\n body: draft.body,\n receiptIds: send.receiptIds,\n sent: send.sent,\n flags,\n });\n } catch (err) {\n const stub = errorDraft((err as Error)?.message);\n drafted.push({\n prospectEmail: t.email,\n prospectName: t.name,\n daysCold: t.daysCold,\n subject: stub.subject,\n body: stub.body,\n receiptIds: stub.receiptIds,\n sent: stub.sent,\n flags: stub.flags,\n });\n }\n }\n\n return { drafted };\n}\n\nfunction ledgerScanTargets(opts: BreakupReviveOptions): BreakupReviveTarget[] {\n const ledger = getLedger();\n const cold = ledger.listColdProspects({\n minDaysSinceLastEvent: opts.minDays ?? 60,\n maxDaysSinceLastEvent: opts.maxDays ?? 90,\n ...(opts.limit ? { limit: opts.limit } : {}),\n });\n return cold\n .filter((p): p is typeof p & { email: string } => p.email != null)\n .map((p) => ({\n name: p.name,\n email: p.email,\n company: p.company,\n daysCold: p.last_event_at\n ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1000))\n : 0,\n lastEventAt: p.last_event_at,\n linkedinUrl: p.linkedin_url ?? null,\n phone: p.phone ?? null,\n }));\n}\n","import { browserTask } from \"@oneshot-gtm/core\";\nimport { emailDomain, safeEnrich } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"competitor-switch\";\n\nexport interface CompetitorSwitchTarget {\n name: string;\n email: string;\n company: string;\n competitor: string;\n /** Optional URL to scrape (G2 review page, BuiltWith page, public job post). */\n evidenceUrl?: string;\n /** Optional pre-supplied evidence string. */\n evidenceText?: string;\n /** Your product's specific advantage over this competitor (one fact). */\n yourEdge: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface CompetitorSwitchRunOptions {\n dryRun: boolean;\n targets: CompetitorSwitchTarget[];\n /** Skip the browser-scraping step even if evidenceUrl is set. */\n skipBrowserScrape?: boolean;\n}\n\nexport interface CompetitorSwitchDraft {\n target: CompetitorSwitchTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n scrapedEvidence?: string;\n}\n\ntype CompetitorSwitchExtra = { scrapedEvidence?: string };\n\nexport function runCompetitorSwitch(\n opts: CompetitorSwitchRunOptions,\n): Promise<{ drafted: CompetitorSwitchDraft[] }> {\n const def: EmailPlayDef<CompetitorSwitchTarget, CompetitorSwitchExtra> = {\n playName: PLAY_NAME,\n promptName: \"competitor-switch-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let scrapedEvidence: string | undefined;\n\n // Enrich on both preview and real send (cached by email).\n const enr = await safeEnrich(\n {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n { playName: PLAY_NAME },\n );\n if (enr.receiptId) receiptIds.push(enr.receiptId);\n const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n if (!dryRun) {\n // Skip the browserTask scrape when evidenceText was already supplied\n // (or when the founder explicitly opts out). Two reasons:\n // 1. The github-topics finder enqueues both — it builds evidenceText\n // from the manifest scan and sets evidenceUrl to the repo. Scraping\n // a code page for \"pain points\" returns nothing useful; the manifest-\n // derived stitch line IS the evidence.\n // 2. browserTask is the slowest call in the SDK (maxSteps:12, easily\n // 30s-3min on JS-heavy pages). Re-scraping when we already have\n // evidence wastes time + ~$0.30+ in browser-task spend.\n // The scrape still fires when the founder pasted only an evidenceUrl\n // (e.g. a G2 review page) — that's when extracting structured pain-\n // points actually pays off.\n const haveEvidenceText =\n typeof t.evidenceText === \"string\" && t.evidenceText.trim().length > 0;\n if (t.evidenceUrl && !opts.skipBrowserScrape && !haveEvidenceText) {\n const browse = await browserTask(\n {\n 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.`,\n startUrl: t.evidenceUrl,\n outputSchema: {\n type: \"object\",\n properties: {\n pain_points: { type: \"array\", items: { type: \"string\" } },\n wished_features: { type: \"array\", items: { type: \"string\" } },\n use_case_context: { type: \"string\" },\n },\n },\n maxSteps: 12,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(browse.receiptId);\n scrapedEvidence =\n typeof browse.result.output === \"string\"\n ? browse.result.output\n : JSON.stringify(browse.result.output ?? {});\n }\n }\n\n return {\n receiptIds,\n dossier,\n ...(scrapedEvidence ? { extra: { scrapedEvidence } } : {}),\n };\n },\n buildInputBlock: (t, prep, cfg) => {\n const evidence = prep.extra?.scrapedEvidence ?? t.evidenceText ?? \"(no evidence supplied)\";\n return [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `COMPETITOR: ${t.competitor}`,\n `EVIDENCE: ${evidence}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\");\n },\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"competitor-switch\",\n }),\n metadata: (t) => ({ competitor: t.competitor, evidenceUrl: t.evidenceUrl ?? null }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"competitor-switch-followup\",\n contextLines: [\n `PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`,\n ],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`],\n }),\n },\n ],\n});\n","import { webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"hiring-signal\";\n\nexport interface HiringSignalTarget {\n /** Hiring manager / function head receiving the email. */\n name: string;\n email: string;\n company: string;\n /** Job title to search for. */\n jobTitle: string;\n /** Optional direct URL to a known job post — skips the search. */\n jobPostUrl?: string;\n /** Your one-line claim about how your product compresses ramp time for this role. */\n yourClaim: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface HiringSignalRunOptions {\n dryRun: boolean;\n targets: HiringSignalTarget[];\n /** Skip the web-search/read steps. */\n skipScrape?: boolean;\n}\n\nexport interface HiringSignalDraft {\n target: HiringSignalTarget;\n subject: string;\n body: string;\n jobPostHook: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\ntype HiringSignalExtra = { jobPostHook: string };\n\nconst NO_HOOK = \"(no specific job post phrase scraped)\";\n\nexport function runHiringSignal(\n opts: HiringSignalRunOptions,\n): Promise<{ drafted: HiringSignalDraft[] }> {\n const def: EmailPlayDef<HiringSignalTarget, HiringSignalExtra> = {\n playName: PLAY_NAME,\n promptName: \"hiring-signal-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n errorExtra: { jobPostHook: \"(error)\" },\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let jobPostHook = NO_HOOK;\n\n if (!dryRun) {\n let jobUrl: string | undefined = t.jobPostUrl;\n if (!jobUrl && !opts.skipScrape) {\n const search = await webSearch(\n {\n query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,\n maxResults: 5,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(search.receiptId);\n jobUrl = search.result.results[0]?.url;\n }\n\n if (jobUrl) {\n const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME });\n receiptIds.push(read.receiptId);\n const md = read.result.markdown ?? \"\";\n // Find a load-bearing phrase: first non-trivial sentence after 'About the role' or 'Responsibilities' if present.\n const hookMatch = md.match(\n /(?:About the role|Responsibilities|Requirements|What you[' ]?ll do)[^\\n]*\\n+([\\s\\S]{40,300})/i,\n );\n jobPostHook = (hookMatch?.[1] ?? md.slice(0, 400)).replace(/\\s+/g, \" \").trim();\n }\n }\n\n return { receiptIds, dossier: \"\", extra: { jobPostHook } };\n },\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `JOB TITLE: ${t.jobTitle}`,\n `JOB POST HOOK (real phrase from the post): ${prep.extra?.jobPostHook ?? NO_HOOK}`,\n `YOUR CLAIM: ${t.yourClaim}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"hiring-signal\",\n }),\n metadata: (t) => ({ jobTitle: t.jobTitle, jobPostUrl: t.jobPostUrl ?? null }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"hiring-signal-followup\",\n contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: hiring-signal. Final breakup.`],\n }),\n },\n ],\n});\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport interface JobChangeTarget {\n name: string;\n email: string;\n newRole: string;\n newCompany: string;\n previousRole?: string;\n previousCompany?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface JobChangeRunOptions {\n dryRun: boolean;\n targets: JobChangeTarget[];\n}\n\nexport interface JobChangeDraft {\n target: JobChangeTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"job-change\";\n\nconst jobChangeDef: EmailPlayDef<JobChangeTarget> = {\n playName: PLAY_NAME,\n promptName: \"job-change-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 4000,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `Public posts, talks, and recent decisions by ${t.name} (joined ${t.newCompany} as ${t.newRole}, formerly ${t.previousRole ?? \"?\"} at ${t.previousCompany ?? \"?\"})`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name}`,\n `NEW ROLE: ${t.newRole} at ${t.newCompany}`,\n `PREVIOUS: ${t.previousRole ?? \"unknown\"} at ${t.previousCompany ?? \"unknown\"}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the trigger only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.newCompany,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"job-change\",\n }),\n metadata: (t) => ({ newRole: t.newRole, newCompany: t.newCompany }),\n};\n\nexport function runJobChange(opts: JobChangeRunOptions): Promise<{ drafted: JobChangeDraft[] }> {\n return runEmailPlay(jobChangeDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 5,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"job-change-followup\",\n contextLines: [\n `CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`,\n ],\n }),\n },\n {\n dayOffset: 9, // ~14 days from enrollment\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: job-change. Sender is closing the file.`],\n }),\n },\n ],\n});\n","import { webSearch } from \"@oneshot-gtm/core\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"podcast-guest\";\n\nexport interface PodcastGuestTarget {\n name: string;\n email: string;\n company: string;\n /** Podcast name (e.g. \"Latent Space\", \"Lenny's Podcast\"). */\n podcast: string;\n /** Episode title or descriptor. */\n episodeTitle: string;\n /** A specific quote or timestamped moment that you'll reference. Required. */\n hookQuote: string;\n /** ONE-sentence reason the moment matters to your work. */\n bridge?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface PodcastGuestRunOptions {\n dryRun: boolean;\n targets: PodcastGuestTarget[];\n /** Skip the optional web-search dossier enrichment. */\n skipSearch?: boolean;\n}\n\nexport interface PodcastGuestDraft {\n target: PodcastGuestTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nexport function runPodcastGuest(\n opts: PodcastGuestRunOptions,\n): Promise<{ drafted: PodcastGuestDraft[] }> {\n const def: EmailPlayDef<PodcastGuestTarget> = {\n playName: PLAY_NAME,\n promptName: \"podcast-guest-email\",\n maxBodyWords: 90,\n enrollCadence: true,\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!dryRun && !opts.skipSearch) {\n const s = await webSearch(\n {\n query: `${t.name} ${t.podcast} \"${t.episodeTitle}\" notes OR transcript`,\n maxResults: 3,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(s.receiptId);\n dossier = s.result.results\n .slice(0, 2)\n .map((r) => `- ${r.title}: ${r.description}`)\n .join(\"\\n\");\n }\n\n return { receiptIds, dossier };\n },\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `PODCAST: ${t.podcast}`,\n `EPISODE: ${t.episodeTitle}`,\n `HOOK QUOTE: ${t.hookQuote}`,\n `BRIDGE TO YOUR WORK: ${t.bridge ?? \"(none — keep the email purely about their point)\"}`,\n `EXTRA CONTEXT FROM SEARCH:\\n${prep.dossier || \"(none)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"podcast-guest\",\n }),\n metadata: (t) => ({ podcast: t.podcast, episodeTitle: t.episodeTitle }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [], // Intentionally empty — podcast-guest is one-touch only.\n});\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport interface PostFundingTarget {\n name: string;\n email: string;\n company: string;\n round: string;\n amountUsd: number;\n leadInvestor?: string;\n sourceUrl: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface PostFundingRunOptions {\n dryRun: boolean;\n targets: PostFundingTarget[];\n}\n\nexport interface PostFundingDraft {\n target: PostFundingTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"post-funding\";\n\nconst postFundingDef: EmailPlayDef<PostFundingTarget> = {\n playName: PLAY_NAME,\n promptName: \"post-funding-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 3500,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `${t.company} ${t.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${t.sourceUrl}`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `ROUND: ${t.round} ($${t.amountUsd.toLocaleString()})`,\n `LEAD INVESTOR: ${t.leadInvestor ?? \"(unspecified)\"}`,\n `SOURCE: ${t.sourceUrl}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the round details only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"post-funding\",\n }),\n metadata: (t) => ({\n round: t.round,\n amountUsd: t.amountUsd,\n leadInvestor: t.leadInvestor,\n }),\n};\n\nexport function runPostFunding(\n opts: PostFundingRunOptions,\n): Promise<{ drafted: PostFundingDraft[] }> {\n return runEmailPlay(postFundingDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 9,\n channel: \"email\",\n breakOnReply: true,\n label: \"case-study follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"post-funding-followup\",\n contextLines: [\n `CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`,\n ],\n }),\n },\n {\n dayOffset: 9, // ~21 days from enrollment\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: post-funding.`],\n }),\n },\n ],\n});\n","import { emailDomain } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\n\nconst PLAY_NAME = \"repo-interest\";\n\nexport interface RepoInterestTarget {\n name: string;\n email: string;\n company: string;\n /** \"owner/name\" of the repo they starred (an adjacent/category tool, not a competitor). */\n repo: string;\n /** Display name for the repo (e.g. \"MCP servers\"); falls back to `repo`. */\n repoLabel?: string;\n /** One fact about how your product helps someone working in this space. */\n yourEdge: string;\n /** The repo URL — founder reference only. */\n evidenceUrl?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface RepoInterestRunOptions {\n dryRun: boolean;\n targets: RepoInterestTarget[];\n}\n\nexport interface RepoInterestDraft {\n target: RepoInterestTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst repoInterestDef: EmailPlayDef<RepoInterestTarget> = {\n playName: PLAY_NAME,\n promptName: \"repo-interest-email\",\n maxBodyWords: 90,\n // One-touch: a cold interest signal doesn't earn a multi-touch chase, so no\n // cadence enroll (mirrors show-hn / podcast-guest).\n toEmail: (t) => t.email,\n // Enrich on preview + send (cached by email). No deepResearch — the starred\n // repo is the load-bearing signal, like stack-consolidation's vendor stack.\n prepare: (t) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n enrichSlice: 3500,\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `STARRED REPO: ${t.repoLabel ?? t.repo}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"repo-interest\",\n }),\n metadata: (t) => ({ repo: t.repo }),\n};\n\nexport function runRepoInterest(\n opts: RepoInterestRunOptions,\n): Promise<{ drafted: RepoInterestDraft[] }> {\n return runEmailPlay(repoInterestDef, opts);\n}\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nexport { receiptUrls } from \"./_lib.ts\";\n\nexport interface ShowHnTarget {\n postTitle: string;\n postUrl: string;\n founderName: string;\n founderEmail: string;\n hookSummary: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface ShowHnRunOptions {\n dryRun: boolean;\n targets: ShowHnTarget[];\n}\n\nexport interface ShowHnRunResult {\n drafted: Array<{\n target: ShowHnTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n }>;\n}\n\nconst PLAY_NAME = \"show-hn\";\n\nconst showHnDef: EmailPlayDef<ShowHnTarget> = {\n playName: PLAY_NAME,\n promptName: \"show-hn-email\",\n maxBodyWords: 90,\n toEmail: (t) => t.founderEmail,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: { email: t.founderEmail, name: t.founderName },\n enrichSlice: 3500,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `Recent public work and engineering decisions by ${t.founderName} on ${t.postTitle}`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SHOW HN: ${t.postTitle}`,\n `URL: ${t.postUrl}`,\n `HOOK: ${t.hookSummary}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the hook only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.founderName,\n email: t.founderEmail,\n company: extractCompany(t.postTitle),\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"show-hn\",\n }),\n metadata: (t) => ({ postUrl: t.postUrl, postTitle: t.postTitle }),\n};\n\nexport function runShowHn(opts: ShowHnRunOptions): Promise<ShowHnRunResult> {\n return runEmailPlay(showHnDef, opts);\n}\n\nfunction extractCompany(title: string): string | null {\n const m = title.match(/Show HN:\\s*([^\\s—–:|-]+)/i);\n return m ? (m[1] ?? null) : null;\n}\n","import { emailDomain } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"stack-consolidation\";\n\nexport interface StackConsolidationTarget {\n name: string;\n email: string;\n company: string;\n /** Comma-separated list of API vendors detected in the repo. */\n vendorStack: string;\n /** How your product collapses the vendor sprawl (one fact). */\n yourEdge: string;\n /** Optional source URL (the repo) for the founder's reference. */\n evidenceUrl?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface StackConsolidationRunOptions {\n dryRun: boolean;\n targets: StackConsolidationTarget[];\n}\n\nexport interface StackConsolidationDraft {\n target: StackConsolidationTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst stackConsolidationDef: EmailPlayDef<StackConsolidationTarget> = {\n playName: PLAY_NAME,\n promptName: \"stack-consolidation-email\",\n maxBodyWords: 100,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email). No deepResearch —\n // the manifest-derived vendor stack is the load-bearing signal here.\n prepare: (t) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n enrichSlice: 3500,\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `STACK: ${t.vendorStack}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"stack-consolidation\",\n }),\n metadata: (t) => ({ vendorStack: t.vendorStack, evidenceUrl: t.evidenceUrl ?? null }),\n};\n\nexport function runStackConsolidation(\n opts: StackConsolidationRunOptions,\n): Promise<{ drafted: StackConsolidationDraft[] }> {\n return runEmailPlay(stackConsolidationDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"stack-consolidation-followup\",\n contextLines: [\n `PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`,\n ],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [\n `PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`,\n ],\n }),\n },\n ],\n});\n","import { type AcceleratorBatchTarget, runAcceleratorBatch } from \"./accelerator-batch.ts\";\nimport { type BreakupReviveTarget, runBreakupRevive } from \"./breakup-revive.ts\";\nimport { type CompetitorSwitchTarget, runCompetitorSwitch } from \"./competitor-switch.ts\";\nimport { type HiringSignalTarget, runHiringSignal } from \"./hiring-signal.ts\";\nimport { type JobChangeTarget, runJobChange } from \"./job-change.ts\";\nimport { type PodcastGuestTarget, runPodcastGuest } from \"./podcast-guest.ts\";\nimport { type PostFundingTarget, runPostFunding } from \"./post-funding.ts\";\nimport { type RepoInterestTarget, runRepoInterest } from \"./repo-interest.ts\";\nimport { type ShowHnTarget, runShowHn } from \"./show-hn.ts\";\nimport { type StackConsolidationTarget, runStackConsolidation } from \"./stack-consolidation.ts\";\n\n/**\n * The fields every play runner's drafted row exposes. Callers (the SSE /run\n * endpoint and the queue drainer) read only these — `target`/`scrapedEvidence`/\n * `jobPostHook`/etc. are extra and ignored here.\n */\nexport interface DraftedRow {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n}\n\n/** Run-level options a play may consume. `targets` is play-specific JSON. */\nexport interface PlayRunInput {\n dryRun: boolean;\n targets: unknown[];\n /** Required by accelerator-batch. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\nexport interface PlayDispatch {\n run: (o: PlayRunInput) => Promise<{ drafted: DraftedRow[] }>;\n}\n\n/**\n * Single source of truth mapping a play name → its runner. Both the server's\n * `/api/run` dispatch and the queue drainer look plays up here, so adding a\n * play means registering it once (its file + this table) instead of editing\n * two parallel switch statements that silently drifted apart.\n */\nexport const PLAYS: Record<string, PlayDispatch> = {\n \"show-hn\": {\n run: (o) => runShowHn({ dryRun: o.dryRun, targets: o.targets as ShowHnTarget[] }),\n },\n \"job-change\": {\n run: (o) => runJobChange({ dryRun: o.dryRun, targets: o.targets as JobChangeTarget[] }),\n },\n \"post-funding\": {\n run: (o) => runPostFunding({ dryRun: o.dryRun, targets: o.targets as PostFundingTarget[] }),\n },\n \"accelerator-batch\": {\n run: (o) =>\n runAcceleratorBatch({\n dryRun: o.dryRun,\n targets: o.targets as AcceleratorBatchTarget[],\n // Run-level fallback for manual /run targets; finder rows carry their own.\n ...(o.senderCohort ? { senderCohort: o.senderCohort } : {}),\n ...(o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {}),\n }),\n },\n \"hiring-signal\": {\n run: (o) => runHiringSignal({ dryRun: o.dryRun, targets: o.targets as HiringSignalTarget[] }),\n },\n \"podcast-guest\": {\n run: (o) => runPodcastGuest({ dryRun: o.dryRun, targets: o.targets as PodcastGuestTarget[] }),\n },\n \"competitor-switch\": {\n run: (o) =>\n runCompetitorSwitch({ dryRun: o.dryRun, targets: o.targets as CompetitorSwitchTarget[] }),\n },\n \"stack-consolidation\": {\n run: (o) =>\n runStackConsolidation({ dryRun: o.dryRun, targets: o.targets as StackConsolidationTarget[] }),\n },\n \"repo-interest\": {\n run: (o) => runRepoInterest({ dryRun: o.dryRun, targets: o.targets as RepoInterestTarget[] }),\n },\n \"breakup-revive\": {\n run: (o) => runBreakupRevive({ dryRun: o.dryRun, targets: o.targets as BreakupReviveTarget[] }),\n },\n};\n\nexport function isSupportedPlay(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(PLAYS, name);\n}\n","import { getLedger, loadConfig, sendSms } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { draftEmailFromPrompt, errorDraft, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"demo-no-show\";\n\nexport interface DemoNoShowTarget {\n name: string;\n email: string;\n phone?: string;\n company: string;\n missedAt: string;\n rescheduleLink: string;\n whatTheyWanted?: string;\n linkedinUrl?: string;\n}\n\nexport interface DemoNoShowRunOptions {\n dryRun: boolean;\n targets: DemoNoShowTarget[];\n /** Skip the SMS step (default: send if phone is present). */\n skipSms?: boolean;\n}\n\nexport interface DemoNoShowResult {\n outcomes: Array<{\n target: DemoNoShowTarget;\n sms: { message: string; sent: boolean } | null;\n email: { subject: string; body: string; sent: boolean; flags: string[] };\n receiptIds: number[];\n }>;\n}\n\nexport async function runDemoNoShow(opts: DemoNoShowRunOptions): Promise<DemoNoShowResult> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n const outcomes: DemoNoShowResult[\"outcomes\"] = [];\n\n for (const t of opts.targets) {\n try {\n const receiptIds: number[] = [];\n\n // SMS first (same-day)\n let smsResult: DemoNoShowResult[\"outcomes\"][number][\"sms\"] = null;\n if (!opts.skipSms && t.phone) {\n const sms = await draftSmsBody(cfg.founderName, cfg.productOneLiner, t);\n let sent = false;\n if (!opts.dryRun && sms.length > 0 && sms.length <= 320) {\n const r = await sendSms({ to: t.phone, message: sms }, { playName: PLAY_NAME });\n receiptIds.push(r.receiptId);\n sent = true;\n }\n smsResult = { message: sms, sent };\n }\n\n // Same-day email\n const draft = await draftEmailFromPrompt({\n promptName: \"demo-no-show-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `MISSED AT: ${t.missedAt}`,\n `RESCHEDULE LINK: ${t.rescheduleLink}`,\n `WHAT THEY WANTED: ${t.whatTheyWanted ?? \"(not captured at booking)\"}`,\n ].join(\"\\n\"),\n });\n const flags = lintEmail(draft.subject, draft.body, 100);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: t.email,\n draft,\n flags,\n prospectMeta: {\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"demo-no-show\",\n },\n metadata: { missedAt: t.missedAt, rescheduleLink: t.rescheduleLink },\n dryRun: opts.dryRun,\n });\n receiptIds.push(...send.receiptIds);\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(t.email);\n if (prospect) {\n enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n }\n\n outcomes.push({\n target: t,\n sms: smsResult,\n email: {\n subject: draft.subject,\n body: draft.body,\n sent: send.sent,\n flags,\n },\n receiptIds,\n });\n } catch (err) {\n const stub = errorDraft((err as Error)?.message);\n outcomes.push({\n target: t,\n sms: null,\n email: { subject: stub.subject, body: stub.body, sent: stub.sent, flags: stub.flags },\n receiptIds: stub.receiptIds,\n });\n }\n }\n\n return { outcomes };\n}\n\nasync function draftSmsBody(\n founderName: string,\n productOneLiner: string,\n target: DemoNoShowTarget,\n): Promise<string> {\n const system = loadPrompt(\"demo-no-show-sms\");\n const user = [\n `FOUNDER: ${founderName.split(/\\s+/)[0]}`,\n `PRODUCT: ${productOneLiner}`,\n `PROSPECT: ${target.name.split(/\\s+/)[0]}`,\n `MISSED AT: ${target.missedAt}`,\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.5,\n maxTokens: 200,\n });\n const parsed = tryParseJsonObject<{ message?: string }>(res.content, {});\n return (parsed.message ?? \"\").trim();\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"day-3 follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"demo-no-show-followup\",\n contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`],\n }),\n },\n ],\n});\n","import { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport {\n getPriorStepsBulk,\n nextStepInfo,\n playFollowupCount,\n previewCadenceStep,\n previewCadenceStepBatch,\n sendCadenceStep,\n sendCadenceStepBatch,\n type BatchItem,\n type PriorStepRow,\n} from \"@oneshot-gtm/plays\";\nimport type { CadenceNextStepDraft, CadenceStatus, CadenceView } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * In-process tracker of cadence steps that have a fire-and-forget send in\n * flight. Populated by sendCadenceStepRoute + sendCadenceBatchRoute when\n * they kick off the background SDK send (~2 min per row), cleared per-row\n * as each send settles. Used by `toView` to surface `isSending: true` so\n * /cadences can visually mark in-flight rows AND gate them out of the\n * sendable-rows count. Lost on server restart (acceptable — in-flight SDK\n * calls die with the process anyway).\n */\nconst inFlightSends = new Set<string>();\nconst inFlightKey = (prospectId: number, playName: string): string => `${prospectId}|${playName}`;\n\n/**\n * Per-play info that doesn't change between rows of the same play. Computed\n * once per unique play_name and reused for every row to avoid re-walking the\n * sequence registry + re-reading config from disk per row.\n */\ninterface PlayInfo {\n nextLabelByStep: Map<number, { label: string | null; isBreakup: boolean }>;\n followupCount: number;\n}\n\nfunction buildPlayInfoMap(\n rows: ReadonlyArray<{ play_name: string; current_step: number }>,\n): Map<string, PlayInfo> {\n const map = new Map<string, PlayInfo>();\n for (const row of rows) {\n let info = map.get(row.play_name);\n if (!info) {\n info = {\n nextLabelByStep: new Map(),\n followupCount: playFollowupCount(row.play_name),\n };\n map.set(row.play_name, info);\n }\n if (!info.nextLabelByStep.has(row.current_step)) {\n const next = nextStepInfo(row.play_name, row.current_step);\n info.nextLabelByStep.set(row.current_step, {\n label: next?.label ?? null,\n isBreakup: next?.isBreakup ?? false,\n });\n }\n }\n return map;\n}\n\nfunction toView(\n row: ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number],\n priorByKey: Map<string, PriorStepRow[]>,\n playInfo: Map<string, PlayInfo>,\n): CadenceView {\n let nextStepDraft: CadenceNextStepDraft | null = null;\n if (row.next_step_draft_json) {\n try {\n const parsed = JSON.parse(row.next_step_draft_json) as CadenceNextStepDraft & {\n payload?: unknown;\n };\n // Strip `payload` from the wire view — internal envelope only the\n // send route reads. UI only needs subject/body/flags/draftedAt.\n nextStepDraft = {\n subject: parsed.subject,\n body: parsed.body,\n flags: parsed.flags ?? [],\n draftedAt: parsed.draftedAt,\n };\n } catch {\n nextStepDraft = null;\n }\n }\n const info = playInfo.get(row.play_name);\n const next = info?.nextLabelByStep.get(row.current_step) ?? null;\n const followupCount = info?.followupCount ?? 0;\n const priorSteps = (priorByKey.get(`${row.prospect_id}|${row.play_name}`) ?? []).map((s) => ({\n stepIndex: s.stepIndex,\n label: s.label,\n subject: s.subject,\n body: s.body,\n sentAt: s.sentAt,\n }));\n return {\n prospectId: row.prospect_id,\n prospectEmail: row.prospect_email,\n prospectName: row.prospect_name,\n prospectCompany: row.prospect_company,\n playName: row.play_name,\n status: row.status as CadenceStatus,\n currentStep: row.current_step,\n enrolledAt: row.enrolled_at,\n nextDueAt: row.next_due_at,\n lastPolledAt: row.last_polled_at,\n nextStepDraft,\n nextStepLabel: next?.label ?? null,\n nextStepIsBreakup: next?.isBreakup ?? false,\n followupCount,\n priorSteps,\n isSending: inFlightSends.has(inFlightKey(row.prospect_id, row.play_name)),\n };\n}\n\nfunction viewsForRows(\n rows: ReadonlyArray<ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number]>,\n): CadenceView[] {\n // Single SQL fetch for ALL (prospect_id, play_name) pairs — replaces the\n // N+1 of one listSequenceEventsForProspectPlay per row.\n const pairs = rows.map((r) => ({ prospectId: r.prospect_id, playName: r.play_name }));\n const priorByKey = getPriorStepsBulk(pairs);\n // Compute play-level info (nextStepInfo + playFollowupCount) once per\n // unique play_name — each calls effectiveSequence → loadConfig (readFileSync).\n const playInfo = buildPlayInfoMap(rows);\n return rows.map((r) => toView(r, priorByKey, playInfo));\n}\n\nexport function listCadences(req: Request): Response {\n const url = new URL(req.url);\n const all = url.searchParams.get(\"all\") === \"1\";\n const ledger = getLedger();\n const rows = all ? ledger.listAllCadences() : ledger.listActiveCadences();\n return jsonResponse({ cadences: viewsForRows(rows) }, 200, req);\n}\n\nexport function getCadence(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const all = ledger.listCadencesForProspect(id);\n if (all.length === 0) return jsonResponse({ error: \"no cadences for prospect\" }, 404, req);\n return jsonResponse({ cadences: viewsForRows(all) }, 200, req);\n}\n\nexport function stopCadence(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\");\n const ledger = getLedger();\n const cadences = ledger.listCadencesForProspect(id).filter((c) => {\n if (playName && c.play_name !== playName) return false;\n return c.status === \"active\";\n });\n for (const cad of cadences) {\n ledger.setCadenceStatus({\n prospectId: id,\n playName: cad.play_name,\n status: \"completed\",\n });\n }\n return jsonResponse({ stopped: cadences.length }, 200, req);\n}\n\nfunction parseProspectAndPlay(\n req: Request,\n params: Record<string, string>,\n): { prospectId: number; playName: string } | Response {\n const prospectId = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(prospectId)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? \"\";\n if (!playName) return jsonResponse({ error: \"play query param required\" }, 400, req);\n return { prospectId, playName };\n}\n\nexport async function previewCadenceStepRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const parsed = parseProspectAndPlay(req, params);\n if (parsed instanceof Response) return parsed;\n try {\n const preview = await previewCadenceStep(parsed);\n return jsonResponse(\n {\n subject: preview.subject,\n body: preview.body,\n flags: preview.flags,\n draftedAt: preview.draftedAt,\n stepLabel: preview.stepLabel,\n isBreakup: preview.isBreakup,\n },\n 200,\n req,\n );\n } catch (err) {\n const msg = (err as Error).message ?? \"preview failed\";\n const status = msg.startsWith(\"no cadence\") || msg.startsWith(\"cadence is\") ? 409 : 500;\n return jsonResponse({ error: msg }, status, req);\n }\n}\n\nexport async function sendCadenceStepRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const parsed = parseProspectAndPlay(req, params);\n if (parsed instanceof Response) return parsed;\n // Verify the preview exists synchronously so we can 409 the founder\n // immediately if they clicked Send without a persisted draft — but the\n // actual send is fire-and-forget. SDK email send takes ~2 min; blocking\n // the modal that long is bad UX, especially since the founder already\n // approved by confirming. Mirrors POST /api/cadences/send-batch.\n try {\n const draft = getLedger().getCadenceDraft(parsed);\n if (!draft) {\n return jsonResponse({ error: \"no persisted preview — click Preview first\" }, 409, req);\n }\n } catch (err) {\n return jsonResponse({ error: (err as Error).message ?? \"send failed\" }, 500, req);\n }\n const key = inFlightKey(parsed.prospectId, parsed.playName);\n inFlightSends.add(key);\n void (async () => {\n try {\n await sendCadenceStep(parsed);\n } catch (err) {\n logEvent(\n \"cadence.send.failed\",\n {\n prospect_id: parsed.prospectId,\n play_name: parsed.playName,\n message_120: ((err as Error)?.message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n } finally {\n inFlightSends.delete(key);\n }\n })();\n return jsonResponse({ accepted: true }, 202, req);\n}\n\nasync function parseBatchItems(req: Request): Promise<BatchItem[] | Response> {\n let body: { items?: unknown };\n try {\n body = (await req.json()) as { items?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!Array.isArray(body.items)) {\n return jsonResponse({ error: \"items: array required\" }, 400, req);\n }\n const items: BatchItem[] = [];\n for (const raw of body.items) {\n if (raw && typeof raw === \"object\" && \"prospectId\" in raw && \"playName\" in raw) {\n const it = raw as { prospectId: unknown; playName: unknown };\n if (typeof it.prospectId === \"number\" && typeof it.playName === \"string\") {\n items.push({ prospectId: it.prospectId, playName: it.playName });\n }\n }\n }\n if (items.length === 0) {\n return jsonResponse({ error: \"no valid items in body\" }, 400, req);\n }\n return items;\n}\n\nexport async function previewCadenceBatchRoute(req: Request): Promise<Response> {\n const itemsOrErr = await parseBatchItems(req);\n if (itemsOrErr instanceof Response) return itemsOrErr;\n const results = await previewCadenceStepBatch(itemsOrErr);\n return jsonResponse({ results }, 200, req);\n}\n\nexport async function sendCadenceBatchRoute(req: Request): Promise<Response> {\n const itemsOrErr = await parseBatchItems(req);\n if (itemsOrErr instanceof Response) return itemsOrErr;\n const items = itemsOrErr;\n // Add all selected rows to the in-flight set up front. Per-item callback\n // clears each as the batch wrapper finishes that row, so the UI marks\n // them as \"sending\" only for the actual SDK-call window — not the entire\n // batch duration.\n for (const item of items) inFlightSends.add(inFlightKey(item.prospectId, item.playName));\n void (async () => {\n try {\n await sendCadenceStepBatch(items, (item) => {\n inFlightSends.delete(inFlightKey(item.prospectId, item.playName));\n });\n } catch (err) {\n // Belt-and-suspenders: the wrapper catches per-item; this catch only\n // fires if the wrapper itself throws (shouldn't, but defense in depth).\n for (const item of items) inFlightSends.delete(inFlightKey(item.prospectId, item.playName));\n logEvent(\n \"cadence.batch.failed\",\n { message_120: ((err as Error)?.message ?? \"\").slice(0, 120) },\n \"error\",\n );\n }\n })();\n return jsonResponse({ accepted: items.length }, 202, req);\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { ReceiptDetail, ReceiptView } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nfunction toView(row: {\n id: number;\n play_name: string;\n call_type: string;\n cost_usd: number | null;\n oneshot_request_id: string | null;\n created_at: string;\n}): ReceiptView {\n return {\n id: row.id,\n playName: row.play_name,\n callType: row.call_type,\n costUsd: row.cost_usd,\n oneshotRequestId: row.oneshot_request_id,\n createdAt: row.created_at,\n };\n}\n\nexport function listReceipts(req: Request): Response {\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? undefined;\n const sinceDays = Number.parseInt(url.searchParams.get(\"sinceDays\") ?? \"\", 10);\n const limit = Math.min(500, Number.parseInt(url.searchParams.get(\"limit\") ?? \"200\", 10) || 200);\n const sinceIso = Number.isFinite(sinceDays)\n ? new Date(Date.now() - sinceDays * 24 * 3600 * 1000).toISOString()\n : undefined;\n\n const ledger = getLedger();\n const rows = ledger.listReceipts({\n ...(playName ? { playName } : {}),\n ...(sinceIso ? { sinceIso } : {}),\n limit,\n });\n return jsonResponse({ receipts: rows.map(toView) }, 200, req);\n}\n\nexport function getReceipt(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const r = getLedger().getReceipt(id);\n if (!r) return jsonResponse({ error: \"not found\" }, 404, req);\n let parsed: unknown = null;\n if (r.signed_receipt) {\n try {\n parsed = JSON.parse(r.signed_receipt);\n } catch {\n parsed = r.signed_receipt;\n }\n }\n const detail: ReceiptDetail = {\n id: r.id,\n playName: r.play_name,\n callType: r.call_type,\n costUsd: r.cost_usd,\n oneshotRequestId: r.oneshot_request_id,\n createdAt: r.created_at,\n signedReceipt: parsed,\n };\n return jsonResponse({ receipt: detail }, 200, req);\n}\n","import { getLedger, listInbox, loadConfig, logEvent } from \"@oneshot-gtm/core\";\nimport type { InboxReplyView, InboxResult } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/** \"Jane Doe <jane@x.com>\" → \"jane@x.com\"; bare addresses pass through. */\nfunction normalizeFrom(raw: string): string {\n const m = raw.match(/<([^>]+)>/);\n return (m ? (m[1] ?? raw) : raw).trim().toLowerCase();\n}\n\n/**\n * Read-only view of the OneShot inbox (replies to outreach). Each email is\n * matched to a known prospect by sender address, annotated with the play +\n * cadence status when available. Live fetch — no storage. The SDK exposes only\n * inboxList (no reply/markRead), so this is read-only.\n */\nexport async function listInboxRoute(req: Request): Promise<Response> {\n const ledger = getLedger();\n\n let emails: Awaited<ReturnType<typeof listInbox>>[\"emails\"];\n try {\n const result = await listInbox({ limit: 50 });\n emails = result.emails;\n } catch (err) {\n logEvent(\n \"inbox.list_failed\",\n { message_120: ((err as Error)?.message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n const out: InboxResult = { replies: [], hasMore: false, error: \"couldn't reach the inbox\" };\n return jsonResponse(out, 200, req);\n }\n\n // Cadence-backed prospects (multi-touch plays) carry play + status + name/co\n // in one JOIN. Index by normalized email; prefer a `replied`/`active` cadence\n // when a prospect has several.\n const byEmail = new Map<\n string,\n { name: string | null; company: string | null; playName: string; status: string }\n >();\n for (const c of ledger.listAllCadences()) {\n if (!c.prospect_email) continue;\n const key = c.prospect_email.trim().toLowerCase();\n const existing = byEmail.get(key);\n const better =\n !existing ||\n c.status === \"replied\" ||\n (c.status === \"active\" && existing.status !== \"replied\");\n if (better) {\n byEmail.set(key, {\n name: c.prospect_name,\n company: c.prospect_company,\n playName: c.play_name,\n status: c.status,\n });\n }\n }\n\n const replies: InboxReplyView[] = emails.map((e) => {\n const fromEmail = normalizeFrom(e.from);\n let matched: InboxReplyView[\"matched\"] = null;\n const cadence = byEmail.get(fromEmail);\n if (cadence) {\n matched = {\n name: cadence.name,\n company: cadence.company,\n playName: cadence.playName,\n cadenceStatus: cadence.status,\n };\n } else {\n // One-touch plays leave no cadence row — fall back to the prospect record.\n const p = ledger.getProspectByEmail(fromEmail);\n if (p) {\n matched = { name: p.name, company: p.company, playName: p.source, cadenceStatus: null };\n }\n }\n return {\n id: e.id,\n fromEmail,\n fromRaw: e.from,\n subject: e.subject,\n receivedAt: e.received_at,\n body: e.body ?? \"\",\n matched,\n };\n });\n\n // Drop mail from the founder's own sending domain — the mailbox accumulates\n // the agent's own sends + platform/system test mail (agent@/info@<domain>),\n // which are never genuine prospect replies. Then newest-first.\n const selfDomain = (loadConfig().sendingDomain ?? \"\").trim().toLowerCase();\n const visible = replies\n .filter((r) => !selfDomain || !r.fromEmail.endsWith(`@${selfDomain}`))\n .toSorted((a, b) => (a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : 0));\n\n const out: InboxResult = { replies: visible, hasMore: false };\n return jsonResponse(out, 200, req);\n}\n","import { loadConfig, saveConfig } from \"@oneshot-gtm/core\";\nimport {\n defaultSequence,\n getSequence,\n isBreakupLabel,\n isBreakupStepAt,\n type Sequence,\n} from \"@oneshot-gtm/plays\";\nimport type { PlayDescriptor, StepChannel } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\ninterface PlayMeta {\n name: string;\n cli: string;\n}\n\nconst PLAY_CATALOG: PlayMeta[] = [\n {\n name: \"show-hn\",\n cli: \"oneshot-gtm motion show-hn --target ./examples/show-hn.json\",\n },\n {\n name: \"job-change\",\n cli: \"oneshot-gtm motion job-change --target ./examples/job-change.json\",\n },\n {\n name: \"post-funding\",\n cli: \"oneshot-gtm motion post-funding --target ./examples/post-funding.json\",\n },\n {\n name: \"accelerator-batch\",\n cli: \"oneshot-gtm motion accelerator-batch --target ./examples/accelerator-batch.json --sender-cohort yc-w26\",\n },\n {\n name: \"concierge\",\n cli: \"oneshot-gtm motion concierge --target ./examples/concierge.json\",\n },\n {\n name: \"demo-no-show\",\n cli: \"oneshot-gtm motion demo-no-show --target ./examples/demo-no-show.json\",\n },\n {\n name: \"competitor-switch\",\n cli: \"oneshot-gtm motion competitor-switch --target ./examples/competitor-switch.json\",\n },\n {\n name: \"stack-consolidation\",\n cli: \"oneshot-gtm find watch # fed by the github-topics finder, drained from /queue\",\n },\n {\n name: \"repo-interest\",\n cli: \"oneshot-gtm find watch # fed by the github-stars finder (adjacent repos), drained from /queue\",\n },\n {\n name: \"hiring-signal\",\n cli: \"oneshot-gtm motion hiring-signal --target ./examples/hiring-signal.json\",\n },\n {\n name: \"podcast-guest\",\n cli: \"oneshot-gtm motion podcast-guest --target ./examples/podcast-guest.json\",\n },\n {\n name: \"breakup-revive\",\n cli: \"oneshot-gtm motion breakup-revive --min-days 60 --max-days 90\",\n },\n];\n\n/** Relative per-step dayOffsets → cumulative days from the day-0 initial send. */\nfunction cumulativeDays(seq: Sequence | undefined): number[] {\n if (!seq) return [];\n let acc = 0;\n return seq.steps.map((s) => (acc += s.dayOffset));\n}\n\nexport function listPlays(req: Request): Response {\n const plays: PlayDescriptor[] = PLAY_CATALOG.map((p) => {\n const seq = getSequence(p.name);\n const channels: StepChannel[] = seq\n ? Array.from(new Set(seq.steps.map((s) => s.channel as StepChannel)))\n : [\"email\"];\n const followupCount = seq?.steps.length ?? 0;\n // hasBreakup uses the same step-position rule as the cadence runtime so\n // accelerator-batch (which uses the breakup PROMPT as its only follow-up\n // at index 0) doesn't get flagged as having a breakup step here.\n const hasBreakup = seq ? isBreakupStepAt(seq, seq.steps.length - 1) : false;\n const days = cumulativeDays(seq);\n const stepsArr = seq?.steps ?? [];\n const steps = stepsArr.map((s, i) => ({\n day: days[i] ?? 0,\n label: s.label ?? `step ${i + 1}`,\n channel: s.channel as StepChannel,\n // Per-step breakup flag using the SAME label rule the cadence engine\n // uses. Note: the /cadences progress UI only treats the FINAL such\n // step as the cadence-terminal breakup (see isBreakupStepAt). Here\n // we surface the label-level signal so /plays can hint a per-step\n // visual without re-deriving the substring.\n isBreakup: isBreakupLabel(s.label),\n }));\n return {\n name: p.name,\n channels,\n followupCount,\n hasBreakup,\n cliInvocation: p.cli,\n steps,\n defaultDays: cumulativeDays(defaultSequence(p.name)),\n };\n });\n return jsonResponse({ plays }, 200, req);\n}\n\n/**\n * Set (or clear) per-play cadence timing. Body: { days: number[] | null }.\n * `days` are CUMULATIVE days from the initial send (intuitive in the UI); we\n * convert to the engine-native relative offsets before persisting. `null`\n * clears the override (reset to code defaults). Timing only — step structure\n * is fixed in code.\n */\nexport async function setCadenceRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"] ?? \"\";\n const def = defaultSequence(name);\n if (!def || def.steps.length === 0) {\n return jsonResponse({ error: `play '${name}' has no editable cadence` }, 400, req);\n }\n\n let body: { days?: number[] | null };\n try {\n body = (await req.json()) as { days?: number[] | null };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n\n const cfg = loadConfig();\n const overrides = { ...cfg.cadenceOverrides };\n\n // Reset path: clear this play's override.\n if (body.days === null || body.days === undefined) {\n delete overrides[name];\n saveConfig({\n ...cfg,\n cadenceOverrides: Object.keys(overrides).length > 0 ? overrides : null,\n });\n return jsonResponse({ ok: true }, 200, req);\n }\n\n const days = body.days;\n const stepCount = def.steps.length;\n if (!Array.isArray(days) || days.length !== stepCount) {\n return jsonResponse(\n { error: `days must be an array of ${stepCount} cumulative day value(s)` },\n 400,\n req,\n );\n }\n if (!days.every((d) => Number.isInteger(d) && d >= 1 && d <= 120)) {\n return jsonResponse({ error: \"each day must be an integer between 1 and 120\" }, 400, req);\n }\n for (let i = 1; i < days.length; i++) {\n if ((days[i] as number) <= (days[i - 1] as number)) {\n return jsonResponse({ error: \"days must be strictly increasing\" }, 400, req);\n }\n }\n\n // Cumulative → relative offsets (each ≥ 1, guaranteed by the checks above).\n const relative = days.map((d, i) => (i === 0 ? d : d - (days[i - 1] as number)));\n overrides[name] = relative;\n saveConfig({ ...cfg, cadenceOverrides: overrides });\n return jsonResponse({ ok: true }, 200, req);\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type {\n EventsByPlay,\n OutcomeByPlay,\n OutcomeRequest,\n SpendByPlay,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nfunction readSinceDays(req: Request): string | undefined {\n const url = new URL(req.url);\n const n = Number.parseInt(url.searchParams.get(\"sinceDays\") ?? \"\", 10);\n if (!Number.isFinite(n)) return undefined;\n return new Date(Date.now() - n * 24 * 3600 * 1000).toISOString();\n}\n\nexport function measureCac(req: Request): Response {\n const sinceIso = readSinceDays(req);\n const ledger = getLedger();\n const spend: SpendByPlay[] = ledger.spendByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n calls: r.calls,\n totalUsd: r.total_usd,\n }));\n const events: EventsByPlay[] = ledger.eventsByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n sent: r.sent,\n delivered: r.delivered,\n replied: r.replied,\n bounced: r.bounced,\n }));\n return jsonResponse({ spend, events }, 200, req);\n}\n\nexport function measureRocs(req: Request): Response {\n const sinceIso = readSinceDays(req);\n const ledger = getLedger();\n const spend: SpendByPlay[] = ledger.spendByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n calls: r.calls,\n totalUsd: r.total_usd,\n }));\n const events: EventsByPlay[] = ledger.eventsByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n sent: r.sent,\n delivered: r.delivered,\n replied: r.replied,\n bounced: r.bounced,\n }));\n const outcomes: OutcomeByPlay[] = ledger\n .outcomesByPlay(sinceIso ? { sinceIso } : {})\n .map((r) => ({\n playName: r.play_name,\n meetings: r.meetings,\n sqls: r.sqls,\n won: r.won,\n lost: r.lost,\n ghosted: r.ghosted,\n }));\n return jsonResponse({ spend, events, outcomes }, 200, req);\n}\n\nexport async function recordOutcome(req: Request): Promise<Response> {\n const body = (await req.json()) as OutcomeRequest;\n const allowed = [\"meeting_booked\", \"sql_qualified\", \"deal_won\", \"deal_lost\", \"ghosted\"];\n if (!allowed.includes(body.outcome)) {\n return jsonResponse({ error: `outcome must be one of: ${allowed.join(\", \")}` }, 400, req);\n }\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(body.email);\n if (!prospect) return jsonResponse({ error: `prospect not found: ${body.email}` }, 404, req);\n const id = ledger.recordOutcome({\n prospectId: prospect.id,\n ...(body.playName ? { playName: body.playName } : {}),\n outcome: body.outcome,\n ...(body.amountUsd != null ? { amountUsd: body.amountUsd } : {}),\n ...(body.notes ? { notes: body.notes } : {}),\n });\n return jsonResponse({ id }, 200, req);\n}\n","import {\n loadConfig,\n saveConfig,\n saveSecrets,\n secretSource,\n secretsPath,\n type OneShotConfig,\n} from \"@oneshot-gtm/core\";\nimport type { LlmProvider, SetupRequest, WalletMode } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * The anonymous clientId is local-only — never exposed to the web layer.\n * Strip it before any HTTP response so the browser never sees it (and can't\n * accidentally clobber it on a subsequent POST).\n */\n/**\n * Strip the anonymous clientId before sending cfg to the web layer. Exported\n * so we can unit-test the privacy boundary directly.\n */\nexport function publicCfg(cfg: OneShotConfig): Omit<OneShotConfig, \"clientId\"> {\n const { clientId: _omit, ...rest } = cfg;\n void _omit;\n return rest;\n}\n\nexport function getSetupStatus(req: Request): Response {\n const cfg = loadConfig();\n return jsonResponse(\n {\n cfg: publicCfg(cfg),\n secretsPath: secretsPath(),\n sources: {\n OPENROUTER_API_KEY: secretSource(\"OPENROUTER_API_KEY\"),\n OPENAI_API_KEY: secretSource(\"OPENAI_API_KEY\"),\n ANTHROPIC_API_KEY: secretSource(\"ANTHROPIC_API_KEY\"),\n CDP_API_KEY_ID: secretSource(\"CDP_API_KEY_ID\"),\n CDP_API_KEY_SECRET: secretSource(\"CDP_API_KEY_SECRET\"),\n CDP_WALLET_SECRET: secretSource(\"CDP_WALLET_SECRET\"),\n AGENT_PRIVATE_KEY: secretSource(\"AGENT_PRIVATE_KEY\"),\n },\n },\n 200,\n req,\n );\n}\n\nexport async function setup(req: Request): Promise<Response> {\n const body = (await req.json()) as SetupRequest;\n const current = loadConfig();\n const llmProvider: LlmProvider = body.llmProvider ?? current.llmProvider;\n const walletMode: WalletMode = body.walletMode ?? current.walletMode;\n\n // clientId is preserved from current — body.clientId is intentionally\n // ignored so a malicious or accidental web POST can't rotate the anonymous\n // install id. saveConfig writes the entire cfg, so omitting clientId here\n // would silently drop it from disk.\n saveConfig({\n walletMode,\n llmProvider,\n llmModel: body.llmModel ?? current.llmModel,\n telemetryEnabled: body.telemetryEnabled ?? current.telemetryEnabled,\n founderName: mergeString(body.founderName, current.founderName),\n founderEmail: mergeString(body.founderEmail, current.founderEmail),\n productOneLiner: mergeString(body.productOneLiner, current.productOneLiner),\n productDomain: mergeString(body.productDomain, current.productDomain),\n sendingDomain: mergeString(body.sendingDomain, current.sendingDomain),\n icpOneLiner: mergeString(body.icpOneLiner, current.icpOneLiner),\n cadenceOverrides: current.cadenceOverrides,\n founderCredentials: mergeString(body.founderCredentials, current.founderCredentials),\n productPortfolio: mergeString(body.productPortfolio, current.productPortfolio),\n partners: mergeString(body.partners, current.partners),\n mobileSignature: body.mobileSignature ?? current.mobileSignature,\n clientId: current.clientId,\n });\n\n if (body.secrets && Object.keys(body.secrets).length > 0) {\n saveSecrets(body.secrets);\n }\n\n return jsonResponse({ ok: true }, 200, req);\n}\n\n/**\n * Merge a form-submitted string into the stored config:\n * undefined → keep existing (caller didn't touch the field)\n * \"\" → clear (caller deliberately emptied the field)\n * non-empty → trim + save\n */\nfunction mergeString(incoming: string | undefined, current: string | null): string | null {\n if (incoming === undefined) return current;\n const trimmed = incoming.trim();\n return trimmed.length === 0 ? null : trimmed;\n}\n","import { logEvent, startRun, webRead } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport type { DeriveIcpResult } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nconst PLAY_NAME = \"config:icp\";\n\nexport async function deriveIcpRoute(req: Request): Promise<Response> {\n startRun();\n let body: { domain?: unknown } = {};\n try {\n body = (await req.json()) as { domain?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (typeof body.domain !== \"string\" || body.domain.trim().length === 0) {\n return jsonResponse({ error: \"domain (string) required\" }, 400, req);\n }\n\n const url = normalizeToHttpsUrl(body.domain);\n if (!url) {\n return jsonResponse({ error: `not a valid domain or URL: ${body.domain}` }, 400, req);\n }\n // Hostname is the public domain the founder pasted — not user-typed PII.\n const host = new URL(url).hostname;\n logEvent(\"derive_icp.start\", { host });\n\n let costUsd = 0;\n let markdown = \"\";\n const readStartedAt = Date.now();\n logEvent(\"derive_icp.read.start\", { host });\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n markdown = (read.result.markdown ?? \"\").trim();\n const c = (read.result as unknown as { cost?: number }).cost;\n if (typeof c === \"number\") costUsd += c;\n logEvent(\"derive_icp.read.done\", {\n host,\n duration_ms: Date.now() - readStartedAt,\n markdown_chars: markdown.length,\n cost_usd: costUsd,\n });\n } catch (err) {\n logEvent(\n \"derive_icp.read.error\",\n {\n host,\n duration_ms: Date.now() - readStartedAt,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n return jsonResponse(\n { error: `webRead failed for ${url}: ${(err as Error).message}` },\n 502,\n req,\n );\n }\n\n if (markdown.length < 80) {\n logEvent(\"derive_icp.too_thin\", { host, markdown_chars: markdown.length }, \"warn\");\n return jsonResponse(\n {\n error: `not enough page content to derive an ICP from ${url} (got ${markdown.length} chars). Try a more specific page (pricing, customers, about).`,\n },\n 422,\n req,\n );\n }\n\n const system = loadPrompt(\"icp-derive-from-site\");\n let proposed = \"\";\n const llmStartedAt = Date.now();\n logEvent(\"derive_icp.llm.start\", { host });\n try {\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: markdown.slice(0, 12000) },\n ],\n temperature: 0.2,\n maxTokens: 200,\n });\n proposed = llm.content.trim().replace(/^[\"']|[\"']$/g, \"\");\n logEvent(\"derive_icp.llm.done\", {\n host,\n duration_ms: Date.now() - llmStartedAt,\n response_chars: proposed.length,\n });\n } catch (err) {\n logEvent(\n \"derive_icp.llm.error\",\n {\n host,\n duration_ms: Date.now() - llmStartedAt,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n return jsonResponse({ error: `LLM call failed: ${(err as Error).message}` }, 502, req);\n }\n\n if (proposed.toLowerCase().startsWith(\"unable to derive\")) {\n logEvent(\"derive_icp.unable_to_derive\", { host, markdown_chars: markdown.length }, \"warn\");\n return jsonResponse({ error: proposed, sourceUrl: url, costUsd }, 422, req);\n }\n\n logEvent(\"derive_icp.done\", { host, cost_usd: costUsd, response_chars: proposed.length });\n const view: DeriveIcpResult = {\n proposedIcp: proposed,\n sourceUrl: url,\n costUsd,\n };\n return jsonResponse(view, 200, req);\n}\n\n/**\n * Accepts a bare domain (\"acme.com\"), a host with subdomain (\"blog.acme.com\"),\n * or a full URL. Always returns an https:// URL. Rejects anything that doesn't\n * parse as a valid hostname.\n */\nfunction normalizeToHttpsUrl(raw: string): string | null {\n const trimmed = raw.trim().replace(/^https?:\\/\\//, \"\");\n // Strip trailing slashes for the bare-host case so URL doesn't choke.\n const candidate = `https://${trimmed.replace(/^\\/+/, \"\")}`;\n try {\n const u = new URL(candidate);\n // Defense: hostname must contain at least one dot and look like a real\n // public host. Reject localhost / IPs / single-label hosts.\n if (!u.hostname.includes(\".\")) return null;\n if (/^[0-9.]+$/.test(u.hostname)) return null;\n if (u.hostname === \"localhost\") return null;\n return u.toString();\n } catch {\n return null;\n }\n}\n","import { loadConfig, logEvent } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\n\nexport interface IcpFilterResult {\n match: boolean;\n reason: string;\n}\n\n/**\n * Resolve the ICP one-liner: explicit override beats config.\n * Returns null if neither is set — caller should fall back to \"match all\".\n */\nexport function resolveIcp(override?: string): string | null {\n if (override && override.trim().length > 0) return override.trim();\n const cfg = loadConfig();\n return cfg.icpOneLiner;\n}\n\n/**\n * Run the ICP classifier against a single candidate. If no ICP is set, every\n * candidate matches (founder hasn't filtered yet — they'll review in queue).\n */\nexport async function icpFilter(input: {\n icp: string | null;\n candidate: {\n title: string;\n url?: string | null;\n summary?: string | null;\n author?: string | null;\n };\n}): Promise<IcpFilterResult> {\n if (!input.icp) {\n return { match: true, reason: \"no ICP set; pass-through\" };\n }\n const system = loadPrompt(\"icp-filter\");\n const user = JSON.stringify({\n icp: input.icp,\n candidate: input.candidate,\n });\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.1,\n maxTokens: 200,\n });\n const decision = parseIcpJson(res.content);\n // Title is a category-ish label sourced from public listings (post titles,\n // job titles, episode titles); reason is the LLM's own classifier output.\n // Neither is user-typed prospect data — safe to log.\n logEvent(\"icp.decision\", {\n match: decision.match,\n reason_120: decision.reason.slice(0, 120),\n candidate_title: input.candidate.title.slice(0, 120),\n });\n return decision;\n}\n\nfunction parseIcpJson(raw: string): IcpFilterResult {\n const parsed = tryParseJsonObject<{ match?: unknown; reason?: unknown }>(raw, {});\n return {\n match: parsed.match === true,\n reason: typeof parsed.reason === \"string\" ? parsed.reason : \"no reason given\",\n };\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\n\n/**\n * True if this (play, dedupe-key) pair is already in the queue\n * OR a prospect with the same email is already known.\n */\nexport function isDuplicate(opts: {\n playName: string;\n dedupeKey: string;\n prospectEmail?: string | null;\n}): boolean {\n const ledger = getLedger();\n if (ledger.isQueueDuplicate(opts.playName, opts.dedupeKey)) return true;\n if (opts.prospectEmail) {\n const existing = ledger.findProspectByEmail(opts.prospectEmail);\n if (existing) return true;\n }\n return false;\n}\n\n/** Extract a domain from an email address. Returns null on garbage input. */\nexport function emailDomain(email: string | null | undefined): string | null {\n if (!email) return null;\n const at = email.indexOf(\"@\");\n if (at < 0) return null;\n return email.slice(at + 1).toLowerCase();\n}\n\n/** Extract a domain from a URL. Returns null on garbage input. */\nexport function urlDomain(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const u = new URL(url);\n return u.hostname.replace(/^www\\./, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n","/**\n * Pre-flight guard for `findEmail` SDK calls.\n *\n * The OneShot `findEmail` SDK receives only `company_domain` + `full_name` and\n * guesses email patterns from those. Two structural causes of dud lookups we\n * can catch BEFORE spending the ~$0.05 per call:\n *\n * 1. `company_domain` points at a host where no company hosts email —\n * free-tier app subdomains (vercel.app, github.io, …), social platforms,\n * personal email providers, code hosts, link aggregators.\n * 2. `full_name` is a single-token handle (`samaralihussain`) not a real\n * person name (`Sam Jones`). Pattern-based email guessing can't\n * disambiguate a username.\n *\n * Callers do `shouldSkipFindEmail(...)` ahead of the SDK call; when it\n * returns `{ok:false}`, increment `result.droppedEnrichment` and emit a\n * `finder.skipped_findemail` event for telemetry, then move to the next\n * candidate. No new wire-protocol surface.\n */\n\n/**\n * Hosts where `findEmail` virtually never finds a deliverable company\n * address. Match is exact on the bare host or any subdomain of one of\n * these entries — `foo.vercel.app` and `bar.foo.vercel.app` both qualify.\n *\n * Curated, static. Adaptive/learned variants are out of scope.\n */\nconst DUD_DOMAINS: ReadonlySet<string> = new Set([\n // Free-tier app / preview subdomains.\n \"vercel.app\",\n \"netlify.app\",\n \"github.io\",\n \"pages.dev\",\n \"fly.dev\",\n \"replit.co\",\n \"replit.app\",\n \"codesandbox.io\",\n \"stackblitz.com\",\n \"glitch.me\",\n \"deno.dev\",\n \"workers.dev\",\n \"herokuapp.com\",\n \"onrender.com\",\n \"railway.app\",\n \"modal.run\",\n \"supabase.co\",\n \"firebaseapp.com\",\n \"appspot.com\",\n \"azurewebsites.net\",\n \"webflow.io\",\n \"wixsite.com\",\n \"googleusercontent.com\",\n // Personal / free email providers — the founder isn't reachable via the\n // generic free-tier handle even if findEmail returns something.\n \"gmail.com\",\n \"yahoo.com\",\n \"outlook.com\",\n \"hotmail.com\",\n \"icloud.com\",\n \"proton.me\",\n \"protonmail.com\",\n \"fastmail.com\",\n // Social, community, content hosts.\n \"twitter.com\",\n \"x.com\",\n \"linkedin.com\",\n \"facebook.com\",\n \"instagram.com\",\n \"youtube.com\",\n \"youtu.be\",\n \"reddit.com\",\n \"medium.com\",\n \"dev.to\",\n \"substack.com\",\n \"hashnode.com\",\n \"hashnode.dev\",\n \"notion.site\",\n \"notion.so\",\n \"tiktok.com\",\n \"pinterest.com\",\n \"threads.net\",\n \"discord.com\",\n \"discord.gg\",\n \"slack.com\",\n \"news.ycombinator.com\",\n // Investor / startup-data aggregators — every result here is a profile\n // page about a company, not the company's own domain.\n \"crunchbase.com\",\n \"producthunt.com\",\n \"wellfound.com\",\n \"pitchbook.com\",\n \"cbinsights.com\",\n \"tracxn.com\",\n // Code hosts (when this is the ONLY domain signal — caller already\n // failed to find a company website).\n \"github.com\",\n \"gitlab.com\",\n \"bitbucket.org\",\n \"gist.github.com\",\n // Link aggregators.\n \"linktr.ee\",\n \"bio.link\",\n \"carrd.co\",\n]);\n\n/**\n * True when the given domain is in the dud blocklist, either as an exact\n * match or as a subdomain (so `foo.vercel.app` is dud). `null`/empty\n * counts as dud — caller has no usable signal.\n *\n * Defensive normalization before matching:\n * - lowercase + trim whitespace\n * - strip `http://` / `https://` scheme\n * - strip everything from the first `/` onward (paths/queries)\n * - strip leading `www.` and trailing `.`\n *\n * Callers should pass bare hostnames (via `urlDomain` from `_dedupe.ts`),\n * but the normalization keeps an accidental full URL or trailing-dot DNS\n * form from silently slipping past the suffix match.\n *\n * Does no DNS lookup — purely suffix-based.\n */\nexport function isDudDomain(domain: string | null | undefined): boolean {\n if (!domain) return true;\n const d = domain\n .trim()\n .toLowerCase()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/[/?#].*$/, \"\")\n .replace(/^www\\./, \"\")\n .replace(/\\.+$/, \"\");\n if (d.length === 0) return true;\n if (DUD_DOMAINS.has(d)) return true;\n for (const dud of DUD_DOMAINS) {\n if (d.endsWith(`.${dud}`)) return true;\n }\n return false;\n}\n\n/**\n * True when the input looks like a single-token username/handle rather\n * than a real person name. Heuristics, in order:\n *\n * - Empty / null → handle (no signal).\n * - Contains whitespace → looks like a name. `\"Sam Jones\"`.\n * - Contains a period → looks like a name. `\"Sam J. Jones\"`.\n * - Single token of `[a-z0-9_-]` (case-insensitive) → handle.\n *\n * False-positive accepted: a real single-name like `Madonna` reads as a\n * handle. That's a fine tradeoff vs the volume of HN-style usernames we\n * filter out (90%+ of Show HN authors).\n */\nexport function looksLikeUserHandle(name: string | null | undefined): boolean {\n if (name == null) return true;\n const trimmed = name.trim();\n if (trimmed.length === 0) return true;\n if (/\\s/.test(trimmed)) return false;\n if (trimmed.includes(\".\")) return false;\n return /^[a-z0-9_-]+$/i.test(trimmed);\n}\n\nexport type PrescreenReason = \"no-domain\" | \"dud-domain\" | \"no-fullname\" | \"handle-not-name\";\n\n/**\n * Pre-flight guard. Returns `{ok:true}` to proceed with the SDK call, or\n * `{ok:false, reason}` to skip. The reason is human-readable and stable\n * across releases — safe to log via `finder.skipped_findemail` for later\n * blocklist tuning.\n *\n * Check order matters: a missing/dud domain dominates a handle check (no\n * point flagging \"handle-not-name\" when the domain alone would have\n * disqualified the row).\n */\nexport function shouldSkipFindEmail(input: {\n fullName?: string | null;\n companyDomain: string | null;\n}): { ok: true } | { ok: false; reason: string } {\n if (!input.companyDomain || input.companyDomain.trim().length === 0) {\n return { ok: false, reason: \"no-domain\" };\n }\n if (isDudDomain(input.companyDomain)) {\n return { ok: false, reason: `dud-domain: ${input.companyDomain.toLowerCase()}` };\n }\n const name = input.fullName?.trim() ?? \"\";\n if (name.length === 0) {\n return { ok: false, reason: \"no-fullname\" };\n }\n if (looksLikeUserHandle(name)) {\n return { ok: false, reason: `handle-not-name: ${name}` };\n }\n return { ok: true };\n}\n","import { logEvent, webSearch } from \"@oneshot-gtm/core\";\n\n/**\n * Shared LinkedIn / phone capture helpers used across all finders. Centralises:\n * - `findLinkedInUrl`: webSearch-based LinkedIn-URL discovery (active lookup)\n * - `extractFirstPhone`: passive read of phone fields from enrichment SDK results\n *\n * Both feed the same goal — populate `target.linkedinUrl` and `target.phone` so\n * the founder sees these signals in /queue review and the prospect row carries\n * them after drain.\n */\n\nconst PLAY_NAME = \"linkedin-lookup\";\n\n/** Match `linkedin.com/in/<slug>` profile URLs. The slug class is permissive\n * enough to cover URL-encoded unicode slugs (e.g. `%E7%8E%8B`) which LinkedIn\n * does serve for non-Latin display names. */\nconst LINKEDIN_PROFILE_RX = /^https?:\\/\\/(?:[a-z0-9-]+\\.)*linkedin\\.com\\/in\\/[a-z0-9-_.%]+/i;\n\n/** Per-process cache so the same `(fullName, disambiguators)` doesn't re-search\n * within a run. `null` is a real cached value (means \"we tried and missed\"). */\nconst cache = new Map<string, string | null>();\n\n/** Test-only: reset the cache between cases. */\nexport function _resetLinkedInCache(): void {\n cache.clear();\n}\n\n/**\n * Returns true when `url` looks like a LinkedIn profile URL (`linkedin.com/in/<slug>`).\n * Use to validate LLM-extracted `linkedinUrl` strings before persisting them —\n * the prompt instructs the LLM to emit only profile URLs but real outputs drift\n * (sometimes a `/posts/` URL, sometimes free-form prose).\n */\nexport function isLinkedInProfileUrl(url: string | null | undefined): boolean {\n if (!url || typeof url !== \"string\") return false;\n return LINKEDIN_PROFILE_RX.test(url.trim());\n}\n\n/**\n * Find a LinkedIn profile URL for a person via webSearch.\n *\n * Query shape: `\"<fullName>\" \"<disambig1>\" \"<disambig2>\" site:linkedin.com/in`.\n * The `site:` operator narrows results to actual profile pages (not company\n * pages or jobs). We iterate `webSearch` result URLs and return the first that\n * matches `linkedin.com/in/<slug>`. No regex over freeform text — webSearch\n * returns structured `{url, title, description}` results.\n *\n * Returns null on:\n * - empty fullName\n * - no result URL matches the LinkedIn-profile shape\n * - webSearch throws (logged as `error.swallowed` so the caller's pipeline\n * doesn't tear down)\n *\n * Cost: ~$0.01 per call (one webSearch). Cached per-run by\n * `(fullName, disambiguators)` so duplicate calls within a finder run are free.\n */\nexport async function findLinkedInUrl(args: {\n fullName: string;\n /** Optional tokens that narrow the search — company name, github handle,\n * podcast name, cohort label, etc. Each becomes a quoted token in the query. */\n disambiguators?: string[];\n accumCost: (c: number | undefined) => void;\n /** Used in the error.swallowed event kind, e.g. \"github-topics\" or \"show-hn\". */\n errKindPrefix: string;\n}): Promise<string | null> {\n const fullName = args.fullName.trim();\n if (fullName.length === 0) return null;\n\n const disambiguators = (args.disambiguators ?? [])\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const cacheKey = JSON.stringify([\n fullName.toLowerCase(),\n disambiguators.map((s) => s.toLowerCase()),\n ]);\n if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null;\n\n const tokens = [fullName, ...disambiguators];\n const query = `${tokens.map((t) => `\"${t}\"`).join(\" \")} site:linkedin.com/in`;\n try {\n const search = await webSearch({ query, maxResults: 5 }, { playName: PLAY_NAME });\n args.accumCost(search.result.cost ?? 0);\n for (const r of search.result.results ?? []) {\n const url = typeof r.url === \"string\" ? r.url : \"\";\n if (LINKEDIN_PROFILE_RX.test(url)) {\n cache.set(cacheKey, url);\n logEvent(\"linkedin.search.found\", { full_name: fullName, url });\n return url;\n }\n }\n cache.set(cacheKey, null);\n logEvent(\"linkedin.search.miss\", { full_name: fullName, disambiguators });\n return null;\n } catch (err) {\n cache.set(cacheKey, null);\n logEvent(\n \"error.swallowed\",\n {\n kind: `${args.errKindPrefix}.linkedin_search`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Pull the first usable phone number out of either an enrichProfile or a\n * deepResearchPerson result shape. Both SDK results may surface a phone — this\n * is the single read site so finders don't have to know which shape they got.\n *\n * Shapes accepted:\n * - deepResearchPerson: `enrichment.fullphone[0].fullphone` (array of objects)\n * - enrichProfile: `profile.phone` (single string)\n * - LLM extracts: `extract.phone` (single string)\n *\n * Returns the raw string from whichever source. No normalization — defer\n * E.164 formatting until a downstream consumer needs it.\n */\nexport function extractFirstPhone(source: unknown): string | null {\n if (!source || typeof source !== \"object\") return null;\n const obj = source as Record<string, unknown>;\n\n // deepResearchPerson `enrichment.fullphone` array shape\n const fullphone = obj[\"fullphone\"];\n if (Array.isArray(fullphone)) {\n for (const entry of fullphone) {\n if (entry && typeof entry === \"object\") {\n const v = (entry as Record<string, unknown>)[\"fullphone\"];\n if (typeof v === \"string\" && v.trim().length > 0) return v.trim();\n } else if (typeof entry === \"string\" && entry.trim().length > 0) {\n return entry.trim();\n }\n }\n }\n\n // enrichProfile `profile.phone` OR LLM-extract `extract.phone` shape\n const phone = obj[\"phone\"];\n if (typeof phone === \"string\" && phone.trim().length > 0) return phone.trim();\n\n return null;\n}\n","import { enrichProfile, logEvent } from \"@oneshot-gtm/core\";\nimport { extractFirstPhone, isLinkedInProfileUrl } from \"./_linkedin.ts\";\n\nexport interface EnrichedContact {\n phone: string | null;\n linkedinUrl: string | null;\n costUsd: number;\n receiptId: number | null;\n}\n\n/**\n * Always-on post-verify enrichment. Called by every enqueueing finder\n * AFTER verifyEmail succeeds + BEFORE enqueueTarget. Reads phone +\n * linkedin off PersonResult and returns them; finder merges into target.\n *\n * Why this exists: phone capture used to fire only on the narrow Path B'\n * + Path C branches in `_repo-pipeline.ts` (~10% of candidates), and the\n * other 6 finders never enriched at all. Empirical audit found 0/514\n * queue rows had a phone despite the SDK clearly returning some on\n * separate enrichProfile calls. Adding one $0.005 call per verified\n * email closes the gap uniformly across every play.\n *\n * Throws are swallowed — one transient SDK blip should never kill an\n * otherwise valid enqueue. Same try/catch pattern as the existing\n * Path B' enrichProfile call in `_repo-pipeline.ts`.\n */\nexport async function enrichVerifiedContact(\n email: string,\n opts: { playName: string; errKindPrefix?: string },\n): Promise<EnrichedContact> {\n try {\n const enriched = await enrichProfile({ email }, { playName: opts.playName });\n const profile = enriched.result.profile;\n const linkedinRaw = profile?.linkedin_url ?? null;\n return {\n phone: extractFirstPhone(profile),\n linkedinUrl: isLinkedInProfileUrl(linkedinRaw) ? linkedinRaw : null,\n costUsd: enriched.result.cost ?? 0,\n receiptId: enriched.receiptId,\n };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${opts.errKindPrefix ?? \"enrich\"}.post_verify`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return { phone: null, linkedinUrl: null, costUsd: 0, receiptId: null };\n }\n}\n","import { getLedger, logEvent, type FindEmailInput } from \"@oneshot-gtm/core\";\nimport { findEmail, verifyEmail, webRead } from \"@oneshot-gtm/core\";\nimport type { ShowHnTarget } from \"@oneshot-gtm/plays\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl } from \"./_linkedin.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport type { FinderResult, RunOpts, ShowHnHit } from \"./_types.ts\";\n\nconst HN_ALGOLIA = \"https://hn.algolia.com/api/v1/search_by_date\";\nconst PLAY_NAME = \"show-hn\";\nconst SOURCE = \"find:show-hn\";\n\nexport interface ShowHnFinderOpts extends RunOpts {\n /** Look back this many days. Default 1. */\n sinceDays?: number;\n /** Skip posts with fewer points than this. Default 5. */\n minPoints?: number;\n /** Max per-candidate pipelines in flight at once. Default 3. */\n concurrency?: number;\n}\n\ninterface SearchHitsResponse {\n hits: ShowHnHit[];\n}\n\n/**\n * Pulls Show HN posts from HN Algolia, ICP-filters them, enriches founder\n * contact via OneShot, dedupes against the ledger, and enqueues into target_queue.\n */\nexport async function runShowHnFinder(opts: ShowHnFinderOpts): Promise<FinderResult> {\n const sinceDays = opts.sinceDays ?? 1;\n const minPoints = opts.minPoints ?? 5;\n const limit = opts.limit ?? 25;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n droppedLowSignal: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n logEvent(\"finder.start\", { name: PLAY_NAME, since_days: sinceDays, limit });\n const sinceUnix = Math.floor((Date.now() - sinceDays * 24 * 3600 * 1000) / 1000);\n const url = `${HN_ALGOLIA}?tags=show_hn&numericFilters=created_at_i>${sinceUnix}&hitsPerPage=${Math.min(50, limit * 2)}`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`HN Algolia fetch failed: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as SearchHitsResponse;\n result.candidates = data.hits.length;\n logEvent(\"finder.fetched\", { name: PLAY_NAME, candidates: result.candidates });\n\n // Per-candidate pipeline runs at `concurrency` (mirrors accelerator-batch /\n // github-topics) — the serial version spent ~70s on 50 candidates waiting on\n // findEmail/verify/enrich one at a time. `halted` is a soft cap: workers in\n // flight when the limit/cost-cap trips may overshoot by up to\n // (concurrency - 1) candidates. The `result.*` accumulators are mutated in\n // place; safe because JS interleaves (never truly parallel) between awaits.\n const concurrency = opts.concurrency ?? 3;\n let halted = false;\n\n await parallelMap(data.hits, concurrency, async (hit) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n if (hit.points < minPoints) {\n result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;\n return;\n }\n\n // Dedupe BEFORE any LLM/OneShot spend.\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.objectID)) {\n result.droppedDuplicate++;\n return;\n }\n\n // ICP filter.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: hit.title,\n url: hit.url,\n summary: hit.story_text?.slice(0, 800) ?? null,\n author: hit.author,\n },\n });\n // Rough cost: ~$0.001 per filter call (LLM tokens; not OneShot $).\n if (!filter.match) {\n result.droppedIcp++;\n // Persist the auto-rejection so the founder can review what got\n // dropped, override (set to approved) if it was a false negative,\n // and so the future learning loop has labeled examples.\n if (!opts.dryRun) {\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { postTitle: hit.title, postUrl: hit.url, founderName: hit.author },\n dedupeKey: hit.objectID,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n }\n return;\n }\n\n if (opts.dryRun) {\n // Just count — don't enrich or enqueue.\n result.enqueued++;\n return;\n }\n\n // Enrich: try to find the founder's email via the landing-page domain + author handle.\n const domain = urlDomain(hit.url);\n if (!domain) {\n result.droppedEnrichment++;\n return;\n }\n\n // Read the landing page so we have content for the hookSummary fallback +\n // a crude \"founder name\" guess (use the HN handle as fullName if present).\n const fullName = hit.author && hit.author.length > 0 ? hit.author : undefined;\n const skip = shouldSkipFindEmail({ fullName, companyDomain: domain });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n return;\n }\n const findInput: FindEmailInput = { companyDomain: domain };\n if (fullName) findInput.fullName = fullName;\n const found = await findEmail(findInput, { playName: PLAY_NAME });\n result.costUsd += found.result.cost ?? 0;\n\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n return;\n }\n const email = found.result.email;\n\n // Verify deliverability.\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n // Cross-table dedupe: same email already a known prospect?\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.objectID, prospectEmail: email })) {\n result.droppedDuplicate++;\n return;\n }\n\n // Optional: read the landing page for a richer hookSummary.\n let hookSummary = (hit.story_text ?? \"\").trim().slice(0, 280);\n if (hookSummary.length < 40 && hit.url) {\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n hookSummary = (read.result.markdown ?? \"\").trim().slice(0, 280);\n } catch (err) {\n // best-effort; fall through to whatever we have\n logEvent(\n \"error.swallowed\",\n {\n kind: \"show-hn.hookSummary.webRead\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n if (!hookSummary || hookSummary.length < 20) {\n hookSummary = `Show HN post: ${hit.title}. ${hit.points} points.`;\n }\n\n const founderName = found.result.full_name ?? hit.author;\n // Always enrich after verify to capture phone + linkedin from the SDK.\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"show-hn\",\n });\n result.costUsd += enr.costUsd;\n const phone = enr.phone;\n let linkedinUrl: string | null = enr.linkedinUrl;\n if (!linkedinUrl) {\n // Last-resort webSearch fallback when enrichProfile didn't surface one.\n linkedinUrl = await findLinkedInUrl({\n fullName: founderName,\n disambiguators: [\"hacker news\", domain],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"show-hn\",\n });\n }\n\n const target: ShowHnTarget = {\n postTitle: hit.title,\n postUrl: `https://news.ycombinator.com/item?id=${hit.objectID}`,\n founderName,\n founderEmail: email,\n hookSummary,\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.objectID,\n source: SOURCE,\n notes: filter.reason,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n });\n\n logEvent(\"finder.done\", {\n name: PLAY_NAME,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n dropped_low_signal: result.droppedLowSignal ?? 0,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return result;\n}\n","import { getLedger, logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { findEmail, verifyEmail } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { PostFundingTarget } from \"@oneshot-gtm/plays\";\nimport { readFileSync } from \"node:fs\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, PostFundingExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"post-funding\";\nconst SOURCE = \"find:post-funding\";\n\nconst ROUND_MAP: Record<string, string> = {\n \"Pre-Seed\": \"Pre-Seed\",\n Seed: \"Seed\",\n \"Series A\": \"Series A\",\n \"Series B\": \"Series B\",\n \"Series C\": \"Series C\",\n \"Series D+\": \"Series D+\",\n};\n\nexport interface PostFundingFinderOpts extends RunOpts {\n /** File with one URL per line (TC / Crunchbase / company-blog). */\n sourceUrlsFile?: string;\n /** Or: pass URLs directly. */\n sourceUrls?: string[];\n /**\n * Auto-discovery mode: if no source URLs are supplied, run a webSearch\n * per round in `autoRounds` for \"<industry hint> <round> announcement\".\n * Industry hint comes from the saved ICP one-liner (or autoIndustry override).\n */\n auto?: boolean;\n /** Rounds to scan in auto mode. Default: [\"Seed\", \"Series A\"]. */\n autoRounds?: string[];\n /** Override the industry hint extracted from the ICP. */\n autoIndustry?: string;\n /** Look back this many days in auto mode (used in the search query). Default 7. */\n autoSinceDays?: number;\n}\n\nexport async function runPostFundingFinder(opts: PostFundingFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"post-funding-extract\");\n\n // Auto mode: harvest URLs via webSearch instead of reading a file.\n let urls = collectUrls(opts);\n let autoCost = 0;\n if (opts.auto && urls.length === 0) {\n const harvested = await harvestAutoUrls({\n rounds: opts.autoRounds ?? [\"Seed\", \"Series A\"],\n industry: opts.autoIndustry ?? deriveIndustryHint(icp),\n sinceDays: opts.autoSinceDays ?? 7,\n limit: limit * 2, // pull a bit extra; ICP filter + extract will winnow\n });\n urls = harvested.urls;\n autoCost = harvested.costUsd;\n }\n\n const result: FinderResult = {\n source: opts.auto ? `${SOURCE}:auto` : SOURCE,\n candidates: urls.length,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: autoCost,\n };\n\n for (const url of urls.slice(0, limit)) {\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n // Dedupe by URL before spending anything (cheap).\n if (ledger.isQueueDuplicate(PLAY_NAME, url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n // Read the announcement.\n let extract: PostFundingExtract;\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: (read.result.markdown ?? \"\").slice(0, 12000) },\n ],\n temperature: 0.1,\n maxTokens: 600,\n });\n extract = parsePostFundingExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"post-funding.read_or_extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.company || !extract.companyDomain || !extract.founderName) {\n result.droppedEnrichment++;\n continue;\n }\n\n // ICP filter on the LLM-extracted summary.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: `${extract.company} ${extract.round ?? \"raised\"} (${extract.industry ?? \"industry n/a\"})`,\n url,\n summary: extract.summary,\n },\n });\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: {\n company: extract.company,\n round: extract.round,\n industry: extract.industry,\n summary: extract.summary,\n sourceUrl: url,\n },\n dedupeKey: url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n // Enrich email.\n const skip = shouldSkipFindEmail({\n fullName: extract.founderName,\n companyDomain: extract.companyDomain,\n });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n continue;\n }\n const found = await findEmail(\n { fullName: extract.founderName, companyDomain: extract.companyDomain },\n { playName: PLAY_NAME },\n );\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n continue;\n }\n const email = found.result.email;\n\n // Cross-table dedupe.\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey: url, prospectEmail: email })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"post-funding\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.founderName,\n disambiguators: [extract.company],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"post-funding\",\n });\n }\n\n const target: PostFundingTarget = {\n name: extract.founderName,\n email,\n company: extract.company,\n round: ROUND_MAP[extract.round ?? \"\"] ?? extract.round ?? \"Seed\",\n amountUsd: extract.amountUsd ?? 0,\n sourceUrl: url,\n ...(extract.leadInvestor ? { leadInvestor: extract.leadInvestor } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: url,\n source: SOURCE,\n notes: `${extract.round ?? \"?\"} ${extract.amountUsd ? `$${extract.amountUsd.toLocaleString()}` : \"\"} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function collectUrls(opts: PostFundingFinderOpts): string[] {\n const urls: string[] = [];\n if (opts.sourceUrls) urls.push(...opts.sourceUrls);\n if (opts.sourceUrlsFile) {\n const raw = readFileSync(opts.sourceUrlsFile, \"utf8\");\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n try {\n const _validate = new URL(trimmed);\n urls.push(_validate.toString());\n } catch {\n // skip non-URL lines\n }\n }\n }\n return [...new Set(urls)];\n}\n\nexport function parsePostFundingExtract(raw: string): PostFundingExtract {\n return tryParseJsonObject<PostFundingExtract>(raw, {\n company: null,\n companyDomain: null,\n round: null,\n amountUsd: null,\n leadInvestor: null,\n founderName: null,\n founderRole: null,\n industry: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n\ninterface HarvestArgs {\n rounds: string[];\n industry: string;\n sinceDays: number;\n limit: number;\n}\n\nconst FUNDING_DOMAIN_HINTS = [\n \"techcrunch.com\",\n \"crunchbase.com\",\n \"businesswire.com\",\n \"prnewswire.com\",\n \"pitchbook.com\",\n \"venturebeat.com\",\n \"axios.com\",\n \"fortune.com\",\n \"forbes.com\",\n \"reuters.com\",\n \"bloomberg.com\",\n \"sifted.eu\",\n \"tech.eu\",\n \"theinformation.com\",\n];\n\nasync function harvestAutoUrls(args: HarvestArgs): Promise<{ urls: string[]; costUsd: number }> {\n const seen = new Set<string>();\n const urls: string[] = [];\n let costUsd = 0;\n const sincePhrase = args.sinceDays <= 1 ? \"today\" : `last ${args.sinceDays} days`;\n const industry = args.industry.trim();\n\n for (const round of args.rounds) {\n if (urls.length >= args.limit) break;\n const queryParts = [\n industry,\n `\"${round}\"`,\n \"funding announcement\",\n sincePhrase,\n \"site:(techcrunch.com OR crunchbase.com OR businesswire.com OR prnewswire.com OR sifted.eu OR tech.eu)\",\n ].filter(Boolean);\n const query = queryParts.join(\" \");\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(20, Math.max(5, args.limit - urls.length)) },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (urls.length >= args.limit) break;\n if (!hit.url) continue;\n const normalized = normalizeUrl(hit.url);\n if (!normalized) continue;\n if (seen.has(normalized)) continue;\n if (!isLikelyFundingUrl(normalized, hit.title, hit.description)) continue;\n seen.add(normalized);\n urls.push(normalized);\n }\n } catch {\n // skip this round on error; keep harvesting others\n }\n }\n return { urls, costUsd };\n}\n\nexport function normalizeUrl(raw: string): string | null {\n try {\n const u = new URL(raw);\n u.hash = \"\";\n return u.toString();\n } catch {\n return null;\n }\n}\n\nexport function isLikelyFundingUrl(url: string, title?: string, description?: string): boolean {\n let host = \"\";\n try {\n host = new URL(url).hostname.toLowerCase();\n } catch {\n return false;\n }\n const hostMatch = FUNDING_DOMAIN_HINTS.some((h) => host === h || host.endsWith(`.${h}`));\n if (hostMatch) return true;\n const text = `${title ?? \"\"} ${description ?? \"\"}`.toLowerCase();\n return /\\b(raises?|raised|series\\s+[a-d]|seed round|pre-?seed|funding round|led by)\\b/.test(text);\n}\n\nexport function deriveIndustryHint(icp: string | null): string {\n if (!icp) return \"startup\";\n const cleaned = icp\n .toLowerCase()\n .replace(/[^a-z0-9\\s+/-]/g, \" \")\n .split(/\\s+/)\n .filter(Boolean);\n const stop = new Set([\n \"the\",\n \"a\",\n \"an\",\n \"and\",\n \"or\",\n \"of\",\n \"for\",\n \"to\",\n \"with\",\n \"in\",\n \"on\",\n \"who\",\n \"that\",\n \"are\",\n \"is\",\n \"be\",\n \"their\",\n \"they\",\n \"we\",\n \"our\",\n \"you\",\n \"your\",\n \"at\",\n \"as\",\n \"by\",\n \"from\",\n \"any\",\n \"need\",\n \"needs\",\n \"want\",\n \"wants\",\n \"use\",\n \"uses\",\n \"using\",\n \"build\",\n \"building\",\n \"ship\",\n \"shipping\",\n \"make\",\n \"making\",\n \"people\",\n \"team\",\n \"teams\",\n \"company\",\n \"companies\",\n \"founder\",\n \"founders\",\n \"developer\",\n \"developers\",\n \"engineer\",\n \"engineers\",\n \"ceo\",\n \"cto\",\n \"vp\",\n \"head\",\n ]);\n const keywords = cleaned.filter((w) => w.length > 2 && !stop.has(w)).slice(0, 4);\n return keywords.length > 0 ? keywords.join(\" \") : \"startup\";\n}\n","import { logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { AcceleratorLaunchExtract, CompanyRecord } from \"./_types.ts\";\n\n/**\n * Fallback adapter for accelerators that DON'T publish a structured directory\n * (Techstars, Antler, 500 Global, AI Grant, SPC, Neo, …). Combo-search shape:\n * webSearch with cohort-derived queries, aggregate hits, dedupe, then per-hit\n * webRead + LLM extract.\n *\n * Less reliable than the yc-oss adapter (search recall depends on the\n * accelerator's web presence) but works without per-accelerator scrapers.\n */\n\nconst PLAY_NAME = \"accelerator-batch\";\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\n/**\n * Build the three search queries from a human-readable cohort label.\n * Founders supply `cohortLabel: \"YC W26\"` or `\"Techstars Toronto Spring 2025\"`\n * and we generate complementary queries. Three is enough to hit different\n * indexing patterns (launch posts vs portfolio pages vs press coverage)\n * without burning the search-call budget.\n */\nexport function buildCohortQueries(cohortLabel: string): string[] {\n const label = cohortLabel.trim();\n if (label.length === 0) return [];\n return [`\"${label}\" launch announcement`, `\"${label}\" portfolio company`, `\"${label}\" demo day`];\n}\n\n/**\n * Drop URL hosts that reliably fail per-page extraction or pollute results.\n * Aggregators (techcrunch, news.yc) carry batch lists, not company-specific\n * pages; social-media root paths surface profiles, not products.\n *\n * Conservative: an empty hit list breaks the finder, so only block hosts\n * that are NEVER useful per-record.\n */\nexport function looksLikeAcceleratorNoise(url: string): boolean {\n let host: string;\n try {\n host = new URL(url).hostname.toLowerCase().replace(/^www\\./, \"\");\n } catch {\n return true; // un-parseable URL is always noise\n }\n // Listicles, social roots, video aggregators — never a per-company page.\n const noiseHosts = [\n \"twitter.com\",\n \"x.com\",\n \"linkedin.com\",\n \"facebook.com\",\n \"youtube.com\",\n \"youtu.be\",\n \"reddit.com\",\n \"medium.com\", // medium URLs sometimes work but recall is bad and noise is high\n ];\n if (noiseHosts.includes(host)) return true;\n // News aggregators that DO host accelerator coverage but rarely as\n // single-company pages — keep the option to surface specific paths later\n // by host-prefix matching, but block bare-host hits for now.\n if (host === \"news.ycombinator.com\") return true;\n if (host === \"techcrunch.com\") return true;\n return false;\n}\n\n/**\n * Fetch search hits for a non-YC accelerator cohort, then extract a\n * `CompanyRecord` per hit via LLM. Honors `limit` at the hit-count level so a\n * sparse search doesn't blow the per-record budget on noise.\n *\n * Cost is non-zero (webSearch + webRead + LLM extract per hit).\n */\nexport async function fetchAcceleratorSearch(\n _cohort: string,\n cohortLabel: string,\n limit: number,\n): Promise<{ records: CompanyRecord[]; costUsd: number; diagnostic: string | null }> {\n const queries = buildCohortQueries(cohortLabel);\n if (queries.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: \"set `cohortLabel` to the human-readable program name\",\n };\n }\n\n let costUsd = 0;\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n for (const query of queries) {\n if (hits.length >= limit * 2) break;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const raw of search.result.results ?? []) {\n if (!raw.url || seen.has(raw.url)) continue;\n if (looksLikeAcceleratorNoise(raw.url)) continue;\n seen.add(raw.url);\n hits.push({ url: raw.url, title: raw.title, description: raw.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-search.query\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n\n if (hits.length === 0) {\n return {\n records: [],\n costUsd,\n diagnostic: `no usable hits for '${cohortLabel}' — try a more specific cohortLabel (e.g. include the city/year)`,\n };\n }\n\n const system = loadPrompt(\"accelerator-launch-extract\");\n const records: CompanyRecord[] = [];\n for (const hit of hits.slice(0, limit)) {\n let extract: AcceleratorLaunchExtract | null = null;\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n title: hit.title,\n description: hit.description,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseAcceleratorLaunchExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-search.read\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n continue;\n }\n if (!extract || !extract.company) continue;\n // The prompt instructs the LLM to return a bare hostname, but LLMs drift —\n // sanitize so an off-spec response can't break URL construction or pass\n // through paths/protocols into findEmail.\n const cleanDomain = sanitizeCompanyDomain(extract.companyDomain);\n const website = cleanDomain ? `https://${cleanDomain}` : null;\n records.push({\n name: extract.company,\n website,\n oneLiner: extract.oneLiner,\n longDescription: null,\n industry: null,\n tags: [],\n ycUrl: null,\n // The websearch extract returns founderName when the page named one\n // explicitly. Keep null here when it didn't — the pipeline still has\n // a chance to resolve via per-page extract on a different URL.\n founderName: extract.founderName?.trim() || null,\n founderLinkedinUrl: isLinkedInProfileUrl(extract.linkedinUrl)\n ? (extract.linkedinUrl as string).trim()\n : null,\n founderPhone: extract.phone?.trim() || null,\n source: \"websearch\",\n });\n }\n\n if (records.length === 0) {\n return {\n records: [],\n costUsd,\n diagnostic: `${hits.length} hits found but none extracted to a usable company record`,\n };\n }\n\n return { records, costUsd, diagnostic: null };\n}\n\n/**\n * Coerce an LLM-supplied \"company domain\" string into a bare hostname.\n * Strips scheme, leading `www.`, paths, query, and fragment. Returns null\n * for null/empty/invalid input.\n *\n * Prompt instructs the LLM to return bare hosts, but real-world outputs\n * include `https://www.foo.com/about`, `foo.com/`, ` foo.com `, etc. This\n * normalizes them so downstream `findEmail` always sees a clean domain.\n */\nexport function sanitizeCompanyDomain(raw: string | null | undefined): string | null {\n if (!raw || typeof raw !== \"string\") return null;\n let v = raw.trim().toLowerCase();\n if (v.length === 0) return null;\n // Strip scheme.\n v = v.replace(/^https?:\\/\\//, \"\");\n // Strip leading www.\n v = v.replace(/^www\\./, \"\");\n // Drop path / query / fragment / port.\n v = v.replace(/[/?#:].*$/, \"\");\n // Trim trailing dots.\n v = v.replace(/\\.+$/, \"\");\n // Sanity: must contain a dot and at least one non-digit char to be a real domain.\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(v)) return null;\n return v;\n}\n\nexport function parseAcceleratorLaunchExtract(raw: string): AcceleratorLaunchExtract {\n return tryParseJsonObject<AcceleratorLaunchExtract>(raw, {\n company: null,\n companyDomain: null,\n oneLiner: null,\n founderName: null,\n founderRole: null,\n launchUrl: null,\n linkedinUrl: null,\n phone: null,\n });\n}\n","import type { CompanyRecord } from \"./_types.ts\";\n\n/**\n * Adapter for the [yc-oss/api](https://github.com/yc-oss/api) public dataset.\n * Free, daily-updated, no auth — strictly better than scraping YC's\n * client-rendered launches page.\n *\n * Schema reference (from `https://yc-oss.github.io/api/batches/<slug>.json`):\n * each record has `name, slug, website, one_liner, long_description, industry,\n * subindustry, tags, batch, status, url, api`. No founder names — the\n * downstream pipeline still calls findEmail on the company domain.\n */\n\nconst YC_OSS_BASE = \"https://yc-oss.github.io/api/batches\";\n\n/**\n * Map a cohort tag (`yc-w26`, `yc-s25`, `yc-spring-26`, `yc-fall-25`) to the\n * yc-oss batch slug (`winter-2026`, `summer-2025`, `spring-2026`, `fall-2025`).\n *\n * Pass-through behavior: a tag that already looks like an yc-oss slug\n * (`winter-2026`, `summer-2024`, etc.) is returned unchanged so founders can\n * paste either form into config.\n *\n * Returns null when the tag doesn't match any known pattern — caller should\n * surface this as a diagnostic, not throw, so the trigger card shows the\n * real reason instead of a 500.\n */\nexport function cohortToBatchSlug(tag: string): string | null {\n const normalized = tag.trim().toLowerCase();\n if (normalized.length === 0) return null;\n\n // Already a yc-oss slug? Accept it verbatim.\n if (/^(winter|summer|spring|fall)-\\d{4}$/.test(normalized)) {\n return normalized;\n }\n\n // yc-w26 / yc-s25 — single-letter season + 2-digit year.\n const short = normalized.match(/^yc-([wsfp])(\\d{2})$/);\n if (short) {\n const letter = short[1] as \"w\" | \"s\" | \"f\" | \"p\";\n const yy = short[2] as string;\n const season = SHORT_SEASON[letter];\n if (!season) return null;\n return `${season}-20${yy}`;\n }\n\n // yc-spring-26 / yc-fall-25 — full season name + 2-digit year.\n const long = normalized.match(/^yc-(winter|summer|spring|fall)-(\\d{2})$/);\n if (long) {\n return `${long[1]}-20${long[2]}`;\n }\n\n // yc-w-2026 / yc-winter-2026 — 4-digit year variants.\n const fourYear = normalized.match(/^yc-(winter|summer|spring|fall|[wsfp])-(\\d{4})$/);\n if (fourYear) {\n const seasonRaw = fourYear[1] as string;\n const yyyy = fourYear[2] as string;\n const season =\n seasonRaw.length === 1\n ? SHORT_SEASON[seasonRaw as \"w\" | \"s\" | \"f\" | \"p\"]\n : (seasonRaw as \"winter\" | \"summer\" | \"spring\" | \"fall\");\n if (!season) return null;\n return `${season}-${yyyy}`;\n }\n\n return null;\n}\n\nconst SHORT_SEASON: Record<\"w\" | \"s\" | \"f\" | \"p\", \"winter\" | \"summer\" | \"fall\" | \"spring\"> = {\n w: \"winter\",\n s: \"summer\",\n f: \"fall\",\n p: \"spring\", // \"p\" for sPring — yc convention varies; spring is rare so this is a best-guess fallback\n};\n\n/**\n * Build a human-readable cohort label from a cohort tag, used when the\n * founder didn't supply `cohortLabel` explicitly.\n *\n * - `yc-w26` → `YC W26` (preserves the canonical YC short form for emails)\n * - `yc-winter-2026` → `YC Winter 2026`\n * - `techstars-toronto-2025` → `Techstars Toronto 2025` (Title-Case + spaces)\n *\n * Used by the websearch adapter's query builder, so a wrong default would\n * search for the wrong program. Tightens behavior after a `cohort` edit —\n * the previous hardcoded `\"YC W26\"` default would silently mismatch.\n */\nexport function deriveCohortLabel(cohort: string): string {\n const tag = cohort.trim();\n if (tag.length === 0) return \"\";\n // Special-case YC short tags to keep the canonical \"YC W26\" form.\n const ycShort = tag.match(/^yc-([wsfp])(\\d{2})$/i);\n if (ycShort) {\n const letter = ycShort[1]!.toUpperCase();\n const yy = ycShort[2]!;\n return `YC ${letter}${yy}`;\n }\n // Generic: split on hyphens, title-case each part. \"yc\" stays uppercase\n // when it's the first segment.\n return tag\n .split(\"-\")\n .map((part, i) => {\n if (i === 0 && part.toLowerCase() === \"yc\") return \"YC\";\n if (/^\\d+$/.test(part)) return part;\n return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();\n })\n .join(\" \");\n}\n\ninterface YcOssCompany {\n name?: unknown;\n website?: unknown;\n one_liner?: unknown;\n long_description?: unknown;\n industry?: unknown;\n tags?: unknown;\n url?: unknown;\n}\n\n/**\n * Fetch a yc-oss batch and map records to the normalized `CompanyRecord`\n * shape. Honors `limit` so we don't pull a 200-record batch when the founder\n * only wants 25.\n *\n * Returns:\n * - `records`: zero or more company records.\n * - `diagnostic`: human-readable reason when records is empty (404, parse\n * error, unknown tag) so the UI can surface it instead of treating zero\n * as success.\n *\n * Cost is always 0 — yc-oss is GitHub Pages, no LLM, no auth.\n */\nexport async function fetchYcOssBatch(\n cohort: string,\n limit: number,\n): Promise<{ records: CompanyRecord[]; costUsd: number; diagnostic: string | null }> {\n const slug = cohortToBatchSlug(cohort);\n if (!slug) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `unknown YC cohort tag '${cohort}' — try 'yc-w26', 'yc-s25', or 'winter-2026'`,\n };\n }\n const url = `${YC_OSS_BASE}/${slug}.json`;\n let res: Response;\n try {\n res = await fetch(url);\n } catch (err) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss fetch failed: ${(err as Error).message ?? \"network error\"}`,\n };\n }\n if (!res.ok) {\n if (res.status === 404) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss has no batch '${slug}' yet — likely too new or misspelled cohort`,\n };\n }\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss returned ${res.status} ${res.statusText}`,\n };\n }\n let parsed: unknown;\n try {\n parsed = await res.json();\n } catch {\n return { records: [], costUsd: 0, diagnostic: \"yc-oss response was not valid JSON\" };\n }\n if (!Array.isArray(parsed)) {\n return { records: [], costUsd: 0, diagnostic: \"yc-oss response was not an array\" };\n }\n if (parsed.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss has no companies for batch '${slug}' yet — likely too new`,\n };\n }\n const records = parsed\n .slice(0, limit)\n .map((c) => mapYcOssCompany(c as YcOssCompany))\n .filter((r): r is CompanyRecord => r !== null);\n if (records.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss returned ${parsed.length} records but none had a usable name`,\n };\n }\n return { records, costUsd: 0, diagnostic: null };\n}\n\n/** Map a single yc-oss company JSON object to the normalized shape. Returns null for malformed records. */\nexport function mapYcOssCompany(c: YcOssCompany): CompanyRecord | null {\n const name = typeof c.name === \"string\" ? c.name.trim() : \"\";\n if (name.length === 0) return null;\n return {\n name,\n website: typeof c.website === \"string\" && c.website.length > 0 ? c.website : null,\n oneLiner: typeof c.one_liner === \"string\" && c.one_liner.length > 0 ? c.one_liner : null,\n longDescription:\n typeof c.long_description === \"string\" && c.long_description.length > 0\n ? c.long_description\n : null,\n industry: typeof c.industry === \"string\" && c.industry.length > 0 ? c.industry : null,\n tags: Array.isArray(c.tags) ? (c.tags.filter((t) => typeof t === \"string\") as string[]) : [],\n ycUrl: typeof c.url === \"string\" && c.url.length > 0 ? c.url : null,\n // yc-oss schema doesn't include founder names — pipeline resolves them on\n // demand via webRead+extract on the YC profile URL.\n founderName: null,\n founderLinkedinUrl: null,\n founderPhone: null,\n source: \"yc-oss\",\n };\n}\n","import { findEmail, getLedger, logEvent, verifyEmail, webRead } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport type { AcceleratorBatchTarget } from \"@oneshot-gtm/plays\";\nimport {\n fetchAcceleratorSearch,\n parseAcceleratorLaunchExtract,\n} from \"./_accelerator-search-adapter.ts\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport { deriveCohortLabel, fetchYcOssBatch } from \"./_yc-oss-adapter.ts\";\nimport type { CompanyRecord, FinderResult, RunOpts } from \"./_types.ts\";\n\n/**\n * Pulls an accelerator-cohort directory, ICP-filters, finds founder contact,\n * enqueues for outreach. Two adapters:\n *\n * - `yc-oss` — free structured directory at yc-oss.github.io (auto-selected\n * when cohort matches `^yc-`). The right path for any YC batch.\n * - `websearch` — combo-search fallback for accelerators without a public API\n * (Techstars, Antler, 500 Global, AI Grant, …). Less reliable recall but\n * works for any cohortLabel.\n *\n * The per-company pipeline is shared: dedupe → ICP filter → findEmail →\n * verifyEmail → enqueue, all under `parallelMap` (concurrency 3, mirrors\n * github-topics).\n */\n\nconst PLAY_NAME = \"accelerator-batch\";\n\nexport interface CohortEntry {\n /** Cohort tag — e.g. `yc-w26`, `techstars-spring-2026`, `spc-2026-1`. */\n cohort: string;\n /** Human-readable label fed into search queries + the email prompt. */\n cohortLabel: string;\n}\n\nexport interface AcceleratorBatchFinderOpts extends RunOpts {\n /**\n * Multi-cohort sweep. Each entry routes to its own adapter — yc-* → yc-oss,\n * everything else → websearch. Per-cohort failures are isolated; the run\n * only halts if EVERY cohort returns 0 records.\n */\n cohorts?: CohortEntry[];\n /** Legacy single-cohort tag. Ignored when `cohorts` is set. */\n cohort?: string;\n /** Legacy human label. Ignored when `cohorts` is set. */\n cohortLabel?: string;\n /** Force a specific adapter for ALL entries. Default: yc-* → yc-oss, else → websearch. */\n adapter?: \"yc-oss\" | \"websearch\";\n /** Concurrency for the per-company pipeline (over the unified pool). Default 3. */\n concurrency?: number;\n /** The sender's own cohort tag — stamped onto every enqueued row so the play\n * can draft inline (self-contained), like github-topics stamps `yourEdge`. */\n senderCohort?: string;\n /** Optional time-bound offer for the sender's cohort, stamped onto each row. */\n freeForCohortOffer?: string;\n}\n\n/**\n * Normalize the legacy single-cohort opts shape into the new multi-cohort\n * list. Old trigger rows with `{cohort, cohortLabel}` keep working — they\n * become a one-entry list. Each entry's `cohort` is trimmed and an empty\n * `cohortLabel` is filled via `deriveCohortLabel`. Malformed entries\n * (missing or empty cohort tag) are dropped silently. Throws when zero\n * usable entries remain — readiness gate is supposed to prevent this.\n */\nexport function normalizeCohorts(\n opts: Pick<AcceleratorBatchFinderOpts, \"cohorts\" | \"cohort\" | \"cohortLabel\">,\n): CohortEntry[] {\n if (opts.cohorts && opts.cohorts.length > 0) {\n const normalized = opts.cohorts\n .map((entry): CohortEntry | null => {\n if (!entry || typeof entry.cohort !== \"string\") return null;\n const cohort = entry.cohort.trim();\n if (cohort.length === 0) return null;\n const labelRaw = typeof entry.cohortLabel === \"string\" ? entry.cohortLabel.trim() : \"\";\n return { cohort, cohortLabel: labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort) };\n })\n .filter((e): e is CohortEntry => e !== null);\n if (normalized.length > 0) return normalized;\n // All entries malformed — fall through to the legacy fields below before\n // throwing, in case the operator set both fields.\n }\n if (typeof opts.cohort === \"string\" && opts.cohort.trim().length > 0) {\n const cohort = opts.cohort.trim();\n const cohortLabel =\n typeof opts.cohortLabel === \"string\" && opts.cohortLabel.trim().length > 0\n ? opts.cohortLabel.trim()\n : deriveCohortLabel(cohort);\n return [{ cohort, cohortLabel }];\n }\n throw new Error(\"accelerator-batch: at least one cohort required\");\n}\n\n/**\n * Round-robin interleave records by their source cohort. Without this, the\n * per-company `parallelMap` would chew through every yc-w26 candidate before\n * touching Techstars — so the global `limit` enqueue cap (25 by default)\n * would be hit before any non-YC cohort got a chance. Interleaving picks\n * one record per cohort in turn until all cohort lists are exhausted, so\n * the eventual queue has a balanced cross-incubator footprint.\n *\n * Stable: ordering within a cohort matches input order. Empty input → [].\n */\nexport function interleaveByCohort<T extends { cohort: string }>(records: T[]): T[] {\n if (records.length === 0) return [];\n const byCohort = new Map<string, T[]>();\n // Preserve cohort first-seen order so the output is deterministic.\n const order: string[] = [];\n for (const r of records) {\n let list = byCohort.get(r.cohort);\n if (!list) {\n list = [];\n byCohort.set(r.cohort, list);\n order.push(r.cohort);\n }\n list.push(r);\n }\n const out: T[] = [];\n let idx = 0;\n while (out.length < records.length) {\n let pushed = false;\n for (const cohort of order) {\n const list = byCohort.get(cohort);\n if (list && idx < list.length) {\n out.push(list[idx]!);\n pushed = true;\n }\n }\n if (!pushed) break;\n idx++;\n }\n return out;\n}\n\n/** Source-tagged company record. Each entry carries the cohort it was fetched under. */\nexport type TaggedCompanyRecord = CompanyRecord & { cohort: string; cohortLabel: string };\n\n/**\n * Cross-cohort dedupe by company name slug. A company appearing in two\n * cohorts (e.g. a YC alum joining Techstars) is rare but possible — keep the\n * first occurrence so the per-company pipeline doesn't pay enrichment cost\n * twice. Slug = lowercase + whitespace→hyphens + non-alphanumerics stripped,\n * matching the dedupeKey shape downstream.\n */\nexport function dedupeRecordsBySlug<T extends CompanyRecord>(records: T[]): T[] {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const r of records) {\n const slug = r.name\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n if (seen.has(slug)) continue;\n seen.add(slug);\n out.push(r);\n }\n return out;\n}\n\nexport async function runAcceleratorBatchFinder(\n opts: AcceleratorBatchFinderOpts,\n): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const concurrency = opts.concurrency ?? 3;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const cohorts = normalizeCohorts(opts);\n // Source string reflects whether this is a sweep or a single-cohort run.\n // Keeps the per-target `source` column on the queue readable.\n const source =\n cohorts.length === 1\n ? `find:accelerator-batch:${cohorts[0]!.cohort}`\n : `find:accelerator-batch:sweep`;\n\n const result: FinderResult = {\n source,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n // Step 1: discover cohort companies — one adapter call per cohort entry.\n // Per-cohort failures (adapter throws, 0 hits) log and continue; we only\n // halt the run when EVERY cohort came back empty.\n //\n // Parallelized at `concurrency` to keep wall-clock reasonable: with 12\n // websearch cohorts at ~30s each, a sequential loop would burn 6+ minutes\n // of pure discovery before the first per-company pipeline starts. The\n // cost-cap check is best-effort under parallelism — workers in flight\n // can overshoot by ~(concurrency - 1) × (per-cohort cost) — acceptable\n // since the per-company loop also overshoots by the same factor.\n type CohortOutcome = {\n records: TaggedCompanyRecord[];\n summary: { cohort: string; records: number; error?: string };\n };\n const cohortResults = await parallelMap<CohortEntry, CohortOutcome>(\n cohorts,\n concurrency,\n async (entry) => {\n // Best-effort cost-cap check before we start the fetch. Workers in\n // flight at cap-trip time still finish their adapter call.\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n return {\n records: [],\n summary: { cohort: entry.cohort, records: 0, error: \"skipped: cost cap\" },\n };\n }\n const adapterName = pickAdapter(entry.cohort, opts.adapter);\n try {\n const fetched =\n adapterName === \"yc-oss\"\n ? await fetchYcOssBatch(entry.cohort, limit)\n : await fetchAcceleratorSearch(entry.cohort, entry.cohortLabel, limit);\n result.costUsd += fetched.costUsd;\n if (fetched.records.length === 0) {\n return {\n records: [],\n summary: {\n cohort: entry.cohort,\n records: 0,\n error: fetched.diagnostic ?? \"no records\",\n },\n };\n }\n // Tag each record with its source cohort so the per-company callback\n // can build dedupe keys, rejection payloads, and final targets without\n // needing the cohort plumbed through opts.\n const tagged = fetched.records.map<TaggedCompanyRecord>((r) => ({\n ...r,\n cohort: entry.cohort,\n cohortLabel: entry.cohortLabel,\n }));\n return {\n records: tagged,\n summary: { cohort: entry.cohort, records: fetched.records.length },\n };\n } catch (err) {\n const message = ((err as Error).message ?? \"\").slice(0, 120);\n logEvent(\n \"error.swallowed\",\n { kind: \"accelerator-batch.adapter\", cohort: entry.cohort, message_120: message },\n \"warn\",\n );\n return {\n records: [],\n summary: { cohort: entry.cohort, records: 0, error: message },\n };\n }\n },\n );\n\n // Reassemble in registry order so the per-cohort summary lines up with\n // the operator's config visually.\n const allRecords: TaggedCompanyRecord[] = [];\n const perCohortOutcomes: Array<{ cohort: string; records: number; error?: string }> = [];\n for (const r of cohortResults) {\n allRecords.push(...r.records);\n perCohortOutcomes.push(r.summary);\n }\n result.perCohort = perCohortOutcomes;\n\n // Interleave + cross-cohort dedupe. Interleave first so the per-company\n // pipeline sees a balanced rotation; dedupe by slug after so a company\n // appearing in two cohorts gets enriched once (kept under its first\n // surfacing cohort).\n const deduped = dedupeRecordsBySlug(interleaveByCohort(allRecords));\n result.candidates = deduped.length;\n if (deduped.length === 0) {\n // Every cohort came back empty. Surface the right diagnostic:\n // - Single-cohort run → the adapter's own message\n // - All cohorts skipped due to cost cap → that\n // - Otherwise → generic sweep-empty\n if (cohorts.length === 1) {\n const first = perCohortOutcomes[0];\n result.halted = first?.error ?? \"adapter returned 0 records\";\n } else if (\n opts.maxCostUsd != null &&\n perCohortOutcomes.every((o) => o.error === \"skipped: cost cap\")\n ) {\n result.halted = `max-cost cap (${opts.maxCostUsd}) during discovery`;\n } else {\n result.halted = `all ${cohorts.length} cohorts returned 0 candidates`;\n }\n return result;\n }\n\n // Step 2: per-company pipeline (parallel, ICP-first like github-topics).\n // `halted` is a soft cap — workers may overshoot by up to (concurrency - 1)\n // candidates. Acceptable at our scale.\n let halted = false;\n\n await parallelMap(deduped, concurrency, async (record) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n\n const dedupeKey = makeDedupeKey(record, record.cohort);\n if (ledger.isQueueDuplicate(PLAY_NAME, dedupeKey)) {\n result.droppedDuplicate++;\n return;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n return;\n }\n\n // ICP filter — cheapest gate first ($0.001). Uses the structured\n // one-liner + tags so the classifier sees more signal than a bare title.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: record.name,\n url: record.website ?? record.ycUrl,\n summary: buildIcpSummary(record),\n },\n });\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: rejectionPayload(record, record.cohort),\n dedupeKey,\n source,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${record.cohortLabel} — ${filter.reason}`,\n });\n return;\n }\n\n // Resolve a founder name for this record. yc-oss directory rows ship\n // without one; the SDK's findEmail requires `full_name` (or first+last)\n // so we MUST acquire a person name before the enrichment call.\n //\n // Strategy: webRead the YC profile page (or fall back to the company\n // website) and run the same `accelerator-launch-extract` prompt the\n // websearch adapter uses. ~$0.02 per ICP-pass — only paid for candidates\n // that survived the cheaper ICP gate.\n let founderName = record.founderName?.trim() || null;\n let resolvedLinkedin: string | null = isLinkedInProfileUrl(record.founderLinkedinUrl)\n ? record.founderLinkedinUrl\n : null;\n let resolvedPhone: string | null = record.founderPhone ?? null;\n if (!founderName) {\n const resolved = await resolveFounderName(record);\n result.costUsd += resolved.costUsd;\n founderName = resolved.founderName;\n resolvedLinkedin = resolvedLinkedin ?? resolved.linkedinUrl;\n resolvedPhone = resolvedPhone ?? resolved.phone;\n }\n if (!founderName) {\n result.droppedEnrichment++;\n return;\n }\n\n const domain = record.website ? urlDomain(record.website) : null;\n if (!domain) {\n result.droppedEnrichment++;\n return;\n }\n const skip = shouldSkipFindEmail({ fullName: founderName, companyDomain: domain });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n return;\n }\n const found = await findEmail(\n { fullName: founderName, companyDomain: domain },\n { playName: PLAY_NAME },\n );\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n return;\n }\n const email = found.result.email;\n // Prefer the SDK's resolved name when available — it's the actual owner of\n // the email — and fall back to the founder name we resolved upstream.\n const fullName = found.result.full_name?.trim() || founderName;\n\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey, prospectEmail: email })) {\n result.droppedDuplicate++;\n return;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"accelerator-batch\",\n });\n result.costUsd += enr.costUsd;\n const phone = resolvedPhone ?? enr.phone;\n let linkedinUrl = resolvedLinkedin ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName,\n disambiguators: [record.name],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"accelerator-batch\",\n });\n }\n\n const target: AcceleratorBatchTarget = {\n name: fullName,\n email,\n company: record.name,\n cohort: record.cohort,\n ...(record.ycUrl\n ? { launchUrl: record.ycUrl }\n : record.website\n ? { launchUrl: record.website }\n : {}),\n ...(record.oneLiner ? { productOneLiner: record.oneLiner } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n // Stamp the sender's own cohort (+ offer) onto the row so the play can\n // draft inline without a run-level senderCohort — mirrors yourEdge.\n ...(opts.senderCohort ? { senderCohort: opts.senderCohort } : {}),\n ...(opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source,\n notes: `${record.cohortLabel} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n });\n\n return result;\n}\n\n/**\n * Pick which adapter handles the cohort. yc-* tags hit the free yc-oss\n * directory; everything else falls back to web search. An explicit override\n * always wins so founders can force a path for testing.\n */\nexport function pickAdapter(cohort: string, override?: string): \"yc-oss\" | \"websearch\" {\n if (override === \"yc-oss\" || override === \"websearch\") return override;\n if (/^yc-/i.test(cohort.trim())) return \"yc-oss\";\n return \"websearch\";\n}\n\nfunction makeDedupeKey(record: CompanyRecord, cohort: string): string {\n const slug = record.name\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n return `${slug}|${cohort}`;\n}\n\nfunction rejectionPayload(record: CompanyRecord, cohort: string): Record<string, unknown> {\n return {\n company: record.name,\n cohort,\n ...(record.ycUrl\n ? { launchUrl: record.ycUrl }\n : record.website\n ? { launchUrl: record.website }\n : {}),\n ...(record.oneLiner ? { oneLiner: record.oneLiner } : {}),\n };\n}\n\nfunction buildIcpSummary(record: CompanyRecord): string {\n const parts: string[] = [];\n if (record.oneLiner) parts.push(record.oneLiner);\n if (record.longDescription) parts.push(record.longDescription.slice(0, 600));\n if (record.industry) parts.push(`Industry: ${record.industry}`);\n if (record.tags.length > 0) parts.push(`Tags: ${record.tags.join(\", \")}`);\n return parts.join(\"\\n\\n\");\n}\n\n/**\n * webRead a per-company URL (YC profile preferred, company website as\n * fallback) and run the `accelerator-launch-extract` prompt to grab a\n * founder name. Returns `{founderName: null}` if no URL is available, the\n * read fails, or the LLM can't surface a name.\n *\n * Only called for ICP-passing candidates so we don't pay this cost on\n * candidates the cheap classifier already rejected.\n */\nexport async function resolveFounderName(record: CompanyRecord): Promise<{\n founderName: string | null;\n linkedinUrl: string | null;\n phone: string | null;\n costUsd: number;\n}> {\n const url = record.ycUrl ?? record.website;\n if (!url) return { founderName: null, linkedinUrl: null, phone: null, costUsd: 0 };\n let costUsd = 0;\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n costUsd += read.result.cost ?? 0;\n const system = loadPrompt(\"accelerator-launch-extract\");\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url,\n company: record.name,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 400,\n });\n const extract = parseAcceleratorLaunchExtract(llm.content);\n const name = extract.founderName?.trim();\n const linkedinUrl = extract.linkedinUrl?.trim() || null;\n return {\n founderName: name && name.length > 0 ? name : null,\n linkedinUrl: isLinkedInProfileUrl(linkedinUrl) ? linkedinUrl : null,\n phone: extract.phone?.trim() || null,\n costUsd,\n };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-batch.resolveFounderName\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return { founderName: null, linkedinUrl: null, phone: null, costUsd };\n }\n}\n","import { findEmail, getLedger, logEvent, verifyEmail, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { JobChangeTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, JobChangeExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"job-change\";\nconst SOURCE = \"find:job-change\";\n\nexport interface JobChangeFinderOpts extends RunOpts {\n /**\n * Target personas to search for (e.g. \"VP Engineering\", \"Head of Growth\").\n * Each persona gets one webSearch query combined with sinceDays.\n */\n personas?: string[];\n /**\n * Optional list of company-name filters to bias results toward (e.g. ICP companies).\n * If empty, casts a wider net per persona.\n */\n companies?: string[];\n /** Days back to bias the search query. Default 14. */\n sinceDays?: number;\n}\n\nconst DEFAULT_PERSONAS = [\n \"VP Engineering\",\n \"Head of Growth\",\n \"Director of Product\",\n \"Chief of Staff\",\n];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runJobChangeFinder(opts: JobChangeFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 14;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"job-change-extract\");\n const personas = opts.personas && opts.personas.length > 0 ? opts.personas : DEFAULT_PERSONAS;\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const seenUrls = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"last week\" : `last ${sinceDays} days`;\n\n for (const persona of personas) {\n if (hits.length >= limit * 2) break;\n const companyClause =\n opts.companies && opts.companies.length > 0\n ? ` (${opts.companies.map((c) => `\"${c}\"`).join(\" OR \")})`\n : \"\";\n const query = `\"joined as ${persona}\"${companyClause} ${sincePhrase}`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seenUrls.has(hit.url)) continue;\n seenUrls.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"job-change.webSearch\",\n persona,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: JobChangeExtract;\n try {\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n title: hit.title,\n description: hit.description,\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseJobChangeExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"job-change.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.fullName || !extract.newRole || !extract.newCompany) {\n result.droppedEnrichment++;\n continue;\n }\n\n const domain = extract.newCompanyDomain ?? urlDomain(hit.url);\n if (!domain) {\n result.droppedEnrichment++;\n continue;\n }\n const skip = shouldSkipFindEmail({ fullName: extract.fullName, companyDomain: domain });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n continue;\n }\n\n const found = await findEmail(\n { fullName: extract.fullName, companyDomain: domain },\n { playName: PLAY_NAME },\n );\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n continue;\n }\n const email = found.result.email;\n\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"job-change\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.fullName,\n disambiguators: [extract.newCompany],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"job-change\",\n });\n }\n\n const target: JobChangeTarget = {\n name: extract.fullName,\n email,\n newRole: extract.newRole,\n newCompany: extract.newCompany,\n ...(extract.previousRole ? { previousRole: extract.previousRole } : {}),\n ...(extract.previousCompany ? { previousCompany: extract.previousCompany } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.fullName} → ${extract.newRole} @ ${extract.newCompany} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function parseJobChangeExtract(raw: string): JobChangeExtract {\n return tryParseJsonObject<JobChangeExtract>(raw, {\n fullName: null,\n newRole: null,\n newCompany: null,\n newCompanyDomain: null,\n previousRole: null,\n previousCompany: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { findEmail, getLedger, logEvent, verifyEmail, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { HiringSignalTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, HiringSignalExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"hiring-signal\";\nconst SOURCE = \"find:hiring-signal\";\n\nconst ATS_DOMAIN_HINTS = [\n \"boards.greenhouse.io\",\n \"jobs.lever.co\",\n \"apply.workable.com\",\n \"jobs.ashbyhq.com\",\n \"ashbyhq.com\",\n];\n\nexport interface HiringSignalFinderOpts extends RunOpts {\n /** Roles to scan for. Default: [\"Staff Engineer\",\"ML Engineer\",\"Solutions Engineer\"]. */\n roles?: string[];\n /** Optional company-name filter to bias results. */\n companies?: string[];\n /**\n * The \"your one-line claim\" that goes onto every queued target — required for the\n * downstream hiring-signal play. If unset, we fall back to a generic placeholder.\n */\n yourClaim?: string;\n /** Days back to bias the search query. Default 14. */\n sinceDays?: number;\n}\n\nconst DEFAULT_ROLES = [\"Staff Engineer\", \"ML Engineer\", \"Solutions Engineer\"];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runHiringSignalFinder(opts: HiringSignalFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 14;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"hiring-signal-extract\");\n const roles = opts.roles && opts.roles.length > 0 ? opts.roles : DEFAULT_ROLES;\n // No hardcoded fallback claim — a generic one would assert a product capability\n // the founder may not have. The trigger's readiness gate blocks the scheduled\n // path; this guards the CLI/direct path so an empty claim never ships.\n const yourClaim = (opts.yourClaim ?? \"\").trim();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n if (!yourClaim) {\n result.halted = \"set `yourClaim` in the hiring-signal config\";\n return result;\n }\n\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"this week\" : `last ${sinceDays} days`;\n const domainCache = new Map<string, string | null>();\n\n for (const role of roles) {\n if (hits.length >= limit * 2) break;\n const companyClause =\n opts.companies && opts.companies.length > 0\n ? ` (${opts.companies.map((c) => `\"${c}\"`).join(\" OR \")})`\n : \"\";\n const query = `\"${role}\"${companyClause} ${sincePhrase} (site:boards.greenhouse.io OR site:jobs.lever.co OR site:apply.workable.com OR site:jobs.ashbyhq.com)`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seen.has(hit.url) || !isAtsUrl(hit.url)) continue;\n seen.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"hiring-signal.webSearch\",\n role,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: HiringSignalExtract;\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseHiringSignalExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"hiring-signal.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.jobTitle || !extract.company) {\n result.droppedEnrichment++;\n continue;\n }\n\n let domain = extract.companyDomain;\n if (!domain) {\n const resolved = await resolveCorporateDomain(extract.company, hit.url, domainCache);\n domain = resolved.domain;\n result.costUsd += resolved.costUsd;\n }\n if (!domain) {\n result.droppedEnrichment++;\n continue;\n }\n\n // Email target = the hiring manager when extracted, else fall back to a\n // best-effort search on the company domain (no name).\n const managerName =\n extract.hiringManagerName && extract.hiringManagerName.length > 0\n ? extract.hiringManagerName\n : null;\n const skip = shouldSkipFindEmail({ fullName: managerName, companyDomain: domain });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n continue;\n }\n const findInput = managerName\n ? { fullName: managerName, companyDomain: domain }\n : { companyDomain: domain };\n const found = await findEmail(findInput, { playName: PLAY_NAME });\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n continue;\n }\n const email = found.result.email;\n\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n const recipientName = extract.hiringManagerName ?? found.result.full_name ?? null;\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"hiring-signal\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl && recipientName) {\n linkedinUrl = await findLinkedInUrl({\n fullName: recipientName,\n disambiguators: [extract.company],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"hiring-signal\",\n });\n }\n\n const target: HiringSignalTarget = {\n name: recipientName ?? \"team\",\n email,\n company: extract.company,\n jobTitle: extract.jobTitle,\n jobPostUrl: extract.jobUrl ?? hit.url,\n yourClaim,\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.company} hiring \"${extract.jobTitle}\"${extract.team ? ` (${extract.team})` : \"\"} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function isAtsUrl(url: string): boolean {\n try {\n const host = new URL(url).hostname.toLowerCase();\n return ATS_DOMAIN_HINTS.some((h) => host === h || host.endsWith(`.${h}`));\n } catch {\n return false;\n }\n}\n\nconst SOCIAL_OR_ATS_HOSTS = new Set([\n \"linkedin.com\",\n \"twitter.com\",\n \"x.com\",\n \"facebook.com\",\n \"instagram.com\",\n \"youtube.com\",\n \"github.com\",\n \"wikipedia.org\",\n \"crunchbase.com\",\n \"glassdoor.com\",\n \"indeed.com\",\n \"builtin.com\",\n \"medium.com\",\n \"substack.com\",\n ...ATS_DOMAIN_HINTS,\n]);\n\n/**\n * Try to find the company's actual corporate domain when the LLM didn't\n * extract one from the job page. webSearch is ~$0.01/call; we cache by\n * company name within a single finder run so repeated postings from the same\n * employer don't double-charge.\n */\nasync function resolveCorporateDomain(\n company: string,\n jobUrl: string,\n cache: Map<string, string | null>,\n): Promise<{ domain: string | null; costUsd: number }> {\n const key = company.trim().toLowerCase();\n if (cache.has(key)) return { domain: cache.get(key) ?? null, costUsd: 0 };\n let costUsd = 0;\n let domain: string | null = null;\n try {\n const search = await webSearch(\n { query: `\"${company}\" official site`, maxResults: 5 },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n const host = pickCorporateHost(hit.url);\n if (host) {\n domain = host;\n break;\n }\n }\n } catch {\n // fall through to slug guess\n }\n if (!domain) domain = slugFallback(jobUrl);\n cache.set(key, domain);\n return { domain, costUsd };\n}\n\nexport function pickCorporateHost(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const host = new URL(url).hostname.replace(/^www\\./, \"\").toLowerCase();\n if (SOCIAL_OR_ATS_HOSTS.has(host)) return null;\n if ([...SOCIAL_OR_ATS_HOSTS].some((h) => host.endsWith(`.${h}`))) return null;\n return host;\n } catch {\n return null;\n }\n}\n\nexport function slugFallback(jobUrl: string): string | null {\n try {\n const u = new URL(jobUrl);\n const seg = u.pathname.split(\"/\").find((s) => s.length > 0);\n if (seg && /^[a-z0-9-]+$/.test(seg)) return `${seg}.com`;\n } catch {\n // ignore\n }\n return null;\n}\n\nexport function parseHiringSignalExtract(raw: string): HiringSignalExtract {\n return tryParseJsonObject<HiringSignalExtract>(raw, {\n jobTitle: null,\n jobUrl: null,\n company: null,\n companyDomain: null,\n hiringManagerName: null,\n hiringManagerRole: null,\n team: null,\n postedAt: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { findEmail, getLedger, logEvent, verifyEmail, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { PodcastGuestTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, PodcastGuestExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"podcast-guest\";\nconst SOURCE = \"find:podcast-guest\";\n\nexport interface PodcastGuestFinderOpts extends RunOpts {\n /** Podcasts to search. Default a small set of YC-adjacent shows. */\n podcasts?: string[];\n /** Days back to bias the search query. Default 21. */\n sinceDays?: number;\n /** Skip the deeper webRead step (cheaper but less accurate). */\n skipRead?: boolean;\n}\n\nconst DEFAULT_PODCASTS = [\n \"Latent Space\",\n \"Lenny's Podcast\",\n \"20VC\",\n \"Acquired\",\n \"Invest Like the Best\",\n];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runPodcastGuestFinder(opts: PodcastGuestFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 21;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"podcast-guest-extract\");\n const podcasts = opts.podcasts && opts.podcasts.length > 0 ? opts.podcasts : DEFAULT_PODCASTS;\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"this week\" : `last ${sinceDays} days`;\n\n for (const show of podcasts) {\n if (hits.length >= limit * 2) break;\n const query = `\"${show}\" episode guest ${sincePhrase}`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seen.has(hit.url)) continue;\n seen.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"podcast-guest.webSearch\",\n show,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: PodcastGuestExtract;\n try {\n let payload: Record<string, unknown> = {\n url: hit.url,\n title: hit.title,\n description: hit.description,\n };\n if (!opts.skipRead) {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n payload = { ...payload, markdown: (read.result.markdown ?? \"\").slice(0, 12000) };\n }\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: JSON.stringify(payload) },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parsePodcastGuestExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"podcast-guest.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.guestName || !extract.guestCompanyDomain || !extract.podcastName) {\n result.droppedEnrichment++;\n continue;\n }\n const skip = shouldSkipFindEmail({\n fullName: extract.guestName,\n companyDomain: extract.guestCompanyDomain,\n });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n continue;\n }\n\n const found = await findEmail(\n { fullName: extract.guestName, companyDomain: extract.guestCompanyDomain },\n { playName: PLAY_NAME },\n );\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n continue;\n }\n const email = found.result.email;\n\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"podcast-guest\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.guestName,\n disambiguators: [extract.podcastName],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"podcast-guest\",\n });\n }\n\n const target: PodcastGuestTarget = {\n name: extract.guestName,\n email,\n company: extract.guestCompany ?? extract.guestCompanyDomain,\n podcast: extract.podcastName,\n episodeTitle: extract.episodeTitle ?? hit.title,\n hookQuote: (extract.summary ?? hit.description ?? \"\").slice(0, 240),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.guestName} on ${extract.podcastName} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function parsePodcastGuestExtract(raw: string): PodcastGuestExtract {\n return tryParseJsonObject<PodcastGuestExtract>(raw, {\n podcastName: null,\n episodeTitle: null,\n episodeUrl: null,\n guestName: null,\n guestRole: null,\n guestCompany: null,\n guestCompanyDomain: null,\n publishedAt: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { BreakupReviveTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"breakup-revive\";\nconst SOURCE = \"find:breakup-revive\";\n\nexport interface BreakupReviveFinderOpts extends RunOpts {\n /** Min days since last activity to consider cold. Default 60. */\n minDays?: number;\n /** Max days since last activity to consider revivable. Default 90. */\n maxDays?: number;\n}\n\n/**\n * Scan the local ledger for cold prospects (no activity in the last\n * min/maxDays window) and enqueue them into target_queue. No LLM calls,\n * no OneShot spend — this is a ledger-only finder that reuses the same\n * review → approve → drain lifecycle as every other finder.\n */\nexport function runBreakupReviveFinder(opts: BreakupReviveFinderOpts): FinderResult {\n const limit = opts.limit ?? 25;\n const minDays = opts.minDays ?? 60;\n const maxDays = opts.maxDays ?? 90;\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const cold = ledger.listColdProspects({\n minDaysSinceLastEvent: minDays,\n maxDaysSinceLastEvent: maxDays,\n limit: limit * 2, // pull extra; we'll drop any already in the queue\n });\n result.candidates = cold.length;\n\n for (const p of cold) {\n if (result.enqueued >= limit) break;\n if (!p.email) {\n result.droppedEnrichment++;\n continue;\n }\n\n // Dedupe key = prospect id so re-running doesn't re-enqueue the same\n // person until their previous queue row is archived or expired.\n const dedupeKey = `prospect:${p.id}`;\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey, prospectEmail: undefined })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const daysCold = p.last_event_at\n ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1000))\n : 0;\n\n const target: BreakupReviveTarget = {\n name: p.name,\n email: p.email,\n company: p.company,\n daysCold,\n lastEventAt: p.last_event_at,\n linkedinUrl: p.linkedin_url ?? null,\n phone: p.phone ?? null,\n };\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source: SOURCE,\n notes: `${daysCold}d cold${p.company ? ` — ${p.company}` : \"\"}`,\n });\n if (id != null) {\n // Link the queue row to the prospect right away so the /queue page\n // can surface the connection without the drain-time backfill dance.\n try {\n ledger.setQueueProspectId(id, p.id);\n } catch {\n // best-effort — drain.ts will also try to backfill\n }\n result.enqueued++;\n } else {\n result.droppedDuplicate++;\n }\n }\n\n return result;\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\n\nexport interface GitHubSearchRepo {\n /** html_url, normalized to canonical github.com/<owner>/<repo>. */\n url: string;\n /** owner/repo. */\n fullName: string;\n description: string | null;\n stars: number;\n /** Self-tagged GitHub topic slugs from the repo's metadata. */\n topics: string[];\n language: string | null;\n pushedAt: string;\n}\n\n/**\n * Search the GitHub Search API for repos tagged with a topic.\n *\n * Uses `GITHUB_TOKEN` from env if set (30 req/min, exempt from secondary\n * abuse detection); falls back to unauthenticated (10 req/min, AND vulnerable\n * to GitHub silently returning empty results when soft-blocked for \"too many\"\n * unauth queries from the same IP — no 429, no error, just zero hits).\n *\n * Returns [] on:\n * - 422 (invalid query — usually a malformed topic slug)\n * - 403 (GitHub's actual unauth rate-limit signal)\n * - 429 (explicit rate-limit)\n * - any other non-2xx\n * - network error\n * - malformed JSON\n *\n * Same fault-tolerance pattern as `fetchGitHubUser`.\n */\nexport async function searchTopicRepos(args: {\n topic: string;\n minStars: number;\n /** ISO date string (YYYY-MM-DD) for the `pushed:>=` filter. */\n pushedSinceIso: string;\n /** Page size. <=100. */\n perPage: number;\n}): Promise<GitHubSearchRepo[]> {\n const q = `topic:${args.topic} stars:>=${args.minStars} pushed:>=${args.pushedSinceIso}`;\n const url =\n `https://api.github.com/search/repositories?q=${encodeURIComponent(q)}` +\n `&sort=updated&order=desc&per_page=${Math.max(1, Math.min(100, args.perPage))}`;\n try {\n const res = await fetch(url, { headers: githubHeaders() });\n if (!res.ok) {\n logEvent(\"github.topic.search\", {\n topic: args.topic,\n ok: false,\n status: res.status,\n });\n return [];\n }\n const json = (await res.json()) as Record<string, unknown>;\n const items = Array.isArray(json[\"items\"])\n ? (json[\"items\"] as Array<Record<string, unknown>>)\n : [];\n const repos = items.map(parseSearchItem).filter((r): r is GitHubSearchRepo => r !== null);\n // Detect GitHub's silent soft-block: 200 OK + empty items + total_count\n // reported as 0 even on slugs that should match (e.g. `langchain`). When\n // the unauth IP gets flagged for abuse, this is the failure mode — no\n // 429, just 0 hits forever for an hour or two. Surface a hint so the\n // caller can stop hammering and the operator can act (set GITHUB_TOKEN).\n const totalCount =\n typeof json[\"total_count\"] === \"number\" ? (json[\"total_count\"] as number) : null;\n const authed = Boolean(process.env[\"GITHUB_TOKEN\"]);\n const ratelimitHint = !authed && repos.length === 0 && totalCount === 0;\n logEvent(\"github.topic.search\", {\n topic: args.topic,\n ok: true,\n count: repos.length,\n total_count: totalCount,\n authed,\n ...(ratelimitHint ? { hint: \"0 hits + unauth — likely soft-blocked; set GITHUB_TOKEN\" } : {}),\n });\n return repos;\n } catch (err) {\n logEvent(\n \"github.topic.search\",\n {\n topic: args.topic,\n ok: false,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return [];\n }\n}\n\n/**\n * Build request headers for the GitHub REST API. Adds `Authorization: Bearer`\n * when `GITHUB_TOKEN` is set, lifting our quota from 10 req/min unauth →\n * 30 req/min for search (5,000/hour for everything else) AND making us\n * exempt from secondary abuse detection on the search endpoint.\n *\n * Exported so `_github-user.ts` can use the same auth shape.\n */\nexport function githubHeaders(): Record<string, string> {\n const headers: Record<string, string> = { Accept: \"application/vnd.github+json\" };\n const token = process.env[\"GITHUB_TOKEN\"];\n if (token && token.length > 0) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n return headers;\n}\n\n/** Parse one search-API `items[]` entry. Returns null on missing required fields. */\nexport function parseSearchItem(raw: Record<string, unknown>): GitHubSearchRepo | null {\n const htmlUrl = typeof raw[\"html_url\"] === \"string\" ? (raw[\"html_url\"] as string) : null;\n const fullName = typeof raw[\"full_name\"] === \"string\" ? (raw[\"full_name\"] as string) : null;\n if (!htmlUrl || !fullName) return null;\n return {\n url: htmlUrl,\n fullName,\n description: typeof raw[\"description\"] === \"string\" ? (raw[\"description\"] as string) : null,\n stars: typeof raw[\"stargazers_count\"] === \"number\" ? (raw[\"stargazers_count\"] as number) : 0,\n topics: Array.isArray(raw[\"topics\"])\n ? (raw[\"topics\"] as unknown[]).filter((t): t is string => typeof t === \"string\")\n : [],\n language: typeof raw[\"language\"] === \"string\" ? (raw[\"language\"] as string) : null,\n pushedAt: typeof raw[\"pushed_at\"] === \"string\" ? (raw[\"pushed_at\"] as string) : \"\",\n };\n}\n\n/**\n * Format a date as YYYY-MM-DD for the GitHub `pushed:>=` query operator.\n * Pulled out so callers can inject `now` for testing.\n */\nexport function isoDateNDaysAgo(days: number, now: Date = new Date()): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString().slice(0, 10);\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\nexport interface GitHubUserInfo {\n login: string;\n /** Human-friendly display name (e.g. \"Ada Lovelace\") when set. Falls back\n * to null — many users leave this blank. */\n name: string | null;\n email: string | null;\n /** A bare hostname extracted from the user's blog URL when present. */\n blogDomain: string | null;\n /** company string from the user's profile (e.g. \"@acme\" or \"Acme Inc\"). */\n company: string | null;\n}\n\n/**\n * Per-process cache of GitHub user lookups. Keyed by login (lowercased to\n * dedupe `Foo` vs `foo` from different combos that surface the same author).\n * `null` is a real cached value — it means we've already tried and the API\n * returned 404 / 429 / network error, so don't retry within the run.\n */\nconst cache = new Map<string, GitHubUserInfo | null>();\n\n/** Test-only: drop the in-memory cache between cases. */\nexport function _resetGitHubUserCache(): void {\n cache.clear();\n}\n\n/**\n * Fetch a GitHub user's public profile via the unauthenticated REST API.\n * Returns null on 404, 403 (GitHub's actual unauth rate-limit signal), 429,\n * any other non-2xx, network error, or malformed response — caller should\n * fall through to the next enrichment strategy rather than treat this as\n * fatal.\n *\n * Unauthenticated quota is 60 req/hour per IP, which is fine for the ~50\n * candidates a single github-topics run inspects. Same-author dedupe via\n * the cache keeps actual fetches down further (a popular author appearing\n * in multiple combos hits the API once).\n */\nexport async function fetchGitHubUser(login: string): Promise<GitHubUserInfo | null> {\n const key = login.toLowerCase();\n if (cache.has(key)) return cache.get(key) ?? null;\n try {\n const res = await fetch(`https://api.github.com/users/${encodeURIComponent(login)}`, {\n headers: githubHeaders(),\n });\n if (res.status === 404) {\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: 404 });\n return null;\n }\n if (res.status === 429 || res.status === 403) {\n // 403 with rate-limit headers is GitHub's actual rate-limit signal for\n // unauthenticated callers. Treat both as \"back off, try later.\"\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: res.status, rate_limited: true });\n return null;\n }\n if (!res.ok) {\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: res.status });\n return null;\n }\n const json = (await res.json()) as Record<string, unknown>;\n const info: GitHubUserInfo = {\n login: typeof json[\"login\"] === \"string\" ? (json[\"login\"] as string) : login,\n name:\n typeof json[\"name\"] === \"string\" && json[\"name\"] !== \"\" ? (json[\"name\"] as string) : null,\n email:\n typeof json[\"email\"] === \"string\" && json[\"email\"] !== \"\"\n ? (json[\"email\"] as string)\n : null,\n blogDomain: extractBlogDomain(json[\"blog\"]),\n company:\n typeof json[\"company\"] === \"string\" && json[\"company\"] !== \"\"\n ? (json[\"company\"] as string)\n : null,\n };\n cache.set(key, info);\n logEvent(\"github.user.fetch\", {\n login,\n ok: true,\n has_email: info.email !== null,\n has_blog: info.blogDomain !== null,\n });\n return info;\n } catch (err) {\n cache.set(key, null);\n logEvent(\n \"github.user.fetch\",\n {\n login,\n ok: false,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Normalize a profile `blog` field to a bare hostname.\n *\n * GitHub stores whatever the user typed, so this needs to handle:\n * `https://acme.dev`, `acme.dev`, `www.acme.dev`, `https://acme.dev/about`,\n * `acme.dev?utm=x`, and (commonly) the empty string. Returns null on anything\n * that doesn't look like a usable hostname.\n */\nexport function extractBlogDomain(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return null;\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n try {\n const u = new URL(withScheme);\n const host = u.hostname.replace(/^www\\./i, \"\").toLowerCase();\n if (host.length === 0 || !host.includes(\".\")) return null;\n return host;\n } catch {\n return null;\n }\n}\n\n/**\n * Pull the `<owner>` segment out of a `https://github.com/<owner>/<repo>` URL\n * so callers don't have to re-implement URL parsing. Returns null if the URL\n * isn't a normalized GitHub repo URL.\n */\nexport function ownerFromRepoUrl(repoUrl: string): string | null {\n try {\n const u = new URL(repoUrl);\n if (!/(^|\\.)github\\.com$/i.test(u.hostname)) return null;\n const parts = u.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 1) return null;\n return parts[0] ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Pull the `<repo>` segment out of a `https://github.com/<owner>/<repo>` URL.\n * Returns null when the URL doesn't have a repo segment (org page, gist, etc).\n */\nexport function repoNameFromRepoUrl(repoUrl: string): string | null {\n try {\n const u = new URL(repoUrl);\n if (!/(^|\\.)github\\.com$/i.test(u.hostname)) return null;\n const parts = u.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n return parts[1] ?? null;\n } catch {\n return null;\n }\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\n/**\n * Deterministic stack detection from a GitHub repo's manifest files. Replaces\n * the older webRead + LLM-extract path that was unreliable in two ways: (1)\n * webRead timed out on ~44% of GitHub README pages (JS-rendered), and (2)\n * READMEs are marketing copy that doesn't always match what the code\n * actually imports. Manifests are authoritative — if `openai` is in\n * `package.json`, the project uses OpenAI.\n *\n * Files we scan in priority order: package.json (npm), pyproject.toml +\n * requirements.txt (Python), .env.example (env-var leakage). Each fetch is\n * independent + best-effort; missing files just contribute nothing.\n *\n * The `vocab` argument is the founder-controlled vendor list. Each vocab\n * string is substring-matched (case-insensitive) against the union of all\n * extracted manifest tokens — `twilio` matches `twilio`, `twilio-node`,\n * `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is no hardcoded\n * vendor catalog; oneshot-gtm is a generic founder tool and competitive\n * vocabularies vary entirely by founder. The strategist proposes vocab\n * populations from the founder's product/ICP context (see\n * `packages/prompts/strategist-trigger.md`).\n *\n * Cost: ~3-4 GitHub API calls per candidate. With `GITHUB_TOKEN` set the\n * 5,000/hr quota is plenty for any practical run.\n */\n\nexport interface StackDetection {\n /** Founder-vocab vendors that matched at least one manifest token. Sorted. */\n detected: string[];\n /** Manifest filenames that were found (for diagnostics + event logging). */\n manifestsFound: string[];\n}\n\n/**\n * Scan a GitHub repo's manifests and return the founder-vocab vendors that\n * match at least one extracted package or env-var-key token.\n */\nexport async function detectRepoStack(args: {\n owner: string;\n repo: string;\n /** Founder's vendor list — substring-matched (case-insensitive) against\n * manifest deps + env-var keys. Empty vocab → empty detection. */\n vocab: string[];\n}): Promise<StackDetection> {\n const { owner, repo, vocab } = args;\n const targets = [\"package.json\", \"pyproject.toml\", \"requirements.txt\", \".env.example\"];\n const fetched = await Promise.all(\n targets.map(async (path) => ({\n path,\n content: await fetchRepoFile(owner, repo, path),\n })),\n );\n\n const allNames = new Set<string>();\n const manifestsFound: string[] = [];\n for (const { path, content } of fetched) {\n if (!content) continue;\n manifestsFound.push(path);\n for (const name of namesFromManifest(path, content)) {\n allNames.add(name.toLowerCase());\n }\n }\n\n // Single transparent matching loop. Each vocab entry is a substring needle\n // searched across every extracted token. Casing doesn't matter (tokens\n // were lowercased on insertion). Substring is intentional: founder typing\n // `twilio` matches `twilio-node`, `@twilio/voice-sdk`, and `TWILIO_*` env\n // keys — three real signals from one vocab entry.\n const detected = new Set<string>();\n for (const v of vocab) {\n const needle = v.toLowerCase();\n if (needle.length === 0) continue;\n for (const n of allNames) {\n if (n.includes(needle)) {\n detected.add(v);\n break;\n }\n }\n }\n\n logEvent(\"github.repo.stack\", {\n owner,\n repo,\n manifests_found: manifestsFound,\n detected_count: detected.size,\n });\n\n return {\n detected: [...detected].toSorted(),\n manifestsFound,\n };\n}\n\n/**\n * Fetch a file from a repo's default branch via the GitHub Contents API.\n * Returns null on any non-2xx (including 404 — file just doesn't exist),\n * network error, or unexpected content type. Same fault-tolerance pattern\n * as `fetchGitHubUser`.\n */\nasync function fetchRepoFile(owner: string, repo: string, path: string): Promise<string | null> {\n const url = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${path}`;\n try {\n const headers = { ...githubHeaders(), Accept: \"application/vnd.github.raw\" };\n const res = await fetch(url, { headers });\n if (!res.ok) return null;\n const text = await res.text();\n // Defensive cap. Manifests are usually < 50KB; anything larger is either\n // a spurious vendored file or a bug. We're only doing substring matches\n // so trimming is safe.\n return text.length > 200_000 ? text.slice(0, 200_000) : text;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract dependency-like name strings from a manifest file's content.\n * Format-aware: each manifest has its own conventions.\n *\n * Exported for unit testing.\n */\nexport function namesFromManifest(path: string, content: string): string[] {\n if (path === \"package.json\") return parsePackageJson(content);\n if (path === \"pyproject.toml\") return parsePyProject(content);\n if (path === \"requirements.txt\") return parseRequirementsTxt(content);\n if (path === \".env.example\") return parseEnvKeys(content);\n return [];\n}\n\n/** Pull `dependencies` + `devDependencies` keys out of a package.json. */\nfunction parsePackageJson(content: string): string[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return [];\n }\n if (!parsed || typeof parsed !== \"object\") return [];\n const obj = parsed as Record<string, unknown>;\n const out: string[] = [];\n for (const key of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const deps = obj[key];\n if (deps && typeof deps === \"object\") {\n out.push(...Object.keys(deps as Record<string, unknown>));\n }\n }\n return out;\n}\n\n/**\n * Pull dep names out of a pyproject.toml. We don't ship a TOML parser — a\n * regex over `name = \"...\"` patterns inside `[project.dependencies]` and\n * Poetry-style `[tool.poetry.dependencies]` sections covers the bulk of\n * real-world files. Fail-soft: missing matches just yield no names.\n */\nfunction parsePyProject(content: string): string[] {\n const out: string[] = [];\n // Poetry: `package_name = \"^1.2.3\"` or `package_name = { version = ... }`\n const poetryRx = /^\\s*([a-zA-Z0-9_\\-.]+)\\s*=\\s*[\"{]/gm;\n let m: RegExpExecArray | null;\n while ((m = poetryRx.exec(content)) !== null) {\n const name = m[1];\n if (name && !RESERVED_PYPROJECT_KEYS.has(name.toLowerCase())) {\n out.push(name);\n }\n }\n // PEP 621: `dependencies = [\"package_name>=1.0\", ...]` — strings inside\n // an array of dependency specifiers.\n const pep621Rx = /[\"']([a-zA-Z0-9_\\-.]+)\\s*(?:[<>=!~][^\"']*)?[\"']/g;\n while ((m = pep621Rx.exec(content)) !== null) {\n const name = m[1];\n if (name && name.length > 1) out.push(name);\n }\n return out;\n}\n\n/**\n * Reserved top-level keys in pyproject.toml that aren't dependencies. The\n * Poetry regex is loose enough to match these; this set filters them out.\n */\nconst RESERVED_PYPROJECT_KEYS = new Set([\n \"name\",\n \"version\",\n \"description\",\n \"readme\",\n \"license\",\n \"authors\",\n \"maintainers\",\n \"homepage\",\n \"repository\",\n \"documentation\",\n \"keywords\",\n \"classifiers\",\n \"requires-python\",\n \"python\",\n \"dependencies\",\n \"optional-dependencies\",\n \"scripts\",\n \"entry-points\",\n \"urls\",\n \"include\",\n \"exclude\",\n \"build-backend\",\n \"build-system\",\n \"requires\",\n]);\n\n/** First token of each non-comment line in requirements.txt. */\nfunction parseRequirementsTxt(content: string): string[] {\n const out: string[] = [];\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (line.length === 0 || line.startsWith(\"#\") || line.startsWith(\"-\")) continue;\n // Strip version specifier and extras: `package[extras]==1.0.0` → `package`\n const m = /^([a-zA-Z0-9_\\-.]+)/.exec(line);\n if (m && m[1]) out.push(m[1]);\n }\n return out;\n}\n\n/**\n * Pull env-var keys out of a `.env.example` (or `.env.sample`). Vendor SDKs\n * conventionally name their keys after themselves (`OPENAI_API_KEY`,\n * `TWILIO_ACCOUNT_SID`, etc), so the keys themselves are great signal even\n * when the values are placeholder.\n */\nfunction parseEnvKeys(content: string): string[] {\n const out: string[] = [];\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (line.length === 0 || line.startsWith(\"#\")) continue;\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n out.push(line.slice(0, eq).trim());\n }\n return out;\n}\n","import {\n deepResearchPerson,\n enrichProfile,\n findEmail,\n getLedger,\n logEvent,\n verifyEmail,\n} from \"@oneshot-gtm/core\";\nimport type { CompetitorSwitchTarget, StackConsolidationTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter } from \"./_filter.ts\";\nimport {\n fetchGitHubUser,\n ownerFromRepoUrl,\n repoNameFromRepoUrl,\n type GitHubUserInfo,\n} from \"./_github-user.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { extractFirstPhone, findLinkedInUrl } from \"./_linkedin.ts\";\nimport { detectRepoStack } from \"./_repo-stack.ts\";\nimport type { AgentBuilderExtract, FinderResult } from \"./_types.ts\";\n\n/**\n * Shared per-candidate pipeline for repo-style finders. Today it has one\n * caller (`github-topics`); kept as its own module because the per-candidate\n * body — snippet ICP → GitHub manifest scan + user fetch → minVendors gate →\n * resolveContact (3-tier: extract domain → GitHub user → deepResearchPerson) →\n * verifyEmail → enqueue — is large enough that inlining it back would obscure\n * the finder, and ctx-based parameterisation keeps the door open for future\n * repo finders without re-extracting later.\n *\n * Stack detection used to be a webRead + LLM extract on the README, which\n * (a) timed out ~44% of the time on JS-rendered GitHub pages and (b) read\n * marketing copy that didn't reflect actual code. We now pull the truth\n * directly from package.json / pyproject.toml / requirements.txt /\n * .env.example via the GitHub Contents API. Free, fast, deterministic.\n */\nconst PLAY_NAME = \"stack-consolidation\";\n\nexport interface RepoCandidate {\n /** Normalized github.com/<owner>/<repo>. */\n url: string;\n title: string;\n description: string;\n /**\n * Pre-discovery vendor hints. github-topics leaves this empty — vendors are\n * detected later via `detectRepoStack` against the repo's manifests.\n * Reserved for future repo-finders that arrive with a known vendor signal\n * at discovery time (would short-circuit the manifest scan).\n */\n vendors: string[];\n /**\n * GitHub topic tags (self-tagged by maintainers). github-topics fills these\n * for the snippet ICP signal.\n */\n topics?: string[];\n}\n\nexport interface RepoPipelineCtx {\n icp: string | null;\n /** Founder's vendor list — passed to detectRepoStack as the matching vocabulary. */\n vocab: string[];\n /**\n * Subset of `vocab` the founder competes with head-on. A candidate whose\n * detected stack includes one routes to competitor-switch; otherwise\n * stack-consolidation. Matched case-insensitively. Empty = always\n * stack-consolidation.\n */\n directCompetitors?: string[];\n yourEdge: string;\n minVendors: number;\n useDeepResearch: boolean;\n /** Mutable accumulator. Workers mutate fields on this directly. */\n result: FinderResult;\n /**\n * Boxed flag so workers share the same reference across the parallelMap\n * pool. Soft halt: workers check at the top of each iteration but several\n * may pass before any flips it — over-shoot up to (concurrency-1) is\n * acceptable for the scales we operate at.\n */\n halted: { value: boolean };\n limit: number;\n maxCostUsd: number | undefined;\n /** Receipt source tag, e.g. \"find:github-topics\". */\n sourceTag: string;\n /** Notes-line prefix, e.g. \"github-topic\". */\n notesPrefix: string;\n dryRun: boolean;\n}\n\n/**\n * Process a single candidate through the full pipeline. Mutates ctx.result.\n * Never throws — internal exceptions become droppedEnrichment increments via\n * the surrounding try/catch blocks. Safe to call concurrently across workers.\n */\nexport async function processRepoCandidate(\n hit: RepoCandidate,\n ctx: RepoPipelineCtx,\n): Promise<void> {\n const { result } = ctx;\n if (ctx.halted.value) return;\n if (result.enqueued >= ctx.limit) {\n ctx.halted.value = true;\n return;\n }\n if (ctx.maxCostUsd != null && result.costUsd >= ctx.maxCostUsd) {\n result.halted = `max-cost cap (${ctx.maxCostUsd})`;\n ctx.halted.value = true;\n return;\n }\n const ledger = getLedger();\n // The play isn't known until the stack is detected below, so check both\n // possible routes — a repo enqueued under either play is a duplicate.\n if (\n ledger.isQueueDuplicate(\"stack-consolidation\", hit.url) ||\n ledger.isQueueDuplicate(\"competitor-switch\", hit.url)\n ) {\n result.droppedDuplicate++;\n return;\n }\n\n if (ctx.dryRun) {\n result.enqueued++;\n return;\n }\n\n const accumCost = (c: number | undefined): void => {\n result.costUsd += c ?? 0;\n };\n const errKindPrefix = ctx.sourceTag.replace(/^find:/, \"\");\n\n // 1) ICP on the snippet — cheap pre-filter. Skips the manifest scan +\n // user-fetch + contact-resolution chain on candidates the classifier\n // rejects, which is most of them in practice.\n const snippetFilter = await icpFilter({\n icp: ctx.icp,\n candidate: {\n title: hit.title,\n url: hit.url,\n summary: describeForIcp(hit),\n },\n });\n if (!snippetFilter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { repoUrl: hit.url, title: hit.title, description: hit.description },\n dedupeKey: hit.url,\n source: ctx.sourceTag,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${snippetFilter.reason}`,\n });\n return;\n }\n\n // 2) Stack detection — deterministic GitHub-API scan of manifest files\n // (package.json, pyproject.toml, requirements.txt, .env.example) instead\n // of webRead + LLM extract. Three reasons:\n // - webRead timed out on ~44% of GitHub repo pages (JS-rendered)\n // - READMEs are marketing copy that don't always match what code imports\n // - Manifest scanning is free (counts against GITHUB_TOKEN's 5k/hr) and\n // authoritative — if `openai` is in package.json the repo uses OpenAI\n //\n // Author / company come from the GitHub user profile (also free).\n const owner = ownerFromRepoUrl(hit.url);\n const repoName = repoNameFromRepoUrl(hit.url);\n if (!owner || !repoName) {\n // Shouldn't happen for normalized URLs but defend against drift.\n result.droppedEnrichment++;\n return;\n }\n const [stack, ghUserInfo] = await Promise.all([\n detectRepoStack({ owner, repo: repoName, vocab: ctx.vocab }),\n fetchGitHubUser(owner),\n ]);\n\n if (stack.detected.length < ctx.minVendors) {\n logEvent(\"github-topics.dropped.min_vendors\", {\n repo: `${owner}/${repoName}`,\n detected_count: stack.detected.length,\n manifests_found: stack.manifestsFound,\n min_vendors: ctx.minVendors,\n });\n result.droppedEnrichment++;\n return;\n }\n\n const extract: AgentBuilderExtract = {\n repoUrl: hit.url,\n githubHandle: owner,\n // Prefer the human-friendly name; many GitHub users leave it blank.\n // findEmail downstream short-circuits gracefully when this is null.\n authorFullName: ghUserInfo?.name ?? null,\n authorRole: null, // not derivable from GitHub user API\n companyName: ghUserInfo?.company ?? null,\n // The GitHub blog field is a single bare hostname — we don't have enough\n // signal to know if it's corporate or personal, so map it to companyDomain\n // and leave personalDomain null. The resolveContact fallback chain reads\n // both via `?? null`, so the choice doesn't change behavior.\n companyDomain: ghUserInfo?.blogDomain ?? null,\n personalDomain: null,\n stackDetected: stack.detected,\n summary: null,\n };\n\n // Route by direct-competitor match: a candidate whose detected stack\n // includes one of the founder's head-on rivals gets the competitor-switch\n // motion (\"switch from X\"); everything else is a stack-consolidation\n // (vendor-sprawl) pitch. directCompetitors is empty by default → always\n // stack-consolidation. The resolved play name is used for the rest of this\n // candidate's pipeline (dedupe, receipt tags, enqueue).\n const directSet = new Set((ctx.directCompetitors ?? []).map((s) => s.toLowerCase()));\n const matchedCompetitor = extract.stackDetected.find((v) => directSet.has(v.toLowerCase()));\n const playName = matchedCompetitor ? \"competitor-switch\" : \"stack-consolidation\";\n\n // 3) Resolve a contact (3-tier: extract domain → GitHub user → deepResearch).\n // Pass the already-fetched ghUserInfo so resolveContact doesn't re-fetch.\n const contact = await resolveContact({\n extract,\n repoUrl: hit.url,\n ghUser: ghUserInfo,\n accumCost,\n useDeepResearch: ctx.useDeepResearch,\n errKindPrefix,\n playName,\n });\n if (!contact) {\n result.droppedEnrichment++;\n return;\n }\n\n if (isDuplicate({ playName, dedupeKey: hit.url, prospectEmail: contact.email })) {\n result.droppedDuplicate++;\n return;\n }\n\n // verifyEmail can throw on transient SDK / network errors. Catch and drop\n // the candidate rather than letting one bad call tear down the pool —\n // identical reasoning to the findEmail wrap in resolveContact.tryFindEmail.\n let verified: Awaited<ReturnType<typeof verifyEmail>>;\n try {\n verified = await verifyEmail({ email: contact.email }, { playName });\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.verify_email`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n return;\n }\n accumCost(verified.result.cost ?? 0);\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n // Always-on post-verify enrichment so phone + linkedin land on every\n // queue row. Path B' may have already populated both — skip the call\n // when so. ~$0.005 per call when fired (per OneShot pricing).\n if (!contact.phone || !contact.linkedinUrl) {\n const enr = await enrichVerifiedContact(contact.email, {\n playName,\n errKindPrefix,\n });\n accumCost(enr.costUsd);\n contact.phone = contact.phone ?? enr.phone;\n contact.linkedinUrl = contact.linkedinUrl ?? enr.linkedinUrl;\n }\n\n const stackLine = extract.stackDetected.join(\", \");\n const vendorCount = extract.stackDetected.length;\n const companyFallback = contact.domain ?? contact.email.split(\"@\")[1] ?? \"\";\n const name = extract.authorFullName ?? contact.fullName ?? extract.githubHandle ?? \"there\";\n const company = extract.companyName ?? extract.githubHandle ?? companyFallback;\n const contactExtras = {\n ...(contact.linkedinUrl ? { linkedinUrl: contact.linkedinUrl } : {}),\n ...(contact.phone ? { phone: contact.phone } : {}),\n };\n\n const target: CompetitorSwitchTarget | StackConsolidationTarget = matchedCompetitor\n ? {\n name,\n email: contact.email,\n company,\n competitor: matchedCompetitor,\n evidenceUrl: hit.url,\n // Honest, specific evidence — no fabricated \"auth surfaces\". Single\n // vendor, so no rule-of-three risk. Setting evidenceText also makes\n // competitor-switch skip its (expensive) browser scrape.\n evidenceText: `Their public repo uses ${matchedCompetitor} (found in ${stack.manifestsFound.join(\", \")}).`,\n yourEdge: ctx.yourEdge,\n ...contactExtras,\n }\n : {\n name,\n email: contact.email,\n company,\n vendorStack: stackLine,\n evidenceUrl: hit.url,\n yourEdge: ctx.yourEdge,\n ...contactExtras,\n };\n const notes = truncate(\n `${ctx.notesPrefix}: ${stackLine} (${vendorCount} vendors) — ${snippetFilter.reason}`,\n 220,\n );\n const id = ledger.enqueueTarget({\n playName,\n payload: target,\n dedupeKey: hit.url,\n source: ctx.sourceTag,\n notes,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n}\n\ninterface ResolvedContact {\n email: string;\n /** Best-effort full name from findEmail; null when GitHub provided the email directly. */\n fullName: string | null;\n /** The domain we ultimately used. Null only when we got a direct GitHub email and no blog/extract domain. */\n domain: string | null;\n /** LinkedIn URL surfaced during contact resolution (Path B' webSearch or enrichProfile). Null when none found. */\n linkedinUrl: string | null;\n /** Phone number surfaced during contact resolution (Path C deepResearch enrichment). Null when none found. */\n phone: string | null;\n}\n\n/**\n * Resolve a deliverable contact for a repo candidate.\n *\n * Decision tree (cheapest path first; one paid call per tier):\n * 1. extract has a domain → findEmail($0.005). Done if found.\n * 2. GitHub user provides an email directly → use it (no findEmail spend).\n * 3. (opt-in) deepResearchPerson($0.05, 2-5 min async) with the repo URL +\n * author name — recovers the bucket where nobody has a resolvable\n * companyDomain anywhere.\n *\n * The pre-fetched `ghUser` is required from the pipeline (we already fetch\n * it for the extract construction); accepting it here avoids a duplicate\n * lookup. Pass null if the candidate isn't a GitHub repo.\n */\nexport async function resolveContact(args: {\n extract: AgentBuilderExtract;\n repoUrl: string;\n /** Pre-fetched GitHub user info from the pipeline. Null when unavailable. */\n ghUser: GitHubUserInfo | null;\n accumCost: (c: number | undefined) => void;\n useDeepResearch: boolean;\n /** Used in the deep-research error event kind, e.g. \"github-topics\". */\n errKindPrefix?: string;\n /** Resolved motion play, used to tag the receipts this resolution spends on. */\n playName?: string;\n}): Promise<ResolvedContact | null> {\n const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;\n const errKindPrefix = args.errKindPrefix ?? \"repo-pipeline\";\n const playName = args.playName ?? PLAY_NAME;\n const extractDomain = extract.companyDomain ?? extract.personalDomain ?? null;\n let discoveredLinkedinUrl: string | null = null;\n\n // Path A: extract has a domain. Try findEmail with it.\n if (extractDomain) {\n const direct = await tryFindEmail(extractDomain, extract, accumCost, errKindPrefix, playName);\n if (direct)\n return {\n ...direct,\n domain: extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: null,\n };\n // Fall through.\n }\n\n // Path B: GitHub user provides an email directly.\n if (ghUser?.email) {\n return {\n email: ghUser.email,\n fullName: null,\n domain: ghUser.blogDomain ?? extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: null,\n };\n }\n\n // Path B': webSearch for the author's LinkedIn URL → enrichProfile to recover\n // company / company_domain / sometimes email. Bridges the common case where\n // GitHub gives us a name but no company/blog — without this, deep-research\n // (Path C) fails its required-identifier gate and the candidate drops.\n //\n // Cost when triggered: $0.01 webSearch + $0.005 enrichProfile = ~$0.015.\n // Skipped entirely when extract.companyName already known OR neither the\n // author name nor github handle is available.\n let companyForGate: string | null = extract.companyName ?? null;\n let domainForGate: string | null = extractDomain;\n if (!companyForGate && (extract.authorFullName || extract.githubHandle)) {\n const tokens = [extract.authorFullName, extract.githubHandle].filter((t): t is string =>\n Boolean(t),\n );\n const linkedinUrl = await findLinkedInUrl({\n fullName: tokens[0] ?? \"\",\n disambiguators: tokens.slice(1),\n accumCost,\n errKindPrefix,\n });\n if (linkedinUrl) {\n discoveredLinkedinUrl = linkedinUrl;\n try {\n const enriched = await enrichProfile({ linkedinUrl }, { playName });\n accumCost(enriched.result.cost ?? 0);\n const profile = enriched.result.profile;\n // PersonResult exposes phone (string) AND fullphone (array) — extractFirstPhone\n // reads either. Capture once and reuse on every return path so we don't drop\n // a phone the SDK already paid to retrieve.\n const enrichedPhone = extractFirstPhone(profile);\n // 1) enrichProfile gave us a direct email — use it.\n if (profile?.email) {\n return {\n email: profile.email,\n fullName: profile.full_name ?? extract.authorFullName,\n domain: profile.company_domain ?? extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: enrichedPhone,\n };\n }\n // 2) Got a company_domain — try findEmail with it.\n if (profile?.company_domain) {\n const viaEnriched = await tryFindEmail(\n profile.company_domain,\n { ...extract, authorFullName: profile.full_name ?? extract.authorFullName },\n accumCost,\n errKindPrefix,\n playName,\n );\n if (viaEnriched)\n return {\n ...viaEnriched,\n domain: profile.company_domain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: enrichedPhone,\n };\n domainForGate = profile.company_domain;\n }\n // 3) At minimum we may have learned a company name — feeds Path C's gate.\n if (profile?.company) companyForGate = profile.company;\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.enrich_profile`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n }\n\n // Path C: deep research as the last resort. The API needs strong identifiers\n // to find a person — empirically, `socialMediaUrl: <github-repo-url>` alone\n // is NOT enough (we burned $0.15 on three \"Could not find data for this\n // person\" failures with just that). Require either:\n // (a) a known email, OR\n // (b) full name AND company (company may have been populated by Path B')\n // Anything weaker spends $0.05 on a near-guaranteed miss. The repoUrl is\n // still passed as `socialMediaUrl` for bonus signal when present.\n if (!useDeepResearch) return null;\n const hasName = Boolean(extract.authorFullName && extract.authorFullName.length > 0);\n const hasCompany = Boolean(companyForGate && companyForGate.length > 0);\n // We never have an email here by definition — Paths A/B both bail before\n // setting one, and a contact found earlier short-circuits before this tier.\n // Kept as a placeholder for future flexibility (e.g. a discovery layer that\n // surfaces a tentative email).\n const hasEmail = false;\n if (!hasEmail && !(hasName && hasCompany)) return null;\n try {\n const dr = await deepResearchPerson(\n {\n socialMediaUrl: repoUrl,\n ...(hasName ? { name: extract.authorFullName as string } : {}),\n ...(hasCompany ? { company: companyForGate as string } : {}),\n },\n { playName },\n );\n accumCost(dr.result.cost ?? 0);\n const enr = dr.result.result?.enrichment;\n const drEmail = enr?.best_work_email ?? enr?.best_personal_email ?? enr?.altemails?.[0] ?? null;\n if (!drEmail) return null;\n const drFullName =\n [enr?.firstname, enr?.lastname]\n .filter((p): p is string => Boolean(p))\n .join(\" \")\n .trim() ||\n enr?.displayname ||\n null;\n const drPhone = extractFirstPhone(enr);\n return {\n email: drEmail,\n fullName: drFullName,\n domain: domainForGate ?? ghUser?.blogDomain ?? drEmail.split(\"@\")[1] ?? null,\n linkedinUrl: discoveredLinkedinUrl,\n phone: drPhone,\n };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.deep_research`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Single findEmail attempt with consistent fault-handling. OneShot's\n * findEmail requires `full_name` (or first+last) — without one it throws\n * synchronously, and a throw here would tear down the parallelMap pool. We\n * short-circuit cleanly when there's no name, and catch the SDK throw on\n * transient network errors. Either failure mode returns null so the caller\n * falls through to the next contact-resolution tier.\n */\nasync function tryFindEmail(\n domain: string,\n extract: AgentBuilderExtract,\n accumCost: (c: number | undefined) => void,\n errKindPrefix: string,\n playName: string,\n): Promise<{ email: string; fullName: string | null } | null> {\n if (!extract.authorFullName || extract.authorFullName.length === 0) {\n return null;\n }\n const skip = shouldSkipFindEmail({\n fullName: extract.authorFullName,\n companyDomain: domain,\n });\n if (!skip.ok) {\n logEvent(\n \"finder.skipped_findemail\",\n { name: playName, reason: skip.reason, kind: `${errKindPrefix}.find_email` },\n \"info\",\n );\n return null;\n }\n let found: Awaited<ReturnType<typeof findEmail>>;\n try {\n found = await findEmail(\n { fullName: extract.authorFullName, companyDomain: domain },\n { playName },\n );\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.find_email`,\n domain,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n accumCost(found.result.cost ?? 0);\n if (found.result.found && found.result.email) {\n return { email: found.result.email, fullName: found.result.full_name ?? null };\n }\n return null;\n}\n\n/**\n * Compose the snippet-ICP `summary` from whichever signal we have. Topic-driven\n * candidates (github-topics) carry the repo's self-tagged GitHub topics. The\n * `vendors` branch is reserved for future finders that surface known vendor\n * names at discovery. If neither is present, return the bare description\n * rather than emitting an empty `topics: ` tail.\n *\n * Exported for direct unit testing — integration coverage of both branches\n * would require a discovery shape that doesn't exist yet.\n */\nexport function describeForIcp(hit: RepoCandidate): string {\n if (hit.vendors.length > 0) {\n return `${hit.description} vendors: ${hit.vendors.join(\", \")}`;\n }\n const topics = hit.topics ?? [];\n if (topics.length > 0) {\n return `${hit.description} topics: ${topics.join(\", \")}`;\n }\n return hit.description;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","/**\n * Generic GitHub-repo URL utilities used by the github-topics finder + the\n * shared `_repo-pipeline.ts`. Kept finder-agnostic — no combo / topic state.\n */\n\nconst NOISE_REPO_PATTERNS = [\n /^awesome[-_]/i,\n /[-_]awesome$/i,\n /^learn[-_]/i,\n /[-_]tutorial(s)?$/i,\n /^tutorial[-_]/i,\n /[-_]example(s)?$/i,\n /^example[-_]/i,\n /[-_]demo$/i,\n /^demo[-_]/i,\n /[-_]course$/i,\n /^course[-_]/i,\n /[-_]bootcamp$/i,\n /^cheatsheet/i,\n /[-_]boilerplate$/i,\n /^template[-_]/i,\n];\n\n/**\n * True when the repo name matches an \"awesome list / tutorial / demo / course /\n * boilerplate\" pattern. Catches the dominant non-buyer repos before the LLM\n * extract spends $0.02+ on them.\n */\nexport function looksLikeNoiseRepo(repoUrl: string): boolean {\n const name = repoUrl.split(\"/\").pop() ?? \"\";\n return NOISE_REPO_PATTERNS.some((rx) => rx.test(name));\n}\n\n/** First-segment paths on github.com that are never repos (org pages, topic indexes, marketplace, …). */\nconst GITHUB_RESERVED_PATHS = new Set([\n \"about\",\n \"collections\",\n \"contact\",\n \"customer-stories\",\n \"enterprise\",\n \"events\",\n \"explore\",\n \"features\",\n \"issues\",\n \"join\",\n \"login\",\n \"marketplace\",\n \"new\",\n \"notifications\",\n \"orgs\",\n \"organizations\",\n \"pricing\",\n \"pulls\",\n \"readme\",\n \"search\",\n \"security\",\n \"settings\",\n \"site\",\n \"sponsors\",\n \"stars\",\n \"topics\",\n \"trending\",\n]);\n\n/**\n * Reduce any GitHub URL down to a canonical `https://github.com/<owner>/<repo>`\n * form, or return null when the URL isn't a repo at all (gist host, reserved\n * first segment, missing repo segment, malformed). Strips `.git` suffix,\n * lowercases the host, drops query/hash and any path beyond owner+repo.\n */\nexport function normalizeRepoUrl(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const u = new URL(url);\n const host = u.hostname.toLowerCase();\n if (host !== \"github.com\" && host !== \"www.github.com\") return null;\n const segs = u.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segs.length < 2) return null;\n const [user, repo] = segs;\n if (!user || !repo) return null;\n if (GITHUB_RESERVED_PATHS.has(user.toLowerCase())) return null;\n const cleanRepo = repo.replace(/\\.git$/i, \"\");\n return `https://github.com/${user}/${cleanRepo}`;\n } catch {\n return null;\n }\n}\n","import { resolveIcp } from \"./_filter.ts\";\nimport { isoDateNDaysAgo, searchTopicRepos } from \"./_github-search.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport {\n processRepoCandidate,\n type RepoCandidate,\n type RepoPipelineCtx,\n} from \"./_repo-pipeline.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\nimport { looksLikeNoiseRepo, normalizeRepoUrl } from \"./_repo-utils.ts\";\n\n/**\n * GitHub-Topic-driven finder. Discovers repos via the (free) GitHub Search\n * API filtered by `topic:<slug>`, then hands each candidate to the shared\n * `_repo-pipeline.ts` (snippet-ICP → webRead → extract → resolveContact →\n * enqueue).\n *\n * Why topic search vs the retired combo-search approach: topic-tagged repos\n * are pre-curated by maintainers self-tagging — much higher signal-per-fetch\n * than `site:github.com \"X\" \"Y\"` Google scraping. The Search API also\n * returns actual repo metadata (description, stars, topics) instead of\n * misleading issue/PR snippets that judged the parent repo on text it didn't\n * own. And discovery is free (no webSearch spend per query).\n */\nconst SOURCE = \"find:github-topics\";\n\nexport interface GitHubTopicsFinderOpts extends RunOpts {\n /** GitHub topic slugs, e.g. [\"llm-agents\", \"ai-agent\", \"langchain\"]. */\n topics: string[];\n /** Canonical vendor names handed to the LLM extract for stack detection. */\n vendors: string[];\n /**\n * Subset of `vendors` the founder competes with head-on. When a candidate's\n * detected stack includes one of these, it routes to the competitor-switch\n * play (\"switch from X\") instead of stack-consolidation. Empty = every\n * candidate is stack-consolidation. Matched case-insensitively.\n */\n directCompetitors?: string[];\n /** YOUR EDGE line handed to the email prompt. */\n yourEdge: string;\n /** Min stars filter. Default 5 (drops abandoned/empty repos). */\n minStars?: number;\n /** Repos pushed within this window. Default 90 days. */\n maxAgeDays?: number;\n /** Max in-flight candidate workers. Default 3. */\n concurrency?: number;\n /** Min vendors detected in README. Default 2. */\n minVendors?: number;\n /** Last-resort deepResearchPerson fallback. Default true. */\n useDeepResearch?: boolean;\n}\n\nexport async function runGitHubTopicsFinder(opts: GitHubTopicsFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const minStars = Math.max(0, opts.minStars ?? 5);\n const maxAgeDays = Math.max(1, opts.maxAgeDays ?? 90);\n const minVendors = Math.max(1, opts.minVendors ?? 2);\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n const useDeepResearch = opts.useDeepResearch !== false;\n const icp = resolveIcp(opts.icpOverride);\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n if (!opts.topics || opts.topics.length === 0) {\n result.halted = \"unconfigured: set `topics` in /queue → github-topics → edit config\";\n return result;\n }\n if (!opts.vendors || opts.vendors.length === 0) {\n result.halted = \"unconfigured: set `vendors` in /queue → github-topics → edit config\";\n return result;\n }\n if (!opts.yourEdge || opts.yourEdge.trim().length === 0) {\n result.halted = \"unconfigured: set `yourEdge` in /queue → github-topics → edit config\";\n return result;\n }\n\n // Discovery: one Search API call per topic. Free, but we cap at limit*2 hits\n // BETWEEN topics so an unconfigured `topics: [...]` of length 20 doesn't\n // dispatch 20 search calls when the first three already over-fill the buffer.\n // The cap is per-iteration, not per-hit — a single noisy topic returning all\n // perPage=50 results still feeds them all into the pool. That's intentional:\n // searchTopicRepos already pre-filters with `stars:>=N pushed:>=Y`, so even\n // 50 hits from one topic is healthy signal. `searchTopicRepos` swallows its\n // own errors (returns []), so no try/catch is needed here.\n const pushedSinceIso = isoDateNDaysAgo(maxAgeDays);\n const seen = new Set<string>();\n const hits: RepoCandidate[] = [];\n for (const topic of opts.topics) {\n if (hits.length >= limit * 2) break;\n const repos = await searchTopicRepos({\n topic,\n minStars,\n pushedSinceIso,\n perPage: 50,\n });\n for (const repo of repos) {\n const url = normalizeRepoUrl(repo.url);\n if (!url || seen.has(url)) continue;\n if (looksLikeNoiseRepo(url)) continue;\n seen.add(url);\n hits.push({\n url,\n title: repo.fullName,\n description: repo.description ?? \"\",\n vendors: [],\n topics: repo.topics,\n });\n }\n }\n result.candidates = hits.length;\n\n const ctx: RepoPipelineCtx = {\n icp,\n vocab: opts.vendors,\n directCompetitors: opts.directCompetitors ?? [],\n yourEdge: opts.yourEdge,\n minVendors,\n useDeepResearch,\n result,\n halted: { value: false },\n limit,\n maxCostUsd: opts.maxCostUsd,\n sourceTag: SOURCE,\n notesPrefix: \"github-topic\",\n dryRun: opts.dryRun,\n };\n\n await parallelMap(hits, concurrency, (hit) => processRepoCandidate(hit, ctx));\n return result;\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\nexport interface Stargazer {\n login: string;\n userUrl: string;\n /** ISO timestamp of the star (from the star+json media type). */\n starredAt: string;\n}\n\n/** Parse one `application/vnd.github.star+json` stargazer row. */\nfunction parseStarRow(raw: unknown): Stargazer | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const starredAt = typeof r[\"starred_at\"] === \"string\" ? (r[\"starred_at\"] as string) : null;\n const user = r[\"user\"];\n if (!starredAt || !user || typeof user !== \"object\") return null;\n const u = user as Record<string, unknown>;\n const login = typeof u[\"login\"] === \"string\" ? (u[\"login\"] as string) : null;\n if (!login) return null;\n const userUrl = typeof u[\"html_url\"] === \"string\" ? (u[\"html_url\"] as string) : null;\n return { login, userUrl: userUrl ?? `https://github.com/${login}`, starredAt };\n}\n\n/** Read the `page=N>; rel=\"last\"` page number from a GitHub `Link` header. */\nfunction parseLastPage(link: string | null): number {\n if (!link) return 1;\n const m = link.match(/[?&]page=(\\d+)>;\\s*rel=\"last\"/);\n return m ? Math.max(1, Number.parseInt(m[1] ?? \"1\", 10)) : 1;\n}\n\n/**\n * Recent stargazers of a public repo. GitHub returns stargazers oldest-first,\n * so the newest stars live on the LAST page — we read the `Link: rel=\"last\"`\n * page number, then page backward (newest → older), collecting stars with\n * `starredAt >= sinceIso` and stopping as soon as a page has none fresh (every\n * earlier page is older still) or `maxPages` is hit. Fault-tolerant like\n * `searchTopicRepos`: returns `{ stargazers: [], error }` on any non-2xx /\n * network / parse failure so the caller logs + continues to the next repo.\n *\n * Requires `GITHUB_TOKEN` for any real volume (5,000 req/hr core); without it\n * GitHub rate-limits hard at 60/hr.\n */\nexport async function recentStargazers(\n repo: string,\n opts: { sinceIso: string; maxPages?: number },\n): Promise<{ stargazers: Stargazer[]; error?: string }> {\n const maxPages = Math.max(1, opts.maxPages ?? 20);\n // star+json gives us `starred_at`; otherwise it's a bare user list.\n const headers = { ...githubHeaders(), Accept: \"application/vnd.github.star+json\" };\n const base = `https://api.github.com/repos/${repo}/stargazers?per_page=100`;\n\n try {\n // Page 1 (oldest) is fetched first only to read the Link header; its rows\n // are reused if the backward walk reaches page 1.\n const firstRes = await fetch(`${base}&page=1`, { headers });\n if (!firstRes.ok) {\n logEvent(\"github.stargazers\", { repo, ok: false, status: firstRes.status }, \"warn\");\n return { stargazers: [], error: `status ${firstRes.status}` };\n }\n const lastPage = parseLastPage(firstRes.headers.get(\"link\"));\n const page1Rows = ((await firstRes.json()) as unknown[]) ?? [];\n\n const out: Stargazer[] = [];\n let pagesFetched = 1;\n for (let page = lastPage; page >= 1 && pagesFetched <= maxPages; page--) {\n let rows: unknown[];\n if (page === 1) {\n rows = page1Rows;\n } else {\n const res = await fetch(`${base}&page=${page}`, { headers });\n pagesFetched++;\n if (!res.ok) break;\n rows = ((await res.json()) as unknown[]) ?? [];\n }\n const parsed = rows\n .map(parseStarRow)\n .filter((s): s is Stargazer => s !== null && s.starredAt >= opts.sinceIso);\n out.push(...parsed);\n // Pages get older as `page` decreases; once a page yields zero fresh\n // stars, every earlier page is older too — stop.\n if (parsed.length === 0) break;\n }\n\n // Dedupe by login (defensive — a user stars a repo once).\n const seen = new Set<string>();\n const stargazers = out.filter((s) => {\n const key = s.login.toLowerCase();\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n logEvent(\"github.stargazers\", {\n repo,\n ok: true,\n fresh: stargazers.length,\n last_page: lastPage,\n pages_fetched: pagesFetched,\n });\n return { stargazers };\n } catch (err) {\n const message = ((err as Error).message ?? \"\").slice(0, 120);\n logEvent(\"github.stargazers\", { repo, ok: false, message_120: message }, \"warn\");\n return { stargazers: [], error: message };\n }\n}\n","import { findEmail, getLedger, logEvent, parallelMap, verifyEmail } from \"@oneshot-gtm/core\";\nimport type { FindEmailInput } from \"@oneshot-gtm/core\";\nimport type { CompetitorSwitchTarget, RepoInterestTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { fetchGitHubUser } from \"./_github-user.ts\";\nimport { recentStargazers, type Stargazer } from \"./_stargazers.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"github-stars\";\n\n/** A repo the founder watches, tagged with how it relates to their product. */\nexport interface RepoWatch {\n /** \"owner/name\". */\n repo: string;\n /** `competitor` → competitor-switch pitch; `adjacent` → repo-interest pitch. */\n rel: \"competitor\" | \"adjacent\";\n /** Display label (e.g. \"Apollo\"); falls back to the repo's name segment. */\n label?: string;\n}\n\nexport interface GitHubStarsFinderOpts extends RunOpts {\n repos: RepoWatch[];\n /** Fed to whichever play a candidate routes to. */\n yourEdge: string;\n /** Only consider stars within the last N days. Default 30. */\n sinceDays?: number;\n /** Per-candidate pipelines in flight at once. Default 3. */\n concurrency?: number;\n}\n\ntype Candidate = Stargazer & { repo: string; rel: RepoWatch[\"rel\"]; label: string };\n\nfunction deriveLabel(repo: string): string {\n return repo.split(\"/\")[1]?.trim() || repo;\n}\n\nfunction sourceFor(repo: string): string {\n return `find:${PLAY_NAME}:${repo}`;\n}\n\n/**\n * github-stars finder: recent stargazers of watched repos → prospects, routed\n * by each repo's founder-tagged `rel`. A `competitor` repo's stargazers become\n * `competitor-switch` rows (\"why teams switch from X\"); an `adjacent` repo's\n * become `repo-interest` rows (\"you're into X — my product helps\"). Reuses the\n * shared finder stack (ICP filter, findEmail/verify/enrich, dedupe, prescreen)\n * and the soft-cap loop pattern from show-hn / accelerator-batch.\n */\nexport async function runGitHubStarsFinder(opts: GitHubStarsFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n const sinceDays = opts.sinceDays ?? 30;\n const sinceIso = new Date(Date.now() - sinceDays * 24 * 3600 * 1000).toISOString();\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: `find:${PLAY_NAME}`,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n logEvent(\"finder.start\", {\n name: PLAY_NAME,\n repos: opts.repos.length,\n since_days: sinceDays,\n limit,\n });\n\n // Step 1: gather recent stargazers across all watched repos, tagged with the\n // repo's rel/label. Per-repo errors log + continue (handled in _stargazers).\n const tagged: Candidate[] = [];\n let anyRepoOk = false;\n for (const w of opts.repos) {\n const { stargazers, error } = await recentStargazers(w.repo, { sinceIso });\n if (!error) anyRepoOk = true;\n const label = w.label?.trim() || deriveLabel(w.repo);\n for (const s of stargazers) tagged.push({ ...s, repo: w.repo, rel: w.rel, label });\n }\n\n // Cross-repo dedupe by login (someone starring two watched repos surfaces once).\n const seen = new Set<string>();\n const candidates = tagged.filter((c) => {\n const k = c.login.toLowerCase();\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n result.candidates = candidates.length;\n\n if (candidates.length === 0) {\n result.halted = anyRepoOk\n ? \"no recent stargazers in the window\"\n : \"all repos failed (check GITHUB_TOKEN / repo names)\";\n logEvent(\"finder.done\", { name: PLAY_NAME, candidates: 0, halted: result.halted });\n return result;\n }\n\n // Step 2: per-candidate pipeline (parallel, soft-capped on limit + cost).\n let halted = false;\n await parallelMap(candidates, concurrency, async (c) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n\n const playName = c.rel === \"competitor\" ? \"competitor-switch\" : \"repo-interest\";\n const dedupeKey = `${PLAY_NAME}:${c.repo}:${c.login}`;\n if (ledger.isQueueDuplicate(playName, dedupeKey)) {\n result.droppedDuplicate++;\n return;\n }\n\n const user = await fetchGitHubUser(c.login);\n if (!user) {\n result.droppedEnrichment++;\n return;\n }\n const fullName = user.name ?? c.login;\n\n // ICP filter on the resolved profile + the repo they starred.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: fullName,\n url: c.userUrl,\n summary: [user.company, `starred ${c.repo}`].filter(Boolean).join(\" · \"),\n },\n });\n if (!filter.match) {\n result.droppedIcp++;\n // Persist the auto-rejection for review (skipped on dry-run previews).\n if (!opts.dryRun) {\n ledger.enqueueTarget({\n playName,\n payload: { name: fullName, company: user.company ?? \"\", repo: c.repo },\n dedupeKey,\n source: sourceFor(c.repo),\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n }\n return;\n }\n\n // Dry-run preview: count ICP-passers, skip the paid enrich + enqueue.\n if (opts.dryRun) {\n result.enqueued++;\n return;\n }\n\n // Resolve an email: public profile email first, else findEmail via the\n // blog domain (gated by the prescreen). No domain + no public email → drop.\n let email = user.email;\n if (!email) {\n const domain = user.blogDomain;\n if (!domain) {\n result.droppedEnrichment++;\n return;\n }\n const skip = shouldSkipFindEmail({ fullName, companyDomain: domain });\n if (!skip.ok) {\n result.droppedEnrichment++;\n logEvent(\"finder.skipped_findemail\", { name: PLAY_NAME, reason: skip.reason }, \"info\");\n return;\n }\n const findInput: FindEmailInput = { companyDomain: domain, fullName };\n const found = await findEmail(findInput, { playName: PLAY_NAME });\n result.costUsd += found.result.cost ?? 0;\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n return;\n }\n email = found.result.email;\n }\n\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += verified.result.cost ?? 0;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n if (isDuplicate({ playName, dedupeKey, prospectEmail: email })) {\n result.droppedDuplicate++;\n return;\n }\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: PLAY_NAME,\n });\n result.costUsd += enr.costUsd;\n\n const company = user.company?.trim() || \"(unknown)\";\n const repoUrl = `https://github.com/${c.repo}`;\n const contactExtras = {\n ...(enr.linkedinUrl ? { linkedinUrl: enr.linkedinUrl } : {}),\n ...(enr.phone ? { phone: enr.phone } : {}),\n };\n\n const target: CompetitorSwitchTarget | RepoInterestTarget =\n c.rel === \"competitor\"\n ? {\n name: fullName,\n email,\n company,\n competitor: c.label,\n evidenceUrl: repoUrl,\n // Pre-supplied evidence → competitor-switch skips its browser scrape\n // (a code page has no \"pain points\" to extract).\n evidenceText: `Starred ${c.label}'s repo (${c.repo}) on ${c.starredAt.slice(0, 10)} — actively evaluating tools in this space.`,\n yourEdge: opts.yourEdge,\n ...contactExtras,\n }\n : {\n name: fullName,\n email,\n company,\n repo: c.repo,\n repoLabel: c.label,\n yourEdge: opts.yourEdge,\n evidenceUrl: repoUrl,\n ...contactExtras,\n };\n\n const id = ledger.enqueueTarget({\n playName,\n payload: target,\n dedupeKey,\n source: sourceFor(c.repo),\n notes: filter.reason,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n });\n\n logEvent(\"finder.done\", {\n name: PLAY_NAME,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return result;\n}\n","import { getLedger, logEvent, startRun } from \"@oneshot-gtm/core\";\nimport { type CohortEntry, runAcceleratorBatchFinder } from \"./accelerator-batch.ts\";\nimport { deriveCohortLabel } from \"./_yc-oss-adapter.ts\";\nimport { runBreakupReviveFinder } from \"./breakup-revive.ts\";\nimport { type RepoWatch, runGitHubStarsFinder } from \"./github-stars.ts\";\nimport { runGitHubTopicsFinder } from \"./github-topics.ts\";\nimport { runHiringSignalFinder } from \"./hiring-signal.ts\";\nimport { runJobChangeFinder } from \"./job-change.ts\";\nimport { runPodcastGuestFinder } from \"./podcast-guest.ts\";\nimport { runPostFundingFinder } from \"./post-funding.ts\";\nimport { runShowHnFinder } from \"./show-hn.ts\";\nimport type { FinderResult } from \"./_types.ts\";\n\nexport interface TriggerSpec {\n name: string;\n defaultIntervalMs: number;\n defaultConfig: Record<string, unknown>;\n /** Whether new installs auto-enable this trigger. Default true. */\n enabledByDefault?: boolean;\n /**\n * Plain-English brief the strategist embeds in its system prompt. Describes\n * what the finder does + what each config key controls. Founder-facing too:\n * the chat references these so the founder doesn't have to know JSON shapes.\n */\n configBrief?: string;\n /**\n * Optional readiness gate. Return `{ready:false, reason}` when the stored\n * config lacks required founder-supplied inputs (e.g. github-topics without\n * `topics`). Consulted by the server's enable/run endpoints and by the watch\n * loop to avoid pointless runs. When absent, the trigger is always ready.\n */\n readiness?: (\n config: Record<string, unknown>,\n ) => { ready: true } | { ready: false; reason: string };\n run: (config: Record<string, unknown>) => Promise<FinderResult>;\n}\n\nexport type Readiness = { ready: true } | { ready: false; reason: string };\n\n/** Evaluate a spec's readiness fn (defaulting to ready when absent). */\nexport function checkReadiness(spec: TriggerSpec, config: Record<string, unknown>): Readiness {\n if (!spec.readiness) return { ready: true };\n try {\n return spec.readiness(config);\n } catch {\n // A throwing readiness fn shouldn't bring down the watch loop; treat as\n // not-ready with a generic reason so the founder sees *something*.\n return { ready: false, reason: \"readiness check threw\" };\n }\n}\n\nconst ONE_HOUR = 3600 * 1000;\n\n/**\n * Default cohort sweep for the `accelerator-batch` trigger. Covers seven\n * incubators × {latest, previous-latest} cohorts as of 2026-05-20. Only the\n * yc-* entries hit the structured yc-oss/api directory; the other 12 route\n * to the websearch + LLM-extract adapter and will have spotty per-cohort\n * recall (Neo is invite-only, SPC publishes thin web footprint, etc.).\n * Per-cohort failures are isolated — the run only halts when EVERY cohort\n * comes back empty.\n *\n * ROTATION: this list goes stale within ~3 months as YC announces W27,\n * Techstars rolls Fall 2026, etc. Founders should edit `cohorts[]` via the\n * trigger config UI on /queue when new batches announce.\n */\nconst DEFAULT_COHORTS: CohortEntry[] = [\n { cohort: \"yc-w26\", cohortLabel: \"YC W26\" },\n { cohort: \"yc-f25\", cohortLabel: \"YC F25\" },\n { cohort: \"techstars-spring-2026\", cohortLabel: \"Techstars Spring 2026\" },\n { cohort: \"techstars-fall-2025\", cohortLabel: \"Techstars Fall 2025\" },\n { cohort: \"antler-q1-2026\", cohortLabel: \"Antler Q1 2026\" },\n { cohort: \"antler-q4-2025\", cohortLabel: \"Antler Q4 2025\" },\n { cohort: \"500global-batch-38\", cohortLabel: \"500 Global Batch 38\" },\n { cohort: \"500global-batch-37\", cohortLabel: \"500 Global Batch 37\" },\n { cohort: \"ai-grant-cohort-5\", cohortLabel: \"AI Grant Cohort 5\" },\n { cohort: \"ai-grant-cohort-4\", cohortLabel: \"AI Grant Cohort 4\" },\n { cohort: \"spc-2026-1\", cohortLabel: \"South Park Commons F1 2026-1\" },\n { cohort: \"spc-2025-2\", cohortLabel: \"South Park Commons F1 2025-2\" },\n { cohort: \"neo-class-2026\", cohortLabel: \"Neo Class 2026\" },\n { cohort: \"neo-class-2025\", cohortLabel: \"Neo Class 2025\" },\n];\n\nexport const TRIGGERS: TriggerSpec[] = [\n {\n name: \"show-hn\",\n defaultIntervalMs: 6 * ONE_HOUR,\n defaultConfig: { sinceDays: 1, limit: 25, maxCostUsd: 5 },\n configBrief:\n \"Polls Hacker News Algolia for recent Show HN posts, ICP-filters them, enriches founder contact, and enqueues them for review. Config: `sinceDays` (lookback window, default 1), `limit` (max kept, default 25), `maxCostUsd` (per-run spend cap). Defaults work for most ICPs — bump sinceDays to 7+ if your ICP is niche enough that daily volume is thin.\",\n run: (cfg) =>\n runShowHnFinder({\n dryRun: false,\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 1,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"accelerator-batch\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n // Default sweep: every known incubator × {latest, previous-latest} cohorts.\n // Founders can trim or edit the list in /queue → trigger config; per-cohort\n // failures don't halt the run, so spotty incubators (Neo, SPC) coexist\n // with high-recall ones (YC, Techstars) in one trigger fire.\n defaultConfig: {\n cohorts: DEFAULT_COHORTS,\n limit: 25,\n maxCostUsd: 15,\n },\n configBrief:\n \"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.\",\n readiness: (cfg) => {\n const cohorts = Array.isArray(cfg[\"cohorts\"]) ? cfg[\"cohorts\"] : null;\n const legacyCohort =\n typeof cfg[\"cohort\"] === \"string\" ? (cfg[\"cohort\"] as string).trim() : \"\";\n if ((!cohorts || cohorts.length === 0) && legacyCohort.length === 0) {\n return {\n ready: false,\n reason: \"set `cohorts[]` (or legacy `cohort`)\",\n };\n }\n const senderCohort =\n typeof cfg[\"senderCohort\"] === \"string\" ? (cfg[\"senderCohort\"] as string).trim() : \"\";\n if (senderCohort.length === 0) {\n return {\n ready: false,\n reason: \"set `senderCohort` (your own cohort tag, e.g. yc-w23)\",\n };\n }\n return { ready: true };\n },\n run: (cfg) => {\n // Multi-cohort path: new `cohorts` array wins. Filter to well-formed\n // entries so a single malformed row doesn't kill the run.\n const cohortsRaw = Array.isArray(cfg[\"cohorts\"]) ? (cfg[\"cohorts\"] as unknown[]) : [];\n const cohorts: CohortEntry[] = cohortsRaw\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const e = entry as Record<string, unknown>;\n const cohort = typeof e[\"cohort\"] === \"string\" ? e[\"cohort\"].trim() : \"\";\n if (cohort.length === 0) return null;\n const labelRaw =\n typeof e[\"cohortLabel\"] === \"string\" ? (e[\"cohortLabel\"] as string).trim() : \"\";\n const cohortLabel = labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort);\n return { cohort, cohortLabel };\n })\n .filter((e): e is CohortEntry => e !== null);\n\n // Legacy single-cohort path: only used when `cohorts` is empty/missing.\n const legacyCohort = typeof cfg[\"cohort\"] === \"string\" ? (cfg[\"cohort\"] as string) : \"\";\n const legacyLabel =\n typeof cfg[\"cohortLabel\"] === \"string\" ? (cfg[\"cohortLabel\"] as string) : \"\";\n\n return runAcceleratorBatchFinder({\n dryRun: false,\n ...(cohorts.length > 0 ? { cohorts } : {}),\n ...(cohorts.length === 0 && legacyCohort.trim().length > 0\n ? { cohort: legacyCohort, cohortLabel: legacyLabel }\n : {}),\n ...(cfg[\"adapter\"] === \"yc-oss\" || cfg[\"adapter\"] === \"websearch\"\n ? { adapter: cfg[\"adapter\"] as \"yc-oss\" | \"websearch\" }\n : {}),\n // Sender cohort (+ offer) stamped onto every enqueued row so the play\n // drafts inline without a run-level value. Readiness gates senderCohort.\n ...(typeof cfg[\"senderCohort\"] === \"string\" && cfg[\"senderCohort\"].trim().length > 0\n ? { senderCohort: (cfg[\"senderCohort\"] as string).trim() }\n : {}),\n ...(typeof cfg[\"freeForCohortOffer\"] === \"string\" &&\n cfg[\"freeForCohortOffer\"].trim().length > 0\n ? { freeForCohortOffer: (cfg[\"freeForCohortOffer\"] as string).trim() }\n : {}),\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 15,\n });\n },\n },\n {\n name: \"post-funding-auto\",\n defaultIntervalMs: 12 * ONE_HOUR,\n defaultConfig: {\n autoRounds: [\"Seed\", \"Series A\"],\n autoSinceDays: 7,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Auto-discovers funding announcements via webSearch, extracts company + founder, ICP-filters. Config: `autoRounds` (e.g. ['Seed','Series A','Series B'] — match what your ICP actually buys at), `autoIndustry` (optional industry hint to bias the search query — derive from the ICP), `autoSinceDays` (lookback, default 7), `limit`, `maxCostUsd`. Tune autoRounds to skip stages that won't buy yet.\",\n run: (cfg) =>\n runPostFundingFinder({\n dryRun: false,\n auto: true,\n autoRounds: (cfg[\"autoRounds\"] as string[]) ?? [\"Seed\", \"Series A\"],\n ...(typeof cfg[\"autoIndustry\"] === \"string\"\n ? { autoIndustry: cfg[\"autoIndustry\"] as string }\n : {}),\n autoSinceDays: (cfg[\"autoSinceDays\"] as number) ?? 7,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n // Opt-in: these finders need founder-supplied personas/roles/podcasts to be\n // useful, so they ship disabled. Enable from /queue → Triggers.\n {\n name: \"job-change\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n personas: [\"VP Engineering\", \"Head of Growth\", \"Director of Product\", \"Chief of Staff\"],\n sinceDays: 14,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Searches for 'joined X as Y' job-change announcements, ICP-filters, enriches the new email. Config: `personas` (the roles whose JOB CHANGE represents a buying moment for THIS product — not generic 'VP Eng' unless that's actually who buys; e.g. 'Head of AI', 'Founding Engineer' for AI-tooling ICPs), `companies` (optional whitelist of companies to bias toward), `sinceDays` (lookback, default 14), `limit`, `maxCostUsd`. Strong personas matter more than long lists.\",\n run: (cfg) =>\n runJobChangeFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"personas\"]) ? { personas: cfg[\"personas\"] as string[] } : {}),\n ...(Array.isArray(cfg[\"companies\"]) ? { companies: cfg[\"companies\"] as string[] } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 14,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"hiring-signal\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n roles: [\"Staff Engineer\", \"ML Engineer\", \"Solutions Engineer\"],\n sinceDays: 14,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"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.\",\n readiness: (cfg) => {\n const claim = typeof cfg[\"yourClaim\"] === \"string\" ? (cfg[\"yourClaim\"] as string).trim() : \"\";\n return claim.length > 0\n ? { ready: true }\n : { ready: false, reason: \"set `yourClaim` (your one-line pitch)\" };\n },\n run: (cfg) =>\n runHiringSignalFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"roles\"]) ? { roles: cfg[\"roles\"] as string[] } : {}),\n ...(Array.isArray(cfg[\"companies\"]) ? { companies: cfg[\"companies\"] as string[] } : {}),\n ...(typeof cfg[\"yourClaim\"] === \"string\" ? { yourClaim: cfg[\"yourClaim\"] as string } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 14,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"podcast-guest\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n podcasts: [\"Latent Space\", \"Lenny's Podcast\", \"20VC\", \"Acquired\", \"Invest Like the Best\"],\n sinceDays: 21,\n skipRead: false,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Discovers recent podcast guests, ICP-filters, enriches their email. Config: `podcasts` (shows whose guest demographic overlaps with the ICP — replace defaults with shows the founder's actual buyer listens to), `sinceDays` (default 21), `skipRead` (skip per-episode webRead for cheaper but less accurate runs), `limit`, `maxCostUsd`. Podcast list is the leverage — narrow + on-target beats broad.\",\n run: (cfg) =>\n runPodcastGuestFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"podcasts\"]) ? { podcasts: cfg[\"podcasts\"] as string[] } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 21,\n skipRead: cfg[\"skipRead\"] === true,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n // GitHub-Topic-driven repo finder. Discovers via the (free) GitHub Search\n // API filtered by `topic:<slug>` — topic-tagged repos are pre-curated by\n // maintainers self-tagging, much higher signal-per-fetch than the\n // retired combo-search approach. Feeds stack-consolidation (vendor-\n // sprawl pitch) by default, or competitor-switch when a detected vendor\n // is on `directCompetitors`. Config-driven — the founder supplies topics\n // + vendors + edge via /queue; ships empty so nothing fires until configured.\n name: \"github-topics\",\n defaultIntervalMs: 12 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n topics: [] as string[],\n vendors: [] as string[],\n directCompetitors: [] as string[],\n yourEdge: \"\",\n minStars: 5,\n maxAgeDays: 90,\n minVendors: 1,\n concurrency: 3,\n useDeepResearch: true,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Discovers repos via GitHub Topic pages (`topic:<slug>` queries on the GitHub Search API), then scans each candidate's package.json / pyproject.toml / requirements.txt / .env.example via the GitHub Contents API to detect which API vendors the repo actually uses. Routes each candidate to one of two motion plays: stack-consolidation (default — pitch collapsing the vendor sprawl into one SDK) or competitor-switch (when a detected vendor is on `directCompetitors` — a head-on 'switch from X' pitch). Required config: `topics` (GitHub topic slugs the founder's ICP overlaps with — lowercase, hyphenated, EXACT GitHub-canonical form; singular vs plural matters), `vendors` (the founder's competitive landscape — the API vendors they aim to replace), `yourEdge` (one-sentence pitch handed to the email). Optional `directCompetitors`: a subset of `vendors` the founder competes with head-on (same canonical spelling, matched case-insensitively); a candidate using one routes to competitor-switch instead of stack-consolidation. Empty by default, so every candidate is stack-consolidation until set. VOCAB SEMANTICS: each `vendors` string is substring-matched (case-insensitive) against manifest deps + env-var keys — so `twilio` matches `twilio`, `twilio-node`, `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is NO hardcoded vendor list; oneshot-gtm is a generic founder tool and competitive vocabularies vary entirely by founder. STRATEGIST DUTY: when you (the strategist) have enough context about the founder's product/ICP, proactively propose BOTH `topics` AND `vendors` via apply-config — topics are GitHub category slugs aligned to ICP; vendors are the API competitors the founder replaces. The founder shouldn't have to enumerate either by hand. Other config: `minStars` (filter, default 5), `maxAgeDays` (default 90), `minVendors` (gate: how many distinct vocab vendors must match in a candidate's manifests; default 1), `concurrency` (in-flight workers; default 3), `useDeepResearch` (default true), `limit`, `maxCostUsd`.\",\n readiness: (cfg) => {\n const topics = cfg[\"topics\"];\n if (!Array.isArray(topics) || topics.length === 0) {\n return {\n ready: false,\n reason: \"set `topics` (one or more GitHub topic slugs, e.g. 'llm-agents')\",\n };\n }\n const vendors = cfg[\"vendors\"];\n if (!Array.isArray(vendors) || vendors.length === 0) {\n return {\n ready: false,\n reason: \"set `vendors` — your competitive landscape (ask the strategist to propose one)\",\n };\n }\n const edge = cfg[\"yourEdge\"];\n if (typeof edge !== \"string\" || edge.trim().length === 0) {\n return {\n ready: false,\n reason: \"set `yourEdge` — one-sentence consolidation pitch\",\n };\n }\n return { ready: true };\n },\n run: (cfg) => {\n const topics = Array.isArray(cfg[\"topics\"])\n ? (cfg[\"topics\"] as unknown[]).filter((t): t is string => typeof t === \"string\")\n : [];\n const vendors = Array.isArray(cfg[\"vendors\"])\n ? (cfg[\"vendors\"] as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n const directCompetitors = Array.isArray(cfg[\"directCompetitors\"])\n ? (cfg[\"directCompetitors\"] as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n const yourEdge = typeof cfg[\"yourEdge\"] === \"string\" ? cfg[\"yourEdge\"] : \"\";\n return runGitHubTopicsFinder({\n dryRun: false,\n topics,\n vendors,\n directCompetitors,\n yourEdge,\n minStars: (cfg[\"minStars\"] as number) ?? 5,\n maxAgeDays: (cfg[\"maxAgeDays\"] as number) ?? 90,\n minVendors: (cfg[\"minVendors\"] as number) ?? 2,\n concurrency: (cfg[\"concurrency\"] as number) ?? 3,\n useDeepResearch: cfg[\"useDeepResearch\"] !== false,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n });\n },\n },\n {\n name: \"github-stars\",\n defaultIntervalMs: 12 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n repos: [] as Array<{ repo: string; rel: string; label?: string }>,\n yourEdge: \"\",\n sinceDays: 30,\n concurrency: 3,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n 'Finds recent stargazers of repos you watch and turns them into prospects. Config: `repos` (array of `{repo:\"owner/name\", rel:\"competitor\"|\"adjacent\", label?}` — tag a repo `competitor` to pitch a switch (→ competitor-switch) or `adjacent` for a complementary intro (→ repo-interest); `label` is the human name, else derived from the repo), `yourEdge` (one-line pitch fed to whichever play, REQUIRED), `sinceDays` (recency window, default 30), `limit`, `maxCostUsd`. Needs `GITHUB_TOKEN` for any volume. STRATEGIST DUTY: pick repos your buyers\\' current tools live in; tag the ones you replace as `competitor`, the rest `adjacent`.',\n readiness: (cfg) => {\n const repos = Array.isArray(cfg[\"repos\"]) ? cfg[\"repos\"] : [];\n const valid = repos.filter((r) => {\n if (!r || typeof r !== \"object\") return false;\n const e = r as Record<string, unknown>;\n return (\n typeof e[\"repo\"] === \"string\" &&\n e[\"repo\"].trim().length > 0 &&\n (e[\"rel\"] === \"competitor\" || e[\"rel\"] === \"adjacent\")\n );\n });\n if (valid.length === 0) {\n return {\n ready: false,\n reason: \"set `repos` (each `{repo, rel:'competitor'|'adjacent'}`)\",\n };\n }\n const edge = cfg[\"yourEdge\"];\n if (typeof edge !== \"string\" || edge.trim().length === 0) {\n return { ready: false, reason: \"set `yourEdge` — your one-line pitch\" };\n }\n return { ready: true };\n },\n run: (cfg) => {\n const repos: RepoWatch[] = (Array.isArray(cfg[\"repos\"]) ? cfg[\"repos\"] : [])\n .map((r): RepoWatch | null => {\n if (!r || typeof r !== \"object\") return null;\n const e = r as Record<string, unknown>;\n const repo = typeof e[\"repo\"] === \"string\" ? e[\"repo\"].trim() : \"\";\n const rel = e[\"rel\"];\n if (repo.length === 0 || (rel !== \"competitor\" && rel !== \"adjacent\")) return null;\n const label = typeof e[\"label\"] === \"string\" ? e[\"label\"].trim() : \"\";\n const watch: RepoWatch = { repo, rel };\n if (label) watch.label = label;\n return watch;\n })\n .filter((r): r is RepoWatch => r !== null);\n return runGitHubStarsFinder({\n dryRun: false,\n repos,\n yourEdge: typeof cfg[\"yourEdge\"] === \"string\" ? cfg[\"yourEdge\"] : \"\",\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 30,\n concurrency: (cfg[\"concurrency\"] as number) ?? 3,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n });\n },\n },\n {\n // Ledger-only finder; no OneShot/LLM spend. Opt-in so it doesn't surprise\n // founders on fresh installs where the ledger is mostly empty.\n name: \"breakup-revive\",\n defaultIntervalMs: 7 * 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: { minDays: 60, maxDays: 90, limit: 25 },\n configBrief:\n \"Scans the founder's local prospect ledger for cold leads (no reply, marketable) within the day window and re-enqueues them for a pattern-interrupt revive. No OneShot/LLM spend (ledger-only). Config: `minDays` / `maxDays` (the cold-window — defaults 60-90), `limit`. Only enable when the founder has been sending for ≥2 months — empty ledger = no revives.\",\n run: async (cfg) =>\n runBreakupReviveFinder({\n dryRun: false,\n minDays: (cfg[\"minDays\"] as number) ?? 60,\n maxDays: (cfg[\"maxDays\"] as number) ?? 90,\n limit: (cfg[\"limit\"] as number) ?? 25,\n }),\n },\n];\n\n/**\n * Resolve the active interval for a trigger: stored config_json may override\n * the registry's defaultIntervalMs via `intervalMs`. This keeps the JSON-config\n * editor in /queue meaningful — bumping it from 24h → 6h actually changes the\n * watch loop's cadence.\n */\nexport function effectiveIntervalMs(\n spec: TriggerSpec,\n config: Record<string, unknown> | null,\n): number {\n const override = config?.[\"intervalMs\"];\n if (typeof override === \"number\" && Number.isFinite(override) && override >= 60_000) {\n return Math.floor(override);\n }\n return spec.defaultIntervalMs;\n}\n\nexport interface TriggerRunOutcome {\n name: string;\n fired: boolean;\n result?: FinderResult;\n error?: string;\n /** ms until this trigger is next due */\n nextDueInMs: number;\n}\n\n/**\n * Maximum age before an in-flight `running_started_at` is considered a\n * killed-by-restart zombie and swept by `sweepStaleRunningTriggers`.\n *\n * Real finder runtimes are dominated by the per-candidate pipeline (icpFilter\n * LLM + findEmail + verifyEmail, occasionally + webRead + deepResearchPerson).\n * github-topics with concurrency=3 typically completes 25 candidates in\n * 5-15 min; the deepResearchPerson tier (2-5 min async per call) sets the\n * realistic upper bound when many candidates fall into the hard-recovery bucket.\n *\n * 4h is set with generous headroom so a genuinely-running finder is never\n * mistakenly classified as zombie. If a run actually exceeds this, the\n * sweep marks it killed and `markTriggerRunning` lets a follow-up click\n * re-claim — bounded duplicate spend is preferable to the permanently-\n * stuck 409 state.\n */\nexport const MAX_RUN_AGE_MS = 4 * 60 * 60 * 1000;\n\n/**\n * Truth of \"is this trigger running\" lives in the ledger\n * (`triggers.running_started_at`). Survives server restart so the UI shows\n * accurate state across `bun --watch` re-execs and OS reboots.\n *\n * The freshness gate (`< MAX_RUN_AGE_MS`) hides stale rows that the boot\n * sweep hasn't cleaned up yet — defense in depth so we never report \"still\n * running\" for a row that's older than any real run could be.\n */\n/**\n * Pure helper extracted so the freshness gate is unit-testable without\n * mocking the ledger. Returns the parsed start-epoch when the iso\n * timestamp is valid AND fresh (within MAX_RUN_AGE_MS of `now`); null\n * otherwise.\n *\n * `nowMs` is injected so tests can drive time without faking Date.\n */\nexport function freshRunningStartedAtMs(\n iso: string | null | undefined,\n nowMs: number,\n): number | null {\n if (!iso) return null;\n const startedMs = new Date(iso).getTime();\n if (!Number.isFinite(startedMs)) return null;\n if (nowMs - startedMs > MAX_RUN_AGE_MS) return null;\n return startedMs;\n}\n\nexport function isTriggerRunning(name: string): boolean {\n return getTriggerRunningSince(name) !== null;\n}\n\nexport function getTriggerRunningSince(name: string): number | null {\n return freshRunningStartedAtMs(getLedger().getTrigger(name)?.running_started_at, Date.now());\n}\n\nexport function listRunningTriggers(): string[] {\n const now = Date.now();\n return getLedger()\n .listTriggers()\n .filter((r) => freshRunningStartedAtMs(r.running_started_at, now) !== null)\n .map((r) => r.name);\n}\n\n/**\n * Fire-and-forget wrapper around `runTriggerNow`: returns immediately after\n * marking the trigger as running in the ledger; the actual finder work runs\n * on the event loop. Throws synchronously if the trigger is unknown,\n * already running, or unready.\n *\n * Errors from the finder are swallowed here — `runTriggerNow` already\n * persists them to the ledger (`last_run_summary`) and emits a\n * `trigger.run.error` event, so there's nothing useful for the caller to do.\n *\n * If the process is killed mid-run (bun --watch re-exec, OS reboot), the\n * row's `running_started_at` stays set. The next cold boot's\n * `sweepStaleRunningTriggers` call writes a `killed_by_restart` summary so\n * the UI shows the truth instead of frozen-from-an-hour-ago state.\n */\nexport function fireTriggerNow(name: string): void {\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) {\n throw new Error(`unknown trigger '${name}'`);\n }\n const ledger = getLedger();\n // Readiness gate: block the run synchronously so the server route can map\n // this to a 409 without the finder ever being invoked on a dead config.\n const stored = ledger.getTrigger(name);\n const config = stored?.config_json\n ? (JSON.parse(stored.config_json) as Record<string, unknown>)\n : spec.defaultConfig;\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n throw new Error(`not ready: ${readiness.reason}`);\n }\n // Bootstrap the row if it doesn't exist yet — markTriggerRunning is an\n // UPDATE that no-ops on a missing row, so we'd silently lose state.\n if (!stored) {\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: spec.enabledByDefault !== false,\n });\n }\n // Atomic claim — no TOCTOU race. Two concurrent fires both calling\n // markTriggerRunning will see exactly one `true` and one `false`, so\n // only one finder run actually launches.\n //\n // The `staleCutoffIso` lets a fresh click reclaim a row whose previous\n // `running_started_at` is older than `MAX_RUN_AGE_MS` — i.e. the freshness\n // gate already says \"not running\" but the DB flag never got cleared\n // (process killed, no cold-boot sweep yet). Without this the user would\n // see Run-button-enabled, click, and get 409'd every retry.\n const nowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_RUN_AGE_MS).toISOString();\n const claimed = ledger.markTriggerRunning(name, nowIso, staleCutoffIso);\n if (!claimed) {\n throw new Error(`trigger '${name}' is already running`);\n }\n // Explicit catch — `void` discards the promise without wiring rejection\n // handling. If `runTriggerNow` throws synchronously OR rejects before its\n // own try/catch (e.g. JSON.parse on a corrupted config_json, an import\n // resolution issue under bun --hot, anything that would otherwise be a\n // silent unhandled rejection), we surface the failure AND clear the\n // stranded `running_started_at` so the row doesn't stay \"running\" until\n // the next boot sweep.\n runTriggerNow(name).catch((err) => {\n const message = (err as Error).message ?? \"runTriggerNow rejected\";\n logEvent(\"trigger.run.fire_failed\", { name, message_120: message.slice(0, 120) }, \"error\");\n try {\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: `fire_failed: ${message}`, at: new Date().toISOString() },\n });\n } catch {\n // updateTriggerLastPoll itself failing is hopeless; the boot sweep\n // is the safety net.\n }\n });\n}\n\n/**\n * Run a single trigger by name immediately, ignoring its scheduled dueAt\n * and the enabled flag. Useful for the /queue UI's \"Run now\" affordance:\n * the founder explicitly asked, so we bypass the scheduler. Persists\n * last_polled_at + last_run_summary so the watch loop respects the run.\n */\nexport async function runTriggerNow(name: string): Promise<TriggerRunOutcome> {\n startRun();\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) throw new Error(`unknown trigger '${name}'`);\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n if (!stored) {\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: spec.enabledByDefault !== false,\n });\n }\n const config = stored?.config_json\n ? (JSON.parse(stored.config_json) as Record<string, unknown>)\n : spec.defaultConfig;\n const intervalMs = effectiveIntervalMs(spec, config);\n // Readiness re-check: fireTriggerNow already gates ad-hoc runs, but a direct\n // CLI/test caller hitting runTriggerNow should get the same protection.\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n const message = `not ready: ${readiness.reason}`;\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\"trigger.run.skipped\", { name, source: \"ad_hoc\", reason: readiness.reason });\n return { name, fired: false, error: message, nextDueInMs: intervalMs };\n }\n const startedAt = Date.now();\n logEvent(\"trigger.run.start\", { name, source: \"ad_hoc\" });\n try {\n const result = await spec.run(config);\n ledger.updateTriggerLastPoll({ name, summary: result });\n logEvent(\"trigger.run.done\", {\n name,\n duration_ms: Date.now() - startedAt,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return { name, fired: true, result, nextDueInMs: intervalMs };\n } catch (err) {\n const message = (err as Error).message ?? \"unknown error\";\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\n \"trigger.run.error\",\n {\n name,\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n return { name, fired: true, error: message, nextDueInMs: intervalMs };\n }\n}\n\n/**\n * Run every registered trigger that's due. Persists last_polled_at + last_run_summary.\n * Returns one outcome per trigger so the caller can log + decide sleep duration.\n */\nexport async function runDueTriggers(): Promise<TriggerRunOutcome[]> {\n startRun();\n const ledger = getLedger();\n const now = Date.now();\n const outcomes: TriggerRunOutcome[] = [];\n logEvent(\"watch.tick.start\", { trigger_count: TRIGGERS.length });\n\n for (const spec of TRIGGERS) {\n const stored = ledger.getTrigger(spec.name);\n const defaultEnabled = spec.enabledByDefault !== false;\n // Initialize on first sight.\n if (!stored) {\n ledger.upsertTrigger({\n name: spec.name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: defaultEnabled,\n });\n }\n\n const config = stored?.config_json\n ? (JSON.parse(stored.config_json) as Record<string, unknown>)\n : spec.defaultConfig;\n const intervalMs = effectiveIntervalMs(spec, config);\n\n const enabled = stored ? Boolean(stored.enabled) : defaultEnabled;\n if (!enabled) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n continue;\n }\n\n // Readiness gate: skip without touching last_polled_at so the watch loop\n // retries on the *next* tick once config is fixed, not on the next\n // interval boundary.\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n logEvent(\"trigger.run.skipped\", {\n name: spec.name,\n source: \"watch\",\n reason: readiness.reason,\n });\n continue;\n }\n\n const lastPolledMs = stored?.last_polled_at ? new Date(stored.last_polled_at).getTime() : 0;\n const dueAt = lastPolledMs + intervalMs;\n if (now < dueAt) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: dueAt - now });\n continue;\n }\n\n // Atomic claim — same pattern as fireTriggerNow (line 436-441) so the\n // scheduled-fire path can't race with a manual click on the same trigger\n // and double-spend. `staleCutoffIso` lets a fresh tick reclaim a row\n // whose previous `running_started_at` is older than MAX_RUN_AGE_MS (the\n // freshness gate already says \"not running\" but the marker never got\n // cleared — process killed before updateTriggerLastPoll ran, no boot\n // sweep yet). Cleared by updateTriggerLastPoll on success/error.\n const claimNowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_RUN_AGE_MS).toISOString();\n const claimed = ledger.markTriggerRunning(spec.name, claimNowIso, staleCutoffIso);\n if (!claimed) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n logEvent(\"trigger.run.skipped\", {\n name: spec.name,\n source: \"watch\",\n reason: \"already-running\",\n });\n continue;\n }\n\n const startedAt = Date.now();\n logEvent(\"trigger.run.start\", { name: spec.name, source: \"watch\" });\n try {\n const result = await spec.run(config);\n ledger.updateTriggerLastPoll({ name: spec.name, summary: result });\n logEvent(\"trigger.run.done\", {\n name: spec.name,\n duration_ms: Date.now() - startedAt,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n outcomes.push({ name: spec.name, fired: true, result, nextDueInMs: intervalMs });\n } catch (err) {\n const message = (err as Error).message ?? \"unknown error\";\n ledger.updateTriggerLastPoll({\n name: spec.name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\n \"trigger.run.error\",\n {\n name: spec.name,\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n outcomes.push({\n name: spec.name,\n fired: true,\n error: message,\n nextDueInMs: intervalMs,\n });\n }\n }\n logEvent(\"watch.tick.done\", { fired: outcomes.filter((o) => o.fired).length });\n return outcomes;\n}\n\nexport function nextSleepMs(outcomes: TriggerRunOutcome[]): number {\n if (outcomes.length === 0) return 60 * 60 * 1000;\n const min = Math.min(...outcomes.map((o) => o.nextDueInMs));\n // Floor at 60s, ceiling at 1h to keep the loop responsive without busy-waiting.\n return Math.max(60_000, Math.min(60 * 60 * 1000, min));\n}\n","import { getLedger, type ProspectRecord, type QueueRow } from \"@oneshot-gtm/core\";\nimport { type DraftedRow, isSupportedPlay, PLAYS } from \"@oneshot-gtm/plays\";\n\nexport interface DrainOpts {\n playName: string;\n limit?: number;\n dryRun: boolean;\n /** Required for accelerator-batch. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\nexport interface DrainOutcome {\n drained: number;\n sent: number;\n errors: Array<{ id: number; message: string }>;\n}\n\n/**\n * Pull approved rows for a play from target_queue, run them through the\n * existing motion play one target at a time, persist the draft for every row\n * (sent OR lint-held OR per-target error), then flip status to `sent` only\n * for the rows whose draft actually shipped. Per-target dispatch isolates\n * SDK throws (e.g. JobTimeoutError on agent.email()) so one bad target\n * can't kill the rest of the batch.\n */\nexport async function drainQueue(opts: DrainOpts): Promise<DrainOutcome> {\n const ledger = getLedger();\n const rows = ledger.dequeueApproved({ playName: opts.playName, limit: opts.limit ?? 50 });\n const outcome: DrainOutcome = { drained: rows.length, sent: 0, errors: [] };\n\n if (rows.length === 0) return outcome;\n\n // Global precondition: the play must exist. accelerator-batch no longer\n // needs a drain-level senderCohort — finder rows carry their own (stamped\n // from trigger config), and the play falls back to the run-level option.\n if (!isSupportedPlay(opts.playName)) {\n outcome.errors.push({ id: -1, message: `drain: unsupported play '${opts.playName}'` });\n return outcome;\n }\n\n for (const row of rows) {\n let draft: DraftedRow;\n try {\n draft = await dispatchOneTarget(opts, row);\n } catch (err) {\n const msg = ((err as Error).message ?? \"play failed\").slice(0, 200);\n draft = {\n subject: \"(error)\",\n body: \"\",\n flags: [`error: ${msg}`],\n sent: false,\n receiptIds: [],\n };\n outcome.errors.push({ id: row.id, message: msg });\n }\n\n try {\n ledger.setQueueDraft({\n id: row.id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: draft.sent,\n receiptIds: draft.receiptIds,\n dryRun: opts.dryRun,\n },\n });\n if (draft.sent && !opts.dryRun) {\n ledger.setQueueStatus({ id: row.id, status: \"sent\" });\n const prospectId = backfillProspectId(row);\n if (prospectId != null) {\n try {\n ledger.setQueueProspectId(row.id, prospectId);\n } catch {\n // best-effort backfill — a schema mismatch shouldn't break the drain\n }\n }\n outcome.sent++;\n }\n } catch (err) {\n outcome.errors.push({\n id: row.id,\n message: ((err as Error).message ?? \"persist failed\").slice(0, 200),\n });\n }\n }\n\n if (opts.dryRun) outcome.sent = rows.length; // would-be-sent (no actual send in dryRun)\n\n return outcome;\n}\n\nasync function dispatchOneTarget(opts: DrainOpts, row: QueueRow): Promise<DraftedRow> {\n const play = PLAYS[opts.playName];\n if (!play) throw new Error(`drain: unsupported play '${opts.playName}'`);\n const target = JSON.parse(row.payload_json) as unknown;\n const result = await play.run({\n dryRun: opts.dryRun,\n targets: [target],\n ...(opts.senderCohort ? { senderCohort: opts.senderCohort } : {}),\n ...(opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}),\n });\n return firstDraft(result.drafted);\n}\n\nfunction firstDraft(drafted: DraftedRow[]): DraftedRow {\n const d = drafted[0];\n if (!d) throw new Error(\"play returned no draft for this target\");\n return d;\n}\n\n/**\n * Map drafted-results back to queue-row IDs by position. Plays return one\n * draft per input target (in order), so drafted[i] always corresponds to\n * rows[i]. We only flip a row to `sent` when its draft actually sent (or in\n * dry-run, when we'd have sent it). The earlier `.filter().map((_, i) => rows[i])`\n * pattern was wrong — after filtering, the index no longer maps to the\n * original row, so partial sends marked the wrong rows as sent.\n */\nexport function idsForSentDrafts(\n drafted: Array<{ sent: boolean }>,\n rows: QueueRow[],\n dryRun: boolean,\n): number[] {\n const ids: number[] = [];\n for (let i = 0; i < drafted.length; i++) {\n const draft = drafted[i];\n const row = rows[i];\n if (!draft || !row) continue;\n if (draft.sent || dryRun) ids.push(row.id);\n }\n return ids;\n}\n\nfunction backfillProspectId(row: QueueRow | null): number | null {\n if (!row) return null;\n try {\n const payload = JSON.parse(row.payload_json) as { email?: string; founderEmail?: string };\n const email = payload.email ?? payload.founderEmail;\n if (!email) return null;\n const ledger = getLedger();\n const p = ledger.findProspectByEmail(email);\n return p ? p.id : null;\n } catch {\n return null;\n }\n}\n\nexport type { ProspectRecord };\n","import { loadConfig, logEvent, startRun, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport { effectiveIntervalMs, TRIGGERS } from \"@oneshot-gtm/find\";\nimport type { StrategistFrame, StrategistRequest } from \"@oneshot-gtm/shared-types\";\nimport { getLedger } from \"@oneshot-gtm/core\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * SSE chat endpoint for the trigger strategist.\n *\n * Request: { messages: Array<{ role: \"user\"|\"assistant\", content: string }> }\n *\n * The server composes the system prompt by interpolating the founder's\n * ICP/product + a one-paragraph brief per available trigger, then calls\n * `complete()` once per turn. The assistant uses ACTION markers\n * (<!--ACTION:enable:show-hn--> etc) to propose changes; the client renders\n * them as confirmation chips and posts back through the existing trigger\n * REST endpoints when the founder clicks.\n *\n * No native tool calling — keeps the contract simple, mirrors the soul-hunt-web\n * strategist pattern, and works with every provider that supports plain\n * chat completion.\n */\n/**\n * Pure body-shape check, extracted so HTTP tests can exercise the failure\n * paths without mocking fetch / Bun.serve. Returns either the parsed\n * messages or a status+error pair the caller can mirror back as JSON.\n */\nexport function validateStrategistBody(\n raw: unknown,\n):\n | { kind: \"ok\"; messages: StrategistRequest[\"messages\"] }\n | { kind: \"error\"; status: number; error: string } {\n if (!raw || typeof raw !== \"object\") {\n return { kind: \"error\", status: 400, error: \"messages must be a non-empty array\" };\n }\n const body = raw as Partial<StrategistRequest>;\n if (!Array.isArray(body.messages) || body.messages.length === 0) {\n return { kind: \"error\", status: 400, error: \"messages must be a non-empty array\" };\n }\n for (const m of body.messages) {\n if (!m || typeof m !== \"object\") {\n return { kind: \"error\", status: 400, error: \"each message must be an object\" };\n }\n if (m.role !== \"user\" && m.role !== \"assistant\") {\n return {\n kind: \"error\",\n status: 400,\n error: `each message.role must be 'user' or 'assistant' (got ${String(m.role)})`,\n };\n }\n if (typeof m.content !== \"string\") {\n return { kind: \"error\", status: 400, error: \"each message.content must be a string\" };\n }\n }\n return { kind: \"ok\", messages: body.messages };\n}\n\n/**\n * Pure cfg readiness check — strategist needs ICP + product to anchor\n * proposals. Same shape as validateStrategistBody so the route handler\n * can mirror either failure verbatim.\n */\nexport function validateCfgForStrategist(cfg: {\n icpOneLiner?: string | null;\n productOneLiner?: string | null;\n}): { kind: \"ok\" } | { kind: \"error\"; status: number; error: string } {\n if (!cfg.icpOneLiner || cfg.icpOneLiner.trim().length === 0) {\n return {\n kind: \"error\",\n status: 400,\n error: \"set ICP one-liner in /setup before opening the strategist\",\n };\n }\n if (!cfg.productOneLiner || cfg.productOneLiner.trim().length === 0) {\n return {\n kind: \"error\",\n status: 400,\n error: \"set product one-liner in /setup before opening the strategist\",\n };\n }\n return { kind: \"ok\" };\n}\n\nexport async function strategistRoute(req: Request): Promise<Response> {\n startRun();\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n const bodyCheck = validateStrategistBody(raw);\n if (bodyCheck.kind === \"error\") {\n return jsonResponse({ error: bodyCheck.error }, bodyCheck.status, req);\n }\n const messages = bodyCheck.messages;\n\n const cfg = loadConfig();\n const cfgCheck = validateCfgForStrategist(cfg);\n if (cfgCheck.kind === \"error\") {\n return jsonResponse({ error: cfgCheck.error }, cfgCheck.status, req);\n }\n\n // Pre-search the web for accelerator data when the founder's latest message\n // is about cohort selection. Strategist's training-data knowledge of which\n // accelerators exist + are accepting applications is stale by months; live\n // search gives it fresh context to ground its proposal in. Empty string when\n // not applicable — composeSystemPrompt then renders no extra section.\n const latestUserMessage = messages.toReversed().find((m) => m.role === \"user\")?.content ?? \"\";\n const webContext = await maybeAcceleratorWebContext(latestUserMessage, cfg.icpOneLiner!);\n\n const systemPrompt = composeSystemPrompt({\n productOneLiner: cfg.productOneLiner!,\n icpOneLiner: cfg.icpOneLiner!,\n webContext,\n });\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const encoder = new TextEncoder();\n let closed = false;\n const send = (event: StrategistFrame): void => {\n if (closed) return;\n try {\n controller.enqueue(\n encoder.encode(`event: ${event.kind}\\ndata: ${JSON.stringify(event)}\\n\\n`),\n );\n } catch {\n // Client disconnected mid-stream — controller already closed by\n // the runtime. Mark and stop trying to write.\n closed = true;\n }\n };\n\n const startedAt = Date.now();\n logEvent(\"strategist.turn.start\", { message_count: messages.length });\n try {\n send({ kind: \"thinking\" });\n const llm = await complete({\n messages: [\n { role: \"system\", content: systemPrompt },\n ...messages.map((m) => ({ role: m.role, content: m.content }) as const),\n ],\n temperature: 0.4,\n // 800 tokens truncated apply-config markers when the proposed JSON\n // ran long (a fully-populated github-topics config with topics +\n // vendors + yourEdge easily hits ~600 chars of JSON + prose). Bumped\n // to 4096 so a multi-field config never gets clipped mid-marker.\n maxTokens: 4096,\n });\n // Fake-stream the assistant content in chunks so the UI gets\n // progressive text instead of a single late drop. Real token streaming\n // is a future hop on intel.complete; this is good enough for chat\n // turns that complete in ~5-10s.\n //\n // Split on Unicode code points (Array.from), not UTF-16 code units —\n // a midstream split through a surrogate pair would yield mojibake on\n // the client. Chunk size is in code-points, not bytes.\n const codePoints = Array.from(llm.content);\n const CHUNK_CODE_POINTS = 60;\n for (let i = 0; i < codePoints.length; i += CHUNK_CODE_POINTS) {\n if (closed) break;\n send({ kind: \"delta\", text: codePoints.slice(i, i + CHUNK_CODE_POINTS).join(\"\") });\n }\n send({ kind: \"done\" });\n logEvent(\"strategist.turn.done\", {\n duration_ms: Date.now() - startedAt,\n response_chars: llm.content.length,\n });\n } catch (err) {\n const message = (err as Error).message ?? \"strategist failed\";\n logEvent(\n \"strategist.turn.error\",\n {\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n send({ kind: \"error\", message });\n } finally {\n closed = true;\n try {\n controller.close();\n } catch {\n // already closed by client disconnect — ignore\n }\n }\n },\n });\n\n // Mirror the loopback CORS handling used by /api/run/:playName.\n const origin = req.headers.get(\"origin\") ?? \"\";\n const isLoopback =\n origin === \"\" ||\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\");\n const sseHeaders: Record<string, string> = {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n \"x-accel-buffering\": \"no\",\n };\n if (isLoopback) {\n sseHeaders[\"Access-Control-Allow-Origin\"] = origin || \"http://127.0.0.1\";\n sseHeaders[\"Vary\"] = \"Origin\";\n }\n\n return new Response(stream, { status: 200, headers: sseHeaders });\n}\n\nfunction composeSystemPrompt(args: {\n productOneLiner: string;\n icpOneLiner: string;\n webContext: string;\n}): string {\n const template = loadPrompt(\"strategist-trigger\");\n const triggerCatalog = buildTriggerCatalog();\n return template\n .replace(\"{{productOneLiner}}\", args.productOneLiner)\n .replace(\"{{icpOneLiner}}\", args.icpOneLiner)\n .replace(\"{{triggerCatalog}}\", triggerCatalog)\n .replace(\"{{webContext}}\", args.webContext);\n}\n\n/**\n * Trigger phrases that imply the founder wants accelerator-batch help. Loose\n * enough to catch \"pick an accelerator\", \"yc batch\", \"any incubators?\", etc.\n * Tight enough that \"what should I enable for my ICP?\" doesn't fire.\n */\nconst ACCELERATOR_KEYWORDS =\n /\\b(accelerator|cohort|batch|incubator|y[ -]?combinator|techstars|antler|ai[ -]?grant|spc|south\\s*park|neo|500\\s*global)\\b/i;\n\n/**\n * If the founder's latest message asks about accelerator-batch, run a web\n * search for accelerators that fit their ICP and format the results as a\n * markdown block to inject into the system prompt. Empty string otherwise\n * (the placeholder collapses to nothing).\n *\n * Cost: ~$0.01 per accelerator-related strategist message. Latency: ~5-15s.\n * Wrapped in try/catch so a search hiccup doesn't block the strategist's\n * normal response.\n */\nasync function maybeAcceleratorWebContext(\n latestUserMessage: string,\n icpOneLiner: string,\n): Promise<string> {\n if (!ACCELERATOR_KEYWORDS.test(latestUserMessage)) return \"\";\n try {\n const query = `${icpOneLiner} startup accelerator OR cohort OR grant 2026 batch`;\n const search = await webSearch({ query, maxResults: 8 }, { playName: \"strategist\" });\n const results = search.result.results ?? [];\n if (results.length === 0) {\n logEvent(\"strategist.web_search.accelerators\", { query_chars: query.length, count: 0 });\n return \"\";\n }\n const lines = results.slice(0, 8).map((r) => {\n const title = (r.title ?? \"\").slice(0, 160);\n const url = (r.url ?? \"\").slice(0, 200);\n const desc = (r.description ?? \"\").slice(0, 240);\n return `- **${title}** — ${url}\\n ${desc}`;\n });\n logEvent(\"strategist.web_search.accelerators\", {\n query_chars: query.length,\n count: results.length,\n });\n return [\n \"## Recent accelerator landscape (web-searched for ICP fit)\",\n \"\",\n \"When proposing `accelerator-batch.cohort`, ground your pick in these\",\n \"results rather than your training-data memory of which accelerators exist.\",\n \"Reason from the founder's ICP to which accelerator's portfolio overlaps best.\",\n \"\",\n ...lines,\n ].join(\"\\n\");\n } catch (err) {\n logEvent(\n \"strategist.web_search.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return \"\";\n }\n}\n\nfunction buildTriggerCatalog(): string {\n const ledger = getLedger();\n const stored = new Map(ledger.listTriggers().map((r) => [r.name, r]));\n const lines: string[] = [];\n for (const spec of TRIGGERS) {\n const row = stored.get(spec.name);\n const defaultEnabled = spec.enabledByDefault !== false;\n const enabled = row ? Boolean(row.enabled) : defaultEnabled;\n const config = row?.config_json ? row.config_json : JSON.stringify(spec.defaultConfig);\n const intervalMs = effectiveIntervalMs(spec, safeParse(config));\n lines.push(\n `### ${spec.name}` +\n `\\n- enabled: ${enabled}` +\n `\\n- interval: ${humanInterval(intervalMs)}` +\n `\\n- current config: ${config}` +\n `\\n- brief: ${spec.configBrief ?? \"(no brief — defaults are sane)\"}`,\n );\n }\n return lines.join(\"\\n\\n\");\n}\n\nfunction safeParse(s: string): Record<string, unknown> | null {\n try {\n return JSON.parse(s) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction humanInterval(ms: number): string {\n if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n if (ms < 3600_000) return `${Math.round(ms / 60_000)}m`;\n if (ms < 24 * 3600_000) return `${(ms / 3600_000).toFixed(1)}h`;\n return `${(ms / (24 * 3600_000)).toFixed(1)}d`;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n configDir,\n getBalance,\n getLedger,\n llmApiKey,\n loadConfig,\n oneshotEnvReady,\n secretSource,\n} from \"@oneshot-gtm/core\";\n\nexport type CheckSeverity = \"ok\" | \"warn\" | \"fail\";\n\nexport interface CheckResult {\n name: string;\n severity: CheckSeverity;\n message: string;\n hint?: string;\n}\n\nexport async function runDoctor(): Promise<CheckResult[]> {\n const cfg = loadConfig();\n const results: CheckResult[] = [];\n\n results.push({\n name: \"config dir\",\n severity: existsSync(configDir()) ? \"ok\" : \"warn\",\n message: existsSync(configDir()) ? configDir() : `missing: ${configDir()}`,\n ...(existsSync(configDir()) ? {} : { hint: \"run: oneshot-gtm init\" }),\n });\n\n results.push({\n name: \"founder profile\",\n severity: cfg.founderName && cfg.productOneLiner ? \"ok\" : \"warn\",\n message:\n cfg.founderName && cfg.productOneLiner\n ? `${cfg.founderName} — ${cfg.productOneLiner}`\n : \"founder name + product one-liner not set\",\n ...(cfg.founderName && cfg.productOneLiner ? {} : { hint: \"run: oneshot-gtm config founder\" }),\n });\n\n const llmEnv = {\n openrouter: \"OPENROUTER_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n }[cfg.llmProvider];\n\n const llmSrc = secretSource(llmEnv as never);\n results.push({\n name: `llm key (${cfg.llmProvider})`,\n severity: llmApiKey(cfg.llmProvider) ? \"ok\" : \"fail\",\n message: llmApiKey(cfg.llmProvider) ? `set (${llmSrc ?? \"?\"})` : `${llmEnv} not set`,\n ...(llmApiKey(cfg.llmProvider) ? {} : { hint: `oneshot-gtm config keys` }),\n });\n\n const cdpSrc = secretSource(\"CDP_API_KEY_ID\");\n const pkSrc = secretSource(\"AGENT_PRIVATE_KEY\");\n const walletSrc = process.env.AGENT_PRIVATE_KEY ? pkSrc : cdpSrc;\n results.push({\n name: \"oneshot wallet env\",\n severity: oneshotEnvReady() ? \"ok\" : \"fail\",\n message: oneshotEnvReady()\n ? `${process.env.AGENT_PRIVATE_KEY ? \"AGENT_PRIVATE_KEY\" : \"CDP wallet\"} set (${walletSrc ?? \"?\"})`\n : \"no wallet credentials\",\n ...(oneshotEnvReady() ? {} : { hint: \"oneshot-gtm config keys\" }),\n });\n\n try {\n const ledger = getLedger();\n const sample = ledger.listReceipts({ limit: 1 });\n results.push({\n name: \"ledger\",\n severity: \"ok\",\n message: `ok, ${sample.length === 0 ? \"empty\" : \"has receipts\"} (${join(configDir(), \"ledger.sqlite\")})`,\n });\n } catch (err) {\n results.push({\n name: \"ledger\",\n severity: \"fail\",\n message: `error opening ledger: ${(err as Error).message}`,\n });\n }\n\n if (oneshotEnvReady()) {\n try {\n const bal = await getBalance();\n results.push({\n name: \"wallet balance\",\n severity: \"ok\",\n message: `${bal.balance}`,\n });\n } catch (err) {\n results.push({\n name: \"wallet balance\",\n severity: \"warn\",\n message: `could not fetch: ${(err as Error).message}`,\n });\n }\n }\n\n return results;\n}\n","import { runDoctor } from \"@oneshot-gtm/doctor\";\nimport type { DoctorCheck } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport async function doctor(req: Request): Promise<Response> {\n const results = await runDoctor();\n const checks: DoctorCheck[] = results.map((r) => {\n const out: DoctorCheck = { name: r.name, severity: r.severity, message: r.message };\n if (r.hint) out.hint = r.hint;\n return out;\n });\n return jsonResponse({ checks }, 200, req);\n}\n","import { PLAYS } from \"@oneshot-gtm/plays\";\nimport type { RunPlayRequest } from \"@oneshot-gtm/shared-types\";\n\nexport interface DraftedView {\n subject: string;\n body: string;\n flags: string[];\n receiptIds: number[];\n sent: boolean;\n}\n\nexport function toDraftedView(d: {\n subject: string;\n body: string;\n flags: string[];\n receiptIds: number[];\n sent: boolean;\n}): DraftedView {\n return {\n subject: d.subject,\n body: d.body,\n flags: d.flags,\n receiptIds: d.receiptIds,\n sent: d.sent,\n };\n}\n\n/**\n * Dispatch a play by name and return one DraftedView per target (in order).\n * Shared by the SSE /api/run endpoint (multi-target) and the /queue\n * regenerate endpoint (single-target dry-run). Throws on unsupported plays.\n */\nexport async function dispatchPlay(playName: string, body: RunPlayRequest): Promise<DraftedView[]> {\n const play = PLAYS[playName];\n if (!play) {\n throw new Error(`unsupported play: ${playName}`);\n }\n\n const result = await play.run({\n dryRun: body.dryRun,\n targets: body.targets,\n ...(body.senderCohort ? { senderCohort: body.senderCohort } : {}),\n ...(body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}),\n });\n return result.drafted.map(toDraftedView);\n}\n","import { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport { verifyAndFilterTargets } from \"@oneshot-gtm/plays\";\nimport type { RunPlayEvent, RunPlayRequest } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\nimport { dispatchPlay, type DraftedView } from \"./_play-dispatch.ts\";\n\nconst SUPPORTED = new Set([\n \"show-hn\",\n \"job-change\",\n \"post-funding\",\n \"accelerator-batch\",\n \"hiring-signal\",\n \"podcast-guest\",\n \"competitor-switch\",\n \"stack-consolidation\",\n \"repo-interest\",\n]);\n\nexport async function runPlay(req: Request, params: Record<string, string>): Promise<Response> {\n const playName = params[\"playName\"] ?? \"\";\n if (!SUPPORTED.has(playName)) {\n return jsonResponse(\n { error: `play '${playName}' is not exposed in the UI; use the CLI` },\n 400,\n req,\n );\n }\n\n let body: RunPlayRequest;\n try {\n body = (await req.json()) as RunPlayRequest;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n\n if (!Array.isArray(body.targets) || body.targets.length === 0) {\n return jsonResponse({ error: \"targets must be a non-empty array\" }, 400, req);\n }\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const encoder = new TextEncoder();\n const send = (event: RunPlayEvent): void => {\n // The client may disconnect mid-run (closed tab, navigation, or a\n // request timeout) — the controller is then closed and enqueue throws.\n // Swallow it: the server-side work (incl. any real send) still happened\n // and there's nothing to stream to. Avoids a false pipeline_error.\n try {\n controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\\n\\n`));\n } catch {\n // client gone — ignore\n }\n };\n\n try {\n // Build email → dedupeKey map BEFORE the verify filter potentially\n // drops rows. The verify pass changes target indices but not target\n // emails, so we can recover the dedupe key per drafted target by\n // looking up the email later. Manual /run entries (no fromQueue)\n // omit `dedupeKeys`; the map stays empty and the persist hook is\n // a no-op.\n const emailToDedupeKey = new Map<string, string>();\n if (body.dedupeKeys && body.dedupeKeys.length === body.targets.length) {\n body.targets.forEach((t, i) => {\n const target = t as { email?: string; founderEmail?: string };\n const email = target.email ?? target.founderEmail;\n const key = body.dedupeKeys?.[i];\n if (email && key) emailToDedupeKey.set(email, key);\n });\n }\n\n // Verify all target emails BEFORE dispatching to the play, so\n // undeliverable rows are dropped before we spend on LLM drafting.\n // Skipped on dryRun (no real spend during preview), AND skipped for\n // queue-sourced runs (dedupeKeys present) — those rows were already\n // verified at finder-enqueue time, so re-verifying just adds latency.\n // The verify event tells the UI which rows were dropped + why.\n const inputCount = body.targets.length;\n const fromQueue =\n Array.isArray(body.dedupeKeys) && body.dedupeKeys.length === body.targets.length;\n let verify: Awaited<ReturnType<typeof verifyAndFilterTargets>>;\n if (fromQueue) {\n verify = { verified: body.targets, dropped: [], receiptIds: [], costUsd: 0 };\n } else {\n send({ kind: \"stage\", stage: \"verifying\" });\n verify = await verifyAndFilterTargets(\n body.targets as Array<{ email?: string; founderEmail?: string }>,\n (t) => t.email ?? t.founderEmail ?? null,\n { playName, dryRun: body.dryRun },\n );\n }\n if (verify.dropped.length > 0) {\n send({\n kind: \"verify\",\n total: inputCount,\n verified: verify.verified.length,\n dropped: verify.dropped.map((d) => ({ email: d.email, reason: d.reason })),\n });\n }\n // If verify dropped every target, skip dispatch entirely — no point\n // calling the play with an empty array (the play would either\n // return empty drafted[] or throw on a \"founder profile incomplete\"\n // pre-check that's irrelevant when there's nothing to send).\n if (verify.verified.length === 0 && inputCount > 0) {\n send({ kind: \"done\", total: 0, sent: 0 });\n return;\n }\n const filteredBody: RunPlayRequest = { ...body, targets: verify.verified };\n\n send({ kind: \"stage\", stage: body.dryRun ? \"drafting\" : \"drafting + sending\" });\n const drafted = await dispatchPlay(playName, filteredBody);\n let sentCount = 0;\n drafted.forEach((d, index) => {\n send({ kind: \"draft\", index, subject: d.subject, body: d.body, flags: d.flags });\n if (d.receiptIds.length > 0) {\n send({ kind: \"send\", index, receiptIds: d.receiptIds });\n }\n if (d.sent) sentCount++;\n });\n send({ kind: \"done\", total: drafted.length, sent: sentCount });\n\n // Persist drafts to their originating queue rows so the founder can\n // review subject/body/flags later via /queue. Best-effort — the\n // SSE stream has already finished by here, so a SQLite hiccup\n // shouldn't surface as a user-visible error.\n if (emailToDedupeKey.size > 0) {\n persistDraftsToQueue({\n playName,\n verifiedTargets: verify.verified as Array<{ email?: string; founderEmail?: string }>,\n drafted,\n dryRun: body.dryRun,\n emailToDedupeKey,\n });\n }\n } catch (err) {\n // Log the full error server-side — the SSE error event only carries a\n // short message (e.g. the SDK's generic \"Tool request failed\"), which\n // is useless for diagnosis. The stack reveals which call failed\n // (sendEmail / enrichProfile / verifyEmail in oneshot.ts).\n const e = err as Error & {\n cause?: unknown;\n statusCode?: number;\n responseBody?: string;\n };\n const causeMsg =\n e?.cause instanceof Error ? e.cause.message : e?.cause ? String(e.cause) : null;\n logEvent(\n \"run.pipeline_error\",\n {\n play: playName,\n message_200: (e?.message ?? \"\").slice(0, 200),\n // OneShot SDK ToolError carries the failing call's HTTP status +\n // server response body — the actual reason, vs the generic message.\n status_code: typeof e?.statusCode === \"number\" ? e.statusCode : null,\n response_body_400:\n typeof e?.responseBody === \"string\" ? e.responseBody.slice(0, 400) : null,\n cause_200: causeMsg ? causeMsg.slice(0, 200) : null,\n stack_300: (e?.stack ?? \"\").slice(0, 300),\n },\n \"error\",\n );\n // Surface the real reason to the UI. The SDK's bare \"Tool request\n // failed\" is useless; the server response body carries the actual\n // error (e.g. {\"error\":\"domain_not_owned\",\"message\":\"…\"}).\n let uiMessage = e?.message ?? \"run failed\";\n if (typeof e?.statusCode === \"number\") {\n let detail = \"\";\n try {\n const parsed = JSON.parse(e.responseBody ?? \"\") as {\n message?: string;\n error?: string;\n };\n detail = parsed.message ?? parsed.error ?? \"\";\n } catch {\n detail = (e.responseBody ?? \"\").slice(0, 160);\n }\n uiMessage = `${uiMessage} (HTTP ${e.statusCode})${detail ? ` — ${detail}` : \"\"}`;\n }\n send({ kind: \"error\", index: -1, message: uiMessage });\n } finally {\n try {\n controller.close();\n } catch {\n // already closed (client disconnected) — ignore\n }\n }\n },\n });\n\n // Loopback-only CORS for SSE. The outer fetch handler already enforces\n // a loopback Host check before this runs, so we just mirror the origin\n // when it's loopback and otherwise omit the header (browser refuses\n // cross-origin response reads).\n const origin = req.headers.get(\"origin\") ?? \"\";\n const isLoopback =\n origin === \"\" ||\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\");\n const sseHeaders: Record<string, string> = {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n \"x-accel-buffering\": \"no\",\n };\n if (isLoopback) {\n sseHeaders[\"Access-Control-Allow-Origin\"] = origin || \"http://127.0.0.1\";\n sseHeaders[\"Vary\"] = \"Origin\";\n }\n\n return new Response(stream, {\n status: 200,\n headers: sseHeaders,\n });\n}\n\n/**\n * After the SSE stream completes, write each generated draft to its\n * originating `target_queue` row. Best-effort: a SQL hiccup during\n * persistence is logged via `error.swallowed` and doesn't affect what the\n * UI already saw on the wire. Indices match because `verifiedTargets[i]`\n * corresponds to `drafted[i]` (both come from the same dispatch).\n */\nfunction persistDraftsToQueue(input: {\n playName: string;\n verifiedTargets: Array<{ email?: string; founderEmail?: string }>;\n drafted: DraftedView[];\n dryRun: boolean;\n emailToDedupeKey: Map<string, string>;\n}): void {\n const ledger = getLedger();\n for (let i = 0; i < input.drafted.length; i++) {\n const target = input.verifiedTargets[i];\n const draft = input.drafted[i];\n if (!target || !draft) continue;\n const email = target.email ?? target.founderEmail;\n if (!email) continue;\n const dedupeKey = input.emailToDedupeKey.get(email);\n if (!dedupeKey) continue;\n try {\n const row = ledger.getQueueRowByDedupe(input.playName, dedupeKey);\n if (!row) continue;\n ledger.setQueueDraft({\n id: row.id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: draft.sent,\n receiptIds: draft.receiptIds,\n dryRun: input.dryRun,\n },\n });\n // A real, successful send must leave the approved pool — otherwise the\n // row stays `approved` and every subsequent drain (esp. limit 1) re-loads\n // the same first approved target forever. Held drafts (lint flags →\n // sent:false) and dry-run previews intentionally stay approved.\n if (draft.sent && !input.dryRun) {\n ledger.setQueueStatus({ id: row.id, status: \"sent\" });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"run.persistDraftsToQueue\",\n play: input.playName,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n}\n","import { getLedger, type QueueRow, type QueueStatus } from \"@oneshot-gtm/core\";\nimport { drainQueue } from \"@oneshot-gtm/find\";\nimport { enrollInCadence, sendDraftedEmail } from \"@oneshot-gtm/plays\";\nimport type {\n DrainRequest,\n DrainResult,\n LastDraft,\n QueueCounts,\n QueueRowView,\n RunPlayRequest,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\nimport { dispatchPlay } from \"./_play-dispatch.ts\";\n\nfunction toView(row: QueueRow): QueueRowView {\n let payload: unknown = null;\n try {\n payload = JSON.parse(row.payload_json);\n } catch {\n payload = row.payload_json;\n }\n let lastDraft: LastDraft | null = null;\n if (row.last_draft_json) {\n try {\n const parsed = JSON.parse(row.last_draft_json) as Partial<LastDraft>;\n // Defensive shape check — older rows or future schema drift\n // shouldn't crash the queue listing.\n if (parsed && typeof parsed.subject === \"string\" && typeof parsed.body === \"string\") {\n lastDraft = {\n subject: parsed.subject,\n body: parsed.body,\n flags: Array.isArray(parsed.flags) ? parsed.flags : [],\n sent: parsed.sent === true,\n receiptIds: Array.isArray(parsed.receiptIds) ? parsed.receiptIds : [],\n dryRun: parsed.dryRun === true,\n draftedAt: typeof parsed.draftedAt === \"string\" ? parsed.draftedAt : \"\",\n };\n }\n } catch {\n lastDraft = null;\n }\n }\n return {\n id: row.id,\n playName: row.play_name,\n payload,\n dedupeKey: row.dedupe_key,\n source: row.source,\n status: row.status,\n foundAt: row.found_at,\n reviewedAt: row.reviewed_at,\n sentAt: row.sent_at,\n notes: row.notes,\n prospectId: row.prospect_id,\n lastDraft,\n lastDraftedAt: row.last_drafted_at,\n };\n}\n\nexport function listQueueRoute(req: Request): Response {\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? undefined;\n const status = (url.searchParams.get(\"status\") ?? undefined) as QueueStatus | undefined;\n const limit = Math.min(500, Number.parseInt(url.searchParams.get(\"limit\") ?? \"200\", 10) || 200);\n const ledger = getLedger();\n const filterArgs: { playName?: string; status?: QueueStatus; limit?: number } = { limit };\n if (playName) filterArgs.playName = playName;\n if (status) filterArgs.status = status;\n const rows = ledger.listQueue(filterArgs);\n const counts: QueueCounts = ledger.queueCounts();\n return jsonResponse({ rows: rows.map(toView), counts }, 200, req);\n}\n\nexport async function approveQueueRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n ledger.setQueueStatus({ id, status: \"approved\" });\n return jsonResponse({ ok: true }, 200, req);\n}\n\nexport async function rejectQueueRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n let body: { reason?: string } = {};\n try {\n body = (await req.json()) as { reason?: string };\n } catch {\n // empty body is fine\n }\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n ledger.setQueueStatus(\n body.reason ? { id, status: \"rejected\", notes: body.reason } : { id, status: \"rejected\" },\n );\n return jsonResponse({ ok: true }, 200, req);\n}\n\nexport async function approveAllRoute(req: Request): Promise<Response> {\n let body: { play?: string } = {};\n try {\n body = (await req.json()) as { play?: string };\n } catch {\n // empty body is fine\n }\n const ledger = getLedger();\n const n = ledger.approveAllPending(body.play ? { playName: body.play } : {});\n return jsonResponse({ approved: n }, 200, req);\n}\n\nexport async function drainQueueRoute(req: Request): Promise<Response> {\n let body: DrainRequest;\n try {\n body = (await req.json()) as DrainRequest;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!body.playName) return jsonResponse({ error: \"playName required\" }, 400, req);\n const result = await drainQueue({\n playName: body.playName,\n limit: body.limit ?? 10,\n dryRun: !!body.dryRun,\n ...(body.senderCohort ? { senderCohort: body.senderCohort } : {}),\n ...(body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}),\n });\n const view: DrainResult = {\n drained: result.drained,\n sent: result.sent,\n errors: result.errors,\n };\n return jsonResponse(view, 200, req);\n}\n\n/**\n * Re-draft a single queue row in PREVIEW mode and overwrite its persisted\n * draft. Always dry-run: enrichment is skipped and nothing is sent, even\n * when the fresh draft is lint-clean. Lets the founder re-roll a held or\n * unsatisfying draft from /queue without leaving the page or risking a\n * send. The new draft replaces `last_draft_json` so the UI shows it on the\n * next queue refetch.\n */\nexport async function regenerateDraftRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n\n let target: unknown;\n try {\n target = JSON.parse(row.payload_json);\n } catch {\n return jsonResponse({ error: \"row payload is not valid JSON\" }, 400, req);\n }\n\n // Carry through any per-play extras the payload happens to hold. Only\n // accelerator-batch needs senderCohort, which usually isn't on the row —\n // dispatchPlay then throws a clear error, surfaced here as a 400.\n const payloadObj = (target && typeof target === \"object\" ? target : {}) as Record<\n string,\n unknown\n >;\n const body: RunPlayRequest = {\n dryRun: true,\n targets: [target],\n ...(typeof payloadObj[\"senderCohort\"] === \"string\"\n ? { senderCohort: payloadObj[\"senderCohort\"] }\n : {}),\n ...(typeof payloadObj[\"freeForCohortOffer\"] === \"string\"\n ? { freeForCohortOffer: payloadObj[\"freeForCohortOffer\"] }\n : {}),\n };\n\n let drafted: Awaited<ReturnType<typeof dispatchPlay>>;\n try {\n drafted = await dispatchPlay(row.play_name, body);\n } catch (err) {\n return jsonResponse({ error: (err as Error).message }, 400, req);\n }\n const draft = drafted[0];\n if (!draft) return jsonResponse({ error: \"no draft produced\" }, 500, req);\n\n ledger.setQueueDraft({\n id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: false,\n receiptIds: [],\n dryRun: true,\n },\n });\n\n const out: LastDraft = {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: false,\n receiptIds: [],\n dryRun: true,\n draftedAt: new Date().toISOString(),\n };\n return jsonResponse(out, 200, req);\n}\n\n/**\n * Send the row's already-reviewed draft VERBATIM — the persisted\n * `last_draft_json` subject/body, no LLM re-roll. This is the review-then-send\n * model: the founder regenerates until the draft is clean, then sends exactly\n * that. Routes through `sendDraftedEmail` (the canonical send: core sendEmail\n * applies HTML + from_name formatting, records the sequence event, upserts the\n * prospect), then enrolls the cadence and flips the row to `sent`. Requires a\n * clean (lint-flag-free), not-yet-sent draft.\n */\nexport async function sendDraftRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n if (row.status === \"sent\") return jsonResponse({ error: \"row already sent\" }, 400, req);\n if (!row.last_draft_json) {\n return jsonResponse({ error: \"no draft to send — regenerate a draft first\" }, 400, req);\n }\n\n let parsed: Partial<LastDraft>;\n try {\n parsed = JSON.parse(row.last_draft_json) as Partial<LastDraft>;\n } catch {\n return jsonResponse({ error: \"stored draft is not valid JSON\" }, 400, req);\n }\n const subject = typeof parsed.subject === \"string\" ? parsed.subject : \"\";\n const body = typeof parsed.body === \"string\" ? parsed.body : \"\";\n const flags = Array.isArray(parsed.flags) ? parsed.flags : [];\n if (!subject || !body) {\n return jsonResponse({ error: \"stored draft is empty — regenerate first\" }, 400, req);\n }\n if (flags.length > 0) {\n return jsonResponse(\n { error: \"draft has lint flags — regenerate to clear them before sending\" },\n 400,\n req,\n );\n }\n if (parsed.sent === true) return jsonResponse({ error: \"draft already sent\" }, 400, req);\n\n let payload: Record<string, unknown> = {};\n try {\n const p = JSON.parse(row.payload_json);\n if (p && typeof p === \"object\") payload = p as Record<string, unknown>;\n } catch {\n // fall through — handled by the missing-email check below\n }\n const str = (k: string): string | null => (typeof payload[k] === \"string\" ? payload[k] : null);\n const email = str(\"email\") ?? str(\"founderEmail\");\n if (!email) return jsonResponse({ error: \"row has no recipient email\" }, 400, req);\n\n let result: Awaited<ReturnType<typeof sendDraftedEmail>>;\n try {\n result = await sendDraftedEmail({\n playName: row.play_name,\n to: email,\n draft: { subject, body },\n flags: [],\n prospectMeta: {\n name: str(\"name\") ?? str(\"founderName\"),\n email,\n company: str(\"company\"),\n linkedin_url: str(\"linkedinUrl\"),\n phone: str(\"phone\"),\n source: row.play_name,\n },\n dryRun: false,\n });\n } catch (err) {\n return jsonResponse({ error: (err as Error).message ?? \"send failed\" }, 400, req);\n }\n if (!result.sent) return jsonResponse({ error: \"send did not complete\" }, 500, req);\n\n const prospect = ledger.findProspectByEmail(email);\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: row.play_name });\n ledger.setQueueStatus({ id, status: \"sent\" });\n ledger.setQueueDraft({\n id,\n draft: { subject, body, flags: [], sent: true, receiptIds: result.receiptIds, dryRun: false },\n });\n\n return jsonResponse({ sent: true, receiptIds: result.receiptIds }, 200, req);\n}\n","import { getLedger, type TriggerRow } from \"@oneshot-gtm/core\";\nimport {\n checkReadiness,\n effectiveIntervalMs,\n fireTriggerNow,\n getTriggerRunningSince,\n isTriggerRunning,\n TRIGGERS,\n type Readiness,\n type TriggerSpec,\n} from \"@oneshot-gtm/find\";\nimport type { RunTriggerResult, TriggerView } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport function toView(\n name: string,\n defaultIntervalMs: number,\n row: TriggerRow | null,\n spec: TriggerSpec | null,\n): TriggerView {\n let lastSummary: unknown = null;\n if (row?.last_run_summary) {\n try {\n lastSummary = JSON.parse(row.last_run_summary);\n } catch {\n lastSummary = row.last_run_summary;\n }\n }\n let config: Record<string, unknown> | null = null;\n if (row?.config_json) {\n try {\n const parsed = JSON.parse(row.config_json) as unknown;\n if (parsed && typeof parsed === \"object\") config = parsed as Record<string, unknown>;\n } catch {\n config = null;\n }\n }\n const defaultEnabled = spec ? spec.enabledByDefault !== false : true;\n const intervalMs = spec ? effectiveIntervalMs(spec, config) : defaultIntervalMs;\n const runningSinceMs = getTriggerRunningSince(name);\n // Explicit annotation keeps the discriminated-union narrowing intact\n // (the literal { ready: true } branch would otherwise widen the union).\n const readiness: Readiness = spec\n ? checkReadiness(spec, config ?? spec.defaultConfig)\n : { ready: true };\n return {\n name,\n enabled: row ? Boolean(row.enabled) : defaultEnabled,\n defaultIntervalMs,\n intervalMs,\n config,\n defaultConfig: spec ? spec.defaultConfig : null,\n lastPolledAt: row?.last_polled_at ?? null,\n lastRunSummary: lastSummary,\n running: isTriggerRunning(name),\n runningSince: runningSinceMs != null ? new Date(runningSinceMs).toISOString() : null,\n ready: readiness.ready,\n notReadyReason: readiness.ready ? null : readiness.reason,\n };\n}\n\nexport function listTriggersRoute(req: Request): Response {\n const ledger = getLedger();\n const rows = ledger.listTriggers();\n const byName = new Map(rows.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const views: TriggerView[] = [];\n for (const spec of TRIGGERS) {\n seen.add(spec.name);\n views.push(toView(spec.name, spec.defaultIntervalMs, byName.get(spec.name) ?? null, spec));\n }\n // Surface any historical triggers stored in the ledger that no longer exist\n // in the registry (e.g. a deprecated cohort) so the founder can disable them.\n for (const row of rows) {\n if (seen.has(row.name)) continue;\n views.push(toView(row.name, 24 * 3600 * 1000, row, null));\n }\n return jsonResponse({ triggers: views }, 200, req);\n}\n\nexport async function setTriggerEnabledRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n let body: { enabled?: boolean } = {};\n try {\n body = (await req.json()) as { enabled?: boolean };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (typeof body.enabled !== \"boolean\") {\n return jsonResponse({ error: \"enabled (boolean) required\" }, 400, req);\n }\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n const spec = TRIGGERS.find((t) => t.name === name) ?? null;\n // Readiness gate: block *enabling* an unready trigger so the scheduler\n // doesn't sit in a loop skipping it every tick. Disabling is always allowed.\n if (body.enabled && spec) {\n const config = stored?.config_json\n ? (JSON.parse(stored.config_json) as Record<string, unknown>)\n : spec.defaultConfig;\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n return jsonResponse(\n {\n error: `trigger '${name}' not ready: ${readiness.reason}`,\n name,\n reason: readiness.reason,\n },\n 409,\n req,\n );\n }\n }\n if (!stored) {\n if (!spec) return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: body.enabled,\n });\n } else {\n ledger.setTriggerEnabled(name, body.enabled);\n }\n return jsonResponse({ ok: true, name, enabled: body.enabled }, 200, req);\n}\n\nexport async function setTriggerConfigRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n let body: { config?: unknown } = {};\n try {\n body = (await req.json()) as { config?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!body.config || typeof body.config !== \"object\") {\n return jsonResponse({ error: \"config (object) required\" }, 400, req);\n }\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n if (!stored) {\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(body.config),\n enabled: true,\n });\n } else {\n ledger.setTriggerConfig(name, JSON.stringify(body.config));\n }\n return jsonResponse({ ok: true, name }, 200, req);\n}\n\n/** Fire-and-forget: 202 on kick-off, 409 if already running. UI polls `GET /api/triggers`. */\nexport function runTriggerRoute(req: Request, params: Record<string, string>): Response {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n if (!TRIGGERS.some((t) => t.name === name)) {\n return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n }\n try {\n fireTriggerNow(name);\n } catch (err) {\n const message = (err as Error).message ?? \"failed to fire\";\n if (message.includes(\"already running\")) {\n return jsonResponse({ error: message, name, running: true }, 409, req);\n }\n if (message.startsWith(\"not ready:\")) {\n const reason = message.slice(\"not ready:\".length).trim();\n return jsonResponse({ error: message, name, reason, ready: false }, 409, req);\n }\n return jsonResponse({ error: message }, 500, req);\n }\n const view: RunTriggerResult = {\n name,\n fired: true,\n pending: true,\n result: null,\n error: null,\n };\n return jsonResponse(view, 202, req);\n}\n","import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { homeMetrics } from \"./api/home.ts\";\nimport {\n listCadences,\n getCadence,\n stopCadence,\n previewCadenceStepRoute,\n sendCadenceStepRoute,\n previewCadenceBatchRoute,\n sendCadenceBatchRoute,\n} from \"./api/cadences.ts\";\nimport { listReceipts, getReceipt } from \"./api/receipts.ts\";\nimport { listInboxRoute } from \"./api/inbox.ts\";\nimport { listPlays, setCadenceRoute } from \"./api/plays.ts\";\nimport { measureCac, measureRocs, recordOutcome } from \"./api/measure.ts\";\nimport { setup, getSetupStatus } from \"./api/setup.ts\";\nimport { deriveIcpRoute } from \"./api/derive-icp.ts\";\nimport { strategistRoute } from \"./api/strategist.ts\";\nimport { doctor } from \"./api/doctor.ts\";\nimport { runPlay } from \"./api/run.ts\";\nimport {\n approveAllRoute,\n approveQueueRoute,\n drainQueueRoute,\n listQueueRoute,\n regenerateDraftRoute,\n rejectQueueRoute,\n sendDraftRoute,\n} from \"./api/queue.ts\";\nimport {\n listTriggersRoute,\n runTriggerRoute,\n setTriggerConfigRoute,\n setTriggerEnabledRoute,\n} from \"./api/triggers.ts\";\n\ninterface ServerOptions {\n port: number;\n}\n\ninterface RouteHandler {\n (req: Request, params: Record<string, string>): Promise<Response> | Response;\n}\n\ninterface RouteEntry {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n handler: RouteHandler;\n}\n\nfunction route(method: string, pattern: string, handler: RouteHandler): RouteEntry {\n const paramNames: string[] = [];\n const regexStr = pattern.replace(/:(\\w+)/g, (_, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n return { method, pattern: new RegExp(`^${regexStr}$`), paramNames, handler };\n}\n\nconst routes: RouteEntry[] = [\n route(\"GET\", \"/api/home\", homeMetrics),\n route(\"GET\", \"/api/cadences\", listCadences),\n route(\"GET\", \"/api/cadences/:id\", getCadence),\n route(\"POST\", \"/api/cadences/:id/stop\", stopCadence),\n route(\"POST\", \"/api/cadences/:id/preview-next\", previewCadenceStepRoute),\n route(\"POST\", \"/api/cadences/:id/send-next\", sendCadenceStepRoute),\n route(\"POST\", \"/api/cadences/preview-batch\", previewCadenceBatchRoute),\n route(\"POST\", \"/api/cadences/send-batch\", sendCadenceBatchRoute),\n route(\"GET\", \"/api/receipts\", listReceipts),\n route(\"GET\", \"/api/receipts/:id\", getReceipt),\n route(\"GET\", \"/api/inbox\", listInboxRoute),\n route(\"GET\", \"/api/plays\", listPlays),\n route(\"POST\", \"/api/plays/:name/cadence\", setCadenceRoute),\n route(\"GET\", \"/api/measure/cac\", measureCac),\n route(\"GET\", \"/api/measure/rocs\", measureRocs),\n route(\"POST\", \"/api/measure/outcome\", recordOutcome),\n route(\"GET\", \"/api/setup\", getSetupStatus),\n route(\"POST\", \"/api/setup\", setup),\n route(\"POST\", \"/api/setup/derive-icp\", deriveIcpRoute),\n route(\"POST\", \"/api/strategist/stream\", strategistRoute),\n route(\"GET\", \"/api/doctor\", doctor),\n route(\"POST\", \"/api/run/:playName\", runPlay),\n route(\"GET\", \"/api/queue\", listQueueRoute),\n route(\"POST\", \"/api/queue/approve-all\", approveAllRoute),\n route(\"POST\", \"/api/queue/drain\", drainQueueRoute),\n route(\"POST\", \"/api/queue/:id/approve\", approveQueueRoute),\n route(\"POST\", \"/api/queue/:id/reject\", rejectQueueRoute),\n route(\"POST\", \"/api/queue/:id/regenerate\", regenerateDraftRoute),\n route(\"POST\", \"/api/queue/:id/send-draft\", sendDraftRoute),\n route(\"GET\", \"/api/triggers\", listTriggersRoute),\n route(\"POST\", \"/api/triggers/:name/enabled\", setTriggerEnabledRoute),\n route(\"POST\", \"/api/triggers/:name/config\", setTriggerConfigRoute),\n route(\"POST\", \"/api/triggers/:name/run\", runTriggerRoute),\n];\n\nfunction findRoute(req: Request): { handler: RouteHandler; params: Record<string, string> } | null {\n const url = new URL(req.url);\n for (const r of routes) {\n if (r.method !== req.method) continue;\n const m = r.pattern.exec(url.pathname);\n if (!m) continue;\n const params: Record<string, string> = {};\n r.paramNames.forEach((name, i) => {\n params[name] = decodeURIComponent(m[i + 1] ?? \"\");\n });\n return { handler: r.handler, params };\n }\n return null;\n}\n\nfunction getStaticDir(): string | null {\n // Layouts we might run from:\n // 1. Source dev: apps/server/src/server.ts → ../../web/dist\n // 2. Bundle: apps/server/dist/bin.mjs → ../../web/dist\n // 3. npm publish: <pkg>/dist/bin.mjs → ./web (we copy apps/web/dist here)\n const here = fileURLToPath(new URL(\".\", import.meta.url));\n const candidates = [\n join(here, \"..\", \"..\", \"web\", \"dist\"),\n join(here, \"..\", \"..\", \"..\", \"web\", \"dist\"),\n join(here, \"web\"),\n ];\n for (const c of candidates) {\n if (existsSync(join(c, \"index.html\"))) return c;\n }\n return null;\n}\n\nasync function serveStatic(staticDir: string, pathname: string): Promise<Response | null> {\n const root = resolve(staticDir);\n const rel = pathname === \"/\" ? \"index.html\" : pathname.replace(/^\\/+/, \"\");\n const candidate = resolve(root, rel);\n // Reject anything that escapes the static dir. `resolve` collapses `..`\n // segments so the prefix check catches both raw `..` and encoded variants.\n if (candidate !== root && !candidate.startsWith(`${root}/`)) return null;\n if (existsSync(candidate)) {\n return new Response(Bun.file(candidate));\n }\n // SPA fallback: serve index.html for non-asset paths (paths without a dot).\n if (!rel.includes(\".\")) {\n return new Response(Bun.file(join(root, \"index.html\")));\n }\n return null;\n}\n\nexport function buildFetchHandler(): (req: Request) => Promise<Response> | Response {\n const staticDir = getStaticDir();\n const viteDevUrl = process.env[\"VITE_DEV_SERVER_URL\"] ?? null;\n\n return async function fetchHandler(req) {\n const url = new URL(req.url);\n\n // DNS-rebinding defense: reject any request whose Host header isn't a\n // loopback name. An attacker who points evil.com at 127.0.0.1 still\n // sends Host: evil.com to the browser, which we reject here.\n if (!isLoopbackHost(req.headers.get(\"host\"))) {\n return new Response(\"forbidden: non-loopback host\", {\n status: 403,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n\n // CORS for vite dev server (different port). Non-loopback origins get\n // an empty header set from corsHeaders() → browser blocks both\n // preflight and the response, preventing CSRF-style side effects on\n // mutating endpoints (e.g. POST /api/run/$playName triggering spend).\n if (req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: corsHeaders(req),\n });\n }\n\n if (url.pathname.startsWith(\"/api/\")) {\n const match = findRoute(req);\n if (!match) {\n return jsonResponse({ error: \"not found\", path: url.pathname }, 404, req);\n }\n try {\n const res = await match.handler(req, match.params);\n // Inject CORS headers if not already set\n for (const [k, v] of Object.entries(corsHeaders(req))) {\n if (!res.headers.has(k)) res.headers.set(k, v);\n }\n return res;\n } catch (err) {\n return jsonResponse({ error: (err as Error).message ?? \"internal error\" }, 500, req);\n }\n }\n\n // Static / SPA serving\n if (staticDir) {\n const r = await serveStatic(staticDir, url.pathname);\n if (r) return r;\n }\n\n // Dev: tell the user where the UI is hosted by Vite.\n if (viteDevUrl) {\n return new Response(\n `<!doctype html><title>oneshot-gtm dev</title>` +\n `<p>API is running at <code>${url.origin}/api</code>.</p>` +\n `<p>Vite dev server should be at <a href=\"${viteDevUrl}\">${viteDevUrl}</a>.</p>`,\n { headers: { \"content-type\": \"text/html\" } },\n );\n }\n\n return new Response(\n \"oneshot-gtm server running. Build the web app to see the dashboard, or set VITE_DEV_SERVER_URL.\",\n { status: 200, headers: { \"content-type\": \"text/plain\" } },\n );\n };\n}\n\n/** Shared options; idleTimeout 255 is the max — Bun defaults to 10s which is short for sync handlers. */\nexport const SERVER_BASE_OPTS = { idleTimeout: 255 } as const;\n\nexport async function startServer(\n opts: ServerOptions,\n): Promise<{ url: string; server: ReturnType<typeof Bun.serve> }> {\n const server = Bun.serve({\n port: opts.port,\n hostname: \"127.0.0.1\",\n ...SERVER_BASE_OPTS,\n fetch: buildFetchHandler(),\n });\n\n return { url: `http://127.0.0.1:${server.port}`, server };\n}\n\nfunction isLoopbackOrigin(origin: string): boolean {\n // Empty origin = same-origin request (curl, server-side fetch); allow.\n if (origin === \"\") return true;\n return (\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\")\n );\n}\n\nfunction isLoopbackHost(host: string | null): boolean {\n if (!host) return false;\n const hostname = host.replace(/:\\d+$/, \"\").toLowerCase();\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\";\n}\n\nfunction corsHeaders(req: Request): Record<string, string> {\n // Loopback-only. Non-loopback origins get NO Access-Control-* headers,\n // which makes the browser refuse both the preflight and any cross-origin\n // response read.\n const origin = req.headers.get(\"origin\") ?? \"\";\n if (!isLoopbackOrigin(origin)) {\n return {};\n }\n return {\n \"Access-Control-Allow-Origin\": origin || \"http://127.0.0.1\",\n \"Access-Control-Allow-Methods\": \"GET,POST,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n Vary: \"Origin\",\n };\n}\n\nexport function jsonResponse(body: unknown, status = 200, req?: Request): Response {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json; charset=utf-8\",\n };\n if (req) Object.assign(headers, corsHeaders(req));\n return new Response(JSON.stringify(body), { status, headers });\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { nextSleepMs, runDueTriggers } from \"@oneshot-gtm/find\";\n\n/**\n * Background scheduler that polls registered triggers on their interval and\n * fires due ones. Runs inside the dashboard server process so the founder\n * doesn't have to keep `bun run cli -- find watch` open in a second terminal\n * for enabled triggers to actually execute.\n *\n * Safety:\n * - Per-trigger atomic claim (in `runDueTriggers`) prevents double-spend if\n * a manual /api/triggers/:name/run click races with a scheduled tick.\n * - Tick-level try/catch keeps a corrupted ledger row or unexpected throw\n * from permanently killing the loop; backs off 60s before retrying.\n * - In-flight finder runs that haven't returned when the process exits get\n * killed mid-run; the cold-boot `sweepStaleRunningTriggers` cleans up\n * the orphaned `running_started_at` markers on the next start.\n */\nexport interface SchedulerHandle {\n stop(): void;\n}\n\nconst FIRST_TICK_DELAY_MS = 5_000;\nconst ERROR_BACKOFF_MS = 60_000;\n\nexport function startScheduler(): SchedulerHandle {\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const tick = async (): Promise<void> => {\n if (cancelled) return;\n try {\n const outcomes = await runDueTriggers();\n const fired = outcomes.filter((o) => o.fired).length;\n logEvent(\"scheduler.tick.done\", { fired, source: \"server\" });\n if (cancelled) return;\n const sleepMs = nextSleepMs(outcomes);\n timer = setTimeout(() => void tick(), sleepMs);\n } catch (err) {\n logEvent(\n \"scheduler.tick.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n if (!cancelled) timer = setTimeout(() => void tick(), ERROR_BACKOFF_MS);\n }\n };\n\n // Short initial delay so the HTTP server is bound and the cold-boot sweep\n // has finished writing `killed_by_restart` summaries before the first tick.\n timer = setTimeout(() => void tick(), FIRST_TICK_DELAY_MS);\n\n return {\n stop(): void {\n cancelled = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n },\n };\n}\n","import open from \"open\";\nimport { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport { buildFetchHandler, SERVER_BASE_OPTS, startServer } from \"./server.ts\";\nimport { startScheduler, type SchedulerHandle } from \"./scheduler.ts\";\n\n// Runtime guard: this binary depends on Bun (bun:sqlite, Bun.serve, Bun.stdin).\n// If invoked under plain node, fail loudly with an install hint.\nif (typeof (globalThis as { Bun?: unknown }).Bun === \"undefined\") {\n process.stderr.write(\n \"oneshot-gtm-server requires the Bun runtime.\\n\" +\n \"Install: curl -fsSL https://bun.sh/install | bash\\n\" +\n \"Re-run: bunx oneshot-gtm-server\\n\",\n );\n process.exit(1);\n}\n\nconst port = Number.parseInt(process.env[\"PORT\"] ?? \"3030\", 10);\nconst noBrowser = process.env[\"ONESHOT_GTM_NO_BROWSER\"] === \"1\";\n\n// Cache the server on globalThis so Bun's `--hot` re-execution (same\n// process) can swap handlers via `server.reload({fetch})` instead of\n// rebinding the port, which would fail with EADDRINUSE.\ntype BunServer = Awaited<ReturnType<typeof startServer>>[\"server\"];\nconst cache = globalThis as {\n __oneshotGtmServer?: BunServer;\n __oneshotGtmScheduler?: SchedulerHandle;\n};\n\nif (cache.__oneshotGtmServer) {\n // Hot reload: keep the existing scheduler running. The reloaded module\n // graph picks up source changes on its next tick (5s-1h away).\n cache.__oneshotGtmServer.reload({\n ...SERVER_BASE_OPTS,\n fetch: buildFetchHandler(),\n });\n process.stdout.write(`\\n oneshot-gtm dashboard: http://127.0.0.1:${port} (reloaded)\\n\\n`);\n} else {\n // Cold boot only — sweep any trigger rows that were marked running by a\n // previous process that never got to call updateTriggerLastPoll\n // (bun --watch re-exec, OS reboot, OOM kill, hung SDK call when the\n // process was killed). Writes a `killed_by_restart` last_run_summary so\n // the UI shows the truth instead of frozen-from-an-hour-ago state.\n //\n // `maxAgeMs: 0` is intentional and important. At cold boot, any non-null\n // `running_started_at` is by definition a zombie — the previous process is\n // gone and an async finder run can't outlive its process. The MAX_RUN_AGE_MS\n // freshness gate (4h) is for live UI reads where a long-running finder\n // shouldn't disappear from the spinner mid-run. Applying it to the boot\n // sweep would let a row that crashed 30 minutes ago survive across reboots\n // and block re-runs with `409 already running` — exactly the bug we hit.\n //\n // Hot reload (the if-branch above) skips the sweep because it preserves\n // the event loop, so any genuinely in-flight run continues.\n //\n // Wrapped — a SQL hiccup here must not take down the server. Boot\n // continuing on stale ledger state is strictly better than refusing to\n // start because of a cleanup detail.\n try {\n const swept = getLedger().sweepStaleRunningTriggers({\n now: new Date(),\n maxAgeMs: 0,\n });\n for (const s of swept) {\n logEvent(\"trigger.killed_by_restart\", { name: s.name, age_ms: s.ageMs }, \"warn\");\n process.stdout.write(` swept stale run: ${s.name} (${Math.round(s.ageMs / 1000)}s old)\\n`);\n }\n } catch (err) {\n logEvent(\n \"trigger.sweep.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(` warn: stale-run sweep failed: ${(err as Error).message}\\n`);\n }\n\n const { url, server } = await startServer({ port });\n cache.__oneshotGtmServer = server;\n\n // Background trigger scheduler — polls due triggers, fires them, sleeps\n // for `nextSleepMs` between ticks. Replaces the need to run a separate\n // `bun run cli -- find watch` daemon. Survives `bun --hot` re-execs by\n // staying anchored to globalThis.\n //\n // Wrapped: scheduler init failure must not take down the server (founder\n // can still drive triggers manually via /queue Run). The cold-boot sweep\n // pattern above does the same thing for ledger-init resilience.\n let scheduler: SchedulerHandle | null = null;\n try {\n scheduler = startScheduler();\n cache.__oneshotGtmScheduler = scheduler;\n } catch (err) {\n logEvent(\n \"scheduler.start.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(` warn: scheduler failed to start: ${(err as Error).message}\\n`);\n }\n\n process.stdout.write(`\\n oneshot-gtm dashboard: ${url}\\n\\n`);\n\n if (!noBrowser) {\n try {\n await open(url);\n } catch {\n // ignore — terminal output already shows the URL.\n }\n }\n\n const shutdown = (): void => {\n process.stdout.write(\"\\n shutting down...\\n\");\n if (scheduler) scheduler.stop();\n server.stop();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n}\n"],"mappings":";;;;;;;;;;AAMA,MAAM,aAAa,KAAK,SAAS,EAAE,eAAe;AAClD,MAAM,cAAc,KAAK,YAAY,cAAc;AACnD,MAAM,eAAe,KAAK,YAAY,OAAO;AAE7C,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAM,WAA0B;CAC9B,YAAY;CACZ,aAAa;CACb,UAAU;CACV,kBAAkB;CAClB,aAA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GACX,CAAC;AACF,OAAK,MAAM,KAAK,OAAO;AACrB,YAAS,6BAA6B;IAAE,MAAM,EAAE;IAAM,QAAQ,EAAE;IAAO,EAAE,OAAO;AAChF,WAAQ,OAAO,MAAM,sBAAsB,EAAE,KAAK,IAAI,KAAK,MAAM,EAAE,QAAQ,IAAK,CAAC,UAAU;;UAEtF,KAAK;AACZ,WACE,wBACA,EAAE,cAAe,IAAc,WAAW,IAAI,MAAM,GAAG,IAAI,EAAE,EAC7D,QACD;AACD,UAAQ,OAAO,MAAM,mCAAoC,IAAc,QAAQ,IAAI;;CAGrF,MAAM,EAAE,KAAK,WAAW,MAAM,YAAY,EAAE,MAAM,CAAC;AACnD,OAAM,qBAAqB;CAU3B,IAAI,YAAoC;AACxC,KAAI;AACF,cAAY,gBAAgB;AAC5B,QAAM,wBAAwB;UACvB,KAAK;AACZ,WACE,0BACA,EAAE,cAAe,IAAc,WAAW,IAAI,MAAM,GAAG,IAAI,EAAE,EAC7D,QACD;AACD,UAAQ,OAAO,MAAM,sCAAuC,IAAc,QAAQ,IAAI;;AAGxF,SAAQ,OAAO,MAAM,8BAA8B,IAAI,MAAM;AAE7D,KAAI,CAAC,UACH,KAAI;AACF,QAAM,KAAK,IAAI;SACT;CAKV,MAAM,iBAAuB;AAC3B,UAAQ,OAAO,MAAM,yBAAyB;AAC9C,MAAI,UAAW,WAAU,MAAM;AAC/B,SAAO,MAAM;AACb,UAAQ,KAAK,EAAE;;AAGjB,SAAQ,GAAG,UAAU,SAAS;AAC9B,SAAQ,GAAG,WAAW,SAAS"}
|
|
1
|
+
{"version":3,"file":"bin.mjs","names":["PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","toView","toView","PLAY_NAME","open","PLAY_NAME","cache","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","PLAY_NAME","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","PLAY_NAME","SOURCE","cache","PLAY_NAME","SOURCE","PLAY_NAME","REQUEST_TIMEOUT_MS","USER_AGENT","toView"],"sources":["../../../packages/core/src/json.ts","../../../packages/core/src/config.ts","../../../packages/core/src/ledger.ts","../../../packages/core/src/events.ts","../../../packages/core/src/parallel.ts","../../../packages/core/src/gmail.ts","../../../packages/core/src/identities.ts","../../../packages/core/src/send-routing.ts","../../../packages/core/src/oneshot.ts","../../../packages/core/src/inflight.ts","../src/api/health.ts","../src/api/home.ts","../../../packages/intel/src/prompts.ts","../../../packages/intel/src/client.ts","../../../packages/intel/src/_parse.ts","../../../packages/plays/src/_lib.ts","../../../packages/plays/src/_cadence.ts","../../../packages/plays/src/_run-play.ts","../../../packages/plays/src/reply.ts","../../../packages/plays/src/accelerator-batch.ts","../../../packages/plays/src/breakup-revive.ts","../../../packages/plays/src/competitor-switch.ts","../../../packages/plays/src/hiring-signal.ts","../../../packages/plays/src/job-change.ts","../../../packages/plays/src/luma-events.ts","../../../packages/plays/src/podcast-guest.ts","../../../packages/plays/src/post-funding.ts","../../../packages/plays/src/repo-interest.ts","../../../packages/plays/src/show-hn.ts","../../../packages/plays/src/stack-consolidation.ts","../../../packages/plays/src/registry.ts","../../../packages/plays/src/demo-no-show.ts","../src/api/cadences.ts","../src/api/receipts.ts","../../../packages/shared-types/src/index.ts","../src/api/inbox.ts","../src/api/plays.ts","../src/api/measure.ts","../src/api/setup.ts","../src/api/gmail-auth.ts","../src/api/derive-icp.ts","../../../packages/find/src/_filter.ts","../../../packages/find/src/_dedupe.ts","../../../packages/find/src/_findemail-prescreen.ts","../../../packages/find/src/_breaker.ts","../../../packages/find/src/_sdk-safe.ts","../../../packages/find/src/_contact.ts","../../../packages/find/src/_linkedin.ts","../../../packages/find/src/_enrich.ts","../../../packages/find/src/_pending.ts","../../../packages/find/src/show-hn.ts","../../../packages/find/src/post-funding.ts","../../../packages/find/src/_accelerator-search-adapter.ts","../../../packages/find/src/_yc-oss-adapter.ts","../../../packages/find/src/accelerator-batch.ts","../../../packages/find/src/job-change.ts","../../../packages/find/src/hiring-signal.ts","../../../packages/find/src/podcast-guest.ts","../../../packages/find/src/breakup-revive.ts","../../../packages/find/src/_github-search.ts","../../../packages/find/src/_github-user.ts","../../../packages/find/src/_repo-stack.ts","../../../packages/find/src/_repo-pipeline.ts","../../../packages/find/src/_repo-utils.ts","../../../packages/find/src/github-topics.ts","../../../packages/find/src/_stargazers.ts","../../../packages/find/src/github-stars.ts","../../../packages/find/src/_luma-auth.ts","../../../packages/find/src/_luma-discover.ts","../../../packages/find/src/luma.ts","../../../packages/find/src/registry.ts","../../../packages/find/src/drain.ts","../src/api/strategist.ts","../../../packages/doctor/src/check.ts","../src/api/doctor.ts","../src/api/_play-dispatch.ts","../src/api/run.ts","../src/api/runs.ts","../src/api/queue.ts","../src/api/triggers.ts","../src/server.ts","../src/scheduler.ts","../src/bin.ts"],"sourcesContent":["/**\n * Parse a JSON string expected to hold an object. Returns null on invalid\n * JSON or any non-object result (arrays, numbers, strings, null) so callers\n * can fall back to a default instead of crashing on a corrupt row.\n */\nexport function safeParseJsonRecord(raw: string): Record<string, unknown> | null {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport { safeParseJsonRecord } from \"./json.ts\";\nimport type { OneShotConfig } from \"./types.ts\";\n\n// Data dir for config.json, .env, ledger.sqlite, events.jsonl, gmail-tokens.json.\n// `ONESHOT_GTM_HOME` overrides the default — tests redirect data-dir I/O to a temp\n// dir (see vitest.setup.ts) so they never touch the real ~/.oneshot-gtm. Read once\n// at module load.\nconst CONFIG_DIR = process.env[\"ONESHOT_GTM_HOME\"]?.trim() || join(homedir(), \".oneshot-gtm\");\nconst CONFIG_PATH = join(CONFIG_DIR, \"config.json\");\nconst SECRETS_PATH = join(CONFIG_DIR, \".env\");\n\nexport const SECRET_KEYS = [\n \"OPENROUTER_API_KEY\",\n \"OPENAI_API_KEY\",\n \"ANTHROPIC_API_KEY\",\n \"CDP_API_KEY_ID\",\n \"CDP_API_KEY_SECRET\",\n \"CDP_WALLET_SECRET\",\n \"AGENT_PRIVATE_KEY\",\n \"GMAIL_CLIENT_ID\",\n \"GMAIL_CLIENT_SECRET\",\n \"GMAIL_REFRESH_TOKEN\",\n] as const;\nexport type SecretKey = (typeof SECRET_KEYS)[number];\n\nconst DEFAULTS: OneShotConfig = {\n walletMode: \"cdp\",\n llmProvider: \"openrouter\",\n llmModel: \"anthropic/claude-sonnet-4.6\",\n telemetryEnabled: true,\n founderName: null,\n founderEmail: null,\n productOneLiner: null,\n productDomain: null,\n sendingDomain: null,\n emailProvider: \"oneshot\",\n emailIdentities: null,\n icpOneLiner: null,\n cadenceOverrides: null,\n founderCredentials: null,\n productPortfolio: null,\n partners: null,\n mobileSignature: false,\n clientId: null,\n};\n\nexport function configDir(): string {\n return CONFIG_DIR;\n}\n\nfunction ensureConfigDir(): void {\n if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });\n}\n\nexport function loadConfig(): OneShotConfig {\n const raw = readConfigOrDefault();\n const { cfg, minted } = bootstrapClientId(raw);\n // First-sight bootstrap of the anonymous install id. Persisted immediately\n // so subsequent reads (and any future telemetry sink) see a stable value.\n // Failures are non-fatal: returning the in-memory id still works for this\n // process, we just won't have it on disk yet — next call will retry.\n if (minted) {\n try {\n saveConfig(cfg);\n } catch {\n // ignore — read-only fs, permission denied, etc. Caller still gets the id.\n }\n }\n return cfg;\n}\n\n/**\n * Pure helper for the clientId bootstrap path — extracted so it can be\n * unit-tested without touching the user's real config file. Mints a fresh\n * UUID when `cfg.clientId` is null/empty, otherwise returns the input\n * unchanged. `minted: true` signals the caller to persist.\n */\nexport function bootstrapClientId(cfg: OneShotConfig): {\n cfg: OneShotConfig;\n minted: boolean;\n} {\n if (cfg.clientId && cfg.clientId.length > 0) return { cfg, minted: false };\n return { cfg: { ...cfg, clientId: randomUUID() }, minted: true };\n}\n\nfunction readConfigOrDefault(): OneShotConfig {\n if (!existsSync(CONFIG_PATH)) return { ...DEFAULTS };\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf8\");\n return { ...DEFAULTS, ...JSON.parse(raw) };\n } catch {\n return { ...DEFAULTS };\n }\n}\n\nexport function saveConfig(cfg: OneShotConfig): void {\n ensureConfigDir();\n if (!existsSync(dirname(CONFIG_PATH))) mkdirSync(dirname(CONFIG_PATH), { recursive: true });\n writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));\n}\n\nexport function secretsPath(): string {\n return SECRETS_PATH;\n}\n\nfunction loadSecretsFile(): Record<string, string> {\n if (!existsSync(SECRETS_PATH)) return {};\n const out: Record<string, string> = {};\n for (const raw of readFileSync(SECRETS_PATH, \"utf8\").split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const eq = line.indexOf(\"=\");\n if (eq < 0) continue;\n const k = line.slice(0, eq).trim();\n let v = line.slice(eq + 1).trim();\n if ((v.startsWith('\"') && v.endsWith('\"')) || (v.startsWith(\"'\") && v.endsWith(\"'\"))) {\n v = v.slice(1, -1);\n }\n out[k] = v;\n }\n return out;\n}\n\nfunction applySecretsToEnv(): void {\n const stored = loadSecretsFile();\n for (const [k, v] of Object.entries(stored)) {\n if (process.env[k] === undefined || process.env[k] === \"\") {\n process.env[k] = v;\n }\n }\n}\n\nexport function saveSecrets(updates: Partial<Record<SecretKey, string>>): void {\n ensureConfigDir();\n const existing = loadSecretsFile();\n for (const [k, v] of Object.entries(updates)) {\n if (v === undefined || v === \"\") continue;\n existing[k] = v;\n }\n const lines = [\n \"# oneshot-gtm secrets — do not commit\",\n \"# this file is read on every CLI invocation; values here override blank process.env\",\n \"\",\n ...Object.entries(existing)\n .filter(([k]) => SECRET_KEYS.includes(k as SecretKey))\n .map(([k, v]) => `${k}=${v}`),\n \"\",\n ];\n writeFileSync(SECRETS_PATH, lines.join(\"\\n\"));\n try {\n chmodSync(SECRETS_PATH, 0o600);\n } catch {\n // chmod may fail on Windows; the file is still in $HOME so reasonably scoped.\n }\n // reflect new values into the running process so `doctor` etc see them immediately\n for (const [k, v] of Object.entries(updates)) {\n if (v) process.env[k] = v;\n }\n}\n\nexport function secretSource(key: SecretKey): \"env\" | \"file\" | null {\n // process.env was populated either by the shell (env) or by applySecretsToEnv (file).\n // We can distinguish by checking the file directly.\n const fromFile = loadSecretsFile();\n if (fromFile[key]) {\n // If the shell ALSO has it AND it differs from the file, the shell value wins (we only fill blanks).\n if (process.env[key] && process.env[key] !== fromFile[key]) return \"env\";\n return \"file\";\n }\n if (process.env[key]) return \"env\";\n return null;\n}\n\n// Auto-apply on first import so downstream code sees keys in process.env without ceremony.\napplySecretsToEnv();\n\nconst GMAIL_TOKENS_PATH = join(CONFIG_DIR, \"gmail-tokens.json\");\n\nexport interface GmailTokenEntry {\n refreshToken: string;\n address: string;\n}\n\n/**\n * Per-identity Gmail refresh tokens. Lives outside the .env SECRET_KEYS\n * whitelist because the key set is dynamic (one token per authorized\n * account). Same trust level as .env: chmod 600, local-only.\n */\nexport function loadGmailTokens(): Record<string, GmailTokenEntry> {\n if (!existsSync(GMAIL_TOKENS_PATH)) return {};\n let raw: string;\n try {\n raw = readFileSync(GMAIL_TOKENS_PATH, \"utf8\");\n } catch {\n return {};\n }\n const parsed = safeParseJsonRecord(raw) ?? {};\n const out: Record<string, GmailTokenEntry> = {};\n for (const [id, entry] of Object.entries(parsed)) {\n const e = entry as Partial<GmailTokenEntry> | null;\n if (e && typeof e === \"object\" && typeof e.refreshToken === \"string\" && e.refreshToken) {\n out[id] = { refreshToken: e.refreshToken, address: typeof e.address === \"string\" ? e.address : \"\" };\n }\n }\n return out;\n}\n\nexport function saveGmailToken(identityId: string, entry: GmailTokenEntry): void {\n ensureConfigDir();\n const all = loadGmailTokens();\n all[identityId] = entry;\n writeFileSync(GMAIL_TOKENS_PATH, JSON.stringify(all, null, 2));\n try {\n chmodSync(GMAIL_TOKENS_PATH, 0o600);\n } catch {\n // chmod may fail on Windows; the file is still in $HOME so reasonably scoped.\n }\n}\n\nexport function deleteGmailToken(identityId: string): void {\n const all = loadGmailTokens();\n if (!(identityId in all)) return;\n delete all[identityId];\n writeFileSync(GMAIL_TOKENS_PATH, JSON.stringify(all, null, 2));\n}\n\nexport function llmApiKey(provider: OneShotConfig[\"llmProvider\"]): string | null {\n switch (provider) {\n case \"openrouter\":\n return process.env.OPENROUTER_API_KEY ?? null;\n case \"openai\":\n return process.env.OPENAI_API_KEY ?? null;\n case \"anthropic\":\n return process.env.ANTHROPIC_API_KEY ?? null;\n }\n}\n\nexport function oneshotEnvReady(): boolean {\n return Boolean(\n (process.env.CDP_API_KEY_ID &&\n process.env.CDP_API_KEY_SECRET &&\n process.env.CDP_WALLET_SECRET) ||\n process.env.AGENT_PRIVATE_KEY,\n );\n}\n","import { Database } from \"bun:sqlite\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { configDir } from \"./config.ts\";\nimport type {\n InterviewRecord,\n ProspectRecord,\n QueueRow,\n QueueStatus,\n ReceiptRecord,\n SequenceEventRecord,\n TriggerRow,\n} from \"./types.ts\";\n\nconst DEFAULT_DB_PATH = join(configDir(), \"ledger.sqlite\");\n\n/** How long a SUCCESSFUL enrichment is reused before refetching (profiles are stable). */\nexport const ENRICH_CACHE_TTL_MS = 30 * 24 * 3600 * 1000;\n/** How long a FAILED enrichment suppresses retries — long enough to ride out an SDK outage, short enough to self-heal. */\nexport const ENRICH_FAILURE_TTL_MS = 3 * 24 * 3600 * 1000;\n/**\n * Hard ceiling on waiting for one enrichProfile call. The platform's enrich\n * tool has been observed HANGING (no error, no result, 5+ min) rather than\n * failing — callers race against this and treat a deadline as a failure.\n */\nexport const ENRICH_DEADLINE_MS = 120_000;\n\n/**\n * Canonical form for matching prospect emails — trim + lowercase. Inbound reply\n * addresses (cadence inbox poll) are normalized the same way, so a prospect\n * stored from a mixed-case address still matches when they reply. Applied on\n * both store (upsertProspect) and every lookup so the two never diverge.\n */\nfunction canonEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\nfunction safeParseJsonArray(raw: string): unknown[] {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n}\n\n/** A `cadence_state` row joined with its prospect's email/name/company. */\nexport interface CadenceWithProspect {\n prospect_id: number;\n play_name: string;\n current_step: number;\n status: string;\n enrolled_at: string;\n next_due_at: string | null;\n last_polled_at: string | null;\n next_step_draft_json: string | null;\n next_step_drafted_at: string | null;\n /**\n * ISO timestamp when a fire-and-forget send was claimed for this cadence.\n * Null = no send in flight. Survives server restart so the UI's \"sending\"\n * spinner doesn't get stranded by a `bun --watch` reload mid-SDK-call.\n */\n sending_started_at: string | null;\n /** Last send-failure message (truncated); cleared on any forward progress.\n * Non-null = the most recent send attempt failed and nothing has succeeded\n * since — drives the \"send failed · retrying\" row indicator. */\n last_send_error: string | null;\n /** ISO timestamp of `last_send_error`. */\n last_send_error_at: string | null;\n prospect_email: string | null;\n prospect_name: string | null;\n prospect_company: string | null;\n}\n\nexport class Ledger {\n private db: Database;\n\n constructor(path: string = DEFAULT_DB_PATH) {\n if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true });\n this.db = new Database(path);\n this.db.exec(\"PRAGMA journal_mode = WAL\");\n // Wait (don't immediately throw) when another connection holds the write\n // lock — e.g. a background send and a request both opening the ledger, or\n // parallel test workers running first-run migrations against a shared file.\n // Without this, concurrent DDL surfaces as a spurious \"database is locked\"\n // / \"no such table\" mid-migration.\n this.db.exec(\"PRAGMA busy_timeout = 5000\");\n this.migrate();\n }\n\n private migrate(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS receipts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n play_name TEXT NOT NULL,\n call_type TEXT NOT NULL,\n cost_usd REAL,\n signed_receipt TEXT,\n oneshot_request_id TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_play ON receipts(play_name);\n CREATE INDEX IF NOT EXISTS idx_receipts_created ON receipts(created_at);\n -- listReceipts / spend rollups filter (play_name, created_at) together and\n -- sort by created_at; the composite serves both without a separate sort scan.\n CREATE INDEX IF NOT EXISTS idx_receipts_play_created ON receipts(play_name, created_at);\n -- Backs recordReceipt's dedup-by-job-id lookup. Partial (non-null only):\n -- many receipts have no request_id and must NOT collapse together.\n CREATE INDEX IF NOT EXISTS idx_receipts_request ON receipts(oneshot_request_id)\n WHERE oneshot_request_id IS NOT NULL;\n\n CREATE TABLE IF NOT EXISTS prospects (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n email TEXT,\n phone TEXT,\n company TEXT,\n linkedin_url TEXT,\n dossier_json TEXT,\n source TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_prospects_email ON prospects(email) WHERE email IS NOT NULL;\n\n CREATE TABLE IF NOT EXISTS sequence_events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n prospect_id INTEGER NOT NULL,\n play_name TEXT NOT NULL,\n step_index INTEGER NOT NULL,\n channel TEXT NOT NULL,\n status TEXT NOT NULL,\n metadata_json TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n -- sequence_events is read by listColdProspects (MAX(created_at) per\n -- prospect), per-play send counts, and cadence scans — all by\n -- prospect_id and/or created_at. Without this it's a full table scan.\n CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_created ON sequence_events(prospect_id, created_at);\n -- listSequenceEventsForProspectPlay (per-row in /api/cadences toView)\n -- and listSequenceEventsForCadences (bulk variant) both filter on\n -- (prospect_id, play_name) and ORDER BY step_index — composite index\n -- serves both the seek and the sort, no temp B-tree.\n CREATE INDEX IF NOT EXISTS idx_sequence_events_prospect_play ON sequence_events(prospect_id, play_name, step_index);\n\n CREATE TABLE IF NOT EXISTS interviews (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n person TEXT NOT NULL,\n transcript_path TEXT,\n jtbd TEXT,\n pain_quotes_json TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n\n CREATE TABLE IF NOT EXISTS cadence_state (\n prospect_id INTEGER NOT NULL,\n play_name TEXT NOT NULL,\n current_step INTEGER NOT NULL DEFAULT 0,\n status TEXT NOT NULL DEFAULT 'active',\n enrolled_at TEXT NOT NULL DEFAULT (datetime('now')),\n next_due_at TEXT,\n last_polled_at TEXT,\n PRIMARY KEY (prospect_id, play_name)\n );\n CREATE INDEX IF NOT EXISTS idx_cadence_status ON cadence_state(status);\n CREATE INDEX IF NOT EXISTS idx_cadence_next_due ON cadence_state(next_due_at);\n\n CREATE TABLE IF NOT EXISTS deal_outcomes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n prospect_id INTEGER NOT NULL,\n play_name TEXT,\n outcome TEXT NOT NULL,\n amount_usd REAL,\n notes TEXT,\n recorded_at TEXT NOT NULL DEFAULT (datetime('now')),\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n CREATE INDEX IF NOT EXISTS idx_outcomes_prospect ON deal_outcomes(prospect_id);\n CREATE INDEX IF NOT EXISTS idx_outcomes_outcome ON deal_outcomes(outcome);\n CREATE INDEX IF NOT EXISTS idx_outcomes_play ON deal_outcomes(play_name);\n\n CREATE TABLE IF NOT EXISTS target_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n play_name TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n dedupe_key TEXT NOT NULL,\n source TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n found_at TEXT NOT NULL DEFAULT (datetime('now')),\n reviewed_at TEXT,\n sent_at TEXT,\n notes TEXT,\n prospect_id INTEGER,\n last_draft_json TEXT,\n last_drafted_at TEXT,\n FOREIGN KEY(prospect_id) REFERENCES prospects(id)\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe ON target_queue(play_name, dedupe_key);\n CREATE INDEX IF NOT EXISTS idx_queue_status ON target_queue(status);\n CREATE INDEX IF NOT EXISTS idx_queue_play ON target_queue(play_name);\n -- The /queue page filters by (status, play) together; the composite\n -- serves that pair without falling back to a single-column scan.\n CREATE INDEX IF NOT EXISTS idx_queue_status_play ON target_queue(status, play_name);\n\n CREATE TABLE IF NOT EXISTS triggers (\n name TEXT PRIMARY KEY,\n last_polled_at TEXT,\n last_run_summary TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n config_json TEXT,\n running_started_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS enrichment_cache (\n email TEXT PRIMARY KEY,\n result_json TEXT NOT NULL,\n fetched_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS runs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n play_name TEXT NOT NULL,\n dry_run INTEGER NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('running','done','interrupted')),\n started_at TEXT NOT NULL,\n completed_at TEXT,\n target_count INTEGER NOT NULL,\n drafted_count INTEGER NOT NULL DEFAULT 0,\n sent_count INTEGER NOT NULL DEFAULT 0,\n error_count INTEGER NOT NULL DEFAULT 0,\n targets_json TEXT NOT NULL,\n events_json TEXT NOT NULL DEFAULT '[]',\n prospect_emails_json TEXT NOT NULL DEFAULT '[]'\n );\n CREATE INDEX IF NOT EXISTS idx_runs_started ON runs(started_at DESC);\n CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status);\n\n CREATE TABLE IF NOT EXISTS schema_version (\n version INTEGER PRIMARY KEY\n );\n INSERT OR IGNORE INTO schema_version(version) VALUES(6);\n `);\n\n // Lightweight migrations for installs that pre-date a column.\n this.addColumnIfMissing(\"prospects\", \"phone\", \"TEXT\");\n // v5 (2026-04): persist trigger run-state so a server restart doesn't\n // strand fire-and-forget runs as silent stale rows. See\n // sweepStaleRunningTriggers + fireTriggerNow.\n this.addColumnIfMissing(\"triggers\", \"running_started_at\", \"TEXT\");\n // v6 (2026-05): persist drafts per target_queue row so the founder can\n // review subject/body/flags after the SSE stream finishes (the /run\n // page itself is ephemeral). See `setQueueDraft` + the persist hook in\n // `apps/server/src/api/run.ts`.\n this.addColumnIfMissing(\"target_queue\", \"last_draft_json\", \"TEXT\");\n this.addColumnIfMissing(\"target_queue\", \"last_drafted_at\", \"TEXT\");\n // v7 (2026-05): lease column for atomic drain claiming. Two concurrent\n // /api/queue/drain calls used to see the same `approved` rows and both\n // start sending; dequeueApproved now atomically flips this column inside\n // a transaction so each drain sees a disjoint slice. Lease defaults to\n // 15 min — long enough for a slow per-target SDK send, short enough that\n // a crashed drain self-heals without a sweeper.\n this.addColumnIfMissing(\"target_queue\", \"drain_claimed_at\", \"TEXT\");\n // v8 (2026-05): persist per-cadence next-step draft so /cadences can\n // preview the 2nd/3rd email before firing (mirrors /queue's\n // last_draft_json). JSON envelope = {subject, body, flags, payload,\n // draftedAt}; cleared on cadence advance.\n this.addColumnIfMissing(\"cadence_state\", \"next_step_draft_json\", \"TEXT\");\n this.addColumnIfMissing(\"cadence_state\", \"next_step_drafted_at\", \"TEXT\");\n // v9 (2026-06): persist \"send in flight\" marker so a fire-and-forget\n // cadence-send survives a server restart. The in-memory `inFlightSends`\n // Set was lost on every bun --watch reload, leaving the founder with no\n // loading state AND no email delivered. Claimed via the atomic\n // claimCadenceSendingMarker CAS update; cleared on success (inside\n // advanceCadence) and on failure (catch). sweepStaleCadenceSends on cold\n // boot treats every existing marker as stranded.\n this.addColumnIfMissing(\"cadence_state\", \"sending_started_at\", \"TEXT\");\n // v10 (2026-06): Mirror of v9 for the queue Send-draft path. Same bug\n // shape — fire-and-forget background SDK send died on every server\n // restart, leaving the founder with no UI feedback and no record. Wired\n // via claimQueueSendingMarker + sweepStaleQueueSends; auto-cleared by\n // setQueueStatus when the row flips to a terminal state.\n this.addColumnIfMissing(\"target_queue\", \"send_started_at\", \"TEXT\");\n // v11 (2026-06): sender rotation. `receipts.sender_identity` records which\n // EmailIdentity (config emailIdentities[].id) sent each email.send — the\n // per-identity daily counter + warm-up first-send date both derive from\n // it. `sender_assignments` pins each prospect (canonical email) to the\n // identity that sent their first touch so follow-ups never switch From\n // address mid-thread. Keyed by email, NOT prospect_id: some sends happen\n // before any prospect row exists (concierge prep email).\n this.addColumnIfMissing(\"receipts\", \"sender_identity\", \"TEXT\");\n // v12 (2026-06): negative enrichment caching. NULL/\"ok\" = success row,\n // \"failed\" = the enrich SDK job failed for this email — readers skip the\n // retry within ENRICH_FAILURE_TTL_MS so drafts stop re-paying ~70s\n // timeouts for known-bad emails (229 such failures on 2026-06-06..08\n // left 154 queue rows re-enriching on every draft).\n this.addColumnIfMissing(\"enrichment_cache\", \"status\", \"TEXT\");\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS sender_assignments (\n email TEXT PRIMARY KEY,\n identity_id TEXT NOT NULL,\n assigned_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE INDEX IF NOT EXISTS idx_receipts_calltype_sender\n ON receipts(call_type, sender_identity, created_at);\n `);\n // v13 (2026-06): persist inbox reply activity. The /inbox composer used to\n // hold the draft + \"replied\" state only in React useState, so a refresh\n // discarded the draft and reverted the row to a blank composer; the sent\n // body was never stored anywhere (receipts hold metadata only). Keyed by\n // thread_key = Gmail thread_id (else the email id) so follow-ups in a\n // thread share one draft + sent history. `inbox_drafts` is the single\n // mutable draft per thread (cleared on send); `inbox_sent` is the\n // append-only history of replies actually sent (we allow replying again).\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS inbox_drafts (\n thread_key TEXT PRIMARY KEY,\n inbound_email_id TEXT NOT NULL,\n to_email TEXT NOT NULL,\n subject TEXT,\n identity_id TEXT,\n body TEXT NOT NULL,\n updated_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE TABLE IF NOT EXISTS inbox_sent (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n thread_key TEXT NOT NULL,\n to_email TEXT NOT NULL,\n subject TEXT,\n body TEXT NOT NULL,\n identity_id TEXT,\n request_id TEXT,\n sent_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE INDEX IF NOT EXISTS idx_inbox_sent_thread\n ON inbox_sent(thread_key, sent_at);\n `);\n // v14 (2026-06): persist the last cadence send FAILURE so the /cadences row\n // can show \"send failed · retrying\" instead of looking identical to a row\n // that's merely waiting on the founder. A failed send doesn't advance the\n // cadence, so without this the founder can't tell \"blocked upstream\" from\n // \"waiting on me\". Set by recordCadenceSendError on a dispatch throw;\n // cleared by advanceCadence / setCadenceStatus on any forward progress.\n this.addColumnIfMissing(\"cadence_state\", \"last_send_error\", \"TEXT\");\n this.addColumnIfMissing(\"cadence_state\", \"last_send_error_at\", \"TEXT\");\n // v15 (2026-06): persist candidates whose paid contact-resolution failed on\n // a TRANSIENT platform error (the OneShot outage), so a finder doesn't lose\n // them — re-scannable finders self-heal, but time-windowed ones (luma,\n // show-hn) can't re-discover an expired source. `raw_json` holds whatever\n // the finder's registered handler needs to re-resolve + enqueue. The\n // scheduler retry pass drains this once the platform recovers; the\n // (play_name, dedupe_key) PK also serves as the de-dup key against re-scan.\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS pending_resolution (\n play_name TEXT NOT NULL,\n dedupe_key TEXT NOT NULL,\n source TEXT NOT NULL,\n raw_json TEXT NOT NULL,\n first_seen_at TEXT NOT NULL DEFAULT (datetime('now')),\n last_attempt_at TEXT,\n attempts INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (play_name, dedupe_key)\n );\n CREATE INDEX IF NOT EXISTS idx_pending_resolution_seen\n ON pending_resolution(first_seen_at);\n `);\n // v16 (2026-06): receipt annotation. memo + decision_context mirror the\n // audit fields already sent to OneShot at call time (buildAuditOpts), stored\n // locally so the /receipts UI can show \"why\" without re-fetching the signed\n // receipt. value_tag (+ value_tagged_at) hold the RoCS outcome value set by\n // tagOutcomeValue once a reply/deal lands (also PATCHed to OneShot via\n // tagReceiptValue). sequence_events.receipt_id links a sent step back to its\n // send receipt so an outcome knows which receipts to tag — SDK 0.21's\n // tagReceiptValue({requestId}) then resolves each via the stored request_id,\n // so no platform receipt-id backfill is needed.\n this.addColumnIfMissing(\"receipts\", \"memo\", \"TEXT\");\n this.addColumnIfMissing(\"receipts\", \"decision_context\", \"TEXT\");\n this.addColumnIfMissing(\"receipts\", \"value_tag\", \"TEXT\");\n this.addColumnIfMissing(\"receipts\", \"value_tagged_at\", \"TEXT\");\n this.addColumnIfMissing(\"sequence_events\", \"receipt_id\", \"INTEGER\");\n this.db.exec(`\n -- value-tag filter on the /receipts page; partial (tagged rows only).\n CREATE INDEX IF NOT EXISTS idx_receipts_value_tag\n ON receipts(value_tag, created_at) WHERE value_tag IS NOT NULL;\n `);\n // v17 (2026-06): goal-level value attribution (SDK 0.22). goal_id mirrors the\n // cadence correlation key sent as decisionContext.goalId, so an outcome tags\n // every receipt in the cadence at once (setReceiptValueTagByGoal) instead of\n // walking sequence_events.receipt_id per receipt.\n this.addColumnIfMissing(\"receipts\", \"goal_id\", \"TEXT\");\n this.db.exec(`\n CREATE INDEX IF NOT EXISTS idx_receipts_goal\n ON receipts(goal_id) WHERE goal_id IS NOT NULL;\n `);\n }\n\n /**\n * CAS-claim a timestamp marker on a single row. Returns true when the row's\n * marker was NULL (or older than `staleCutoffIso` when provided) and we set\n * it to `startedAtIso`; false when another caller already holds the claim.\n *\n * Shared by every in-flight marker in the ledger: triggers.running_started_at,\n * cadence_state.sending_started_at, target_queue.send_started_at. Each domain\n * just supplies its own table + primary-key WHERE fragment.\n *\n * Identifier validation (table + column) mirrors `addColumnIfMissing` —\n * SQLite has no parameter binding for table/column names, so we whitelist\n * to bare ASCII to slam the door on any injection vector.\n */\n private claimMarker(opts: {\n table: string;\n pkeyWhere: string;\n column: string;\n pkeyValues: unknown[];\n startedAtIso: string;\n staleCutoffIso?: string;\n }): boolean {\n this.assertSafeIdentifiers(opts.table, opts.column);\n const staleClause = opts.staleCutoffIso\n ? ` AND (${opts.column} IS NULL OR ${opts.column} < ?)`\n : ` AND ${opts.column} IS NULL`;\n const args = opts.staleCutoffIso\n ? [opts.startedAtIso, ...opts.pkeyValues, opts.staleCutoffIso]\n : [opts.startedAtIso, ...opts.pkeyValues];\n const result = this.db\n .prepare(\n `UPDATE ${opts.table}\n SET ${opts.column} = ?\n WHERE ${opts.pkeyWhere}${staleClause}`,\n )\n .run(...(args as never[]));\n return result.changes > 0;\n }\n\n /**\n * Release a timestamp marker (set to NULL). Idempotent — no-op if the row\n * doesn't exist or the column is already NULL.\n */\n private clearMarker(opts: {\n table: string;\n pkeyWhere: string;\n column: string;\n pkeyValues: unknown[];\n }): void {\n this.assertSafeIdentifiers(opts.table, opts.column);\n this.db\n .prepare(`UPDATE ${opts.table} SET ${opts.column} = NULL WHERE ${opts.pkeyWhere}`)\n .run(...(opts.pkeyValues as never[]));\n }\n\n private assertSafeIdentifiers(table: string, column: string): void {\n const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;\n if (!ident.test(table) || !ident.test(column)) {\n throw new Error(`unsafe identifier in marker helper: ${table}.${column}`);\n }\n }\n\n private addColumnIfMissing(table: string, column: string, type: string): void {\n // Defense-in-depth: SQLite has no parameter binding for table/column/type\n // names, so we must validate. Whitelist to bare ASCII identifiers only.\n const ident = /^[A-Za-z_][A-Za-z0-9_]*$/;\n if (!ident.test(table) || !ident.test(column)) {\n throw new Error(`unsafe identifier in addColumnIfMissing: ${table}.${column}`);\n }\n if (!/^[A-Z][A-Z0-9_ ]*$/.test(type)) {\n throw new Error(`unsafe column type in addColumnIfMissing: ${type}`);\n }\n const cols = this.db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n if (cols.some((c) => c.name === column)) return;\n this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);\n }\n\n enrollCadence(input: { prospectId: number; playName: string; nextDueAt: string }): void {\n this.db\n .prepare(\n `INSERT INTO cadence_state(prospect_id, play_name, current_step, status, next_due_at)\n VALUES(?, ?, 0, 'active', ?)\n ON CONFLICT(prospect_id, play_name) DO UPDATE SET\n status = 'active',\n next_due_at = excluded.next_due_at,\n last_polled_at = NULL,\n last_send_error = NULL,\n last_send_error_at = NULL`,\n )\n .run(input.prospectId, input.playName, input.nextDueAt);\n }\n\n listActiveCadences(opts: { dueByIso?: string } = {}): CadenceWithProspect[] {\n const where: string[] = [\"c.status = 'active'\"];\n const args: unknown[] = [];\n if (opts.dueByIso) {\n where.push(\"(c.next_due_at IS NULL OR c.next_due_at <= ?)\");\n args.push(opts.dueByIso);\n }\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE ${where.join(\" AND \")}\n ORDER BY c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all(...(args as never[])) as never;\n }\n\n listAllCadences(): CadenceWithProspect[] {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all() as never;\n }\n\n /**\n * Single cadence (joined with its prospect) by (prospect_id, play_name) — an\n * index seek on the `cadence_state` PRIMARY KEY. Replaces the O(n)\n * `listAllCadences().find(...)` scan callers used to do per row.\n */\n getCadence(prospectId: number, playName: string): CadenceWithProspect | null {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE c.prospect_id = ? AND c.play_name = ?\n `;\n return (this.db.query(sql).get(prospectId, playName) as CadenceWithProspect) ?? null;\n }\n\n /** All cadences for one prospect — index seek on cadence_state.prospect_id (PK prefix). */\n listCadencesForProspect(prospectId: number): CadenceWithProspect[] {\n const sql = `\n SELECT c.*, p.email AS prospect_email, p.name AS prospect_name, p.company AS prospect_company\n FROM cadence_state c\n JOIN prospects p ON p.id = c.prospect_id\n WHERE c.prospect_id = ?\n ORDER BY c.status ASC, c.next_due_at ASC NULLS LAST\n `;\n return this.db.query(sql).all(prospectId) as never;\n }\n\n advanceCadence(input: {\n prospectId: number;\n playName: string;\n newStep: number;\n nextDueAt: string | null;\n }): void {\n // Also clear any persisted next-step draft AND the sending marker — the\n // draft was for the OLD next step (stale after advance), and a successful\n // advance means the in-flight send for this row is done. /cadences will\n // surface a fresh \"no preview yet\" state.\n // A successful advance also clears any prior send-failure marker (the send\n // that just advanced us obviously succeeded).\n this.db\n .prepare(\n `UPDATE cadence_state\n SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now'),\n next_step_draft_json = NULL, next_step_drafted_at = NULL,\n sending_started_at = NULL,\n last_send_error = NULL, last_send_error_at = NULL\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.newStep, input.nextDueAt, input.prospectId, input.playName);\n }\n\n /**\n * Record the last cadence send FAILURE so /cadences can show the row is\n * blocked upstream (vs. waiting on the founder). Cleared by advanceCadence /\n * setCadenceStatus on any forward progress. No-op if the row is gone.\n */\n recordCadenceSendError(input: { prospectId: number; playName: string; error: string }): void {\n this.db\n .prepare(\n `UPDATE cadence_state\n SET last_send_error = ?, last_send_error_at = datetime('now')\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.error.slice(0, 200), input.prospectId, input.playName);\n }\n\n setCadenceStatus(input: {\n prospectId: number;\n playName: string;\n status: \"active\" | \"replied\" | \"breakup\" | \"completed\";\n }): void {\n // Non-active terminal states clear the persisted draft AND any send\n // marker — a replied / breakup / completed cadence shouldn't have a\n // sendable preview hanging around or a stuck \"sending\" flag. A reply /\n // breakup / completion also clears any stale send-failure marker.\n this.db\n .prepare(\n `UPDATE cadence_state\n SET status = ?,\n next_step_draft_json = CASE WHEN ? = 'active' THEN next_step_draft_json ELSE NULL END,\n next_step_drafted_at = CASE WHEN ? = 'active' THEN next_step_drafted_at ELSE NULL END,\n sending_started_at = CASE WHEN ? = 'active' THEN sending_started_at ELSE NULL END,\n last_send_error = CASE WHEN ? = 'active' THEN last_send_error ELSE NULL END,\n last_send_error_at = CASE WHEN ? = 'active' THEN last_send_error_at ELSE NULL END\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(\n input.status,\n input.status,\n input.status,\n input.status,\n input.status,\n input.status,\n input.prospectId,\n input.playName,\n );\n }\n\n setCadenceDraft(input: {\n prospectId: number;\n playName: string;\n draft: {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n };\n }): void {\n const draftedAtIso = new Date().toISOString();\n const json = JSON.stringify({ ...input.draft, draftedAt: draftedAtIso });\n this.db\n .prepare(\n `UPDATE cadence_state\n SET next_step_draft_json = ?, next_step_drafted_at = ?\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(json, draftedAtIso, input.prospectId, input.playName);\n }\n\n getCadenceDraft(input: { prospectId: number; playName: string }): {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n draftedAt: string;\n } | null {\n const row = this.db\n .query(\n `SELECT next_step_draft_json AS j FROM cadence_state\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .get(input.prospectId, input.playName) as { j: string | null } | null;\n if (!row?.j) return null;\n try {\n return JSON.parse(row.j) as {\n subject: string;\n body: string;\n flags: string[];\n payload: unknown;\n draftedAt: string;\n };\n } catch {\n return null;\n }\n }\n\n clearCadenceDraft(input: { prospectId: number; playName: string }): void {\n this.db\n .prepare(\n `UPDATE cadence_state\n SET next_step_draft_json = NULL, next_step_drafted_at = NULL\n WHERE prospect_id = ? AND play_name = ?`,\n )\n .run(input.prospectId, input.playName);\n }\n\n /**\n * Save (or overwrite) the single in-progress draft for an inbox thread.\n * Backs the /inbox composer's debounced auto-save so a refresh or navigation\n * away no longer discards the draft. Keyed by thread_key (see `inboxThreadKey`\n * in shared-types) — Gmail thread_id, else the email id.\n */\n upsertInboxDraft(input: {\n threadKey: string;\n inboundEmailId: string;\n toEmail: string;\n subject: string;\n identityId: string | null;\n body: string;\n }): void {\n this.db\n .prepare(\n `INSERT INTO inbox_drafts(thread_key, inbound_email_id, to_email, subject, identity_id, body, updated_at)\n VALUES(?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(thread_key) DO UPDATE SET\n inbound_email_id = excluded.inbound_email_id,\n to_email = excluded.to_email,\n subject = excluded.subject,\n identity_id = excluded.identity_id,\n body = excluded.body,\n updated_at = excluded.updated_at`,\n )\n .run(\n input.threadKey,\n input.inboundEmailId,\n input.toEmail,\n input.subject,\n input.identityId,\n input.body,\n new Date().toISOString(),\n );\n }\n\n clearInboxDraft(threadKey: string): void {\n this.db.prepare(`DELETE FROM inbox_drafts WHERE thread_key = ?`).run(threadKey);\n }\n\n /**\n * Record a reply that was actually sent (append to history) and clear the\n * thread's draft in one transaction. History is append-only because we let\n * the founder reply again on the same thread.\n */\n recordInboxSent(input: {\n threadKey: string;\n toEmail: string;\n subject: string;\n body: string;\n identityId: string | null;\n requestId: string | null;\n }): void {\n this.db.transaction(() => {\n this.db\n .prepare(\n `INSERT INTO inbox_sent(thread_key, to_email, subject, body, identity_id, request_id, sent_at)\n VALUES(?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.threadKey,\n input.toEmail,\n input.subject,\n input.body,\n input.identityId,\n input.requestId,\n new Date().toISOString(),\n );\n this.db.prepare(`DELETE FROM inbox_drafts WHERE thread_key = ?`).run(input.threadKey);\n })();\n }\n\n /**\n * Bulk-read persisted reply state for the inbox list route: the saved draft\n * (if any) plus the sent history per thread. Mirrors the `byEmail` map the\n * list route builds for cadence context — one read, indexed by thread_key.\n */\n getInboxThreads(): Map<\n string,\n { draftBody: string | null; sent: { body: string; sentAt: string }[] }\n > {\n const map = new Map<\n string,\n { draftBody: string | null; sent: { body: string; sentAt: string }[] }\n >();\n const ensure = (key: string) => {\n let entry = map.get(key);\n if (!entry) {\n entry = { draftBody: null, sent: [] };\n map.set(key, entry);\n }\n return entry;\n };\n const drafts = this.db\n .query(`SELECT thread_key AS k, body AS b FROM inbox_drafts`)\n .all() as Array<{ k: string; b: string }>;\n for (const d of drafts) ensure(d.k).draftBody = d.b;\n const sent = this.db\n .query(`SELECT thread_key AS k, body AS b, sent_at AS t FROM inbox_sent ORDER BY sent_at ASC`)\n .all() as Array<{ k: string; b: string; t: string }>;\n for (const s of sent) ensure(s.k).sent.push({ body: s.b, sentAt: s.t });\n return map;\n }\n\n /**\n * Atomic claim of the sending marker. Returns `true` when the row had a\n * NULL `sending_started_at` and the marker was set; `false` if another\n * caller already holds the claim. Mirrors triggers' `markTriggerRunning`\n * CAS pattern so two concurrent Send clicks can't double-fire.\n *\n * `staleCutoffIso` (optional): allows a fresh click to reclaim a marker\n * whose `sending_started_at` is older than the cutoff — for the case where\n * a previous send was stranded by a server restart and the cold-boot\n * sweeper hasn't cleared it yet. Without this, the row would 409 every\n * retry until the next boot sweep.\n */\n claimCadenceSendingMarker(input: {\n prospectId: number;\n playName: string;\n startedAtIso: string;\n staleCutoffIso?: string;\n }): boolean {\n return this.claimMarker({\n table: \"cadence_state\",\n pkeyWhere: \"prospect_id = ? AND play_name = ?\",\n column: \"sending_started_at\",\n pkeyValues: [input.prospectId, input.playName],\n startedAtIso: input.startedAtIso,\n ...(input.staleCutoffIso ? { staleCutoffIso: input.staleCutoffIso } : {}),\n });\n }\n\n /** Release the sending marker for this cadence (sets sending_started_at = NULL). */\n clearCadenceSendingMarker(input: { prospectId: number; playName: string }): void {\n this.clearMarker({\n table: \"cadence_state\",\n pkeyWhere: \"prospect_id = ? AND play_name = ?\",\n column: \"sending_started_at\",\n pkeyValues: [input.prospectId, input.playName],\n });\n }\n\n /**\n * Sweep cadence rows whose `sending_started_at` is older than the cutoff\n * (or any non-null value when `staleAgeMs` is 0 — cold-boot semantics).\n * For each match, classify by whether a `sequence_events` row for the\n * (prospect, play, current_step) already exists:\n * - event present → the send actually went out; clear the marker only.\n * - event absent → the send was stranded (server died mid-call); clear\n * the marker but leave the draft so the founder can re-click Send.\n * Returns the swept rows so the caller can log them.\n *\n * Pure-ish (takes `now` + `maxAgeMs` as args) — tests can drive both\n * \"fresh markers spared\" and \"stale markers swept\" without faking the clock.\n */\n sweepStaleCadenceSends(input: { now: Date; maxAgeMs: number }): Array<{\n prospectId: number;\n playName: string;\n startedAt: string;\n ageMs: number;\n actuallySent: boolean;\n }> {\n const cutoffMs = input.now.getTime() - input.maxAgeMs;\n const rows = this.db\n .query(\n `SELECT prospect_id, play_name, current_step, sending_started_at\n FROM cadence_state\n WHERE sending_started_at IS NOT NULL`,\n )\n .all() as Array<{\n prospect_id: number;\n play_name: string;\n current_step: number;\n sending_started_at: string;\n }>;\n const swept: Array<{\n prospectId: number;\n playName: string;\n startedAt: string;\n ageMs: number;\n actuallySent: boolean;\n }> = [];\n const checkEvent = this.db.prepare(\n `SELECT 1 FROM sequence_events\n WHERE prospect_id = ? AND play_name = ? AND step_index = ?\n AND status IN ('sent','delivered','replied')\n LIMIT 1`,\n );\n const clear = this.db.prepare(\n `UPDATE cadence_state\n SET sending_started_at = NULL\n WHERE prospect_id = ? AND play_name = ?`,\n );\n for (const row of rows) {\n const startedMs = new Date(row.sending_started_at).getTime();\n if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue; // still fresh\n const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;\n // The in-flight step's step_index is `current_step + 1` (= nextIndex in the\n // engine): the marker is claimed while current_step still holds the OLD\n // value, and `recordSequenceEvent` writes at nextIndex. So \"did the\n // in-flight send land?\" checks current_step + 1. We also check current_step\n // to cover the race where advanceCadence already ran (current_step moved to\n // the sent step) but the marker hadn't been cleared yet.\n const sentInflight = checkEvent.get(row.prospect_id, row.play_name, row.current_step + 1);\n const sentAfterAdvance = checkEvent.get(row.prospect_id, row.play_name, row.current_step);\n const actuallySent = sentInflight != null || sentAfterAdvance != null;\n clear.run(row.prospect_id, row.play_name);\n swept.push({\n prospectId: row.prospect_id,\n playName: row.play_name,\n startedAt: row.sending_started_at,\n ageMs,\n actuallySent,\n });\n }\n return swept;\n }\n\n findProspectByEmail(email: string): { id: number } | null {\n return (\n (this.db.query(\"SELECT id FROM prospects WHERE email = ?\").get(canonEmail(email)) as {\n id: number;\n }) ?? null\n );\n }\n\n /** Full prospect record by email — used to attach name/company to inbox replies. */\n getProspectByEmail(email: string): ProspectRecord | null {\n return (\n (this.db\n .query(\"SELECT * FROM prospects WHERE email = ?\")\n .get(canonEmail(email)) as ProspectRecord) ?? null\n );\n }\n\n /** Full prospect record by id (PK seek). Avoids loading every prospect to find one. */\n getProspectById(id: number): ProspectRecord | null {\n return (\n (this.db.query(\"SELECT * FROM prospects WHERE id = ?\").get(id) as ProspectRecord) ?? null\n );\n }\n\n /**\n * Cached enrichProfile result for an email (profiles are stable; reused\n * with a TTL). `status` is NULL/\"ok\" for success rows, \"failed\" for\n * negative entries (the SDK job failed — readers skip re-attempting within\n * ENRICH_FAILURE_TTL_MS instead of paying the ~70s call again).\n */\n getCachedEnrichment(\n email: string,\n ): { result_json: string; fetched_at: string; status: string | null } | null {\n return (\n (this.db\n .query(\"SELECT result_json, fetched_at, status FROM enrichment_cache WHERE email = ?\")\n .get(email) as { result_json: string; fetched_at: string; status: string | null }) ?? null\n );\n }\n\n setCachedEnrichment(email: string, resultJson: string): void {\n // status reset to NULL: a fresh success must clear any prior \"failed\"\n // marker — luma/_repo-pipeline write success rows through this method\n // without knowing about negative entries.\n this.db\n .prepare(\n `INSERT INTO enrichment_cache(email, result_json, fetched_at, status)\n VALUES(?, ?, ?, NULL)\n ON CONFLICT(email) DO UPDATE SET\n result_json = excluded.result_json,\n fetched_at = excluded.fetched_at,\n status = NULL`,\n )\n .run(email, resultJson, new Date().toISOString());\n }\n\n /** Negative cache entry: the enrichment SDK job failed for this email. */\n setCachedEnrichmentFailure(email: string, message: string): void {\n this.db\n .prepare(\n `INSERT INTO enrichment_cache(email, result_json, fetched_at, status)\n VALUES(?, ?, ?, 'failed')\n ON CONFLICT(email) DO UPDATE SET\n result_json = excluded.result_json,\n fetched_at = excluded.fetched_at,\n status = 'failed'`,\n )\n .run(\n email,\n JSON.stringify({ failed: true, message: message.slice(0, 300) }),\n new Date().toISOString(),\n );\n }\n\n recordReceipt(input: {\n playName: string;\n callType: string;\n /** Per-call USD cost. Every wrapper in `oneshot.ts` reads `result.cost`\n * from the SDK response (declared on every result type in\n * `@oneshot-agent/sdk@0.15.2+`) and forwards it here. NULL in the\n * column when undefined — visible signal that the SDK omitted cost. */\n costUsd?: number;\n signedReceipt?: unknown;\n oneshotRequestId?: string;\n /** EmailIdentity id for email.send receipts — drives per-identity daily caps. */\n senderIdentity?: string;\n /** Call-time memo (the same value sent to OneShot); defaults to \"{play} {callType}\". */\n memo?: string;\n /** Call-time decisionContext blob; JSON-stringified into the column. */\n decisionContext?: unknown;\n }): number {\n // Idempotent on the job id: the SDK's idempotency replay returns the\n // ORIGINAL request_id when a timed-out/double-fired send is retried, and a\n // Gmail message id is unique per send — so a non-null request_id already in\n // the table means \"same underlying send\". Return the existing receipt\n // instead of inserting a duplicate that would double-count spend and caps.\n // Null request_ids (cache hits, SDK omissions) are distinct events and skip\n // this — they must never collapse together.\n if (input.oneshotRequestId) {\n const existing = this.db\n .query(\"SELECT id FROM receipts WHERE oneshot_request_id = ?\")\n .get(input.oneshotRequestId) as { id: number } | undefined;\n if (existing) return existing.id;\n }\n // Number.isFinite guard rejects undefined / Infinity / NaN — those land\n // as NULL in the column, NOT silently distorted into a number.\n const costUsd =\n typeof input.costUsd === \"number\" && Number.isFinite(input.costUsd) ? input.costUsd : null;\n // Mirror what buildAuditOpts sends to OneShot so the stored memo/context\n // match the platform receipt even at call sites that don't enrich.\n const memo = input.memo ?? `${input.playName} ${input.callType}`;\n const decisionContext = input.decisionContext ?? {\n playName: input.playName,\n callType: input.callType,\n };\n // Mirror the cadence correlation key (decisionContext.goalId) into its own\n // column so an outcome can value-tag the whole goal in one UPDATE.\n const goalId =\n typeof (decisionContext as { goalId?: unknown }).goalId === \"string\"\n ? (decisionContext as { goalId: string }).goalId\n : null;\n const stmt = this.db.prepare(`\n INSERT INTO receipts(play_name, call_type, cost_usd, signed_receipt, oneshot_request_id, sender_identity, memo, decision_context, goal_id)\n VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.playName,\n input.callType,\n costUsd,\n input.signedReceipt ? JSON.stringify(input.signedReceipt) : null,\n input.oneshotRequestId ?? null,\n input.senderIdentity ?? null,\n memo,\n JSON.stringify(decisionContext),\n goalId,\n );\n return Number(result.lastInsertRowid);\n }\n\n getSenderAssignment(email: string): string | null {\n const row = this.db\n .query(\"SELECT identity_id FROM sender_assignments WHERE email = ?\")\n .get(canonEmail(email)) as { identity_id: string } | undefined;\n return row?.identity_id ?? null;\n }\n\n /**\n * Pin a prospect email to a sending identity. INSERT OR IGNORE + read-back\n * makes concurrent first-touches race-safe: both callers end up using the\n * single winning assignment instead of splitting the thread across senders.\n */\n assignSender(email: string, identityId: string): string {\n const canon = canonEmail(email);\n this.db\n .prepare(\"INSERT OR IGNORE INTO sender_assignments(email, identity_id) VALUES(?, ?)\")\n .run(canon, identityId);\n return this.getSenderAssignment(canon) ?? identityId;\n }\n\n /**\n * Sends by an identity since `sinceUtcSqlite`. The timestamp MUST be in\n * SQLite datetime('now') format (\"YYYY-MM-DD HH:MM:SS\", UTC) — receipts\n * default created_at to that format, and an ISO string with its 'T'\n * separator compares GREATER than any same-day SQLite timestamp, silently\n * excluding today's rows.\n */\n countEmailSendsSince(identityId: string, sinceUtcSqlite: string): number {\n const row = this.db\n .query(\n `SELECT COUNT(*) AS n FROM receipts\n WHERE call_type = 'email.send' AND sender_identity = ? AND created_at >= ?`,\n )\n .get(identityId, sinceUtcSqlite) as { n: number };\n return row.n;\n }\n\n /**\n * Did we ever email this address pre-rotation? Used to lazy-pin legacy\n * prospects (e.g. in-flight cadences) to the legacy identity instead of\n * letting the rotation picker move their thread to a new From address.\n */\n hasPriorEmailSend(email: string): boolean {\n const row = this.db\n .query(\n `SELECT 1 FROM sequence_events se\n JOIN prospects p ON p.id = se.prospect_id\n WHERE p.email = ? AND se.channel = 'email'\n AND se.status IN ('sent','delivered','replied')\n LIMIT 1`,\n )\n .get(canonEmail(email)) as 1 | undefined;\n return row != null;\n }\n\n /** First email.send by this identity (warm-up ramp anchor). SQLite-format UTC or null. */\n firstEmailSendAt(identityId: string): string | null {\n const row = this.db\n .query(\n `SELECT MIN(created_at) AS first FROM receipts\n WHERE call_type = 'email.send' AND sender_identity = ?`,\n )\n .get(identityId) as { first: string | null };\n return row.first;\n }\n\n getReceipt(id: number): ReceiptRecord | null {\n return (this.db.query(\"SELECT * FROM receipts WHERE id = ?\").get(id) as ReceiptRecord) ?? null;\n }\n\n listReceipts(\n opts: { playName?: string; sinceIso?: string; limit?: number } = {},\n ): ReceiptRecord[] {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `SELECT * FROM receipts ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"} ORDER BY created_at DESC LIMIT ?`;\n args.push(opts.limit ?? 200);\n return this.db.query(sql).all(...(args as never[])) as ReceiptRecord[];\n }\n\n upsertProspect(input: Partial<ProspectRecord> & { email?: string | null }): number {\n // Store the canonical (lowercased) email so reply matching — which\n // normalizes the inbound from-address the same way — always lands.\n const email = input.email ? canonEmail(input.email) : null;\n if (email) {\n const existing = this.db.query(\"SELECT id FROM prospects WHERE email = ?\").get(email) as\n | { id: number }\n | undefined;\n if (existing) return existing.id;\n }\n const stmt = this.db.prepare(`\n INSERT INTO prospects(name, email, phone, company, linkedin_url, dossier_json, source)\n VALUES(?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.name ?? null,\n email,\n (input as { phone?: string | null }).phone ?? null,\n input.company ?? null,\n input.linkedin_url ?? null,\n input.dossier_json ?? null,\n input.source ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n recordOutcome(input: {\n prospectId: number;\n playName?: string;\n outcome: \"meeting_booked\" | \"sql_qualified\" | \"deal_won\" | \"deal_lost\" | \"ghosted\";\n amountUsd?: number;\n notes?: string;\n }): number {\n const stmt = this.db.prepare(`\n INSERT INTO deal_outcomes(prospect_id, play_name, outcome, amount_usd, notes)\n VALUES(?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.prospectId,\n input.playName ?? null,\n input.outcome,\n input.amountUsd ?? null,\n input.notes ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n countOutcomes(\n opts: {\n sinceIso?: string;\n playName?: string;\n outcome?: string;\n } = {},\n ): number {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"recorded_at >= ?\");\n args.push(opts.sinceIso);\n }\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.outcome) {\n where.push(\"outcome = ?\");\n args.push(opts.outcome);\n }\n const sql = `SELECT COUNT(*) AS n FROM deal_outcomes ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}`;\n return (this.db.query(sql).get(...(args as never[])) as { n: number } | null)?.n ?? 0;\n }\n\n outcomesByPlay(opts: { sinceIso?: string } = {}): Array<{\n play_name: string | null;\n meetings: number;\n sqls: number;\n won: number;\n lost: number;\n ghosted: number;\n }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"recorded_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT\n play_name,\n SUM(CASE WHEN outcome = 'meeting_booked' THEN 1 ELSE 0 END) AS meetings,\n SUM(CASE WHEN outcome = 'sql_qualified' THEN 1 ELSE 0 END) AS sqls,\n SUM(CASE WHEN outcome = 'deal_won' THEN 1 ELSE 0 END) AS won,\n SUM(CASE WHEN outcome = 'deal_lost' THEN 1 ELSE 0 END) AS lost,\n SUM(CASE WHEN outcome = 'ghosted' THEN 1 ELSE 0 END) AS ghosted\n FROM deal_outcomes\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n ORDER BY play_name ASC NULLS LAST\n `;\n return this.db.query(sql).all(...(args as never[])) as never;\n }\n\n listColdProspects(opts: {\n minDaysSinceLastEvent: number;\n maxDaysSinceLastEvent: number;\n limit?: number;\n }): Array<{\n id: number;\n name: string | null;\n email: string | null;\n company: string | null;\n linkedin_url: string | null;\n phone: string | null;\n last_event_at: string | null;\n }> {\n const sql = `\n SELECT p.id, p.name, p.email, p.company, p.linkedin_url, p.phone, MAX(s.created_at) AS last_event_at\n FROM prospects p\n LEFT JOIN sequence_events s ON s.prospect_id = p.id\n GROUP BY p.id\n HAVING last_event_at IS NOT NULL\n AND julianday('now') - julianday(last_event_at) BETWEEN ? AND ?\n ORDER BY last_event_at ASC\n LIMIT ?\n `;\n return this.db\n .query(sql)\n .all(opts.minDaysSinceLastEvent, opts.maxDaysSinceLastEvent, opts.limit ?? 50) as never;\n }\n\n recordSequenceEvent(input: {\n prospectId: number;\n playName: string;\n stepIndex: number;\n channel: SequenceEventRecord[\"channel\"];\n status: SequenceEventRecord[\"status\"];\n metadata?: unknown;\n /** The send receipt this step produced — links the step to its billable call\n * so an outcome (reply/deal) can tag the receipt's value. */\n receiptId?: number;\n }): number {\n const stmt = this.db.prepare(`\n INSERT INTO sequence_events(prospect_id, play_name, step_index, channel, status, metadata_json, receipt_id)\n VALUES(?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.prospectId,\n input.playName,\n input.stepIndex,\n input.channel,\n input.status,\n input.metadata ? JSON.stringify(input.metadata) : null,\n input.receiptId ?? null,\n );\n return Number(result.lastInsertRowid);\n }\n\n /** Persist the RoCS value tag (JSON `{type,amount?,label?}`) on a single receipt. */\n setReceiptValueTag(receiptId: number, valueTagJson: string): void {\n this.db\n .prepare(`UPDATE receipts SET value_tag = ?, value_tagged_at = datetime('now') WHERE id = ?`)\n .run(valueTagJson, receiptId);\n }\n\n /**\n * Local mirror of a goal-level value tag: stamp every receipt in the cadence\n * (matching `goal_id`) so the /receipts UI shows the value per row. Returns the\n * number of receipts touched. The platform records the value once per goal via\n * `tagReceiptValue({goalId})`; this just keeps the dashboard in sync.\n */\n setReceiptValueTagByGoal(goalId: string, valueTagJson: string): number {\n const res = this.db\n .prepare(\n `UPDATE receipts SET value_tag = ?, value_tagged_at = datetime('now') WHERE goal_id = ?`,\n )\n .run(valueTagJson, goalId);\n return res.changes;\n }\n\n /** Current local value tag for a goal (any one of its receipts), or null. */\n currentGoalValueTag(goalId: string): string | null {\n const row = this.db\n .query(`SELECT value_tag FROM receipts WHERE goal_id = ? AND value_tag IS NOT NULL LIMIT 1`)\n .get(goalId) as { value_tag: string } | undefined;\n return row?.value_tag ?? null;\n }\n\n /**\n * Human labels (play + prospect) for a set of goalIds, derived from the local\n * receipts so the Measure page can render OneShot's opaque goal_id rollups as\n * \"{play} → {prospect}\". First receipt per goal wins.\n */\n goalLabels(goalIds: string[]): Map<string, { playName: string | null; prospect: string | null }> {\n const out = new Map<string, { playName: string | null; prospect: string | null }>();\n if (goalIds.length === 0) return out;\n const placeholders = goalIds.map(() => \"?\").join(\",\");\n const rows = this.db\n .query(\n `SELECT goal_id, play_name, decision_context FROM receipts WHERE goal_id IN (${placeholders})`,\n )\n .all(...goalIds) as Array<{\n goal_id: string;\n play_name: string;\n decision_context: string | null;\n }>;\n for (const r of rows) {\n if (out.has(r.goal_id)) continue;\n let prospect: string | null = null;\n if (r.decision_context) {\n try {\n const dc = JSON.parse(r.decision_context) as {\n prospectEmail?: string;\n customerName?: string;\n };\n prospect = dc.prospectEmail ?? dc.customerName ?? null;\n } catch {\n prospect = null;\n }\n }\n out.set(r.goal_id, { playName: r.play_name, prospect });\n }\n return out;\n }\n\n /**\n * True when a (prospect, play, step) already has a terminal-sent sequence_event\n * — i.e. that step's email/SMS/voice already went out. Used by the cadence\n * engine as a pre-dispatch guard so a crash between `recordSequenceEvent` and\n * `advanceCadence` (which leaves `current_step` lagging the sent step) can't\n * cause a re-send on the next due tick. Same status predicate as the stale-send\n * sweep below.\n */\n hasSentSequenceEvent(prospectId: number, playName: string, stepIndex: number): boolean {\n return (\n this.db\n .prepare(\n `SELECT 1 FROM sequence_events\n WHERE prospect_id = ? AND play_name = ? AND step_index = ?\n AND status IN ('sent','delivered','replied')\n LIMIT 1`,\n )\n .get(prospectId, playName, stepIndex) != null\n );\n }\n\n /**\n * Mark a prospect's latest sent step `replied` (the reply-rate signal behind\n * the home dashboard + measure/CAC, which all read `status='replied'` from\n * sequence_events — nothing else writes it). A reply is modelled as a state\n * transition of an existing sent step, NOT a new event, so `sent` counts that\n * read `status IN ('sent','delivered','replied')` stay correct.\n *\n * Idempotent and safe to call on every poll: the `NOT EXISTS` guard means once\n * any step for this (prospect, play) is `replied`, further calls are no-ops —\n * so it never walks backwards marking earlier steps too. Returns true on the\n * one call that flips a row.\n */\n markLatestStepReplied(input: { prospectId: number; playName: string }): boolean {\n const result = this.db\n .prepare(\n `UPDATE sequence_events SET status = 'replied'\n WHERE id = (\n SELECT id FROM sequence_events\n WHERE prospect_id = ? AND play_name = ? AND status IN ('sent','delivered')\n ORDER BY created_at DESC, id DESC LIMIT 1\n )\n AND NOT EXISTS (\n SELECT 1 FROM sequence_events\n WHERE prospect_id = ? AND play_name = ? AND status = 'replied'\n )`,\n )\n .run(input.prospectId, input.playName, input.prospectId, input.playName);\n return result.changes > 0;\n }\n\n /**\n * Single source of truth for \"a prospect replied to a cadence\". Atomically\n * writes BOTH planes so they can't drift:\n * - control plane: `cadence_state.status='replied'` (stops further sends), and\n * - analytics plane: the latest sent step → `replied` in sequence_events\n * (the event log behind every reply metric — home, CAC, weekly review).\n * The two surfaces read different tables on purpose (a lifetime status snapshot\n * vs a 7-day count), but a reply now updates them together in one transaction.\n *\n * Reads the current status inside the transaction and acts on it, so callers\n * just hand it a (prospect, play): an `active` cadence flips + records; an\n * already-`replied` one only backfills the event (idempotent); a terminal\n * `breakup`/`completed` cadence is left untouched. Returns `newlyReplied` —\n * true only on the active→replied transition, so callers count a reply once.\n */\n recordCadenceReply(input: { prospectId: number; playName: string }): { newlyReplied: boolean } {\n return this.db.transaction(() => {\n const cad = this.getCadence(input.prospectId, input.playName);\n const newlyReplied = cad?.status === \"active\";\n if (newlyReplied) {\n this.setCadenceStatus({\n prospectId: input.prospectId,\n playName: input.playName,\n status: \"replied\",\n });\n }\n if (newlyReplied || cad?.status === \"replied\") {\n this.markLatestStepReplied({\n prospectId: input.prospectId,\n playName: input.playName,\n });\n }\n return { newlyReplied };\n })();\n }\n\n listSequenceEventsForProspectPlay(prospectId: number, playName: string): SequenceEventRecord[] {\n return this.db\n .query(\n `SELECT * FROM sequence_events\n WHERE prospect_id = ? AND play_name = ?\n AND status IN ('sent','delivered','replied')\n ORDER BY step_index ASC, id ASC`,\n )\n .all(prospectId, playName) as SequenceEventRecord[];\n }\n\n /**\n * Bulk variant of listSequenceEventsForProspectPlay: one SQL round-trip for\n * many (prospect_id, play_name) pairs. Returns a Map keyed by\n * `${prospect_id}|${play_name}` so callers can index in O(1). The\n * per-key arrays preserve the same (step_index ASC, id ASC) ordering the\n * single-row method returns. Empty input → empty map (no query).\n *\n * Index-served by idx_sequence_events_prospect_play; the OR-chain is\n * expanded into per-pair index seeks by the query planner.\n */\n listSequenceEventsForCadences(\n pairs: ReadonlyArray<{ prospectId: number; playName: string }>,\n ): Map<string, SequenceEventRecord[]> {\n const map = new Map<string, SequenceEventRecord[]>();\n if (pairs.length === 0) return map;\n const conditions = pairs.map(() => \"(prospect_id = ? AND play_name = ?)\").join(\" OR \");\n const args: unknown[] = [];\n for (const p of pairs) {\n args.push(p.prospectId, p.playName);\n }\n const rows = this.db\n .query(\n `SELECT * FROM sequence_events\n WHERE (${conditions})\n AND status IN ('sent','delivered','replied')\n ORDER BY prospect_id ASC, play_name ASC, step_index ASC, id ASC`,\n )\n .all(...(args as never[])) as SequenceEventRecord[];\n for (const r of rows) {\n const key = `${r.prospect_id}|${r.play_name}`;\n let list = map.get(key);\n if (!list) {\n list = [];\n map.set(key, list);\n }\n list.push(r);\n }\n return map;\n }\n\n recordInterview(input: Omit<InterviewRecord, \"id\" | \"created_at\">): number {\n const stmt = this.db.prepare(`\n INSERT INTO interviews(person, transcript_path, jtbd, pain_quotes_json)\n VALUES(?, ?, ?, ?)\n `);\n const result = stmt.run(\n input.person,\n input.transcript_path,\n input.jtbd,\n input.pain_quotes_json,\n );\n return Number(result.lastInsertRowid);\n }\n\n countSends(opts: { playName?: string } = {}): number {\n const sql = opts.playName\n ? \"SELECT COUNT(*) AS n FROM sequence_events WHERE play_name = ? AND status IN ('sent', 'delivered', 'replied')\"\n : \"SELECT COUNT(*) AS n FROM sequence_events WHERE status IN ('sent', 'delivered', 'replied')\";\n const args = opts.playName ? [opts.playName] : [];\n return (this.db.query(sql).get(...(args as never[])) as { n: number } | null)?.n ?? 0;\n }\n\n spendByPlay(\n opts: { sinceIso?: string } = {},\n ): Array<{ play_name: string; calls: number; total_usd: number }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT play_name, COUNT(*) AS calls, COALESCE(SUM(cost_usd), 0) AS total_usd\n FROM receipts\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n ORDER BY total_usd DESC, calls DESC\n `;\n return this.db.query(sql).all(...(args as never[])) as Array<{\n play_name: string;\n calls: number;\n total_usd: number;\n }>;\n }\n\n eventsByPlay(opts: { sinceIso?: string } = {}): Array<{\n play_name: string;\n sent: number;\n delivered: number;\n replied: number;\n bounced: number;\n }> {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `\n SELECT\n play_name,\n SUM(CASE WHEN status IN ('sent', 'delivered', 'replied') THEN 1 ELSE 0 END) AS sent,\n SUM(CASE WHEN status IN ('delivered', 'replied') THEN 1 ELSE 0 END) AS delivered,\n SUM(CASE WHEN status = 'replied' THEN 1 ELSE 0 END) AS replied,\n SUM(CASE WHEN status = 'bounced' THEN 1 ELSE 0 END) AS bounced\n FROM sequence_events\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n GROUP BY play_name\n `;\n return this.db.query(sql).all(...(args as never[])) as Array<{\n play_name: string;\n sent: number;\n delivered: number;\n replied: number;\n bounced: number;\n }>;\n }\n\n totalSpendUsd(opts: { sinceIso?: string; playName?: string } = {}): number {\n const where: string[] = [\"cost_usd IS NOT NULL\"];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.sinceIso) {\n where.push(\"created_at >= ?\");\n args.push(opts.sinceIso);\n }\n const sql = `SELECT COALESCE(SUM(cost_usd), 0) AS total FROM receipts WHERE ${where.join(\" AND \")}`;\n return (this.db.query(sql).get(...(args as never[])) as { total: number } | null)?.total ?? 0;\n }\n\n // ── target_queue ────────────────────────────────────────────────────────────\n\n /**\n * Insert a row into target_queue. Returns the new id, or null if a row with\n * the same (play_name, dedupe_key) already exists.\n */\n enqueueTarget(input: {\n playName: string;\n payload: unknown;\n dedupeKey: string;\n source: string;\n notes?: string;\n /**\n * Status to insert with. Defaults to \"pending\" (the normal review path).\n * Pass \"rejected\" to record an auto-drop (e.g. ICP filter said no) so the\n * founder can see what was filtered out and override if needed.\n */\n initialStatus?: QueueStatus;\n }): number | null {\n try {\n const status = input.initialStatus ?? \"pending\";\n const reviewedAt = status === \"pending\" ? null : new Date().toISOString();\n const result = this.db\n .prepare(\n `INSERT INTO target_queue(play_name, payload_json, dedupe_key, source, status, reviewed_at, notes)\n VALUES(?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n input.playName,\n JSON.stringify(input.payload),\n input.dedupeKey,\n input.source,\n status,\n reviewedAt,\n input.notes ?? null,\n );\n return Number(result.lastInsertRowid);\n } catch (err) {\n // Unique constraint violation = already queued; return null to signal dedupe.\n const msg = (err as Error).message ?? \"\";\n if (msg.includes(\"UNIQUE constraint failed\")) return null;\n throw err;\n }\n }\n\n isQueueDuplicate(playName: string, dedupeKey: string): boolean {\n const row = this.db\n .query(\"SELECT 1 FROM target_queue WHERE play_name = ? AND dedupe_key = ?\")\n .get(playName, dedupeKey);\n return row !== null && row !== undefined;\n }\n\n /**\n * Persist a candidate whose paid resolution hit a transient platform error,\n * so the retry pass can complete it later (and re-scan won't re-create it).\n * Idempotent: a re-discovered candidate keeps its original first_seen_at and\n * attempt count (the retry pass owns attempt bookkeeping).\n */\n upsertPendingResolution(input: {\n playName: string;\n dedupeKey: string;\n source: string;\n raw: unknown;\n }): void {\n this.db\n .prepare(\n `INSERT INTO pending_resolution(play_name, dedupe_key, source, raw_json)\n VALUES(?, ?, ?, ?)\n ON CONFLICT(play_name, dedupe_key) DO UPDATE SET\n source = excluded.source,\n raw_json = excluded.raw_json`,\n )\n .run(input.playName, input.dedupeKey, input.source, JSON.stringify(input.raw));\n }\n\n /** True when (play, dedupeKey) is awaiting retry — finders OR this into their dedup. */\n isPendingResolution(playName: string, dedupeKey: string): boolean {\n const row = this.db\n .query(\"SELECT 1 FROM pending_resolution WHERE play_name = ? AND dedupe_key = ?\")\n .get(playName, dedupeKey);\n return row !== null && row !== undefined;\n }\n\n /** Pending rows (optionally one play), oldest first, for the retry pass. */\n listPendingResolution(opts?: { playName?: string; limit?: number }): Array<{\n play_name: string;\n dedupe_key: string;\n source: string;\n raw_json: string;\n first_seen_at: string;\n last_attempt_at: string | null;\n attempts: number;\n }> {\n const where = opts?.playName ? \"WHERE play_name = ?\" : \"\";\n const limit = opts?.limit ? `LIMIT ${Math.max(1, Math.floor(opts.limit))}` : \"\";\n const sql = `SELECT * FROM pending_resolution ${where} ORDER BY first_seen_at ASC ${limit}`;\n const q = this.db.query(sql);\n return (opts?.playName ? q.all(opts.playName) : q.all()) as never;\n }\n\n /** Mark a pending row as just-attempted (bumps attempts + last_attempt_at). */\n markPendingResolutionAttempted(playName: string, dedupeKey: string): void {\n this.db\n .prepare(\n `UPDATE pending_resolution\n SET attempts = attempts + 1, last_attempt_at = datetime('now')\n WHERE play_name = ? AND dedupe_key = ?`,\n )\n .run(playName, dedupeKey);\n }\n\n deletePendingResolution(playName: string, dedupeKey: string): void {\n this.db\n .prepare(\"DELETE FROM pending_resolution WHERE play_name = ? AND dedupe_key = ?\")\n .run(playName, dedupeKey);\n }\n\n /**\n * Purge pending rows older than maxAgeMs (permanently-unresolvable or an\n * aged-out time-windowed source) so their dedupe_key frees for future\n * re-discovery and the table doesn't silt. Returns the number removed.\n */\n sweepStalePendingResolution(maxAgeMs: number): number {\n const cutoff = new Date(Date.now() - maxAgeMs).toISOString();\n const res = this.db\n .prepare(\"DELETE FROM pending_resolution WHERE first_seen_at < ?\")\n .run(cutoff);\n return Number(res.changes ?? 0);\n }\n\n /**\n * Cross-play dedup (finder side): is this email already sitting in a\n * non-terminal queue row under ANY play? Catches the window where the same\n * person is queued under two plays before either has sent (so no prospect row\n * exists yet for findProspectByEmail to catch). Terminal rows\n * (sent/rejected/expired) are excluded so they never block future work.\n * Matches both `email` (most plays) and `founderEmail` (show-hn-style).\n */\n isEmailPendingInQueue(email: string): boolean {\n // Case-insensitive to match findProspectByEmail/upsertProspect, which store\n // and look up the canonical (lowercased) email — otherwise a casing mismatch\n // between two finders would slip a dup through. LOWER() on the JSON side,\n // canonEmail() on the arg.\n const row = this.db\n .query(\n `SELECT 1 FROM target_queue\n WHERE status IN ('pending','approved')\n AND (LOWER(json_extract(payload_json, '$.email')) = ?1\n OR LOWER(json_extract(payload_json, '$.founderEmail')) = ?1)\n LIMIT 1`,\n )\n .get(canonEmail(email));\n return row !== null && row !== undefined;\n }\n\n /**\n * Cross-play dedup (send side): has this prospect already received an initial\n * (step-0) touch under ANY play? The authoritative guard against first-touching\n * the same person twice. Mirrors the step-0 existence check in\n * sweepStaleCadenceSends. Note: deliberate re-engagement (breakup-revive)\n * bypasses this via sendDraftedEmail's `allowRecontact`.\n */\n prospectHasFirstTouch(prospectId: number): boolean {\n const row = this.db\n .query(\n `SELECT 1 FROM sequence_events\n WHERE prospect_id = ? AND step_index = 0\n AND status IN ('sent','delivered','replied')\n LIMIT 1`,\n )\n .get(prospectId);\n return row !== null && row !== undefined;\n }\n\n /**\n * Look up a queue row by its (play_name, dedupe_key) — the unique pair.\n * Used by the SSE /run endpoint to map drafts back to the originating\n * row so we can persist `last_draft_json`. Returns null when absent.\n */\n getQueueRowByDedupe(playName: string, dedupeKey: string): QueueRow | null {\n return (\n (this.db\n .query(\"SELECT * FROM target_queue WHERE play_name = ? AND dedupe_key = ?\")\n .get(playName, dedupeKey) as QueueRow) ?? null\n );\n }\n\n listQueue(opts: { playName?: string; status?: QueueStatus; limit?: number } = {}): QueueRow[] {\n const where: string[] = [];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n if (opts.status) {\n where.push(\"status = ?\");\n args.push(opts.status);\n }\n const sql = `\n SELECT * FROM target_queue\n ${where.length ? `WHERE ${where.join(\" AND \")}` : \"\"}\n ORDER BY found_at DESC\n LIMIT ?\n `;\n args.push(opts.limit ?? 200);\n return this.db.query(sql).all(...(args as never[])) as QueueRow[];\n }\n\n getQueueRow(id: number): QueueRow | null {\n return (this.db.query(\"SELECT * FROM target_queue WHERE id = ?\").get(id) as QueueRow) ?? null;\n }\n\n setQueueStatus(input: { id: number; status: QueueStatus; notes?: string }): void {\n const now = new Date().toISOString();\n // Every status transition clears `send_started_at` — a deliberate status\n // change means the previous \"sending\" attempt (if any) is settled. Terminal\n // states (sent/rejected/expired) clear naturally. Approved → approved\n // doesn't need to preserve a marker (caller re-claims on the next send).\n if (input.status === \"sent\") {\n this.db\n .prepare(\n `UPDATE target_queue SET status = ?, sent_at = ?, reviewed_at = COALESCE(reviewed_at, ?), send_started_at = NULL ${input.notes ? \", notes = ?\" : \"\"} WHERE id = ?`,\n )\n .run(\n ...(input.notes\n ? [input.status, now, now, input.notes, input.id]\n : [input.status, now, now, input.id]),\n );\n } else if (input.status === \"approved\" || input.status === \"rejected\") {\n this.db\n .prepare(\n `UPDATE target_queue SET status = ?, reviewed_at = ?, send_started_at = NULL ${input.notes ? \", notes = ?\" : \"\"} WHERE id = ?`,\n )\n .run(\n ...(input.notes\n ? [input.status, now, input.notes, input.id]\n : [input.status, now, input.id]),\n );\n } else {\n this.db\n .prepare(`UPDATE target_queue SET status = ?, send_started_at = NULL WHERE id = ?`)\n .run(input.status, input.id);\n }\n }\n\n /**\n * Atomic claim of the queue-send marker on `target_queue.send_started_at`.\n * Mirrors `claimCadenceSendingMarker` semantics — survives server restart so\n * `/queue` Send-draft UI doesn't lose its spinner on `bun --watch` reloads.\n * Cleared on success via `setQueueStatus('sent', …)`, on failure via\n * `clearQueueSendingMarker`, on cold boot via `sweepStaleQueueSends`.\n */\n claimQueueSendingMarker(input: {\n id: number;\n startedAtIso: string;\n staleCutoffIso?: string;\n }): boolean {\n return this.claimMarker({\n table: \"target_queue\",\n pkeyWhere: \"id = ?\",\n column: \"send_started_at\",\n pkeyValues: [input.id],\n startedAtIso: input.startedAtIso,\n ...(input.staleCutoffIso ? { staleCutoffIso: input.staleCutoffIso } : {}),\n });\n }\n\n clearQueueSendingMarker(id: number): void {\n this.clearMarker({\n table: \"target_queue\",\n pkeyWhere: \"id = ?\",\n column: \"send_started_at\",\n pkeyValues: [id],\n });\n }\n\n /**\n * Sweep queue rows whose `send_started_at` is older than `maxAgeMs` (or any\n * non-null when 0 — cold-boot semantics). For each: classify by current\n * status. status='sent' means the SDK call landed before the kill (clear\n * the marker only); otherwise the send was stranded (clear the marker,\n * draft is still on the row for retry).\n */\n sweepStaleQueueSends(input: { now: Date; maxAgeMs: number }): Array<{\n id: number;\n startedAt: string;\n ageMs: number;\n actuallySent: boolean;\n }> {\n const cutoffMs = input.now.getTime() - input.maxAgeMs;\n const rows = this.db\n .query(\n `SELECT id, status, send_started_at FROM target_queue WHERE send_started_at IS NOT NULL`,\n )\n .all() as Array<{ id: number; status: string; send_started_at: string }>;\n const swept: Array<{\n id: number;\n startedAt: string;\n ageMs: number;\n actuallySent: boolean;\n }> = [];\n const clear = this.db.prepare(`UPDATE target_queue SET send_started_at = NULL WHERE id = ?`);\n for (const row of rows) {\n const startedMs = new Date(row.send_started_at).getTime();\n if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue;\n const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;\n clear.run(row.id);\n swept.push({\n id: row.id,\n startedAt: row.send_started_at,\n ageMs,\n actuallySent: row.status === \"sent\",\n });\n }\n return swept;\n }\n\n approveAllPending(opts: { playName?: string } = {}): number {\n const where: string[] = [\"status = 'pending'\"];\n const args: unknown[] = [];\n if (opts.playName) {\n where.push(\"play_name = ?\");\n args.push(opts.playName);\n }\n const result = this.db\n .prepare(\n `UPDATE target_queue SET status = 'approved', reviewed_at = ? WHERE ${where.join(\" AND \")}`,\n )\n .run(...([new Date().toISOString(), ...args] as never[]));\n return Number(result.changes);\n }\n\n /**\n * Atomic claim-and-return. SELECTs approved rows whose lease has expired\n * (or was never set) and UPDATEs their `drain_claimed_at` inside a single\n * transaction so two concurrent drains can't return overlapping row sets.\n * Default lease: 15 min — a crashed drain's claims self-heal after that\n * without any sweeper. Held/error rows naturally back off for the lease\n * duration (no LLM-burn loops on stuck-flagged content).\n */\n dequeueApproved(opts: { playName: string; limit?: number; leaseSeconds?: number }): QueueRow[] {\n const leaseSeconds = opts.leaseSeconds ?? 900;\n const claimedAt = new Date().toISOString();\n const cutoff = new Date(Date.now() - leaseSeconds * 1000).toISOString();\n const limit = opts.limit ?? 50;\n const txn = this.db.transaction((): QueueRow[] => {\n const rows = this.db\n .query(\n `SELECT * FROM target_queue\n WHERE play_name = ? AND status = 'approved'\n AND (drain_claimed_at IS NULL OR drain_claimed_at < ?)\n ORDER BY found_at ASC\n LIMIT ?`,\n )\n .all(opts.playName, cutoff, limit) as QueueRow[];\n if (rows.length === 0) return [];\n const ids = rows.map((r) => r.id);\n const placeholders = ids.map(() => \"?\").join(\",\");\n this.db\n .prepare(`UPDATE target_queue SET drain_claimed_at = ? WHERE id IN (${placeholders})`)\n .run(...([claimedAt, ...ids] as never[]));\n return rows;\n });\n // BEGIN IMMEDIATE takes a RESERVED lock at the start of the transaction\n // instead of the default DEFERRED (which only locks on the first write).\n // In WAL mode with two processes, DEFERRED lets both transactions pass\n // the SELECT before either holds the write lock, then the second UPDATE\n // silently overwrites the first's claim — both drains would consider the\n // rows theirs. IMMEDIATE serializes the whole thing across connections.\n return txn.immediate();\n }\n\n expirePendingOlderThan(days: number): number {\n const sinceIso = new Date(Date.now() - days * 24 * 3600 * 1000).toISOString();\n const result = this.db\n .prepare(\n `UPDATE target_queue SET status = 'expired' WHERE status = 'pending' AND found_at < ?`,\n )\n .run(sinceIso);\n return Number(result.changes);\n }\n\n queueCounts(): Record<QueueStatus, number> {\n const rows = this.db\n .query(\"SELECT status, COUNT(*) AS n FROM target_queue GROUP BY status\")\n .all() as Array<{ status: QueueStatus; n: number }>;\n const out: Record<QueueStatus, number> = {\n pending: 0,\n approved: 0,\n rejected: 0,\n sent: 0,\n expired: 0,\n };\n for (const r of rows) out[r.status] = r.n;\n return out;\n }\n\n // ── runs (per-/run-page dispatch records) ──────────────────────────────────\n //\n // Each click of the /run page's Execute CTA creates one `runs` row. The SSE\n // endpoint persists every draft / send / error event to the row's\n // `events_json` and updates counters atomically. The UI reads this row to\n // rebuild progress on nav-back, and inspects `status` to decide whether to\n // poll (running) or stop (done / interrupted). Cold-boot sweep flips any\n // stranded `running` rows to `interrupted` so the founder sees the truth\n // instead of an eternal spinner.\n\n createRun(input: { playName: string; dryRun: boolean; targets: unknown[] }): {\n runId: number;\n startedAt: string;\n } {\n const startedAt = new Date().toISOString();\n const result = this.db\n .prepare(\n `INSERT INTO runs(play_name, dry_run, status, started_at, target_count, targets_json)\n VALUES(?, ?, 'running', ?, ?, ?)`,\n )\n .run(\n input.playName,\n input.dryRun ? 1 : 0,\n startedAt,\n input.targets.length,\n JSON.stringify(input.targets),\n );\n return { runId: Number(result.lastInsertRowid), startedAt };\n }\n\n /**\n * Append a single event to a run's events_json and bump the matching\n * counter. Cheap re-serialize is fine — events_json fits in a single row;\n * runs are bounded at ~25 targets typically.\n */\n appendRunEvent(input: { runId: number; event: unknown }): void {\n const row = this.db\n .query(\n `SELECT events_json, drafted_count, sent_count, error_count\n FROM runs WHERE id = ?`,\n )\n .get(input.runId) as {\n events_json: string;\n drafted_count: number;\n sent_count: number;\n error_count: number;\n } | null;\n if (!row) return;\n let events: unknown[];\n try {\n events = JSON.parse(row.events_json) as unknown[];\n if (!Array.isArray(events)) events = [];\n } catch {\n events = [];\n }\n events.push(input.event);\n // Counter bump driven by event.kind — keeps the writer side simple and\n // the read side stable. Unknown kinds are appended without counter change.\n const kind =\n input.event && typeof input.event === \"object\"\n ? ((input.event as { kind?: string }).kind ?? null)\n : null;\n let drafted = row.drafted_count;\n let sent = row.sent_count;\n let errors = row.error_count;\n if (kind === \"draft\") drafted++;\n else if (kind === \"send\") sent++;\n else if (kind === \"error\") errors++;\n this.db\n .prepare(\n `UPDATE runs\n SET events_json = ?, drafted_count = ?, sent_count = ?, error_count = ?\n WHERE id = ?`,\n )\n .run(JSON.stringify(events), drafted, sent, errors, input.runId);\n }\n\n markRunComplete(input: {\n runId: number;\n status: \"done\" | \"interrupted\";\n sentEmails?: string[];\n }): void {\n const completedAt = new Date().toISOString();\n this.db\n .prepare(\n `UPDATE runs\n SET status = ?, completed_at = ?, prospect_emails_json = ?\n WHERE id = ? AND status = 'running'`,\n )\n .run(input.status, completedAt, JSON.stringify(input.sentEmails ?? []), input.runId);\n }\n\n getRun(runId: number): {\n id: number;\n playName: string;\n dryRun: boolean;\n status: \"running\" | \"done\" | \"interrupted\";\n startedAt: string;\n completedAt: string | null;\n targetCount: number;\n draftedCount: number;\n sentCount: number;\n errorCount: number;\n targets: unknown[];\n events: unknown[];\n prospectEmails: string[];\n } | null {\n const row = this.db.query(`SELECT * FROM runs WHERE id = ?`).get(runId) as {\n id: number;\n play_name: string;\n dry_run: number;\n status: \"running\" | \"done\" | \"interrupted\";\n started_at: string;\n completed_at: string | null;\n target_count: number;\n drafted_count: number;\n sent_count: number;\n error_count: number;\n targets_json: string;\n events_json: string;\n prospect_emails_json: string;\n } | null;\n if (!row) return null;\n return {\n id: row.id,\n playName: row.play_name,\n dryRun: row.dry_run === 1,\n status: row.status,\n startedAt: row.started_at,\n completedAt: row.completed_at,\n targetCount: row.target_count,\n draftedCount: row.drafted_count,\n sentCount: row.sent_count,\n errorCount: row.error_count,\n targets: safeParseJsonArray(row.targets_json),\n events: safeParseJsonArray(row.events_json),\n prospectEmails: safeParseJsonArray(row.prospect_emails_json) as string[],\n };\n }\n\n /**\n * Compact run listing for dashboards. Returns lightweight columns only —\n * `events_json` + `targets_json` stay on the row but aren't read here so\n * `/api/home` doesn't pay to ship them on every 30s poll. Default order:\n * newest started_at first; capped at `limit` rows (default 5). When\n * `status` is set, filters via the existing `idx_runs_status` index.\n */\n listRuns(opts: { status?: \"running\" | \"done\" | \"interrupted\"; limit?: number } = {}): Array<{\n id: number;\n playName: string;\n status: \"running\" | \"done\" | \"interrupted\";\n startedAt: string;\n completedAt: string | null;\n targetCount: number;\n draftedCount: number;\n sentCount: number;\n errorCount: number;\n }> {\n const limit = Math.max(1, Math.min(50, opts.limit ?? 5));\n const where = opts.status ? \"WHERE status = ?\" : \"\";\n const args = opts.status ? [opts.status, limit] : [limit];\n const rows = this.db\n .query(\n `SELECT id, play_name, status, started_at, completed_at,\n target_count, drafted_count, sent_count, error_count\n FROM runs\n ${where}\n ORDER BY started_at DESC\n LIMIT ?`,\n )\n .all(...(args as never[])) as Array<{\n id: number;\n play_name: string;\n status: \"running\" | \"done\" | \"interrupted\";\n started_at: string;\n completed_at: string | null;\n target_count: number;\n drafted_count: number;\n sent_count: number;\n error_count: number;\n }>;\n return rows.map((r) => ({\n id: r.id,\n playName: r.play_name,\n status: r.status,\n startedAt: r.started_at,\n completedAt: r.completed_at,\n targetCount: r.target_count,\n draftedCount: r.drafted_count,\n sentCount: r.sent_count,\n errorCount: r.error_count,\n }));\n }\n\n /**\n * Sweep run rows whose status is still 'running' but predate the cutoff\n * (or any non-null when 0 — cold-boot semantics). Marks them as\n * 'interrupted' so the UI shows a truthful banner instead of an eternal\n * spinner. Returns the swept rows so the caller can log them.\n */\n sweepStaleRuns(input: { now: Date; maxAgeMs: number }): Array<{\n id: number;\n playName: string;\n startedAt: string;\n ageMs: number;\n }> {\n const cutoffMs = input.now.getTime() - input.maxAgeMs;\n const rows = this.db\n .query(`SELECT id, play_name, started_at FROM runs WHERE status = 'running'`)\n .all() as Array<{ id: number; play_name: string; started_at: string }>;\n const swept: Array<{\n id: number;\n playName: string;\n startedAt: string;\n ageMs: number;\n }> = [];\n const update = this.db.prepare(\n `UPDATE runs SET status = 'interrupted', completed_at = ? WHERE id = ?`,\n );\n for (const row of rows) {\n const startedMs = new Date(row.started_at).getTime();\n if (Number.isFinite(startedMs) && startedMs > cutoffMs) continue;\n const ageMs = Number.isFinite(startedMs) ? input.now.getTime() - startedMs : -1;\n update.run(input.now.toISOString(), row.id);\n swept.push({\n id: row.id,\n playName: row.play_name,\n startedAt: row.started_at,\n ageMs,\n });\n }\n return swept;\n }\n\n // ── triggers (find watch state) ────────────────────────────────────────────\n\n upsertTrigger(input: { name: string; configJson: string; enabled?: boolean }): void {\n this.db\n .prepare(\n `INSERT INTO triggers(name, enabled, config_json)\n VALUES(?, ?, ?)\n ON CONFLICT(name) DO UPDATE SET\n enabled = excluded.enabled,\n config_json = excluded.config_json`,\n )\n .run(input.name, input.enabled === false ? 0 : 1, input.configJson);\n }\n\n getTrigger(name: string): TriggerRow | null {\n return (this.db.query(\"SELECT * FROM triggers WHERE name = ?\").get(name) as TriggerRow) ?? null;\n }\n\n listTriggers(): TriggerRow[] {\n return this.db.query(\"SELECT * FROM triggers ORDER BY name ASC\").all() as TriggerRow[];\n }\n\n /**\n * Records the result of a finished run AND clears `running_started_at` in\n * the same statement. This is the only \"completed\" path — both success and\n * caught-finder-throw funnel through here, so clearing the in-flight flag\n * here is the right semantic.\n */\n updateTriggerLastPoll(input: { name: string; summary: unknown }): void {\n this.db\n .prepare(\n `UPDATE triggers\n SET last_polled_at = ?, last_run_summary = ?, running_started_at = NULL\n WHERE name = ?`,\n )\n .run(new Date().toISOString(), JSON.stringify(input.summary), input.name);\n }\n\n /**\n * Atomic claim: marks a trigger as in-flight ONLY if it's not already\n * running. Returns true when the claim succeeded (caller may proceed to\n * fire), false when another caller already holds the slot.\n *\n * The conditional UPDATE closes the TOCTOU race that would otherwise let\n * two concurrent `fireTriggerNow` calls both pass an `isTriggerRunning()`\n * check, both write, both fire — burning real $ on duplicate API spend.\n * SQLite serializes writes per process, so the second UPDATE's `changes`\n * count is 0.\n *\n * `staleCutoffIso` (optional): when provided, the claim ALSO succeeds if\n * the existing `running_started_at` is older than the cutoff — a stale\n * marker (process killed, never cleared, freshness gate already says \"not\n * running\"). Without this, a 4h-stale row would 409 every retry until\n * the next cold-boot sweep, leaving the founder stuck.\n *\n * Cleared by `updateTriggerLastPoll` on completion or by\n * `sweepStaleRunningTriggers` on the next cold boot.\n */\n markTriggerRunning(name: string, startedAtIso: string, staleCutoffIso?: string): boolean {\n return this.claimMarker({\n table: \"triggers\",\n pkeyWhere: \"name = ?\",\n column: \"running_started_at\",\n pkeyValues: [name],\n startedAtIso,\n ...(staleCutoffIso ? { staleCutoffIso } : {}),\n });\n }\n\n /**\n * Sweep trigger rows whose `running_started_at` is older than `maxAgeMs`.\n * For each match, write a `last_run_summary = { error: \"killed_by_restart\",\n * at }` and clear the in-flight flag. Returns the swept rows so the caller\n * can log them.\n *\n * Pure-ish (takes `now` + `maxAgeMs` as args) so tests can drive both\n * \"fresh entries are spared\" and \"stale entries are swept\" without\n * faking the system clock.\n */\n sweepStaleRunningTriggers(input: {\n now: Date;\n maxAgeMs: number;\n }): Array<{ name: string; startedAt: string; ageMs: number }> {\n const cutoffMs = input.now.getTime() - input.maxAgeMs;\n const rows = this.db\n .query(`SELECT name, running_started_at FROM triggers WHERE running_started_at IS NOT NULL`)\n .all() as Array<{ name: string; running_started_at: string }>;\n const swept: Array<{ name: string; startedAt: string; ageMs: number }> = [];\n const update = this.db.prepare(\n `UPDATE triggers\n SET last_polled_at = ?, last_run_summary = ?, running_started_at = NULL\n WHERE name = ?`,\n );\n for (const row of rows) {\n const startedMs = new Date(row.running_started_at).getTime();\n if (!Number.isFinite(startedMs)) {\n // Garbage timestamp — clear it so it doesn't perpetually re-trip.\n update.run(\n input.now.toISOString(),\n JSON.stringify({\n error: \"killed_by_restart\",\n reason: \"running_started_at unparseable\",\n at: input.now.toISOString(),\n }),\n row.name,\n );\n continue;\n }\n if (startedMs > cutoffMs) continue; // still fresh\n const ageMs = input.now.getTime() - startedMs;\n update.run(\n input.now.toISOString(),\n JSON.stringify({\n error: \"killed_by_restart\",\n startedAt: row.running_started_at,\n ageMs,\n at: input.now.toISOString(),\n }),\n row.name,\n );\n swept.push({ name: row.name, startedAt: row.running_started_at, ageMs });\n }\n return swept;\n }\n\n setTriggerEnabled(name: string, enabled: boolean): void {\n this.db.prepare(`UPDATE triggers SET enabled = ? WHERE name = ?`).run(enabled ? 1 : 0, name);\n }\n\n setTriggerConfig(name: string, configJson: string): void {\n this.db.prepare(`UPDATE triggers SET config_json = ? WHERE name = ?`).run(configJson, name);\n }\n\n /**\n * Associate a queued target with a known prospect (so the queue page can\n * link back to the prospect record). Best-effort — the caller is expected\n * to swallow failures since the link is a convenience, not a correctness\n * invariant.\n */\n setQueueProspectId(id: number, prospectId: number): void {\n this.db.prepare(`UPDATE target_queue SET prospect_id = ? WHERE id = ?`).run(prospectId, id);\n }\n\n /**\n * Persist the most-recent draft generated for this queue row. Called by\n * the SSE /run endpoint after the play returns drafted output, so the\n * founder can review subject/body/flags on /queue at any later time\n * (the /run page itself is ephemeral).\n *\n * Most-recent-wins — re-runs overwrite without history. `last_drafted_at`\n * is stored as ISO so it sorts/compares cleanly with the rest of the\n * timestamp columns; the JSON envelope also embeds `draftedAt` for\n * callers that already have the row payload.\n */\n setQueueDraft(input: {\n id: number;\n draft: {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n dryRun: boolean;\n enrichmentFailed?: boolean;\n };\n }): void {\n const draftedAtIso = new Date().toISOString();\n const json = JSON.stringify({ ...input.draft, draftedAt: draftedAtIso });\n this.db\n .prepare(`UPDATE target_queue SET last_draft_json = ?, last_drafted_at = ? WHERE id = ?`)\n .run(json, draftedAtIso, input.id);\n }\n\n close(): void {\n this.db.close();\n }\n}\n\nlet singleton: Ledger | null = null;\n\nexport function getLedger(): Ledger {\n if (!singleton) singleton = new Ledger();\n return singleton;\n}\n","import { appendFileSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { configDir } from \"./config.ts\";\n\n/**\n * Local-only structured event log.\n *\n * Every interesting moment (LLM call, ICP filter decision, finder lifecycle,\n * swallowed errors) appends one JSON line to ~/.oneshot-gtm/events.jsonl.\n * Tail it with `tail -f ~/.oneshot-gtm/events.jsonl | jq` while iterating.\n *\n * ## Privacy boundary\n *\n * `ctx` may contain primitives, counters, durations, category labels, error\n * class names, hostname/domain. It must NEVER contain user-typed values like\n * email addresses or ICP one-liner text, prospect data, or LLM completions\n * verbatim. This is the same boundary that will apply when an opt-in HTTP\n * sink is added later — keeping the rule tight today means schema reuse\n * tomorrow.\n *\n * Not enforced programmatically. Code-review discipline at the call sites.\n *\n * ## Failure mode\n *\n * Logging never throws. A logging bug must not break the caller. If the\n * filesystem is read-only or the config dir doesn't exist, the event is\n * dropped silently.\n */\n\ntype EventLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\ninterface DevEvent {\n ts: string;\n kind: string;\n level: EventLevel;\n ctx?: Record<string, unknown>;\n /** Anonymous per-install id; resolved lazily so tests can mock it. */\n client_id?: string;\n /** Groups all events emitted within one \"run\" (one watch tick, one HTTP request, one CLI invocation). */\n run_id?: string;\n}\n\nconst EVENTS_PATH = join(configDir(), \"events.jsonl\");\nconst DEBUG_ENABLED = (process.env[\"DEBUG\"] ?? \"\").includes(\"oneshot\");\n\nlet runId: string | null = null;\nlet cachedClientId: string | null = null;\nlet clientIdResolved = false;\nlet configDirEnsured = false;\n\n/**\n * Begin a new \"run\" — subsequent events emitted from this process will share\n * the returned run_id until the next call. Useful for grouping with jq:\n * jq 'select(.run_id == \"abc-…\")'\n */\nexport function startRun(): string {\n runId = randomUUID();\n return runId;\n}\n\nexport function logEvent(\n kind: string,\n ctx?: Record<string, unknown>,\n level: EventLevel = \"info\",\n): void {\n // Whole body is best-effort; a logging bug must not break the caller.\n // buildEventLine can throw on BigInt / circular refs (JSON.stringify), so\n // it goes inside the try block alongside the filesystem work.\n try {\n const line = buildEventLine(kind, ctx, level, runId, resolveClientId(), new Date());\n\n if (!configDirEnsured) {\n if (!existsSync(configDir())) mkdirSync(configDir(), { recursive: true });\n configDirEnsured = true;\n }\n appendFileSync(EVENTS_PATH, line);\n\n if (DEBUG_ENABLED) {\n // Mirror to stderr so it doesn't interleave with command output on stdout.\n process.stderr.write(line);\n }\n } catch {\n // dropped silently — see file header\n }\n}\n\n/**\n * Pure builder for a single JSONL line. Extracted for testability — the\n * call site supplies `now`, `runId`, `clientId` so tests can pin them\n * without touching the module-level singletons or the filesystem.\n *\n * Includes the trailing newline so the caller can append in a single\n * fs syscall.\n */\nexport function buildEventLine(\n kind: string,\n ctx: Record<string, unknown> | undefined,\n level: EventLevel,\n runId: string | null,\n clientId: string | null,\n now: Date,\n): string {\n const event: DevEvent = {\n ts: now.toISOString(),\n kind,\n level,\n };\n if (ctx) event.ctx = ctx;\n if (clientId) event.client_id = clientId;\n if (runId) event.run_id = runId;\n return JSON.stringify(event) + \"\\n\";\n}\n\n/**\n * Read the clientId straight from config.json instead of going through\n * loadConfig() — that would create a circular import (config doesn't depend\n * on events today; we keep it that way). Survives the case where the file\n * doesn't exist yet: returns null and the event ships without a client_id.\n * Cached for the process lifetime once non-null.\n */\nfunction resolveClientId(): string | null {\n // First call resolves and caches, subsequent calls return the cached value\n // even if it's null. The previous `clientIdResolved && cachedClientId` check\n // re-read the config file on every event when bootstrap hadn't finished\n // yet — turning the once-per-process cost into a per-event syscall.\n if (clientIdResolved) return cachedClientId;\n clientIdResolved = true;\n try {\n const path = join(configDir(), \"config.json\");\n if (!existsSync(path)) return null;\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as { clientId?: string };\n cachedClientId = typeof parsed.clientId === \"string\" ? parsed.clientId : null;\n } catch {\n cachedClientId = null;\n }\n return cachedClientId;\n}\n\n/**\n * Test-only escape hatch. Lets vitest reset the cached id between cases when\n * it manipulates the underlying config file. Not exported via the package\n * barrel — import directly if you really need it.\n */\nexport function _resetClientIdCacheForTests(): void {\n cachedClientId = null;\n clientIdResolved = false;\n configDirEnsured = false;\n runId = null;\n}\n\n","/**\n * Run `fn` over `items` with at most `concurrency` Promises in flight at once.\n * Preserves input order in the result array. Errors propagate via Promise.all\n * — caller is expected to catch per-item internally if partial success matters.\n *\n * Worker-pool implementation: spawn `concurrency` workers that pull from a\n * shared cursor. Cheaper than a chunked Promise.all (which stalls on the\n * slowest item per chunk) and avoids the dependency surface of p-limit.\n *\n * Lives in core so both `find` (candidate pipelines) and `plays` (batch send\n * loops) can share it without a cross-package dependency.\n */\n/**\n * Bound a promise to `ms`. On deadline: rejects with `<label> deadline\n * exceeded` — the underlying promise keeps running (callers that care attach\n * their own late-settle handlers; an abandoned SDK job is harmless). Guards\n * against platform endpoints that hang instead of failing (observed on both\n * the inbox and enrichment tools 2026-06).\n */\nexport function withDeadline<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(`${label} deadline exceeded (${Math.round(ms / 1000)}s)`)),\n ms,\n );\n promise.then(\n (v) => {\n clearTimeout(timer);\n resolve(v);\n },\n (e) => {\n clearTimeout(timer);\n reject(e as Error);\n },\n );\n });\n}\n\nexport async function parallelMap<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n /**\n * Optional per-completion hook. Fires once per item AFTER `fn(item, i)`\n * resolves, with the (item, result, index). Used by /api/run's SSE handler\n * to emit `draft` + `send` frames as each target finishes — instead of\n * batching them all at the end when the whole `Promise.all` resolves.\n *\n * Order: callbacks fire in COMPLETION order across workers, not input\n * order. Consumers that care about index (the SSE event already does)\n * key by the `index` argument.\n *\n * Throws inside the callback propagate as if `fn` threw — keep handlers\n * defensive.\n */\n onItem?: (item: T, result: R, index: number) => void,\n): Promise<R[]> {\n const out: R[] = Array.from({ length: items.length });\n if (items.length === 0) return out;\n const workers = Math.max(1, Math.min(concurrency, items.length));\n let cursor = 0;\n async function worker(): Promise<void> {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n const item = items[i] as T;\n const result = await fn(item, i);\n out[i] = result;\n if (onItem) onItem(item, result, i);\n }\n }\n await Promise.all(Array.from({ length: workers }, () => worker()));\n return out;\n}\n","import type { InboxEmail, InboxListResult } from \"@oneshot-agent/sdk\";\nimport { parallelMap } from \"./parallel.ts\";\n\n/**\n * Gmail / Google Workspace send + reply path. Plain-fetch OAuth2 + Gmail REST\n * — no googleapis dependency. Credentials come from three secrets minted by\n * `bun run cli -- gmail auth`: GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET,\n * GMAIL_REFRESH_TOKEN (stored in ~/.oneshot-gtm/.env, applied to process.env\n * by config.ts on import).\n */\n\nconst TOKEN_URL = \"https://oauth2.googleapis.com/token\";\nconst GMAIL_API = \"https://gmail.googleapis.com/gmail/v1/users/me\";\n\nexport const GMAIL_AUTH_HINT = \"run: bun run cli -- gmail auth\";\n\nexport const GMAIL_OAUTH_SCOPES =\n \"https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/gmail.readonly\";\n\n/** Google consent URL for the loopback OAuth flow (CLI command and /setup button share it). */\nexport function gmailConsentUrl(opts: {\n clientId: string;\n redirectUri: string;\n state: string;\n}): string {\n return `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({\n client_id: opts.clientId,\n redirect_uri: opts.redirectUri,\n response_type: \"code\",\n scope: GMAIL_OAUTH_SCOPES,\n access_type: \"offline\",\n prompt: \"consent\",\n state: opts.state,\n })}`;\n}\n\n/** Exchange an authorization code for a refresh token. Throws with an actionable message on any failure. */\nexport async function exchangeGmailAuthCode(opts: {\n code: string;\n clientId: string;\n clientSecret: string;\n redirectUri: string;\n}): Promise<string> {\n const res = await fetch(TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n code: opts.code,\n client_id: opts.clientId,\n client_secret: opts.clientSecret,\n redirect_uri: opts.redirectUri,\n grant_type: \"authorization_code\",\n }),\n });\n const data = (await res.json()) as {\n refresh_token?: string;\n error?: string;\n error_description?: string;\n };\n if (!res.ok || !data.refresh_token) {\n const detail = data.error\n ? `${data.error}${data.error_description ? ` — ${data.error_description}` : \"\"}`\n : `http ${res.status}`;\n const hint =\n res.ok && !data.refresh_token\n ? \" (no refresh_token returned — revoke prior access at myaccount.google.com/permissions and retry)\"\n : \"\";\n throw new Error(`Gmail token exchange failed: ${detail}${hint}`);\n }\n return data.refresh_token;\n}\n\nexport function missingGmailSecrets(): string[] {\n return [\"GMAIL_CLIENT_ID\", \"GMAIL_CLIENT_SECRET\", \"GMAIL_REFRESH_TOKEN\"].filter(\n (k) => !(process.env[k] ?? \"\").trim(),\n );\n}\n\n/**\n * One authorized Gmail account in the rotation pool. `id` keys the token /\n * profile caches; `refreshToken` comes from the gmail-tokens.json store (or\n * the legacy GMAIL_REFRESH_TOKEN secret). Omitted account = legacy\n * single-account mode reading the env secret directly.\n */\nexport interface GmailAccount {\n id: string;\n refreshToken: string;\n}\n\nconst LEGACY_CACHE_KEY = \"__legacy_env__\";\n\nconst tokenCache = new Map<string, { token: string; expiresAt: number }>();\nconst profileCache = new Map<string, { emailAddress: string }>();\n\n/** Test-only: clears the memoized access tokens + profiles (all accounts). */\nexport function _resetGmailCache(): void {\n tokenCache.clear();\n profileCache.clear();\n}\n\nexport async function getGmailAccessToken(account?: GmailAccount): Promise<string> {\n const cacheKey = account?.id ?? LEGACY_CACHE_KEY;\n const cached = tokenCache.get(cacheKey);\n // 60s skew so a token that expires mid-send is refreshed up front.\n if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.token;\n const refreshToken = account?.refreshToken ?? (process.env[\"GMAIL_REFRESH_TOKEN\"] ?? \"\").trim();\n const missing = account\n ? missingGmailSecrets().filter((k) => k !== \"GMAIL_REFRESH_TOKEN\")\n : missingGmailSecrets();\n if (missing.length > 0 || !refreshToken) {\n const what = [...missing, ...(refreshToken ? [] : [\"refresh token\"])].join(\", \");\n throw new Error(`Gmail credentials missing (${what}) — ${GMAIL_AUTH_HINT}`);\n }\n const res = await fetch(TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: process.env[\"GMAIL_CLIENT_ID\"]!,\n client_secret: process.env[\"GMAIL_CLIENT_SECRET\"]!,\n refresh_token: refreshToken,\n grant_type: \"refresh_token\",\n }),\n });\n const data = (await res.json()) as {\n access_token?: string;\n expires_in?: number;\n error?: string;\n error_description?: string;\n };\n if (!res.ok || !data.access_token) {\n if (data.error === \"invalid_grant\") {\n throw new Error(\n `Gmail auth expired or revoked${account ? ` for ${account.id}` : \"\"} — ${GMAIL_AUTH_HINT}`,\n );\n }\n throw new Error(`Gmail token refresh failed (${res.status}): ${data.error ?? \"unknown\"}`);\n }\n const entry = {\n token: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000,\n };\n tokenCache.set(cacheKey, entry);\n return entry.token;\n}\n\nasync function gmailFetch(\n path: string,\n init?: RequestInit,\n account?: GmailAccount,\n): Promise<Response> {\n const token = await getGmailAccessToken(account);\n return fetch(`${GMAIL_API}${path}`, {\n ...init,\n headers: { ...init?.headers, Authorization: `Bearer ${token}` },\n });\n}\n\nasync function gmailJson<T>(path: string, init?: RequestInit, account?: GmailAccount): Promise<T> {\n const res = await gmailFetch(path, init, account);\n if (!res.ok) {\n const body = (await res.text()).slice(0, 200);\n if (res.status === 401) {\n throw new Error(`Gmail auth rejected (401) — ${GMAIL_AUTH_HINT}`);\n }\n throw new Error(`Gmail API ${path.split(\"?\")[0]} failed (${res.status}): ${body}`);\n }\n return (await res.json()) as T;\n}\n\n/** Header values must be single-line; strips CR/LF to block header injection. */\nfunction headerValue(s: string): string {\n return s.replace(/[\\r\\n]+/g, \" \").trim();\n}\n\n/** RFC 2047 B-encoding for non-ASCII header text (subject, display name). */\nfunction encodeHeaderText(s: string): string {\n if (/^[\\x20-\\x7e]*$/.test(s)) return s;\n return `=?UTF-8?B?${Buffer.from(s, \"utf8\").toString(\"base64\")}?=`;\n}\n\nexport interface RawMessageInput {\n to: string;\n fromEmail: string;\n fromName?: string | null;\n subject: string;\n htmlBody: string;\n /** RFC 2822 Message-ID of the email being replied to → In-Reply-To header. */\n inReplyTo?: string;\n /** Prior Message-IDs of the conversation → References header (recipient-side threading). */\n references?: string[];\n}\n\n/** Build the base64url-encoded RFC 2822 message Gmail's `messages.send` expects. */\nexport function buildRawMessage(input: RawMessageInput): string {\n const name = headerValue(input.fromName ?? \"\");\n const from = name\n ? `\"${encodeHeaderText(name).replace(/\"/g, \"\")}\" <${headerValue(input.fromEmail)}>`\n : headerValue(input.fromEmail);\n const lines = [\n `From: ${from}`,\n `To: ${headerValue(input.to)}`,\n `Subject: ${encodeHeaderText(headerValue(input.subject))}`,\n ];\n if (input.inReplyTo) lines.push(`In-Reply-To: ${headerValue(input.inReplyTo)}`);\n if (input.references?.length) {\n lines.push(`References: ${headerValue(input.references.join(\" \"))}`);\n }\n lines.push(\n \"MIME-Version: 1.0\",\n 'Content-Type: text/html; charset=\"UTF-8\"',\n \"Content-Transfer-Encoding: 8bit\",\n \"\",\n input.htmlBody,\n );\n return Buffer.from(lines.join(\"\\r\\n\"), \"utf8\").toString(\"base64url\");\n}\n\nexport interface GmailSendResult {\n id: string;\n threadId: string;\n}\n\nexport async function sendGmailMessage(\n input: RawMessageInput,\n account?: GmailAccount,\n /** Gmail thread to attach the send to (threads our copy in the sender's mailbox). */\n threadId?: string,\n): Promise<GmailSendResult> {\n return gmailJson<GmailSendResult>(\n \"/messages/send\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n // threadId is a field of the Message resource (not a query param).\n body: JSON.stringify({ raw: buildRawMessage(input), ...(threadId ? { threadId } : {}) }),\n },\n account,\n );\n}\n\nexport async function getGmailProfile(account?: GmailAccount): Promise<{ emailAddress: string }> {\n const cacheKey = account?.id ?? LEGACY_CACHE_KEY;\n const cached = profileCache.get(cacheKey);\n if (cached) return cached;\n const profile = await gmailJson<{ emailAddress: string }>(\"/profile\", undefined, account);\n profileCache.set(cacheKey, profile);\n return profile;\n}\n\ninterface GmailMessageMeta {\n id: string;\n threadId: string;\n internalDate: string;\n payload?: GmailPayloadPart;\n}\n\ninterface GmailPayloadPart {\n mimeType?: string;\n headers?: Array<{ name: string; value: string }>;\n body?: { data?: string };\n parts?: GmailPayloadPart[];\n}\n\nfunction header(msg: GmailMessageMeta, name: string): string {\n const h = msg.payload?.headers?.find((x) => x.name.toLowerCase() === name.toLowerCase());\n return h?.value ?? \"\";\n}\n\nfunction extractPlainText(part: GmailPayloadPart | undefined): string {\n if (!part) return \"\";\n if (part.mimeType === \"text/plain\" && part.body?.data) {\n return Buffer.from(part.body.data, \"base64url\").toString(\"utf8\");\n }\n for (const child of part.parts ?? []) {\n const text = extractPlainText(child);\n if (text) return text;\n }\n return \"\";\n}\n\n/**\n * Inbox replies, mapped to the OneShot InboxListResult contract so\n * advanceCadence (stop-on-reply) and the /inbox route work unchanged.\n * `-from:me` excludes the founder's own sends at the query level — the\n * Gmail-mode equivalent of the OneShot path's self-domain filter.\n */\nexport async function listGmailReplies(\n opts?: {\n since?: string;\n limit?: number;\n },\n account?: GmailAccount,\n): Promise<InboxListResult> {\n const sinceClause = opts?.since\n ? `after:${Math.floor(new Date(opts.since).getTime() / 1000)}`\n : \"newer_than:30d\";\n const params = new URLSearchParams({\n q: `in:inbox -from:me ${sinceClause}`,\n maxResults: String(opts?.limit ?? 50),\n });\n const list = await gmailJson<{ messages?: Array<{ id: string }> }>(\n `/messages?${params}`,\n undefined,\n account,\n );\n const ids = (list.messages ?? []).map((m) => m.id);\n const emails = await parallelMap(\n ids,\n 4,\n async (id): Promise<InboxEmail & { message_id?: string }> => {\n const msg = await gmailJson<GmailMessageMeta>(\n `/messages/${id}?format=full`,\n undefined,\n account,\n );\n // RFC 2822 Message-ID — needed as In-Reply-To/References on a threaded reply.\n const messageId = header(msg, \"Message-ID\");\n return {\n id: msg.id,\n from: header(msg, \"From\"),\n subject: header(msg, \"Subject\"),\n received_at: new Date(Number(msg.internalDate)).toISOString(),\n thread_id: msg.threadId,\n body: extractPlainText(msg.payload),\n ...(messageId ? { message_id: messageId } : {}),\n };\n },\n );\n return { emails, count: emails.length, has_more: false, agent_id: \"gmail\" };\n}\n","import {\n deleteGmailToken,\n loadConfig,\n loadGmailTokens,\n saveConfig,\n saveGmailToken,\n} from \"./config.ts\";\nimport type { EmailIdentity, OneShotConfig } from \"./types.ts\";\n\nexport const LEGACY_ONESHOT_ID = \"legacy-oneshot\";\nexport const LEGACY_GMAIL_ID = \"legacy-gmail\";\n\n/**\n * Cold-start warm-up ramp for a freshly added sending identity: 10/day,\n * +10/week, capped at 50/day. Provider-agnostic — a brand-new Gmail account and\n * a brand-new OneShot domain/mailbox both start cold, so both ramp the same way.\n */\nexport const WARMUP_DEFAULTS: Pick<EmailIdentity, \"maxPerDay\" | \"warmup\"> = {\n maxPerDay: 50,\n warmup: { startPerDay: 10, incrementPerWeek: 10 },\n};\n\n/** @deprecated alias for {@link WARMUP_DEFAULTS}; kept for existing call sites. */\nexport const GMAIL_IDENTITY_DEFAULTS = WARMUP_DEFAULTS;\n\n/**\n * Normalize an email local-part: lowercase, trim, strip anything that isn't\n * alphanumeric / dot / dash / underscore / plus. Returns \"\" when nothing usable\n * survives so callers can fall back to a founder-derived default.\n */\nfunction normalizeMailbox(raw: string | null | undefined): string {\n return (raw ?? \"\")\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._+-]/g, \"\");\n}\n\n/**\n * The active sender pool. `emailIdentities` set → returned verbatim.\n * Null → legacy single-identity mode: synthesize one identity from the\n * pre-rotation fields (emailProvider + sendingDomain / env refresh token) so\n * existing installs behave exactly as before rotation existed. Legacy\n * identities are uncapped — capping them would silently stall sends on\n * installs that never opted into rotation.\n */\nexport function resolveIdentities(cfg: OneShotConfig): EmailIdentity[] {\n if (cfg.emailIdentities && cfg.emailIdentities.length > 0) return cfg.emailIdentities;\n if (cfg.emailProvider === \"gmail\") {\n return [\n {\n id: LEGACY_GMAIL_ID,\n provider: \"gmail\",\n label: \"Gmail (legacy single-account mode)\",\n maxPerDay: null,\n warmup: null,\n },\n ];\n }\n return [\n {\n id: LEGACY_ONESHOT_ID,\n provider: \"oneshot\",\n label: \"OneShot (legacy mode)\",\n sendingDomain: cfg.sendingDomain,\n maxPerDay: null,\n warmup: null,\n },\n ];\n}\n\n/**\n * Persist a freshly authorized Gmail account: refresh token into the\n * chmod-600 store, identity into the rotation pool with warm-up defaults.\n * Legacy installs get their synthesized identity persisted first so existing\n * prospects keep their original From address. Re-auth of a known account\n * only refreshes the token — tuned caps are left alone.\n */\nexport function registerGmailIdentity(input: { address: string; refreshToken: string }): {\n identityId: string;\n created: boolean;\n} {\n const identityId = `gmail:${input.address.trim().toLowerCase()}`;\n saveGmailToken(identityId, { refreshToken: input.refreshToken, address: input.address });\n const cfg = loadConfig();\n const pool: EmailIdentity[] = cfg.emailIdentities\n ? [...cfg.emailIdentities]\n : resolveIdentities(cfg);\n if (pool.some((i) => i.id === identityId)) return { identityId, created: false };\n pool.push({\n id: identityId,\n provider: \"gmail\",\n label: input.address,\n address: input.address,\n ...WARMUP_DEFAULTS,\n });\n saveConfig({ ...cfg, emailIdentities: pool });\n return { identityId, created: true };\n}\n\n/**\n * Founder-name-derived default local-part (first token, normalized) — the\n * mailbox used when an OneShot identity is added without an explicit one. Falls\n * back to \"agent\". Mirrors `fromLocalpart` in oneshot.ts but lives here to keep\n * identities.ts free of an import cycle with the send layer.\n */\nfunction defaultMailbox(founderName: string | null): string {\n const first = normalizeMailbox((founderName ?? \"\").trim().split(/\\s+/)[0] ?? \"\");\n return first.length > 0 ? first : \"agent\";\n}\n\n/**\n * Add a OneShot sending identity (a wallet-owned domain + a mailbox local-part)\n * to the rotation pool. The OneShot analogue of `registerGmailIdentity`: there\n * was previously no way to put a second OneShot domain — or a second mailbox on\n * one domain — into the pool, only the single legacy `sendingDomain` config.\n *\n * Mirrors the Gmail path's invariants: the pool is materialized from legacy\n * config on first add (so existing prospect pins to the legacy sender survive),\n * and a duplicate id is a no-op. `sendingDomain` is NOT validated here against\n * the provisioned pool — callers (setup API / CLI) do that against\n * `listSendingDomains()` so this stays a pure persistence helper.\n *\n * Cap defaults, least-surprising:\n * - neither field given → full cold-start ramp (10/day, +10/week, max 50).\n * - `maxPerDay: <n>` → that hard ceiling, still ramping up to it (the ramp is\n * kept unless the caller overrides `warmup`).\n * - `maxPerDay: null` → truly uncapped — warmup is cleared too, since a ramp\n * without a ceiling would itself re-impose one (warmupCap clamps to 50).\n * - `warmup` always wins when explicitly provided.\n */\nexport function registerOneShotIdentity(input: {\n sendingDomain: string;\n mailbox?: string | null;\n label?: string | null;\n maxPerDay?: number | null;\n warmup?: EmailIdentity[\"warmup\"];\n}): { identityId: string; created: boolean } {\n const cfg = loadConfig();\n const sendingDomain = input.sendingDomain.trim().toLowerCase();\n if (!sendingDomain) throw new Error(\"sendingDomain is required to add a OneShot identity\");\n const mailbox = normalizeMailbox(input.mailbox) || defaultMailbox(cfg.founderName);\n const identityId = `oneshot:${mailbox}@${sendingDomain}`;\n\n const pool: EmailIdentity[] = cfg.emailIdentities\n ? [...cfg.emailIdentities]\n : resolveIdentities(cfg);\n if (pool.some((i) => i.id === identityId)) return { identityId, created: false };\n\n let maxPerDay: number | null;\n let warmup: EmailIdentity[\"warmup\"];\n if (!(\"maxPerDay\" in input) && !(\"warmup\" in input)) {\n ({ maxPerDay, warmup } = WARMUP_DEFAULTS);\n } else {\n maxPerDay = input.maxPerDay ?? null;\n warmup =\n \"warmup\" in input\n ? (input.warmup ?? null)\n : maxPerDay == null\n ? null // uncapped — don't let a default ramp silently re-cap at 50\n : WARMUP_DEFAULTS.warmup;\n }\n const caps: Pick<EmailIdentity, \"maxPerDay\" | \"warmup\"> = { maxPerDay, warmup };\n pool.push({\n id: identityId,\n provider: \"oneshot\",\n label: input.label?.trim() || `${mailbox}@${sendingDomain}`,\n sendingDomain,\n mailbox,\n ...caps,\n });\n saveConfig({ ...cfg, emailIdentities: pool });\n return { identityId, created: true };\n}\n\n/**\n * Drop an identity from the rotation pool. Materializes the pool from legacy\n * config first so a removal on a not-yet-persisted pool still takes effect.\n * Best-effort token cleanup for Gmail identities. Returns whether anything was\n * removed. NOTE: prospects already pinned to this id will refuse to send until\n * the id is restored — `resolveSenderIdentity` surfaces that loudly by design.\n */\nexport function removeIdentity(identityId: string): { removed: boolean } {\n const cfg = loadConfig();\n const pool = cfg.emailIdentities ?? resolveIdentities(cfg);\n const next = pool.filter((i) => i.id !== identityId);\n if (next.length === pool.length) return { removed: false };\n try {\n deleteGmailToken(identityId);\n } catch {\n // token-store cleanup is best-effort; the identity is gone either way.\n }\n saveConfig({ ...cfg, emailIdentities: next });\n return { removed: true };\n}\n\n/**\n * Refresh token for a gmail identity. Identities created by `gmail auth` live\n * in the gmail-tokens.json store keyed by identity id. ONLY the legacy\n * synthetic identity may fall back to the single GMAIL_REFRESH_TOKEN secret —\n * letting any identity fall back would silently send from whatever account\n * the env token belongs to when a store entry goes missing, switching a\n * thread's From address mid-conversation.\n */\nexport function gmailAccountFor(\n identity: EmailIdentity,\n): { id: string; refreshToken: string } | null {\n if (identity.provider !== \"gmail\") return null;\n const stored = loadGmailTokens()[identity.id];\n if (stored?.refreshToken) return { id: identity.id, refreshToken: stored.refreshToken };\n if (identity.id === LEGACY_GMAIL_ID) {\n const legacy = (process.env[\"GMAIL_REFRESH_TOKEN\"] ?? \"\").trim();\n if (legacy) return { id: identity.id, refreshToken: legacy };\n }\n return null;\n}\n","import { loadConfig } from \"./config.ts\";\nimport { logEvent } from \"./events.ts\";\nimport { LEGACY_GMAIL_ID, LEGACY_ONESHOT_ID, resolveIdentities } from \"./identities.ts\";\nimport { getLedger } from \"./ledger.ts\";\nimport type { EmailIdentity } from \"./types.ts\";\n\n/**\n * Thrown by sendEmail (pre-flight, before any network or LLM spend) when\n * every identity in the pool has exhausted its daily cap. Callers treat it\n * as \"try again tomorrow\": cadence steps stay due, queue rows stay approved.\n */\nexport class SendDeferredError extends Error {\n constructor(message: string) {\n super(message);\n // Explicit name so isSendDeferred works across module instances /\n // serialization boundaries where instanceof would lie.\n this.name = \"SendDeferredError\";\n }\n}\n\nexport function isSendDeferred(err: unknown): boolean {\n return err instanceof Error && err.name === \"SendDeferredError\";\n}\n\n/**\n * True when an error is a TRANSIENT platform/transport failure (the OneShot\n * backend or the network briefly broke) rather than a genuine negative result\n * (email not found, undeliverable, no enrichment data). Callers must NOT treat\n * a transient failure as a durable verdict about the candidate: don't drop it,\n * don't negative-cache it, defer/retry instead. Matches the failure shapes seen\n * in the 2026-06 worker outage. Message-based so it works across the SDK's\n * thrown errors, the `withDeadline` rejection, and serialized boundaries.\n *\n * Genuine negatives (\"not found\", \"undeliverable\", \"no profile data\") return\n * false — those ARE durable verdicts and should drop/negative-cache as before.\n */\nexport function isTransientToolError(err: unknown): boolean {\n const msg = (err instanceof Error ? err.message : String(err ?? \"\")).toLowerCase();\n if (!msg) return false;\n return (\n msg.includes(\"tool execution failed\") || // OneShot worker crash (generic)\n msg.includes(\"timed out\") || // job/operation timeout\n msg.includes(\"timeout\") ||\n msg.includes(\"deadline exceeded\") || // withDeadline rejection\n msg.includes(\"operation timed out\") ||\n msg.includes(\"fetch failed\") || // undici/network\n msg.includes(\"could not fetch\") ||\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"etimedout\") ||\n msg.includes(\"socket hang up\") ||\n // Bare \"network\" over-matches genuine negatives (e.g. \"professional\n // network\") — the econn*/fetch-failed/socket checks already cover real\n // network faults; match only explicit network errors.\n /network (error|unreachable|timeout)/.test(msg) ||\n msg.includes(\"rate limit\") || // rate-limited → back off + retry, not a verdict\n /\\b(50[0-9]|429)\\b/.test(msg) // 5xx / rate-limit HTTP statuses\n );\n}\n\n/** \"YYYY-MM-DD HH:MM:SS\" UTC — the format SQLite's datetime('now') writes into receipts.created_at. */\nfunction toSqliteUtc(d: Date): string {\n return d.toISOString().slice(0, 19).replace(\"T\", \" \");\n}\n\n/**\n * Start of the founder's current LOCAL calendar day, rendered in the SQLite\n * UTC format the receipts column actually stores. Caps are \"per day\" in the\n * founder's mental model, so the boundary is local midnight, not UTC.\n */\nexport function todayStartSqliteUtc(now = new Date()): string {\n const localMidnight = new Date(now);\n localMidnight.setHours(0, 0, 0, 0);\n return toSqliteUtc(localMidnight);\n}\n\nconst MS_PER_WEEK = 7 * 24 * 3600 * 1000;\nconst DEFAULT_WARMUP_MAX = 50;\n\n/**\n * Today's send ceiling for an identity. Uncapped (Infinity) only when both\n * maxPerDay and warmup are null. With a warmup ramp, capacity grows from\n * startPerDay by incrementPerWeek for each full week since the identity's\n * first recorded send, clamped to maxPerDay.\n */\nexport function warmupCap(\n identity: EmailIdentity,\n firstSendAtSqliteUtc: string | null,\n now = new Date(),\n): number {\n if (identity.maxPerDay == null && identity.warmup == null) return Infinity;\n const max = identity.maxPerDay ?? DEFAULT_WARMUP_MAX;\n if (!identity.warmup) return max;\n if (!firstSendAtSqliteUtc) return Math.min(identity.warmup.startPerDay, max);\n const firstMs = new Date(`${firstSendAtSqliteUtc.replace(\" \", \"T\")}Z`).getTime();\n const weeks = Number.isFinite(firstMs)\n ? Math.max(0, Math.floor((now.getTime() - firstMs) / MS_PER_WEEK))\n : 0;\n return Math.min(identity.warmup.startPerDay + weeks * identity.warmup.incrementPerWeek, max);\n}\n\n/**\n * The unit that shares one daily ceiling + warm-up ramp. OneShot reputation and\n * the daily send limit are PER-DOMAIN (every mailbox on a domain pools the same\n * reputation), so all oneshot identities with the same sendingDomain share a\n * budget. Gmail accounts are independent — Google warms per-account — so each\n * Gmail identity is its own group keyed by id (this also keeps two Gmail\n * accounts on one Workspace domain from sharing a cap, matching prior behavior).\n */\nexport function capGroupKey(identity: EmailIdentity): string {\n if (identity.provider === \"oneshot\") {\n return `domain:${(identity.sendingDomain ?? \"__sdk_default__\").trim().toLowerCase()}`;\n }\n return `id:${identity.id}`;\n}\n\ninterface GroupCapacity {\n cap: number;\n sent: number;\n remaining: number;\n}\n\ninterface PoolCapacity {\n byGroup: Map<string, GroupCapacity>;\n /** identity.id → its cap-group key. */\n groupOf: Map<string, string>;\n /** identity.id → its OWN sends today (0 for uncapped groups unless countUncapped). */\n identitySent: Map<string, number>;\n}\n\n/**\n * Aggregate today's capacity for every cap-group in the pool:\n * - ceiling = MAX member warm-up cap (the domain ramps as one; any uncapped\n * member ⟹ uncapped group / overflow absorber),\n * - warm-up anchor = EARLIEST member first-send,\n * - used = SUM of member sends today.\n * A group with an uncapped member short-circuits to Infinity with NO ledger\n * read on the routing path, so legacy single-identity installs still pay\n * nothing to learn \"∞\". Display callers pass `countUncapped` to get the real\n * per-identity counts even for uncapped groups.\n */\nfunction computeCapacities(\n identities: EmailIdentity[],\n now = new Date(),\n opts: { countUncapped?: boolean } = {},\n): PoolCapacity {\n const members = new Map<string, EmailIdentity[]>();\n const groupOf = new Map<string, string>();\n for (const identity of identities) {\n const key = capGroupKey(identity);\n groupOf.set(identity.id, key);\n let arr = members.get(key);\n if (!arr) {\n arr = [];\n members.set(key, arr);\n }\n arr.push(identity);\n }\n\n const byGroup = new Map<string, GroupCapacity>();\n const identitySent = new Map<string, number>();\n const todayStart = todayStartSqliteUtc(now);\n for (const [key, group] of members) {\n const uncapped = group.some((i) => i.maxPerDay == null && i.warmup == null);\n if (uncapped && !opts.countUncapped) {\n byGroup.set(key, { cap: Infinity, sent: 0, remaining: Infinity });\n for (const i of group) identitySent.set(i.id, 0);\n continue;\n }\n const ledger = getLedger();\n let firstSendAt: string | null = null;\n let sent = 0;\n for (const i of group) {\n // SQLite \"YYYY-MM-DD HH:MM:SS\" UTC strings sort lexicographically.\n const first = ledger.firstEmailSendAt(i.id);\n if (first && (firstSendAt == null || first < firstSendAt)) firstSendAt = first;\n const own = ledger.countEmailSendsSince(i.id, todayStart);\n identitySent.set(i.id, own);\n sent += own;\n }\n const cap = uncapped ? Infinity : Math.max(...group.map((i) => warmupCap(i, firstSendAt, now)));\n byGroup.set(key, {\n cap,\n sent,\n remaining: cap === Infinity ? Infinity : Math.max(0, cap - sent),\n });\n }\n return { byGroup, groupOf, identitySent };\n}\n\n/** This identity's view of its group's capacity: shared remaining + its own sends (for tie-breaking). */\nfunction capacityFor(\n pool: PoolCapacity,\n identity: EmailIdentity,\n): { remaining: number; sent: number } {\n const key = pool.groupOf.get(identity.id) ?? capGroupKey(identity);\n return {\n remaining: pool.byGroup.get(key)?.remaining ?? 0,\n sent: pool.identitySent.get(identity.id) ?? 0,\n };\n}\n\nexport function remainingToday(identity: EmailIdentity, now = new Date()): number {\n const identities = resolveIdentities(loadConfig());\n const pool = computeCapacities(identities, now);\n if (pool.groupOf.has(identity.id)) return capacityFor(pool, identity).remaining;\n // Identity not in the active pool — evaluate it as its own group.\n return capacityFor(computeCapacities([identity], now), identity).remaining;\n}\n\n/** True when at least one cap-group can still send today — lets the cadence engine skip LLM drafting on fully capped days. */\nexport function hasAnySendCapacity(now = new Date()): boolean {\n const pool = computeCapacities(resolveIdentities(loadConfig()), now);\n for (const g of pool.byGroup.values()) if (g.remaining > 0) return true;\n return false;\n}\n\n/** Per-identity capacity for display (setup / doctor / CLI): the shared domain ceiling + both the domain total and this mailbox's own sends today. */\nexport interface IdentityCapacityView {\n /** Domain (group) ceiling after the ramp; Infinity = uncapped. */\n capToday: number;\n /** Sends across the whole cap-group today (the shared budget used). */\n domainSentToday: number;\n /** This identity's own sends today. */\n identitySentToday: number;\n /** Group remaining today. */\n remaining: number;\n}\n\nexport function identityCapacities(now = new Date()): Map<string, IdentityCapacityView> {\n const identities = resolveIdentities(loadConfig());\n const pool = computeCapacities(identities, now, { countUncapped: true });\n const out = new Map<string, IdentityCapacityView>();\n for (const identity of identities) {\n const key = pool.groupOf.get(identity.id)!;\n const g = pool.byGroup.get(key)!;\n out.set(identity.id, {\n capToday: g.cap,\n domainSentToday: g.sent,\n identitySentToday: pool.identitySent.get(identity.id) ?? 0,\n remaining: g.remaining,\n });\n }\n return out;\n}\n\n/**\n * Which identity sends to this address. Resolution order:\n * 1. Existing sender_assignments pin → that identity (config error if the\n * id was removed from the pool — never silently re-route a live thread).\n * 2. No pin but the address was emailed pre-rotation → lazy-pin to the\n * legacy identity (keeps in-flight cadences on their original From).\n * 3. Fresh prospect → CAPPED groups first: most remaining capacity today (the\n * budget is per cap-group, so all mailboxes on one OneShot domain share it),\n * tie → fewer sends by that mailbox (spreads traffic across mailboxes in a\n * domain), then pool order. Uncapped groups are the overflow absorber, used\n * only when every capped one is full — otherwise an uncapped OneShot domain\n * would always win on remaining capacity (∞) and the warming Gmail accounts\n * would never receive traffic. Pinned immediately so retries and follow-ups\n * are deterministic.\n * 4. Nothing has capacity → SendDeferredError (callers leave work queued).\n */\nexport function resolveSenderIdentity(to: string, now = new Date()): EmailIdentity {\n const cfg = loadConfig();\n const identities = resolveIdentities(cfg);\n const ledger = getLedger();\n const byId = new Map(identities.map((i) => [i.id, i]));\n\n const assigned = ledger.getSenderAssignment(to);\n if (assigned) {\n const identity = byId.get(assigned);\n if (!identity) {\n throw new Error(\n `prospect ${to} is pinned to sender identity '${assigned}' which is no longer configured — restore it in emailIdentities or reassign explicitly`,\n );\n }\n return identity;\n }\n\n if (ledger.hasPriorEmailSend(to)) {\n const legacyId = cfg.emailProvider === \"gmail\" ? LEGACY_GMAIL_ID : LEGACY_ONESHOT_ID;\n const legacy =\n byId.get(legacyId) ??\n identities.find((i) => i.provider === (cfg.emailProvider === \"gmail\" ? \"gmail\" : \"oneshot\"));\n if (legacy) {\n const winner = ledger.assignSender(to, legacy.id);\n return byId.get(winner) ?? legacy;\n }\n // No identity of the legacy provider left in the pool — fall through to\n // the capacity picker rather than stranding the prospect forever. This\n // DOES switch the thread's From address (the founder removed the\n // original sender), so surface it loudly.\n logEvent(\"send.legacy_identity_missing\", { email_domain: to.split(\"@\")[1] ?? \"\" }, \"warn\");\n }\n\n const pool = computeCapacities(identities, now);\n let best: { identity: EmailIdentity; remaining: number; sent: number } | null = null;\n let overflow: EmailIdentity | null = null;\n for (const identity of identities) {\n const { remaining, sent } = capacityFor(pool, identity);\n if (remaining <= 0) continue;\n if (remaining === Infinity) {\n overflow ??= identity;\n continue;\n }\n if (!best || remaining > best.remaining || (remaining === best.remaining && sent < best.sent)) {\n best = { identity, remaining, sent };\n }\n }\n const picked = best?.identity ?? overflow;\n if (!picked) {\n throw new SendDeferredError(\n \"all sender identities have reached their daily cap — send deferred until tomorrow\",\n );\n }\n const winner = ledger.assignSender(to, picked.id);\n return byId.get(winner) ?? picked;\n}\n","import {\n OneShot,\n type BrowserResult,\n type DeepResearchPersonResult,\n type DomainPoolEntry,\n type EmailResult,\n type EnrichProfileResult,\n type FindEmailResult,\n type InboxEmail,\n type InboxListResult,\n type ResearchResult,\n type SmsSendResult,\n type VerifyEmailResult,\n type VoiceCallResult,\n type WebReadResult,\n type WebSearchResult,\n} from \"@oneshot-agent/sdk\";\nimport { createHash } from \"node:crypto\";\nimport { getLedger } from \"./ledger.ts\";\nimport { loadConfig, oneshotEnvReady } from \"./config.ts\";\nimport { logEvent } from \"./events.ts\";\nimport { getGmailProfile, listGmailReplies, sendGmailMessage } from \"./gmail.ts\";\nimport { gmailAccountFor, resolveIdentities } from \"./identities.ts\";\nimport { parallelMap, withDeadline } from \"./parallel.ts\";\nimport { isTransientToolError, resolveSenderIdentity } from \"./send-routing.ts\";\nimport type { EmailIdentity } from \"./types.ts\";\n\n/** Re-exported so callers don't reach into the SDK for the domain-pool shape. */\nexport type { DomainPoolEntry } from \"@oneshot-agent/sdk\";\n\nexport interface SendEmailInput {\n to: string;\n subject: string;\n body: string;\n /** OneShot provider only — ignored when config.emailProvider is \"gmail\" (Gmail always sends from the authenticated account). */\n fromDomain?: string;\n}\n\nexport interface ResearchInput {\n topic: string;\n depth?: \"quick\" | \"deep\";\n}\n\nexport interface EnrichInput {\n email?: string;\n linkedinUrl?: string;\n name?: string;\n companyDomain?: string;\n}\n\nexport interface CallContext {\n playName: string;\n /**\n * Short human-readable reason for this tool call. Lands on the signed\n * receipt's `memo` field via SDK 0.16.2+. SDK truncates at 1000 chars and\n * warns (not errors) when omitted on a paid call. Defaults to\n * `\"{playName} {callType}\"` when unset.\n */\n memo?: string;\n /**\n * Machine-readable decision rationale. Merged with `{playName, callType}`\n * defaults; caller-supplied keys win. Lands on the receipt's\n * `decisionContext` for supervisor-agent / external auditor consumption.\n */\n decisionContext?: Record<string, unknown>;\n}\n\n/**\n * Build the `{memo, decisionContext}` audit blob the SDK 0.16.2+ accepts as\n * top-level fields on every paid tool's option bag. Sensible defaults (playName\n * + callType) so even call sites that don't enrich still emit a usable audit\n * trail; callers that DO enrich override / extend via `ctx.decisionContext`.\n */\nexport function buildAuditOpts(\n ctx: CallContext,\n callType: string,\n): { memo: string; decisionContext: Record<string, unknown> } {\n return {\n memo: ctx.memo ?? `${ctx.playName} ${callType}`,\n decisionContext: { playName: ctx.playName, callType, ...ctx.decisionContext },\n };\n}\n\n/**\n * Record a receipt for a billable call, persisting the SAME memo/decisionContext\n * we send to OneShot (buildAuditOpts) so the local row matches the platform\n * receipt. Every wrapper below funnels through this instead of calling\n * `getLedger().recordReceipt` directly.\n */\nfunction recordCallReceipt(args: {\n ctx: CallContext;\n callType: string;\n signedReceipt?: unknown;\n costUsd?: number;\n oneshotRequestId?: string;\n senderIdentity?: string;\n}): number {\n const audit = buildAuditOpts(args.ctx, args.callType);\n return getLedger().recordReceipt({\n playName: args.ctx.playName,\n callType: args.callType,\n signedReceipt: args.signedReceipt,\n costUsd: args.costUsd,\n oneshotRequestId: args.oneshotRequestId,\n senderIdentity: args.senderIdentity,\n memo: audit.memo,\n decisionContext: audit.decisionContext,\n });\n}\n\n/**\n * Stable correlation key for a (prospect, play) cadence. Set as\n * `decisionContext.goalId` on every send so OneShot groups the whole sequence's\n * spend, and tagged once on outcome via `tagReceiptValue({ goalId })`. Hashed so\n * no raw email leaks into the id; deterministic so the same cadence always maps\n * to the same goal.\n */\nexport function cadenceGoalId(playName: string, email: string): string {\n const canon = email.trim().toLowerCase();\n return `goal_${createHash(\"sha256\").update(`${playName}:${canon}`).digest(\"hex\").slice(0, 24)}`;\n}\n\nlet agentSingleton: OneShot | null = null;\n\nasync function initAgent(): Promise<OneShot> {\n if (!oneshotEnvReady()) {\n throw new Error(\n \"Agent wallet credentials missing. Set CDP_API_KEY_ID + CDP_API_KEY_SECRET + CDP_WALLET_SECRET, or AGENT_PRIVATE_KEY. Run `oneshot-gtm doctor` for details.\",\n );\n }\n if (process.env[\"AGENT_PRIVATE_KEY\"]) {\n return new OneShot({ privateKey: process.env[\"AGENT_PRIVATE_KEY\"] });\n }\n return await OneShot.create({ cdp: true });\n}\n\nasync function getAgent(): Promise<OneShot> {\n if (!agentSingleton) agentSingleton = await initAgent();\n return agentSingleton;\n}\n\n/**\n * The wallet's provisioned sending-domain pool (SDK 0.19+ `listDomains`), used\n * to validate a `sendingDomain` is wallet-owned BEFORE a live send 403s with\n * `domain_not_owned`, and to populate the domain picker in setup.\n *\n * Transient-tolerant by design: a brief OneShot/transport outage returns `[]`\n * (\"couldn't enumerate\") so it never blocks the founder from saving an identity\n * — callers must treat an empty list as \"unknown\", not \"no domains owned\".\n * Genuine auth failures (bad/absent wallet creds) DO propagate, since those are\n * a real config error the founder needs to see.\n */\nexport async function listSendingDomains(): Promise<DomainPoolEntry[]> {\n try {\n const agent = await getAgent();\n const result = await agent.listDomains();\n return result.domains ?? [];\n } catch (err) {\n if (isTransientToolError(err)) {\n logEvent(\n \"domains.list_transient_failure\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Derive the From localpart from the founder's name (first token, lowercased,\n * non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back\n * to `agent` when the name yields nothing usable. (\"Jane Doe\" → \"jane\".)\n */\nexport function fromLocalpart(name: string | null): string {\n const first = (name ?? \"\").trim().split(/\\s+/)[0] ?? \"\";\n const clean = first.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return clean.length > 0 ? clean : \"agent\";\n}\n\n/**\n * Stable Idempotency-Key for a OneShot email send (SDK 0.19+, honored by\n * email.send with a 24h replay window). Derived from the send's content so a\n * retry of the SAME logical email — a double-click, or a client retry after\n * the platform hung but actually sent — returns the original job instead of\n * charging + sending twice. A genuinely different body/subject hashes\n * differently, so it gets its own key (the server 422s same-key-different-body).\n */\nfunction emailIdempotencyKey(parts: Array<string>): string {\n // NUL separator: it can't appear in an email address, identity id, subject,\n // or body, so distinct field splits can't realign to the same joined string\n // (e.g. [\"a\",\"b c\"] vs [\"a b\",\"c\"] both → \"a b c\" under a space separator).\n return createHash(\"sha256\")\n .update(parts.join(String.fromCharCode(0)))\n .digest(\"hex\")\n .slice(0, 40);\n}\n\n/**\n * OneShot renders the email `body` as HTML, so plain-text newlines collapse\n * into one run-on paragraph. Escape HTML metacharacters and turn newlines into\n * <br> so paragraphs + the signature lines render the way the draft intended.\n */\nexport function toHtmlBody(text: string): string {\n return text\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\\r\\n/g, \"\\n\")\n .replace(/\\n/g, \"<br>\\n\");\n}\n\n/**\n * Gmail-path send. Same return contract as the OneShot path: callers consume\n * `receiptId` plus `result.cost` / `result.request_id`. Receipts are recorded\n * with cost 0 (Gmail sends are free) and the Gmail message id as request id,\n * so /receipts and spend rollups stay truthful.\n */\nasync function sendEmailViaGmail(input: SendEmailInput, ctx: CallContext, identity: EmailIdentity) {\n const cfg = loadConfig();\n const account = gmailAccountFor(identity);\n // Hard stop, never fall through to the legacy env token: that token may\n // belong to a DIFFERENT account, and sending through it would switch the\n // thread's From address mid-conversation.\n if (!account) {\n throw new Error(\n `no Gmail refresh token stored for sender identity '${identity.id}' — re-authorize it (bun run cli -- gmail auth)`,\n );\n }\n const { emailAddress } = await getGmailProfile(account);\n const sent = await sendGmailMessage(\n {\n to: input.to,\n fromEmail: emailAddress,\n fromName: cfg.founderName,\n subject: input.subject,\n htmlBody: toHtmlBody(input.body),\n },\n account,\n );\n const result: EmailResult = {\n status: \"sent\",\n request_id: sent.id,\n cost: 0,\n email: { id: sent.id, provider_message_id: sent.id, status: \"sent\" },\n };\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.send\",\n signedReceipt: {\n provider: \"gmail\",\n message_id: sent.id,\n thread_id: sent.threadId,\n from: emailAddress,\n to: input.to,\n subject: input.subject,\n memo: ctx.memo ?? `${ctx.playName} email.send`,\n },\n costUsd: 0,\n oneshotRequestId: sent.id,\n senderIdentity: identity.id,\n });\n return { result, receiptId };\n}\n\nexport async function sendEmail(input: SendEmailInput, ctx: CallContext) {\n // Sender rotation: resolve the sticky per-prospect identity BEFORE any\n // network call. Throws SendDeferredError when every identity is at its\n // daily cap — callers leave the work queued for tomorrow.\n const identity = resolveSenderIdentity(input.to);\n if (identity.provider === \"gmail\") {\n return sendEmailViaGmail(input, ctx, identity);\n }\n const agent = await getAgent();\n const cfg = loadConfig();\n // Pinning from_domain (+ from_mailbox below) opts this send OUT of the\n // platform's domain rotation: the named domain auto-provisions if unknown and\n // sends as-is (the worker only requires status='verified'; there's no\n // domain_not_owned 403). The trade-off is that pinned sends BYPASS the\n // server's warm-up gating — the per-identity client cap is the only throttle.\n // An unset domain falls back to the SDK's shared demo domain.\n const fromDomain = input.fromDomain ?? identity.sendingDomain ?? cfg.sendingDomain ?? null;\n\n const opts: Parameters<OneShot[\"email\"]>[0] = {\n to: input.to,\n subject: input.subject,\n body: toHtmlBody(input.body),\n // Dedupes a retry after the platform hangs-but-sends (the 2026-06 incident)\n // or a double-fire from the queue/cadence layer. Keyed on content so two\n // distinct emails to the same prospect don't collide.\n idempotencyKey: emailIdempotencyKey([identity.id, input.to, input.subject, input.body]),\n ...buildAuditOpts(ctx, \"email.send\"),\n };\n if (fromDomain) {\n // Send from <mailbox-or-first-name>@<domain> with the founder's name as the\n // display name. from_mailbox (localpart) + from_name (display name) are native fields in\n // SDK ≥0.16.2 — from_name ships as a separate field, so the bare\n // from_address still passes the server's strict email validation.\n opts.from_domain = fromDomain;\n opts.from_mailbox = identity.mailbox?.trim() || fromLocalpart(cfg.founderName);\n const name = (cfg.founderName ?? \"\").trim();\n if (name) opts.from_name = name;\n }\n const result = await agent.email(opts);\n\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.send\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n senderIdentity: identity.id,\n });\n return { result, receiptId };\n}\n\nexport interface ReplyEmailInput {\n /** Sender identity that RECEIVED the inbound email; the reply goes out from it. */\n identityId: string;\n to: string;\n /** Inbound subject — normalized to \"Re: …\" here (idempotent). */\n subject: string;\n body: string;\n /** Gmail only: thread to attach the reply to (sender-side threading). */\n threadId?: string;\n /** Gmail only: RFC 2822 Message-ID of the inbound email (In-Reply-To/References). */\n inReplyTo?: string;\n /**\n * OneShot only: id of the inbound OneShot inbox email (from inboxList). The\n * platform resolves In-Reply-To/References/thread_id and can derive\n * to/subject from it (SDK 0.19+).\n */\n replyToEmailId?: string;\n}\n\n/** \"Re: \" prefix, idempotent and case-insensitive (\"RE: x\" passes through). */\nexport function replySubject(subject: string): string {\n const s = subject.trim();\n return /^re:/i.test(s) ? s : `Re: ${s}`;\n}\n\n/**\n * Reply to an inbound email from the identity whose mailbox received it.\n * Deliberately NOT routed through sender rotation (resolveSenderIdentity): a\n * reply must keep the thread's From address, and replies to engaged humans\n * shouldn't be deferred by warmup caps. Receipts use callType \"email.reply\",\n * which also keeps them out of per-identity cap counting (email.send only).\n * Both transports thread for real: Gmail via threadId + In-Reply-To/References\n * on the raw message; OneShot via `reply_to_email_id` (SDK 0.19+ — the\n * platform resolves the threading headers + thread_id server-side). The\n * OneShot send also carries an idempotency key so a retry can't double-send.\n */\nexport async function replyEmail(input: ReplyEmailInput, ctx: CallContext) {\n const cfg = loadConfig();\n const identity = resolveIdentities(cfg).find((i) => i.id === input.identityId);\n if (!identity) {\n throw new Error(\n `unknown sender identity '${input.identityId}' — it may have been removed from the pool`,\n );\n }\n const subject = replySubject(input.subject);\n\n if (identity.provider === \"gmail\") {\n const account = gmailAccountFor(identity);\n if (!account) {\n throw new Error(\n `no Gmail refresh token stored for sender identity '${identity.id}' — re-authorize it (bun run cli -- gmail auth)`,\n );\n }\n const { emailAddress } = await getGmailProfile(account);\n const sent = await sendGmailMessage(\n {\n to: input.to,\n fromEmail: emailAddress,\n fromName: cfg.founderName,\n subject,\n htmlBody: toHtmlBody(input.body),\n ...(input.inReplyTo ? { inReplyTo: input.inReplyTo, references: [input.inReplyTo] } : {}),\n },\n account,\n input.threadId,\n );\n const result: EmailResult = {\n status: \"sent\",\n request_id: sent.id,\n cost: 0,\n email: { id: sent.id, provider_message_id: sent.id, status: \"sent\" },\n };\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.reply\",\n signedReceipt: {\n provider: \"gmail\",\n message_id: sent.id,\n thread_id: sent.threadId,\n from: emailAddress,\n to: input.to,\n subject,\n memo: ctx.memo ?? `${ctx.playName} email.reply`,\n },\n costUsd: 0,\n oneshotRequestId: sent.id,\n senderIdentity: identity.id,\n });\n return { result, receiptId };\n }\n\n const agent = await getAgent();\n const fromDomain = identity.sendingDomain ?? cfg.sendingDomain ?? null;\n const opts: Parameters<OneShot[\"email\"]>[0] = {\n to: input.to,\n subject,\n body: toHtmlBody(input.body),\n idempotencyKey: emailIdempotencyKey([\n identity.id,\n input.to,\n input.body,\n input.replyToEmailId ?? \"\",\n ]),\n ...buildAuditOpts(ctx, \"email.reply\"),\n };\n // Thread server-side when we know the inbound email id. We still pass\n // to/subject (the SDK forwards them); a missing id degrades to a fresh\n // \"Re:\" send, the pre-0.19 behavior.\n if (input.replyToEmailId) opts.reply_to_email_id = input.replyToEmailId;\n if (fromDomain) {\n opts.from_domain = fromDomain;\n opts.from_mailbox = identity.mailbox?.trim() || fromLocalpart(cfg.founderName);\n const name = (cfg.founderName ?? \"\").trim();\n if (name) opts.from_name = name;\n }\n const result = await agent.email(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.reply\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n senderIdentity: identity.id,\n });\n return { result, receiptId };\n}\n\nexport async function deepResearch(input: ResearchInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: ResearchResult = await agent.research({\n topic: input.topic,\n depth: input.depth ?? \"quick\",\n ...buildAuditOpts(ctx, \"research.deep\"),\n });\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"research.deep\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport async function enrichProfile(input: EnrichInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"enrichProfile\"]>[0] = {\n ...buildAuditOpts(ctx, \"enrich.profile\"),\n };\n if (input.email) opts.email = input.email;\n if (input.linkedinUrl) opts.linkedin_url = input.linkedinUrl;\n if (input.name) opts.name = input.name;\n if (input.companyDomain) opts.company_domain = input.companyDomain;\n\n const result: EnrichProfileResult = await agent.enrichProfile(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"enrich.profile\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface DeepResearchPersonInput {\n /** A known email address — feeds dossier lookup. */\n email?: string;\n /** Any social URL (LinkedIn, Twitter, GitHub) the engine can chase. */\n socialMediaUrl?: string;\n /** Best-guess full name. */\n name?: string;\n /** Best-guess company name (free text — can be a domain or a brand). */\n company?: string;\n}\n\n/**\n * Multi-source person dossier: emails (work + personal + alts), phones,\n * org history, social profiles. Higher cost (~$0.05) and 2–5 min async vs.\n * findEmail's seconds-and-half-a-cent — use when you don't have a\n * `companyDomain` to feed findEmail (e.g. GitHub repo owners with no\n * resolvable company), not as a default first-pass.\n */\nexport async function deepResearchPerson(input: DeepResearchPersonInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"deepResearchPerson\"]>[0] = {\n ...buildAuditOpts(ctx, \"research.person\"),\n };\n if (input.email) opts.email = input.email;\n if (input.socialMediaUrl) opts.social_media_url = input.socialMediaUrl;\n if (input.name) opts.name = input.name;\n if (input.company) opts.company = input.company;\n\n const result: DeepResearchPersonResult = await agent.deepResearchPerson(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"research.person\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface FindEmailInput {\n /** Pass either fullName, OR firstName + lastName. companyDomain is required. */\n fullName?: string;\n firstName?: string;\n lastName?: string;\n companyDomain: string;\n}\n\nexport async function findEmail(input: FindEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"findEmail\"]>[0] = {\n company_domain: input.companyDomain,\n ...buildAuditOpts(ctx, \"email.find\"),\n };\n if (input.fullName) opts.full_name = input.fullName;\n if (input.firstName) opts.first_name = input.firstName;\n if (input.lastName) opts.last_name = input.lastName;\n const result: FindEmailResult = await agent.findEmail(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.find\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface VerifyEmailInput {\n email: string;\n}\n\nexport async function verifyEmail(input: VerifyEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: VerifyEmailResult = await agent.verifyEmail({\n email: input.email,\n ...buildAuditOpts(ctx, \"email.verify\"),\n });\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"email.verify\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport async function getBalance(\n tokenAddress?: string,\n): Promise<{ balance: string; raw: unknown }> {\n const agent = await getAgent();\n const raw = await agent.getBalance(tokenAddress);\n return { balance: raw, raw };\n}\n\n/**\n * Hard deadline for one inbox source. Without it a hung upstream (the OneShot\n * inbox endpoint has been observed stalling to Bun's ~300s default fetch\n * timeout) blocks the /inbox route and stop-on-reply for minutes. The\n * underlying request keeps running after the race loses — fine, we only need\n * the caller unblocked; the next poll gets a fresh attempt.\n */\nconst INBOX_SOURCE_TIMEOUT_MS = 15_000;\n\nasync function listOneShotInbox(opts?: {\n since?: string;\n limit?: number;\n}): Promise<InboxListResult> {\n const agent = await getAgent();\n const out: { since?: string; limit?: number; include_body?: boolean } = { include_body: true };\n if (opts?.since) out.since = opts.since;\n if (opts?.limit) out.limit = opts.limit;\n return agent.inboxList(out);\n}\n\n/**\n * InboxEmail plus local-only annotations: `message_id` (RFC 2822, Gmail\n * sources only — needed for In-Reply-To on a threaded reply) and\n * `source_identity_id` (which sender identity's mailbox received it — a reply\n * must go out from that same identity). Extends the SDK type, so existing\n * consumers (stop-on-reply reads `from` only) are unaffected.\n */\nexport type AnnotatedInboxEmail = InboxEmail & {\n message_id?: string;\n source_identity_id?: string;\n};\n\nexport interface AnnotatedInboxListResult extends InboxListResult {\n emails: AnnotatedInboxEmail[];\n}\n\nfunction annotateInboxResult(r: InboxListResult, identityId: string): AnnotatedInboxListResult {\n return { ...r, emails: r.emails.map((e) => ({ ...e, source_identity_id: identityId })) };\n}\n\n/**\n * Replies across the WHOLE sender pool: the OneShot inbox (once, if any\n * oneshot identity exists) merged with every authorized Gmail account.\n * Stop-on-reply must see a reply no matter which identity sent the thread.\n * With multiple sources each is fetched under its own try/catch — one\n * revoked Gmail token must not blind reply detection for everything else.\n * A single source keeps legacy throw semantics (the /inbox route maps a\n * throw to its \"couldn't reach the inbox\" state).\n */\nexport async function listInbox(opts?: {\n since?: string;\n limit?: number;\n}): Promise<AnnotatedInboxListResult> {\n const identities = resolveIdentities(loadConfig());\n const sources: Array<{\n label: string;\n identityId: string;\n fetch: () => Promise<InboxListResult>;\n }> = [];\n const oneshotIdentity = identities.find((i) => i.provider === \"oneshot\");\n if (oneshotIdentity) {\n sources.push({\n label: \"oneshot\",\n identityId: oneshotIdentity.id,\n fetch: () => listOneShotInbox(opts),\n });\n }\n for (const identity of identities.filter((i) => i.provider === \"gmail\")) {\n sources.push({\n label: identity.id,\n identityId: identity.id,\n fetch: () => {\n const account = gmailAccountFor(identity);\n if (!account) {\n // Reject (not fall back to the env token — possibly a different\n // account's inbox). Multi-source: logged + skipped; single-source:\n // propagates like any other inbox failure.\n return Promise.reject(\n new Error(\n `no Gmail refresh token stored for sender identity '${identity.id}' — re-authorize it (bun run cli -- gmail auth)`,\n ),\n );\n }\n return listGmailReplies(opts, account);\n },\n });\n }\n\n if (sources.length === 1) {\n const only = sources[0]!;\n return annotateInboxResult(\n await withDeadline(only.fetch(), INBOX_SOURCE_TIMEOUT_MS, `inbox source '${only.label}'`),\n only.identityId,\n );\n }\n\n const results = await parallelMap(sources, 3, async (source) => {\n try {\n return annotateInboxResult(\n await withDeadline(\n source.fetch(),\n INBOX_SOURCE_TIMEOUT_MS,\n `inbox source '${source.label}'`,\n ),\n source.identityId,\n );\n } catch (err) {\n logEvent(\n \"inbox.source_failed\",\n { source: source.label, message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return null;\n }\n });\n const ok = results.filter((r): r is AnnotatedInboxListResult => r != null);\n if (ok.length === 0) {\n throw new Error(\"all inbox sources failed — check doctor for identity auth status\");\n }\n const seen = new Set<string>();\n const emails = ok\n .flatMap((r) => r.emails)\n .filter((e) => (seen.has(e.id) ? false : (seen.add(e.id), true)))\n .toSorted((a, b) =>\n a.received_at < b.received_at ? 1 : a.received_at > b.received_at ? -1 : 0,\n )\n .slice(0, opts?.limit ?? 50);\n return {\n emails,\n count: emails.length,\n has_more: ok.some((r) => r.has_more),\n agent_id: ok.map((r) => r.agent_id).join(\"+\"),\n };\n}\n\nexport interface BuildSiteInput {\n name: string;\n description: string;\n type?:\n | \"saas\"\n | \"portfolio\"\n | \"agency\"\n | \"personal\"\n | \"product\"\n | \"funnel\"\n | \"restaurant\"\n | \"event\";\n sections?: string[];\n leadCaptureEmail?: string;\n primaryColor?: string;\n tone?: \"professional\" | \"playful\" | \"bold\" | \"minimal\";\n domain?: string;\n}\n\nexport async function buildSite(input: BuildSiteInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"build\"]>[0] = {\n product: { name: input.name, description: input.description },\n ...buildAuditOpts(ctx, \"build.website\"),\n };\n if (input.type) opts.type = input.type;\n if (input.sections) opts.sections = input.sections;\n if (input.leadCaptureEmail) {\n opts.lead_capture = { enabled: true, inbox_email: input.leadCaptureEmail };\n }\n if (input.primaryColor || input.tone) {\n opts.brand = {};\n if (input.primaryColor) opts.brand.primary_color = input.primaryColor;\n if (input.tone) opts.brand.tone = input.tone;\n }\n if (input.domain) opts.domain = input.domain;\n\n const result = await agent.build(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"build.website\",\n signedReceipt: result,\n costUsd: result.cost,\n });\n return { result, receiptId };\n}\n\nexport interface SendSmsInput {\n to: string | string[];\n message: string;\n maxCost?: number;\n}\n\nexport async function sendSms(input: SendSmsInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"sms\"]>[0] = {\n to_number: input.to,\n message: input.message,\n ...buildAuditOpts(ctx, \"sms.send\"),\n };\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: SmsSendResult = await agent.sms(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"sms.send\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.details[0]?.message_sid ?? undefined,\n });\n return { result, receiptId };\n}\n\nexport interface VoiceCallInput {\n objective: string;\n to: string | string[];\n callerPersona?: string;\n context?: string;\n maxDurationMinutes?: number;\n maxCost?: number;\n}\n\nexport async function voiceCall(input: VoiceCallInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"voice\"]>[0] = {\n objective: input.objective,\n target_number: input.to,\n ...buildAuditOpts(ctx, \"voice.call\"),\n };\n if (input.callerPersona) opts.caller_persona = input.callerPersona;\n if (input.context) opts.context = input.context;\n if (input.maxDurationMinutes) opts.max_duration_minutes = input.maxDurationMinutes;\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: VoiceCallResult = await agent.voice(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"voice.call\",\n costUsd: result.cost,\n signedReceipt: result,\n });\n return { result, receiptId };\n}\n\nexport interface WebSearchInput {\n query: string;\n maxResults?: number;\n}\n\nexport async function webSearch(input: WebSearchInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"webSearch\"]>[0] = {\n query: input.query,\n ...buildAuditOpts(ctx, \"web.search\"),\n };\n if (input.maxResults) opts.max_results = input.maxResults;\n const result: WebSearchResult = await agent.webSearch(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"web.search\",\n signedReceipt: result,\n costUsd: result.cost,\n });\n return { result, receiptId };\n}\n\nexport interface WebReadInput {\n url: string;\n}\n\nexport async function webRead(input: WebReadInput, ctx: CallContext) {\n const agent = await getAgent();\n const result: WebReadResult = await agent.webRead({\n url: input.url,\n ...buildAuditOpts(ctx, \"web.read\"),\n });\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"web.read\",\n signedReceipt: result,\n costUsd: result.cost,\n oneshotRequestId: result.request_id,\n });\n return { result, receiptId };\n}\n\nexport interface BrowserTaskInput {\n task: string;\n startUrl?: string;\n allowedDomains?: string[];\n outputSchema?: Record<string, unknown>;\n profileId?: string;\n maxSteps?: number;\n maxCost?: number;\n}\n\nexport async function browserTask(input: BrowserTaskInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"browser\"]>[0] = {\n task: input.task,\n ...buildAuditOpts(ctx, \"browser.task\"),\n };\n if (input.startUrl) opts.start_url = input.startUrl;\n if (input.allowedDomains) opts.allowed_domains = input.allowedDomains;\n if (input.outputSchema) opts.output_schema = input.outputSchema;\n if (input.profileId) opts.profile_id = input.profileId;\n if (input.maxSteps) opts.max_steps = input.maxSteps;\n if (input.maxCost) opts.maxCost = input.maxCost;\n const result: BrowserResult = await agent.browser(opts);\n const receiptId = recordCallReceipt({\n ctx,\n callType: \"browser.task\",\n costUsd: result.cost,\n signedReceipt: result,\n oneshotRequestId: result.browser_task_id ?? undefined,\n });\n return { result, receiptId };\n}\n\nexport type {\n BrowserResult,\n DeepResearchPersonResult,\n InboxEmail,\n InboxListResult,\n SmsSendResult,\n VoiceCallResult,\n WebReadResult,\n WebSearchResult,\n};\n\nexport function receiptUrlForId(receiptId: number): string {\n return `local://receipt/${receiptId}`;\n}\n\n/** RoCS value tag — the shape OneShot's `tagReceiptValue` accepts. */\nexport type ValueTag = { type: string; amount?: number; label?: string };\n\n/**\n * Funnel rank of a value-tag type, so a later outcome never *downgrades* a\n * receipt's value (e.g. a reply poll firing AFTER a deal is recorded must not\n * overwrite `revenue` with `engagement`). Unknown types rank 0.\n */\nfunction valueTagRank(type: string): number {\n switch (type) {\n case \"revenue\":\n return 4;\n case \"qualified\":\n return 3;\n case \"meeting\":\n return 2;\n case \"engagement\":\n return 1;\n default:\n return 0;\n }\n}\n\n/**\n * Map a recorded deal outcome to a RoCS value tag, or null when there's no\n * positive value to attribute (deal_lost / ghosted are left untagged).\n */\nexport function outcomeToValueTag(\n outcome: \"meeting_booked\" | \"sql_qualified\" | \"deal_won\" | \"deal_lost\" | \"ghosted\",\n amountUsd?: number,\n): ValueTag | null {\n switch (outcome) {\n case \"meeting_booked\":\n return { type: \"meeting\", label: \"meeting booked\" };\n case \"sql_qualified\":\n return { type: \"qualified\", label: \"SQL qualified\" };\n case \"deal_won\":\n return Number.isFinite(amountUsd)\n ? { type: \"revenue\", amount: amountUsd, label: \"deal won\" }\n : { type: \"revenue\", label: \"deal won\" };\n case \"deal_lost\":\n case \"ghosted\":\n return null;\n }\n}\n\n/** One cadence's RoCS rollup (spend vs value), keyed by its goalId. */\nexport interface CadenceRocsGoal {\n goalId: string;\n spend: number;\n value: number;\n pendingValue: number;\n rocs: number;\n receiptCount: number;\n}\n\n/**\n * Per-cadence RoCS from OneShot (`rocsByGoal`): spend (receipts grouped by\n * `decisionContext.goalId`) vs value (outcomes tagged via `tagReceiptValue({goalId})`).\n * Transient-tolerant — a brief outage returns `[]` rather than blocking the\n * Measure page; genuine auth errors propagate so misconfig is visible.\n */\nexport async function cadenceRocs(opts: { periodDays?: number } = {}): Promise<CadenceRocsGoal[]> {\n try {\n const agent = await getAgent();\n const res = await agent.rocsByGoal(opts.periodDays != null ? { period: opts.periodDays } : {});\n return res.goals.map((g) => ({\n goalId: g.goal_id,\n spend: Number(g.spend),\n value: Number(g.value),\n pendingValue: Number(g.pending_value),\n rocs: g.rocs,\n receiptCount: g.receipt_count,\n }));\n } catch (err) {\n if (isTransientToolError(err)) {\n logEvent(\n \"rocs_by_goal.transient_failure\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Tag a cadence's value once its outcome (reply / meeting / deal) is known.\n * Resolves the cadence correlation key from (prospect, play), records the value\n * to OneShot in ONE call via `tagReceiptValue({goalId})` (SDK 0.22 fans it out\n * across the goal's receipts, recorded once so it can't double-count), and\n * mirrors the tag onto the local receipts for the /receipts UI. Best-effort —\n * any failure is logged and swallowed so it never breaks the triggering flow.\n *\n * A precedence/dedup guard skips an identical re-tag (avoids a duplicate platform\n * outcome) and never downgrades a higher-value tag (e.g. a reply detected AFTER a\n * deal is logged must not overwrite `revenue` with `engagement`).\n */\nexport async function tagOutcomeValue(input: {\n prospectId: number;\n playName: string;\n valueTag: ValueTag;\n}): Promise<{ tagged: boolean }> {\n const ledger = getLedger();\n const email = ledger.getProspectById(input.prospectId)?.email;\n const goalId = cadenceGoalId(input.playName, email ?? `pid:${input.prospectId}`);\n const tagJson = JSON.stringify(input.valueTag);\n\n // Precedence/dedup guard against the goal's current local tag.\n const existing = ledger.currentGoalValueTag(goalId);\n if (existing) {\n if (existing === tagJson) return { tagged: false };\n let existingType = \"\";\n try {\n existingType = (JSON.parse(existing) as ValueTag).type ?? \"\";\n } catch {\n existingType = \"\";\n }\n if (valueTagRank(existingType) > valueTagRank(input.valueTag.type)) return { tagged: false };\n }\n\n // Mirror locally first so the UI reflects the outcome even if the platform call\n // can't run (no wallet creds) or fails. No-op when no receipt carries this goal.\n const mirrored = ledger.setReceiptValueTagByGoal(goalId, tagJson);\n if (mirrored === 0) return { tagged: false };\n\n let agent: OneShot | null = null;\n try {\n agent = await getAgent();\n } catch (err) {\n logEvent(\n \"receipt.value_tag.agent_unavailable\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return { tagged: false };\n }\n try {\n await agent.tagReceiptValue({ goalId }, input.valueTag);\n return { tagged: true };\n } catch (err) {\n logEvent(\n \"receipt.value_tag.failed\",\n { goal_id: goalId, message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n isTransientToolError(err) ? \"warn\" : \"error\",\n );\n return { tagged: false };\n }\n}\n","/**\n * Process-wide in-flight SEND tracker, used to drain gracefully on shutdown.\n *\n * The risk this guards: a `kill`/Ctrl-C lands between \"OneShot accepted the\n * send\" and \"we wrote the local `sequence_events` row\". The dedup keys off that\n * row, so a send lost in that gap can be re-sent (a duplicate) on retry. The\n * server's shutdown handler waits for `activeSendCount()` to reach 0 before\n * exiting, so every in-flight send finishes recording first.\n *\n * In-memory by design: it complements the PERSISTED `send_started_at` /\n * `sending_started_at` markers (which survive a hard kill and are reconciled by\n * the cold-boot sweep). This counter only exists within a live process and only\n * matters for the graceful (signal) path. A hard SIGKILL skips it — the boot\n * sweep is the backstop there.\n */\n\nlet active = 0;\nlet draining = false;\n\n/** Mark a send as started. Pair with exactly one `endSend()`. Prefer `trackSend`. */\nexport function beginSend(): void {\n active++;\n}\n\n/** Mark a send as finished. Never drops below 0 even if mis-paired. */\nexport function endSend(): void {\n active = Math.max(0, active - 1);\n}\n\n/**\n * Wrap a send-and-persist span so it's counted as in-flight for its whole\n * duration — including the local record write that follows the SDK call. The\n * counter decrements even if `fn` throws.\n */\nexport async function trackSend<T>(fn: () => Promise<T>): Promise<T> {\n beginSend();\n try {\n return await fn();\n } finally {\n endSend();\n }\n}\n\n/** How many sends are currently in-flight. */\nexport function activeSendCount(): number {\n return active;\n}\n\n/** Flip the draining flag — send routes should start refusing new work (503). */\nexport function beginDraining(): void {\n draining = true;\n}\n\n/** True once shutdown has begun draining; new sends should be refused. */\nexport function isDraining(): boolean {\n return draining;\n}\n\n/** Test-only: reset module state between cases. */\nexport function __resetInflight(): void {\n active = 0;\n draining = false;\n}\n\n/**\n * Poll until no sends are in-flight or `timeoutMs` elapses. Resolves\n * immediately when already idle. On timeout, returns `{ drained: false }` with\n * the count still outstanding so the caller can log it and exit anyway (the\n * boot sweep reconciles whatever was left).\n */\nexport async function waitForSendsToDrain(opts: {\n timeoutMs: number;\n pollMs?: number;\n}): Promise<{ drained: boolean; remaining: number }> {\n const poll = opts.pollMs ?? 200;\n const deadline = Date.now() + opts.timeoutMs;\n // `active` is mutated by concurrent endSend() calls during the await, not in\n // this body — read it through the accessor each tick.\n while (activeSendCount() > 0 && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, poll));\n }\n const remaining = activeSendCount();\n return { drained: remaining === 0, remaining };\n}\n","import { activeSendCount, isDraining } from \"@oneshot-gtm/core\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * Liveness + in-flight-send count. Exposes the same in-memory `activeSendCount()`\n * the shutdown drain reads, so an external restart flow can wait for sends to\n * finish before sending SIGTERM (instead of force-killing through them). The DB\n * `sending_started_at` markers can't substitute — they survive a crash and lag\n * the live counter, so they over-report.\n */\nexport function health(req: Request): Response {\n return jsonResponse(\n { ok: true, inFlightSends: activeSendCount(), draining: isDraining() },\n 200,\n req,\n );\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { HomeMetrics } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport function homeMetrics(req: Request): Response {\n const ledger = getLedger();\n const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000).toISOString();\n const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 3600 * 1000).toISOString();\n\n const recent7d = ledger.listReceipts({ sinceIso: sevenDaysAgo, limit: 1000 });\n const events7d = ledger.eventsByPlay({ sinceIso: sevenDaysAgo });\n const sent7d = events7d.reduce((acc, e) => acc + e.sent, 0);\n const replied7d = events7d.reduce((acc, e) => acc + e.replied, 0);\n const active = ledger.listActiveCadences();\n\n const metrics: HomeMetrics = {\n spendUsd7d: ledger.totalSpendUsd({ sinceIso: sevenDaysAgo }),\n spendUsd30d: ledger.totalSpendUsd({ sinceIso: thirtyDaysAgo }),\n callsLast7d: recent7d.length,\n sentLast7d: sent7d,\n repliedLast7d: replied7d,\n activeCadences: active.length,\n // In-flight /run dispatches — surfaces a \"Resume\" link on the home dashboard\n // so the founder can hop back to a running batch without remembering the URL.\n // Capped at 5 (the widget hides itself when empty).\n currentRuns: ledger.listRuns({ status: \"running\", limit: 5 }),\n };\n\n return jsonResponse(metrics, 200, req);\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\nconst candidates = [\n join(here, \"..\", \"..\", \"prompts\"),\n join(here, \"..\", \"..\", \"..\", \"prompts\"),\n join(process.cwd(), \"packages\", \"prompts\"),\n];\n\n// Matches the bracketed reference line prompt files use to point at the\n// humanizer doc: `[See _humanizer.md — every rule binding...]`. The `[^\\]]*`\n// (non-greedy through the close-bracket) avoids any chance of consuming a\n// downstream `]` if a prompt accidentally has another bracket on the line.\nconst HUMANIZER_REF_RE = /^\\[See _humanizer\\.md[^\\]]*\\]\\s*$/gm;\n\nlet humanizerCache: string | null = null;\n\n// Final (post-humanizer-inline) prompt text by name. Prompt files ship with\n// the package and aren't founder-edited at runtime, so caching is safe; in a\n// 50-target batch drain this saves 49 re-reads of the same file.\nconst promptCache = new Map<string, string>();\n\nfunction readPromptFile(name: string): string | null {\n for (const dir of candidates) {\n const path = join(dir, `${name}.md`);\n if (existsSync(path)) return readFileSync(path, \"utf8\");\n }\n return null;\n}\n\nfunction loadHumanizer(): string {\n if (humanizerCache != null) return humanizerCache;\n const content = readPromptFile(\"_humanizer\");\n if (content == null) {\n throw new Error(`_humanizer.md not found in any of: ${candidates.join(\", \")}`);\n }\n humanizerCache = content.trimEnd();\n return humanizerCache;\n}\n\nexport function loadPrompt(name: string): string {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new Error(`invalid prompt name: ${JSON.stringify(name)}`);\n }\n const cached = promptCache.get(name);\n if (cached != null) return cached;\n const raw = readPromptFile(name);\n if (raw == null) {\n throw new Error(`prompt not found: ${name}.md (searched: ${candidates.join(\", \")})`);\n }\n // The textual `[See _humanizer.md ...]` reference in many prompts was a\n // false promise: the LLM read \"see X\" but the content was never attached.\n // Inline it here so every prompt that opts in (by including the reference)\n // actually receives the humanizer rules.\n const final = HUMANIZER_REF_RE.test(raw) ? raw.replace(HUMANIZER_REF_RE, loadHumanizer()) : raw;\n promptCache.set(name, final);\n return final;\n}\n\n/** Test-only: clears the memoized humanizer + prompt reads. Not used in production. */\nexport function _resetPromptCache(): void {\n humanizerCache = null;\n promptCache.clear();\n}\n","import { llmApiKey, loadConfig, logEvent } from \"@oneshot-gtm/core\";\nimport { loadPrompt } from \"./prompts.ts\";\n\nexport interface LlmMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface LlmCompleteInput {\n messages: LlmMessage[];\n temperature?: number;\n maxTokens?: number;\n}\n\nexport interface LlmCompleteOutput {\n content: string;\n provider: string;\n model: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\nclass LlmError extends Error {\n constructor(\n message: string,\n public readonly status?: number,\n ) {\n super(message);\n this.name = \"LlmError\";\n }\n}\n\nlet humanizerPrologueCache: string | null = null;\nfunction humanizerPrologue(): string {\n if (humanizerPrologueCache !== null) return humanizerPrologueCache;\n try {\n humanizerPrologueCache = loadPrompt(\"_humanizer\");\n } catch {\n humanizerPrologueCache = \"\";\n }\n return humanizerPrologueCache;\n}\n\nfunction injectHumanizer(messages: LlmMessage[]): LlmMessage[] {\n const prologue = humanizerPrologue();\n if (!prologue) return messages;\n const sysIdx = messages.findIndex((m) => m.role === \"system\");\n if (sysIdx < 0) {\n return [{ role: \"system\", content: prologue }, ...messages];\n }\n const sys = messages[sysIdx];\n if (!sys) return messages;\n if (sys.content.includes(\"_humanizer.md\") || sys.content.includes(\"Anti-AI-slop rules\")) {\n const out: LlmMessage[] = messages.slice();\n out[sysIdx] = { role: \"system\", content: `${prologue}\\n\\n---\\n\\n${sys.content}` };\n return out;\n }\n return messages;\n}\n\nexport async function complete(input: LlmCompleteInput): Promise<LlmCompleteOutput> {\n const cfg = loadConfig();\n const key = llmApiKey(cfg.llmProvider);\n if (!key) {\n const envName = {\n openrouter: \"OPENROUTER_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n }[cfg.llmProvider];\n throw new LlmError(`No ${envName} set. Run: oneshot-gtm config llm`);\n }\n\n const expanded: LlmCompleteInput = { ...input, messages: injectHumanizer(input.messages) };\n\n const startedAt = Date.now();\n logEvent(\"llm.start\", {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n message_count: expanded.messages.length,\n max_tokens: expanded.maxTokens ?? null,\n });\n try {\n let result: LlmCompleteOutput;\n switch (cfg.llmProvider) {\n case \"openrouter\":\n result = await openaiCompatibleComplete({\n key,\n model: cfg.llmModel,\n baseUrl: \"https://openrouter.ai/api/v1\",\n provider: \"openrouter\",\n input: expanded,\n extraHeaders: {\n \"HTTP-Referer\": \"https://github.com/oneshot-agent/oneshot-gtm\",\n \"X-Title\": \"oneshot-gtm\",\n },\n });\n break;\n case \"openai\":\n result = await openaiCompatibleComplete({\n key,\n model: cfg.llmModel,\n baseUrl: \"https://api.openai.com/v1\",\n provider: \"openai\",\n input: expanded,\n });\n break;\n case \"anthropic\":\n result = await anthropicComplete({ key, model: cfg.llmModel, input: expanded });\n break;\n }\n logEvent(\"llm.done\", {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n duration_ms: Date.now() - startedAt,\n response_chars: result.content.length,\n });\n return result;\n } catch (err) {\n logEvent(\n \"llm.error\",\n {\n provider: cfg.llmProvider,\n model: cfg.llmModel,\n duration_ms: Date.now() - startedAt,\n error_class: (err as Error).constructor.name,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n throw err;\n }\n}\n\ninterface OpenAIArgs {\n key: string;\n model: string;\n baseUrl: string;\n provider: string;\n input: LlmCompleteInput;\n extraHeaders?: Record<string, string>;\n}\n\nasync function openaiCompatibleComplete(args: OpenAIArgs): Promise<LlmCompleteOutput> {\n const res = await fetch(`${args.baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${args.key}`,\n ...args.extraHeaders,\n },\n body: JSON.stringify({\n model: args.model,\n messages: args.input.messages,\n temperature: args.input.temperature ?? 0.7,\n max_tokens: args.input.maxTokens ?? 1024,\n }),\n });\n\n if (!res.ok) {\n const body = await res.text();\n throw new LlmError(`${args.provider} ${res.status}: ${body.slice(0, 400)}`, res.status);\n }\n\n const data = (await res.json()) as {\n choices: Array<{ message: { content: string } }>;\n usage?: { prompt_tokens?: number; completion_tokens?: number };\n };\n\n const choice = data.choices[0];\n if (!choice) throw new LlmError(`${args.provider} returned no choices`);\n\n return {\n content: choice.message.content,\n provider: args.provider,\n model: args.model,\n inputTokens: data.usage?.prompt_tokens,\n outputTokens: data.usage?.completion_tokens,\n };\n}\n\ninterface AnthropicArgs {\n key: string;\n model: string;\n input: LlmCompleteInput;\n}\n\nasync function anthropicComplete(args: AnthropicArgs): Promise<LlmCompleteOutput> {\n const system = args.input.messages.find((m) => m.role === \"system\")?.content;\n const messages = args.input.messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({ role: m.role, content: m.content }));\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": args.key,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: args.model,\n max_tokens: args.input.maxTokens ?? 1024,\n temperature: args.input.temperature ?? 0.7,\n ...(system ? { system } : {}),\n messages,\n }),\n });\n\n if (!res.ok) {\n const body = await res.text();\n throw new LlmError(`anthropic ${res.status}: ${body.slice(0, 400)}`, res.status);\n }\n\n const data = (await res.json()) as {\n content: Array<{ type: string; text?: string }>;\n usage?: { input_tokens?: number; output_tokens?: number };\n };\n\n const text = data.content.map((b) => b.text ?? \"\").join(\"\");\n return {\n content: text,\n provider: \"anthropic\",\n model: args.model,\n inputTokens: data.usage?.input_tokens,\n outputTokens: data.usage?.output_tokens,\n };\n}\n","/**\n * Parse a JSON object out of an LLM response. Handles three shapes in order:\n * 1. A fenced ```json ... ``` block.\n * 2. A raw JSON document (with optional surrounding whitespace).\n * 3. A response with prose before/after — slice between the outer braces.\n *\n * Returns `fallback` when all three attempts fail. The helper exists so every\n * finder/play that asks the LLM for structured JSON doesn't re-implement the\n * same four-step recovery ceremony (there were seven copies of it before).\n */\nexport function tryParseJsonObject<T>(raw: string, fallback: T): T {\n const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const candidate = (fenced ? fenced[1] : raw) ?? \"\";\n const trimmed = candidate.trim();\n if (trimmed.length > 0) {\n try {\n return JSON.parse(trimmed) as T;\n } catch {\n // fall through to brace-slice\n }\n const start = candidate.indexOf(\"{\");\n const end = candidate.lastIndexOf(\"}\");\n if (start >= 0 && end > start) {\n try {\n return JSON.parse(candidate.slice(start, end + 1)) as T;\n } catch {\n // fall through to fallback\n }\n }\n }\n return fallback;\n}\n","import {\n cadenceGoalId,\n ENRICH_CACHE_TTL_MS,\n ENRICH_DEADLINE_MS,\n ENRICH_FAILURE_TTL_MS,\n enrichProfile,\n getLedger,\n isTransientToolError,\n loadConfig,\n logEvent,\n receiptUrlForId,\n sendEmail,\n trackSend,\n verifyEmail,\n withDeadline,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\n\n/** The shape safeEnrich returns when enrichment failed (live or negative-cached). */\nconst FAILED_ENRICH = { status: \"failed\", profile: null, cost: 0 };\n\n/**\n * enrichProfile that (a) never throws and (b) caches by email. The dossier is a\n * nice-to-have for drafting, the SDK call is slow (~70s) and billed, and the\n * same person can recur across plays / repeated previews / re-sends — so we\n * cache the result by email (TTL) and reuse it. A cache hit returns receiptId 0\n * (no new SDK call, no spend). On failure: log a warn and return an empty\n * result so callers' `enr.result` / `enr.receiptId` usage keeps working.\n */\nexport async function safeEnrich(\n input: Parameters<typeof enrichProfile>[0],\n ctx: Parameters<typeof enrichProfile>[1],\n): Promise<Awaited<ReturnType<typeof enrichProfile>>> {\n const ledger = getLedger();\n const email = typeof input.email === \"string\" ? input.email.trim().toLowerCase() : null;\n\n if (email) {\n const cached = ledger.getCachedEnrichment(email);\n if (cached) {\n const ageMs = Date.now() - new Date(cached.fetched_at).getTime();\n // Negative entry: the SDK job failed recently — don't burn another ~70s\n // attempt; draft from payload context. Expired failures fall through\n // and retry below.\n if (cached.status === \"failed\") {\n if (ageMs < ENRICH_FAILURE_TTL_MS) {\n return { result: FAILED_ENRICH, receiptId: 0 } as unknown as Awaited<\n ReturnType<typeof enrichProfile>\n >;\n }\n } else if (ageMs < ENRICH_CACHE_TTL_MS) {\n try {\n return { result: JSON.parse(cached.result_json), receiptId: 0 } as Awaited<\n ReturnType<typeof enrichProfile>\n >;\n } catch {\n // corrupt cache row — fall through and refetch\n }\n }\n }\n }\n\n try {\n // Default audit context so even ad-hoc callers that pass only {playName}\n // get a useful decisionContext on the receipt. Caller-supplied keys win.\n const enrichedCtx = {\n ...ctx,\n decisionContext: {\n source: \"play.enrich\",\n ...(email ? { prospectEmail: email } : {}),\n ...(input.linkedinUrl ? { linkedinUrl: input.linkedinUrl } : {}),\n ...(input.companyDomain ? { companyDomain: input.companyDomain } : {}),\n ...ctx.decisionContext,\n },\n };\n const live = enrichProfile(input, enrichedCtx);\n // Cache writes ride on the LIVE promise, not the deadline race — a call\n // that outlives the deadline still records its outcome when it settles\n // (late success overwrites the failure marker written below).\n live.then(\n (out) => {\n if (email) {\n try {\n ledger.setCachedEnrichment(email, JSON.stringify(out.result));\n } catch {\n // cache write is best-effort\n }\n }\n },\n () => {\n // Rejection is handled by the race's catch below (or already raced\n // out); this handler only exists to silence unhandled-rejection noise\n // from the abandoned promise.\n },\n );\n return await withDeadline(live, ENRICH_DEADLINE_MS, \"enrichProfile\");\n } catch (err) {\n const message = (err as Error)?.message ?? \"\";\n logEvent(\"enrich.failed\", { play: ctx.playName, message_120: message.slice(0, 120) }, \"warn\");\n // Only negative-cache a GENUINE failure (no data for this email). A\n // transient platform/transport error (e.g. \"Tool execution failed\" during\n // the 2026-06 outage) must NOT be cached, or every email it touched stays\n // un-enrichable for ENRICH_FAILURE_TTL_MS even after the platform recovers.\n if (email && !isTransientToolError(err)) {\n try {\n ledger.setCachedEnrichmentFailure(email, message);\n } catch {\n // cache write is best-effort\n }\n }\n return {\n result: FAILED_ENRICH,\n receiptId: 0,\n } as unknown as Awaited<ReturnType<typeof enrichProfile>>;\n }\n}\n\nexport const SLOP_PHRASES: Array<[RegExp, string]> = [\n [/\\bI noticed\\b/i, \"banned-opener:I-noticed\"],\n [/\\bI came across\\b/i, \"banned-opener:I-came-across\"],\n [/\\bHope this (?:email )?finds you well\\b/i, \"banned-opener:hope-this-finds\"],\n [/\\bQuick question\\b/i, \"banned-opener:quick-question\"],\n [/\\bLoved your launch\\b/i, \"banned-opener:loved-your-launch\"],\n [/\\bReaching out because\\b/i, \"banned-opener:reaching-out\"],\n [/\\bI'd love to (?:chat|connect|jump on a call|hear)\\b/i, \"banned-cta:love-to-chat\"],\n [/\\bWorth a 15.?min\\b/i, \"banned-cta:worth-15-min\"],\n [/\\bMind if I\\b/i, \"banned-cta:mind-if-i\"],\n [/\\bJust wanted to\\b/i, \"banned-filler:just-wanted-to\"],\n [/\\bcurious to (?:learn|hear)\\b/i, \"banned-filler:curious-to\"],\n [\n /\\b(?:additionally|crucial|delve|enduring|enhance|fostering|garner|highlight|interplay|intricate|pivotal|showcase|tapestry|testament|underscore|leverage|navigate|elevate|empower|seamless|robust|comprehensive|vibrant|profound|groundbreaking|revolutionary)\\b/i,\n \"ai-vocab\",\n ],\n [\n /\\b(?:serves as|stands as|represents a|marks a|functions as|boasts a|features a)\\b/i,\n \"copula-avoidance\",\n ],\n [/^(?:Great question|Certainly|Of course|Absolutely)[!,]/i, \"sycophantic-opener\"],\n [\n /\\b(?:as of my last training|based on available information|while specific details are limited)\\b/i,\n \"knowledge-cutoff-hedge\",\n ],\n [/\\bIt'?s not (?:just|merely) [^.]+, it'?s\\b/i, \"negative-parallelism\"],\n [\n /\\b(?:the future looks bright|exciting times lie ahead|journey toward)\\b/i,\n \"generic-positive-ending\",\n ],\n [/\\b(?:hope this helps|let me know if you'?d like|happy to expand)\\b/i, \"servile-closer\"],\n];\n\n/**\n * Trailing signature lines that the signatureDirective forces the LLM to\n * append (founder name, then product domain, then optional \"Sent from my\n * iPhone\"). Returned in last-line-first order so callers can peel from the\n * end. Empty when neither name nor domain is configured (no sig to strip).\n */\nfunction configuredSigLines(): string[] {\n const cfg = loadConfig();\n const out: string[] = [];\n if (cfg.mobileSignature === true) out.push(\"Sent from my iPhone\");\n const domain = (cfg.productDomain ?? \"\").trim();\n if (domain) out.push(domain);\n const name = (cfg.founderName ?? \"\").trim();\n if (name) out.push(name);\n return out;\n}\n\n/**\n * Word count for body-too-long lint. Strips the trailing signature lines so\n * the LLM isn't penalized for the 2-3 deterministic words the\n * signatureDirective forces it to append. Otherwise a prompt that says \"≤110\n * words\" only really gives the LLM ~107 for content, and borderline drafts\n * trip body-too-long even when they're inside the contract.\n *\n * `sigLines` (last-line-first order) is exposed for tests so they don't have\n * to mock loadConfig — production passes nothing and reads config.\n */\nexport function bodyWordsForLint(body: string, sigLines?: string[]): number {\n const lines = sigLines ?? configuredSigLines();\n let trimmed = body.replace(/\\s+$/, \"\");\n // Peel each sig line off the tail, but only if it matches the current\n // last line — guarantees we never chop content that happens to contain\n // the founder's name mid-paragraph.\n for (const line of lines) {\n const i = trimmed.lastIndexOf(\"\\n\");\n const last = (i < 0 ? trimmed : trimmed.slice(i + 1)).trim();\n if (last !== line) break;\n trimmed = trimmed.slice(0, i < 0 ? 0 : i).replace(/\\s+$/, \"\");\n }\n return trimmed.split(/\\s+/).filter(Boolean).length;\n}\n\nexport function lintEmail(subject: string, body: string, maxBodyWords = 110): string[] {\n const flags: string[] = [];\n if (subject.length === 0) flags.push(\"empty-subject\");\n if (subject.length > 60) flags.push(\"subject-too-long\");\n if (/[A-Z]{2,}/.test(subject)) flags.push(\"subject-shouty\");\n if (body.length === 0) flags.push(\"empty-body\");\n if (bodyWordsForLint(body) > maxBodyWords) flags.push(\"body-too-long\");\n if (body.includes(\"—\")) flags.push(\"em-dash\");\n if (/[“”‘’]/.test(body)) flags.push(\"curly-quotes\");\n if (/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}]/u.test(body)) flags.push(\"emoji\");\n for (const [re, label] of SLOP_PHRASES) {\n if (re.test(body)) flags.push(label);\n }\n if (/(\\b\\w+\\b),\\s+(\\b\\w+\\b),\\s+and\\s+\\b\\w+\\b/.test(body)) flags.push(\"rule-of-three\");\n if ((body.match(/!/g) ?? []).length > 1) flags.push(\"excess-exclamations\");\n if (body.toLowerCase().includes(\"calendly\")) flags.push(\"calendar-link\");\n return flags;\n}\n\nexport interface DraftedEmail {\n subject: string;\n body: string;\n}\n\n/**\n * Stub drafted-row for a target whose per-target processing threw (LLM API\n * error, SDK JobTimeoutError, ledger write failure, etc.). Plays wrap their\n * per-target body in try/catch and push this on failure so the rest of the\n * batch can keep going. Same shape `drain.ts` synthesizes when its outer\n * `dispatchOneTarget` catches — one source of truth for the error envelope.\n */\ninterface ErrorDraft {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n}\nexport function errorDraft(message: string | null | undefined): ErrorDraft {\n const msg = (message ?? \"play failed\").slice(0, 80);\n return {\n subject: \"(error)\",\n body: \"\",\n flags: [`error: ${msg}`],\n sent: false,\n receiptIds: [],\n };\n}\n\n/**\n * Deterministic, semantics-preserving cleanups that the LLM occasionally\n * slips through despite the humanizer rules being in its system prompt.\n * Applied silently inside `draftEmailFromPrompt` so these four flags never\n * surface in the UI.\n */\nexport function humanizeDraft(input: DraftedEmail): DraftedEmail {\n return {\n subject: applyAutofixes(input.subject),\n body: applyAutofixes(input.body),\n };\n}\n\nfunction applyAutofixes(s: string): string {\n return (\n s\n // Collapse only horizontal whitespace around the em-dash. Using `\\s*`\n // here would eat a trailing newline when an em-dash ends a paragraph,\n // silently merging paragraphs.\n .replace(/[ \\t]*—[ \\t]*/g, \", \")\n .replace(/[“”]/g, '\"')\n .replace(/[‘’]/g, \"'\")\n // Emoji ranges: main BMP+SMP block, dingbats, and the regional-\n // indicator pair used for country flags (🇺🇸 = 1F1FA + 1F1F8).\n .replace(/[\\u{1F300}-\\u{1FAFF}\\u{2600}-\\u{27BF}\\u{1F1E6}-\\u{1F1FF}]/gu, \"\")\n // Variation-selector + ZWJ stripped in a second pass — leaving them\n // would produce a dangling glyph after the emoji itself is gone\n // (e.g. `☀️` → `️`).\n .replace(/\\u{FE0F}|\\u{200D}/gu, \"\")\n .replace(/!\\s*!+/g, \"!\")\n // Strip trailing horizontal whitespace before a newline. Catches the\n // `paragraph,_\\n` artifact left by an em-dash at end-of-line, plus\n // any stray trailing space from emoji removal.\n .replace(/[ \\t]+\\n/g, \"\\n\")\n .trim()\n );\n}\n\n/**\n * Binding sign-off directive appended to every email system prompt. Forces\n * the founder's product domain onto its own line beneath their name, even on\n * prompts that say \"no links / no tagline\" (a bare domain is a signature, not\n * a hyperlink). Returns \"\" when no domain is configured, so founders who\n * haven't set one keep the prior name-only sign-off. Loaded fresh each call\n * so a /setup change takes effect without a process restart.\n */\nexport function signatureDirective(): string {\n const cfg = loadConfig();\n const domain = (cfg.productDomain ?? \"\").trim();\n if (!domain) return \"\";\n const name = (cfg.founderName ?? \"\").trim() || \"[founder name]\";\n const mobile = cfg.mobileSignature === true;\n const sigLines = [name, domain];\n if (mobile) sigLines.push(\"Sent from my iPhone\");\n return [\n \"\",\n \"\",\n \"## Signature (binding — overrides any sign-off rule above)\",\n mobile\n ? \"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:\"\n : \"End the email with the founder's name, then their domain on the very next line:\",\n \"\",\n ...sigLines,\n \"\",\n `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.`,\n ...(mobile\n ? [\n `The \"Sent from my iPhone\" line is a literal proof-of-human artifact. Always exactly that string, no variation, no quotes.`,\n ]\n : []),\n ].join(\"\\n\");\n}\n\n/**\n * Build a SOCIAL PROOF input block from the founder's three optional config\n * fields. Returns null when none are set — callers skip the line entirely\n * so the prompt's \"if SOCIAL PROOF is in the inputs\" conditional kicks in.\n * Each prompt should weave AT MOST ONE beat (credentials OR built-with OR\n * partners) into the email, not stack them.\n */\nexport function socialProofBlock(): string | null {\n const cfg = loadConfig();\n const lines: string[] = [];\n const cred = cfg.founderCredentials?.trim();\n const built = cfg.productPortfolio?.trim();\n const partners = cfg.partners?.trim();\n if (cred) lines.push(`CREDENTIALS: ${cred}`);\n if (built) lines.push(`PORTFOLIO: ${built}`);\n if (partners) lines.push(`PARTNERS: ${partners}`);\n if (lines.length === 0) return null;\n return [\n \"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):\",\n ...lines,\n ].join(\"\\n\");\n}\n\nexport async function draftEmailFromPrompt(opts: {\n promptName: string;\n inputBlock: string;\n temperature?: number;\n maxTokens?: number;\n}): Promise<DraftedEmail> {\n const system = loadPrompt(opts.promptName) + signatureDirective();\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: opts.inputBlock },\n ],\n temperature: opts.temperature ?? 0.65,\n maxTokens: opts.maxTokens ?? 500,\n });\n return humanizeDraft(parseSubjectBody(res.content));\n}\n\nfunction parseSubjectBody(raw: string): DraftedEmail {\n const parsed = tryParseJsonObject<{ subject?: string; body?: string }>(raw, {});\n return {\n subject: (parsed.subject ?? \"\").trim(),\n body: (parsed.body ?? \"\").trim(),\n };\n}\n\nexport interface SendDraftedOpts {\n playName: string;\n to: string;\n draft: DraftedEmail;\n flags: string[];\n prospectMeta: {\n name?: string | null;\n email?: string | null;\n company?: string | null;\n linkedin_url?: string | null;\n phone?: string | null;\n source?: string | null;\n };\n metadata?: Record<string, unknown>;\n dryRun: boolean;\n /**\n * Allow a first-touch even if the prospect was already touched by ANOTHER\n * play. Off by default (we never first-touch the same person twice). Only\n * breakup-revive sets this — deliberately re-contacting cold prospects is its\n * whole job, mirroring how its finder bypasses isDuplicate.\n */\n allowRecontact?: boolean;\n}\n\nexport interface SendDraftedResult {\n receiptIds: number[];\n sent: boolean;\n}\n\nexport async function sendDraftedEmail(opts: SendDraftedOpts): Promise<SendDraftedResult> {\n const ledger = getLedger();\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n const receiptIds: number[] = [];\n let sent = false;\n if (!opts.dryRun && opts.flags.length === 0) {\n // Pre-send dedupe: refuse to send step-0 a second time to the same\n // (prospect, play). Catches double-fire from drain-after-drain, /run\n // resubmits, two-tab races, etc. Residual race window is microseconds\n // between this read and recordSequenceEvent; documented as acceptable.\n const existing = ledger.findProspectByEmail(opts.to);\n if (existing) {\n const prior = ledger.listSequenceEventsForProspectPlay(existing.id, opts.playName);\n if (prior.some((e) => e.step_index === 0)) {\n opts.flags.push(\"already-enrolled\");\n return { receiptIds: [], sent: false };\n }\n // Cross-play guard: never first-touch someone a DIFFERENT play already\n // first-touched. The authoritative dedup for the \"same person queued\n // under two plays before either sent\" race. breakup-revive opts out.\n if (!opts.allowRecontact && ledger.prospectHasFirstTouch(existing.id)) {\n opts.flags.push(\"already-contacted\");\n return { receiptIds: [], sent: false };\n }\n }\n // Track as in-flight for the WHOLE send-and-record span (SDK call →\n // sequence_events row), so a graceful shutdown drains it before exiting and\n // never leaves a sent-but-unrecorded email the dedup can't see.\n const receiptId = await trackSend(async () => {\n const send = await sendEmail(\n { to: opts.to, subject: opts.draft.subject, body: opts.draft.body },\n {\n playName: opts.playName,\n memo: `${opts.playName} step 0 → ${opts.to}`,\n decisionContext: {\n source: \"play.initial\",\n goalId: cadenceGoalId(opts.playName, opts.to),\n prospectEmail: opts.to,\n prospectName: opts.prospectMeta.name ?? null,\n company: opts.prospectMeta.company ?? null,\n subject: opts.draft.subject,\n },\n },\n );\n const prospectId = ledger.upsertProspect(opts.prospectMeta);\n ledger.recordSequenceEvent({\n prospectId,\n playName: opts.playName,\n stepIndex: 0,\n channel: \"email\",\n status: \"sent\",\n receiptId: send.receiptId,\n metadata: { subject: opts.draft.subject, body: opts.draft.body, ...opts.metadata },\n });\n return send.receiptId;\n });\n receiptIds.push(receiptId);\n sent = true;\n }\n return { receiptIds, sent };\n}\n\nexport function receiptUrls(receiptIds: number[]): string[] {\n return receiptIds.map(receiptUrlForId);\n}\n\n/** Domain portion of an email address, or undefined if it has no `@`. */\nexport function emailDomain(email: string): string | undefined {\n const at = email.indexOf(\"@\");\n if (at < 0) return undefined;\n return email.slice(at + 1);\n}\n\nconst HONORIFIC_TOKENS = new Set([\n \"dr.\",\n \"dr\",\n \"mr.\",\n \"mr\",\n \"mrs.\",\n \"mrs\",\n \"ms.\",\n \"ms\",\n \"prof.\",\n \"prof\",\n \"sr.\",\n \"sr\",\n \"jr.\",\n \"jr\",\n]);\n\n/**\n * Best-effort first-name extraction from a prospect's `name` field. Returns\n * `null` when we shouldn't use a greeting at all: missing data, the placeholder\n * \"(unknown)\", a username-looking handle, or a non-capitalized opening token\n * (which usually signals a handle fragment rather than a real first name).\n *\n * Used to optionally surface `PROSPECT_FIRST_NAME` to the LLM input block so\n * prompts can occasionally open with `Hey {firstName},`. The LLM owns the\n * decision to actually greet — this helper just gates whether the field is\n * present.\n */\nexport function firstNameFrom(name: string | null | undefined): string | null {\n if (!name) return null;\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed === \"(unknown)\") return null;\n const tokens = trimmed.split(/\\s+/);\n let i = 0;\n while (i < tokens.length && HONORIFIC_TOKENS.has(tokens[i]!.toLowerCase())) {\n i++;\n }\n const first = tokens[i];\n if (!first) return null;\n // Handle-looking inputs (\"schen\", \"samaralihussain\") almost always come from\n // a finder pre-screen failure; greeting \"Hey schen,\" is worse than no greeting.\n if (!/^[A-Z]/.test(first)) return null;\n // Strip a trailing comma if it slipped through (e.g. \"Sarah, PhD\").\n return first.replace(/,$/, \"\");\n}\n\ninterface VerifyAndFilterResult<T> {\n verified: T[];\n dropped: Array<{ target: T; email: string; reason: string }>;\n receiptIds: number[];\n costUsd: number;\n}\n\n/**\n * Verify a batch of target emails BEFORE drafting + sending. Used by\n * direct-input entry points (CLI motion commands + dashboard /run) where\n * the founder pastes targets directly without going through a finder.\n * Drops undeliverable rows so the caller skips ~$0.005-0.02 of LLM\n * drafting cost per bad email AND avoids the send attempt itself.\n *\n * Skips on dryRun (no real spend during preview) and on empty input.\n * De-dupes the underlying verifyEmail calls so a duplicated email in\n * the input doesn't double-bill.\n *\n * Finder-sourced rows that flow through /queue → drain do NOT call this\n * — they were already verified at finder enqueue time.\n */\nexport async function verifyAndFilterTargets<T>(\n targets: T[],\n getEmail: (target: T) => string | null | undefined,\n opts: { playName: string; dryRun: boolean },\n): Promise<VerifyAndFilterResult<T>> {\n if (opts.dryRun || targets.length === 0) {\n return { verified: targets, dropped: [], receiptIds: [], costUsd: 0 };\n }\n\n const emailFor = new Map<T, string>();\n for (const t of targets) {\n const e = (getEmail(t) ?? \"\").trim().toLowerCase();\n if (e.length > 0) emailFor.set(t, e);\n }\n\n const uniqueEmails = [...new Set(emailFor.values())];\n // Catch SDK throws (transient network / rate-limit / invalid-format errors)\n // and treat the affected target as dropped rather than aborting the whole\n // run. Mirrors the per-candidate handling finders already do — one bad\n // verify call shouldn't kill a 25-target batch.\n const verifications = await Promise.all(\n uniqueEmails.map(async (email) => {\n try {\n const r = await verifyEmail({ email }, { playName: opts.playName });\n return {\n email,\n deliverable: Boolean(r.result.deliverable),\n receiptId: r.receiptId,\n costUsd: r.result.cost ?? 0,\n errored: false as const,\n };\n } catch (err) {\n return {\n email,\n deliverable: false,\n receiptId: 0,\n costUsd: 0,\n errored: true as const,\n message: ((err as Error).message ?? \"verify failed\").slice(0, 120),\n };\n }\n }),\n );\n const byEmail = new Map(verifications.map((v) => [v.email, v]));\n\n const verified: T[] = [];\n const dropped: VerifyAndFilterResult<T>[\"dropped\"] = [];\n let costUsd = 0;\n const receiptIds: number[] = [];\n for (const v of verifications) {\n costUsd += v.costUsd;\n if (v.receiptId > 0) receiptIds.push(v.receiptId);\n }\n\n for (const t of targets) {\n const email = emailFor.get(t);\n if (!email) {\n dropped.push({ target: t, email: \"\", reason: \"missing email\" });\n continue;\n }\n const v = byEmail.get(email);\n if (!v) {\n dropped.push({ target: t, email, reason: \"undeliverable\" });\n continue;\n }\n if (v.errored) {\n dropped.push({ target: t, email, reason: `verify-error: ${v.message}` });\n continue;\n }\n if (!v.deliverable) {\n dropped.push({ target: t, email, reason: \"undeliverable\" });\n continue;\n }\n verified.push(t);\n }\n\n return { verified, dropped, receiptIds, costUsd };\n}\n","import {\n getLedger,\n hasAnySendCapacity,\n isSendDeferred,\n listInbox,\n loadConfig,\n logEvent,\n parallelMap,\n cadenceGoalId,\n receiptUrlForId,\n sendEmail,\n sendSms,\n tagOutcomeValue,\n trackSend,\n voiceCall,\n type ProspectRecord,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport {\n firstNameFrom,\n humanizeDraft,\n lintEmail,\n signatureDirective,\n socialProofBlock,\n} from \"./_lib.ts\";\n\nexport interface CadenceContext {\n prospect: ProspectRecord;\n cfg: ReturnType<typeof loadConfig>;\n metadata: Record<string, unknown>;\n}\n\nexport type StepPayload =\n | { kind: \"email\"; subject: string; body: string }\n | { kind: \"sms\"; message: string; toPhone?: string }\n | {\n kind: \"voice\";\n objective: string;\n toPhone?: string;\n context?: string;\n maxDurationMinutes?: number;\n };\n\ninterface SequenceStep {\n /** Days after enrollment (step 0 was the original send). step 1 is the first follow-up. */\n dayOffset: number;\n channel: \"email\" | \"sms\" | \"voice\";\n /** When true, an inbound reply at any time stops the cadence. */\n breakOnReply: boolean;\n /** Builder returns null to skip this step gracefully. */\n builder: (ctx: CadenceContext) => Promise<StepPayload | null>;\n /** Optional label for logs. */\n label?: string;\n}\n\nexport interface Sequence {\n playName: string;\n steps: SequenceStep[];\n}\n\nconst playSequences = new Map<string, Sequence>();\n\nexport function registerSequence(seq: Sequence): void {\n playSequences.set(seq.playName, seq);\n}\n\n/**\n * \"Does this label name a breakup step?\" — single source of truth for the\n * label-substring check. Used by isBreakupStepAt for the cadence-final\n * semantic check AND by /plays for per-step rendering where each row is\n * already a step.\n */\nexport function isBreakupLabel(label: string | null | undefined): boolean {\n return Boolean(label && label.toLowerCase().includes(\"breakup\"));\n}\n\n/**\n * Centralized breakup-step detection for cadence-progress semantics. A\n * step is \"the breakup\" iff (a) it sits at the END of the sequence and\n * (b) its label is a breakup label. Both clauses matter: the\n * breakup-email PROMPT is also used as accelerator-batch's only\n * follow-up — at index 0 — and that one isn't semantically a breakup\n * for cadence UX purposes (no value follow-up preceded it).\n */\nexport function isBreakupStepAt(seq: Sequence, stepEntryIndex: number): boolean {\n if (stepEntryIndex !== seq.steps.length - 1) return false;\n return isBreakupLabel(seq.steps[stepEntryIndex]?.label);\n}\n\nexport interface NextStepInfo {\n /** Label of the next step (e.g. \"value follow-up\", \"breakup\"). */\n label: string | null;\n /** True when the next step is the final breakup. */\n isBreakup: boolean;\n /** 1-based index of the next step within the follow-up steps array. */\n nextStepNumber: number;\n}\n\n/**\n * Number of follow-up steps registered for this play (excludes day-0).\n * Always returns the registered total regardless of current_step — the UI\n * uses `playFollowupCount + 1` for the StepProgress dot count which should\n * be stable for completed cadences too.\n */\nexport function playFollowupCount(playName: string): number {\n return effectiveSequence(playName)?.steps.length ?? 0;\n}\n\n/**\n * Given a play + the cadence's current_step, describe the NEXT step\n * scheduled to fire. Returns null when the cadence is at or past the\n * last step (no more steps to send). Source of truth for both the\n * server's CadenceView and the /cadences UI — avoids hardcoded\n * play→step-count Records in the web layer.\n */\nexport function nextStepInfo(playName: string, currentStep: number): NextStepInfo | null {\n const seq = effectiveSequence(playName);\n if (!seq) return null;\n const nextIndex = currentStep + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) return null;\n const step = seq.steps[stepEntryIndex];\n return {\n label: step?.label ?? null,\n isBreakup: isBreakupStepAt(seq, stepEntryIndex),\n nextStepNumber: nextIndex,\n };\n}\n\nexport function getSequence(playName: string): Sequence | undefined {\n return effectiveSequence(playName);\n}\n\n/** The registered (code) sequence, ignoring any founder override. For \"reset\". */\nexport function defaultSequence(playName: string): Sequence | undefined {\n return playSequences.get(playName);\n}\n\n/**\n * The registered (code) sequence with the founder's per-play timing overrides\n * applied. The code sequence defines the structure (which prompts fire, where\n * the breakup sits); a matching-length `cadenceOverrides[playName]` in config\n * replaces each step's RELATIVE dayOffset. A length mismatch (e.g. after a\n * later structural change) is ignored — the code default wins, never throws.\n * Read fresh each call so a /plays edit takes effect without a restart.\n */\nexport function effectiveSequence(playName: string): Sequence | undefined {\n const base = playSequences.get(playName);\n if (!base) return undefined;\n const override = loadConfig().cadenceOverrides?.[playName];\n if (!Array.isArray(override) || override.length !== base.steps.length) return base;\n return {\n playName: base.playName,\n steps: base.steps.map((step, i) => ({\n dayOffset: override[i] as number,\n channel: step.channel,\n breakOnReply: step.breakOnReply,\n label: step.label,\n builder: step.builder,\n })),\n };\n}\n\nexport function enrollInCadence(input: { prospectId: number; playName: string }): void {\n const seq = effectiveSequence(input.playName);\n if (!seq || seq.steps.length === 0) return;\n const next = seq.steps[0];\n if (!next) return;\n const dueAt = new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString();\n getLedger().enrollCadence({\n prospectId: input.prospectId,\n playName: input.playName,\n nextDueAt: dueAt,\n });\n}\n\nexport interface AdvanceResult {\n polled: number;\n repliesDetected: number;\n stepsExecuted: number;\n breakups: number;\n completed: number;\n details: Array<{\n prospectEmail: string | null;\n playName: string;\n action: \"step-sent\" | \"marked-replied\" | \"breakup\" | \"completed\" | \"waiting\" | \"skipped\";\n note?: string;\n receiptIds: number[];\n }>;\n}\n\nexport interface ReplyPollResult {\n /** Inbox emails examined. */\n polled: number;\n /** Active cadences flipped to `replied` this poll. */\n repliesDetected: number;\n details: Array<{ prospectEmail: string; playName: string; subject: string }>;\n}\n\n/**\n * Poll the inbox and mark any active cadence `replied` when an inbound email's\n * from-address matches its prospect. Read-only except for the status flip — it\n * never drafts or sends, so it's safe to run on a background timer (the server\n * scheduler) as well as inside `advanceCadence`. Without a background caller,\n * replies are only noticed when the founder manually advances/sends a cadence,\n * so a reply can sit unrecognized for days and the sequence keeps emailing.\n */\nexport async function pollInboxReplies(): Promise<ReplyPollResult> {\n const ledger = getLedger();\n const out: ReplyPollResult = { polled: 0, repliesDetected: 0, details: [] };\n const inbox = await listInbox({ limit: 50 });\n out.polled = inbox.emails.length;\n for (const e of inbox.emails) {\n const from = normalizeEmail(e.from);\n const prospect = ledger.findProspectByEmail(from);\n if (!prospect) continue;\n // Index seek per matched sender, not a full-table scan per inbox email.\n // recordCadenceReply atomically flips control state + records the analytics\n // event; it decides per-status (active flips & counts, already-replied just\n // backfills the event idempotently, terminal states are left alone).\n for (const cad of ledger.listCadencesForProspect(prospect.id)) {\n const { newlyReplied } = ledger.recordCadenceReply({\n prospectId: prospect.id,\n playName: cad.play_name,\n });\n if (newlyReplied) {\n out.repliesDetected++;\n out.details.push({ prospectEmail: from, playName: cad.play_name, subject: e.subject });\n // A reply is the first value signal — tag the cadence's send receipts so\n // RoCS reflects engagement. Best-effort (tagOutcomeValue swallows errors).\n await tagOutcomeValue({\n prospectId: prospect.id,\n playName: cad.play_name,\n valueTag: { type: \"engagement\", label: \"reply\" },\n });\n }\n }\n }\n return out;\n}\n\nexport async function advanceCadence(\n opts: { dryRun: boolean } = { dryRun: false },\n): Promise<AdvanceResult> {\n const ledger = getLedger();\n const result: AdvanceResult = {\n polled: 0,\n repliesDetected: 0,\n stepsExecuted: 0,\n breakups: 0,\n completed: 0,\n details: [],\n };\n\n // 1. Poll inbox for new replies, mark cadences as replied where we recognize the from-address.\n if (!opts.dryRun) {\n try {\n const poll = await pollInboxReplies();\n result.polled = poll.polled;\n result.repliesDetected = poll.repliesDetected;\n for (const d of poll.details) {\n result.details.push({\n prospectEmail: d.prospectEmail,\n playName: d.playName,\n action: \"marked-replied\",\n note: `inbound: ${d.subject}`,\n receiptIds: [],\n });\n }\n } catch (err) {\n result.details.push({\n prospectEmail: null,\n playName: \"(poll)\",\n action: \"skipped\",\n note: `inbox poll failed: ${(err as Error).message}`,\n receiptIds: [],\n });\n }\n }\n\n // 2. For each active cadence with next_due_at <= now, execute the next step.\n // Parallelized (concurrency 3): each step is an LLM draft + send (~5-90s), and\n // `due` rows are distinct (prospect, play) pairs, so there's no shared-write\n // contention. Results are collected in input order before counting.\n const nowIso = new Date().toISOString();\n const due = ledger.listActiveCadences({ dueByIso: nowIso });\n\n // Capacity gate BEFORE drafting: when every sender identity is at its daily\n // cap, a step would burn an LLM draft and then fail the send anyway. Steps\n // stay due; tomorrow's poll picks them up with fresh capacity.\n if (!opts.dryRun && due.length > 0 && !hasAnySendCapacity()) {\n for (const cad of due) {\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"skipped\",\n note: \"deferred: daily send caps reached\",\n receiptIds: [],\n });\n }\n return result;\n }\n\n const outs = await parallelMap(due, 3, async (cad): Promise<RunCadenceStepResult> => {\n try {\n return await runCadenceStepForProspect({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\n dryRun: opts.dryRun,\n });\n } catch (err) {\n // Deferral mid-pass (caps filled while this batch ran): the step simply\n // stays due. Anything else propagates — parallelMap rejects the whole\n // pass, matching pre-rotation behavior for unexpected errors.\n if (isSendDeferred(err)) {\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: \"deferred: daily send caps reached\",\n };\n }\n throw err;\n }\n });\n\n for (let i = 0; i < due.length; i++) {\n const cad = due[i]!;\n const out = outs[i]!;\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: out.action,\n ...(out.note ? { note: out.note } : {}),\n receiptIds: out.receiptIds,\n });\n if (out.action === \"step-sent\") result.stepsExecuted++;\n else if (out.action === \"breakup\") result.breakups++;\n else if (out.action === \"completed\") result.completed++;\n }\n\n return result;\n}\n\nexport interface RunCadenceStepOptions {\n prospectId: number;\n playName: string;\n dryRun: boolean;\n /** Skip the step's builder and send this verbatim (mirrors /queue's\n send-this-one — used by the /cadences UI after a Preview round-trip). */\n persistedPayload?: StepPayload;\n}\n\nexport interface RunCadenceStepResult {\n action: AdvanceResult[\"details\"][number][\"action\"];\n payload: StepPayload | null;\n receiptIds: number[];\n note?: string;\n}\n\n/**\n * Per-prospect cadence step runner. Single source of truth for both the\n * batch `advanceCadence` (CLI) and the per-row /cadences UI (preview + send).\n * Caller decides dryRun (no send) or persistedPayload (send a previously\n * built draft verbatim). On a successful send, advances `current_step`\n * to `nextIndex` and sets `next_due_at` to the next step's offset; clears\n * any persisted preview draft via ledger.advanceCadence.\n */\nexport async function runCadenceStepForProspect(\n opts: RunCadenceStepOptions,\n): Promise<RunCadenceStepResult> {\n const ledger = getLedger();\n const cfg = loadConfig();\n const cadence = ledger.getCadence(opts.prospectId, opts.playName);\n if (!cadence) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"no cadence\" };\n }\n if (cadence.status !== \"active\") {\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: `cadence is ${cadence.status}`,\n };\n }\n const seq = effectiveSequence(opts.playName);\n if (!seq) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"no registered sequence\" };\n }\n const nextIndex = cadence.current_step + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n return { action: \"completed\", payload: null, receiptIds: [] };\n }\n const step = seq.steps[stepEntryIndex];\n if (!step) return { action: \"skipped\", payload: null, receiptIds: [] };\n\n // Re-send guard. `current_step` advances only AFTER a successful send, so a\n // crash between dispatch and `advanceCadence` (e.g. a `bun --watch` reload\n // killing the fire-and-forget send batch) leaves a prospect that already\n // received step `nextIndex` still sitting at the old `current_step`. Without\n // this guard the next due tick re-dispatches that step — and the SDK\n // idempotency key is content-keyed, not step-keyed, so a redraft drift would\n // send a real duplicate. If the step already has a terminal-sent event,\n // reconcile by moving the cadence forward WITHOUT re-sending — running the\n // SAME terminal transition a successful send would (so a reconciled breakup\n // step lands in `breakup`, not `completed`), but skipping both the dispatch\n // and the builder (no LLM redraft). Skipped on dryRun — previews never record\n // sequence_events, and we don't want a preview to silently advance a real\n // cadence.\n if (!opts.dryRun && ledger.hasSentSequenceEvent(opts.prospectId, opts.playName, nextIndex)) {\n logEvent(\n \"cadence.step.reconciled_already_sent\",\n { prospect_id: opts.prospectId, play_name: opts.playName, step_index: nextIndex },\n \"warn\",\n );\n if (isBreakupStepAt(seq, stepEntryIndex)) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"breakup\",\n });\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: `step ${nextIndex} already sent — reconciled (breakup)`,\n };\n }\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: opts.prospectId,\n playName: opts.playName,\n newStep: nextIndex,\n nextDueAt: next\n ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString()\n : null,\n });\n if (!next) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n }\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: `step ${nextIndex} already sent — reconciled (advanced without re-send)`,\n };\n }\n\n const prospect = loadProspect(opts.prospectId);\n if (!prospect) {\n return { action: \"skipped\", payload: null, receiptIds: [], note: \"prospect not found\" };\n }\n\n const built: StepPayload | null = opts.persistedPayload\n ? opts.persistedPayload\n : await step.builder({ prospect, cfg, metadata: {} });\n\n if (!built) {\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: opts.prospectId,\n playName: opts.playName,\n newStep: nextIndex,\n nextDueAt: next\n ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString()\n : null,\n });\n if (!next) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n return {\n action: \"completed\",\n payload: null,\n receiptIds: [],\n note: step.label ?? `step ${nextIndex} builder returned null`,\n };\n }\n return {\n action: \"skipped\",\n payload: null,\n receiptIds: [],\n note: step.label ?? `step ${nextIndex} builder returned null`,\n };\n }\n\n const receiptIds: number[] = [];\n if (!opts.dryRun) {\n // Single send convergence point for every path (advance / per-row / batch).\n // On a hard send failure (e.g. the platform's \"Tool execution failed\"),\n // persist it so /cadences can show \"send failed · retrying\" instead of an\n // indistinguishable \"overdue\"; the existing caller catches still log/clear\n // the in-flight marker. Cleared on the next successful advance.\n let channelOutcome: Awaited<ReturnType<typeof dispatchStep>>;\n try {\n channelOutcome = await dispatchStep({\n playName: opts.playName,\n prospectId: opts.prospectId,\n prospectEmail: cadence.prospect_email,\n stepIndex: nextIndex,\n step,\n payload: built,\n ...(step.label !== undefined ? { label: step.label } : {}),\n });\n } catch (err) {\n // A daily-cap deferral isn't a failure — the step just stays due for\n // tomorrow. Only record genuine send errors (e.g. platform \"Tool\n // execution failed\"); deferrals propagate untouched as before.\n if (!isSendDeferred(err)) {\n ledger.recordCadenceSendError({\n prospectId: opts.prospectId,\n playName: opts.playName,\n error: (err as Error)?.message ?? \"send failed\",\n });\n }\n throw err;\n }\n if (channelOutcome.skipReason) {\n return {\n action: \"skipped\",\n payload: built,\n receiptIds: [],\n note: channelOutcome.skipReason,\n };\n }\n receiptIds.push(...channelOutcome.receiptIds);\n }\n\n if (isBreakupStepAt(seq, stepEntryIndex)) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"breakup\",\n });\n return {\n action: \"breakup\",\n payload: built,\n receiptIds,\n note: step.label ?? `step ${nextIndex}`,\n };\n }\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: opts.prospectId,\n playName: opts.playName,\n newStep: nextIndex,\n nextDueAt: next ? new Date(Date.now() + next.dayOffset * 24 * 3600 * 1000).toISOString() : null,\n });\n if (!next) {\n ledger.setCadenceStatus({\n prospectId: opts.prospectId,\n playName: opts.playName,\n status: \"completed\",\n });\n }\n return {\n action: \"step-sent\",\n payload: built,\n receiptIds,\n note: step.label ?? `step ${nextIndex}`,\n };\n}\n\nexport interface CadenceStepPreview {\n subject: string;\n body: string;\n flags: string[];\n payload: StepPayload;\n draftedAt: string;\n stepLabel: string | null;\n isBreakup: boolean;\n}\n\n/**\n * Build the next step's draft and persist it via setCadenceDraft. Never\n * sends. Mirrors the /queue regenerate route — the founder reviews on\n * /cadences, then clicks Send next which calls sendCadenceStep.\n */\nexport async function previewCadenceStep(input: {\n prospectId: number;\n playName: string;\n}): Promise<CadenceStepPreview> {\n const ledger = getLedger();\n const cfg = loadConfig();\n const cadence = ledger.getCadence(input.prospectId, input.playName);\n if (!cadence) throw new Error(\"no cadence for that prospect+play\");\n if (cadence.status !== \"active\") {\n throw new Error(`cadence is ${cadence.status}, can only preview an active cadence`);\n }\n const seq = effectiveSequence(input.playName);\n if (!seq) throw new Error(`no registered sequence for play '${input.playName}'`);\n const nextIndex = cadence.current_step + 1;\n const stepEntryIndex = nextIndex - 1;\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {\n throw new Error(\"no next step (cadence is at or past the last step)\");\n }\n const step = seq.steps[stepEntryIndex];\n if (!step) throw new Error(\"step undefined\");\n const prospect = loadProspect(input.prospectId);\n if (!prospect) throw new Error(\"prospect not found\");\n const built = await step.builder({ prospect, cfg, metadata: {} });\n if (!built) throw new Error(\"builder returned null — nothing to preview\");\n\n const subject = built.kind === \"email\" ? built.subject : \"(non-email step)\";\n const body =\n built.kind === \"email\"\n ? built.body\n : built.kind === \"sms\"\n ? built.message\n : built.kind === \"voice\"\n ? built.objective\n : \"\";\n const flags = built.kind === \"email\" ? lintEmail(subject, body, 100) : [];\n ledger.setCadenceDraft({\n prospectId: input.prospectId,\n playName: input.playName,\n draft: { subject, body, flags, payload: built },\n });\n const draft = ledger.getCadenceDraft({\n prospectId: input.prospectId,\n playName: input.playName,\n });\n const draftedAt = draft?.draftedAt ?? new Date().toISOString();\n return {\n subject,\n body,\n flags,\n payload: built,\n draftedAt,\n stepLabel: step.label ?? null,\n isBreakup: isBreakupStepAt(seq, stepEntryIndex),\n };\n}\n\n/**\n * Send a previously-previewed cadence step verbatim. Reads the persisted\n * draft (or 409s if none), dispatches it through runCadenceStepForProspect,\n * and advances the cadence. The advance clears the persisted draft so a\n * subsequent Preview rebuilds against the new current_step.\n */\nexport async function sendCadenceStep(input: {\n prospectId: number;\n playName: string;\n}): Promise<RunCadenceStepResult> {\n const ledger = getLedger();\n const draft = ledger.getCadenceDraft(input);\n if (!draft) throw new Error(\"no persisted preview — click Preview first\");\n return runCadenceStepForProspect({\n prospectId: input.prospectId,\n playName: input.playName,\n dryRun: false,\n persistedPayload: draft.payload as StepPayload,\n });\n}\n\nexport interface BatchItem {\n prospectId: number;\n playName: string;\n}\n\ninterface BatchPreviewResult {\n prospectId: number;\n playName: string;\n ok: boolean;\n preview?: CadenceStepPreview;\n error?: string;\n}\n\nexport interface BatchSendResult {\n prospectId: number;\n playName: string;\n ok: boolean;\n action?: RunCadenceStepResult[\"action\"];\n receiptIds?: number[];\n error?: string;\n}\n\n/**\n * Parallel preview of a list of cadence rows (concurrency 3). Each\n * per-prospect failure is captured in the result array — the batch never\n * throws. `parallelMap` preserves input order so the returned array matches\n * `items` 1:1. Concurrency mirrors `runEmailPlay` + `advanceCadence`; the\n * founder is waiting at the UI, so 3× speedup on a 10-row preview drops\n * wall-clock from ~100s to ~35s.\n */\nexport async function previewCadenceStepBatch(items: BatchItem[]): Promise<BatchPreviewResult[]> {\n return parallelMap(items, 3, async (item) => {\n try {\n const preview = await previewCadenceStep(item);\n return { prospectId: item.prospectId, playName: item.playName, ok: true, preview };\n } catch (err) {\n return {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: false,\n error: ((err as Error)?.message ?? \"preview failed\").slice(0, 120),\n };\n }\n });\n}\n\n/**\n * Serial send of a list of previewed cadence rows. Each per-prospect failure\n * is captured; the batch never throws. Used by `POST /api/cadences/send-batch`\n * as a background promise — caller returns 202 immediately and the UI sees\n * progress via subsequent `/api/cadences` refetches (the existing\n * `advanceCadence` clears `next_step_draft_json` as each row completes).\n *\n * Sends stay serial (unlike previewCadenceStepBatch) for two reasons: the\n * `onItemSettled` callback drives the in-flight UI badge per row (parallel\n * would batch-flash all rows at once), and parallel SMTP to the same\n * domain risks soft-bounces.\n */\nexport async function sendCadenceStepBatch(\n items: BatchItem[],\n /** Fires after each item resolves (ok OR error) — lets the API layer\n * track per-row in-flight state without splitting the iteration. */\n onItemSettled?: (item: BatchItem, result: BatchSendResult) => void,\n): Promise<BatchSendResult[]> {\n const out: BatchSendResult[] = [];\n for (const item of items) {\n let result: BatchSendResult;\n try {\n const r = await sendCadenceStep(item);\n result = {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: true,\n action: r.action,\n receiptIds: r.receiptIds,\n };\n } catch (err) {\n result = {\n prospectId: item.prospectId,\n playName: item.playName,\n ok: false,\n error: ((err as Error)?.message ?? \"send failed\").slice(0, 120),\n };\n }\n out.push(result);\n onItemSettled?.(item, result);\n }\n return out;\n}\n\nfunction dispatchStep(\n input: Parameters<typeof dispatchStepImpl>[0],\n): ReturnType<typeof dispatchStepImpl> {\n // Count the whole dispatch as one in-flight send so a graceful shutdown\n // drains it (SDK call + its sequence_events write) before the process exits.\n return trackSend(() => dispatchStepImpl(input));\n}\n\nasync function dispatchStepImpl(input: {\n playName: string;\n prospectId: number;\n prospectEmail: string | null;\n stepIndex: number;\n step: SequenceStep;\n payload: StepPayload;\n label?: string | undefined;\n}): Promise<{ receiptIds: number[]; skipReason?: string }> {\n const ledger = getLedger();\n const receiptIds: number[] = [];\n\n // Per-step audit envelope: same shape across all channels so receipts can\n // be grouped/filtered by (prospectId, stepIndex, label) on the OneShot side.\n const cadenceAudit = {\n source: \"cadence\" as const,\n prospectId: input.prospectId,\n prospectEmail: input.prospectEmail,\n stepIndex: input.stepIndex,\n label: input.label ?? null,\n // Cadence correlation key — groups every step's receipts under one goal so an\n // outcome tags the whole sequence at once. Same key the tagger derives from\n // (prospect, play) at outcome time.\n goalId: cadenceGoalId(input.playName, input.prospectEmail ?? `pid:${input.prospectId}`),\n };\n const labelTail = input.label ? ` ${input.label}` : \"\";\n\n if (input.payload.kind === \"email\") {\n if (!input.prospectEmail) return { receiptIds, skipReason: \"prospect has no email\" };\n const send = await sendEmail(\n { to: input.prospectEmail, subject: input.payload.subject, body: input.payload.body },\n {\n playName: input.playName,\n memo: `${input.playName} step ${input.stepIndex}${labelTail} → ${input.prospectEmail}`,\n decisionContext: { ...cadenceAudit, subject: input.payload.subject },\n },\n );\n receiptIds.push(send.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"email\",\n status: \"sent\",\n receiptId: send.receiptId,\n metadata: {\n subject: input.payload.subject,\n body: input.payload.body,\n label: input.label,\n },\n });\n return { receiptIds };\n }\n\n if (input.payload.kind === \"sms\") {\n if (!input.payload.toPhone) {\n return { receiptIds, skipReason: \"prospect has no phone for SMS\" };\n }\n const send = await sendSms(\n { to: input.payload.toPhone, message: input.payload.message },\n {\n playName: input.playName,\n memo: `${input.playName} step ${input.stepIndex}${labelTail} SMS → ${input.payload.toPhone}`,\n decisionContext: { ...cadenceAudit, toPhone: input.payload.toPhone },\n },\n );\n receiptIds.push(send.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"sms\",\n status: \"sent\",\n receiptId: send.receiptId,\n metadata: { label: input.label },\n });\n return { receiptIds };\n }\n\n if (input.payload.kind === \"voice\") {\n if (!input.payload.toPhone) {\n return { receiptIds, skipReason: \"prospect has no phone for voice\" };\n }\n const call = await voiceCall(\n {\n objective: input.payload.objective,\n to: input.payload.toPhone,\n ...(input.payload.context ? { context: input.payload.context } : {}),\n ...(input.payload.maxDurationMinutes\n ? { maxDurationMinutes: input.payload.maxDurationMinutes }\n : {}),\n },\n {\n playName: input.playName,\n memo: `${input.playName} step ${input.stepIndex}${labelTail} voice → ${input.payload.toPhone}`,\n decisionContext: {\n ...cadenceAudit,\n toPhone: input.payload.toPhone,\n objective: input.payload.objective.slice(0, 120),\n },\n },\n );\n receiptIds.push(call.receiptId);\n ledger.recordSequenceEvent({\n prospectId: input.prospectId,\n playName: input.playName,\n stepIndex: input.stepIndex,\n channel: \"voice\",\n status: \"sent\",\n receiptId: call.receiptId,\n metadata: { label: input.label, ended_reason: call.result.ended_reason ?? null },\n });\n return { receiptIds };\n }\n\n return { receiptIds, skipReason: \"unknown step payload kind\" };\n}\n\nfunction normalizeEmail(raw: string): string {\n const m = raw.match(/<([^>]+)>/);\n return (m ? m[1]! : raw).trim().toLowerCase();\n}\n\nfunction loadProspect(id: number): ProspectRecord | null {\n return getLedger().getProspectById(id);\n}\n\nexport function buildFollowUpEmail(opts: {\n playName: string;\n promptName: string;\n contextLines: string[];\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const system = loadPrompt(opts.promptName) + signatureDirective();\n const priorBlock = buildPriorEmailsBlock(ctx.prospect.id, opts.playName);\n const proofBlock = socialProofBlock();\n // Optional first-name field: prompt rule lets the LLM occasionally open\n // with \"Hey {firstName},\". Absent when name is null / (unknown) / handle.\n const firstName = firstNameFrom(ctx.prospect.name);\n const user = [\n `FOUNDER: ${ctx.cfg.founderName}`,\n `PRODUCT: ${ctx.cfg.productOneLiner}`,\n `PROSPECT: ${ctx.prospect.name ?? \"(unknown)\"}`,\n `EMAIL: ${ctx.prospect.email ?? \"\"}`,\n `COMPANY: ${ctx.prospect.company ?? \"(unknown)\"}`,\n ...opts.contextLines,\n ...(priorBlock ? [\"\", priorBlock] : []),\n ...(proofBlock ? [\"\", proofBlock] : []),\n ...(firstName ? [\"\", `PROSPECT_FIRST_NAME: ${firstName}`] : []),\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.6,\n maxTokens: 500,\n });\n const parsed = tryParseJsonObject<{ subject?: string; body?: string }>(res.content, {});\n if (!parsed.subject || !parsed.body) return null;\n // Apply the deterministic autofixer (em-dash → \", \", curly quotes → ASCII,\n // emoji strip, etc.) — same humanization the initial-send plays get via\n // draftEmailFromPrompt. Without this, cadence follow-ups ship em-dashes\n // raw even though lintEmail flags them.\n const cleaned = humanizeDraft({\n subject: parsed.subject.trim(),\n body: parsed.body.trim(),\n });\n return { kind: \"email\", subject: cleaned.subject, body: cleaned.body };\n };\n}\n\nexport interface PriorStepRow {\n stepIndex: number;\n /** \"initial send\" for step 0; the registered step label for 1+; \"follow-up\" if missing. */\n label: string;\n subject: string;\n /** Null for legacy pre-v8 rows whose metadata_json didn't include the body. */\n body: string | null;\n /** sequence_events.created_at (UTC ISO). */\n sentAt: string;\n status: \"sent\" | \"delivered\" | \"replied\";\n}\n\n/**\n * Parse a prospect's prior sends for a given play into clean per-step rows.\n * Source of truth shared by the LLM PRIOR-EMAILS injection (which filters\n * legacy rows) and the /api/cadences view (which surfaces them with a\n * \"body not captured\" placeholder).\n */\nexport function getPriorStepsForProspect(prospectId: number, playName: string): PriorStepRow[] {\n if (!prospectId) return [];\n let rows: Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>;\n try {\n rows = getLedger().listSequenceEventsForProspectPlay(prospectId, playName) as Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>;\n } catch {\n return [];\n }\n return rows.map(rowToPriorStep);\n}\n\nfunction rowToPriorStep(r: {\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n}): PriorStepRow {\n const meta = tryParseJsonObject<{ subject?: string; body?: string; label?: string }>(\n r.metadata_json ?? \"\",\n {},\n );\n return {\n stepIndex: r.step_index,\n label: meta.label ?? (r.step_index === 0 ? \"initial send\" : \"follow-up\"),\n subject: meta.subject ?? \"(no subject)\",\n body: meta.body ?? null,\n sentAt: r.created_at,\n status: (r.status as PriorStepRow[\"status\"]) ?? \"sent\",\n };\n}\n\n/**\n * Bulk variant of getPriorStepsForProspect: one SQL round-trip for many\n * (prospect_id, play_name) pairs. Returns a Map keyed by\n * `${prospectId}|${playName}` so /api/cadences's toView can index in O(1)\n * instead of issuing one query per row. Pairs the founder hasn't sent for\n * are absent from the map (callers should default to []).\n */\nexport function getPriorStepsBulk(\n pairs: ReadonlyArray<{ prospectId: number; playName: string }>,\n): Map<string, PriorStepRow[]> {\n if (pairs.length === 0) return new Map();\n let bulk: Map<\n string,\n Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>\n >;\n try {\n bulk = getLedger().listSequenceEventsForCadences(pairs) as Map<\n string,\n Array<{\n step_index: number;\n metadata_json: string | null;\n status: string;\n created_at: string;\n }>\n >;\n } catch {\n return new Map();\n }\n const out = new Map<string, PriorStepRow[]>();\n for (const [key, rows] of bulk) {\n out.set(key, rows.map(rowToPriorStep));\n }\n return out;\n}\n\nfunction buildPriorEmailsBlock(prospectId: number, playName: string): string | null {\n const prior = getPriorStepsForProspect(prospectId, playName).filter(\n (r): r is PriorStepRow & { body: string } => r.body !== null && r.body.length > 0,\n );\n if (prior.length === 0) return null;\n const lines = [\n \"PRIOR EMAILS (your previous touches to this prospect on this play; do not repeat their angles, hooks, openers, or closes):\",\n ];\n for (const row of prior) {\n lines.push(`--- step ${row.stepIndex} (${row.label}) ---`);\n lines.push(`Subject: ${row.subject}`);\n lines.push(row.body);\n }\n return lines.join(\"\\n\");\n}\n\nexport function buildSmsStep(opts: {\n promptName: string;\n contextLines: string[];\n toPhone: (ctx: CadenceContext) => string | null;\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const phone = opts.toPhone(ctx);\n if (!phone) return null;\n const system = loadPrompt(opts.promptName);\n const user = [\n `FOUNDER: ${ctx.cfg.founderName}`,\n `PRODUCT: ${ctx.cfg.productOneLiner}`,\n `PROSPECT: ${ctx.prospect.name ?? \"(unknown)\"}`,\n ...opts.contextLines,\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.5,\n maxTokens: 250,\n });\n const parsed = tryParseJsonObject<{ message?: string }>(res.content, {});\n if (!parsed.message) return null;\n return { kind: \"sms\", message: parsed.message.trim(), toPhone: phone };\n };\n}\n\nexport function buildVoiceStep(opts: {\n toPhone: (ctx: CadenceContext) => string | null;\n objective: (ctx: CadenceContext) => string;\n context?: (ctx: CadenceContext) => string;\n maxDurationMinutes?: number;\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\n const phone = opts.toPhone(ctx);\n if (!phone) return null;\n return {\n kind: \"voice\",\n objective: opts.objective(ctx),\n toPhone: phone,\n ...(opts.context ? { context: opts.context(ctx) } : {}),\n ...(opts.maxDurationMinutes ? { maxDurationMinutes: opts.maxDurationMinutes } : {}),\n };\n };\n}\n\nexport function receiptUrlsForCadence(receiptIds: number[]): string[] {\n return receiptIds.map(receiptUrlForId);\n}\n","import { deepResearch, getLedger, isSendDeferred, loadConfig, parallelMap } from \"@oneshot-gtm/core\";\nimport {\n draftEmailFromPrompt,\n errorDraft,\n firstNameFrom,\n lintEmail,\n safeEnrich,\n sendDraftedEmail,\n socialProofBlock,\n type SendDraftedOpts,\n} from \"./_lib.ts\";\nimport { enrollInCadence } from \"./_cadence.ts\";\n\ntype AppConfig = ReturnType<typeof loadConfig>;\n\n/**\n * What a play's per-target `prepare` step hands back to the executor: the\n * receipts it billed, the dossier string it assembled (may be empty), and an\n * optional `extra` bag of play-specific fields that get merged onto the\n * drafted row verbatim (e.g. competitor-switch's `scrapedEvidence`,\n * hiring-signal's `jobPostHook`). `X` defaults to no extra fields.\n */\nexport interface Prepared<X = Record<string, never>> {\n receiptIds: number[];\n dossier: string;\n /**\n * The enrichment SDK call failed (live or negative-cached) — the draft was\n * built from payload context only. Travels to the persisted draft envelope\n * so /queue can surface it; deliberately NOT a lint flag (flags block\n * sending, and a payload-only draft is still sendable).\n */\n enrichmentFailed?: boolean;\n extra?: X;\n}\n\n/** Drafted row every email play returns: the standard six fields plus `X`. */\nexport type PlayDraft<T, X = Record<string, never>> = {\n target: T;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n /** See Prepared.enrichmentFailed. */\n enrichmentFailed?: boolean;\n} & X;\n\n/**\n * Declarative definition of an email play. The shared executor (`runEmailPlay`)\n * walks the targets, runs `prepare` → draft → lint → send → optional cadence\n * enroll, and wraps each per-target body in the same try/catch error envelope.\n * Everything that varies between plays is a field or a closure here.\n */\nexport interface EmailPlayDef<T, X = Record<string, never>> {\n playName: string;\n promptName: string;\n /** Per-play word budget passed to `lintEmail`. */\n maxBodyWords: number;\n toEmail: (t: T) => string;\n /**\n * Enrichment / research / scrape phase. Owns all SDK calls that build\n * context for the draft. Use `standardEnrich` for the safeEnrich(+deepResearch)\n * shape; plays with browser/websearch context supply their own.\n */\n prepare: (t: T, dryRun: boolean) => Promise<Prepared<X>>;\n buildInputBlock: (t: T, prep: Prepared<X>, cfg: AppConfig) => string;\n prospectMeta: (t: T) => SendDraftedOpts[\"prospectMeta\"];\n metadata?: (t: T) => Record<string, unknown>;\n /**\n * Play-specific flags merged with the lint flags. Any non-empty flag set\n * holds the draft (sendDraftedEmail won't send when flags are present), so\n * this is how a play marks a target as draft-but-don't-auto-send for review\n * (e.g. luma-events flags `stale-event` for long-passed events).\n */\n extraFlags?: (t: T) => string[];\n /** Enroll the prospect in this play's cadence after a real send. */\n enrollCadence?: boolean;\n /** Extra fields merged onto the row when a target throws (e.g. jobPostHook). */\n errorExtra?: X;\n}\n\n/**\n * Run an email play over its targets. Behavior-preserving extraction of the\n * per-target loop that every email play used to hand-roll: enrich/research →\n * draft → lint → send → (optional) cadence enroll, with a per-target try/catch\n * so one bad target can't kill the batch.\n */\nexport async function runEmailPlay<T, X = Record<string, never>>(\n def: EmailPlayDef<T, X>,\n opts: {\n dryRun: boolean;\n targets: T[];\n /**\n * Optional per-target progress callback. Fires once per target after the\n * full prepare → draft → lint → send chain resolves (or throws + lands as\n * an errorDraft). The /api/run SSE handler uses this to emit `draft` +\n * `send` events live so the UI's progress counters tick as each target\n * finishes, instead of jumping from 0/N to N/N at the very end.\n *\n * Order: fires in completion order across the worker pool, not input\n * order. Consumers that need stable indexing read the `index` arg.\n */\n onProgress?: (index: number, draft: PlayDraft<T, X>) => void;\n },\n): Promise<{ drafted: Array<PlayDraft<T, X>> }> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n\n // Process targets in parallel (each is an LLM draft + send, ~5-90s). Drop to\n // serial when the batch has duplicate emails: sendDraftedEmail's per-(prospect,\n // play) step-0 dedupe is read-then-write, and only the serial order guarantees\n // a duplicate doesn't slip a second send through the window. Finder-drained\n // batches are already unique, so they get the full concurrency.\n //\n // Concurrency 6 (was 3): the per-target chain is mostly I/O bound on the\n // OneShot SDK + LLM provider, both of which handle parallel calls fine. With\n // the find→cache→/run cache-hit path warm, the residual draft+send time is\n // small enough that 6 workers comfortably halve wall-clock without tripping\n // SDK rate limits in observed runs.\n const emails = opts.targets.map((t) => def.toEmail(t).trim().toLowerCase());\n const hasDupeEmails = new Set(emails).size !== emails.length;\n const concurrency = hasDupeEmails ? 1 : 6;\n\n const drafted = await parallelMap(\n opts.targets,\n concurrency,\n async (target) => {\n try {\n const prep = await def.prepare(target, opts.dryRun);\n\n // Append SOCIAL PROOF block when any of the three optional fields is\n // set. Prompts treat it as conditional input — present only when set,\n // and the prompt picks ONE beat per email (never stacks).\n const proof = socialProofBlock();\n let inputBlock = proof\n ? `${def.buildInputBlock(target, prep, cfg)}\\n\\n${proof}`\n : def.buildInputBlock(target, prep, cfg);\n // Surface a real first name when extractable so the prompt can\n // occasionally open with \"Hey {firstName},\". Absent → prompt rule\n // says never invent a greeting; LLM dives into the Hook.\n const firstName = firstNameFrom(def.prospectMeta(target).name ?? null);\n if (firstName) {\n inputBlock = `${inputBlock}\\n\\nPROSPECT_FIRST_NAME: ${firstName}`;\n }\n const draft = await draftEmailFromPrompt({\n promptName: def.promptName,\n inputBlock,\n });\n\n const flags = [\n ...lintEmail(draft.subject, draft.body, def.maxBodyWords),\n ...(def.extraFlags?.(target) ?? []),\n ];\n\n const send = await sendDraftedEmail({\n playName: def.playName,\n to: def.toEmail(target),\n draft,\n flags,\n prospectMeta: def.prospectMeta(target),\n ...(def.metadata ? { metadata: def.metadata(target) } : {}),\n dryRun: opts.dryRun,\n });\n\n if (send.sent && def.enrollCadence) {\n const prospect = getLedger().findProspectByEmail(def.toEmail(target));\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: def.playName });\n }\n\n return {\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...prep.receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n ...(prep.enrichmentFailed ? { enrichmentFailed: true } : {}),\n ...(prep.extra ?? ({} as X)),\n } as PlayDraft<T, X>;\n } catch (err) {\n // Daily-cap deferral is not a per-target failure — propagate so the\n // caller (drain / SSE run) leaves remaining targets queued.\n if (isSendDeferred(err)) throw err;\n return {\n target,\n ...errorDraft((err as Error)?.message),\n ...(def.errorExtra ?? ({} as X)),\n } as PlayDraft<T, X>;\n }\n },\n // parallelMap's per-completion hook — forward through if the caller wired\n // a progress sink. Stays in completion order (not index order); the SSE\n // consumer keys by the `index` arg.\n opts.onProgress\n ? (_target, result, index) => opts.onProgress?.(index, result)\n : undefined,\n );\n\n return { drafted };\n}\n\n/**\n * The common `prepare` body for plays that personalize via `safeEnrich` (cached\n * by email, never throws) and, on real sends only, a `deepResearch` dossier.\n * Pass `research` only when you want the research call to fire — callers gate it\n * on `!dryRun` (and, for accelerator-batch, on a launch URL being present).\n */\nexport async function standardEnrich(opts: {\n playName: string;\n enrichInput: Parameters<typeof safeEnrich>[0];\n enrichSlice: number;\n research?: { topic: string; slice?: number };\n}): Promise<Prepared> {\n const receiptIds: number[] = [];\n\n const enr = await safeEnrich(opts.enrichInput, { playName: opts.playName });\n if (enr.receiptId) receiptIds.push(enr.receiptId);\n const enrichmentFailed = (enr.result as { status?: string }).status === \"failed\";\n let dossier = JSON.stringify(enr.result, null, 2).slice(0, opts.enrichSlice);\n\n if (opts.research) {\n const research = await deepResearch(\n { topic: opts.research.topic, depth: \"quick\" },\n { playName: opts.playName },\n );\n receiptIds.push(research.receiptId);\n dossier +=\n \"\\n\\n---\\n\\n\" +\n JSON.stringify(research.result, null, 2).slice(0, opts.research.slice ?? 4000);\n }\n\n return { receiptIds, dossier, ...(enrichmentFailed ? { enrichmentFailed: true } : {}) };\n}\n","import { loadConfig } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { getPriorStepsForProspect, type PriorStepRow } from \"./_cadence.ts\";\nimport { firstNameFrom, humanizeDraft, signatureDirective, socialProofBlock } from \"./_lib.ts\";\n\n/** Mirror triage.ts's truncation — inbound bodies can be huge (quoted chains). */\nconst INBOUND_BODY_MAX = 2000;\n\n/**\n * Drop the quoted prior-thread chain mail clients top-post beneath the new\n * reply. Without this, a blind head-truncation can keep 2000 chars of OUR\n * own quoted email and cut off the prospect's actual new text below it. Cuts\n * at the first attribution line (\"On <date>, <name> wrote:\") or the first run\n * of `>`-quoted lines — whichever comes first. Falls back to the full body\n * when no quote marker is found (plain replies, or clients we don't match).\n */\nexport function stripQuotedChain(body: string): string {\n const lines = body.split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trim();\n // Gmail/Apple/Outlook attribution line that precedes the quoted block.\n if (/^On\\b.*\\bwrote:$/.test(line)) return lines.slice(0, i).join(\"\\n\").trim();\n // A quoted line with real content above it — the chain has started.\n if (line.startsWith(\">\") && i > 0) return lines.slice(0, i).join(\"\\n\").trim();\n }\n return body.trim();\n}\n\nexport interface DraftInboxReplyInput {\n /** Normalized sender address of the inbound email. */\n fromEmail: string;\n /** Inbound subject (the reply keeps it as \"Re: …\" — only the body is drafted). */\n subject: string;\n /** Inbound plain-text body. */\n body: string;\n /** Prospect match, when the sender is a known prospect (name/company/play context). */\n matched?: {\n prospectId: number | null;\n name: string | null;\n company: string | null;\n playName: string | null;\n } | null;\n}\n\n/**\n * Draft a reply to an inbound prospect email, in the founder's voice. Same\n * scaffolding as cadence follow-ups (signature directive, social proof, prior\n * touches, humanizer autofixes) but answering THEIR message rather than\n * continuing a sequence. Returns the body only — the subject stays \"Re: …\".\n * Throws on LLM/provider errors; the route maps that to a 4xx message.\n */\nexport async function draftInboxReply(input: DraftInboxReplyInput): Promise<{ body: string }> {\n const cfg = loadConfig();\n const system = loadPrompt(\"reply-email\") + signatureDirective();\n\n const prior: PriorStepRow[] =\n input.matched?.prospectId && input.matched.playName\n ? getPriorStepsForProspect(input.matched.prospectId, input.matched.playName).filter(\n (r) => r.body !== null && r.body.length > 0,\n )\n : [];\n const priorBlock =\n prior.length > 0\n ? [\n \"PRIOR EMAILS (what you already sent this prospect — this is what they're replying to):\",\n ...prior.flatMap((r) => [\n `--- step ${r.stepIndex} (${r.label}) ---`,\n `Subject: ${r.subject}`,\n r.body!,\n ]),\n ].join(\"\\n\")\n : null;\n\n const proofBlock = socialProofBlock();\n const firstName = firstNameFrom(input.matched?.name ?? null);\n const user = [\n `FOUNDER: ${cfg.founderName ?? \"(unknown)\"}`,\n `PRODUCT: ${cfg.productOneLiner ?? \"(unknown)\"}`,\n `PROSPECT: ${input.matched?.name ?? \"(unknown)\"}`,\n `EMAIL: ${input.fromEmail}`,\n `COMPANY: ${input.matched?.company ?? \"(unknown)\"}`,\n ...(input.matched?.playName ? [`PLAY: ${input.matched.playName}`] : []),\n ...(priorBlock ? [\"\", priorBlock] : []),\n \"\",\n \"INBOUND EMAIL (the message you are answering):\",\n `Subject: ${input.subject}`,\n stripQuotedChain(input.body).slice(0, INBOUND_BODY_MAX),\n ...(proofBlock ? [\"\", proofBlock] : []),\n ...(firstName ? [\"\", `PROSPECT_FIRST_NAME: ${firstName}`] : []),\n ].join(\"\\n\");\n\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.6,\n maxTokens: 500,\n });\n const parsed = tryParseJsonObject<{ body?: string }>(res.content, {});\n const body = (parsed.body ?? \"\").trim();\n if (!body) throw new Error(\"the model returned an empty reply draft — try again\");\n // Same deterministic autofixes the outbound drafts get (em-dash, curly\n // quotes, emoji). humanizeDraft wants a subject — pass a dummy.\n return { body: humanizeDraft({ subject: \"x\", body }).body };\n}\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport interface AcceleratorBatchTarget {\n name: string;\n email: string;\n company: string;\n cohort: string;\n launchUrl?: string;\n productOneLiner?: string;\n linkedinUrl?: string;\n phone?: string;\n /** The SENDER's own cohort (peer angle). Stamped onto finder rows from the\n * trigger config so the row is self-contained; falls back to the run-level\n * option for manually-entered /run targets. */\n senderCohort?: string;\n /** Optional time-bound offer for the sender's cohort. Same fallback rules. */\n freeForCohortOffer?: string;\n}\n\nexport interface AcceleratorBatchRunOptions {\n dryRun: boolean;\n targets: AcceleratorBatchTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n /** Run-level fallback applied to any target that doesn't carry its own. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\ninterface AcceleratorBatchDraft {\n target: AcceleratorBatchTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"accelerator-batch\";\n\nexport function runAcceleratorBatch(\n opts: AcceleratorBatchRunOptions,\n): Promise<{ drafted: AcceleratorBatchDraft[] }> {\n // senderCohort / freeForCohortOffer are read target-first (finder rows carry\n // their own, stamped from trigger config) with the run-level option as a\n // fallback for manually-entered /run targets. Built per-call to close over\n // that fallback.\n const senderCohortFor = (t: AcceleratorBatchTarget): string =>\n (t.senderCohort?.trim() || opts.senderCohort || \"\").trim();\n const offerFor = (t: AcceleratorBatchTarget): string | undefined =>\n t.freeForCohortOffer ?? opts.freeForCohortOffer;\n const def: EmailPlayDef<AcceleratorBatchTarget> = {\n playName: PLAY_NAME,\n promptName: \"accelerator-batch-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email); deepResearch is\n // real-send only AND only when a launch URL is present to anchor it.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 3500,\n ...(!dryRun && t.launchUrl\n ? {\n research: {\n topic: `Recent public work and decisions by ${t.name} at ${t.company} (${t.cohort}). Pull launch context from ${t.launchUrl}.`,\n },\n }\n : {}),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SENDER COHORT: ${senderCohortFor(t) || \"(unspecified)\"}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `PROSPECT COHORT: ${t.cohort}`,\n `PROSPECT PRODUCT: ${t.productOneLiner ?? \"(unknown)\"}`,\n `LAUNCH URL: ${t.launchUrl ?? \"(none)\"}`,\n `FREE-FOR-COHORT OFFER: ${offerFor(t) ?? \"(no active offer for this cohort)\"}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the cohort match only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: `accelerator-${t.cohort}`,\n }),\n metadata: (t) => ({\n senderCohort: senderCohortFor(t),\n prospectCohort: t.cohort,\n }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 5,\n channel: \"email\",\n breakOnReply: true,\n label: \"single follow-up + breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [\n `PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`,\n ],\n }),\n },\n ],\n});\n","import { getLedger, isSendDeferred, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, errorDraft, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\n\nconst PLAY_NAME = \"breakup-revive\";\n\nexport interface BreakupReviveTarget {\n name: string | null;\n email: string;\n company: string | null;\n daysCold: number;\n lastEventAt: string | null;\n linkedinUrl?: string | null;\n phone?: string | null;\n}\n\nexport interface BreakupReviveOptions {\n dryRun: boolean;\n /**\n * When provided, skip the ledger scan and use these prospects directly.\n * The queue-based flow (`find breakup-revive` → `find drain breakup-revive`)\n * goes through this path. When omitted, fall back to scanning the ledger.\n */\n targets?: BreakupReviveTarget[];\n /** Min days since last activity to consider cold. Default 60. (Ledger-scan mode only.) */\n minDays?: number;\n /** Max days since last activity to consider revivable. Default 90. (Ledger-scan mode only.) */\n maxDays?: number;\n /** Hard cap on prospects to revive in one run. Default 25. */\n limit?: number;\n /** Optional value drop to lead with (a new feature, a benchmark, a case study you can offer). */\n valueDrop?: string;\n}\n\ninterface BreakupReviveDraft {\n prospectEmail: string | null;\n prospectName: string | null;\n daysCold: number;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nexport async function runBreakupRevive(\n opts: BreakupReviveOptions,\n): Promise<{ drafted: BreakupReviveDraft[] }> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n\n const targets = opts.targets ?? ledgerScanTargets(opts);\n const drafted: BreakupReviveDraft[] = [];\n\n for (const t of targets) {\n if (!t.email) continue;\n try {\n const draft = await draftEmailFromPrompt({\n promptName: \"breakup-revive-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name ?? \"(unknown)\"} at ${t.company ?? \"(unknown)\"}`,\n `DAYS SINCE LAST ACTIVITY: ${t.daysCold}`,\n `OPTIONAL VALUE DROP: ${opts.valueDrop ?? \"(none — go with a probe question instead)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 80);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: t.email,\n draft,\n flags,\n prospectMeta: {\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"breakup-revive\",\n },\n metadata: { daysCold: t.daysCold, lastEventAt: t.lastEventAt },\n dryRun: opts.dryRun,\n // Re-engaging an already-contacted cold prospect is the whole point —\n // opt out of the cross-play first-touch guard.\n allowRecontact: true,\n });\n\n drafted.push({\n prospectEmail: t.email,\n prospectName: t.name,\n daysCold: t.daysCold,\n subject: draft.subject,\n body: draft.body,\n receiptIds: send.receiptIds,\n sent: send.sent,\n flags,\n });\n } catch (err) {\n // Daily-cap deferral is not a per-target failure — abort the run so the\n // caller leaves remaining targets queued instead of stamping error drafts.\n if (isSendDeferred(err)) throw err;\n const stub = errorDraft((err as Error)?.message);\n drafted.push({\n prospectEmail: t.email,\n prospectName: t.name,\n daysCold: t.daysCold,\n subject: stub.subject,\n body: stub.body,\n receiptIds: stub.receiptIds,\n sent: stub.sent,\n flags: stub.flags,\n });\n }\n }\n\n return { drafted };\n}\n\nfunction ledgerScanTargets(opts: BreakupReviveOptions): BreakupReviveTarget[] {\n const ledger = getLedger();\n const cold = ledger.listColdProspects({\n minDaysSinceLastEvent: opts.minDays ?? 60,\n maxDaysSinceLastEvent: opts.maxDays ?? 90,\n ...(opts.limit ? { limit: opts.limit } : {}),\n });\n return cold\n .filter((p): p is typeof p & { email: string } => p.email != null)\n .map((p) => ({\n name: p.name,\n email: p.email,\n company: p.company,\n daysCold: p.last_event_at\n ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1000))\n : 0,\n lastEventAt: p.last_event_at,\n linkedinUrl: p.linkedin_url ?? null,\n phone: p.phone ?? null,\n }));\n}\n","import { browserTask } from \"@oneshot-gtm/core\";\nimport { emailDomain, safeEnrich } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"competitor-switch\";\n\nexport interface CompetitorSwitchTarget {\n name: string;\n email: string;\n company: string;\n competitor: string;\n /** Optional URL to scrape (G2 review page, BuiltWith page, public job post). */\n evidenceUrl?: string;\n /** Optional pre-supplied evidence string. */\n evidenceText?: string;\n /** Your product's specific advantage over this competitor (one fact). */\n yourEdge: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface CompetitorSwitchRunOptions {\n dryRun: boolean;\n targets: CompetitorSwitchTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n /** Skip the browser-scraping step even if evidenceUrl is set. */\n skipBrowserScrape?: boolean;\n}\n\ninterface CompetitorSwitchDraft {\n target: CompetitorSwitchTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n scrapedEvidence?: string;\n}\n\ntype CompetitorSwitchExtra = { scrapedEvidence?: string };\n\nexport function runCompetitorSwitch(\n opts: CompetitorSwitchRunOptions,\n): Promise<{ drafted: CompetitorSwitchDraft[] }> {\n const def: EmailPlayDef<CompetitorSwitchTarget, CompetitorSwitchExtra> = {\n playName: PLAY_NAME,\n promptName: \"competitor-switch-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let scrapedEvidence: string | undefined;\n\n // Enrich on both preview and real send (cached by email).\n const enr = await safeEnrich(\n {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n { playName: PLAY_NAME },\n );\n if (enr.receiptId) receiptIds.push(enr.receiptId);\n const enrichmentFailed = (enr.result as { status?: string }).status === \"failed\";\n const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n if (!dryRun) {\n // Skip the browserTask scrape when evidenceText was already supplied\n // (or when the founder explicitly opts out). Two reasons:\n // 1. The github-topics finder enqueues both — it builds evidenceText\n // from the manifest scan and sets evidenceUrl to the repo. Scraping\n // a code page for \"pain points\" returns nothing useful; the manifest-\n // derived stitch line IS the evidence.\n // 2. browserTask is the slowest call in the SDK (maxSteps:12, easily\n // 30s-3min on JS-heavy pages). Re-scraping when we already have\n // evidence wastes time + ~$0.30+ in browser-task spend.\n // The scrape still fires when the founder pasted only an evidenceUrl\n // (e.g. a G2 review page) — that's when extracting structured pain-\n // points actually pays off.\n const haveEvidenceText =\n typeof t.evidenceText === \"string\" && t.evidenceText.trim().length > 0;\n if (t.evidenceUrl && !opts.skipBrowserScrape && !haveEvidenceText) {\n const browse = await browserTask(\n {\n 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.`,\n startUrl: t.evidenceUrl,\n outputSchema: {\n type: \"object\",\n properties: {\n pain_points: { type: \"array\", items: { type: \"string\" } },\n wished_features: { type: \"array\", items: { type: \"string\" } },\n use_case_context: { type: \"string\" },\n },\n },\n maxSteps: 12,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(browse.receiptId);\n scrapedEvidence =\n typeof browse.result.output === \"string\"\n ? browse.result.output\n : JSON.stringify(browse.result.output ?? {});\n }\n }\n\n return {\n receiptIds,\n dossier,\n ...(enrichmentFailed ? { enrichmentFailed: true } : {}),\n ...(scrapedEvidence ? { extra: { scrapedEvidence } } : {}),\n };\n },\n buildInputBlock: (t, prep, cfg) => {\n const evidence = prep.extra?.scrapedEvidence ?? t.evidenceText ?? \"(no evidence supplied)\";\n return [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `COMPETITOR: ${t.competitor}`,\n `EVIDENCE: ${evidence}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\");\n },\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"competitor-switch\",\n }),\n metadata: (t) => ({ competitor: t.competitor, evidenceUrl: t.evidenceUrl ?? null }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"competitor-switch-followup\",\n contextLines: [\n `PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`,\n ],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`],\n }),\n },\n ],\n});\n","import { webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"hiring-signal\";\n\nexport interface HiringSignalTarget {\n /** Hiring manager / function head receiving the email. */\n name: string;\n email: string;\n company: string;\n /** Job title to search for. */\n jobTitle: string;\n /** Optional direct URL to a known job post — skips the search. */\n jobPostUrl?: string;\n /** Your one-line claim about how your product compresses ramp time for this role. */\n yourClaim: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface HiringSignalRunOptions {\n dryRun: boolean;\n targets: HiringSignalTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n /** Skip the web-search/read steps. */\n skipScrape?: boolean;\n}\n\ninterface HiringSignalDraft {\n target: HiringSignalTarget;\n subject: string;\n body: string;\n jobPostHook: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\ntype HiringSignalExtra = { jobPostHook: string };\n\nconst NO_HOOK = \"(no specific job post phrase scraped)\";\n\nexport function runHiringSignal(\n opts: HiringSignalRunOptions,\n): Promise<{ drafted: HiringSignalDraft[] }> {\n const def: EmailPlayDef<HiringSignalTarget, HiringSignalExtra> = {\n playName: PLAY_NAME,\n promptName: \"hiring-signal-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n errorExtra: { jobPostHook: \"(error)\" },\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let jobPostHook = NO_HOOK;\n\n if (!dryRun) {\n let jobUrl: string | undefined = t.jobPostUrl;\n if (!jobUrl && !opts.skipScrape) {\n const search = await webSearch(\n {\n query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,\n maxResults: 5,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(search.receiptId);\n jobUrl = search.result.results[0]?.url;\n }\n\n if (jobUrl) {\n const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME });\n receiptIds.push(read.receiptId);\n const md = read.result.markdown ?? \"\";\n // Find a load-bearing phrase: first non-trivial sentence after 'About the role' or 'Responsibilities' if present.\n const hookMatch = md.match(\n /(?:About the role|Responsibilities|Requirements|What you[' ]?ll do)[^\\n]*\\n+([\\s\\S]{40,300})/i,\n );\n jobPostHook = (hookMatch?.[1] ?? md.slice(0, 400)).replace(/\\s+/g, \" \").trim();\n }\n }\n\n return { receiptIds, dossier: \"\", extra: { jobPostHook } };\n },\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `JOB TITLE: ${t.jobTitle}`,\n `JOB POST HOOK (real phrase from the post): ${prep.extra?.jobPostHook ?? NO_HOOK}`,\n `YOUR CLAIM: ${t.yourClaim}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"hiring-signal\",\n }),\n metadata: (t) => ({ jobTitle: t.jobTitle, jobPostUrl: t.jobPostUrl ?? null }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"hiring-signal-followup\",\n contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: hiring-signal. Final breakup.`],\n }),\n },\n ],\n});\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport interface JobChangeTarget {\n name: string;\n email: string;\n newRole: string;\n newCompany: string;\n previousRole?: string;\n previousCompany?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface JobChangeRunOptions {\n dryRun: boolean;\n targets: JobChangeTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\ninterface JobChangeDraft {\n target: JobChangeTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"job-change\";\n\nconst jobChangeDef: EmailPlayDef<JobChangeTarget> = {\n playName: PLAY_NAME,\n promptName: \"job-change-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 4000,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `Public posts, talks, and recent decisions by ${t.name} (joined ${t.newCompany} as ${t.newRole}, formerly ${t.previousRole ?? \"?\"} at ${t.previousCompany ?? \"?\"})`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name}`,\n `NEW ROLE: ${t.newRole} at ${t.newCompany}`,\n `PREVIOUS: ${t.previousRole ?? \"unknown\"} at ${t.previousCompany ?? \"unknown\"}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the trigger only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.newCompany,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"job-change\",\n }),\n metadata: (t) => ({ newRole: t.newRole, newCompany: t.newCompany }),\n};\n\nexport function runJobChange(opts: JobChangeRunOptions): Promise<{ drafted: JobChangeDraft[] }> {\n return runEmailPlay(jobChangeDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 5,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"job-change-followup\",\n contextLines: [\n `CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`,\n ],\n }),\n },\n {\n dayOffset: 9, // ~14 days from enrollment\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: job-change. Sender is closing the file.`],\n }),\n },\n ],\n});\n","import { emailDomain } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\n\nconst PLAY_NAME = \"luma-events\";\n\n/**\n * Past this many days, a passed event's guest-list signal is stale: we still\n * draft a (retrospective) email but hold it behind a `stale-event` flag for\n * founder review instead of auto-sending. Mirrored loosely by the queue UI's\n * \"· passed\" treatment (apps/web/src/lib/cn.ts).\n */\nconst STALE_AFTER_DAYS = 14;\n\n/**\n * Classify an event's ISO date relative to now and produce a concrete human\n * phrase for the prompt. Three states drive the copy + send decision:\n * - \"upcoming\": today or future → forward-looking pitch, auto-sends.\n * - \"past\": within STALE_AFTER_DAYS behind → retrospective pitch, auto-sends.\n * - \"stale\": further back → retrospective pitch but HELD (see runLumaEvents\n * extraFlags). Signal too old to cold-open on without a human glance.\n * The phrase keeps the prompt input concrete so the LLM never does calendar\n * math (and can't infer a future weekday from a date that's already gone —\n * the bug this replaces: a passed Friday read back as \"this Friday\").\n */\nfunction describeEventDate(iso: string): {\n status: \"upcoming\" | \"past\" | \"stale\";\n phrase: string;\n} {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return { status: \"upcoming\", phrase: iso };\n const dayMs = 24 * 3600 * 1000;\n const days = Math.round((d.getTime() - Date.now()) / dayMs);\n const weekday = d.toLocaleDateString(\"en-US\", { weekday: \"long\" });\n const absolute = d.toLocaleDateString(\"en-US\", {\n weekday: \"short\",\n month: \"short\",\n day: \"numeric\",\n });\n\n // Future / today: forward-looking.\n if (days >= 0) {\n if (days === 0) return { status: \"upcoming\", phrase: \"today\" };\n if (days === 1) return { status: \"upcoming\", phrase: \"tomorrow\" };\n if (days <= 6) return { status: \"upcoming\", phrase: `this ${weekday}` };\n if (days <= 13) return { status: \"upcoming\", phrase: `next ${weekday}` };\n return { status: \"upcoming\", phrase: absolute };\n }\n\n // Past: retrospective. Beyond the staleness window we still draft, but hold.\n const status = days < -STALE_AFTER_DAYS ? \"stale\" : \"past\";\n if (status === \"stale\") return { status, phrase: absolute };\n if (days === -1) return { status, phrase: \"yesterday\" };\n if (days >= -6) return { status, phrase: `last ${weekday}` };\n return { status, phrase: \"last week\" };\n}\n\nexport interface LumaEventsTarget {\n name: string;\n email: string;\n company?: string;\n /** One-line bio / role pulled from the prospect's Luma profile (e.g. \"Founder @ AcmeAI\"). */\n attendeeBio?: string;\n /**\n * Relationship to the event: \"Host\" (organizer) vs \"Guest\" (featured\n * attendee). Surfaced in the queue for review and fed to the prompt so a\n * host isn't pitched as if they're merely attending their own event.\n */\n role?: string;\n /** Event display name, e.g. \"SF AI Builders Meetup\". */\n eventTitle: string;\n /**\n * Short summary of what the event is about (from the Luma page). Grounds the\n * draft's TOPIC so the Offer/CTA aren't guessed from a vague title. Founder\n * reference only — the prompt won't quote it verbatim. Absent for events\n * found before this was wired (falls back to title-only inference).\n */\n eventDescription?: string;\n /** ISO date or datetime; UI/prompt humanizes to \"next Tuesday\". */\n eventDate: string;\n /** City or \"Online\". */\n eventCity: string;\n /** luma.com/<slug>; founder reference only — prompt won't paste it in the body. */\n eventUrl: string;\n /** Founder-provided one-liner about why their product helps attendees of events like this. */\n yourEdge: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface LumaEventsRunOptions {\n dryRun: boolean;\n targets: LumaEventsTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\ninterface LumaEventsDraft {\n target: LumaEventsTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst lumaEventsDef: EmailPlayDef<LumaEventsTarget> = {\n playName: PLAY_NAME,\n promptName: \"luma-events-email\",\n maxBodyWords: 150,\n // One-touch: events are time-sensitive — a multi-touch chase reads worse\n // than silence after the event passes. Matches show-hn / podcast-guest /\n // repo-interest.\n toEmail: (t) => t.email,\n // Enrich on preview + send (cached by email). No deepResearch — the event\n // attendance itself is the load-bearing signal.\n prepare: (t) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n enrichSlice: 3500,\n }),\n buildInputBlock: (t, prep, cfg) => {\n const when = describeEventDate(t.eventDate);\n // \"stale\" still reads as PAST to the prompt — it drafts retrospectively;\n // the staleness only changes whether we hold (see extraFlags below).\n const timing =\n when.status === \"upcoming\"\n ? \"UPCOMING\"\n : \"PAST — already happened, write retrospectively (do NOT use future tense)\";\n return [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name}${t.company ? ` at ${t.company}` : \"\"}`,\n `ATTENDEE BIO/ROLE: ${t.attendeeBio ?? \"(none)\"}`,\n // \"Host\" = they RUN the event — never write as if they're merely going.\n `RELATIONSHIP TO EVENT: ${t.role ?? \"(unknown — assume attendee)\"}`,\n `EVENT TITLE: ${t.eventTitle}`,\n // Collapse whitespace defensively: the description is already flattened\n // upstream, but the LLM-extract path may still return newlines, and a raw\n // newline here would split the line-delimited input block mid-field.\n `EVENT ABOUT: ${(t.eventDescription ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 600) || \"(none)\"}`,\n `EVENT CITY: ${t.eventCity}`,\n `EVENT DATE: ${when.phrase} (${t.eventDate})`,\n `EVENT TIMING: ${timing}`,\n `EVENT URL: ${t.eventUrl}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\");\n },\n // Hold (don't auto-send) drafts for events past the staleness window — the\n // guest-list signal is too old to cold-open on without a founder glance. A\n // non-empty flags array is what holds a draft (see _lib.ts sendDraftedEmail).\n extraFlags: (t) => (describeEventDate(t.eventDate).status === \"stale\" ? [\"stale-event\"] : []),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company ?? null,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"luma-events\",\n }),\n metadata: (t) => ({ eventTitle: t.eventTitle, eventUrl: t.eventUrl, eventDate: t.eventDate }),\n};\n\nexport function runLumaEvents(opts: LumaEventsRunOptions): Promise<{ drafted: LumaEventsDraft[] }> {\n return runEmailPlay(lumaEventsDef, opts);\n}\n","import { webSearch } from \"@oneshot-gtm/core\";\nimport { type EmailPlayDef, runEmailPlay } from \"./_run-play.ts\";\nimport { registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"podcast-guest\";\n\nexport interface PodcastGuestTarget {\n name: string;\n email: string;\n company: string;\n /** Podcast name (e.g. \"Latent Space\", \"Lenny's Podcast\"). */\n podcast: string;\n /** Episode title or descriptor. */\n episodeTitle: string;\n /** A specific quote or timestamped moment that you'll reference. Required. */\n hookQuote: string;\n /** ONE-sentence reason the moment matters to your work. */\n bridge?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface PodcastGuestRunOptions {\n dryRun: boolean;\n targets: PodcastGuestTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n /** Skip the optional web-search dossier enrichment. */\n skipSearch?: boolean;\n}\n\nexport interface PodcastGuestDraft {\n target: PodcastGuestTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nexport function runPodcastGuest(\n opts: PodcastGuestRunOptions,\n): Promise<{ drafted: PodcastGuestDraft[] }> {\n const def: EmailPlayDef<PodcastGuestTarget> = {\n playName: PLAY_NAME,\n promptName: \"podcast-guest-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n prepare: async (t, dryRun) => {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!dryRun && !opts.skipSearch) {\n const s = await webSearch(\n {\n query: `${t.name} ${t.podcast} \"${t.episodeTitle}\" notes OR transcript`,\n maxResults: 3,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(s.receiptId);\n dossier = s.result.results\n .slice(0, 2)\n .map((r) => `- ${r.title}: ${r.description}`)\n .join(\"\\n\");\n }\n\n return { receiptIds, dossier };\n },\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `PODCAST: ${t.podcast}`,\n `EPISODE: ${t.episodeTitle}`,\n `HOOK QUOTE: ${t.hookQuote}`,\n `BRIDGE TO YOUR WORK: ${t.bridge ?? \"(none — keep the email purely about their point)\"}`,\n `EXTRA CONTEXT FROM SEARCH:\\n${prep.dossier || \"(none)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"podcast-guest\",\n }),\n metadata: (t) => ({ podcast: t.podcast, episodeTitle: t.episodeTitle }),\n };\n\n return runEmailPlay(def, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [], // Intentionally empty — podcast-guest is one-touch only.\n});\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nexport interface PostFundingTarget {\n name: string;\n email: string;\n company: string;\n round: string;\n amountUsd: number;\n leadInvestor?: string;\n sourceUrl: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface PostFundingRunOptions {\n dryRun: boolean;\n targets: PostFundingTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\nexport interface PostFundingDraft {\n target: PostFundingTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst PLAY_NAME = \"post-funding\";\n\nconst postFundingDef: EmailPlayDef<PostFundingTarget> = {\n playName: PLAY_NAME,\n promptName: \"post-funding-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n ...(t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {}),\n name: t.name,\n },\n enrichSlice: 3500,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `${t.company} ${t.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${t.sourceUrl}`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `ROUND: ${t.round} ($${t.amountUsd.toLocaleString()})`,\n `LEAD INVESTOR: ${t.leadInvestor ?? \"(unspecified)\"}`,\n `SOURCE: ${t.sourceUrl}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the round details only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"post-funding\",\n }),\n metadata: (t) => ({\n round: t.round,\n amountUsd: t.amountUsd,\n leadInvestor: t.leadInvestor,\n }),\n};\n\nexport function runPostFunding(\n opts: PostFundingRunOptions,\n): Promise<{ drafted: PostFundingDraft[] }> {\n return runEmailPlay(postFundingDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 9,\n channel: \"email\",\n breakOnReply: true,\n label: \"case-study follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"post-funding-followup\",\n contextLines: [\n `CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`,\n ],\n }),\n },\n {\n dayOffset: 9, // ~21 days from enrollment\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [`PLAY: post-funding.`],\n }),\n },\n ],\n});\n","import { emailDomain } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"repo-interest\";\n\nexport interface RepoInterestTarget {\n name: string;\n email: string;\n company: string;\n /** \"owner/name\" of the repo they starred (an adjacent/category tool, not a competitor). */\n repo: string;\n /** Display name for the repo (e.g. \"MCP servers\"); falls back to `repo`. */\n repoLabel?: string;\n /** One fact about how your product helps someone working in this space. */\n yourEdge: string;\n /**\n * Optional: one true line on why THIS repo is notable + the respectful\n * bridge to your offer. Used as a peer-level shared-taste nod (never\n * flattery) that also shapes how the offer is framed.\n */\n repoEdge?: string;\n /** The repo URL — founder reference only. */\n evidenceUrl?: string;\n linkedinUrl?: string;\n phone?: string;\n /** Candidate's GitHub login — kept on the payload so a future regenerate can\n * re-fetch their repos if we ever want it. Not consumed by the prompt today. */\n candidateLogin?: string;\n /**\n * Candidate's own top public repos (sorted by recent push, forks excluded).\n * Optional context fed to the prompt — the LLM picks at most one to weave\n * as shared-taste evidence, or ignores when nothing fits. Absent / empty =\n * the prompt's no-candidate-repos path kicks in.\n */\n candidateRepos?: Array<{\n name: string;\n description: string | null;\n language: string | null;\n }>;\n}\n\nexport interface RepoInterestRunOptions {\n dryRun: boolean;\n targets: RepoInterestTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\nexport interface RepoInterestDraft {\n target: RepoInterestTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst repoInterestDef: EmailPlayDef<RepoInterestTarget> = {\n playName: PLAY_NAME,\n promptName: \"repo-interest-email\",\n // 150 across all plays — generous safety net. The prompt-side AIM stays\n // tight (under ~90 reads tighter); the lint just stops gating drafts that\n // miss the aim by a few words. Real run-on slop still gets flagged.\n maxBodyWords: 150,\n // Two-touch: the intro plus one soft day-3 ping (no breakup). A peer who\n // starred an adjacent repo earns a single gentle nudge, not a full chase.\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on preview + send (cached by email). No deepResearch — the starred\n // repo is the load-bearing signal, like stack-consolidation's vendor stack.\n prepare: (t) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n enrichSlice: 3500,\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `STARRED REPO: ${t.repoLabel ?? t.repo}`,\n `YOUR EDGE: ${t.yourEdge}`,\n ...(t.repoEdge\n ? [`WHY THIS REPO IS NOTABLE (peer nod + how your offer fits — see prompt): ${t.repoEdge}`]\n : []),\n ...(Array.isArray(t.candidateRepos) && t.candidateRepos.length > 0\n ? [\n `CANDIDATE REPOS (their public work, sorted by recent push):`,\n ...t.candidateRepos.map(\n (r) =>\n `- ${r.name}${r.language ? ` [${r.language}]` : \"\"}: ${r.description ?? \"(no description)\"}`,\n ),\n ]\n : []),\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"repo-interest\",\n }),\n metadata: (t) => ({ repo: t.repo }),\n};\n\nexport function runRepoInterest(\n opts: RepoInterestRunOptions,\n): Promise<{ drafted: RepoInterestDraft[] }> {\n return runEmailPlay(repoInterestDef, opts);\n}\n\n// Two-touch cadence: one soft day-3 ping, no breakup. Mirrors\n// stack-consolidation's structure minus the final breakup step.\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"repo-interest-followup\",\n contextLines: [\n `PLAY: repo-interest. Day-3 soft nudge after the peer-to-peer intro about a repo they starred.`,\n ],\n }),\n },\n ],\n});\n","import { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nexport { receiptUrls } from \"./_lib.ts\";\n\nexport interface ShowHnTarget {\n postTitle: string;\n postUrl: string;\n founderName: string;\n founderEmail: string;\n hookSummary: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface ShowHnRunOptions {\n dryRun: boolean;\n targets: ShowHnTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\nexport interface ShowHnRunResult {\n drafted: Array<{\n target: ShowHnTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n }>;\n}\n\nconst PLAY_NAME = \"show-hn\";\n\nconst showHnDef: EmailPlayDef<ShowHnTarget> = {\n playName: PLAY_NAME,\n promptName: \"show-hn-email\",\n maxBodyWords: 150,\n toEmail: (t) => t.founderEmail,\n // Enrich on both preview and real send (cached by email) so the reviewed\n // draft is personalized; the heavier deepResearch stays real-send only.\n prepare: (t, dryRun) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: { email: t.founderEmail, name: t.founderName },\n enrichSlice: 3500,\n ...(dryRun\n ? {}\n : {\n research: {\n topic: `Recent public work and engineering decisions by ${t.founderName} on ${t.postTitle}`,\n },\n }),\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SHOW HN: ${t.postTitle}`,\n `URL: ${t.postUrl}`,\n `HOOK: ${t.hookSummary}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run; rely on the hook only)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.founderName,\n email: t.founderEmail,\n company: extractCompany(t.postTitle),\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"show-hn\",\n }),\n metadata: (t) => ({ postUrl: t.postUrl, postTitle: t.postTitle }),\n};\n\nexport function runShowHn(opts: ShowHnRunOptions): Promise<ShowHnRunResult> {\n return runEmailPlay(showHnDef, opts);\n}\n\nfunction extractCompany(title: string): string | null {\n const m = title.match(/Show HN:\\s*([^\\s—–:|-]+)/i);\n return m ? (m[1] ?? null) : null;\n}\n","import { emailDomain } from \"./_lib.ts\";\nimport { type EmailPlayDef, runEmailPlay, standardEnrich } from \"./_run-play.ts\";\nimport { buildFollowUpEmail, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"stack-consolidation\";\n\nexport interface StackConsolidationTarget {\n name: string;\n email: string;\n company: string;\n /** Comma-separated list of API vendors detected in the repo. */\n vendorStack: string;\n /** How your product collapses the vendor sprawl (one fact). */\n yourEdge: string;\n /** Optional source URL (the repo) for the founder's reference. */\n evidenceUrl?: string;\n linkedinUrl?: string;\n phone?: string;\n}\n\nexport interface StackConsolidationRunOptions {\n dryRun: boolean;\n targets: StackConsolidationTarget[];\n /** Per-target progress hook installed by /api/run SSE handler. */\n onProgress?: (\n index: number,\n draft: { subject: string; body: string; flags: string[]; sent: boolean; receiptIds: number[] },\n ) => void;\n}\n\nexport interface StackConsolidationDraft {\n target: StackConsolidationTarget;\n subject: string;\n body: string;\n receiptIds: number[];\n sent: boolean;\n flags: string[];\n}\n\nconst stackConsolidationDef: EmailPlayDef<StackConsolidationTarget> = {\n playName: PLAY_NAME,\n promptName: \"stack-consolidation-email\",\n maxBodyWords: 150,\n enrollCadence: true,\n toEmail: (t) => t.email,\n // Enrich on both preview and real send (cached by email). No deepResearch —\n // the manifest-derived vendor stack is the load-bearing signal here.\n prepare: (t) =>\n standardEnrich({\n playName: PLAY_NAME,\n enrichInput: {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: emailDomain(t.email),\n },\n enrichSlice: 3500,\n }),\n buildInputBlock: (t, prep, cfg) =>\n [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `STACK: ${t.vendorStack}`,\n `YOUR EDGE: ${t.yourEdge}`,\n `DOSSIER:\\n${prep.dossier || \"(dry-run)\"}`,\n ].join(\"\\n\"),\n prospectMeta: (t) => ({\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"stack-consolidation\",\n }),\n metadata: (t) => ({ vendorStack: t.vendorStack, evidenceUrl: t.evidenceUrl ?? null }),\n};\n\nexport function runStackConsolidation(\n opts: StackConsolidationRunOptions,\n): Promise<{ drafted: StackConsolidationDraft[] }> {\n return runEmailPlay(stackConsolidationDef, opts);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"value follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"stack-consolidation-followup\",\n contextLines: [\n `PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`,\n ],\n }),\n },\n {\n dayOffset: 8,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"breakup-email\",\n contextLines: [\n `PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`,\n ],\n }),\n },\n ],\n});\n","import { type AcceleratorBatchTarget, runAcceleratorBatch } from \"./accelerator-batch.ts\";\nimport { type BreakupReviveTarget, runBreakupRevive } from \"./breakup-revive.ts\";\nimport { type CompetitorSwitchTarget, runCompetitorSwitch } from \"./competitor-switch.ts\";\nimport { type HiringSignalTarget, runHiringSignal } from \"./hiring-signal.ts\";\nimport { type JobChangeTarget, runJobChange } from \"./job-change.ts\";\nimport { type LumaEventsTarget, runLumaEvents } from \"./luma-events.ts\";\nimport { type PodcastGuestTarget, runPodcastGuest } from \"./podcast-guest.ts\";\nimport { type PostFundingTarget, runPostFunding } from \"./post-funding.ts\";\nimport { type RepoInterestTarget, runRepoInterest } from \"./repo-interest.ts\";\nimport { type ShowHnTarget, runShowHn } from \"./show-hn.ts\";\nimport { type StackConsolidationTarget, runStackConsolidation } from \"./stack-consolidation.ts\";\n\n/**\n * The fields every play runner's drafted row exposes. Callers (the SSE /run\n * endpoint and the queue drainer) read only these — `target`/`scrapedEvidence`/\n * `jobPostHook`/etc. are extra and ignored here.\n */\nexport interface DraftedRow {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n /** Enrichment SDK failed — draft built from payload only (non-blocking; surfaced on /queue). */\n enrichmentFailed?: boolean;\n}\n\n/** Run-level options a play may consume. `targets` is play-specific JSON. */\nexport interface PlayRunInput {\n dryRun: boolean;\n targets: unknown[];\n /** Required by accelerator-batch. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n /**\n * Optional per-target progress callback. Fires AFTER each target's full\n * prepare → draft → lint → send chain resolves (in completion order, not\n * input order). The /api/run SSE handler installs this so the UI's\n * counters tick from 0/N → N/N as targets finish, instead of jumping at\n * the end. Plays that don't use `runEmailPlay` (e.g. breakup-revive's\n * custom loop) silently ignore this field — they still work, just without\n * live ticks.\n */\n onProgress?: (index: number, draft: DraftedRow) => void;\n}\n\nexport interface PlayDispatch {\n run: (o: PlayRunInput) => Promise<{ drafted: DraftedRow[] }>;\n}\n\n/**\n * Single source of truth mapping a play name → its runner. Both the server's\n * `/api/run` dispatch and the queue drainer look plays up here, so adding a\n * play means registering it once (its file + this table) instead of editing\n * two parallel switch statements that silently drifted apart.\n */\n// All onProgress callbacks are DraftedRow-typed; the per-play wrappers'\n// own draft types (RepoInterestDraft, ShowHnDraft, …) all structurally\n// satisfy DraftedRow, so the cast inside each forward is safe.\ntype PlayProgressFn = (index: number, draft: DraftedRow) => void;\nconst progressOpt = (o: PlayRunInput): { onProgress?: PlayProgressFn } =>\n o.onProgress ? { onProgress: o.onProgress } : {};\n\nexport const PLAYS: Record<string, PlayDispatch> = {\n \"show-hn\": {\n run: (o) =>\n runShowHn({\n dryRun: o.dryRun,\n targets: o.targets as ShowHnTarget[],\n ...progressOpt(o),\n }),\n },\n \"job-change\": {\n run: (o) =>\n runJobChange({\n dryRun: o.dryRun,\n targets: o.targets as JobChangeTarget[],\n ...progressOpt(o),\n }),\n },\n \"post-funding\": {\n run: (o) =>\n runPostFunding({\n dryRun: o.dryRun,\n targets: o.targets as PostFundingTarget[],\n ...progressOpt(o),\n }),\n },\n \"accelerator-batch\": {\n run: (o) =>\n runAcceleratorBatch({\n dryRun: o.dryRun,\n targets: o.targets as AcceleratorBatchTarget[],\n // Run-level fallback for manual /run targets; finder rows carry their own.\n ...(o.senderCohort ? { senderCohort: o.senderCohort } : {}),\n ...(o.freeForCohortOffer ? { freeForCohortOffer: o.freeForCohortOffer } : {}),\n ...progressOpt(o),\n }),\n },\n \"hiring-signal\": {\n run: (o) =>\n runHiringSignal({\n dryRun: o.dryRun,\n targets: o.targets as HiringSignalTarget[],\n ...progressOpt(o),\n }),\n },\n \"podcast-guest\": {\n run: (o) =>\n runPodcastGuest({\n dryRun: o.dryRun,\n targets: o.targets as PodcastGuestTarget[],\n ...progressOpt(o),\n }),\n },\n \"competitor-switch\": {\n run: (o) =>\n runCompetitorSwitch({\n dryRun: o.dryRun,\n targets: o.targets as CompetitorSwitchTarget[],\n ...progressOpt(o),\n }),\n },\n \"stack-consolidation\": {\n run: (o) =>\n runStackConsolidation({\n dryRun: o.dryRun,\n targets: o.targets as StackConsolidationTarget[],\n ...progressOpt(o),\n }),\n },\n \"repo-interest\": {\n run: (o) =>\n runRepoInterest({\n dryRun: o.dryRun,\n targets: o.targets as RepoInterestTarget[],\n ...progressOpt(o),\n }),\n },\n \"luma-events\": {\n run: (o) =>\n runLumaEvents({\n dryRun: o.dryRun,\n targets: o.targets as LumaEventsTarget[],\n ...progressOpt(o),\n }),\n },\n \"breakup-revive\": {\n // Custom loop (not runEmailPlay). Silently ignores onProgress for now;\n // counters will jump at the end. Acceptable until breakup-revive grows\n // a parallelMap-style worker pool.\n run: (o) => runBreakupRevive({ dryRun: o.dryRun, targets: o.targets as BreakupReviveTarget[] }),\n },\n};\n\nexport function isSupportedPlay(name: string): boolean {\n return Object.prototype.hasOwnProperty.call(PLAYS, name);\n}\n","import { getLedger, isSendDeferred, loadConfig, sendSms } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { draftEmailFromPrompt, errorDraft, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, registerSequence } from \"./_cadence.ts\";\n\nconst PLAY_NAME = \"demo-no-show\";\n\nexport interface DemoNoShowTarget {\n name: string;\n email: string;\n phone?: string;\n company: string;\n missedAt: string;\n rescheduleLink: string;\n whatTheyWanted?: string;\n linkedinUrl?: string;\n}\n\nexport interface DemoNoShowRunOptions {\n dryRun: boolean;\n targets: DemoNoShowTarget[];\n /** Skip the SMS step (default: send if phone is present). */\n skipSms?: boolean;\n}\n\nexport interface DemoNoShowResult {\n outcomes: Array<{\n target: DemoNoShowTarget;\n sms: { message: string; sent: boolean } | null;\n email: { subject: string; body: string; sent: boolean; flags: string[] };\n receiptIds: number[];\n }>;\n}\n\nexport async function runDemoNoShow(opts: DemoNoShowRunOptions): Promise<DemoNoShowResult> {\n const cfg = loadConfig();\n if (!cfg.founderName || !cfg.productOneLiner) {\n throw new Error(\"founder profile incomplete. Run: oneshot-gtm config founder\");\n }\n const outcomes: DemoNoShowResult[\"outcomes\"] = [];\n\n for (const t of opts.targets) {\n try {\n const receiptIds: number[] = [];\n\n // SMS first (same-day)\n let smsResult: DemoNoShowResult[\"outcomes\"][number][\"sms\"] = null;\n if (!opts.skipSms && t.phone) {\n const sms = await draftSmsBody(cfg.founderName, cfg.productOneLiner, t);\n let sent = false;\n if (!opts.dryRun && sms.length > 0 && sms.length <= 320) {\n const r = await sendSms({ to: t.phone, message: sms }, { playName: PLAY_NAME });\n receiptIds.push(r.receiptId);\n sent = true;\n }\n smsResult = { message: sms, sent };\n }\n\n // Same-day email\n const draft = await draftEmailFromPrompt({\n promptName: \"demo-no-show-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${t.name} at ${t.company}`,\n `MISSED AT: ${t.missedAt}`,\n `RESCHEDULE LINK: ${t.rescheduleLink}`,\n `WHAT THEY WANTED: ${t.whatTheyWanted ?? \"(not captured at booking)\"}`,\n ].join(\"\\n\"),\n });\n const flags = lintEmail(draft.subject, draft.body, 100);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: t.email,\n draft,\n flags,\n prospectMeta: {\n name: t.name,\n email: t.email,\n company: t.company,\n linkedin_url: t.linkedinUrl ?? null,\n phone: t.phone ?? null,\n source: \"demo-no-show\",\n },\n metadata: { missedAt: t.missedAt, rescheduleLink: t.rescheduleLink },\n dryRun: opts.dryRun,\n });\n receiptIds.push(...send.receiptIds);\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(t.email);\n if (prospect) {\n enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n }\n\n outcomes.push({\n target: t,\n sms: smsResult,\n email: {\n subject: draft.subject,\n body: draft.body,\n sent: send.sent,\n flags,\n },\n receiptIds,\n });\n } catch (err) {\n // Daily-cap deferral is not a per-target failure — abort so remaining\n // targets stay queued instead of getting error drafts.\n if (isSendDeferred(err)) throw err;\n const stub = errorDraft((err as Error)?.message);\n outcomes.push({\n target: t,\n sms: null,\n email: { subject: stub.subject, body: stub.body, sent: stub.sent, flags: stub.flags },\n receiptIds: stub.receiptIds,\n });\n }\n }\n\n return { outcomes };\n}\n\nasync function draftSmsBody(\n founderName: string,\n productOneLiner: string,\n target: DemoNoShowTarget,\n): Promise<string> {\n const system = loadPrompt(\"demo-no-show-sms\");\n const user = [\n `FOUNDER: ${founderName.split(/\\s+/)[0]}`,\n `PRODUCT: ${productOneLiner}`,\n `PROSPECT: ${target.name.split(/\\s+/)[0]}`,\n `MISSED AT: ${target.missedAt}`,\n ].join(\"\\n\");\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.5,\n maxTokens: 200,\n });\n const parsed = tryParseJsonObject<{ message?: string }>(res.content, {});\n return (parsed.message ?? \"\").trim();\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 3,\n channel: \"email\",\n breakOnReply: true,\n label: \"day-3 follow-up\",\n builder: buildFollowUpEmail({\n playName: PLAY_NAME,\n promptName: \"demo-no-show-followup\",\n contextLines: [`PLAY: demo-no-show day-3 follow-up. After this, drop the lead.`],\n }),\n },\n ],\n});\n","import { getLedger, isDraining, logEvent } from \"@oneshot-gtm/core\";\nimport {\n getPriorStepsBulk,\n nextStepInfo,\n playFollowupCount,\n previewCadenceStep,\n previewCadenceStepBatch,\n sendCadenceStep,\n sendCadenceStepBatch,\n type BatchItem,\n type PriorStepRow,\n} from \"@oneshot-gtm/plays\";\nimport type {\n CadenceCounts,\n CadenceNextStepDraft,\n CadenceStatus,\n CadenceView,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * In-flight cadence sends are tracked on the cadence_state row's\n * `sending_started_at` column (claimed atomically by\n * `ledger.claimCadenceSendingMarker` before the background SDK send fires,\n * cleared on success via `advanceCadence` and on failure in the catch).\n *\n * History: this used to be an in-memory Set. Under `bun --watch` a file save\n * killed the background promise mid-SDK-call, leaving the founder with no\n * \"sending\" UI signal AND no email delivered. The DB-backed marker survives\n * restarts; the cold-boot sweeper recovers stranded rows.\n *\n * Stale-cutoff window: a fresh Send click can reclaim a marker older than\n * this. Set to MAX_SEND_AGE_MS to match the cold-boot sweeper threshold —\n * the only way the marker is older is if a previous send was killed.\n */\nconst MAX_SEND_AGE_MS = 5 * 60 * 1000;\n\n/**\n * Per-play info that doesn't change between rows of the same play. Computed\n * once per unique play_name and reused for every row to avoid re-walking the\n * sequence registry + re-reading config from disk per row.\n */\ninterface PlayInfo {\n nextLabelByStep: Map<number, { label: string | null; isBreakup: boolean }>;\n followupCount: number;\n}\n\nfunction buildPlayInfoMap(\n rows: ReadonlyArray<{ play_name: string; current_step: number }>,\n): Map<string, PlayInfo> {\n const map = new Map<string, PlayInfo>();\n for (const row of rows) {\n let info = map.get(row.play_name);\n if (!info) {\n info = {\n nextLabelByStep: new Map(),\n followupCount: playFollowupCount(row.play_name),\n };\n map.set(row.play_name, info);\n }\n if (!info.nextLabelByStep.has(row.current_step)) {\n const next = nextStepInfo(row.play_name, row.current_step);\n info.nextLabelByStep.set(row.current_step, {\n label: next?.label ?? null,\n isBreakup: next?.isBreakup ?? false,\n });\n }\n }\n return map;\n}\n\nfunction toView(\n row: ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number],\n priorByKey: Map<string, PriorStepRow[]>,\n playInfo: Map<string, PlayInfo>,\n): CadenceView {\n let nextStepDraft: CadenceNextStepDraft | null = null;\n if (row.next_step_draft_json) {\n try {\n const parsed = JSON.parse(row.next_step_draft_json) as CadenceNextStepDraft & {\n payload?: unknown;\n };\n // Strip `payload` from the wire view — internal envelope only the\n // send route reads. UI only needs subject/body/flags/draftedAt.\n nextStepDraft = {\n subject: parsed.subject,\n body: parsed.body,\n flags: parsed.flags ?? [],\n draftedAt: parsed.draftedAt,\n };\n } catch {\n nextStepDraft = null;\n }\n }\n const info = playInfo.get(row.play_name);\n const next = info?.nextLabelByStep.get(row.current_step) ?? null;\n const followupCount = info?.followupCount ?? 0;\n const priorSteps = (priorByKey.get(`${row.prospect_id}|${row.play_name}`) ?? []).map((s) => ({\n stepIndex: s.stepIndex,\n label: s.label,\n subject: s.subject,\n body: s.body,\n sentAt: s.sentAt,\n }));\n return {\n prospectId: row.prospect_id,\n prospectEmail: row.prospect_email,\n prospectName: row.prospect_name,\n prospectCompany: row.prospect_company,\n playName: row.play_name,\n status: row.status as CadenceStatus,\n currentStep: row.current_step,\n enrolledAt: row.enrolled_at,\n nextDueAt: row.next_due_at,\n lastPolledAt: row.last_polled_at,\n nextStepDraft,\n nextStepLabel: next?.label ?? null,\n nextStepIsBreakup: next?.isBreakup ?? false,\n followupCount,\n priorSteps,\n isSending: row.sending_started_at != null,\n lastSendError: row.last_send_error,\n lastSendErrorAt: row.last_send_error_at,\n };\n}\n\nfunction viewsForRows(\n rows: ReadonlyArray<ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number]>,\n): CadenceView[] {\n // Single SQL fetch for ALL (prospect_id, play_name) pairs — replaces the\n // N+1 of one listSequenceEventsForProspectPlay per row.\n const pairs = rows.map((r) => ({ prospectId: r.prospect_id, playName: r.play_name }));\n const priorByKey = getPriorStepsBulk(pairs);\n // Compute play-level info (nextStepInfo + playFollowupCount) once per\n // unique play_name — each calls effectiveSequence → loadConfig (readFileSync).\n const playInfo = buildPlayInfoMap(rows);\n return rows.map((r) => toView(r, priorByKey, playInfo));\n}\n\nexport function listCadences(req: Request): Response {\n const url = new URL(req.url);\n const all = url.searchParams.get(\"all\") === \"1\";\n // Optional `?sinceRun=N` filter — the /run-page → /cadences deep-link from\n // run-complete mode. Resolves `runs.prospect_emails_json` for run N and\n // filters cadences to that prospect set (matched by canonicalized email).\n // Falls back to all-cadences when the run id is malformed or unknown.\n const sinceRunRaw = url.searchParams.get(\"sinceRun\");\n const sinceRunId =\n sinceRunRaw && Number.isFinite(Number.parseInt(sinceRunRaw, 10))\n ? Number.parseInt(sinceRunRaw, 10)\n : null;\n const ledger = getLedger();\n // Full status-complete set for the summary tiles. The active/all toggle only\n // narrows the TABLE; the tiles must reflect every status (else REPLIED reads 0\n // whenever the default \"active\" filter is on). Both derive from this one set.\n const allRows = ledger.listAllCadences();\n let countRows = allRows;\n let rows = all ? allRows : allRows.filter((r) => r.status === \"active\");\n if (sinceRunId != null) {\n const run = ledger.getRun(sinceRunId);\n // Unknown runId → return zero rows. The UI shows \"0 cadences filtered to\n // run #N\" with a [clear filter] CTA, which is clearer than silently\n // ignoring the filter and showing everything.\n const wantedEmails = new Set(\n (run?.prospectEmails ?? []).map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0),\n );\n const inRun = (r: { prospect_email: string | null }): boolean => {\n const email = r.prospect_email?.trim().toLowerCase();\n return email != null && wantedEmails.has(email);\n };\n rows = rows.filter(inRun);\n // Scope the tiles to the run too, so they describe the same filtered view.\n countRows = countRows.filter(inRun);\n }\n return jsonResponse({ cadences: viewsForRows(rows), counts: tallyCounts(countRows) }, 200, req);\n}\n\n/** Status breakdown for the summary tiles — `overdue` = active & past due. */\nfunction tallyCounts(\n rows: ReadonlyArray<{ status: string; next_due_at: string | null }>,\n): CadenceCounts {\n const now = Date.now();\n const counts: CadenceCounts = {\n active: 0,\n replied: 0,\n breakup: 0,\n completed: 0,\n paused: 0,\n overdue: 0,\n };\n for (const r of rows) {\n if (\n r.status === \"active\" ||\n r.status === \"replied\" ||\n r.status === \"breakup\" ||\n r.status === \"completed\" ||\n r.status === \"paused\"\n ) {\n counts[r.status]++;\n if (r.status === \"active\" && r.next_due_at && new Date(r.next_due_at).getTime() <= now) {\n counts.overdue++;\n }\n }\n }\n return counts;\n}\n\nexport function getCadence(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const all = ledger.listCadencesForProspect(id);\n if (all.length === 0) return jsonResponse({ error: \"no cadences for prospect\" }, 404, req);\n return jsonResponse({ cadences: viewsForRows(all) }, 200, req);\n}\n\nexport function stopCadence(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\");\n const ledger = getLedger();\n const cadences = ledger.listCadencesForProspect(id).filter((c) => {\n if (playName && c.play_name !== playName) return false;\n return c.status === \"active\";\n });\n for (const cad of cadences) {\n ledger.setCadenceStatus({\n prospectId: id,\n playName: cad.play_name,\n status: \"completed\",\n });\n }\n return jsonResponse({ stopped: cadences.length }, 200, req);\n}\n\nfunction parseProspectAndPlay(\n req: Request,\n params: Record<string, string>,\n): { prospectId: number; playName: string } | Response {\n const prospectId = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(prospectId)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? \"\";\n if (!playName) return jsonResponse({ error: \"play query param required\" }, 400, req);\n return { prospectId, playName };\n}\n\nexport async function previewCadenceStepRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const parsed = parseProspectAndPlay(req, params);\n if (parsed instanceof Response) return parsed;\n try {\n const preview = await previewCadenceStep(parsed);\n return jsonResponse(\n {\n subject: preview.subject,\n body: preview.body,\n flags: preview.flags,\n draftedAt: preview.draftedAt,\n stepLabel: preview.stepLabel,\n isBreakup: preview.isBreakup,\n },\n 200,\n req,\n );\n } catch (err) {\n const msg = (err as Error).message ?? \"preview failed\";\n const status = msg.startsWith(\"no cadence\") || msg.startsWith(\"cadence is\") ? 409 : 500;\n return jsonResponse({ error: msg }, status, req);\n }\n}\n\nexport async function sendCadenceStepRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n if (isDraining()) {\n return jsonResponse({ error: \"server restarting — retry in a moment\" }, 503, req);\n }\n const parsed = parseProspectAndPlay(req, params);\n if (parsed instanceof Response) return parsed;\n // Verify the preview exists synchronously so we can 409 the founder\n // immediately if they clicked Send without a persisted draft — but the\n // actual send is fire-and-forget. SDK email send takes ~2 min; blocking\n // the modal that long is bad UX, especially since the founder already\n // approved by confirming. Mirrors POST /api/cadences/send-batch.\n const ledger = getLedger();\n try {\n const draft = ledger.getCadenceDraft(parsed);\n if (!draft) {\n return jsonResponse({ error: \"no persisted preview — click Preview first\" }, 409, req);\n }\n } catch (err) {\n return jsonResponse({ error: (err as Error).message ?? \"send failed\" }, 500, req);\n }\n // Atomic claim — survives server restart. `staleCutoffIso` lets a fresh\n // click reclaim a marker stranded by a previous restart (the cold-boot\n // sweep also clears these, but a fast retry shouldn't have to wait).\n const nowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_SEND_AGE_MS).toISOString();\n const claimed = ledger.claimCadenceSendingMarker({\n prospectId: parsed.prospectId,\n playName: parsed.playName,\n startedAtIso: nowIso,\n staleCutoffIso,\n });\n if (!claimed) {\n return jsonResponse(\n { error: \"already sending — wait for the in-flight send to complete\" },\n 409,\n req,\n );\n }\n void (async () => {\n try {\n await sendCadenceStep(parsed);\n // Success path: advanceCadence inside sendCadenceStep already cleared\n // sending_started_at as part of its UPDATE. Nothing to do here.\n } catch (err) {\n logEvent(\n \"cadence.send.failed\",\n {\n prospect_id: parsed.prospectId,\n play_name: parsed.playName,\n message_120: ((err as Error)?.message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n // Failure path: advanceCadence never ran, so the marker is stuck.\n // Release it so the founder can re-Send without waiting for the sweep.\n try {\n ledger.clearCadenceSendingMarker(parsed);\n } catch {\n // Ledger write failing is the sweeper's problem; not worth re-throwing.\n }\n }\n })();\n return jsonResponse({ accepted: true }, 202, req);\n}\n\nasync function parseBatchItems(req: Request): Promise<BatchItem[] | Response> {\n let body: { items?: unknown };\n try {\n body = (await req.json()) as { items?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!Array.isArray(body.items)) {\n return jsonResponse({ error: \"items: array required\" }, 400, req);\n }\n const items: BatchItem[] = [];\n for (const raw of body.items) {\n if (raw && typeof raw === \"object\" && \"prospectId\" in raw && \"playName\" in raw) {\n const it = raw as { prospectId: unknown; playName: unknown };\n if (typeof it.prospectId === \"number\" && typeof it.playName === \"string\") {\n items.push({ prospectId: it.prospectId, playName: it.playName });\n }\n }\n }\n if (items.length === 0) {\n return jsonResponse({ error: \"no valid items in body\" }, 400, req);\n }\n return items;\n}\n\nexport async function previewCadenceBatchRoute(req: Request): Promise<Response> {\n const itemsOrErr = await parseBatchItems(req);\n if (itemsOrErr instanceof Response) return itemsOrErr;\n const results = await previewCadenceStepBatch(itemsOrErr);\n return jsonResponse({ results }, 200, req);\n}\n\nexport async function sendCadenceBatchRoute(req: Request): Promise<Response> {\n if (isDraining()) {\n return jsonResponse({ error: \"server restarting — retry in a moment\" }, 503, req);\n }\n const itemsOrErr = await parseBatchItems(req);\n if (itemsOrErr instanceof Response) return itemsOrErr;\n const items = itemsOrErr;\n // Claim each row's marker atomically. Rows that fail to claim (already\n // sending) are dropped from the batch — `accepted` reflects the actual\n // attempt count.\n const ledger = getLedger();\n const nowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_SEND_AGE_MS).toISOString();\n const claimed: BatchItem[] = [];\n for (const item of items) {\n const ok = ledger.claimCadenceSendingMarker({\n prospectId: item.prospectId,\n playName: item.playName,\n startedAtIso: nowIso,\n staleCutoffIso,\n });\n if (ok) claimed.push(item);\n }\n if (claimed.length === 0) {\n return jsonResponse(\n { error: \"no claimable rows — all selected are already sending\" },\n 409,\n req,\n );\n }\n void (async () => {\n try {\n // Per-item callback: clear the marker on each settled row. The serial\n // sendCadenceStepBatch already calls advanceCadence on success (which\n // clears the marker as part of the same UPDATE), so this catches the\n // failure path only — defensive clear is idempotent.\n await sendCadenceStepBatch(claimed, (item) => {\n try {\n ledger.clearCadenceSendingMarker(item);\n } catch {\n /* sweeper safety net */\n }\n });\n } catch (err) {\n // Belt-and-suspenders: the wrapper catches per-item; this catch only\n // fires if the wrapper itself throws. Release everything so the founder\n // can retry without waiting for the sweep.\n for (const item of claimed) {\n try {\n ledger.clearCadenceSendingMarker(item);\n } catch {\n /* ignore */\n }\n }\n logEvent(\n \"cadence.batch.failed\",\n { message_120: ((err as Error)?.message ?? \"\").slice(0, 120) },\n \"error\",\n );\n }\n })();\n return jsonResponse({ accepted: claimed.length }, 202, req);\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { ReceiptRecord } from \"@oneshot-gtm/core\";\nimport type { ReceiptDetail, ReceiptValueTag, ReceiptView } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/** Parse the JSON `value_tag` column to the wire shape; null on absent/garbage. */\nfunction parseValueTag(raw: string | null): ReceiptValueTag | null {\n if (!raw) return null;\n try {\n const v = JSON.parse(raw) as ReceiptValueTag;\n return v && typeof v.type === \"string\" ? v : null;\n } catch {\n return null;\n }\n}\n\nfunction toView(row: ReceiptRecord): ReceiptView {\n return {\n id: row.id,\n playName: row.play_name,\n callType: row.call_type,\n costUsd: row.cost_usd,\n oneshotRequestId: row.oneshot_request_id,\n createdAt: row.created_at,\n memo: row.memo,\n valueTag: parseValueTag(row.value_tag),\n };\n}\n\nexport function listReceipts(req: Request): Response {\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? undefined;\n const sinceDays = Number.parseInt(url.searchParams.get(\"sinceDays\") ?? \"\", 10);\n const limit = Math.min(500, Number.parseInt(url.searchParams.get(\"limit\") ?? \"200\", 10) || 200);\n const sinceIso = Number.isFinite(sinceDays)\n ? new Date(Date.now() - sinceDays * 24 * 3600 * 1000).toISOString()\n : undefined;\n\n const ledger = getLedger();\n const rows = ledger.listReceipts({\n ...(playName ? { playName } : {}),\n ...(sinceIso ? { sinceIso } : {}),\n limit,\n });\n return jsonResponse({ receipts: rows.map(toView) }, 200, req);\n}\n\nexport function getReceipt(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const r = getLedger().getReceipt(id);\n if (!r) return jsonResponse({ error: \"not found\" }, 404, req);\n let parsed: unknown = null;\n if (r.signed_receipt) {\n try {\n parsed = JSON.parse(r.signed_receipt);\n } catch {\n parsed = r.signed_receipt;\n }\n }\n let decisionContext: unknown = null;\n if (r.decision_context) {\n try {\n decisionContext = JSON.parse(r.decision_context);\n } catch {\n decisionContext = r.decision_context;\n }\n }\n const detail: ReceiptDetail = {\n ...toView(r),\n signedReceipt: parsed,\n decisionContext,\n };\n return jsonResponse({ receipt: detail }, 200, req);\n}\n","/**\n * Wire types shared between apps/cli, apps/server, and apps/web.\n * These are the API contracts for /api/* endpoints. Keep stable.\n */\n\nexport type CadenceStatus = \"active\" | \"replied\" | \"breakup\" | \"completed\" | \"paused\";\n\nexport interface CadenceNextStepDraft {\n subject: string;\n body: string;\n flags: string[];\n draftedAt: string;\n}\n\nexport interface CadenceSentStep {\n /** 0 = initial send; 1..N = registered cadence follow-ups in order. */\n stepIndex: number;\n /** Step label from the play registry (\"initial send\", \"value follow-up\", \"breakup\", …). */\n label: string;\n subject: string;\n /** Null when this row was written before subject/body persistence landed (pre-v8). */\n body: string | null;\n /** ISO timestamp of when the email actually sent. */\n sentAt: string;\n}\nexport type StepChannel = \"email\" | \"sms\" | \"voice\" | \"linkedin\";\n\nexport interface CadenceView {\n prospectId: number;\n prospectEmail: string | null;\n prospectName: string | null;\n prospectCompany: string | null;\n playName: string;\n status: CadenceStatus;\n currentStep: number;\n enrolledAt: string;\n nextDueAt: string | null;\n lastPolledAt: string | null;\n /** Persisted next-step preview (set by Preview, cleared on advance). */\n nextStepDraft: CadenceNextStepDraft | null;\n /** Label of the next step (\"value follow-up\", \"breakup\", …). Null when\n * no next step exists (cadence is at or past the last step). */\n nextStepLabel: string | null;\n /** Whether the next step is the final breakup. Derived from the cadence\n * engine's registered sequence — single source of truth. */\n nextStepIsBreakup: boolean;\n /** Total registered follow-up steps for this play (excludes day-0).\n * The UI uses `followupCount + 1` for the step-progress dot count. */\n followupCount: number;\n /** Touches already sent for this cadence (step 0 + cadence follow-ups), oldest first.\n * Empty array when the cadence has just been enrolled and nothing has fired yet. */\n priorSteps: CadenceSentStep[];\n /** True when a fire-and-forget background send is currently in flight for this\n * cadence step (set by the API layer when /send-next or /send-batch kicks off,\n * cleared as each row's SDK call resolves). Drives the \"sending…\" badge on\n * /cadences and gates the row out of further Send actions until it completes. */\n isSending: boolean;\n /** Last send-failure message (incl. platform `ref:`) when the most recent send\n * attempt failed and nothing has succeeded since; null otherwise. Drives the\n * \"send failed · retrying\" row indicator so a row blocked upstream reads\n * differently from one merely waiting on the founder. */\n lastSendError: string | null;\n /** ISO timestamp of `lastSendError`. */\n lastSendErrorAt: string | null;\n}\n\n/**\n * Status breakdown for the /cadences summary tiles. Always computed over the\n * full set (scoped only by a sinceRun deep-link), independent of the active/all\n * table toggle — so REPLIED/BREAKUP/COMPLETED never read 0 just because the\n * table is filtered to active rows. `overdue` counts active cadences past due.\n */\nexport interface CadenceCounts {\n active: number;\n replied: number;\n breakup: number;\n completed: number;\n paused: number;\n overdue: number;\n}\n\nexport interface CadencesResult {\n cadences: CadenceView[];\n counts: CadenceCounts;\n}\n\n/** RoCS value tag attached to a receipt once its outcome is known. */\nexport interface ReceiptValueTag {\n type: string;\n amount?: number;\n label?: string;\n}\n\nexport interface ReceiptView {\n id: number;\n playName: string;\n callType: string;\n costUsd: number | null;\n oneshotRequestId: string | null;\n createdAt: string;\n /** Call-time reason (\"why did I make this call?\"). */\n memo: string | null;\n /** Outcome value (\"did this call generate value?\"), null until tagged. */\n valueTag: ReceiptValueTag | null;\n}\n\nexport interface ReceiptDetail extends ReceiptView {\n signedReceipt: unknown | null;\n /** Structured call-time reasoning (\"what was the structured reasoning?\"). */\n decisionContext: unknown | null;\n}\n\nexport interface SpendByPlay {\n playName: string;\n calls: number;\n totalUsd: number;\n}\n\nexport interface EventsByPlay {\n playName: string;\n sent: number;\n delivered: number;\n replied: number;\n bounced: number;\n}\n\nexport interface OutcomeByPlay {\n playName: string | null;\n meetings: number;\n sqls: number;\n won: number;\n lost: number;\n ghosted: number;\n}\n\n/**\n * Per-cadence RoCS rollup (OneShot `rocsByGoal`) with local labels. `value` is\n * confirmed outcome value, `pendingValue` self-reported but unconfirmed; `rocs`\n * is value ÷ spend.\n */\nexport interface RocsGoalView {\n goalId: string;\n playName: string | null;\n prospect: string | null;\n spend: number;\n value: number;\n pendingValue: number;\n rocs: number;\n receiptCount: number;\n}\n\n/**\n * Lightweight projection of a `runs` row for the home dashboard's \"In flight\"\n * strip. Slim shape — `targets` and `events` stay on the `RunRecord` returned\n * by `GET /api/runs/:id` where they're actually needed for the per-target\n * rendering. Avoids paying to serialize event arrays on every 30s home poll.\n */\nexport interface RunSummary {\n id: number;\n playName: string;\n status: RunStatus;\n startedAt: string;\n completedAt: string | null;\n targetCount: number;\n draftedCount: number;\n sentCount: number;\n errorCount: number;\n}\n\nexport interface HomeMetrics {\n spendUsd7d: number;\n spendUsd30d: number;\n callsLast7d: number;\n sentLast7d: number;\n repliedLast7d: number;\n activeCadences: number;\n /**\n * Runs currently `running` (in-flight). Capped at 5 for the home widget.\n * The `CurrentRunsStrip` on /home hides itself when this is empty.\n */\n currentRuns: RunSummary[];\n}\n\nexport interface PlayDescriptor {\n name: string;\n channels: StepChannel[];\n followupCount: number;\n hasBreakup: boolean;\n cliInvocation: string;\n /**\n * Follow-up steps with effective (override-applied) CUMULATIVE day from the\n * day-0 initial send. The initial send itself isn't listed (always day 0,\n * not editable). Empty for one-touch plays.\n */\n steps: { day: number; label: string; channel: StepChannel; isBreakup: boolean }[];\n /** Code-default cumulative days for the same steps — lets the UI offer \"reset\". */\n defaultDays: number[];\n}\n\nexport type LlmProvider = \"openrouter\" | \"openai\" | \"anthropic\";\nexport type WalletMode = \"cdp\" | \"private-key\";\nexport type KeySource = \"env\" | \"file\" | null;\n\nexport interface DoctorCheck {\n name: string;\n severity: \"ok\" | \"warn\" | \"fail\";\n message: string;\n hint?: string;\n}\n\nexport interface SetupRequest {\n founderName?: string;\n founderEmail?: string;\n productOneLiner?: string;\n productDomain?: string;\n sendingDomain?: string;\n /** Email transport: OneShot SDK (wallet-owned domain) or the founder's own Gmail/Workspace account. Legacy — ignored once the identities pool exists. */\n emailProvider?: \"oneshot\" | \"gmail\";\n /** Per-identity daily-cap edits ({ id, maxPerDay }). Null maxPerDay = uncapped. */\n identityUpdates?: Array<{ id: string; maxPerDay: number | null }>;\n /**\n * New OneShot sending identities to add to the pool (a wallet-owned domain +\n * a mailbox local-part). `sendingDomain` must be one returned by the\n * provisioned-domain pool. Omit `maxPerDay` to take the cold-start warm-up\n * ramp; pass `null` to add uncapped.\n */\n addIdentities?: Array<{\n provider: \"oneshot\";\n sendingDomain: string;\n mailbox?: string;\n label?: string;\n maxPerDay?: number | null;\n }>;\n /** Identities to drop from the rotation pool. Existing prospect pins to a removed id will refuse to send until restored. */\n removeIdentityIds?: string[];\n icpOneLiner?: string;\n /** Founder background — résumé, prior companies, named roles. Founder-trust proof. */\n founderCredentials?: string;\n /** Products / projects you've shipped (free text, e.g. comma-separated). Peer-founder proof. */\n productPortfolio?: string;\n /** Notable partners / customers (free text, brand names). Brand-recognition proof. */\n partners?: string;\n /** When true, signature appends a literal \"Sent from my iPhone\" line. */\n mobileSignature?: boolean;\n llmProvider?: LlmProvider;\n llmModel?: string;\n telemetryEnabled?: boolean;\n walletMode?: WalletMode;\n secrets?: Partial<\n Record<\n | \"OPENROUTER_API_KEY\"\n | \"OPENAI_API_KEY\"\n | \"ANTHROPIC_API_KEY\"\n | \"CDP_API_KEY_ID\"\n | \"CDP_API_KEY_SECRET\"\n | \"CDP_WALLET_SECRET\"\n | \"AGENT_PRIVATE_KEY\"\n | \"GMAIL_CLIENT_ID\"\n | \"GMAIL_CLIENT_SECRET\"\n | \"GMAIL_REFRESH_TOKEN\",\n string\n >\n >;\n}\n\n/**\n * One provisioned sending domain as seen by the browser — the wallet-owned\n * domain pool (SDK 0.19 `listDomains`), trimmed to the fields the setup UI\n * needs. Mirrors the SDK's DomainPoolEntry without leaking the SDK type into\n * the web layer.\n */\nexport interface DomainPoolView {\n domain: string;\n poolStatus: \"active\" | \"warming\" | \"paused\" | \"removed\";\n warmupScore: number | null;\n dailySendLimit: number;\n dailySentCount: number;\n}\n\n/** One sender identity as shown on /setup: pool entry + today's usage. */\nexport interface SenderIdentityView {\n id: string;\n provider: \"oneshot\" | \"gmail\";\n label: string | null;\n address: string | null;\n sendingDomain: string | null;\n /** OneShot only: the From local-part (mailbox) for this identity. Null for Gmail / legacy. */\n mailbox: string | null;\n maxPerDay: number | null;\n warmup: { startPerDay: number; incrementPerWeek: number } | null;\n /** This mailbox's own sends today. */\n sentToday: number;\n /**\n * Sends today across the whole cap-group this identity shares — i.e. every\n * mailbox on the same OneShot sending domain (reputation + the daily limit\n * are per-domain). Equals `sentToday` when the identity is the only mailbox\n * on its domain (and for Gmail, which is always per-account).\n */\n domainSentToday: number;\n /** The cap-group's effective ceiling today after the warm-up ramp (shared across the domain's mailboxes); null = uncapped. */\n capToday: number | null;\n /** True when synthesized from legacy single-provider config (not yet a persisted pool). */\n legacy: boolean;\n}\n\nexport type QueueStatusView = \"pending\" | \"approved\" | \"rejected\" | \"sent\" | \"expired\";\n\nexport interface QueueRowView {\n id: number;\n playName: string;\n payload: unknown;\n dedupeKey: string;\n source: string;\n status: QueueStatusView;\n foundAt: string;\n reviewedAt: string | null;\n sentAt: string | null;\n notes: string | null;\n prospectId: number | null;\n /**\n * Most-recent draft generated for this row by the /api/run SSE endpoint.\n * Null on rows that have never been through a /run pass. The /queue UI\n * uses this to render the draft block in the expanded row.\n */\n lastDraft: LastDraft | null;\n /** ISO timestamp of `lastDraft`. Null when no draft persisted. */\n lastDraftedAt: string | null;\n /**\n * True when a Send-draft is in flight on this row. Backed by the persisted\n * `target_queue.send_started_at` marker so the `/queue` UI's spinner\n * survives navigate-away-and-back AND server restart. Cleared automatically\n * when the row's status flips to a terminal state.\n */\n isSending: boolean;\n}\n\n/**\n * Per-row draft envelope persisted after each /api/run dispatch. `dryRun`\n * distinguishes preview-only drafts from real-send attempts; `sent` is\n * true only when the SDK actually emitted the email (false for dryRun\n * and for lint-blocked drafts).\n */\nexport interface LastDraft {\n subject: string;\n body: string;\n flags: string[];\n sent: boolean;\n receiptIds: number[];\n dryRun: boolean;\n draftedAt: string;\n /** Enrichment SDK failed for this prospect — draft built from payload only. Non-blocking (send stays enabled). */\n enrichmentFailed?: boolean;\n}\n\n/**\n * Draft flags that HOLD a draft from auto-send but are deliberately overridable\n * by a founder on a manual \"send this one\" — they mean \"needs a human glance,\"\n * not \"broken copy.\" Unlike lint flags (em-dash, rule-of-three, …) or dedup\n * outcomes (already-contacted), regenerating won't clear these and shouldn't:\n * the founder either sends as-is or rejects.\n *\n * Currently: `stale-event` — a luma-events event >14 days past, where the\n * guest-list signal is old enough to want confirmation before sending.\n */\nexport const SOFT_REVIEW_FLAGS: readonly string[] = [\"stale-event\"];\n\n/**\n * The subset of a draft's flags that genuinely block sending (everything except\n * the founder-overridable soft-review flags). Empty → the draft is sendable.\n * Shared by the server send gate and the queue UI's send button so the two\n * never disagree on whether a held draft can be force-sent.\n */\nexport function blockingFlags(flags: string[]): string[] {\n return flags.filter((f) => !SOFT_REVIEW_FLAGS.includes(f));\n}\n\n/** A single inbox email (reply to outreach), with prospect/play context when matched. */\nexport interface InboxReplyView {\n id: string;\n /** Normalized sender address (lowercased, display-name stripped). */\n fromEmail: string;\n /** Raw From header as received (may include a display name). */\n fromRaw: string;\n subject: string;\n receivedAt: string;\n body: string;\n /** Sender identity whose mailbox received this email — the reply goes out from it. Null on legacy/unattributed rows. */\n sourceIdentityId: string | null;\n /** Provider of the receiving identity. Gmail replies thread properly; oneshot replies are best-effort fresh sends (paid, subject-threading only). */\n sourceProvider: \"gmail\" | \"oneshot\" | null;\n /** Gmail thread id (gmail sources only) — passed back on send to thread the reply. */\n threadId: string | null;\n /** RFC 2822 Message-ID of the inbound email (gmail sources only) — In-Reply-To on the reply. */\n messageId: string | null;\n /** Set when the sender matches a known prospect; null for unmatched mail. */\n matched: {\n name: string | null;\n company: string | null;\n playName: string | null;\n cadenceStatus: string | null;\n } | null;\n /**\n * Persisted reply activity for this thread: the saved (auto-saved) draft, and\n * the append-only history of replies already sent. Null when nothing has been\n * drafted or sent yet. Keyed server-side by `inboxThreadKey`.\n */\n thread: {\n draftBody: string | null;\n sent: { body: string; sentAt: string }[];\n } | null;\n}\n\n/**\n * Stable key for an inbox thread, shared by the server (persistence) and the\n * web composer (send payload) so both sides agree. Gmail rows carry a\n * thread_id; OneShot rows fall back to the email id (best-effort — OneShot has\n * no thread API).\n */\nexport function inboxThreadKey(v: { threadId: string | null; id: string }): string {\n return v.threadId ?? v.id;\n}\n\nexport interface InboxResult {\n replies: InboxReplyView[];\n hasMore: boolean;\n /** Present when the inbox fetch failed; replies will be empty. */\n error?: string;\n}\n\n/** POST /api/inbox/draft-reply — generate an LLM reply draft for an inbound email. */\nexport interface InboxDraftReplyRequest {\n fromEmail: string;\n subject: string;\n body: string;\n}\n\nexport interface InboxDraftReplyResult {\n body: string;\n}\n\n/** POST /api/inbox/draft — persist the in-progress draft for a thread (auto-save). */\nexport interface InboxSaveDraftRequest {\n threadKey: string;\n inboundEmailId: string;\n toEmail: string;\n subject: string;\n identityId: string | null;\n body: string;\n}\n\nexport interface InboxSaveDraftResult {\n saved: boolean;\n}\n\n/** POST /api/inbox/reply — send a (possibly edited) reply. */\nexport interface InboxSendReplyRequest {\n to: string;\n subject: string;\n body: string;\n identityId: string;\n /** Thread key for persisting the sent reply (see `inboxThreadKey`). */\n threadKey: string;\n threadId?: string | null;\n inReplyTo?: string | null;\n /** OneShot inbox email id for server-side threading (OneShot-source rows). */\n replyToEmailId?: string | null;\n}\n\nexport interface InboxSendReplyResult {\n sent: boolean;\n id: string;\n costUsd: number;\n}\n\nexport interface QueueCounts {\n pending: number;\n approved: number;\n rejected: number;\n sent: number;\n expired: number;\n}\n\nexport interface DrainRequest {\n playName: string;\n limit: number;\n dryRun: boolean;\n /** For accelerator-batch: required cohort tag. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\nexport interface DrainResult {\n drained: number;\n sent: number;\n errors: Array<{ id: number; message: string }>;\n}\n\nexport interface TriggerView {\n name: string;\n lastPolledAt: string | null;\n lastRunSummary: unknown | null;\n enabled: boolean;\n config: Record<string, unknown> | null;\n /** Registry default config. Null if this trigger isn't in the registry (orphan). */\n defaultConfig: Record<string, unknown> | null;\n defaultIntervalMs: number;\n /** Currently-active interval (defaultIntervalMs unless overridden via config.intervalMs). */\n intervalMs: number;\n /** True while an ad-hoc run is in flight on the server (fire-and-forget). */\n running: boolean;\n /** ISO timestamp of when the current in-flight run started. Null when `running=false`. */\n runningSince: string | null;\n /**\n * False when the spec declares a `readiness` fn that returns not-ready for\n * the current config (e.g. github-topics without `topics`). The UI uses\n * this to disable the Enable toggle + Run button.\n */\n ready: boolean;\n /** Human-readable reason when `ready === false`; null otherwise. */\n notReadyReason: string | null;\n}\n\nexport interface DeriveIcpResult {\n proposedIcp: string;\n sourceUrl: string;\n costUsd: number;\n}\n\nexport interface RunTriggerResult {\n name: string;\n fired: boolean;\n /**\n * True when the run was kicked off fire-and-forget — work is still in\n * progress on the server. `result` and `error` will be null; poll\n * `GET /api/triggers` for `lastRunSummary` to see the outcome.\n */\n pending: boolean;\n result: {\n source: string;\n candidates: number;\n droppedIcp: number;\n droppedDuplicate: number;\n droppedEnrichment: number;\n enqueued: number;\n costUsd: number;\n halted?: string;\n } | null;\n error: string | null;\n}\n\nexport interface StrategistMessage {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface StrategistRequest {\n messages: StrategistMessage[];\n}\n\n/** Server-Sent Events frame contract for /api/strategist/stream. */\nexport type StrategistFrame =\n | { kind: \"thinking\" }\n | { kind: \"delta\"; text: string }\n | { kind: \"done\" }\n | { kind: \"error\"; message: string };\n\nexport interface OutcomeRequest {\n email: string;\n outcome: \"meeting_booked\" | \"sql_qualified\" | \"deal_won\" | \"deal_lost\" | \"ghosted\";\n playName?: string;\n amountUsd?: number;\n notes?: string;\n}\n\nexport interface RunPlayRequest {\n dryRun: boolean;\n /** Free-form per-play target rows; the server validates per-play shape. */\n targets: unknown[];\n /**\n * Optional parallel array of `target_queue.dedupe_key` values, one per\n * `targets[i]`. When present and length-matched, the SSE endpoint persists\n * each generated draft back to the matching queue row (`last_draft_json`).\n * Manual /run entries omit this so the persist hook is skipped — the\n * /queue is the authoritative archive only for queue-originated runs.\n */\n dedupeKeys?: (string | null)[];\n /** For accelerator-batch: sender cohort + free offer text. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\n/** Server-Sent Events frame contract for /api/run/$playName. */\nexport type RunPlayEvent =\n | {\n kind: \"verify\";\n total: number;\n verified: number;\n dropped: Array<{ email: string; reason: string }>;\n }\n | { kind: \"stage\"; stage: string }\n | { kind: \"draft\"; index: number; subject: string; body: string; flags: string[] }\n | { kind: \"send\"; index: number; receiptIds: number[] }\n | { kind: \"error\"; index: number; message: string }\n | { kind: \"done\"; total: number; sent: number }\n /** First frame the server emits — gives the UI the runId so it can resume on nav-back. */\n | { kind: \"runStarted\"; runId: number; startedAt: string };\n\n/** Lifecycle status of a /run-page dispatch persisted in the `runs` table. */\nexport type RunStatus = \"running\" | \"done\" | \"interrupted\";\n\n/**\n * Snapshot of one /run-page dispatch — returned by GET /api/runs/:id so the UI\n * can rebuild the per-target progress view after navigate-away-and-back, AND\n * decide whether to keep polling (status === 'running') or stop (done /\n * interrupted). `events` is the accumulated SSE stream (same shape callers\n * see live), so the client renderer can be source-shared.\n */\nexport interface RunRecord {\n id: number;\n playName: string;\n dryRun: boolean;\n status: RunStatus;\n startedAt: string;\n completedAt: string | null;\n targetCount: number;\n draftedCount: number;\n sentCount: number;\n errorCount: number;\n /** Original targets array as posted to /api/run/:playName. */\n targets: unknown[];\n /** All SSE events accumulated so far (or all of them, when status !== 'running'). */\n events: RunPlayEvent[];\n /** Emails that were actually sent — used by /cadences?sinceRun to filter. */\n prospectEmails: string[];\n}\n","import {\n getGmailProfile,\n getLedger,\n isDraining,\n listInbox,\n loadConfig,\n logEvent,\n replyEmail,\n resolveIdentities,\n trackSend,\n} from \"@oneshot-gtm/core\";\nimport { draftInboxReply } from \"@oneshot-gtm/plays\";\nimport {\n type InboxDraftReplyRequest,\n type InboxDraftReplyResult,\n type InboxReplyView,\n type InboxResult,\n type InboxSaveDraftRequest,\n type InboxSaveDraftResult,\n type InboxSendReplyRequest,\n type InboxSendReplyResult,\n inboxThreadKey,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/** \"Jane Doe <jane@x.com>\" → \"jane@x.com\"; bare addresses pass through. */\nfunction normalizeFrom(raw: string): string {\n const m = raw.match(/<([^>]+)>/);\n return (m ? (m[1] ?? raw) : raw).trim().toLowerCase();\n}\n\n/**\n * Cadence-status priority for \"which play represents this prospect's reply\":\n * a `replied` cadence wins, then `active`, then anything else. Shared by the\n * list route (badge) and the draft route (prior-email context) so the play\n * shown and the play whose history feeds the LLM never diverge for a prospect\n * enrolled in several plays. Ties keep the first row seen.\n */\nfunction cadenceRank(status: string): number {\n if (status === \"replied\") return 2;\n if (status === \"active\") return 1;\n return 0;\n}\n\n/**\n * Read-only view of the OneShot inbox (replies to outreach). Each email is\n * matched to a known prospect by sender address, annotated with the play +\n * cadence status when available. Live fetch — no storage. The SDK exposes only\n * inboxList (no reply/markRead), so this is read-only.\n */\nexport async function listInboxRoute(req: Request): Promise<Response> {\n const ledger = getLedger();\n\n let emails: Awaited<ReturnType<typeof listInbox>>[\"emails\"];\n try {\n // Fetch a wide window (not just the newest handful): mailboxes fill with\n // newsletters/bounces/DMARC noise, and matching only runs over what's\n // fetched — too small a window buries a genuine prospect reply (and its\n // match) below the noise. The UI defaults to the `matched` filter to surface\n // those; this gives it enough history to find them.\n const result = await listInbox({ limit: 200 });\n emails = result.emails;\n } catch (err) {\n logEvent(\n \"inbox.list_failed\",\n { message_120: ((err as Error)?.message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n const out: InboxResult = { replies: [], hasMore: false, error: \"couldn't reach the inbox\" };\n return jsonResponse(out, 200, req);\n }\n\n // Cadence-backed prospects (multi-touch plays) carry play + status + name/co\n // in one JOIN. Index by normalized email; prefer a `replied`/`active` cadence\n // when a prospect has several.\n const byEmail = new Map<\n string,\n { name: string | null; company: string | null; playName: string; status: string }\n >();\n for (const c of ledger.listAllCadences()) {\n if (!c.prospect_email) continue;\n const key = c.prospect_email.trim().toLowerCase();\n const existing = byEmail.get(key);\n const better = !existing || cadenceRank(c.status) > cadenceRank(existing.status);\n if (better) {\n byEmail.set(key, {\n name: c.prospect_name,\n company: c.prospect_company,\n playName: c.play_name,\n status: c.status,\n });\n }\n }\n\n // Identity provider per id — the UI needs to know whether a reply will be a\n // threaded Gmail send or a best-effort (paid, unthreaded) OneShot send.\n const cfg = loadConfig();\n const providerById = new Map(resolveIdentities(cfg).map((i) => [i.id, i.provider]));\n\n // Persisted reply activity (saved draft + sent history), indexed by thread_key.\n const threads = ledger.getInboxThreads();\n\n const replies: InboxReplyView[] = emails.map((e) => {\n const fromEmail = normalizeFrom(e.from);\n let matched: InboxReplyView[\"matched\"] = null;\n const cadence = byEmail.get(fromEmail);\n if (cadence) {\n matched = {\n name: cadence.name,\n company: cadence.company,\n playName: cadence.playName,\n cadenceStatus: cadence.status,\n };\n } else {\n // One-touch plays leave no cadence row — fall back to the prospect record.\n const p = ledger.getProspectByEmail(fromEmail);\n if (p) {\n matched = { name: p.name, company: p.company, playName: p.source, cadenceStatus: null };\n }\n }\n const threadId = e.thread_id ?? null;\n return {\n id: e.id,\n fromEmail,\n fromRaw: e.from,\n subject: e.subject,\n receivedAt: e.received_at,\n body: e.body ?? \"\",\n sourceIdentityId: e.source_identity_id ?? null,\n sourceProvider: e.source_identity_id\n ? (providerById.get(e.source_identity_id) ?? null)\n : null,\n threadId,\n messageId: e.message_id ?? null,\n matched,\n thread: threads.get(inboxThreadKey({ threadId, id: e.id })) ?? null,\n };\n });\n\n // Drop mail from the founder's own sending domain — the mailbox accumulates\n // the agent's own sends + platform/system test mail (agent@/info@<domain>),\n // which are never genuine prospect replies. Then newest-first.\n const selfDomain = (cfg.sendingDomain ?? \"\").trim().toLowerCase();\n // Gmail self-sends: the Gmail query already excludes `from:me`, but\n // belt-and-braces against forwarded copies of the founder's own address.\n // Pool identities carry their address in config — no network call needed.\n // Only the legacy synthesized identity (no address field) needs a live\n // profile lookup, and that failing shouldn't break the replies page.\n const gmailIdentities = resolveIdentities(cfg).filter((i) => i.provider === \"gmail\");\n const selfAddresses = new Set(\n gmailIdentities.map((i) => (i.address ?? \"\").trim().toLowerCase()).filter((a) => a.length > 0),\n );\n if (gmailIdentities.some((i) => !i.address)) {\n try {\n selfAddresses.add((await getGmailProfile()).emailAddress.trim().toLowerCase());\n } catch {\n // best-effort — `-from:me` already filters at the source.\n }\n }\n const visible = replies\n .filter((r) => !selfDomain || !r.fromEmail.endsWith(`@${selfDomain}`))\n .filter((r) => !selfAddresses.has(r.fromEmail))\n .toSorted((a, b) => (a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : 0));\n\n const out: InboxResult = { replies: visible, hasMore: false };\n return jsonResponse(out, 200, req);\n}\n\n/**\n * Generate an LLM reply draft for an inbound email. The client sends the\n * email content it already has (re-fetching the live inbox here would add a\n * multi-second round-trip per draft). Prospect/play context is re-resolved\n * from the ledger by sender address — same matching as the list route.\n */\nexport async function draftReplyRoute(req: Request): Promise<Response> {\n let body: Partial<InboxDraftReplyRequest>;\n try {\n body = (await req.json()) as Partial<InboxDraftReplyRequest>;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n const fromEmail = (body.fromEmail ?? \"\").trim().toLowerCase();\n const subject = (body.subject ?? \"\").trim();\n const inboundBody = (body.body ?? \"\").trim();\n if (!fromEmail || !inboundBody) {\n return jsonResponse({ error: \"fromEmail and body are required\" }, 400, req);\n }\n\n const ledger = getLedger();\n const prospect = ledger.getProspectByEmail(fromEmail);\n let matched: Parameters<typeof draftInboxReply>[0][\"matched\"] = null;\n if (prospect) {\n // Same ranking as the list route's badge (cadenceRank) so the play whose\n // prior emails feed the draft matches the one the founder sees.\n const cadences = ledger.listCadencesForProspect(prospect.id);\n const best = cadences.reduce<(typeof cadences)[number] | undefined>(\n (acc, c) => (!acc || cadenceRank(c.status) > cadenceRank(acc.status) ? c : acc),\n undefined,\n );\n matched = {\n prospectId: prospect.id,\n name: prospect.name,\n company: prospect.company,\n playName: best?.play_name ?? prospect.source,\n };\n }\n\n try {\n const draft = await draftInboxReply({ fromEmail, subject, body: inboundBody, matched });\n const out: InboxDraftReplyResult = { body: draft.body };\n return jsonResponse(out, 200, req);\n } catch (err) {\n const message = (err as Error)?.message ?? \"draft failed\";\n logEvent(\"inbox.reply.draft_failed\", { message_120: message.slice(0, 120) }, \"warn\");\n return jsonResponse({ error: message }, 400, req);\n }\n}\n\n/**\n * Persist the in-progress reply draft for a thread (debounced auto-save from\n * the composer). Distinct from `/api/inbox/draft-reply`, which only generates\n * an LLM draft and stores nothing. Upsert-by-thread-key so typing overwrites.\n */\nexport async function saveDraftRoute(req: Request): Promise<Response> {\n let body: Partial<InboxSaveDraftRequest>;\n try {\n body = (await req.json()) as Partial<InboxSaveDraftRequest>;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n const threadKey = (body.threadKey ?? \"\").trim();\n const inboundEmailId = (body.inboundEmailId ?? \"\").trim();\n const toEmail = (body.toEmail ?? \"\").trim();\n if (!threadKey || !inboundEmailId || !toEmail) {\n return jsonResponse({ error: \"threadKey, inboundEmailId and toEmail are required\" }, 400, req);\n }\n\n const ledger = getLedger();\n // An emptied composer clears the persisted draft rather than storing a blank\n // one, so deleting all text and refreshing doesn't resurrect the old draft.\n if ((body.body ?? \"\").trim() === \"\") {\n ledger.clearInboxDraft(threadKey);\n } else {\n ledger.upsertInboxDraft({\n threadKey,\n inboundEmailId,\n toEmail,\n subject: (body.subject ?? \"\").trim(),\n identityId: body.identityId ?? null,\n body: body.body ?? \"\",\n });\n }\n const out: InboxSaveDraftResult = { saved: true };\n return jsonResponse(out, 200, req);\n}\n\n/**\n * Send a (possibly founder-edited) reply from the identity whose mailbox\n * received the inbound email. Gmail sources thread properly; oneshot sources\n * are a best-effort fresh send (no threading API — verified against the\n * platform's OpenAPI spec).\n */\nexport async function sendReplyRoute(req: Request): Promise<Response> {\n if (isDraining()) {\n return jsonResponse({ error: \"server restarting — retry in a moment\" }, 503, req);\n }\n let body: Partial<InboxSendReplyRequest>;\n try {\n body = (await req.json()) as Partial<InboxSendReplyRequest>;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n const to = (body.to ?? \"\").trim();\n const subject = (body.subject ?? \"\").trim();\n const replyBody = (body.body ?? \"\").trim();\n const identityId = (body.identityId ?? \"\").trim();\n const threadKey = (body.threadKey ?? \"\").trim();\n if (!to || !subject || !replyBody || !identityId || !threadKey) {\n return jsonResponse(\n { error: \"to, subject, body, identityId and threadKey are required\" },\n 400,\n req,\n );\n }\n\n try {\n const { result } = await trackSend(() =>\n replyEmail(\n {\n identityId,\n to,\n subject,\n body: replyBody,\n ...(body.threadId ? { threadId: body.threadId } : {}),\n ...(body.inReplyTo ? { inReplyTo: body.inReplyTo } : {}),\n ...(body.replyToEmailId ? { replyToEmailId: body.replyToEmailId } : {}),\n },\n { playName: \"inbox-reply\", memo: `manual inbox reply to ${to}` },\n ),\n );\n // Persist the sent reply (append to thread history, clear the draft) so the\n // founder can see what they sent after a refresh.\n getLedger().recordInboxSent({\n threadKey,\n toEmail: to,\n subject,\n body: replyBody,\n identityId,\n requestId: result.request_id ?? null,\n });\n logEvent(\"inbox.reply.sent\", { to_domain: to.split(\"@\")[1] ?? \"\", identity: identityId });\n const out: InboxSendReplyResult = {\n sent: true,\n id: result.request_id ?? \"\",\n costUsd: result.cost ?? 0,\n };\n return jsonResponse(out, 200, req);\n } catch (err) {\n const message = (err as Error)?.message ?? \"send failed\";\n logEvent(\"inbox.reply.send_failed\", { message_120: message.slice(0, 120) }, \"warn\");\n return jsonResponse({ error: message }, 400, req);\n }\n}\n","import { loadConfig, saveConfig } from \"@oneshot-gtm/core\";\nimport {\n defaultSequence,\n getSequence,\n isBreakupLabel,\n isBreakupStepAt,\n type Sequence,\n} from \"@oneshot-gtm/plays\";\nimport type { PlayDescriptor, StepChannel } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\ninterface PlayMeta {\n name: string;\n cli: string;\n}\n\nconst PLAY_CATALOG: PlayMeta[] = [\n {\n name: \"show-hn\",\n cli: \"oneshot-gtm motion show-hn --target ./examples/show-hn.json\",\n },\n {\n name: \"job-change\",\n cli: \"oneshot-gtm motion job-change --target ./examples/job-change.json\",\n },\n {\n name: \"post-funding\",\n cli: \"oneshot-gtm motion post-funding --target ./examples/post-funding.json\",\n },\n {\n name: \"accelerator-batch\",\n cli: \"oneshot-gtm motion accelerator-batch --target ./examples/accelerator-batch.json --sender-cohort yc-w26\",\n },\n {\n name: \"concierge\",\n cli: \"oneshot-gtm motion concierge --target ./examples/concierge.json\",\n },\n {\n name: \"demo-no-show\",\n cli: \"oneshot-gtm motion demo-no-show --target ./examples/demo-no-show.json\",\n },\n {\n name: \"competitor-switch\",\n cli: \"oneshot-gtm motion competitor-switch --target ./examples/competitor-switch.json\",\n },\n {\n name: \"stack-consolidation\",\n cli: \"oneshot-gtm find watch # fed by the github-topics finder, drained from /queue\",\n },\n {\n name: \"repo-interest\",\n cli: \"oneshot-gtm find watch # fed by the github-stars finder (adjacent repos), drained from /queue\",\n },\n {\n name: \"luma-events\",\n cli: \"oneshot-gtm find watch # fed by the luma-events finder (publicly-visible attendees), drained from /queue\",\n },\n {\n name: \"hiring-signal\",\n cli: \"oneshot-gtm motion hiring-signal --target ./examples/hiring-signal.json\",\n },\n {\n name: \"podcast-guest\",\n cli: \"oneshot-gtm motion podcast-guest --target ./examples/podcast-guest.json\",\n },\n {\n name: \"breakup-revive\",\n cli: \"oneshot-gtm motion breakup-revive --min-days 60 --max-days 90\",\n },\n];\n\n/** Relative per-step dayOffsets → cumulative days from the day-0 initial send. */\nfunction cumulativeDays(seq: Sequence | undefined): number[] {\n if (!seq) return [];\n let acc = 0;\n return seq.steps.map((s) => (acc += s.dayOffset));\n}\n\nexport function listPlays(req: Request): Response {\n const plays: PlayDescriptor[] = PLAY_CATALOG.map((p) => {\n const seq = getSequence(p.name);\n const channels: StepChannel[] = seq\n ? Array.from(new Set(seq.steps.map((s) => s.channel as StepChannel)))\n : [\"email\"];\n const followupCount = seq?.steps.length ?? 0;\n // hasBreakup uses the same step-position rule as the cadence runtime so\n // accelerator-batch (which uses the breakup PROMPT as its only follow-up\n // at index 0) doesn't get flagged as having a breakup step here.\n const hasBreakup = seq ? isBreakupStepAt(seq, seq.steps.length - 1) : false;\n const days = cumulativeDays(seq);\n const stepsArr = seq?.steps ?? [];\n const steps = stepsArr.map((s, i) => ({\n day: days[i] ?? 0,\n label: s.label ?? `step ${i + 1}`,\n channel: s.channel as StepChannel,\n // Per-step breakup flag using the SAME label rule the cadence engine\n // uses. Note: the /cadences progress UI only treats the FINAL such\n // step as the cadence-terminal breakup (see isBreakupStepAt). Here\n // we surface the label-level signal so /plays can hint a per-step\n // visual without re-deriving the substring.\n isBreakup: isBreakupLabel(s.label),\n }));\n return {\n name: p.name,\n channels,\n followupCount,\n hasBreakup,\n cliInvocation: p.cli,\n steps,\n defaultDays: cumulativeDays(defaultSequence(p.name)),\n };\n });\n return jsonResponse({ plays }, 200, req);\n}\n\n/**\n * Set (or clear) per-play cadence timing. Body: { days: number[] | null }.\n * `days` are CUMULATIVE days from the initial send (intuitive in the UI); we\n * convert to the engine-native relative offsets before persisting. `null`\n * clears the override (reset to code defaults). Timing only — step structure\n * is fixed in code.\n */\nexport async function setCadenceRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"] ?? \"\";\n const def = defaultSequence(name);\n if (!def || def.steps.length === 0) {\n return jsonResponse({ error: `play '${name}' has no editable cadence` }, 400, req);\n }\n\n let body: { days?: number[] | null };\n try {\n body = (await req.json()) as { days?: number[] | null };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n\n const cfg = loadConfig();\n const overrides = { ...cfg.cadenceOverrides };\n\n // Reset path: clear this play's override.\n if (body.days === null || body.days === undefined) {\n delete overrides[name];\n saveConfig({\n ...cfg,\n cadenceOverrides: Object.keys(overrides).length > 0 ? overrides : null,\n });\n return jsonResponse({ ok: true }, 200, req);\n }\n\n const days = body.days;\n const stepCount = def.steps.length;\n if (!Array.isArray(days) || days.length !== stepCount) {\n return jsonResponse(\n { error: `days must be an array of ${stepCount} cumulative day value(s)` },\n 400,\n req,\n );\n }\n if (!days.every((d) => Number.isInteger(d) && d >= 1 && d <= 120)) {\n return jsonResponse({ error: \"each day must be an integer between 1 and 120\" }, 400, req);\n }\n for (let i = 1; i < days.length; i++) {\n if ((days[i] as number) <= (days[i - 1] as number)) {\n return jsonResponse({ error: \"days must be strictly increasing\" }, 400, req);\n }\n }\n\n // Cumulative → relative offsets (each ≥ 1, guaranteed by the checks above).\n const relative = days.map((d, i) => (i === 0 ? d : d - (days[i - 1] as number)));\n overrides[name] = relative;\n saveConfig({ ...cfg, cadenceOverrides: overrides });\n return jsonResponse({ ok: true }, 200, req);\n}\n","import {\n cadenceRocs,\n getLedger,\n logEvent,\n outcomeToValueTag,\n tagOutcomeValue,\n} from \"@oneshot-gtm/core\";\nimport type {\n EventsByPlay,\n OutcomeByPlay,\n OutcomeRequest,\n RocsGoalView,\n SpendByPlay,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nfunction readSinceDays(req: Request): string | undefined {\n const url = new URL(req.url);\n const n = Number.parseInt(url.searchParams.get(\"sinceDays\") ?? \"\", 10);\n if (!Number.isFinite(n)) return undefined;\n return new Date(Date.now() - n * 24 * 3600 * 1000).toISOString();\n}\n\nfunction readPeriodDays(req: Request): number | undefined {\n const n = Number.parseInt(new URL(req.url).searchParams.get(\"sinceDays\") ?? \"\", 10);\n return Number.isFinite(n) ? n : undefined;\n}\n\nexport function measureCac(req: Request): Response {\n const sinceIso = readSinceDays(req);\n const ledger = getLedger();\n const spend: SpendByPlay[] = ledger.spendByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n calls: r.calls,\n totalUsd: r.total_usd,\n }));\n const events: EventsByPlay[] = ledger.eventsByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n sent: r.sent,\n delivered: r.delivered,\n replied: r.replied,\n bounced: r.bounced,\n }));\n return jsonResponse({ spend, events }, 200, req);\n}\n\nexport function measureRocs(req: Request): Response {\n const sinceIso = readSinceDays(req);\n const ledger = getLedger();\n const spend: SpendByPlay[] = ledger.spendByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n calls: r.calls,\n totalUsd: r.total_usd,\n }));\n const events: EventsByPlay[] = ledger.eventsByPlay(sinceIso ? { sinceIso } : {}).map((r) => ({\n playName: r.play_name,\n sent: r.sent,\n delivered: r.delivered,\n replied: r.replied,\n bounced: r.bounced,\n }));\n const outcomes: OutcomeByPlay[] = ledger\n .outcomesByPlay(sinceIso ? { sinceIso } : {})\n .map((r) => ({\n playName: r.play_name,\n meetings: r.meetings,\n sqls: r.sqls,\n won: r.won,\n lost: r.lost,\n ghosted: r.ghosted,\n }));\n return jsonResponse({ spend, events, outcomes }, 200, req);\n}\n\nexport async function recordOutcome(req: Request): Promise<Response> {\n const body = (await req.json()) as OutcomeRequest;\n const allowed = [\"meeting_booked\", \"sql_qualified\", \"deal_won\", \"deal_lost\", \"ghosted\"];\n if (!allowed.includes(body.outcome)) {\n return jsonResponse({ error: `outcome must be one of: ${allowed.join(\", \")}` }, 400, req);\n }\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(body.email);\n if (!prospect) return jsonResponse({ error: `prospect not found: ${body.email}` }, 404, req);\n const id = ledger.recordOutcome({\n prospectId: prospect.id,\n ...(body.playName ? { playName: body.playName } : {}),\n outcome: body.outcome,\n ...(body.amountUsd != null ? { amountUsd: body.amountUsd } : {}),\n ...(body.notes ? { notes: body.notes } : {}),\n });\n // Tag the value of the receipts that earned this outcome. When no play is\n // given, tag every cadence the prospect is in. Best-effort (tagOutcomeValue\n // swallows its own errors) — never block recording the outcome.\n const valueTag = outcomeToValueTag(body.outcome, body.amountUsd ?? undefined);\n if (valueTag) {\n const plays = body.playName\n ? [body.playName]\n : ledger.listCadencesForProspect(prospect.id).map((c) => c.play_name);\n for (const playName of plays) {\n await tagOutcomeValue({ prospectId: prospect.id, playName, valueTag });\n }\n }\n return jsonResponse({ id }, 200, req);\n}\n\n/**\n * Per-cadence RoCS: OneShot's goal-level spend-vs-value rollup, labelled with the\n * local play + prospect. Degrades to an empty list (never 500s the Measure page)\n * when the platform read fails or the wallet is unconfigured.\n */\nexport async function measureRocsByGoal(req: Request): Promise<Response> {\n const periodDays = readPeriodDays(req);\n let goals: RocsGoalView[] = [];\n try {\n const rollups = await cadenceRocs(periodDays != null ? { periodDays } : {});\n const labels = getLedger().goalLabels(rollups.map((g) => g.goalId));\n // Scope to THIS app's cadences: rocsByGoal returns every goal on the wallet\n // (other tools' compute goals, other installs sharing the key); keep only\n // goals we have local receipts for, so the table reads as our cadences.\n goals = rollups\n .filter((g) => labels.has(g.goalId))\n .map((g) => ({\n goalId: g.goalId,\n playName: labels.get(g.goalId)?.playName ?? null,\n prospect: labels.get(g.goalId)?.prospect ?? null,\n spend: g.spend,\n value: g.value,\n pendingValue: g.pendingValue,\n rocs: g.rocs,\n receiptCount: g.receiptCount,\n }));\n } catch (err) {\n logEvent(\n \"measure.rocs_by_goal.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n }\n return jsonResponse({ goals }, 200, req);\n}\n","import {\n deleteGmailToken,\n identityCapacities,\n listSendingDomains,\n loadConfig,\n registerOneShotIdentity,\n resolveIdentities,\n saveConfig,\n saveSecrets,\n secretSource,\n secretsPath,\n type DomainPoolEntry,\n type EmailIdentity,\n type OneShotConfig,\n} from \"@oneshot-gtm/core\";\nimport type {\n DomainPoolView,\n LlmProvider,\n SenderIdentityView,\n SetupRequest,\n WalletMode,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * The anonymous clientId is local-only — never exposed to the web layer.\n * Strip it before any HTTP response so the browser never sees it (and can't\n * accidentally clobber it on a subsequent POST).\n */\n/**\n * Strip the anonymous clientId before sending cfg to the web layer. Exported\n * so we can unit-test the privacy boundary directly.\n */\nexport function publicCfg(cfg: OneShotConfig): Omit<OneShotConfig, \"clientId\"> {\n const { clientId: _omit, ...rest } = cfg;\n void _omit;\n return rest;\n}\n\nfunction identityViews(cfg: OneShotConfig): SenderIdentityView[] {\n const legacy = cfg.emailIdentities == null;\n // Per cap-group: capToday + domainSentToday reflect the shared per-domain\n // budget (all mailboxes on one OneShot domain pool one reputation/limit).\n const caps = identityCapacities();\n return resolveIdentities(cfg).map((i) => {\n const cap = caps.get(i.id);\n return {\n id: i.id,\n provider: i.provider,\n label: i.label ?? null,\n address: i.address ?? null,\n sendingDomain: i.sendingDomain ?? null,\n mailbox: i.mailbox ?? null,\n maxPerDay: i.maxPerDay,\n warmup: i.warmup,\n sentToday: cap?.identitySentToday ?? 0,\n domainSentToday: cap?.domainSentToday ?? 0,\n capToday: cap && Number.isFinite(cap.capToday) ? cap.capToday : null,\n legacy,\n };\n });\n}\n\n/** SDK domain-pool entries → the trimmed shape the browser consumes. */\nfunction domainViews(entries: DomainPoolEntry[]): DomainPoolView[] {\n return entries.map((d) => ({\n domain: d.domain,\n poolStatus: d.pool_status,\n warmupScore: d.warmup_score,\n dailySendLimit: d.daily_send_limit,\n dailySentCount: d.daily_sent_count,\n }));\n}\n\n/**\n * Best-effort provisioned-domain pool for the setup UI. Swallows every failure\n * (transient OR auth) to `[]` so the setup page always renders — a missing\n * domain list degrades the picker, it shouldn't 500 the whole status call.\n */\nasync function provisionedDomainViews(): Promise<DomainPoolView[]> {\n try {\n return domainViews(await listSendingDomains());\n } catch {\n return [];\n }\n}\n\nexport async function getSetupStatus(req: Request): Promise<Response> {\n const cfg = loadConfig();\n return jsonResponse(\n {\n cfg: publicCfg(cfg),\n identities: identityViews(cfg),\n provisionedDomains: await provisionedDomainViews(),\n secretsPath: secretsPath(),\n sources: {\n OPENROUTER_API_KEY: secretSource(\"OPENROUTER_API_KEY\"),\n OPENAI_API_KEY: secretSource(\"OPENAI_API_KEY\"),\n ANTHROPIC_API_KEY: secretSource(\"ANTHROPIC_API_KEY\"),\n CDP_API_KEY_ID: secretSource(\"CDP_API_KEY_ID\"),\n CDP_API_KEY_SECRET: secretSource(\"CDP_API_KEY_SECRET\"),\n CDP_WALLET_SECRET: secretSource(\"CDP_WALLET_SECRET\"),\n AGENT_PRIVATE_KEY: secretSource(\"AGENT_PRIVATE_KEY\"),\n GMAIL_CLIENT_ID: secretSource(\"GMAIL_CLIENT_ID\"),\n GMAIL_CLIENT_SECRET: secretSource(\"GMAIL_CLIENT_SECRET\"),\n GMAIL_REFRESH_TOKEN: secretSource(\"GMAIL_REFRESH_TOKEN\"),\n },\n },\n 200,\n req,\n );\n}\n\nexport async function setup(req: Request): Promise<Response> {\n const body = (await req.json()) as SetupRequest;\n const current = loadConfig();\n const llmProvider: LlmProvider = body.llmProvider ?? current.llmProvider;\n const walletMode: WalletMode = body.walletMode ?? current.walletMode;\n\n // NOTE: we deliberately do NOT reject domains absent from the provisioned\n // pool. A pinned send (we always set from_domain + from_mailbox) names the\n // domain, which AUTO-PROVISIONS it on the platform on first reference — there\n // is no `domain_not_owned` error to pre-empt. The /setup picker and CLI steer\n // toward already-warmed domains; a brand-new one is a legitimate add (it\n // provisions on the first cadence send). The real risk is deliverability, not\n // a hard failure: pinned sends bypass the server's warmup gating, so the\n // client-side warm-up ramp is the only throttle — hence new identities\n // default to it.\n const adds = body.addIdentities ?? [];\n\n // Identity-pool edits (cap changes / removals). The first edit materializes\n // the pool from legacy config so the change has somewhere to persist.\n let emailIdentities = current.emailIdentities;\n const hasIdentityEdits =\n (body.identityUpdates?.length ?? 0) > 0 || (body.removeIdentityIds?.length ?? 0) > 0;\n if (hasIdentityEdits) {\n let pool: EmailIdentity[] = current.emailIdentities ?? resolveIdentities(current);\n for (const upd of body.identityUpdates ?? []) {\n const cap =\n typeof upd.maxPerDay === \"number\" && Number.isFinite(upd.maxPerDay) && upd.maxPerDay >= 0\n ? Math.floor(upd.maxPerDay)\n : null;\n pool = pool.map((i) => (i.id === upd.id ? { ...i, maxPerDay: cap } : i));\n }\n const remove = new Set(body.removeIdentityIds ?? []);\n if (remove.size > 0) {\n pool = pool.filter((i) => !remove.has(i.id));\n for (const id of remove) {\n try {\n deleteGmailToken(id);\n } catch {\n // token-store cleanup is best-effort; the identity is gone either way.\n }\n }\n }\n emailIdentities = pool;\n }\n\n // clientId is preserved from current — body.clientId is intentionally\n // ignored so a malicious or accidental web POST can't rotate the anonymous\n // install id. saveConfig writes the entire cfg, so omitting clientId here\n // would silently drop it from disk.\n saveConfig({\n walletMode,\n llmProvider,\n llmModel: body.llmModel ?? current.llmModel,\n telemetryEnabled: body.telemetryEnabled ?? current.telemetryEnabled,\n founderName: mergeString(body.founderName, current.founderName),\n founderEmail: mergeString(body.founderEmail, current.founderEmail),\n productOneLiner: mergeString(body.productOneLiner, current.productOneLiner),\n productDomain: mergeString(body.productDomain, current.productDomain),\n sendingDomain: mergeString(body.sendingDomain, current.sendingDomain),\n emailProvider:\n body.emailProvider === \"gmail\" || body.emailProvider === \"oneshot\"\n ? body.emailProvider\n : current.emailProvider,\n emailIdentities,\n icpOneLiner: mergeString(body.icpOneLiner, current.icpOneLiner),\n cadenceOverrides: current.cadenceOverrides,\n founderCredentials: mergeString(body.founderCredentials, current.founderCredentials),\n productPortfolio: mergeString(body.productPortfolio, current.productPortfolio),\n partners: mergeString(body.partners, current.partners),\n mobileSignature: body.mobileSignature ?? current.mobileSignature,\n clientId: current.clientId,\n });\n\n // Adds run AFTER the main saveConfig: registerOneShotIdentity reloads the\n // freshly-persisted config (so it sees the cap/removal edits above and any\n // legacy-pool materialization) before appending. Validated already.\n for (const add of adds) {\n if (!add.sendingDomain?.trim()) continue;\n registerOneShotIdentity({\n sendingDomain: add.sendingDomain,\n mailbox: add.mailbox,\n label: add.label,\n ...(\"maxPerDay\" in add ? { maxPerDay: add.maxPerDay ?? null } : {}),\n });\n }\n\n if (body.secrets && Object.keys(body.secrets).length > 0) {\n saveSecrets(body.secrets);\n }\n\n return jsonResponse({ ok: true }, 200, req);\n}\n\n/**\n * Merge a form-submitted string into the stored config:\n * undefined → keep existing (caller didn't touch the field)\n * \"\" → clear (caller deliberately emptied the field)\n * non-empty → trim + save\n */\nfunction mergeString(incoming: string | undefined, current: string | null): string | null {\n if (incoming === undefined) return current;\n const trimmed = incoming.trim();\n return trimmed.length === 0 ? null : trimmed;\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n _resetGmailCache,\n exchangeGmailAuthCode,\n getGmailProfile,\n gmailConsentUrl,\n registerGmailIdentity,\n} from \"@oneshot-gtm/core\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * Browser variant of `oneshot-gtm gmail auth`: /setup's \"Connect Gmail\"\n * button navigates to /start, Google consent redirects back to /callback on\n * this same local server, and the founder lands back on /setup with the\n * outcome in a query param. Server is loopback-only, so the redirect URI is\n * always a 127.0.0.1/localhost origin — valid for Desktop-type OAuth clients.\n */\n\nconst STATE_TTL_MS = 10 * 60 * 1000;\nconst pendingStates = new Map<string, { createdAt: number; redirectUri: string }>();\n\nfunction prune(): void {\n const cutoff = Date.now() - STATE_TTL_MS;\n for (const [state, entry] of pendingStates) {\n if (entry.createdAt < cutoff) pendingStates.delete(state);\n }\n}\n\nfunction clientCreds(): { clientId: string; clientSecret: string } | null {\n const clientId = (process.env[\"GMAIL_CLIENT_ID\"] ?? \"\").trim();\n const clientSecret = (process.env[\"GMAIL_CLIENT_SECRET\"] ?? \"\").trim();\n return clientId && clientSecret ? { clientId, clientSecret } : null;\n}\n\nexport function startGmailAuthRoute(req: Request): Response {\n const creds = clientCreds();\n if (!creds) {\n return jsonResponse(\n { error: \"GMAIL_CLIENT_ID / GMAIL_CLIENT_SECRET not set — save them in /setup first\" },\n 409,\n req,\n );\n }\n prune();\n const url = new URL(req.url);\n const redirectUri = `${url.origin}/api/gmail/auth/callback`;\n const state = randomUUID();\n pendingStates.set(state, { createdAt: Date.now(), redirectUri });\n return Response.redirect(gmailConsentUrl({ clientId: creds.clientId, redirectUri, state }), 302);\n}\n\nexport async function gmailAuthCallbackRoute(req: Request): Promise<Response> {\n const url = new URL(req.url);\n const backToSetup = (outcome: string): Response =>\n Response.redirect(`${url.origin}/setup?gmailAuth=${encodeURIComponent(outcome)}`, 302);\n\n const consentError = url.searchParams.get(\"error\");\n if (consentError) return backToSetup(`error:${consentError}`);\n\n const state = url.searchParams.get(\"state\") ?? \"\";\n const pending = pendingStates.get(state);\n pendingStates.delete(state);\n if (!pending || Date.now() - pending.createdAt > STATE_TTL_MS) {\n return backToSetup(\"error:state mismatch or expired — retry\");\n }\n const code = url.searchParams.get(\"code\");\n if (!code) return backToSetup(\"error:no code in callback\");\n const creds = clientCreds();\n if (!creds) return backToSetup(\"error:client credentials missing\");\n\n try {\n const refreshToken = await exchangeGmailAuthCode({\n code,\n clientId: creds.clientId,\n clientSecret: creds.clientSecret,\n redirectUri: pending.redirectUri,\n });\n // Resolve which account consented BEFORE registering, so the identity id\n // is the real address, not a guess. Throwaway cache key, cleared after.\n _resetGmailCache();\n const { emailAddress } = await getGmailProfile({ id: \"web-auth-pending\", refreshToken });\n _resetGmailCache();\n registerGmailIdentity({ address: emailAddress, refreshToken });\n return backToSetup(`ok:${emailAddress}`);\n } catch (err) {\n return backToSetup(`error:${((err as Error).message ?? \"token exchange failed\").slice(0, 140)}`);\n }\n}\n","import { logEvent, startRun, webRead } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport type { DeriveIcpResult } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nconst PLAY_NAME = \"config:icp\";\n\nexport async function deriveIcpRoute(req: Request): Promise<Response> {\n startRun();\n let body: { domain?: unknown } = {};\n try {\n body = (await req.json()) as { domain?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (typeof body.domain !== \"string\" || body.domain.trim().length === 0) {\n return jsonResponse({ error: \"domain (string) required\" }, 400, req);\n }\n\n const url = normalizeToHttpsUrl(body.domain);\n if (!url) {\n return jsonResponse({ error: `not a valid domain or URL: ${body.domain}` }, 400, req);\n }\n // Hostname is the public domain the founder pasted — not user-typed PII.\n const host = new URL(url).hostname;\n logEvent(\"derive_icp.start\", { host });\n\n let costUsd = 0;\n let markdown = \"\";\n const readStartedAt = Date.now();\n logEvent(\"derive_icp.read.start\", { host });\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n markdown = (read.result.markdown ?? \"\").trim();\n const c = (read.result as unknown as { cost?: number }).cost;\n if (typeof c === \"number\") costUsd += c;\n logEvent(\"derive_icp.read.done\", {\n host,\n duration_ms: Date.now() - readStartedAt,\n markdown_chars: markdown.length,\n cost_usd: costUsd,\n });\n } catch (err) {\n logEvent(\n \"derive_icp.read.error\",\n {\n host,\n duration_ms: Date.now() - readStartedAt,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n return jsonResponse(\n { error: `webRead failed for ${url}: ${(err as Error).message}` },\n 502,\n req,\n );\n }\n\n if (markdown.length < 80) {\n logEvent(\"derive_icp.too_thin\", { host, markdown_chars: markdown.length }, \"warn\");\n return jsonResponse(\n {\n error: `not enough page content to derive an ICP from ${url} (got ${markdown.length} chars). Try a more specific page (pricing, customers, about).`,\n },\n 422,\n req,\n );\n }\n\n const system = loadPrompt(\"icp-derive-from-site\");\n let proposed = \"\";\n const llmStartedAt = Date.now();\n logEvent(\"derive_icp.llm.start\", { host });\n try {\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: markdown.slice(0, 12000) },\n ],\n temperature: 0.2,\n maxTokens: 200,\n });\n proposed = llm.content.trim().replace(/^[\"']|[\"']$/g, \"\");\n logEvent(\"derive_icp.llm.done\", {\n host,\n duration_ms: Date.now() - llmStartedAt,\n response_chars: proposed.length,\n });\n } catch (err) {\n logEvent(\n \"derive_icp.llm.error\",\n {\n host,\n duration_ms: Date.now() - llmStartedAt,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"error\",\n );\n return jsonResponse({ error: `LLM call failed: ${(err as Error).message}` }, 502, req);\n }\n\n if (proposed.toLowerCase().startsWith(\"unable to derive\")) {\n logEvent(\"derive_icp.unable_to_derive\", { host, markdown_chars: markdown.length }, \"warn\");\n return jsonResponse({ error: proposed, sourceUrl: url, costUsd }, 422, req);\n }\n\n logEvent(\"derive_icp.done\", { host, cost_usd: costUsd, response_chars: proposed.length });\n const view: DeriveIcpResult = {\n proposedIcp: proposed,\n sourceUrl: url,\n costUsd,\n };\n return jsonResponse(view, 200, req);\n}\n\n/**\n * Accepts a bare domain (\"acme.com\"), a host with subdomain (\"blog.acme.com\"),\n * or a full URL. Always returns an https:// URL. Rejects anything that doesn't\n * parse as a valid hostname.\n */\nfunction normalizeToHttpsUrl(raw: string): string | null {\n const trimmed = raw.trim().replace(/^https?:\\/\\//, \"\");\n // Strip trailing slashes for the bare-host case so URL doesn't choke.\n const candidate = `https://${trimmed.replace(/^\\/+/, \"\")}`;\n try {\n const u = new URL(candidate);\n // Defense: hostname must contain at least one dot and look like a real\n // public host. Reject localhost / IPs / single-label hosts.\n if (!u.hostname.includes(\".\")) return null;\n if (/^[0-9.]+$/.test(u.hostname)) return null;\n if (u.hostname === \"localhost\") return null;\n return u.toString();\n } catch {\n return null;\n }\n}\n","import { loadConfig, logEvent } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\n\nexport interface IcpFilterResult {\n /**\n * Tri-state:\n * - `true` → candidate matches the ICP (or no ICP set; pass-through)\n * - `false` → real ICP miss → callers persist a rejected row (audit trail\n * + manual override path)\n * - `null` → TRANSIENT classifier failure (LLM 5xx / timeout / rate-limit).\n * Callers must DROP the candidate without persisting — the\n * dedupeKey would otherwise burn for every future watch tick\n * (isQueueDuplicate ignores status).\n */\n match: boolean | null;\n reason: string;\n}\n\n/**\n * Resolve the ICP one-liner: explicit override beats config.\n * Returns null if neither is set — caller should fall back to \"match all\".\n */\nexport function resolveIcp(override?: string): string | null {\n if (override && override.trim().length > 0) return override.trim();\n const cfg = loadConfig();\n return cfg.icpOneLiner;\n}\n\n/**\n * Run the ICP classifier against a single candidate. If no ICP is set, every\n * candidate matches (founder hasn't filtered yet — they'll review in queue).\n */\nexport async function icpFilter(input: {\n icp: string | null;\n candidate: {\n title: string;\n url?: string | null;\n summary?: string | null;\n author?: string | null;\n };\n}): Promise<IcpFilterResult> {\n if (!input.icp) {\n return { match: true, reason: \"no ICP set; pass-through\" };\n }\n const system = loadPrompt(\"icp-filter\");\n const user = JSON.stringify({\n icp: input.icp,\n candidate: input.candidate,\n });\n let decision: IcpFilterResult;\n try {\n const res = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: user },\n ],\n temperature: 0.1,\n maxTokens: 200,\n });\n decision = parseIcpJson(res.content);\n } catch (err) {\n // A classifier failure (LLM timeout / provider error) must not abort the\n // whole finder run — drop just this candidate. Drop-on-error (not\n // pass-through) keeps a systematic outage visible as an empty run rather\n // than flooding the queue with unfiltered candidates.\n logEvent(\n \"error.swallowed\",\n {\n kind: \"icp-filter\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return { match: null, reason: \"icp classifier unavailable\" };\n }\n // Title is a category-ish label sourced from public listings (post titles,\n // job titles, episode titles); reason is the LLM's own classifier output.\n // Neither is user-typed prospect data — safe to log.\n logEvent(\"icp.decision\", {\n match: decision.match,\n reason_120: decision.reason.slice(0, 120),\n candidate_title: input.candidate.title.slice(0, 120),\n });\n return decision;\n}\n\nfunction parseIcpJson(raw: string): IcpFilterResult {\n const parsed = tryParseJsonObject<{ match?: unknown; reason?: unknown }>(raw, {});\n // A malformed / truncated / refused response yields the `{}` fallback (no\n // boolean `match`). Treat that as a transient failure (`null`) — same as a\n // thrown classifier error — so callers drop WITHOUT persisting a rejected\n // row. Collapsing it to `false` would burn the dedupeKey forever, since\n // isQueueDuplicate ignores status.\n if (typeof parsed.match !== \"boolean\") {\n return { match: null, reason: \"icp classifier malformed response\" };\n }\n return {\n match: parsed.match,\n reason: typeof parsed.reason === \"string\" ? parsed.reason : \"no reason given\",\n };\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\n\n/**\n * True if this (play, dedupe-key) pair is already in the queue,\n * OR a prospect with the same email is already known,\n * OR the same email is already pending in the queue under ANOTHER play\n * (cross-play dedup — don't queue + enrich someone a different play already\n * surfaced and is about to email).\n *\n * The email-based checks are gated on `prospectEmail`, so callers that pass\n * `undefined` (breakup-revive, by design) still bypass them to re-engage.\n */\nexport function isDuplicate(opts: {\n playName: string;\n dedupeKey: string;\n prospectEmail?: string | null;\n}): boolean {\n const ledger = getLedger();\n if (ledger.isQueueDuplicate(opts.playName, opts.dedupeKey)) return true;\n if (opts.prospectEmail) {\n const existing = ledger.findProspectByEmail(opts.prospectEmail);\n if (existing) return true;\n if (ledger.isEmailPendingInQueue(opts.prospectEmail)) return true;\n }\n return false;\n}\n\n/** Extract a domain from an email address. Returns null on garbage input. */\nexport function emailDomain(email: string | null | undefined): string | null {\n if (!email) return null;\n const at = email.indexOf(\"@\");\n if (at < 0) return null;\n return email.slice(at + 1).toLowerCase();\n}\n\n/** Extract a domain from a URL. Returns null on garbage input. */\nexport function urlDomain(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const u = new URL(url);\n return u.hostname.replace(/^www\\./, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n","/**\n * Pre-flight guard for `findEmail` SDK calls.\n *\n * The OneShot `findEmail` SDK receives only `company_domain` + `full_name` and\n * guesses email patterns from those. Two structural causes of dud lookups we\n * can catch BEFORE spending the ~$0.05 per call:\n *\n * 1. `company_domain` points at a host where no company hosts email —\n * free-tier app subdomains (vercel.app, github.io, …), social platforms,\n * personal email providers, code hosts, link aggregators.\n * 2. `full_name` is a single-token handle (`samaralihussain`) not a real\n * person name (`Sam Jones`). Pattern-based email guessing can't\n * disambiguate a username.\n *\n * Callers do `shouldSkipFindEmail(...)` ahead of the SDK call; when it\n * returns `{ok:false}`, increment `result.droppedEnrichment` and emit a\n * `finder.skipped_findemail` event for telemetry, then move to the next\n * candidate. No new wire-protocol surface.\n */\n\n/**\n * Hosts where `findEmail` virtually never finds a deliverable company\n * address. Match is exact on the bare host or any subdomain of one of\n * these entries — `foo.vercel.app` and `bar.foo.vercel.app` both qualify.\n *\n * Curated, static. Adaptive/learned variants are out of scope.\n */\nconst DUD_DOMAINS: ReadonlySet<string> = new Set([\n // Free-tier app / preview subdomains.\n \"vercel.app\",\n \"netlify.app\",\n \"github.io\",\n \"pages.dev\",\n \"fly.dev\",\n \"replit.co\",\n \"replit.app\",\n \"codesandbox.io\",\n \"stackblitz.com\",\n \"glitch.me\",\n \"deno.dev\",\n \"workers.dev\",\n \"herokuapp.com\",\n \"onrender.com\",\n \"railway.app\",\n \"modal.run\",\n \"supabase.co\",\n \"firebaseapp.com\",\n \"appspot.com\",\n \"azurewebsites.net\",\n \"webflow.io\",\n \"wixsite.com\",\n \"googleusercontent.com\",\n // Personal / free email providers — the founder isn't reachable via the\n // generic free-tier handle even if findEmail returns something.\n \"gmail.com\",\n \"yahoo.com\",\n \"outlook.com\",\n \"hotmail.com\",\n \"icloud.com\",\n \"proton.me\",\n \"protonmail.com\",\n \"fastmail.com\",\n // Social, community, content hosts.\n \"twitter.com\",\n \"x.com\",\n \"linkedin.com\",\n \"facebook.com\",\n \"instagram.com\",\n \"youtube.com\",\n \"youtu.be\",\n \"reddit.com\",\n \"medium.com\",\n \"dev.to\",\n \"substack.com\",\n \"hashnode.com\",\n \"hashnode.dev\",\n \"notion.site\",\n \"notion.so\",\n \"tiktok.com\",\n \"pinterest.com\",\n \"threads.net\",\n \"discord.com\",\n \"discord.gg\",\n \"slack.com\",\n \"news.ycombinator.com\",\n // Investor / startup-data aggregators — every result here is a profile\n // page about a company, not the company's own domain.\n \"crunchbase.com\",\n \"producthunt.com\",\n \"wellfound.com\",\n \"pitchbook.com\",\n \"cbinsights.com\",\n \"tracxn.com\",\n // Code hosts (when this is the ONLY domain signal — caller already\n // failed to find a company website).\n \"github.com\",\n \"gitlab.com\",\n \"bitbucket.org\",\n \"gist.github.com\",\n // Link aggregators.\n \"linktr.ee\",\n \"bio.link\",\n \"carrd.co\",\n]);\n\n/**\n * True when the given domain is in the dud blocklist, either as an exact\n * match or as a subdomain (so `foo.vercel.app` is dud). `null`/empty\n * counts as dud — caller has no usable signal.\n *\n * Defensive normalization before matching:\n * - lowercase + trim whitespace\n * - strip `http://` / `https://` scheme\n * - strip everything from the first `/` onward (paths/queries)\n * - strip leading `www.` and trailing `.`\n *\n * Callers should pass bare hostnames (via `urlDomain` from `_dedupe.ts`),\n * but the normalization keeps an accidental full URL or trailing-dot DNS\n * form from silently slipping past the suffix match.\n *\n * Does no DNS lookup — purely suffix-based.\n */\nexport function isDudDomain(domain: string | null | undefined): boolean {\n if (!domain) return true;\n const d = domain\n .trim()\n .toLowerCase()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/[/?#].*$/, \"\")\n .replace(/^www\\./, \"\")\n .replace(/\\.+$/, \"\");\n if (d.length === 0) return true;\n if (DUD_DOMAINS.has(d)) return true;\n for (const dud of DUD_DOMAINS) {\n if (d.endsWith(`.${dud}`)) return true;\n }\n return false;\n}\n\n/**\n * True when the input looks like a single-token username/handle rather\n * than a real person name. Heuristics, in order:\n *\n * - Empty / null → handle (no signal).\n * - Contains whitespace → looks like a name. `\"Sam Jones\"`.\n * - Contains a period → looks like a name. `\"Sam J. Jones\"`.\n * - Single token of `[a-z0-9_-]` (case-insensitive) → handle.\n *\n * False-positive accepted: a real single-name like `Madonna` reads as a\n * handle. That's a fine tradeoff vs the volume of HN-style usernames we\n * filter out (90%+ of Show HN authors).\n */\nexport function looksLikeUserHandle(name: string | null | undefined): boolean {\n if (name == null) return true;\n const trimmed = name.trim();\n if (trimmed.length === 0) return true;\n if (/\\s/.test(trimmed)) return false;\n if (trimmed.includes(\".\")) return false;\n return /^[a-z0-9_-]+$/i.test(trimmed);\n}\n\n/**\n * Pre-flight guard. Returns `{ok:true}` to proceed with the SDK call, or\n * `{ok:false, reason}` to skip. The reason is human-readable and stable\n * across releases — safe to log via `finder.skipped_findemail` for later\n * blocklist tuning.\n *\n * Check order matters: a missing/dud domain dominates a handle check (no\n * point flagging \"handle-not-name\" when the domain alone would have\n * disqualified the row).\n */\nexport function shouldSkipFindEmail(input: {\n fullName?: string | null;\n companyDomain: string | null;\n}): { ok: true } | { ok: false; reason: string } {\n if (!input.companyDomain || input.companyDomain.trim().length === 0) {\n return { ok: false, reason: \"no-domain\" };\n }\n if (isDudDomain(input.companyDomain)) {\n return { ok: false, reason: `dud-domain: ${input.companyDomain.toLowerCase()}` };\n }\n const name = input.fullName?.trim() ?? \"\";\n if (name.length === 0) {\n return { ok: false, reason: \"no-fullname\" };\n }\n if (looksLikeUserHandle(name)) {\n return { ok: false, reason: `handle-not-name: ${name}` };\n }\n return { ok: true };\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\n\n/**\n * Process-wide circuit breaker for OneShot paid contact-resolution calls\n * (findEmail/verifyEmail). During a backend outage EVERY candidate's resolution\n * throws; without this, a run burns ~70s + spend per candidate draining all of\n * them through doomed calls (and drops each as if it were a bad candidate).\n *\n * State machine (closed → open → half-open → closed/open):\n * - CLOSED: calls flow normally. `isCircuitOpen()` → false.\n * - OPEN: trips after N consecutive platform errors. `isCircuitOpen()` → true,\n * so `resolveAndVerifyContact` short-circuits (no spend) for COOLDOWN_MS.\n * - HALF-OPEN: once the cooldown elapses, `isCircuitOpen()` → false again so the\n * next resolution issues a real probe call. That call's outcome either CLOSES\n * the breaker (success) or RE-ARMS the cooldown (failure) — so a sustained\n * outage keeps short-circuiting between probes instead of hammering, and a\n * recovered backend closes the breaker on the first probe. Without the\n * cooldown the breaker would latch open forever (nothing calls\n * recordResolutionOutcome while open), permanently breaking finders until a\n * process restart.\n *\n * The counter is process-wide and only platform errors (`status:\"error\"` from\n * the safe wrappers) count toward tripping; any genuine outcome resets it, so a\n * run of legitimately-unresolvable candidates never opens it.\n */\nconst THRESHOLD = 5;\nexport const COOLDOWN_MS = 60_000;\nlet consecutivePlatformErrors = 0;\nlet open = false;\nlet openedAt = 0;\n\n/** Record one resolution outcome. `isPlatformError` = the backend threw/timed out. */\nexport function recordResolutionOutcome(isPlatformError: boolean): void {\n if (isPlatformError) {\n consecutivePlatformErrors++;\n if (!open && consecutivePlatformErrors >= THRESHOLD) {\n open = true;\n openedAt = Date.now();\n logEvent(\n \"finder.circuit_open\",\n { consecutive: consecutivePlatformErrors, reason: \"oneshot resolution unavailable\" },\n \"warn\",\n );\n } else if (open) {\n // A half-open probe failed (or errors kept landing while open) — re-arm\n // the cooldown so we short-circuit again instead of hammering.\n openedAt = Date.now();\n }\n } else {\n if (open) logEvent(\"finder.circuit_reset\", {});\n consecutivePlatformErrors = 0;\n open = false;\n }\n}\n\n/**\n * True while the breaker is open AND within the cooldown — callers short-circuit\n * (skip paid resolution, defer). Returns false once the cooldown elapses\n * (half-open: let the next call probe for recovery) or when fully closed.\n */\nexport function isCircuitOpen(): boolean {\n if (!open) return false;\n return Date.now() - openedAt < COOLDOWN_MS;\n}\n\n/** Test-only: reset breaker state between cases. */\nexport function _resetBreaker(): void {\n consecutivePlatformErrors = 0;\n open = false;\n openedAt = 0;\n}\n","import { findEmail, logEvent, verifyEmail } from \"@oneshot-gtm/core\";\nimport type { CallContext, FindEmailInput, VerifyEmailInput } from \"@oneshot-gtm/core\";\n\n/**\n * Per-candidate-safe wrappers for the two job-based contact-resolution SDK calls.\n *\n * Finders process candidates concurrently via `parallelMap` (errors propagate\n * through Promise.all) or in sequential loops. An unguarded throw from one\n * candidate's `findEmail`/`verifyEmail` — e.g. a OneShot backend job timeout —\n * rejects the whole batch and aborts the entire trigger run. These wrappers\n * swallow the throw, log `error.swallowed`, and return a graceful \"not found /\n * not deliverable\" sentinel so the caller's existing drop branch handles just\n * that candidate and the run continues. Same pattern as `enrichVerifiedContact`\n * (_enrich.ts) and `findLinkedInUrl` (_linkedin.ts). The full `CallContext` is\n * forwarded unchanged, so audit/decisionContext metadata is preserved.\n */\n\nfunction swallow(ctx: CallContext, call: string, err: unknown): void {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${ctx.playName}.${call}`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n}\n\n/** findEmail that never throws — a failure resolves to `found: false` (drop). */\nexport async function safeFindEmail(\n input: FindEmailInput,\n ctx: CallContext,\n): Promise<Awaited<ReturnType<typeof findEmail>>> {\n try {\n return await findEmail(input, ctx);\n } catch (err) {\n swallow(ctx, \"find_email\", err);\n // cost 0 / receiptId 0 mirror the cache-miss sentinels in _enrich.ts.\n return { result: { status: \"error\", email: null, found: false, cost: 0 }, receiptId: 0 };\n }\n}\n\n/** verifyEmail that never throws — a failure resolves to `deliverable: false` (drop). */\nexport async function safeVerifyEmail(\n input: VerifyEmailInput,\n ctx: CallContext,\n): Promise<Awaited<ReturnType<typeof verifyEmail>>> {\n try {\n return await verifyEmail(input, ctx);\n } catch (err) {\n swallow(ctx, \"verify_email\", err);\n return {\n result: {\n status: \"error\",\n email: input.email,\n valid: false,\n deliverable: false,\n catch_all: false,\n disposable: false,\n cost: 0,\n },\n receiptId: 0,\n };\n }\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport type { CallContext, FindEmailInput } from \"@oneshot-gtm/core\";\nimport { isCircuitOpen, recordResolutionOutcome } from \"./_breaker.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { safeFindEmail, safeVerifyEmail } from \"./_sdk-safe.ts\";\n\n/**\n * Outcome of the shared contact-resolution spine. On `ok`, the caller has a\n * verified, non-duplicate email; otherwise `reason` says which gate dropped the\n * candidate. `costUsd` is the find + verify spend accrued so far — returned on\n * EVERY path so callers never lose cost tracking on a drop.\n */\nexport type ContactResolution =\n | { ok: true; email: string; fullName: string | null; costUsd: number }\n | {\n ok: false;\n reason:\n | \"no-domain\"\n | \"prescreen\"\n | \"not-found\"\n | \"duplicate\"\n | \"undeliverable\"\n // The backend threw/timed out — NOT a verdict about the candidate.\n // Callers should defer/persist-for-retry rather than treat as bad.\n | \"platform-error\";\n costUsd: number;\n };\n\n/**\n * The prescreen → findEmail → dedupe → verify spine shared by every enqueueing\n * finder. Extracted so the per-candidate isolation (safeFindEmail/safeVerifyEmail\n * never throw) and the dedupe-before-verify ordering live in one place instead\n * of being re-implemented (and drifting) in each finder.\n *\n * Boundary: this owns email resolution + verification only. Downstream steps\n * (enrichVerifiedContact, findLinkedInUrl, webRead, enqueue) stay in the caller\n * because they vary too much between finders.\n *\n * - `knownEmail`: when the caller already has a usable email (a public profile\n * email, or one surfaced by LinkedIn enrichment), pass it to skip the\n * prescreen + findEmail entirely.\n * - `companyDomain`: required when `knownEmail` is absent (the findEmail input).\n * - `isDuplicate`: called with the resolved email BEFORE verify, so a\n * cross-table duplicate is dropped without paying for a verify call. Dedupe\n * stays caller-owned (each finder has its own `dedupeKey`).\n * - `decisionContext`: threaded to both findEmail and verify as audit metadata.\n */\nexport async function resolveAndVerifyContact(args: {\n playName: string;\n fullName: string | null;\n knownEmail?: string | null;\n companyDomain?: string | null;\n isDuplicate?: (email: string) => boolean;\n decisionContext?: CallContext[\"decisionContext\"];\n}): Promise<ContactResolution> {\n const ctx: CallContext = { playName: args.playName };\n if (args.decisionContext) ctx.decisionContext = args.decisionContext;\n\n let costUsd = 0;\n let email: string;\n let fullName = args.fullName;\n\n if (args.knownEmail) {\n email = args.knownEmail;\n } else {\n if (!args.companyDomain) return { ok: false, reason: \"no-domain\", costUsd };\n const skip = shouldSkipFindEmail({\n fullName: args.fullName,\n companyDomain: args.companyDomain,\n });\n if (!skip.ok) {\n logEvent(\"finder.skipped_findemail\", { name: args.playName, reason: skip.reason }, \"info\");\n return { ok: false, reason: \"prescreen\", costUsd };\n }\n // Circuit open (backend outage): skip the paid call entirely — fast-fail as\n // a platform error so the caller defers instead of burning spend + ~70s.\n if (isCircuitOpen()) return { ok: false, reason: \"platform-error\", costUsd };\n const findInput: FindEmailInput = { companyDomain: args.companyDomain };\n if (args.fullName) findInput.fullName = args.fullName;\n const found = await safeFindEmail(findInput, ctx);\n costUsd += found.result.cost ?? 0;\n // status:\"error\" = the safe wrapper caught a throw (platform/transport\n // failure), NOT a genuine \"no email for this person\". Don't treat as a\n // verdict; feed the breaker and defer.\n if (found.result.status === \"error\") {\n recordResolutionOutcome(true);\n return { ok: false, reason: \"platform-error\", costUsd };\n }\n recordResolutionOutcome(false); // backend answered (found or genuinely not)\n if (!found.result.found || !found.result.email) {\n return { ok: false, reason: \"not-found\", costUsd };\n }\n email = found.result.email;\n fullName = found.result.full_name ?? args.fullName;\n }\n\n if (args.isDuplicate?.(email)) return { ok: false, reason: \"duplicate\", costUsd };\n\n if (isCircuitOpen()) return { ok: false, reason: \"platform-error\", costUsd };\n const verified = await safeVerifyEmail({ email }, ctx);\n costUsd += verified.result.cost ?? 0;\n if (verified.result.status === \"error\") {\n recordResolutionOutcome(true);\n return { ok: false, reason: \"platform-error\", costUsd };\n }\n recordResolutionOutcome(false);\n if (!verified.result.deliverable) return { ok: false, reason: \"undeliverable\", costUsd };\n\n return { ok: true, email, fullName, costUsd };\n}\n","import { logEvent, webSearch } from \"@oneshot-gtm/core\";\n\n/**\n * Shared LinkedIn / phone capture helpers used across all finders. Centralises:\n * - `findLinkedInUrl`: webSearch-based LinkedIn-URL discovery (active lookup)\n * - `extractFirstPhone`: passive read of phone fields from enrichment SDK results\n *\n * Both feed the same goal — populate `target.linkedinUrl` and `target.phone` so\n * the founder sees these signals in /queue review and the prospect row carries\n * them after drain.\n */\n\nconst PLAY_NAME = \"linkedin-lookup\";\n\n/** Match `linkedin.com/in/<slug>` profile URLs. The slug class is permissive\n * enough to cover URL-encoded unicode slugs (e.g. `%E7%8E%8B`) which LinkedIn\n * does serve for non-Latin display names. */\nconst LINKEDIN_PROFILE_RX = /^https?:\\/\\/(?:[a-z0-9-]+\\.)*linkedin\\.com\\/in\\/[a-z0-9-_.%]+/i;\n\n/** Per-process cache so the same `(fullName, disambiguators)` doesn't re-search\n * within a run. `null` is a real cached value (means \"we tried and missed\"). */\nconst cache = new Map<string, string | null>();\n\n/** Test-only: reset the cache between cases. */\nexport function _resetLinkedInCache(): void {\n cache.clear();\n}\n\n/**\n * Returns true when `url` looks like a LinkedIn profile URL (`linkedin.com/in/<slug>`).\n * Use to validate LLM-extracted `linkedinUrl` strings before persisting them —\n * the prompt instructs the LLM to emit only profile URLs but real outputs drift\n * (sometimes a `/posts/` URL, sometimes free-form prose).\n */\nexport function isLinkedInProfileUrl(url: string | null | undefined): boolean {\n if (!url || typeof url !== \"string\") return false;\n return LINKEDIN_PROFILE_RX.test(url.trim());\n}\n\n/**\n * Find a LinkedIn profile URL for a person via webSearch.\n *\n * Query shape: `\"<fullName>\" \"<disambig1>\" \"<disambig2>\" site:linkedin.com/in`.\n * The `site:` operator narrows results to actual profile pages (not company\n * pages or jobs). We iterate `webSearch` result URLs and return the first that\n * matches `linkedin.com/in/<slug>`. No regex over freeform text — webSearch\n * returns structured `{url, title, description}` results.\n *\n * Returns null on:\n * - empty fullName\n * - no result URL matches the LinkedIn-profile shape\n * - webSearch throws (logged as `error.swallowed` so the caller's pipeline\n * doesn't tear down)\n *\n * Cost: ~$0.01 per call (one webSearch). Cached per-run by\n * `(fullName, disambiguators)` so duplicate calls within a finder run are free.\n */\nexport async function findLinkedInUrl(args: {\n fullName: string;\n /** Optional tokens that narrow the search — company name, github handle,\n * podcast name, cohort label, etc. Each becomes a quoted token in the query. */\n disambiguators?: string[];\n accumCost: (c: number | undefined) => void;\n /** Used in the error.swallowed event kind, e.g. \"github-topics\" or \"show-hn\". */\n errKindPrefix: string;\n}): Promise<string | null> {\n const fullName = args.fullName.trim();\n if (fullName.length === 0) return null;\n\n const disambiguators = (args.disambiguators ?? [])\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const cacheKey = JSON.stringify([\n fullName.toLowerCase(),\n disambiguators.map((s) => s.toLowerCase()),\n ]);\n if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null;\n\n const tokens = [fullName, ...disambiguators];\n const query = `${tokens.map((t) => `\"${t}\"`).join(\" \")} site:linkedin.com/in`;\n try {\n const search = await webSearch({ query, maxResults: 5 }, { playName: PLAY_NAME });\n args.accumCost(search.result.cost ?? 0);\n for (const r of search.result.results ?? []) {\n const url = typeof r.url === \"string\" ? r.url : \"\";\n if (LINKEDIN_PROFILE_RX.test(url)) {\n cache.set(cacheKey, url);\n logEvent(\"linkedin.search.found\", { full_name: fullName, url });\n return url;\n }\n }\n cache.set(cacheKey, null);\n logEvent(\"linkedin.search.miss\", { full_name: fullName, disambiguators });\n return null;\n } catch (err) {\n cache.set(cacheKey, null);\n logEvent(\n \"error.swallowed\",\n {\n kind: `${args.errKindPrefix}.linkedin_search`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Pull the first usable phone number out of either an enrichProfile or a\n * deepResearchPerson result shape. Both SDK results may surface a phone — this\n * is the single read site so finders don't have to know which shape they got.\n *\n * Shapes accepted:\n * - deepResearchPerson: `enrichment.fullphone[0].fullphone` (array of objects)\n * - enrichProfile: `profile.phone` (single string)\n * - LLM extracts: `extract.phone` (single string)\n *\n * Returns the raw string from whichever source. No normalization — defer\n * E.164 formatting until a downstream consumer needs it.\n */\nexport function extractFirstPhone(source: unknown): string | null {\n if (!source || typeof source !== \"object\") return null;\n const obj = source as Record<string, unknown>;\n\n // deepResearchPerson `enrichment.fullphone` array shape\n const fullphone = obj[\"fullphone\"];\n if (Array.isArray(fullphone)) {\n for (const entry of fullphone) {\n if (entry && typeof entry === \"object\") {\n const v = (entry as Record<string, unknown>)[\"fullphone\"];\n if (typeof v === \"string\" && v.trim().length > 0) return v.trim();\n } else if (typeof entry === \"string\" && entry.trim().length > 0) {\n return entry.trim();\n }\n }\n }\n\n // enrichProfile `profile.phone` OR LLM-extract `extract.phone` shape\n const phone = obj[\"phone\"];\n if (typeof phone === \"string\" && phone.trim().length > 0) return phone.trim();\n\n return null;\n}\n","import {\n ENRICH_CACHE_TTL_MS,\n ENRICH_DEADLINE_MS,\n ENRICH_FAILURE_TTL_MS,\n enrichProfile,\n getLedger,\n isTransientToolError,\n logEvent,\n withDeadline,\n} from \"@oneshot-gtm/core\";\nimport { extractFirstPhone, isLinkedInProfileUrl } from \"./_linkedin.ts\";\n\nexport interface EnrichedContact {\n phone: string | null;\n linkedinUrl: string | null;\n costUsd: number;\n receiptId: number | null;\n}\n\n/**\n * Always-on post-verify enrichment. Called by every enqueueing finder\n * AFTER verifyEmail succeeds + BEFORE enqueueTarget. Reads phone +\n * linkedin off PersonResult and returns them; finder merges into target.\n *\n * Why this exists: phone capture used to fire only on the narrow Path B'\n * + Path C branches in `_repo-pipeline.ts` (~10% of candidates), and the\n * other 6 finders never enriched at all. Empirical audit found 0/514\n * queue rows had a phone despite the SDK clearly returning some on\n * separate enrichProfile calls. Adding one $0.005 call per verified\n * email closes the gap uniformly across every play.\n *\n * Throws are swallowed — one transient SDK blip should never kill an\n * otherwise valid enqueue. Same try/catch pattern as the existing\n * Path B' enrichProfile call in `_repo-pipeline.ts`.\n */\nexport async function enrichVerifiedContact(\n email: string,\n opts: { playName: string; errKindPrefix?: string },\n): Promise<EnrichedContact> {\n const ledger = getLedger();\n const key = email.trim().toLowerCase();\n\n // Cache-read short-circuit. If a prior find pass already enriched this email\n // (either via this function OR via the linkedin-keyed sites in luma.ts /\n // _repo-pipeline.ts that ALSO populate the same cache by surfaced email),\n // skip the SDK call entirely — phone + linkedin can be derived from the\n // cached profile. This eliminates the double-enrich on linkedin-bearing\n // candidates (find used to pay $0.005 twice + ~70s twice per such person).\n // Mirrors the read pattern in safeEnrich at packages/plays/src/_lib.ts:31.\n try {\n const cached = ledger.getCachedEnrichment(key);\n // Fresh negative entry: the SDK job failed recently for this email —\n // skip the retry, the finder proceeds without phone/linkedin.\n if (\n cached?.status === \"failed\" &&\n Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_FAILURE_TTL_MS\n ) {\n return { phone: null, linkedinUrl: null, costUsd: 0, receiptId: null };\n }\n if (\n cached &&\n cached.status !== \"failed\" &&\n Date.now() - new Date(cached.fetched_at).getTime() < ENRICH_CACHE_TTL_MS\n ) {\n try {\n const cachedResult = JSON.parse(cached.result_json) as {\n profile?: Parameters<typeof extractFirstPhone>[0];\n };\n const profile = cachedResult.profile ?? null;\n const linkedinRaw =\n (profile as { linkedin_url?: string | null } | null)?.linkedin_url ?? null;\n return {\n phone: extractFirstPhone(profile),\n linkedinUrl: isLinkedInProfileUrl(linkedinRaw) ? linkedinRaw : null,\n // Cache hit: no new SDK call, so no new spend and no new receipt\n // attributed to this call. The original receipt is still on file\n // from whatever finder first paid for the enrichment.\n costUsd: 0,\n receiptId: null,\n };\n } catch {\n // Corrupt cache row — fall through to a fresh SDK call.\n }\n }\n } catch {\n // Ledger read failed — fall through to the SDK path.\n }\n\n try {\n const live = enrichProfile(\n { email },\n {\n playName: opts.playName,\n decisionContext: { source: \"finder.post_verify\", prospectEmail: email },\n },\n );\n // Populate the same per-email enrichment cache that `safeEnrich` reads on\n // /run dispatch. Rides on the LIVE promise (not the deadline race) so a\n // call that outlives the deadline still records its outcome — a late\n // success overwrites the failure marker the catch below writes.\n live.then(\n (out) => {\n try {\n ledger.setCachedEnrichment(key, JSON.stringify(out.result));\n } catch {\n // cache write is best-effort — find's contract is phone + linkedin,\n // not populating a cache. A SQLite hiccup shouldn't break the enqueue.\n }\n },\n () => {\n // Rejections surface through the race below; this only silences the\n // abandoned promise's unhandled-rejection noise.\n },\n );\n const enriched = await withDeadline(live, ENRICH_DEADLINE_MS, \"enrichProfile\");\n const profile = enriched.result.profile;\n const linkedinRaw = profile?.linkedin_url ?? null;\n return {\n phone: extractFirstPhone(profile),\n linkedinUrl: isLinkedInProfileUrl(linkedinRaw) ? linkedinRaw : null,\n costUsd: enriched.result.cost ?? 0,\n receiptId: enriched.receiptId,\n };\n } catch (err) {\n const message = (err as Error).message ?? \"\";\n logEvent(\n \"error.swallowed\",\n {\n kind: `${opts.errKindPrefix ?? \"enrich\"}.post_verify`,\n message_120: message.slice(0, 120),\n },\n \"warn\",\n );\n // Negative-cache only a GENUINE no-data failure. A transient platform error\n // (worker crash / timeout / 5xx — the 2026-06 outage) must NOT be cached, or\n // the email stays un-enrichable for ENRICH_FAILURE_TTL_MS after recovery.\n if (!isTransientToolError(err)) {\n try {\n ledger.setCachedEnrichmentFailure(key, message);\n } catch {\n // cache write is best-effort\n }\n }\n return { phone: null, linkedinUrl: null, costUsd: 0, receiptId: null };\n }\n}\n","import { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport { isCircuitOpen } from \"./_breaker.ts\";\n\n/**\n * Retry queue for candidates whose paid contact-resolution hit a TRANSIENT\n * platform error (the OneShot outage). Re-scannable finders self-heal on their\n * next run, but time-windowed ones (luma-events, show-hn) can't re-discover an\n * expired source — so they persist the raw candidate here and a scheduler pass\n * drains it once the backend recovers.\n *\n * Each participating finder registers a retry handler keyed by play name; the\n * handler re-runs that finder's per-candidate resolve→enqueue for one persisted\n * `raw` blob and reports the outcome. Finders with no handler (the re-scannable\n * ones) never persist here, so the runner simply skips/sweeps any it doesn't own.\n */\nexport type RetryOutcome = \"enqueued\" | \"dropped\" | \"platform-error\";\ntype RetryHandler = (raw: unknown) => Promise<RetryOutcome>;\n\nconst handlers = new Map<string, RetryHandler>();\n\nexport function registerPendingRetry(playName: string, handler: RetryHandler): void {\n handlers.set(playName, handler);\n}\n\n/** Persist a candidate that hit a transient platform error during resolution. */\nexport function persistPending(input: {\n playName: string;\n dedupeKey: string;\n source: string;\n raw: unknown;\n}): void {\n getLedger().upsertPendingResolution(input);\n}\n\n/** Stale cutoff: a candidate not resolved within a week (source likely expired). */\nconst STALE_MS = 7 * 24 * 3600 * 1000;\n/** Cap retries per tick so a large backlog can't stall the scheduler loop. */\nconst MAX_PER_TICK = 25;\n\n/**\n * Drain pending rows once the platform is healthy. Called by the scheduler tick.\n * Sweeps stale rows first, then retries up to MAX_PER_TICK via each row's\n * registered handler. A still-`platform-error` outcome keeps the row for next\n * tick; enqueued/dropped remove it. Defers entirely while the breaker is open.\n */\nexport async function runPendingRetries(): Promise<{\n retried: number;\n enqueued: number;\n dropped: number;\n deferred: number;\n swept: number;\n}> {\n const ledger = getLedger();\n const swept = ledger.sweepStalePendingResolution(STALE_MS);\n const out = { retried: 0, enqueued: 0, dropped: 0, deferred: 0, swept };\n const rows = ledger.listPendingResolution({ limit: MAX_PER_TICK });\n for (const row of rows) {\n const handler = handlers.get(row.play_name);\n if (!handler) continue; // re-scannable finder (no handler) — leave for the sweep\n if (isCircuitOpen()) {\n out.deferred++;\n continue; // platform still down — don't hammer it\n }\n out.retried++;\n ledger.markPendingResolutionAttempted(row.play_name, row.dedupe_key);\n let outcome: RetryOutcome;\n try {\n outcome = await handler(JSON.parse(row.raw_json));\n } catch (err) {\n logEvent(\n \"finder.pending_retry.error\",\n { play: row.play_name, message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n outcome = \"platform-error\";\n }\n if (outcome === \"enqueued\") {\n ledger.deletePendingResolution(row.play_name, row.dedupe_key);\n out.enqueued++;\n } else if (outcome === \"dropped\") {\n ledger.deletePendingResolution(row.play_name, row.dedupe_key);\n out.dropped++;\n } else {\n out.deferred++; // platform-error: keep for the next tick\n }\n }\n if (out.retried > 0 || out.swept > 0) logEvent(\"finder.pending_retry.done\", out);\n return out;\n}\n\n/** Test-only: clear the handler registry between cases. */\nexport function _clearPendingHandlers(): void {\n handlers.clear();\n}\n","import { getLedger, logEvent, webRead } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport type { ShowHnTarget } from \"@oneshot-gtm/plays\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl } from \"./_linkedin.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport { persistPending, registerPendingRetry } from \"./_pending.ts\";\nimport type { FinderResult, RunOpts, ShowHnHit } from \"./_types.ts\";\n\nconst HN_ALGOLIA = \"https://hn.algolia.com/api/v1/search_by_date\";\nconst PLAY_NAME = \"show-hn\";\nconst SOURCE = \"find:show-hn\";\n\nexport interface ShowHnFinderOpts extends RunOpts {\n /** Look back this many days. Default 1. */\n sinceDays?: number;\n /** Skip posts with fewer points than this. Default 5. */\n minPoints?: number;\n /** Max per-candidate pipelines in flight at once. Default 3. */\n concurrency?: number;\n}\n\ninterface SearchHitsResponse {\n hits: ShowHnHit[];\n}\n\n/**\n * Pulls Show HN posts from HN Algolia, ICP-filters them, enriches founder\n * contact via OneShot, dedupes against the ledger, and enqueues into target_queue.\n */\nexport async function runShowHnFinder(opts: ShowHnFinderOpts): Promise<FinderResult> {\n const sinceDays = opts.sinceDays ?? 1;\n const minPoints = opts.minPoints ?? 5;\n const limit = opts.limit ?? 25;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n droppedLowSignal: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n logEvent(\"finder.start\", { name: PLAY_NAME, since_days: sinceDays, limit });\n const sinceUnix = Math.floor((Date.now() - sinceDays * 24 * 3600 * 1000) / 1000);\n const url = `${HN_ALGOLIA}?tags=show_hn&numericFilters=created_at_i>${sinceUnix}&hitsPerPage=${Math.min(50, limit * 2)}`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`HN Algolia fetch failed: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as SearchHitsResponse;\n result.candidates = data.hits.length;\n logEvent(\"finder.fetched\", { name: PLAY_NAME, candidates: result.candidates });\n\n // Per-candidate pipeline runs at `concurrency` (mirrors accelerator-batch /\n // github-topics) — the serial version spent ~70s on 50 candidates waiting on\n // findEmail/verify/enrich one at a time. `halted` is a soft cap: workers in\n // flight when the limit/cost-cap trips may overshoot by up to\n // (concurrency - 1) candidates. The `result.*` accumulators are mutated in\n // place; safe because JS interleaves (never truly parallel) between awaits.\n const concurrency = opts.concurrency ?? 3;\n let halted = false;\n\n await parallelMap(data.hits, concurrency, async (hit) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n if (hit.points < minPoints) {\n result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;\n return;\n }\n\n // Dedupe BEFORE any LLM/OneShot spend — against the queue AND the\n // pending-retry table (so a re-scan doesn't recreate a candidate already\n // awaiting outage retry).\n if (\n ledger.isQueueDuplicate(PLAY_NAME, hit.objectID) ||\n ledger.isPendingResolution(PLAY_NAME, hit.objectID)\n ) {\n result.droppedDuplicate++;\n return;\n }\n\n // ICP filter.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: hit.title,\n url: hit.url,\n summary: hit.story_text?.slice(0, 800) ?? null,\n author: hit.author,\n },\n });\n // Rough cost: ~$0.001 per filter call (LLM tokens; not OneShot $).\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n return;\n }\n if (!filter.match) {\n result.droppedIcp++;\n // Persist the auto-rejection so the founder can review what got\n // dropped, override (set to approved) if it was a false negative,\n // and so the future learning loop has labeled examples.\n if (!opts.dryRun) {\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { postTitle: hit.title, postUrl: hit.url, founderName: hit.author },\n dedupeKey: hit.objectID,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n }\n return;\n }\n\n if (opts.dryRun) {\n // Just count — don't enrich or enqueue.\n result.enqueued++;\n return;\n }\n\n // Shared resolve→enqueue spine (also used by the pending-retry handler).\n const outcome = await resolveAndEnqueueShowHn(hit, filter.reason, (c) => {\n result.costUsd += c;\n });\n if (outcome === \"enqueued\") result.enqueued++;\n else if (outcome === \"duplicate\") result.droppedDuplicate++;\n else if (outcome === \"platform-error\") {\n // Backend outage: don't lose the candidate (the HN post ages out of the\n // Algolia window, so a re-scan can't recover it). Persist for retry.\n persistPending({\n playName: PLAY_NAME,\n dedupeKey: hit.objectID,\n source: SOURCE,\n raw: { hit, filterReason: filter.reason },\n });\n result.droppedEnrichment++;\n } else result.droppedEnrichment++;\n });\n\n logEvent(\"finder.done\", {\n name: PLAY_NAME,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n dropped_low_signal: result.droppedLowSignal ?? 0,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return result;\n}\n\n/**\n * Resolve + enrich + enqueue one already-ICP-passed Show HN candidate. Shared\n * by the live run loop and the outage retry handler. `costSink` accumulates\n * spend into the caller's running total (a no-op for retries). Returns a coarse\n * outcome the caller maps to counters / pending persistence.\n */\nasync function resolveAndEnqueueShowHn(\n hit: ShowHnHit,\n filterReason: string,\n costSink: (c: number) => void,\n): Promise<\"enqueued\" | \"duplicate\" | \"dropped\" | \"platform-error\"> {\n const ledger = getLedger();\n const domain = urlDomain(hit.url);\n if (!domain) return \"dropped\";\n\n const fullName = hit.author && hit.author.length > 0 ? hit.author : null;\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName,\n companyDomain: domain,\n isDuplicate: (email) =>\n isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.objectID, prospectEmail: email }),\n });\n costSink(contact.costUsd);\n if (!contact.ok) {\n if (contact.reason === \"platform-error\") return \"platform-error\";\n if (contact.reason === \"duplicate\") return \"duplicate\";\n return \"dropped\";\n }\n const email = contact.email;\n\n // Optional: read the landing page for a richer hookSummary.\n let hookSummary = (hit.story_text ?? \"\").trim().slice(0, 280);\n if (hookSummary.length < 40 && hit.url) {\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n costSink(read.result.cost ?? 0);\n hookSummary = (read.result.markdown ?? \"\").trim().slice(0, 280);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"show-hn.hookSummary.webRead\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n if (!hookSummary || hookSummary.length < 20) {\n hookSummary = `Show HN post: ${hit.title}. ${hit.points} points.`;\n }\n\n const founderName = contact.fullName ?? hit.author;\n const enr = await enrichVerifiedContact(email, { playName: PLAY_NAME, errKindPrefix: \"show-hn\" });\n costSink(enr.costUsd);\n const phone = enr.phone;\n let linkedinUrl: string | null = enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: founderName,\n disambiguators: [\"hacker news\", domain],\n accumCost: (c) => costSink(c ?? 0),\n errKindPrefix: \"show-hn\",\n });\n }\n\n const target: ShowHnTarget = {\n postTitle: hit.title,\n postUrl: `https://news.ycombinator.com/item?id=${hit.objectID}`,\n founderName,\n founderEmail: email,\n hookSummary,\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.objectID,\n source: SOURCE,\n notes: filterReason,\n });\n return id != null ? \"enqueued\" : \"duplicate\";\n}\n\n// Outage retry: re-run the resolve→enqueue spine for a persisted candidate.\n// \"enqueued\" → done; \"platform-error\" → keep for the next tick; dup/dropped → drop.\nregisterPendingRetry(PLAY_NAME, async (raw) => {\n const { hit, filterReason } = raw as { hit: ShowHnHit; filterReason: string };\n const outcome = await resolveAndEnqueueShowHn(hit, filterReason, () => {});\n return outcome === \"enqueued\" ? \"enqueued\" : outcome === \"platform-error\" ? \"platform-error\" : \"dropped\";\n});\n","import { getLedger, logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { PostFundingTarget } from \"@oneshot-gtm/plays\";\nimport { readFileSync } from \"node:fs\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, PostFundingExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"post-funding\";\nconst SOURCE = \"find:post-funding\";\n\nconst ROUND_MAP: Record<string, string> = {\n \"Pre-Seed\": \"Pre-Seed\",\n Seed: \"Seed\",\n \"Series A\": \"Series A\",\n \"Series B\": \"Series B\",\n \"Series C\": \"Series C\",\n \"Series D+\": \"Series D+\",\n};\n\nexport interface PostFundingFinderOpts extends RunOpts {\n /** File with one URL per line (TC / Crunchbase / company-blog). */\n sourceUrlsFile?: string;\n /** Or: pass URLs directly. */\n sourceUrls?: string[];\n /**\n * Auto-discovery mode: if no source URLs are supplied, run a webSearch\n * per round in `autoRounds` for \"<industry hint> <round> announcement\".\n * Industry hint comes from the saved ICP one-liner (or autoIndustry override).\n */\n auto?: boolean;\n /** Rounds to scan in auto mode. Default: [\"Seed\", \"Series A\"]. */\n autoRounds?: string[];\n /** Override the industry hint extracted from the ICP. */\n autoIndustry?: string;\n /** Look back this many days in auto mode (used in the search query). Default 7. */\n autoSinceDays?: number;\n}\n\nexport async function runPostFundingFinder(opts: PostFundingFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"post-funding-extract\");\n\n // Auto mode: harvest URLs via webSearch instead of reading a file.\n let urls = collectUrls(opts);\n let autoCost = 0;\n if (opts.auto && urls.length === 0) {\n const harvested = await harvestAutoUrls({\n rounds: opts.autoRounds ?? [\"Seed\", \"Series A\"],\n industry: opts.autoIndustry ?? deriveIndustryHint(icp),\n sinceDays: opts.autoSinceDays ?? 7,\n limit: limit * 2, // pull a bit extra; ICP filter + extract will winnow\n });\n urls = harvested.urls;\n autoCost = harvested.costUsd;\n }\n\n const result: FinderResult = {\n source: opts.auto ? `${SOURCE}:auto` : SOURCE,\n candidates: urls.length,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: autoCost,\n };\n\n for (const url of urls.slice(0, limit)) {\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n // Dedupe by URL before spending anything (cheap).\n if (ledger.isQueueDuplicate(PLAY_NAME, url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n // Read the announcement.\n let extract: PostFundingExtract;\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: (read.result.markdown ?? \"\").slice(0, 12000) },\n ],\n temperature: 0.1,\n maxTokens: 600,\n });\n extract = parsePostFundingExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"post-funding.read_or_extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.company || !extract.companyDomain || !extract.founderName) {\n result.droppedEnrichment++;\n continue;\n }\n\n // ICP filter on the LLM-extracted summary.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: `${extract.company} ${extract.round ?? \"raised\"} (${extract.industry ?? \"industry n/a\"})`,\n url,\n summary: extract.summary,\n },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n continue;\n }\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: {\n company: extract.company,\n round: extract.round,\n industry: extract.industry,\n summary: extract.summary,\n sourceUrl: url,\n },\n dedupeKey: url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n // Resolve + verify the founder's email (prescreen → findEmail → dedupe → verify).\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: extract.founderName,\n companyDomain: extract.companyDomain,\n isDuplicate: (email) =>\n isDuplicate({ playName: PLAY_NAME, dedupeKey: url, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n continue;\n }\n const email = contact.email;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"post-funding\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.founderName,\n disambiguators: [extract.company],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"post-funding\",\n });\n }\n\n const target: PostFundingTarget = {\n name: extract.founderName,\n email,\n company: extract.company,\n round: ROUND_MAP[extract.round ?? \"\"] ?? extract.round ?? \"Seed\",\n amountUsd: extract.amountUsd ?? 0,\n sourceUrl: url,\n ...(extract.leadInvestor ? { leadInvestor: extract.leadInvestor } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: url,\n source: SOURCE,\n notes: `${extract.round ?? \"?\"} ${extract.amountUsd ? `$${extract.amountUsd.toLocaleString()}` : \"\"} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function collectUrls(opts: PostFundingFinderOpts): string[] {\n const urls: string[] = [];\n if (opts.sourceUrls) urls.push(...opts.sourceUrls);\n if (opts.sourceUrlsFile) {\n const raw = readFileSync(opts.sourceUrlsFile, \"utf8\");\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n try {\n const _validate = new URL(trimmed);\n urls.push(_validate.toString());\n } catch {\n // skip non-URL lines\n }\n }\n }\n return [...new Set(urls)];\n}\n\nexport function parsePostFundingExtract(raw: string): PostFundingExtract {\n return tryParseJsonObject<PostFundingExtract>(raw, {\n company: null,\n companyDomain: null,\n round: null,\n amountUsd: null,\n leadInvestor: null,\n founderName: null,\n founderRole: null,\n industry: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n\ninterface HarvestArgs {\n rounds: string[];\n industry: string;\n sinceDays: number;\n limit: number;\n}\n\nconst FUNDING_DOMAIN_HINTS = [\n \"techcrunch.com\",\n \"crunchbase.com\",\n \"businesswire.com\",\n \"prnewswire.com\",\n \"pitchbook.com\",\n \"venturebeat.com\",\n \"axios.com\",\n \"fortune.com\",\n \"forbes.com\",\n \"reuters.com\",\n \"bloomberg.com\",\n \"sifted.eu\",\n \"tech.eu\",\n \"theinformation.com\",\n];\n\nasync function harvestAutoUrls(args: HarvestArgs): Promise<{ urls: string[]; costUsd: number }> {\n const seen = new Set<string>();\n const urls: string[] = [];\n let costUsd = 0;\n const sincePhrase = args.sinceDays <= 1 ? \"today\" : `last ${args.sinceDays} days`;\n const industry = args.industry.trim();\n\n for (const round of args.rounds) {\n if (urls.length >= args.limit) break;\n const queryParts = [\n industry,\n `\"${round}\"`,\n \"funding announcement\",\n sincePhrase,\n \"site:(techcrunch.com OR crunchbase.com OR businesswire.com OR prnewswire.com OR sifted.eu OR tech.eu)\",\n ].filter(Boolean);\n const query = queryParts.join(\" \");\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(20, Math.max(5, args.limit - urls.length)) },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (urls.length >= args.limit) break;\n if (!hit.url) continue;\n const normalized = normalizeUrl(hit.url);\n if (!normalized) continue;\n if (seen.has(normalized)) continue;\n if (!isLikelyFundingUrl(normalized, hit.title, hit.description)) continue;\n seen.add(normalized);\n urls.push(normalized);\n }\n } catch {\n // skip this round on error; keep harvesting others\n }\n }\n return { urls, costUsd };\n}\n\nexport function normalizeUrl(raw: string): string | null {\n try {\n const u = new URL(raw);\n u.hash = \"\";\n return u.toString();\n } catch {\n return null;\n }\n}\n\nexport function isLikelyFundingUrl(url: string, title?: string, description?: string): boolean {\n let host = \"\";\n try {\n host = new URL(url).hostname.toLowerCase();\n } catch {\n return false;\n }\n const hostMatch = FUNDING_DOMAIN_HINTS.some((h) => host === h || host.endsWith(`.${h}`));\n if (hostMatch) return true;\n const text = `${title ?? \"\"} ${description ?? \"\"}`.toLowerCase();\n return /\\b(raises?|raised|series\\s+[a-d]|seed round|pre-?seed|funding round|led by)\\b/.test(text);\n}\n\nexport function deriveIndustryHint(icp: string | null): string {\n if (!icp) return \"startup\";\n const cleaned = icp\n .toLowerCase()\n .replace(/[^a-z0-9\\s+/-]/g, \" \")\n .split(/\\s+/)\n .filter(Boolean);\n const stop = new Set([\n \"the\",\n \"a\",\n \"an\",\n \"and\",\n \"or\",\n \"of\",\n \"for\",\n \"to\",\n \"with\",\n \"in\",\n \"on\",\n \"who\",\n \"that\",\n \"are\",\n \"is\",\n \"be\",\n \"their\",\n \"they\",\n \"we\",\n \"our\",\n \"you\",\n \"your\",\n \"at\",\n \"as\",\n \"by\",\n \"from\",\n \"any\",\n \"need\",\n \"needs\",\n \"want\",\n \"wants\",\n \"use\",\n \"uses\",\n \"using\",\n \"build\",\n \"building\",\n \"ship\",\n \"shipping\",\n \"make\",\n \"making\",\n \"people\",\n \"team\",\n \"teams\",\n \"company\",\n \"companies\",\n \"founder\",\n \"founders\",\n \"developer\",\n \"developers\",\n \"engineer\",\n \"engineers\",\n \"ceo\",\n \"cto\",\n \"vp\",\n \"head\",\n ]);\n const keywords = cleaned.filter((w) => w.length > 2 && !stop.has(w)).slice(0, 4);\n return keywords.length > 0 ? keywords.join(\" \") : \"startup\";\n}\n","import { logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { AcceleratorLaunchExtract, CompanyRecord } from \"./_types.ts\";\n\n/**\n * Fallback adapter for accelerators that DON'T publish a structured directory\n * (Techstars, Antler, 500 Global, AI Grant, SPC, Neo, …). Combo-search shape:\n * webSearch with cohort-derived queries, aggregate hits, dedupe, then per-hit\n * webRead + LLM extract.\n *\n * Less reliable than the yc-oss adapter (search recall depends on the\n * accelerator's web presence) but works without per-accelerator scrapers.\n */\n\nconst PLAY_NAME = \"accelerator-batch\";\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\n/**\n * Build the three search queries from a human-readable cohort label.\n * Founders supply `cohortLabel: \"YC W26\"` or `\"Techstars Toronto Spring 2025\"`\n * and we generate complementary queries. Three is enough to hit different\n * indexing patterns (launch posts vs portfolio pages vs press coverage)\n * without burning the search-call budget.\n */\nexport function buildCohortQueries(cohortLabel: string): string[] {\n const label = cohortLabel.trim();\n if (label.length === 0) return [];\n return [`\"${label}\" launch announcement`, `\"${label}\" portfolio company`, `\"${label}\" demo day`];\n}\n\n/**\n * Drop URL hosts that reliably fail per-page extraction or pollute results.\n * Aggregators (techcrunch, news.yc) carry batch lists, not company-specific\n * pages; social-media root paths surface profiles, not products.\n *\n * Conservative: an empty hit list breaks the finder, so only block hosts\n * that are NEVER useful per-record.\n */\nexport function looksLikeAcceleratorNoise(url: string): boolean {\n let host: string;\n try {\n host = new URL(url).hostname.toLowerCase().replace(/^www\\./, \"\");\n } catch {\n return true; // un-parseable URL is always noise\n }\n // Listicles, social roots, video aggregators — never a per-company page.\n const noiseHosts = [\n \"twitter.com\",\n \"x.com\",\n \"linkedin.com\",\n \"facebook.com\",\n \"youtube.com\",\n \"youtu.be\",\n \"reddit.com\",\n \"medium.com\", // medium URLs sometimes work but recall is bad and noise is high\n ];\n if (noiseHosts.includes(host)) return true;\n // News aggregators that DO host accelerator coverage but rarely as\n // single-company pages — keep the option to surface specific paths later\n // by host-prefix matching, but block bare-host hits for now.\n if (host === \"news.ycombinator.com\") return true;\n if (host === \"techcrunch.com\") return true;\n return false;\n}\n\n/**\n * Fetch search hits for a non-YC accelerator cohort, then extract a\n * `CompanyRecord` per hit via LLM. Honors `limit` at the hit-count level so a\n * sparse search doesn't blow the per-record budget on noise.\n *\n * Cost is non-zero (webSearch + webRead + LLM extract per hit).\n */\nexport async function fetchAcceleratorSearch(\n _cohort: string,\n cohortLabel: string,\n limit: number,\n): Promise<{ records: CompanyRecord[]; costUsd: number; diagnostic: string | null }> {\n const queries = buildCohortQueries(cohortLabel);\n if (queries.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: \"set `cohortLabel` to the human-readable program name\",\n };\n }\n\n let costUsd = 0;\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n for (const query of queries) {\n if (hits.length >= limit * 2) break;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const raw of search.result.results ?? []) {\n if (!raw.url || seen.has(raw.url)) continue;\n if (looksLikeAcceleratorNoise(raw.url)) continue;\n seen.add(raw.url);\n hits.push({ url: raw.url, title: raw.title, description: raw.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-search.query\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n\n if (hits.length === 0) {\n return {\n records: [],\n costUsd,\n diagnostic: `no usable hits for '${cohortLabel}' — try a more specific cohortLabel (e.g. include the city/year)`,\n };\n }\n\n const system = loadPrompt(\"accelerator-launch-extract\");\n const records: CompanyRecord[] = [];\n for (const hit of hits.slice(0, limit)) {\n let extract: AcceleratorLaunchExtract | null = null;\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n title: hit.title,\n description: hit.description,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseAcceleratorLaunchExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-search.read\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n continue;\n }\n if (!extract || !extract.company) continue;\n // The prompt instructs the LLM to return a bare hostname, but LLMs drift —\n // sanitize so an off-spec response can't break URL construction or pass\n // through paths/protocols into findEmail.\n const cleanDomain = sanitizeCompanyDomain(extract.companyDomain);\n const website = cleanDomain ? `https://${cleanDomain}` : null;\n records.push({\n name: extract.company,\n website,\n oneLiner: extract.oneLiner,\n longDescription: null,\n industry: null,\n tags: [],\n ycUrl: null,\n // The websearch extract returns founderName when the page named one\n // explicitly. Keep null here when it didn't — the pipeline still has\n // a chance to resolve via per-page extract on a different URL.\n founderName: extract.founderName?.trim() || null,\n founderLinkedinUrl: isLinkedInProfileUrl(extract.linkedinUrl)\n ? (extract.linkedinUrl as string).trim()\n : null,\n founderPhone: extract.phone?.trim() || null,\n source: \"websearch\",\n });\n }\n\n if (records.length === 0) {\n return {\n records: [],\n costUsd,\n diagnostic: `${hits.length} hits found but none extracted to a usable company record`,\n };\n }\n\n return { records, costUsd, diagnostic: null };\n}\n\n/**\n * Coerce an LLM-supplied \"company domain\" string into a bare hostname.\n * Strips scheme, leading `www.`, paths, query, and fragment. Returns null\n * for null/empty/invalid input.\n *\n * Prompt instructs the LLM to return bare hosts, but real-world outputs\n * include `https://www.foo.com/about`, `foo.com/`, ` foo.com `, etc. This\n * normalizes them so downstream `findEmail` always sees a clean domain.\n */\nexport function sanitizeCompanyDomain(raw: string | null | undefined): string | null {\n if (!raw || typeof raw !== \"string\") return null;\n let v = raw.trim().toLowerCase();\n if (v.length === 0) return null;\n // Strip scheme.\n v = v.replace(/^https?:\\/\\//, \"\");\n // Strip leading www.\n v = v.replace(/^www\\./, \"\");\n // Drop path / query / fragment / port.\n v = v.replace(/[/?#:].*$/, \"\");\n // Trim trailing dots.\n v = v.replace(/\\.+$/, \"\");\n // Sanity: must contain a dot and at least one non-digit char to be a real domain.\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(v)) return null;\n return v;\n}\n\nexport function parseAcceleratorLaunchExtract(raw: string): AcceleratorLaunchExtract {\n return tryParseJsonObject<AcceleratorLaunchExtract>(raw, {\n company: null,\n companyDomain: null,\n oneLiner: null,\n founderName: null,\n founderRole: null,\n launchUrl: null,\n linkedinUrl: null,\n phone: null,\n });\n}\n","import type { CompanyRecord } from \"./_types.ts\";\n\n/**\n * Adapter for the [yc-oss/api](https://github.com/yc-oss/api) public dataset.\n * Free, daily-updated, no auth — strictly better than scraping YC's\n * client-rendered launches page.\n *\n * Schema reference (from `https://yc-oss.github.io/api/batches/<slug>.json`):\n * each record has `name, slug, website, one_liner, long_description, industry,\n * subindustry, tags, batch, status, url, api`. No founder names — the\n * downstream pipeline still calls findEmail on the company domain.\n */\n\nconst YC_OSS_BASE = \"https://yc-oss.github.io/api/batches\";\n\n/**\n * Map a cohort tag (`yc-w26`, `yc-s25`, `yc-spring-26`, `yc-fall-25`) to the\n * yc-oss batch slug (`winter-2026`, `summer-2025`, `spring-2026`, `fall-2025`).\n *\n * Pass-through behavior: a tag that already looks like an yc-oss slug\n * (`winter-2026`, `summer-2024`, etc.) is returned unchanged so founders can\n * paste either form into config.\n *\n * Returns null when the tag doesn't match any known pattern — caller should\n * surface this as a diagnostic, not throw, so the trigger card shows the\n * real reason instead of a 500.\n */\nexport function cohortToBatchSlug(tag: string): string | null {\n const normalized = tag.trim().toLowerCase();\n if (normalized.length === 0) return null;\n\n // Already a yc-oss slug? Accept it verbatim.\n if (/^(winter|summer|spring|fall)-\\d{4}$/.test(normalized)) {\n return normalized;\n }\n\n // yc-w26 / yc-s25 — single-letter season + 2-digit year.\n const short = normalized.match(/^yc-([wsfp])(\\d{2})$/);\n if (short) {\n const letter = short[1] as \"w\" | \"s\" | \"f\" | \"p\";\n const yy = short[2] as string;\n const season = SHORT_SEASON[letter];\n if (!season) return null;\n return `${season}-20${yy}`;\n }\n\n // yc-spring-26 / yc-fall-25 — full season name + 2-digit year.\n const long = normalized.match(/^yc-(winter|summer|spring|fall)-(\\d{2})$/);\n if (long) {\n return `${long[1]}-20${long[2]}`;\n }\n\n // yc-w-2026 / yc-winter-2026 — 4-digit year variants.\n const fourYear = normalized.match(/^yc-(winter|summer|spring|fall|[wsfp])-(\\d{4})$/);\n if (fourYear) {\n const seasonRaw = fourYear[1] as string;\n const yyyy = fourYear[2] as string;\n const season =\n seasonRaw.length === 1\n ? SHORT_SEASON[seasonRaw as \"w\" | \"s\" | \"f\" | \"p\"]\n : (seasonRaw as \"winter\" | \"summer\" | \"spring\" | \"fall\");\n if (!season) return null;\n return `${season}-${yyyy}`;\n }\n\n return null;\n}\n\nconst SHORT_SEASON: Record<\"w\" | \"s\" | \"f\" | \"p\", \"winter\" | \"summer\" | \"fall\" | \"spring\"> = {\n w: \"winter\",\n s: \"summer\",\n f: \"fall\",\n p: \"spring\", // \"p\" for sPring — yc convention varies; spring is rare so this is a best-guess fallback\n};\n\n/**\n * Build a human-readable cohort label from a cohort tag, used when the\n * founder didn't supply `cohortLabel` explicitly.\n *\n * - `yc-w26` → `YC W26` (preserves the canonical YC short form for emails)\n * - `yc-winter-2026` → `YC Winter 2026`\n * - `techstars-toronto-2025` → `Techstars Toronto 2025` (Title-Case + spaces)\n *\n * Used by the websearch adapter's query builder, so a wrong default would\n * search for the wrong program. Tightens behavior after a `cohort` edit —\n * the previous hardcoded `\"YC W26\"` default would silently mismatch.\n */\nexport function deriveCohortLabel(cohort: string): string {\n const tag = cohort.trim();\n if (tag.length === 0) return \"\";\n // Special-case YC short tags to keep the canonical \"YC W26\" form.\n const ycShort = tag.match(/^yc-([wsfp])(\\d{2})$/i);\n if (ycShort) {\n const letter = ycShort[1]!.toUpperCase();\n const yy = ycShort[2]!;\n return `YC ${letter}${yy}`;\n }\n // Generic: split on hyphens, title-case each part. \"yc\" stays uppercase\n // when it's the first segment.\n return tag\n .split(\"-\")\n .map((part, i) => {\n if (i === 0 && part.toLowerCase() === \"yc\") return \"YC\";\n if (/^\\d+$/.test(part)) return part;\n return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();\n })\n .join(\" \");\n}\n\ninterface YcOssCompany {\n name?: unknown;\n website?: unknown;\n one_liner?: unknown;\n long_description?: unknown;\n industry?: unknown;\n tags?: unknown;\n url?: unknown;\n}\n\n/**\n * Fetch a yc-oss batch and map records to the normalized `CompanyRecord`\n * shape. Honors `limit` so we don't pull a 200-record batch when the founder\n * only wants 25.\n *\n * Returns:\n * - `records`: zero or more company records.\n * - `diagnostic`: human-readable reason when records is empty (404, parse\n * error, unknown tag) so the UI can surface it instead of treating zero\n * as success.\n *\n * Cost is always 0 — yc-oss is GitHub Pages, no LLM, no auth.\n */\nexport async function fetchYcOssBatch(\n cohort: string,\n limit: number,\n): Promise<{ records: CompanyRecord[]; costUsd: number; diagnostic: string | null }> {\n const slug = cohortToBatchSlug(cohort);\n if (!slug) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `unknown YC cohort tag '${cohort}' — try 'yc-w26', 'yc-s25', or 'winter-2026'`,\n };\n }\n const url = `${YC_OSS_BASE}/${slug}.json`;\n let res: Response;\n try {\n res = await fetch(url);\n } catch (err) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss fetch failed: ${(err as Error).message ?? \"network error\"}`,\n };\n }\n if (!res.ok) {\n if (res.status === 404) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss has no batch '${slug}' yet — likely too new or misspelled cohort`,\n };\n }\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss returned ${res.status} ${res.statusText}`,\n };\n }\n let parsed: unknown;\n try {\n parsed = await res.json();\n } catch {\n return { records: [], costUsd: 0, diagnostic: \"yc-oss response was not valid JSON\" };\n }\n if (!Array.isArray(parsed)) {\n return { records: [], costUsd: 0, diagnostic: \"yc-oss response was not an array\" };\n }\n if (parsed.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss has no companies for batch '${slug}' yet — likely too new`,\n };\n }\n const records = parsed\n .slice(0, limit)\n .map((c) => mapYcOssCompany(c as YcOssCompany))\n .filter((r): r is CompanyRecord => r !== null);\n if (records.length === 0) {\n return {\n records: [],\n costUsd: 0,\n diagnostic: `yc-oss returned ${parsed.length} records but none had a usable name`,\n };\n }\n return { records, costUsd: 0, diagnostic: null };\n}\n\n/** Map a single yc-oss company JSON object to the normalized shape. Returns null for malformed records. */\nexport function mapYcOssCompany(c: YcOssCompany): CompanyRecord | null {\n const name = typeof c.name === \"string\" ? c.name.trim() : \"\";\n if (name.length === 0) return null;\n return {\n name,\n website: typeof c.website === \"string\" && c.website.length > 0 ? c.website : null,\n oneLiner: typeof c.one_liner === \"string\" && c.one_liner.length > 0 ? c.one_liner : null,\n longDescription:\n typeof c.long_description === \"string\" && c.long_description.length > 0\n ? c.long_description\n : null,\n industry: typeof c.industry === \"string\" && c.industry.length > 0 ? c.industry : null,\n tags: Array.isArray(c.tags) ? (c.tags.filter((t) => typeof t === \"string\") as string[]) : [],\n ycUrl: typeof c.url === \"string\" && c.url.length > 0 ? c.url : null,\n // yc-oss schema doesn't include founder names — pipeline resolves them on\n // demand via webRead+extract on the YC profile URL.\n founderName: null,\n founderLinkedinUrl: null,\n founderPhone: null,\n source: \"yc-oss\",\n };\n}\n","import { getLedger, logEvent, webRead } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport type { AcceleratorBatchTarget } from \"@oneshot-gtm/plays\";\nimport {\n fetchAcceleratorSearch,\n parseAcceleratorLaunchExtract,\n} from \"./_accelerator-search-adapter.ts\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport { deriveCohortLabel, fetchYcOssBatch } from \"./_yc-oss-adapter.ts\";\nimport type { CompanyRecord, FinderResult, RunOpts } from \"./_types.ts\";\n\n/**\n * Pulls an accelerator-cohort directory, ICP-filters, finds founder contact,\n * enqueues for outreach. Two adapters:\n *\n * - `yc-oss` — free structured directory at yc-oss.github.io (auto-selected\n * when cohort matches `^yc-`). The right path for any YC batch.\n * - `websearch` — combo-search fallback for accelerators without a public API\n * (Techstars, Antler, 500 Global, AI Grant, …). Less reliable recall but\n * works for any cohortLabel.\n *\n * The per-company pipeline is shared: dedupe → ICP filter → findEmail →\n * verifyEmail → enqueue, all under `parallelMap` (concurrency 3, mirrors\n * github-topics).\n */\n\nconst PLAY_NAME = \"accelerator-batch\";\n\nexport interface CohortEntry {\n /** Cohort tag — e.g. `yc-w26`, `techstars-spring-2026`, `spc-2026-1`. */\n cohort: string;\n /** Human-readable label fed into search queries + the email prompt. */\n cohortLabel: string;\n}\n\nexport interface AcceleratorBatchFinderOpts extends RunOpts {\n /**\n * Multi-cohort sweep. Each entry routes to its own adapter — yc-* → yc-oss,\n * everything else → websearch. Per-cohort failures are isolated; the run\n * only halts if EVERY cohort returns 0 records.\n */\n cohorts?: CohortEntry[];\n /** Legacy single-cohort tag. Ignored when `cohorts` is set. */\n cohort?: string;\n /** Legacy human label. Ignored when `cohorts` is set. */\n cohortLabel?: string;\n /** Force a specific adapter for ALL entries. Default: yc-* → yc-oss, else → websearch. */\n adapter?: \"yc-oss\" | \"websearch\";\n /** Concurrency for the per-company pipeline (over the unified pool). Default 3. */\n concurrency?: number;\n /** The sender's own cohort tag — stamped onto every enqueued row so the play\n * can draft inline (self-contained), like github-topics stamps `yourEdge`. */\n senderCohort?: string;\n /** Optional time-bound offer for the sender's cohort, stamped onto each row. */\n freeForCohortOffer?: string;\n}\n\n/**\n * Normalize the legacy single-cohort opts shape into the new multi-cohort\n * list. Old trigger rows with `{cohort, cohortLabel}` keep working — they\n * become a one-entry list. Each entry's `cohort` is trimmed and an empty\n * `cohortLabel` is filled via `deriveCohortLabel`. Malformed entries\n * (missing or empty cohort tag) are dropped silently. Throws when zero\n * usable entries remain — readiness gate is supposed to prevent this.\n */\nexport function normalizeCohorts(\n opts: Pick<AcceleratorBatchFinderOpts, \"cohorts\" | \"cohort\" | \"cohortLabel\">,\n): CohortEntry[] {\n if (opts.cohorts && opts.cohorts.length > 0) {\n const normalized = opts.cohorts\n .map((entry): CohortEntry | null => {\n if (!entry || typeof entry.cohort !== \"string\") return null;\n const cohort = entry.cohort.trim();\n if (cohort.length === 0) return null;\n const labelRaw = typeof entry.cohortLabel === \"string\" ? entry.cohortLabel.trim() : \"\";\n return { cohort, cohortLabel: labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort) };\n })\n .filter((e): e is CohortEntry => e !== null);\n if (normalized.length > 0) return normalized;\n // All entries malformed — fall through to the legacy fields below before\n // throwing, in case the operator set both fields.\n }\n if (typeof opts.cohort === \"string\" && opts.cohort.trim().length > 0) {\n const cohort = opts.cohort.trim();\n const cohortLabel =\n typeof opts.cohortLabel === \"string\" && opts.cohortLabel.trim().length > 0\n ? opts.cohortLabel.trim()\n : deriveCohortLabel(cohort);\n return [{ cohort, cohortLabel }];\n }\n throw new Error(\"accelerator-batch: at least one cohort required\");\n}\n\n/**\n * Round-robin interleave records by their source cohort. Without this, the\n * per-company `parallelMap` would chew through every yc-w26 candidate before\n * touching Techstars — so the global `limit` enqueue cap (25 by default)\n * would be hit before any non-YC cohort got a chance. Interleaving picks\n * one record per cohort in turn until all cohort lists are exhausted, so\n * the eventual queue has a balanced cross-incubator footprint.\n *\n * Stable: ordering within a cohort matches input order. Empty input → [].\n */\nexport function interleaveByCohort<T extends { cohort: string }>(records: T[]): T[] {\n if (records.length === 0) return [];\n const byCohort = new Map<string, T[]>();\n // Preserve cohort first-seen order so the output is deterministic.\n const order: string[] = [];\n for (const r of records) {\n let list = byCohort.get(r.cohort);\n if (!list) {\n list = [];\n byCohort.set(r.cohort, list);\n order.push(r.cohort);\n }\n list.push(r);\n }\n const out: T[] = [];\n let idx = 0;\n while (out.length < records.length) {\n let pushed = false;\n for (const cohort of order) {\n const list = byCohort.get(cohort);\n if (list && idx < list.length) {\n out.push(list[idx]!);\n pushed = true;\n }\n }\n if (!pushed) break;\n idx++;\n }\n return out;\n}\n\n/** Source-tagged company record. Each entry carries the cohort it was fetched under. */\nexport type TaggedCompanyRecord = CompanyRecord & { cohort: string; cohortLabel: string };\n\n/**\n * Cross-cohort dedupe by company name slug. A company appearing in two\n * cohorts (e.g. a YC alum joining Techstars) is rare but possible — keep the\n * first occurrence so the per-company pipeline doesn't pay enrichment cost\n * twice. Slug = lowercase + whitespace→hyphens + non-alphanumerics stripped,\n * matching the dedupeKey shape downstream.\n */\nexport function dedupeRecordsBySlug<T extends CompanyRecord>(records: T[]): T[] {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const r of records) {\n const slug = r.name\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n if (seen.has(slug)) continue;\n seen.add(slug);\n out.push(r);\n }\n return out;\n}\n\nexport async function runAcceleratorBatchFinder(\n opts: AcceleratorBatchFinderOpts,\n): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const concurrency = opts.concurrency ?? 3;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const cohorts = normalizeCohorts(opts);\n // Source string reflects whether this is a sweep or a single-cohort run.\n // Keeps the per-target `source` column on the queue readable.\n const source =\n cohorts.length === 1\n ? `find:accelerator-batch:${cohorts[0]!.cohort}`\n : `find:accelerator-batch:sweep`;\n\n const result: FinderResult = {\n source,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n // Step 1: discover cohort companies — one adapter call per cohort entry.\n // Per-cohort failures (adapter throws, 0 hits) log and continue; we only\n // halt the run when EVERY cohort came back empty.\n //\n // Parallelized at `concurrency` to keep wall-clock reasonable: with 12\n // websearch cohorts at ~30s each, a sequential loop would burn 6+ minutes\n // of pure discovery before the first per-company pipeline starts. The\n // cost-cap check is best-effort under parallelism — workers in flight\n // can overshoot by ~(concurrency - 1) × (per-cohort cost) — acceptable\n // since the per-company loop also overshoots by the same factor.\n type CohortOutcome = {\n records: TaggedCompanyRecord[];\n summary: { cohort: string; records: number; error?: string };\n };\n const cohortResults = await parallelMap<CohortEntry, CohortOutcome>(\n cohorts,\n concurrency,\n async (entry) => {\n // Best-effort cost-cap check before we start the fetch. Workers in\n // flight at cap-trip time still finish their adapter call.\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n return {\n records: [],\n summary: { cohort: entry.cohort, records: 0, error: \"skipped: cost cap\" },\n };\n }\n const adapterName = pickAdapter(entry.cohort, opts.adapter);\n try {\n const fetched =\n adapterName === \"yc-oss\"\n ? await fetchYcOssBatch(entry.cohort, limit)\n : await fetchAcceleratorSearch(entry.cohort, entry.cohortLabel, limit);\n result.costUsd += fetched.costUsd;\n if (fetched.records.length === 0) {\n return {\n records: [],\n summary: {\n cohort: entry.cohort,\n records: 0,\n error: fetched.diagnostic ?? \"no records\",\n },\n };\n }\n // Tag each record with its source cohort so the per-company callback\n // can build dedupe keys, rejection payloads, and final targets without\n // needing the cohort plumbed through opts.\n const tagged = fetched.records.map<TaggedCompanyRecord>((r) => ({\n ...r,\n cohort: entry.cohort,\n cohortLabel: entry.cohortLabel,\n }));\n return {\n records: tagged,\n summary: { cohort: entry.cohort, records: fetched.records.length },\n };\n } catch (err) {\n const message = ((err as Error).message ?? \"\").slice(0, 120);\n logEvent(\n \"error.swallowed\",\n { kind: \"accelerator-batch.adapter\", cohort: entry.cohort, message_120: message },\n \"warn\",\n );\n return {\n records: [],\n summary: { cohort: entry.cohort, records: 0, error: message },\n };\n }\n },\n );\n\n // Reassemble in registry order so the per-cohort summary lines up with\n // the operator's config visually.\n const allRecords: TaggedCompanyRecord[] = [];\n const perCohortOutcomes: Array<{ cohort: string; records: number; error?: string }> = [];\n for (const r of cohortResults) {\n allRecords.push(...r.records);\n perCohortOutcomes.push(r.summary);\n }\n result.perCohort = perCohortOutcomes;\n\n // Interleave + cross-cohort dedupe. Interleave first so the per-company\n // pipeline sees a balanced rotation; dedupe by slug after so a company\n // appearing in two cohorts gets enriched once (kept under its first\n // surfacing cohort).\n const deduped = dedupeRecordsBySlug(interleaveByCohort(allRecords));\n result.candidates = deduped.length;\n if (deduped.length === 0) {\n // Every cohort came back empty. Surface the right diagnostic:\n // - Single-cohort run → the adapter's own message\n // - All cohorts skipped due to cost cap → that\n // - Otherwise → generic sweep-empty\n if (cohorts.length === 1) {\n const first = perCohortOutcomes[0];\n result.halted = first?.error ?? \"adapter returned 0 records\";\n } else if (\n opts.maxCostUsd != null &&\n perCohortOutcomes.every((o) => o.error === \"skipped: cost cap\")\n ) {\n result.halted = `max-cost cap (${opts.maxCostUsd}) during discovery`;\n } else {\n result.halted = `all ${cohorts.length} cohorts returned 0 candidates`;\n }\n return result;\n }\n\n // Step 2: per-company pipeline (parallel, ICP-first like github-topics).\n // `halted` is a soft cap — workers may overshoot by up to (concurrency - 1)\n // candidates. Acceptable at our scale.\n let halted = false;\n\n await parallelMap(deduped, concurrency, async (record) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n\n const dedupeKey = makeDedupeKey(record, record.cohort);\n if (ledger.isQueueDuplicate(PLAY_NAME, dedupeKey)) {\n result.droppedDuplicate++;\n return;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n return;\n }\n\n // ICP filter — cheapest gate first ($0.001). Uses the structured\n // one-liner + tags so the classifier sees more signal than a bare title.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: record.name,\n url: record.website ?? record.ycUrl,\n summary: buildIcpSummary(record),\n },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n return;\n }\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: rejectionPayload(record, record.cohort),\n dedupeKey,\n source,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${record.cohortLabel} — ${filter.reason}`,\n });\n return;\n }\n\n // Resolve a founder name for this record. yc-oss directory rows ship\n // without one; the SDK's findEmail requires `full_name` (or first+last)\n // so we MUST acquire a person name before the enrichment call.\n //\n // Strategy: webRead the YC profile page (or fall back to the company\n // website) and run the same `accelerator-launch-extract` prompt the\n // websearch adapter uses. ~$0.02 per ICP-pass — only paid for candidates\n // that survived the cheaper ICP gate.\n let founderName = record.founderName?.trim() || null;\n let resolvedLinkedin: string | null = isLinkedInProfileUrl(record.founderLinkedinUrl)\n ? record.founderLinkedinUrl\n : null;\n let resolvedPhone: string | null = record.founderPhone ?? null;\n if (!founderName) {\n const resolved = await resolveFounderName(record);\n result.costUsd += resolved.costUsd;\n founderName = resolved.founderName;\n resolvedLinkedin = resolvedLinkedin ?? resolved.linkedinUrl;\n resolvedPhone = resolvedPhone ?? resolved.phone;\n }\n if (!founderName) {\n result.droppedEnrichment++;\n return;\n }\n\n const domain = record.website ? urlDomain(record.website) : null;\n if (!domain) {\n result.droppedEnrichment++;\n return;\n }\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: founderName,\n companyDomain: domain,\n isDuplicate: (email) => isDuplicate({ playName: PLAY_NAME, dedupeKey, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n return;\n }\n const email = contact.email;\n // Prefer the SDK's resolved name when available — it's the actual owner of\n // the email — and fall back to the founder name we resolved upstream.\n const fullName = contact.fullName?.trim() || founderName;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"accelerator-batch\",\n });\n result.costUsd += enr.costUsd;\n const phone = resolvedPhone ?? enr.phone;\n let linkedinUrl = resolvedLinkedin ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName,\n disambiguators: [record.name],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"accelerator-batch\",\n });\n }\n\n const target: AcceleratorBatchTarget = {\n name: fullName,\n email,\n company: record.name,\n cohort: record.cohort,\n ...(record.ycUrl\n ? { launchUrl: record.ycUrl }\n : record.website\n ? { launchUrl: record.website }\n : {}),\n ...(record.oneLiner ? { productOneLiner: record.oneLiner } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n // Stamp the sender's own cohort (+ offer) onto the row so the play can\n // draft inline without a run-level senderCohort — mirrors yourEdge.\n ...(opts.senderCohort ? { senderCohort: opts.senderCohort } : {}),\n ...(opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source,\n notes: `${record.cohortLabel} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n });\n\n return result;\n}\n\n/**\n * Pick which adapter handles the cohort. yc-* tags hit the free yc-oss\n * directory; everything else falls back to web search. An explicit override\n * always wins so founders can force a path for testing.\n */\nexport function pickAdapter(cohort: string, override?: string): \"yc-oss\" | \"websearch\" {\n if (override === \"yc-oss\" || override === \"websearch\") return override;\n if (/^yc-/i.test(cohort.trim())) return \"yc-oss\";\n return \"websearch\";\n}\n\nfunction makeDedupeKey(record: CompanyRecord, cohort: string): string {\n const slug = record.name\n .toLowerCase()\n .replace(/\\s+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n return `${slug}|${cohort}`;\n}\n\nfunction rejectionPayload(record: CompanyRecord, cohort: string): Record<string, unknown> {\n return {\n company: record.name,\n cohort,\n ...(record.ycUrl\n ? { launchUrl: record.ycUrl }\n : record.website\n ? { launchUrl: record.website }\n : {}),\n ...(record.oneLiner ? { oneLiner: record.oneLiner } : {}),\n };\n}\n\nfunction buildIcpSummary(record: CompanyRecord): string {\n const parts: string[] = [];\n if (record.oneLiner) parts.push(record.oneLiner);\n if (record.longDescription) parts.push(record.longDescription.slice(0, 600));\n if (record.industry) parts.push(`Industry: ${record.industry}`);\n if (record.tags.length > 0) parts.push(`Tags: ${record.tags.join(\", \")}`);\n return parts.join(\"\\n\\n\");\n}\n\n/**\n * webRead a per-company URL (YC profile preferred, company website as\n * fallback) and run the `accelerator-launch-extract` prompt to grab a\n * founder name. Returns `{founderName: null}` if no URL is available, the\n * read fails, or the LLM can't surface a name.\n *\n * Only called for ICP-passing candidates so we don't pay this cost on\n * candidates the cheap classifier already rejected.\n */\nexport async function resolveFounderName(record: CompanyRecord): Promise<{\n founderName: string | null;\n linkedinUrl: string | null;\n phone: string | null;\n costUsd: number;\n}> {\n const url = record.ycUrl ?? record.website;\n if (!url) return { founderName: null, linkedinUrl: null, phone: null, costUsd: 0 };\n let costUsd = 0;\n try {\n const read = await webRead({ url }, { playName: PLAY_NAME });\n costUsd += read.result.cost ?? 0;\n const system = loadPrompt(\"accelerator-launch-extract\");\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url,\n company: record.name,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 400,\n });\n const extract = parseAcceleratorLaunchExtract(llm.content);\n const name = extract.founderName?.trim();\n const linkedinUrl = extract.linkedinUrl?.trim() || null;\n return {\n founderName: name && name.length > 0 ? name : null,\n linkedinUrl: isLinkedInProfileUrl(linkedinUrl) ? linkedinUrl : null,\n phone: extract.phone?.trim() || null,\n costUsd,\n };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"accelerator-batch.resolveFounderName\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return { founderName: null, linkedinUrl: null, phone: null, costUsd };\n }\n}\n","import { getLedger, logEvent, webSearch } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { JobChangeTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, JobChangeExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"job-change\";\nconst SOURCE = \"find:job-change\";\n\nexport interface JobChangeFinderOpts extends RunOpts {\n /**\n * Target personas to search for (e.g. \"VP Engineering\", \"Head of Growth\").\n * Each persona gets one webSearch query combined with sinceDays.\n */\n personas?: string[];\n /**\n * Optional list of company-name filters to bias results toward (e.g. ICP companies).\n * If empty, casts a wider net per persona.\n */\n companies?: string[];\n /** Days back to bias the search query. Default 14. */\n sinceDays?: number;\n}\n\nconst DEFAULT_PERSONAS = [\n \"VP Engineering\",\n \"Head of Growth\",\n \"Director of Product\",\n \"Chief of Staff\",\n];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runJobChangeFinder(opts: JobChangeFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 14;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"job-change-extract\");\n const personas = opts.personas && opts.personas.length > 0 ? opts.personas : DEFAULT_PERSONAS;\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const seenUrls = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"last week\" : `last ${sinceDays} days`;\n\n for (const persona of personas) {\n if (hits.length >= limit * 2) break;\n const companyClause =\n opts.companies && opts.companies.length > 0\n ? ` (${opts.companies.map((c) => `\"${c}\"`).join(\" OR \")})`\n : \"\";\n const query = `\"joined as ${persona}\"${companyClause} ${sincePhrase}`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seenUrls.has(hit.url)) continue;\n seenUrls.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"job-change.webSearch\",\n persona,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n continue;\n }\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: JobChangeExtract;\n try {\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n title: hit.title,\n description: hit.description,\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseJobChangeExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"job-change.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.fullName || !extract.newRole || !extract.newCompany) {\n result.droppedEnrichment++;\n continue;\n }\n\n const domain = extract.newCompanyDomain ?? urlDomain(hit.url);\n if (!domain) {\n result.droppedEnrichment++;\n continue;\n }\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: extract.fullName,\n companyDomain: domain,\n isDuplicate: (email) =>\n isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n continue;\n }\n const email = contact.email;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"job-change\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.fullName,\n disambiguators: [extract.newCompany],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"job-change\",\n });\n }\n\n const target: JobChangeTarget = {\n name: extract.fullName,\n email,\n newRole: extract.newRole,\n newCompany: extract.newCompany,\n ...(extract.previousRole ? { previousRole: extract.previousRole } : {}),\n ...(extract.previousCompany ? { previousCompany: extract.previousCompany } : {}),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.fullName} → ${extract.newRole} @ ${extract.newCompany} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function parseJobChangeExtract(raw: string): JobChangeExtract {\n return tryParseJsonObject<JobChangeExtract>(raw, {\n fullName: null,\n newRole: null,\n newCompany: null,\n newCompanyDomain: null,\n previousRole: null,\n previousCompany: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { getLedger, logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { HiringSignalTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, HiringSignalExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"hiring-signal\";\nconst SOURCE = \"find:hiring-signal\";\n\nconst ATS_DOMAIN_HINTS = [\n \"boards.greenhouse.io\",\n \"jobs.lever.co\",\n \"apply.workable.com\",\n \"jobs.ashbyhq.com\",\n \"ashbyhq.com\",\n];\n\nexport interface HiringSignalFinderOpts extends RunOpts {\n /** Roles to scan for. Default: [\"Staff Engineer\",\"ML Engineer\",\"Solutions Engineer\"]. */\n roles?: string[];\n /** Optional company-name filter to bias results. */\n companies?: string[];\n /**\n * The \"your one-line claim\" that goes onto every queued target — required for the\n * downstream hiring-signal play. If unset, we fall back to a generic placeholder.\n */\n yourClaim?: string;\n /** Days back to bias the search query. Default 14. */\n sinceDays?: number;\n}\n\nconst DEFAULT_ROLES = [\"Staff Engineer\", \"ML Engineer\", \"Solutions Engineer\"];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runHiringSignalFinder(opts: HiringSignalFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 14;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"hiring-signal-extract\");\n const roles = opts.roles && opts.roles.length > 0 ? opts.roles : DEFAULT_ROLES;\n // No hardcoded fallback claim — a generic one would assert a product capability\n // the founder may not have. The trigger's readiness gate blocks the scheduled\n // path; this guards the CLI/direct path so an empty claim never ships.\n const yourClaim = (opts.yourClaim ?? \"\").trim();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n if (!yourClaim) {\n result.halted = \"set `yourClaim` in the hiring-signal config\";\n return result;\n }\n\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"this week\" : `last ${sinceDays} days`;\n const domainCache = new Map<string, string | null>();\n\n for (const role of roles) {\n if (hits.length >= limit * 2) break;\n const companyClause =\n opts.companies && opts.companies.length > 0\n ? ` (${opts.companies.map((c) => `\"${c}\"`).join(\" OR \")})`\n : \"\";\n const query = `\"${role}\"${companyClause} ${sincePhrase} (site:boards.greenhouse.io OR site:jobs.lever.co OR site:apply.workable.com OR site:jobs.ashbyhq.com)`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seen.has(hit.url) || !isAtsUrl(hit.url)) continue;\n seen.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"hiring-signal.webSearch\",\n role,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n continue;\n }\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: HiringSignalExtract;\n try {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n {\n role: \"user\",\n content: JSON.stringify({\n url: hit.url,\n markdown: (read.result.markdown ?? \"\").slice(0, 12000),\n }),\n },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parseHiringSignalExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"hiring-signal.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.jobTitle || !extract.company) {\n result.droppedEnrichment++;\n continue;\n }\n\n let domain = extract.companyDomain;\n if (!domain) {\n const resolved = await resolveCorporateDomain(extract.company, hit.url, domainCache);\n domain = resolved.domain;\n result.costUsd += resolved.costUsd;\n }\n if (!domain) {\n result.droppedEnrichment++;\n continue;\n }\n\n // Email target = the hiring manager when extracted, else fall back to a\n // best-effort search on the company domain (no name).\n const managerName =\n extract.hiringManagerName && extract.hiringManagerName.length > 0\n ? extract.hiringManagerName\n : null;\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: managerName,\n companyDomain: domain,\n isDuplicate: (email) =>\n isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n continue;\n }\n const email = contact.email;\n\n const recipientName = extract.hiringManagerName ?? contact.fullName;\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"hiring-signal\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl && recipientName) {\n linkedinUrl = await findLinkedInUrl({\n fullName: recipientName,\n disambiguators: [extract.company],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"hiring-signal\",\n });\n }\n\n const target: HiringSignalTarget = {\n name: recipientName ?? \"team\",\n email,\n company: extract.company,\n jobTitle: extract.jobTitle,\n jobPostUrl: extract.jobUrl ?? hit.url,\n yourClaim,\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.company} hiring \"${extract.jobTitle}\"${extract.team ? ` (${extract.team})` : \"\"} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function isAtsUrl(url: string): boolean {\n try {\n const host = new URL(url).hostname.toLowerCase();\n return ATS_DOMAIN_HINTS.some((h) => host === h || host.endsWith(`.${h}`));\n } catch {\n return false;\n }\n}\n\nconst SOCIAL_OR_ATS_HOSTS = new Set([\n \"linkedin.com\",\n \"twitter.com\",\n \"x.com\",\n \"facebook.com\",\n \"instagram.com\",\n \"youtube.com\",\n \"github.com\",\n \"wikipedia.org\",\n \"crunchbase.com\",\n \"glassdoor.com\",\n \"indeed.com\",\n \"builtin.com\",\n \"medium.com\",\n \"substack.com\",\n ...ATS_DOMAIN_HINTS,\n]);\n\n/**\n * Try to find the company's actual corporate domain when the LLM didn't\n * extract one from the job page. webSearch is ~$0.01/call; we cache by\n * company name within a single finder run so repeated postings from the same\n * employer don't double-charge.\n */\nasync function resolveCorporateDomain(\n company: string,\n jobUrl: string,\n cache: Map<string, string | null>,\n): Promise<{ domain: string | null; costUsd: number }> {\n const key = company.trim().toLowerCase();\n if (cache.has(key)) return { domain: cache.get(key) ?? null, costUsd: 0 };\n let costUsd = 0;\n let domain: string | null = null;\n try {\n const search = await webSearch(\n { query: `\"${company}\" official site`, maxResults: 5 },\n { playName: PLAY_NAME },\n );\n costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n const host = pickCorporateHost(hit.url);\n if (host) {\n domain = host;\n break;\n }\n }\n } catch {\n // fall through to slug guess\n }\n if (!domain) domain = slugFallback(jobUrl);\n cache.set(key, domain);\n return { domain, costUsd };\n}\n\nexport function pickCorporateHost(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const host = new URL(url).hostname.replace(/^www\\./, \"\").toLowerCase();\n if (SOCIAL_OR_ATS_HOSTS.has(host)) return null;\n if ([...SOCIAL_OR_ATS_HOSTS].some((h) => host.endsWith(`.${h}`))) return null;\n return host;\n } catch {\n return null;\n }\n}\n\nexport function slugFallback(jobUrl: string): string | null {\n try {\n const u = new URL(jobUrl);\n const seg = u.pathname.split(\"/\").find((s) => s.length > 0);\n if (seg && /^[a-z0-9-]+$/.test(seg)) return `${seg}.com`;\n } catch {\n // ignore\n }\n return null;\n}\n\nexport function parseHiringSignalExtract(raw: string): HiringSignalExtract {\n return tryParseJsonObject<HiringSignalExtract>(raw, {\n jobTitle: null,\n jobUrl: null,\n company: null,\n companyDomain: null,\n hiringManagerName: null,\n hiringManagerRole: null,\n team: null,\n postedAt: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { getLedger, logEvent, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { PodcastGuestTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport type { FinderResult, PodcastGuestExtract, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"podcast-guest\";\nconst SOURCE = \"find:podcast-guest\";\n\nexport interface PodcastGuestFinderOpts extends RunOpts {\n /** Podcasts to search. Default a small set of YC-adjacent shows. */\n podcasts?: string[];\n /** Days back to bias the search query. Default 21. */\n sinceDays?: number;\n /** Skip the deeper webRead step (cheaper but less accurate). */\n skipRead?: boolean;\n}\n\nconst DEFAULT_PODCASTS = [\n \"Latent Space\",\n \"Lenny's Podcast\",\n \"20VC\",\n \"Acquired\",\n \"Invest Like the Best\",\n];\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\nexport async function runPodcastGuestFinder(opts: PodcastGuestFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 21;\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const system = loadPrompt(\"podcast-guest-extract\");\n const podcasts = opts.podcasts && opts.podcasts.length > 0 ? opts.podcasts : DEFAULT_PODCASTS;\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const seen = new Set<string>();\n const hits: SearchHit[] = [];\n const sincePhrase = sinceDays <= 7 ? \"this week\" : `last ${sinceDays} days`;\n\n for (const show of podcasts) {\n if (hits.length >= limit * 2) break;\n const query = `\"${show}\" episode guest ${sincePhrase}`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(15, limit) },\n { playName: PLAY_NAME },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url || seen.has(hit.url)) continue;\n seen.add(hit.url);\n hits.push({ url: hit.url, title: hit.title, description: hit.description });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"podcast-guest.webSearch\",\n show,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n result.candidates = hits.length;\n\n for (const hit of hits.slice(0, limit)) {\n if (result.enqueued >= limit) break;\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n break;\n }\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\n result.droppedDuplicate++;\n continue;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const filter = await icpFilter({\n icp,\n candidate: { title: hit.title, url: hit.url, summary: hit.description },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n continue;\n }\n if (!filter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { title: hit.title, url: hit.url, description: hit.description },\n dedupeKey: hit.url,\n source: SOURCE,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n continue;\n }\n\n let extract: PodcastGuestExtract;\n try {\n let payload: Record<string, unknown> = {\n url: hit.url,\n title: hit.title,\n description: hit.description,\n };\n if (!opts.skipRead) {\n const read = await webRead({ url: hit.url }, { playName: PLAY_NAME });\n result.costUsd += read.result.cost ?? 0;\n payload = { ...payload, markdown: (read.result.markdown ?? \"\").slice(0, 12000) };\n }\n const llm = await complete({\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: JSON.stringify(payload) },\n ],\n temperature: 0.1,\n maxTokens: 500,\n });\n extract = parsePodcastGuestExtract(llm.content);\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"podcast-guest.llm.extract\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n continue;\n }\n\n if (!extract.guestName || !extract.guestCompanyDomain || !extract.podcastName) {\n result.droppedEnrichment++;\n continue;\n }\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: extract.guestName,\n companyDomain: extract.guestCompanyDomain,\n isDuplicate: (email) =>\n isDuplicate({ playName: PLAY_NAME, dedupeKey: hit.url, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n continue;\n }\n const email = contact.email;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"podcast-guest\",\n });\n result.costUsd += enr.costUsd;\n // Priority mirrors LinkedIn chain: page-specific extract beats generic\n // enrichment lookup when both are set.\n const phone = (extract.phone || null) ?? enr.phone;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\n linkedinUrl = linkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: extract.guestName,\n disambiguators: [extract.podcastName],\n accumCost: (c) => {\n result.costUsd += c ?? 0;\n },\n errKindPrefix: \"podcast-guest\",\n });\n }\n\n const target: PodcastGuestTarget = {\n name: extract.guestName,\n email,\n company: extract.guestCompany ?? extract.guestCompanyDomain,\n podcast: extract.podcastName,\n episodeTitle: extract.episodeTitle ?? hit.title,\n hookQuote: (extract.summary ?? hit.description ?? \"\").slice(0, 240),\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey: hit.url,\n source: SOURCE,\n notes: `${extract.guestName} on ${extract.podcastName} — ${filter.reason}`,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n }\n\n return result;\n}\n\nexport function parsePodcastGuestExtract(raw: string): PodcastGuestExtract {\n return tryParseJsonObject<PodcastGuestExtract>(raw, {\n podcastName: null,\n episodeTitle: null,\n episodeUrl: null,\n guestName: null,\n guestRole: null,\n guestCompany: null,\n guestCompanyDomain: null,\n publishedAt: null,\n linkedinUrl: null,\n phone: null,\n summary: null,\n });\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { BreakupReviveTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"breakup-revive\";\nconst SOURCE = \"find:breakup-revive\";\n\nexport interface BreakupReviveFinderOpts extends RunOpts {\n /** Min days since last activity to consider cold. Default 60. */\n minDays?: number;\n /** Max days since last activity to consider revivable. Default 90. */\n maxDays?: number;\n}\n\n/**\n * Scan the local ledger for cold prospects (no activity in the last\n * min/maxDays window) and enqueue them into target_queue. No LLM calls,\n * no OneShot spend — this is a ledger-only finder that reuses the same\n * review → approve → drain lifecycle as every other finder.\n */\nexport function runBreakupReviveFinder(opts: BreakupReviveFinderOpts): FinderResult {\n const limit = opts.limit ?? 25;\n const minDays = opts.minDays ?? 60;\n const maxDays = opts.maxDays ?? 90;\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n const cold = ledger.listColdProspects({\n minDaysSinceLastEvent: minDays,\n maxDaysSinceLastEvent: maxDays,\n limit: limit * 2, // pull extra; we'll drop any already in the queue\n });\n result.candidates = cold.length;\n\n for (const p of cold) {\n if (result.enqueued >= limit) break;\n if (!p.email) {\n result.droppedEnrichment++;\n continue;\n }\n\n // Dedupe key = prospect id so re-running doesn't re-enqueue the same\n // person until their previous queue row is archived or expired.\n const dedupeKey = `prospect:${p.id}`;\n if (isDuplicate({ playName: PLAY_NAME, dedupeKey, prospectEmail: undefined })) {\n result.droppedDuplicate++;\n continue;\n }\n\n const daysCold = p.last_event_at\n ? Math.floor((Date.now() - new Date(p.last_event_at).getTime()) / (24 * 3600 * 1000))\n : 0;\n\n const target: BreakupReviveTarget = {\n name: p.name,\n email: p.email,\n company: p.company,\n daysCold,\n lastEventAt: p.last_event_at,\n linkedinUrl: p.linkedin_url ?? null,\n phone: p.phone ?? null,\n };\n\n if (opts.dryRun) {\n result.enqueued++;\n continue;\n }\n\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source: SOURCE,\n notes: `${daysCold}d cold${p.company ? ` — ${p.company}` : \"\"}`,\n });\n if (id != null) {\n // Link the queue row to the prospect right away so the /queue page\n // can surface the connection without the drain-time backfill dance.\n try {\n ledger.setQueueProspectId(id, p.id);\n } catch {\n // best-effort — drain.ts will also try to backfill\n }\n result.enqueued++;\n } else {\n result.droppedDuplicate++;\n }\n }\n\n return result;\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\n\nexport interface GitHubSearchRepo {\n /** html_url, normalized to canonical github.com/<owner>/<repo>. */\n url: string;\n /** owner/repo. */\n fullName: string;\n description: string | null;\n stars: number;\n /** Self-tagged GitHub topic slugs from the repo's metadata. */\n topics: string[];\n language: string | null;\n pushedAt: string;\n}\n\n/**\n * Search the GitHub Search API for repos tagged with a topic.\n *\n * Uses `GITHUB_TOKEN` from env if set (30 req/min, exempt from secondary\n * abuse detection); falls back to unauthenticated (10 req/min, AND vulnerable\n * to GitHub silently returning empty results when soft-blocked for \"too many\"\n * unauth queries from the same IP — no 429, no error, just zero hits).\n *\n * Returns [] on:\n * - 422 (invalid query — usually a malformed topic slug)\n * - 403 (GitHub's actual unauth rate-limit signal)\n * - 429 (explicit rate-limit)\n * - any other non-2xx\n * - network error\n * - malformed JSON\n *\n * Same fault-tolerance pattern as `fetchGitHubUser`.\n */\nexport async function searchTopicRepos(args: {\n topic: string;\n minStars: number;\n /** ISO date string (YYYY-MM-DD) for the `pushed:>=` filter. */\n pushedSinceIso: string;\n /** Page size. <=100. */\n perPage: number;\n}): Promise<GitHubSearchRepo[]> {\n const q = `topic:${args.topic} stars:>=${args.minStars} pushed:>=${args.pushedSinceIso}`;\n const url =\n `https://api.github.com/search/repositories?q=${encodeURIComponent(q)}` +\n `&sort=updated&order=desc&per_page=${Math.max(1, Math.min(100, args.perPage))}`;\n try {\n const res = await fetch(url, { headers: githubHeaders() });\n if (!res.ok) {\n logEvent(\"github.topic.search\", {\n topic: args.topic,\n ok: false,\n status: res.status,\n });\n return [];\n }\n const json = (await res.json()) as Record<string, unknown>;\n const items = Array.isArray(json[\"items\"])\n ? (json[\"items\"] as Array<Record<string, unknown>>)\n : [];\n const repos = items.map(parseSearchItem).filter((r): r is GitHubSearchRepo => r !== null);\n // Detect GitHub's silent soft-block: 200 OK + empty items + total_count\n // reported as 0 even on slugs that should match (e.g. `langchain`). When\n // the unauth IP gets flagged for abuse, this is the failure mode — no\n // 429, just 0 hits forever for an hour or two. Surface a hint so the\n // caller can stop hammering and the operator can act (set GITHUB_TOKEN).\n const totalCount =\n typeof json[\"total_count\"] === \"number\" ? (json[\"total_count\"] as number) : null;\n const authed = Boolean(process.env[\"GITHUB_TOKEN\"]);\n const ratelimitHint = !authed && repos.length === 0 && totalCount === 0;\n logEvent(\"github.topic.search\", {\n topic: args.topic,\n ok: true,\n count: repos.length,\n total_count: totalCount,\n authed,\n ...(ratelimitHint ? { hint: \"0 hits + unauth — likely soft-blocked; set GITHUB_TOKEN\" } : {}),\n });\n return repos;\n } catch (err) {\n logEvent(\n \"github.topic.search\",\n {\n topic: args.topic,\n ok: false,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return [];\n }\n}\n\n/**\n * Build request headers for the GitHub REST API. Adds `Authorization: Bearer`\n * when `GITHUB_TOKEN` is set, lifting our quota from 10 req/min unauth →\n * 30 req/min for search (5,000/hour for everything else) AND making us\n * exempt from secondary abuse detection on the search endpoint.\n *\n * Exported so `_github-user.ts` can use the same auth shape.\n */\nexport function githubHeaders(): Record<string, string> {\n const headers: Record<string, string> = { Accept: \"application/vnd.github+json\" };\n const token = process.env[\"GITHUB_TOKEN\"];\n if (token && token.length > 0) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n return headers;\n}\n\n/** Parse one search-API `items[]` entry. Returns null on missing required fields. */\nexport function parseSearchItem(raw: Record<string, unknown>): GitHubSearchRepo | null {\n const htmlUrl = typeof raw[\"html_url\"] === \"string\" ? (raw[\"html_url\"] as string) : null;\n const fullName = typeof raw[\"full_name\"] === \"string\" ? (raw[\"full_name\"] as string) : null;\n if (!htmlUrl || !fullName) return null;\n return {\n url: htmlUrl,\n fullName,\n description: typeof raw[\"description\"] === \"string\" ? (raw[\"description\"] as string) : null,\n stars: typeof raw[\"stargazers_count\"] === \"number\" ? (raw[\"stargazers_count\"] as number) : 0,\n topics: Array.isArray(raw[\"topics\"])\n ? (raw[\"topics\"] as unknown[]).filter((t): t is string => typeof t === \"string\")\n : [],\n language: typeof raw[\"language\"] === \"string\" ? (raw[\"language\"] as string) : null,\n pushedAt: typeof raw[\"pushed_at\"] === \"string\" ? (raw[\"pushed_at\"] as string) : \"\",\n };\n}\n\n/**\n * Format a date as YYYY-MM-DD for the GitHub `pushed:>=` query operator.\n * Pulled out so callers can inject `now` for testing.\n */\nexport function isoDateNDaysAgo(days: number, now: Date = new Date()): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString().slice(0, 10);\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\nexport interface GitHubUserInfo {\n login: string;\n name: string | null;\n email: string | null;\n /** Bare hostname extracted from the user's blog URL. */\n blogDomain: string | null;\n company: string | null;\n}\n\n/** Lowercase-keyed cache; `null` = \"tried, got 404/429/network error\". */\nconst cache = new Map<string, GitHubUserInfo | null>();\n\n/** Test-only: drop the in-memory cache between cases. */\nexport function _resetGitHubUserCache(): void {\n cache.clear();\n}\n\n/**\n * Fetch a GitHub user's public profile via the unauth REST API. 403 is\n * GitHub's actual unauth rate-limit signal (not 429); treat both as\n * back-off. Null on any failure — caller falls through to the next\n * enrichment strategy.\n *\n * Unauth quota is 60 req/hour per IP. The cache keeps a popular author\n * surfaced by multiple combos at one API hit.\n */\nexport async function fetchGitHubUser(login: string): Promise<GitHubUserInfo | null> {\n const key = login.toLowerCase();\n if (cache.has(key)) return cache.get(key) ?? null;\n try {\n const res = await fetch(`https://api.github.com/users/${encodeURIComponent(login)}`, {\n headers: githubHeaders(),\n });\n if (res.status === 404) {\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: 404 });\n return null;\n }\n if (res.status === 429 || res.status === 403) {\n // 403 with rate-limit headers is GitHub's actual rate-limit signal for\n // unauthenticated callers. Treat both as \"back off, try later.\"\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: res.status, rate_limited: true });\n return null;\n }\n if (!res.ok) {\n cache.set(key, null);\n logEvent(\"github.user.fetch\", { login, ok: false, status: res.status });\n return null;\n }\n const json = (await res.json()) as Record<string, unknown>;\n const info: GitHubUserInfo = {\n login: typeof json[\"login\"] === \"string\" ? (json[\"login\"] as string) : login,\n name:\n typeof json[\"name\"] === \"string\" && json[\"name\"] !== \"\" ? (json[\"name\"] as string) : null,\n email:\n typeof json[\"email\"] === \"string\" && json[\"email\"] !== \"\"\n ? (json[\"email\"] as string)\n : null,\n blogDomain: extractBlogDomain(json[\"blog\"]),\n company:\n typeof json[\"company\"] === \"string\" && json[\"company\"] !== \"\"\n ? (json[\"company\"] as string)\n : null,\n };\n cache.set(key, info);\n logEvent(\"github.user.fetch\", {\n login,\n ok: true,\n has_email: info.email !== null,\n has_blog: info.blogDomain !== null,\n });\n return info;\n } catch (err) {\n cache.set(key, null);\n logEvent(\n \"github.user.fetch\",\n {\n login,\n ok: false,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * One of the candidate's own public repos. Star count + dates intentionally\n * dropped to keep token budget tight — the LLM picks ONE by topical fit, not\n * metrics.\n */\nexport interface TopRepo {\n name: string;\n description: string | null;\n language: string | null;\n}\n\n/** `null` = \"we tried and got 404/429/network error, don't retry within the run.\" */\nconst reposCache = new Map<string, TopRepo[] | null>();\n\n/** Test-only: drop the in-memory repos cache between cases. */\nexport function _resetTopReposCache(): void {\n reposCache.clear();\n}\n\n/**\n * Fetch the candidate's top 10 OWN public repos, sorted by most-recent push.\n *\n * `null` return: any non-2xx / network error / parse failure — caller skips\n * the repos block in the prompt. Empty `[]` is distinct from `null` and means\n * \"we asked, user has no public repos\".\n */\nexport async function fetchTopRepos(login: string): Promise<TopRepo[] | null> {\n const key = login.toLowerCase();\n if (reposCache.has(key)) return reposCache.get(key) ?? null;\n try {\n const url = `https://api.github.com/users/${encodeURIComponent(login)}/repos?per_page=10&sort=pushed&type=owner`;\n const res = await fetch(url, { headers: githubHeaders() });\n if (res.status === 404) {\n reposCache.set(key, null);\n logEvent(\"github.repos.fetch\", { login, ok: false, status: 404 });\n return null;\n }\n if (res.status === 429 || res.status === 403) {\n reposCache.set(key, null);\n logEvent(\"github.repos.fetch\", {\n login,\n ok: false,\n status: res.status,\n rate_limited: true,\n });\n return null;\n }\n if (!res.ok) {\n reposCache.set(key, null);\n logEvent(\"github.repos.fetch\", { login, ok: false, status: res.status });\n return null;\n }\n const json = (await res.json()) as Array<Record<string, unknown>>;\n if (!Array.isArray(json)) {\n reposCache.set(key, null);\n logEvent(\"github.repos.fetch\", { login, ok: false, status: res.status, malformed: true });\n return null;\n }\n // Drop forks (GitHub's `type=owner` filters by ownership relation, NOT\n // fork status — a daily-syncing fork of kubernetes/next.js would float to\n // the top via sort=pushed and read as shipping evidence to the LLM).\n // Drop archived + missing-name entries. Cap description at 160 chars.\n const repos: TopRepo[] = json\n .filter(\n (r) =>\n r[\"archived\"] !== true &&\n r[\"fork\"] !== true &&\n typeof r[\"name\"] === \"string\" &&\n r[\"name\"] !== \"\",\n )\n .map((r) => {\n const rawDesc =\n typeof r[\"description\"] === \"string\" && r[\"description\"] !== \"\"\n ? (r[\"description\"] as string)\n : null;\n return {\n name: r[\"name\"] as string,\n description: rawDesc && rawDesc.length > 160 ? `${rawDesc.slice(0, 159)}…` : rawDesc,\n language: typeof r[\"language\"] === \"string\" ? (r[\"language\"] as string) : null,\n };\n });\n reposCache.set(key, repos);\n logEvent(\"github.repos.fetch\", { login, ok: true, count: repos.length });\n return repos;\n } catch (err) {\n reposCache.set(key, null);\n logEvent(\n \"github.repos.fetch\",\n {\n login,\n ok: false,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Normalize a profile `blog` field to a bare hostname.\n *\n * GitHub stores whatever the user typed, so this needs to handle:\n * `https://acme.dev`, `acme.dev`, `www.acme.dev`, `https://acme.dev/about`,\n * `acme.dev?utm=x`, and (commonly) the empty string. Returns null on anything\n * that doesn't look like a usable hostname.\n */\nexport function extractBlogDomain(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n if (trimmed.length === 0) return null;\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n try {\n const u = new URL(withScheme);\n const host = u.hostname.replace(/^www\\./i, \"\").toLowerCase();\n if (host.length === 0 || !host.includes(\".\")) return null;\n return host;\n } catch {\n return null;\n }\n}\n\n/**\n * Pull the `<owner>` segment out of a `https://github.com/<owner>/<repo>` URL\n * so callers don't have to re-implement URL parsing. Returns null if the URL\n * isn't a normalized GitHub repo URL.\n */\nexport function ownerFromRepoUrl(repoUrl: string): string | null {\n try {\n const u = new URL(repoUrl);\n if (!/(^|\\.)github\\.com$/i.test(u.hostname)) return null;\n const parts = u.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 1) return null;\n return parts[0] ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Pull the `<repo>` segment out of a `https://github.com/<owner>/<repo>` URL.\n * Returns null when the URL doesn't have a repo segment (org page, gist, etc).\n */\nexport function repoNameFromRepoUrl(repoUrl: string): string | null {\n try {\n const u = new URL(repoUrl);\n if (!/(^|\\.)github\\.com$/i.test(u.hostname)) return null;\n const parts = u.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n return parts[1] ?? null;\n } catch {\n return null;\n }\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\n/**\n * Deterministic stack detection from a GitHub repo's manifest files. Replaces\n * the older webRead + LLM-extract path that was unreliable in two ways: (1)\n * webRead timed out on ~44% of GitHub README pages (JS-rendered), and (2)\n * READMEs are marketing copy that doesn't always match what the code\n * actually imports. Manifests are authoritative — if `openai` is in\n * `package.json`, the project uses OpenAI.\n *\n * Files we scan in priority order: package.json (npm), pyproject.toml +\n * requirements.txt (Python), .env.example (env-var leakage). Each fetch is\n * independent + best-effort; missing files just contribute nothing.\n *\n * The `vocab` argument is the founder-controlled vendor list. Each vocab\n * string is substring-matched (case-insensitive) against the union of all\n * extracted manifest tokens — `twilio` matches `twilio`, `twilio-node`,\n * `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is no hardcoded\n * vendor catalog; oneshot-gtm is a generic founder tool and competitive\n * vocabularies vary entirely by founder. The strategist proposes vocab\n * populations from the founder's product/ICP context (see\n * `packages/prompts/strategist-trigger.md`).\n *\n * Cost: ~3-4 GitHub API calls per candidate. With `GITHUB_TOKEN` set the\n * 5,000/hr quota is plenty for any practical run.\n */\n\nexport interface StackDetection {\n /** Founder-vocab vendors that matched at least one manifest token. Sorted. */\n detected: string[];\n /** Manifest filenames that were found (for diagnostics + event logging). */\n manifestsFound: string[];\n}\n\n/**\n * Scan a GitHub repo's manifests and return the founder-vocab vendors that\n * match at least one extracted package or env-var-key token.\n */\nexport async function detectRepoStack(args: {\n owner: string;\n repo: string;\n /** Founder's vendor list — substring-matched (case-insensitive) against\n * manifest deps + env-var keys. Empty vocab → empty detection. */\n vocab: string[];\n}): Promise<StackDetection> {\n const { owner, repo, vocab } = args;\n const targets = [\"package.json\", \"pyproject.toml\", \"requirements.txt\", \".env.example\"];\n const fetched = await Promise.all(\n targets.map(async (path) => ({\n path,\n content: await fetchRepoFile(owner, repo, path),\n })),\n );\n\n const allNames = new Set<string>();\n const manifestsFound: string[] = [];\n for (const { path, content } of fetched) {\n if (!content) continue;\n manifestsFound.push(path);\n for (const name of namesFromManifest(path, content)) {\n allNames.add(name.toLowerCase());\n }\n }\n\n // Single transparent matching loop. Each vocab entry is a substring needle\n // searched across every extracted token. Casing doesn't matter (tokens\n // were lowercased on insertion). Substring is intentional: founder typing\n // `twilio` matches `twilio-node`, `@twilio/voice-sdk`, and `TWILIO_*` env\n // keys — three real signals from one vocab entry.\n const detected = new Set<string>();\n for (const v of vocab) {\n const needle = v.toLowerCase();\n if (needle.length === 0) continue;\n for (const n of allNames) {\n if (n.includes(needle)) {\n detected.add(v);\n break;\n }\n }\n }\n\n logEvent(\"github.repo.stack\", {\n owner,\n repo,\n manifests_found: manifestsFound,\n detected_count: detected.size,\n });\n\n return {\n detected: [...detected].toSorted(),\n manifestsFound,\n };\n}\n\n/**\n * Fetch a file from a repo's default branch via the GitHub Contents API.\n * Returns null on any non-2xx (including 404 — file just doesn't exist),\n * network error, or unexpected content type. Same fault-tolerance pattern\n * as `fetchGitHubUser`.\n */\nasync function fetchRepoFile(owner: string, repo: string, path: string): Promise<string | null> {\n const url = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${path}`;\n try {\n const headers = { ...githubHeaders(), Accept: \"application/vnd.github.raw\" };\n const res = await fetch(url, { headers });\n if (!res.ok) return null;\n const text = await res.text();\n // Defensive cap. Manifests are usually < 50KB; anything larger is either\n // a spurious vendored file or a bug. We're only doing substring matches\n // so trimming is safe.\n return text.length > 200_000 ? text.slice(0, 200_000) : text;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract dependency-like name strings from a manifest file's content.\n * Format-aware: each manifest has its own conventions.\n *\n * Exported for unit testing.\n */\nexport function namesFromManifest(path: string, content: string): string[] {\n if (path === \"package.json\") return parsePackageJson(content);\n if (path === \"pyproject.toml\") return parsePyProject(content);\n if (path === \"requirements.txt\") return parseRequirementsTxt(content);\n if (path === \".env.example\") return parseEnvKeys(content);\n return [];\n}\n\n/** Pull `dependencies` + `devDependencies` keys out of a package.json. */\nfunction parsePackageJson(content: string): string[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return [];\n }\n if (!parsed || typeof parsed !== \"object\") return [];\n const obj = parsed as Record<string, unknown>;\n const out: string[] = [];\n for (const key of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const deps = obj[key];\n if (deps && typeof deps === \"object\") {\n out.push(...Object.keys(deps as Record<string, unknown>));\n }\n }\n return out;\n}\n\n/**\n * Pull dep names out of a pyproject.toml. We don't ship a TOML parser — a\n * regex over `name = \"...\"` patterns inside `[project.dependencies]` and\n * Poetry-style `[tool.poetry.dependencies]` sections covers the bulk of\n * real-world files. Fail-soft: missing matches just yield no names.\n */\nfunction parsePyProject(content: string): string[] {\n const out: string[] = [];\n // Poetry: `package_name = \"^1.2.3\"` or `package_name = { version = ... }`\n const poetryRx = /^\\s*([a-zA-Z0-9_\\-.]+)\\s*=\\s*[\"{]/gm;\n let m: RegExpExecArray | null;\n while ((m = poetryRx.exec(content)) !== null) {\n const name = m[1];\n if (name && !RESERVED_PYPROJECT_KEYS.has(name.toLowerCase())) {\n out.push(name);\n }\n }\n // PEP 621: `dependencies = [\"package_name>=1.0\", ...]` — strings inside\n // an array of dependency specifiers.\n const pep621Rx = /[\"']([a-zA-Z0-9_\\-.]+)\\s*(?:[<>=!~][^\"']*)?[\"']/g;\n while ((m = pep621Rx.exec(content)) !== null) {\n const name = m[1];\n if (name && name.length > 1) out.push(name);\n }\n return out;\n}\n\n/**\n * Reserved top-level keys in pyproject.toml that aren't dependencies. The\n * Poetry regex is loose enough to match these; this set filters them out.\n */\nconst RESERVED_PYPROJECT_KEYS = new Set([\n \"name\",\n \"version\",\n \"description\",\n \"readme\",\n \"license\",\n \"authors\",\n \"maintainers\",\n \"homepage\",\n \"repository\",\n \"documentation\",\n \"keywords\",\n \"classifiers\",\n \"requires-python\",\n \"python\",\n \"dependencies\",\n \"optional-dependencies\",\n \"scripts\",\n \"entry-points\",\n \"urls\",\n \"include\",\n \"exclude\",\n \"build-backend\",\n \"build-system\",\n \"requires\",\n]);\n\n/** First token of each non-comment line in requirements.txt. */\nfunction parseRequirementsTxt(content: string): string[] {\n const out: string[] = [];\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (line.length === 0 || line.startsWith(\"#\") || line.startsWith(\"-\")) continue;\n // Strip version specifier and extras: `package[extras]==1.0.0` → `package`\n const m = /^([a-zA-Z0-9_\\-.]+)/.exec(line);\n if (m && m[1]) out.push(m[1]);\n }\n return out;\n}\n\n/**\n * Pull env-var keys out of a `.env.example` (or `.env.sample`). Vendor SDKs\n * conventionally name their keys after themselves (`OPENAI_API_KEY`,\n * `TWILIO_ACCOUNT_SID`, etc), so the keys themselves are great signal even\n * when the values are placeholder.\n */\nfunction parseEnvKeys(content: string): string[] {\n const out: string[] = [];\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (line.length === 0 || line.startsWith(\"#\")) continue;\n const eq = line.indexOf(\"=\");\n if (eq <= 0) continue;\n out.push(line.slice(0, eq).trim());\n }\n return out;\n}\n","import {\n deepResearchPerson,\n enrichProfile,\n findEmail,\n getLedger,\n logEvent,\n verifyEmail,\n} from \"@oneshot-gtm/core\";\nimport type { CompetitorSwitchTarget, StackConsolidationTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { shouldSkipFindEmail } from \"./_findemail-prescreen.ts\";\nimport { icpFilter } from \"./_filter.ts\";\nimport {\n fetchGitHubUser,\n ownerFromRepoUrl,\n repoNameFromRepoUrl,\n type GitHubUserInfo,\n} from \"./_github-user.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { extractFirstPhone, findLinkedInUrl } from \"./_linkedin.ts\";\nimport { detectRepoStack } from \"./_repo-stack.ts\";\nimport type { AgentBuilderExtract, FinderResult } from \"./_types.ts\";\n\n/**\n * Shared per-candidate pipeline for repo-style finders. Today it has one\n * caller (`github-topics`); kept as its own module because the per-candidate\n * body — snippet ICP → GitHub manifest scan + user fetch → minVendors gate →\n * resolveContact (3-tier: extract domain → GitHub user → deepResearchPerson) →\n * verifyEmail → enqueue — is large enough that inlining it back would obscure\n * the finder, and ctx-based parameterisation keeps the door open for future\n * repo finders without re-extracting later.\n *\n * Stack detection used to be a webRead + LLM extract on the README, which\n * (a) timed out ~44% of the time on JS-rendered GitHub pages and (b) read\n * marketing copy that didn't reflect actual code. We now pull the truth\n * directly from package.json / pyproject.toml / requirements.txt /\n * .env.example via the GitHub Contents API. Free, fast, deterministic.\n */\nconst PLAY_NAME = \"stack-consolidation\";\n\nexport interface RepoCandidate {\n /** Normalized github.com/<owner>/<repo>. */\n url: string;\n title: string;\n description: string;\n /** Pre-discovery vendor hints; github-topics leaves empty (manifest scan later). */\n vendors: string[];\n /** GitHub topic tags, used as the snippet-ICP signal when present. */\n topics?: string[];\n}\n\nexport interface RepoPipelineCtx {\n icp: string | null;\n /** Founder's vendor list — passed to detectRepoStack as the matching vocabulary. */\n vocab: string[];\n /**\n * Subset of `vocab` the founder competes with head-on. A candidate whose\n * detected stack includes one routes to competitor-switch; otherwise\n * stack-consolidation. Matched case-insensitively. Empty = always\n * stack-consolidation.\n */\n directCompetitors?: string[];\n yourEdge: string;\n minVendors: number;\n useDeepResearch: boolean;\n /** Mutable accumulator. Workers mutate fields on this directly. */\n result: FinderResult;\n /**\n * Boxed flag so workers share the same reference across the parallelMap\n * pool. Soft halt: workers check at the top of each iteration but several\n * may pass before any flips it — over-shoot up to (concurrency-1) is\n * acceptable for the scales we operate at.\n */\n halted: { value: boolean };\n limit: number;\n maxCostUsd: number | undefined;\n /** Receipt source tag, e.g. \"find:github-topics\". */\n sourceTag: string;\n /** Notes-line prefix, e.g. \"github-topic\". */\n notesPrefix: string;\n dryRun: boolean;\n}\n\n/**\n * Process a single candidate through the full pipeline. Mutates ctx.result.\n * Never throws — internal exceptions become droppedEnrichment increments via\n * the surrounding try/catch blocks. Safe to call concurrently across workers.\n */\nexport async function processRepoCandidate(\n hit: RepoCandidate,\n ctx: RepoPipelineCtx,\n): Promise<void> {\n const { result } = ctx;\n if (ctx.halted.value) return;\n if (result.enqueued >= ctx.limit) {\n ctx.halted.value = true;\n return;\n }\n if (ctx.maxCostUsd != null && result.costUsd >= ctx.maxCostUsd) {\n result.halted = `max-cost cap (${ctx.maxCostUsd})`;\n ctx.halted.value = true;\n return;\n }\n const ledger = getLedger();\n // The play isn't known until the stack is detected below, so check both\n // possible routes — a repo enqueued under either play is a duplicate.\n if (\n ledger.isQueueDuplicate(\"stack-consolidation\", hit.url) ||\n ledger.isQueueDuplicate(\"competitor-switch\", hit.url)\n ) {\n result.droppedDuplicate++;\n return;\n }\n\n if (ctx.dryRun) {\n result.enqueued++;\n return;\n }\n\n const accumCost = (c: number | undefined): void => {\n result.costUsd += c ?? 0;\n };\n const errKindPrefix = ctx.sourceTag.replace(/^find:/, \"\");\n\n // 1) ICP on the snippet — cheap pre-filter. Skips the manifest scan +\n // user-fetch + contact-resolution chain on candidates the classifier\n // rejects, which is most of them in practice.\n const snippetFilter = await icpFilter({\n icp: ctx.icp,\n candidate: {\n title: hit.title,\n url: hit.url,\n summary: describeForIcp(hit),\n },\n });\n if (snippetFilter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n return;\n }\n if (!snippetFilter.match) {\n result.droppedIcp++;\n ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: { repoUrl: hit.url, title: hit.title, description: hit.description },\n dedupeKey: hit.url,\n source: ctx.sourceTag,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${snippetFilter.reason}`,\n });\n return;\n }\n\n // 2) Stack detection — deterministic GitHub-API scan of manifest files\n // (package.json, pyproject.toml, requirements.txt, .env.example) instead\n // of webRead + LLM extract. Three reasons:\n // - webRead timed out on ~44% of GitHub repo pages (JS-rendered)\n // - READMEs are marketing copy that don't always match what code imports\n // - Manifest scanning is free (counts against GITHUB_TOKEN's 5k/hr) and\n // authoritative — if `openai` is in package.json the repo uses OpenAI\n //\n // Author / company come from the GitHub user profile (also free).\n const owner = ownerFromRepoUrl(hit.url);\n const repoName = repoNameFromRepoUrl(hit.url);\n if (!owner || !repoName) {\n // Shouldn't happen for normalized URLs but defend against drift.\n result.droppedEnrichment++;\n return;\n }\n const [stack, ghUserInfo] = await Promise.all([\n detectRepoStack({ owner, repo: repoName, vocab: ctx.vocab }),\n fetchGitHubUser(owner),\n ]);\n\n if (stack.detected.length < ctx.minVendors) {\n logEvent(\"github-topics.dropped.min_vendors\", {\n repo: `${owner}/${repoName}`,\n detected_count: stack.detected.length,\n manifests_found: stack.manifestsFound,\n min_vendors: ctx.minVendors,\n });\n result.droppedEnrichment++;\n return;\n }\n\n const extract: AgentBuilderExtract = {\n repoUrl: hit.url,\n githubHandle: owner,\n // Prefer the human-friendly name; many GitHub users leave it blank.\n // findEmail downstream short-circuits gracefully when this is null.\n authorFullName: ghUserInfo?.name ?? null,\n authorRole: null, // not derivable from GitHub user API\n companyName: ghUserInfo?.company ?? null,\n // The GitHub blog field is a single bare hostname — we don't have enough\n // signal to know if it's corporate or personal, so map it to companyDomain\n // and leave personalDomain null. The resolveContact fallback chain reads\n // both via `?? null`, so the choice doesn't change behavior.\n companyDomain: ghUserInfo?.blogDomain ?? null,\n personalDomain: null,\n stackDetected: stack.detected,\n summary: null,\n };\n\n // Route by direct-competitor match: a candidate whose detected stack\n // includes one of the founder's head-on rivals gets the competitor-switch\n // motion (\"switch from X\"); everything else is a stack-consolidation\n // (vendor-sprawl) pitch. directCompetitors is empty by default → always\n // stack-consolidation. The resolved play name is used for the rest of this\n // candidate's pipeline (dedupe, receipt tags, enqueue).\n const directSet = new Set((ctx.directCompetitors ?? []).map((s) => s.toLowerCase()));\n const matchedCompetitor = extract.stackDetected.find((v) => directSet.has(v.toLowerCase()));\n const playName = matchedCompetitor ? \"competitor-switch\" : \"stack-consolidation\";\n\n // 3) Resolve a contact (3-tier: extract domain → GitHub user → deepResearch).\n // Pass the already-fetched ghUserInfo so resolveContact doesn't re-fetch.\n const contact = await resolveContact({\n extract,\n repoUrl: hit.url,\n ghUser: ghUserInfo,\n accumCost,\n useDeepResearch: ctx.useDeepResearch,\n errKindPrefix,\n playName,\n });\n if (!contact) {\n result.droppedEnrichment++;\n return;\n }\n\n if (isDuplicate({ playName, dedupeKey: hit.url, prospectEmail: contact.email })) {\n result.droppedDuplicate++;\n return;\n }\n\n // verifyEmail can throw on transient SDK / network errors. Catch and drop\n // the candidate rather than letting one bad call tear down the pool —\n // identical reasoning to the findEmail wrap in resolveContact.tryFindEmail.\n let verified: Awaited<ReturnType<typeof verifyEmail>>;\n try {\n verified = await verifyEmail({ email: contact.email }, { playName });\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.verify_email`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n result.droppedEnrichment++;\n return;\n }\n accumCost(verified.result.cost ?? 0);\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n // Always-on post-verify enrichment so phone + linkedin land on every\n // queue row. Path B' may have already populated both — skip the call\n // when so. ~$0.005 per call when fired (per OneShot pricing).\n if (!contact.phone || !contact.linkedinUrl) {\n const enr = await enrichVerifiedContact(contact.email, {\n playName,\n errKindPrefix,\n });\n accumCost(enr.costUsd);\n contact.phone = contact.phone ?? enr.phone;\n contact.linkedinUrl = contact.linkedinUrl ?? enr.linkedinUrl;\n }\n\n const stackLine = extract.stackDetected.join(\", \");\n const vendorCount = extract.stackDetected.length;\n const companyFallback = contact.domain ?? contact.email.split(\"@\")[1] ?? \"\";\n const name = extract.authorFullName ?? contact.fullName ?? extract.githubHandle ?? \"there\";\n const company = extract.companyName ?? extract.githubHandle ?? companyFallback;\n const contactExtras = {\n ...(contact.linkedinUrl ? { linkedinUrl: contact.linkedinUrl } : {}),\n ...(contact.phone ? { phone: contact.phone } : {}),\n };\n\n const target: CompetitorSwitchTarget | StackConsolidationTarget = matchedCompetitor\n ? {\n name,\n email: contact.email,\n company,\n competitor: matchedCompetitor,\n evidenceUrl: hit.url,\n // Honest, specific evidence — no fabricated \"auth surfaces\". Single\n // vendor, so no rule-of-three risk. Setting evidenceText also makes\n // competitor-switch skip its (expensive) browser scrape.\n evidenceText: `Their public repo uses ${matchedCompetitor} (found in ${stack.manifestsFound.join(\", \")}).`,\n yourEdge: ctx.yourEdge,\n ...contactExtras,\n }\n : {\n name,\n email: contact.email,\n company,\n vendorStack: stackLine,\n evidenceUrl: hit.url,\n yourEdge: ctx.yourEdge,\n ...contactExtras,\n };\n const notes = truncate(\n `${ctx.notesPrefix}: ${stackLine} (${vendorCount} vendors) — ${snippetFilter.reason}`,\n 220,\n );\n const id = ledger.enqueueTarget({\n playName,\n payload: target,\n dedupeKey: hit.url,\n source: ctx.sourceTag,\n notes,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n}\n\ninterface ResolvedContact {\n email: string;\n /** From findEmail; null when GitHub gave us the email directly. */\n fullName: string | null;\n /** The domain we used; null only on a direct GitHub email with no blog/extract domain. */\n domain: string | null;\n /** Surfaced via Path B' webSearch / enrichProfile. */\n linkedinUrl: string | null;\n /** Surfaced via Path C deepResearch enrichment. */\n phone: string | null;\n}\n\n/**\n * Resolve a deliverable contact for a repo candidate.\n *\n * Decision tree (cheapest path first; one paid call per tier):\n * 1. extract has a domain → findEmail($0.005). Done if found.\n * 2. GitHub user provides an email directly → use it (no findEmail spend).\n * 3. (opt-in) deepResearchPerson($0.05, 2-5 min async) with the repo URL +\n * author name — recovers the bucket where nobody has a resolvable\n * companyDomain anywhere.\n *\n * The pre-fetched `ghUser` is required from the pipeline (we already fetch\n * it for the extract construction); accepting it here avoids a duplicate\n * lookup. Pass null if the candidate isn't a GitHub repo.\n */\nexport async function resolveContact(args: {\n extract: AgentBuilderExtract;\n repoUrl: string;\n /** Pre-fetched GitHub user info from the pipeline. Null when unavailable. */\n ghUser: GitHubUserInfo | null;\n accumCost: (c: number | undefined) => void;\n useDeepResearch: boolean;\n /** Used in the deep-research error event kind, e.g. \"github-topics\". */\n errKindPrefix?: string;\n /** Resolved motion play, used to tag the receipts this resolution spends on. */\n playName?: string;\n}): Promise<ResolvedContact | null> {\n const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;\n const errKindPrefix = args.errKindPrefix ?? \"repo-pipeline\";\n const playName = args.playName ?? PLAY_NAME;\n const extractDomain = extract.companyDomain ?? extract.personalDomain ?? null;\n let discoveredLinkedinUrl: string | null = null;\n\n // Path A: extract has a domain. Try findEmail with it.\n if (extractDomain) {\n const direct = await tryFindEmail(extractDomain, extract, accumCost, errKindPrefix, playName);\n if (direct)\n return {\n ...direct,\n domain: extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: null,\n };\n // Fall through.\n }\n\n // Path B: GitHub user provides an email directly.\n if (ghUser?.email) {\n return {\n email: ghUser.email,\n fullName: null,\n domain: ghUser.blogDomain ?? extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: null,\n };\n }\n\n // Path B': webSearch for the author's LinkedIn URL → enrichProfile to recover\n // company / company_domain / sometimes email. Bridges the common case where\n // GitHub gives us a name but no company/blog — without this, deep-research\n // (Path C) fails its required-identifier gate and the candidate drops.\n //\n // Cost when triggered: $0.01 webSearch + $0.005 enrichProfile = ~$0.015.\n // Skipped entirely when extract.companyName already known OR neither the\n // author name nor github handle is available.\n let companyForGate: string | null = extract.companyName ?? null;\n let domainForGate: string | null = extractDomain;\n if (!companyForGate && (extract.authorFullName || extract.githubHandle)) {\n const tokens = [extract.authorFullName, extract.githubHandle].filter((t): t is string =>\n Boolean(t),\n );\n const linkedinUrl = await findLinkedInUrl({\n fullName: tokens[0] ?? \"\",\n disambiguators: tokens.slice(1),\n accumCost,\n errKindPrefix,\n });\n if (linkedinUrl) {\n discoveredLinkedinUrl = linkedinUrl;\n try {\n const enriched = await enrichProfile({ linkedinUrl }, { playName });\n accumCost(enriched.result.cost ?? 0);\n const profile = enriched.result.profile;\n // PersonResult exposes phone (string) AND fullphone (array) — extractFirstPhone\n // reads either. Capture once and reuse on every return path so we don't drop\n // a phone the SDK already paid to retrieve.\n const enrichedPhone = extractFirstPhone(profile);\n // Cache the linkedin-keyed enrich by the SURFACED email so the later\n // post-verify enrichVerifiedContact (by email) becomes a cache hit and\n // skips its second SDK call. Only cache when profile.email is directly\n // surfaced — for paths that derive the email via findEmail (different\n // API), we can't guarantee the profile is for the same person, so\n // skip the cache to avoid poisoning.\n if (profile?.email) {\n try {\n getLedger().setCachedEnrichment(\n profile.email.trim().toLowerCase(),\n JSON.stringify(enriched.result),\n );\n } catch {\n // cache write is best-effort.\n }\n }\n // 1) enrichProfile gave us a direct email — use it.\n if (profile?.email) {\n return {\n email: profile.email,\n fullName: profile.full_name ?? extract.authorFullName,\n domain: profile.company_domain ?? extractDomain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: enrichedPhone,\n };\n }\n // 2) Got a company_domain — try findEmail with it.\n if (profile?.company_domain) {\n const viaEnriched = await tryFindEmail(\n profile.company_domain,\n { ...extract, authorFullName: profile.full_name ?? extract.authorFullName },\n accumCost,\n errKindPrefix,\n playName,\n );\n if (viaEnriched)\n return {\n ...viaEnriched,\n domain: profile.company_domain,\n linkedinUrl: discoveredLinkedinUrl,\n phone: enrichedPhone,\n };\n domainForGate = profile.company_domain;\n }\n // 3) At minimum we may have learned a company name — feeds Path C's gate.\n if (profile?.company) companyForGate = profile.company;\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.enrich_profile`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n }\n\n // Path C: deep research as the last resort. The API needs strong identifiers\n // to find a person — empirically, `socialMediaUrl: <github-repo-url>` alone\n // is NOT enough (we burned $0.15 on three \"Could not find data for this\n // person\" failures with just that). Require either:\n // (a) a known email, OR\n // (b) full name AND company (company may have been populated by Path B')\n // Anything weaker spends $0.05 on a near-guaranteed miss. The repoUrl is\n // still passed as `socialMediaUrl` for bonus signal when present.\n if (!useDeepResearch) return null;\n const hasName = Boolean(extract.authorFullName && extract.authorFullName.length > 0);\n const hasCompany = Boolean(companyForGate && companyForGate.length > 0);\n // We never have an email here by definition — Paths A/B both bail before\n // setting one, and a contact found earlier short-circuits before this tier.\n // Kept as a placeholder for future flexibility (e.g. a discovery layer that\n // surfaces a tentative email).\n const hasEmail = false;\n if (!hasEmail && !(hasName && hasCompany)) return null;\n try {\n const dr = await deepResearchPerson(\n {\n socialMediaUrl: repoUrl,\n ...(hasName ? { name: extract.authorFullName as string } : {}),\n ...(hasCompany ? { company: companyForGate as string } : {}),\n },\n { playName },\n );\n accumCost(dr.result.cost ?? 0);\n const enr = dr.result.result?.enrichment;\n const drEmail = enr?.best_work_email ?? enr?.best_personal_email ?? enr?.altemails?.[0] ?? null;\n if (!drEmail) return null;\n const drFullName =\n [enr?.firstname, enr?.lastname]\n .filter((p): p is string => Boolean(p))\n .join(\" \")\n .trim() ||\n enr?.displayname ||\n null;\n const drPhone = extractFirstPhone(enr);\n return {\n email: drEmail,\n fullName: drFullName,\n domain: domainForGate ?? ghUser?.blogDomain ?? drEmail.split(\"@\")[1] ?? null,\n linkedinUrl: discoveredLinkedinUrl,\n phone: drPhone,\n };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.deep_research`,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n}\n\n/**\n * Single findEmail attempt with consistent fault-handling. OneShot's\n * findEmail requires `full_name` (or first+last) — without one it throws\n * synchronously, and a throw here would tear down the parallelMap pool. We\n * short-circuit cleanly when there's no name, and catch the SDK throw on\n * transient network errors. Either failure mode returns null so the caller\n * falls through to the next contact-resolution tier.\n */\nasync function tryFindEmail(\n domain: string,\n extract: AgentBuilderExtract,\n accumCost: (c: number | undefined) => void,\n errKindPrefix: string,\n playName: string,\n): Promise<{ email: string; fullName: string | null } | null> {\n if (!extract.authorFullName || extract.authorFullName.length === 0) {\n return null;\n }\n const skip = shouldSkipFindEmail({\n fullName: extract.authorFullName,\n companyDomain: domain,\n });\n if (!skip.ok) {\n logEvent(\n \"finder.skipped_findemail\",\n { name: playName, reason: skip.reason, kind: `${errKindPrefix}.find_email` },\n \"info\",\n );\n return null;\n }\n let found: Awaited<ReturnType<typeof findEmail>>;\n try {\n found = await findEmail(\n { fullName: extract.authorFullName, companyDomain: domain },\n { playName },\n );\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: `${errKindPrefix}.find_email`,\n domain,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n accumCost(found.result.cost ?? 0);\n if (found.result.found && found.result.email) {\n return { email: found.result.email, fullName: found.result.full_name ?? null };\n }\n return null;\n}\n\n/**\n * Compose the snippet-ICP `summary` from whichever signal we have. Topic-driven\n * candidates (github-topics) carry the repo's self-tagged GitHub topics. The\n * `vendors` branch is reserved for future finders that surface known vendor\n * names at discovery. If neither is present, return the bare description\n * rather than emitting an empty `topics: ` tail.\n *\n * Exported for direct unit testing — integration coverage of both branches\n * would require a discovery shape that doesn't exist yet.\n */\nexport function describeForIcp(hit: RepoCandidate): string {\n if (hit.vendors.length > 0) {\n return `${hit.description} vendors: ${hit.vendors.join(\", \")}`;\n }\n const topics = hit.topics ?? [];\n if (topics.length > 0) {\n return `${hit.description} topics: ${topics.join(\", \")}`;\n }\n return hit.description;\n}\n\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","/**\n * Generic GitHub-repo URL utilities used by the github-topics finder + the\n * shared `_repo-pipeline.ts`. Kept finder-agnostic — no combo / topic state.\n */\n\nconst NOISE_REPO_PATTERNS = [\n /^awesome[-_]/i,\n /[-_]awesome$/i,\n /^learn[-_]/i,\n /[-_]tutorial(s)?$/i,\n /^tutorial[-_]/i,\n /[-_]example(s)?$/i,\n /^example[-_]/i,\n /[-_]demo$/i,\n /^demo[-_]/i,\n /[-_]course$/i,\n /^course[-_]/i,\n /[-_]bootcamp$/i,\n /^cheatsheet/i,\n /[-_]boilerplate$/i,\n /^template[-_]/i,\n];\n\n/**\n * True when the repo name matches an \"awesome list / tutorial / demo / course /\n * boilerplate\" pattern. Catches the dominant non-buyer repos before the LLM\n * extract spends $0.02+ on them.\n */\nexport function looksLikeNoiseRepo(repoUrl: string): boolean {\n const name = repoUrl.split(\"/\").pop() ?? \"\";\n return NOISE_REPO_PATTERNS.some((rx) => rx.test(name));\n}\n\n/** First-segment paths on github.com that are never repos (org pages, topic indexes, marketplace, …). */\nconst GITHUB_RESERVED_PATHS = new Set([\n \"about\",\n \"collections\",\n \"contact\",\n \"customer-stories\",\n \"enterprise\",\n \"events\",\n \"explore\",\n \"features\",\n \"issues\",\n \"join\",\n \"login\",\n \"marketplace\",\n \"new\",\n \"notifications\",\n \"orgs\",\n \"organizations\",\n \"pricing\",\n \"pulls\",\n \"readme\",\n \"search\",\n \"security\",\n \"settings\",\n \"site\",\n \"sponsors\",\n \"stars\",\n \"topics\",\n \"trending\",\n]);\n\n/**\n * Reduce any GitHub URL down to a canonical `https://github.com/<owner>/<repo>`\n * form, or return null when the URL isn't a repo at all (gist host, reserved\n * first segment, missing repo segment, malformed). Strips `.git` suffix,\n * lowercases the host, drops query/hash and any path beyond owner+repo.\n */\nexport function normalizeRepoUrl(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const u = new URL(url);\n const host = u.hostname.toLowerCase();\n if (host !== \"github.com\" && host !== \"www.github.com\") return null;\n const segs = u.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segs.length < 2) return null;\n const [user, repo] = segs;\n if (!user || !repo) return null;\n if (GITHUB_RESERVED_PATHS.has(user.toLowerCase())) return null;\n const cleanRepo = repo.replace(/\\.git$/i, \"\");\n return `https://github.com/${user}/${cleanRepo}`;\n } catch {\n return null;\n }\n}\n","import { resolveIcp } from \"./_filter.ts\";\nimport { isoDateNDaysAgo, searchTopicRepos } from \"./_github-search.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport {\n processRepoCandidate,\n type RepoCandidate,\n type RepoPipelineCtx,\n} from \"./_repo-pipeline.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\nimport { looksLikeNoiseRepo, normalizeRepoUrl } from \"./_repo-utils.ts\";\n\n/**\n * GitHub-Topic-driven finder. Discovers repos via the (free) GitHub Search\n * API filtered by `topic:<slug>`, then hands each candidate to the shared\n * `_repo-pipeline.ts` (snippet-ICP → webRead → extract → resolveContact →\n * enqueue).\n *\n * Why topic search vs the retired combo-search approach: topic-tagged repos\n * are pre-curated by maintainers self-tagging — much higher signal-per-fetch\n * than `site:github.com \"X\" \"Y\"` Google scraping. The Search API also\n * returns actual repo metadata (description, stars, topics) instead of\n * misleading issue/PR snippets that judged the parent repo on text it didn't\n * own. And discovery is free (no webSearch spend per query).\n */\nconst SOURCE = \"find:github-topics\";\n\nexport interface GitHubTopicsFinderOpts extends RunOpts {\n /** GitHub topic slugs, e.g. [\"llm-agents\", \"ai-agent\", \"langchain\"]. */\n topics: string[];\n /** Canonical vendor names handed to the LLM extract for stack detection. */\n vendors: string[];\n /**\n * Subset of `vendors` the founder competes with head-on. When a candidate's\n * detected stack includes one of these, it routes to the competitor-switch\n * play (\"switch from X\") instead of stack-consolidation. Empty = every\n * candidate is stack-consolidation. Matched case-insensitively.\n */\n directCompetitors?: string[];\n /** YOUR EDGE line handed to the email prompt. */\n yourEdge: string;\n /** Min stars filter. Default 5 (drops abandoned/empty repos). */\n minStars?: number;\n /** Repos pushed within this window. Default 90 days. */\n maxAgeDays?: number;\n /** Max in-flight candidate workers. Default 3. */\n concurrency?: number;\n /** Min vendors detected in README. Default 2. */\n minVendors?: number;\n /** Last-resort deepResearchPerson fallback. Default true. */\n useDeepResearch?: boolean;\n}\n\nexport async function runGitHubTopicsFinder(opts: GitHubTopicsFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const minStars = Math.max(0, opts.minStars ?? 5);\n const maxAgeDays = Math.max(1, opts.maxAgeDays ?? 90);\n const minVendors = Math.max(1, opts.minVendors ?? 2);\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n const useDeepResearch = opts.useDeepResearch !== false;\n const icp = resolveIcp(opts.icpOverride);\n\n const result: FinderResult = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n if (!opts.topics || opts.topics.length === 0) {\n result.halted = \"unconfigured: set `topics` in /queue → github-topics → edit config\";\n return result;\n }\n if (!opts.vendors || opts.vendors.length === 0) {\n result.halted = \"unconfigured: set `vendors` in /queue → github-topics → edit config\";\n return result;\n }\n if (!opts.yourEdge || opts.yourEdge.trim().length === 0) {\n result.halted = \"unconfigured: set `yourEdge` in /queue → github-topics → edit config\";\n return result;\n }\n\n // Discovery: one Search API call per topic. Free, but we cap at limit*2 hits\n // BETWEEN topics so an unconfigured `topics: [...]` of length 20 doesn't\n // dispatch 20 search calls when the first three already over-fill the buffer.\n // The cap is per-iteration, not per-hit — a single noisy topic returning all\n // perPage=50 results still feeds them all into the pool. That's intentional:\n // searchTopicRepos already pre-filters with `stars:>=N pushed:>=Y`, so even\n // 50 hits from one topic is healthy signal. `searchTopicRepos` swallows its\n // own errors (returns []), so no try/catch is needed here.\n const pushedSinceIso = isoDateNDaysAgo(maxAgeDays);\n const seen = new Set<string>();\n const hits: RepoCandidate[] = [];\n for (const topic of opts.topics) {\n if (hits.length >= limit * 2) break;\n const repos = await searchTopicRepos({\n topic,\n minStars,\n pushedSinceIso,\n perPage: 50,\n });\n for (const repo of repos) {\n const url = normalizeRepoUrl(repo.url);\n if (!url || seen.has(url)) continue;\n if (looksLikeNoiseRepo(url)) continue;\n seen.add(url);\n hits.push({\n url,\n title: repo.fullName,\n description: repo.description ?? \"\",\n vendors: [],\n topics: repo.topics,\n });\n }\n }\n result.candidates = hits.length;\n\n const ctx: RepoPipelineCtx = {\n icp,\n vocab: opts.vendors,\n directCompetitors: opts.directCompetitors ?? [],\n yourEdge: opts.yourEdge,\n minVendors,\n useDeepResearch,\n result,\n halted: { value: false },\n limit,\n maxCostUsd: opts.maxCostUsd,\n sourceTag: SOURCE,\n notesPrefix: \"github-topic\",\n dryRun: opts.dryRun,\n };\n\n await parallelMap(hits, concurrency, (hit) => processRepoCandidate(hit, ctx));\n return result;\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { githubHeaders } from \"./_github-search.ts\";\n\nexport interface Stargazer {\n login: string;\n userUrl: string;\n /** ISO timestamp of the star (from the star+json media type). */\n starredAt: string;\n}\n\n/** Parse one `application/vnd.github.star+json` stargazer row. */\nfunction parseStarRow(raw: unknown): Stargazer | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const starredAt = typeof r[\"starred_at\"] === \"string\" ? (r[\"starred_at\"] as string) : null;\n const user = r[\"user\"];\n if (!starredAt || !user || typeof user !== \"object\") return null;\n const u = user as Record<string, unknown>;\n const login = typeof u[\"login\"] === \"string\" ? (u[\"login\"] as string) : null;\n if (!login) return null;\n const userUrl = typeof u[\"html_url\"] === \"string\" ? (u[\"html_url\"] as string) : null;\n return { login, userUrl: userUrl ?? `https://github.com/${login}`, starredAt };\n}\n\n/** Read the `page=N>; rel=\"last\"` page number from a GitHub `Link` header. */\nfunction parseLastPage(link: string | null): number {\n if (!link) return 1;\n const m = link.match(/[?&]page=(\\d+)>;\\s*rel=\"last\"/);\n return m ? Math.max(1, Number.parseInt(m[1] ?? \"1\", 10)) : 1;\n}\n\nexport interface StargazersResult {\n stargazers: Stargazer[];\n /**\n * Most-recent `starred_at` seen across the fetched pages, regardless of the\n * recency window. Lets the caller explain \"newest was Nd ago\" when the window\n * turns up empty (vs an outright failure). Null when nothing parsed.\n */\n newestSeen: string | null;\n /** Set on a non-2xx / network / parse failure — distinguishes a real error\n * (e.g. rate limit) from an honest \"no recent stars\". */\n error?: string;\n}\n\n/**\n * Recent stargazers of a public repo. GitHub returns stargazers oldest-first,\n * so the newest stars live on the LAST page — we read the `Link: rel=\"last\"`\n * page number, then page backward (newest → older), collecting stars with\n * `starredAt >= sinceIso` and stopping as soon as a page has none fresh (every\n * earlier page is older still) or `maxPages` is hit. Fault-tolerant like\n * `searchTopicRepos`: returns `{ stargazers, error }` on any non-2xx / network\n * / parse failure so the caller logs + continues. A non-2xx on a BACKWARD page\n * surfaces as `error` (it usually means a rate-limit mid-walk) rather than\n * silently masquerading as \"no recent stars\".\n *\n * Requires `GITHUB_TOKEN` for any real volume (5,000 req/hr core); without it\n * GitHub rate-limits hard at 60/hr — which a backward walk through a big repo\n * hits fast.\n */\nexport async function recentStargazers(\n repo: string,\n opts: { sinceIso: string; maxPages?: number },\n): Promise<StargazersResult> {\n const maxPages = Math.max(1, opts.maxPages ?? 20);\n // star+json gives us `starred_at`; otherwise it's a bare user list.\n const headers = { ...githubHeaders(), Accept: \"application/vnd.github.star+json\" };\n const base = `https://api.github.com/repos/${repo}/stargazers?per_page=100`;\n\n const out: Stargazer[] = [];\n let newestSeen: string | null = null;\n const dedupe = (): Stargazer[] => {\n const seen = new Set<string>();\n return out.filter((s) => {\n const key = s.login.toLowerCase();\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n };\n\n try {\n // Page 1 (oldest) is fetched first only to read the Link header; its rows\n // are reused if the backward walk reaches page 1.\n const firstRes = await fetch(`${base}&page=1`, { headers });\n if (!firstRes.ok) {\n logEvent(\"github.stargazers\", { repo, ok: false, status: firstRes.status }, \"warn\");\n return { stargazers: [], newestSeen: null, error: `status ${firstRes.status}` };\n }\n const lastPage = parseLastPage(firstRes.headers.get(\"link\"));\n const page1Rows = ((await firstRes.json()) as unknown[]) ?? [];\n\n let pagesFetched = 1;\n for (let page = lastPage; page >= 1 && pagesFetched <= maxPages; page--) {\n let rows: unknown[];\n if (page === 1) {\n rows = page1Rows;\n } else {\n const res = await fetch(`${base}&page=${page}`, { headers });\n pagesFetched++;\n if (!res.ok) {\n // Surface it — a 403/429 mid-walk is almost always the rate limit,\n // NOT \"no recent stars\". Return what we have so far + the error.\n logEvent(\n \"github.stargazers\",\n { repo, ok: false, status: res.status, page },\n \"warn\",\n );\n return {\n stargazers: dedupe(),\n newestSeen,\n error: `status ${res.status} on page ${page}`,\n };\n }\n rows = ((await res.json()) as unknown[]) ?? [];\n }\n const parsed = rows.map(parseStarRow).filter((s): s is Stargazer => s !== null);\n // Track the newest star regardless of the window (parsed is one page;\n // the last page holds the newest, so this captures the global max).\n for (const s of parsed) {\n if (!newestSeen || s.starredAt > newestSeen) newestSeen = s.starredAt;\n }\n const fresh = parsed.filter((s) => s.starredAt >= opts.sinceIso);\n out.push(...fresh);\n // Pages get older as `page` decreases; once a page yields zero fresh\n // stars, every earlier page is older too — stop.\n if (fresh.length === 0) break;\n }\n\n const stargazers = dedupe();\n logEvent(\"github.stargazers\", {\n repo,\n ok: true,\n fresh: stargazers.length,\n last_page: lastPage,\n pages_fetched: pagesFetched,\n });\n return { stargazers, newestSeen };\n } catch (err) {\n const message = ((err as Error).message ?? \"\").slice(0, 120);\n logEvent(\"github.stargazers\", { repo, ok: false, message_120: message }, \"warn\");\n return { stargazers: dedupe(), newestSeen, error: message };\n }\n}\n","import { getLedger, logEvent, parallelMap } from \"@oneshot-gtm/core\";\nimport type { CompetitorSwitchTarget, RepoInterestTarget } from \"@oneshot-gtm/plays\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { fetchGitHubUser, fetchTopRepos } from \"./_github-user.ts\";\nimport { recentStargazers, type Stargazer } from \"./_stargazers.ts\";\nimport type { FinderResult, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"github-stars\";\n\n/** A repo the founder watches, tagged with how it relates to their product. */\nexport interface RepoWatch {\n /** \"owner/name\". */\n repo: string;\n /** `competitor` → competitor-switch pitch; `adjacent` → repo-interest pitch. */\n rel: \"competitor\" | \"adjacent\";\n /** Display label (e.g. \"Apollo\"); falls back to the repo's name segment. */\n label?: string;\n /**\n * Optional, per-repo: one true line about why THIS repo is notable plus how\n * your offer bridges to it respectfully. Surfaced to the email as a\n * shared-taste nod (never flattery) that also shapes the offer's framing —\n * e.g. a privacy-first repo's edge leads the pitch with control/auditability\n * rather than \"we do it for you\". Adjacent repos only (→ repo-interest).\n */\n repoEdge?: string;\n}\n\nexport interface GitHubStarsFinderOpts extends RunOpts {\n repos: RepoWatch[];\n /** Fed to whichever play a candidate routes to. */\n yourEdge: string;\n /** Only consider stars within the last N days. Default 30. */\n sinceDays?: number;\n /** Per-candidate pipelines in flight at once. Default 3. */\n concurrency?: number;\n}\n\ntype Candidate = Stargazer & {\n repo: string;\n rel: RepoWatch[\"rel\"];\n label: string;\n repoEdge?: string;\n};\n\nfunction deriveLabel(repo: string): string {\n return repo.split(\"/\")[1]?.trim() || repo;\n}\n\nfunction sourceFor(repo: string): string {\n return `find:${PLAY_NAME}:${repo}`;\n}\n\n/**\n * github-stars finder: recent stargazers of watched repos → prospects, routed\n * by each repo's founder-tagged `rel`. A `competitor` repo's stargazers become\n * `competitor-switch` rows (\"why teams switch from X\"); an `adjacent` repo's\n * become `repo-interest` rows (\"you're into X — my product helps\"). Reuses the\n * shared finder stack (ICP filter, findEmail/verify/enrich, dedupe, prescreen)\n * and the soft-cap loop pattern from show-hn / accelerator-batch.\n */\nexport async function runGitHubStarsFinder(opts: GitHubStarsFinderOpts): Promise<FinderResult> {\n const limit = opts.limit ?? 25;\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n const sinceDays = opts.sinceDays ?? 30;\n const sinceIso = new Date(Date.now() - sinceDays * 24 * 3600 * 1000).toISOString();\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n\n const result: FinderResult = {\n source: `find:${PLAY_NAME}`,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n };\n\n logEvent(\"finder.start\", {\n name: PLAY_NAME,\n repos: opts.repos.length,\n since_days: sinceDays,\n limit,\n });\n\n // Step 1: gather recent stargazers across all watched repos, tagged with the\n // repo's rel/label. Per-repo errors log + continue (handled in _stargazers).\n const tagged: Candidate[] = [];\n let firstError: string | null = null;\n let newestSeen: string | null = null; // newest star across all repos, ignoring the window\n for (const w of opts.repos) {\n const {\n stargazers,\n error,\n newestSeen: repoNewest,\n } = await recentStargazers(w.repo, {\n sinceIso,\n });\n if (error && !firstError) firstError = `${w.repo}: ${error}`;\n if (repoNewest && (!newestSeen || repoNewest > newestSeen)) newestSeen = repoNewest;\n const label = w.label?.trim() || deriveLabel(w.repo);\n const repoEdge = w.repoEdge?.trim();\n for (const s of stargazers) {\n tagged.push({ ...s, repo: w.repo, rel: w.rel, label, ...(repoEdge ? { repoEdge } : {}) });\n }\n }\n\n // Cross-repo dedupe by login (someone starring two watched repos surfaces once).\n const seen = new Set<string>();\n const candidates = tagged.filter((c) => {\n const k = c.login.toLowerCase();\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n result.candidates = candidates.length;\n\n if (candidates.length === 0) {\n // Distinguish a fetch failure (usually the unauth rate limit) from an honest\n // empty window, and when empty, say how stale the newest star is so the\n // founder knows to widen `sinceDays` rather than wonder what broke.\n if (firstError) {\n result.halted = `github fetch failed (${firstError}) — set GITHUB_TOKEN for higher rate limits`;\n } else if (newestSeen) {\n const ageDays = Math.floor((Date.now() - new Date(newestSeen).getTime()) / 86_400_000);\n result.halted = `no stars in last ${sinceDays}d — newest was ${ageDays}d ago; widen sinceDays`;\n } else {\n result.halted = \"no stargazers found (check repo names / GITHUB_TOKEN)\";\n }\n logEvent(\"finder.done\", { name: PLAY_NAME, candidates: 0, halted: result.halted });\n return result;\n }\n\n // Step 2: per-candidate pipeline (parallel, soft-capped on limit + cost).\n let halted = false;\n await parallelMap(candidates, concurrency, async (c) => {\n if (halted) return;\n if (result.enqueued >= limit) {\n halted = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n halted = true;\n return;\n }\n\n const playName = c.rel === \"competitor\" ? \"competitor-switch\" : \"repo-interest\";\n const dedupeKey = `${PLAY_NAME}:${c.repo}:${c.login}`;\n if (ledger.isQueueDuplicate(playName, dedupeKey)) {\n result.droppedDuplicate++;\n return;\n }\n\n const user = await fetchGitHubUser(c.login);\n if (!user) {\n result.droppedEnrichment++;\n return;\n }\n const fullName = user.name ?? c.login;\n\n // ICP filter on the resolved profile + the repo they starred.\n const filter = await icpFilter({\n icp,\n candidate: {\n title: fullName,\n url: c.userUrl,\n summary: [user.company, `starred ${c.repo}`].filter(Boolean).join(\" · \"),\n },\n });\n if (filter.match === null) {\n // Transient classifier failure (Anthropic 5xx, timeout, rate limit) —\n // drop without persisting. A rejection would burn the dedupeKey for\n // every future watch tick since isQueueDuplicate ignores status.\n result.droppedEnrichment++;\n return;\n }\n if (!filter.match) {\n result.droppedIcp++;\n // Persist the auto-rejection for review (skipped on dry-run previews).\n if (!opts.dryRun) {\n ledger.enqueueTarget({\n playName,\n payload: { name: fullName, company: user.company ?? \"\", repo: c.repo },\n dedupeKey,\n source: sourceFor(c.repo),\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${filter.reason}`,\n });\n }\n return;\n }\n\n // Dry-run preview: count ICP-passers, skip the paid enrich + enqueue.\n if (opts.dryRun) {\n result.enqueued++;\n return;\n }\n\n // Resolve + verify an email: public profile email first, else findEmail via\n // the blog domain (gated by the prescreen). No domain + no public email → drop.\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName,\n knownEmail: user.email,\n companyDomain: user.blogDomain,\n isDuplicate: (email) => isDuplicate({ playName, dedupeKey, prospectEmail: email }),\n });\n result.costUsd += contact.costUsd;\n if (!contact.ok) {\n if (contact.reason === \"duplicate\") result.droppedDuplicate++;\n else result.droppedEnrichment++;\n return;\n }\n const email = contact.email;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: PLAY_NAME,\n });\n result.costUsd += enr.costUsd;\n\n const company = user.company?.trim() || \"(unknown)\";\n const repoUrl = `https://github.com/${c.repo}`;\n const contactExtras = {\n ...(enr.linkedinUrl ? { linkedinUrl: enr.linkedinUrl } : {}),\n ...(enr.phone ? { phone: enr.phone } : {}),\n };\n\n // repo-interest is a peer-builder pitch — what the candidate ships gives\n // the LLM concrete shared-taste evidence. competitor-switch is a head-on\n // pitch where the starred repo IS the signal; candidate's own repos add\n // noise, so we only fetch for the repo-interest branch.\n const candidateRepos =\n c.rel === \"competitor\" ? undefined : ((await fetchTopRepos(c.login)) ?? undefined);\n\n const target: CompetitorSwitchTarget | RepoInterestTarget =\n c.rel === \"competitor\"\n ? {\n name: fullName,\n email,\n company,\n competitor: c.label,\n evidenceUrl: repoUrl,\n // Pre-supplied evidence → competitor-switch skips its browser scrape\n // (a code page has no \"pain points\" to extract).\n evidenceText: `Starred ${c.label}'s repo (${c.repo}) on ${c.starredAt.slice(0, 10)} — actively evaluating tools in this space.`,\n yourEdge: opts.yourEdge,\n ...contactExtras,\n }\n : {\n name: fullName,\n email,\n company,\n repo: c.repo,\n repoLabel: c.label,\n yourEdge: opts.yourEdge,\n ...(c.repoEdge ? { repoEdge: c.repoEdge } : {}),\n evidenceUrl: repoUrl,\n candidateLogin: c.login,\n ...(candidateRepos ? { candidateRepos } : {}),\n ...contactExtras,\n };\n\n const id = ledger.enqueueTarget({\n playName,\n payload: target,\n dedupeKey,\n source: sourceFor(c.repo),\n notes: filter.reason,\n });\n if (id != null) result.enqueued++;\n else result.droppedDuplicate++;\n });\n\n logEvent(\"finder.done\", {\n name: PLAY_NAME,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return result;\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport type { LumaPublicAttendee } from \"./_types.ts\";\n\n/**\n * Optional auth path for the luma-events finder. When the founder has pasted\n * their `luma.auth-session-key` cookie into `LUMA_SESSION_COOKIE`, this helper\n * tries to fetch the FULL guest list from Luma's internal API.\n *\n * KNOWN LIMIT (verified live, 2026-06): the guest-list endpoint is HOST-ONLY —\n * a valid cookie on someone else's event returns 403 \"You don't have access to\n * this event\", even when the host shows \"Who's Coming\". So this path only adds\n * coverage for events the FOUNDER hosts. (It also expects the `evt-` api_id\n * where the caller passes the URL slug, which 404s first — moot for cold\n * discovery given the 403.) Cold-discovery contact data comes from the public\n * `api.lu.ma/url` event JSON instead — see `fetchEventDetails` in\n * `_luma-discover.ts`.\n *\n * The endpoint is undocumented and may change. We try two URL shapes (the\n * `/admin/` and the bare variant) and fall back gracefully to null on any\n * 4xx / shape drift / network blip. The caller (luma.ts) treats null as\n * \"stay in public-only mode for this event\" — no crash.\n *\n * TOS posture: this is the founder's own cookie hitting pages they could\n * read in a browser. The cookie value is never logged (only its presence is)\n * and never persisted by this codebase beyond the `~/.oneshot-gtm/.env` file\n * the founder owns.\n */\n\nconst ENDPOINTS = [\n \"https://api.lu.ma/event/admin/get-guest-list\",\n \"https://api.lu.ma/event/get-guest-list\",\n];\n\nconst COOKIE_NAME = \"luma.auth-session-key\";\nconst REQUEST_TIMEOUT_MS = 10_000;\nconst USER_AGENT =\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 oneshot-gtm/luma-events\";\nconst MAX_AUTHED_ATTENDEES = 30;\n\ninterface RawGuest {\n user?: {\n name?: string | null;\n avatar_url?: string | null;\n website?: string | null;\n linkedin_handle?: string | null;\n twitter_handle?: string | null;\n bio?: string | null;\n bio_short?: string | null;\n url?: string | null;\n } | null;\n name?: string | null;\n // Surface \"Approved Going\" / \"Speaker\" / etc when present at this level.\n registration_status?: string | null;\n role?: string | null;\n}\n\ninterface RawResponse {\n entries?: RawGuest[];\n guests?: RawGuest[];\n}\n\nexport function buildLinkedinUrl(input: string | null | undefined): string | null {\n if (!input) return null;\n const v = String(input).trim();\n if (v.length === 0) return null;\n if (/^https?:\\/\\//i.test(v)) return v;\n // Handle no-scheme variants like \"linkedin.com/in/sarah\", \"www.linkedin.com/in/sarah\",\n // and the bare-path shape the lu.ma API returns (\"/in/sarah\" or \"in/sarah\"):\n // strip those prefixes so we don't end up with \"/in//in/sarah\".\n const cleaned = v\n .replace(/^(?:www\\.)?linkedin\\.com\\/in\\//i, \"\")\n .replace(/^\\/?in\\//i, \"\")\n .replace(/^\\//, \"\");\n return `https://www.linkedin.com/in/${cleaned.replace(/^@/, \"\")}`;\n}\n\nexport function buildTwitterUrl(input: string | null | undefined): string | null {\n if (!input) return null;\n const v = String(input).trim();\n if (v.length === 0) return null;\n if (/^https?:\\/\\//i.test(v)) return v;\n const cleaned = v.replace(/^(?:www\\.)?(?:twitter\\.com|x\\.com)\\//i, \"\");\n return `https://x.com/${cleaned.replace(/^@/, \"\")}`;\n}\n\nfunction projectRawGuest(raw: RawGuest): LumaPublicAttendee | null {\n const u = raw.user ?? null;\n const name = (u?.name ?? raw.name ?? \"\").trim();\n if (!name) return null;\n const profileUrl = u?.url ?? null;\n return {\n name,\n profileUrl,\n websiteUrl: u?.website ?? null,\n linkedinUrl: buildLinkedinUrl(u?.linkedin_handle),\n twitterUrl: buildTwitterUrl(u?.twitter_handle),\n bio: u?.bio_short ?? u?.bio ?? null,\n role: raw.role ?? raw.registration_status ?? null,\n };\n}\n\n/**\n * Fetch a Luma event's full guest list using the founder's session cookie.\n * Returns null on any failure mode (no cookie, expired cookie, 4xx, shape\n * drift, network blip) — the caller falls back to public-only mode.\n */\nexport async function fetchAuthedGuestList(\n eventSlug: string,\n cookie: string,\n): Promise<LumaPublicAttendee[] | null> {\n if (!cookie || !eventSlug) return null;\n const cookieHeader = `${COOKIE_NAME}=${cookie}`;\n\n let lastStatus: number | null = null;\n for (const base of ENDPOINTS) {\n const url = `${base}?event_api_id=${encodeURIComponent(eventSlug)}`;\n let res: Response;\n try {\n res = await fetch(url, {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Cookie: cookieHeader,\n \"User-Agent\": USER_AGENT,\n },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.auth_fetch\",\n slug: eventSlug,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n // Network blip — try the next endpoint, but don't keep retrying\n // forever. The next iteration's fetch will either work or this catch\n // will fire again and exit the loop after the URL list is exhausted.\n lastStatus = null;\n continue;\n }\n lastStatus = res.status;\n if (res.status === 404) continue; // try next endpoint shape\n if (res.status === 401 || res.status === 403) {\n logEvent(\"luma-events.auth_unauthorized\", { slug: eventSlug, status: res.status }, \"warn\");\n return null;\n }\n if (!res.ok) {\n logEvent(\n \"error.swallowed\",\n { kind: \"luma-events.auth_status\", slug: eventSlug, status: res.status },\n \"warn\",\n );\n return null;\n }\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n logEvent(\"error.swallowed\", { kind: \"luma-events.auth_parse\", slug: eventSlug }, \"warn\");\n return null;\n }\n const parsed = body as RawResponse | null;\n const raws = parsed?.entries ?? parsed?.guests ?? null;\n if (!Array.isArray(raws)) {\n logEvent(\"error.swallowed\", { kind: \"luma-events.auth_shape\", slug: eventSlug }, \"warn\");\n return null;\n }\n const projected: LumaPublicAttendee[] = [];\n for (const raw of raws) {\n const a = projectRawGuest(raw);\n if (a) projected.push(a);\n if (projected.length >= MAX_AUTHED_ATTENDEES) break;\n }\n return projected;\n }\n // Both endpoints returned 404 — likely wrong slug or API path drift.\n if (lastStatus === 404) {\n logEvent(\n \"error.swallowed\",\n { kind: \"luma-events.auth_404_all_endpoints\", slug: eventSlug },\n \"warn\",\n );\n }\n return null;\n}\n\n/**\n * Merge public (LLM-extracted) attendees with auth'd attendees. Dedupe key is\n * the lowercased trimmed name; matches the per-event dedupe key used downstream.\n *\n * Per-field union: when both sides have an entry for the same name, the auth\n * value wins on conflict, but public values fill in any nulls. This handles\n * the realistic case where the auth API doesn't surface a field (`linkedinUrl`\n * = null) that the LLM caught from a visible attendee card.\n */\nexport function mergeAttendees(\n publicList: LumaPublicAttendee[],\n authedList: LumaPublicAttendee[],\n): LumaPublicAttendee[] {\n const byName = new Map<string, LumaPublicAttendee>();\n for (const a of publicList) {\n const key = a.name.trim().toLowerCase();\n if (key.length === 0) continue;\n byName.set(key, a);\n }\n for (const auth of authedList) {\n const key = auth.name.trim().toLowerCase();\n if (key.length === 0) continue;\n const pub = byName.get(key);\n if (!pub) {\n byName.set(key, auth);\n continue;\n }\n byName.set(key, {\n name: auth.name, // canonical capitalization from the auth source\n profileUrl: auth.profileUrl ?? pub.profileUrl,\n websiteUrl: auth.websiteUrl ?? pub.websiteUrl,\n linkedinUrl: auth.linkedinUrl ?? pub.linkedinUrl,\n twitterUrl: auth.twitterUrl ?? pub.twitterUrl,\n bio: auth.bio ?? pub.bio,\n role: auth.role ?? pub.role,\n });\n }\n return [...byName.values()];\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { buildLinkedinUrl, buildTwitterUrl } from \"./_luma-auth.ts\";\nimport type { LumaPublicAttendee } from \"./_types.ts\";\n\n/**\n * Primary discovery path for the luma-events finder. Instead of webSearch\n * (which surfaces search-INDEXED — i.e. older/established — Luma pages and so\n * reliably returns past events), this fetches Luma's per-city page directly.\n *\n * `https://luma.com/<city-slug>` server-renders the city's UPCOMING events into\n * a single `<script id=\"__NEXT_DATA__\">` JSON blob. The city is selected by\n * slug (not by caller IP, unlike the `api.lu.ma/discover` endpoint), so it\n * works from any server. Each event carries a real `start_at` ISO timestamp,\n * so the caller can window-filter BEFORE spending on per-event reads.\n *\n * Undocumented surface: parsing is shape-tolerant (recursive collect) and every\n * failure mode returns null so the caller falls back to webSearch. Same posture\n * as `_luma-auth.ts`: spoofed UA, short timeout, graceful null, never throws.\n */\n\nconst REQUEST_TIMEOUT_MS = 10_000;\nconst USER_AGENT =\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 oneshot-gtm/luma-events\";\nconst NEXT_DATA_OPEN = '<script id=\"__NEXT_DATA__\" type=\"application/json\">';\nconst NEXT_DATA_CLOSE = \"</script>\";\nconst MAX_EVENTS = 60;\nconst MAX_NODES = 200_000; // walk guard for the (large) embedded JSON tree\n\nexport interface LumaDiscoveredEvent {\n /** Event url slug → `https://luma.com/<slug>`. */\n slug: string;\n name: string;\n startAtIso: string;\n city: string | null;\n}\n\n/**\n * Luma city slugs are irregular (\"sf\", not \"sanfrancisco\"), so map the common\n * hubs explicitly. An unmapped city returns null and the caller falls back to\n * webSearch. Trivially extensible — add the city-name → slug pair.\n */\nconst CITY_SLUGS: Record<string, string> = {\n \"san francisco\": \"sf\",\n sf: \"sf\",\n \"sf bay area\": \"sf\",\n \"bay area\": \"sf\",\n \"new york\": \"nyc\",\n \"new york city\": \"nyc\",\n nyc: \"nyc\",\n \"los angeles\": \"la\",\n la: \"la\",\n london: \"london\",\n paris: \"paris\",\n berlin: \"berlin\",\n amsterdam: \"amsterdam\",\n singapore: \"singapore\",\n tokyo: \"tokyo\",\n bangalore: \"bangalore\",\n bengaluru: \"bangalore\",\n toronto: \"toronto\",\n seattle: \"seattle\",\n austin: \"austin\",\n boston: \"boston\",\n miami: \"miami\",\n chicago: \"chicago\",\n denver: \"denver\",\n washington: \"dc\",\n \"washington dc\": \"dc\",\n dc: \"dc\",\n};\n\n/** Resolve a founder-supplied city name to a Luma local-page slug, or null. */\nexport function cityToSlug(city: string): string | null {\n return CITY_SLUGS[city.trim().toLowerCase()] ?? null;\n}\n\n/**\n * Coarse, free topic gate on an event name. Returns true if the name contains\n * any word-boundary token derived from the founder's `topics` — so \"AI Agents\n * Hackathon\" passes for topic \"AI agents\" but \"Evening Yoga\" doesn't. Word\n * boundaries avoid substring false-hits (e.g. \"ai\" inside \"Maizie\"). Returns\n * true when `topics` is empty (no gate). Lenient by design: it only skips an\n * LLM relevance call on obvious non-matches; the event-level icpFilter is the\n * authority for everything that passes.\n */\n// Light de-pluralization so a topic \"AI agents\" matches an event \"… Agent …\".\nfunction stemWord(w: string): string {\n return w.length > 3 && w.endsWith(\"s\") ? w.slice(0, -1) : w;\n}\nfunction topicTokens(s: string): string[] {\n return s\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((w) => w.length >= 2)\n .map(stemWord);\n}\n\nexport function eventNameMatchesTopics(name: string, topics: string[]): boolean {\n const tokens = new Set(topics.flatMap(topicTokens));\n if (tokens.size === 0) return true; // no topics configured → no gate\n const words = new Set(topicTokens(name));\n for (const tok of tokens) {\n if (words.has(tok)) return true;\n }\n return false;\n}\n\n/** Slice the `__NEXT_DATA__` JSON out of the page HTML and parse it. */\nfunction parseNextData(html: string): unknown | null {\n const open = html.indexOf(NEXT_DATA_OPEN);\n if (open === -1) return null;\n const from = open + NEXT_DATA_OPEN.length;\n const end = html.indexOf(NEXT_DATA_CLOSE, from);\n if (end === -1) return null;\n try {\n return JSON.parse(html.slice(from, end));\n } catch {\n return null;\n }\n}\n\n/**\n * Recursively collect event-shaped objects from the parsed tree. Matching on\n * the event's own fields (api_id `evt-`, plus a slug `url`, `name`, `start_at`)\n * rather than a fixed nesting path keeps this resilient to Next.js shape drift.\n * Deduped by api_id; the wrapper `entry` objects lack `start_at` so they're\n * skipped.\n */\nfunction collectEvents(root: unknown): LumaDiscoveredEvent[] {\n const out: LumaDiscoveredEvent[] = [];\n const seen = new Set<string>();\n const stack: unknown[] = [root];\n let visited = 0;\n\n while (stack.length > 0 && visited < MAX_NODES) {\n const node = stack.pop();\n visited++;\n if (Array.isArray(node)) {\n for (const v of node) stack.push(v);\n continue;\n }\n if (!node || typeof node !== \"object\") continue;\n const o = node as Record<string, unknown>;\n\n const apiId = o[\"api_id\"];\n const url = o[\"url\"];\n const name = o[\"name\"];\n const startAt = o[\"start_at\"];\n if (\n typeof apiId === \"string\" &&\n apiId.startsWith(\"evt-\") &&\n typeof url === \"string\" &&\n url.length > 0 &&\n !url.includes(\"/\") && // the slug is bare; a full URL means this isn't the event node\n typeof name === \"string\" &&\n name.trim().length > 0 &&\n typeof startAt === \"string\" &&\n startAt.length > 0 &&\n !seen.has(apiId)\n ) {\n seen.add(apiId);\n const geo = o[\"geo_address_info\"];\n const city =\n geo &&\n typeof geo === \"object\" &&\n typeof (geo as Record<string, unknown>)[\"city\"] === \"string\"\n ? ((geo as Record<string, unknown>)[\"city\"] as string)\n : null;\n out.push({ slug: url, name: name.trim(), startAtIso: startAt, city });\n }\n\n for (const v of Object.values(o)) stack.push(v);\n }\n return out;\n}\n\n/**\n * Fetch a Luma city page and return its embedded events (all of them — the\n * caller applies the date window). Returns null on any failure (unknown slug,\n * non-2xx, no `__NEXT_DATA__`, parse error, network blip) so the caller falls\n * back to webSearch.\n */\nexport async function fetchCityEvents(citySlug: string): Promise<LumaDiscoveredEvent[] | null> {\n if (!citySlug) return null;\n let res: Response;\n try {\n res = await fetch(`https://luma.com/${encodeURIComponent(citySlug)}`, {\n method: \"GET\",\n headers: { Accept: \"text/html\", \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.discover_fetch\",\n slug: citySlug,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n if (!res.ok) {\n logEvent(\n \"error.swallowed\",\n { kind: \"luma-events.discover_status\", slug: citySlug, status: res.status },\n \"warn\",\n );\n return null;\n }\n let html: string;\n try {\n html = await res.text();\n } catch {\n return null;\n }\n const data = parseNextData(html);\n if (data == null) {\n logEvent(\n \"error.swallowed\",\n { kind: \"luma-events.discover_no_nextdata\", slug: citySlug },\n \"warn\",\n );\n return null;\n }\n return collectEvents(data).slice(0, MAX_EVENTS);\n}\n\n// Per-event structured details (api.lu.ma/url)\n\nconst MAX_DETAIL_ATTENDEES = 30;\n// Cap the raw description we keep off the api.lu.ma payload. Matches the\n// luma-event-extract prompt's ~500-char guidance so both discovery paths feed\n// the draft a comparably-sized blurb; the draft prompt slices defensively too.\nconst MAX_DETAIL_DESCRIPTION = 500;\n\nexport interface LumaEventDetails {\n eventTitle: string | null;\n eventDateIso: string | null;\n eventCity: string | null;\n /** Plain-text event description, capped at MAX_DETAIL_DESCRIPTION. Null when absent. */\n eventDescription: string | null;\n /** Hosts (role \"Host\", listed first) + featured guests (role \"Guest\"). */\n attendees: LumaPublicAttendee[];\n}\n\n/**\n * Flatten a Luma `description_mirror` (a ProseMirror/TipTap rich-text doc:\n * `{ type, content: [...] }`) to plain text by concatenating every `text` leaf.\n * Drops zero-width spaces Luma sprinkles in, then collapses whitespace so the\n * result is one clean line (the draft input block is newline-delimited).\n * Returns \"\" for anything that isn't a doc with text leaves.\n */\nfunction flattenProseMirror(node: unknown): string {\n const parts: string[] = [];\n const visit = (n: unknown): void => {\n if (Array.isArray(n)) {\n for (const v of n) visit(v);\n return;\n }\n if (!n || typeof n !== \"object\") return;\n const o = n as Record<string, unknown>;\n if (o[\"type\"] === \"text\" && typeof o[\"text\"] === \"string\") parts.push(o[\"text\"]);\n for (const v of Object.values(o)) visit(v);\n };\n visit(node);\n return parts.join(\" \").replace(/\\u200b/g, \"\").replace(/\\s+/g, \" \").trim();\n}\n\n/** Person shape shared by `hosts` and `featured_guests` in the /url payload. */\ninterface RawUrlPerson {\n name?: string | null;\n username?: string | null;\n website?: string | null;\n linkedin_handle?: string | null;\n twitter_handle?: string | null;\n bio_short?: string | null;\n}\n\nfunction projectUrlPerson(raw: RawUrlPerson, role: \"Host\" | \"Guest\"): LumaPublicAttendee | null {\n const name = (raw.name ?? \"\").trim();\n if (!name) return null;\n return {\n name,\n profileUrl: raw.username ? `https://luma.com/user/${raw.username}` : null,\n websiteUrl: raw.website ?? null,\n linkedinUrl: buildLinkedinUrl(raw.linkedin_handle),\n twitterUrl: buildTwitterUrl(raw.twitter_handle),\n bio: raw.bio_short ?? null,\n role,\n };\n}\n\n/**\n * Fetch one event's structured details from `api.lu.ma/url?url=<slug>` — the\n * same anonymous JSON the event page renders from. Unlike the webRead + LLM\n * extract (which only sees names in the rendered text), this carries each\n * person's `linkedin_handle` / `website`, which is exactly what the contact\n * resolution in Phase 3 needs. `hosts` is present even when the guest list is\n * hidden; `featured_guests` (~10) appears when the host shows \"Who's Coming\".\n * Returns null on any failure so the caller falls back to webRead + LLM.\n */\nexport async function fetchEventDetails(slug: string): Promise<LumaEventDetails | null> {\n if (!slug) return null;\n let res: Response;\n try {\n res = await fetch(`https://api.lu.ma/url?url=${encodeURIComponent(slug)}`, {\n method: \"GET\",\n headers: { Accept: \"application/json\", \"User-Agent\": USER_AGENT },\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.details_fetch\",\n slug,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n if (!res.ok) {\n logEvent(\n \"error.swallowed\",\n { kind: \"luma-events.details_status\", slug, status: res.status },\n \"warn\",\n );\n return null;\n }\n let data: unknown;\n try {\n data = await res.json();\n } catch {\n logEvent(\"error.swallowed\", { kind: \"luma-events.details_parse\", slug }, \"warn\");\n return null;\n }\n\n // Shape-tolerant walk: take the first event node (api_id `evt-` + start_at)\n // and the first non-empty `hosts` / `featured_guests` arrays anywhere in the\n // payload, rather than relying on a fixed nesting path.\n let eventTitle: string | null = null;\n let eventDateIso: string | null = null;\n let eventCity: string | null = null;\n let eventDescription: string | null = null;\n let hosts: RawUrlPerson[] | null = null;\n let guests: RawUrlPerson[] | null = null;\n const stack: unknown[] = [data];\n let visited = 0;\n while (stack.length > 0 && visited < MAX_NODES) {\n const node = stack.pop();\n visited++;\n if (Array.isArray(node)) {\n for (const v of node) stack.push(v);\n continue;\n }\n if (!node || typeof node !== \"object\") continue;\n const o = node as Record<string, unknown>;\n if (\n eventTitle == null &&\n typeof o[\"api_id\"] === \"string\" &&\n (o[\"api_id\"] as string).startsWith(\"evt-\") &&\n typeof o[\"start_at\"] === \"string\" &&\n typeof o[\"name\"] === \"string\"\n ) {\n eventTitle = (o[\"name\"] as string).trim() || null;\n eventDateIso = (o[\"start_at\"] as string) || null;\n const geo = o[\"geo_address_info\"];\n if (geo && typeof geo === \"object\") {\n const c = (geo as Record<string, unknown>)[\"city\"];\n if (typeof c === \"string\") eventCity = c;\n }\n }\n // The event blurb is NOT on the event node — it sits on the wrapping\n // `data` object as `description_mirror` (a ProseMirror doc). Capture the\n // first one found (the page's primary event; `data` is walked early), and\n // fall back to the calendar/category `description_short` / `description`\n // strings when an event has no body of its own.\n if (eventDescription == null) {\n const mirror = o[\"description_mirror\"];\n if (mirror && typeof mirror === \"object\") {\n const flat = flattenProseMirror(mirror);\n if (flat) eventDescription = flat.slice(0, MAX_DETAIL_DESCRIPTION);\n }\n }\n if (eventDescription == null) {\n for (const key of [\"description_short\", \"description\"]) {\n const v = o[key];\n if (typeof v === \"string\" && v.trim()) {\n eventDescription = v.trim().replace(/\\s+/g, \" \").slice(0, MAX_DETAIL_DESCRIPTION);\n break;\n }\n }\n }\n if (hosts == null && Array.isArray(o[\"hosts\"]) && o[\"hosts\"].length > 0) {\n hosts = o[\"hosts\"] as RawUrlPerson[];\n }\n if (guests == null && Array.isArray(o[\"featured_guests\"]) && o[\"featured_guests\"].length > 0) {\n guests = o[\"featured_guests\"] as RawUrlPerson[];\n }\n for (const v of Object.values(o)) stack.push(v);\n }\n\n // Hosts first (canonical name casing + the better targets), then guests;\n // dedupe by lowercased name (a host can also appear as a featured guest).\n const byName = new Map<string, LumaPublicAttendee>();\n for (const [list, role] of [\n [hosts ?? [], \"Host\"],\n [guests ?? [], \"Guest\"],\n ] as const) {\n for (const raw of list) {\n const a = projectUrlPerson(raw, role);\n if (!a) continue;\n const key = a.name.toLowerCase();\n if (!byName.has(key)) byName.set(key, a);\n if (byName.size >= MAX_DETAIL_ATTENDEES) break;\n }\n }\n\n const attendees = [...byName.values()];\n if (!eventTitle && attendees.length === 0) {\n logEvent(\"error.swallowed\", { kind: \"luma-events.details_shape\", slug }, \"warn\");\n return null;\n }\n return { eventTitle, eventDateIso, eventCity, eventDescription, attendees };\n}\n","import {\n enrichProfile,\n getLedger,\n logEvent,\n parallelMap,\n webRead,\n webSearch,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport type { LumaEventsTarget } from \"@oneshot-gtm/plays\";\nimport { isDuplicate, urlDomain } from \"./_dedupe.ts\";\nimport { resolveAndVerifyContact } from \"./_contact.ts\";\nimport { enrichVerifiedContact } from \"./_enrich.ts\";\nimport { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport { persistPending, registerPendingRetry } from \"./_pending.ts\";\nimport { fetchAuthedGuestList, mergeAttendees } from \"./_luma-auth.ts\";\nimport {\n cityToSlug,\n eventNameMatchesTopics,\n fetchCityEvents,\n fetchEventDetails,\n} from \"./_luma-discover.ts\";\nimport type { LumaEventExtract, LumaPublicAttendee, RunOpts } from \"./_types.ts\";\n\nconst PLAY_NAME = \"luma-events\";\nconst SOURCE = \"find:luma-events\";\n/** Cap per-event LLM extract input — Luma event pages are usually under 8k chars. */\nconst READ_MARKDOWN_SLICE = 12000;\n/** Sane upper bound — no event we care about has >30 public attendees. */\nconst MAX_ATTENDEES_PER_EVENT = 30;\n\nexport interface LumaFinderOpts extends RunOpts {\n /** Topic phrases to combine with cities (e.g. [\"AI\", \"founders\"]). REQUIRED via readiness gate. */\n topics?: string[];\n /** City names to scope each search (e.g. [\"San Francisco\", \"New York\"]). REQUIRED via readiness gate. */\n cities?: string[];\n /** Founder's one-line angle, threaded to the play. REQUIRED via readiness gate. */\n yourEdge?: string;\n /**\n * Forward-looking window in days. Events further out than this are dropped\n * (founder almost never wants to pitch a Q4 attendee in June).\n */\n sinceDays?: number;\n}\n\ninterface SearchHit {\n url: string;\n title: string;\n description: string;\n}\n\ninterface AttendeeWithEvent {\n attendee: LumaPublicAttendee;\n event: {\n url: string;\n title: string;\n dateIso: string;\n city: string;\n description: string;\n };\n}\n\n/**\n * Extract the single-segment slug from a Luma event URL. Returns null when\n * the URL isn't a single-event page. Used to address Luma's internal API\n * (`api.lu.ma/event/get-guest-list?event_api_id=<slug>`) when the founder\n * has set `LUMA_SESSION_COOKIE`.\n */\nexport function lumaEventSlug(url: string): string | null {\n try {\n const u = new URL(url);\n if (!/^(www\\.)?(luma\\.com|lu\\.ma)$/.test(u.hostname)) return null;\n const segments = u.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segments.length !== 1) return null;\n return segments[0] ?? null;\n } catch {\n return null;\n }\n}\n\nexport function looksLikeLumaEventUrl(url: string): boolean {\n // Accept luma.com/<slug> and lu.ma/<slug>. Reject calendar / category pages.\n try {\n const u = new URL(url);\n if (!/^(www\\.)?(luma\\.com|lu\\.ma)$/.test(u.hostname)) return false;\n // Calendar pages: ?k=c; category/city: ?k=t or ?k=p. Real events have no\n // `k` query param and a single-path-segment slug.\n if (u.searchParams.has(\"k\")) return false;\n const segments = u.pathname.split(\"/\").filter((s) => s.length > 0);\n if (segments.length !== 1) return false;\n // Reserved discovery paths.\n const reserved = new Set([\n \"discover\",\n \"home\",\n \"events\",\n \"calendars\",\n \"create\",\n \"login\",\n \"signup\",\n \"user\",\n ]);\n return !reserved.has(segments[0]!.toLowerCase());\n } catch {\n return false;\n }\n}\n\nconst MONTHS = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\n/**\n * Literal month-name tokens spanning [now, now + sinceDays] — e.g. \"June 2026\"\n * or \"June 2026 July 2026\" across a boundary. Appended to the discovery query\n * so search ranks upcoming Luma pages (which render the month) above stale\n * ones. A relative phrase like \"next 7 days\" is useless to an index that has\n * no notion of today; a literal month the event page actually shows is not.\n */\nfunction upcomingMonths(sinceDays: number): string {\n const start = new Date(Date.now());\n const end = new Date(Date.now() + sinceDays * 24 * 3600 * 1000);\n // Walk by month index (not by adding days) so a multi-month window names\n // EVERY month it spans — June+July+August, not just the two endpoints.\n const endIdx = end.getFullYear() * 12 + end.getMonth();\n const months: string[] = [];\n for (let y = start.getFullYear(), m = start.getMonth(); y * 12 + m <= endIdx; ) {\n months.push(`${MONTHS[m]!} ${y}`);\n if (++m > 11) {\n m = 0;\n y++;\n }\n }\n return months.join(\" \");\n}\n\nexport async function runLumaFinder(opts: LumaFinderOpts): Promise<{\n source: string;\n candidates: number;\n droppedIcp: number;\n droppedDuplicate: number;\n droppedEnrichment: number;\n enqueued: number;\n costUsd: number;\n halted?: string;\n}> {\n const limit = opts.limit ?? 25;\n const sinceDays = opts.sinceDays ?? 14;\n const topics = (opts.topics ?? []).filter((t) => t.trim().length > 0);\n const cities = (opts.cities ?? []).filter((c) => c.trim().length > 0);\n const yourEdge = (opts.yourEdge ?? \"\").trim();\n const icp = resolveIcp(opts.icpOverride);\n const ledger = getLedger();\n const extractSystem = loadPrompt(\"luma-event-extract\");\n // Optional v2 auth mode. When unset, public-only path runs as before.\n const sessionCookie = (process.env[\"LUMA_SESSION_COOKIE\"] ?? \"\").trim();\n if (!sessionCookie) {\n logEvent(\n \"luma-events.cookie_unset\",\n {\n hint: \"optional LUMA_SESSION_COOKIE only unlocks full guest lists for events YOU host; hosts + featured guests are pulled publicly regardless\",\n },\n \"info\",\n );\n }\n\n const result = {\n source: SOURCE,\n candidates: 0,\n droppedIcp: 0,\n droppedDuplicate: 0,\n droppedEnrichment: 0,\n enqueued: 0,\n costUsd: 0,\n halted: undefined as string | undefined,\n };\n\n // Phase 1: discover event URLs via webSearch over each (topic × city) pair.\n // Bias toward UPCOMING events: a search index has no notion of \"today\", so a\n // relative phrase (\"next 7 days\") doesn't work — but Luma event pages render\n // the literal month + year, so naming the month(s) the forward window spans\n // (plus \"upcoming\") ranks future pages above last quarter's. The date defense\n // after extract still enforces the exact window.\n const windowMonths = upcomingMonths(sinceDays);\n const seenUrls = new Set<string>();\n const hits: SearchHit[] = [];\n const cap = limit * 3;\n const windowStart = Date.now() - 24 * 3600 * 1000;\n const windowEnd = Date.now() + sinceDays * 24 * 3600 * 1000;\n\n const pushHit = (url: string, title: string, description: string): void => {\n const canonical = url.split(\"?\")[0]!.replace(/\\/$/, \"\");\n if (seenUrls.has(canonical)) return;\n seenUrls.add(canonical);\n hits.push({ url: canonical, title, description });\n };\n\n // webSearch fallback for a single city — used when the city isn't a mapped\n // Luma hub or its page can't be parsed. This path surfaces search-INDEXED\n // (older) pages, which is why the date defense downstream still matters.\n const webSearchCity = async (city: string): Promise<void> => {\n for (const topic of topics) {\n if (hits.length >= cap) return;\n const query = `site:luma.com \"${topic}\" \"${city}\" upcoming event ${windowMonths}`;\n try {\n const search = await webSearch(\n { query, maxResults: Math.min(10, limit) },\n { playName: PLAY_NAME, decisionContext: { source: \"finder\", topic, city } },\n );\n result.costUsd += search.result.cost ?? 0;\n for (const hit of search.result.results ?? []) {\n if (!hit.url) continue;\n // Gate on the ORIGINAL URL — `looksLikeLumaEventUrl` inspects the\n // query string (`?k=t` / `?k=c` mark Luma's category + calendar\n // pages); canonicalizing first would strip those markers.\n if (!looksLikeLumaEventUrl(hit.url)) continue;\n pushHit(hit.url, hit.title, hit.description);\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.webSearch\",\n topic,\n city,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n };\n\n // Discovery-first: Luma's per-city page (`luma.com/<slug>`) lists UPCOMING\n // events directly with real start_at timestamps — geo-robust and free (a\n // plain fetch, no SDK spend). Window-filter here so Phase 2 only pays to read\n // genuinely-upcoming events. Fall back to webSearch per city when the city\n // isn't a mapped hub, the page won't parse, or nothing lands in the window.\n for (const city of cities) {\n if (hits.length >= cap) break;\n const slug = cityToSlug(city);\n const discovered = slug ? await fetchCityEvents(slug) : null;\n if (discovered && discovered.length > 0) {\n let kept = 0;\n for (const ev of discovered) {\n if (hits.length >= cap) break;\n const ms = new Date(ev.startAtIso).getTime();\n if (!Number.isFinite(ms) || ms < windowStart || ms > windowEnd) continue;\n pushHit(`https://luma.com/${ev.slug}`, ev.name, \"\");\n kept++;\n }\n logEvent(\n \"luma-events.discover_ok\",\n { name: PLAY_NAME, city, slug, found: discovered.length, in_window: kept },\n \"info\",\n );\n if (kept > 0) continue;\n }\n await webSearchCity(city);\n }\n result.candidates = hits.length;\n\n // Event-level relevance criterion: one LLM call (below) weighs the founder's\n // ICP AND topics, on the event NAME, BEFORE any webRead — so we never pay to\n // read the dance-cardio / wine-tasting noise that city pages surface. This\n // replaces the old per-attendee ICP filter, which rejected even on-topic\n // attendees because Luma's public attendee data is too thin to judge.\n const relevanceCriteria = [\n icp,\n topics.length > 0 ? `Event must relate to: ${topics.join(\", \")}` : null,\n ]\n .filter(Boolean)\n .join(\". \");\n\n // Phase 2: topic/ICP gate → webRead + LLM extract per event, parallelized.\n // Each surviving event yields 0..N attendees; flatten into one work list.\n const concurrency = 3;\n const eventExtracts: Array<{ hit: SearchHit; extract: LumaEventExtract } | null> =\n await parallelMap(hits.slice(0, limit * 2), concurrency, async (hit) => {\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) return null;\n\n // Free keyword pre-filter: skip the LLM call for obvious off-topic names.\n if (topics.length > 0 && !eventNameMatchesTopics(hit.title, topics)) {\n logEvent(\"finder.skipped_off_topic\", { name: PLAY_NAME, url: hit.url, title: hit.title });\n return null;\n }\n // Event-level relevance gate (topic + ICP in one call), on the name only.\n if (relevanceCriteria) {\n const ev = await icpFilter({\n icp: relevanceCriteria,\n candidate: { title: hit.title, url: hit.url },\n });\n if (ev.match === null) return null; // transient classifier failure → drop, no persist\n if (!ev.match) {\n result.droppedIcp++;\n logEvent(\n \"finder.skipped_off_icp\",\n {\n name: PLAY_NAME,\n url: hit.url,\n title: hit.title,\n reason_120: ev.reason.slice(0, 120),\n },\n \"info\",\n );\n return null;\n }\n }\n\n try {\n // Structured-first: the anonymous `api.lu.ma/url` JSON carries the\n // event meta AND each host/featured-guest's linkedin/website — exactly\n // what contact resolution needs and what the rendered page (webRead +\n // LLM extract) loses, since attendee cards only render names as text.\n // Free, so it replaces the paid webRead+extract whenever it succeeds;\n // any failure falls through to the webRead path below.\n let extract: LumaEventExtract;\n const eventSlug = lumaEventSlug(hit.url);\n const details = eventSlug ? await fetchEventDetails(eventSlug) : null;\n if (details && details.eventTitle && details.attendees.length > 0) {\n extract = {\n eventTitle: details.eventTitle,\n eventDateIso: details.eventDateIso,\n eventCity: details.eventCity,\n eventDescription: details.eventDescription,\n eventHasPassed: false, // the date defense below is the authority\n publicAttendees: details.attendees,\n };\n logEvent(\n \"luma-events.details_ok\",\n {\n name: PLAY_NAME,\n url: hit.url,\n attendees: details.attendees.length,\n with_linkedin: details.attendees.filter((a) => a.linkedinUrl).length,\n },\n \"info\",\n );\n } else {\n const read = await webRead(\n { url: hit.url },\n {\n playName: PLAY_NAME,\n decisionContext: { source: \"finder\", eventUrl: hit.url },\n },\n );\n result.costUsd += read.result.cost ?? 0;\n const payload: Record<string, unknown> = {\n url: hit.url,\n title: hit.title,\n description: hit.description,\n markdown: (read.result.markdown ?? \"\").slice(0, READ_MARKDOWN_SLICE),\n };\n const llm = await complete({\n messages: [\n { role: \"system\", content: extractSystem },\n { role: \"user\", content: JSON.stringify(payload) },\n ],\n temperature: 0.1,\n maxTokens: 1500,\n });\n extract = parseLumaEventExtract(llm.content);\n }\n if (!extract.eventTitle) {\n logEvent(\"finder.skipped_non_event\", { name: PLAY_NAME, url: hit.url }, \"info\");\n return null;\n }\n if (extract.eventHasPassed) {\n logEvent(\n \"finder.skipped_past_event\",\n { name: PLAY_NAME, url: hit.url, eventTitle: extract.eventTitle },\n \"info\",\n );\n return null;\n }\n // Defense beyond LLM judgement: drop events with no parsable date OR\n // a date in the past. The play's date-humanizer needs a real ISO; an\n // empty `EVENT DATE` produces a worse hook than no email at all.\n if (!extract.eventDateIso) {\n logEvent(\n \"finder.skipped_no_event_date\",\n { name: PLAY_NAME, url: hit.url, eventTitle: extract.eventTitle },\n \"info\",\n );\n return null;\n }\n const eventMs = new Date(extract.eventDateIso).getTime();\n if (!Number.isFinite(eventMs) || eventMs < Date.now() - 24 * 3600 * 1000) {\n logEvent(\n \"finder.skipped_past_event\",\n {\n name: PLAY_NAME,\n url: hit.url,\n eventTitle: extract.eventTitle,\n eventDateIso: extract.eventDateIso,\n reason: \"date defense\",\n },\n \"info\",\n );\n return null;\n }\n // Forward-window cap: drop events that are too far out (founder rarely\n // wants to pitch a Q4 attendee in June). `sinceDays` is the cap.\n if (eventMs > Date.now() + sinceDays * 24 * 3600 * 1000) {\n logEvent(\n \"finder.skipped_too_far_out\",\n {\n name: PLAY_NAME,\n url: hit.url,\n eventTitle: extract.eventTitle,\n eventDateIso: extract.eventDateIso,\n sinceDays,\n },\n \"info\",\n );\n return null;\n }\n // v2 auth merge: when the founder's session cookie is set, fetch the\n // full guest list and merge it with the LLM-extracted public ones.\n // Auth wins on name collision (canonical source). Failures (no cookie,\n // expired, network blip, shape drift) return null — we keep the\n // public-only list. Gate the <2 check AFTER the merge so an\n // auth-unlocked event isn't dropped because the public extract was thin.\n if (sessionCookie) {\n const slug = lumaEventSlug(hit.url);\n if (slug) {\n const authed = await fetchAuthedGuestList(slug, sessionCookie);\n if (authed) {\n const before = extract.publicAttendees.length;\n const merged = mergeAttendees(extract.publicAttendees, authed);\n extract.publicAttendees = merged;\n logEvent(\n \"finder.luma_auth.success\",\n {\n name: PLAY_NAME,\n slug,\n public_count: before,\n authed_count: authed.length,\n merged_count: merged.length,\n },\n \"info\",\n );\n }\n }\n }\n if (extract.publicAttendees.length < 2) {\n logEvent(\n \"finder.skipped_no_public_guests\",\n { name: PLAY_NAME, url: hit.url, eventTitle: extract.eventTitle },\n \"info\",\n );\n return null;\n }\n return { hit, extract };\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.extract\",\n url: hit.url,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return null;\n }\n });\n\n const attendeesWork: AttendeeWithEvent[] = [];\n for (const item of eventExtracts) {\n if (!item) continue;\n const { hit, extract } = item;\n const eventCtx = {\n url: hit.url,\n title: extract.eventTitle ?? hit.title,\n dateIso: extract.eventDateIso ?? \"\",\n city: extract.eventCity ?? \"\",\n description: extract.eventDescription ?? \"\",\n };\n for (const attendee of extract.publicAttendees.slice(0, MAX_ATTENDEES_PER_EVENT)) {\n if (!attendee.name || attendee.name.trim().length === 0) continue;\n attendeesWork.push({ attendee, event: eventCtx });\n }\n }\n\n // Phase 3: per-attendee contact resolution, concurrency 3 to bound SDK\n // burst. Soft halt via boxed flag (same pattern as _repo-pipeline): workers\n // check at the top of each iteration but several may pass before any flips\n // it — enrichment SPEND can overshoot by up to (concurrency-1) attendees.\n // The enqueue count itself stays exact via the synchronous re-check right\n // before enqueueTarget below.\n const phase3Halted = { value: false };\n await parallelMap(attendeesWork, 3, async (work) => {\n if (phase3Halted.value) return;\n if (result.enqueued >= limit) {\n phase3Halted.value = true;\n return;\n }\n if (opts.maxCostUsd != null && result.costUsd >= opts.maxCostUsd) {\n result.halted = `max-cost cap (${opts.maxCostUsd})`;\n phase3Halted.value = true;\n return;\n }\n // Per-attendee dedupe key = event URL + name (lowercased). Same person across\n // two events is fine to re-pitch with the new event's hook.\n const dedupeKey = `${work.event.url}#${work.attendee.name.toLowerCase()}`;\n if (\n ledger.isQueueDuplicate(PLAY_NAME, dedupeKey) ||\n ledger.isPendingResolution(PLAY_NAME, dedupeKey)\n ) {\n result.droppedDuplicate++;\n return;\n }\n\n if (opts.dryRun) {\n result.enqueued++;\n return;\n }\n\n // No per-attendee ICP filter: the event cleared the event-level topic+ICP\n // gate in Phase 2, so its public attendees are in-scope. Shared\n // resolve→enqueue spine (also used by the outage retry handler).\n const outcome = await resolveAndEnqueueLumaAttendee(\n work,\n yourEdge,\n (c) => {\n result.costUsd += c;\n },\n () => result.enqueued >= limit,\n () => {\n result.enqueued++;\n },\n );\n if (outcome === \"enqueued\") {\n // counter already bumped synchronously via onEnqueued\n } else if (outcome === \"capped\") phase3Halted.value = true;\n else if (outcome === \"duplicate\") result.droppedDuplicate++;\n else if (outcome === \"platform-error\") {\n // Backend outage: the event ages out of \"upcoming\", so a re-scan can't\n // recover this attendee — persist for retry once the platform recovers.\n persistPending({ playName: PLAY_NAME, dedupeKey, source: SOURCE, raw: { work, yourEdge } });\n result.droppedEnrichment++;\n } else result.droppedEnrichment++;\n });\n\n return result;\n}\n\nexport function parseLumaEventExtract(raw: string): LumaEventExtract {\n const fallback: LumaEventExtract = {\n eventTitle: null,\n eventDateIso: null,\n eventCity: null,\n eventDescription: null,\n eventHasPassed: false,\n publicAttendees: [],\n };\n const parsed = tryParseJsonObject<LumaEventExtract>(raw, fallback);\n // Defensive: ensure publicAttendees is an array; LLM may return null.\n if (!Array.isArray(parsed.publicAttendees)) {\n return { ...parsed, publicAttendees: [] };\n }\n return parsed;\n}\n\n/**\n * Resolve + enrich + enqueue one Luma attendee (host or guest) for an\n * already-gated event. Shared by the live run loop and the outage retry\n * handler. Depends only on `work` (attendee + event) and `yourEdge`, so it's\n * fully re-runnable from a persisted candidate. `costSink` accumulates spend\n * into the caller's running total (a no-op on retry). Returns a coarse outcome\n * the caller maps to counters / pending persistence.\n */\nasync function resolveAndEnqueueLumaAttendee(\n work: AttendeeWithEvent,\n yourEdge: string,\n costSink: (c: number) => void,\n /** Checked synchronously right before enqueue so the run's enqueue cap stays\n * exact under concurrency (a worker may finish enrichment after the cap\n * filled). Omitted on retry (no cap). */\n capReached?: () => boolean,\n /** Called synchronously immediately after a successful enqueue — the cap\n * re-check, enqueue, and this increment run with no await between them, so\n * the queue cap is exact. Omitted on retry. */\n onEnqueued?: () => void,\n): Promise<\"enqueued\" | \"duplicate\" | \"dropped\" | \"platform-error\" | \"capped\"> {\n const ledger = getLedger();\n const dedupeKey = `${work.event.url}#${work.attendee.name.toLowerCase()}`;\n try {\n // Resolve a contact domain: linkedin first (richest, often surfaces the\n // email so we can skip findEmail), then website.\n let companyDomain: string | null = null;\n const resolvedLinkedinUrl: string | null = isLinkedInProfileUrl(work.attendee.linkedinUrl)\n ? work.attendee.linkedinUrl\n : null;\n let resolvedCompany: string | null = null;\n let surfacedEmail: string | null = null;\n\n if (resolvedLinkedinUrl) {\n try {\n const enr = await enrichProfile(\n { linkedinUrl: resolvedLinkedinUrl, name: work.attendee.name },\n {\n playName: PLAY_NAME,\n decisionContext: { source: \"finder\", linkedinUrl: resolvedLinkedinUrl },\n },\n );\n costSink(enr.result.cost ?? 0);\n const profile = enr.result.profile;\n companyDomain = profile?.company_domain ?? null;\n resolvedCompany = profile?.company ?? null;\n surfacedEmail = profile?.best_work_email ?? profile?.email ?? null;\n if (surfacedEmail) {\n try {\n ledger.setCachedEnrichment(\n surfacedEmail.trim().toLowerCase(),\n JSON.stringify(enr.result),\n );\n } catch {\n // cache write is best-effort\n }\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.enrichProfile\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n if (!companyDomain && work.attendee.websiteUrl) {\n companyDomain = urlDomain(work.attendee.websiteUrl);\n }\n\n const contact = await resolveAndVerifyContact({\n playName: PLAY_NAME,\n fullName: work.attendee.name,\n knownEmail: surfacedEmail,\n companyDomain,\n isDuplicate: (email) => isDuplicate({ playName: PLAY_NAME, dedupeKey, prospectEmail: email }),\n decisionContext: {\n source: \"finder\",\n attendeeName: work.attendee.name,\n companyDomain,\n eventUrl: work.event.url,\n },\n });\n costSink(contact.costUsd);\n if (!contact.ok) {\n if (contact.reason === \"no-domain\") {\n logEvent(\n \"finder.skipped_no_contact_domain\",\n { name: PLAY_NAME, attendeeName: work.attendee.name, eventUrl: work.event.url },\n \"info\",\n );\n }\n if (contact.reason === \"platform-error\") return \"platform-error\";\n if (contact.reason === \"duplicate\") return \"duplicate\";\n return \"dropped\";\n }\n const email = contact.email;\n\n const enr = await enrichVerifiedContact(email, {\n playName: PLAY_NAME,\n errKindPrefix: \"luma-events\",\n });\n costSink(enr.costUsd);\n const phone = enr.phone;\n let linkedinUrl: string | null = resolvedLinkedinUrl ?? enr.linkedinUrl;\n if (!linkedinUrl) {\n linkedinUrl = await findLinkedInUrl({\n fullName: work.attendee.name,\n disambiguators: [work.event.title, work.event.city].filter((s) => s.length > 0),\n accumCost: (c) => costSink(c ?? 0),\n errKindPrefix: \"luma-events\",\n });\n }\n\n const target: LumaEventsTarget = {\n name: work.attendee.name,\n email,\n ...(resolvedCompany ? { company: resolvedCompany } : {}),\n ...(work.attendee.bio || work.attendee.role\n ? { attendeeBio: work.attendee.bio ?? work.attendee.role ?? \"\" }\n : {}),\n ...(work.attendee.role ? { role: work.attendee.role } : {}),\n eventTitle: work.event.title,\n eventDate: work.event.dateIso,\n eventCity: work.event.city,\n eventUrl: work.event.url,\n ...(work.event.description ? { eventDescription: work.event.description } : {}),\n yourEdge,\n ...(linkedinUrl ? { linkedinUrl } : {}),\n ...(phone ? { phone } : {}),\n };\n // Synchronous cap re-check right before enqueue — no await between here and\n // the caller's enqueued++, so the queue cap is exact even under concurrency.\n if (capReached?.()) return \"capped\";\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source: SOURCE,\n notes: `${work.attendee.name} ${work.attendee.role === \"Host\" ? \"hosting\" : \"going to\"} ${work.event.title}`,\n });\n if (id != null) {\n onEnqueued?.(); // synchronous with the cap check above — keeps the cap exact\n return \"enqueued\";\n }\n return \"duplicate\";\n } catch (err) {\n // SDK calls swallow their own failures; this catches anything else (e.g. a\n // ledger hiccup). Treat as a genuine drop, not a retryable platform error,\n // so it can't loop forever on a real bug.\n logEvent(\n \"error.swallowed\",\n {\n kind: \"luma-events.attendee\",\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n return \"dropped\";\n }\n}\n\n// Outage retry: re-run the resolve→enqueue spine for a persisted attendee.\nregisterPendingRetry(PLAY_NAME, async (raw) => {\n const { work, yourEdge } = raw as { work: AttendeeWithEvent; yourEdge: string };\n const outcome = await resolveAndEnqueueLumaAttendee(work, yourEdge, () => {});\n return outcome === \"enqueued\" ? \"enqueued\" : outcome === \"platform-error\" ? \"platform-error\" : \"dropped\";\n});\n","import {\n getLedger,\n logEvent,\n safeParseJsonRecord,\n startRun,\n type TriggerRow,\n} from \"@oneshot-gtm/core\";\nimport { type CohortEntry, runAcceleratorBatchFinder } from \"./accelerator-batch.ts\";\nimport { deriveCohortLabel } from \"./_yc-oss-adapter.ts\";\nimport { runBreakupReviveFinder } from \"./breakup-revive.ts\";\nimport { type RepoWatch, runGitHubStarsFinder } from \"./github-stars.ts\";\nimport { runGitHubTopicsFinder } from \"./github-topics.ts\";\nimport { runHiringSignalFinder } from \"./hiring-signal.ts\";\nimport { runJobChangeFinder } from \"./job-change.ts\";\nimport { runLumaFinder } from \"./luma.ts\";\nimport { runPodcastGuestFinder } from \"./podcast-guest.ts\";\nimport { runPostFundingFinder } from \"./post-funding.ts\";\nimport { runShowHnFinder } from \"./show-hn.ts\";\nimport type { FinderResult } from \"./_types.ts\";\n\nexport interface TriggerSpec {\n name: string;\n defaultIntervalMs: number;\n defaultConfig: Record<string, unknown>;\n /** Whether new installs auto-enable this trigger. Default true. */\n enabledByDefault?: boolean;\n /**\n * Plain-English brief the strategist embeds in its system prompt. Describes\n * what the finder does + what each config key controls. Founder-facing too:\n * the chat references these so the founder doesn't have to know JSON shapes.\n */\n configBrief?: string;\n /**\n * Optional readiness gate. Return `{ready:false, reason}` when the stored\n * config lacks required founder-supplied inputs (e.g. github-topics without\n * `topics`). Consulted by the server's enable/run endpoints and by the watch\n * loop to avoid pointless runs. When absent, the trigger is always ready.\n */\n readiness?: (\n config: Record<string, unknown>,\n ) => { ready: true } | { ready: false; reason: string };\n run: (config: Record<string, unknown>) => Promise<FinderResult>;\n}\n\nexport type Readiness = { ready: true } | { ready: false; reason: string };\n\n/** Evaluate a spec's readiness fn (defaulting to ready when absent). */\nexport function checkReadiness(spec: TriggerSpec, config: Record<string, unknown>): Readiness {\n if (!spec.readiness) return { ready: true };\n try {\n return spec.readiness(config);\n } catch {\n // A throwing readiness fn shouldn't bring down the watch loop; treat as\n // not-ready with a generic reason so the founder sees *something*.\n return { ready: false, reason: \"readiness check threw\" };\n }\n}\n\nconst ONE_HOUR = 3600 * 1000;\n\n/**\n * Default cohort sweep for the `accelerator-batch` trigger. Covers seven\n * incubators × {latest, previous-latest} cohorts as of 2026-05-20. Only the\n * yc-* entries hit the structured yc-oss/api directory; the other 12 route\n * to the websearch + LLM-extract adapter and will have spotty per-cohort\n * recall (Neo is invite-only, SPC publishes thin web footprint, etc.).\n * Per-cohort failures are isolated — the run only halts when EVERY cohort\n * comes back empty.\n *\n * ROTATION: this list goes stale within ~3 months as YC announces W27,\n * Techstars rolls Fall 2026, etc. Founders should edit `cohorts[]` via the\n * trigger config UI on /queue when new batches announce.\n */\nconst DEFAULT_COHORTS: CohortEntry[] = [\n { cohort: \"yc-w26\", cohortLabel: \"YC W26\" },\n { cohort: \"yc-f25\", cohortLabel: \"YC F25\" },\n { cohort: \"techstars-spring-2026\", cohortLabel: \"Techstars Spring 2026\" },\n { cohort: \"techstars-fall-2025\", cohortLabel: \"Techstars Fall 2025\" },\n { cohort: \"antler-q1-2026\", cohortLabel: \"Antler Q1 2026\" },\n { cohort: \"antler-q4-2025\", cohortLabel: \"Antler Q4 2025\" },\n { cohort: \"500global-batch-38\", cohortLabel: \"500 Global Batch 38\" },\n { cohort: \"500global-batch-37\", cohortLabel: \"500 Global Batch 37\" },\n { cohort: \"ai-grant-cohort-5\", cohortLabel: \"AI Grant Cohort 5\" },\n { cohort: \"ai-grant-cohort-4\", cohortLabel: \"AI Grant Cohort 4\" },\n { cohort: \"spc-2026-1\", cohortLabel: \"South Park Commons F1 2026-1\" },\n { cohort: \"spc-2025-2\", cohortLabel: \"South Park Commons F1 2025-2\" },\n { cohort: \"neo-class-2026\", cohortLabel: \"Neo Class 2026\" },\n { cohort: \"neo-class-2025\", cohortLabel: \"Neo Class 2025\" },\n];\n\nexport const TRIGGERS: TriggerSpec[] = [\n {\n name: \"show-hn\",\n defaultIntervalMs: 6 * ONE_HOUR,\n defaultConfig: { sinceDays: 1, limit: 25, maxCostUsd: 5 },\n configBrief:\n \"Polls Hacker News Algolia for recent Show HN posts, ICP-filters them, enriches founder contact, and enqueues them for review. Config: `sinceDays` (lookback window, default 1), `limit` (max kept, default 25), `maxCostUsd` (per-run spend cap). Defaults work for most ICPs — bump sinceDays to 7+ if your ICP is niche enough that daily volume is thin.\",\n run: (cfg) =>\n runShowHnFinder({\n dryRun: false,\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 1,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"accelerator-batch\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n // Default sweep: every known incubator × {latest, previous-latest} cohorts.\n // Founders can trim or edit the list in /queue → trigger config; per-cohort\n // failures don't halt the run, so spotty incubators (Neo, SPC) coexist\n // with high-recall ones (YC, Techstars) in one trigger fire.\n defaultConfig: {\n cohorts: DEFAULT_COHORTS,\n limit: 25,\n maxCostUsd: 15,\n },\n configBrief:\n \"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.\",\n readiness: (cfg) => {\n const cohorts = Array.isArray(cfg[\"cohorts\"]) ? cfg[\"cohorts\"] : null;\n const legacyCohort =\n typeof cfg[\"cohort\"] === \"string\" ? (cfg[\"cohort\"] as string).trim() : \"\";\n if ((!cohorts || cohorts.length === 0) && legacyCohort.length === 0) {\n return {\n ready: false,\n reason: \"set `cohorts[]` (or legacy `cohort`)\",\n };\n }\n const senderCohort =\n typeof cfg[\"senderCohort\"] === \"string\" ? (cfg[\"senderCohort\"] as string).trim() : \"\";\n if (senderCohort.length === 0) {\n return {\n ready: false,\n reason: \"set `senderCohort` (your own cohort tag, e.g. yc-w23)\",\n };\n }\n return { ready: true };\n },\n run: (cfg) => {\n // Multi-cohort path: new `cohorts` array wins. Filter to well-formed\n // entries so a single malformed row doesn't kill the run.\n const cohortsRaw = Array.isArray(cfg[\"cohorts\"]) ? (cfg[\"cohorts\"] as unknown[]) : [];\n const cohorts: CohortEntry[] = cohortsRaw\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const e = entry as Record<string, unknown>;\n const cohort = typeof e[\"cohort\"] === \"string\" ? e[\"cohort\"].trim() : \"\";\n if (cohort.length === 0) return null;\n const labelRaw =\n typeof e[\"cohortLabel\"] === \"string\" ? (e[\"cohortLabel\"] as string).trim() : \"\";\n const cohortLabel = labelRaw.length > 0 ? labelRaw : deriveCohortLabel(cohort);\n return { cohort, cohortLabel };\n })\n .filter((e): e is CohortEntry => e !== null);\n\n // Legacy single-cohort path: only used when `cohorts` is empty/missing.\n const legacyCohort = typeof cfg[\"cohort\"] === \"string\" ? (cfg[\"cohort\"] as string) : \"\";\n const legacyLabel =\n typeof cfg[\"cohortLabel\"] === \"string\" ? (cfg[\"cohortLabel\"] as string) : \"\";\n\n return runAcceleratorBatchFinder({\n dryRun: false,\n ...(cohorts.length > 0 ? { cohorts } : {}),\n ...(cohorts.length === 0 && legacyCohort.trim().length > 0\n ? { cohort: legacyCohort, cohortLabel: legacyLabel }\n : {}),\n ...(cfg[\"adapter\"] === \"yc-oss\" || cfg[\"adapter\"] === \"websearch\"\n ? { adapter: cfg[\"adapter\"] as \"yc-oss\" | \"websearch\" }\n : {}),\n // Sender cohort (+ offer) stamped onto every enqueued row so the play\n // drafts inline without a run-level value. Readiness gates senderCohort.\n ...(typeof cfg[\"senderCohort\"] === \"string\" && cfg[\"senderCohort\"].trim().length > 0\n ? { senderCohort: (cfg[\"senderCohort\"] as string).trim() }\n : {}),\n ...(typeof cfg[\"freeForCohortOffer\"] === \"string\" &&\n cfg[\"freeForCohortOffer\"].trim().length > 0\n ? { freeForCohortOffer: (cfg[\"freeForCohortOffer\"] as string).trim() }\n : {}),\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 15,\n });\n },\n },\n {\n name: \"post-funding-auto\",\n defaultIntervalMs: 12 * ONE_HOUR,\n defaultConfig: {\n autoRounds: [\"Seed\", \"Series A\"],\n autoSinceDays: 7,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Auto-discovers funding announcements via webSearch, extracts company + founder, ICP-filters. Config: `autoRounds` (e.g. ['Seed','Series A','Series B'] — match what your ICP actually buys at), `autoIndustry` (optional industry hint to bias the search query — derive from the ICP), `autoSinceDays` (lookback, default 7), `limit`, `maxCostUsd`. Tune autoRounds to skip stages that won't buy yet.\",\n run: (cfg) =>\n runPostFundingFinder({\n dryRun: false,\n auto: true,\n autoRounds: (cfg[\"autoRounds\"] as string[]) ?? [\"Seed\", \"Series A\"],\n ...(typeof cfg[\"autoIndustry\"] === \"string\"\n ? { autoIndustry: cfg[\"autoIndustry\"] as string }\n : {}),\n autoSinceDays: (cfg[\"autoSinceDays\"] as number) ?? 7,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n // Opt-in: these finders need founder-supplied personas/roles/podcasts to be\n // useful, so they ship disabled. Enable from /queue → Triggers.\n {\n name: \"job-change\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n personas: [\"VP Engineering\", \"Head of Growth\", \"Director of Product\", \"Chief of Staff\"],\n sinceDays: 14,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Searches for 'joined X as Y' job-change announcements, ICP-filters, enriches the new email. Config: `personas` (the roles whose JOB CHANGE represents a buying moment for THIS product — not generic 'VP Eng' unless that's actually who buys; e.g. 'Head of AI', 'Founding Engineer' for AI-tooling ICPs), `companies` (optional whitelist of companies to bias toward), `sinceDays` (lookback, default 14), `limit`, `maxCostUsd`. Strong personas matter more than long lists.\",\n run: (cfg) =>\n runJobChangeFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"personas\"]) ? { personas: cfg[\"personas\"] as string[] } : {}),\n ...(Array.isArray(cfg[\"companies\"]) ? { companies: cfg[\"companies\"] as string[] } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 14,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"hiring-signal\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n roles: [\"Staff Engineer\", \"ML Engineer\", \"Solutions Engineer\"],\n sinceDays: 14,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"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.\",\n readiness: (cfg) => {\n const claim = typeof cfg[\"yourClaim\"] === \"string\" ? (cfg[\"yourClaim\"] as string).trim() : \"\";\n return claim.length > 0\n ? { ready: true }\n : { ready: false, reason: \"set `yourClaim` (your one-line pitch)\" };\n },\n run: (cfg) =>\n runHiringSignalFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"roles\"]) ? { roles: cfg[\"roles\"] as string[] } : {}),\n ...(Array.isArray(cfg[\"companies\"]) ? { companies: cfg[\"companies\"] as string[] } : {}),\n ...(typeof cfg[\"yourClaim\"] === \"string\" ? { yourClaim: cfg[\"yourClaim\"] as string } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 14,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n name: \"podcast-guest\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n podcasts: [\"Latent Space\", \"Lenny's Podcast\", \"20VC\", \"Acquired\", \"Invest Like the Best\"],\n sinceDays: 21,\n skipRead: false,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Discovers recent podcast guests, ICP-filters, enriches their email. Config: `podcasts` (shows whose guest demographic overlaps with the ICP — replace defaults with shows the founder's actual buyer listens to), `sinceDays` (default 21), `skipRead` (skip per-episode webRead for cheaper but less accurate runs), `limit`, `maxCostUsd`. Podcast list is the leverage — narrow + on-target beats broad.\",\n run: (cfg) =>\n runPodcastGuestFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"podcasts\"]) ? { podcasts: cfg[\"podcasts\"] as string[] } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 21,\n skipRead: cfg[\"skipRead\"] === true,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n // Luma upcoming-event hosts + featured guests. Discovery reads Luma's\n // per-city pages (genuinely upcoming; webSearch fallback for unmapped\n // cities); each event passes a keyword + LLM topic/ICP gate before any\n // paid read; attendees come structured (with linkedin/website) from\n // Luma's public event JSON. Contact via LinkedIn enrichProfile or\n // website domain, then the standard findEmail chain.\n name: \"luma-events\",\n defaultIntervalMs: 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n topics: [\"AI\", \"founders\"] as string[],\n cities: [\"San Francisco\", \"New York\"] as string[],\n sinceDays: 14,\n yourEdge: \"\",\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Discovers upcoming Luma events from Luma's per-city pages, gates each event on the founder's topics + ICP (a free keyword pre-filter, then one LLM relevance call on the event name) BEFORE any paid read, then pitches the event's hosts + featured guests — Luma's public event JSON carries their LinkedIn/website, so contact resolution lands. Coverage per event: the hosts (always public) + up to ~10 featured guests when the organizer shows 'Who's Coming'. Each row is tagged Host or Guest and the email is drafted role-aware. Config: `topics` (phrases whose words must appear in / relate to the event name — e.g. ['AI agents', 'MCP']; they gate events, not search queries), `cities` (major hubs work best — San Francisco, New York, LA, London, etc. map to Luma city pages; other cities fall back to webSearch), `yourEdge` (one-line angle on why your product helps event-going people, REQUIRED), `sinceDays` (forward-looking window in days — events further out than this are dropped), `limit`, `maxCostUsd`. STRATEGIST DUTY: align topics to your ICP's actual gathering spots (AI hackers ≠ growth marketers) and include the vocabulary event names actually use (e.g. 'agents', 'hackathon', 'MCP').\",\n readiness: (cfg) => {\n const topics = Array.isArray(cfg[\"topics\"]) ? cfg[\"topics\"] : null;\n if (!topics || topics.filter((t) => typeof t === \"string\" && t.trim()).length === 0) {\n return { ready: false, reason: \"set `topics` (e.g. ['AI','founders'])\" };\n }\n const cities = Array.isArray(cfg[\"cities\"]) ? cfg[\"cities\"] : null;\n if (!cities || cities.filter((c) => typeof c === \"string\" && c.trim()).length === 0) {\n return { ready: false, reason: \"set `cities` (e.g. ['San Francisco'])\" };\n }\n const edge = cfg[\"yourEdge\"];\n if (typeof edge !== \"string\" || edge.trim().length === 0) {\n return { ready: false, reason: \"set `yourEdge` — one-line pitch for event attendees\" };\n }\n return { ready: true };\n },\n run: (cfg) =>\n runLumaFinder({\n dryRun: false,\n ...(Array.isArray(cfg[\"topics\"])\n ? {\n topics: (cfg[\"topics\"] as unknown[]).filter(\n (t): t is string => typeof t === \"string\",\n ),\n }\n : {}),\n ...(Array.isArray(cfg[\"cities\"])\n ? {\n cities: (cfg[\"cities\"] as unknown[]).filter(\n (c): c is string => typeof c === \"string\",\n ),\n }\n : {}),\n ...(typeof cfg[\"yourEdge\"] === \"string\" ? { yourEdge: cfg[\"yourEdge\"] as string } : {}),\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 14,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n }),\n },\n {\n // GitHub-Topic-driven repo finder. Discovers via the (free) GitHub Search\n // API filtered by `topic:<slug>` — topic-tagged repos are pre-curated by\n // maintainers self-tagging, much higher signal-per-fetch than the\n // retired combo-search approach. Feeds stack-consolidation (vendor-\n // sprawl pitch) by default, or competitor-switch when a detected vendor\n // is on `directCompetitors`. Config-driven — the founder supplies topics\n // + vendors + edge via /queue; ships empty so nothing fires until configured.\n name: \"github-topics\",\n defaultIntervalMs: 12 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n topics: [] as string[],\n vendors: [] as string[],\n directCompetitors: [] as string[],\n yourEdge: \"\",\n minStars: 5,\n maxAgeDays: 90,\n minVendors: 1,\n concurrency: 3,\n useDeepResearch: true,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Discovers repos via GitHub Topic pages (`topic:<slug>` queries on the GitHub Search API), then scans each candidate's package.json / pyproject.toml / requirements.txt / .env.example via the GitHub Contents API to detect which API vendors the repo actually uses. Routes each candidate to one of two motion plays: stack-consolidation (default — pitch collapsing the vendor sprawl into one SDK) or competitor-switch (when a detected vendor is on `directCompetitors` — a head-on 'switch from X' pitch). Required config: `topics` (GitHub topic slugs the founder's ICP overlaps with — lowercase, hyphenated, EXACT GitHub-canonical form; singular vs plural matters), `vendors` (the founder's competitive landscape — the API vendors they aim to replace), `yourEdge` (one-sentence pitch handed to the email). Optional `directCompetitors`: a subset of `vendors` the founder competes with head-on (same canonical spelling, matched case-insensitively); a candidate using one routes to competitor-switch instead of stack-consolidation. Empty by default, so every candidate is stack-consolidation until set. VOCAB SEMANTICS: each `vendors` string is substring-matched (case-insensitive) against manifest deps + env-var keys — so `twilio` matches `twilio`, `twilio-node`, `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is NO hardcoded vendor list; oneshot-gtm is a generic founder tool and competitive vocabularies vary entirely by founder. STRATEGIST DUTY: when you (the strategist) have enough context about the founder's product/ICP, proactively propose BOTH `topics` AND `vendors` via apply-config — topics are GitHub category slugs aligned to ICP; vendors are the API competitors the founder replaces. The founder shouldn't have to enumerate either by hand. Other config: `minStars` (filter, default 5), `maxAgeDays` (default 90), `minVendors` (gate: how many distinct vocab vendors must match in a candidate's manifests; default 1), `concurrency` (in-flight workers; default 3), `useDeepResearch` (default true), `limit`, `maxCostUsd`.\",\n readiness: (cfg) => {\n const topics = cfg[\"topics\"];\n if (!Array.isArray(topics) || topics.length === 0) {\n return {\n ready: false,\n reason: \"set `topics` (one or more GitHub topic slugs, e.g. 'llm-agents')\",\n };\n }\n const vendors = cfg[\"vendors\"];\n if (!Array.isArray(vendors) || vendors.length === 0) {\n return {\n ready: false,\n reason: \"set `vendors` — your competitive landscape (ask the strategist to propose one)\",\n };\n }\n const edge = cfg[\"yourEdge\"];\n if (typeof edge !== \"string\" || edge.trim().length === 0) {\n return {\n ready: false,\n reason: \"set `yourEdge` — one-sentence consolidation pitch\",\n };\n }\n return { ready: true };\n },\n run: (cfg) => {\n const topics = Array.isArray(cfg[\"topics\"])\n ? (cfg[\"topics\"] as unknown[]).filter((t): t is string => typeof t === \"string\")\n : [];\n const vendors = Array.isArray(cfg[\"vendors\"])\n ? (cfg[\"vendors\"] as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n const directCompetitors = Array.isArray(cfg[\"directCompetitors\"])\n ? (cfg[\"directCompetitors\"] as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n const yourEdge = typeof cfg[\"yourEdge\"] === \"string\" ? cfg[\"yourEdge\"] : \"\";\n return runGitHubTopicsFinder({\n dryRun: false,\n topics,\n vendors,\n directCompetitors,\n yourEdge,\n minStars: (cfg[\"minStars\"] as number) ?? 5,\n maxAgeDays: (cfg[\"maxAgeDays\"] as number) ?? 90,\n minVendors: (cfg[\"minVendors\"] as number) ?? 2,\n concurrency: (cfg[\"concurrency\"] as number) ?? 3,\n useDeepResearch: cfg[\"useDeepResearch\"] !== false,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n });\n },\n },\n {\n name: \"github-stars\",\n defaultIntervalMs: 12 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: {\n repos: [] as Array<{ repo: string; rel: string; label?: string; repoEdge?: string }>,\n yourEdge: \"\",\n sinceDays: 30,\n concurrency: 3,\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n 'Finds recent stargazers of repos you watch and turns them into prospects. Config: `repos` (array of `{repo:\"owner/name\", rel:\"competitor\"|\"adjacent\", label?, repoEdge?}` — tag a repo `competitor` to pitch a switch (→ competitor-switch) or `adjacent` for a complementary intro (→ repo-interest); `label` is the human name, else derived from the repo; `repoEdge` is an OPTIONAL per-repo line on why THAT repo is notable + the respectful bridge to your offer, used by repo-interest as a shared-taste nod that also shapes the pitch — e.g. a privacy-first repo leads with control/auditability, not \"we do it for you\"), `yourEdge` (one-line pitch fed to whichever play, REQUIRED), `sinceDays` (recency window, default 30), `limit`, `maxCostUsd`. Needs `GITHUB_TOKEN` for any volume. STRATEGIST DUTY: pick repos your buyers\\' current tools live in; tag the ones you replace as `competitor`, the rest `adjacent`; give each adjacent repo a `repoEdge` so the intro nods to why they chose THAT tool.',\n readiness: (cfg) => {\n const repos = Array.isArray(cfg[\"repos\"]) ? cfg[\"repos\"] : [];\n const valid = repos.filter((r) => {\n if (!r || typeof r !== \"object\") return false;\n const e = r as Record<string, unknown>;\n return (\n typeof e[\"repo\"] === \"string\" &&\n e[\"repo\"].trim().length > 0 &&\n (e[\"rel\"] === \"competitor\" || e[\"rel\"] === \"adjacent\")\n );\n });\n if (valid.length === 0) {\n return {\n ready: false,\n reason: \"set `repos` (each `{repo, rel:'competitor'|'adjacent'}`)\",\n };\n }\n const edge = cfg[\"yourEdge\"];\n if (typeof edge !== \"string\" || edge.trim().length === 0) {\n return { ready: false, reason: \"set `yourEdge` — your one-line pitch\" };\n }\n return { ready: true };\n },\n run: (cfg) => {\n const repos: RepoWatch[] = (Array.isArray(cfg[\"repos\"]) ? cfg[\"repos\"] : [])\n .map((r): RepoWatch | null => {\n if (!r || typeof r !== \"object\") return null;\n const e = r as Record<string, unknown>;\n const repo = typeof e[\"repo\"] === \"string\" ? e[\"repo\"].trim() : \"\";\n const rel = e[\"rel\"];\n if (repo.length === 0 || (rel !== \"competitor\" && rel !== \"adjacent\")) return null;\n const label = typeof e[\"label\"] === \"string\" ? e[\"label\"].trim() : \"\";\n const repoEdge = typeof e[\"repoEdge\"] === \"string\" ? e[\"repoEdge\"].trim() : \"\";\n const watch: RepoWatch = { repo, rel };\n if (label) watch.label = label;\n if (repoEdge) watch.repoEdge = repoEdge;\n return watch;\n })\n .filter((r): r is RepoWatch => r !== null);\n return runGitHubStarsFinder({\n dryRun: false,\n repos,\n yourEdge: typeof cfg[\"yourEdge\"] === \"string\" ? cfg[\"yourEdge\"] : \"\",\n sinceDays: (cfg[\"sinceDays\"] as number) ?? 30,\n concurrency: (cfg[\"concurrency\"] as number) ?? 3,\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\n });\n },\n },\n {\n // Ledger-only finder; no OneShot/LLM spend. Opt-in so it doesn't surprise\n // founders on fresh installs where the ledger is mostly empty.\n name: \"breakup-revive\",\n defaultIntervalMs: 7 * 24 * ONE_HOUR,\n enabledByDefault: false,\n defaultConfig: { minDays: 60, maxDays: 90, limit: 25 },\n configBrief:\n \"Scans the founder's local prospect ledger for cold leads (no reply, marketable) within the day window and re-enqueues them for a pattern-interrupt revive. No agent/LLM spend (ledger-only). Config: `minDays` / `maxDays` (the cold-window — defaults 60-90), `limit`. Only enable when the founder has been sending for ≥2 months — empty ledger = no revives.\",\n run: async (cfg) =>\n runBreakupReviveFinder({\n dryRun: false,\n minDays: (cfg[\"minDays\"] as number) ?? 60,\n maxDays: (cfg[\"maxDays\"] as number) ?? 90,\n limit: (cfg[\"limit\"] as number) ?? 25,\n }),\n },\n];\n\n/**\n * Resolve the active interval for a trigger: stored config_json may override\n * the registry's defaultIntervalMs via `intervalMs`. This keeps the JSON-config\n * editor in /queue meaningful — bumping it from 24h → 6h actually changes the\n * watch loop's cadence.\n */\nexport function effectiveIntervalMs(\n spec: TriggerSpec,\n config: Record<string, unknown> | null,\n): number {\n const override = config?.[\"intervalMs\"];\n if (typeof override === \"number\" && Number.isFinite(override) && override >= 60_000) {\n return Math.floor(override);\n }\n return spec.defaultIntervalMs;\n}\n\nexport interface TriggerRunOutcome {\n name: string;\n fired: boolean;\n result?: FinderResult;\n error?: string;\n /** ms until this trigger is next due */\n nextDueInMs: number;\n}\n\n/**\n * Maximum age before an in-flight `running_started_at` is considered a\n * killed-by-restart zombie and swept by `sweepStaleRunningTriggers`.\n *\n * Real finder runtimes are dominated by the per-candidate pipeline (icpFilter\n * LLM + findEmail + verifyEmail, occasionally + webRead + deepResearchPerson).\n * github-topics with concurrency=3 typically completes 25 candidates in\n * 5-15 min; the deepResearchPerson tier (2-5 min async per call) sets the\n * realistic upper bound when many candidates fall into the hard-recovery bucket.\n *\n * 4h is set with generous headroom so a genuinely-running finder is never\n * mistakenly classified as zombie. If a run actually exceeds this, the\n * sweep marks it killed and `markTriggerRunning` lets a follow-up click\n * re-claim — bounded duplicate spend is preferable to the permanently-\n * stuck 409 state.\n */\nexport const MAX_RUN_AGE_MS = 4 * 60 * 60 * 1000;\n\n/**\n * Truth of \"is this trigger running\" lives in the ledger\n * (`triggers.running_started_at`). Survives server restart so the UI shows\n * accurate state across `bun --watch` re-execs and OS reboots.\n *\n * The freshness gate (`< MAX_RUN_AGE_MS`) hides stale rows that the boot\n * sweep hasn't cleaned up yet — defense in depth so we never report \"still\n * running\" for a row that's older than any real run could be.\n */\n/**\n * Pure helper extracted so the freshness gate is unit-testable without\n * mocking the ledger. Returns the parsed start-epoch when the iso\n * timestamp is valid AND fresh (within MAX_RUN_AGE_MS of `now`); null\n * otherwise.\n *\n * `nowMs` is injected so tests can drive time without faking Date.\n */\nexport function freshRunningStartedAtMs(\n iso: string | null | undefined,\n nowMs: number,\n): number | null {\n if (!iso) return null;\n const startedMs = new Date(iso).getTime();\n if (!Number.isFinite(startedMs)) return null;\n if (nowMs - startedMs > MAX_RUN_AGE_MS) return null;\n return startedMs;\n}\n\nexport function isTriggerRunning(name: string): boolean {\n return getTriggerRunningSince(name) !== null;\n}\n\nexport function getTriggerRunningSince(name: string): number | null {\n return freshRunningStartedAtMs(getLedger().getTrigger(name)?.running_started_at, Date.now());\n}\n\n/**\n * Stored config with corruption fallback. A bare JSON.parse here used to let\n * one corrupt config_json row throw out of runDueTriggers' loop and stall\n * every trigger until the row was fixed by hand; now the trigger runs on its\n * defaults with a warning instead.\n */\nexport function storedTriggerConfig(\n stored: TriggerRow | null,\n spec: TriggerSpec,\n): Record<string, unknown> {\n if (!stored?.config_json) return spec.defaultConfig;\n const parsed = safeParseJsonRecord(stored.config_json);\n if (parsed == null) {\n logEvent(\"trigger.config.corrupt\", { name: spec.name }, \"warn\");\n return spec.defaultConfig;\n }\n return parsed;\n}\n\n/**\n * Fire-and-forget wrapper around `runTriggerNow`: returns immediately after\n * marking the trigger as running in the ledger; the actual finder work runs\n * on the event loop. Throws synchronously if the trigger is unknown,\n * already running, or unready.\n *\n * Errors from the finder are swallowed here — `runTriggerNow` already\n * persists them to the ledger (`last_run_summary`) and emits a\n * `trigger.run.error` event, so there's nothing useful for the caller to do.\n *\n * If the process is killed mid-run (bun --watch re-exec, OS reboot), the\n * row's `running_started_at` stays set. The next cold boot's\n * `sweepStaleRunningTriggers` call writes a `killed_by_restart` summary so\n * the UI shows the truth instead of frozen-from-an-hour-ago state.\n */\nexport function fireTriggerNow(name: string): void {\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) {\n throw new Error(`unknown trigger '${name}'`);\n }\n const ledger = getLedger();\n // Readiness gate: block the run synchronously so the server route can map\n // this to a 409 without the finder ever being invoked on a dead config.\n const stored = ledger.getTrigger(name);\n const config = storedTriggerConfig(stored, spec);\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n throw new Error(`not ready: ${readiness.reason}`);\n }\n // Bootstrap the row if it doesn't exist yet — markTriggerRunning is an\n // UPDATE that no-ops on a missing row, so we'd silently lose state.\n if (!stored) {\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: spec.enabledByDefault !== false,\n });\n }\n // Atomic claim — no TOCTOU race. Two concurrent fires both calling\n // markTriggerRunning will see exactly one `true` and one `false`, so\n // only one finder run actually launches.\n //\n // The `staleCutoffIso` lets a fresh click reclaim a row whose previous\n // `running_started_at` is older than `MAX_RUN_AGE_MS` — i.e. the freshness\n // gate already says \"not running\" but the DB flag never got cleared\n // (process killed, no cold-boot sweep yet). Without this the user would\n // see Run-button-enabled, click, and get 409'd every retry.\n const nowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_RUN_AGE_MS).toISOString();\n const claimed = ledger.markTriggerRunning(name, nowIso, staleCutoffIso);\n if (!claimed) {\n throw new Error(`trigger '${name}' is already running`);\n }\n // Explicit catch — `void` discards the promise without wiring rejection\n // handling. If `runTriggerNow` throws synchronously OR rejects before its\n // own try/catch (e.g. JSON.parse on a corrupted config_json, an import\n // resolution issue under bun --hot, anything that would otherwise be a\n // silent unhandled rejection), we surface the failure AND clear the\n // stranded `running_started_at` so the row doesn't stay \"running\" until\n // the next boot sweep.\n runTriggerNow(name).catch((err) => {\n const message = (err as Error).message ?? \"runTriggerNow rejected\";\n logEvent(\"trigger.run.fire_failed\", { name, message_120: message.slice(0, 120) }, \"error\");\n try {\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: `fire_failed: ${message}`, at: new Date().toISOString() },\n });\n } catch {\n // updateTriggerLastPoll itself failing is hopeless; the boot sweep\n // is the safety net.\n }\n });\n}\n\n/**\n * Run a single trigger by name immediately, ignoring its scheduled dueAt\n * and the enabled flag. Useful for the /queue UI's \"Run now\" affordance:\n * the founder explicitly asked, so we bypass the scheduler. Persists\n * last_polled_at + last_run_summary so the watch loop respects the run.\n */\nexport async function runTriggerNow(name: string): Promise<TriggerRunOutcome> {\n startRun();\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) throw new Error(`unknown trigger '${name}'`);\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n if (!stored) {\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: spec.enabledByDefault !== false,\n });\n }\n const config = storedTriggerConfig(stored, spec);\n const intervalMs = effectiveIntervalMs(spec, config);\n // Readiness re-check: fireTriggerNow already gates ad-hoc runs, but a direct\n // CLI/test caller hitting runTriggerNow should get the same protection.\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n const message = `not ready: ${readiness.reason}`;\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\"trigger.run.skipped\", { name, source: \"ad_hoc\", reason: readiness.reason });\n return { name, fired: false, error: message, nextDueInMs: intervalMs };\n }\n const startedAt = Date.now();\n logEvent(\"trigger.run.start\", { name, source: \"ad_hoc\" });\n try {\n const result = await spec.run(config);\n ledger.updateTriggerLastPoll({ name, summary: result });\n logEvent(\"trigger.run.done\", {\n name,\n duration_ms: Date.now() - startedAt,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n return { name, fired: true, result, nextDueInMs: intervalMs };\n } catch (err) {\n const message = (err as Error).message ?? \"unknown error\";\n ledger.updateTriggerLastPoll({\n name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\n \"trigger.run.error\",\n {\n name,\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n return { name, fired: true, error: message, nextDueInMs: intervalMs };\n }\n}\n\n/**\n * Run every registered trigger that's due. Persists last_polled_at + last_run_summary.\n * Returns one outcome per trigger so the caller can log + decide sleep duration.\n */\nexport async function runDueTriggers(): Promise<TriggerRunOutcome[]> {\n startRun();\n const ledger = getLedger();\n const now = Date.now();\n const outcomes: TriggerRunOutcome[] = [];\n logEvent(\"watch.tick.start\", { trigger_count: TRIGGERS.length });\n\n for (const spec of TRIGGERS) {\n const stored = ledger.getTrigger(spec.name);\n const defaultEnabled = spec.enabledByDefault !== false;\n // Initialize on first sight.\n if (!stored) {\n ledger.upsertTrigger({\n name: spec.name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: defaultEnabled,\n });\n }\n\n const config = storedTriggerConfig(stored, spec);\n const intervalMs = effectiveIntervalMs(spec, config);\n\n const enabled = stored ? Boolean(stored.enabled) : defaultEnabled;\n if (!enabled) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n continue;\n }\n\n // Readiness gate: skip without touching last_polled_at so the watch loop\n // retries on the *next* tick once config is fixed, not on the next\n // interval boundary.\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n logEvent(\"trigger.run.skipped\", {\n name: spec.name,\n source: \"watch\",\n reason: readiness.reason,\n });\n continue;\n }\n\n const lastPolledMs = stored?.last_polled_at ? new Date(stored.last_polled_at).getTime() : 0;\n const dueAt = lastPolledMs + intervalMs;\n if (now < dueAt) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: dueAt - now });\n continue;\n }\n\n // Atomic claim — same pattern as fireTriggerNow (line 436-441) so the\n // scheduled-fire path can't race with a manual click on the same trigger\n // and double-spend. `staleCutoffIso` lets a fresh tick reclaim a row\n // whose previous `running_started_at` is older than MAX_RUN_AGE_MS (the\n // freshness gate already says \"not running\" but the marker never got\n // cleared — process killed before updateTriggerLastPoll ran, no boot\n // sweep yet). Cleared by updateTriggerLastPoll on success/error.\n const claimNowIso = new Date().toISOString();\n const staleCutoffIso = new Date(Date.now() - MAX_RUN_AGE_MS).toISOString();\n const claimed = ledger.markTriggerRunning(spec.name, claimNowIso, staleCutoffIso);\n if (!claimed) {\n outcomes.push({ name: spec.name, fired: false, nextDueInMs: intervalMs });\n logEvent(\"trigger.run.skipped\", {\n name: spec.name,\n source: \"watch\",\n reason: \"already-running\",\n });\n continue;\n }\n\n const startedAt = Date.now();\n logEvent(\"trigger.run.start\", { name: spec.name, source: \"watch\" });\n try {\n const result = await spec.run(config);\n ledger.updateTriggerLastPoll({ name: spec.name, summary: result });\n logEvent(\"trigger.run.done\", {\n name: spec.name,\n duration_ms: Date.now() - startedAt,\n candidates: result.candidates,\n enqueued: result.enqueued,\n dropped_icp: result.droppedIcp,\n dropped_dup: result.droppedDuplicate,\n dropped_enrich: result.droppedEnrichment,\n cost_usd: result.costUsd,\n halted: result.halted ?? null,\n });\n outcomes.push({ name: spec.name, fired: true, result, nextDueInMs: intervalMs });\n } catch (err) {\n const message = (err as Error).message ?? \"unknown error\";\n ledger.updateTriggerLastPoll({\n name: spec.name,\n summary: { error: message, at: new Date().toISOString() },\n });\n logEvent(\n \"trigger.run.error\",\n {\n name: spec.name,\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n outcomes.push({\n name: spec.name,\n fired: true,\n error: message,\n nextDueInMs: intervalMs,\n });\n }\n }\n logEvent(\"watch.tick.done\", { fired: outcomes.filter((o) => o.fired).length });\n return outcomes;\n}\n\nexport function nextSleepMs(outcomes: TriggerRunOutcome[]): number {\n if (outcomes.length === 0) return 60 * 60 * 1000;\n const min = Math.min(...outcomes.map((o) => o.nextDueInMs));\n // Floor at 60s, ceiling at 1h to keep the loop responsive without busy-waiting.\n return Math.max(60_000, Math.min(60 * 60 * 1000, min));\n}\n","import { getLedger, isSendDeferred, type ProspectRecord, type QueueRow } from \"@oneshot-gtm/core\";\nimport { type DraftedRow, isSupportedPlay, PLAYS } from \"@oneshot-gtm/plays\";\n\nexport interface DrainOpts {\n playName: string;\n limit?: number;\n dryRun: boolean;\n /** Required for accelerator-batch. */\n senderCohort?: string;\n freeForCohortOffer?: string;\n}\n\nexport interface DrainOutcome {\n drained: number;\n sent: number;\n /** Rows left approved because every sender identity hit its daily cap. */\n deferred: number;\n errors: Array<{ id: number; message: string }>;\n}\n\n/**\n * Pull approved rows for a play from target_queue, run them through the\n * existing motion play one target at a time, persist the draft for every row\n * (sent OR lint-held OR per-target error), then flip status to `sent` only\n * for the rows whose draft actually shipped. Per-target dispatch isolates\n * SDK throws (e.g. JobTimeoutError on agent.email()) so one bad target\n * can't kill the rest of the batch.\n */\nexport async function drainQueue(opts: DrainOpts): Promise<DrainOutcome> {\n const ledger = getLedger();\n const rows = ledger.dequeueApproved({ playName: opts.playName, limit: opts.limit ?? 50 });\n const outcome: DrainOutcome = { drained: rows.length, sent: 0, deferred: 0, errors: [] };\n\n if (rows.length === 0) return outcome;\n\n // Global precondition: the play must exist. accelerator-batch no longer\n // needs a drain-level senderCohort — finder rows carry their own (stamped\n // from trigger config), and the play falls back to the run-level option.\n if (!isSupportedPlay(opts.playName)) {\n outcome.errors.push({ id: -1, message: `drain: unsupported play '${opts.playName}'` });\n return outcome;\n }\n\n for (let r = 0; r < rows.length; r++) {\n const row = rows[r]!;\n let draft: DraftedRow;\n try {\n draft = await dispatchOneTarget(opts, row);\n } catch (err) {\n // Daily caps exhausted: leave this row (and the rest of the batch)\n // approved with their reviewed drafts intact — the 15-min drain lease\n // expires and tomorrow's drain picks them up with fresh capacity.\n // Writing the \"(error)\" stub here would stomp a founder-reviewed draft.\n if (isSendDeferred(err)) {\n outcome.deferred += rows.length - r;\n break;\n }\n const msg = ((err as Error).message ?? \"play failed\").slice(0, 200);\n draft = {\n subject: \"(error)\",\n body: \"\",\n flags: [`error: ${msg}`],\n sent: false,\n receiptIds: [],\n };\n outcome.errors.push({ id: row.id, message: msg });\n }\n\n try {\n ledger.setQueueDraft({\n id: row.id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: draft.sent,\n receiptIds: draft.receiptIds,\n dryRun: opts.dryRun,\n ...(draft.enrichmentFailed ? { enrichmentFailed: true } : {}),\n },\n });\n if (draft.sent && !opts.dryRun) {\n ledger.setQueueStatus({ id: row.id, status: \"sent\" });\n const prospectId = backfillProspectId(row);\n if (prospectId != null) {\n try {\n ledger.setQueueProspectId(row.id, prospectId);\n } catch {\n // best-effort backfill — a schema mismatch shouldn't break the drain\n }\n }\n outcome.sent++;\n }\n } catch (err) {\n outcome.errors.push({\n id: row.id,\n message: ((err as Error).message ?? \"persist failed\").slice(0, 200),\n });\n }\n }\n\n if (opts.dryRun) outcome.sent = rows.length; // would-be-sent (no actual send in dryRun)\n\n return outcome;\n}\n\nasync function dispatchOneTarget(opts: DrainOpts, row: QueueRow): Promise<DraftedRow> {\n const play = PLAYS[opts.playName];\n if (!play) throw new Error(`drain: unsupported play '${opts.playName}'`);\n const target = JSON.parse(row.payload_json) as unknown;\n const result = await play.run({\n dryRun: opts.dryRun,\n targets: [target],\n ...(opts.senderCohort ? { senderCohort: opts.senderCohort } : {}),\n ...(opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}),\n });\n return firstDraft(result.drafted);\n}\n\nfunction firstDraft(drafted: DraftedRow[]): DraftedRow {\n const d = drafted[0];\n if (!d) throw new Error(\"play returned no draft for this target\");\n return d;\n}\n\n/**\n * Map drafted-results back to queue-row IDs by position. Plays return one\n * draft per input target (in order), so drafted[i] always corresponds to\n * rows[i]. We only flip a row to `sent` when its draft actually sent (or in\n * dry-run, when we'd have sent it). The earlier `.filter().map((_, i) => rows[i])`\n * pattern was wrong — after filtering, the index no longer maps to the\n * original row, so partial sends marked the wrong rows as sent.\n */\nexport function idsForSentDrafts(\n drafted: Array<{ sent: boolean }>,\n rows: QueueRow[],\n dryRun: boolean,\n): number[] {\n const ids: number[] = [];\n for (let i = 0; i < drafted.length; i++) {\n const draft = drafted[i];\n const row = rows[i];\n if (!draft || !row) continue;\n if (draft.sent || dryRun) ids.push(row.id);\n }\n return ids;\n}\n\nfunction backfillProspectId(row: QueueRow | null): number | null {\n if (!row) return null;\n try {\n const payload = JSON.parse(row.payload_json) as { email?: string; founderEmail?: string };\n const email = payload.email ?? payload.founderEmail;\n if (!email) return null;\n const ledger = getLedger();\n const p = ledger.findProspectByEmail(email);\n return p ? p.id : null;\n } catch {\n return null;\n }\n}\n\nexport type { ProspectRecord };\n","import { loadConfig, logEvent, startRun, webSearch } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt } from \"@oneshot-gtm/intel\";\nimport { effectiveIntervalMs, TRIGGERS } from \"@oneshot-gtm/find\";\nimport type { StrategistFrame, StrategistRequest } from \"@oneshot-gtm/shared-types\";\nimport { getLedger } from \"@oneshot-gtm/core\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * SSE chat endpoint for the trigger strategist.\n * Request: { messages: Array<{ role: \"user\"|\"assistant\", content: string }> }.\n *\n * Composes a system prompt from the founder's ICP/product + a brief per trigger,\n * then calls `complete()` once per turn. The assistant proposes changes via\n * ACTION markers (<!--ACTION:enable:show-hn-->) that the client renders as\n * confirmation chips and posts back through the trigger REST endpoints. No native\n * tool calling — keeps the contract simple and works with any chat provider.\n */\n/**\n * Pure body-shape check, extracted so HTTP tests can exercise the failure\n * paths without mocking fetch / Bun.serve. Returns either the parsed\n * messages or a status+error pair the caller can mirror back as JSON.\n */\nexport function validateStrategistBody(\n raw: unknown,\n):\n | { kind: \"ok\"; messages: StrategistRequest[\"messages\"] }\n | { kind: \"error\"; status: number; error: string } {\n if (!raw || typeof raw !== \"object\") {\n return { kind: \"error\", status: 400, error: \"messages must be a non-empty array\" };\n }\n const body = raw as Partial<StrategistRequest>;\n if (!Array.isArray(body.messages) || body.messages.length === 0) {\n return { kind: \"error\", status: 400, error: \"messages must be a non-empty array\" };\n }\n for (const m of body.messages) {\n if (!m || typeof m !== \"object\") {\n return { kind: \"error\", status: 400, error: \"each message must be an object\" };\n }\n if (m.role !== \"user\" && m.role !== \"assistant\") {\n return {\n kind: \"error\",\n status: 400,\n error: `each message.role must be 'user' or 'assistant' (got ${String(m.role)})`,\n };\n }\n if (typeof m.content !== \"string\") {\n return { kind: \"error\", status: 400, error: \"each message.content must be a string\" };\n }\n }\n return { kind: \"ok\", messages: body.messages };\n}\n\n/**\n * Pure cfg readiness check — strategist needs ICP + product to anchor\n * proposals. Same shape as validateStrategistBody so the route handler\n * can mirror either failure verbatim.\n */\nexport function validateCfgForStrategist(cfg: {\n icpOneLiner?: string | null;\n productOneLiner?: string | null;\n}): { kind: \"ok\" } | { kind: \"error\"; status: number; error: string } {\n if (!cfg.icpOneLiner || cfg.icpOneLiner.trim().length === 0) {\n return {\n kind: \"error\",\n status: 400,\n error: \"set ICP one-liner in /setup before opening the strategist\",\n };\n }\n if (!cfg.productOneLiner || cfg.productOneLiner.trim().length === 0) {\n return {\n kind: \"error\",\n status: 400,\n error: \"set product one-liner in /setup before opening the strategist\",\n };\n }\n return { kind: \"ok\" };\n}\n\nexport async function strategistRoute(req: Request): Promise<Response> {\n startRun();\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n const bodyCheck = validateStrategistBody(raw);\n if (bodyCheck.kind === \"error\") {\n return jsonResponse({ error: bodyCheck.error }, bodyCheck.status, req);\n }\n const messages = bodyCheck.messages;\n\n const cfg = loadConfig();\n const cfgCheck = validateCfgForStrategist(cfg);\n if (cfgCheck.kind === \"error\") {\n return jsonResponse({ error: cfgCheck.error }, cfgCheck.status, req);\n }\n\n // Pre-search the web for accelerator data when the founder's latest message\n // is about cohort selection. Strategist's training-data knowledge of which\n // accelerators exist + are accepting applications is stale by months; live\n // search gives it fresh context to ground its proposal in. Empty string when\n // not applicable — composeSystemPrompt then renders no extra section.\n const latestUserMessage = messages.toReversed().find((m) => m.role === \"user\")?.content ?? \"\";\n const webContext = await maybeAcceleratorWebContext(latestUserMessage, cfg.icpOneLiner!);\n\n const systemPrompt = composeSystemPrompt({\n productOneLiner: cfg.productOneLiner!,\n icpOneLiner: cfg.icpOneLiner!,\n webContext,\n });\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const encoder = new TextEncoder();\n let closed = false;\n const send = (event: StrategistFrame): void => {\n if (closed) return;\n try {\n controller.enqueue(\n encoder.encode(`event: ${event.kind}\\ndata: ${JSON.stringify(event)}\\n\\n`),\n );\n } catch {\n // Client disconnected mid-stream — controller already closed by\n // the runtime. Mark and stop trying to write.\n closed = true;\n }\n };\n\n const startedAt = Date.now();\n logEvent(\"strategist.turn.start\", { message_count: messages.length });\n try {\n send({ kind: \"thinking\" });\n const llm = await complete({\n messages: [\n { role: \"system\", content: systemPrompt },\n ...messages.map((m) => ({ role: m.role, content: m.content }) as const),\n ],\n temperature: 0.4,\n // 800 tokens truncated apply-config markers when the proposed JSON\n // ran long (a fully-populated github-topics config with topics +\n // vendors + yourEdge easily hits ~600 chars of JSON + prose). Bumped\n // to 4096 so a multi-field config never gets clipped mid-marker.\n maxTokens: 4096,\n });\n // Fake-stream the assistant content in chunks so the UI gets\n // progressive text instead of a single late drop. Real token streaming\n // is a future hop on intel.complete; this is good enough for chat\n // turns that complete in ~5-10s.\n //\n // Split on Unicode code points (Array.from), not UTF-16 code units —\n // a midstream split through a surrogate pair would yield mojibake on\n // the client. Chunk size is in code-points, not bytes.\n const codePoints = Array.from(llm.content);\n const CHUNK_CODE_POINTS = 60;\n for (let i = 0; i < codePoints.length; i += CHUNK_CODE_POINTS) {\n if (closed) break;\n send({ kind: \"delta\", text: codePoints.slice(i, i + CHUNK_CODE_POINTS).join(\"\") });\n }\n send({ kind: \"done\" });\n logEvent(\"strategist.turn.done\", {\n duration_ms: Date.now() - startedAt,\n response_chars: llm.content.length,\n });\n } catch (err) {\n const message = (err as Error).message ?? \"strategist failed\";\n logEvent(\n \"strategist.turn.error\",\n {\n duration_ms: Date.now() - startedAt,\n message_120: message.slice(0, 120),\n },\n \"error\",\n );\n send({ kind: \"error\", message });\n } finally {\n closed = true;\n try {\n controller.close();\n } catch {\n // already closed by client disconnect — ignore\n }\n }\n },\n });\n\n // Mirror the loopback CORS handling used by /api/run/:playName.\n const origin = req.headers.get(\"origin\") ?? \"\";\n const isLoopback =\n origin === \"\" ||\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\");\n const sseHeaders: Record<string, string> = {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n \"x-accel-buffering\": \"no\",\n };\n if (isLoopback) {\n sseHeaders[\"Access-Control-Allow-Origin\"] = origin || \"http://127.0.0.1\";\n sseHeaders[\"Vary\"] = \"Origin\";\n }\n\n return new Response(stream, { status: 200, headers: sseHeaders });\n}\n\nfunction composeSystemPrompt(args: {\n productOneLiner: string;\n icpOneLiner: string;\n webContext: string;\n}): string {\n const template = loadPrompt(\"strategist-trigger\");\n const triggerCatalog = buildTriggerCatalog();\n return template\n .replace(\"{{productOneLiner}}\", args.productOneLiner)\n .replace(\"{{icpOneLiner}}\", args.icpOneLiner)\n .replace(\"{{triggerCatalog}}\", triggerCatalog)\n .replace(\"{{webContext}}\", args.webContext);\n}\n\n/**\n * Trigger phrases that imply the founder wants accelerator-batch help. Loose\n * enough to catch \"pick an accelerator\", \"yc batch\", \"any incubators?\", etc.\n * Tight enough that \"what should I enable for my ICP?\" doesn't fire.\n */\nconst ACCELERATOR_KEYWORDS =\n /\\b(accelerator|cohort|batch|incubator|y[ -]?combinator|techstars|antler|ai[ -]?grant|spc|south\\s*park|neo|500\\s*global)\\b/i;\n\n/**\n * If the founder's latest message asks about accelerator-batch, run a web\n * search for accelerators that fit their ICP and format the results as a\n * markdown block to inject into the system prompt. Empty string otherwise\n * (the placeholder collapses to nothing).\n *\n * Cost: ~$0.01 per accelerator-related strategist message. Latency: ~5-15s.\n * Wrapped in try/catch so a search hiccup doesn't block the strategist's\n * normal response.\n */\nasync function maybeAcceleratorWebContext(\n latestUserMessage: string,\n icpOneLiner: string,\n): Promise<string> {\n if (!ACCELERATOR_KEYWORDS.test(latestUserMessage)) return \"\";\n try {\n const query = `${icpOneLiner} startup accelerator OR cohort OR grant 2026 batch`;\n const search = await webSearch({ query, maxResults: 8 }, { playName: \"strategist\" });\n const results = search.result.results ?? [];\n if (results.length === 0) {\n logEvent(\"strategist.web_search.accelerators\", { query_chars: query.length, count: 0 });\n return \"\";\n }\n const lines = results.slice(0, 8).map((r) => {\n const title = (r.title ?? \"\").slice(0, 160);\n const url = (r.url ?? \"\").slice(0, 200);\n const desc = (r.description ?? \"\").slice(0, 240);\n return `- **${title}** — ${url}\\n ${desc}`;\n });\n logEvent(\"strategist.web_search.accelerators\", {\n query_chars: query.length,\n count: results.length,\n });\n return [\n \"## Recent accelerator landscape (web-searched for ICP fit)\",\n \"\",\n \"When proposing `accelerator-batch.cohort`, ground your pick in these\",\n \"results rather than your training-data memory of which accelerators exist.\",\n \"Reason from the founder's ICP to which accelerator's portfolio overlaps best.\",\n \"\",\n ...lines,\n ].join(\"\\n\");\n } catch (err) {\n logEvent(\n \"strategist.web_search.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n return \"\";\n }\n}\n\nfunction buildTriggerCatalog(): string {\n const ledger = getLedger();\n const stored = new Map(ledger.listTriggers().map((r) => [r.name, r]));\n const lines: string[] = [];\n for (const spec of TRIGGERS) {\n const row = stored.get(spec.name);\n const defaultEnabled = spec.enabledByDefault !== false;\n const enabled = row ? Boolean(row.enabled) : defaultEnabled;\n const config = row?.config_json ? row.config_json : JSON.stringify(spec.defaultConfig);\n const intervalMs = effectiveIntervalMs(spec, safeParse(config));\n lines.push(\n `### ${spec.name}` +\n `\\n- enabled: ${enabled}` +\n `\\n- interval: ${humanInterval(intervalMs)}` +\n `\\n- current config: ${config}` +\n `\\n- brief: ${spec.configBrief ?? \"(no brief — defaults are sane)\"}`,\n );\n }\n return lines.join(\"\\n\\n\");\n}\n\nfunction safeParse(s: string): Record<string, unknown> | null {\n try {\n return JSON.parse(s) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction humanInterval(ms: number): string {\n if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n if (ms < 3600_000) return `${Math.round(ms / 60_000)}m`;\n if (ms < 24 * 3600_000) return `${(ms / 3600_000).toFixed(1)}h`;\n return `${(ms / (24 * 3600_000)).toFixed(1)}d`;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n capGroupKey,\n configDir,\n getBalance,\n getGmailProfile,\n getLedger,\n GMAIL_AUTH_HINT,\n gmailAccountFor,\n identityCapacities,\n listSendingDomains,\n llmApiKey,\n loadConfig,\n missingGmailSecrets,\n oneshotEnvReady,\n resolveIdentities,\n secretSource,\n} from \"@oneshot-gtm/core\";\n\ntype CheckSeverity = \"ok\" | \"warn\" | \"fail\";\n\ninterface CheckResult {\n name: string;\n severity: CheckSeverity;\n message: string;\n hint?: string;\n}\n\nexport async function runDoctor(): Promise<CheckResult[]> {\n const cfg = loadConfig();\n const results: CheckResult[] = [];\n\n results.push({\n name: \"config dir\",\n severity: existsSync(configDir()) ? \"ok\" : \"warn\",\n message: existsSync(configDir()) ? configDir() : `missing: ${configDir()}`,\n ...(existsSync(configDir()) ? {} : { hint: \"run: oneshot-gtm init\" }),\n });\n\n results.push({\n name: \"founder profile\",\n severity: cfg.founderName && cfg.productOneLiner ? \"ok\" : \"warn\",\n message:\n cfg.founderName && cfg.productOneLiner\n ? `${cfg.founderName} — ${cfg.productOneLiner}`\n : \"founder name + product one-liner not set\",\n ...(cfg.founderName && cfg.productOneLiner ? {} : { hint: \"run: oneshot-gtm config founder\" }),\n });\n\n const llmEnv = {\n openrouter: \"OPENROUTER_API_KEY\",\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n }[cfg.llmProvider];\n\n const llmSrc = secretSource(llmEnv as never);\n results.push({\n name: `llm key (${cfg.llmProvider})`,\n severity: llmApiKey(cfg.llmProvider) ? \"ok\" : \"fail\",\n message: llmApiKey(cfg.llmProvider) ? `set (${llmSrc ?? \"?\"})` : `${llmEnv} not set`,\n ...(llmApiKey(cfg.llmProvider) ? {} : { hint: `oneshot-gtm config keys` }),\n });\n\n const cdpSrc = secretSource(\"CDP_API_KEY_ID\");\n const pkSrc = secretSource(\"AGENT_PRIVATE_KEY\");\n const walletSrc = process.env.AGENT_PRIVATE_KEY ? pkSrc : cdpSrc;\n results.push({\n name: \"wallet env\",\n severity: oneshotEnvReady() ? \"ok\" : \"fail\",\n message: oneshotEnvReady()\n ? `${process.env.AGENT_PRIVATE_KEY ? \"AGENT_PRIVATE_KEY\" : \"CDP wallet\"} set (${walletSrc ?? \"?\"})`\n : \"no wallet credentials\",\n ...(oneshotEnvReady() ? {} : { hint: \"oneshot-gtm config keys\" }),\n });\n\n try {\n const ledger = getLedger();\n const sample = ledger.listReceipts({ limit: 1 });\n results.push({\n name: \"ledger\",\n severity: \"ok\",\n message: `ok, ${sample.length === 0 ? \"empty\" : \"has receipts\"} (${join(configDir(), \"ledger.sqlite\")})`,\n });\n } catch (err) {\n results.push({\n name: \"ledger\",\n severity: \"fail\",\n message: `error opening ledger: ${(err as Error).message}`,\n });\n }\n\n // One line per sender identity in the rotation pool. Legacy installs\n // (emailIdentities unset) get their single synthesized identity, so this\n // doubles as the old single-provider gmail check.\n try {\n const identities = resolveIdentities(cfg);\n // Per cap-group capacity (the shared per-domain budget). Used for the usage\n // string so doctor reports the real gate, not a per-mailbox illusion.\n const caps = identityCapacities();\n const groupSize = new Map<string, number>();\n for (const i of identities) {\n const k = capGroupKey(i);\n groupSize.set(k, (groupSize.get(k) ?? 0) + 1);\n }\n\n // Provisioned-domain pool, fetched once and only when it can matter (a\n // wallet exists AND at least one OneShot identity to report on). Empty map =\n // \"couldn't enumerate\" → skip the warmth report rather than cry wolf.\n // We report warmth, not ownership: a pinned send (we always set from_domain)\n // AUTO-PROVISIONS an unknown domain and BYPASSES the server's warmup gating,\n // so there is no domain_not_owned failure to pre-empt — the deliverability\n // risk is sending from a cold/warming domain with only the client cap as a\n // throttle.\n let domainPool: Map<string, { warmupScore: number | null; status: string }> | null = null;\n if (oneshotEnvReady() && identities.some((i) => i.provider === \"oneshot\")) {\n try {\n const pool = await listSendingDomains();\n if (pool.length > 0) {\n domainPool = new Map(\n pool.map((d) => [\n d.domain.toLowerCase(),\n { warmupScore: d.warmup_score, status: d.pool_status },\n ]),\n );\n }\n } catch {\n // Leave null — transient/auth failure shouldn't downgrade the check.\n }\n }\n\n for (const identity of identities) {\n const c = caps.get(identity.id);\n const capStr = c && Number.isFinite(c.capToday) ? String(c.capToday) : \"∞\";\n const shared = (groupSize.get(capGroupKey(identity)) ?? 1) > 1;\n // When mailboxes share a domain, show the shared domain total alongside\n // this mailbox's own count so the cap reads honestly.\n const usage = shared\n ? `today ${c?.identitySentToday ?? 0} · domain ${c?.domainSentToday ?? 0}/${capStr} shared`\n : `today ${c?.identitySentToday ?? 0}/${capStr}`;\n const name = `sender ${identity.id}`;\n if (identity.provider === \"gmail\") {\n const missing = missingGmailSecrets().filter((k) => k !== \"GMAIL_REFRESH_TOKEN\");\n const account = gmailAccountFor(identity);\n if (missing.length > 0 || !account) {\n results.push({\n name,\n severity: \"fail\",\n message:\n missing.length > 0 ? `missing: ${missing.join(\", \")}` : \"no refresh token stored\",\n hint: GMAIL_AUTH_HINT,\n });\n continue;\n }\n try {\n const { emailAddress } = await getGmailProfile(account);\n results.push({ name, severity: \"ok\", message: `sending as ${emailAddress} · ${usage}` });\n } catch (err) {\n results.push({\n name,\n severity: \"fail\",\n message: `auth check failed: ${(err as Error).message}`,\n hint: GMAIL_AUTH_HINT,\n });\n }\n } else {\n const domain = identity.sendingDomain ?? cfg.sendingDomain;\n const localpart = identity.mailbox ? `${identity.mailbox}@` : \"\";\n const entry = domain && domainPool ? domainPool.get(domain.toLowerCase()) : undefined;\n if (!domain) {\n results.push({\n name,\n severity: \"warn\",\n message: `no sendingDomain — SDK default domain · ${usage}`,\n });\n } else if (domainPool && !entry) {\n // Known pool, domain absent: not an error (auto-provisions on first\n // send) but it'll go out cold with no server warmup — lean on the cap.\n results.push({\n name,\n severity: \"warn\",\n message: `${localpart}${domain} not yet provisioned — auto-provisions on first send and bypasses server warm-up; client cap is the only throttle · ${usage}`,\n hint: \"Confirm you control this domain, or pick a warmed one (oneshot-gtm identities list).\",\n });\n } else if (entry && (entry.status === \"paused\" || entry.status === \"removed\")) {\n results.push({\n name,\n severity: \"warn\",\n message: `${localpart}${domain} is ${entry.status} in the pool · ${usage}`,\n hint: \"Resume it (agent.resumeDomain) before relying on it.\",\n });\n } else {\n const warmth =\n entry?.status === \"warming\"\n ? ` · warming${entry.warmupScore != null ? ` (score ${entry.warmupScore})` : \"\"} — pinned sends skip server warm-up, client cap throttles`\n : \"\";\n results.push({\n name,\n severity: \"ok\",\n message: `sending from ${localpart}${domain} · ${usage}${warmth}`,\n });\n }\n }\n }\n } catch (err) {\n results.push({\n name: \"sender identities\",\n severity: \"warn\",\n message: `could not evaluate: ${(err as Error).message}`,\n });\n }\n\n if (oneshotEnvReady()) {\n try {\n const bal = await getBalance();\n results.push({\n name: \"wallet balance\",\n severity: \"ok\",\n message: `${bal.balance}`,\n });\n } catch (err) {\n results.push({\n name: \"wallet balance\",\n severity: \"warn\",\n message: `could not fetch: ${(err as Error).message}`,\n });\n }\n }\n\n return results;\n}\n","import { runDoctor } from \"@oneshot-gtm/doctor\";\nimport type { DoctorCheck } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport async function doctor(req: Request): Promise<Response> {\n const results = await runDoctor();\n const checks: DoctorCheck[] = results.map((r) => {\n const out: DoctorCheck = { name: r.name, severity: r.severity, message: r.message };\n if (r.hint) out.hint = r.hint;\n return out;\n });\n return jsonResponse({ checks }, 200, req);\n}\n","import { PLAYS } from \"@oneshot-gtm/plays\";\nimport type { RunPlayRequest } from \"@oneshot-gtm/shared-types\";\n\nexport interface DraftedView {\n subject: string;\n body: string;\n flags: string[];\n receiptIds: number[];\n sent: boolean;\n enrichmentFailed?: boolean;\n}\n\nexport function toDraftedView(d: {\n subject: string;\n body: string;\n flags: string[];\n receiptIds: number[];\n sent: boolean;\n enrichmentFailed?: boolean;\n}): DraftedView {\n return {\n subject: d.subject,\n body: d.body,\n flags: d.flags,\n receiptIds: d.receiptIds,\n sent: d.sent,\n ...(d.enrichmentFailed ? { enrichmentFailed: true } : {}),\n };\n}\n\n/**\n * Dispatch a play by name and return one DraftedView per target (in order).\n * Shared by the SSE /api/run endpoint (multi-target) and the /queue\n * regenerate endpoint (single-target dry-run). Throws on unsupported plays.\n *\n * `onProgress`: optional per-target hook fired AFTER each target completes.\n * The SSE handler uses this to emit `draft` + `send` events live as they\n * happen instead of batching at the end. The PlayDraft → DraftedView\n * projection is applied inside the wrapper so the callback gets the same\n * shape downstream code expects.\n */\nexport async function dispatchPlay(\n playName: string,\n body: RunPlayRequest,\n onProgress?: (index: number, view: DraftedView) => void,\n): Promise<DraftedView[]> {\n const play = PLAYS[playName];\n if (!play) {\n throw new Error(`unsupported play: ${playName}`);\n }\n\n const result = await play.run({\n dryRun: body.dryRun,\n targets: body.targets,\n ...(body.senderCohort ? { senderCohort: body.senderCohort } : {}),\n ...(body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}),\n ...(onProgress\n ? {\n onProgress: (index: number, draft: Parameters<typeof toDraftedView>[0]) =>\n onProgress(index, toDraftedView(draft)),\n }\n : {}),\n });\n return result.drafted.map(toDraftedView);\n}\n","import { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport { verifyAndFilterTargets } from \"@oneshot-gtm/plays\";\nimport type { RunPlayEvent, RunPlayRequest } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\nimport { dispatchPlay, type DraftedView } from \"./_play-dispatch.ts\";\n\nconst SUPPORTED = new Set([\n \"show-hn\",\n \"job-change\",\n \"post-funding\",\n \"accelerator-batch\",\n \"hiring-signal\",\n \"podcast-guest\",\n \"competitor-switch\",\n \"stack-consolidation\",\n \"repo-interest\",\n \"luma-events\",\n]);\n\nexport async function runPlay(req: Request, params: Record<string, string>): Promise<Response> {\n const playName = params[\"playName\"] ?? \"\";\n if (!SUPPORTED.has(playName)) {\n return jsonResponse(\n { error: `play '${playName}' is not exposed in the UI; use the CLI` },\n 400,\n req,\n );\n }\n\n let body: RunPlayRequest;\n try {\n body = (await req.json()) as RunPlayRequest;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n\n if (!Array.isArray(body.targets) || body.targets.length === 0) {\n return jsonResponse({ error: \"targets must be a non-empty array\" }, 400, req);\n }\n\n // Create a runs row up-front so the UI gets a runId to navigate to + can\n // resume on nav-back via GET /api/runs/:id. Every SSE event we emit below\n // is also appended to the row's events_json so the resume view rebuilds\n // accurately. Marked 'done' at the end of the try (success) or the catch\n // (failure); cold-boot sweep flips any stranded 'running' rows to\n // 'interrupted'.\n const { runId, startedAt } = getLedger().createRun({\n playName,\n dryRun: body.dryRun,\n targets: body.targets,\n });\n // Track which emails actually sent successfully so the UI can deep-link\n // to /cadences?sinceRun=N filtered to just-enrolled prospects.\n const sentEmails: string[] = [];\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const encoder = new TextEncoder();\n const ledger = getLedger();\n const send = (event: RunPlayEvent): void => {\n // Persist FIRST — even if the client has disconnected, the resume\n // view needs every event. SSE write second; swallow if the client\n // is gone (closed tab, navigation, or timeout). The server-side\n // work (incl. any real send) still happened — no false pipeline_error.\n try {\n ledger.appendRunEvent({ runId, event });\n } catch {\n // ledger write failing is the sweeper's problem; keep streaming.\n }\n try {\n controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\\n\\n`));\n } catch {\n // client gone — ignore\n }\n };\n\n // First frame: tell the UI its runId so it can switch to progress mode.\n send({ kind: \"runStarted\", runId, startedAt });\n\n try {\n // Build email → dedupeKey map BEFORE the verify filter potentially\n // drops rows. The verify pass changes target indices but not target\n // emails, so we can recover the dedupe key per drafted target by\n // looking up the email later. Manual /run entries (no fromQueue)\n // omit `dedupeKeys`; the map stays empty and the persist hook is\n // a no-op.\n const emailToDedupeKey = new Map<string, string>();\n if (body.dedupeKeys && body.dedupeKeys.length === body.targets.length) {\n body.targets.forEach((t, i) => {\n const target = t as { email?: string; founderEmail?: string };\n const email = target.email ?? target.founderEmail;\n const key = body.dedupeKeys?.[i];\n if (email && key) emailToDedupeKey.set(email, key);\n });\n }\n\n // Verify all target emails BEFORE dispatching to the play, so\n // undeliverable rows are dropped before we spend on LLM drafting.\n // Skipped on dryRun (no real spend during preview), AND skipped for\n // queue-sourced runs (dedupeKeys present) — those rows were already\n // verified at finder-enqueue time, so re-verifying just adds latency.\n // The verify event tells the UI which rows were dropped + why.\n const inputCount = body.targets.length;\n const fromQueue =\n Array.isArray(body.dedupeKeys) && body.dedupeKeys.length === body.targets.length;\n let verify: Awaited<ReturnType<typeof verifyAndFilterTargets>>;\n if (fromQueue) {\n verify = { verified: body.targets, dropped: [], receiptIds: [], costUsd: 0 };\n } else {\n send({ kind: \"stage\", stage: \"verifying\" });\n verify = await verifyAndFilterTargets(\n body.targets as Array<{ email?: string; founderEmail?: string }>,\n (t) => t.email ?? t.founderEmail ?? null,\n { playName, dryRun: body.dryRun },\n );\n }\n if (verify.dropped.length > 0) {\n send({\n kind: \"verify\",\n total: inputCount,\n verified: verify.verified.length,\n dropped: verify.dropped.map((d) => ({ email: d.email, reason: d.reason })),\n });\n }\n // If verify dropped every target, skip dispatch entirely — no point\n // calling the play with an empty array (the play would either\n // return empty drafted[] or throw on a \"founder profile incomplete\"\n // pre-check that's irrelevant when there's nothing to send).\n if (verify.verified.length === 0 && inputCount > 0) {\n send({ kind: \"done\", total: 0, sent: 0 });\n return;\n }\n const filteredBody: RunPlayRequest = { ...body, targets: verify.verified };\n\n send({ kind: \"stage\", stage: body.dryRun ? \"drafting\" : \"drafting + sending\" });\n let sentCount = 0;\n // Per-target callback installed by dispatchPlay → play.run → parallelMap.\n // Fires the draft + (optional) send events live so the runs row's\n // counters and the UI tick from 0/N → N/N as each target completes,\n // instead of jumping at the end.\n const drafted = await dispatchPlay(playName, filteredBody, (index, d) => {\n send({ kind: \"draft\", index, subject: d.subject, body: d.body, flags: d.flags });\n if (d.receiptIds.length > 0) {\n send({ kind: \"send\", index, receiptIds: d.receiptIds });\n }\n if (d.sent) {\n sentCount++;\n // Pull the email back out of the verified target so /cadences?sinceRun\n // can later resolve \"what was just sent\" without re-parsing events.\n const t = verify.verified[index] as\n | { email?: string; founderEmail?: string }\n | undefined;\n const email = t?.email ?? t?.founderEmail;\n if (email) sentEmails.push(email);\n }\n });\n send({ kind: \"done\", total: drafted.length, sent: sentCount });\n\n // Persist drafts to their originating queue rows so the founder can\n // review subject/body/flags later via /queue. Best-effort — the\n // SSE stream has already finished by here, so a SQLite hiccup\n // shouldn't surface as a user-visible error.\n if (emailToDedupeKey.size > 0) {\n persistDraftsToQueue({\n playName,\n verifiedTargets: verify.verified as Array<{ email?: string; founderEmail?: string }>,\n drafted,\n dryRun: body.dryRun,\n emailToDedupeKey,\n });\n }\n } catch (err) {\n // Log the full error server-side — the SSE error event only carries a\n // short message (e.g. the SDK's generic \"Tool request failed\"), which\n // is useless for diagnosis. The stack reveals which call failed\n // (sendEmail / enrichProfile / verifyEmail in oneshot.ts).\n const e = err as Error & {\n cause?: unknown;\n statusCode?: number;\n responseBody?: string;\n };\n const causeMsg =\n e?.cause instanceof Error ? e.cause.message : e?.cause ? String(e.cause) : null;\n logEvent(\n \"run.pipeline_error\",\n {\n play: playName,\n message_200: (e?.message ?? \"\").slice(0, 200),\n // OneShot SDK ToolError carries the failing call's HTTP status +\n // server response body — the actual reason, vs the generic message.\n status_code: typeof e?.statusCode === \"number\" ? e.statusCode : null,\n response_body_400:\n typeof e?.responseBody === \"string\" ? e.responseBody.slice(0, 400) : null,\n cause_200: causeMsg ? causeMsg.slice(0, 200) : null,\n stack_300: (e?.stack ?? \"\").slice(0, 300),\n },\n \"error\",\n );\n // Surface the real reason to the UI. The SDK's bare \"Tool request\n // failed\" is useless; the server response body carries the actual\n // error (e.g. {\"error\":\"domain_not_owned\",\"message\":\"…\"}).\n let uiMessage = e?.message ?? \"run failed\";\n if (typeof e?.statusCode === \"number\") {\n let detail = \"\";\n try {\n const parsed = JSON.parse(e.responseBody ?? \"\") as {\n message?: string;\n error?: string;\n };\n detail = parsed.message ?? parsed.error ?? \"\";\n } catch {\n detail = (e.responseBody ?? \"\").slice(0, 160);\n }\n uiMessage = `${uiMessage} (HTTP ${e.statusCode})${detail ? ` — ${detail}` : \"\"}`;\n }\n send({ kind: \"error\", index: -1, message: uiMessage });\n } finally {\n // Flip the runs row to 'done' regardless of success/failure — the\n // per-event counters on the row are already accurate. Cold-boot sweep\n // only sees rows still stuck at 'running', so a clean shutdown here\n // means no false-positive `interrupted` next boot.\n try {\n getLedger().markRunComplete({ runId, status: \"done\", sentEmails });\n } catch {\n // sweeper safety net\n }\n try {\n controller.close();\n } catch {\n // already closed (client disconnected) — ignore\n }\n }\n },\n });\n\n // Loopback-only CORS for SSE. The outer fetch handler already enforces\n // a loopback Host check before this runs, so we just mirror the origin\n // when it's loopback and otherwise omit the header (browser refuses\n // cross-origin response reads).\n const origin = req.headers.get(\"origin\") ?? \"\";\n const isLoopback =\n origin === \"\" ||\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\");\n const sseHeaders: Record<string, string> = {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n \"x-accel-buffering\": \"no\",\n };\n if (isLoopback) {\n sseHeaders[\"Access-Control-Allow-Origin\"] = origin || \"http://127.0.0.1\";\n sseHeaders[\"Vary\"] = \"Origin\";\n }\n\n return new Response(stream, {\n status: 200,\n headers: sseHeaders,\n });\n}\n\n/**\n * After the SSE stream completes, write each generated draft to its\n * originating `target_queue` row. Best-effort: a SQL hiccup during\n * persistence is logged via `error.swallowed` and doesn't affect what the\n * UI already saw on the wire. Indices match because `verifiedTargets[i]`\n * corresponds to `drafted[i]` (both come from the same dispatch).\n */\nfunction persistDraftsToQueue(input: {\n playName: string;\n verifiedTargets: Array<{ email?: string; founderEmail?: string }>;\n drafted: DraftedView[];\n dryRun: boolean;\n emailToDedupeKey: Map<string, string>;\n}): void {\n const ledger = getLedger();\n for (let i = 0; i < input.drafted.length; i++) {\n const target = input.verifiedTargets[i];\n const draft = input.drafted[i];\n if (!target || !draft) continue;\n const email = target.email ?? target.founderEmail;\n if (!email) continue;\n const dedupeKey = input.emailToDedupeKey.get(email);\n if (!dedupeKey) continue;\n try {\n const row = ledger.getQueueRowByDedupe(input.playName, dedupeKey);\n if (!row) continue;\n ledger.setQueueDraft({\n id: row.id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: draft.sent,\n receiptIds: draft.receiptIds,\n dryRun: input.dryRun,\n ...(draft.enrichmentFailed ? { enrichmentFailed: true } : {}),\n },\n });\n // A real, successful send must leave the approved pool — otherwise the\n // row stays `approved` and every subsequent drain (esp. limit 1) re-loads\n // the same first approved target forever. Held drafts (lint flags →\n // sent:false) and dry-run previews intentionally stay approved.\n if (draft.sent && !input.dryRun) {\n ledger.setQueueStatus({ id: row.id, status: \"sent\" });\n }\n } catch (err) {\n logEvent(\n \"error.swallowed\",\n {\n kind: \"run.persistDraftsToQueue\",\n play: input.playName,\n message_120: ((err as Error).message ?? \"\").slice(0, 120),\n },\n \"warn\",\n );\n }\n }\n}\n","import { getLedger } from \"@oneshot-gtm/core\";\nimport type { RunRecord, RunPlayEvent } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\n/**\n * `GET /api/runs/:id` — snapshot of one /run-page dispatch. The UI polls this\n * every 2s while `status === 'running'`, then stops once `status` flips to\n * `done` or `interrupted`. The full events array is returned so the resume\n * view can rebuild per-target rows identically to a live SSE consumer.\n */\nexport function getRunRoute(req: Request, params: Record<string, string>): Response {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const run = getLedger().getRun(id);\n if (!run) return jsonResponse({ error: `run #${id} not found` }, 404, req);\n // Cast events through unknown → RunPlayEvent[]. Ledger stores them as\n // unknown[] (shape-agnostic); the route is the typed boundary.\n const view: RunRecord = {\n id: run.id,\n playName: run.playName,\n dryRun: run.dryRun,\n status: run.status,\n startedAt: run.startedAt,\n completedAt: run.completedAt,\n targetCount: run.targetCount,\n draftedCount: run.draftedCount,\n sentCount: run.sentCount,\n errorCount: run.errorCount,\n targets: run.targets,\n events: run.events as RunPlayEvent[],\n prospectEmails: run.prospectEmails,\n };\n return jsonResponse(view, 200, req);\n}\n","import {\n getLedger,\n isDraining,\n isSendDeferred,\n type QueueRow,\n type QueueStatus,\n} from \"@oneshot-gtm/core\";\nimport { drainQueue } from \"@oneshot-gtm/find\";\nimport { enrollInCadence, sendDraftedEmail } from \"@oneshot-gtm/plays\";\nimport {\n blockingFlags,\n type DrainRequest,\n type DrainResult,\n type LastDraft,\n type QueueCounts,\n type QueueRowView,\n type RunPlayRequest,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\nimport { dispatchPlay } from \"./_play-dispatch.ts\";\n\nfunction toView(row: QueueRow): QueueRowView {\n let payload: unknown = null;\n try {\n payload = JSON.parse(row.payload_json);\n } catch {\n payload = row.payload_json;\n }\n let lastDraft: LastDraft | null = null;\n if (row.last_draft_json) {\n try {\n const parsed = JSON.parse(row.last_draft_json) as Partial<LastDraft>;\n // Defensive shape check — older rows or future schema drift\n // shouldn't crash the queue listing.\n if (parsed && typeof parsed.subject === \"string\" && typeof parsed.body === \"string\") {\n lastDraft = {\n subject: parsed.subject,\n body: parsed.body,\n flags: Array.isArray(parsed.flags) ? parsed.flags : [],\n sent: parsed.sent === true,\n receiptIds: Array.isArray(parsed.receiptIds) ? parsed.receiptIds : [],\n dryRun: parsed.dryRun === true,\n draftedAt: typeof parsed.draftedAt === \"string\" ? parsed.draftedAt : \"\",\n ...(parsed.enrichmentFailed === true ? { enrichmentFailed: true } : {}),\n };\n }\n } catch {\n lastDraft = null;\n }\n }\n return {\n id: row.id,\n playName: row.play_name,\n payload,\n dedupeKey: row.dedupe_key,\n source: row.source,\n status: row.status,\n foundAt: row.found_at,\n reviewedAt: row.reviewed_at,\n sentAt: row.sent_at,\n notes: row.notes,\n prospectId: row.prospect_id,\n lastDraft,\n lastDraftedAt: row.last_drafted_at,\n isSending: row.send_started_at != null,\n };\n}\n\nexport function listQueueRoute(req: Request): Response {\n const url = new URL(req.url);\n const playName = url.searchParams.get(\"play\") ?? undefined;\n const status = (url.searchParams.get(\"status\") ?? undefined) as QueueStatus | undefined;\n const limit = Math.min(500, Number.parseInt(url.searchParams.get(\"limit\") ?? \"200\", 10) || 200);\n const ledger = getLedger();\n const filterArgs: { playName?: string; status?: QueueStatus; limit?: number } = { limit };\n if (playName) filterArgs.playName = playName;\n if (status) filterArgs.status = status;\n const rows = ledger.listQueue(filterArgs);\n const counts: QueueCounts = ledger.queueCounts();\n return jsonResponse({ rows: rows.map(toView), counts }, 200, req);\n}\n\nexport async function approveQueueRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n ledger.setQueueStatus({ id, status: \"approved\" });\n return jsonResponse({ ok: true }, 200, req);\n}\n\nexport async function rejectQueueRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n let body: { reason?: string } = {};\n try {\n body = (await req.json()) as { reason?: string };\n } catch {\n // empty body is fine\n }\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n ledger.setQueueStatus(\n body.reason ? { id, status: \"rejected\", notes: body.reason } : { id, status: \"rejected\" },\n );\n return jsonResponse({ ok: true }, 200, req);\n}\n\nexport async function approveAllRoute(req: Request): Promise<Response> {\n let body: { play?: string } = {};\n try {\n body = (await req.json()) as { play?: string };\n } catch {\n // empty body is fine\n }\n const ledger = getLedger();\n const n = ledger.approveAllPending(body.play ? { playName: body.play } : {});\n return jsonResponse({ approved: n }, 200, req);\n}\n\nexport async function drainQueueRoute(req: Request): Promise<Response> {\n let body: DrainRequest;\n try {\n body = (await req.json()) as DrainRequest;\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!body.playName) return jsonResponse({ error: \"playName required\" }, 400, req);\n const result = await drainQueue({\n playName: body.playName,\n limit: body.limit ?? 10,\n dryRun: !!body.dryRun,\n ...(body.senderCohort ? { senderCohort: body.senderCohort } : {}),\n ...(body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}),\n });\n const view: DrainResult = {\n drained: result.drained,\n sent: result.sent,\n errors: result.errors,\n };\n return jsonResponse(view, 200, req);\n}\n\n/**\n * Re-draft a single queue row in PREVIEW mode and overwrite its persisted\n * draft. Always dry-run: enrichment is skipped and nothing is sent, even\n * when the fresh draft is lint-clean. Lets the founder re-roll a held or\n * unsatisfying draft from /queue without leaving the page or risking a\n * send. The new draft replaces `last_draft_json` so the UI shows it on the\n * next queue refetch.\n */\nexport async function regenerateDraftRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n // Once sent, last_draft_json IS the frozen sent content — never overwrite it\n // with a fresh dry-run draft. Mirrors the guard in sendDraftRoute.\n if (row.status === \"sent\") return jsonResponse({ error: \"row already sent\" }, 400, req);\n // A send claimed the row but hasn't flipped status yet — refuse to start a\n // regenerate that would race it. Mirrors the claimQueueSendingMarker\n // primitive sendDraftRoute uses. Catches Scenario B (send started first).\n if (row.send_started_at != null) {\n return jsonResponse({ error: \"send in flight, can't regenerate\" }, 409, req);\n }\n\n let target: unknown;\n try {\n target = JSON.parse(row.payload_json);\n } catch {\n return jsonResponse({ error: \"row payload is not valid JSON\" }, 400, req);\n }\n\n // Carry through any per-play extras the payload happens to hold. Only\n // accelerator-batch needs senderCohort, which usually isn't on the row —\n // dispatchPlay then throws a clear error, surfaced here as a 400.\n const payloadObj = (target && typeof target === \"object\" ? target : {}) as Record<\n string,\n unknown\n >;\n const body: RunPlayRequest = {\n dryRun: true,\n targets: [target],\n ...(typeof payloadObj[\"senderCohort\"] === \"string\"\n ? { senderCohort: payloadObj[\"senderCohort\"] }\n : {}),\n ...(typeof payloadObj[\"freeForCohortOffer\"] === \"string\"\n ? { freeForCohortOffer: payloadObj[\"freeForCohortOffer\"] }\n : {}),\n };\n\n let drafted: Awaited<ReturnType<typeof dispatchPlay>>;\n try {\n drafted = await dispatchPlay(row.play_name, body);\n } catch (err) {\n return jsonResponse({ error: (err as Error).message }, 400, req);\n }\n const draft = drafted[0];\n if (!draft) return jsonResponse({ error: \"no draft produced\" }, 500, req);\n\n // TOCTOU close: re-read the row after the multi-second dispatchPlay await.\n // Catches Scenario A — a concurrent send completed during our LLM call.\n // Without this, setQueueDraft below would overwrite the canonical sent\n // body + wipe the receiptIds list.\n const fresh = ledger.getQueueRow(id);\n if (!fresh || fresh.status === \"sent\" || fresh.send_started_at != null) {\n return jsonResponse(\n { error: \"send completed (or started) during regenerate\" },\n 409,\n req,\n );\n }\n\n ledger.setQueueDraft({\n id,\n draft: {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: false,\n receiptIds: [],\n dryRun: true,\n ...(draft.enrichmentFailed ? { enrichmentFailed: true } : {}),\n },\n });\n\n const out: LastDraft = {\n subject: draft.subject,\n body: draft.body,\n flags: draft.flags,\n sent: false,\n receiptIds: [],\n dryRun: true,\n draftedAt: new Date().toISOString(),\n ...(draft.enrichmentFailed ? { enrichmentFailed: true } : {}),\n };\n return jsonResponse(out, 200, req);\n}\n\n/**\n * Send the row's already-reviewed draft VERBATIM — the persisted\n * `last_draft_json` subject/body, no LLM re-roll. This is the review-then-send\n * model: the founder regenerates until the draft is clean, then sends exactly\n * that. Routes through `sendDraftedEmail` (the canonical send: core sendEmail\n * applies HTML + from_name formatting, records the sequence event, upserts the\n * prospect), then enrolls the cadence and flips the row to `sent`. Requires a\n * clean (lint-flag-free), not-yet-sent draft.\n */\nexport async function sendDraftRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const id = Number.parseInt(params[\"id\"] ?? \"\", 10);\n if (!Number.isFinite(id)) return jsonResponse({ error: \"bad id\" }, 400, req);\n // Server is draining for shutdown — don't start a new send that the drain\n // would then have to wait on or abandon. Retry once it's back.\n if (isDraining()) {\n return jsonResponse({ error: \"server restarting — retry in a moment\" }, 503, req);\n }\n const ledger = getLedger();\n const row = ledger.getQueueRow(id);\n if (!row) return jsonResponse({ error: `row #${id} not found` }, 404, req);\n if (row.status === \"sent\") return jsonResponse({ error: \"row already sent\" }, 400, req);\n if (!row.last_draft_json) {\n return jsonResponse({ error: \"no draft to send — regenerate a draft first\" }, 400, req);\n }\n\n let parsed: Partial<LastDraft>;\n try {\n parsed = JSON.parse(row.last_draft_json) as Partial<LastDraft>;\n } catch {\n return jsonResponse({ error: \"stored draft is not valid JSON\" }, 400, req);\n }\n const subject = typeof parsed.subject === \"string\" ? parsed.subject : \"\";\n const body = typeof parsed.body === \"string\" ? parsed.body : \"\";\n const flags = Array.isArray(parsed.flags) ? parsed.flags : [];\n if (!subject || !body) {\n return jsonResponse({ error: \"stored draft is empty — regenerate first\" }, 400, req);\n }\n // Soft review flags (e.g. stale-event) hold a draft from auto-send but are\n // founder-overridable here — this IS the review-then-send step. Only genuine\n // blocking flags (lint, dedup) refuse a manual send.\n if (blockingFlags(flags).length > 0) {\n return jsonResponse(\n { error: \"draft has lint flags — regenerate to clear them before sending\" },\n 400,\n req,\n );\n }\n if (parsed.sent === true) return jsonResponse({ error: \"draft already sent\" }, 400, req);\n\n // Atomic claim of the sending marker — survives server restart so the UI's\n // spinner doesn't get stranded by a `bun --watch` reload mid-SDK-call. Stale\n // cutoff matches the cadence-send window (5 min); past that, a fresh click\n // can reclaim. Cleared automatically on success by setQueueStatus('sent',…);\n // explicitly in the catch on failure.\n const QUEUE_SEND_MAX_AGE_MS = 5 * 60 * 1000;\n const claimed = ledger.claimQueueSendingMarker({\n id,\n startedAtIso: new Date().toISOString(),\n staleCutoffIso: new Date(Date.now() - QUEUE_SEND_MAX_AGE_MS).toISOString(),\n });\n if (!claimed) {\n return jsonResponse(\n { error: \"already sending — wait for the in-flight send to complete\" },\n 409,\n req,\n );\n }\n\n let payload: Record<string, unknown> = {};\n try {\n const p = JSON.parse(row.payload_json);\n if (p && typeof p === \"object\") payload = p as Record<string, unknown>;\n } catch {\n // fall through — handled by the missing-email check below\n }\n const str = (k: string): string | null => (typeof payload[k] === \"string\" ? payload[k] : null);\n const email = str(\"email\") ?? str(\"founderEmail\");\n if (!email) return jsonResponse({ error: \"row has no recipient email\" }, 400, req);\n\n // sendDraftedEmail pushes dedup outcomes (\"already-enrolled\" / \"already-\n // contacted\") onto this array, so we can tell a deliberate skip apart from a\n // genuine send failure below.\n const sendFlags: string[] = [];\n let result: Awaited<ReturnType<typeof sendDraftedEmail>>;\n try {\n result = await sendDraftedEmail({\n playName: row.play_name,\n to: email,\n draft: { subject, body },\n flags: sendFlags,\n prospectMeta: {\n name: str(\"name\") ?? str(\"founderName\"),\n email,\n company: str(\"company\"),\n linkedin_url: str(\"linkedinUrl\"),\n phone: str(\"phone\"),\n source: row.play_name,\n },\n dryRun: false,\n });\n } catch (err) {\n // Release the marker so the founder can retry without waiting for the\n // cold-boot sweep. setQueueStatus would also clear it, but we only run\n // that on success.\n try {\n ledger.clearQueueSendingMarker(id);\n } catch {\n /* sweeper safety net */\n }\n // Daily caps exhausted — not a failure. Row stays approved with its\n // reviewed draft; 429 tells the UI \"try again tomorrow\".\n if (isSendDeferred(err)) {\n return jsonResponse({ error: (err as Error).message, deferred: true }, 429, req);\n }\n return jsonResponse({ error: (err as Error).message ?? \"send failed\" }, 400, req);\n }\n if (!result.sent) {\n try {\n ledger.clearQueueSendingMarker(id);\n } catch {\n /* sweeper safety net */\n }\n // Deliberate dedup skip (not a failure): this person was already first-\n // touched (same play, or another play via the cross-play guard). Mark the\n // row rejected with the reason so it leaves the actionable queue and the\n // founder isn't stuck re-clicking a Send that will never go through.\n const dedup = sendFlags.find((f) => f === \"already-contacted\" || f === \"already-enrolled\");\n if (dedup) {\n const reason =\n dedup === \"already-contacted\"\n ? \"already contacted via another play\"\n : \"already sent this play\";\n ledger.setQueueStatus({ id, status: \"rejected\", notes: `auto: ${reason} — not re-sent` });\n return jsonResponse({ error: `${reason} — not re-sent`, skipped: true, reason: dedup }, 409, req);\n }\n return jsonResponse({ error: \"send did not complete\" }, 500, req);\n }\n\n const prospect = ledger.findProspectByEmail(email);\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: row.play_name });\n ledger.setQueueStatus({ id, status: \"sent\" });\n ledger.setQueueDraft({\n id,\n draft: { subject, body, flags: [], sent: true, receiptIds: result.receiptIds, dryRun: false },\n });\n\n return jsonResponse({ sent: true, receiptIds: result.receiptIds }, 200, req);\n}\n","import { getLedger, type TriggerRow } from \"@oneshot-gtm/core\";\nimport {\n checkReadiness,\n effectiveIntervalMs,\n fireTriggerNow,\n getTriggerRunningSince,\n isTriggerRunning,\n storedTriggerConfig,\n TRIGGERS,\n type Readiness,\n type TriggerSpec,\n} from \"@oneshot-gtm/find\";\nimport type { RunTriggerResult, TriggerView } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nexport function toView(\n name: string,\n defaultIntervalMs: number,\n row: TriggerRow | null,\n spec: TriggerSpec | null,\n): TriggerView {\n let lastSummary: unknown = null;\n if (row?.last_run_summary) {\n try {\n lastSummary = JSON.parse(row.last_run_summary);\n } catch {\n lastSummary = row.last_run_summary;\n }\n }\n let config: Record<string, unknown> | null = null;\n if (row?.config_json) {\n try {\n const parsed = JSON.parse(row.config_json) as unknown;\n if (parsed && typeof parsed === \"object\") config = parsed as Record<string, unknown>;\n } catch {\n config = null;\n }\n }\n const defaultEnabled = spec ? spec.enabledByDefault !== false : true;\n const intervalMs = spec ? effectiveIntervalMs(spec, config) : defaultIntervalMs;\n const runningSinceMs = getTriggerRunningSince(name);\n // Explicit annotation keeps the discriminated-union narrowing intact\n // (the literal { ready: true } branch would otherwise widen the union).\n const readiness: Readiness = spec\n ? checkReadiness(spec, config ?? spec.defaultConfig)\n : { ready: true };\n return {\n name,\n enabled: row ? Boolean(row.enabled) : defaultEnabled,\n defaultIntervalMs,\n intervalMs,\n config,\n defaultConfig: spec ? spec.defaultConfig : null,\n lastPolledAt: row?.last_polled_at ?? null,\n lastRunSummary: lastSummary,\n running: isTriggerRunning(name),\n runningSince: runningSinceMs != null ? new Date(runningSinceMs).toISOString() : null,\n ready: readiness.ready,\n notReadyReason: readiness.ready ? null : readiness.reason,\n };\n}\n\nexport function listTriggersRoute(req: Request): Response {\n const ledger = getLedger();\n const rows = ledger.listTriggers();\n const byName = new Map(rows.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const views: TriggerView[] = [];\n for (const spec of TRIGGERS) {\n seen.add(spec.name);\n views.push(toView(spec.name, spec.defaultIntervalMs, byName.get(spec.name) ?? null, spec));\n }\n // Surface any historical triggers stored in the ledger that no longer exist\n // in the registry (e.g. a deprecated cohort) so the founder can disable them.\n for (const row of rows) {\n if (seen.has(row.name)) continue;\n views.push(toView(row.name, 24 * 3600 * 1000, row, null));\n }\n return jsonResponse({ triggers: views }, 200, req);\n}\n\nexport async function setTriggerEnabledRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n let body: { enabled?: boolean } = {};\n try {\n body = (await req.json()) as { enabled?: boolean };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (typeof body.enabled !== \"boolean\") {\n return jsonResponse({ error: \"enabled (boolean) required\" }, 400, req);\n }\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n const spec = TRIGGERS.find((t) => t.name === name) ?? null;\n // Readiness gate: block *enabling* an unready trigger so the scheduler\n // doesn't sit in a loop skipping it every tick. Disabling is always allowed.\n if (body.enabled && spec) {\n const config = storedTriggerConfig(stored, spec);\n const readiness = checkReadiness(spec, config);\n if (!readiness.ready) {\n return jsonResponse(\n {\n error: `trigger '${name}' not ready: ${readiness.reason}`,\n name,\n reason: readiness.reason,\n },\n 409,\n req,\n );\n }\n }\n if (!stored) {\n if (!spec) return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(spec.defaultConfig),\n enabled: body.enabled,\n });\n } else {\n ledger.setTriggerEnabled(name, body.enabled);\n }\n return jsonResponse({ ok: true, name, enabled: body.enabled }, 200, req);\n}\n\nexport async function setTriggerConfigRoute(\n req: Request,\n params: Record<string, string>,\n): Promise<Response> {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n let body: { config?: unknown } = {};\n try {\n body = (await req.json()) as { config?: unknown };\n } catch {\n return jsonResponse({ error: \"invalid JSON body\" }, 400, req);\n }\n if (!body.config || typeof body.config !== \"object\") {\n return jsonResponse({ error: \"config (object) required\" }, 400, req);\n }\n const ledger = getLedger();\n const stored = ledger.getTrigger(name);\n if (!stored) {\n const spec = TRIGGERS.find((t) => t.name === name);\n if (!spec) return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n ledger.upsertTrigger({\n name,\n configJson: JSON.stringify(body.config),\n enabled: true,\n });\n } else {\n ledger.setTriggerConfig(name, JSON.stringify(body.config));\n }\n return jsonResponse({ ok: true, name }, 200, req);\n}\n\n/** Fire-and-forget: 202 on kick-off, 409 if already running. UI polls `GET /api/triggers`. */\nexport function runTriggerRoute(req: Request, params: Record<string, string>): Response {\n const name = params[\"name\"];\n if (!name) return jsonResponse({ error: \"name required\" }, 400, req);\n if (!TRIGGERS.some((t) => t.name === name)) {\n return jsonResponse({ error: `unknown trigger '${name}'` }, 404, req);\n }\n try {\n fireTriggerNow(name);\n } catch (err) {\n const message = (err as Error).message ?? \"failed to fire\";\n if (message.includes(\"already running\")) {\n return jsonResponse({ error: message, name, running: true }, 409, req);\n }\n if (message.startsWith(\"not ready:\")) {\n const reason = message.slice(\"not ready:\".length).trim();\n return jsonResponse({ error: message, name, reason, ready: false }, 409, req);\n }\n return jsonResponse({ error: message }, 500, req);\n }\n const view: RunTriggerResult = {\n name,\n fired: true,\n pending: true,\n result: null,\n error: null,\n };\n return jsonResponse(view, 202, req);\n}\n","import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { health } from \"./api/health.ts\";\nimport { homeMetrics } from \"./api/home.ts\";\nimport {\n listCadences,\n getCadence,\n stopCadence,\n previewCadenceStepRoute,\n sendCadenceStepRoute,\n previewCadenceBatchRoute,\n sendCadenceBatchRoute,\n} from \"./api/cadences.ts\";\nimport { listReceipts, getReceipt } from \"./api/receipts.ts\";\nimport { draftReplyRoute, listInboxRoute, saveDraftRoute, sendReplyRoute } from \"./api/inbox.ts\";\nimport { listPlays, setCadenceRoute } from \"./api/plays.ts\";\nimport { measureCac, measureRocs, measureRocsByGoal, recordOutcome } from \"./api/measure.ts\";\nimport { setup, getSetupStatus } from \"./api/setup.ts\";\nimport { gmailAuthCallbackRoute, startGmailAuthRoute } from \"./api/gmail-auth.ts\";\nimport { deriveIcpRoute } from \"./api/derive-icp.ts\";\nimport { strategistRoute } from \"./api/strategist.ts\";\nimport { doctor } from \"./api/doctor.ts\";\nimport { runPlay } from \"./api/run.ts\";\nimport { getRunRoute } from \"./api/runs.ts\";\nimport {\n approveAllRoute,\n approveQueueRoute,\n drainQueueRoute,\n listQueueRoute,\n regenerateDraftRoute,\n rejectQueueRoute,\n sendDraftRoute,\n} from \"./api/queue.ts\";\nimport {\n listTriggersRoute,\n runTriggerRoute,\n setTriggerConfigRoute,\n setTriggerEnabledRoute,\n} from \"./api/triggers.ts\";\n\ninterface ServerOptions {\n port: number;\n}\n\ninterface RouteHandler {\n (req: Request, params: Record<string, string>): Promise<Response> | Response;\n}\n\ninterface RouteEntry {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n handler: RouteHandler;\n}\n\nfunction route(method: string, pattern: string, handler: RouteHandler): RouteEntry {\n const paramNames: string[] = [];\n const regexStr = pattern.replace(/:(\\w+)/g, (_, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n return { method, pattern: new RegExp(`^${regexStr}$`), paramNames, handler };\n}\n\nconst routes: RouteEntry[] = [\n route(\"GET\", \"/api/health\", health),\n route(\"GET\", \"/api/home\", homeMetrics),\n route(\"GET\", \"/api/cadences\", listCadences),\n route(\"GET\", \"/api/cadences/:id\", getCadence),\n route(\"POST\", \"/api/cadences/:id/stop\", stopCadence),\n route(\"POST\", \"/api/cadences/:id/preview-next\", previewCadenceStepRoute),\n route(\"POST\", \"/api/cadences/:id/send-next\", sendCadenceStepRoute),\n route(\"POST\", \"/api/cadences/preview-batch\", previewCadenceBatchRoute),\n route(\"POST\", \"/api/cadences/send-batch\", sendCadenceBatchRoute),\n route(\"GET\", \"/api/receipts\", listReceipts),\n route(\"GET\", \"/api/receipts/:id\", getReceipt),\n route(\"GET\", \"/api/inbox\", listInboxRoute),\n route(\"POST\", \"/api/inbox/draft-reply\", draftReplyRoute),\n route(\"POST\", \"/api/inbox/draft\", saveDraftRoute),\n route(\"POST\", \"/api/inbox/reply\", sendReplyRoute),\n route(\"GET\", \"/api/plays\", listPlays),\n route(\"POST\", \"/api/plays/:name/cadence\", setCadenceRoute),\n route(\"GET\", \"/api/measure/cac\", measureCac),\n route(\"GET\", \"/api/measure/rocs\", measureRocs),\n route(\"GET\", \"/api/measure/rocs-by-goal\", measureRocsByGoal),\n route(\"POST\", \"/api/measure/outcome\", recordOutcome),\n route(\"GET\", \"/api/setup\", getSetupStatus),\n route(\"POST\", \"/api/setup\", setup),\n route(\"GET\", \"/api/gmail/auth/start\", startGmailAuthRoute),\n route(\"GET\", \"/api/gmail/auth/callback\", gmailAuthCallbackRoute),\n route(\"POST\", \"/api/setup/derive-icp\", deriveIcpRoute),\n route(\"POST\", \"/api/strategist/stream\", strategistRoute),\n route(\"GET\", \"/api/doctor\", doctor),\n route(\"POST\", \"/api/run/:playName\", runPlay),\n route(\"GET\", \"/api/runs/:id\", getRunRoute),\n route(\"GET\", \"/api/queue\", listQueueRoute),\n route(\"POST\", \"/api/queue/approve-all\", approveAllRoute),\n route(\"POST\", \"/api/queue/drain\", drainQueueRoute),\n route(\"POST\", \"/api/queue/:id/approve\", approveQueueRoute),\n route(\"POST\", \"/api/queue/:id/reject\", rejectQueueRoute),\n route(\"POST\", \"/api/queue/:id/regenerate\", regenerateDraftRoute),\n route(\"POST\", \"/api/queue/:id/send-draft\", sendDraftRoute),\n route(\"GET\", \"/api/triggers\", listTriggersRoute),\n route(\"POST\", \"/api/triggers/:name/enabled\", setTriggerEnabledRoute),\n route(\"POST\", \"/api/triggers/:name/config\", setTriggerConfigRoute),\n route(\"POST\", \"/api/triggers/:name/run\", runTriggerRoute),\n];\n\nfunction findRoute(req: Request): { handler: RouteHandler; params: Record<string, string> } | null {\n const url = new URL(req.url);\n for (const r of routes) {\n if (r.method !== req.method) continue;\n const m = r.pattern.exec(url.pathname);\n if (!m) continue;\n const params: Record<string, string> = {};\n r.paramNames.forEach((name, i) => {\n params[name] = decodeURIComponent(m[i + 1] ?? \"\");\n });\n return { handler: r.handler, params };\n }\n return null;\n}\n\nfunction getStaticDir(): string | null {\n // Layouts we might run from:\n // 1. Source dev: apps/server/src/server.ts → ../../web/dist\n // 2. Bundle: apps/server/dist/bin.mjs → ../../web/dist\n // 3. npm publish: <pkg>/dist/bin.mjs → ./web (we copy apps/web/dist here)\n const here = fileURLToPath(new URL(\".\", import.meta.url));\n const candidates = [\n join(here, \"..\", \"..\", \"web\", \"dist\"),\n join(here, \"..\", \"..\", \"..\", \"web\", \"dist\"),\n join(here, \"web\"),\n ];\n for (const c of candidates) {\n if (existsSync(join(c, \"index.html\"))) return c;\n }\n return null;\n}\n\nasync function serveStatic(staticDir: string, pathname: string): Promise<Response | null> {\n const root = resolve(staticDir);\n const rel = pathname === \"/\" ? \"index.html\" : pathname.replace(/^\\/+/, \"\");\n const candidate = resolve(root, rel);\n // Reject anything that escapes the static dir. `resolve` collapses `..`\n // segments so the prefix check catches both raw `..` and encoded variants.\n if (candidate !== root && !candidate.startsWith(`${root}/`)) return null;\n if (existsSync(candidate)) {\n return new Response(Bun.file(candidate));\n }\n // SPA fallback: serve index.html for non-asset paths (paths without a dot).\n if (!rel.includes(\".\")) {\n return new Response(Bun.file(join(root, \"index.html\")));\n }\n return null;\n}\n\nexport function buildFetchHandler(): (req: Request) => Promise<Response> | Response {\n const staticDir = getStaticDir();\n const viteDevUrl = process.env[\"VITE_DEV_SERVER_URL\"] ?? null;\n\n return async function fetchHandler(req) {\n const url = new URL(req.url);\n\n // DNS-rebinding defense: reject any request whose Host header isn't a\n // loopback name. An attacker who points evil.com at 127.0.0.1 still\n // sends Host: evil.com to the browser, which we reject here.\n if (!isLoopbackHost(req.headers.get(\"host\"))) {\n return new Response(\"forbidden: non-loopback host\", {\n status: 403,\n headers: { \"content-type\": \"text/plain\" },\n });\n }\n\n // CORS for vite dev server (different port). Non-loopback origins get\n // an empty header set from corsHeaders() → browser blocks both\n // preflight and the response, preventing CSRF-style side effects on\n // mutating endpoints (e.g. POST /api/run/$playName triggering spend).\n if (req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: corsHeaders(req),\n });\n }\n\n if (url.pathname.startsWith(\"/api/\")) {\n const match = findRoute(req);\n if (!match) {\n return jsonResponse({ error: \"not found\", path: url.pathname }, 404, req);\n }\n try {\n const res = await match.handler(req, match.params);\n // Inject CORS headers if not already set\n for (const [k, v] of Object.entries(corsHeaders(req))) {\n if (!res.headers.has(k)) res.headers.set(k, v);\n }\n return res;\n } catch (err) {\n return jsonResponse({ error: (err as Error).message ?? \"internal error\" }, 500, req);\n }\n }\n\n // Dev: the real UI is served by Vite (with HMR), so redirect non-API\n // requests there — preserving the path so a bookmarked deep-link like\n // :3030/cadences lands on :5173/cadences. This takes precedence over the\n // built `dist`: in dev that bundle is stale (frontend changes only land in\n // `dist` on a rebuild), and serving it silently is a footgun.\n if (viteDevUrl) {\n return Response.redirect(`${viteDevUrl}${url.pathname}${url.search}`, 302);\n }\n\n // Static / SPA serving (production / built dashboard).\n if (staticDir) {\n const r = await serveStatic(staticDir, url.pathname);\n if (r) return r;\n }\n\n return new Response(\n \"oneshot-gtm server running. Build the web app to see the dashboard, or set VITE_DEV_SERVER_URL.\",\n { status: 200, headers: { \"content-type\": \"text/plain\" } },\n );\n };\n}\n\n/** Shared options; idleTimeout 255 is the max — Bun defaults to 10s which is short for sync handlers. */\nexport const SERVER_BASE_OPTS = { idleTimeout: 255 } as const;\n\nexport async function startServer(\n opts: ServerOptions,\n): Promise<{ url: string; server: ReturnType<typeof Bun.serve> }> {\n const server = Bun.serve({\n port: opts.port,\n hostname: \"127.0.0.1\",\n ...SERVER_BASE_OPTS,\n fetch: buildFetchHandler(),\n });\n\n return { url: `http://127.0.0.1:${server.port}`, server };\n}\n\nfunction isLoopbackOrigin(origin: string): boolean {\n // Empty origin = same-origin request (curl, server-side fetch); allow.\n if (origin === \"\") return true;\n return (\n origin.startsWith(\"http://127.0.0.1\") ||\n origin.startsWith(\"http://localhost\") ||\n origin.startsWith(\"http://[::1]\")\n );\n}\n\nfunction isLoopbackHost(host: string | null): boolean {\n if (!host) return false;\n const hostname = host.replace(/:\\d+$/, \"\").toLowerCase();\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\";\n}\n\nfunction corsHeaders(req: Request): Record<string, string> {\n // Loopback-only. Non-loopback origins get NO Access-Control-* headers,\n // which makes the browser refuse both the preflight and any cross-origin\n // response read.\n const origin = req.headers.get(\"origin\") ?? \"\";\n if (!isLoopbackOrigin(origin)) {\n return {};\n }\n return {\n \"Access-Control-Allow-Origin\": origin || \"http://127.0.0.1\",\n \"Access-Control-Allow-Methods\": \"GET,POST,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"content-type\",\n Vary: \"Origin\",\n };\n}\n\nexport function jsonResponse(body: unknown, status = 200, req?: Request): Response {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json; charset=utf-8\",\n };\n if (req) Object.assign(headers, corsHeaders(req));\n return new Response(JSON.stringify(body), { status, headers });\n}\n","import { logEvent } from \"@oneshot-gtm/core\";\nimport { nextSleepMs, runDueTriggers, runPendingRetries } from \"@oneshot-gtm/find\";\nimport { pollInboxReplies } from \"@oneshot-gtm/plays\";\n\n/**\n * Background scheduler that polls registered triggers on their interval and\n * fires due ones. Runs inside the dashboard server process so the founder\n * doesn't have to keep `bun run cli -- find watch` open in a second terminal\n * for enabled triggers to actually execute.\n *\n * Safety:\n * - Per-trigger atomic claim (in `runDueTriggers`) prevents double-spend if\n * a manual /api/triggers/:name/run click races with a scheduled tick.\n * - Tick-level try/catch keeps a corrupted ledger row or unexpected throw\n * from permanently killing the loop; backs off 60s before retrying.\n * - In-flight finder runs that haven't returned when the process exits get\n * killed mid-run; the cold-boot `sweepStaleRunningTriggers` cleans up\n * the orphaned `running_started_at` markers on the next start.\n *\n * The tick also polls the inbox for prospect replies and stops their cadences\n * (`pollInboxReplies`). That detection otherwise only ran when the founder\n * manually advanced a cadence, so a reply could sit unrecognized for days while\n * the sequence kept emailing. It's read-only apart from the status flip — no\n * step is sent — so it never spends. Tick cadence is clamped to REPLY_POLL_MAX\n * so replies surface within minutes even when no trigger is due for an hour.\n */\nexport interface SchedulerHandle {\n stop(): void;\n}\n\nconst FIRST_TICK_DELAY_MS = 5_000;\nconst ERROR_BACKOFF_MS = 60_000;\nconst REPLY_POLL_MAX_MS = 5 * 60_000;\n\nexport function startScheduler(): SchedulerHandle {\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const tick = async (): Promise<void> => {\n if (cancelled) return;\n try {\n const outcomes = await runDueTriggers();\n const fired = outcomes.filter((o) => o.fired).length;\n // Reply detection is isolated: an inbox outage must not skip trigger\n // scheduling (or vice-versa), and it never sends, so it can't double-spend.\n let repliesDetected = 0;\n try {\n repliesDetected = (await pollInboxReplies()).repliesDetected;\n } catch (err) {\n logEvent(\n \"scheduler.reply_poll.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n }\n // Drain outage-deferred candidates (time-windowed finders) now the\n // backend may be healthy again. Isolated like the reply poll — its\n // failure must not skip trigger scheduling.\n try {\n await runPendingRetries();\n } catch (err) {\n logEvent(\n \"scheduler.pending_retry.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"warn\",\n );\n }\n logEvent(\"scheduler.tick.done\", { fired, repliesDetected, source: \"server\" });\n if (cancelled) return;\n const sleepMs = Math.min(nextSleepMs(outcomes), REPLY_POLL_MAX_MS);\n timer = setTimeout(() => void tick(), sleepMs);\n } catch (err) {\n logEvent(\n \"scheduler.tick.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n if (!cancelled) timer = setTimeout(() => void tick(), ERROR_BACKOFF_MS);\n }\n };\n\n // Short initial delay so the HTTP server is bound and the cold-boot sweep\n // has finished writing `killed_by_restart` summaries before the first tick.\n timer = setTimeout(() => void tick(), FIRST_TICK_DELAY_MS);\n\n return {\n stop(): void {\n cancelled = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n },\n };\n}\n","import open from \"open\";\nimport {\n activeSendCount,\n beginDraining,\n getLedger,\n logEvent,\n waitForSendsToDrain,\n} from \"@oneshot-gtm/core\";\nimport { buildFetchHandler, SERVER_BASE_OPTS, startServer } from \"./server.ts\";\nimport { startScheduler, type SchedulerHandle } from \"./scheduler.ts\";\n\n// Runtime guard: this binary depends on Bun (bun:sqlite, Bun.serve, Bun.stdin).\n// If invoked under plain node, fail loudly with an install hint.\nif (typeof (globalThis as { Bun?: unknown }).Bun === \"undefined\") {\n process.stderr.write(\n \"oneshot-gtm-server requires the Bun runtime.\\n\" +\n \"Install: curl -fsSL https://bun.sh/install | bash\\n\" +\n \"Re-run: bunx oneshot-gtm-server\\n\",\n );\n process.exit(1);\n}\n\nconst port = Number.parseInt(process.env[\"PORT\"] ?? \"3030\", 10);\nconst noBrowser = process.env[\"ONESHOT_GTM_NO_BROWSER\"] === \"1\";\n\n// Cache the server on globalThis so Bun's `--hot` re-execution (same\n// process) can swap handlers via `server.reload({fetch})` instead of\n// rebinding the port, which would fail with EADDRINUSE.\ntype BunServer = Awaited<ReturnType<typeof startServer>>[\"server\"];\nconst cache = globalThis as {\n __oneshotGtmServer?: BunServer;\n __oneshotGtmScheduler?: SchedulerHandle;\n};\n\nif (cache.__oneshotGtmServer) {\n // Hot reload: keep the existing scheduler running. The reloaded module\n // graph picks up source changes on its next tick (5s-1h away).\n cache.__oneshotGtmServer.reload({\n ...SERVER_BASE_OPTS,\n fetch: buildFetchHandler(),\n });\n process.stdout.write(`\\n oneshot-gtm dashboard: http://127.0.0.1:${port} (reloaded)\\n\\n`);\n} else {\n // Cold boot only — sweep any trigger rows that were marked running by a\n // previous process that never got to call updateTriggerLastPoll\n // (bun --watch re-exec, OS reboot, OOM kill, hung SDK call when the\n // process was killed). Writes a `killed_by_restart` last_run_summary so\n // the UI shows the truth instead of frozen-from-an-hour-ago state.\n //\n // `maxAgeMs: 0` is intentional and important. At cold boot, any non-null\n // `running_started_at` is by definition a zombie — the previous process is\n // gone and an async finder run can't outlive its process. The MAX_RUN_AGE_MS\n // freshness gate (4h) is for live UI reads where a long-running finder\n // shouldn't disappear from the spinner mid-run. Applying it to the boot\n // sweep would let a row that crashed 30 minutes ago survive across reboots\n // and block re-runs with `409 already running` — exactly the bug we hit.\n //\n // Hot reload (the if-branch above) skips the sweep because it preserves\n // the event loop, so any genuinely in-flight run continues.\n //\n // Wrapped — a SQL hiccup here must not take down the server. Boot\n // continuing on stale ledger state is strictly better than refusing to\n // start because of a cleanup detail.\n try {\n const swept = getLedger().sweepStaleRunningTriggers({\n now: new Date(),\n maxAgeMs: 0,\n });\n for (const s of swept) {\n logEvent(\"trigger.killed_by_restart\", { name: s.name, age_ms: s.ageMs }, \"warn\");\n process.stdout.write(` swept stale run: ${s.name} (${Math.round(s.ageMs / 1000)}s old)\\n`);\n }\n } catch (err) {\n logEvent(\n \"trigger.sweep.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(` warn: stale-run sweep failed: ${(err as Error).message}\\n`);\n }\n\n // Same idea for fire-and-forget cadence sends. Any cadence_state row whose\n // `sending_started_at` predates this process was either (a) the previous\n // process succeeded — in which case the sequence_events row landed and the\n // sweep just clears the now-meaningless marker, or (b) the previous process\n // died mid-SDK-call — in which case the marker is stranded, the draft is\n // still there, and the founder can re-click Send. The sweeper logs both\n // cases so the founder can see \"send was lost\" in events.jsonl.\n try {\n const swept = getLedger().sweepStaleCadenceSends({\n now: new Date(),\n maxAgeMs: 0,\n });\n for (const s of swept) {\n logEvent(\n s.actuallySent ? \"cadence.send.cleared_marker\" : \"cadence.send.killed_by_restart\",\n {\n prospect_id: s.prospectId,\n play_name: s.playName,\n age_ms: s.ageMs,\n actually_sent: s.actuallySent,\n },\n s.actuallySent ? \"info\" : \"warn\",\n );\n if (!s.actuallySent) {\n process.stdout.write(\n ` swept stale cadence send: ${s.playName} (prospect ${s.prospectId}, ${Math.round(s.ageMs / 1000)}s old) — re-click Send to retry\\n`,\n );\n }\n }\n } catch (err) {\n logEvent(\n \"cadence.send.sweep_failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(\n ` warn: stale-send sweep failed: ${(err as Error).message}\\n`,\n );\n }\n\n // Mirror of the cadence sweep for `target_queue.send_started_at`. A queue\n // row with a marker from a previous process either (a) had its SDK call\n // complete before the kill — `status === 'sent'`, we just clear the marker —\n // or (b) was stranded mid-call — clear the marker, the draft is still on the\n // row for retry. Either way: cold boot wipes every existing marker.\n try {\n const swept = getLedger().sweepStaleQueueSends({\n now: new Date(),\n maxAgeMs: 0,\n });\n for (const s of swept) {\n logEvent(\n s.actuallySent ? \"queue.send.cleared_marker\" : \"queue.send.killed_by_restart\",\n {\n queue_id: s.id,\n age_ms: s.ageMs,\n actually_sent: s.actuallySent,\n },\n s.actuallySent ? \"info\" : \"warn\",\n );\n if (!s.actuallySent) {\n process.stdout.write(\n ` swept stale queue send: row ${s.id} (${Math.round(s.ageMs / 1000)}s old) — re-click Send to retry\\n`,\n );\n }\n }\n } catch (err) {\n logEvent(\n \"queue.send.sweep_failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(\n ` warn: stale queue-send sweep failed: ${(err as Error).message}\\n`,\n );\n }\n\n // Cold-boot sweep for /run dispatches: any run still marked 'running' from\n // a previous process is a zombie — the SSE stream is gone, the dispatch was\n // killed. Flipping to 'interrupted' lets the /run page show a truthful\n // banner instead of an eternal \"running\" view. Counters on the row are\n // already accurate from the per-event appends, so the founder still sees\n // what landed before the crash.\n try {\n const swept = getLedger().sweepStaleRuns({ now: new Date(), maxAgeMs: 0 });\n for (const s of swept) {\n logEvent(\n \"run.killed_by_restart\",\n { run_id: s.id, play_name: s.playName, age_ms: s.ageMs },\n \"warn\",\n );\n process.stdout.write(\n ` swept stale run: #${s.id} ${s.playName} (${Math.round(s.ageMs / 1000)}s old)\\n`,\n );\n }\n } catch (err) {\n logEvent(\n \"run.sweep_failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(` warn: stale-run sweep failed: ${(err as Error).message}\\n`);\n }\n\n const { url, server } = await startServer({ port });\n cache.__oneshotGtmServer = server;\n\n // Background trigger scheduler — polls due triggers, fires them, sleeps\n // for `nextSleepMs` between ticks. Replaces the need to run a separate\n // `bun run cli -- find watch` daemon. Survives `bun --hot` re-execs by\n // staying anchored to globalThis.\n //\n // Wrapped: scheduler init failure must not take down the server (founder\n // can still drive triggers manually via /queue Run). The cold-boot sweep\n // pattern above does the same thing for ledger-init resilience.\n let scheduler: SchedulerHandle | null = null;\n try {\n scheduler = startScheduler();\n cache.__oneshotGtmScheduler = scheduler;\n } catch (err) {\n logEvent(\n \"scheduler.start.failed\",\n { message_120: ((err as Error).message ?? \"\").slice(0, 120) },\n \"error\",\n );\n process.stderr.write(` warn: scheduler failed to start: ${(err as Error).message}\\n`);\n }\n\n process.stdout.write(`\\n oneshot-gtm dashboard: ${url}\\n\\n`);\n\n if (!noBrowser) {\n try {\n await open(url);\n } catch {\n // ignore — terminal output already shows the URL.\n }\n }\n\n // Graceful drain: on a signal, stop taking new sends and wait for any\n // in-flight send to finish writing its sequence_events row before exiting —\n // closing the window where a sent-but-unrecorded email could be re-sent on\n // retry. A SIGKILL skips this; the cold-boot sweep above is the backstop.\n // Default 30s; a long voice call past that is force-exited and reconciled.\n const drainTimeoutMs = Number.parseInt(\n process.env[\"ONESHOT_GTM_DRAIN_TIMEOUT_MS\"] ?? \"30000\",\n 10,\n );\n let shuttingDown = false;\n const shutdown = async (signal: string): Promise<void> => {\n // Second signal while draining → the operator wants out now. Honor it.\n if (shuttingDown) {\n process.stdout.write(\"\\n forced exit.\\n\");\n process.exit(1);\n }\n shuttingDown = true;\n beginDraining();\n if (scheduler) scheduler.stop();\n const inflight = activeSendCount();\n if (inflight > 0) {\n process.stdout.write(\n `\\n ${signal} — draining ${inflight} in-flight send(s)... (Ctrl-C again to force)\\n`,\n );\n const { drained, remaining } = await waitForSendsToDrain({ timeoutMs: drainTimeoutMs });\n if (drained) {\n process.stdout.write(\" drained — all sends recorded.\\n\");\n } else {\n logEvent(\"server.drain.timeout\", { remaining, timeout_ms: drainTimeoutMs }, \"warn\");\n process.stdout.write(\n ` WARN: ${remaining} send(s) still in-flight after ${drainTimeoutMs}ms — exiting; boot sweep will reconcile.\\n`,\n );\n }\n } else {\n process.stdout.write(\"\\n shutting down...\\n\");\n }\n server.stop();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAgB,oBAAoB,KAA6C;AAC/E,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CACxE,QAAO;AAET,SAAO;SACD;AACN,SAAO;;;;;ACFX,MAAM,aAAa,QAAQ,IAAI,qBAAqB,MAAM,IAAI,KAAK,SAAS,EAAE,eAAe;AAC7F,MAAM,cAAc,KAAK,YAAY,cAAc;AACnD,MAAM,eAAe,KAAK,YAAY,OAAO;AAE7C,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAM,WAA0B;CAC9B,YAAY;CACZ,aAAa;CACb,UAAU;CACV,kBAAkB;CAClB,aAAa;CACb,cAAc;CACd,iBAAiB;CACjB,eAAe;CACf,eAAe;CACf,eAAe;CACf,iBAAiB;CACjB,aAAa;CACb,kBAAkB;CAClB,oBAAoB;CACpB,kBAAkB;CAClB,UAAU;CACV,iBAAiB;CACjB,UAAU;CACX;AAED,SAAgB,YAAoB;AAClC,QAAO;;AAGT,SAAS,kBAAwB;AAC/B,KAAI,CAAC,WAA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