fullstackgtm 0.43.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +193 -0
- package/README.md +18 -7
- package/dist/cli.js +634 -56
- package/dist/connectors/outboxChannel.d.ts +64 -0
- package/dist/connectors/outboxChannel.js +170 -0
- package/dist/connectors/prospectSources.d.ts +22 -0
- package/dist/connectors/prospectSources.js +43 -0
- package/dist/connectors/signalSources.d.ts +105 -0
- package/dist/connectors/signalSources.js +316 -0
- package/dist/connectors/theirstack.d.ts +84 -0
- package/dist/connectors/theirstack.js +125 -0
- package/dist/icp.d.ts +47 -3
- package/dist/icp.js +105 -11
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/init.js +3 -0
- package/dist/judgeEval.d.ts +7 -0
- package/dist/judgeEval.js +8 -1
- package/dist/runReport.d.ts +26 -0
- package/dist/runReport.js +15 -0
- package/dist/schedule.js +18 -4
- package/dist/signals.d.ts +54 -0
- package/dist/signals.js +64 -0
- package/dist/tam.d.ts +225 -0
- package/dist/tam.js +470 -0
- package/docs/api.md +18 -4
- package/docs/outbox-format.md +92 -0
- package/docs/recipes.md +37 -0
- package/docs/roadmap-to-1.0.md +31 -1
- package/docs/signal-spool-format.md +162 -0
- package/docs/tam.md +195 -0
- package/llms.txt +68 -5
- package/package.json +1 -1
- package/skills/fullstackgtm/SKILL.md +3 -2
- package/src/cli.ts +714 -51
- package/src/connectors/outboxChannel.ts +202 -0
- package/src/connectors/prospectSources.ts +57 -0
- package/src/connectors/signalSources.ts +363 -0
- package/src/connectors/theirstack.ts +170 -0
- package/src/icp.ts +113 -11
- package/src/index.ts +32 -0
- package/src/init.ts +3 -0
- package/src/judgeEval.ts +8 -1
- package/src/runReport.ts +39 -0
- package/src/schedule.ts +20 -4
- package/src/signals.ts +90 -0
- package/src/tam.ts +654 -0
package/src/tam.ts
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tam` — Total Addressable Market mapping.
|
|
3
|
+
*
|
|
4
|
+
* Market mapping (`market`) answers "who else is in this category and where are
|
|
5
|
+
* the open fronts." TAM mapping answers a different, longer-horizon question:
|
|
6
|
+
* "how big is the reachable market for *my* ICP, and how far along am I in
|
|
7
|
+
* actually putting it in the CRM?"
|
|
8
|
+
*
|
|
9
|
+
* It is deliberately NOT a one-shot "$10B TAM" headline. The flow is iterative:
|
|
10
|
+
* 1. `tam estimate` — derive a defensible universe from the ICP: a real
|
|
11
|
+
* account count (a discovery provider's total-match for the ICP filter, or
|
|
12
|
+
* an explicit assumption), × ACV for the dollar figure, with buyers/account
|
|
13
|
+
* giving the *contact* population target. Citable cross-checks optional.
|
|
14
|
+
* 2. `tam populate` — schedule governed `enrich acquire --save` runs that chip
|
|
15
|
+
* away at the universe (plan-only; apply stays a separate human gate).
|
|
16
|
+
* 3. `tam status` / `tam report` — coverage over time: accounts/contacts/$
|
|
17
|
+
* in the CRM vs. the universe, what THIS campaign added since baseline, and
|
|
18
|
+
* an ETA at the current burn rate — so "it'll take a while" is quantified.
|
|
19
|
+
*
|
|
20
|
+
* This module is the pure, deterministic core (estimation + coverage + ETA math
|
|
21
|
+
* + a profile-scoped store). The CLI wires it to the ICP, the CRM snapshot, the
|
|
22
|
+
* discovery providers, and the scheduler.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
|
|
28
|
+
import { credentialsDir, ensureSecureHomeDir, writeSecureFile } from "./credentials.ts";
|
|
29
|
+
import type { CanonicalAccount, CanonicalGtmSnapshot } from "./types.ts";
|
|
30
|
+
|
|
31
|
+
// ── Model ───────────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* ACV basis. `account` (per logo / contract — the standard TAM basis) makes
|
|
35
|
+
* TAM = accounts × ACV. `buyer` (per seat) makes TAM = contacts × ACV, for
|
|
36
|
+
* genuinely seat-priced products. Buyers/account always drives the *contact*
|
|
37
|
+
* population target regardless of basis.
|
|
38
|
+
*/
|
|
39
|
+
export type AcvBasis = "account" | "buyer";
|
|
40
|
+
|
|
41
|
+
/** A citable market-research figure that cross-checks the bottom-up estimate. */
|
|
42
|
+
export type TamCrossCheck = {
|
|
43
|
+
claim: string;
|
|
44
|
+
/** Parsed dollar value, when the claim is a $ figure — enables a direct compare. */
|
|
45
|
+
valueUsd?: number;
|
|
46
|
+
sourceUrl: string;
|
|
47
|
+
/** Verbatim snippet (same evidence posture as market signals). */
|
|
48
|
+
quote: string;
|
|
49
|
+
asOf?: string;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Real CRM counts that "fill" the TAM — accounts with a domain + their contacts. */
|
|
53
|
+
export type TamCoverageCounts = {
|
|
54
|
+
accounts: number;
|
|
55
|
+
contacts: number;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type TamUniverse = {
|
|
59
|
+
accounts: number;
|
|
60
|
+
/** Where the account count came from: "provider:explorium" or "assumption". */
|
|
61
|
+
accountsSource: string;
|
|
62
|
+
buyersPerAccount: number;
|
|
63
|
+
/** how buyersPerAccount was set: "crm:avg-contacts-per-account (N)" or "explicit" or "assumption:...". */
|
|
64
|
+
buyersSource: string;
|
|
65
|
+
/** accounts × buyersPerAccount — the contact population target. */
|
|
66
|
+
contacts: number;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The ICP criteria the TAM was estimated against — captured at estimate time so
|
|
71
|
+
* `status` can classify CRM accounts as in/out of THIS TAM. geo/technology aren't
|
|
72
|
+
* on a CanonicalAccount, so only `employeeBands`/`industries` are CRM-checkable;
|
|
73
|
+
* geo + technographic verification needs re-enrichment (`--reverify`, future).
|
|
74
|
+
*/
|
|
75
|
+
export type TamTargeting = {
|
|
76
|
+
geos?: string[];
|
|
77
|
+
employeeBands?: string[];
|
|
78
|
+
industries?: string[];
|
|
79
|
+
technologies?: string[];
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
export type TamModel = {
|
|
83
|
+
name: string;
|
|
84
|
+
icpName: string;
|
|
85
|
+
universe: TamUniverse;
|
|
86
|
+
/** the ICP filter this TAM was sized against (for coverage classification). */
|
|
87
|
+
targeting?: TamTargeting;
|
|
88
|
+
/** ACV must be REAL, never a fabricated default: `source` says where it came
|
|
89
|
+
* from ("explicit" from the operator, or "crm:closed-won (N deals, median)"). */
|
|
90
|
+
acv: { basis: AcvBasis; valueUsd: number; source: string };
|
|
91
|
+
/** accounts × ACV (account basis) or contacts × ACV (buyer basis). */
|
|
92
|
+
tamUsd: number;
|
|
93
|
+
crossChecks: TamCrossCheck[];
|
|
94
|
+
/** CRM counts at estimate time, so `status` can attribute what the campaign added. */
|
|
95
|
+
baseline: TamCoverageCounts;
|
|
96
|
+
createdAt: string;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** CRM accounts classified against the TAM ICP — only the in-TAM bucket counts. */
|
|
100
|
+
export type TamClassified = {
|
|
101
|
+
/** matches every CRM-checkable criterion (no contradiction) — counts toward coverage. */
|
|
102
|
+
inTam: number;
|
|
103
|
+
/** fails a checkable criterion (wrong size/industry) — NOT in this market. */
|
|
104
|
+
outOfTam: number;
|
|
105
|
+
/** missing the data to classify — surfaced, never silently counted. */
|
|
106
|
+
unknown: number;
|
|
107
|
+
/** all domain-bearing CRM accounts (inTam + outOfTam + unknown). */
|
|
108
|
+
totalCrm: number;
|
|
109
|
+
/** which criteria were CRM-checkable, e.g. ["size","industry"]. */
|
|
110
|
+
criteria: string[];
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
export type TamCoverage = {
|
|
114
|
+
at: string;
|
|
115
|
+
universe: { accounts: number; contacts: number; tamUsd: number };
|
|
116
|
+
inCrm: TamCoverageCounts;
|
|
117
|
+
/** current − baseline (floored at 0) — what's been added since the TAM was set. */
|
|
118
|
+
addedSinceBaseline: TamCoverageCounts;
|
|
119
|
+
/** in-TAM (or total when unclassified) / universe, capped at 1. */
|
|
120
|
+
accountCoverage: number;
|
|
121
|
+
contactCoverage: number;
|
|
122
|
+
/** accountCoverage × tamUsd. */
|
|
123
|
+
dollarCovered: number;
|
|
124
|
+
/** present when the model carries targeting — the in/out/unknown breakdown. */
|
|
125
|
+
classified?: TamClassified;
|
|
126
|
+
/** max(estimate, inTam): the bottom-up count is a floor on the real universe. */
|
|
127
|
+
reconciledUniverse?: number;
|
|
128
|
+
/** inTam > the top-down estimate — the estimate was low; revise it UP. */
|
|
129
|
+
bottomUpExceedsEstimate?: boolean;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/** Linear projection of when the universe is filled, from the coverage timeline. */
|
|
133
|
+
export type TamEta = {
|
|
134
|
+
/** accounts added per day, measured across the timeline window. */
|
|
135
|
+
accountsPerDay: number;
|
|
136
|
+
accountsRemaining: number;
|
|
137
|
+
daysRemaining: number;
|
|
138
|
+
/** ISO date (YYYY-MM-DD) the account universe is projected to be covered. */
|
|
139
|
+
etaDate: string;
|
|
140
|
+
/** how the rate was measured — the timeline span used. */
|
|
141
|
+
basis: string;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// ── Estimation (pure) ─────────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
export type EstimateTamInput = {
|
|
147
|
+
name: string;
|
|
148
|
+
icpName: string;
|
|
149
|
+
accounts: number;
|
|
150
|
+
accountsSource: string;
|
|
151
|
+
buyersPerAccount?: number;
|
|
152
|
+
buyersSource?: string;
|
|
153
|
+
targeting?: TamTargeting;
|
|
154
|
+
acv: { basis?: AcvBasis; valueUsd: number; source?: string };
|
|
155
|
+
crossChecks?: TamCrossCheck[];
|
|
156
|
+
baseline: TamCoverageCounts;
|
|
157
|
+
createdAt: string;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
export function estimateTam(input: EstimateTamInput): TamModel {
|
|
161
|
+
if (!Number.isFinite(input.accounts) || input.accounts < 0) {
|
|
162
|
+
throw new Error(`tam: account universe must be a non-negative number (got ${input.accounts})`);
|
|
163
|
+
}
|
|
164
|
+
if (!Number.isFinite(input.acv.valueUsd) || input.acv.valueUsd <= 0) {
|
|
165
|
+
throw new Error(`tam: ACV must be a positive number (got ${input.acv.valueUsd}) — a TAM needs a real ACV`);
|
|
166
|
+
}
|
|
167
|
+
const buyersPerAccount = input.buyersPerAccount ?? 1;
|
|
168
|
+
if (!Number.isFinite(buyersPerAccount) || buyersPerAccount <= 0) {
|
|
169
|
+
throw new Error(`tam: buyers-per-account must be positive (got ${buyersPerAccount})`);
|
|
170
|
+
}
|
|
171
|
+
const accounts = Math.round(input.accounts);
|
|
172
|
+
const contacts = Math.round(accounts * buyersPerAccount);
|
|
173
|
+
const basis: AcvBasis = input.acv.basis ?? "account";
|
|
174
|
+
const tamUsd = Math.round((basis === "buyer" ? contacts : accounts) * input.acv.valueUsd);
|
|
175
|
+
return {
|
|
176
|
+
name: input.name,
|
|
177
|
+
icpName: input.icpName,
|
|
178
|
+
universe: {
|
|
179
|
+
accounts,
|
|
180
|
+
accountsSource: input.accountsSource,
|
|
181
|
+
buyersPerAccount,
|
|
182
|
+
buyersSource: input.buyersSource ?? "explicit",
|
|
183
|
+
contacts,
|
|
184
|
+
},
|
|
185
|
+
...(input.targeting ? { targeting: input.targeting } : {}),
|
|
186
|
+
acv: { basis, valueUsd: input.acv.valueUsd, source: input.acv.source ?? "explicit" },
|
|
187
|
+
tamUsd,
|
|
188
|
+
crossChecks: input.crossChecks ?? [],
|
|
189
|
+
baseline: input.baseline,
|
|
190
|
+
createdAt: input.createdAt,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ── Deriving real signal from the CRM (no fabricated defaults) ─────────────────
|
|
195
|
+
|
|
196
|
+
function median(values: number[]): number {
|
|
197
|
+
const s = [...values].sort((a, b) => a - b);
|
|
198
|
+
const mid = Math.floor(s.length / 2);
|
|
199
|
+
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export type DerivedAcv = { valueUsd: number; dealCount: number; meanUsd: number };
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Derive a real ACV from the CRM's closed-won deals (median amount — robust to
|
|
206
|
+
* outliers). Returns null when there are no usable won deals, so the caller can
|
|
207
|
+
* refuse to fabricate a dollar TAM. The median is the headline; the mean is
|
|
208
|
+
* surfaced too so a skewed pipeline is visible.
|
|
209
|
+
*/
|
|
210
|
+
export function deriveAcvFromClosedWon(snapshot: CanonicalGtmSnapshot): DerivedAcv | null {
|
|
211
|
+
const amounts = (snapshot.deals ?? [])
|
|
212
|
+
.filter((d) => d.isWon === true && typeof d.amount === "number" && Number.isFinite(d.amount) && d.amount > 0)
|
|
213
|
+
.map((d) => d.amount as number);
|
|
214
|
+
if (amounts.length === 0) return null;
|
|
215
|
+
const meanUsd = Math.round(amounts.reduce((a, b) => a + b, 0) / amounts.length);
|
|
216
|
+
return { valueUsd: Math.round(median(amounts)), dealCount: amounts.length, meanUsd };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export type DerivedBuyers = { value: number; accountsSampled: number };
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Derive buyers/account from the CRM: the average number of contacts on accounts
|
|
223
|
+
* that have at least one. A real proxy for the buying group, vs. a hardcoded
|
|
224
|
+
* guess. Returns null when no account has a contact.
|
|
225
|
+
*/
|
|
226
|
+
export function deriveBuyersPerAccount(snapshot: CanonicalGtmSnapshot): DerivedBuyers | null {
|
|
227
|
+
const perAccount = new Map<string, number>();
|
|
228
|
+
for (const c of snapshot.contacts ?? []) {
|
|
229
|
+
if (c.accountId) perAccount.set(c.accountId, (perAccount.get(c.accountId) ?? 0) + 1);
|
|
230
|
+
}
|
|
231
|
+
if (perAccount.size === 0) return null;
|
|
232
|
+
const total = [...perAccount.values()].reduce((a, b) => a + b, 0);
|
|
233
|
+
return { value: Math.round((total / perAccount.size) * 10) / 10, accountsSampled: perAccount.size };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ── Coverage (pure) ───────────────────────────────────────────────────────────
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Count what "fills" the TAM from a CRM snapshot: accounts that carry a domain
|
|
240
|
+
* (real, signal-watchable records — a name-only stub doesn't count) and the
|
|
241
|
+
* contacts at them. Coverage is measured against these, so a TAM you've started
|
|
242
|
+
* filling reads truthfully even for accounts that pre-dated the campaign.
|
|
243
|
+
*/
|
|
244
|
+
export function coverageCountsFromSnapshot(snapshot: CanonicalGtmSnapshot): TamCoverageCounts {
|
|
245
|
+
const accounts = (snapshot.accounts ?? []).filter((a) => Boolean(a.domain && a.domain.trim())).length;
|
|
246
|
+
const contacts = (snapshot.contacts ?? []).length;
|
|
247
|
+
return { accounts, contacts };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const cap1 = (n: number): number => (n <= 0 ? 0 : n >= 1 ? 1 : n);
|
|
251
|
+
|
|
252
|
+
// ── TAM membership classification ──────────────────────────────────────────────
|
|
253
|
+
|
|
254
|
+
export type AccountTamClass = "in" | "out" | "unknown";
|
|
255
|
+
|
|
256
|
+
function parseBand(band: string): [number, number] | null {
|
|
257
|
+
const plus = /^(\d+)\+$/.exec(band.trim());
|
|
258
|
+
if (plus) return [Number(plus[1]), Number.POSITIVE_INFINITY];
|
|
259
|
+
const range = /^(\d+)\s*-\s*(\d+)$/.exec(band.trim());
|
|
260
|
+
if (range) return [Number(range[1]), Number(range[2])];
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function employeeCountInBands(count: number, bands: string[]): boolean {
|
|
265
|
+
return bands.some((b) => {
|
|
266
|
+
const r = parseBand(b);
|
|
267
|
+
return r ? count >= r[0] && count <= r[1] : false;
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function industryMatches(accountIndustry: string, tamIndustries: string[]): boolean {
|
|
272
|
+
const a = accountIndustry.toLowerCase();
|
|
273
|
+
return tamIndustries.some((i) => {
|
|
274
|
+
const t = i.toLowerCase().trim();
|
|
275
|
+
return t.length > 0 && (a.includes(t) || t.includes(a));
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** The TAM criteria checkable from a CanonicalAccount — geo/technology are NOT on
|
|
280
|
+
* the record, so they need re-enrichment and are excluded here. */
|
|
281
|
+
export function crmCheckableCriteria(t: TamTargeting): string[] {
|
|
282
|
+
const c: string[] = [];
|
|
283
|
+
if (t.employeeBands?.length) c.push("size");
|
|
284
|
+
if (t.industries?.length) c.push("industry");
|
|
285
|
+
return c;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Classify one CRM account against the TAM ICP, using only CRM-checkable criteria
|
|
290
|
+
* (size, industry). "out" if any criterion contradicts (wrong size/industry);
|
|
291
|
+
* "in" if at least one passes and none contradict; "unknown" if nothing could be
|
|
292
|
+
* evaluated (missing fields, or the TAM is defined only by geo/technology). Note:
|
|
293
|
+
* geo + "uses a CRM" can't be confirmed from a CanonicalAccount, so an "in" here
|
|
294
|
+
* means "matches what the CRM lets us check" — not a full technographic match.
|
|
295
|
+
*/
|
|
296
|
+
export function classifyAccount(account: CanonicalAccount, t: TamTargeting): AccountTamClass {
|
|
297
|
+
let pass = 0;
|
|
298
|
+
let fail = 0;
|
|
299
|
+
let checkable = 0;
|
|
300
|
+
if (t.employeeBands?.length) {
|
|
301
|
+
checkable++;
|
|
302
|
+
if (typeof account.employeeCount === "number" && Number.isFinite(account.employeeCount)) {
|
|
303
|
+
if (employeeCountInBands(account.employeeCount, t.employeeBands)) pass++;
|
|
304
|
+
else fail++;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (t.industries?.length) {
|
|
308
|
+
checkable++;
|
|
309
|
+
if (account.industry && account.industry.trim()) {
|
|
310
|
+
if (industryMatches(account.industry, t.industries)) pass++;
|
|
311
|
+
else fail++;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (checkable === 0) return "unknown"; // TAM is geo/technology-only → not CRM-checkable
|
|
315
|
+
if (fail > 0) return "out";
|
|
316
|
+
if (pass > 0) return "in";
|
|
317
|
+
return "unknown"; // criteria specified but the account had no data for them
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Coverage that classifies CRM accounts against THIS TAM's ICP — so accounts
|
|
322
|
+
* loaded from anywhere that DON'T match the target market (wrong size/industry)
|
|
323
|
+
* land in out-of-TAM/unknown and never inflate coverage. Reconciles bottom-up vs
|
|
324
|
+
* top-down: the in-TAM count is a FLOOR on the real universe (you've verified
|
|
325
|
+
* those exist), so when it exceeds the estimate, the estimate was low.
|
|
326
|
+
*/
|
|
327
|
+
export function classifyCoverage(model: TamModel, snapshot: CanonicalGtmSnapshot, at: string): TamCoverage {
|
|
328
|
+
const accounts = (snapshot.accounts ?? []).filter((a) => Boolean(a.domain && a.domain.trim()));
|
|
329
|
+
const totalCrm = accounts.length;
|
|
330
|
+
const allContacts = (snapshot.contacts ?? []).length;
|
|
331
|
+
const t = model.targeting;
|
|
332
|
+
const criteria = t ? crmCheckableCriteria(t) : [];
|
|
333
|
+
|
|
334
|
+
let inTam = totalCrm;
|
|
335
|
+
let outOfTam = 0;
|
|
336
|
+
let unknown = 0;
|
|
337
|
+
const inTamIds = new Set<string>(accounts.map((a) => a.id)); // legacy default: all in
|
|
338
|
+
if (t && criteria.length > 0) {
|
|
339
|
+
inTam = 0;
|
|
340
|
+
inTamIds.clear();
|
|
341
|
+
for (const a of accounts) {
|
|
342
|
+
const klass = classifyAccount(a, t);
|
|
343
|
+
if (klass === "in") {
|
|
344
|
+
inTam++;
|
|
345
|
+
inTamIds.add(a.id);
|
|
346
|
+
} else if (klass === "out") {
|
|
347
|
+
outOfTam++;
|
|
348
|
+
} else {
|
|
349
|
+
unknown++;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const inTamContacts =
|
|
354
|
+
criteria.length > 0
|
|
355
|
+
? (snapshot.contacts ?? []).filter((c) => c.accountId && inTamIds.has(c.accountId)).length
|
|
356
|
+
: allContacts;
|
|
357
|
+
|
|
358
|
+
const accountCoverage = model.universe.accounts > 0 ? cap1(inTam / model.universe.accounts) : 0;
|
|
359
|
+
const contactCoverage = model.universe.contacts > 0 ? cap1(inTamContacts / model.universe.contacts) : 0;
|
|
360
|
+
return {
|
|
361
|
+
at,
|
|
362
|
+
universe: { accounts: model.universe.accounts, contacts: model.universe.contacts, tamUsd: model.tamUsd },
|
|
363
|
+
inCrm: { accounts: totalCrm, contacts: allContacts },
|
|
364
|
+
addedSinceBaseline: {
|
|
365
|
+
accounts: Math.max(0, totalCrm - model.baseline.accounts),
|
|
366
|
+
contacts: Math.max(0, allContacts - model.baseline.contacts),
|
|
367
|
+
},
|
|
368
|
+
accountCoverage,
|
|
369
|
+
contactCoverage,
|
|
370
|
+
dollarCovered: Math.round(accountCoverage * model.tamUsd),
|
|
371
|
+
classified: { inTam, outOfTam, unknown, totalCrm, criteria },
|
|
372
|
+
reconciledUniverse: Math.max(model.universe.accounts, inTam),
|
|
373
|
+
bottomUpExceedsEstimate: inTam > model.universe.accounts,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** The covered-account count a coverage reading represents: in-TAM when
|
|
378
|
+
* classified, else the raw CRM count (legacy). Used for ETA + reconciliation. */
|
|
379
|
+
export function coveredAccounts(c: TamCoverage): number {
|
|
380
|
+
return c.classified ? c.classified.inTam : c.inCrm.accounts;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function computeCoverage(model: TamModel, inCrm: TamCoverageCounts, at: string): TamCoverage {
|
|
384
|
+
const accountCoverage = model.universe.accounts > 0 ? cap1(inCrm.accounts / model.universe.accounts) : 0;
|
|
385
|
+
const contactCoverage = model.universe.contacts > 0 ? cap1(inCrm.contacts / model.universe.contacts) : 0;
|
|
386
|
+
return {
|
|
387
|
+
at,
|
|
388
|
+
universe: { accounts: model.universe.accounts, contacts: model.universe.contacts, tamUsd: model.tamUsd },
|
|
389
|
+
inCrm,
|
|
390
|
+
addedSinceBaseline: {
|
|
391
|
+
accounts: Math.max(0, inCrm.accounts - model.baseline.accounts),
|
|
392
|
+
contacts: Math.max(0, inCrm.contacts - model.baseline.contacts),
|
|
393
|
+
},
|
|
394
|
+
accountCoverage,
|
|
395
|
+
contactCoverage,
|
|
396
|
+
dollarCovered: Math.round(accountCoverage * model.tamUsd),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const MS_PER_DAY = 86_400_000;
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Project when the account universe is filled, from the coverage timeline. Uses
|
|
404
|
+
* the first and last readings that show real movement. Returns null when there
|
|
405
|
+
* isn't enough signal (fewer than two readings, no elapsed time, or a flat/
|
|
406
|
+
* negative burn rate) — an honest "can't project yet" rather than a fake date.
|
|
407
|
+
*/
|
|
408
|
+
export function projectEta(model: TamModel, timeline: TamCoverage[]): TamEta | null {
|
|
409
|
+
if (timeline.length < 2) return null;
|
|
410
|
+
const sorted = [...timeline].sort((a, b) => a.at.localeCompare(b.at));
|
|
411
|
+
const first = sorted[0];
|
|
412
|
+
const last = sorted[sorted.length - 1];
|
|
413
|
+
const elapsedDays = (Date.parse(last.at) - Date.parse(first.at)) / MS_PER_DAY;
|
|
414
|
+
if (!Number.isFinite(elapsedDays) || elapsedDays <= 0) return null;
|
|
415
|
+
// Pace is measured on IN-TAM accounts (when classified) — off-ICP accounts
|
|
416
|
+
// loaded from elsewhere don't count as progress toward THIS universe.
|
|
417
|
+
const gained = coveredAccounts(last) - coveredAccounts(first);
|
|
418
|
+
if (gained <= 0) return null;
|
|
419
|
+
const accountsPerDay = gained / elapsedDays;
|
|
420
|
+
const accountsRemaining = Math.max(0, model.universe.accounts - coveredAccounts(last));
|
|
421
|
+
const daysRemaining = Math.ceil(accountsRemaining / accountsPerDay);
|
|
422
|
+
const etaDate = new Date(Date.parse(last.at) + daysRemaining * MS_PER_DAY).toISOString().slice(0, 10);
|
|
423
|
+
return {
|
|
424
|
+
accountsPerDay: Math.round(accountsPerDay * 10) / 10,
|
|
425
|
+
accountsRemaining,
|
|
426
|
+
daysRemaining,
|
|
427
|
+
etaDate,
|
|
428
|
+
basis: `${gained} accounts over ${Math.round(elapsedDays)}d (${first.at.slice(0, 10)}→${last.at.slice(0, 10)})`,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ── Profile-scoped store ──────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
function safeName(name: string): string {
|
|
435
|
+
if (!/^[\w.-]+$/.test(name)) throw new Error(`tam: invalid name "${name}" (use letters, digits, . _ -)`);
|
|
436
|
+
return name;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** `$FSGTM_HOME[/profiles/<profile>]/tam/<name>/`. */
|
|
440
|
+
export function tamDir(name: string): string {
|
|
441
|
+
return join(credentialsDir(), "tam", safeName(name));
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export function saveTamModel(model: TamModel): string {
|
|
445
|
+
ensureSecureHomeDir();
|
|
446
|
+
const dir = tamDir(model.name);
|
|
447
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
448
|
+
const path = join(dir, "model.json");
|
|
449
|
+
writeSecureFile(path, `${JSON.stringify(model, null, 2)}\n`);
|
|
450
|
+
return path;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function loadTamModel(name: string): TamModel | null {
|
|
454
|
+
try {
|
|
455
|
+
return JSON.parse(readFileSync(join(tamDir(name), "model.json"), "utf8")) as TamModel;
|
|
456
|
+
} catch {
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Append a coverage reading to the TAM's append-only timeline (0600). */
|
|
462
|
+
export function appendCoverage(name: string, coverage: TamCoverage): void {
|
|
463
|
+
ensureSecureHomeDir();
|
|
464
|
+
const dir = tamDir(name);
|
|
465
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
466
|
+
appendFileSync(join(dir, "coverage.jsonl"), `${JSON.stringify(coverage)}\n`, { mode: 0o600 });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Read the TAM's coverage timeline; tolerant of partial/corrupt lines. */
|
|
470
|
+
export function readCoverageTimeline(name: string): TamCoverage[] {
|
|
471
|
+
let raw: string;
|
|
472
|
+
try {
|
|
473
|
+
raw = readFileSync(join(tamDir(name), "coverage.jsonl"), "utf8");
|
|
474
|
+
} catch {
|
|
475
|
+
return [];
|
|
476
|
+
}
|
|
477
|
+
const out: TamCoverage[] = [];
|
|
478
|
+
for (const line of raw.split("\n")) {
|
|
479
|
+
const t = line.trim();
|
|
480
|
+
if (!t) continue;
|
|
481
|
+
try {
|
|
482
|
+
out.push(JSON.parse(t) as TamCoverage);
|
|
483
|
+
} catch {
|
|
484
|
+
// skip a torn line rather than failing the rollup
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return out;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// ── Rendering ─────────────────────────────────────────────────────────────────
|
|
491
|
+
|
|
492
|
+
function usd(n: number): string {
|
|
493
|
+
if (n >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(2)}B`;
|
|
494
|
+
if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
|
|
495
|
+
if (n >= 1_000) return `$${(n / 1_000).toFixed(0)}K`;
|
|
496
|
+
return `$${Math.round(n)}`;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const pct = (x: number): string => `${Math.round(x * 100)}%`;
|
|
500
|
+
|
|
501
|
+
/** A compact human summary for `tam status`. */
|
|
502
|
+
export function coverageToText(model: TamModel, coverage: TamCoverage, eta: TamEta | null): string {
|
|
503
|
+
const c = coverage.classified;
|
|
504
|
+
const lines = [
|
|
505
|
+
`TAM "${model.name}" (ICP: ${model.icpName}) — ${model.acv.basis}-basis ACV ${usd(model.acv.valueUsd)} ` +
|
|
506
|
+
`[${model.acv.source}]`,
|
|
507
|
+
`Universe: ${model.universe.accounts.toLocaleString()} accounts (${model.universe.accountsSource}) / ` +
|
|
508
|
+
`${model.universe.contacts.toLocaleString()} contacts ` +
|
|
509
|
+
`(${model.universe.buyersPerAccount} buyers/account [${model.universe.buyersSource}]) / ${usd(model.tamUsd)}`,
|
|
510
|
+
];
|
|
511
|
+
if (c && c.criteria.length > 0) {
|
|
512
|
+
// Classified coverage: only in-TAM accounts count; junk is bucketed out.
|
|
513
|
+
lines.push(
|
|
514
|
+
`In CRM: ${c.totalCrm.toLocaleString()} accounts → ${c.inTam.toLocaleString()} in-TAM (${pct(coverage.accountCoverage)}), ` +
|
|
515
|
+
`${c.outOfTam.toLocaleString()} out-of-TAM, ${c.unknown.toLocaleString()} unknown`,
|
|
516
|
+
` (classified on ${c.criteria.join(" + ")}; geo + "uses-CRM" not CRM-verified)`,
|
|
517
|
+
`$ covered: ${usd(coverage.dollarCovered)} of ${usd(model.tamUsd)} (${pct(coverage.accountCoverage)} of estimate)`,
|
|
518
|
+
);
|
|
519
|
+
if (coverage.bottomUpExceedsEstimate) {
|
|
520
|
+
lines.push(
|
|
521
|
+
`⚠ Bottom-up exceeds the estimate: ${c.inTam.toLocaleString()} in-TAM accounts in CRM > ` +
|
|
522
|
+
`${model.universe.accounts.toLocaleString()} estimated. The estimate was a FLOOR — your real market is ` +
|
|
523
|
+
`at least ${(coverage.reconciledUniverse ?? c.inTam).toLocaleString()}. Re-estimate (broader ICP / better ` +
|
|
524
|
+
`source) to find the remaining headroom.`,
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
if (c.unknown > 0) {
|
|
528
|
+
lines.push(
|
|
529
|
+
` ${c.unknown.toLocaleString()} accounts couldn't be classified (missing ${c.criteria.join("/")} on the record) ` +
|
|
530
|
+
"— enrich them, or they may be in- or out-of-TAM.",
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
} else {
|
|
534
|
+
// Unclassified (legacy model with no targeting, or geo/tech-only ICP).
|
|
535
|
+
lines.push(
|
|
536
|
+
`In CRM: ${coverage.inCrm.accounts.toLocaleString()} accounts (${pct(coverage.accountCoverage)}) / ` +
|
|
537
|
+
`${coverage.inCrm.contacts.toLocaleString()} contacts (${pct(coverage.contactCoverage)})`,
|
|
538
|
+
` └ added since baseline: ${coverage.addedSinceBaseline.accounts.toLocaleString()} accounts / ` +
|
|
539
|
+
`${coverage.addedSinceBaseline.contacts.toLocaleString()} contacts`,
|
|
540
|
+
`$ covered: ${usd(coverage.dollarCovered)} of ${usd(model.tamUsd)} (${pct(coverage.accountCoverage)})`,
|
|
541
|
+
);
|
|
542
|
+
if (coverage.classified) {
|
|
543
|
+
lines.push(
|
|
544
|
+
` (counting ALL CRM accounts — this TAM has no CRM-checkable criteria (geo/technology only); ` +
|
|
545
|
+
"re-estimate with size/industry in the ICP to classify in/out-of-TAM)",
|
|
546
|
+
);
|
|
547
|
+
} else if (!model.targeting) {
|
|
548
|
+
lines.push(" (counting ALL CRM accounts — re-run `tam estimate` to store the ICP filter and classify in/out-of-TAM)");
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
if (eta) {
|
|
552
|
+
lines.push(
|
|
553
|
+
`Pace: ${eta.accountsPerDay}/day → ~${eta.daysRemaining} days to fill ` +
|
|
554
|
+
`(${eta.accountsRemaining.toLocaleString()} accounts left, ETA ${eta.etaDate}; ${eta.basis})`,
|
|
555
|
+
);
|
|
556
|
+
} else {
|
|
557
|
+
lines.push(`Pace: not enough history to project an ETA yet — save another reading after some population runs.`);
|
|
558
|
+
}
|
|
559
|
+
if (model.crossChecks.length) {
|
|
560
|
+
lines.push(`Cross-checks:`);
|
|
561
|
+
for (const cc of model.crossChecks) {
|
|
562
|
+
lines.push(` • ${cc.claim}${cc.valueUsd ? ` (${usd(cc.valueUsd)})` : ""} — ${cc.sourceUrl}`);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return lines.join("\n");
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** A client-ready markdown deliverable for `tam report`. */
|
|
569
|
+
export function tamReportToMarkdown(model: TamModel, timeline: TamCoverage[], eta: TamEta | null): string {
|
|
570
|
+
const latest = timeline.length ? timeline[timeline.length - 1] : computeCoverage(model, model.baseline, model.createdAt);
|
|
571
|
+
const lines: string[] = [
|
|
572
|
+
`# TAM map — ${model.name}`,
|
|
573
|
+
"",
|
|
574
|
+
`**ICP:** ${model.icpName} · **Created:** ${model.createdAt.slice(0, 10)}`,
|
|
575
|
+
"",
|
|
576
|
+
"## The universe",
|
|
577
|
+
"",
|
|
578
|
+
`| | Estimate |`,
|
|
579
|
+
`| --- | --- |`,
|
|
580
|
+
`| Accounts | ${model.universe.accounts.toLocaleString()} (${model.universe.accountsSource}) |`,
|
|
581
|
+
`| Buyers / account | ${model.universe.buyersPerAccount} (${model.universe.buyersSource}) |`,
|
|
582
|
+
`| Contacts (population target) | ${model.universe.contacts.toLocaleString()} |`,
|
|
583
|
+
`| ACV (${model.acv.basis} basis) | ${usd(model.acv.valueUsd)} (${model.acv.source}) |`,
|
|
584
|
+
`| **TAM** | **${usd(model.tamUsd)}** |`,
|
|
585
|
+
"",
|
|
586
|
+
];
|
|
587
|
+
if (model.crossChecks.length) {
|
|
588
|
+
lines.push("### Cross-checks (citable)", "");
|
|
589
|
+
for (const c of model.crossChecks) {
|
|
590
|
+
lines.push(`- **${c.claim}**${c.valueUsd ? ` — ${usd(c.valueUsd)}` : ""} `);
|
|
591
|
+
lines.push(` > ${c.quote} `);
|
|
592
|
+
lines.push(` [source](${c.sourceUrl})${c.asOf ? ` · ${c.asOf}` : ""}`);
|
|
593
|
+
}
|
|
594
|
+
lines.push("");
|
|
595
|
+
}
|
|
596
|
+
const cl = latest.classified;
|
|
597
|
+
const inTamAccounts = cl && cl.criteria.length > 0 ? cl.inTam : latest.inCrm.accounts;
|
|
598
|
+
lines.push(
|
|
599
|
+
"## Coverage",
|
|
600
|
+
"",
|
|
601
|
+
`| Dimension | In CRM (in-TAM) | Universe | Covered |`,
|
|
602
|
+
`| --- | --- | --- | --- |`,
|
|
603
|
+
`| Accounts | ${inTamAccounts.toLocaleString()} | ${latest.universe.accounts.toLocaleString()} | ${pct(latest.accountCoverage)} |`,
|
|
604
|
+
`| Dollars | ${usd(latest.dollarCovered)} | ${usd(latest.universe.tamUsd)} | ${pct(latest.accountCoverage)} |`,
|
|
605
|
+
"",
|
|
606
|
+
);
|
|
607
|
+
if (cl && cl.criteria.length > 0) {
|
|
608
|
+
lines.push(
|
|
609
|
+
`Of **${cl.totalCrm.toLocaleString()}** CRM accounts: **${cl.inTam.toLocaleString()} in-TAM**, ` +
|
|
610
|
+
`${cl.outOfTam.toLocaleString()} out-of-TAM, ${cl.unknown.toLocaleString()} unknown ` +
|
|
611
|
+
`(classified on ${cl.criteria.join(" + ")}; geo + "uses-CRM" not CRM-verified).`,
|
|
612
|
+
"",
|
|
613
|
+
);
|
|
614
|
+
if (latest.bottomUpExceedsEstimate) {
|
|
615
|
+
lines.push(
|
|
616
|
+
`> ⚠ **Bottom-up exceeds the estimate.** ${cl.inTam.toLocaleString()} in-TAM accounts already in CRM > ` +
|
|
617
|
+
`${model.universe.accounts.toLocaleString()} estimated — the estimate was a floor; the real universe is ` +
|
|
618
|
+
`at least ${(latest.reconciledUniverse ?? cl.inTam).toLocaleString()}. Re-estimate to find the headroom.`,
|
|
619
|
+
"",
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
} else {
|
|
623
|
+
lines.push(
|
|
624
|
+
`Added since baseline: **${latest.addedSinceBaseline.accounts.toLocaleString()} accounts**, ` +
|
|
625
|
+
`**${latest.addedSinceBaseline.contacts.toLocaleString()} contacts**. ` +
|
|
626
|
+
"_(All CRM accounts counted — no ICP filter stored; re-estimate to classify in/out-of-TAM.)_",
|
|
627
|
+
"",
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
if (eta) {
|
|
631
|
+
lines.push(
|
|
632
|
+
"## Pace & ETA",
|
|
633
|
+
"",
|
|
634
|
+
`At **${eta.accountsPerDay} accounts/day** (${eta.basis}), ~**${eta.daysRemaining} days** remain ` +
|
|
635
|
+
`to cover the account universe (${eta.accountsRemaining.toLocaleString()} left) — projected **${eta.etaDate}**.`,
|
|
636
|
+
"",
|
|
637
|
+
);
|
|
638
|
+
} else {
|
|
639
|
+
lines.push(
|
|
640
|
+
"## Pace & ETA",
|
|
641
|
+
"",
|
|
642
|
+
"_Not enough history to project yet._ Save another `tam status --save` reading after a few population runs.",
|
|
643
|
+
"",
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
if (timeline.length >= 2) {
|
|
647
|
+
lines.push("### Burn-up", "", `| Date | Accounts in CRM | Covered |`, `| --- | --- | --- |`);
|
|
648
|
+
for (const c of timeline) {
|
|
649
|
+
lines.push(`| ${c.at.slice(0, 10)} | ${c.inCrm.accounts.toLocaleString()} | ${pct(c.accountCoverage)} |`);
|
|
650
|
+
}
|
|
651
|
+
lines.push("");
|
|
652
|
+
}
|
|
653
|
+
return lines.join("\n");
|
|
654
|
+
}
|