oneshot-gtm-server 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +3318 -1084
- package/dist/bin.mjs.map +1 -1
- package/dist/web/assets/Badge-Bl9eBoUa.js +2 -0
- package/dist/web/assets/Badge-Bl9eBoUa.js.map +1 -0
- package/dist/web/assets/Button-D1rFtlez.js +2 -0
- package/dist/web/assets/Button-D1rFtlez.js.map +1 -0
- package/dist/web/assets/EmptyNote-CZaRRtmD.js +2 -0
- package/dist/web/assets/{EmptyNote-C4quX2dg.js.map → EmptyNote-CZaRRtmD.js.map} +1 -1
- package/dist/web/assets/Field-DJ9InfU_.js +2 -0
- package/dist/web/assets/Field-DJ9InfU_.js.map +1 -0
- package/dist/web/assets/{Modal-BVbdN0gj.js → Modal-CturxR2v.js} +2 -2
- package/dist/web/assets/{Modal-BVbdN0gj.js.map → Modal-CturxR2v.js.map} +1 -1
- package/dist/web/assets/Skeleton-CHzR-B21.js +2 -0
- package/dist/web/assets/{Skeleton-D7Z-VTMo.js.map → Skeleton-CHzR-B21.js.map} +1 -1
- package/dist/web/assets/cadences-D9cvMlfq.js +2 -0
- package/dist/web/assets/cadences-D9cvMlfq.js.map +1 -0
- package/dist/web/assets/chevron-down-J-vUa4uQ.js +2 -0
- package/dist/web/assets/chevron-down-J-vUa4uQ.js.map +1 -0
- package/dist/web/assets/chevron-right-DAxZefV9.js +2 -0
- package/dist/web/assets/chevron-right-DAxZefV9.js.map +1 -0
- package/dist/web/assets/inbox-Dsg3_bXr.js +2 -0
- package/dist/web/assets/inbox-Dsg3_bXr.js.map +1 -0
- package/dist/web/assets/index-BVno9lTD.js +60 -0
- package/dist/web/assets/index-BVno9lTD.js.map +1 -0
- package/dist/web/assets/index-Ya_svHJk.css +2 -0
- package/dist/web/assets/loader-circle-B_w_dqVu.js +2 -0
- package/dist/web/assets/loader-circle-B_w_dqVu.js.map +1 -0
- package/dist/web/assets/{measure-DLFAK1ZQ.js → measure-CV7Towgf.js} +2 -2
- package/dist/web/assets/{measure-DLFAK1ZQ.js.map → measure-CV7Towgf.js.map} +1 -1
- package/dist/web/assets/plays-BSlXDDDK.js +2 -0
- package/dist/web/assets/plays-BSlXDDDK.js.map +1 -0
- package/dist/web/assets/queue-BHKT-qjx.js +2 -0
- package/dist/web/assets/queue-BHKT-qjx.js.map +1 -0
- package/dist/web/assets/receipts-opTtY1t7.js +2 -0
- package/dist/web/assets/receipts-opTtY1t7.js.map +1 -0
- package/dist/web/assets/refresh-cw-BO0blIzU.js +2 -0
- package/dist/web/assets/refresh-cw-BO0blIzU.js.map +1 -0
- package/dist/web/assets/routes-BgDvPuJP.js +2 -0
- package/dist/web/assets/routes-BgDvPuJP.js.map +1 -0
- package/dist/web/assets/run._playName-CQU-5e18.js +5 -0
- package/dist/web/assets/run._playName-CQU-5e18.js.map +1 -0
- package/dist/web/assets/send-9D8YeqmY.js +2 -0
- package/dist/web/assets/send-9D8YeqmY.js.map +1 -0
- package/dist/web/assets/setup-CqCzlBdR.js +2 -0
- package/dist/web/assets/setup-CqCzlBdR.js.map +1 -0
- package/dist/web/assets/summarizeRun-D5Pd2arb.js +2 -0
- package/dist/web/assets/summarizeRun-D5Pd2arb.js.map +1 -0
- package/dist/web/index.html +3 -3
- package/package.json +2 -2
- package/dist/web/assets/Button-DPVQuma9.js +0 -2
- package/dist/web/assets/Button-DPVQuma9.js.map +0 -1
- package/dist/web/assets/EmptyNote-C4quX2dg.js +0 -2
- package/dist/web/assets/Field-D9WpcA8z.js +0 -2
- package/dist/web/assets/Field-D9WpcA8z.js.map +0 -1
- package/dist/web/assets/Skeleton-D7Z-VTMo.js +0 -2
- package/dist/web/assets/cadences-B8mwchUk.js +0 -2
- package/dist/web/assets/cadences-B8mwchUk.js.map +0 -1
- package/dist/web/assets/index-DkobhtBa.js +0 -60
- package/dist/web/assets/index-DkobhtBa.js.map +0 -1
- package/dist/web/assets/index-Dovjfyuq.css +0 -2
- package/dist/web/assets/plays-BUfo3QKZ.js +0 -2
- package/dist/web/assets/plays-BUfo3QKZ.js.map +0 -1
- package/dist/web/assets/queue-0mKz6GO1.js +0 -2
- package/dist/web/assets/queue-0mKz6GO1.js.map +0 -1
- package/dist/web/assets/receipts-CzIfb6zY.js +0 -2
- package/dist/web/assets/receipts-CzIfb6zY.js.map +0 -1
- package/dist/web/assets/routes-BEYqVix5.js +0 -2
- package/dist/web/assets/routes-BEYqVix5.js.map +0 -1
- package/dist/web/assets/run._playName-CJIjxoPb.js +0 -5
- package/dist/web/assets/run._playName-CJIjxoPb.js.map +0 -1
- package/dist/web/assets/setup-CFmdIoj0.js +0 -2
- package/dist/web/assets/setup-CFmdIoj0.js.map +0 -1
package/dist/bin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.mjs","names":["toView","toView","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","PLAY_NAME","cache","extractCost","PLAY_NAME","SOURCE","extractCost","PLAY_NAME","SOURCE","extractCost","PLAY_NAME","extractCost","PLAY_NAME","extractCost","PLAY_NAME","SOURCE","extractCost","PLAY_NAME","SOURCE","extractCost","PLAY_NAME","SOURCE","extractCost","PLAY_NAME","SOURCE","cache","dispatchPlay","toView"],"sources":["../../../packages/core/src/config.ts","../../../packages/core/src/ledger.ts","../../../packages/core/src/oneshot.ts","../../../packages/core/src/events.ts","../src/api/home.ts","../src/api/cadences.ts","../src/api/receipts.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/show-hn.ts","../../../packages/plays/src/job-change.ts","../../../packages/plays/src/post-funding.ts","../../../packages/plays/src/accelerator-batch.ts","../../../packages/plays/src/demo-no-show.ts","../../../packages/plays/src/competitor-switch.ts","../../../packages/plays/src/hiring-signal.ts","../../../packages/plays/src/podcast-guest.ts","../../../packages/plays/src/breakup-revive.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/_linkedin.ts","../../../packages/find/src/show-hn.ts","../../../packages/find/src/post-funding.ts","../../../packages/find/src/_accelerator-search-adapter.ts","../../../packages/find/src/_parallel.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/registry.ts","../../../packages/find/src/drain.ts","../src/api/strategist.ts","../../../packages/doctor/src/check.ts","../src/api/doctor.ts","../src/api/run.ts","../src/api/queue.ts","../src/api/triggers.ts","../src/server.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 icpOneLiner: null,\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\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\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\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 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\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 schema_version (\n version INTEGER PRIMARY KEY\n );\n INSERT OR IGNORE INTO schema_version(version) VALUES(5);\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 }\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 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(): 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 prospect_email: string | null;\n prospect_name: string | null;\n prospect_company: string | null;\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 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 advanceCadence(input: {\n prospectId: number;\n playName: string;\n newStep: number;\n nextDueAt: string | null;\n }): void {\n this.db\n .prepare(\n `UPDATE cadence_state\n SET current_step = ?, next_due_at = ?, last_polled_at = datetime('now')\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 this.db\n .prepare(`UPDATE cadence_state SET status = ? WHERE prospect_id = ? AND play_name = ?`)\n .run(input.status, 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(email) as { id: number }) ??\n null\n );\n }\n\n recordReceipt(input: {\n playName: string;\n callType: string;\n costUsd?: number;\n signedReceipt?: unknown;\n oneshotRequestId?: string;\n }): number {\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 input.costUsd ?? null,\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 if (input.email) {\n const existing = this.db\n .query(\"SELECT id FROM prospects WHERE email = ?\")\n .get(input.email) as { id: number } | 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 input.email ?? null,\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 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 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 dequeueApproved(opts: { playName: string; limit?: number }): QueueRow[] {\n const sql = `\n SELECT * FROM target_queue\n WHERE play_name = ? AND status = 'approved'\n ORDER BY found_at ASC\n LIMIT ?\n `;\n return this.db.query(sql).all(opts.playName, opts.limit ?? 50) as QueueRow[];\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 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 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 { getLedger } from \"./ledger.ts\";\nimport { 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\nfunction emailRequestId(r: EmailResult): string | undefined {\n return r.email?.id;\n}\n\nexport async function sendEmail(input: SendEmailInput, ctx: CallContext) {\n const agent = await getAgent();\n const opts: Parameters<OneShot[\"email\"]>[0] = {\n to: input.to,\n subject: input.subject,\n body: input.body,\n };\n if (input.fromDomain) opts.from_domain = input.fromDomain;\n const result = await agent.email(opts);\n const receiptId = getLedger().recordReceipt({\n playName: ctx.playName,\n callType: \"email.send\",\n signedReceipt: result,\n oneshotRequestId: emailRequestId(result) ?? undefined,\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 });\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 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 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 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 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 });\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 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 });\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 });\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","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 { getLedger } from \"@oneshot-gtm/core\";\nimport type { CadenceView, CadenceStatus } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nfunction toView(\n row: ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number],\n): CadenceView {\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 };\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: rows.map(toView) }, 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.listAllCadences().filter((c) => c.prospect_id === id);\n if (all.length === 0) return jsonResponse({ error: \"no cadences for prospect\" }, 404, req);\n return jsonResponse({ cadences: all.map(toView) }, 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.listAllCadences().filter((c) => {\n if (c.prospect_id !== id) return false;\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","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 { 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\nexport function loadPrompt(name: string): string {\n // Reject any path-traversal attempt. Prompt names are always hardcoded\n // identifiers in this codebase (e.g. \"personalize\", \"advise\"); rejecting\n // anything else is defense-in-depth in case a future caller passes user\n // input through.\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new Error(`invalid prompt name: ${JSON.stringify(name)}`);\n }\n for (const dir of candidates) {\n const path = join(dir, `${name}.md`);\n if (existsSync(path)) return readFileSync(path, \"utf8\");\n }\n throw new Error(`prompt not found: ${name}.md (searched: ${candidates.join(\", \")})`);\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 { getLedger, loadConfig, receiptUrlForId, sendEmail } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\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\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);\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 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 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, ...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","import {\n getLedger,\n listInbox,\n loadConfig,\n receiptUrlForId,\n sendEmail,\n sendSms,\n voiceCall,\n type ProspectRecord,\n} from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\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\nexport function getSequence(playName: string): Sequence | undefined {\n return playSequences.get(playName);\n}\n\nexport function enrollInCadence(input: { prospectId: number; playName: string }): void {\n const seq = playSequences.get(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 cfg = loadConfig();\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 const activeForProspect = ledger\n .listAllCadences()\n .filter((c) => c.prospect_id === prospect.id && 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 const nowIso = new Date().toISOString();\n const due = ledger.listActiveCadences({ dueByIso: nowIso });\n\n for (const cad of due) {\n const seq = playSequences.get(cad.play_name);\n if (!seq) {\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"skipped\",\n note: \"no registered sequence\",\n receiptIds: [],\n });\n continue;\n }\n const nextIndex = cad.current_step + 1; // current_step starts at 0 (initial send), step 1 is first follow-up\n const stepEntryIndex = nextIndex - 1; // sequence array is 0-indexed for follow-ups\n if (stepEntryIndex < 0 || stepEntryIndex >= seq.steps.length) {\n ledger.setCadenceStatus({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\n status: \"completed\",\n });\n result.completed++;\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"completed\",\n receiptIds: [],\n });\n continue;\n }\n const step = seq.steps[stepEntryIndex];\n if (!step) continue;\n\n const prospect = loadProspect(cad.prospect_id);\n if (!prospect) continue;\n\n const built = await step.builder({\n prospect,\n cfg,\n metadata: {},\n });\n\n if (!built) {\n // Skip this step; advance to next.\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\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: cad.prospect_id,\n playName: cad.play_name,\n status: \"completed\",\n });\n result.completed++;\n }\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"skipped\",\n note: step.label ?? `step ${nextIndex} builder returned null`,\n receiptIds: [],\n });\n continue;\n }\n\n const receiptIds: number[] = [];\n if (!opts.dryRun) {\n const channelOutcome = await dispatchStep({\n playName: cad.play_name,\n prospectId: cad.prospect_id,\n prospectEmail: cad.prospect_email,\n stepIndex: nextIndex,\n step,\n payload: built,\n label: step.label,\n });\n if (channelOutcome.skipReason) {\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"skipped\",\n note: channelOutcome.skipReason,\n receiptIds: [],\n });\n continue;\n }\n receiptIds.push(...channelOutcome.receiptIds);\n }\n\n const isBreakup =\n stepEntryIndex === seq.steps.length - 1 && step.label?.toLowerCase().includes(\"breakup\");\n if (isBreakup) {\n ledger.setCadenceStatus({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\n status: \"breakup\",\n });\n result.breakups++;\n } else {\n const next = seq.steps[stepEntryIndex + 1];\n ledger.advanceCadence({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\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: cad.prospect_id,\n playName: cad.play_name,\n status: \"completed\",\n });\n result.completed++;\n }\n }\n\n result.stepsExecuted++;\n result.details.push({\n prospectEmail: cad.prospect_email,\n playName: cad.play_name,\n action: \"step-sent\",\n note: step.label ?? `step ${nextIndex}`,\n receiptIds,\n });\n }\n\n return result;\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: { subject: input.payload.subject, label: input.label },\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 // Lightweight read; ledger doesn't expose getProspect yet.\n const row = (\n getLedger() as unknown as { db: { query: (s: string) => { get: (id: number) => unknown } } }\n ).db\n .query(\"SELECT * FROM prospects WHERE id = ?\")\n .get(id);\n return (row as ProspectRecord | null) ?? null;\n}\n\nexport function buildFollowUpEmail(opts: {\n promptName: string;\n contextLines: string[];\n}): SequenceStep[\"builder\"] {\n return async (ctx: CadenceContext) => {\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 `EMAIL: ${ctx.prospect.email ?? \"\"}`,\n `COMPANY: ${ctx.prospect.company ?? \"(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.6,\n maxTokens: 500,\n });\n const parsed = tryParseJsonObject<{ subject?: string; body?: string }>(res.content, {});\n if (!parsed.subject || !parsed.body) return null;\n return { kind: \"email\", subject: parsed.subject.trim(), body: parsed.body.trim() };\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, enrichProfile, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.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\nexport async function runShowHn(opts: ShowHnRunOptions): Promise<ShowHnRunResult> {\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 drafted: ShowHnRunResult[\"drafted\"] = [];\n\n for (const target of opts.targets) {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile(\n { email: target.founderEmail, name: target.founderName },\n { playName: PLAY_NAME },\n );\n receiptIds.push(enr.receiptId);\n dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n const research = await deepResearch(\n {\n topic: `Recent public work and engineering decisions by ${target.founderName} on ${target.postTitle}`,\n depth: \"quick\",\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(research.receiptId);\n dossier += \"\\n\\n---\\n\\n\" + JSON.stringify(research.result, null, 2).slice(0, 4000);\n }\n\n const draft = await draftEmailFromPrompt({\n promptName: \"show-hn-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SHOW HN: ${target.postTitle}`,\n `URL: ${target.postUrl}`,\n `HOOK: ${target.hookSummary}`,\n `DOSSIER:\\n${dossier || \"(dry-run; rely on the hook only)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 90);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: target.founderEmail,\n draft,\n flags,\n prospectMeta: {\n name: target.founderName,\n email: target.founderEmail,\n company: extractCompany(target.postTitle),\n linkedin_url: target.linkedinUrl ?? null,\n phone: target.phone ?? null,\n source: \"show-hn\",\n },\n metadata: { postUrl: target.postUrl, postTitle: target.postTitle },\n dryRun: opts.dryRun,\n });\n\n drafted.push({\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\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 { deepResearch, enrichProfile, getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, 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\nexport async function runJobChange(\n opts: JobChangeRunOptions,\n): Promise<{ drafted: JobChangeDraft[] }> {\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 drafted: JobChangeDraft[] = [];\n\n for (const target of opts.targets) {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile(\n {\n ...(target.email ? { email: target.email } : {}),\n ...(target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {}),\n name: target.name,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(enr.receiptId);\n dossier = JSON.stringify(enr.result, null, 2).slice(0, 4000);\n\n const research = await deepResearch(\n {\n topic: `Public posts, talks, and recent decisions by ${target.name} (joined ${target.newCompany} as ${target.newRole}, formerly ${target.previousRole ?? \"?\"} at ${target.previousCompany ?? \"?\"})`,\n depth: \"quick\",\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(research.receiptId);\n dossier += \"\\n\\n---\\n\\n\" + JSON.stringify(research.result, null, 2).slice(0, 4000);\n }\n\n const draft = await draftEmailFromPrompt({\n promptName: \"job-change-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${target.name}`,\n `NEW ROLE: ${target.newRole} at ${target.newCompany}`,\n `PREVIOUS: ${target.previousRole ?? \"unknown\"} at ${target.previousCompany ?? \"unknown\"}`,\n `DOSSIER:\\n${dossier || \"(dry-run; rely on the trigger only)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 100);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: target.email,\n draft,\n flags,\n prospectMeta: {\n name: target.name,\n email: target.email,\n company: target.newCompany,\n linkedin_url: target.linkedinUrl ?? null,\n phone: target.phone ?? null,\n source: \"job-change\",\n },\n metadata: { newRole: target.newRole, newCompany: target.newCompany },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(target.email);\n if (prospect) {\n enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n }\n\n drafted.push({\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\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 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 promptName: \"breakup-email\",\n contextLines: [`PLAY: job-change. Sender is closing the file.`],\n }),\n },\n ],\n});\n","import { deepResearch, enrichProfile, getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, 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\nexport async function runPostFunding(\n opts: PostFundingRunOptions,\n): Promise<{ drafted: PostFundingDraft[] }> {\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 drafted: PostFundingDraft[] = [];\n\n for (const target of opts.targets) {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile(\n {\n ...(target.email ? { email: target.email } : {}),\n ...(target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {}),\n name: target.name,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(enr.receiptId);\n dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n const research = await deepResearch(\n {\n topic: `${target.company} ${target.round} announcement: open job postings, hiring page, public roadmap, named challenges in the press release. Source: ${target.sourceUrl}`,\n depth: \"quick\",\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(research.receiptId);\n dossier += \"\\n\\n---\\n\\n\" + JSON.stringify(research.result, null, 2).slice(0, 4000);\n }\n\n const draft = await draftEmailFromPrompt({\n promptName: \"post-funding-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `PROSPECT: ${target.name} at ${target.company}`,\n `ROUND: ${target.round} ($${target.amountUsd.toLocaleString()})`,\n `LEAD INVESTOR: ${target.leadInvestor ?? \"(unspecified)\"}`,\n `SOURCE: ${target.sourceUrl}`,\n `DOSSIER:\\n${dossier || \"(dry-run; rely on the round details only)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 100);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: target.email,\n draft,\n flags,\n prospectMeta: {\n name: target.name,\n email: target.email,\n company: target.company,\n linkedin_url: target.linkedinUrl ?? null,\n phone: target.phone ?? null,\n source: \"post-funding\",\n },\n metadata: {\n round: target.round,\n amountUsd: target.amountUsd,\n leadInvestor: target.leadInvestor,\n },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(target.email);\n if (prospect) {\n enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n }\n\n drafted.push({\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\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 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 promptName: \"breakup-email\",\n contextLines: [`PLAY: post-funding.`],\n }),\n },\n ],\n});\n","import { deepResearch, enrichProfile, getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, 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}\n\nexport interface AcceleratorBatchRunOptions {\n dryRun: boolean;\n targets: AcceleratorBatchTarget[];\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 async function runAcceleratorBatch(\n opts: AcceleratorBatchRunOptions,\n): Promise<{ drafted: AcceleratorBatchDraft[] }> {\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 drafted: AcceleratorBatchDraft[] = [];\n\n for (const target of opts.targets) {\n const receiptIds: number[] = [];\n let dossier = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile(\n {\n ...(target.email ? { email: target.email } : {}),\n ...(target.linkedinUrl ? { linkedinUrl: target.linkedinUrl } : {}),\n name: target.name,\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(enr.receiptId);\n dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n if (target.launchUrl) {\n const research = await deepResearch(\n {\n topic: `Recent public work and decisions by ${target.name} at ${target.company} (${target.cohort}). Pull launch context from ${target.launchUrl}.`,\n depth: \"quick\",\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(research.receiptId);\n dossier += \"\\n\\n---\\n\\n\" + JSON.stringify(research.result, null, 2).slice(0, 4000);\n }\n }\n\n const draft = await draftEmailFromPrompt({\n promptName: \"accelerator-batch-email\",\n inputBlock: [\n `FOUNDER: ${cfg.founderName}`,\n `PRODUCT: ${cfg.productOneLiner}`,\n `SENDER COHORT: ${opts.senderCohort}`,\n `PROSPECT: ${target.name} at ${target.company}`,\n `PROSPECT COHORT: ${target.cohort}`,\n `PROSPECT PRODUCT: ${target.productOneLiner ?? \"(unknown)\"}`,\n `LAUNCH URL: ${target.launchUrl ?? \"(none)\"}`,\n `FREE-FOR-COHORT OFFER: ${opts.freeForCohortOffer ?? \"(no active offer for this cohort)\"}`,\n `DOSSIER:\\n${dossier || \"(dry-run; rely on the cohort match only)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 100);\n\n const send = await sendDraftedEmail({\n playName: PLAY_NAME,\n to: target.email,\n draft,\n flags,\n prospectMeta: {\n name: target.name,\n email: target.email,\n company: target.company,\n linkedin_url: target.linkedinUrl ?? null,\n phone: target.phone ?? null,\n source: `accelerator-${target.cohort}`,\n },\n metadata: {\n senderCohort: opts.senderCohort,\n prospectCohort: target.cohort,\n },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(target.email);\n if (prospect) {\n enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n }\n\n drafted.push({\n target,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\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 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, sendSms } from \"@oneshot-gtm/core\";\nimport { complete, loadPrompt, tryParseJsonObject } from \"@oneshot-gtm/intel\";\nimport { draftEmailFromPrompt, 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 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 }\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 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 { browserTask, enrichProfile, getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, 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\nexport async function runCompetitorSwitch(\n opts: CompetitorSwitchRunOptions,\n): Promise<{ drafted: CompetitorSwitchDraft[] }> {\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 drafted: CompetitorSwitchDraft[] = [];\n\n for (const t of opts.targets) {\n const receiptIds: number[] = [];\n let scrapedEvidence: string | undefined;\n let dossier = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile(\n {\n ...(t.email ? { email: t.email } : {}),\n name: t.name,\n companyDomain: extractDomain(t.email),\n },\n { playName: PLAY_NAME },\n );\n receiptIds.push(enr.receiptId);\n dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);\n\n if (t.evidenceUrl && !opts.skipBrowserScrape) {\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 const evidence = scrapedEvidence ?? t.evidenceText ?? \"(no evidence supplied)\";\n\n const draft = await draftEmailFromPrompt({\n promptName: \"competitor-switch-email\",\n inputBlock: [\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${dossier || \"(dry-run)\"}`,\n ].join(\"\\n\"),\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: \"competitor-switch\",\n },\n metadata: { competitor: t.competitor, evidenceUrl: t.evidenceUrl ?? null },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(t.email);\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n\n drafted.push({\n target: t,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n ...(scrapedEvidence ? { scrapedEvidence } : {}),\n });\n }\n\n return { drafted };\n}\n\nfunction extractDomain(email: string): string | undefined {\n const at = email.indexOf(\"@\");\n if (at < 0) return undefined;\n return email.slice(at + 1);\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 7,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n promptName: \"breakup-email\",\n contextLines: [\n `PLAY: competitor-switch. Single follow-up after the migration-honesty pitch.`,\n ],\n }),\n },\n ],\n});\n","import { enrichProfile, getLedger, loadConfig, webRead, webSearch } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { buildFollowUpEmail, enrollInCadence, 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\nexport async function runHiringSignal(\n opts: HiringSignalRunOptions,\n): Promise<{ drafted: HiringSignalDraft[] }> {\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 drafted: HiringSignalDraft[] = [];\n\n for (const t of opts.targets) {\n const receiptIds: number[] = [];\n let jobPostHook = \"(no specific job post phrase scraped)\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile({ email: t.email, name: t.name }, { playName: PLAY_NAME });\n receiptIds.push(enr.receiptId);\n\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 const draft = await draftEmailFromPrompt({\n promptName: \"hiring-signal-email\",\n inputBlock: [\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): ${jobPostHook}`,\n `YOUR CLAIM: ${t.yourClaim}`,\n ].join(\"\\n\"),\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: \"hiring-signal\",\n },\n metadata: { jobTitle: t.jobTitle, jobPostUrl: t.jobPostUrl ?? null },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(t.email);\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n\n drafted.push({\n target: t,\n subject: draft.subject,\n body: draft.body,\n jobPostHook,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [\n {\n dayOffset: 7,\n channel: \"email\",\n breakOnReply: true,\n label: \"breakup\",\n builder: buildFollowUpEmail({\n promptName: \"breakup-email\",\n contextLines: [`PLAY: hiring-signal. Single follow-up.`],\n }),\n },\n ],\n});\n","import { enrichProfile, getLedger, loadConfig, webSearch } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, lintEmail, sendDraftedEmail } from \"./_lib.ts\";\nimport { enrollInCadence, 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 async function runPodcastGuest(\n opts: PodcastGuestRunOptions,\n): Promise<{ drafted: PodcastGuestDraft[] }> {\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 drafted: PodcastGuestDraft[] = [];\n\n for (const t of opts.targets) {\n const receiptIds: number[] = [];\n let extra = \"\";\n\n if (!opts.dryRun) {\n const enr = await enrichProfile({ email: t.email, name: t.name }, { playName: PLAY_NAME });\n receiptIds.push(enr.receiptId);\n\n if (!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 extra = s.result.results\n .slice(0, 2)\n .map((r) => `- ${r.title}: ${r.description}`)\n .join(\"\\n\");\n }\n }\n\n const draft = await draftEmailFromPrompt({\n promptName: \"podcast-guest-email\",\n inputBlock: [\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${extra || \"(none)\"}`,\n ].join(\"\\n\"),\n });\n\n const flags = lintEmail(draft.subject, draft.body, 90);\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: \"podcast-guest\",\n },\n metadata: { podcast: t.podcast, episodeTitle: t.episodeTitle },\n dryRun: opts.dryRun,\n });\n\n if (send.sent) {\n const ledger = getLedger();\n const prospect = ledger.findProspectByEmail(t.email);\n if (prospect) enrollInCadence({ prospectId: prospect.id, playName: PLAY_NAME });\n }\n\n drafted.push({\n target: t,\n subject: draft.subject,\n body: draft.body,\n receiptIds: [...receiptIds, ...send.receiptIds],\n sent: send.sent,\n flags,\n });\n }\n\n return { drafted };\n}\n\nregisterSequence({\n playName: PLAY_NAME,\n steps: [], // Intentionally empty — podcast-guest is one-touch only.\n});\n","import { getLedger, loadConfig } from \"@oneshot-gtm/core\";\nimport { draftEmailFromPrompt, 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 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 }\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 { getSequence } 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: \"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\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 const hasBreakup = seq?.steps.some((s) => s.label?.toLowerCase().includes(\"breakup\")) ?? false;\n return {\n name: p.name,\n channels,\n followupCount,\n hasBreakup,\n cliInvocation: p.cli,\n };\n });\n return jsonResponse({ plays }, 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 icpOneLiner: mergeString(body.icpOneLiner, current.icpOneLiner),\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","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 =\n /^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 ?? []).map((s) => s.trim()).filter((s) => s.length > 0);\n const cacheKey = JSON.stringify([fullName.toLowerCase(), disambiguators.map((s) => s.toLowerCase())]);\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(extractCost(search.result) ?? 0.01);\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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 { findLinkedInUrl } from \"./_linkedin.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}\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 for (const hit of data.hits) {\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 (hit.points < minPoints) {\n result.droppedLowSignal = (result.droppedLowSignal ?? 0) + 1;\n continue;\n }\n\n // Dedupe BEFORE any LLM/OneShot spend.\n if (ledger.isQueueDuplicate(PLAY_NAME, hit.objectID)) {\n result.droppedDuplicate++;\n continue;\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 continue;\n }\n\n if (opts.dryRun) {\n // Just count — don't enrich or enqueue.\n result.enqueued++;\n continue;\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 continue;\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 findInput: FindEmailInput = { companyDomain: domain };\n if (fullName) findInput.fullName = fullName;\n const found = await findEmail(findInput, { playName: PLAY_NAME });\n result.costUsd += extractCost(found.result) ?? 0.05;\n\n if (!found.result.found || !found.result.email) {\n result.droppedEnrichment++;\n continue;\n }\n const email = found.result.email;\n\n // Verify deliverability.\n const verified = await verifyEmail({ email }, { playName: PLAY_NAME });\n result.costUsd += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\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 continue;\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 += extractCost(read.result) ?? 0.02;\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 const 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 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 };\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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 { 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 += extractCost(read.result) ?? 0.02;\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 found = await findEmail(\n { fullName: extract.founderName, companyDomain: extract.companyDomain },\n { playName: PLAY_NAME },\n );\n result.costUsd += extractCost(found.result) ?? 0.05;\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 += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\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 ...(extract.phone ? { phone: extract.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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 += extractCost(search.result) ?? 0.01;\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 += extractCost(search.result) ?? 0.01;\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 += extractCost(read.result) ?? 0.02;\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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 */\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 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 { icpFilter, resolveIcp } from \"./_filter.ts\";\nimport { findLinkedInUrl, isLinkedInProfileUrl } from \"./_linkedin.ts\";\nimport { parallelMap } from \"./_parallel.ts\";\nimport { 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 AcceleratorBatchFinderOpts extends RunOpts {\n /** Cohort tag — e.g. `yc-w26`, `yc-s25`, `techstars-toronto-2025`. */\n cohort: string;\n /** Human-readable label fed into search queries + the email prompt. */\n cohortLabel: string;\n /** Force a specific adapter. Default: yc-* → yc-oss, everything else → websearch. */\n adapter?: \"yc-oss\" | \"websearch\";\n /** Concurrency for the per-company pipeline. Default 3. */\n concurrency?: number;\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 source = `find:accelerator-batch:${opts.cohort}`;\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 via the adapter.\n const adapterName = pickAdapter(opts.cohort, opts.adapter);\n const adapter =\n adapterName === \"yc-oss\"\n ? () => fetchYcOssBatch(opts.cohort, limit)\n : () => fetchAcceleratorSearch(opts.cohort, opts.cohortLabel, limit);\n const fetched = await adapter();\n result.costUsd += fetched.costUsd;\n if (fetched.records.length === 0) {\n // Surface the adapter's diagnostic on the run summary so the trigger\n // card explains WHY zero — better than the silent-success the previous\n // implementation produced.\n result.halted = fetched.diagnostic ?? \"adapter returned 0 records\";\n return result;\n }\n result.candidates = fetched.records.length;\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(fetched.records, 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, opts.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, opts.cohort),\n dedupeKey,\n source,\n initialStatus: \"rejected\",\n notes: `auto: ICP — ${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 found = await findEmail(\n { fullName: founderName, companyDomain: domain },\n { playName: PLAY_NAME },\n );\n result.costUsd += extractCost(found.result) ?? 0.05;\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 += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n let linkedinUrl = resolvedLinkedin;\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: opts.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 ...(resolvedPhone ? { phone: resolvedPhone } : {}),\n };\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\n payload: target,\n dedupeKey,\n source,\n notes: 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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 += extractCost(read.result) ?? 0.02;\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 { icpFilter, resolveIcp } from \"./_filter.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 += extractCost(search.result) ?? 0.01;\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\n const found = await findEmail(\n { fullName: extract.fullName, companyDomain: domain },\n { playName: PLAY_NAME },\n );\n result.costUsd += extractCost(found.result) ?? 0.05;\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 += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\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 ...(extract.phone ? { phone: extract.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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 { icpFilter, resolveIcp } from \"./_filter.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\"];\nconst DEFAULT_CLAIM =\n \"we cut new-hire ramp time by ~30% on the team they're hiring for — happy to share how\";\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 const yourClaim = opts.yourClaim ?? DEFAULT_CLAIM;\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 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 += extractCost(search.result) ?? 0.01;\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 += extractCost(read.result) ?? 0.02;\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 findInput =\n extract.hiringManagerName && extract.hiringManagerName.length > 0\n ? { fullName: extract.hiringManagerName, companyDomain: domain }\n : { companyDomain: domain };\n const found = await findEmail(findInput, { playName: PLAY_NAME });\n result.costUsd += extractCost(found.result) ?? 0.05;\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 += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n const recipientName = extract.hiringManagerName ?? found.result.full_name ?? null;\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\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 ...(extract.phone ? { phone: extract.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 += extractCost(search.result) ?? 0.01;\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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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 { icpFilter, resolveIcp } from \"./_filter.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 += extractCost(search.result) ?? 0.01;\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 += extractCost(read.result) ?? 0.02;\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\n const found = await findEmail(\n { fullName: extract.guestName, companyDomain: extract.guestCompanyDomain },\n { playName: PLAY_NAME },\n );\n result.costUsd += extractCost(found.result) ?? 0.05;\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 += extractCost(verified.result) ?? 0.01;\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n continue;\n }\n\n let linkedinUrl: string | null = isLinkedInProfileUrl(extract.linkedinUrl)\n ? extract.linkedinUrl\n : null;\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 ...(extract.phone ? { phone: extract.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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\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\"]) ? (json[\"items\"] as Array<Record<string, unknown>>) : [];\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 = 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: typeof json[\"name\"] === \"string\" && json[\"name\"] !== \"\" ? (json[\"name\"] as string) : null,\n email: typeof json[\"email\"] === \"string\" && json[\"email\"] !== \"\" ? (json[\"email\"] as string) : null,\n blogDomain: extractBlogDomain(json[\"blog\"]),\n company: typeof json[\"company\"] === \"string\" && json[\"company\"] !== \"\" ? (json[\"company\"] as string) : 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(\n owner: string,\n repo: string,\n path: string,\n): 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 } from \"@oneshot-gtm/plays\";\nimport { isDuplicate } from \"./_dedupe.ts\";\nimport { icpFilter } from \"./_filter.ts\";\nimport {\n fetchGitHubUser,\n ownerFromRepoUrl,\n repoNameFromRepoUrl,\n type GitHubUserInfo,\n} from \"./_github-user.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 = \"competitor-switch\";\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 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 if (ledger.isQueueDuplicate(PLAY_NAME, hit.url)) {\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(\n \"github-topics.dropped.min_vendors\",\n {\n repo: `${owner}/${repoName}`,\n detected_count: stack.detected.length,\n manifests_found: stack.manifestsFound,\n min_vendors: ctx.minVendors,\n },\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 // 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 });\n if (!contact) {\n result.droppedEnrichment++;\n return;\n }\n\n if (isDuplicate({ playName: PLAY_NAME, 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: PLAY_NAME });\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(extractCost(verified.result) ?? 0.01);\n if (!verified.result.deliverable) {\n result.droppedEnrichment++;\n return;\n }\n\n const stackLine = extract.stackDetected.join(\", \");\n const vendorCount = extract.stackDetected.length;\n const evidenceText =\n `Their repo stitches together ${stackLine} — ${vendorCount} separate auth ` +\n `surfaces and ${vendorCount} bills to manage.`;\n const competitorLabel = extract.stackDetected[0] as string;\n const companyFallback = contact.domain ?? contact.email.split(\"@\")[1] ?? \"\";\n\n const target: CompetitorSwitchTarget = {\n name: extract.authorFullName ?? contact.fullName ?? extract.githubHandle ?? \"there\",\n email: contact.email,\n company: extract.companyName ?? extract.githubHandle ?? companyFallback,\n competitor: competitorLabel,\n evidenceUrl: hit.url,\n evidenceText,\n yourEdge: ctx.yourEdge,\n ...(contact.linkedinUrl ? { linkedinUrl: contact.linkedinUrl } : {}),\n ...(contact.phone ? { phone: contact.phone } : {}),\n };\n const notes = truncate(\n `${ctx.notesPrefix}: ${stackLine} (${vendorCount} vendors) — ${snippetFilter.reason}`,\n 220,\n );\n const id = ledger.enqueueTarget({\n playName: PLAY_NAME,\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}): Promise<ResolvedContact | null> {\n const { extract, repoUrl, ghUser, accumCost, useDeepResearch } = args;\n const errKindPrefix = args.errKindPrefix ?? \"repo-pipeline\";\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);\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: PLAY_NAME });\n accumCost(extractCost(enriched.result) ?? 0.005);\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 );\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: PLAY_NAME },\n );\n accumCost(extractCost(dr.result) ?? 0.05);\n const enr = dr.result.result?.enrichment;\n const drEmail =\n 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].filter((p): p is string => Boolean(p)).join(\" \").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): Promise<{ email: string; fullName: string | null } | null> {\n if (!extract.authorFullName || extract.authorFullName.length === 0) {\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: PLAY_NAME },\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(extractCost(found.result) ?? 0.005);\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\nfunction extractCost(r: unknown): number | undefined {\n if (!r || typeof r !== \"object\") return undefined;\n const v = (r as Record<string, unknown>)[\"cost\"];\n return typeof v === \"number\" ? v : undefined;\n}\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 /** 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(\n opts: GitHubTopicsFinderOpts,\n): 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 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 { getLedger, logEvent, startRun } from \"@oneshot-gtm/core\";\nimport { runAcceleratorBatchFinder } from \"./accelerator-batch.ts\";\nimport { deriveCohortLabel } from \"./_yc-oss-adapter.ts\";\nimport { runBreakupReviveFinder } from \"./breakup-revive.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\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 // Ships empty so the strategist is forced to propose a cohort tuned to the\n // founder's ICP rather than reflexively defaulting to YC. Each accelerator\n // (YC, Techstars, Antler, AI Grant, SPC, Neo, 500 Global, etc.) attracts a\n // different founder population — the right pick depends on who buys.\n defaultConfig: {\n cohort: \"\",\n cohortLabel: \"\",\n limit: 25,\n maxCostUsd: 5,\n },\n configBrief:\n \"Pulls an accelerator cohort directory, ICP-filters companies, finds founder contact, enqueues for outreach. SHIPS EMPTY — pick a cohort that matches your ICP. Each accelerator surfaces a different founder population: YC for AI/infra-heavy startups, Techstars for vertical SaaS + corporate-partnered batches, Antler for solo founders + day-zero, AI Grant for AI-only research-product founders, SPC / Neo for senior-engineer founders, 500 Global for international + emerging markets. Config: `cohort` (tag — e.g. `yc-w26`, `techstars-toronto-2025`, `antler-nyc-q1-2026`, `ai-grant-2026`), `cohortLabel` (human label fed to email + search queries; auto-derived from cohort when not set), optional `adapter` (`yc-oss` | `websearch`; auto-picked from cohort prefix — yc-* tags use the free yc-oss/api directory, everything else falls back to web search), `limit`, `maxCostUsd`. STRATEGIST DUTY: when proposing this trigger, anchor the cohort recommendation in the founder's ICP — don't reflexively pick YC. If multiple accelerators fit, propose the top match and mention 1-2 alternatives in prose so the founder can swap.\",\n readiness: (cfg) => {\n const cohort = cfg[\"cohort\"];\n if (typeof cohort !== \"string\" || cohort.trim().length === 0) {\n return {\n ready: false,\n reason: \"set `cohort` (ask the strategist to propose one tuned to your ICP)\",\n };\n }\n return { ready: true };\n },\n run: (cfg) => {\n const cohort = (cfg[\"cohort\"] as string) ?? \"yc-w26\";\n // Derive cohortLabel from cohort when the founder didn't set one\n // explicitly. This matters most after a `cohort` change — without\n // derivation the label would stay \"YC W26\" while the cohort points\n // at e.g. techstars, and the websearch adapter would query the wrong\n // program. Explicit override always wins.\n const labelFromCfg = typeof cfg[\"cohortLabel\"] === \"string\" ? cfg[\"cohortLabel\"].trim() : \"\";\n const cohortLabel = labelFromCfg.length > 0 ? labelFromCfg : deriveCohortLabel(cohort);\n return runAcceleratorBatchFinder({\n dryRun: false,\n cohort,\n cohortLabel,\n ...(cfg[\"adapter\"] === \"yc-oss\" || cfg[\"adapter\"] === \"websearch\"\n ? { adapter: cfg[\"adapter\"] as \"yc-oss\" | \"websearch\" }\n : {}),\n limit: (cfg[\"limit\"] as number) ?? 25,\n maxCostUsd: (cfg[\"maxCostUsd\"] as number) ?? 5,\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), `sinceDays`, `limit`, `maxCostUsd`. The roles + yourClaim need to be tightly coupled to the product.\",\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 competitor-switch (migration-\n // honesty pitch). Config-driven — the founder supplies topics + vendors\n // + 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 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. Feeds the competitor-switch motion play. Required config: `topics` (GitHub topic slugs the founder's ICP overlaps with — lowercase, hyphenated, EXACT GitHub-canonical form; singular vs plural matters), `vendors` (the founder's competitive landscape — the API vendors they aim to replace), `yourEdge` (one-sentence pitch handed to the email). VOCAB SEMANTICS: each `vendors` string is substring-matched (case-insensitive) against manifest deps + env-var keys — so `twilio` matches `twilio`, `twilio-node`, `@twilio/voice-sdk`, AND `TWILIO_ACCOUNT_SID`. There is NO hardcoded vendor list; oneshot-gtm is a generic founder tool and competitive vocabularies vary entirely by founder. STRATEGIST DUTY: when you (the strategist) have enough context about the founder's product/ICP, proactively propose BOTH `topics` AND `vendors` via apply-config — topics are GitHub category slugs aligned to ICP; vendors are the API competitors the founder replaces. The founder shouldn't have to enumerate either by hand. Other config: `minStars` (filter, default 5), `maxAgeDays` (default 90), `minVendors` (gate: how many distinct vocab vendors must match in a candidate's manifests; default 1), `concurrency` (in-flight workers; default 3), `useDeepResearch` (default true), `limit`, `maxCostUsd`.\",\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 yourEdge = typeof cfg[\"yourEdge\"] === \"string\" ? cfg[\"yourEdge\"] : \"\";\n return runGitHubTopicsFinder({\n dryRun: false,\n topics,\n vendors,\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 // 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 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 } from \"@oneshot-gtm/core\";\nimport {\n runAcceleratorBatch,\n runBreakupRevive,\n runCompetitorSwitch,\n runHiringSignal,\n runJobChange,\n runPodcastGuest,\n runPostFunding,\n runShowHn,\n type AcceleratorBatchTarget,\n type BreakupReviveTarget,\n type CompetitorSwitchTarget,\n type HiringSignalTarget,\n type JobChangeTarget,\n type PodcastGuestTarget,\n type PostFundingTarget,\n type ShowHnTarget,\n} from \"@oneshot-gtm/plays\";\nimport type { QueueRow } from \"@oneshot-gtm/core\";\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, and mark each as sent (or rollback on error).\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 try {\n const sentIds = await dispatchPlay(opts, rows);\n if (!opts.dryRun) {\n for (const id of sentIds) {\n const prospectId = backfillProspectId(rows.find((r) => r.id === id) ?? null);\n ledger.setQueueStatus({ id, status: \"sent\" });\n if (prospectId != null) {\n try {\n ledger.setQueueProspectId(id, prospectId);\n } catch {\n // best-effort backfill — a schema mismatch shouldn't break the drain\n }\n }\n }\n outcome.sent = sentIds.length;\n } else {\n outcome.sent = rows.length; // would-be-sent\n }\n } catch (err) {\n outcome.errors.push({ id: -1, message: (err as Error).message ?? \"drain failed\" });\n }\n\n return outcome;\n}\n\nasync function dispatchPlay(opts: DrainOpts, rows: QueueRow[]): Promise<number[]> {\n switch (opts.playName) {\n case \"show-hn\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as ShowHnTarget);\n const result = await runShowHn({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"job-change\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as JobChangeTarget);\n const result = await runJobChange({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"post-funding\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as PostFundingTarget);\n const result = await runPostFunding({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"accelerator-batch\": {\n if (!opts.senderCohort) {\n throw new Error(\"--sender-cohort is required for draining accelerator-batch\");\n }\n const targets = rows.map((r) => JSON.parse(r.payload_json) as AcceleratorBatchTarget);\n const result = await runAcceleratorBatch({\n dryRun: opts.dryRun,\n targets,\n senderCohort: opts.senderCohort,\n ...(opts.freeForCohortOffer ? { freeForCohortOffer: opts.freeForCohortOffer } : {}),\n });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"hiring-signal\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as HiringSignalTarget);\n const result = await runHiringSignal({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"podcast-guest\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as PodcastGuestTarget);\n const result = await runPodcastGuest({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"breakup-revive\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as BreakupReviveTarget);\n const result = await runBreakupRevive({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n case \"competitor-switch\": {\n const targets = rows.map((r) => JSON.parse(r.payload_json) as CompetitorSwitchTarget);\n const result = await runCompetitorSwitch({ dryRun: opts.dryRun, targets });\n return idsForSentDrafts(result.drafted, rows, opts.dryRun);\n }\n default:\n throw new Error(`drain: unsupported play '${opts.playName}'`);\n }\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 =\n 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 {\n runAcceleratorBatch,\n runHiringSignal,\n runJobChange,\n runPodcastGuest,\n runPostFunding,\n runShowHn,\n type AcceleratorBatchTarget,\n type HiringSignalTarget,\n type JobChangeTarget,\n type PodcastGuestTarget,\n type PostFundingTarget,\n type ShowHnTarget,\n} from \"@oneshot-gtm/plays\";\nimport type { RunPlayEvent, RunPlayRequest } from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.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]);\n\ninterface DraftedView {\n subject: string;\n body: string;\n flags: string[];\n receiptIds: number[];\n sent: boolean;\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 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\\n\\n`));\n };\n\n try {\n const drafted = await dispatchPlay(playName, body);\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 } catch (err) {\n send({ kind: \"error\", index: -1, message: (err as Error).message });\n } finally {\n controller.close();\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\nasync function dispatchPlay(playName: string, body: RunPlayRequest): Promise<DraftedView[]> {\n switch (playName) {\n case \"show-hn\": {\n const result = await runShowHn({\n dryRun: body.dryRun,\n targets: body.targets as ShowHnTarget[],\n });\n return result.drafted.map(toDraftedView);\n }\n case \"job-change\": {\n const result = await runJobChange({\n dryRun: body.dryRun,\n targets: body.targets as JobChangeTarget[],\n });\n return result.drafted.map(toDraftedView);\n }\n case \"post-funding\": {\n const result = await runPostFunding({\n dryRun: body.dryRun,\n targets: body.targets as PostFundingTarget[],\n });\n return result.drafted.map(toDraftedView);\n }\n case \"accelerator-batch\": {\n if (!body.senderCohort || body.senderCohort.length === 0) {\n throw new Error(\"accelerator-batch requires senderCohort\");\n }\n const result = await runAcceleratorBatch({\n dryRun: body.dryRun,\n targets: body.targets as AcceleratorBatchTarget[],\n senderCohort: body.senderCohort,\n ...(body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}),\n });\n return result.drafted.map(toDraftedView);\n }\n case \"hiring-signal\": {\n const result = await runHiringSignal({\n dryRun: body.dryRun,\n targets: body.targets as HiringSignalTarget[],\n });\n return result.drafted.map(toDraftedView);\n }\n case \"podcast-guest\": {\n const result = await runPodcastGuest({\n dryRun: body.dryRun,\n targets: body.targets as PodcastGuestTarget[],\n });\n return result.drafted.map(toDraftedView);\n }\n default:\n throw new Error(`unsupported play: ${playName}`);\n }\n}\n\nfunction 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","import { getLedger, type QueueRow, type QueueStatus } from \"@oneshot-gtm/core\";\nimport { drainQueue } from \"@oneshot-gtm/find\";\nimport type {\n DrainRequest,\n DrainResult,\n QueueCounts,\n QueueRowView,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.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 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 };\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","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 { listCadences, getCadence, stopCadence } from \"./api/cadences.ts\";\nimport { listReceipts, getReceipt } from \"./api/receipts.ts\";\nimport { listPlays } 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 rejectQueueRoute,\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(\"GET\", \"/api/receipts\", listReceipts),\n route(\"GET\", \"/api/receipts/:id\", getReceipt),\n route(\"GET\", \"/api/plays\", listPlays),\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(\"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 open from \"open\";\nimport { getLedger, logEvent } from \"@oneshot-gtm/core\";\nimport { buildFetchHandler, SERVER_BASE_OPTS, startServer } from \"./server.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 { __oneshotGtmServer?: BunServer };\n\nif (cache.__oneshotGtmServer) {\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 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 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,aAAa;CACb,cAAc;CACd,iBAAiB;CACjB,aAAa;CACb,UAAU;CACX;AAED,SAAgB,Y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AY_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","toView"],"sources":["../../../packages/core/src/config.ts","../../../packages/core/src/ledger.ts","../../../packages/core/src/oneshot.ts","../../../packages/core/src/events.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/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/_parallel.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/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\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\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\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(): 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 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 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: {\n prospectId: number;\n playName: string;\n }): {\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\n .query(\"SELECT id FROM prospects WHERE email = ?\")\n .get(canonEmail(email)) as { id: number }) ?? 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 /** 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(\n prospectId: number,\n playName: string,\n ): 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 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: {\n playName: string;\n limit?: number;\n leaseSeconds?: number;\n }): 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(\n `UPDATE target_queue SET drain_claimed_at = ? WHERE id IN (${placeholders})`,\n )\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","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 { result: { status: \"failed\", profile: null, cost: 0 }, receiptId: 0 } as unknown as Awaited<\n ReturnType<typeof enrichProfile>\n >;\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 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 const activeForProspect = ledger\n .listAllCadences()\n .filter((c) => c.prospect_id === prospect.id && 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 const nowIso = new Date().toISOString();\n const due = ledger.listActiveCadences({ dueByIso: nowIso });\n\n for (const cad of due) {\n const out = await runCadenceStepForProspect({\n prospectId: cad.prospect_id,\n playName: cad.play_name,\n dryRun: opts.dryRun,\n });\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\n .listAllCadences()\n .find((c) => c.prospect_id === opts.prospectId && c.play_name === 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\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: \"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\n .listAllCadences()\n .find((c) => c.prospect_id === input.prospectId && c.play_name === 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 * Serial preview of a list of cadence rows. Each per-prospect failure is\n * captured in the result array — the batch never throws. Sequential\n * iteration is deliberate: parallel LLM calls would risk burst rate-limits\n * and the founder is waiting on us anyway (~10s/row).\n */\nexport async function previewCadenceStepBatch(items: BatchItem[]): Promise<BatchPreviewResult[]> {\n const out: BatchPreviewResult[] = [];\n for (const item of items) {\n try {\n const preview = await previewCadenceStep(item);\n out.push({ prospectId: item.prospectId, playName: item.playName, ok: true, preview });\n } catch (err) {\n out.push({\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 return out;\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 */\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 // Lightweight read; ledger doesn't expose getProspect yet.\n const row = (\n getLedger() as unknown as { db: { query: (s: string) => { get: (id: number) => unknown } } }\n ).db\n .query(\"SELECT * FROM prospects WHERE id = ?\")\n .get(id);\n return (row as ProspectRecord | null) ?? null;\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(\n prospectId: number,\n playName: string,\n): 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((r) => {\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\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 } 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 const drafted: Array<PlayDraft<T, X>> = [];\n\n for (const target of opts.targets) {\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 drafted.push({\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 drafted.push({\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\" + 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: [\n `PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`,\n ],\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 { 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 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 \"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 getPriorStepsForProspect,\n nextStepInfo,\n playFollowupCount,\n previewCadenceStep,\n previewCadenceStepBatch,\n sendCadenceStep,\n sendCadenceStepBatch,\n type BatchItem,\n} from \"@oneshot-gtm/plays\";\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 =>\n `${prospectId}|${playName}`;\nimport type {\n CadenceNextStepDraft,\n CadenceStatus,\n CadenceView,\n} from \"@oneshot-gtm/shared-types\";\nimport { jsonResponse } from \"../server.ts\";\n\nfunction toView(\n row: ReturnType<ReturnType<typeof getLedger>[\"listAllCadences\"]>[number],\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 next = nextStepInfo(row.play_name, row.current_step);\n const priorSteps = getPriorStepsForProspect(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: playFollowupCount(row.play_name),\n priorSteps,\n isSending: inFlightSends.has(inFlightKey(row.prospect_id, row.play_name)),\n };\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: rows.map(toView) }, 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.listAllCadences().filter((c) => c.prospect_id === id);\n if (all.length === 0) return jsonResponse({ error: \"no cadences for prospect\" }, 404, req);\n return jsonResponse({ cadences: all.map(toView) }, 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.listAllCadences().filter((c) => {\n if (c.prospect_id !== id) return false;\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(\n { error: \"no persisted preview — click Preview first\" },\n 409,\n req,\n );\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)\n 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 = !existing || c.status === \"replied\" || (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: \"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","/**\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 */\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, 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 { 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 { 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\" && 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 // 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]);\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: 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 = (\n target && typeof target === \"object\" ? target : {}\n ) as Record<string, unknown>;\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,aAAa;CACb,cAAc;CACd,iBAAiB;CACjB,eAAe;CACf,eAAe;CACf,aAAa;CACb,kBAAkB;CAClB,oBAAoB;CACpB,kBAAkB;CAClB,UAAU;CACV,iBAAiB;CACjB,UAAU;CACX;AAED,SAAgB,YAAoB;AAClC,QAAO;;AAGT,SAAgB,kBAAwB;AACtC,KAAI,CAAC,WAAW,WAAW,CAAE,WAAU,YAAY,EAAE,WAAW,MAAM,CAAC;;AAGzE,SAAgB,aAA4B;CAE1C,MAAM,EAAE,KAAK,WAAW,kBADZ,qBACiC,CAAC;AAK9C,KAAI,OACF,KAAI;AACF,aAAW,IAAI;SACT;AAIV,QAAO;;;;;;;;AAST,SAAgB,kBAAkB,KAGhC;AACA,KAAI,IAAI,YAAY,IAAI,SAAS,SAAS,EAAG,QAAO;EAAE;EAAK,QAAQ;EAAO;AAC1E,QAAO;EAAE,KAAK;GAAE,GAAG;GAAK,UAAU,YAAY;GAAE;EAAE,QAAQ;EAAM;;AAGlE,SAAS,sBAAqC;AAC5C,KAAI,CAAC,WAAW,YAAY,CAAE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