oneshot-gtm-server 0.1.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 +6915 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/web/assets/Button-DPVQuma9.js +2 -0
- package/dist/web/assets/Button-DPVQuma9.js.map +1 -0
- package/dist/web/assets/EmptyNote-C4quX2dg.js +2 -0
- package/dist/web/assets/EmptyNote-C4quX2dg.js.map +1 -0
- package/dist/web/assets/Field-D9WpcA8z.js +2 -0
- package/dist/web/assets/Field-D9WpcA8z.js.map +1 -0
- package/dist/web/assets/Modal-BVbdN0gj.js +2 -0
- package/dist/web/assets/Modal-BVbdN0gj.js.map +1 -0
- package/dist/web/assets/Skeleton-D7Z-VTMo.js +2 -0
- package/dist/web/assets/Skeleton-D7Z-VTMo.js.map +1 -0
- package/dist/web/assets/cadences-B8mwchUk.js +2 -0
- package/dist/web/assets/cadences-B8mwchUk.js.map +1 -0
- package/dist/web/assets/host-grotesk-latin-ext-wght-normal-B8jkyusk.woff2 +0 -0
- package/dist/web/assets/host-grotesk-latin-wght-normal-CBa0fl4q.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/web/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-400-normal-BTotfTJu.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-400-normal-DZqxrq2p.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-500-normal-ByOcLdNv.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-500-normal-CocWQlwt.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-600-normal-71GNu3SW.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-600-normal-BGq0mW3O.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-700-normal-D_uavGvn.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-700-normal-RFb1v-CK.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-400-normal-Dsrv2Tcn.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-400-normal-g30qAdWV.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-500-normal-Cs5J6C77.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-500-normal-DB5PtV2g.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-600-normal-Bz0x94Yp.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-600-normal-DUMzJB7m.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-700-normal-BmRLXWpJ.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-cyrillic-ext-700-normal-DCQwxkRk.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-400-normal-D9ESIMu3.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-400-normal-_efipK4i.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-500-normal-CuWXN6rf.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-500-normal-JMMifIXV.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-600-normal-D-CqTdkO.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-600-normal-DzTrcv_p.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-700-normal-CkZN0sRy.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-greek-700-normal-wyJ6jzdA.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-700-normal-Bth3BMcD.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-700-normal-Bxkt5Cjx.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-400-normal-C5H60-Va.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-400-normal-RBey6euL.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-500-normal-D0aIdm-b.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-500-normal-DakdToA3.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-600-normal-DIrixKbi.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-600-normal-DOrvGEcy.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-700-normal-DZH6Xh-4.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-ext-700-normal-aMgXseD4.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-400-normal-DG4YqDda.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-400-normal-fK1oJ5dG.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-500-normal-BEb3_waV.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-500-normal-e4dixQRQ.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-600-normal-DgdngZtN.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-600-normal-DpPYBSTl.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-700-normal-BV5B8Are.woff +0 -0
- package/dist/web/assets/ibm-plex-sans-vietnamese-700-normal-CkEo6LDy.woff2 +0 -0
- package/dist/web/assets/index-DkobhtBa.js +60 -0
- package/dist/web/assets/index-DkobhtBa.js.map +1 -0
- package/dist/web/assets/index-Dovjfyuq.css +2 -0
- package/dist/web/assets/measure-DLFAK1ZQ.js +2 -0
- package/dist/web/assets/measure-DLFAK1ZQ.js.map +1 -0
- package/dist/web/assets/plays-BUfo3QKZ.js +2 -0
- package/dist/web/assets/plays-BUfo3QKZ.js.map +1 -0
- package/dist/web/assets/queue-0mKz6GO1.js +2 -0
- package/dist/web/assets/queue-0mKz6GO1.js.map +1 -0
- package/dist/web/assets/receipts-CzIfb6zY.js +2 -0
- package/dist/web/assets/receipts-CzIfb6zY.js.map +1 -0
- package/dist/web/assets/routes-BEYqVix5.js +2 -0
- package/dist/web/assets/routes-BEYqVix5.js.map +1 -0
- package/dist/web/assets/run._playName-CJIjxoPb.js +5 -0
- package/dist/web/assets/run._playName-CJIjxoPb.js.map +1 -0
- package/dist/web/assets/setup-CFmdIoj0.js +2 -0
- package/dist/web/assets/setup-CFmdIoj0.js.map +1 -0
- package/dist/web/index.html +14 -0
- package/package.json +46 -0
package/dist/bin.mjs.map
ADDED
|
@@ -0,0 +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,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,QAAO,EAAE,GAAG,UAAU;AACpD,KAAI;EACF,MAAM,MAAM,aAAa,aAAa,OAAO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