@egbe-ai/opencode 0.0.0-stage → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (479) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +124 -2
  3. package/index.js +5 -0
  4. package/package.json +55 -4
  5. package/plugin.js +230 -0
  6. package/session-log.js +315 -0
  7. package/skills/.egbe-catalog/manifest.json +1 -0
  8. package/skills/egbe-os-analytics/SKILL.md +499 -0
  9. package/skills/egbe-os-analytics/canonical-events.v1.json +256 -0
  10. package/skills/egbe-os-analytics/references/session-funnel.md +130 -0
  11. package/skills/egbe-os-analytics/references/workflows/activation-tracking.md +147 -0
  12. package/skills/egbe-os-analytics/references/workflows/landing-click-tracking.md +209 -0
  13. package/skills/egbe-os-analytics/references/workflows/payment-lifecycle-tracking.md +122 -0
  14. package/skills/egbe-os-analytics/references/workflows/product-funnel-tracking.md +77 -0
  15. package/skills/egbe-os-analytics/references/workflows/signup-lifecycle-tracking.md +208 -0
  16. package/skills/egbe-os-analytics/scripts/umami_funnel.py +927 -0
  17. package/skills/egbe-os-apollo-lead-finder/SKILL.md +135 -0
  18. package/skills/egbe-os-apollo-lead-finder/references/operations.md +240 -0
  19. package/skills/egbe-os-apollo-lead-finder/scripts/enrich.js +6 -0
  20. package/skills/egbe-os-apollo-lead-finder/scripts/enrich.sh +4 -0
  21. package/skills/egbe-os-apollo-lead-finder/scripts/find-leads.js +6 -0
  22. package/skills/egbe-os-apollo-lead-finder/scripts/find-leads.sh +4 -0
  23. package/skills/egbe-os-apollo-lead-finder/scripts/lib/apollo-client.js +343 -0
  24. package/skills/egbe-os-apollo-lead-finder/scripts/lib/connection-identity.js +17 -0
  25. package/skills/egbe-os-apollo-lead-finder/scripts/lib/helpers.js +127 -0
  26. package/skills/egbe-os-apollo-lead-finder/scripts/lib/places-filters.js +217 -0
  27. package/skills/egbe-os-apollo-lead-finder/scripts/lib/sourcing.js +153 -0
  28. package/skills/egbe-os-apollo-lead-finder/scripts/places-leads.js +653 -0
  29. package/skills/egbe-os-apollo-lead-finder/scripts/places-leads.sh +4 -0
  30. package/skills/egbe-os-apollo-lead-finder/scripts/search.js +6 -0
  31. package/skills/egbe-os-apollo-lead-finder/scripts/search.sh +4 -0
  32. package/skills/egbe-os-campaign-landing-page/SKILL.md +95 -0
  33. package/skills/egbe-os-campaign-landing-page/agents/openai.yaml +4 -0
  34. package/skills/egbe-os-campaign-landing-page/references/leads-calendar-and-tracking.md +66 -0
  35. package/skills/egbe-os-campaign-landing-page/references/os-wiring.md +58 -0
  36. package/skills/egbe-os-campaign-landing-page/references/qa.md +40 -0
  37. package/skills/egbe-os-campaign-landing-page/references/routing.md +32 -0
  38. package/skills/egbe-os-db/SKILL.md +174 -0
  39. package/skills/egbe-os-deploy/SKILL.md +412 -0
  40. package/skills/egbe-os-design/SKILL.md +182 -0
  41. package/skills/egbe-os-design-landing-page/SKILL.md +117 -0
  42. package/skills/egbe-os-design-landing-page/agents/openai.yaml +4 -0
  43. package/skills/egbe-os-design-landing-page/assets/scaffold/.dockerignore +11 -0
  44. package/skills/egbe-os-design-landing-page/assets/scaffold/AGENTS.md +31 -0
  45. package/skills/egbe-os-design-landing-page/assets/scaffold/Dockerfile +21 -0
  46. package/skills/egbe-os-design-landing-page/assets/scaffold/eslint.config.mjs +18 -0
  47. package/skills/egbe-os-design-landing-page/assets/scaffold/next.config.ts +11 -0
  48. package/skills/egbe-os-design-landing-page/assets/scaffold/package.json +36 -0
  49. package/skills/egbe-os-design-landing-page/assets/scaffold/postcss.config.mjs +7 -0
  50. package/skills/egbe-os-design-landing-page/assets/scaffold/public/.gitkeep +1 -0
  51. package/skills/egbe-os-design-landing-page/assets/scaffold/sentry.edge.config.ts +13 -0
  52. package/skills/egbe-os-design-landing-page/assets/scaffold/sentry.server.config.ts +13 -0
  53. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/global-error.tsx +19 -0
  54. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/globals.css +22 -0
  55. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/layout.tsx +21 -0
  56. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/page.tsx +3 -0
  57. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/privacy/page.tsx +28 -0
  58. package/skills/egbe-os-design-landing-page/assets/scaffold/src/components/egbe-analytics.tsx +39 -0
  59. package/skills/egbe-os-design-landing-page/assets/scaffold/src/instrumentation-client.ts +15 -0
  60. package/skills/egbe-os-design-landing-page/assets/scaffold/src/instrumentation.ts +13 -0
  61. package/skills/egbe-os-design-landing-page/assets/scaffold/src/lib/egbe-observability.generated.ts +20 -0
  62. package/skills/egbe-os-design-landing-page/assets/scaffold/src/lib/utils.ts +6 -0
  63. package/skills/egbe-os-design-landing-page/assets/scaffold/tsconfig.json +34 -0
  64. package/skills/egbe-os-design-landing-page/references/application-preparation.md +44 -0
  65. package/skills/egbe-os-design-landing-page/references/page-inputs.md +22 -0
  66. package/skills/egbe-os-destination-readiness/SKILL.md +132 -0
  67. package/skills/egbe-os-destination-readiness/references/checks.md +130 -0
  68. package/skills/egbe-os-destination-readiness/references/network-requirements.md +34 -0
  69. package/skills/egbe-os-destination-readiness/references/report.md +116 -0
  70. package/skills/egbe-os-domains/SKILL.md +189 -0
  71. package/skills/egbe-os-errors/SKILL.md +259 -0
  72. package/skills/egbe-os-git/SKILL.md +275 -0
  73. package/skills/egbe-os-git/references/issues.md +33 -0
  74. package/skills/egbe-os-google-ads/SKILL.md +163 -0
  75. package/skills/egbe-os-google-ads/references/artifacts.md +133 -0
  76. package/skills/egbe-os-google-ads/references/campaigns.md +157 -0
  77. package/skills/egbe-os-google-ads/references/conversions.md +153 -0
  78. package/skills/egbe-os-google-ads/references/delivery.md +128 -0
  79. package/skills/egbe-os-google-ads/references/keyword-ideas.md +40 -0
  80. package/skills/egbe-os-google-ads/references/reporting.md +105 -0
  81. package/skills/egbe-os-google-ads/references/search-assets.md +219 -0
  82. package/skills/egbe-os-google-ads/references/server-conversions.md +119 -0
  83. package/skills/egbe-os-google-auth/SKILL.md +285 -0
  84. package/skills/egbe-os-google-auth/agents/openai.yaml +4 -0
  85. package/skills/egbe-os-gtm-knowledge/SKILL.md +151 -0
  86. package/skills/egbe-os-images/SKILL.md +163 -0
  87. package/skills/egbe-os-images/references/stock-images.md +21 -0
  88. package/skills/egbe-os-instantly-campaign-launcher/SKILL.md +127 -0
  89. package/skills/egbe-os-instantly-campaign-launcher/references/instantly-ops.md +260 -0
  90. package/skills/egbe-os-instantly-campaign-launcher/references/observation-and-scheduling.md +188 -0
  91. package/skills/egbe-os-instantly-campaign-launcher/references/reply-handling.md +116 -0
  92. package/skills/egbe-os-instantly-campaign-launcher/references/run-spec-template.json +65 -0
  93. package/skills/egbe-os-instantly-campaign-launcher/references/run-state.md +145 -0
  94. package/skills/egbe-os-instantly-campaign-launcher/scripts/conclude-campaign.js +158 -0
  95. package/skills/egbe-os-instantly-campaign-launcher/scripts/install-crons.js +956 -0
  96. package/skills/egbe-os-instantly-campaign-launcher/scripts/launch-campaign.js +2008 -0
  97. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/campaign-metrics.js +124 -0
  98. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/confirmed-opt-outs.js +208 -0
  99. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/connection-identity.js +17 -0
  100. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/create-once.js +23 -0
  101. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/gtm-identity.js +125 -0
  102. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/helpers.js +545 -0
  103. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/html-body.js +266 -0
  104. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/instantly-client.js +328 -0
  105. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/outreach-db.js +370 -0
  106. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/recipient-exclusion/index.js +86 -0
  107. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/replenish-test-harness.js +53 -0
  108. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/reply-queue.js +67 -0
  109. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/run-config.js +103 -0
  110. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/sender-selection.js +105 -0
  111. package/skills/egbe-os-instantly-campaign-launcher/scripts/monitor-campaign.js +607 -0
  112. package/skills/egbe-os-instantly-campaign-launcher/scripts/outreach-report.js +147 -0
  113. package/skills/egbe-os-instantly-campaign-launcher/scripts/replenish-leads.js +619 -0
  114. package/skills/egbe-os-instantly-campaign-launcher/scripts/reply-worker.js +258 -0
  115. package/skills/egbe-os-instantly-campaign-launcher/scripts/run-cron-job.js +32 -0
  116. package/skills/egbe-os-instantly-campaign-launcher/scripts/send-reply.js +260 -0
  117. package/skills/egbe-os-linkedin-ads/SKILL.md +114 -0
  118. package/skills/egbe-os-linkedin-ads/references/destination-requirements.md +30 -0
  119. package/skills/egbe-os-linkedin-ads/references/runtime/api-reference.md +154 -0
  120. package/skills/egbe-os-linkedin-ads/references/runtime/artifacts.md +63 -0
  121. package/skills/egbe-os-linkedin-ads/references/workflows/build-paused.md +44 -0
  122. package/skills/egbe-os-linkedin-ads/references/workflows/conversions.md +88 -0
  123. package/skills/egbe-os-linkedin-ads/references/workflows/launch-and-pause.md +49 -0
  124. package/skills/egbe-os-linkedin-ads/references/workflows/monitoring.md +35 -0
  125. package/skills/egbe-os-linkedin-ads/references/workflows/readiness.md +63 -0
  126. package/skills/egbe-os-linkedin-ads/references/workflows/targeting-and-creative.md +52 -0
  127. package/skills/egbe-os-llm/SKILL.md +160 -0
  128. package/skills/egbe-os-mail/SKILL.md +180 -0
  129. package/skills/egbe-os-me/SKILL.md +119 -0
  130. package/skills/egbe-os-meta-ads/SKILL.md +114 -0
  131. package/skills/egbe-os-meta-ads/references/creative/creative-specs.md +15 -0
  132. package/skills/egbe-os-meta-ads/references/creative/talking-head.md +35 -0
  133. package/skills/egbe-os-meta-ads/references/destination-requirements.md +30 -0
  134. package/skills/egbe-os-meta-ads/references/runtime/api-reference.md +436 -0
  135. package/skills/egbe-os-meta-ads/references/runtime/artifacts.md +51 -0
  136. package/skills/egbe-os-meta-ads/references/runtime/insights-reference.md +187 -0
  137. package/skills/egbe-os-meta-ads/references/runtime/pixel-install.md +196 -0
  138. package/skills/egbe-os-meta-ads/references/runtime/shared-analytics-attribution.md +16 -0
  139. package/skills/egbe-os-meta-ads/references/workflows/build-paused.md +36 -0
  140. package/skills/egbe-os-meta-ads/references/workflows/launch-ready.md +16 -0
  141. package/skills/egbe-os-meta-ads/references/workflows/launch.md +23 -0
  142. package/skills/egbe-os-meta-ads/references/workflows/monitoring.md +72 -0
  143. package/skills/egbe-os-meta-ads/references/workflows/pause.md +17 -0
  144. package/skills/egbe-os-meta-ads/references/workflows/recovery.md +23 -0
  145. package/skills/egbe-os-meta-ads/scripts/check-pixel.py +229 -0
  146. package/skills/egbe-os-meta-ads/scripts/validate-meta-artifacts.py +187 -0
  147. package/skills/egbe-os-notifications/SKILL.md +78 -0
  148. package/skills/egbe-os-openai-ads/SKILL.md +149 -0
  149. package/skills/egbe-os-openai-ads/references/creative/chat-card.md +51 -0
  150. package/skills/egbe-os-openai-ads/references/destination-requirements.md +29 -0
  151. package/skills/egbe-os-openai-ads/references/runtime/api-reference.md +219 -0
  152. package/skills/egbe-os-openai-ads/references/runtime/artifacts.md +169 -0
  153. package/skills/egbe-os-openai-ads/references/workflows/build-paused.md +40 -0
  154. package/skills/egbe-os-openai-ads/references/workflows/conversions.md +40 -0
  155. package/skills/egbe-os-openai-ads/references/workflows/creative-assembly.md +24 -0
  156. package/skills/egbe-os-openai-ads/references/workflows/launch.md +27 -0
  157. package/skills/egbe-os-openai-ads/references/workflows/monitoring.md +54 -0
  158. package/skills/egbe-os-openai-ads/references/workflows/pause.md +22 -0
  159. package/skills/egbe-os-openai-ads/references/workflows/readiness.md +37 -0
  160. package/skills/egbe-os-openai-ads/references/workflows/tracking.md +32 -0
  161. package/skills/egbe-os-openai-ads/scripts/validate-openai-artifacts.py +271 -0
  162. package/skills/egbe-os-organic-trend-watch/SKILL.md +139 -0
  163. package/skills/egbe-os-organic-trend-watch/agents/openai.yaml +4 -0
  164. package/skills/egbe-os-organic-trend-watch/references/analysis-and-adaptation.md +54 -0
  165. package/skills/egbe-os-organic-trend-watch/references/collection-and-analysis.md +117 -0
  166. package/skills/egbe-os-organic-trend-watch/references/output-contract.md +133 -0
  167. package/skills/egbe-os-organic-trend-watch/references/provider-contract.md +169 -0
  168. package/skills/egbe-os-organic-trend-watch/references/runtime-contract.md +204 -0
  169. package/skills/egbe-os-organic-trend-watch/references/visual-analysis-prompt.md +17 -0
  170. package/skills/egbe-os-organic-trend-watch/scripts/_analysis.py +612 -0
  171. package/skills/egbe-os-organic-trend-watch/scripts/_contract.py +1133 -0
  172. package/skills/egbe-os-organic-trend-watch/scripts/_provider_inputs.py +165 -0
  173. package/skills/egbe-os-organic-trend-watch/scripts/analyze-visual-evidence.py +315 -0
  174. package/skills/egbe-os-organic-trend-watch/scripts/build-provider-inputs.py +88 -0
  175. package/skills/egbe-os-organic-trend-watch/scripts/connection_identity.py +22 -0
  176. package/skills/egbe-os-organic-trend-watch/scripts/egbe_artifacts.py +24 -0
  177. package/skills/egbe-os-organic-trend-watch/scripts/finalize-receipt.py +106 -0
  178. package/skills/egbe-os-organic-trend-watch/scripts/normalize-videos.py +647 -0
  179. package/skills/egbe-os-organic-trend-watch/scripts/prepare-visual-evidence.py +324 -0
  180. package/skills/egbe-os-organic-trend-watch/scripts/render-result.py +30 -0
  181. package/skills/egbe-os-organic-trend-watch/scripts/run-apify.py +723 -0
  182. package/skills/egbe-os-organic-trend-watch/scripts/run-state.py +192 -0
  183. package/skills/egbe-os-organic-trend-watch/scripts/validate-context.py +27 -0
  184. package/skills/egbe-os-organic-trend-watch/scripts/validate-runtime.py +137 -0
  185. package/skills/egbe-os-payments/SKILL.md +215 -0
  186. package/skills/egbe-os-payments/agents/openai.yaml +4 -0
  187. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/.egbe/scaffolds/billing-nextjs-subscription.v1.json +5 -0
  188. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/AGENTS.append.md +13 -0
  189. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/db/migrations/1000_egbe_billing.sql +66 -0
  190. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/package.fragment.json +12 -0
  191. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/scripts/billing-sync.mjs +162 -0
  192. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/error.tsx +11 -0
  193. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/loading.tsx +8 -0
  194. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/page.tsx +121 -0
  195. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/checkout/route.ts +102 -0
  196. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/portal/route.ts +54 -0
  197. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/status/route.ts +22 -0
  198. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/payments/webhook/route.ts +65 -0
  199. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/components/egbe-billing/plan-badge.tsx +16 -0
  200. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/billing-sync.test.mjs +58 -0
  201. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/catalog.ts +82 -0
  202. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/checkout-payload.ts +47 -0
  203. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/foundation-contract.test.mjs +59 -0
  204. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.d.ts +16 -0
  205. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.mjs +82 -0
  206. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.test.mjs +94 -0
  207. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/os-client.ts +96 -0
  208. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/plans.json +17 -0
  209. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/repository.ts +325 -0
  210. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/signature.d.ts +6 -0
  211. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/signature.mjs +22 -0
  212. package/skills/egbe-os-payments/references/contracts/plan-catalog.md +46 -0
  213. package/skills/egbe-os-payments/references/security/durable-verification.md +64 -0
  214. package/skills/egbe-os-payments/references/security/server-integration.md +26 -0
  215. package/skills/egbe-os-payments/references/security/webhook-and-entitlements.md +152 -0
  216. package/skills/egbe-os-payments/references/ux/billing-experience.md +47 -0
  217. package/skills/egbe-os-payments/references/workflows/account-billing.md +64 -0
  218. package/skills/egbe-os-payments/references/workflows/discounts-and-promotion-codes.md +265 -0
  219. package/skills/egbe-os-payments/references/workflows/one-time-purchase.md +75 -0
  220. package/skills/egbe-os-payments/references/workflows/product-checkout.md +355 -0
  221. package/skills/egbe-os-payments/references/workflows/subscription-lifecycle.md +55 -0
  222. package/skills/egbe-os-playbook/SKILL.md +79 -0
  223. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/email-outreach.md +91 -0
  224. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/google-search.md +40 -0
  225. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/linkedin.md +24 -0
  226. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/meta.md +23 -0
  227. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/openai.md +15 -0
  228. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/reddit.md +56 -0
  229. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/choose-test.md +73 -0
  230. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/evaluate.md +91 -0
  231. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/market.md +96 -0
  232. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/run-test.md +111 -0
  233. package/skills/egbe-os-playbook/playbooks/market-and-acquisition.md +56 -0
  234. package/skills/egbe-os-playbook/playbooks/product/business-loop.md +141 -0
  235. package/skills/egbe-os-playbook/playbooks/product/collaboration.md +26 -0
  236. package/skills/egbe-os-playbook/playbooks/product/deliver.md +75 -0
  237. package/skills/egbe-os-playbook/playbooks/product/diagnose.md +80 -0
  238. package/skills/egbe-os-playbook/playbooks/product/evaluate.md +67 -0
  239. package/skills/egbe-os-playbook/playbooks/product/experience.md +132 -0
  240. package/skills/egbe-os-playbook/playbooks/product/loop-examples.md +67 -0
  241. package/skills/egbe-os-playbook/playbooks/product/offer.md +65 -0
  242. package/skills/egbe-os-playbook/playbooks/product/value.md +91 -0
  243. package/skills/egbe-os-playbook/playbooks/product.md +67 -0
  244. package/skills/egbe-os-playbook/references/catalog.md +127 -0
  245. package/skills/egbe-os-playbook/references/changes.md +167 -0
  246. package/skills/egbe-os-playbook/scripts/playbook-changes.py +6 -0
  247. package/skills/egbe-os-playbook/scripts/playbook_changes/__init__.py +1 -0
  248. package/skills/egbe-os-playbook/scripts/playbook_changes/cli.py +57 -0
  249. package/skills/egbe-os-playbook/scripts/playbook_changes/operations.py +137 -0
  250. package/skills/egbe-os-playbook/scripts/playbook_changes/protocol.py +132 -0
  251. package/skills/egbe-os-playbook/scripts/playbook_changes/storage.py +180 -0
  252. package/skills/egbe-os-playbook/scripts/playbook_changes/transport.py +113 -0
  253. package/skills/egbe-os-product-auth/SKILL.md +151 -0
  254. package/skills/egbe-os-product-auth/agents/openai.yaml +4 -0
  255. package/skills/egbe-os-product-auth/assets/db/README.md +102 -0
  256. package/skills/egbe-os-product-auth/assets/db/create-validation-session.mjs +223 -0
  257. package/skills/egbe-os-product-auth/assets/db/migrate.mjs +64 -0
  258. package/skills/egbe-os-product-auth/assets/db/migrations/0001_auth.sql +33 -0
  259. package/skills/egbe-os-product-auth/assets/db/migrations/0002_auth_identities.sql +16 -0
  260. package/skills/egbe-os-product-auth/assets/scaffolds/product-auth-database/AGENTS.append.md +17 -0
  261. package/skills/egbe-os-product-auth/assets/scaffolds/product-auth-database/package.fragment.json +10 -0
  262. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/AGENTS.append.md +9 -0
  263. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/package.fragment.json +13 -0
  264. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/db.ts +31 -0
  265. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/identity.ts +94 -0
  266. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/index.ts +3 -0
  267. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/session.ts +91 -0
  268. package/skills/egbe-os-product-auth/references/contracts/live-auth-interface.md +108 -0
  269. package/skills/egbe-os-product-auth/references/frameworks/nextjs.md +34 -0
  270. package/skills/egbe-os-product-auth/references/security/session-and-credentials.md +73 -0
  271. package/skills/egbe-os-product-auth/references/ux/auth-experience.md +58 -0
  272. package/skills/egbe-os-product-auth/references/workflows/account-recovery.md +22 -0
  273. package/skills/egbe-os-product-auth/references/workflows/build-auth.md +212 -0
  274. package/skills/egbe-os-product-auth/references/workflows/google.md +34 -0
  275. package/skills/egbe-os-product-auth/references/workflows/passwordless-email.md +65 -0
  276. package/skills/egbe-os-product-build/SKILL.md +111 -0
  277. package/skills/egbe-os-product-build/agents/openai.yaml +4 -0
  278. package/skills/egbe-os-product-build/references/capabilities.md +25 -0
  279. package/skills/egbe-os-product-build/references/engineering.md +72 -0
  280. package/skills/egbe-os-product-build/references/execution.md +55 -0
  281. package/skills/egbe-os-product-build/references/foundations.md +93 -0
  282. package/skills/egbe-os-product-build/references/interface-quality.md +32 -0
  283. package/skills/egbe-os-product-build/references/workflows/private-review-handoff.md +86 -0
  284. package/skills/egbe-os-product-build/scripts/scaffold.py +296 -0
  285. package/skills/egbe-os-product-demo-video/SKILL.md +118 -0
  286. package/skills/egbe-os-product-demo-video/references/recording.md +32 -0
  287. package/skills/egbe-os-product-market-research/SKILL.md +159 -0
  288. package/skills/egbe-os-product-market-research/agents/openai.yaml +4 -0
  289. package/skills/egbe-os-product-market-research/references/catalog.v1.json +177 -0
  290. package/skills/egbe-os-product-market-research/references/config/channel-footprint-sources.v1.json +99 -0
  291. package/skills/egbe-os-product-market-research/references/config/creative-taxonomy.v1.json +367 -0
  292. package/skills/egbe-os-product-market-research/references/contracts/creative-video.md +75 -0
  293. package/skills/egbe-os-product-market-research/references/contracts/funnel-teardown.md +235 -0
  294. package/skills/egbe-os-product-market-research/references/contracts/geography-comparison.md +71 -0
  295. package/skills/egbe-os-product-market-research/references/contracts/lifecycle-capture.md +119 -0
  296. package/skills/egbe-os-product-market-research/references/contracts/research-artifacts.md +520 -0
  297. package/skills/egbe-os-product-market-research/references/contracts/walk-mechanics.v2.json +18 -0
  298. package/skills/egbe-os-product-market-research/references/prompts/acquisition-channels.md +137 -0
  299. package/skills/egbe-os-product-market-research/references/prompts/acquisition-channels.user.md +4 -0
  300. package/skills/egbe-os-product-market-research/references/prompts/competitive-landscape.md +118 -0
  301. package/skills/egbe-os-product-market-research/references/prompts/competitive-landscape.user.md +4 -0
  302. package/skills/egbe-os-product-market-research/references/prompts/demand-validation.md +154 -0
  303. package/skills/egbe-os-product-market-research/references/prompts/demand-validation.user.md +4 -0
  304. package/skills/egbe-os-product-market-research/references/prompts/market-size-and-dynamics.md +100 -0
  305. package/skills/egbe-os-product-market-research/references/prompts/market-size-and-dynamics.user.md +4 -0
  306. package/skills/egbe-os-product-market-research/references/prompts/pricing-and-monetization.md +126 -0
  307. package/skills/egbe-os-product-market-research/references/prompts/pricing-and-monetization.user.md +4 -0
  308. package/skills/egbe-os-product-market-research/references/prompts/target-audience.md +98 -0
  309. package/skills/egbe-os-product-market-research/references/prompts/target-audience.user.md +4 -0
  310. package/skills/egbe-os-product-market-research/references/prompts/unit-economics.md +217 -0
  311. package/skills/egbe-os-product-market-research/references/prompts/unit-economics.user.md +4 -0
  312. package/skills/egbe-os-product-market-research/references/prompts/value-proposition.md +113 -0
  313. package/skills/egbe-os-product-market-research/references/prompts/value-proposition.user.md +4 -0
  314. package/skills/egbe-os-product-market-research/references/workflows/acquisition-channels.md +27 -0
  315. package/skills/egbe-os-product-market-research/references/workflows/channel-footprint.md +163 -0
  316. package/skills/egbe-os-product-market-research/references/workflows/community-demand.md +100 -0
  317. package/skills/egbe-os-product-market-research/references/workflows/competitive-landscape.md +27 -0
  318. package/skills/egbe-os-product-market-research/references/workflows/competitor-ads.md +82 -0
  319. package/skills/egbe-os-product-market-research/references/workflows/competitor-set.md +300 -0
  320. package/skills/egbe-os-product-market-research/references/workflows/creative-patterns.md +228 -0
  321. package/skills/egbe-os-product-market-research/references/workflows/demand-validation.md +27 -0
  322. package/skills/egbe-os-product-market-research/references/workflows/fleet-prior.md +80 -0
  323. package/skills/egbe-os-product-market-research/references/workflows/funnel-teardown.md +184 -0
  324. package/skills/egbe-os-product-market-research/references/workflows/geography-comparison.md +84 -0
  325. package/skills/egbe-os-product-market-research/references/workflows/keyword-economics.md +122 -0
  326. package/skills/egbe-os-product-market-research/references/workflows/lifecycle-capture.md +218 -0
  327. package/skills/egbe-os-product-market-research/references/workflows/local-research.md +55 -0
  328. package/skills/egbe-os-product-market-research/references/workflows/market-size-and-dynamics.md +27 -0
  329. package/skills/egbe-os-product-market-research/references/workflows/preview.md +175 -0
  330. package/skills/egbe-os-product-market-research/references/workflows/pricing-and-monetization.md +27 -0
  331. package/skills/egbe-os-product-market-research/references/workflows/recommendations.md +35 -0
  332. package/skills/egbe-os-product-market-research/references/workflows/review-mining.md +76 -0
  333. package/skills/egbe-os-product-market-research/references/workflows/target-audience.md +27 -0
  334. package/skills/egbe-os-product-market-research/references/workflows/tiktok-reels-market-trends.md +46 -0
  335. package/skills/egbe-os-product-market-research/references/workflows/unit-economics.md +27 -0
  336. package/skills/egbe-os-product-market-research/references/workflows/value-proposition.md +27 -0
  337. package/skills/egbe-os-product-market-research/scripts/build-organic-trend-context.py +167 -0
  338. package/skills/egbe-os-product-market-research/scripts/build-preview-context.py +91 -0
  339. package/skills/egbe-os-product-market-research/scripts/build-research-query.py +225 -0
  340. package/skills/egbe-os-product-market-research/scripts/channel-footprint-model.py +294 -0
  341. package/skills/egbe-os-product-market-research/scripts/connection_identity.py +22 -0
  342. package/skills/egbe-os-product-market-research/scripts/creative-model.py +364 -0
  343. package/skills/egbe-os-product-market-research/scripts/creative-selection.py +113 -0
  344. package/skills/egbe-os-product-market-research/scripts/creative-semantics.py +365 -0
  345. package/skills/egbe-os-product-market-research/scripts/creative-video.py +542 -0
  346. package/skills/egbe-os-product-market-research/scripts/egbe_artifacts.py +24 -0
  347. package/skills/egbe-os-product-market-research/scripts/finalize-organic-trend-watch.py +304 -0
  348. package/skills/egbe-os-product-market-research/scripts/funnel-email-review.py +97 -0
  349. package/skills/egbe-os-product-market-research/scripts/funnel-model.py +966 -0
  350. package/skills/egbe-os-product-market-research/scripts/funnel_features.py +50 -0
  351. package/skills/egbe-os-product-market-research/scripts/geography-comparison-contract.py +172 -0
  352. package/skills/egbe-os-product-market-research/scripts/geography-comparison.py +169 -0
  353. package/skills/egbe-os-product-market-research/scripts/keyword-forecast.py +61 -0
  354. package/skills/egbe-os-product-market-research/scripts/keyword-locale-publication.py +136 -0
  355. package/skills/egbe-os-product-market-research/scripts/lifecycle-start.py +190 -0
  356. package/skills/egbe-os-product-market-research/scripts/persist-research-report.py +63 -0
  357. package/skills/egbe-os-product-market-research/scripts/research-artifact-io.py +281 -0
  358. package/skills/egbe-os-product-market-research/scripts/research-evidence.py +496 -0
  359. package/skills/egbe-os-product-market-research/scripts/research-policy.py +33 -0
  360. package/skills/egbe-os-product-market-research/scripts/research-section-runtime.py +343 -0
  361. package/skills/egbe-os-product-market-research/scripts/research-section-workflow.py +288 -0
  362. package/skills/egbe-os-product-market-research/scripts/research_integrity.py +122 -0
  363. package/skills/egbe-os-product-market-research/scripts/review-research-completion.py +306 -0
  364. package/skills/egbe-os-product-market-research/scripts/run-acquisition-channels.py +72 -0
  365. package/skills/egbe-os-product-market-research/scripts/run-channel-footprint.py +2258 -0
  366. package/skills/egbe-os-product-market-research/scripts/run-community-demand.py +1603 -0
  367. package/skills/egbe-os-product-market-research/scripts/run-competitive-landscape.py +66 -0
  368. package/skills/egbe-os-product-market-research/scripts/run-competitor-ads.py +1156 -0
  369. package/skills/egbe-os-product-market-research/scripts/run-competitor-set.py +2514 -0
  370. package/skills/egbe-os-product-market-research/scripts/run-creative-patterns.py +2042 -0
  371. package/skills/egbe-os-product-market-research/scripts/run-demand-validation.py +72 -0
  372. package/skills/egbe-os-product-market-research/scripts/run-fleet-prior.py +652 -0
  373. package/skills/egbe-os-product-market-research/scripts/run-funnel-teardown.py +493 -0
  374. package/skills/egbe-os-product-market-research/scripts/run-keyword-economics.py +1443 -0
  375. package/skills/egbe-os-product-market-research/scripts/run-lifecycle-capture.py +1543 -0
  376. package/skills/egbe-os-product-market-research/scripts/run-market-size-and-dynamics.py +66 -0
  377. package/skills/egbe-os-product-market-research/scripts/run-os-research.py +311 -0
  378. package/skills/egbe-os-product-market-research/scripts/run-pricing-and-monetization.py +71 -0
  379. package/skills/egbe-os-product-market-research/scripts/run-review-mining.py +1051 -0
  380. package/skills/egbe-os-product-market-research/scripts/run-target-audience.py +66 -0
  381. package/skills/egbe-os-product-market-research/scripts/run-unit-economics.py +71 -0
  382. package/skills/egbe-os-product-market-research/scripts/run-value-proposition.py +67 -0
  383. package/skills/egbe-os-product-market-research/scripts/upsert-markdown-section.py +156 -0
  384. package/skills/egbe-os-product-market-research/scripts/walk-funnels.py +249 -0
  385. package/skills/egbe-os-product-market-research/scripts/write-preview.py +710 -0
  386. package/skills/egbe-os-product-market-research/scripts/write-recommendations.py +272 -0
  387. package/skills/egbe-os-product-report/SKILL.md +150 -0
  388. package/skills/egbe-os-product-report/references/artifacts.md +84 -0
  389. package/skills/egbe-os-product-report/references/brief.md +34 -0
  390. package/skills/egbe-os-product-report/references/daily.md +76 -0
  391. package/skills/egbe-os-product-report/references/sources.md +68 -0
  392. package/skills/egbe-os-product-routines/SKILL.md +166 -0
  393. package/skills/egbe-os-product-routines/references/catalog.md +22 -0
  394. package/skills/egbe-os-product-routines/references/continuation-check.md +41 -0
  395. package/skills/egbe-os-product-routines/references/product-reporting.md +163 -0
  396. package/skills/egbe-os-product-routines/references/run-preset.md +32 -0
  397. package/skills/egbe-os-quickstart/scripts/egbe-curl.py +357 -0
  398. package/skills/egbe-os-quiz-funnel/SKILL.md +152 -0
  399. package/skills/egbe-os-quiz-funnel/agents/openai.yaml +4 -0
  400. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.d.mts +224 -0
  401. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.mjs +652 -0
  402. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.test.mjs +764 -0
  403. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.d.mts +31 -0
  404. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.mjs +87 -0
  405. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.test.mjs +265 -0
  406. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-reference.test.mjs +254 -0
  407. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/QUIZ.md +195 -0
  408. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/quiz.json +421 -0
  409. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/quiz.public.json +369 -0
  410. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/validation.json +21 -0
  411. package/skills/egbe-os-quiz-funnel/assets/reference/index.html +26 -0
  412. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-bootstrap.js +31 -0
  413. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-early-actions.mjs +11 -0
  414. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-first-screen.mjs +32 -0
  415. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-page.mjs +480 -0
  416. package/skills/egbe-os-quiz-funnel/assets/reference/quiz.css +264 -0
  417. package/skills/egbe-os-quiz-funnel/references/competitor-teardown.md +159 -0
  418. package/skills/egbe-os-quiz-funnel/references/conversion-handoff.md +156 -0
  419. package/skills/egbe-os-quiz-funnel/references/implementation.md +207 -0
  420. package/skills/egbe-os-quiz-funnel/references/inputs.md +37 -0
  421. package/skills/egbe-os-quiz-funnel/references/measurement.md +122 -0
  422. package/skills/egbe-os-quiz-funnel/references/spec-contract.md +335 -0
  423. package/skills/egbe-os-quiz-funnel/references/verification.md +101 -0
  424. package/skills/egbe-os-quiz-funnel/references/walk-mechanics.v2.json +18 -0
  425. package/skills/egbe-os-quiz-funnel/scripts/compile-quiz-spec.py +1869 -0
  426. package/skills/egbe-os-quiz-funnel/scripts/prepare-research-identity.py +66 -0
  427. package/skills/egbe-os-reddit-ads/SKILL.md +121 -0
  428. package/skills/egbe-os-reddit-ads/assets/static-banners/bold-statement/schema.json +41 -0
  429. package/skills/egbe-os-reddit-ads/assets/static-banners/bold-statement/template.html +106 -0
  430. package/skills/egbe-os-reddit-ads/assets/static-banners/data-proof/schema.json +61 -0
  431. package/skills/egbe-os-reddit-ads/assets/static-banners/data-proof/template.html +151 -0
  432. package/skills/egbe-os-reddit-ads/assets/static-banners/honest-breakdown/schema.json +91 -0
  433. package/skills/egbe-os-reddit-ads/assets/static-banners/honest-breakdown/template.html +185 -0
  434. package/skills/egbe-os-reddit-ads/assets/static-banners/question-hook/schema.json +51 -0
  435. package/skills/egbe-os-reddit-ads/assets/static-banners/question-hook/template.html +121 -0
  436. package/skills/egbe-os-reddit-ads/assets/static-banners/reddit-post-style/schema.json +87 -0
  437. package/skills/egbe-os-reddit-ads/assets/static-banners/reddit-post-style/template.html +212 -0
  438. package/skills/egbe-os-reddit-ads/references/creative/html-to-png-pipeline.md +123 -0
  439. package/skills/egbe-os-reddit-ads/references/creative/static-banner-qa.md +12 -0
  440. package/skills/egbe-os-reddit-ads/references/creative/static-banner-system.md +16 -0
  441. package/skills/egbe-os-reddit-ads/references/destination-requirements.md +36 -0
  442. package/skills/egbe-os-reddit-ads/references/runtime/api-reference.md +435 -0
  443. package/skills/egbe-os-reddit-ads/references/runtime/artifacts.md +57 -0
  444. package/skills/egbe-os-reddit-ads/references/runtime/monitoring.md +64 -0
  445. package/skills/egbe-os-reddit-ads/references/runtime/pixel-and-tracking.md +49 -0
  446. package/skills/egbe-os-reddit-ads/references/runtime/policies.md +19 -0
  447. package/skills/egbe-os-reddit-ads/references/runtime/shared-analytics-attribution.md +14 -0
  448. package/skills/egbe-os-reddit-ads/references/workflows/build-paused.md +35 -0
  449. package/skills/egbe-os-reddit-ads/references/workflows/launch-ready.md +19 -0
  450. package/skills/egbe-os-reddit-ads/references/workflows/launch.md +32 -0
  451. package/skills/egbe-os-reddit-ads/references/workflows/readiness.md +9 -0
  452. package/skills/egbe-os-reddit-ads/scripts/capture-ad.sh +178 -0
  453. package/skills/egbe-os-reddit-ads/scripts/validate-reddit-artifacts.py +187 -0
  454. package/skills/egbe-os-report-ui/SKILL.md +133 -0
  455. package/skills/egbe-os-report-ui/assets/egbe-wordmark.svg +9 -0
  456. package/skills/egbe-os-report-ui/assets/examples/components.html +417 -0
  457. package/skills/egbe-os-report-ui/assets/examples/editorial.html +209 -0
  458. package/skills/egbe-os-report-ui/assets/scaffold.html +179 -0
  459. package/skills/egbe-os-report-ui/references/components.md +209 -0
  460. package/skills/egbe-os-research/SKILL.md +125 -0
  461. package/skills/egbe-os-saas-unit-economics/SKILL.md +188 -0
  462. package/skills/egbe-os-scrape/SKILL.md +160 -0
  463. package/skills/egbe-os-search/SKILL.md +182 -0
  464. package/skills/egbe-os-search/references/google-places.md +81 -0
  465. package/skills/egbe-os-support/SKILL.md +149 -0
  466. package/skills/egbe-os-telemetry/SKILL.md +344 -0
  467. package/skills/egbe-os-telemetry/references/harnesses/claude-code.md +97 -0
  468. package/skills/egbe-os-telemetry/references/harnesses/codex.md +22 -0
  469. package/skills/egbe-os-telemetry/references/harnesses/hermes.md +39 -0
  470. package/skills/egbe-os-telemetry/references/harnesses/openclaw.md +139 -0
  471. package/skills/egbe-os-telemetry/references/harnesses/opencode.md +28 -0
  472. package/skills/egbe-os-tools/SKILL.md +180 -0
  473. package/skills/egbe-os-tools/references/theona.md +26 -0
  474. package/skills/egbe-os-wallet/SKILL.md +181 -0
  475. package/skills/egbe-setup/EGBE.md +484 -0
  476. package/skills/egbe-setup/SKILL.md +116 -0
  477. package/skills/egbe-setup/references/project.md +80 -0
  478. package/state.js +37 -0
  479. package/update.js +361 -0
@@ -0,0 +1,370 @@
1
+ const path = require("path");
2
+ const { DatabaseSync } = require("node:sqlite");
3
+ const { ensureDir, isoNow, normalizeEmail } = require("./helpers");
4
+
5
+ function dbPathForRun(runDir) {
6
+ // runDir = egbe-docs/marketing/campaigns/instantly/<id>
7
+ return path.resolve(runDir, "..", "outreach.db");
8
+ }
9
+
10
+ const _dbCache = new Map();
11
+
12
+ function openDb(dbPath) {
13
+ let db = _dbCache.get(dbPath);
14
+ if (db) return db;
15
+ ensureDir(path.dirname(dbPath));
16
+ db = new DatabaseSync(dbPath);
17
+ // Committed campaign state must be portable in the tracked database file,
18
+ // not split between it and an untracked WAL. Quiesce workers before Git sync.
19
+ db.exec("PRAGMA journal_mode=DELETE;");
20
+ db.exec("PRAGMA foreign_keys=ON;");
21
+ db.exec("PRAGMA busy_timeout=5000;");
22
+ _dbCache.set(dbPath, db);
23
+ return db;
24
+ }
25
+
26
+ function columnExists(db, table, column) {
27
+ try {
28
+ const rows = db.prepare(`PRAGMA table_info(${table});`).all();
29
+ return rows.some((r) => r.name === column);
30
+ } catch (_) {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ function ensureColumn(db, table, column, definition) {
36
+ if (columnExists(db, table, column)) return;
37
+ try {
38
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition};`);
39
+ } catch (_) {
40
+ // ignore: race or already-added
41
+ }
42
+ }
43
+
44
+ function initDb(runDir) {
45
+ const dbPath = dbPathForRun(runDir);
46
+ const db = openDb(dbPath);
47
+
48
+ db.exec(`
49
+ CREATE TABLE IF NOT EXISTS outreach_runs (
50
+ run_key TEXT PRIMARY KEY,
51
+ product_name TEXT NOT NULL,
52
+ segment_name TEXT NOT NULL,
53
+ offer_headline TEXT NOT NULL,
54
+ campaign_id TEXT,
55
+ campaign_name TEXT,
56
+ status TEXT NOT NULL DEFAULT 'draft',
57
+ verdict TEXT,
58
+ verdict_reason TEXT,
59
+ reply_rate REAL,
60
+ concluded_at TEXT,
61
+ created_at TEXT NOT NULL,
62
+ updated_at TEXT NOT NULL
63
+ );
64
+
65
+ CREATE TABLE IF NOT EXISTS leads (
66
+ email TEXT PRIMARY KEY,
67
+ first_name TEXT,
68
+ last_name TEXT,
69
+ company_name TEXT,
70
+ website TEXT,
71
+ title TEXT,
72
+ linkedin_url TEXT,
73
+ city TEXT,
74
+ state TEXT,
75
+ country TEXT,
76
+ source TEXT NOT NULL,
77
+ source_ref TEXT,
78
+ email_status TEXT,
79
+ created_at TEXT NOT NULL,
80
+ updated_at TEXT NOT NULL
81
+ );
82
+
83
+ CREATE TABLE IF NOT EXISTS run_leads (
84
+ run_key TEXT NOT NULL,
85
+ email TEXT NOT NULL,
86
+ campaign_id TEXT,
87
+ imported_at TEXT,
88
+ verification_status TEXT NOT NULL DEFAULT 'pending',
89
+ last_known_status TEXT NOT NULL DEFAULT 'new',
90
+ last_contacted_at TEXT,
91
+ last_replied_at TEXT,
92
+ last_bounced_at TEXT,
93
+ last_unsubscribed_at TEXT,
94
+ reply_intent TEXT,
95
+ ownership_tag TEXT,
96
+ notes TEXT,
97
+ created_at TEXT NOT NULL,
98
+ updated_at TEXT NOT NULL,
99
+ PRIMARY KEY (run_key, email),
100
+ FOREIGN KEY (run_key) REFERENCES outreach_runs(run_key),
101
+ FOREIGN KEY (email) REFERENCES leads(email)
102
+ );
103
+
104
+ CREATE TABLE IF NOT EXISTS lead_events (
105
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
106
+ run_key TEXT NOT NULL,
107
+ email TEXT NOT NULL,
108
+ event_type TEXT NOT NULL,
109
+ event_at TEXT NOT NULL,
110
+ payload_json TEXT,
111
+ FOREIGN KEY (run_key) REFERENCES outreach_runs(run_key),
112
+ FOREIGN KEY (email) REFERENCES leads(email)
113
+ );
114
+
115
+ CREATE TABLE IF NOT EXISTS reply_queue (
116
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
117
+ run_key TEXT NOT NULL,
118
+ email TEXT NOT NULL,
119
+ message_id TEXT,
120
+ intent TEXT NOT NULL,
121
+ recommended_reply TEXT,
122
+ status TEXT NOT NULL DEFAULT 'pending',
123
+ created_at TEXT NOT NULL,
124
+ updated_at TEXT NOT NULL,
125
+ FOREIGN KEY (run_key) REFERENCES outreach_runs(run_key),
126
+ FOREIGN KEY (email) REFERENCES leads(email)
127
+ );
128
+
129
+ CREATE INDEX IF NOT EXISTS idx_run_leads_campaign_id ON run_leads(campaign_id);
130
+ CREATE INDEX IF NOT EXISTS idx_run_leads_status ON run_leads(last_known_status);
131
+ CREATE INDEX IF NOT EXISTS idx_lead_events_run_key ON lead_events(run_key);
132
+ CREATE INDEX IF NOT EXISTS idx_lead_events_email ON lead_events(email);
133
+ CREATE INDEX IF NOT EXISTS idx_reply_queue_status ON reply_queue(status);
134
+
135
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_confirmed_opt_out_message
136
+ ON lead_events(run_key, email, json_extract(payload_json, '$.message_id'))
137
+ WHERE event_type = 'opt_out_confirmed';
138
+ -- A run's report/reply rebuild must not erase project-wide refusals.
139
+ -- Foreign keys also retain the referenced run and recipient records.
140
+ CREATE TRIGGER IF NOT EXISTS preserve_confirmed_opt_out
141
+ BEFORE DELETE ON lead_events WHEN OLD.event_type = 'opt_out_confirmed'
142
+ BEGIN SELECT RAISE(IGNORE); END;
143
+ `);
144
+
145
+ // Backfill columns added after the original schema.
146
+ ensureColumn(db, "outreach_runs", "verdict", "TEXT");
147
+ ensureColumn(db, "outreach_runs", "verdict_reason", "TEXT");
148
+ ensureColumn(db, "outreach_runs", "reply_rate", "REAL");
149
+ ensureColumn(db, "outreach_runs", "concluded_at", "TEXT");
150
+ db.exec(
151
+ `CREATE INDEX IF NOT EXISTS idx_outreach_runs_product_concluded
152
+ ON outreach_runs(product_name, concluded_at);`,
153
+ );
154
+
155
+ return dbPath;
156
+ }
157
+
158
+ function upsertRun(dbPath, run) {
159
+ const db = openDb(dbPath);
160
+ const now = isoNow();
161
+ db.prepare(
162
+ `INSERT INTO outreach_runs (
163
+ run_key, product_name, segment_name, offer_headline,
164
+ campaign_id, campaign_name, status, created_at, updated_at
165
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
166
+ ON CONFLICT(run_key) DO UPDATE SET
167
+ product_name = excluded.product_name,
168
+ segment_name = excluded.segment_name,
169
+ offer_headline = excluded.offer_headline,
170
+ campaign_id = excluded.campaign_id,
171
+ campaign_name = excluded.campaign_name,
172
+ status = excluded.status,
173
+ updated_at = excluded.updated_at;`,
174
+ ).run(
175
+ run.run_key,
176
+ run.product_name || "Unknown product",
177
+ run.segment_name || "Unknown segment",
178
+ run.offer_headline || "Unknown offer",
179
+ run.campaign_id ?? null,
180
+ run.campaign_name ?? null,
181
+ run.status || "draft",
182
+ run.created_at || now,
183
+ now,
184
+ );
185
+ }
186
+
187
+ function inferLeadSource(lead) {
188
+ if (lead.source) return lead.source;
189
+ if (lead.apollo_id) return "apollo";
190
+ return "import";
191
+ }
192
+
193
+ function inferLeadSourceRef(lead) {
194
+ return lead.source_ref || lead.apollo_id || null;
195
+ }
196
+
197
+ function upsertLead(dbPath, lead) {
198
+ const email = normalizeEmail(lead.email);
199
+ if (!email) return;
200
+ const db = openDb(dbPath);
201
+ const now = isoNow();
202
+ db.prepare(
203
+ `INSERT INTO leads (
204
+ email, first_name, last_name, company_name, website,
205
+ title, linkedin_url, city, state, country,
206
+ source, source_ref, email_status, created_at, updated_at
207
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
208
+ ON CONFLICT(email) DO UPDATE SET
209
+ first_name = COALESCE(excluded.first_name, leads.first_name),
210
+ last_name = COALESCE(excluded.last_name, leads.last_name),
211
+ company_name = COALESCE(excluded.company_name, leads.company_name),
212
+ website = COALESCE(excluded.website, leads.website),
213
+ title = COALESCE(excluded.title, leads.title),
214
+ linkedin_url = COALESCE(excluded.linkedin_url, leads.linkedin_url),
215
+ city = COALESCE(excluded.city, leads.city),
216
+ state = COALESCE(excluded.state, leads.state),
217
+ country = COALESCE(excluded.country, leads.country),
218
+ source = COALESCE(excluded.source, leads.source),
219
+ source_ref = COALESCE(excluded.source_ref, leads.source_ref),
220
+ email_status = COALESCE(excluded.email_status, leads.email_status),
221
+ updated_at = excluded.updated_at;`,
222
+ ).run(
223
+ email,
224
+ lead.first_name || lead.firstName || null,
225
+ lead.last_name || lead.lastName || null,
226
+ lead.company_name || lead.companyName || null,
227
+ lead.website || null,
228
+ lead.title || null,
229
+ lead.linkedin_url || lead.linkedinUrl || null,
230
+ lead.city || null,
231
+ lead.state || null,
232
+ lead.country || null,
233
+ inferLeadSource(lead),
234
+ inferLeadSourceRef(lead),
235
+ lead.email_status || null,
236
+ now,
237
+ now,
238
+ );
239
+ }
240
+
241
+ function upsertRunLead(dbPath, entry) {
242
+ const email = normalizeEmail(entry.email);
243
+ if (!entry.run_key || !email) return;
244
+ const db = openDb(dbPath);
245
+ const now = isoNow();
246
+ db.prepare(
247
+ `INSERT INTO run_leads (
248
+ run_key, email, campaign_id, imported_at, verification_status,
249
+ last_known_status, last_contacted_at, last_replied_at, last_bounced_at,
250
+ last_unsubscribed_at, reply_intent, ownership_tag, notes, created_at, updated_at
251
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
252
+ ON CONFLICT(run_key, email) DO UPDATE SET
253
+ campaign_id = COALESCE(excluded.campaign_id, run_leads.campaign_id),
254
+ imported_at = COALESCE(excluded.imported_at, run_leads.imported_at),
255
+ verification_status = COALESCE(excluded.verification_status, run_leads.verification_status),
256
+ last_known_status = COALESCE(excluded.last_known_status, run_leads.last_known_status),
257
+ last_contacted_at = COALESCE(excluded.last_contacted_at, run_leads.last_contacted_at),
258
+ last_replied_at = COALESCE(excluded.last_replied_at, run_leads.last_replied_at),
259
+ last_bounced_at = COALESCE(excluded.last_bounced_at, run_leads.last_bounced_at),
260
+ last_unsubscribed_at = COALESCE(excluded.last_unsubscribed_at, run_leads.last_unsubscribed_at),
261
+ reply_intent = COALESCE(excluded.reply_intent, run_leads.reply_intent),
262
+ ownership_tag = COALESCE(excluded.ownership_tag, run_leads.ownership_tag),
263
+ notes = COALESCE(excluded.notes, run_leads.notes),
264
+ updated_at = excluded.updated_at;`,
265
+ ).run(
266
+ entry.run_key,
267
+ email,
268
+ entry.campaign_id || null,
269
+ entry.imported_at || null,
270
+ entry.verification_status || "pending",
271
+ entry.last_known_status || "new",
272
+ entry.last_contacted_at || null,
273
+ entry.last_replied_at || null,
274
+ entry.last_bounced_at || null,
275
+ entry.last_unsubscribed_at || null,
276
+ entry.reply_intent || null,
277
+ entry.ownership_tag || null,
278
+ entry.notes || null,
279
+ now,
280
+ now,
281
+ );
282
+ }
283
+
284
+ function insertLeadEvent(dbPath, event) {
285
+ const email = normalizeEmail(event.email);
286
+ if (!event.run_key || !email || !event.event_type) return;
287
+ const db = openDb(dbPath);
288
+ db.prepare(
289
+ `INSERT INTO lead_events (run_key, email, event_type, event_at, payload_json)
290
+ VALUES (?, ?, ?, ?, ?);`,
291
+ ).run(
292
+ event.run_key,
293
+ email,
294
+ event.event_type,
295
+ event.event_at || isoNow(),
296
+ event.payload_json ? JSON.stringify(event.payload_json) : null,
297
+ );
298
+ }
299
+
300
+ function confirmOptOut(dbPath, { run_key, email, message_id, campaign_id, event_at }) {
301
+ email = normalizeEmail(email);
302
+ if (!run_key || !email || !message_id || !campaign_id)
303
+ throw new Error("Confirmed opt-out requires run, campaign recipient and source message ID");
304
+ const db = openDb(dbPath);
305
+ const result = db.prepare(
306
+ `INSERT OR IGNORE INTO lead_events (run_key, email, event_type, event_at, payload_json)
307
+ VALUES (?, ?, 'opt_out_confirmed', ?, ?);`,
308
+ ).run(run_key, email, event_at || isoNow(), JSON.stringify({ message_id, campaign_id }));
309
+ return { inserted: result.changes === 1, email, message_id };
310
+ }
311
+
312
+ function upsertReplyQueueItem(dbPath, item) {
313
+ const email = normalizeEmail(item.email);
314
+ if (!item.run_key || !email || !item.intent) return;
315
+ const db = openDb(dbPath);
316
+ const now = isoNow();
317
+ db.prepare(
318
+ `INSERT INTO reply_queue (
319
+ run_key, email, message_id, intent, recommended_reply,
320
+ status, created_at, updated_at
321
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`,
322
+ ).run(
323
+ item.run_key,
324
+ email,
325
+ item.message_id || null,
326
+ item.intent,
327
+ item.recommended_reply || null,
328
+ item.status || "pending",
329
+ now,
330
+ now,
331
+ );
332
+ }
333
+
334
+ function setReplyQueueStatus(dbPath, { run_key, message_id, status }) {
335
+ if (!run_key || !message_id || !status) return;
336
+ const db = openDb(dbPath);
337
+ db.prepare(
338
+ `UPDATE reply_queue SET status = ?, updated_at = ?
339
+ WHERE run_key = ? AND message_id = ?;`,
340
+ ).run(status, isoNow(), run_key, message_id);
341
+ }
342
+
343
+ function queryAll(dbPath, sql, params = []) {
344
+ const db = openDb(dbPath);
345
+ return db.prepare(sql).all(...params);
346
+ }
347
+
348
+ function queryAllReadOnly(dbPath, sql, params = []) {
349
+ const db = new DatabaseSync(dbPath, { readOnly: true });
350
+ try {
351
+ db.exec("PRAGMA busy_timeout=5000;");
352
+ return db.prepare(sql).all(...params);
353
+ } finally {
354
+ db.close();
355
+ }
356
+ }
357
+
358
+ module.exports = {
359
+ dbPathForRun,
360
+ initDb,
361
+ upsertRun,
362
+ upsertLead,
363
+ upsertRunLead,
364
+ insertLeadEvent,
365
+ confirmOptOut,
366
+ upsertReplyQueueItem,
367
+ setReplyQueueStatus,
368
+ queryAll,
369
+ queryAllReadOnly,
370
+ };
@@ -0,0 +1,86 @@
1
+ const validId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
2
+ const successful = response => response?.status >= 200 && response.status < 300;
3
+
4
+ async function listLeadRows(client, campaignId) {
5
+ const rows = [];
6
+ const ids = new Set();
7
+ const cursors = new Set();
8
+ let cursor;
9
+ for (let page = 0; page < 1000; page++) {
10
+ let response;
11
+ try { response = await client.listLeads(campaignId, { limit: 100, starting_after: cursor }); }
12
+ catch { return { ok: false, rows }; }
13
+ if (!successful(response)) return { ok: false, rows };
14
+ const body = response.body;
15
+ const items = Array.isArray(body) ? body : body?.items;
16
+ if (!Array.isArray(items)) return { ok: false, rows };
17
+ for (const row of items) {
18
+ if (!validId(row?.id) || ids.has(row.id)
19
+ || row.campaign !== campaignId
20
+ || (Object.hasOwn(row, 'campaign_id') && row.campaign_id !== campaignId)
21
+ || typeof row.email !== 'string' || !row.email.trim()) return { ok: false, rows };
22
+ ids.add(row.id);
23
+ rows.push(row);
24
+ }
25
+ // Native continuation is authoritative even on short pages. Legacy array
26
+ // and older gateway responses use last-ID pagination on full pages only.
27
+ const declared = !Array.isArray(body) && Object.hasOwn(body, 'next_starting_after');
28
+ const next = declared ? body.next_starting_after : (items.length >= 100 ? items.at(-1)?.id : null);
29
+ if (next == null || next === '') return { ok: true, rows };
30
+ if (!items.length || typeof next !== 'string' || !next.trim() || next.length > 512
31
+ || cursors.has(next)) return { ok: false, rows };
32
+ cursors.add(next);
33
+ cursor = next;
34
+ }
35
+ return { ok: false, rows };
36
+ }
37
+
38
+ function confirmedEvidence(response, campaignId, leadId) {
39
+ const body = response?.body;
40
+ return successful(response) && body?.state === 'confirmed'
41
+ && body.campaign_id === campaignId && body.lead_id === leadId
42
+ && body.scope === 'main_campaign_sequence'
43
+ && body.lead_status === 3 && body.interest_status === -1
44
+ && typeof body.observed_at === 'string' && Number.isFinite(Date.parse(body.observed_at));
45
+ }
46
+
47
+ // Caller supplies persisted refusal authority; native labels cannot create it.
48
+ // Every matching retained copy needs its own fresh, owned semantic readback.
49
+ async function assessRecipient(client, campaignId, email, { confirmed = false, mutate = false, population = null } = {}) {
50
+ if (!confirmed) return { state: 'unknown', reason: 'local_refusal_unconfirmed' };
51
+ const members = population || await listLeadRows(client, campaignId);
52
+ if (!members.ok) return { state: 'unknown', reason: 'membership_unavailable' };
53
+ const matching = members.rows.filter(row => row.email.trim().toLowerCase() === email.trim().toLowerCase());
54
+ if (!matching.length) return { state: 'absent', evidence: [] };
55
+ const evidence = [];
56
+ for (const lead of matching) {
57
+ let response;
58
+ try {
59
+ response = await client.getRecipientExclusion(campaignId, lead.id);
60
+ // Once an uncertain write occurred, GET is the only automatic recovery.
61
+ if (!confirmedEvidence(response, campaignId, lead.id) && mutate && successful(response)
62
+ && response.body?.state === 'eligible'
63
+ && response.body.campaign_id === campaignId && response.body.lead_id === lead.id
64
+ && response.body.scope === 'main_campaign_sequence') {
65
+ try { response = await client.excludeRecipient(campaignId, lead.id); }
66
+ catch { response = null; }
67
+ if (!confirmedEvidence(response, campaignId, lead.id))
68
+ response = await client.getRecipientExclusion(campaignId, lead.id);
69
+ }
70
+ } catch { response = null; }
71
+ evidence.push({ lead_id: lead.id, confirmed: confirmedEvidence(response, campaignId, lead.id),
72
+ result: successful(response) ? response.body : null });
73
+ }
74
+ return { state: evidence.every(item => item.confirmed) ? 'excluded' : 'unknown', evidence };
75
+ }
76
+
77
+ async function assessCampaignOptOuts(client, campaignId, emails) {
78
+ const population = await listLeadRows(client, campaignId);
79
+ if (!population.ok) return { ok: false, reason: 'campaign_membership_unavailable', recipients: [] };
80
+ const recipients = [];
81
+ for (const email of emails) recipients.push({ email,
82
+ ...await assessRecipient(client, campaignId, email, { confirmed: true, population }) });
83
+ return { ok: recipients.every(row => ['absent', 'excluded'].includes(row.state)), recipients };
84
+ }
85
+
86
+ module.exports = { listLeadRows, assessRecipient, assessCampaignOptOuts, confirmedEvidence };
@@ -0,0 +1,53 @@
1
+ // Shared fixtures for replenish-leads tests: a run dir with manifest, run-spec,
2
+ // carry-over and DB row, a mock OS outreach server, and the script runner.
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const http = require("node:http");
7
+ const { spawn } = require("node:child_process");
8
+ const { initDb, upsertRun } = require("./outreach-db");
9
+
10
+ function makeRun(carryOver, prefix = "replenish-") {
11
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
12
+ const runDir = path.join(root, "runs", "test");
13
+ const stateDir = path.join(runDir, "state");
14
+ fs.mkdirSync(stateDir, { recursive: true });
15
+ const write = (name, value) => fs.writeFileSync(path.join(runDir, name), JSON.stringify(value));
16
+ write("manifest.json", { run_key: "test-run", campaign: { id: "c", name: "test-campaign" } });
17
+ write("run-spec.json", { product: { name: "test" }, segment: { name: "test" }, offer: { headline: "test" },
18
+ lead_replenishment: { enabled: true, batch_size: 1, max_total_leads: 250,
19
+ max_replenishments: 4, utilization_threshold: 0.8, cooldown_minutes: 0 } });
20
+ write("state/carry-over-leads.json", carryOver);
21
+ const dbPath = initDb(runDir);
22
+ upsertRun(dbPath, { run_key: "test-run", product_name: "test", segment_name: "test", offer_headline: "test", campaign_id: "c", status: "launched" });
23
+ return { root, runDir, stateDir, dbPath, cleanup: () => fs.rmSync(root, { recursive: true, force: true }) };
24
+ }
25
+
26
+ // handler(endpoint, req) returns { status = 200, data }, or null for a 400.
27
+ async function startServer(handler) {
28
+ const srv = http.createServer((req, res) => {
29
+ const reply = handler(req.url.split("?")[0], req);
30
+ req.resume();
31
+ res.writeHead(reply ? reply.status ?? 200 : 400, { "content-type": "application/json" });
32
+ res.end(JSON.stringify({ data: reply?.data }));
33
+ });
34
+ await new Promise((resolve) => srv.listen(0, "127.0.0.1", resolve));
35
+ return { url: `http://127.0.0.1:${srv.address().port}`, close: () => srv.close() };
36
+ }
37
+
38
+ function replenish(runDir, url, extraArgs = []) {
39
+ return new Promise((resolve, reject) => {
40
+ const child = spawn(process.execPath, [path.join(__dirname, "../replenish-leads.js"), "--run-dir", runDir, ...extraArgs], {
41
+ env: { ...process.env, OS_API_KEY: "test", OS_URL: url },
42
+ stdio: ["ignore", "pipe", "pipe"],
43
+ });
44
+ let stdout = "";
45
+ let stderr = "";
46
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
47
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
48
+ child.on("error", reject);
49
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
50
+ });
51
+ }
52
+
53
+ module.exports = { makeRun, startServer, replenish };
@@ -0,0 +1,67 @@
1
+ // reply-queue.json is shared by reply-worker.js (adds items) and send-reply.js
2
+ // (changes their status). Every change goes through updateQueue: one writer at
3
+ // a time (a lock directory next to the file) and an atomic replace, so two
4
+ // processes cannot overwrite each other's updates.
5
+ const fs = require("fs");
6
+ const path = require("path");
7
+
8
+ const STALE_LOCK_MS = 10 * 60 * 1000;
9
+
10
+ function pause(ms) {
11
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
12
+ }
13
+
14
+ function updateQueue(runDir, change, { waitMs = 30000 } = {}) {
15
+ const file = path.join(runDir, "reply-queue.json");
16
+ const lock = path.join(runDir, ".reply-queue.lock");
17
+ const deadline = Date.now() + waitMs;
18
+ for (;;) {
19
+ try {
20
+ fs.mkdirSync(lock);
21
+ break;
22
+ } catch (err) {
23
+ if (err.code !== "EEXIST") throw err;
24
+ let age = 0;
25
+ try {
26
+ age = Date.now() - fs.statSync(lock).mtimeMs;
27
+ } catch {}
28
+ // A holder never keeps the lock longer than one read-modify-write; a
29
+ // lock this old was left by a killed process.
30
+ if (age > STALE_LOCK_MS) {
31
+ // Rename first: only one waiter can move the stale lock away, so two
32
+ // waiters cannot both remove it and enter together.
33
+ const moved = `${lock}.stale.${process.pid}.${Date.now()}`;
34
+ try {
35
+ fs.renameSync(lock, moved);
36
+ // Another waiter may have replaced the stale lock with its own in
37
+ // the meantime; a fresh one goes back where it was.
38
+ if (Date.now() - fs.statSync(moved).mtimeMs <= STALE_LOCK_MS) {
39
+ fs.renameSync(moved, lock);
40
+ } else {
41
+ fs.rmSync(moved, { recursive: true, force: true });
42
+ }
43
+ } catch (renameErr) {
44
+ if (renameErr.code !== "ENOENT") throw renameErr;
45
+ }
46
+ continue;
47
+ }
48
+ if (Date.now() > deadline)
49
+ throw new Error(`Reply queue is locked by another process: ${lock}`);
50
+ pause(200);
51
+ }
52
+ }
53
+ try {
54
+ const queue = fs.existsSync(file)
55
+ ? JSON.parse(fs.readFileSync(file, "utf8"))
56
+ : [];
57
+ const result = change(queue);
58
+ const tmp = `${file}.${process.pid}.tmp`;
59
+ fs.writeFileSync(tmp, JSON.stringify(queue, null, 2) + "\n");
60
+ fs.renameSync(tmp, file);
61
+ return result;
62
+ } finally {
63
+ fs.rmSync(lock, { recursive: true, force: true });
64
+ }
65
+ }
66
+
67
+ module.exports = { updateQueue };
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+
3
+ // Execution bounds are authored for the run. Do not infer a marketing plan.
4
+ function numberIn(value, min, max = Infinity, integer = false) {
5
+ return typeof value === "number" && Number.isFinite(value) && value >= min &&
6
+ value <= max && (!integer || Number.isInteger(value));
7
+ }
8
+
9
+ function replenishmentConfig(spec) {
10
+ const config = spec.lead_replenishment;
11
+ if (config?.enabled !== true) return null;
12
+ const checks = {
13
+ batch_size: numberIn(config.batch_size, 1, Infinity, true),
14
+ max_total_leads: numberIn(config.max_total_leads, 1, Infinity, true),
15
+ max_replenishments: numberIn(config.max_replenishments, 0, Infinity, true),
16
+ utilization_threshold: numberIn(config.utilization_threshold, 0, 1),
17
+ cooldown_minutes: numberIn(config.cooldown_minutes, 0),
18
+ };
19
+ const missing = Object.keys(checks).filter(key => !checks[key]);
20
+ if (missing.length) throw new Error(`Enabled lead_replenishment requires explicit valid bounds: ${missing.join(", ")}`);
21
+ return config;
22
+ }
23
+
24
+ function protectionConfig(spec) {
25
+ const thresholds = spec.monitoring?.thresholds || {};
26
+ const errors = [];
27
+ if (!numberIn(thresholds.max_bounce_rate, 0, 100))
28
+ errors.push("monitoring.thresholds.max_bounce_rate must be an explicit percentage (0–100)");
29
+ if (thresholds.max_spam_complaint_rate !== undefined &&
30
+ !numberIn(thresholds.max_spam_complaint_rate, 0, 100))
31
+ errors.push("max_spam_complaint_rate must be a percentage when this signal is monitored");
32
+ if (spec.monitoring?.autopause_on_risk !== undefined &&
33
+ typeof spec.monitoring.autopause_on_risk !== "boolean")
34
+ errors.push("autopause_on_risk must be boolean");
35
+ return { valid: !errors.length, errors,
36
+ autopause: spec.monitoring?.autopause_on_risk !== false,
37
+ thresholds: {
38
+ max_bounce_rate: thresholds.max_bounce_rate ?? null,
39
+ max_spam_complaint_rate: thresholds.max_spam_complaint_rate ?? null,
40
+ },
41
+ denominator: "contacted_count",
42
+ };
43
+ }
44
+
45
+ function validateLaunchConfig(spec) {
46
+ if (!numberIn(spec.campaign?.daily_limit, 1, Infinity, true))
47
+ throw new Error("campaign.daily_limit must be an explicit positive integer (campaign-wide daily cap)");
48
+ if (spec.campaign.daily_max_new_leads !== undefined &&
49
+ !numberIn(spec.campaign.daily_max_new_leads, 0, Infinity, true))
50
+ throw new Error("campaign.daily_max_new_leads must be a non-negative integer");
51
+ replenishmentConfig(spec);
52
+ if (spec.campaign.activate_on_launch === true) {
53
+ const protection = protectionConfig(spec);
54
+ if (!protection.valid) throw new Error(`Cannot activate: ${protection.errors.join("; ")}`);
55
+ }
56
+ }
57
+
58
+ function metricNumber(value) {
59
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
60
+ }
61
+
62
+ function initialBatchLimit(spec, existingCount, candidateCount) {
63
+ const config = replenishmentConfig(spec);
64
+ if (!config) return candidateCount;
65
+ if (!numberIn(existingCount, 0, Infinity, true))
66
+ throw new Error("A complete campaign member count is required before a bounded import");
67
+ return Math.min(candidateCount, config.batch_size, Math.max(0, config.max_total_leads - existingCount));
68
+ }
69
+
70
+ function evaluateProtection(spec, metrics) {
71
+ const config = protectionConfig(spec);
72
+ const triggered = [], skipped = [], evaluated = [];
73
+ if (!config.valid) triggered.push({ gate: "configuration", value: null,
74
+ threshold: null, reason: config.errors.join("; ") });
75
+ const contacted = metricNumber(metrics.contacted_count);
76
+ const hasActivity = ["emails_sent_count", "new_leads_contacted_count", "reply_count_unique",
77
+ "bounced_count", "spam_complaint_count", "spam_count"].some(key => metricNumber(metrics[key]) > 0);
78
+ for (const [gate, key, raw] of [
79
+ ["bounce", "max_bounce_rate", metrics.bounced_count],
80
+ ["spam", "max_spam_complaint_rate", metrics.spam_complaint_count ?? metrics.spam_count],
81
+ ]) {
82
+ const threshold = config.thresholds[key];
83
+ if (threshold === null) { skipped.push({ gate, reason: "not_configured" }); continue; }
84
+ const count = metricNumber(raw);
85
+ // A scoped, consistent zero is not an outage; missing signals are not zero.
86
+ if (contacted === 0 && count === 0 && !hasActivity && !metrics._partial && !metrics._possibly_workspace_level) {
87
+ skipped.push({ gate, reason: "no_recipients_yet" }); continue;
88
+ }
89
+ if (count === null || contacted === null || contacted === 0 || count > contacted ||
90
+ metrics._partial || metrics._possibly_workspace_level) {
91
+ triggered.push({ gate: `${gate}_unavailable`, value: null, threshold,
92
+ reason: "Required campaign-scoped signal unavailable after read fallbacks" });
93
+ continue;
94
+ }
95
+ const value = count / contacted * 100;
96
+ evaluated.push(gate);
97
+ if (value > threshold) triggered.push({ gate, value, threshold, count });
98
+ }
99
+ return { ...config, contacted, triggered, skipped, evaluated };
100
+ }
101
+
102
+ module.exports = { numberIn, replenishmentConfig, protectionConfig, validateLaunchConfig, initialBatchLimit,
103
+ metricNumber, evaluateProtection };