fullstackgtm 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/CHANGELOG.md +293 -1
  2. package/INSTALL_FOR_AGENTS.md +13 -11
  3. package/README.md +45 -24
  4. package/dist/audit.d.ts +3 -1
  5. package/dist/audit.js +29 -2
  6. package/dist/backfill.d.ts +86 -0
  7. package/dist/backfill.js +251 -0
  8. package/dist/bin.js +4 -1
  9. package/dist/cli/audit.d.ts +15 -0
  10. package/dist/cli/audit.js +392 -0
  11. package/dist/cli/auth.d.ts +82 -0
  12. package/dist/cli/auth.js +607 -0
  13. package/dist/cli/backfill.d.ts +1 -0
  14. package/dist/cli/backfill.js +125 -0
  15. package/dist/cli/backfillRuns.d.ts +1 -0
  16. package/dist/cli/backfillRuns.js +187 -0
  17. package/dist/cli/call.d.ts +1 -0
  18. package/dist/cli/call.js +387 -0
  19. package/dist/cli/capabilities.d.ts +30 -0
  20. package/dist/cli/capabilities.js +197 -0
  21. package/dist/cli/draft.d.ts +7 -0
  22. package/dist/cli/draft.js +87 -0
  23. package/dist/cli/enrich.d.ts +8 -0
  24. package/dist/cli/enrich.js +806 -0
  25. package/dist/cli/fix.d.ts +33 -0
  26. package/dist/cli/fix.js +346 -0
  27. package/dist/cli/help.d.ts +25 -0
  28. package/dist/cli/help.js +646 -0
  29. package/dist/cli/icp.d.ts +7 -0
  30. package/dist/cli/icp.js +229 -0
  31. package/dist/cli/init.d.ts +7 -0
  32. package/dist/cli/init.js +58 -0
  33. package/dist/cli/market.d.ts +1 -0
  34. package/dist/cli/market.js +391 -0
  35. package/dist/cli/plans.d.ts +5 -0
  36. package/dist/cli/plans.js +456 -0
  37. package/dist/cli/schedule.d.ts +8 -0
  38. package/dist/cli/schedule.js +479 -0
  39. package/dist/cli/shared.d.ts +71 -0
  40. package/dist/cli/shared.js +342 -0
  41. package/dist/cli/signals.d.ts +7 -0
  42. package/dist/cli/signals.js +412 -0
  43. package/dist/cli/suggest.d.ts +49 -0
  44. package/dist/cli/suggest.js +135 -0
  45. package/dist/cli/tam.d.ts +9 -0
  46. package/dist/cli/tam.js +387 -0
  47. package/dist/cli/ui.d.ts +142 -0
  48. package/dist/cli/ui.js +427 -0
  49. package/dist/cli.d.ts +1 -57
  50. package/dist/cli.js +123 -5157
  51. package/dist/connector.d.ts +23 -0
  52. package/dist/connector.js +47 -0
  53. package/dist/connectors/hubspot.d.ts +10 -1
  54. package/dist/connectors/hubspot.js +244 -10
  55. package/dist/connectors/hubspotAuth.js +5 -1
  56. package/dist/connectors/linkedin.js +14 -14
  57. package/dist/connectors/salesforce.d.ts +10 -1
  58. package/dist/connectors/salesforce.js +39 -6
  59. package/dist/connectors/signalSources.js +7 -59
  60. package/dist/connectors/stripe.d.ts +37 -0
  61. package/dist/connectors/stripe.js +103 -31
  62. package/dist/enrich.d.ts +7 -0
  63. package/dist/enrich.js +7 -0
  64. package/dist/health.d.ts +11 -69
  65. package/dist/health.js +4 -134
  66. package/dist/healthScore.d.ts +71 -0
  67. package/dist/healthScore.js +143 -0
  68. package/dist/icp.d.ts +15 -11
  69. package/dist/icp.js +19 -36
  70. package/dist/index.d.ts +3 -1
  71. package/dist/index.js +3 -1
  72. package/dist/judge.d.ts +2 -0
  73. package/dist/judge.js +6 -0
  74. package/dist/llm.d.ts +29 -0
  75. package/dist/llm.js +206 -0
  76. package/dist/market.d.ts +39 -1
  77. package/dist/market.js +116 -44
  78. package/dist/marketClassify.d.ts +11 -1
  79. package/dist/marketClassify.js +17 -2
  80. package/dist/marketTaxonomy.d.ts +6 -1
  81. package/dist/marketTaxonomy.js +4 -2
  82. package/dist/mcp-bin.js +31 -2
  83. package/dist/mcp.js +372 -166
  84. package/dist/progress.d.ts +96 -0
  85. package/dist/progress.js +142 -0
  86. package/dist/runReport.d.ts +24 -0
  87. package/dist/runReport.js +139 -4
  88. package/dist/schedule.d.ts +80 -2
  89. package/dist/schedule.js +254 -1
  90. package/dist/spoolFiles.d.ts +44 -0
  91. package/dist/spoolFiles.js +114 -0
  92. package/dist/types.d.ts +29 -1
  93. package/docs/api.md +75 -8
  94. package/docs/architecture.md +2 -0
  95. package/docs/linkedin-connector-spec.md +1 -1
  96. package/docs/signal-spool-format.md +13 -0
  97. package/llms.txt +18 -9
  98. package/package.json +10 -3
  99. package/skills/fullstackgtm/SKILL.md +2 -1
  100. package/src/audit.ts +27 -1
  101. package/src/backfill.ts +340 -0
  102. package/src/bin.ts +5 -1
  103. package/src/cli/audit.ts +447 -0
  104. package/src/cli/auth.ts +669 -0
  105. package/src/cli/backfill.ts +156 -0
  106. package/src/cli/backfillRuns.ts +198 -0
  107. package/src/cli/call.ts +414 -0
  108. package/src/cli/capabilities.ts +215 -0
  109. package/src/cli/draft.ts +101 -0
  110. package/src/cli/enrich.ts +908 -0
  111. package/src/cli/fix.ts +373 -0
  112. package/src/cli/help.ts +702 -0
  113. package/src/cli/icp.ts +265 -0
  114. package/src/cli/init.ts +65 -0
  115. package/src/cli/market.ts +423 -0
  116. package/src/cli/plans.ts +524 -0
  117. package/src/cli/schedule.ts +526 -0
  118. package/src/cli/shared.ts +392 -0
  119. package/src/cli/signals.ts +434 -0
  120. package/src/cli/suggest.ts +151 -0
  121. package/src/cli/tam.ts +435 -0
  122. package/src/cli/ui.ts +497 -0
  123. package/src/cli.ts +122 -5855
  124. package/src/connector.ts +66 -0
  125. package/src/connectors/hubspot.ts +273 -9
  126. package/src/connectors/hubspotAuth.ts +5 -1
  127. package/src/connectors/linkedin.ts +14 -14
  128. package/src/connectors/salesforce.ts +51 -3
  129. package/src/connectors/signalSources.ts +7 -56
  130. package/src/connectors/stripe.ts +154 -34
  131. package/src/enrich.ts +13 -0
  132. package/src/health.ts +14 -213
  133. package/src/healthScore.ts +223 -0
  134. package/src/icp.ts +19 -35
  135. package/src/index.ts +28 -1
  136. package/src/judge.ts +7 -0
  137. package/src/llm.ts +239 -0
  138. package/src/market.ts +157 -44
  139. package/src/marketClassify.ts +26 -2
  140. package/src/marketTaxonomy.ts +10 -2
  141. package/src/mcp-bin.ts +34 -2
  142. package/src/mcp.ts +270 -63
  143. package/src/progress.ts +197 -0
  144. package/src/runReport.ts +159 -4
  145. package/src/schedule.ts +310 -3
  146. package/src/spoolFiles.ts +116 -0
  147. package/src/types.ts +32 -2
  148. package/docs/dx-punch-list.md +0 -87
  149. package/docs/roadmap-to-1.0.md +0 -211
package/src/cli/tam.ts ADDED
@@ -0,0 +1,435 @@
1
+ // Extracted verbatim from src/cli.ts (mechanical split, no behavior change).
2
+
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { getCredential } from "../credentials.ts";
6
+ import { appendCoverage, computeCoverage, coverageCountsFromSnapshot, classifyCoverage, coverageToText, deriveAcvFromClosedWon, deriveBuyersPerAccount, estimateTam, loadTamModel, projectEta, readCoverageTimeline, saveTamModel, tamReportToMarkdown, type AcvBasis, type TamCrossCheck } from "../tam.ts";
7
+ import { probeExploriumBusinessCount } from "../connectors/prospectSources.ts";
8
+ import { theirStackCountCompanies, theirStackPullCost, theirStackSearchCompanies } from "../connectors/theirstack.ts";
9
+ import { icpToExploriumBusinessFilters, icpToTheirStackFilters } from "../icp.ts";
10
+ import { scheduleCommand } from "./schedule.ts";
11
+ import { loadIcp, numericOption, option, readSnapshot, saveRequested } from "./shared.ts";
12
+ import { unknownSubcommandError } from "./suggest.ts";
13
+
14
+
15
+ /** Best-effort enrich-config load for apply-time acquire-budget enforcement. */
16
+ /** Provider API key: env override first, then the credential store (`login`). */
17
+ export function providerKey(provider: "explorium" | "pipe0" | "heyreach" | "theirstack"): string {
18
+ const envName =
19
+ provider === "explorium"
20
+ ? "EXPLORIUM_API_KEY"
21
+ : provider === "pipe0"
22
+ ? "PIPE0_API_KEY"
23
+ : provider === "theirstack"
24
+ ? "THEIRSTACK_API_KEY"
25
+ : "HEYREACH_API_KEY";
26
+ if (process.env[envName]) return process.env[envName] as string;
27
+ const stored = getCredential(provider);
28
+ if (stored) return stored.accessToken;
29
+ throw new Error(`No ${provider} credentials. Run \`echo "$KEY" | fullstackgtm login ${provider}\`, or set ${envName}.`);
30
+ }
31
+
32
+ /**
33
+ * `tam` — Total Addressable Market mapping. Estimate a defensible universe from
34
+ * the ICP, then iteratively populate it via scheduled governed acquire runs and
35
+ * track coverage over time. Subcommands: estimate, status, report, populate.
36
+ */
37
+ export async function tamCommand(args: string[]) {
38
+ const [sub, ...rest] = args;
39
+ if (!sub || args.includes("--help") || args.includes("-h")) {
40
+ console.log(`Usage:
41
+ fullstackgtm tam estimate [--name <n>] [--icp <path>] (--accounts <n> | --source theirstack|explorium)
42
+ (--acv <annual-usd> | --acv-from-crm --deal-period monthly|quarterly|annual) [--acv-basis account|buyer]
43
+ [--buyers-per-account <n>] [--cross-checks <file.json>] [source options for a baseline] [--json]
44
+ fullstackgtm tam accounts [--name <n>] [--icp <path>] --source theirstack [--max <n>] [--dry-run | --confirm] [--max-credits <n>] [--usd-per-credit <r>] [--out <file.csv> | --json]
45
+ fullstackgtm tam status [--name <n>] <source options> [--save] [--json]
46
+ fullstackgtm tam report [--name <n>] [--out <path>]
47
+ fullstackgtm tam populate [--name <n>] --cron "<expr>" [--source pipe0|explorium|linkedin] [--provider hubspot|salesforce] [--label <l>]
48
+
49
+ Estimate the reachable market FROM your ICP: a real account count × a confirmed
50
+ ANNUAL ACV (--acv <annual-usd>, or --acv-from-crm --deal-period monthly|quarterly|
51
+ annual to derive+annualize from closed-won — no band defaults, a bare --provider
52
+ does NOT set ACV, refuses without one); buyers/account (explicit or CRM-derived).
53
+ Then populate it with scheduled \`enrich acquire --save\` runs (plan-only — apply
54
+ stays a separate human gate) and watch coverage close. \`status --save\` stamps the
55
+ timeline so \`report\`/ETA can project how long full coverage will take.
56
+
57
+ --source theirstack counts (and \`tam accounts\` LISTS) companies that actually USE a
58
+ CRM/MAP (set firmographics.technologies, e.g. ["salesforce","hubspot"]) — the real
59
+ RevOps universe, with real names. --source explorium is a firmographic count only
60
+ (NAICS/size/geo, no list). See docs/tam.md.`);
61
+ return;
62
+ }
63
+ const name = option(rest, "--name") ?? "default";
64
+
65
+ if (sub === "estimate") {
66
+ const icp = loadIcp(rest);
67
+ if (!icp) {
68
+ throw new Error(
69
+ "tam estimate derives the universe from your ICP — none found (icp.json in cwd, or --icp <path>). " +
70
+ "Build one: `fullstackgtm icp interview`, or scaffold a workspace with `fullstackgtm init`.",
71
+ );
72
+ }
73
+ // The account universe: an explicit --accounts assumption, or a live count of
74
+ // matching COMPANIES. `theirstack` is technographic — it counts companies that
75
+ // actually USE a CRM/MAP (the real RevOps buying signal) and can return the
76
+ // list. `explorium` is a firmographic count only (NAICS/size/geo, no list).
77
+ let accounts = numericOption(rest, "--accounts");
78
+ let accountsSource = "assumption";
79
+ let capped = false;
80
+ const probeSource = option(rest, "--source");
81
+ if (accounts === undefined && probeSource) {
82
+ if (probeSource === "theirstack") {
83
+ const total = await theirStackCountCompanies({
84
+ apiKey: providerKey("theirstack"),
85
+ filters: icpToTheirStackFilters(icp),
86
+ });
87
+ if (total === null) {
88
+ throw new Error(
89
+ "TheirStack returned no total for the ICP — check firmographics.technologies (e.g. [\"salesforce\",\"hubspot\"]) " +
90
+ "and geos/employeeBands, or pass --accounts <n>.",
91
+ );
92
+ }
93
+ accounts = total;
94
+ accountsSource = "provider:theirstack (uses-CRM)";
95
+ } else if (probeSource === "explorium") {
96
+ const probe = await probeExploriumBusinessCount({
97
+ apiKey: providerKey("explorium"),
98
+ filters: icpToExploriumBusinessFilters(icp),
99
+ });
100
+ if (probe === null) {
101
+ throw new Error(
102
+ "Explorium /v1/businesses returned no total for the ICP firmographic — pass --accounts <n>. See docs/tam.md.",
103
+ );
104
+ }
105
+ accounts = probe.total;
106
+ capped = probe.capped;
107
+ accountsSource = capped ? "provider:explorium (≥60k cap — floor)" : "provider:explorium";
108
+ } else {
109
+ throw new Error(
110
+ `tam estimate --source must be theirstack (technographic, uses-CRM + a real list) or explorium ` +
111
+ `(firmographic count only) — got "${probeSource}". pipe0 is a population source, not a count.`,
112
+ );
113
+ }
114
+ }
115
+ if (accounts === undefined) {
116
+ throw new Error(
117
+ "tam estimate needs the account universe size: --source theirstack (count companies that use a CRM), " +
118
+ "--source explorium (firmographic count), or --accounts <n>.",
119
+ );
120
+ }
121
+ const basis = (option(rest, "--acv-basis") ?? "account") as AcvBasis;
122
+ if (basis !== "account" && basis !== "buyer") {
123
+ throw new Error(`tam: --acv-basis must be account|buyer (got "${basis}")`);
124
+ }
125
+ const ccPath = option(rest, "--cross-checks");
126
+ const crossChecks: TamCrossCheck[] = ccPath
127
+ ? (JSON.parse(readFileSync(resolve(process.cwd(), ccPath), "utf8")) as TamCrossCheck[])
128
+ : [];
129
+ // Load the CRM snapshot ONCE if a source is given — reused for the coverage
130
+ // baseline AND for deriving real ACV / buyers-per-account from the CRM.
131
+ const hasSource =
132
+ Boolean(option(rest, "--provider")) ||
133
+ Boolean(option(rest, "--input")) ||
134
+ rest.includes("--demo") ||
135
+ rest.includes("--sample");
136
+ const snapshot = hasSource ? await readSnapshot(rest) : undefined;
137
+ const baseline = snapshot ? coverageCountsFromSnapshot(snapshot) : { accounts: 0, contacts: 0 };
138
+
139
+ // ACV must be a REAL, ANNUAL figure that the operator confirms — never a band
140
+ // default, and never silently lifted from the CRM. `--provider` is the
141
+ // COVERAGE source, not the ACV: the TAM's economics aren't HubSpot's job.
142
+ // Two confirmed paths: an explicit annual `--acv`, or an opt-in
143
+ // `--acv-from-crm` that derives the median closed-won amount AND annualizes it
144
+ // per a REQUIRED `--deal-period` (a monthly MRR deal × 12 = annual ACV).
145
+ const acvExplicit = numericOption(rest, "--acv");
146
+ const acvFromCrm = rest.includes("--acv-from-crm");
147
+ let acvValue: number;
148
+ let acvSource: string;
149
+ if (acvExplicit !== undefined) {
150
+ acvValue = acvExplicit;
151
+ acvSource = "explicit (annual)";
152
+ } else if (acvFromCrm) {
153
+ if (!snapshot) {
154
+ throw new Error("--acv-from-crm needs a CRM source — add --provider <crm> or --input <snapshot>.");
155
+ }
156
+ const period = option(rest, "--deal-period");
157
+ const factor = period === "monthly" ? 12 : period === "quarterly" ? 4 : period === "annual" ? 1 : undefined;
158
+ if (factor === undefined) {
159
+ throw new Error(
160
+ "--acv-from-crm requires --deal-period monthly|quarterly|annual — deal amounts can be MRR or annual " +
161
+ "or one-time, and we won't guess (guessing the period is a 4–12× error). e.g. a $15k/mo deal needs " +
162
+ "`--deal-period monthly` → $180k annual ACV.",
163
+ );
164
+ }
165
+ const derived = deriveAcvFromClosedWon(snapshot);
166
+ if (!derived) {
167
+ throw new Error(
168
+ "--acv-from-crm found no closed-won deals with amounts in the snapshot — pass --acv <annual-usd> instead.",
169
+ );
170
+ }
171
+ acvValue = derived.valueUsd * factor;
172
+ acvSource =
173
+ `crm:closed-won (${derived.dealCount} deal${derived.dealCount === 1 ? "" : "s"}, ` +
174
+ `median $${derived.valueUsd.toLocaleString()}/${period}${factor > 1 ? ` ×${factor}` : ""} = annual)`;
175
+ } else {
176
+ throw new Error(
177
+ "tam estimate needs a real ANNUAL ACV — and it won't guess one. Pass --acv <annual-usd> (your " +
178
+ "confirmed annualized ACV), or --acv-from-crm --deal-period monthly|quarterly|annual to derive it " +
179
+ "from closed-won deals. (--provider is your coverage source, not your ACV — it no longer auto-sets it.)",
180
+ );
181
+ }
182
+
183
+ // Buyers/account — real signal (avg CRM contacts/account) or an explicit
184
+ // value; never a silent guess. With neither, a clearly-labeled minimal
185
+ // assumption of 1 (so the contact target = accounts, not an inflated number).
186
+ let buyersPerAccount = numericOption(rest, "--buyers-per-account");
187
+ let buyersSource = "explicit";
188
+ if (buyersPerAccount === undefined) {
189
+ const db = snapshot ? deriveBuyersPerAccount(snapshot) : null;
190
+ if (db) {
191
+ buyersPerAccount = db.value;
192
+ buyersSource = `crm:avg-contacts/account (${db.accountsSampled} accounts)`;
193
+ } else {
194
+ buyersPerAccount = 1;
195
+ buyersSource = "assumption:1-buyer (no CRM signal)";
196
+ console.error(
197
+ "tam: buyers/account not given and no CRM contacts to derive from — assuming 1 buyer/account. " +
198
+ "Set --buyers-per-account <n> or pass --provider for a real contacts-per-account average.",
199
+ );
200
+ }
201
+ }
202
+ const createdAt = option(rest, "--today") ?? new Date().toISOString();
203
+
204
+ const model = estimateTam({
205
+ name,
206
+ icpName: icp.name,
207
+ accounts,
208
+ accountsSource,
209
+ buyersPerAccount,
210
+ buyersSource,
211
+ // Capture the ICP filter so `tam status` can classify CRM accounts as
212
+ // in/out of THIS TAM (not just count everything).
213
+ targeting: {
214
+ geos: icp.firmographics?.geos,
215
+ employeeBands: icp.firmographics?.employeeBands,
216
+ industries: icp.firmographics?.industries,
217
+ technologies: icp.firmographics?.technologies,
218
+ },
219
+ acv: { basis, valueUsd: acvValue, source: acvSource },
220
+ crossChecks,
221
+ baseline,
222
+ createdAt,
223
+ });
224
+ saveTamModel(model);
225
+ if (rest.includes("--json")) {
226
+ console.log(JSON.stringify(model, null, 2));
227
+ return;
228
+ }
229
+ const coverage = computeCoverage(model, baseline, createdAt);
230
+ console.log(coverageToText(model, coverage, null));
231
+ if (capped) {
232
+ console.log(
233
+ `\n⚠ The account count hit Explorium's 60,000 ceiling — the true universe is LARGER. ` +
234
+ "Treat this TAM as a floor, or narrow the ICP (tighter industry/geo/size) for an exact count.",
235
+ );
236
+ }
237
+ console.log(
238
+ `\nSaved TAM "${name}". Next: schedule population with ` +
239
+ `\`fullstackgtm tam populate --name ${name} --cron "0 7 * * 1-5"\`, ` +
240
+ `then track with \`fullstackgtm tam status --name ${name} --provider hubspot --save\`.`,
241
+ );
242
+ return;
243
+ }
244
+
245
+ if (sub === "status") {
246
+ const model = loadTamModel(name);
247
+ if (!model) throw new Error(`No TAM "${name}" — run \`fullstackgtm tam estimate\` first.`);
248
+ const snapshot = await readSnapshot(rest);
249
+ const at = option(rest, "--today") ?? new Date().toISOString();
250
+ // Classify CRM accounts against THIS TAM's ICP — only in-TAM accounts count
251
+ // toward coverage; off-ICP junk lands in out-of-TAM/unknown. Reconciles
252
+ // bottom-up vs top-down (the in-TAM count is a floor on the real universe).
253
+ const coverage = classifyCoverage(model, snapshot, at);
254
+ const save = saveRequested(rest);
255
+ if (save) appendCoverage(name, coverage);
256
+ // Include the current reading in the ETA basis whether or not we persisted it.
257
+ const timeline = save ? readCoverageTimeline(name) : [...readCoverageTimeline(name), coverage];
258
+ const eta = projectEta(model, timeline);
259
+ if (rest.includes("--json")) {
260
+ console.log(JSON.stringify({ model, coverage, eta, saved: save }, null, 2));
261
+ return;
262
+ }
263
+ console.log(coverageToText(model, coverage, eta));
264
+ if (!save) console.log(`\n(reading not saved — add --save to stamp the timeline for ETA tracking)`);
265
+ return;
266
+ }
267
+
268
+ if (sub === "report") {
269
+ const model = loadTamModel(name);
270
+ if (!model) throw new Error(`No TAM "${name}" — run \`fullstackgtm tam estimate\` first.`);
271
+ const timeline = readCoverageTimeline(name);
272
+ const eta = projectEta(model, timeline);
273
+ const md = tamReportToMarkdown(model, timeline, eta);
274
+ const out = option(rest, "--out");
275
+ if (out) {
276
+ writeFileSync(resolve(process.cwd(), out), md);
277
+ console.log(`Wrote ${out}.`);
278
+ } else {
279
+ console.log(md);
280
+ }
281
+ return;
282
+ }
283
+
284
+ if (sub === "populate") {
285
+ await tamPopulate(name, rest);
286
+ return;
287
+ }
288
+
289
+ if (sub === "accounts") {
290
+ await tamAccounts(rest);
291
+ return;
292
+ }
293
+
294
+ throw unknownSubcommandError("tam", sub, ["estimate", "status", "report", "populate", "accounts"]);
295
+ }
296
+
297
+ /**
298
+ * `tam accounts` — pull the REAL target-account list from a technographic source
299
+ * (companies that actually use a CRM, matched to the ICP). This is the
300
+ * materialized list the count can't give you: real names + domains you can
301
+ * review, save, and acquire into the CRM. Read-only (no CRM write); each pulled
302
+ * company costs provider credits, so `--max` caps the page.
303
+ */
304
+ async function tamAccounts(rest: string[]) {
305
+ const source = option(rest, "--source") ?? "theirstack";
306
+ if (source !== "theirstack") {
307
+ throw new Error(`tam accounts --source supports theirstack (only technographic list source wired) — got "${source}".`);
308
+ }
309
+ const icp = loadIcp(rest);
310
+ if (!icp) {
311
+ throw new Error("tam accounts needs an ICP (icp.json in cwd, or --icp <path>) — its technologies/firmographics are the filter.");
312
+ }
313
+ const max = Math.min(numericOption(rest, "--max") ?? 25, 100);
314
+
315
+ // Pulling the list costs TheirStack credits (~3/company) — never spend by
316
+ // surprise. Show the cost up front; --dry-run prices it without spending; a
317
+ // pull above --max-credits (default 150 ≈ 50 companies) needs --confirm.
318
+ const usdPerCredit = numericOption(rest, "--usd-per-credit") ?? undefined;
319
+ const thisCost = theirStackPullCost(max, usdPerCredit);
320
+ const usdStr = (c: { usd?: number }): string => (c.usd !== undefined ? ` (~$${c.usd.toLocaleString()})` : "");
321
+ const model = loadTamModel(option(rest, "--name") ?? "default");
322
+ const fullUniverse = model?.universe.accounts;
323
+ const fullCost = fullUniverse ? theirStackPullCost(fullUniverse, usdPerCredit) : undefined;
324
+ const costLine =
325
+ `Pull cost: up to ${max} companies ≈ ${thisCost.credits.toLocaleString()} TheirStack credits${usdStr(thisCost)}` +
326
+ (fullCost
327
+ ? `. Full TAM (~${fullUniverse!.toLocaleString()} accounts) ≈ ${fullCost.credits.toLocaleString()} credits${usdStr(fullCost)} to materialize.`
328
+ : ".");
329
+
330
+ if (rest.includes("--dry-run")) {
331
+ console.log(`${costLine}\n(dry run — nothing pulled, 0 credits spent. Add --usd-per-credit <rate> for a $ estimate.)`);
332
+ return;
333
+ }
334
+ const maxCredits = numericOption(rest, "--max-credits") ?? 150;
335
+ if (thisCost.credits > maxCredits && !rest.includes("--confirm")) {
336
+ console.error(
337
+ `${costLine}\nThis pull (${thisCost.credits.toLocaleString()} credits) exceeds the --max-credits guard (${maxCredits}). ` +
338
+ "Re-run with --confirm to spend it, lower --max, or --dry-run to just price it.",
339
+ );
340
+ process.exitCode = 2;
341
+ return;
342
+ }
343
+ console.error(costLine);
344
+
345
+ const { companies: raw, total } = await theirStackSearchCompanies({
346
+ apiKey: providerKey("theirstack"),
347
+ filters: icpToTheirStackFilters(icp),
348
+ limit: max,
349
+ });
350
+ // A company carries its WHOLE tech stack (often 200+ slugs) — noise. Keep only
351
+ // the ICP-targeted technologies (the CRMs/MAPs that put it in the list).
352
+ const targeted = new Set((icp.firmographics.technologies ?? []).map((t) => t.trim().toLowerCase()));
353
+ const companies = raw.map((c) => ({
354
+ ...c,
355
+ technologies: (c.technologies ?? []).filter((t) => targeted.has(t.toLowerCase())),
356
+ }));
357
+ const out = option(rest, "--out");
358
+ if (rest.includes("--json")) {
359
+ console.log(JSON.stringify({ total, returned: companies.length, companies }, null, 2));
360
+ return;
361
+ }
362
+ if (out) {
363
+ const header = "name,domain,employee_count,country,linkedin_url,matched_technologies";
364
+ const esc = (v: string | number | undefined): string => {
365
+ const s = v === undefined ? "" : String(v);
366
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
367
+ };
368
+ const rows = companies.map((c) =>
369
+ [c.name, c.domain, c.employeeCount, c.countryCode, c.linkedinUrl, (c.technologies ?? []).join("|")]
370
+ .map(esc)
371
+ .join(","),
372
+ );
373
+ writeFileSync(resolve(process.cwd(), out), `${[header, ...rows].join("\n")}\n`);
374
+ console.log(`Wrote ${companies.length} companies to ${out}${total !== null ? ` (of ${total.toLocaleString()} matching)` : ""}.`);
375
+ return;
376
+ }
377
+ console.log(
378
+ `${companies.length} companies${total !== null ? ` of ${total.toLocaleString()} matching the ICP` : ""} ` +
379
+ `(uses ${[...targeted].join("/")}):\n`,
380
+ );
381
+ for (const c of companies) {
382
+ console.log(
383
+ ` ${(c.name ?? "?").padEnd(32)} ${(c.domain ?? "").padEnd(28)} ${String(c.employeeCount ?? "?").padStart(6)} emp ` +
384
+ `[${(c.technologies ?? []).join(",")}]`,
385
+ );
386
+ }
387
+ console.log(
388
+ `\nNext: stage them with \`fullstackgtm enrich ingest <file.csv> --source clay --objects companies\` ` +
389
+ "→ `enrich acquire` to create governed account records (or re-run with --out <file.csv>).",
390
+ );
391
+ }
392
+
393
+ /**
394
+ * `tam populate` — wire the scheduled population of a TAM: a recurring
395
+ * `enrich acquire --source <s> --save` that queues a needs_approval lead plan
396
+ * each firing (apply stays a separate human gate; the meter is charged only at
397
+ * apply). Delegates to the scheduler so the cron + allowlist (incl. the --save
398
+ * guard) are validated the same way as any `schedule add`.
399
+ */
400
+ async function tamPopulate(name: string, rest: string[]) {
401
+ const model = loadTamModel(name);
402
+ if (!model) throw new Error(`No TAM "${name}" — run \`fullstackgtm tam estimate\` first.`);
403
+ const cron = option(rest, "--cron");
404
+ if (!cron) {
405
+ throw new Error('tam populate requires --cron "<expr>" (e.g. "0 7 * * 1-5" = 7am on weekdays)');
406
+ }
407
+ const source = option(rest, "--source") ?? "pipe0";
408
+ const provider = option(rest, "--provider") ?? "hubspot";
409
+ const label = option(rest, "--label") ?? `tam-${name}`;
410
+
411
+ const acquireCmd = `enrich acquire --source ${source} --provider ${provider} --save`;
412
+ // Reuse the scheduler: validates the cron, the allowlist, and the --save guard.
413
+ await scheduleCommand(["add", acquireCmd, "--cron", cron, "--label", label]);
414
+
415
+ const remainingAccounts = Math.max(0, model.universe.accounts - model.baseline.accounts);
416
+ console.log(
417
+ `\nPopulating TAM "${name}": each firing queues a needs_approval lead plan — apply stays gated, the ` +
418
+ `acquire meter is charged only at apply. ~${remainingAccounts.toLocaleString()} of ` +
419
+ `${model.universe.accounts.toLocaleString()} accounts remain to reach the universe ` +
420
+ `($${model.tamUsd.toLocaleString()} TAM).`,
421
+ );
422
+ console.log(
423
+ "Next: `fullstackgtm schedule install` to activate, then each cycle " +
424
+ "`fullstackgtm plans list` → `plans approve` → `apply`. Track progress with " +
425
+ `\`fullstackgtm tam status --name ${name} --provider ${provider} --save\`.`,
426
+ );
427
+ // Cost lives in two separate places — be explicit so neither surprises.
428
+ const ts = theirStackPullCost(model.universe.accounts);
429
+ console.log(
430
+ `\nCost: population spend is the acquire provider's (${source}), governed by the per-profile acquire meter ` +
431
+ "(records + $/day caps in enrich.config.json) — not TheirStack. Separately, materializing the account LIST " +
432
+ `from TheirStack (\`tam accounts\`) is ~${ts.credits.toLocaleString()} credits for the full ${model.universe.accounts.toLocaleString()}-account ` +
433
+ "universe; `tam accounts --dry-run [--usd-per-credit <r>]` prices any pull without spending.",
434
+ );
435
+ }