fullstackgtm 0.34.0 → 0.37.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 +91 -0
- package/README.md +25 -0
- package/dist/acquireMeter.d.ts +67 -0
- package/dist/acquireMeter.js +145 -0
- package/dist/acquireSeen.d.ts +5 -0
- package/dist/acquireSeen.js +54 -0
- package/dist/cli.js +732 -21
- package/dist/connectors/hubspot.js +135 -0
- package/dist/connectors/prospectSources.d.ts +91 -0
- package/dist/connectors/prospectSources.js +227 -0
- package/dist/enrich.d.ts +87 -0
- package/dist/enrich.js +188 -4
- package/dist/format.d.ts +3 -1
- package/dist/format.js +14 -2
- package/dist/health.d.ts +71 -0
- package/dist/health.js +172 -0
- package/dist/icp.d.ts +96 -0
- package/dist/icp.js +256 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mappings.js +3 -0
- package/dist/types.d.ts +17 -1
- package/docs/api.md +29 -2
- package/docs/architecture.md +8 -1
- package/docs/dx-punch-list.md +87 -0
- package/llms.txt +16 -0
- package/package.json +1 -1
- package/skills/fullstackgtm/SKILL.md +2 -1
- package/src/acquireMeter.ts +186 -0
- package/src/acquireSeen.ts +57 -0
- package/src/cli.ts +870 -20
- package/src/connectors/hubspot.ts +140 -0
- package/src/connectors/prospectSources.ts +324 -0
- package/src/enrich.ts +275 -3
- package/src/format.ts +20 -2
- package/src/health.ts +238 -0
- package/src/icp.ts +313 -0
- package/src/index.ts +8 -0
- package/src/mappings.ts +3 -0
- package/src/types.ts +24 -0
package/dist/enrich.js
CHANGED
|
@@ -11,7 +11,7 @@ const MATCH_KEYS = {
|
|
|
11
11
|
contact: ["email", "name"],
|
|
12
12
|
};
|
|
13
13
|
/** API source ids the MVP can pull from. */
|
|
14
|
-
export const SUPPORTED_API_SOURCES = ["apollo"];
|
|
14
|
+
export const SUPPORTED_API_SOURCES = ["apollo", "explorium", "pipe0"];
|
|
15
15
|
/**
|
|
16
16
|
* Canonical fields enrich may target, plus the HubSpot property spellings the
|
|
17
17
|
* config may use for them (so `"crm": "numberofemployees"` and
|
|
@@ -171,10 +171,74 @@ export function parseEnrichConfig(raw) {
|
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
173
|
}
|
|
174
|
-
|
|
175
|
-
|
|
174
|
+
// `fields` drives append/refresh. An acquire-only config (net-new lead
|
|
175
|
+
// creation, no blank-filling) legitimately maps no fields — accept it when
|
|
176
|
+
// an acquire.create mapping is present.
|
|
177
|
+
const hasAcquireCreate = Boolean(config.acquire?.create && Object.keys(config.acquire.create).length > 0);
|
|
178
|
+
if (!anyField && !hasAcquireCreate) {
|
|
179
|
+
fail('"fields" maps nothing — add at least one field entry (or an "acquire.create" mapping)');
|
|
180
|
+
}
|
|
176
181
|
return config;
|
|
177
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Built-in zero-config presets for well-known sources, so the common Mode-A
|
|
185
|
+
* loop — "feed a Clay export, get the dedup/routing verdict" — needs no
|
|
186
|
+
* hand-authored config. These are **match-only** (empty `fields`): the value is
|
|
187
|
+
* the matched / unmatched / ambiguous routing and collision detection, not field
|
|
188
|
+
* writes. Drop an `enrich.config.json` next to your run to map fields for actual
|
|
189
|
+
* field enrichment; an explicit config always wins over a preset. Constructed
|
|
190
|
+
* directly (not via `parseEnrichConfig`) so the match-only shape is allowed.
|
|
191
|
+
*/
|
|
192
|
+
export const BUILTIN_ENRICH_PRESETS = {
|
|
193
|
+
clay: {
|
|
194
|
+
sources: { clay: { kind: "ingest", format: "csv" } },
|
|
195
|
+
policy: { overwrite: "never", defaultStaleDays: 90 },
|
|
196
|
+
match: {
|
|
197
|
+
company: { keys: ["domain"], onAmbiguous: "skip" },
|
|
198
|
+
contact: { keys: ["email"], onAmbiguous: "skip" },
|
|
199
|
+
},
|
|
200
|
+
fields: {},
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
export function builtinEnrichPreset(source) {
|
|
204
|
+
return source ? BUILTIN_ENRICH_PRESETS[source] : undefined;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Zero-config `enrich acquire` preset so every client gets targeted, deduped,
|
|
208
|
+
* metered lead-fill out of the box — no hand-authored enrich.config.json. The
|
|
209
|
+
* ICP (icp.json) supplies the targeting; this supplies sensible plumbing. The
|
|
210
|
+
* create mapping writes the prospect's LinkedIn URL into hs_linkedin_url, so
|
|
211
|
+
* each created contact strengthens future dedup. An explicit config always wins.
|
|
212
|
+
*/
|
|
213
|
+
export function builtinAcquirePreset(source) {
|
|
214
|
+
const provider = source ?? "pipe0";
|
|
215
|
+
if (provider !== "pipe0" && provider !== "explorium")
|
|
216
|
+
return undefined;
|
|
217
|
+
return {
|
|
218
|
+
sources: { [provider]: { kind: "api" } },
|
|
219
|
+
match: { contact: { keys: ["email"], onAmbiguous: "skip" } },
|
|
220
|
+
fields: {},
|
|
221
|
+
policy: { overwrite: "never" },
|
|
222
|
+
acquire: {
|
|
223
|
+
budget: { records: { perDay: 50, perMonth: 500 }, spend: { perDay: 25, perMonth: 250 } },
|
|
224
|
+
costPerRecord: { pipe0: 0.1, explorium: 0.4 },
|
|
225
|
+
discovery: { [provider]: { provider, size: 25 } },
|
|
226
|
+
create: {
|
|
227
|
+
contact: {
|
|
228
|
+
matchKey: "email",
|
|
229
|
+
properties: {
|
|
230
|
+
email: "email",
|
|
231
|
+
firstname: "firstName",
|
|
232
|
+
lastname: "lastName",
|
|
233
|
+
jobtitle: "jobTitle",
|
|
234
|
+
company: "companyName",
|
|
235
|
+
hs_linkedin_url: "linkedin",
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
178
242
|
export function loadEnrichConfig(path) {
|
|
179
243
|
let raw;
|
|
180
244
|
try {
|
|
@@ -429,7 +493,12 @@ export function buildEnrichPlan(options) {
|
|
|
429
493
|
for (const record of records) {
|
|
430
494
|
const match = config.match[record.objectType];
|
|
431
495
|
const fields = (config.fields[record.objectType] ?? []).filter((field) => field.from[source] !== undefined);
|
|
432
|
-
|
|
496
|
+
// Run the matcher whenever the object type has match keys; field mappings
|
|
497
|
+
// only gate whether we EMIT field ops. With no fields (a match-only config,
|
|
498
|
+
// e.g. the built-in Clay preset) this still reports the matched / ambiguous
|
|
499
|
+
// / unmatched routing verdict and records collisions — the Mode-A hygiene
|
|
500
|
+
// gate — it just proposes zero field writes.
|
|
501
|
+
if (!match) {
|
|
433
502
|
counts.unmatched += 1;
|
|
434
503
|
unmatchedSourceIds.push(record.id);
|
|
435
504
|
continue;
|
|
@@ -583,6 +652,121 @@ export function buildEnrichPlan(options) {
|
|
|
583
652
|
};
|
|
584
653
|
return { plan, counts, stamps, ambiguities, unmatchedSourceIds };
|
|
585
654
|
}
|
|
655
|
+
/**
|
|
656
|
+
* Match each sourced record against the snapshot and route it: matched =
|
|
657
|
+
* already in the CRM (skip), ambiguous = a possible duplicate exists (skip —
|
|
658
|
+
* resolve-first never creates over ambiguity), unmatched = a net-new lead.
|
|
659
|
+
* Unmatched rows with a dedupe key and at least one mapped property become
|
|
660
|
+
* `create_record` operations, capped at `maxRecords` (the meter's headroom).
|
|
661
|
+
* Always a dry-run plan; nothing is written until apply.
|
|
662
|
+
*/
|
|
663
|
+
export function buildAcquirePlan(options) {
|
|
664
|
+
const { config, source, snapshot, records, runLabel } = options;
|
|
665
|
+
const nowIso = (options.now ?? (() => new Date()))().toISOString();
|
|
666
|
+
const sourceConfig = config.sources[source];
|
|
667
|
+
if (!sourceConfig)
|
|
668
|
+
throw new Error(`enrich: source "${source}" is not declared in the config`);
|
|
669
|
+
const acquire = config.acquire;
|
|
670
|
+
if (!acquire)
|
|
671
|
+
throw new Error('enrich acquire: config has no "acquire" section');
|
|
672
|
+
const cap = options.maxRecords ?? null;
|
|
673
|
+
const costPerRecord = acquire.costPerRecord?.[source] ?? 0;
|
|
674
|
+
const operations = [];
|
|
675
|
+
const evidence = [];
|
|
676
|
+
const counts = {
|
|
677
|
+
fetched: records.length,
|
|
678
|
+
matched: 0,
|
|
679
|
+
ambiguous: 0,
|
|
680
|
+
unmatched: 0,
|
|
681
|
+
created: 0,
|
|
682
|
+
withheldByMeter: 0,
|
|
683
|
+
};
|
|
684
|
+
let estCostUsd = 0;
|
|
685
|
+
for (const record of records) {
|
|
686
|
+
const createMap = acquire.create[record.objectType];
|
|
687
|
+
const match = config.match[record.objectType];
|
|
688
|
+
// No create mapping or no match config for this type — can neither create
|
|
689
|
+
// nor dedupe it safely; count as unmatched and skip.
|
|
690
|
+
if (!createMap || !match) {
|
|
691
|
+
counts.unmatched += 1;
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
const outcome = matchSourceRecord(snapshot, record.objectType, match.keys, record.keys);
|
|
695
|
+
if (outcome.status === "matched") {
|
|
696
|
+
counts.matched += 1;
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
if (outcome.status === "ambiguous") {
|
|
700
|
+
// Resolve-first: a possible duplicate exists — never create over it.
|
|
701
|
+
counts.ambiguous += 1;
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
counts.unmatched += 1;
|
|
705
|
+
const matchValue = String(record.keys[createMap.matchKey] ?? "").trim();
|
|
706
|
+
if (!matchValue)
|
|
707
|
+
continue; // no dedupe key → refuse to create (can't resolve-first)
|
|
708
|
+
if (cap !== null && counts.created >= cap) {
|
|
709
|
+
counts.withheldByMeter += 1;
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
712
|
+
const properties = {};
|
|
713
|
+
for (const [crmProp, path] of Object.entries(createMap.properties)) {
|
|
714
|
+
const value = sourceValueAt(record.payload, path);
|
|
715
|
+
if (!isEmptyValue(value))
|
|
716
|
+
properties[crmProp] = String(value);
|
|
717
|
+
}
|
|
718
|
+
if (Object.keys(properties).length === 0)
|
|
719
|
+
continue; // nothing to write
|
|
720
|
+
let associateCompanyName;
|
|
721
|
+
if (createMap.associateCompanyFrom) {
|
|
722
|
+
const companyValue = sourceValueAt(record.payload, createMap.associateCompanyFrom);
|
|
723
|
+
if (!isEmptyValue(companyValue))
|
|
724
|
+
associateCompanyName = String(companyValue);
|
|
725
|
+
}
|
|
726
|
+
const recordEvidence = evidenceFor(source, sourceConfig.kind, sourceConfig.format, record, undefined, nowIso);
|
|
727
|
+
evidence.push(recordEvidence);
|
|
728
|
+
const payload = {
|
|
729
|
+
properties,
|
|
730
|
+
matchKey: createMap.matchKey,
|
|
731
|
+
matchValue,
|
|
732
|
+
source,
|
|
733
|
+
estCostUsd: costPerRecord,
|
|
734
|
+
associateCompanyName,
|
|
735
|
+
};
|
|
736
|
+
operations.push({
|
|
737
|
+
id: `op_acq_${fnv1a(`${source}:${record.objectType}:${matchValue}`)}`,
|
|
738
|
+
objectType: canonicalObjectType(record.objectType),
|
|
739
|
+
objectId: `create:${matchValue}`,
|
|
740
|
+
operation: "create_record",
|
|
741
|
+
beforeValue: null,
|
|
742
|
+
afterValue: payload,
|
|
743
|
+
reason: `${source} sourced net-new ${record.objectType} "${describeSourceRecord(record)}" ` +
|
|
744
|
+
`(${createMap.matchKey}=${matchValue}); no CRM match — create as a lead.`,
|
|
745
|
+
sourceRuleOrPolicy: `acquire:${source}`,
|
|
746
|
+
riskLevel: "medium",
|
|
747
|
+
approvalRequired: true,
|
|
748
|
+
rollback: "Archive the created record (it was net-new).",
|
|
749
|
+
evidenceIds: [recordEvidence.id],
|
|
750
|
+
});
|
|
751
|
+
counts.created += 1;
|
|
752
|
+
estCostUsd += costPerRecord;
|
|
753
|
+
}
|
|
754
|
+
const plan = {
|
|
755
|
+
id: `patch_plan_acq_${fnv1a(`${source}:${runLabel}:${nowIso}`)}`,
|
|
756
|
+
title: `Acquire leads — ${source}`,
|
|
757
|
+
createdAt: nowIso,
|
|
758
|
+
status: operations.length > 0 ? "needs_approval" : "draft",
|
|
759
|
+
dryRun: true,
|
|
760
|
+
summary: `${counts.created} net-new lead(s) proposed from ${source} (${counts.fetched} sourced: ` +
|
|
761
|
+
`${counts.matched} already in CRM, ${counts.ambiguous} ambiguous skipped, ${counts.unmatched} unmatched` +
|
|
762
|
+
`${counts.withheldByMeter > 0 ? `, ${counts.withheldByMeter} withheld by meter` : ""}). ` +
|
|
763
|
+
`Est. cost $${estCostUsd.toFixed(2)}.`,
|
|
764
|
+
findings: [],
|
|
765
|
+
evidence,
|
|
766
|
+
operations,
|
|
767
|
+
};
|
|
768
|
+
return { plan, counts, estCostUsd };
|
|
769
|
+
}
|
|
586
770
|
// ---------------------------------------------------------------------------
|
|
587
771
|
// Staleness: compute the refresh work set from run-store stamps.
|
|
588
772
|
/** Latest stamp per (objectType, objectId, field) across a source's runs. */
|
package/dist/format.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { PatchPlan, PatchPlanRun } from "./types.ts";
|
|
2
|
-
export declare function patchPlanToMarkdown(plan: PatchPlan
|
|
2
|
+
export declare function patchPlanToMarkdown(plan: PatchPlan, opts?: {
|
|
3
|
+
summary?: boolean;
|
|
4
|
+
}): string;
|
|
3
5
|
export declare function formatPatchPlanRun(run: PatchPlanRun): string;
|
package/dist/format.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
// `summary: true` renders only the header + the Findings-by-Rule table + an
|
|
2
|
+
// operation count, for read verbs like `audit` where the full per-operation
|
|
3
|
+
// dump (1,400+ lines on a real portal) buries the signal. Defaults to the full
|
|
4
|
+
// view so write-preview callers (bulk-update, fix, dedupe, plans show, MCP) —
|
|
5
|
+
// where you approve specific operations — keep every operation's detail.
|
|
6
|
+
export function patchPlanToMarkdown(plan, opts = {}) {
|
|
2
7
|
const lines = [
|
|
3
8
|
`# ${plan.title}`,
|
|
4
9
|
"",
|
|
@@ -20,6 +25,13 @@ export function patchPlanToMarkdown(plan) {
|
|
|
20
25
|
});
|
|
21
26
|
lines.push("");
|
|
22
27
|
}
|
|
28
|
+
if (opts.summary) {
|
|
29
|
+
const ops = plan.operations.length;
|
|
30
|
+
lines.push(ops === 0
|
|
31
|
+
? "No patch operations proposed."
|
|
32
|
+
: `${ops} dry-run patch operation${ops === 1 ? "" : "s"} proposed — nothing written.`, "", "Full plan detail: re-run with `--full`.", "Client-ready report: `fullstackgtm report` (add `--format html` for a printable file).");
|
|
33
|
+
return `${lines.join("\n")}\n`;
|
|
34
|
+
}
|
|
23
35
|
lines.push("## Findings", "");
|
|
24
36
|
const findings = plan.pipelineFindings ?? [];
|
|
25
37
|
if (findings.length > 0) {
|
|
@@ -58,7 +70,7 @@ export function patchPlanToMarkdown(plan) {
|
|
|
58
70
|
lines.push(`- **${operation.operation}** ${operation.objectType}/${operation.objectId}`, ` - ID: ${operation.id}`, ` - Field/action: ${operation.field ?? operation.operation}`, ` - Findings: ${formatRefs(operation.findingIds)}`, ` - Evidence refs: ${formatRefs(operation.evidenceIds)}`, ` - Before: ${formatValue(operation.beforeValue)}`, ` - After: ${formatValue(operation.afterValue)}`, ` - Reason: ${operation.reason}`, ` - Source rule/policy: ${operation.sourceRuleOrPolicy ?? "unspecified"}`, ` - Risk: ${operation.riskLevel}`, ` - Approval required: ${operation.approvalRequired ? "yes" : "no"}`, ` - Rollback: ${operation.rollback ?? "restore prior value if apply is rejected or verification fails"}`, ` - Verification: ${formatVerification(operation.verification)}`);
|
|
59
71
|
}
|
|
60
72
|
}
|
|
61
|
-
lines.push("", ">
|
|
73
|
+
lines.push("", "> Dry-run plan — read-only. No provider write happens until you approve specific operations and run `apply`; placeholder values are refused without an explicit override. These safety invariants are not beta.");
|
|
62
74
|
return `${lines.join("\n")}\n`;
|
|
63
75
|
}
|
|
64
76
|
export function formatPatchPlanRun(run) {
|
package/dist/health.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { AuditFindingSeverity, CanonicalGtmSnapshot, PatchPlan } from "./types.ts";
|
|
2
|
+
export type HealthEntry = {
|
|
3
|
+
/** ISO timestamp of the audit that produced this entry. */
|
|
4
|
+
at: string;
|
|
5
|
+
/** The saved plan this entry summarizes (correlates to plans/ and snapshots/). */
|
|
6
|
+
planId: string;
|
|
7
|
+
/** Deterministic 0–100 hygiene score (higher is healthier). */
|
|
8
|
+
score: number;
|
|
9
|
+
/** Total finding count across all rules. */
|
|
10
|
+
findings: number;
|
|
11
|
+
/** Severity-weighted finding total (drives the score). */
|
|
12
|
+
weightedFindings: number;
|
|
13
|
+
/** Record counts at audit time — the denominator that normalizes the score. */
|
|
14
|
+
records: {
|
|
15
|
+
accounts: number;
|
|
16
|
+
contacts: number;
|
|
17
|
+
deals: number;
|
|
18
|
+
total: number;
|
|
19
|
+
};
|
|
20
|
+
/** Finding count per rule id. */
|
|
21
|
+
byRule: Record<string, number>;
|
|
22
|
+
/** Finding count per severity. */
|
|
23
|
+
severityCounts: Record<AuditFindingSeverity, number>;
|
|
24
|
+
};
|
|
25
|
+
export type HealthRuleDelta = {
|
|
26
|
+
ruleId: string;
|
|
27
|
+
current: number;
|
|
28
|
+
previous: number;
|
|
29
|
+
/** current − previous: positive = more findings (worse), negative = fewer (better). */
|
|
30
|
+
delta: number;
|
|
31
|
+
};
|
|
32
|
+
export type HealthRollup = {
|
|
33
|
+
profile: string;
|
|
34
|
+
auditCount: number;
|
|
35
|
+
first: string;
|
|
36
|
+
latest: string;
|
|
37
|
+
current: HealthEntry;
|
|
38
|
+
previous: HealthEntry | null;
|
|
39
|
+
/** current.score − previous.score: positive = improving. null on the first audit. */
|
|
40
|
+
scoreDelta: number | null;
|
|
41
|
+
ruleDeltas: HealthRuleDelta[];
|
|
42
|
+
history: Array<{
|
|
43
|
+
at: string;
|
|
44
|
+
score: number;
|
|
45
|
+
findings: number;
|
|
46
|
+
}>;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Deterministically score a saved audit. score = 100 / (1 + weighted findings
|
|
50
|
+
* per record): 0 findings → 100; one weighted finding per record → 50; the
|
|
51
|
+
* curve is bounded (0, 100], monotonic, and needs no clamping or magic
|
|
52
|
+
* constants. A messy 50-record CRM scores worse than the same finding count
|
|
53
|
+
* across 5,000 records, which is the point.
|
|
54
|
+
*/
|
|
55
|
+
export declare function computeHealth(plan: PatchPlan, snapshot: CanonicalGtmSnapshot, at: string): HealthEntry;
|
|
56
|
+
/** Roll a timeline up into the current state, the change since last time, and per-rule deltas. */
|
|
57
|
+
export declare function summarizeHealth(entries: HealthEntry[], profile: string): HealthRollup | null;
|
|
58
|
+
/** Human-readable rollup: headline score + trend, then per-rule change since last audit. */
|
|
59
|
+
export declare function healthToMarkdown(rollup: HealthRollup): string;
|
|
60
|
+
/** `$FSGTM_HOME[/profiles/<name>]/health.jsonl` — append-only, one entry per audit-save. */
|
|
61
|
+
export declare function healthFilePath(): string;
|
|
62
|
+
/** `$FSGTM_HOME[/profiles/<name>]/snapshots/` — canonical snapshots correlated by plan id. */
|
|
63
|
+
export declare function snapshotsDir(): string;
|
|
64
|
+
/** Append a health entry to the active profile's timeline (0600, owner-only). */
|
|
65
|
+
export declare function appendHealthEntry(entry: HealthEntry): void;
|
|
66
|
+
/** Read the active profile's health timeline; tolerant of partial/corrupt lines. */
|
|
67
|
+
export declare function readHealthTimeline(): HealthEntry[];
|
|
68
|
+
/** Persist the snapshot behind a saved audit so the timeline can diff/attribute later. */
|
|
69
|
+
export declare function saveWorkspaceSnapshot(planId: string, snapshot: CanonicalGtmSnapshot): string;
|
|
70
|
+
/** The active profile name, for rollup labeling. */
|
|
71
|
+
export declare function activeWorkspaceProfile(): string;
|
package/dist/health.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { activeProfile, credentialsDir, ensureSecureHomeDir, writeSecureFile } from "./credentials.js";
|
|
4
|
+
/**
|
|
5
|
+
* The engagement workspace: a per-client health timeline that accrues from the
|
|
6
|
+
* verb people already run (`audit --save`). State lives in the profile dir
|
|
7
|
+
* (`$FSGTM_HOME[/profiles/<name>]`) alongside credentials and plans, so a
|
|
8
|
+
* consultant working `--profile <client>` builds a continuous record of one
|
|
9
|
+
* org's CRM health over time — not just episodic one-off audits.
|
|
10
|
+
*
|
|
11
|
+
* The score is DETERMINISTIC (no LLM): same plan + same snapshot → same score,
|
|
12
|
+
* so it is stable in CI and comparable run-over-run.
|
|
13
|
+
*/
|
|
14
|
+
// Severity weights: a critical finding costs ~3× a warning, ~10× an info.
|
|
15
|
+
const SEVERITY_WEIGHT = { info: 1, warning: 3, critical: 10 };
|
|
16
|
+
/**
|
|
17
|
+
* Deterministically score a saved audit. score = 100 / (1 + weighted findings
|
|
18
|
+
* per record): 0 findings → 100; one weighted finding per record → 50; the
|
|
19
|
+
* curve is bounded (0, 100], monotonic, and needs no clamping or magic
|
|
20
|
+
* constants. A messy 50-record CRM scores worse than the same finding count
|
|
21
|
+
* across 5,000 records, which is the point.
|
|
22
|
+
*/
|
|
23
|
+
export function computeHealth(plan, snapshot, at) {
|
|
24
|
+
const byRule = {};
|
|
25
|
+
const severityCounts = { info: 0, warning: 0, critical: 0 };
|
|
26
|
+
let weightedFindings = 0;
|
|
27
|
+
for (const finding of plan.findings) {
|
|
28
|
+
byRule[finding.ruleId] = (byRule[finding.ruleId] ?? 0) + 1;
|
|
29
|
+
severityCounts[finding.severity] += 1;
|
|
30
|
+
weightedFindings += SEVERITY_WEIGHT[finding.severity];
|
|
31
|
+
}
|
|
32
|
+
const records = {
|
|
33
|
+
accounts: snapshot.accounts.length,
|
|
34
|
+
contacts: snapshot.contacts.length,
|
|
35
|
+
deals: snapshot.deals.length,
|
|
36
|
+
total: snapshot.accounts.length + snapshot.contacts.length + snapshot.deals.length,
|
|
37
|
+
};
|
|
38
|
+
const penalty = weightedFindings / Math.max(records.total, 1);
|
|
39
|
+
const score = Math.round(100 / (1 + penalty));
|
|
40
|
+
return {
|
|
41
|
+
at,
|
|
42
|
+
planId: plan.id,
|
|
43
|
+
score,
|
|
44
|
+
findings: plan.findings.length,
|
|
45
|
+
weightedFindings,
|
|
46
|
+
records,
|
|
47
|
+
byRule,
|
|
48
|
+
severityCounts,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Roll a timeline up into the current state, the change since last time, and per-rule deltas. */
|
|
52
|
+
export function summarizeHealth(entries, profile) {
|
|
53
|
+
if (entries.length === 0)
|
|
54
|
+
return null;
|
|
55
|
+
// Oldest → newest, so `current` is the last entry.
|
|
56
|
+
const sorted = [...entries].sort((a, b) => a.at.localeCompare(b.at));
|
|
57
|
+
const current = sorted[sorted.length - 1];
|
|
58
|
+
const previous = sorted.length > 1 ? sorted[sorted.length - 2] : null;
|
|
59
|
+
const ruleIds = new Set([
|
|
60
|
+
...Object.keys(current.byRule),
|
|
61
|
+
...(previous ? Object.keys(previous.byRule) : []),
|
|
62
|
+
]);
|
|
63
|
+
const ruleDeltas = [...ruleIds]
|
|
64
|
+
.map((ruleId) => {
|
|
65
|
+
const cur = current.byRule[ruleId] ?? 0;
|
|
66
|
+
const prev = previous?.byRule[ruleId] ?? 0;
|
|
67
|
+
return { ruleId, current: cur, previous: prev, delta: cur - prev };
|
|
68
|
+
})
|
|
69
|
+
.sort((a, b) => b.current - a.current || a.ruleId.localeCompare(b.ruleId));
|
|
70
|
+
return {
|
|
71
|
+
profile,
|
|
72
|
+
auditCount: sorted.length,
|
|
73
|
+
first: sorted[0].at,
|
|
74
|
+
latest: current.at,
|
|
75
|
+
current,
|
|
76
|
+
previous,
|
|
77
|
+
scoreDelta: previous ? current.score - previous.score : null,
|
|
78
|
+
ruleDeltas,
|
|
79
|
+
history: sorted.map((entry) => ({ at: entry.at, score: entry.score, findings: entry.findings })),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
// Sign-based and uniform: ▲ = the number went up, ▼ = down. The reader supplies
|
|
83
|
+
// the meaning (score up = good; findings up = bad) — mixing arrow direction with
|
|
84
|
+
// good/bad reads as contradictory ("▲ -3").
|
|
85
|
+
function arrow(delta) {
|
|
86
|
+
if (delta === 0)
|
|
87
|
+
return "·";
|
|
88
|
+
return delta > 0 ? "▲" : "▼";
|
|
89
|
+
}
|
|
90
|
+
/** Human-readable rollup: headline score + trend, then per-rule change since last audit. */
|
|
91
|
+
export function healthToMarkdown(rollup) {
|
|
92
|
+
const { current, scoreDelta } = rollup;
|
|
93
|
+
const lines = [`# GTM health — profile \`${rollup.profile}\``, ""];
|
|
94
|
+
const deltaText = scoreDelta === null
|
|
95
|
+
? "(first audit — no prior reading)"
|
|
96
|
+
: `${arrow(scoreDelta)} ${scoreDelta >= 0 ? "+" : ""}${scoreDelta} since the previous audit`;
|
|
97
|
+
lines.push(`Score: **${current.score}/100** ${deltaText}`, `Audits: ${rollup.auditCount} over ${shortDate(rollup.first)} → ${shortDate(rollup.latest)}`, `Findings: ${current.findings} (${current.severityCounts.critical} critical, ${current.severityCounts.warning} warning, ${current.severityCounts.info} info)`, `Records: ${current.records.accounts} accounts, ${current.records.contacts} contacts, ${current.records.deals} deals`, "");
|
|
98
|
+
if (rollup.history.length > 1) {
|
|
99
|
+
lines.push("## Trend", "");
|
|
100
|
+
for (const point of rollup.history) {
|
|
101
|
+
const marker = point.at === rollup.latest ? " ← latest" : "";
|
|
102
|
+
lines.push(`- ${shortDate(point.at)} score ${point.score} (${point.findings} findings)${marker}`);
|
|
103
|
+
}
|
|
104
|
+
lines.push("");
|
|
105
|
+
}
|
|
106
|
+
if (rollup.ruleDeltas.length > 0) {
|
|
107
|
+
lines.push("## By rule (Δ since previous audit)", "", "| Rule | Findings | Δ |", "| --- | --- | --- |");
|
|
108
|
+
for (const rule of rollup.ruleDeltas) {
|
|
109
|
+
const sign = rule.delta > 0 ? `+${rule.delta}` : `${rule.delta}`;
|
|
110
|
+
const cell = rule.delta === 0 ? "·" : `${arrow(rule.delta)} ${sign}`;
|
|
111
|
+
lines.push(`| ${rule.ruleId} | ${rule.current} | ${cell} |`);
|
|
112
|
+
}
|
|
113
|
+
lines.push("");
|
|
114
|
+
}
|
|
115
|
+
lines.push("> Score is deterministic: 100 / (1 + severity-weighted findings per record). Lower findings or more clean records ⇒ higher score.");
|
|
116
|
+
return `${lines.join("\n")}\n`;
|
|
117
|
+
}
|
|
118
|
+
function shortDate(iso) {
|
|
119
|
+
return iso.slice(0, 10);
|
|
120
|
+
}
|
|
121
|
+
// ── Profile-scoped storage ──────────────────────────────────────────────────
|
|
122
|
+
/** `$FSGTM_HOME[/profiles/<name>]/health.jsonl` — append-only, one entry per audit-save. */
|
|
123
|
+
export function healthFilePath() {
|
|
124
|
+
return join(credentialsDir(), "health.jsonl");
|
|
125
|
+
}
|
|
126
|
+
/** `$FSGTM_HOME[/profiles/<name>]/snapshots/` — canonical snapshots correlated by plan id. */
|
|
127
|
+
export function snapshotsDir() {
|
|
128
|
+
return join(credentialsDir(), "snapshots");
|
|
129
|
+
}
|
|
130
|
+
/** Append a health entry to the active profile's timeline (0600, owner-only). */
|
|
131
|
+
export function appendHealthEntry(entry) {
|
|
132
|
+
ensureSecureHomeDir();
|
|
133
|
+
appendFileSync(healthFilePath(), `${JSON.stringify(entry)}\n`, { mode: 0o600 });
|
|
134
|
+
}
|
|
135
|
+
/** Read the active profile's health timeline; tolerant of partial/corrupt lines. */
|
|
136
|
+
export function readHealthTimeline() {
|
|
137
|
+
let raw;
|
|
138
|
+
try {
|
|
139
|
+
raw = readFileSync(healthFilePath(), "utf8");
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
const entries = [];
|
|
145
|
+
for (const line of raw.split("\n")) {
|
|
146
|
+
const trimmed = line.trim();
|
|
147
|
+
if (!trimmed)
|
|
148
|
+
continue;
|
|
149
|
+
try {
|
|
150
|
+
entries.push(JSON.parse(trimmed));
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
// Skip a torn line rather than failing the whole rollup.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return entries;
|
|
157
|
+
}
|
|
158
|
+
/** Persist the snapshot behind a saved audit so the timeline can diff/attribute later. */
|
|
159
|
+
export function saveWorkspaceSnapshot(planId, snapshot) {
|
|
160
|
+
if (!/^[\w.-]+$/.test(planId))
|
|
161
|
+
throw new Error(`Invalid plan id: ${planId}`);
|
|
162
|
+
ensureSecureHomeDir();
|
|
163
|
+
const dir = snapshotsDir();
|
|
164
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
165
|
+
const path = join(dir, `${planId}.json`);
|
|
166
|
+
writeSecureFile(path, `${JSON.stringify(snapshot)}\n`);
|
|
167
|
+
return path;
|
|
168
|
+
}
|
|
169
|
+
/** The active profile name, for rollup labeling. */
|
|
170
|
+
export function activeWorkspaceProfile() {
|
|
171
|
+
return activeProfile();
|
|
172
|
+
}
|
package/dist/icp.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ICP — the Ideal Customer Profile that makes `enrich acquire` targeted instead
|
|
3
|
+
* of random. One structured artifact drives two things:
|
|
4
|
+
* 1. discovery filters — translated per provider (Explorium, pipe0/Crustdata)
|
|
5
|
+
* so the pull only returns ICP-shaped companies + people, and
|
|
6
|
+
* 2. fit scoring — every discovered prospect is scored against the persona so
|
|
7
|
+
* only above-threshold leads become create_record ops.
|
|
8
|
+
*
|
|
9
|
+
* Develop one via interview: an agent (Claude Code / Codex) reads INTERVIEW_SPEC,
|
|
10
|
+
* asks the questions with its AskUserQuestion tool, and writes the answers into
|
|
11
|
+
* an Icp (CLI: `icp interview` emits the spec, `icp show` renders the result).
|
|
12
|
+
*
|
|
13
|
+
* Zero runtime deps; pure functions (translation + scoring take plain data).
|
|
14
|
+
*/
|
|
15
|
+
export type Icp = {
|
|
16
|
+
name: string;
|
|
17
|
+
firmographics: {
|
|
18
|
+
/** human industry labels, e.g. ["software","saas"] — used for keyword/industry filters */
|
|
19
|
+
industries?: string[];
|
|
20
|
+
/** Explorium naics_category codes, e.g. ["5112"] (software publishers) */
|
|
21
|
+
naics?: string[];
|
|
22
|
+
/** provider-agnostic employee bands: "1-10","11-50","51-200","201-500","501-1000","1001-5000","5001-10000","10001+" */
|
|
23
|
+
employeeBands?: string[];
|
|
24
|
+
/** ISO country codes, lowercased, e.g. ["us"] */
|
|
25
|
+
geos?: string[];
|
|
26
|
+
};
|
|
27
|
+
persona: {
|
|
28
|
+
/** seniority: "cxo","vp","director","manager","owner","senior" */
|
|
29
|
+
jobLevels?: string[];
|
|
30
|
+
/** "sales","marketing","operations","finance" */
|
|
31
|
+
departments?: string[];
|
|
32
|
+
/** the title phrases that DEFINE the buyer — also the scoring signal */
|
|
33
|
+
titleKeywords?: string[];
|
|
34
|
+
};
|
|
35
|
+
signals?: {
|
|
36
|
+
intentTopics?: string[];
|
|
37
|
+
};
|
|
38
|
+
scoring?: {
|
|
39
|
+
/** minimum fit (0..1) for a prospect to become a create_record op. Default 0.5. */
|
|
40
|
+
threshold?: number;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export declare const DEFAULT_FIT_THRESHOLD = 0.5;
|
|
44
|
+
export declare function parseIcp(raw: string): Icp;
|
|
45
|
+
/** Explorium /v1/prospects filters from the ICP. */
|
|
46
|
+
export declare function icpToExploriumFilters(icp: Icp): Record<string, {
|
|
47
|
+
values?: string[];
|
|
48
|
+
value?: boolean;
|
|
49
|
+
}>;
|
|
50
|
+
/**
|
|
51
|
+
* pipe0 Crustdata people-search config.filters from the ICP. `current_job_titles`
|
|
52
|
+
* matches real LinkedIn title strings (case-sensitive), so keywords are Title
|
|
53
|
+
* Cased. Seniority + industry are mapped to Crustdata's controlled vocab via the
|
|
54
|
+
* tables above. NOTE: the exact pipe0→Crustdata value set could not be re-run
|
|
55
|
+
* live (pipe0 credits were exhausted) — validate when credits refill; fit
|
|
56
|
+
* scoring is the safety net for persona precision regardless.
|
|
57
|
+
*/
|
|
58
|
+
export declare function icpToCrustdataFilters(icp: Icp): Record<string, unknown>;
|
|
59
|
+
export type IcpFit = {
|
|
60
|
+
score: number;
|
|
61
|
+
reasons: string[];
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Score a prospect's PERSONA fit 0..1. Title-keyword match is the strongest
|
|
65
|
+
* signal (it's what defines the buyer); job level and department add to it.
|
|
66
|
+
* Firmographics aren't re-scored here — discovery already filtered on them.
|
|
67
|
+
*/
|
|
68
|
+
export declare function scoreProspectAgainstIcp(prospect: {
|
|
69
|
+
jobTitle?: string;
|
|
70
|
+
jobLevel?: string;
|
|
71
|
+
jobDepartment?: string;
|
|
72
|
+
}, icp: Icp): IcpFit;
|
|
73
|
+
export declare function fitThreshold(icp: Icp): number;
|
|
74
|
+
export type IcpInterviewQuestion = {
|
|
75
|
+
id: keyof FlatIcpAnswers;
|
|
76
|
+
header: string;
|
|
77
|
+
question: string;
|
|
78
|
+
multiSelect: boolean;
|
|
79
|
+
options: {
|
|
80
|
+
label: string;
|
|
81
|
+
value: string | string[];
|
|
82
|
+
description: string;
|
|
83
|
+
}[];
|
|
84
|
+
};
|
|
85
|
+
/** Flattened answer keys the interview collects (assembled into an Icp). */
|
|
86
|
+
export type FlatIcpAnswers = {
|
|
87
|
+
industries: string[];
|
|
88
|
+
employeeBands: string[];
|
|
89
|
+
jobLevels: string[];
|
|
90
|
+
departments: string[];
|
|
91
|
+
titleKeywords: string[];
|
|
92
|
+
geos: string[];
|
|
93
|
+
};
|
|
94
|
+
export declare const INTERVIEW_SPEC: IcpInterviewQuestion[];
|
|
95
|
+
/** Assemble an Icp from flattened interview answers. */
|
|
96
|
+
export declare function icpFromAnswers(name: string, answers: FlatIcpAnswers): Icp;
|