@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.
@@ -0,0 +1,3010 @@
1
+ #!/usr/bin/env node
2
+ process.noDeprecation = true;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+
8
+ // src/baselines/metrics-benchmarks.ts
9
+ function motionBenchmarkLabel(motion) {
10
+ return MOTION_LABELS[motion ?? "mid_market"];
11
+ }
12
+ var METRICS_BENCHMARKS, MOTION_LABELS;
13
+ var init_metrics_benchmarks = __esm({
14
+ "src/baselines/metrics-benchmarks.ts"() {
15
+ "use strict";
16
+ METRICS_BENCHMARKS = {
17
+ plg: {
18
+ nrr: { green: 110, yellow: 100 },
19
+ grr: { green: 85, yellow: 75 },
20
+ win_rate: { green: 25, yellow: 15 },
21
+ pipeline_coverage: { green: 4, yellow: 2.5 },
22
+ magic_number: { green: 1, yellow: 0.75 },
23
+ payback_months: { green: 12, yellow: 18 }
24
+ },
25
+ smb_velocity: {
26
+ nrr: { green: 105, yellow: 95 },
27
+ grr: { green: 88, yellow: 78 },
28
+ win_rate: { green: 22, yellow: 12 },
29
+ pipeline_coverage: { green: 3.5, yellow: 2 },
30
+ magic_number: { green: 0.9, yellow: 0.6 },
31
+ payback_months: { green: 14, yellow: 20 }
32
+ },
33
+ mid_market: {
34
+ nrr: { green: 100, yellow: 90 },
35
+ grr: { green: 90, yellow: 80 },
36
+ win_rate: { green: 20, yellow: 12 },
37
+ pipeline_coverage: { green: 3, yellow: 2 },
38
+ magic_number: { green: 0.75, yellow: 0.5 },
39
+ payback_months: { green: 16, yellow: 22 }
40
+ },
41
+ enterprise: {
42
+ nrr: { green: 95, yellow: 85 },
43
+ grr: { green: 92, yellow: 82 },
44
+ win_rate: { green: 15, yellow: 8 },
45
+ pipeline_coverage: { green: 2.5, yellow: 1.5 },
46
+ magic_number: { green: 0.6, yellow: 0.4 },
47
+ payback_months: { green: 18, yellow: 24 }
48
+ }
49
+ };
50
+ MOTION_LABELS = {
51
+ plg: "PLG",
52
+ smb_velocity: "SMB Velocity",
53
+ mid_market: "Mid-Market",
54
+ enterprise: "Enterprise"
55
+ };
56
+ }
57
+ });
58
+
59
+ // src/data/metric-definitions.ts
60
+ function pctBand(metric, motion) {
61
+ const m = motion ?? "mid_market";
62
+ const t = METRICS_BENCHMARKS[m][metric];
63
+ return `${motionBenchmarkLabel(m)} green \u2265${t.green}${metric === "pipeline_coverage" ? "x" : "%"}, yellow \u2265${t.yellow}${metric === "pipeline_coverage" ? "x" : "%"}`;
64
+ }
65
+ function monthsBand(motion) {
66
+ const m = motion ?? "mid_market";
67
+ const t = METRICS_BENCHMARKS[m].payback_months;
68
+ return `${motionBenchmarkLabel(m)} green \u2264${t.green}mo, yellow \u2264${t.yellow}mo`;
69
+ }
70
+ function magicBand(motion) {
71
+ const m = motion ?? "mid_market";
72
+ const t = METRICS_BENCHMARKS[m].magic_number;
73
+ return `${motionBenchmarkLabel(m)} green \u2265${t.green}, yellow \u2265${t.yellow}`;
74
+ }
75
+ function getMetricExplainer(id) {
76
+ return BY_ID.get(id);
77
+ }
78
+ function resolveMetricId(query) {
79
+ const q = query.trim().toLowerCase().replace(/\s+/g, " ");
80
+ if (!q) return void 0;
81
+ if (BY_ID.has(q)) return q;
82
+ const direct = ALIAS_INDEX.get(q);
83
+ if (direct) return direct;
84
+ const norm = q.replace(/[-\s]+/g, "_");
85
+ if (BY_ID.has(norm)) return norm;
86
+ return ALIAS_INDEX.get(norm);
87
+ }
88
+ function getCoreDeckExplainers() {
89
+ return CORE_DECK_IDS.map((id) => BY_ID.get(id)).filter(Boolean);
90
+ }
91
+ var VITALS, SAAS, METRIC_DEFINITIONS, CORE_DECK_IDS, BY_ID, ALIAS_INDEX, VITAL_IDS, SAAS_METRIC_IDS;
92
+ var init_metric_definitions = __esm({
93
+ "src/data/metric-definitions.ts"() {
94
+ "use strict";
95
+ init_metrics_benchmarks();
96
+ VITALS = [
97
+ {
98
+ id: "freshness",
99
+ kind: "vital",
100
+ label: "Freshness",
101
+ group: "Vital Signs",
102
+ tagline: "Is your CRM telling the truth about what's alive?",
103
+ 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.",
104
+ formula_lines: [
105
+ "freshness = people%\xD70.35 + orgs%\xD70.30 + opps%\xD70.35",
106
+ "people/orgs fresh if activity within 90d",
107
+ "opps fresh if activity within 30d AND not past-due"
108
+ ],
109
+ meaning: 'Board question: "how much of this pipeline is real vs fiction?" Dollar value = sum of amount on stale opportunities \u2014 pipeline at risk.',
110
+ 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.",
111
+ deepdive: [
112
+ "Status: green \u226580, yellow \u226560, red below 60 (motion presets can shift windows).",
113
+ 'Dollar translation: sum of amount on stale open opportunities \u2192 "pipeline at risk".',
114
+ "Layer 1 of the gating stack \u2014 a red here bounds what you can trust downstream.",
115
+ "Trigger play: Clean Dead Pipeline (clean-dead-pipeline) when score < 60.",
116
+ "Levers: stale-deal alert at N quiet days, weekly hygiene scrub, enrichment refresh on quiet records, signal-triggered reactivation for paid-for dormant accounts."
117
+ ],
118
+ visual: {
119
+ kind: "bars",
120
+ caption: "Exemplar component mix (higher = fresher)",
121
+ bars: [
122
+ { label: "People", value: 72, tone: "yellow" },
123
+ { label: "Organizations", value: 81, tone: "green" },
124
+ { label: "Opportunities", value: 44, tone: "red" }
125
+ ]
126
+ },
127
+ play_id: "clean-dead-pipeline",
128
+ dollar_label: "pipeline at risk",
129
+ audience: {
130
+ board: "Freshness answers whether the pipeline number is real. Low freshness means forecast risk \u2014 stale deals inflate coverage and hide the true gap.",
131
+ 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."
132
+ },
133
+ aliases: ["data freshness", "stale", "zombie deals", "crm freshness"]
134
+ },
135
+ {
136
+ id: "flow_rate",
137
+ kind: "vital",
138
+ label: "Flow Rate",
139
+ group: "Vital Signs",
140
+ tagline: "How fast do deals actually move \u2014 and where do they die?",
141
+ 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.",
142
+ formula_lines: [
143
+ "base = 100 \xD7 (1 \u2212 avgOpenAge / max_days)",
144
+ "score = base \u2212 stuckSharePenalty (\u226420)",
145
+ "stuck = no update > stuck_days OR past-due close"
146
+ ],
147
+ meaning: 'Board question: "is next quarter slipping because deals are stuck?" Dollar value = amount stuck in pipeline.',
148
+ 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.",
149
+ deepdive: [
150
+ "Status from avg open age: \u226445d green, \u226490d yellow, else red (defaults; max_days 120, stuck_days 60).",
151
+ 'Dollar translation: sum of amount on stuck deals \u2192 "stuck in pipeline".',
152
+ "Layer 2 of the gating stack (with Drop Rate).",
153
+ "Trigger play: Unstick the Pipeline (unstick-pipeline) when score is weak.",
154
+ "Levers: stage-age report, past-due close cleanup, progression plans on stuck deals, forecast hygiene on happy-ears dates."
155
+ ],
156
+ visual: {
157
+ kind: "funnel",
158
+ caption: "Exemplar stage ages \u2014 find the stage where deals go to die",
159
+ funnel: [
160
+ { label: "Discovery", widthPct: 100 },
161
+ { label: "Qualify", widthPct: 78 },
162
+ { label: "Propose", widthPct: 55 },
163
+ { label: "Negotiate", widthPct: 22 },
164
+ { label: "Closed", widthPct: 12 }
165
+ ]
166
+ },
167
+ play_id: "unstick-pipeline",
168
+ dollar_label: "stuck in pipeline",
169
+ audience: {
170
+ 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.",
171
+ ops: "Find the stage with collapsing advancement and age. Clear past-due closes, write progression plans on stuck deals. Play: Unstick the Pipeline."
172
+ },
173
+ aliases: ["flow rate", "deal velocity", "stuck deals", "stuck pipeline"]
174
+ },
175
+ {
176
+ id: "drop_rate",
177
+ kind: "vital",
178
+ label: "Drop Rate",
179
+ group: "Vital Signs",
180
+ tagline: "Where do leads vanish between systems?",
181
+ 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.",
182
+ formula_lines: [
183
+ "score = crossSystemRetention\xD70.6 + oppRetention\xD70.4",
184
+ "cross-system = marketing people also in sales CRM",
185
+ "abandoned = open opps with no activity in 30d"
186
+ ],
187
+ 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.',
188
+ 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.",
189
+ deepdive: [
190
+ "Status: green \u226580, yellow \u226560, red below 60.",
191
+ 'Dollar translation: dropped \xD7 conversion \xD7 avg deal (fallback: drop% \xD7 open pipeline) \u2192 "est. lost at handoff".',
192
+ "Layer 2 of the gating stack (with Flow Rate).",
193
+ "Trigger play: Fix the Handoff Gap (fix-handoff-gap) when drop is high.",
194
+ "Levers: source-level handoff audit, routing + sync repair, time-to-first-touch SLA, weekly marketing-only-leads report."
195
+ ],
196
+ visual: {
197
+ kind: "funnel",
198
+ caption: "Exemplar handoff funnel \u2014 the leak is usually one or two sources",
199
+ funnel: [
200
+ { label: "Marketing leads", widthPct: 100 },
201
+ { label: "In sales CRM", widthPct: 62 },
202
+ { label: "Assigned + touched", widthPct: 41 },
203
+ { label: "Active opportunities", widthPct: 28 }
204
+ ]
205
+ },
206
+ play_id: "fix-handoff-gap",
207
+ dollar_label: "est. lost at handoff",
208
+ audience: {
209
+ 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.",
210
+ ops: "Audit by source, fix routing/sync/dead queues, instrument time-to-first-touch. Play: Fix the Handoff Gap."
211
+ },
212
+ aliases: ["drop rate", "handoff", "handoff gap", "lead leak", "marketing sales handoff"]
213
+ },
214
+ {
215
+ id: "signal_to_noise",
216
+ kind: "vital",
217
+ label: "Signal:Noise",
218
+ group: "Vital Signs",
219
+ tagline: "How much activity is aimed at deals that can still close?",
220
+ 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.",
221
+ formula_lines: [
222
+ "score = (signalCount / activityCount) \xD7 100",
223
+ "signal = linked to open opp / pipeline person / pipeline org",
224
+ "lookback = trailing 90 days"
225
+ ],
226
+ meaning: 'Board question: "are we burning capacity on dead water?" Dollar value = noiseCount \xD7 hours_per_activity \xD7 rep_hourly_cost \u2014 misdirected effort.',
227
+ 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.",
228
+ deepdive: [
229
+ "Status: green \u226565, yellow \u226540, red below 40.",
230
+ "Dollar defaults: 0.25 hours/activity \xD7 $75/hr (config: hours_per_activity, rep_hourly_cost).",
231
+ "Layer 3 of the gating stack \u2014 trust Freshness / Flow / Drop before reading activity efficiency.",
232
+ "Trigger play: Retarget Misdirected Effort (retarget-effort) when score is low.",
233
+ "Levers: refresh account lists, signal-based targeting, stop logging against closed/unlinked records, coverage-model redesign."
234
+ ],
235
+ visual: {
236
+ kind: "split",
237
+ caption: "Exemplar activity mix \u2014 signal vs noise",
238
+ bars: [
239
+ { label: "Signal", value: 38, tone: "green" },
240
+ { label: "Noise", value: 62, tone: "red" }
241
+ ]
242
+ },
243
+ play_id: "retarget-effort",
244
+ dollar_label: "misdirected effort",
245
+ audience: {
246
+ 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.",
247
+ ops: "Score = % of activities linked to live pipeline. Cut by rep and account status; refresh targeting. Play: Retarget Misdirected Effort."
248
+ },
249
+ aliases: ["signal to noise", "signal:noise", "s/n", "activity efficiency", "noise"]
250
+ },
251
+ {
252
+ id: "thread_depth",
253
+ kind: "vital",
254
+ label: "Thread Depth",
255
+ group: "Vital Signs",
256
+ tagline: "How fragile is the pipeline if one champion goes dark?",
257
+ 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).",
258
+ formula_lines: [
259
+ "score = % open deals with \u22652 active people (90d)",
260
+ "people counted via opp contacts + same-org activity",
261
+ "threshold configurable (default 2)"
262
+ ],
263
+ meaning: 'Board question: "how much revenue dies if one contact changes jobs?" Dollar value = sum of amount on single-threaded deals.',
264
+ 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.",
265
+ deepdive: [
266
+ "Status: green \u226565, yellow \u226540, red below 40.",
267
+ 'Dollar translation: sum of amount on single-threaded deals \u2192 "single-threaded".',
268
+ "Layer 4 of the gating stack \u2014 read last, after the upstream vitals.",
269
+ "Trigger play: Multi-Thread Your Deals (multi-thread-deals) when depth is low.",
270
+ "Levers: buying-committee map, warm internal referral first, CRM contact roles, mid-stage single-thread alerts, champion job-change signals."
271
+ ],
272
+ visual: {
273
+ kind: "bars",
274
+ caption: "Exemplar \u2014 multi-threaded vs single-threaded open deals",
275
+ bars: [
276
+ { label: "Multi-threaded", value: 34, tone: "green" },
277
+ { label: "Single-threaded", value: 66, tone: "red" }
278
+ ]
279
+ },
280
+ play_id: "multi-thread-deals",
281
+ dollar_label: "single-threaded",
282
+ audience: {
283
+ 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.",
284
+ 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."
285
+ },
286
+ aliases: ["thread depth", "multithreading", "multi-thread", "single-threaded", "buying committee"]
287
+ }
288
+ ];
289
+ SAAS = [
290
+ // —— Revenue ——
291
+ {
292
+ id: "arr",
293
+ kind: "saas",
294
+ label: "ARR",
295
+ group: "Revenue",
296
+ tagline: "How big is the revenue engine \u2014 and from where?",
297
+ how_computed: "Sum of amount on closed-won opportunities in the dataset (pipeline-inferred ARR when a pure subscription ledger is unavailable).",
298
+ formula_lines: [
299
+ "ARR \u2248 \u03A3 amount on closed-won opportunities",
300
+ "New + Expansion = growth \xB7 Churned + Contraction = leakage"
301
+ ],
302
+ meaning: 'Board question: "how fast are we growing, and from where?" Always decompose growth into new vs expansion \u2014 the mix is the story.',
303
+ 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.",
304
+ deepdive: [
305
+ "Companion metrics: New ARR, Expansion ARR, Churned ARR, Contraction ARR.",
306
+ "Estimation method may be ledger, pipeline_inferred, or snapshot \u2014 read confidence + reliability_gate.",
307
+ "Cross-check with Freshness before trusting ARR growth stories built on zombie deals."
308
+ ],
309
+ visual: {
310
+ kind: "waterfall",
311
+ caption: "Exemplar ARR walk \u2014 growth vs leakage",
312
+ waterfall: [
313
+ { label: "Starting", delta: 100, cumulative: 100 },
314
+ { label: "+ New", delta: 18, cumulative: 118 },
315
+ { label: "+ Expansion", delta: 12, cumulative: 130 },
316
+ { label: "\u2212 Contraction", delta: -4, cumulative: 126 },
317
+ { label: "\u2212 Churned", delta: -8, cumulative: 118 }
318
+ ]
319
+ },
320
+ audience: {
321
+ 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.",
322
+ ops: "Computed as \u03A3 closed-won amounts (pipeline-inferred when no ledger). Decompose into new / expansion / churned / contraction before briefing anyone."
323
+ },
324
+ aliases: ["annual recurring revenue", "revenue"]
325
+ },
326
+ {
327
+ id: "new_arr",
328
+ kind: "saas",
329
+ label: "New ARR",
330
+ group: "Revenue",
331
+ tagline: "How much growth came from brand-new customers?",
332
+ how_computed: "Closed-won tagged New Business, or first closed-won deal per organization when tags are missing.",
333
+ formula_lines: [
334
+ "New ARR = \u03A3 closed-won tagged New Business",
335
+ "fallback: first closed-won deal per organization"
336
+ ],
337
+ meaning: 'Board question: "is growth coming from the top of funnel, or are we farming the base?"',
338
+ expert_read: "Rising New ARR with falling Expansion usually means land-and-expand is underpowered \u2014 packaging or CS motion, not just sales capacity.",
339
+ deepdive: [
340
+ "Pair with Expansion ARR \u2014 the mix tells you which motion is carrying growth.",
341
+ "Tag quality matters: untagged deals fall into the first-deal-per-org heuristic."
342
+ ],
343
+ visual: {
344
+ kind: "bars",
345
+ caption: "Exemplar growth mix",
346
+ bars: [
347
+ { label: "New ARR", value: 60, tone: "accent" },
348
+ { label: "Expansion ARR", value: 40, tone: "green" }
349
+ ]
350
+ },
351
+ audience: {
352
+ board: "New ARR is net-new logos. Read it next to Expansion \u2014 a healthy mix beats a one-sided engine.",
353
+ ops: "Prefer CRM New Business tags; otherwise first closed-won per org. Watch tag hygiene."
354
+ },
355
+ aliases: ["new business arr", "new logo arr"]
356
+ },
357
+ {
358
+ id: "expansion_arr",
359
+ kind: "saas",
360
+ label: "Expansion ARR",
361
+ group: "Revenue",
362
+ tagline: "How much are existing customers buying more?",
363
+ how_computed: "Closed-won tagged Expansion, or later closed-won deals per organization after the first win.",
364
+ formula_lines: [
365
+ "Expansion ARR = \u03A3 closed-won tagged Expansion",
366
+ "fallback: later closed-won deals per organization"
367
+ ],
368
+ meaning: 'Board question: "is the installed base compounding?"',
369
+ 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.",
370
+ deepdive: [
371
+ "Feeds NRR as the upside term.",
372
+ "Compare to Contraction \u2014 net expansion = expansion \u2212 contraction."
373
+ ],
374
+ visual: {
375
+ kind: "bars",
376
+ caption: "Exemplar \u2014 expansion vs contraction",
377
+ bars: [
378
+ { label: "Expansion", value: 70, tone: "green" },
379
+ { label: "Contraction", value: 25, tone: "yellow" }
380
+ ]
381
+ },
382
+ audience: {
383
+ board: "Expansion ARR is installed-base compounding \u2014 the cheapest growth when it works.",
384
+ ops: "Tagged Expansion or subsequent wins per org. Pair with Contraction before celebrating net expansion."
385
+ },
386
+ aliases: ["upsell", "upsell arr", "cross-sell"]
387
+ },
388
+ {
389
+ id: "churned_arr",
390
+ kind: "saas",
391
+ label: "Churned ARR",
392
+ group: "Revenue",
393
+ tagline: "How much revenue walked out the door?",
394
+ 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.",
395
+ formula_lines: [
396
+ "Churned ARR = \u03A3 historical wins for orgs with",
397
+ " no win in trailing 12mo AND no active open opp"
398
+ ],
399
+ meaning: `Board question: "how leaky is the bucket before expansion papers over it?" (with Contraction, this is GRR's downside).`,
400
+ expert_read: "Pipeline-inferred churn is a hypothesis \u2014 confirm with billing status when available. A spike often clusters in one segment or cohort.",
401
+ deepdive: [
402
+ "Feeds GRR and NRR as the churn term.",
403
+ "Cut by segment / motion before treating it as a company-wide PMF problem."
404
+ ],
405
+ visual: {
406
+ kind: "bars",
407
+ caption: "Exemplar leakage mix",
408
+ bars: [
409
+ { label: "Churned", value: 55, tone: "red" },
410
+ { label: "Contraction", value: 30, tone: "yellow" }
411
+ ]
412
+ },
413
+ audience: {
414
+ board: "Churned ARR is full logo loss. With Contraction it sets the floor of the business (GRR).",
415
+ ops: "Heuristic: historical winners with no trailing-12 win and no open opp. Validate against billing when you can."
416
+ },
417
+ aliases: ["churn", "logo churn", "churned revenue"]
418
+ },
419
+ {
420
+ id: "contraction_arr",
421
+ kind: "saas",
422
+ label: "Contraction ARR",
423
+ group: "Revenue",
424
+ tagline: "How much did existing customers buy less?",
425
+ how_computed: "Organizations with \u22652 wins where the latest amount is less than the prior \u2014 sum of the negative deltas.",
426
+ formula_lines: [
427
+ "Contraction = \u03A3 (prior \u2212 latest) where latest < prior",
428
+ "requires \u22652 closed-won deals per organization"
429
+ ],
430
+ meaning: 'Board question: "are we quietly shrinking inside the base while logos stay?"',
431
+ 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.",
432
+ deepdive: [
433
+ "Feeds GRR and NRR.",
434
+ "Needs multi-deal history per org \u2014 thin history understates contraction."
435
+ ],
436
+ visual: {
437
+ kind: "waterfall",
438
+ caption: "Exemplar \u2014 contraction digs into the base",
439
+ waterfall: [
440
+ { label: "Prior", delta: 100, cumulative: 100 },
441
+ { label: "Latest", delta: -18, cumulative: 82 }
442
+ ]
443
+ },
444
+ audience: {
445
+ board: "Contraction is silent shrink inside retained logos \u2014 often packaging or seats, not a cancelled contract.",
446
+ ops: "Requires \u22652 wins per org with a down-round. Pair with Expansion for net expansion."
447
+ },
448
+ aliases: ["downgrade", "seat reduction", "contraction"]
449
+ },
450
+ // —— Retention ——
451
+ {
452
+ id: "nrr",
453
+ kind: "saas",
454
+ label: "Net Revenue Retention",
455
+ group: "Retention",
456
+ tagline: "Would this business grow if sales stopped selling?",
457
+ how_computed: "startingArr = ARR + Churned + Contraction \u2212 Expansion; NRR = ((starting \u2212 Churned \u2212 Contraction + Expansion) / starting) \xD7 100.",
458
+ formula_lines: [
459
+ "starting = ARR + churned + contraction \u2212 expansion",
460
+ "NRR = (starting \u2212 churned \u2212 contraction + expansion) / starting \xD7 100",
461
+ "NRR = 100% + expansion% \u2212 contraction% \u2212 churn%"
462
+ ],
463
+ meaning: 'Board question: "would this business grow if sales stopped selling?" >100% means growing from existing customers.',
464
+ 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.",
465
+ deepdive: [
466
+ "Always show the waterfall: +expansion \u2212contraction \u2212churn.",
467
+ "GRR is the floor; NRR adds expansion on top.",
468
+ "On pipeline-only data, treat as a hypothesis \u2014 check confidence / reliability_gate."
469
+ ],
470
+ visual: {
471
+ kind: "waterfall",
472
+ caption: "Exemplar NRR walk from 100%",
473
+ waterfall: [
474
+ { label: "100%", delta: 100, cumulative: 100 },
475
+ { label: "+ Expansion", delta: 14, cumulative: 114 },
476
+ { label: "\u2212 Contraction", delta: -4, cumulative: 110 },
477
+ { label: "\u2212 Churn", delta: -6, cumulative: 104 }
478
+ ]
479
+ },
480
+ audience: {
481
+ board: "NRR >100% means the base compounds without new logos. Decompose before judging \u2014 same number, different owners.",
482
+ ops: "NRR = 100 + expansion \u2212 contraction \u2212 churn. Motion benchmarks calibrate green/yellow bands. Check reliability_gate on pipeline-inferred data."
483
+ },
484
+ aliases: ["net revenue retention", "net retention", "ndr"],
485
+ benchmarkHint: (motion) => pctBand("nrr", motion)
486
+ },
487
+ {
488
+ id: "grr",
489
+ kind: "saas",
490
+ label: "Gross Revenue Retention",
491
+ group: "Retention",
492
+ tagline: "How leaky is the bucket before expansion papers over it?",
493
+ how_computed: "GRR = ((startingArr \u2212 Churned \u2212 Contraction) / startingArr) \xD7 100 \u2014 expansion is excluded on purpose.",
494
+ formula_lines: [
495
+ "starting = ARR + churned + contraction \u2212 expansion",
496
+ "GRR = (starting \u2212 churned \u2212 contraction) / starting \xD7 100"
497
+ ],
498
+ meaning: 'Board question: "how leaky is the bucket before expansion papers over it?" Prior: >90% healthy, >95% strong for enterprise.',
499
+ expert_read: "GRR is the honesty metric. Expansion can make NRR look fine while GRR is quietly eroding \u2014 always read both.",
500
+ deepdive: [
501
+ "GRR never includes Expansion \u2014 that is the point.",
502
+ "Owners: product/CS for churn, packaging for contraction."
503
+ ],
504
+ visual: {
505
+ kind: "gauge",
506
+ caption: "Exemplar GRR \u2014 floor of the business",
507
+ gauge: 92
508
+ },
509
+ audience: {
510
+ board: "GRR is the floor \u2014 churn + contraction only. Expansion cannot paper over a leaky bucket here.",
511
+ ops: "Exclude Expansion by design. Pair with NRR; diagnose churn vs contraction separately."
512
+ },
513
+ aliases: ["gross revenue retention", "gross retention"],
514
+ benchmarkHint: (motion) => pctBand("grr", motion)
515
+ },
516
+ // —— Pipeline ——
517
+ {
518
+ id: "pipeline_coverage",
519
+ kind: "saas",
520
+ label: "Pipeline Coverage",
521
+ group: "Pipeline",
522
+ tagline: "Is next quarter already at risk?",
523
+ how_computed: "Open pipeline amount \xF7 trailing-90-day closed-won amount.",
524
+ formula_lines: [
525
+ "Coverage = openPipeline / trailing_90d_won",
526
+ "required \u2248 1 / win_rate (discount for time left)"
527
+ ],
528
+ meaning: 'Board question: "is next quarter already at risk?" Priors scale with cycle length: ~3x velocity/SMB, 4\u20135x enterprise.',
529
+ 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.",
530
+ deepdive: [
531
+ "Always pair with Win Rate and Freshness.",
532
+ "Weighted Pipeline is the credibility-adjusted cousin."
533
+ ],
534
+ visual: {
535
+ kind: "gauge",
536
+ caption: "Exemplar coverage vs a 3x target",
537
+ gauge: 72,
538
+ bars: [
539
+ { label: "Open pipeline", value: 75, tone: "accent" },
540
+ { label: "Trailing won (scaled)", value: 25, tone: "neutral" }
541
+ ]
542
+ },
543
+ audience: {
544
+ board: "Coverage answers whether next quarter is already under-piped. Fake coverage from zombies is worse than an honest gap.",
545
+ ops: "open / trailing-90d won. Required \u2248 1/win_rate. Cross-check Freshness before briefing."
546
+ },
547
+ aliases: ["coverage", "pipeline coverage", "pipe coverage"],
548
+ benchmarkHint: (motion) => pctBand("pipeline_coverage", motion)
549
+ },
550
+ {
551
+ id: "weighted_pipeline",
552
+ kind: "saas",
553
+ label: "Weighted Pipeline",
554
+ group: "Pipeline",
555
+ tagline: "What is the pipeline worth after stage probability?",
556
+ how_computed: "Sum of amount \xD7 stage probability for open deals (CRM Probability when present, else stage defaults).",
557
+ formula_lines: [
558
+ "Weighted = \u03A3 (amount \xD7 stageProbability)",
559
+ "trust \u2264 stage discipline deserves"
560
+ ],
561
+ meaning: 'Board question: "what should we actually forecast from open pipe?"',
562
+ expert_read: "Trust it only as much as stage discipline deserves. Inflated late stages make weighted pipeline a fiction.",
563
+ deepdive: [
564
+ "Compare to unweighted open pipeline \u2014 a huge gap means optimistic stages.",
565
+ "Pair with Flow Rate (stuck late stages)."
566
+ ],
567
+ visual: {
568
+ kind: "bars",
569
+ caption: "Exemplar \u2014 open vs weighted",
570
+ bars: [
571
+ { label: "Open pipeline", value: 100, tone: "neutral" },
572
+ { label: "Weighted", value: 42, tone: "accent" }
573
+ ]
574
+ },
575
+ audience: {
576
+ board: "Weighted Pipeline is the credibility-adjusted forecast input \u2014 only as good as stage discipline.",
577
+ ops: "\u03A3 amount \xD7 probability. Audit stage probabilities when weighted << open."
578
+ },
579
+ aliases: ["weighted pipe", "probability-weighted pipeline"]
580
+ },
581
+ {
582
+ id: "pipeline_created",
583
+ kind: "saas",
584
+ label: "Pipeline Created (90d)",
585
+ group: "Pipeline",
586
+ tagline: "How much new pipe did we generate recently?",
587
+ how_computed: "Sum of amounts for opportunities created in the last 90 days.",
588
+ formula_lines: ["Pipeline Created = \u03A3 amount where created_at within 90d"],
589
+ meaning: 'Board question: "is the top of funnel still filling?"',
590
+ expert_read: "Falling created pipeline with flat coverage is a future miss \u2014 coverage is lagging; created is leading.",
591
+ deepdive: [
592
+ "Leading indicator for next-quarter coverage.",
593
+ "Cut by source / segment to find where creation stalled."
594
+ ],
595
+ visual: {
596
+ kind: "bars",
597
+ caption: "Exemplar \u2014 created vs needed",
598
+ bars: [
599
+ { label: "Created (90d)", value: 55, tone: "yellow" },
600
+ { label: "Target pace", value: 80, tone: "green" }
601
+ ]
602
+ },
603
+ audience: {
604
+ board: "Pipeline Created is a leading indicator \u2014 coverage lagging means the miss is already in motion.",
605
+ ops: "\u03A3 amounts on opps created in 90d. Cut by source when it dips."
606
+ },
607
+ aliases: ["pipe gen", "pipeline generation", "created pipeline"]
608
+ },
609
+ {
610
+ id: "pipeline_velocity",
611
+ kind: "saas",
612
+ label: "Pipeline Velocity",
613
+ group: "Pipeline",
614
+ tagline: "Revenue throughput per day \u2014 four levers, one number.",
615
+ how_computed: "(openOpps \xD7 avgDeal \xD7 winRate) / avgCycleDays \u2014 requires \u22653 dated closed-won deals. Unit: $/day.",
616
+ formula_lines: [
617
+ "Velocity = (openOpps \xD7 avgDeal \xD7 winRate) / avgCycleDays",
618
+ "four levers: #opps \xB7 deal size \xB7 win rate \xB7 cycle days"
619
+ ],
620
+ meaning: 'Board question: "which lever moved when throughput changed?" The most decision-ready pipeline metric.',
621
+ expert_read: "When velocity changes, name WHICH lever moved. A win-rate rise on falling opp volume is qualification tightening, not improvement.",
622
+ deepdive: [
623
+ "Needs \u22653 dated wins \u2014 otherwise unavailable.",
624
+ "Pairs with Flow Rate (cycle) and Win Rate (conversion)."
625
+ ],
626
+ visual: {
627
+ kind: "levers",
628
+ caption: "Four levers \u2014 say which one moved",
629
+ levers: ["# Open opps", "Avg deal size", "Win rate", "Cycle days"]
630
+ },
631
+ audience: {
632
+ board: "Velocity is throughput. When it moves, demand the lever \u2014 volume, size, win rate, or cycle \u2014 not a shrug.",
633
+ ops: "(opps \xD7 avgDeal \xD7 winRate) / cycleDays. Diagnose the moved lever before prescribing."
634
+ },
635
+ aliases: ["velocity", "pipeline velocity", "throughput"]
636
+ },
637
+ // —— Sales efficiency ——
638
+ {
639
+ id: "win_rate",
640
+ kind: "saas",
641
+ label: "Win Rate",
642
+ group: "Sales Efficiency",
643
+ tagline: "Of decided deals, how often do we win?",
644
+ how_computed: "closed-won / (won + lost) \xD7 100.",
645
+ formula_lines: ["Win Rate = won / (won + lost) \xD7 100"],
646
+ meaning: 'Board question: "are we converting the pipe we create?" Priors: 25\u201335% SMB, 18\u201325% mid-market, 12\u201318% enterprise on qualified opps.',
647
+ expert_read: "A rising win rate on falling opp volume is qualification tightening, not improvement \u2014 check the denominator.",
648
+ deepdive: [
649
+ "Required coverage \u2248 1 / win rate.",
650
+ "Cut by segment / source before company-wide coaching."
651
+ ],
652
+ visual: {
653
+ kind: "split",
654
+ caption: "Exemplar decided deals",
655
+ bars: [
656
+ { label: "Won", value: 28, tone: "green" },
657
+ { label: "Lost", value: 72, tone: "red" }
658
+ ]
659
+ },
660
+ audience: {
661
+ board: "Win Rate is conversion of decided deals. Rising win rate with falling volume is often tighter qualification, not better selling.",
662
+ ops: "won/(won+lost). Check the denominator. Motion benchmarks set green/yellow bands."
663
+ },
664
+ aliases: ["close rate", "winrate", "win %"],
665
+ benchmarkHint: (motion) => pctBand("win_rate", motion)
666
+ },
667
+ {
668
+ id: "avg_deal_size",
669
+ kind: "saas",
670
+ label: "Avg Deal Size",
671
+ group: "Sales Efficiency",
672
+ tagline: "What does a typical win look like?",
673
+ how_computed: "Mean amount on closed-won opportunities.",
674
+ formula_lines: ["Avg Deal = mean(closed-won amount)"],
675
+ meaning: 'Board question: "are we selling the motion we think we are?"',
676
+ 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.",
677
+ deepdive: [
678
+ "Feeds Pipeline Velocity and LTV proxy.",
679
+ "Cut by segment \u2014 averages hide bimodal motions."
680
+ ],
681
+ visual: {
682
+ kind: "bars",
683
+ caption: "Exemplar \u2014 size mix by segment",
684
+ bars: [
685
+ { label: "SMB", value: 30, tone: "neutral" },
686
+ { label: "Mid-market", value: 55, tone: "accent" },
687
+ { label: "Enterprise", value: 90, tone: "green" }
688
+ ]
689
+ },
690
+ audience: {
691
+ board: "Avg Deal Size should match the motion you claim. Mix shift changes coverage and capacity math.",
692
+ ops: "Mean closed-won amount. Segment before coaching on size."
693
+ },
694
+ aliases: ["average deal size", "asp", "acv"]
695
+ },
696
+ {
697
+ id: "avg_sales_cycle",
698
+ kind: "saas",
699
+ label: "Avg Sales Cycle",
700
+ group: "Sales Efficiency",
701
+ tagline: "How long from create to close on wins?",
702
+ how_computed: "Mean days from created_at to close date on dated closed-won deals.",
703
+ formula_lines: ["Avg Cycle = mean(close_date \u2212 created_at) on dated wins"],
704
+ meaning: 'Board question: "is the cycle stretching \u2014 the earliest soft signal of deal-quality decay?"',
705
+ expert_read: "Cycle stretching past the motion's norm is the earliest soft signal of deal-quality decay. Pair with Flow Rate stuck stages.",
706
+ deepdive: [
707
+ "Feeds Pipeline Velocity as the denominator.",
708
+ "Needs dated wins \u2014 missing close dates understate/omit."
709
+ ],
710
+ visual: {
711
+ kind: "bars",
712
+ caption: "Exemplar cycle vs motion norm",
713
+ bars: [
714
+ { label: "Your cycle", value: 78, tone: "yellow" },
715
+ { label: "Motion norm", value: 55, tone: "green" }
716
+ ]
717
+ },
718
+ audience: {
719
+ board: "Cycle stretch is an early soft signal that quality or process is slipping \u2014 before the miss shows in bookings.",
720
+ ops: "Mean create\u2192close on dated wins. Investigate the stage that aged."
721
+ },
722
+ aliases: ["sales cycle", "cycle length", "time to close"]
723
+ },
724
+ {
725
+ id: "stage_conversion",
726
+ kind: "saas",
727
+ label: "Stage Conversion",
728
+ group: "Sales Efficiency",
729
+ tagline: "Where in the stage model does advancement collapse?",
730
+ how_computed: "From metadata.stage_history stage advances when present; otherwise a win-rate proxy.",
731
+ formula_lines: [
732
+ "Preferred: advancement rates from stage_history",
733
+ "Fallback: win-rate proxy when history is missing"
734
+ ],
735
+ meaning: 'Board question: "which single stage is starving everything downstream?"',
736
+ expert_read: "Find the one stage where conversion collapses \u2014 that's the process problem; everything downstream is starvation.",
737
+ deepdive: [
738
+ "Best with stage_history metadata; otherwise treat as proxy.",
739
+ "Pairs with Flow Rate stage-age cuts."
740
+ ],
741
+ visual: {
742
+ kind: "funnel",
743
+ caption: "Exemplar \u2014 find the collapse",
744
+ funnel: [
745
+ { label: "Stage 1\u21922", widthPct: 100 },
746
+ { label: "Stage 2\u21923", widthPct: 72 },
747
+ { label: "Stage 3\u21924", widthPct: 28 },
748
+ { label: "Stage 4\u2192Close", widthPct: 18 }
749
+ ]
750
+ },
751
+ audience: {
752
+ board: "Stage Conversion names the bottleneck stage \u2014 one collapse starves every stage after it.",
753
+ ops: "Prefer stage_history advances. Fix the collapse stage before coaching downstream reps."
754
+ },
755
+ aliases: ["stage conversion", "stage advance", "conversion by stage"]
756
+ },
757
+ // —— Unit economics ——
758
+ {
759
+ id: "ltv_proxy",
760
+ kind: "saas",
761
+ label: "LTV (Proxy)",
762
+ group: "Unit Economics",
763
+ tagline: "Rough lifetime value from deal size and GRR.",
764
+ how_computed: "avgDeal / ((100 \u2212 GRR) / 100) when GRR < 100. Unavailable when GRR is 100%+ or missing.",
765
+ formula_lines: [
766
+ "LTV \u2248 avgDeal / churnRate",
767
+ "churnRate = (100 \u2212 GRR) / 100 (requires GRR < 100)"
768
+ ],
769
+ meaning: 'Board question: "what is a customer roughly worth over their life?"',
770
+ expert_read: "This is a proxy \u2014 not a cohort LTV. Use it for direction, not capital allocation.",
771
+ deepdive: [
772
+ "Unavailable when GRR \u2265 100 or missing.",
773
+ "Pairs with CAC for LTV:CAC when spend data exists."
774
+ ],
775
+ visual: {
776
+ kind: "gauge",
777
+ caption: "Exemplar LTV proxy (directional)",
778
+ gauge: 68
779
+ },
780
+ audience: {
781
+ board: "LTV Proxy is directional from deal size and GRR \u2014 not a cohort LTV. Use for orientation, not capital decisions.",
782
+ ops: "avgDeal / ((100\u2212GRR)/100). Needs GRR < 100. Prefer cohort math when billing data arrives."
783
+ },
784
+ aliases: ["ltv", "lifetime value"]
785
+ },
786
+ {
787
+ id: "cac",
788
+ kind: "saas",
789
+ label: "CAC",
790
+ group: "Unit Economics",
791
+ tagline: "Customer acquisition cost \u2014 needs spend data.",
792
+ how_computed: "Requires campaign / sales spend data. Currently unavailable on CRM-only datasets.",
793
+ formula_lines: ["CAC = sales & marketing spend / new customers", "(requires spend data \u2014 not in CRM-only exports)"],
794
+ meaning: 'Board question: "what does a new logo cost to win?"',
795
+ expert_read: "Without spend, NTRP cannot invent CAC. Wire campaign spend or finance exports to unlock unit economics.",
796
+ deepdive: [
797
+ "Always unavailable on CRM-only demos \u2014 expected.",
798
+ "Unlocks LTV:CAC, Payback, Magic Number when spend lands."
799
+ ],
800
+ visual: { kind: "none", caption: "Needs campaign spend / finance export" },
801
+ audience: {
802
+ board: "CAC is locked until spend data is connected \u2014 CRM alone cannot price acquisition.",
803
+ ops: "Bring campaign or S&M spend. Until then unit-econ metrics stay unavailable by design."
804
+ },
805
+ aliases: ["customer acquisition cost", "acquisition cost"]
806
+ },
807
+ {
808
+ id: "ltv_cac_ratio",
809
+ kind: "saas",
810
+ label: "LTV:CAC Ratio",
811
+ group: "Unit Economics",
812
+ tagline: "Is acquisition spend earning its keep?",
813
+ how_computed: "LTV proxy \xF7 CAC. Unavailable without spend (CAC).",
814
+ formula_lines: ["LTV:CAC = LTV_proxy / CAC", "(requires CAC)"],
815
+ meaning: 'Board question: "do we earn enough lifetime value per dollar spent to acquire?"',
816
+ 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.",
817
+ deepdive: ["Blocked on CAC. See LTV Proxy and CAC."],
818
+ visual: { kind: "none", caption: "Needs CAC (spend data)" },
819
+ audience: {
820
+ board: "LTV:CAC is the acquisition ROI story \u2014 available once spend is wired.",
821
+ ops: "LTV_proxy / CAC. Unlocks with spend import."
822
+ },
823
+ aliases: ["ltv cac", "ltv/cac", "ltv to cac"]
824
+ },
825
+ {
826
+ id: "payback_months",
827
+ kind: "saas",
828
+ label: "Payback Months",
829
+ group: "Unit Economics",
830
+ tagline: "How many months to recover CAC?",
831
+ how_computed: "Requires CAC / spend. Lower is better.",
832
+ formula_lines: ["Payback \u2248 CAC / (monthly gross profit per customer)", "(requires spend data)"],
833
+ meaning: 'Board question: "how fast does acquisition spend return?" Efficiency era prior: <18 months often healthy.',
834
+ expert_read: "Boards now weigh payback (<18mo) as heavily as growth in many motions.",
835
+ deepdive: ["Blocked on CAC. Benchmarks exist per motion once data lands."],
836
+ visual: { kind: "none", caption: "Needs CAC (spend data)" },
837
+ audience: {
838
+ board: "Payback is how fast CAC returns. Efficiency-era boards often want <18 months.",
839
+ ops: "Requires CAC. Motion green/yellow bands apply when available."
840
+ },
841
+ aliases: ["payback", "cac payback"],
842
+ benchmarkHint: (motion) => monthsBand(motion)
843
+ },
844
+ {
845
+ id: "magic_number",
846
+ kind: "saas",
847
+ label: "Magic Number",
848
+ group: "Unit Economics",
849
+ tagline: "Sales efficiency \u2014 net new ARR per sales dollar.",
850
+ how_computed: "Requires sales spend. Classic form: net new ARR (quarter) / prior-quarter S&M spend.",
851
+ formula_lines: [
852
+ "Magic Number \u2248 Net New ARR(q) / S&M spend(q\u22121)",
853
+ "(requires spend data)"
854
+ ],
855
+ meaning: 'Board question: "how efficiently does sales spend produce net new ARR?" Prior: >0.75 often healthy; >1 strong.',
856
+ expert_read: "Efficiency era: magic number >0.75 is weighed alongside growth. Without spend, NTRP keeps this unavailable rather than inventing it.",
857
+ deepdive: ["Blocked on spend. Benchmarks per motion ready when data lands."],
858
+ visual: { kind: "none", caption: "Needs S&M spend data" },
859
+ audience: {
860
+ board: "Magic Number prices sales efficiency. Available once S&M spend is connected.",
861
+ ops: "Net new ARR / prior S&M. Motion benchmarks apply when spend lands."
862
+ },
863
+ aliases: ["sales magic number", "sales efficiency magic number"],
864
+ benchmarkHint: (motion) => magicBand(motion)
865
+ }
866
+ ];
867
+ METRIC_DEFINITIONS = [...VITALS, ...SAAS];
868
+ CORE_DECK_IDS = [
869
+ "arr",
870
+ "nrr",
871
+ "grr",
872
+ "pipeline_coverage",
873
+ "win_rate",
874
+ "pipeline_velocity",
875
+ "freshness",
876
+ "flow_rate",
877
+ "drop_rate",
878
+ "signal_to_noise",
879
+ "thread_depth"
880
+ ];
881
+ BY_ID = new Map(METRIC_DEFINITIONS.map((m) => [m.id, m]));
882
+ ALIAS_INDEX = (() => {
883
+ const idx = /* @__PURE__ */ new Map();
884
+ for (const m of METRIC_DEFINITIONS) {
885
+ idx.set(m.id.toLowerCase(), m.id);
886
+ idx.set(m.label.toLowerCase(), m.id);
887
+ for (const a of m.aliases ?? []) {
888
+ idx.set(a.toLowerCase(), m.id);
889
+ }
890
+ }
891
+ idx.set("signal-to-noise", "signal_to_noise");
892
+ idx.set("signal:noise", "signal_to_noise");
893
+ idx.set("flow-rate", "flow_rate");
894
+ idx.set("drop-rate", "drop_rate");
895
+ idx.set("thread-depth", "thread_depth");
896
+ return idx;
897
+ })();
898
+ VITAL_IDS = [
899
+ "freshness",
900
+ "flow_rate",
901
+ "drop_rate",
902
+ "signal_to_noise",
903
+ "thread_depth"
904
+ ];
905
+ SAAS_METRIC_IDS = SAAS.map((m) => m.id);
906
+ }
907
+ });
908
+
909
+ // src/output/formatters.ts
910
+ var init_formatters = __esm({
911
+ "src/output/formatters.ts"() {
912
+ "use strict";
913
+ }
914
+ });
915
+
916
+ // src/ui/theme.ts
917
+ import chalk from "chalk";
918
+ function paint(token, text) {
919
+ if (token === "dim") return chalk.dim(text);
920
+ return chalk.hex(TOKENS[token])(text);
921
+ }
922
+ function bold(text) {
923
+ return chalk.bold(text);
924
+ }
925
+ function badge(label, tone = "muted") {
926
+ const normalized = ` ${label.toUpperCase()} `;
927
+ if (tone === "muted") return chalk.dim(normalized);
928
+ const color = BADGE_TONE_COLORS[tone];
929
+ if (chalk.level >= 2) {
930
+ return chalk.bgHex(color).hex(BADGE_TEXT).bold(normalized);
931
+ }
932
+ return chalk.hex(color)(normalized);
933
+ }
934
+ function sectionHeading(label) {
935
+ return `${paint("accent", "\u25B8")} ${paint("accent", bold(label))}`;
936
+ }
937
+ function statusDot(status) {
938
+ if (status === "neutral") return chalk.dim("\u25CB");
939
+ return chalk.hex(STATUS[status])("\u25CF");
940
+ }
941
+ function scoreBar(score, status, width = 14) {
942
+ const filled = Math.round(score / 100 * width);
943
+ const color = chalk.hex(STATUS[status]);
944
+ let filledPart = "";
945
+ for (let i = 0; i < filled; i++) {
946
+ filledPart += i % 2 === 0 ? "\u2588" : "\u2593";
947
+ }
948
+ const emptyPart = "\u2591".repeat(width - filled);
949
+ return color(filledPart) + chalk.dim(emptyPart);
950
+ }
951
+ var STATUS, TOKENS, BADGE_TONE_COLORS, BADGE_TEXT;
952
+ var init_theme = __esm({
953
+ "src/ui/theme.ts"() {
954
+ "use strict";
955
+ init_formatters();
956
+ STATUS = {
957
+ green: "#22c55e",
958
+ yellow: "#eab308",
959
+ red: "#ef4444",
960
+ neutral: "#64748b"
961
+ };
962
+ TOKENS = {
963
+ accent: "#14b8a6",
964
+ accentBright: "#2dd4bf",
965
+ border: "#334155",
966
+ borderMuted: "#1e293b",
967
+ dim: "#64748b",
968
+ text: "#e2e8f0",
969
+ info: "#3b82f6",
970
+ ...STATUS,
971
+ success: STATUS.green,
972
+ warning: STATUS.yellow,
973
+ error: STATUS.red
974
+ };
975
+ BADGE_TONE_COLORS = {
976
+ success: TOKENS.success,
977
+ warning: TOKENS.warning,
978
+ error: TOKENS.error,
979
+ info: TOKENS.info,
980
+ accent: TOKENS.accent
981
+ };
982
+ BADGE_TEXT = "#0f172a";
983
+ }
984
+ });
985
+
986
+ // src/ui/layout.ts
987
+ function stripAnsi(text) {
988
+ return text.replace(ANSI_RE, "");
989
+ }
990
+ function visibleWidth(text) {
991
+ return stripAnsi(text).length;
992
+ }
993
+ function padRight(text, width) {
994
+ const gap = Math.max(0, width - visibleWidth(text));
995
+ return `${text}${" ".repeat(gap)}`;
996
+ }
997
+ function truncateVisible(text, maxVisible, ellipsis = "\u2026") {
998
+ if (visibleWidth(text) <= maxVisible) return text;
999
+ if (maxVisible <= ellipsis.length) return stripAnsi(text).slice(0, maxVisible);
1000
+ const target = maxVisible - ellipsis.length;
1001
+ let visible = 0;
1002
+ let i = 0;
1003
+ let sawAnsi = false;
1004
+ while (i < text.length && visible < target) {
1005
+ if (text[i] === "\x1B") {
1006
+ const match = text.slice(i).match(/^\u001B\[[0-9;]*m/);
1007
+ if (match) {
1008
+ i += match[0].length;
1009
+ sawAnsi = true;
1010
+ continue;
1011
+ }
1012
+ }
1013
+ visible++;
1014
+ i++;
1015
+ }
1016
+ const reset = sawAnsi ? "\x1B[0m" : "";
1017
+ return text.slice(0, i) + reset + ellipsis;
1018
+ }
1019
+ function wrapWords(text, maxW) {
1020
+ const words = text.split(/\s+/).filter(Boolean);
1021
+ const lines = [];
1022
+ let cur = "";
1023
+ for (let word of words) {
1024
+ if (visibleWidth(word) > maxW) {
1025
+ if (cur) {
1026
+ lines.push(cur);
1027
+ cur = "";
1028
+ }
1029
+ word = truncateVisible(word, maxW, maxW > 3 ? "\u2026" : "");
1030
+ }
1031
+ const test = cur ? `${cur} ${word}` : word;
1032
+ if (cur && visibleWidth(test) > maxW) {
1033
+ lines.push(cur);
1034
+ cur = word;
1035
+ } else {
1036
+ cur = test;
1037
+ }
1038
+ }
1039
+ if (cur) lines.push(cur);
1040
+ return lines.length ? lines : [""];
1041
+ }
1042
+ function termWidth() {
1043
+ return process.stdout.columns && process.stdout.columns > 0 ? process.stdout.columns : 80;
1044
+ }
1045
+ function resolveCardWidth(opts = {}) {
1046
+ const { min = 60, max = 100, margin = 4 } = opts;
1047
+ const usable = Math.max(20, termWidth() - margin);
1048
+ return Math.max(Math.min(min, usable), Math.min(usable, max));
1049
+ }
1050
+ var ANSI_RE;
1051
+ var init_layout = __esm({
1052
+ "src/ui/layout.ts"() {
1053
+ "use strict";
1054
+ ANSI_RE = /\u001b\[[0-9;]*m/g;
1055
+ }
1056
+ });
1057
+
1058
+ // src/ui/slides.ts
1059
+ import chalk2 from "chalk";
1060
+ function slideCardWidth() {
1061
+ return resolveCardWidth({ min: 64, max: 100, margin: 4 });
1062
+ }
1063
+ function tonePaint(tone = "accent") {
1064
+ switch (tone) {
1065
+ case "green":
1066
+ return chalk2.hex("#22c55e");
1067
+ case "yellow":
1068
+ return chalk2.hex("#eab308");
1069
+ case "red":
1070
+ return chalk2.hex("#ef4444");
1071
+ case "neutral":
1072
+ return chalk2.dim;
1073
+ default:
1074
+ return (t) => paint("accent", t);
1075
+ }
1076
+ }
1077
+ function renderBarRow(bar, barWidth, labelW) {
1078
+ const fill = Math.max(0, Math.min(barWidth, Math.round(bar.value / 100 * barWidth)));
1079
+ const body = "\u2588".repeat(fill) + "\u2591".repeat(barWidth - fill);
1080
+ const colored = tonePaint(bar.tone)(body);
1081
+ const label = padRight(truncateVisible(bar.label, labelW), labelW);
1082
+ const pct = String(Math.round(bar.value)).padStart(3);
1083
+ return `${label} ${colored} ${chalk2.dim(pct)}`;
1084
+ }
1085
+ function renderBars(bars, inner) {
1086
+ const labelW = Math.min(18, Math.max(...bars.map((b) => visibleWidth(b.label)), 8));
1087
+ const barWidth = Math.max(8, Math.min(28, inner - labelW - 6));
1088
+ return bars.map((b) => renderBarRow(b, barWidth, labelW));
1089
+ }
1090
+ function renderFunnel(steps, inner) {
1091
+ const maxBar = Math.max(12, Math.min(40, inner - 22));
1092
+ const lines = [];
1093
+ for (const step of steps) {
1094
+ const w = Math.max(2, Math.round(step.widthPct / 100 * maxBar));
1095
+ const bar = paint("accent", "\u2588".repeat(w));
1096
+ const label = truncateVisible(step.label, Math.max(8, inner - maxBar - 8));
1097
+ lines.push(`${padRight(label, Math.min(18, inner - maxBar - 6))} ${bar} ${chalk2.dim(`${step.widthPct}%`)}`);
1098
+ }
1099
+ return lines;
1100
+ }
1101
+ function renderWaterfall(steps, inner) {
1102
+ const maxAbs = Math.max(...steps.map((s) => Math.abs(s.cumulative)), 1);
1103
+ const barW = Math.max(10, Math.min(28, inner - 28));
1104
+ const lines = [];
1105
+ for (const step of steps) {
1106
+ const fill = Math.max(1, Math.round(Math.abs(step.cumulative) / maxAbs * barW));
1107
+ const bar = step.delta >= 0 ? chalk2.hex("#22c55e")("\u2588".repeat(fill)) : chalk2.hex("#ef4444")("\u2588".repeat(fill));
1108
+ const deltaStr = step.delta > 0 ? `+${step.delta}` : step.delta < 0 ? `${step.delta}` : `${step.delta}`;
1109
+ const deltaPainted = step.delta > 0 ? chalk2.hex("#22c55e")(deltaStr.padStart(5)) : step.delta < 0 ? chalk2.hex("#ef4444")(deltaStr.padStart(5)) : chalk2.dim(deltaStr.padStart(5));
1110
+ const label = padRight(truncateVisible(step.label, 14), 14);
1111
+ lines.push(`${label} ${deltaPainted} ${bar} ${chalk2.dim(`\u2192 ${step.cumulative}`)}`);
1112
+ }
1113
+ return lines;
1114
+ }
1115
+ function renderLayerStack(layers, inner) {
1116
+ const lines = [];
1117
+ for (let i = 0; i < layers.length; i++) {
1118
+ const layer = layers[i];
1119
+ const marker = layer.highlight ? paint("accent", "\u25C6") : chalk2.dim("\u25C7");
1120
+ const text = layer.highlight ? bold(layer.label) : chalk2.dim(layer.label);
1121
+ lines.push(`${marker} ${truncateVisible(text, inner - 4)}`);
1122
+ if (i < layers.length - 1) {
1123
+ lines.push(chalk2.dim(" \u2502"));
1124
+ }
1125
+ }
1126
+ return lines;
1127
+ }
1128
+ function renderLevers(levers, inner) {
1129
+ const cell = Math.floor((inner - 9) / 2);
1130
+ const lines = [];
1131
+ lines.push(chalk2.dim("\u250C" + "\u2500".repeat(Math.max(8, cell)) + "\u2510 \u250C" + "\u2500".repeat(Math.max(8, cell)) + "\u2510"));
1132
+ for (let i = 0; i < levers.length; i += 2) {
1133
+ const a = padRight(truncateVisible(levers[i] ?? "", cell - 2), cell - 2);
1134
+ const b = padRight(truncateVisible(levers[i + 1] ?? "", cell - 2), cell - 2);
1135
+ lines.push(
1136
+ `${paint("accent", "\u2502")} ${a} ${paint("accent", "\u2502")} ${paint("accent", "\u2502")} ${b} ${paint("accent", "\u2502")}`
1137
+ );
1138
+ }
1139
+ lines.push(chalk2.dim("\u2514" + "\u2500".repeat(Math.max(8, cell)) + "\u2518 \u2514" + "\u2500".repeat(Math.max(8, cell)) + "\u2518"));
1140
+ return lines;
1141
+ }
1142
+ function renderGauge(score, inner, status) {
1143
+ const st = status ?? (score >= 80 ? "green" : score >= 60 ? "yellow" : "red");
1144
+ const bar = scoreBar(score, st === "neutral" ? "yellow" : st, Math.min(28, inner - 12));
1145
+ return [`${statusDot(st)} ${bar} ${bold(String(Math.round(score)))}`];
1146
+ }
1147
+ function renderSplit(bars, inner) {
1148
+ if (bars.length < 2) return renderBars(bars, inner);
1149
+ const total = bars.reduce((s, b) => s + b.value, 0) || 100;
1150
+ const width = Math.max(16, Math.min(40, inner - 4));
1151
+ let used = 0;
1152
+ const parts = [];
1153
+ for (let i = 0; i < bars.length; i++) {
1154
+ const b = bars[i];
1155
+ const w = i === bars.length - 1 ? width - used : Math.max(1, Math.round(b.value / total * width));
1156
+ used += w;
1157
+ parts.push(tonePaint(b.tone)("\u2588".repeat(w)));
1158
+ }
1159
+ const legend = bars.map((b) => `${tonePaint(b.tone)("\u25CF")} ${b.label} ${chalk2.dim(`${Math.round(b.value)}%`)}`).join(" ");
1160
+ return [parts.join(""), truncateVisible(legend, inner)];
1161
+ }
1162
+ function renderVisual(visual, inner) {
1163
+ const lines = [];
1164
+ switch (visual.kind) {
1165
+ case "bars":
1166
+ if (visual.bars?.length) lines.push(...renderBars(visual.bars, inner));
1167
+ break;
1168
+ case "funnel":
1169
+ if (visual.funnel?.length) lines.push(...renderFunnel(visual.funnel, inner));
1170
+ break;
1171
+ case "waterfall":
1172
+ if (visual.waterfall?.length) lines.push(...renderWaterfall(visual.waterfall, inner));
1173
+ break;
1174
+ case "layer_stack":
1175
+ if (visual.layers?.length) lines.push(...renderLayerStack(visual.layers, inner));
1176
+ break;
1177
+ case "levers":
1178
+ if (visual.levers?.length) lines.push(...renderLevers(visual.levers, inner));
1179
+ break;
1180
+ case "gauge":
1181
+ lines.push(...renderGauge(visual.gauge ?? 50, inner));
1182
+ if (visual.bars?.length) lines.push(...renderBars(visual.bars, inner));
1183
+ break;
1184
+ case "split":
1185
+ if (visual.bars?.length) lines.push(...renderSplit(visual.bars, inner));
1186
+ break;
1187
+ case "none":
1188
+ default:
1189
+ break;
1190
+ }
1191
+ if (visual.caption) {
1192
+ lines.push(chalk2.dim(truncateVisible(visual.caption, inner)));
1193
+ }
1194
+ return lines;
1195
+ }
1196
+ function kindBadge(explainer) {
1197
+ if (explainer.kind === "vital") return badge("VITAL", "accent");
1198
+ return badge("SAAS", "info");
1199
+ }
1200
+ function statusToTone(status) {
1201
+ if (status === "green") return "success";
1202
+ if (status === "yellow") return "warning";
1203
+ if (status === "red") return "error";
1204
+ return "muted";
1205
+ }
1206
+ function pushWrapped(out, text, inner, indent = "") {
1207
+ for (const w of wrapWords(text, inner - indent.length)) {
1208
+ out.push(indent + w);
1209
+ }
1210
+ }
1211
+ function buildSlideContent(explainer, opts = {}) {
1212
+ const width = slideCardWidth();
1213
+ const inner = width - 4;
1214
+ const lines = [];
1215
+ const title = opts.titleOverride ?? (explainer ? explainer.label : "Metrics");
1216
+ if (explainer) {
1217
+ const headerBits = [
1218
+ kindBadge(explainer),
1219
+ chalk2.dim(explainer.group)
1220
+ ];
1221
+ if (opts.index != null && opts.total != null) {
1222
+ headerBits.push(chalk2.dim(`slide ${opts.index}/${opts.total}`));
1223
+ }
1224
+ lines.push(headerBits.join(chalk2.dim(" \xB7 ")));
1225
+ lines.push(chalk2.dim(explainer.tagline));
1226
+ lines.push("");
1227
+ if (opts.live) {
1228
+ const live = opts.live;
1229
+ const tone = statusToTone(live.status);
1230
+ const liveLine = `${statusDot(live.status)} ${bold("Your reading:")} ${bold(live.formatted)} ` + badge(String(live.status), tone);
1231
+ lines.push(truncateVisible(liveLine, inner));
1232
+ if (live.dollarLine) {
1233
+ lines.push(chalk2.dim(` $ ${live.dollarLine}`));
1234
+ }
1235
+ if (live.benchmarkNote) {
1236
+ lines.push(chalk2.dim(` ${live.benchmarkNote}`));
1237
+ }
1238
+ lines.push("");
1239
+ } else {
1240
+ const hint = explainer.benchmarkHint?.(opts.motion);
1241
+ if (hint) {
1242
+ lines.push(chalk2.dim(`Benchmark \xB7 ${hint}`));
1243
+ lines.push("");
1244
+ }
1245
+ }
1246
+ const visual = opts.visualOverride ?? explainer.visual;
1247
+ const visLines = renderVisual(visual, inner);
1248
+ if (visLines.length) {
1249
+ lines.push(...visLines);
1250
+ lines.push("");
1251
+ }
1252
+ lines.push(sectionHeading("What it means"));
1253
+ pushWrapped(lines, explainer.meaning, inner, " ");
1254
+ lines.push("");
1255
+ if (!opts.skipFormula) {
1256
+ lines.push(sectionHeading("How it's calculated"));
1257
+ pushWrapped(lines, explainer.how_computed, inner, " ");
1258
+ for (const f of explainer.formula_lines) {
1259
+ lines.push(paint("accent", ` ${f}`));
1260
+ }
1261
+ lines.push("");
1262
+ }
1263
+ if (opts.deepdive) {
1264
+ lines.push(sectionHeading("Deep dive"));
1265
+ pushWrapped(lines, explainer.expert_read, inner, " ");
1266
+ lines.push("");
1267
+ for (const bullet of explainer.deepdive) {
1268
+ pushWrapped(lines, `\xB7 ${bullet}`, inner, " ");
1269
+ }
1270
+ if (explainer.play_id) {
1271
+ lines.push("");
1272
+ lines.push(
1273
+ chalk2.dim(" Play: ") + paint("accent", explainer.play_id)
1274
+ );
1275
+ }
1276
+ lines.push("");
1277
+ }
1278
+ }
1279
+ if (opts.extraLines?.length) {
1280
+ for (const line of opts.extraLines) {
1281
+ if (line === "") lines.push("");
1282
+ else pushWrapped(lines, line, inner);
1283
+ }
1284
+ }
1285
+ return { title, lines, width, inner };
1286
+ }
1287
+ function renderMetricSlide(explainer, opts = {}) {
1288
+ const { title, lines, width, inner } = buildSlideContent(explainer, opts);
1289
+ const border = (s) => paint("border", s);
1290
+ const termW = termWidth();
1291
+ const outerPad = " ".repeat(Math.max(0, Math.floor((termW - width) / 2)));
1292
+ const out = [];
1293
+ out.push("");
1294
+ out.push(`${outerPad}${border(`\u256D${"\u2500".repeat(width - 2)}\u256E`)}`);
1295
+ out.push(
1296
+ `${outerPad}${border("\u2502 ")}${padRight(sectionHeading(title), inner)}${border(" \u2502")}`
1297
+ );
1298
+ out.push(`${outerPad}${border(`\u251C${"\u2500".repeat(width - 2)}\u2524`)}`);
1299
+ for (const row of lines) {
1300
+ out.push(
1301
+ `${outerPad}${border("\u2502 ")}${padRight(truncateVisible(row, inner), inner)}${border(" \u2502")}`
1302
+ );
1303
+ }
1304
+ const footer = opts.footer ?? (opts.deepdive ? `\u23CE next \xB7 b back \xB7 q quit` : `\u23CE next \xB7 /deepdive more \xB7 b back \xB7 q quit`);
1305
+ out.push(`${outerPad}${border(`\u251C${"\u2500".repeat(width - 2)}\u2524`)}`);
1306
+ out.push(
1307
+ `${outerPad}${border("\u2502 ")}${padRight(chalk2.dim(truncateVisible(footer, inner)), inner)}${border(" \u2502")}`
1308
+ );
1309
+ out.push(`${outerPad}${border(`\u2570${"\u2500".repeat(width - 2)}\u256F`)}`);
1310
+ out.push("");
1311
+ if (opts.asLines) return out;
1312
+ for (const line of out) console.log(line);
1313
+ }
1314
+ function measureSlideWidth(lines) {
1315
+ return Math.max(0, ...lines.map(visibleWidth));
1316
+ }
1317
+ var init_slides = __esm({
1318
+ "src/ui/slides.ts"() {
1319
+ "use strict";
1320
+ init_theme();
1321
+ init_layout();
1322
+ }
1323
+ });
1324
+
1325
+ // src/ai/llm/thread-compat.ts
1326
+ var init_thread_compat = __esm({
1327
+ "src/ai/llm/thread-compat.ts"() {
1328
+ "use strict";
1329
+ }
1330
+ });
1331
+
1332
+ // src/io/context.ts
1333
+ var init_context = __esm({
1334
+ "src/io/context.ts"() {
1335
+ "use strict";
1336
+ }
1337
+ });
1338
+
1339
+ // src/config/store.ts
1340
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
1341
+ import { homedir } from "os";
1342
+ import { join, resolve } from "path";
1343
+ function ntrpHome() {
1344
+ return NTRP_DIR;
1345
+ }
1346
+ function ensureDir() {
1347
+ if (!existsSync(NTRP_DIR)) {
1348
+ mkdirSync(NTRP_DIR, { recursive: true });
1349
+ }
1350
+ }
1351
+ function loadConfig() {
1352
+ if (cachedConfig) return cachedConfig;
1353
+ ensureDir();
1354
+ if (!existsSync(CONFIG_PATH)) {
1355
+ cachedConfig = {};
1356
+ return cachedConfig;
1357
+ }
1358
+ try {
1359
+ cachedConfig = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
1360
+ } catch {
1361
+ cachedConfig = {};
1362
+ }
1363
+ return cachedConfig;
1364
+ }
1365
+ function saveConfig(config) {
1366
+ ensureDir();
1367
+ writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n");
1368
+ cachedConfig = config;
1369
+ }
1370
+ function getConfigValue(key) {
1371
+ if (key === "api-key") return loadConfig()["api-key"];
1372
+ if (key === "license-key") return process.env.NTRP_LICENSE_KEY ?? loadConfig()["license-key"];
1373
+ const config = loadConfig();
1374
+ return config[key];
1375
+ }
1376
+ function setConfigValue(key, value) {
1377
+ const config = loadConfig();
1378
+ config[key] = value;
1379
+ saveConfig(config);
1380
+ }
1381
+ function deleteConfigValue(key) {
1382
+ const config = loadConfig();
1383
+ delete config[key];
1384
+ saveConfig(config);
1385
+ }
1386
+ var NTRP_DIR, CONFIG_PATH, cachedConfig;
1387
+ var init_store = __esm({
1388
+ "src/config/store.ts"() {
1389
+ "use strict";
1390
+ NTRP_DIR = process.env.NTRP_HOME ? resolve(process.env.NTRP_HOME) : join(homedir(), ".ntrp");
1391
+ CONFIG_PATH = join(NTRP_DIR, "config.json");
1392
+ cachedConfig = null;
1393
+ }
1394
+ });
1395
+
1396
+ // src/output/path-safety.ts
1397
+ import { homedir as homedir2 } from "os";
1398
+ import { resolve as resolve2, sep } from "path";
1399
+ var NTRP_HOME;
1400
+ var init_path_safety = __esm({
1401
+ "src/output/path-safety.ts"() {
1402
+ "use strict";
1403
+ init_store();
1404
+ NTRP_HOME = ntrpHome();
1405
+ }
1406
+ });
1407
+
1408
+ // src/services/exports-registry.ts
1409
+ import {
1410
+ appendFileSync,
1411
+ copyFileSync,
1412
+ cpSync,
1413
+ existsSync as existsSync2,
1414
+ mkdirSync as mkdirSync2,
1415
+ readFileSync as readFileSync2,
1416
+ readdirSync,
1417
+ renameSync,
1418
+ rmSync,
1419
+ statSync,
1420
+ writeFileSync as writeFileSync2
1421
+ } from "fs";
1422
+ import { basename, dirname, join as join2, resolve as resolve3, sep as sep2 } from "path";
1423
+ import { randomUUID } from "crypto";
1424
+ var init_exports_registry = __esm({
1425
+ "src/services/exports-registry.ts"() {
1426
+ "use strict";
1427
+ init_store();
1428
+ init_path_safety();
1429
+ }
1430
+ });
1431
+
1432
+ // src/services/terminal-capture.ts
1433
+ var init_terminal_capture = __esm({
1434
+ "src/services/terminal-capture.ts"() {
1435
+ "use strict";
1436
+ }
1437
+ });
1438
+
1439
+ // src/services/context-doc.ts
1440
+ import { writeFileSync as writeFileSync3 } from "fs";
1441
+ var init_context_doc = __esm({
1442
+ "src/services/context-doc.ts"() {
1443
+ "use strict";
1444
+ init_context2();
1445
+ init_formatters();
1446
+ init_store();
1447
+ init_exports_registry();
1448
+ init_terminal_capture();
1449
+ }
1450
+ });
1451
+
1452
+ // src/services/transcript.ts
1453
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4, rmSync as rmSync2 } from "fs";
1454
+ import { join as join3 } from "path";
1455
+ var init_transcript = __esm({
1456
+ "src/services/transcript.ts"() {
1457
+ "use strict";
1458
+ init_context2();
1459
+ init_terminal_capture();
1460
+ }
1461
+ });
1462
+
1463
+ // src/cli/context.ts
1464
+ import { basename as basename2, join as join4, resolve as resolve4, sep as sep3 } from "path";
1465
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, rmSync as rmSync3 } from "fs";
1466
+ import { homedir as homedir3 } from "os";
1467
+ import { randomUUID as randomUUID2 } from "crypto";
1468
+ function ntrpHomeDir() {
1469
+ return process.env.NTRP_HOME ? resolve4(process.env.NTRP_HOME) : join4(homedir3(), ".ntrp");
1470
+ }
1471
+ function getSessionsDir() {
1472
+ const dir = join4(ntrpHomeDir(), "sessions");
1473
+ if (!existsSync4(dir)) {
1474
+ mkdirSync3(dir, { recursive: true });
1475
+ }
1476
+ return dir;
1477
+ }
1478
+ function isValidSessionId(id) {
1479
+ return SESSION_ID_RE.test(id);
1480
+ }
1481
+ function listSessions(opts) {
1482
+ const dir = getSessionsDir();
1483
+ const entries = [];
1484
+ try {
1485
+ const files = readdirSync2(dir).filter((name) => name.endsWith(".json")).map((name) => {
1486
+ const filePath = join4(dir, name);
1487
+ return { name, filePath, mtime: statSync2(filePath).mtimeMs };
1488
+ }).sort((a, b) => b.mtime - a.mtime);
1489
+ const filesToRead = opts?.limit ? files.slice(0, opts.limit) : files;
1490
+ for (const { name, filePath, mtime } of filesToRead) {
1491
+ const id = basename2(name, ".json");
1492
+ if (!isValidSessionId(id)) continue;
1493
+ try {
1494
+ const raw = readFileSync4(filePath, "utf-8");
1495
+ const session = JSON.parse(raw);
1496
+ entries.push({
1497
+ id,
1498
+ created_at: session.created_at,
1499
+ ended_at: session.ended_at,
1500
+ exchange_count: session.exchange_count ?? Math.floor(session.messages.length / 2),
1501
+ summary: session.summary,
1502
+ name: session.name,
1503
+ stage: session.stage,
1504
+ dataset: session.dataset,
1505
+ deliverables: session.deliverables,
1506
+ analysis: session.analysis,
1507
+ scope: session.scope,
1508
+ mtime
1509
+ });
1510
+ } catch {
1511
+ }
1512
+ }
1513
+ } catch {
1514
+ return [];
1515
+ }
1516
+ entries.sort((a, b) => b.mtime - a.mtime);
1517
+ if (opts?.limit) return entries.slice(0, opts.limit);
1518
+ return entries;
1519
+ }
1520
+ var STALE_SESSION_MS, SESSION_ID_RE;
1521
+ var init_context2 = __esm({
1522
+ "src/cli/context.ts"() {
1523
+ "use strict";
1524
+ init_thread_compat();
1525
+ init_context();
1526
+ init_context_doc();
1527
+ init_transcript();
1528
+ STALE_SESSION_MS = 14 * 24 * 60 * 60 * 1e3;
1529
+ SESSION_ID_RE = /^\d{4}-\d{2}-\d{2}-[a-f0-9]{4}$/i;
1530
+ }
1531
+ });
1532
+
1533
+ // src/config/profile.ts
1534
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync6, existsSync as existsSync5, mkdirSync as mkdirSync4 } from "fs";
1535
+ import { join as join5 } from "path";
1536
+ var NTRP_DIR2, PROFILE_PATH;
1537
+ var init_profile = __esm({
1538
+ "src/config/profile.ts"() {
1539
+ "use strict";
1540
+ init_store();
1541
+ NTRP_DIR2 = ntrpHome();
1542
+ PROFILE_PATH = join5(NTRP_DIR2, "profile.json");
1543
+ }
1544
+ });
1545
+
1546
+ // src/conversation/keyless-definitions.ts
1547
+ import chalk3 from "chalk";
1548
+ function isPossessiveMetricAsk(input) {
1549
+ return POSSESSIVE_RE.test(input.trim());
1550
+ }
1551
+ function isDefinitionAsk(input) {
1552
+ const line = input.trim();
1553
+ if (!line) return false;
1554
+ if (isPossessiveMetricAsk(line)) return false;
1555
+ return DEFINITION_RE.test(line) || MEAN_RE.test(line);
1556
+ }
1557
+ function extractDefinitionQuery(input) {
1558
+ const line = input.trim().replace(/[?.!]+$/, "");
1559
+ const mean = line.match(MEAN_RE);
1560
+ if (mean?.[1]) return cleanQuery(mean[1]);
1561
+ const how = line.match(HOW_CALC_RE);
1562
+ if (how?.[1]) return cleanQuery(how[1]);
1563
+ const what = line.match(WHAT_IS_RE);
1564
+ if (what?.[1]) return cleanQuery(what[1]);
1565
+ return void 0;
1566
+ }
1567
+ function cleanQuery(raw) {
1568
+ return raw.replace(/^(?:a|an|the|our|my)\s+/i, "").replace(/\b(metric|score|number|vital(?:\s+sign)?|kpi)\b/gi, "").replace(/\s+/g, " ").trim();
1569
+ }
1570
+ function matchDefinitionExplainer(input) {
1571
+ if (!isDefinitionAsk(input)) return void 0;
1572
+ const query = extractDefinitionQuery(input);
1573
+ if (!query) return void 0;
1574
+ const id = resolveMetricId(query);
1575
+ if (!id) {
1576
+ const tokens = query.split(/\s+/);
1577
+ for (let n = tokens.length; n >= 1; n--) {
1578
+ for (let i = 0; i + n <= tokens.length; i++) {
1579
+ const slice = tokens.slice(i, i + n).join(" ");
1580
+ const hit = resolveMetricId(slice);
1581
+ if (hit) return getMetricExplainer(hit);
1582
+ }
1583
+ }
1584
+ return void 0;
1585
+ }
1586
+ return getMetricExplainer(id);
1587
+ }
1588
+ var POSSESSIVE_RE, DEFINITION_RE, MEAN_RE, HOW_CALC_RE, WHAT_IS_RE;
1589
+ var init_keyless_definitions = __esm({
1590
+ "src/conversation/keyless-definitions.ts"() {
1591
+ "use strict";
1592
+ init_context2();
1593
+ init_profile();
1594
+ init_metric_definitions();
1595
+ init_theme();
1596
+ init_layout();
1597
+ POSSESSIVE_RE = /\b(our|my|we|us|the company'?s|this (company|business|org|pipeline)|current|actual|latest)\b/i;
1598
+ DEFINITION_RE = /^(?:(?:please|can you|could you)\s+)?(?:what\s+(?:is|are|does)|what'?s|whats|define|explain|describe|how\s+(?:is|are|do(?:es)?)\s+(?:.+?\s+)?(?:calculated|computed|measured|defined)|how\s+do(?:es)?\s+(?:.+?\s+)?(?:work|get calculated)|tell me about|meaning of)\b/i;
1599
+ MEAN_RE = /\bwhat does\b(.+?)\bmean\b/i;
1600
+ HOW_CALC_RE = /\bhow (?:is|are|do(?:es)?)\b(.+?)\b(?:calculated|computed|measured|defined|work)\b/i;
1601
+ WHAT_IS_RE = /\b(?:what(?:'s|s)?|define|explain|describe|tell me about|meaning of)\s+(.+?)(?:\?|$)/i;
1602
+ }
1603
+ });
1604
+
1605
+ // src/services/metric-explainers.ts
1606
+ function normalizeAudience(audience) {
1607
+ if (!audience) return "board";
1608
+ const a = String(audience).toLowerCase();
1609
+ if (a === "ops" || a === "operations" || a === "operator" || a === "team") {
1610
+ return "ops";
1611
+ }
1612
+ return "board";
1613
+ }
1614
+ function audienceLabel(audience) {
1615
+ return audience === "ops" ? "ops" : "board / exec";
1616
+ }
1617
+ function statusRankFrom(status) {
1618
+ if (status === "red") return 0;
1619
+ if (status === "yellow") return 1;
1620
+ if (status === "green") return 2;
1621
+ return 3;
1622
+ }
1623
+ function collectCandidates(bundle, opts) {
1624
+ const prefer = new Set(opts.prefer ?? []);
1625
+ const map = /* @__PURE__ */ new Map();
1626
+ const upsert = (id, priority, status) => {
1627
+ if (!getMetricExplainer(id)) return;
1628
+ const existing = map.get(id);
1629
+ const rank = statusRankFrom(status);
1630
+ if (!existing) {
1631
+ map.set(id, { id, priority, statusRank: rank });
1632
+ return;
1633
+ }
1634
+ existing.priority = Math.min(existing.priority, priority);
1635
+ existing.statusRank = Math.min(existing.statusRank, rank);
1636
+ };
1637
+ const health = bundle?.diagnosis?.health;
1638
+ const fromDiag = opts.vitals ?? health?.vital_signs ?? [];
1639
+ const gating = opts.prefer?.[0] ?? health?.gating_vital_sign;
1640
+ if (gating) upsert(String(gating), 0, "red");
1641
+ for (const vs of fromDiag) {
1642
+ const id = vs.vital_sign;
1643
+ upsert(id, prefer.has(id) ? 0 : 1, vs.status);
1644
+ }
1645
+ const rawMetrics = opts.metrics ?? bundle?.metrics?.metrics ?? [];
1646
+ let sawMetrics = rawMetrics.length > 0;
1647
+ for (const row of rawMetrics) {
1648
+ const id = String(row.metric ?? row.metric ?? "");
1649
+ if (!id) continue;
1650
+ const status = String(row.status ?? row.status ?? "");
1651
+ const value = row.value ?? row.value;
1652
+ const unavailable = row.unavailable_reason ?? row.unavailable_reason;
1653
+ if (value == null && unavailable) continue;
1654
+ upsert(id, prefer.has(id) ? 0 : 2, status);
1655
+ }
1656
+ if (sawMetrics || bundle?.metrics) {
1657
+ for (const id of ["arr", "nrr", "pipeline_coverage", "win_rate"]) {
1658
+ if (!map.has(id) && getMetricExplainer(id)) {
1659
+ upsert(id, 3, "neutral");
1660
+ }
1661
+ }
1662
+ }
1663
+ if (map.size === 0) {
1664
+ for (const id of ["freshness", "flow_rate", "drop_rate", "signal_to_noise", "thread_depth"]) {
1665
+ upsert(id, 4, "neutral");
1666
+ }
1667
+ }
1668
+ return [...map.values()].sort((a, b) => {
1669
+ if (a.priority !== b.priority) return a.priority - b.priority;
1670
+ if (a.statusRank !== b.statusRank) return a.statusRank - b.statusRank;
1671
+ return a.id.localeCompare(b.id);
1672
+ });
1673
+ }
1674
+ function formatEntry(explainer, audience) {
1675
+ const framing = audience === "ops" ? explainer.audience.ops : explainer.audience.board;
1676
+ const lines = [];
1677
+ lines.push(`### ${explainer.label} (\`${explainer.id}\`)`);
1678
+ lines.push("");
1679
+ lines.push(framing);
1680
+ lines.push("");
1681
+ if (audience === "ops") {
1682
+ lines.push("**How it's calculated**");
1683
+ lines.push("");
1684
+ for (const f of explainer.formula_lines) {
1685
+ lines.push(`- \`${f}\``);
1686
+ }
1687
+ lines.push("");
1688
+ } else {
1689
+ lines.push(`*${explainer.tagline}*`);
1690
+ lines.push("");
1691
+ }
1692
+ return lines;
1693
+ }
1694
+ function buildDefinitionsAppendix(bundle, opts = {}) {
1695
+ const audience = normalizeAudience(opts.audience);
1696
+ const cap = opts.cap ?? DEFAULT_CAP;
1697
+ const candidates = collectCandidates(bundle, opts).slice(0, cap);
1698
+ if (candidates.length === 0) return "";
1699
+ const lines = [];
1700
+ lines.push(`## Metric definitions (for the ${audienceLabel(audience)})`);
1701
+ lines.push("");
1702
+ lines.push(
1703
+ audience === "ops" ? "Formula-first brief for operators executing the plan. Full slides: `/deepdive <metric>`." : "Meaning-first brief for the room. Full slides: `/deepdive <metric>`."
1704
+ );
1705
+ lines.push("");
1706
+ for (const c of candidates) {
1707
+ const explainer = getMetricExplainer(c.id);
1708
+ if (!explainer) continue;
1709
+ lines.push(...formatEntry(explainer, audience));
1710
+ }
1711
+ return lines.join("\n");
1712
+ }
1713
+ function injectDefinitionsAppendix(markdown, appendix) {
1714
+ if (!appendix.trim()) return markdown;
1715
+ const block = appendix.trimEnd() + "\n";
1716
+ const footerIdx = markdown.lastIndexOf("\n---\n");
1717
+ if (footerIdx >= 0) {
1718
+ return markdown.slice(0, footerIdx + 1) + "\n" + block + "\n" + markdown.slice(footerIdx + 1);
1719
+ }
1720
+ return markdown.trimEnd() + "\n\n" + block + "\n";
1721
+ }
1722
+ var DEFAULT_CAP;
1723
+ var init_metric_explainers = __esm({
1724
+ "src/services/metric-explainers.ts"() {
1725
+ "use strict";
1726
+ init_metric_definitions();
1727
+ DEFAULT_CAP = 8;
1728
+ }
1729
+ });
1730
+
1731
+ // src/ui/spinner.ts
1732
+ import ora from "ora";
1733
+ var init_spinner = __esm({
1734
+ "src/ui/spinner.ts"() {
1735
+ "use strict";
1736
+ }
1737
+ });
1738
+
1739
+ // src/config/install.ts
1740
+ import { randomUUID as randomUUID3 } from "crypto";
1741
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
1742
+ import { join as join6 } from "path";
1743
+ function installPath() {
1744
+ return join6(ntrpHome(), "install.json");
1745
+ }
1746
+ function ensureDir2() {
1747
+ const dir = ntrpHome();
1748
+ if (!existsSync6(dir)) {
1749
+ mkdirSync5(dir, { recursive: true });
1750
+ }
1751
+ }
1752
+ function isValidInstall(value) {
1753
+ if (!value || typeof value !== "object") return false;
1754
+ const r = value;
1755
+ return r.schema_version === 1 && typeof r.install_id === "string" && r.install_id.length > 0 && typeof r.created_at === "string";
1756
+ }
1757
+ function ensureInstall() {
1758
+ if (cachedInstall) return cachedInstall;
1759
+ const path = installPath();
1760
+ if (existsSync6(path)) {
1761
+ try {
1762
+ const parsed = JSON.parse(readFileSync6(path, "utf-8"));
1763
+ if (isValidInstall(parsed)) {
1764
+ cachedInstall = parsed;
1765
+ return parsed;
1766
+ }
1767
+ } catch {
1768
+ }
1769
+ }
1770
+ const record = {
1771
+ schema_version: 1,
1772
+ install_id: randomUUID3(),
1773
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1774
+ };
1775
+ ensureDir2();
1776
+ writeFileSync7(path, JSON.stringify(record, null, 2) + "\n");
1777
+ cachedInstall = record;
1778
+ return record;
1779
+ }
1780
+ function getInstallId() {
1781
+ return ensureInstall().install_id;
1782
+ }
1783
+ var cachedInstall;
1784
+ var init_install = __esm({
1785
+ "src/config/install.ts"() {
1786
+ "use strict";
1787
+ init_store();
1788
+ cachedInstall = null;
1789
+ }
1790
+ });
1791
+
1792
+ // src/config/progress-migrate.ts
1793
+ import { existsSync as existsSync7, readFileSync as readFileSync7, renameSync as renameSync2, writeFileSync as writeFileSync8 } from "fs";
1794
+ import { join as join7 } from "path";
1795
+ function legacyStatePath() {
1796
+ return join7(ntrpHome(), "state.json");
1797
+ }
1798
+ function legacyStateBackupPath() {
1799
+ return join7(ntrpHome(), "state.json.bak");
1800
+ }
1801
+ function progressPath() {
1802
+ return join7(ntrpHome(), "progress.json");
1803
+ }
1804
+ function isValidLegacyState(value) {
1805
+ if (!value || typeof value !== "object") return false;
1806
+ const s = value;
1807
+ return s.schema_version === 1 && typeof s.total_minutes_saved === "number" && Array.isArray(s.credits) && Array.isArray(s.milestones_unlocked);
1808
+ }
1809
+ function migrateLegacyStateIfNeeded(installId) {
1810
+ if (existsSync7(progressPath())) return null;
1811
+ const legacyPath = legacyStatePath();
1812
+ if (!existsSync7(legacyPath)) return null;
1813
+ try {
1814
+ const parsed = JSON.parse(readFileSync7(legacyPath, "utf-8"));
1815
+ if (!isValidLegacyState(parsed)) return null;
1816
+ const { schema_version: _v, ...rest } = parsed;
1817
+ const progress = {
1818
+ ...rest,
1819
+ schema_version: 2,
1820
+ install_id: installId
1821
+ };
1822
+ writeFileSync8(progressPath(), JSON.stringify(progress, null, 2) + "\n");
1823
+ try {
1824
+ renameSync2(legacyPath, legacyStateBackupPath());
1825
+ } catch {
1826
+ }
1827
+ return progress;
1828
+ } catch {
1829
+ return null;
1830
+ }
1831
+ }
1832
+ var init_progress_migrate = __esm({
1833
+ "src/config/progress-migrate.ts"() {
1834
+ "use strict";
1835
+ init_store();
1836
+ }
1837
+ });
1838
+
1839
+ // src/whimsy/usage-backfill.ts
1840
+ function isoWeekKey(d) {
1841
+ const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
1842
+ const day = date.getUTCDay() || 7;
1843
+ date.setUTCDate(date.getUTCDate() + 4 - day);
1844
+ const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
1845
+ const weekNo = Math.ceil(((date.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
1846
+ return `${date.getUTCFullYear()}-W${String(weekNo).padStart(2, "0")}`;
1847
+ }
1848
+ function actionBase(action) {
1849
+ return action.split(":")[0] ?? action;
1850
+ }
1851
+ function bumpWeekly(weekly, week, patch) {
1852
+ const idx = weekly.findIndex((w) => w.week === week);
1853
+ const row = idx >= 0 ? { ...weekly[idx] } : { week, minutes_saved: 0, llm_calls: 0, actions: 0 };
1854
+ if (patch.minutes_saved) row.minutes_saved += patch.minutes_saved;
1855
+ if (patch.actions) row.actions += patch.actions;
1856
+ return idx >= 0 ? weekly.map((w, i) => i === idx ? row : w) : [...weekly, row];
1857
+ }
1858
+ function rebuildFromCredits(credits) {
1859
+ let diagnoses = 0;
1860
+ let metrics_runs = 0;
1861
+ let deliverables = 0;
1862
+ let nl_exchanges = 0;
1863
+ let weekly = [];
1864
+ let first_active_at;
1865
+ let last_active_at;
1866
+ for (const credit of credits) {
1867
+ if (!first_active_at || credit.at < first_active_at) first_active_at = credit.at;
1868
+ if (!last_active_at || credit.at > last_active_at) last_active_at = credit.at;
1869
+ const base = actionBase(credit.action);
1870
+ if (base === "diagnose" || base === "diagnose_findings") diagnoses++;
1871
+ if (base === "metrics" || base === "metrics_findings") metrics_runs++;
1872
+ if (base === "deliverable" || base === "deliverable_deck") deliverables++;
1873
+ if (base === "nl_answer") nl_exchanges++;
1874
+ const week = isoWeekKey(new Date(credit.at));
1875
+ weekly = bumpWeekly(weekly, week, { minutes_saved: credit.minutes, actions: 1 });
1876
+ }
1877
+ return {
1878
+ first_active_at,
1879
+ last_active_at,
1880
+ diagnoses,
1881
+ metrics_runs,
1882
+ deliverables,
1883
+ nl_exchanges,
1884
+ weekly
1885
+ };
1886
+ }
1887
+ function mergeWeekly(existing, fromCredits) {
1888
+ const byWeek = /* @__PURE__ */ new Map();
1889
+ for (const row of fromCredits) {
1890
+ byWeek.set(row.week, { ...row });
1891
+ }
1892
+ for (const row of existing) {
1893
+ const prior = byWeek.get(row.week);
1894
+ if (prior) {
1895
+ byWeek.set(row.week, {
1896
+ week: row.week,
1897
+ minutes_saved: Math.max(prior.minutes_saved, row.minutes_saved),
1898
+ actions: Math.max(prior.actions, row.actions),
1899
+ llm_calls: row.llm_calls
1900
+ });
1901
+ } else {
1902
+ byWeek.set(row.week, { ...row });
1903
+ }
1904
+ }
1905
+ return [...byWeek.values()].sort((a, b) => a.week.localeCompare(b.week));
1906
+ }
1907
+ function migrateUsageIfNeeded(state) {
1908
+ if (state.credits.length === 0) return { state, changed: false };
1909
+ if (state.usage?.first_active_at) return { state, changed: false };
1910
+ const fromCredits = rebuildFromCredits(state.credits);
1911
+ const prior = state.usage;
1912
+ const usage = {
1913
+ sessions_closed: prior?.sessions_closed ?? 0,
1914
+ llm_calls: prior?.llm_calls ?? 0,
1915
+ input_tokens: prior?.input_tokens ?? 0,
1916
+ output_tokens: prior?.output_tokens ?? 0,
1917
+ ...fromCredits,
1918
+ weekly: mergeWeekly(prior?.weekly ?? [], fromCredits.weekly)
1919
+ };
1920
+ return { state: { ...state, usage }, changed: true };
1921
+ }
1922
+ var init_usage_backfill = __esm({
1923
+ "src/whimsy/usage-backfill.ts"() {
1924
+ "use strict";
1925
+ }
1926
+ });
1927
+
1928
+ // src/config/progress.ts
1929
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync8, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "fs";
1930
+ import { join as join8 } from "path";
1931
+ function progressPath2() {
1932
+ return join8(ntrpHome(), "progress.json");
1933
+ }
1934
+ function legacyStatePath2() {
1935
+ return join8(ntrpHome(), "state.json");
1936
+ }
1937
+ function legacyStateBackupPath2() {
1938
+ return join8(ntrpHome(), "state.json.bak");
1939
+ }
1940
+ function ensureDir3() {
1941
+ const dir = ntrpHome();
1942
+ if (!existsSync8(dir)) {
1943
+ mkdirSync6(dir, { recursive: true });
1944
+ }
1945
+ }
1946
+ function emptyProgress(installId) {
1947
+ return {
1948
+ schema_version: 2,
1949
+ install_id: installId,
1950
+ total_minutes_saved: 0,
1951
+ credits: [],
1952
+ milestones_unlocked: []
1953
+ };
1954
+ }
1955
+ function isValidProgress(value) {
1956
+ if (!value || typeof value !== "object") return false;
1957
+ const s = value;
1958
+ return s.schema_version === 2 && typeof s.install_id === "string" && typeof s.total_minutes_saved === "number" && Array.isArray(s.credits) && Array.isArray(s.milestones_unlocked);
1959
+ }
1960
+ function reconcileInstallId(state) {
1961
+ const localId = getInstallId();
1962
+ if (state.install_id === localId) return { state, changed: false };
1963
+ if (!installMismatchWarned) {
1964
+ installMismatchWarned = true;
1965
+ console.warn(
1966
+ " progress.json install_id did not match this machine \u2014 rebound to local install."
1967
+ );
1968
+ }
1969
+ return { state: { ...state, install_id: localId }, changed: true };
1970
+ }
1971
+ function readProgressFile() {
1972
+ const path = progressPath2();
1973
+ if (!existsSync8(path)) return { state: null, changed: false };
1974
+ try {
1975
+ const parsed = JSON.parse(readFileSync8(path, "utf-8"));
1976
+ if (!isValidProgress(parsed)) return { state: null, changed: false };
1977
+ return reconcileInstallId(parsed);
1978
+ } catch {
1979
+ return { state: null, changed: false };
1980
+ }
1981
+ }
1982
+ function loadProgress() {
1983
+ ensureInstall();
1984
+ const installId = getInstallId();
1985
+ let state = null;
1986
+ let changed = false;
1987
+ const fromFile = readProgressFile();
1988
+ if (fromFile.state) {
1989
+ state = fromFile.state;
1990
+ changed = fromFile.changed;
1991
+ }
1992
+ if (!state) {
1993
+ const migrated = migrateLegacyStateIfNeeded(installId);
1994
+ if (migrated) {
1995
+ state = migrated;
1996
+ changed = true;
1997
+ }
1998
+ }
1999
+ if (!state) {
2000
+ state = emptyProgress(installId);
2001
+ changed = true;
2002
+ }
2003
+ const { state: usageMigrated, changed: usageChanged } = migrateUsageIfNeeded(state);
2004
+ state = usageMigrated;
2005
+ if (usageChanged) changed = true;
2006
+ if (changed) saveProgress(state);
2007
+ return state;
2008
+ }
2009
+ function saveProgress(state) {
2010
+ ensureDir3();
2011
+ const next = {
2012
+ ...state,
2013
+ schema_version: 2,
2014
+ install_id: getInstallId()
2015
+ };
2016
+ writeFileSync9(progressPath2(), JSON.stringify(next, null, 2) + "\n");
2017
+ }
2018
+ function wipeProgressFiles() {
2019
+ installMismatchWarned = false;
2020
+ for (const path of [progressPath2(), legacyStatePath2(), legacyStateBackupPath2()]) {
2021
+ if (existsSync8(path)) {
2022
+ unlinkSync2(path);
2023
+ }
2024
+ }
2025
+ }
2026
+ function unlockProgressMilestone(id) {
2027
+ const state = loadProgress();
2028
+ if (state.milestones_unlocked.includes(id)) return false;
2029
+ saveProgress({
2030
+ ...state,
2031
+ milestones_unlocked: [...state.milestones_unlocked, id]
2032
+ });
2033
+ return true;
2034
+ }
2035
+ var installMismatchWarned;
2036
+ var init_progress = __esm({
2037
+ "src/config/progress.ts"() {
2038
+ "use strict";
2039
+ init_install();
2040
+ init_progress_migrate();
2041
+ init_store();
2042
+ init_usage_backfill();
2043
+ installMismatchWarned = false;
2044
+ }
2045
+ });
2046
+
2047
+ // src/whimsy/time-milestones.ts
2048
+ var init_time_milestones = __esm({
2049
+ "src/whimsy/time-milestones.ts"() {
2050
+ "use strict";
2051
+ }
2052
+ });
2053
+
2054
+ // src/whimsy/time-perspectives.ts
2055
+ var TIME_PERSPECTIVES;
2056
+ var init_time_perspectives = __esm({
2057
+ "src/whimsy/time-perspectives.ts"() {
2058
+ "use strict";
2059
+ TIME_PERSPECTIVES = [
2060
+ { id: "dsotm", category: "music", reference_hours: 0.74, label: "Dark Side of the Moon", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 1, max_ratio: 200 },
2061
+ { id: "rush_2112", category: "music", reference_hours: 0.33, label: "2112", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 2, max_ratio: 200 },
2062
+ { id: "bohemian_rhapsody", category: "music", reference_hours: 0.1, label: "Bohemian Rhapsody", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 5, max_ratio: 500 },
2063
+ { id: "stairway", category: "music", reference_hours: 0.13, label: "Stairway to Heaven", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 5, max_ratio: 400 },
2064
+ { id: "podcast_binge", category: "music", reference_hours: 0.75, label: "hour-long podcast episodes", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 300 },
2065
+ { id: "abbey_road", category: "music", reference_hours: 0.8, label: "Abbey Road", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 1, max_ratio: 200 },
2066
+ { id: "iron_maiden_set", category: "music", reference_hours: 2, label: "an Iron Maiden marathon set", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 50 },
2067
+ { id: "festival_set", category: "music", reference_hours: 1.5, label: "main-stage festival sets", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 100 },
2068
+ { id: "jazz_club", category: "music", reference_hours: 3, label: "late-night jazz sets", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 80 },
2069
+ { id: "ring_cycle", category: "music", reference_hours: 15, label: "Wagner's Ring Cycle", template: "\u2248 {pct}% of {label}", min_ratio: 0.1, max_ratio: 2 },
2070
+ { id: "shrek", category: "film", reference_hours: 1.5, label: "Shrek (the first one)", template: "\u2248 {ratio}\xD7 watching {label}", min_ratio: 1, max_ratio: 150 },
2071
+ { id: "blockbuster", category: "film", reference_hours: 2.1, label: "average blockbusters", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 100 },
2072
+ { id: "dune_two", category: "film", reference_hours: 2.75, label: "Dune: Part Two", template: "\u2248 {ratio}\xD7 in theater for {label}", min_ratio: 1, max_ratio: 100 },
2073
+ { id: "scorsese", category: "film", reference_hours: 3.5, label: "Goodfellas", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 80 },
2074
+ { id: "godfather", category: "film", reference_hours: 6.5, label: "the Godfather saga", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 20 },
2075
+ { id: "lotr_extended", category: "film", reference_hours: 11.4, label: "the LOTR extended trilogy", template: "Longer than all of {label}", min_ratio: 1, max_ratio: 50 },
2076
+ { id: "cooking_brisket", category: "film", reference_hours: 12, label: "low-and-slow brisket cooks", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
2077
+ { id: "the_office", category: "film", reference_hours: 68, label: "The Office (full series)", template: "\u2248 {ratio}\xD7 bingeing {label}", min_ratio: 5, max_ratio: 200 },
2078
+ { id: "marvel_marathon", category: "film", reference_hours: 50, label: "an MCU Phase One marathon", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
2079
+ { id: "around_world", category: "film", reference_hours: 1920, label: "Around the World in 80 Days (fictionally)", template: "\u2248 {pct}% of {label}", min_ratio: 0.3, max_ratio: 1 },
2080
+ { id: "soccer_match", category: "sports", reference_hours: 1.75, label: "Premier League matches", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 150 },
2081
+ { id: "marathon", category: "sports", reference_hours: 2, label: "marathons at world-record pace", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 80 },
2082
+ { id: "baseball_game", category: "sports", reference_hours: 3, label: "nine-inning baseball games", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 80 },
2083
+ { id: "superbowl", category: "sports", reference_hours: 3.5, label: "Super Bowls", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 80 },
2084
+ { id: "nfl_game", category: "sports", reference_hours: 3.25, label: "NFL games (with commercials)", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 50 },
2085
+ { id: "wimbledon", category: "sports", reference_hours: 5, label: "Wimbledon finals", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
2086
+ { id: "tour_stage", category: "sports", reference_hours: 4.5, label: "Tour de France stages", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 60 },
2087
+ { id: "olympics", category: "sports", reference_hours: 250, label: "Summer Olympics broadcast hours", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 10 },
2088
+ { id: "moon_light", category: "cosmos", reference_hours: 1.3 / 3600, label: "a beam of light Earth \u2192 Moon", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1e3, max_ratio: 1e6 },
2089
+ { id: "iss_orbit", category: "cosmos", reference_hours: 1.5, label: "ISS orbits", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 200 },
2090
+ { id: "light_sun", category: "cosmos", reference_hours: 8.3, label: "solar light crossing to Earth", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 200 },
2091
+ { id: "sleep_cycle", category: "cosmos", reference_hours: 8, label: "full nights of sleep", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 150 },
2092
+ { id: "red_eye", category: "cosmos", reference_hours: 5.5, label: "transcontinental red-eyes", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 100 },
2093
+ { id: "mayfly", category: "cosmos", reference_hours: 24, label: "a mayfly's entire adult life", template: "\u2248 {pct}% of {label}", min_ratio: 0.1, max_ratio: 2 },
2094
+ { id: "earth_rotation", category: "cosmos", reference_hours: 24, label: "Earth rotations", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.1, max_ratio: 50 },
2095
+ { id: "jupiter_storm", category: "cosmos", reference_hours: 150, label: "Jupiter's Great Red Spot rotation", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 15 },
2096
+ { id: "lunar_month", category: "cosmos", reference_hours: 708, label: "a lunar cycle", template: "\u2248 {pct}% of {label}", min_ratio: 0.05, max_ratio: 2 },
2097
+ { id: "mars_transit", category: "cosmos", reference_hours: 5110, label: "a one-way Mars transit (optimistic)", template: "\u2248 {pct}% of {label}", min_ratio: 1e-3, max_ratio: 5 },
2098
+ { id: "calendar_year", category: "cosmos", reference_hours: 8760, label: "all the hours in a calendar year", template: "\u2248 {pct}% of {label}", min_ratio: 0.05, max_ratio: 0.2 },
2099
+ { id: "standup", category: "gtm", reference_hours: 0.25, label: "daily standups", template: "\u2248 {ratio}\xD7 skipped {label}", min_ratio: 4, max_ratio: 500 },
2100
+ { id: "quick_sync", category: "gtm", reference_hours: 0.5, label: "avoided 'quick syncs'", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 200 },
2101
+ { id: "pipeline_review", category: "gtm", reference_hours: 1, label: "weekly pipeline reviews", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 200 },
2102
+ { id: "forecast_call", category: "gtm", reference_hours: 1.5, label: "forecast calls", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 150 },
2103
+ { id: "pivot_spiral", category: "gtm", reference_hours: 2, label: "spreadsheet pivot-table spirals", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 100 },
2104
+ { id: "win_loss", category: "gtm", reference_hours: 4, label: "win/loss interview blocks", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 50 },
2105
+ { id: "crm_cleanup", category: "gtm", reference_hours: 6, label: "CRM hygiene sprints", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 40 },
2106
+ { id: "qbr_prep", category: "gtm", reference_hours: 8, label: "QBR prep blocks", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 20 },
2107
+ { id: "board_deck", category: "gtm", reference_hours: 12, label: "board deck builds", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
2108
+ { id: "semester", category: "gtm", reference_hours: 400, label: "a college semester of analyst coverage", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 5 },
2109
+ { id: "business_year", category: "gtm", reference_hours: 2e3, label: "a full-time analyst year", template: "\u2248 {pct}% of {label}", min_ratio: 0.2, max_ratio: 1 }
2110
+ ];
2111
+ }
2112
+ });
2113
+
2114
+ // src/whimsy/time-bank-whimsy.ts
2115
+ var init_time_bank_whimsy = __esm({
2116
+ "src/whimsy/time-bank-whimsy.ts"() {
2117
+ "use strict";
2118
+ }
2119
+ });
2120
+
2121
+ // src/whimsy/perspective-rotation.ts
2122
+ var PERSPECTIVE_ROTATE_CALENDAR_MS;
2123
+ var init_perspective_rotation = __esm({
2124
+ "src/whimsy/perspective-rotation.ts"() {
2125
+ "use strict";
2126
+ PERSPECTIVE_ROTATE_CALENDAR_MS = 7 * 24 * 60 * 60 * 1e3;
2127
+ }
2128
+ });
2129
+
2130
+ // src/whimsy/usage-stats.ts
2131
+ var init_usage_stats = __esm({
2132
+ "src/whimsy/usage-stats.ts"() {
2133
+ "use strict";
2134
+ init_progress();
2135
+ }
2136
+ });
2137
+
2138
+ // src/whimsy/time-bank.ts
2139
+ import chalk4 from "chalk";
2140
+ var init_time_bank = __esm({
2141
+ "src/whimsy/time-bank.ts"() {
2142
+ "use strict";
2143
+ init_progress();
2144
+ init_theme();
2145
+ init_time_milestones();
2146
+ init_time_perspectives();
2147
+ init_time_bank_whimsy();
2148
+ init_perspective_rotation();
2149
+ init_usage_stats();
2150
+ }
2151
+ });
2152
+
2153
+ // src/data/playbook.ts
2154
+ import { existsSync as existsSync9, readFileSync as readFileSync9, appendFileSync as appendFileSync2 } from "fs";
2155
+ import { join as join9 } from "path";
2156
+ var init_playbook = __esm({
2157
+ "src/data/playbook.ts"() {
2158
+ "use strict";
2159
+ init_store();
2160
+ }
2161
+ });
2162
+
2163
+ // src/memory/play-outcomes.ts
2164
+ import { existsSync as existsSync10, readFileSync as readFileSync10, appendFileSync as appendFileSync3 } from "fs";
2165
+ import { join as join10 } from "path";
2166
+ import { randomUUID as randomUUID4 } from "crypto";
2167
+ var init_play_outcomes = __esm({
2168
+ "src/memory/play-outcomes.ts"() {
2169
+ "use strict";
2170
+ init_store();
2171
+ }
2172
+ });
2173
+
2174
+ // src/workflows/registry.ts
2175
+ var init_registry = __esm({
2176
+ "src/workflows/registry.ts"() {
2177
+ "use strict";
2178
+ }
2179
+ });
2180
+
2181
+ // src/ai/prompt-parts.ts
2182
+ import { existsSync as existsSync11, readFileSync as readFileSync11 } from "fs";
2183
+ import { join as join11 } from "path";
2184
+ var init_prompt_parts = __esm({
2185
+ "src/ai/prompt-parts.ts"() {
2186
+ "use strict";
2187
+ init_profile();
2188
+ init_store();
2189
+ init_playbook();
2190
+ init_play_outcomes();
2191
+ init_registry();
2192
+ }
2193
+ });
2194
+
2195
+ // src/ai/llm/providers.ts
2196
+ var init_providers = __esm({
2197
+ "src/ai/llm/providers.ts"() {
2198
+ "use strict";
2199
+ init_store();
2200
+ }
2201
+ });
2202
+
2203
+ // src/config/llm-config.ts
2204
+ var init_llm_config = __esm({
2205
+ "src/config/llm-config.ts"() {
2206
+ "use strict";
2207
+ init_providers();
2208
+ init_store();
2209
+ }
2210
+ });
2211
+
2212
+ // src/ai/llm/gate.ts
2213
+ var init_gate = __esm({
2214
+ "src/ai/llm/gate.ts"() {
2215
+ "use strict";
2216
+ init_llm_config();
2217
+ }
2218
+ });
2219
+
2220
+ // src/ai/repl-api.ts
2221
+ var init_repl_api = __esm({
2222
+ "src/ai/repl-api.ts"() {
2223
+ "use strict";
2224
+ init_gate();
2225
+ }
2226
+ });
2227
+
2228
+ // src/ai/explore-mode.ts
2229
+ var init_explore_mode = __esm({
2230
+ "src/ai/explore-mode.ts"() {
2231
+ "use strict";
2232
+ init_context2();
2233
+ }
2234
+ });
2235
+
2236
+ // src/ai/llm/models-cache.ts
2237
+ var CACHE_TTL_MS;
2238
+ var init_models_cache = __esm({
2239
+ "src/ai/llm/models-cache.ts"() {
2240
+ "use strict";
2241
+ init_store();
2242
+ CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
2243
+ }
2244
+ });
2245
+
2246
+ // src/ai/llm/catalog.ts
2247
+ var ENTRIES, byId;
2248
+ var init_catalog = __esm({
2249
+ "src/ai/llm/catalog.ts"() {
2250
+ "use strict";
2251
+ init_models_cache();
2252
+ ENTRIES = [
2253
+ {
2254
+ id: "claude-opus-4-6",
2255
+ provider: "anthropic",
2256
+ tier: "high",
2257
+ status: "active",
2258
+ successor_id: null,
2259
+ supports_tools: true,
2260
+ max_context_tokens: 2e5,
2261
+ display_name: "Claude Opus 4.6",
2262
+ relative_cost: 3
2263
+ },
2264
+ {
2265
+ id: "claude-sonnet-4-5-20250929",
2266
+ provider: "anthropic",
2267
+ tier: "medium",
2268
+ status: "active",
2269
+ successor_id: null,
2270
+ supports_tools: true,
2271
+ max_context_tokens: 2e5,
2272
+ display_name: "Claude Sonnet 4.5",
2273
+ relative_cost: 2
2274
+ },
2275
+ {
2276
+ id: "claude-haiku-4-5-20251001",
2277
+ provider: "anthropic",
2278
+ tier: "low",
2279
+ status: "active",
2280
+ successor_id: null,
2281
+ supports_tools: true,
2282
+ max_context_tokens: 2e5,
2283
+ display_name: "Claude Haiku 4.5",
2284
+ relative_cost: 1
2285
+ },
2286
+ {
2287
+ id: "gpt-4.1",
2288
+ provider: "openai",
2289
+ tier: "high",
2290
+ status: "active",
2291
+ successor_id: null,
2292
+ supports_tools: true,
2293
+ max_context_tokens: 1047576,
2294
+ display_name: "GPT-4.1",
2295
+ relative_cost: 3
2296
+ },
2297
+ {
2298
+ id: "gpt-4.1-mini",
2299
+ provider: "openai",
2300
+ tier: "medium",
2301
+ status: "active",
2302
+ successor_id: null,
2303
+ supports_tools: true,
2304
+ max_context_tokens: 1047576,
2305
+ display_name: "GPT-4.1 Mini",
2306
+ relative_cost: 2
2307
+ },
2308
+ {
2309
+ id: "gpt-4.1-nano",
2310
+ provider: "openai",
2311
+ tier: "low",
2312
+ status: "active",
2313
+ successor_id: null,
2314
+ supports_tools: true,
2315
+ max_context_tokens: 1047576,
2316
+ display_name: "GPT-4.1 Nano",
2317
+ relative_cost: 1
2318
+ }
2319
+ ];
2320
+ byId = new Map(ENTRIES.map((e) => [e.id, e]));
2321
+ }
2322
+ });
2323
+
2324
+ // src/ai/llm/surfaces.ts
2325
+ var init_surfaces = __esm({
2326
+ "src/ai/llm/surfaces.ts"() {
2327
+ "use strict";
2328
+ }
2329
+ });
2330
+
2331
+ // src/ai/llm/session-state.ts
2332
+ var init_session_state = __esm({
2333
+ "src/ai/llm/session-state.ts"() {
2334
+ "use strict";
2335
+ init_llm_config();
2336
+ init_catalog();
2337
+ init_surfaces();
2338
+ }
2339
+ });
2340
+
2341
+ // src/conversation/recommended-action.ts
2342
+ var init_recommended_action = __esm({
2343
+ "src/conversation/recommended-action.ts"() {
2344
+ "use strict";
2345
+ init_repl_api();
2346
+ init_phase();
2347
+ }
2348
+ });
2349
+
2350
+ // src/conversation/phase.ts
2351
+ import chalk5 from "chalk";
2352
+ var init_phase = __esm({
2353
+ "src/conversation/phase.ts"() {
2354
+ "use strict";
2355
+ init_context2();
2356
+ init_repl_api();
2357
+ init_explore_mode();
2358
+ init_session_state();
2359
+ init_theme();
2360
+ init_recommended_action();
2361
+ }
2362
+ });
2363
+
2364
+ // src/cli/args.ts
2365
+ import { basename as basename3 } from "path";
2366
+ var init_args = __esm({
2367
+ "src/cli/args.ts"() {
2368
+ "use strict";
2369
+ }
2370
+ });
2371
+
2372
+ // src/cli/global-admin.ts
2373
+ var init_global_admin = __esm({
2374
+ "src/cli/global-admin.ts"() {
2375
+ "use strict";
2376
+ init_args();
2377
+ }
2378
+ });
2379
+
2380
+ // src/cli/post-action.ts
2381
+ var init_post_action = __esm({
2382
+ "src/cli/post-action.ts"() {
2383
+ "use strict";
2384
+ }
2385
+ });
2386
+
2387
+ // src/cli/repl-globals.ts
2388
+ var init_repl_globals = __esm({
2389
+ "src/cli/repl-globals.ts"() {
2390
+ "use strict";
2391
+ }
2392
+ });
2393
+
2394
+ // src/ui/banner.ts
2395
+ import chalk7 from "chalk";
2396
+ var init_banner = __esm({
2397
+ "src/ui/banner.ts"() {
2398
+ "use strict";
2399
+ init_theme();
2400
+ init_layout();
2401
+ }
2402
+ });
2403
+
2404
+ // src/license/trial-policy.ts
2405
+ var init_trial_policy = __esm({
2406
+ "src/license/trial-policy.ts"() {
2407
+ "use strict";
2408
+ }
2409
+ });
2410
+
2411
+ // src/license/upgrade-whimsy.ts
2412
+ var init_upgrade_whimsy = __esm({
2413
+ "src/license/upgrade-whimsy.ts"() {
2414
+ "use strict";
2415
+ init_trial_policy();
2416
+ }
2417
+ });
2418
+
2419
+ // src/license/normalize.ts
2420
+ var init_normalize = __esm({
2421
+ "src/license/normalize.ts"() {
2422
+ "use strict";
2423
+ }
2424
+ });
2425
+
2426
+ // src/license/lemonsqueezy.ts
2427
+ import { hostname } from "os";
2428
+ var init_lemonsqueezy = __esm({
2429
+ "src/license/lemonsqueezy.ts"() {
2430
+ "use strict";
2431
+ }
2432
+ });
2433
+
2434
+ // src/license/verify.ts
2435
+ var init_verify = __esm({
2436
+ "src/license/verify.ts"() {
2437
+ "use strict";
2438
+ init_store();
2439
+ init_trial_policy();
2440
+ init_upgrade_whimsy();
2441
+ init_normalize();
2442
+ init_lemonsqueezy();
2443
+ }
2444
+ });
2445
+
2446
+ // src/cli/prompts.ts
2447
+ import { createInterface } from "readline/promises";
2448
+ import { clearLine, cursorTo } from "readline";
2449
+ import { StringDecoder } from "string_decoder";
2450
+ import chalk8 from "chalk";
2451
+ var init_prompts = __esm({
2452
+ "src/cli/prompts.ts"() {
2453
+ "use strict";
2454
+ init_repl_globals();
2455
+ init_theme();
2456
+ }
2457
+ });
2458
+
2459
+ // src/ui/open-browser.ts
2460
+ import { spawn } from "child_process";
2461
+ import { platform } from "os";
2462
+ var init_open_browser = __esm({
2463
+ "src/ui/open-browser.ts"() {
2464
+ "use strict";
2465
+ }
2466
+ });
2467
+
2468
+ // src/license/upgrade.ts
2469
+ import chalk9 from "chalk";
2470
+ var init_upgrade = __esm({
2471
+ "src/license/upgrade.ts"() {
2472
+ "use strict";
2473
+ init_prompts();
2474
+ init_store();
2475
+ init_banner();
2476
+ init_theme();
2477
+ init_verify();
2478
+ init_trial_policy();
2479
+ init_upgrade_whimsy();
2480
+ init_open_browser();
2481
+ }
2482
+ });
2483
+
2484
+ // src/license/activation.ts
2485
+ import chalk10 from "chalk";
2486
+ var init_activation = __esm({
2487
+ "src/license/activation.ts"() {
2488
+ "use strict";
2489
+ init_banner();
2490
+ init_theme();
2491
+ init_verify();
2492
+ init_trial_policy();
2493
+ init_upgrade();
2494
+ }
2495
+ });
2496
+
2497
+ // src/license/gate.ts
2498
+ var init_gate2 = __esm({
2499
+ "src/license/gate.ts"() {
2500
+ "use strict";
2501
+ }
2502
+ });
2503
+
2504
+ // src/cli/dispatch.ts
2505
+ import chalk11 from "chalk";
2506
+ var init_dispatch = __esm({
2507
+ "src/cli/dispatch.ts"() {
2508
+ "use strict";
2509
+ init_args();
2510
+ init_global_admin();
2511
+ init_post_action();
2512
+ init_repl_globals();
2513
+ init_registry();
2514
+ init_theme();
2515
+ init_activation();
2516
+ init_gate2();
2517
+ init_upgrade();
2518
+ }
2519
+ });
2520
+
2521
+ // src/baselines/profile-presets.ts
2522
+ var init_profile_presets = __esm({
2523
+ "src/baselines/profile-presets.ts"() {
2524
+ "use strict";
2525
+ }
2526
+ });
2527
+
2528
+ // src/baselines/defaults.ts
2529
+ var init_defaults = __esm({
2530
+ "src/baselines/defaults.ts"() {
2531
+ "use strict";
2532
+ }
2533
+ });
2534
+
2535
+ // src/baselines/resolve.ts
2536
+ var init_resolve = __esm({
2537
+ "src/baselines/resolve.ts"() {
2538
+ "use strict";
2539
+ init_defaults();
2540
+ init_profile_presets();
2541
+ }
2542
+ });
2543
+
2544
+ // src/cli/argparse.ts
2545
+ var init_argparse = __esm({
2546
+ "src/cli/argparse.ts"() {
2547
+ "use strict";
2548
+ }
2549
+ });
2550
+
2551
+ // src/ui/markdown.ts
2552
+ import chalk12 from "chalk";
2553
+ import Table from "cli-table3";
2554
+ var init_markdown = __esm({
2555
+ "src/ui/markdown.ts"() {
2556
+ "use strict";
2557
+ init_layout();
2558
+ }
2559
+ });
2560
+
2561
+ // src/commands/profile.ts
2562
+ import chalk13 from "chalk";
2563
+ var init_profile2 = __esm({
2564
+ "src/commands/profile.ts"() {
2565
+ "use strict";
2566
+ init_store();
2567
+ init_profile();
2568
+ init_profile_presets();
2569
+ init_defaults();
2570
+ init_resolve();
2571
+ init_argparse();
2572
+ init_markdown();
2573
+ init_theme();
2574
+ }
2575
+ });
2576
+
2577
+ // src/db/connection.ts
2578
+ import { dirname as dirname2, join as join12, resolve as resolve5 } from "path";
2579
+ var NTRP_DIR3, DEFAULT_DB_PATH, DB_PATH_PINNED;
2580
+ var init_connection = __esm({
2581
+ "src/db/connection.ts"() {
2582
+ "use strict";
2583
+ NTRP_DIR3 = process.env.NTRP_HOME ? resolve5(process.env.NTRP_HOME) : join12(process.env.HOME ?? "", ".ntrp");
2584
+ DEFAULT_DB_PATH = process.env.NTRP_DB_PATH ? resolve5(process.env.NTRP_DB_PATH) : join12(NTRP_DIR3, "ntrp.duckdb");
2585
+ DB_PATH_PINNED = !!process.env.NTRP_DB_PATH;
2586
+ }
2587
+ });
2588
+
2589
+ // src/db/queries.ts
2590
+ var init_queries = __esm({
2591
+ "src/db/queries.ts"() {
2592
+ "use strict";
2593
+ init_connection();
2594
+ init_formatters();
2595
+ init_connection();
2596
+ }
2597
+ });
2598
+
2599
+ // src/db/schema.ts
2600
+ var init_schema = __esm({
2601
+ "src/db/schema.ts"() {
2602
+ "use strict";
2603
+ init_connection();
2604
+ }
2605
+ });
2606
+
2607
+ // src/config/update-check.ts
2608
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync12, unlinkSync as unlinkSync3, writeFileSync as writeFileSync10 } from "fs";
2609
+ import { join as join13 } from "path";
2610
+ var init_update_check = __esm({
2611
+ "src/config/update-check.ts"() {
2612
+ "use strict";
2613
+ init_store();
2614
+ }
2615
+ });
2616
+
2617
+ // src/version.ts
2618
+ import { existsSync as existsSync13, readFileSync as readFileSync13 } from "fs";
2619
+ import { dirname as dirname3, join as join14 } from "path";
2620
+ import { fileURLToPath } from "url";
2621
+ var init_version = __esm({
2622
+ "src/version.ts"() {
2623
+ "use strict";
2624
+ }
2625
+ });
2626
+
2627
+ // src/update/registry.ts
2628
+ var init_registry2 = __esm({
2629
+ "src/update/registry.ts"() {
2630
+ "use strict";
2631
+ init_update_check();
2632
+ init_version();
2633
+ }
2634
+ });
2635
+
2636
+ // src/conversation/metric-tour.ts
2637
+ import chalk16 from "chalk";
2638
+ function hasCompletedMetricsTour() {
2639
+ return Boolean(getConfigValue(TOUR_COMPLETED_KEY));
2640
+ }
2641
+ function markMetricsTourCompleted() {
2642
+ if (hasCompletedMetricsTour()) return;
2643
+ setConfigValue(TOUR_COMPLETED_KEY, (/* @__PURE__ */ new Date()).toISOString());
2644
+ }
2645
+ function hasSkippedMetricsTour() {
2646
+ return Boolean(getConfigValue(TOUR_SKIPPED_KEY));
2647
+ }
2648
+ function markMetricsTourSkipped() {
2649
+ if (hasSkippedMetricsTour()) return;
2650
+ setConfigValue(TOUR_SKIPPED_KEY, (/* @__PURE__ */ new Date()).toISOString());
2651
+ }
2652
+ function hasSeenDeepdiveHomeNudge() {
2653
+ return Boolean(getConfigValue(HOME_NUDGE_SEEN_KEY));
2654
+ }
2655
+ function markDeepdiveHomeNudgeSeen() {
2656
+ if (hasSeenDeepdiveHomeNudge()) return;
2657
+ setConfigValue(HOME_NUDGE_SEEN_KEY, (/* @__PURE__ */ new Date()).toISOString());
2658
+ }
2659
+ function hasAnalysisForDeepdiveNudge(ctx) {
2660
+ if (ctx.stage === "analyzed") return true;
2661
+ if (ctx.analysis.completed.length > 0) return true;
2662
+ try {
2663
+ return listSessions({ limit: 20 }).some(
2664
+ (s) => s.stage === "analyzed" || (s.analysis?.completed?.length ?? 0) > 0
2665
+ );
2666
+ } catch {
2667
+ return false;
2668
+ }
2669
+ }
2670
+ function getDeepdiveNudge(ctx) {
2671
+ if (hasCompletedMetricsTour() || hasSeenDeepdiveHomeNudge()) return null;
2672
+ if (!hasAnalysisForDeepdiveNudge(ctx)) return null;
2673
+ return {
2674
+ text: "Metrics tour \u2014 what each number means",
2675
+ command: "/deepdive"
2676
+ };
2677
+ }
2678
+ var TOUR_COMPLETED_KEY, TOUR_SKIPPED_KEY, HOME_NUDGE_SEEN_KEY, METRICS_TOUR_MILESTONE_ID;
2679
+ var init_metric_tour = __esm({
2680
+ "src/conversation/metric-tour.ts"() {
2681
+ "use strict";
2682
+ init_context2();
2683
+ init_prompts();
2684
+ init_store();
2685
+ init_progress();
2686
+ init_profile();
2687
+ init_metric_definitions();
2688
+ init_slides();
2689
+ init_theme();
2690
+ TOUR_COMPLETED_KEY = "metrics-tour-completed";
2691
+ TOUR_SKIPPED_KEY = "metrics-tour-skipped";
2692
+ HOME_NUDGE_SEEN_KEY = "metrics-tour-home-nudge-seen";
2693
+ METRICS_TOUR_MILESTONE_ID = "metrics_tour";
2694
+ }
2695
+ });
2696
+
2697
+ // src/conversation/deepdive-smoke.ts
2698
+ init_metric_definitions();
2699
+ init_slides();
2700
+ init_keyless_definitions();
2701
+ init_metric_explainers();
2702
+
2703
+ // src/cli/repl.ts
2704
+ init_spinner();
2705
+ init_context2();
2706
+ init_transcript();
2707
+ init_time_bank();
2708
+ init_prompt_parts();
2709
+ init_store();
2710
+ init_phase();
2711
+ init_recommended_action();
2712
+ import { createInterface as createInterface2 } from "readline/promises";
2713
+ import { clearLine as clearLine2, cursorTo as cursorTo2 } from "readline";
2714
+ import chalk15 from "chalk";
2715
+ import { join as join15 } from "path";
2716
+
2717
+ // src/conversation/loop-guard.ts
2718
+ init_theme();
2719
+ import chalk6 from "chalk";
2720
+
2721
+ // src/cli/repl.ts
2722
+ init_dispatch();
2723
+ init_post_action();
2724
+ init_global_admin();
2725
+ init_repl_globals();
2726
+ init_registry();
2727
+ init_theme();
2728
+ init_layout();
2729
+ init_banner();
2730
+
2731
+ // src/ui/welcome.ts
2732
+ init_context2();
2733
+ init_phase();
2734
+ init_layout();
2735
+ init_theme();
2736
+ init_banner();
2737
+ init_store();
2738
+ init_profile();
2739
+ init_profile2();
2740
+ init_verify();
2741
+ init_queries();
2742
+ init_schema();
2743
+ import chalk14 from "chalk";
2744
+
2745
+ // src/cli/repl.ts
2746
+ init_registry2();
2747
+
2748
+ // src/conversation/deepdive-complete.ts
2749
+ init_metric_definitions();
2750
+ var SUBCOMMANDS = ["list", "tour", "start", "ls", "catalog"];
2751
+ function deepdiveArgCandidates() {
2752
+ const ids = METRIC_DEFINITIONS.map((m) => m.id);
2753
+ const coreSet = new Set(CORE_DECK_IDS);
2754
+ const core = CORE_DECK_IDS.filter((id) => ids.includes(id));
2755
+ const rest = ids.filter((id) => !coreSet.has(id));
2756
+ return [...SUBCOMMANDS, ...core, ...rest];
2757
+ }
2758
+ function completeDeepdiveLine(line) {
2759
+ const match = /^(?:\/)?deepdive(\s+)(.*)$/i.exec(line);
2760
+ if (!match) return null;
2761
+ const partial = match[2] ?? "";
2762
+ const lower = partial.toLowerCase();
2763
+ const hits = deepdiveArgCandidates().filter((c) => c.startsWith(lower));
2764
+ return [hits, partial];
2765
+ }
2766
+ function deepdiveGhostSuffix(line) {
2767
+ const result = completeDeepdiveLine(line);
2768
+ if (!result) return null;
2769
+ const [hits, partial] = result;
2770
+ if (hits.length === 0) return null;
2771
+ if (hits.length === 1) {
2772
+ const only = hits[0];
2773
+ return only === partial ? null : only.slice(partial.length);
2774
+ }
2775
+ let common = hits[0];
2776
+ for (const hit of hits) {
2777
+ let i = 0;
2778
+ while (i < common.length && i < hit.length && common[i] === hit[i]) i++;
2779
+ common = common.slice(0, i);
2780
+ }
2781
+ return common.length > partial.length ? common.slice(partial.length) : null;
2782
+ }
2783
+
2784
+ // src/cli/repl.ts
2785
+ var GHOST_HINTS = {
2786
+ orient: [
2787
+ 'try "pipeline health"',
2788
+ "try /deepdive",
2789
+ 'try "is our retention real for the board?"',
2790
+ 'try "what is the most expensive problem to solve?"',
2791
+ 'try "board deck on Q3"'
2792
+ ],
2793
+ explore: [
2794
+ 'try "what is ARR?"',
2795
+ "try /deepdive freshness",
2796
+ 'try "how should we fix this?"',
2797
+ 'try "which segment is weakest?"',
2798
+ 'try "ship a board deck"'
2799
+ ]
2800
+ };
2801
+
2802
+ // src/conversation/deepdive-smoke.ts
2803
+ init_metric_tour();
2804
+ init_store();
2805
+ init_progress();
2806
+ function stubCtx(overrides = {}) {
2807
+ return {
2808
+ sessionId: "smoke",
2809
+ sessionFile: "/tmp/ntrp-deepdive-smoke-session.json",
2810
+ oneShot: true,
2811
+ execution: { mode: "interactive" },
2812
+ snapshot: { computeResult: null, divergences: [] },
2813
+ messages: [],
2814
+ conversation: [],
2815
+ stage: "new",
2816
+ deliverables: [],
2817
+ analysis: { primary: "gtm_health", completed: [] },
2818
+ wizardDepth: 0,
2819
+ ...overrides
2820
+ };
2821
+ }
2822
+ function assert(cond, msg) {
2823
+ if (!cond) throw new Error(msg);
2824
+ }
2825
+ function section(name) {
2826
+ console.log(` \xB7 ${name}`);
2827
+ }
2828
+ section("registry covers all vitals + SaaS ids");
2829
+ for (const id of VITAL_IDS) {
2830
+ assert(getMetricExplainer(id), `missing vital explainer: ${id}`);
2831
+ }
2832
+ for (const id of SAAS_METRIC_IDS) {
2833
+ assert(getMetricExplainer(id), `missing saas explainer: ${id}`);
2834
+ }
2835
+ assert(METRIC_DEFINITIONS.length === VITAL_IDS.length + SAAS_METRIC_IDS.length, "count mismatch");
2836
+ assert(VITAL_IDS.length === 5, "expected 5 vitals");
2837
+ assert(SAAS_METRIC_IDS.length === 20, `expected 20 saas, got ${SAAS_METRIC_IDS.length}`);
2838
+ section("core deck order");
2839
+ assert(CORE_DECK_IDS.length === 11, `core deck should be 11, got ${CORE_DECK_IDS.length}`);
2840
+ for (const id of CORE_DECK_IDS) {
2841
+ assert(getMetricExplainer(id), `core deck missing: ${id}`);
2842
+ }
2843
+ assert(getCoreDeckExplainers().length === CORE_DECK_IDS.length, "core deck resolve failed");
2844
+ section("alias resolution");
2845
+ assert(resolveMetricId("NRR") === "nrr", "NRR alias");
2846
+ assert(resolveMetricId("signal:noise") === "signal_to_noise", "signal:noise");
2847
+ assert(resolveMetricId("thread depth") === "thread_depth", "thread depth");
2848
+ assert(resolveMetricId("annual recurring revenue") === "arr", "ARR alias");
2849
+ assert(resolveMetricId("nope-metric-xyz") === void 0, "unknown should miss");
2850
+ section("slides render at widths without throw");
2851
+ var widths = [60, 80, 120];
2852
+ var originals = process.stdout.columns;
2853
+ for (const w of widths) {
2854
+ Object.defineProperty(process.stdout, "columns", { value: w, configurable: true });
2855
+ for (const explainer of METRIC_DEFINITIONS) {
2856
+ const { lines, width } = buildSlideContent(explainer, {
2857
+ index: 1,
2858
+ total: 11,
2859
+ deepdive: true
2860
+ });
2861
+ assert(width <= Math.max(20, w), `card wider than term at ${w}: ${explainer.id} \u2192 ${width}`);
2862
+ const painted = renderMetricSlide(explainer, {
2863
+ asLines: true,
2864
+ deepdive: false,
2865
+ index: 1,
2866
+ total: 11
2867
+ });
2868
+ const maxVis = measureSlideWidth(painted);
2869
+ assert(maxVis <= Math.max(w + 4, width + 8), `painted too wide for ${explainer.id} @${w}: ${maxVis}`);
2870
+ assert(lines.length > 0, `empty slide content for ${explainer.id}`);
2871
+ renderVisual(explainer.visual, Math.max(20, width - 4));
2872
+ }
2873
+ }
2874
+ if (originals != null) {
2875
+ Object.defineProperty(process.stdout, "columns", { value: originals, configurable: true });
2876
+ }
2877
+ section("keyless definition matcher");
2878
+ assert(isDefinitionAsk("what is ARR?"), "what is ARR");
2879
+ assert(isDefinitionAsk("how is freshness calculated?"), "how calculated");
2880
+ assert(isDefinitionAsk("what does NRR mean?"), "what does mean");
2881
+ assert(isDefinitionAsk("define thread depth"), "define");
2882
+ assert(!isDefinitionAsk("what is our ARR?"), "possessive our");
2883
+ assert(isPossessiveMetricAsk("what is our ARR?"), "possessive detect");
2884
+ assert(!isDefinitionAsk("what is my NRR looking like"), "possessive my");
2885
+ assert(matchDefinitionExplainer("what is ARR?")?.id === "arr", "match ARR");
2886
+ assert(matchDefinitionExplainer("how is drop rate calculated?")?.id === "drop_rate", "match drop");
2887
+ assert(matchDefinitionExplainer("what is our ARR?") === void 0, "possessive no match");
2888
+ assert(extractDefinitionQuery("what is pipeline coverage?")?.toLowerCase().includes("pipeline"), "extract");
2889
+ section("definitions appendix");
2890
+ var boardAppendix = buildDefinitionsAppendix(null, {
2891
+ audience: "board",
2892
+ vitals: [
2893
+ {
2894
+ vital_sign: "freshness",
2895
+ score: 29,
2896
+ status: "red",
2897
+ components: {},
2898
+ entity_details: [],
2899
+ dollar_value: 31e5,
2900
+ dollar_label: "pipeline at risk"
2901
+ },
2902
+ {
2903
+ vital_sign: "flow_rate",
2904
+ score: 55,
2905
+ status: "yellow",
2906
+ components: {},
2907
+ entity_details: [],
2908
+ dollar_value: 1e6,
2909
+ dollar_label: "stuck in pipeline"
2910
+ }
2911
+ ],
2912
+ prefer: ["freshness"],
2913
+ metrics: [
2914
+ {
2915
+ metric: "nrr",
2916
+ label: "Net Revenue Retention",
2917
+ group: "Retention",
2918
+ value: 95,
2919
+ formatted: "95%",
2920
+ status: "yellow",
2921
+ components: {}
2922
+ },
2923
+ {
2924
+ metric: "arr",
2925
+ label: "ARR",
2926
+ group: "Revenue",
2927
+ value: 24e5,
2928
+ formatted: "$2.4M",
2929
+ status: "green",
2930
+ components: {}
2931
+ }
2932
+ ]
2933
+ });
2934
+ assert(boardAppendix.includes("Metric definitions"), "appendix heading");
2935
+ assert(boardAppendix.includes("Freshness"), "includes gating vital");
2936
+ assert(boardAppendix.includes("board"), "board framing label");
2937
+ assert(!boardAppendix.toLowerCase().includes("formula-first"), "board is meaning-first");
2938
+ var opsAppendix = buildDefinitionsAppendix(null, {
2939
+ audience: "ops",
2940
+ prefer: ["freshness"],
2941
+ vitals: [
2942
+ {
2943
+ vital_sign: "freshness",
2944
+ score: 29,
2945
+ status: "red",
2946
+ components: {},
2947
+ entity_details: [],
2948
+ dollar_value: null,
2949
+ dollar_label: null
2950
+ }
2951
+ ]
2952
+ });
2953
+ assert(opsAppendix.includes("How it's calculated") || opsAppendix.includes("ops"), "ops framing");
2954
+ var injected = injectDefinitionsAppendix(
2955
+ "# Report\n\nbody\n\n---\n*Generated by ntrp-cli*\n",
2956
+ boardAppendix
2957
+ );
2958
+ assert(injected.includes("Metric definitions"), "inject keeps appendix");
2959
+ assert(injected.indexOf("Metric definitions") < injected.indexOf("*Generated by ntrp-cli*"), "before footer");
2960
+ section("ghost hints teach /deepdive");
2961
+ assert(
2962
+ (GHOST_HINTS.orient ?? []).some((h) => h.includes("/deepdive")),
2963
+ "orient ghost includes /deepdive"
2964
+ );
2965
+ assert(
2966
+ (GHOST_HINTS.explore ?? []).some((h) => h.includes("/deepdive")),
2967
+ "explore ghost includes /deepdive"
2968
+ );
2969
+ section("getDeepdiveNudge one-shot home chip + skip defer");
2970
+ deleteConfigValue("metrics-tour-completed");
2971
+ deleteConfigValue("metrics-tour-skipped");
2972
+ deleteConfigValue("metrics-tour-home-nudge-seen");
2973
+ var cold = stubCtx({ stage: "new" });
2974
+ assert(getDeepdiveNudge(cold) === null, "no nudge before analysis");
2975
+ markMetricsTourSkipped();
2976
+ assert(hasSkippedMetricsTour(), "skip recorded");
2977
+ assert(!hasCompletedMetricsTour(), "skip does not complete tour");
2978
+ assert(getDeepdiveNudge(cold) === null, "still no nudge before analysis after skip");
2979
+ var analyzed = stubCtx({
2980
+ stage: "analyzed",
2981
+ analysis: { primary: "gtm_health", completed: ["gtm_health"] }
2982
+ });
2983
+ assert(getDeepdiveNudge(analyzed)?.command === "/deepdive", "nudge after analysis when incomplete");
2984
+ markDeepdiveHomeNudgeSeen();
2985
+ assert(hasSeenDeepdiveHomeNudge(), "home nudge marked seen");
2986
+ assert(getDeepdiveNudge(analyzed) === null, "nudge suppressed after seen");
2987
+ deleteConfigValue("metrics-tour-home-nudge-seen");
2988
+ markMetricsTourCompleted();
2989
+ assert(hasCompletedMetricsTour(), "tour marked completed");
2990
+ assert(getDeepdiveNudge(analyzed) === null, "nudge suppressed after tour completed");
2991
+ section("deepdive tab/ghost completion");
2992
+ {
2993
+ const [hits, partial] = completeDeepdiveLine("/deepdive fr");
2994
+ assert(partial === "fr", "completer partial is fr");
2995
+ assert(hits.includes("freshness"), "completer returns freshness for /deepdive fr");
2996
+ assert(!hits.includes("nrr"), "fr does not match nrr");
2997
+ }
2998
+ assert(completeDeepdiveLine("/deepdive") === null, "bare /deepdive is command-level");
2999
+ assert(deepdiveGhostSuffix("/deepdive fr") === "eshness" || (deepdiveGhostSuffix("/deepdive fr") ?? "").startsWith("e"), "ghost extends fr");
3000
+ assert(completeDeepdiveLine("/deepdive list")?.[0].includes("list"), "list subcommand completes");
3001
+ section("metrics_tour progress milestone");
3002
+ wipeProgressFiles();
3003
+ assert(unlockProgressMilestone(METRICS_TOUR_MILESTONE_ID), "milestone unlocks once");
3004
+ assert(!unlockProgressMilestone(METRICS_TOUR_MILESTONE_ID), "milestone unlock is idempotent");
3005
+ assert(
3006
+ loadProgress().milestones_unlocked.includes(METRICS_TOUR_MILESTONE_ID),
3007
+ "milestone persisted"
3008
+ );
3009
+ console.log("PASS deepdive-smoke (unit)");
3010
+ //# sourceMappingURL=deepdive-smoke.js.map