@sonnechasser/ntrp 0.3.2 → 0.3.5

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.
@@ -5,6 +5,14 @@ var __esm = (fn, res) => function __init() {
5
5
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
6
  };
7
7
 
8
+ // src/ui/spinner.ts
9
+ import ora from "ora";
10
+ var init_spinner = __esm({
11
+ "src/ui/spinner.ts"() {
12
+ "use strict";
13
+ }
14
+ });
15
+
8
16
  // src/ai/llm/thread-compat.ts
9
17
  var init_thread_compat = __esm({
10
18
  "src/ai/llm/thread-compat.ts"() {
@@ -26,6 +34,65 @@ var init_formatters = __esm({
26
34
  }
27
35
  });
28
36
 
37
+ // src/config/store.ts
38
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
39
+ import { homedir } from "os";
40
+ import { join, resolve } from "path";
41
+ function ntrpHome() {
42
+ return NTRP_DIR;
43
+ }
44
+ function getMemoryDir() {
45
+ const dir = join(NTRP_DIR, "memory");
46
+ if (!existsSync(dir)) {
47
+ mkdirSync(dir, { recursive: true });
48
+ }
49
+ return dir;
50
+ }
51
+ var NTRP_DIR, CONFIG_PATH;
52
+ var init_store = __esm({
53
+ "src/config/store.ts"() {
54
+ "use strict";
55
+ NTRP_DIR = process.env.NTRP_HOME ? resolve(process.env.NTRP_HOME) : join(homedir(), ".ntrp");
56
+ CONFIG_PATH = join(NTRP_DIR, "config.json");
57
+ }
58
+ });
59
+
60
+ // src/output/path-safety.ts
61
+ import { homedir as homedir2 } from "os";
62
+ import { resolve as resolve2, sep } from "path";
63
+ var NTRP_HOME;
64
+ var init_path_safety = __esm({
65
+ "src/output/path-safety.ts"() {
66
+ "use strict";
67
+ init_store();
68
+ NTRP_HOME = ntrpHome();
69
+ }
70
+ });
71
+
72
+ // src/services/exports-registry.ts
73
+ import {
74
+ appendFileSync,
75
+ copyFileSync,
76
+ cpSync,
77
+ existsSync as existsSync2,
78
+ mkdirSync as mkdirSync2,
79
+ readFileSync as readFileSync2,
80
+ readdirSync,
81
+ renameSync,
82
+ rmSync,
83
+ statSync,
84
+ writeFileSync as writeFileSync2
85
+ } from "fs";
86
+ import { basename, dirname, join as join2, resolve as resolve3, sep as sep2 } from "path";
87
+ import { randomUUID } from "crypto";
88
+ var init_exports_registry = __esm({
89
+ "src/services/exports-registry.ts"() {
90
+ "use strict";
91
+ init_store();
92
+ init_path_safety();
93
+ }
94
+ });
95
+
29
96
  // src/services/terminal-capture.ts
30
97
  var init_terminal_capture = __esm({
31
98
  "src/services/terminal-capture.ts"() {
@@ -34,19 +101,21 @@ var init_terminal_capture = __esm({
34
101
  });
35
102
 
36
103
  // src/services/context-doc.ts
37
- import { writeFileSync } from "fs";
104
+ import { writeFileSync as writeFileSync3 } from "fs";
38
105
  var init_context_doc = __esm({
39
106
  "src/services/context-doc.ts"() {
40
107
  "use strict";
41
108
  init_context2();
42
109
  init_formatters();
110
+ init_store();
111
+ init_exports_registry();
43
112
  init_terminal_capture();
44
113
  }
45
114
  });
46
115
 
47
116
  // src/services/transcript.ts
48
- import { existsSync, readFileSync, writeFileSync as writeFileSync2, rmSync } from "fs";
49
- import { join } from "path";
117
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4, rmSync as rmSync2 } from "fs";
118
+ import { join as join3 } from "path";
50
119
  var init_transcript = __esm({
51
120
  "src/services/transcript.ts"() {
52
121
  "use strict";
@@ -56,12 +125,14 @@ var init_transcript = __esm({
56
125
  });
57
126
 
58
127
  // src/cli/context.ts
59
- import { basename, join as join2, resolve, sep } from "path";
60
- import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3, readFileSync as readFileSync2, readdirSync, statSync, rmSync as rmSync2 } from "fs";
61
- import { homedir } from "os";
62
- import { randomUUID } from "crypto";
128
+ import { basename as basename2, join as join4, resolve as resolve4, sep as sep3 } from "path";
129
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, rmSync as rmSync3 } from "fs";
130
+ import { homedir as homedir3 } from "os";
131
+ import { randomUUID as randomUUID2 } from "crypto";
63
132
  function isAnalysisReady(ctx) {
64
- if (ctx.stage !== "analyzed" || ctx.analysis.completed.length === 0) return false;
133
+ if (ctx.stage !== "analyzed" && ctx.stage !== "delivered" || ctx.analysis.completed.length === 0) {
134
+ return false;
135
+ }
65
136
  if (!ctx.dataset) return false;
66
137
  const counts = ctx.dataset.counts ?? {};
67
138
  return Object.values(counts).some((n) => n > 0);
@@ -81,50 +152,27 @@ var init_context2 = __esm({
81
152
  }
82
153
  });
83
154
 
84
- // src/config/store.ts
85
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync4, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
86
- import { homedir as homedir2 } from "os";
87
- import { join as join3, resolve as resolve2 } from "path";
88
- function ntrpHome() {
89
- return NTRP_DIR;
90
- }
91
- function getMemoryDir() {
92
- const dir = join3(NTRP_DIR, "memory");
93
- if (!existsSync3(dir)) {
94
- mkdirSync2(dir, { recursive: true });
95
- }
96
- return dir;
97
- }
98
- var NTRP_DIR, CONFIG_PATH;
99
- var init_store = __esm({
100
- "src/config/store.ts"() {
101
- "use strict";
102
- NTRP_DIR = process.env.NTRP_HOME ? resolve2(process.env.NTRP_HOME) : join3(homedir2(), ".ntrp");
103
- CONFIG_PATH = join3(NTRP_DIR, "config.json");
104
- }
105
- });
106
-
107
155
  // src/config/profile.ts
108
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
109
- import { join as join4 } from "path";
156
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync6, existsSync as existsSync5, mkdirSync as mkdirSync4 } from "fs";
157
+ import { join as join5 } from "path";
110
158
  var NTRP_DIR2, PROFILE_PATH;
111
159
  var init_profile = __esm({
112
160
  "src/config/profile.ts"() {
113
161
  "use strict";
114
162
  init_store();
115
163
  NTRP_DIR2 = ntrpHome();
116
- PROFILE_PATH = join4(NTRP_DIR2, "profile.json");
164
+ PROFILE_PATH = join5(NTRP_DIR2, "profile.json");
117
165
  }
118
166
  });
119
167
 
120
168
  // src/db/connection.ts
121
- import { dirname, join as join5, resolve as resolve3 } from "path";
169
+ import { dirname as dirname2, join as join6, resolve as resolve5 } from "path";
122
170
  var NTRP_DIR3, DEFAULT_DB_PATH, DB_PATH_PINNED;
123
171
  var init_connection = __esm({
124
172
  "src/db/connection.ts"() {
125
173
  "use strict";
126
- NTRP_DIR3 = process.env.NTRP_HOME ? resolve3(process.env.NTRP_HOME) : join5(process.env.HOME ?? "", ".ntrp");
127
- DEFAULT_DB_PATH = process.env.NTRP_DB_PATH ? resolve3(process.env.NTRP_DB_PATH) : join5(NTRP_DIR3, "ntrp.duckdb");
174
+ NTRP_DIR3 = process.env.NTRP_HOME ? resolve5(process.env.NTRP_HOME) : join6(process.env.HOME ?? "", ".ntrp");
175
+ DEFAULT_DB_PATH = process.env.NTRP_DB_PATH ? resolve5(process.env.NTRP_DB_PATH) : join6(NTRP_DIR3, "ntrp.duckdb");
128
176
  DB_PATH_PINNED = !!process.env.NTRP_DB_PATH;
129
177
  }
130
178
  });
@@ -141,10 +189,37 @@ var init_queries = __esm({
141
189
 
142
190
  // src/ui/theme.ts
143
191
  import chalk from "chalk";
192
+ var STATUS, TOKENS, BADGE_TONE_COLORS;
144
193
  var init_theme = __esm({
145
194
  "src/ui/theme.ts"() {
146
195
  "use strict";
147
196
  init_formatters();
197
+ STATUS = {
198
+ green: "#22c55e",
199
+ yellow: "#eab308",
200
+ red: "#ef4444",
201
+ neutral: "#64748b"
202
+ };
203
+ TOKENS = {
204
+ accent: "#14b8a6",
205
+ accentBright: "#2dd4bf",
206
+ border: "#334155",
207
+ borderMuted: "#1e293b",
208
+ dim: "#64748b",
209
+ text: "#e2e8f0",
210
+ info: "#3b82f6",
211
+ ...STATUS,
212
+ success: STATUS.green,
213
+ warning: STATUS.yellow,
214
+ error: STATUS.red
215
+ };
216
+ BADGE_TONE_COLORS = {
217
+ success: TOKENS.success,
218
+ warning: TOKENS.warning,
219
+ error: TOKENS.error,
220
+ info: TOKENS.info,
221
+ accent: TOKENS.accent
222
+ };
148
223
  }
149
224
  });
150
225
 
@@ -159,6 +234,879 @@ var init_session_analysis = __esm({
159
234
  }
160
235
  });
161
236
 
237
+ // src/baselines/metrics-benchmarks.ts
238
+ function motionBenchmarkLabel(motion) {
239
+ return MOTION_LABELS[motion ?? "mid_market"];
240
+ }
241
+ var METRICS_BENCHMARKS, MOTION_LABELS;
242
+ var init_metrics_benchmarks = __esm({
243
+ "src/baselines/metrics-benchmarks.ts"() {
244
+ "use strict";
245
+ METRICS_BENCHMARKS = {
246
+ plg: {
247
+ nrr: { green: 110, yellow: 100 },
248
+ grr: { green: 85, yellow: 75 },
249
+ win_rate: { green: 25, yellow: 15 },
250
+ pipeline_coverage: { green: 4, yellow: 2.5 },
251
+ magic_number: { green: 1, yellow: 0.75 },
252
+ payback_months: { green: 12, yellow: 18 }
253
+ },
254
+ smb_velocity: {
255
+ nrr: { green: 105, yellow: 95 },
256
+ grr: { green: 88, yellow: 78 },
257
+ win_rate: { green: 22, yellow: 12 },
258
+ pipeline_coverage: { green: 3.5, yellow: 2 },
259
+ magic_number: { green: 0.9, yellow: 0.6 },
260
+ payback_months: { green: 14, yellow: 20 }
261
+ },
262
+ mid_market: {
263
+ nrr: { green: 100, yellow: 90 },
264
+ grr: { green: 90, yellow: 80 },
265
+ win_rate: { green: 20, yellow: 12 },
266
+ pipeline_coverage: { green: 3, yellow: 2 },
267
+ magic_number: { green: 0.75, yellow: 0.5 },
268
+ payback_months: { green: 16, yellow: 22 }
269
+ },
270
+ enterprise: {
271
+ nrr: { green: 95, yellow: 85 },
272
+ grr: { green: 92, yellow: 82 },
273
+ win_rate: { green: 15, yellow: 8 },
274
+ pipeline_coverage: { green: 2.5, yellow: 1.5 },
275
+ magic_number: { green: 0.6, yellow: 0.4 },
276
+ payback_months: { green: 18, yellow: 24 }
277
+ }
278
+ };
279
+ MOTION_LABELS = {
280
+ plg: "PLG",
281
+ smb_velocity: "SMB Velocity",
282
+ mid_market: "Mid-Market",
283
+ enterprise: "Enterprise"
284
+ };
285
+ }
286
+ });
287
+
288
+ // src/data/metric-definitions.ts
289
+ function pctBand(metric, motion) {
290
+ const m = motion ?? "mid_market";
291
+ const t = METRICS_BENCHMARKS[m][metric];
292
+ return `${motionBenchmarkLabel(m)} green \u2265${t.green}${metric === "pipeline_coverage" ? "x" : "%"}, yellow \u2265${t.yellow}${metric === "pipeline_coverage" ? "x" : "%"}`;
293
+ }
294
+ function monthsBand(motion) {
295
+ const m = motion ?? "mid_market";
296
+ const t = METRICS_BENCHMARKS[m].payback_months;
297
+ return `${motionBenchmarkLabel(m)} green \u2264${t.green}mo, yellow \u2264${t.yellow}mo`;
298
+ }
299
+ function magicBand(motion) {
300
+ const m = motion ?? "mid_market";
301
+ const t = METRICS_BENCHMARKS[m].magic_number;
302
+ return `${motionBenchmarkLabel(m)} green \u2265${t.green}, yellow \u2265${t.yellow}`;
303
+ }
304
+ var VITALS, SAAS, METRIC_DEFINITIONS, BY_ID, ALIAS_INDEX, SAAS_METRIC_IDS;
305
+ var init_metric_definitions = __esm({
306
+ "src/data/metric-definitions.ts"() {
307
+ "use strict";
308
+ init_metrics_benchmarks();
309
+ VITALS = [
310
+ {
311
+ id: "freshness",
312
+ kind: "vital",
313
+ label: "Freshness",
314
+ group: "Vital Signs",
315
+ tagline: "Is your CRM telling the truth about what's alive?",
316
+ how_computed: "Weighted average of people, organizations, and opportunities with recent activity (and open opps not past-due). Defaults: people/orgs 90-day window, opps 30-day window; weights 35/30/35.",
317
+ formula_lines: [
318
+ "freshness = people%\xD70.35 + orgs%\xD70.30 + opps%\xD70.35",
319
+ "people/orgs fresh if activity within 90d",
320
+ "opps fresh if activity within 30d AND not past-due"
321
+ ],
322
+ meaning: 'Board question: "how much of this pipeline is real vs fiction?" Dollar value = sum of amount on stale opportunities \u2014 pipeline at risk.',
323
+ expert_read: "Cut by owner and by stage first \u2014 freshness reds concentrate on people or process, rarely evenly. In a long-cycle enterprise motion 30 quiet days can be normal cadence; in a velocity motion it's a dead deal. A sudden cliff usually means a broken integration or a departed rep, not gradual decay. False positive to check: bulk-imported records nobody has touched yet.",
324
+ deepdive: [
325
+ "Status: green \u226580, yellow \u226560, red below 60 (motion presets can shift windows).",
326
+ 'Dollar translation: sum of amount on stale open opportunities \u2192 "pipeline at risk".',
327
+ "Layer 1 of the gating stack \u2014 a red here bounds what you can trust downstream.",
328
+ "Trigger play: Clean Dead Pipeline (clean-dead-pipeline) when score < 60.",
329
+ "Levers: stale-deal alert at N quiet days, weekly hygiene scrub, enrichment refresh on quiet records, signal-triggered reactivation for paid-for dormant accounts."
330
+ ],
331
+ visual: {
332
+ kind: "bars",
333
+ caption: "Exemplar component mix (higher = fresher)",
334
+ bars: [
335
+ { label: "People", value: 72, tone: "yellow" },
336
+ { label: "Organizations", value: 81, tone: "green" },
337
+ { label: "Opportunities", value: 44, tone: "red" }
338
+ ]
339
+ },
340
+ play_id: "clean-dead-pipeline",
341
+ dollar_label: "pipeline at risk",
342
+ audience: {
343
+ board: "Freshness answers whether the pipeline number is real. Low freshness means forecast risk \u2014 stale deals inflate coverage and hide the true gap.",
344
+ ops: "Score = weighted recency across people/orgs/opps. Cut by owner and stage; install a stale-deal alert and weekly scrub. Play: Clean Dead Pipeline."
345
+ },
346
+ aliases: ["data freshness", "stale", "zombie deals", "crm freshness"]
347
+ },
348
+ {
349
+ id: "flow_rate",
350
+ kind: "vital",
351
+ label: "Flow Rate",
352
+ group: "Vital Signs",
353
+ tagline: "How fast do deals actually move \u2014 and where do they die?",
354
+ how_computed: "Base score from average open-deal age vs max_days, then a penalty (up to \u221220) for the share of stuck deals (no update beyond stuck_days, or past-due close). Status is driven by average open age, not the score alone.",
355
+ formula_lines: [
356
+ "base = 100 \xD7 (1 \u2212 avgOpenAge / max_days)",
357
+ "score = base \u2212 stuckSharePenalty (\u226420)",
358
+ "stuck = no update > stuck_days OR past-due close"
359
+ ],
360
+ meaning: 'Board question: "is next quarter slipping because deals are stuck?" Dollar value = amount stuck in pipeline.',
361
+ expert_read: "Cut by stage-age, not just deal-age \u2014 find the stage where deals go to die (usually one). Compare stuck-deal age to this company's own median cycle, not a generic norm. Stuck + past-due close dates together signal happy-ears forecasting, a credibility problem before it's a revenue problem.",
362
+ deepdive: [
363
+ "Status from avg open age: \u226445d green, \u226490d yellow, else red (defaults; max_days 120, stuck_days 60).",
364
+ 'Dollar translation: sum of amount on stuck deals \u2192 "stuck in pipeline".',
365
+ "Layer 2 of the gating stack (with Drop Rate).",
366
+ "Trigger play: Unstick the Pipeline (unstick-pipeline) when score is weak.",
367
+ "Levers: stage-age report, past-due close cleanup, progression plans on stuck deals, forecast hygiene on happy-ears dates."
368
+ ],
369
+ visual: {
370
+ kind: "funnel",
371
+ caption: "Exemplar stage ages \u2014 find the stage where deals go to die",
372
+ funnel: [
373
+ { label: "Discovery", widthPct: 100 },
374
+ { label: "Qualify", widthPct: 78 },
375
+ { label: "Propose", widthPct: 55 },
376
+ { label: "Negotiate", widthPct: 22 },
377
+ { label: "Closed", widthPct: 12 }
378
+ ]
379
+ },
380
+ play_id: "unstick-pipeline",
381
+ dollar_label: "stuck in pipeline",
382
+ audience: {
383
+ board: "Flow Rate is velocity risk. Stuck pipeline with past-due closes is a credibility problem for the forecast before it is a revenue miss.",
384
+ ops: "Find the stage with collapsing advancement and age. Clear past-due closes, write progression plans on stuck deals. Play: Unstick the Pipeline."
385
+ },
386
+ aliases: ["flow rate", "deal velocity", "stuck deals", "stuck pipeline"]
387
+ },
388
+ {
389
+ id: "drop_rate",
390
+ kind: "vital",
391
+ label: "Drop Rate",
392
+ group: "Vital Signs",
393
+ tagline: "Where do leads vanish between systems?",
394
+ how_computed: "Blend of cross-system retention (marketing people also present in sales) and opportunity retention (open opps not abandoned). Defaults weight cross-system 60% / opp retention 40%. Abandoned = open opps with no activity in 30 days.",
395
+ formula_lines: [
396
+ "score = crossSystemRetention\xD70.6 + oppRetention\xD70.4",
397
+ "cross-system = marketing people also in sales CRM",
398
+ "abandoned = open opps with no activity in 30d"
399
+ ],
400
+ meaning: 'Board question: "how much pipeline are we paying for and never working?" Dollar value = droppedCount \xD7 conversionRate \xD7 avgDealSize \u2014 est. lost at handoff.',
401
+ expert_read: "This is almost always a systems failure \u2014 routing rules, unassigned territories, dead rep queues, or a sync gap between marketing and CRM \u2014 not lazy reps. First cut by lead source; the leak usually concentrates in one or two sources. The cheapest pipeline this business can buy is the leads it already paid for.",
402
+ deepdive: [
403
+ "Status: green \u226580, yellow \u226560, red below 60.",
404
+ 'Dollar translation: dropped \xD7 conversion \xD7 avg deal (fallback: drop% \xD7 open pipeline) \u2192 "est. lost at handoff".',
405
+ "Layer 2 of the gating stack (with Flow Rate).",
406
+ "Trigger play: Fix the Handoff Gap (fix-handoff-gap) when drop is high.",
407
+ "Levers: source-level handoff audit, routing + sync repair, time-to-first-touch SLA, weekly marketing-only-leads report."
408
+ ],
409
+ visual: {
410
+ kind: "funnel",
411
+ caption: "Exemplar handoff funnel \u2014 the leak is usually one or two sources",
412
+ funnel: [
413
+ { label: "Marketing leads", widthPct: 100 },
414
+ { label: "In sales CRM", widthPct: 62 },
415
+ { label: "Assigned + touched", widthPct: 41 },
416
+ { label: "Active opportunities", widthPct: 28 }
417
+ ]
418
+ },
419
+ play_id: "fix-handoff-gap",
420
+ dollar_label: "est. lost at handoff",
421
+ audience: {
422
+ board: "Drop Rate prices the handoff leak \u2014 budget already spent on leads that never reach a working rep. Usually a systems failure, not a people failure.",
423
+ ops: "Audit by source, fix routing/sync/dead queues, instrument time-to-first-touch. Play: Fix the Handoff Gap."
424
+ },
425
+ aliases: ["drop rate", "handoff", "handoff gap", "lead leak", "marketing sales handoff"]
426
+ },
427
+ {
428
+ id: "signal_to_noise",
429
+ kind: "vital",
430
+ label: "Signal:Noise",
431
+ group: "Vital Signs",
432
+ tagline: "How much activity is aimed at deals that can still close?",
433
+ how_computed: "Over a 90-day lookback: (signal activities / all activities) \xD7 100. Signal = activity linked to an open opportunity, a pipeline person, or a pipeline organization.",
434
+ formula_lines: [
435
+ "score = (signalCount / activityCount) \xD7 100",
436
+ "signal = linked to open opp / pipeline person / pipeline org",
437
+ "lookback = trailing 90 days"
438
+ ],
439
+ meaning: 'Board question: "are we burning capacity on dead water?" Dollar value = noiseCount \xD7 hours_per_activity \xD7 rep_hourly_cost \u2014 misdirected effort.',
440
+ expert_read: "Cut by rep and by account status \u2014 noise usually means reps fishing in the pond they can see (dead accounts they know) because targeting and account lists are stale. Persistent noise is a coverage-model problem, not a coaching problem. Check whether activity is logged against closed or unlinked records \u2014 often a hygiene artifact.",
441
+ deepdive: [
442
+ "Status: green \u226565, yellow \u226540, red below 40.",
443
+ "Dollar defaults: 0.25 hours/activity \xD7 $75/hr (config: hours_per_activity, rep_hourly_cost).",
444
+ "Layer 3 of the gating stack \u2014 trust Freshness / Flow / Drop before reading activity efficiency.",
445
+ "Trigger play: Retarget Misdirected Effort (retarget-effort) when score is low.",
446
+ "Levers: refresh account lists, signal-based targeting, stop logging against closed/unlinked records, coverage-model redesign."
447
+ ],
448
+ visual: {
449
+ kind: "split",
450
+ caption: "Exemplar activity mix \u2014 signal vs noise",
451
+ bars: [
452
+ { label: "Signal", value: 38, tone: "green" },
453
+ { label: "Noise", value: 62, tone: "red" }
454
+ ]
455
+ },
456
+ play_id: "retarget-effort",
457
+ dollar_label: "misdirected effort",
458
+ audience: {
459
+ board: "Signal:Noise prices wasted capacity. Persistent noise is usually a coverage-model problem, not a coaching problem \u2014 reps fish in dead ponds they already know.",
460
+ ops: "Score = % of activities linked to live pipeline. Cut by rep and account status; refresh targeting. Play: Retarget Misdirected Effort."
461
+ },
462
+ aliases: ["signal to noise", "signal:noise", "s/n", "activity efficiency", "noise"]
463
+ },
464
+ {
465
+ id: "thread_depth",
466
+ kind: "vital",
467
+ label: "Thread Depth",
468
+ group: "Vital Signs",
469
+ tagline: "How fragile is the pipeline if one champion goes dark?",
470
+ how_computed: "Percent of open deals with at least multi_thread_threshold (default 2) distinct people active in the last 90 days (opp-direct contacts + same-org activity).",
471
+ formula_lines: [
472
+ "score = % open deals with \u22652 active people (90d)",
473
+ "people counted via opp contacts + same-org activity",
474
+ "threshold configurable (default 2)"
475
+ ],
476
+ meaning: 'Board question: "how much revenue dies if one contact changes jobs?" Dollar value = sum of amount on single-threaded deals.',
477
+ expert_read: "Weight by deal size \u2014 one single-threaded mega-deal outweighs ten small ones. Single-threading late in the cycle is far more dangerous than early. In enterprise motions, thread depth is a leading indicator of slipped quarters: champions change jobs, and there's no second door in.",
478
+ deepdive: [
479
+ "Status: green \u226565, yellow \u226540, red below 40.",
480
+ 'Dollar translation: sum of amount on single-threaded deals \u2192 "single-threaded".',
481
+ "Layer 4 of the gating stack \u2014 read last, after the upstream vitals.",
482
+ "Trigger play: Multi-Thread Your Deals (multi-thread-deals) when depth is low.",
483
+ "Levers: buying-committee map, warm internal referral first, CRM contact roles, mid-stage single-thread alerts, champion job-change signals."
484
+ ],
485
+ visual: {
486
+ kind: "bars",
487
+ caption: "Exemplar \u2014 multi-threaded vs single-threaded open deals",
488
+ bars: [
489
+ { label: "Multi-threaded", value: 34, tone: "green" },
490
+ { label: "Single-threaded", value: 66, tone: "red" }
491
+ ]
492
+ },
493
+ play_id: "multi-thread-deals",
494
+ dollar_label: "single-threaded",
495
+ audience: {
496
+ board: "Thread Depth is resilience risk. One single-threaded mega-deal outweighs ten small ones \u2014 late-cycle single-threading is a leading indicator of slipped quarters.",
497
+ ops: "Score = % of open deals with \u22652 active contacts in 90d. Map the buying committee; alert on mid-stage singles. Play: Multi-Thread Your Deals."
498
+ },
499
+ aliases: ["thread depth", "multithreading", "multi-thread", "single-threaded", "buying committee"]
500
+ }
501
+ ];
502
+ SAAS = [
503
+ // —— Revenue ——
504
+ {
505
+ id: "arr",
506
+ kind: "saas",
507
+ label: "ARR",
508
+ group: "Revenue",
509
+ tagline: "How big is the revenue engine \u2014 and from where?",
510
+ how_computed: "Sum of amount on closed-won opportunities in the dataset (pipeline-inferred ARR when a pure subscription ledger is unavailable).",
511
+ formula_lines: [
512
+ "ARR \u2248 \u03A3 amount on closed-won opportunities",
513
+ "New + Expansion = growth \xB7 Churned + Contraction = leakage"
514
+ ],
515
+ meaning: 'Board question: "how fast are we growing, and from where?" Always decompose growth into new vs expansion \u2014 the mix is the story.',
516
+ expert_read: "Always decompose growth into new vs expansion \u2014 the mix is the story. Instrument trust: prefer this company's own trailing history over any external prior; a number below its reliability gate is a hypothesis, not a fact.",
517
+ deepdive: [
518
+ "Companion metrics: New ARR, Expansion ARR, Churned ARR, Contraction ARR.",
519
+ "Estimation method may be ledger, pipeline_inferred, or snapshot \u2014 read confidence + reliability_gate.",
520
+ "Cross-check with Freshness before trusting ARR growth stories built on zombie deals."
521
+ ],
522
+ visual: {
523
+ kind: "waterfall",
524
+ caption: "Exemplar ARR walk \u2014 growth vs leakage",
525
+ waterfall: [
526
+ { label: "Starting", delta: 100, cumulative: 100 },
527
+ { label: "+ New", delta: 18, cumulative: 118 },
528
+ { label: "+ Expansion", delta: 12, cumulative: 130 },
529
+ { label: "\u2212 Contraction", delta: -4, cumulative: 126 },
530
+ { label: "\u2212 Churned", delta: -8, cumulative: 118 }
531
+ ]
532
+ },
533
+ audience: {
534
+ board: "ARR is the size of the engine. The story is the mix \u2014 new vs expansion growth, and how much leakage (churn + contraction) ate it.",
535
+ ops: "Computed as \u03A3 closed-won amounts (pipeline-inferred when no ledger). Decompose into new / expansion / churned / contraction before briefing anyone."
536
+ },
537
+ aliases: ["annual recurring revenue", "revenue"]
538
+ },
539
+ {
540
+ id: "new_arr",
541
+ kind: "saas",
542
+ label: "New ARR",
543
+ group: "Revenue",
544
+ tagline: "How much growth came from brand-new customers?",
545
+ how_computed: "Closed-won tagged New Business, or first closed-won deal per organization when tags are missing.",
546
+ formula_lines: [
547
+ "New ARR = \u03A3 closed-won tagged New Business",
548
+ "fallback: first closed-won deal per organization"
549
+ ],
550
+ meaning: 'Board question: "is growth coming from the top of funnel, or are we farming the base?"',
551
+ expert_read: "Rising New ARR with falling Expansion usually means land-and-expand is underpowered \u2014 packaging or CS motion, not just sales capacity.",
552
+ deepdive: [
553
+ "Pair with Expansion ARR \u2014 the mix tells you which motion is carrying growth.",
554
+ "Tag quality matters: untagged deals fall into the first-deal-per-org heuristic."
555
+ ],
556
+ visual: {
557
+ kind: "bars",
558
+ caption: "Exemplar growth mix",
559
+ bars: [
560
+ { label: "New ARR", value: 60, tone: "accent" },
561
+ { label: "Expansion ARR", value: 40, tone: "green" }
562
+ ]
563
+ },
564
+ audience: {
565
+ board: "New ARR is net-new logos. Read it next to Expansion \u2014 a healthy mix beats a one-sided engine.",
566
+ ops: "Prefer CRM New Business tags; otherwise first closed-won per org. Watch tag hygiene."
567
+ },
568
+ aliases: ["new business arr", "new logo arr"]
569
+ },
570
+ {
571
+ id: "expansion_arr",
572
+ kind: "saas",
573
+ label: "Expansion ARR",
574
+ group: "Revenue",
575
+ tagline: "How much are existing customers buying more?",
576
+ how_computed: "Closed-won tagged Expansion, or later closed-won deals per organization after the first win.",
577
+ formula_lines: [
578
+ "Expansion ARR = \u03A3 closed-won tagged Expansion",
579
+ "fallback: later closed-won deals per organization"
580
+ ],
581
+ meaning: 'Board question: "is the installed base compounding?"',
582
+ expert_read: "Expansion is the cheapest growth. Weak Expansion with strong New ARR is a land-only motion \u2014 packaging, CS capacity, or product attach is usually the lever.",
583
+ deepdive: [
584
+ "Feeds NRR as the upside term.",
585
+ "Compare to Contraction \u2014 net expansion = expansion \u2212 contraction."
586
+ ],
587
+ visual: {
588
+ kind: "bars",
589
+ caption: "Exemplar \u2014 expansion vs contraction",
590
+ bars: [
591
+ { label: "Expansion", value: 70, tone: "green" },
592
+ { label: "Contraction", value: 25, tone: "yellow" }
593
+ ]
594
+ },
595
+ audience: {
596
+ board: "Expansion ARR is installed-base compounding \u2014 the cheapest growth when it works.",
597
+ ops: "Tagged Expansion or subsequent wins per org. Pair with Contraction before celebrating net expansion."
598
+ },
599
+ aliases: ["upsell", "upsell arr", "cross-sell"]
600
+ },
601
+ {
602
+ id: "churned_arr",
603
+ kind: "saas",
604
+ label: "Churned ARR",
605
+ group: "Revenue",
606
+ tagline: "How much revenue walked out the door?",
607
+ how_computed: "Organizations with historical wins, no win in the trailing 12 months, and no active open opportunity \u2014 sum of their historical closed-won amounts.",
608
+ formula_lines: [
609
+ "Churned ARR = \u03A3 historical wins for orgs with",
610
+ " no win in trailing 12mo AND no active open opp"
611
+ ],
612
+ meaning: `Board question: "how leaky is the bucket before expansion papers over it?" (with Contraction, this is GRR's downside).`,
613
+ expert_read: "Pipeline-inferred churn is a hypothesis \u2014 confirm with billing status when available. A spike often clusters in one segment or cohort.",
614
+ deepdive: [
615
+ "Feeds GRR and NRR as the churn term.",
616
+ "Cut by segment / motion before treating it as a company-wide PMF problem."
617
+ ],
618
+ visual: {
619
+ kind: "bars",
620
+ caption: "Exemplar leakage mix",
621
+ bars: [
622
+ { label: "Churned", value: 55, tone: "red" },
623
+ { label: "Contraction", value: 30, tone: "yellow" }
624
+ ]
625
+ },
626
+ audience: {
627
+ board: "Churned ARR is full logo loss. With Contraction it sets the floor of the business (GRR).",
628
+ ops: "Heuristic: historical winners with no trailing-12 win and no open opp. Validate against billing when you can."
629
+ },
630
+ aliases: ["churn", "logo churn", "churned revenue"]
631
+ },
632
+ {
633
+ id: "contraction_arr",
634
+ kind: "saas",
635
+ label: "Contraction ARR",
636
+ group: "Revenue",
637
+ tagline: "How much did existing customers buy less?",
638
+ how_computed: "Organizations with \u22652 wins where the latest amount is less than the prior \u2014 sum of the negative deltas.",
639
+ formula_lines: [
640
+ "Contraction = \u03A3 (prior \u2212 latest) where latest < prior",
641
+ "requires \u22652 closed-won deals per organization"
642
+ ],
643
+ meaning: 'Board question: "are we quietly shrinking inside the base while logos stay?"',
644
+ expert_read: "Contraction is often packaging, seat-reduction, or downgrade \u2014 different owner than logo churn. Same NRR can be a churn problem or a no-expansion problem.",
645
+ deepdive: [
646
+ "Feeds GRR and NRR.",
647
+ "Needs multi-deal history per org \u2014 thin history understates contraction."
648
+ ],
649
+ visual: {
650
+ kind: "waterfall",
651
+ caption: "Exemplar \u2014 contraction digs into the base",
652
+ waterfall: [
653
+ { label: "Prior", delta: 100, cumulative: 100 },
654
+ { label: "Latest", delta: -18, cumulative: 82 }
655
+ ]
656
+ },
657
+ audience: {
658
+ board: "Contraction is silent shrink inside retained logos \u2014 often packaging or seats, not a cancelled contract.",
659
+ ops: "Requires \u22652 wins per org with a down-round. Pair with Expansion for net expansion."
660
+ },
661
+ aliases: ["downgrade", "seat reduction", "contraction"]
662
+ },
663
+ // —— Retention ——
664
+ {
665
+ id: "nrr",
666
+ kind: "saas",
667
+ label: "Net Revenue Retention",
668
+ group: "Retention",
669
+ tagline: "Would this business grow if sales stopped selling?",
670
+ how_computed: "startingArr = ARR + Churned + Contraction \u2212 Expansion; NRR = ((starting \u2212 Churned \u2212 Contraction + Expansion) / starting) \xD7 100.",
671
+ formula_lines: [
672
+ "starting = ARR + churned + contraction \u2212 expansion",
673
+ "NRR = (starting \u2212 churned \u2212 contraction + expansion) / starting \xD7 100",
674
+ "NRR = 100% + expansion% \u2212 contraction% \u2212 churn%"
675
+ ],
676
+ meaning: 'Board question: "would this business grow if sales stopped selling?" >100% means growing from existing customers.',
677
+ expert_read: "Decompose before judging: the same 95% can be a churn problem (product/PMF) or a no-expansion problem (packaging/motion) with different owners. Priors by segment: ~97% SMB, ~108% mid-market, ~118% enterprise medians; 110%+ is a strong signal at any stage.",
678
+ deepdive: [
679
+ "Always show the waterfall: +expansion \u2212contraction \u2212churn.",
680
+ "GRR is the floor; NRR adds expansion on top.",
681
+ "On pipeline-only data, treat as a hypothesis \u2014 check confidence / reliability_gate."
682
+ ],
683
+ visual: {
684
+ kind: "waterfall",
685
+ caption: "Exemplar NRR walk from 100%",
686
+ waterfall: [
687
+ { label: "100%", delta: 100, cumulative: 100 },
688
+ { label: "+ Expansion", delta: 14, cumulative: 114 },
689
+ { label: "\u2212 Contraction", delta: -4, cumulative: 110 },
690
+ { label: "\u2212 Churn", delta: -6, cumulative: 104 }
691
+ ]
692
+ },
693
+ audience: {
694
+ board: "NRR >100% means the base compounds without new logos. Decompose before judging \u2014 same number, different owners.",
695
+ ops: "NRR = 100 + expansion \u2212 contraction \u2212 churn. Motion benchmarks calibrate green/yellow bands. Check reliability_gate on pipeline-inferred data."
696
+ },
697
+ aliases: ["net revenue retention", "net retention", "ndr"],
698
+ benchmarkHint: (motion) => pctBand("nrr", motion)
699
+ },
700
+ {
701
+ id: "grr",
702
+ kind: "saas",
703
+ label: "Gross Revenue Retention",
704
+ group: "Retention",
705
+ tagline: "How leaky is the bucket before expansion papers over it?",
706
+ how_computed: "GRR = ((startingArr \u2212 Churned \u2212 Contraction) / startingArr) \xD7 100 \u2014 expansion is excluded on purpose.",
707
+ formula_lines: [
708
+ "starting = ARR + churned + contraction \u2212 expansion",
709
+ "GRR = (starting \u2212 churned \u2212 contraction) / starting \xD7 100"
710
+ ],
711
+ meaning: 'Board question: "how leaky is the bucket before expansion papers over it?" Prior: >90% healthy, >95% strong for enterprise.',
712
+ expert_read: "GRR is the honesty metric. Expansion can make NRR look fine while GRR is quietly eroding \u2014 always read both.",
713
+ deepdive: [
714
+ "GRR never includes Expansion \u2014 that is the point.",
715
+ "Owners: product/CS for churn, packaging for contraction."
716
+ ],
717
+ visual: {
718
+ kind: "gauge",
719
+ caption: "Exemplar GRR \u2014 floor of the business",
720
+ gauge: 92
721
+ },
722
+ audience: {
723
+ board: "GRR is the floor \u2014 churn + contraction only. Expansion cannot paper over a leaky bucket here.",
724
+ ops: "Exclude Expansion by design. Pair with NRR; diagnose churn vs contraction separately."
725
+ },
726
+ aliases: ["gross revenue retention", "gross retention"],
727
+ benchmarkHint: (motion) => pctBand("grr", motion)
728
+ },
729
+ // —— Pipeline ——
730
+ {
731
+ id: "pipeline_coverage",
732
+ kind: "saas",
733
+ label: "Pipeline Coverage",
734
+ group: "Pipeline",
735
+ tagline: "Is next quarter already at risk?",
736
+ how_computed: "Open pipeline amount \xF7 trailing-90-day closed-won amount.",
737
+ formula_lines: [
738
+ "Coverage = openPipeline / trailing_90d_won",
739
+ "required \u2248 1 / win_rate (discount for time left)"
740
+ ],
741
+ meaning: 'Board question: "is next quarter already at risk?" Priors scale with cycle length: ~3x velocity/SMB, 4\u20135x enterprise.',
742
+ expert_read: "Coverage means nothing without win rate: required coverage \u2248 1 / win rate, discounted for time left in period. Inflated stages and zombie deals fake coverage \u2014 cross-check with Freshness before trusting it.",
743
+ deepdive: [
744
+ "Always pair with Win Rate and Freshness.",
745
+ "Weighted Pipeline is the credibility-adjusted cousin."
746
+ ],
747
+ visual: {
748
+ kind: "gauge",
749
+ caption: "Exemplar coverage vs a 3x target",
750
+ gauge: 72,
751
+ bars: [
752
+ { label: "Open pipeline", value: 75, tone: "accent" },
753
+ { label: "Trailing won (scaled)", value: 25, tone: "neutral" }
754
+ ]
755
+ },
756
+ audience: {
757
+ board: "Coverage answers whether next quarter is already under-piped. Fake coverage from zombies is worse than an honest gap.",
758
+ ops: "open / trailing-90d won. Required \u2248 1/win_rate. Cross-check Freshness before briefing."
759
+ },
760
+ aliases: ["coverage", "pipeline coverage", "pipe coverage"],
761
+ benchmarkHint: (motion) => pctBand("pipeline_coverage", motion)
762
+ },
763
+ {
764
+ id: "weighted_pipeline",
765
+ kind: "saas",
766
+ label: "Weighted Pipeline",
767
+ group: "Pipeline",
768
+ tagline: "What is the pipeline worth after stage probability?",
769
+ how_computed: "Sum of amount \xD7 stage probability for open deals (CRM Probability when present, else stage defaults).",
770
+ formula_lines: [
771
+ "Weighted = \u03A3 (amount \xD7 stageProbability)",
772
+ "trust \u2264 stage discipline deserves"
773
+ ],
774
+ meaning: 'Board question: "what should we actually forecast from open pipe?"',
775
+ expert_read: "Trust it only as much as stage discipline deserves. Inflated late stages make weighted pipeline a fiction.",
776
+ deepdive: [
777
+ "Compare to unweighted open pipeline \u2014 a huge gap means optimistic stages.",
778
+ "Pair with Flow Rate (stuck late stages)."
779
+ ],
780
+ visual: {
781
+ kind: "bars",
782
+ caption: "Exemplar \u2014 open vs weighted",
783
+ bars: [
784
+ { label: "Open pipeline", value: 100, tone: "neutral" },
785
+ { label: "Weighted", value: 42, tone: "accent" }
786
+ ]
787
+ },
788
+ audience: {
789
+ board: "Weighted Pipeline is the credibility-adjusted forecast input \u2014 only as good as stage discipline.",
790
+ ops: "\u03A3 amount \xD7 probability. Audit stage probabilities when weighted << open."
791
+ },
792
+ aliases: ["weighted pipe", "probability-weighted pipeline"]
793
+ },
794
+ {
795
+ id: "pipeline_created",
796
+ kind: "saas",
797
+ label: "Pipeline Created (90d)",
798
+ group: "Pipeline",
799
+ tagline: "How much new pipe did we generate recently?",
800
+ how_computed: "Sum of amounts for opportunities created in the last 90 days.",
801
+ formula_lines: ["Pipeline Created = \u03A3 amount where created_at within 90d"],
802
+ meaning: 'Board question: "is the top of funnel still filling?"',
803
+ expert_read: "Falling created pipeline with flat coverage is a future miss \u2014 coverage is lagging; created is leading.",
804
+ deepdive: [
805
+ "Leading indicator for next-quarter coverage.",
806
+ "Cut by source / segment to find where creation stalled."
807
+ ],
808
+ visual: {
809
+ kind: "bars",
810
+ caption: "Exemplar \u2014 created vs needed",
811
+ bars: [
812
+ { label: "Created (90d)", value: 55, tone: "yellow" },
813
+ { label: "Target pace", value: 80, tone: "green" }
814
+ ]
815
+ },
816
+ audience: {
817
+ board: "Pipeline Created is a leading indicator \u2014 coverage lagging means the miss is already in motion.",
818
+ ops: "\u03A3 amounts on opps created in 90d. Cut by source when it dips."
819
+ },
820
+ aliases: ["pipe gen", "pipeline generation", "created pipeline"]
821
+ },
822
+ {
823
+ id: "pipeline_velocity",
824
+ kind: "saas",
825
+ label: "Pipeline Velocity",
826
+ group: "Pipeline",
827
+ tagline: "Revenue throughput per day \u2014 four levers, one number.",
828
+ how_computed: "(openOpps \xD7 avgDeal \xD7 winRate) / avgCycleDays \u2014 requires \u22653 dated closed-won deals. Unit: $/day.",
829
+ formula_lines: [
830
+ "Velocity = (openOpps \xD7 avgDeal \xD7 winRate) / avgCycleDays",
831
+ "four levers: #opps \xB7 deal size \xB7 win rate \xB7 cycle days"
832
+ ],
833
+ meaning: 'Board question: "which lever moved when throughput changed?" The most decision-ready pipeline metric.',
834
+ expert_read: "When velocity changes, name WHICH lever moved. A win-rate rise on falling opp volume is qualification tightening, not improvement.",
835
+ deepdive: [
836
+ "Needs \u22653 dated wins \u2014 otherwise unavailable.",
837
+ "Pairs with Flow Rate (cycle) and Win Rate (conversion)."
838
+ ],
839
+ visual: {
840
+ kind: "levers",
841
+ caption: "Four levers \u2014 say which one moved",
842
+ levers: ["# Open opps", "Avg deal size", "Win rate", "Cycle days"]
843
+ },
844
+ audience: {
845
+ board: "Velocity is throughput. When it moves, demand the lever \u2014 volume, size, win rate, or cycle \u2014 not a shrug.",
846
+ ops: "(opps \xD7 avgDeal \xD7 winRate) / cycleDays. Diagnose the moved lever before prescribing."
847
+ },
848
+ aliases: ["velocity", "pipeline velocity", "throughput"]
849
+ },
850
+ // —— Sales efficiency ——
851
+ {
852
+ id: "win_rate",
853
+ kind: "saas",
854
+ label: "Win Rate",
855
+ group: "Sales Efficiency",
856
+ tagline: "Of decided deals, how often do we win?",
857
+ how_computed: "closed-won / (won + lost) \xD7 100.",
858
+ formula_lines: ["Win Rate = won / (won + lost) \xD7 100"],
859
+ meaning: 'Board question: "are we converting the pipe we create?" Priors: 25\u201335% SMB, 18\u201325% mid-market, 12\u201318% enterprise on qualified opps.',
860
+ expert_read: "A rising win rate on falling opp volume is qualification tightening, not improvement \u2014 check the denominator.",
861
+ deepdive: [
862
+ "Required coverage \u2248 1 / win rate.",
863
+ "Cut by segment / source before company-wide coaching."
864
+ ],
865
+ visual: {
866
+ kind: "split",
867
+ caption: "Exemplar decided deals",
868
+ bars: [
869
+ { label: "Won", value: 28, tone: "green" },
870
+ { label: "Lost", value: 72, tone: "red" }
871
+ ]
872
+ },
873
+ audience: {
874
+ board: "Win Rate is conversion of decided deals. Rising win rate with falling volume is often tighter qualification, not better selling.",
875
+ ops: "won/(won+lost). Check the denominator. Motion benchmarks set green/yellow bands."
876
+ },
877
+ aliases: ["close rate", "winrate", "win %"],
878
+ benchmarkHint: (motion) => pctBand("win_rate", motion)
879
+ },
880
+ {
881
+ id: "avg_deal_size",
882
+ kind: "saas",
883
+ label: "Avg Deal Size",
884
+ group: "Sales Efficiency",
885
+ tagline: "What does a typical win look like?",
886
+ how_computed: "Mean amount on closed-won opportunities.",
887
+ formula_lines: ["Avg Deal = mean(closed-won amount)"],
888
+ meaning: 'Board question: "are we selling the motion we think we are?"',
889
+ expert_read: "Deal size drifting down while volume rises often means mix shift into a lower segment \u2014 not always a problem, but it changes coverage math.",
890
+ deepdive: [
891
+ "Feeds Pipeline Velocity and LTV proxy.",
892
+ "Cut by segment \u2014 averages hide bimodal motions."
893
+ ],
894
+ visual: {
895
+ kind: "bars",
896
+ caption: "Exemplar \u2014 size mix by segment",
897
+ bars: [
898
+ { label: "SMB", value: 30, tone: "neutral" },
899
+ { label: "Mid-market", value: 55, tone: "accent" },
900
+ { label: "Enterprise", value: 90, tone: "green" }
901
+ ]
902
+ },
903
+ audience: {
904
+ board: "Avg Deal Size should match the motion you claim. Mix shift changes coverage and capacity math.",
905
+ ops: "Mean closed-won amount. Segment before coaching on size."
906
+ },
907
+ aliases: ["average deal size", "asp", "acv"]
908
+ },
909
+ {
910
+ id: "avg_sales_cycle",
911
+ kind: "saas",
912
+ label: "Avg Sales Cycle",
913
+ group: "Sales Efficiency",
914
+ tagline: "How long from create to close on wins?",
915
+ how_computed: "Mean days from created_at to close date on dated closed-won deals.",
916
+ formula_lines: ["Avg Cycle = mean(close_date \u2212 created_at) on dated wins"],
917
+ meaning: 'Board question: "is the cycle stretching \u2014 the earliest soft signal of deal-quality decay?"',
918
+ expert_read: "Cycle stretching past the motion's norm is the earliest soft signal of deal-quality decay. Pair with Flow Rate stuck stages.",
919
+ deepdive: [
920
+ "Feeds Pipeline Velocity as the denominator.",
921
+ "Needs dated wins \u2014 missing close dates understate/omit."
922
+ ],
923
+ visual: {
924
+ kind: "bars",
925
+ caption: "Exemplar cycle vs motion norm",
926
+ bars: [
927
+ { label: "Your cycle", value: 78, tone: "yellow" },
928
+ { label: "Motion norm", value: 55, tone: "green" }
929
+ ]
930
+ },
931
+ audience: {
932
+ board: "Cycle stretch is an early soft signal that quality or process is slipping \u2014 before the miss shows in bookings.",
933
+ ops: "Mean create\u2192close on dated wins. Investigate the stage that aged."
934
+ },
935
+ aliases: ["sales cycle", "cycle length", "time to close"]
936
+ },
937
+ {
938
+ id: "stage_conversion",
939
+ kind: "saas",
940
+ label: "Stage Conversion",
941
+ group: "Sales Efficiency",
942
+ tagline: "Where in the stage model does advancement collapse?",
943
+ how_computed: "From metadata.stage_history stage advances when present; otherwise a win-rate proxy.",
944
+ formula_lines: [
945
+ "Preferred: advancement rates from stage_history",
946
+ "Fallback: win-rate proxy when history is missing"
947
+ ],
948
+ meaning: 'Board question: "which single stage is starving everything downstream?"',
949
+ expert_read: "Find the one stage where conversion collapses \u2014 that's the process problem; everything downstream is starvation.",
950
+ deepdive: [
951
+ "Best with stage_history metadata; otherwise treat as proxy.",
952
+ "Pairs with Flow Rate stage-age cuts."
953
+ ],
954
+ visual: {
955
+ kind: "funnel",
956
+ caption: "Exemplar \u2014 find the collapse",
957
+ funnel: [
958
+ { label: "Stage 1\u21922", widthPct: 100 },
959
+ { label: "Stage 2\u21923", widthPct: 72 },
960
+ { label: "Stage 3\u21924", widthPct: 28 },
961
+ { label: "Stage 4\u2192Close", widthPct: 18 }
962
+ ]
963
+ },
964
+ audience: {
965
+ board: "Stage Conversion names the bottleneck stage \u2014 one collapse starves every stage after it.",
966
+ ops: "Prefer stage_history advances. Fix the collapse stage before coaching downstream reps."
967
+ },
968
+ aliases: ["stage conversion", "stage advance", "conversion by stage"]
969
+ },
970
+ // —— Unit economics ——
971
+ {
972
+ id: "ltv_proxy",
973
+ kind: "saas",
974
+ label: "LTV (Proxy)",
975
+ group: "Unit Economics",
976
+ tagline: "Rough lifetime value from deal size and GRR.",
977
+ how_computed: "avgDeal / ((100 \u2212 GRR) / 100) when GRR < 100. Unavailable when GRR is 100%+ or missing.",
978
+ formula_lines: [
979
+ "LTV \u2248 avgDeal / churnRate",
980
+ "churnRate = (100 \u2212 GRR) / 100 (requires GRR < 100)"
981
+ ],
982
+ meaning: 'Board question: "what is a customer roughly worth over their life?"',
983
+ expert_read: "This is a proxy \u2014 not a cohort LTV. Use it for direction, not capital allocation.",
984
+ deepdive: [
985
+ "Unavailable when GRR \u2265 100 or missing.",
986
+ "Pairs with CAC for LTV:CAC when spend data exists."
987
+ ],
988
+ visual: {
989
+ kind: "gauge",
990
+ caption: "Exemplar LTV proxy (directional)",
991
+ gauge: 68
992
+ },
993
+ audience: {
994
+ board: "LTV Proxy is directional from deal size and GRR \u2014 not a cohort LTV. Use for orientation, not capital decisions.",
995
+ ops: "avgDeal / ((100\u2212GRR)/100). Needs GRR < 100. Prefer cohort math when billing data arrives."
996
+ },
997
+ aliases: ["ltv", "lifetime value"]
998
+ },
999
+ {
1000
+ id: "cac",
1001
+ kind: "saas",
1002
+ label: "CAC",
1003
+ group: "Unit Economics",
1004
+ tagline: "Customer acquisition cost \u2014 needs spend data.",
1005
+ how_computed: "Requires campaign / sales spend data. Currently unavailable on CRM-only datasets.",
1006
+ formula_lines: ["CAC = sales & marketing spend / new customers", "(requires spend data \u2014 not in CRM-only exports)"],
1007
+ meaning: 'Board question: "what does a new logo cost to win?"',
1008
+ expert_read: "Without spend, NTRP cannot invent CAC. Wire campaign spend or finance exports to unlock unit economics.",
1009
+ deepdive: [
1010
+ "Always unavailable on CRM-only demos \u2014 expected.",
1011
+ "Unlocks LTV:CAC, Payback, Magic Number when spend lands."
1012
+ ],
1013
+ visual: { kind: "none", caption: "Needs campaign spend / finance export" },
1014
+ audience: {
1015
+ board: "CAC is locked until spend data is connected \u2014 CRM alone cannot price acquisition.",
1016
+ ops: "Bring campaign or S&M spend. Until then unit-econ metrics stay unavailable by design."
1017
+ },
1018
+ aliases: ["customer acquisition cost", "acquisition cost"]
1019
+ },
1020
+ {
1021
+ id: "ltv_cac_ratio",
1022
+ kind: "saas",
1023
+ label: "LTV:CAC Ratio",
1024
+ group: "Unit Economics",
1025
+ tagline: "Is acquisition spend earning its keep?",
1026
+ how_computed: "LTV proxy \xF7 CAC. Unavailable without spend (CAC).",
1027
+ formula_lines: ["LTV:CAC = LTV_proxy / CAC", "(requires CAC)"],
1028
+ meaning: 'Board question: "do we earn enough lifetime value per dollar spent to acquire?"',
1029
+ expert_read: "Efficiency era: boards weigh LTV:CAC and payback as heavily as growth. Classic rule of thumb \u22653x, but motion and gross margin matter.",
1030
+ deepdive: ["Blocked on CAC. See LTV Proxy and CAC."],
1031
+ visual: { kind: "none", caption: "Needs CAC (spend data)" },
1032
+ audience: {
1033
+ board: "LTV:CAC is the acquisition ROI story \u2014 available once spend is wired.",
1034
+ ops: "LTV_proxy / CAC. Unlocks with spend import."
1035
+ },
1036
+ aliases: ["ltv cac", "ltv/cac", "ltv to cac"]
1037
+ },
1038
+ {
1039
+ id: "payback_months",
1040
+ kind: "saas",
1041
+ label: "Payback Months",
1042
+ group: "Unit Economics",
1043
+ tagline: "How many months to recover CAC?",
1044
+ how_computed: "Requires CAC / spend. Lower is better.",
1045
+ formula_lines: ["Payback \u2248 CAC / (monthly gross profit per customer)", "(requires spend data)"],
1046
+ meaning: 'Board question: "how fast does acquisition spend return?" Efficiency era prior: <18 months often healthy.',
1047
+ expert_read: "Boards now weigh payback (<18mo) as heavily as growth in many motions.",
1048
+ deepdive: ["Blocked on CAC. Benchmarks exist per motion once data lands."],
1049
+ visual: { kind: "none", caption: "Needs CAC (spend data)" },
1050
+ audience: {
1051
+ board: "Payback is how fast CAC returns. Efficiency-era boards often want <18 months.",
1052
+ ops: "Requires CAC. Motion green/yellow bands apply when available."
1053
+ },
1054
+ aliases: ["payback", "cac payback"],
1055
+ benchmarkHint: (motion) => monthsBand(motion)
1056
+ },
1057
+ {
1058
+ id: "magic_number",
1059
+ kind: "saas",
1060
+ label: "Magic Number",
1061
+ group: "Unit Economics",
1062
+ tagline: "Sales efficiency \u2014 net new ARR per sales dollar.",
1063
+ how_computed: "Requires sales spend. Classic form: net new ARR (quarter) / prior-quarter S&M spend.",
1064
+ formula_lines: [
1065
+ "Magic Number \u2248 Net New ARR(q) / S&M spend(q\u22121)",
1066
+ "(requires spend data)"
1067
+ ],
1068
+ meaning: 'Board question: "how efficiently does sales spend produce net new ARR?" Prior: >0.75 often healthy; >1 strong.',
1069
+ expert_read: "Efficiency era: magic number >0.75 is weighed alongside growth. Without spend, NTRP keeps this unavailable rather than inventing it.",
1070
+ deepdive: ["Blocked on spend. Benchmarks per motion ready when data lands."],
1071
+ visual: { kind: "none", caption: "Needs S&M spend data" },
1072
+ audience: {
1073
+ board: "Magic Number prices sales efficiency. Available once S&M spend is connected.",
1074
+ ops: "Net new ARR / prior S&M. Motion benchmarks apply when spend lands."
1075
+ },
1076
+ aliases: ["sales magic number", "sales efficiency magic number"],
1077
+ benchmarkHint: (motion) => magicBand(motion)
1078
+ }
1079
+ ];
1080
+ METRIC_DEFINITIONS = [...VITALS, ...SAAS];
1081
+ BY_ID = new Map(METRIC_DEFINITIONS.map((m) => [m.id, m]));
1082
+ ALIAS_INDEX = (() => {
1083
+ const idx = /* @__PURE__ */ new Map();
1084
+ for (const m of METRIC_DEFINITIONS) {
1085
+ idx.set(m.id.toLowerCase(), m.id);
1086
+ idx.set(m.label.toLowerCase(), m.id);
1087
+ for (const a of m.aliases ?? []) {
1088
+ idx.set(a.toLowerCase(), m.id);
1089
+ }
1090
+ }
1091
+ idx.set("signal-to-noise", "signal_to_noise");
1092
+ idx.set("signal:noise", "signal_to_noise");
1093
+ idx.set("flow-rate", "flow_rate");
1094
+ idx.set("drop-rate", "drop_rate");
1095
+ idx.set("thread-depth", "thread_depth");
1096
+ return idx;
1097
+ })();
1098
+ SAAS_METRIC_IDS = SAAS.map((m) => m.id);
1099
+ }
1100
+ });
1101
+
1102
+ // src/services/metric-explainers.ts
1103
+ var init_metric_explainers = __esm({
1104
+ "src/services/metric-explainers.ts"() {
1105
+ "use strict";
1106
+ init_metric_definitions();
1107
+ }
1108
+ });
1109
+
162
1110
  // src/conversation/handoff-draft.ts
163
1111
  function isShipIntent(input) {
164
1112
  const line = input.trim();
@@ -171,6 +1119,7 @@ var init_handoff_draft = __esm({
171
1119
  "use strict";
172
1120
  init_profile();
173
1121
  init_session_analysis();
1122
+ init_metric_explainers();
174
1123
  QUESTION_LEAD_RE = /^\s*(what|why|how|when|where|who|which|is|are|was|were|do|does|did|explain|tell me|help me understand)\b/i;
175
1124
  SHIP_INTENT_RE = /\b(ship|export|deliver|write[- ]?up|board memo|action plan|turn (this|it|that) into|(draft|create|make|build|prepare|generate|send)\s+(me\s+)?(a\s+|the\s+)?hand[- ]?off|hand[- ]?off\s+(prompt|doc|document|plan))\b/i;
176
1125
  }
@@ -219,6 +1168,7 @@ var init_repl_globals = __esm({
219
1168
  // src/cli/prompts.ts
220
1169
  import { createInterface } from "readline/promises";
221
1170
  import { clearLine, cursorTo } from "readline";
1171
+ import { StringDecoder } from "string_decoder";
222
1172
  import chalk2 from "chalk";
223
1173
  var init_prompts = __esm({
224
1174
  "src/cli/prompts.ts"() {
@@ -351,13 +1301,6 @@ var init_schema = __esm({
351
1301
  }
352
1302
  });
353
1303
 
354
- // src/baselines/metrics-benchmarks.ts
355
- var init_metrics_benchmarks = __esm({
356
- "src/baselines/metrics-benchmarks.ts"() {
357
- "use strict";
358
- }
359
- });
360
-
361
1304
  // src/metrics/classify-source.ts
362
1305
  var init_classify_source = __esm({
363
1306
  "src/metrics/classify-source.ts"() {
@@ -596,6 +1539,15 @@ var init_session_state = __esm({
596
1539
  }
597
1540
  });
598
1541
 
1542
+ // src/conversation/recommended-action.ts
1543
+ var init_recommended_action = __esm({
1544
+ "src/conversation/recommended-action.ts"() {
1545
+ "use strict";
1546
+ init_repl_api();
1547
+ init_phase();
1548
+ }
1549
+ });
1550
+
599
1551
  // src/conversation/phase.ts
600
1552
  import chalk3 from "chalk";
601
1553
  function sessionHasData(ctx) {
@@ -605,7 +1557,7 @@ function sessionHasData(ctx) {
605
1557
  function resolveConversationPhase(ctx) {
606
1558
  if (ctx.deliverIntent) return "deliver";
607
1559
  if (ctx.computeInProgress) return "compute";
608
- if (ctx.strategistState && ctx.strategistState.step !== "awaiting_analysis") {
1560
+ if (ctx.strategistState && ctx.strategistState.step !== "awaiting_analysis" && ctx.strategistState.step !== "awaiting_connect") {
609
1561
  return "strategize";
610
1562
  }
611
1563
  if (isAnalysisReady(ctx)) return "explore";
@@ -625,6 +1577,7 @@ var init_phase = __esm({
625
1577
  init_explore_mode();
626
1578
  init_session_state();
627
1579
  init_theme();
1580
+ init_recommended_action();
628
1581
  }
629
1582
  });
630
1583
 
@@ -642,8 +1595,8 @@ var init_gap_audit = __esm({
642
1595
  });
643
1596
 
644
1597
  // src/strategies/library.ts
645
- import { writeFileSync as writeFileSync6 } from "fs";
646
- import { join as join6 } from "path";
1598
+ import { writeFileSync as writeFileSync7 } from "fs";
1599
+ import { join as join7 } from "path";
647
1600
  import { stringify as stringifyYaml } from "yaml";
648
1601
  var init_library = __esm({
649
1602
  "src/strategies/library.ts"() {
@@ -693,9 +1646,9 @@ var init_types2 = __esm({
693
1646
  });
694
1647
 
695
1648
  // src/config/install.ts
696
- import { randomUUID as randomUUID2 } from "crypto";
697
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
698
- import { join as join7 } from "path";
1649
+ import { randomUUID as randomUUID3 } from "crypto";
1650
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync8 } from "fs";
1651
+ import { join as join8 } from "path";
699
1652
  var init_install = __esm({
700
1653
  "src/config/install.ts"() {
701
1654
  "use strict";
@@ -704,8 +1657,8 @@ var init_install = __esm({
704
1657
  });
705
1658
 
706
1659
  // src/config/progress-migrate.ts
707
- import { existsSync as existsSync6, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync8 } from "fs";
708
- import { join as join8 } from "path";
1660
+ import { existsSync as existsSync7, readFileSync as readFileSync7, renameSync as renameSync2, writeFileSync as writeFileSync9 } from "fs";
1661
+ import { join as join9 } from "path";
709
1662
  var init_progress_migrate = __esm({
710
1663
  "src/config/progress-migrate.ts"() {
711
1664
  "use strict";
@@ -721,8 +1674,8 @@ var init_usage_backfill = __esm({
721
1674
  });
722
1675
 
723
1676
  // src/config/progress.ts
724
- import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync7, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "fs";
725
- import { join as join9 } from "path";
1677
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync8, unlinkSync as unlinkSync2, writeFileSync as writeFileSync10 } from "fs";
1678
+ import { join as join10 } from "path";
726
1679
  var init_progress = __esm({
727
1680
  "src/config/progress.ts"() {
728
1681
  "use strict";
@@ -850,13 +1803,13 @@ var init_tool_schemas = __esm({
850
1803
  });
851
1804
 
852
1805
  // src/ai/privacy.ts
853
- import { homedir as homedir3 } from "os";
854
- import { join as join10 } from "path";
1806
+ import { homedir as homedir4 } from "os";
1807
+ import { join as join11 } from "path";
855
1808
  var AUDIT_DIR;
856
1809
  var init_privacy = __esm({
857
1810
  "src/ai/privacy.ts"() {
858
1811
  "use strict";
859
- AUDIT_DIR = join10(homedir3(), ".ntrp", "audit");
1812
+ AUDIT_DIR = join11(homedir4(), ".ntrp", "audit");
860
1813
  }
861
1814
  });
862
1815
 
@@ -905,16 +1858,16 @@ var init_thread = __esm({
905
1858
  });
906
1859
 
907
1860
  // src/data/playbook.ts
908
- import { existsSync as existsSync8, readFileSync as readFileSync8, appendFileSync } from "fs";
909
- import { join as join11 } from "path";
1861
+ import { existsSync as existsSync9, readFileSync as readFileSync9, appendFileSync as appendFileSync2 } from "fs";
1862
+ import { join as join12 } from "path";
910
1863
  function playsPath() {
911
- return join11(getMemoryDir(), PLAYS_FILE);
1864
+ return join12(getMemoryDir(), PLAYS_FILE);
912
1865
  }
913
1866
  function getCustomPlays() {
914
1867
  const path = playsPath();
915
- if (!existsSync8(path)) return [];
1868
+ if (!existsSync9(path)) return [];
916
1869
  const out = [];
917
- for (const line of readFileSync8(path, "utf-8").split("\n")) {
1870
+ for (const line of readFileSync9(path, "utf-8").split("\n")) {
918
1871
  const trimmed = line.trim();
919
1872
  if (!trimmed) continue;
920
1873
  try {
@@ -1150,9 +2103,9 @@ var init_playbook = __esm({
1150
2103
  });
1151
2104
 
1152
2105
  // src/memory/play-outcomes.ts
1153
- import { existsSync as existsSync9, readFileSync as readFileSync9, appendFileSync as appendFileSync2 } from "fs";
1154
- import { join as join12 } from "path";
1155
- import { randomUUID as randomUUID3 } from "crypto";
2106
+ import { existsSync as existsSync10, readFileSync as readFileSync10, appendFileSync as appendFileSync3 } from "fs";
2107
+ import { join as join13 } from "path";
2108
+ import { randomUUID as randomUUID4 } from "crypto";
1156
2109
  var init_play_outcomes = __esm({
1157
2110
  "src/memory/play-outcomes.ts"() {
1158
2111
  "use strict";
@@ -1168,8 +2121,8 @@ var init_registry = __esm({
1168
2121
  });
1169
2122
 
1170
2123
  // src/ai/prompt-parts.ts
1171
- import { existsSync as existsSync10, readFileSync as readFileSync10 } from "fs";
1172
- import { join as join13 } from "path";
2124
+ import { existsSync as existsSync11, readFileSync as readFileSync11 } from "fs";
2125
+ import { join as join14 } from "path";
1173
2126
  var init_prompt_parts = __esm({
1174
2127
  "src/ai/prompt-parts.ts"() {
1175
2128
  "use strict";
@@ -1190,6 +2143,12 @@ var init_strategist_prompt = __esm({
1190
2143
  });
1191
2144
 
1192
2145
  // src/ai/json-response.ts
2146
+ function stripJsonFences(text) {
2147
+ const trimmed = text.trim();
2148
+ const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
2149
+ if (fenced) return fenced[1].trim();
2150
+ return trimmed.replace(/```(?:json)?\s*/gi, "").replace(/```/g, "").trim();
2151
+ }
1193
2152
  var init_json_response = __esm({
1194
2153
  "src/ai/json-response.ts"() {
1195
2154
  "use strict";
@@ -1197,6 +2156,46 @@ var init_json_response = __esm({
1197
2156
  });
1198
2157
 
1199
2158
  // src/ai/strategist-validate.ts
2159
+ function parseJsonObjectFromText(text) {
2160
+ const cleaned = stripJsonFences(text);
2161
+ const start = cleaned.indexOf("{");
2162
+ if (start === -1) return null;
2163
+ let depth = 0;
2164
+ let inString = false;
2165
+ let escaped = false;
2166
+ let end = -1;
2167
+ for (let i = start; i < cleaned.length; i++) {
2168
+ const ch = cleaned[i];
2169
+ if (escaped) {
2170
+ escaped = false;
2171
+ continue;
2172
+ }
2173
+ if (ch === "\\") {
2174
+ if (inString) escaped = true;
2175
+ continue;
2176
+ }
2177
+ if (ch === '"') {
2178
+ inString = !inString;
2179
+ continue;
2180
+ }
2181
+ if (inString) continue;
2182
+ if (ch === "{") depth++;
2183
+ else if (ch === "}") {
2184
+ depth--;
2185
+ if (depth === 0) {
2186
+ end = i;
2187
+ break;
2188
+ }
2189
+ }
2190
+ }
2191
+ if (end === -1) return null;
2192
+ try {
2193
+ const parsed = JSON.parse(cleaned.slice(start, end + 1));
2194
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2195
+ } catch {
2196
+ return null;
2197
+ }
2198
+ }
1200
2199
  function extractNumbers(text) {
1201
2200
  const out = [];
1202
2201
  for (const match of text.matchAll(NUMBER_RE)) {
@@ -1250,12 +2249,12 @@ function strArray(value) {
1250
2249
  if (!Array.isArray(value)) return [];
1251
2250
  return value.map(str).filter(Boolean);
1252
2251
  }
1253
- function num(value, fallback) {
2252
+ function num(value, fallback2) {
1254
2253
  const n = typeof value === "number" ? value : Number(value);
1255
- return Number.isFinite(n) ? n : fallback;
2254
+ return Number.isFinite(n) ? n : fallback2;
1256
2255
  }
1257
- function enumValue(value, allowed, fallback) {
1258
- return typeof value === "string" && allowed.includes(value) ? value : fallback;
2256
+ function enumValue(value, allowed, fallback2) {
2257
+ return typeof value === "string" && allowed.includes(value) ? value : fallback2;
1259
2258
  }
1260
2259
  function hasNumber(text) {
1261
2260
  return extractNumbers(text).length > 0;
@@ -1347,12 +2346,12 @@ function validateContingency(raw, today2) {
1347
2346
  if (!raw || typeof raw !== "object") return null;
1348
2347
  const record = raw;
1349
2348
  const trigger = str(record.trigger);
1350
- const fallback = str(record.fallback);
1351
- if (!trigger || !fallback) return null;
2349
+ const fallback2 = str(record.fallback);
2350
+ if (!trigger || !fallback2) return null;
1352
2351
  return {
1353
2352
  trigger,
1354
2353
  trigger_check_date: normalizeDate(record.trigger_check_date, today2, 21).iso,
1355
- fallback
2354
+ fallback: fallback2
1356
2355
  };
1357
2356
  }
1358
2357
  function validPlayIds(value) {
@@ -1468,11 +2467,90 @@ function validateStrategistPlan(raw, opts) {
1468
2467
  };
1469
2468
  return { plan, issues, measurableTargets, totalTargets };
1470
2469
  }
2470
+ function buildGroundedFallbackPlan(input) {
2471
+ const today2 = parseIsoDate(input.todayIso) ?? /* @__PURE__ */ new Date();
2472
+ const triggered2 = matchTriggeredPlays(input.vitals, LAYERS);
2473
+ const issues = [
2474
+ "LLM plan JSON invalid \u2014 using grounded fallback from triggered plays and live vitals"
2475
+ ];
2476
+ const sources = triggered2.length > 0 ? triggered2.slice(0, 3) : input.vitals.slice().sort((a, b) => a.score - b.score).slice(0, 2).map((vital) => {
2477
+ const play = getPlaybook().find((p) => p.trigger_vital_sign === vital.vital_sign) ?? getPlaybook()[0];
2478
+ return { play, vital, layer: 1 };
2479
+ });
2480
+ const workstreams = sources.map(({ play, vital }, index) => {
2481
+ const score = Math.round(vital.score);
2482
+ const dollar = vital.dollar_value != null && vital.dollar_value > 0 ? `$${Math.round(vital.dollar_value).toLocaleString("en-US")}` : null;
2483
+ const baseline = dollar ?? String(score);
2484
+ const targetLow = vital.dollar_value != null && vital.dollar_value > 0 ? `$${Math.round(vital.dollar_value * 0.4).toLocaleString("en-US")}` : String(Math.min(100, score + 20));
2485
+ const targetHigh = vital.dollar_value != null && vital.dollar_value > 0 ? `$${Math.round(vital.dollar_value * 0.6).toLocaleString("en-US")}` : String(Math.min(100, score + 35));
2486
+ const checkDate = toIso(addDays(today2, 21 + index * 7));
2487
+ const outcome = {
2488
+ metric: vital.vital_sign,
2489
+ baseline,
2490
+ target_range: `${baseline} -> ${targetLow}-${targetHigh}`,
2491
+ check_date: checkDate,
2492
+ measured_by: `${vital.vital_sign} vital sign`
2493
+ };
2494
+ return {
2495
+ order: index + 1,
2496
+ title: play.name,
2497
+ problem: `${vital.vital_sign} score ${score} (${vital.status})${dollar ? ` \u2014 ${dollar} ${vital.dollar_label ?? ""}`.trimEnd() : ""}`,
2498
+ rationale: index === 0 ? "Layer-order first: clean or unblock the gating vital before downstream work" : "Next in dependency order after the prior workstream",
2499
+ play_ids: [play.id],
2500
+ actions: play.steps.slice(0, 3),
2501
+ effort_hours: 8 + index * 4,
2502
+ milestones: [
2503
+ {
2504
+ label: `Check ${vital.vital_sign} movement`,
2505
+ due: checkDate,
2506
+ verification: `${vital.vital_sign} score moves toward ${targetLow}-${targetHigh} (baseline ${baseline})`
2507
+ }
2508
+ ],
2509
+ deliverables: [
2510
+ {
2511
+ label: `${play.name} triage list`,
2512
+ kind: "artifact",
2513
+ due: toIso(addDays(today2, 7 + index * 7))
2514
+ }
2515
+ ],
2516
+ expected_outcome: outcome,
2517
+ leading_indicators: [],
2518
+ contingency: {
2519
+ trigger: `${vital.vital_sign} flat or worse at first check`,
2520
+ trigger_check_date: checkDate,
2521
+ fallback: "Descope to the single highest-dollar entity cohort and re-run /strategy review"
2522
+ }
2523
+ };
2524
+ });
2525
+ const gating = input.gatingVitalSign ?? sources[0]?.vital.vital_sign ?? "freshness";
2526
+ const varLabel = input.totalValueAtRisk != null && input.totalValueAtRisk > 0 ? `$${Math.round(input.totalValueAtRisk).toLocaleString("en-US")} at risk` : "material pipeline dollars at risk";
2527
+ const plan = {
2528
+ title: "Grounded recovery plan",
2529
+ objective: input.objective,
2530
+ summary_30k: `${gating} is the gating pressure (${varLabel}). This fallback sequences ${workstreams.length} playbook workstream(s) in layer order so data trust and handoffs unlock pipeline movement. Treat baselines as live vital readings; refine with /strategy after the first review.`,
2531
+ hypothesis: "If plays execute in layer order against the live vital scores, the objective metrics should move into the stated ranges within one review cycle.",
2532
+ target_segment: "Whole pipeline",
2533
+ priority: "high",
2534
+ review_cadence: "Weekly",
2535
+ confidence: 0.45,
2536
+ constraints: ["Generated without a validated LLM plan JSON \u2014 confirm capacity before staffing"],
2537
+ assumptions: ["Outcome ranges are heuristic halves/increments of live vitals, not model-authored forecasts"],
2538
+ risks: ["Fallback plans lack stress-test revisions \u2014 run /strategy once the engine emits valid JSON"],
2539
+ workstreams
2540
+ };
2541
+ return {
2542
+ plan,
2543
+ issues,
2544
+ measurableTargets: workstreams.length,
2545
+ totalTargets: workstreams.length
2546
+ };
2547
+ }
1471
2548
  var NUMBER_RE, SUFFIX_MULTIPLIER, INSTRUMENT_TOKENS, ISO_DATE_RE;
1472
2549
  var init_strategist_validate = __esm({
1473
2550
  "src/ai/strategist-validate.ts"() {
1474
2551
  "use strict";
1475
2552
  init_playbook();
2553
+ init_health_score();
1476
2554
  init_json_response();
1477
2555
  NUMBER_RE = /\$?\s*(\d[\d,]*\.?\d*)\s*(m|k|b|million|thousand|billion)?\b/gi;
1478
2556
  SUFFIX_MULTIPLIER = {
@@ -1550,6 +2628,20 @@ var init_strategist_validate = __esm({
1550
2628
  });
1551
2629
 
1552
2630
  // src/ai/strategist.ts
2631
+ function describePlanValidationFailure(text, evidenceText, todayIso) {
2632
+ const raw = parseJsonObjectFromText(text);
2633
+ if (!raw) {
2634
+ if (text.includes("{") && !text.trim().endsWith("}")) {
2635
+ return "JSON object appears truncated (increase brevity: \u22643 workstreams) or incomplete";
2636
+ }
2637
+ return "not parseable as a JSON object (prose or truncated output)";
2638
+ }
2639
+ const result = validateStrategistPlan(raw, { evidenceText, todayIso });
2640
+ if (!result) {
2641
+ return "JSON parsed but no usable workstreams remained after measurability checks (need \u22651 workstream with measurable outcome or dated milestone)";
2642
+ }
2643
+ return "unknown validation failure";
2644
+ }
1553
2645
  var init_strategist2 = __esm({
1554
2646
  "src/ai/strategist.ts"() {
1555
2647
  "use strict";
@@ -1565,6 +2657,7 @@ var init_strategist2 = __esm({
1565
2657
  init_thread();
1566
2658
  init_strategist_prompt();
1567
2659
  init_strategist_validate();
2660
+ init_strategist_prompt();
1568
2661
  }
1569
2662
  });
1570
2663
 
@@ -1693,7 +2786,6 @@ var init_time_bank = __esm({
1693
2786
  });
1694
2787
 
1695
2788
  // src/conversation/strategist-flow.ts
1696
- import ora from "ora";
1697
2789
  import chalk7 from "chalk";
1698
2790
  function isStrategistIntent(input) {
1699
2791
  const line = input.trim();
@@ -1709,6 +2801,7 @@ var STRATEGIST_INTENT_RE;
1709
2801
  var init_strategist_flow = __esm({
1710
2802
  "src/conversation/strategist-flow.ts"() {
1711
2803
  "use strict";
2804
+ init_spinner();
1712
2805
  init_context2();
1713
2806
  init_handoff_draft();
1714
2807
  init_repl_api();
@@ -1731,6 +2824,7 @@ init_strategist_flow();
1731
2824
  init_phase();
1732
2825
  init_context2();
1733
2826
  init_strategist_validate();
2827
+ init_strategist2();
1734
2828
  init_playbook();
1735
2829
  init_health_score();
1736
2830
  var failures = [];
@@ -1864,6 +2958,40 @@ assert(triggered.length >= 1, "keyless skeleton triggers at least one play");
1864
2958
  assert(triggered[0].layer === 1, "first triggered play respects LAYERS order (freshness first)");
1865
2959
  var nums = extractNumbers("$3.1M stale pipeline, 120 deals");
1866
2960
  assert(nums.some((n) => n >= 3e6), "extractNumbers parses $3.1M");
2961
+ assert(
2962
+ describePlanValidationFailure("not json at all", evidence, today).includes("not parseable"),
2963
+ "describePlanValidationFailure: prose \u2192 not parseable"
2964
+ );
2965
+ assert(
2966
+ describePlanValidationFailure('{"title":"x","workstreams":[]}', evidence, today).includes("no usable workstreams"),
2967
+ "describePlanValidationFailure: empty workstreams \u2192 demoted message"
2968
+ );
2969
+ assert(
2970
+ describePlanValidationFailure('{"title":"cut off", "workstreams": [{"title":', evidence, today).includes("truncated"),
2971
+ "describePlanValidationFailure: truncated JSON \u2192 truncated message"
2972
+ );
2973
+ var fallback = buildGroundedFallbackPlan({
2974
+ objective: "Cut stale pipeline in half before Q4",
2975
+ vitals: ["freshness", "flow_rate", "drop_rate", "signal_to_noise", "thread_depth"].map(
2976
+ (sign) => ({
2977
+ vital_sign: sign,
2978
+ score: sign === "freshness" ? 29 : sign === "flow_rate" ? 40 : 70,
2979
+ status: sign === "freshness" ? "red" : sign === "flow_rate" ? "red" : "yellow",
2980
+ dollar_value: sign === "freshness" ? 31e5 : sign === "flow_rate" ? 12e5 : null,
2981
+ dollar_label: sign === "freshness" ? "pipeline at risk" : sign === "flow_rate" ? "stuck in pipeline" : null
2982
+ })
2983
+ ),
2984
+ todayIso: today,
2985
+ gatingVitalSign: "freshness",
2986
+ totalValueAtRisk: 43e5
2987
+ });
2988
+ assert(fallback.plan.workstreams.length >= 1, "grounded fallback has workstreams");
2989
+ assert(fallback.plan.objective.includes("stale pipeline"), "grounded fallback keeps objective");
2990
+ assert(
2991
+ fallback.plan.workstreams.some((ws) => ws.play_ids.includes("clean-dead-pipeline")),
2992
+ "grounded fallback links freshness play"
2993
+ );
2994
+ assert(fallback.issues.some((i) => i.includes("grounded fallback")), "grounded fallback records issue");
1867
2995
  if (failures.length > 0) {
1868
2996
  console.error("FAIL strategist-smoke:");
1869
2997
  for (const f of failures) console.error(" -", f);