@sonnechasser/ntrp 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1873 @@
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/ai/llm/thread-compat.ts
9
+ var init_thread_compat = __esm({
10
+ "src/ai/llm/thread-compat.ts"() {
11
+ "use strict";
12
+ }
13
+ });
14
+
15
+ // src/io/context.ts
16
+ var init_context = __esm({
17
+ "src/io/context.ts"() {
18
+ "use strict";
19
+ }
20
+ });
21
+
22
+ // src/output/formatters.ts
23
+ var init_formatters = __esm({
24
+ "src/output/formatters.ts"() {
25
+ "use strict";
26
+ }
27
+ });
28
+
29
+ // src/services/terminal-capture.ts
30
+ var init_terminal_capture = __esm({
31
+ "src/services/terminal-capture.ts"() {
32
+ "use strict";
33
+ }
34
+ });
35
+
36
+ // src/services/context-doc.ts
37
+ import { writeFileSync } from "fs";
38
+ var init_context_doc = __esm({
39
+ "src/services/context-doc.ts"() {
40
+ "use strict";
41
+ init_context2();
42
+ init_formatters();
43
+ init_terminal_capture();
44
+ }
45
+ });
46
+
47
+ // src/services/transcript.ts
48
+ import { existsSync, readFileSync, writeFileSync as writeFileSync2, rmSync } from "fs";
49
+ import { join } from "path";
50
+ var init_transcript = __esm({
51
+ "src/services/transcript.ts"() {
52
+ "use strict";
53
+ init_context2();
54
+ init_terminal_capture();
55
+ }
56
+ });
57
+
58
+ // src/cli/context.ts
59
+ import { basename, join as join2, resolve, sep } from "path";
60
+ import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3, readFileSync as readFileSync2, readdirSync, statSync, rmSync as rmSync2 } from "fs";
61
+ import { homedir } from "os";
62
+ import { randomUUID } from "crypto";
63
+ function isAnalysisReady(ctx) {
64
+ if (ctx.stage !== "analyzed" || ctx.analysis.completed.length === 0) return false;
65
+ if (!ctx.dataset) return false;
66
+ const counts = ctx.dataset.counts ?? {};
67
+ return Object.values(counts).some((n) => n > 0);
68
+ }
69
+ function defaultSessionAnalysis(primary = "gtm_health") {
70
+ return { primary, completed: [] };
71
+ }
72
+ var STALE_SESSION_MS;
73
+ var init_context2 = __esm({
74
+ "src/cli/context.ts"() {
75
+ "use strict";
76
+ init_thread_compat();
77
+ init_context();
78
+ init_context_doc();
79
+ init_transcript();
80
+ STALE_SESSION_MS = 14 * 24 * 60 * 60 * 1e3;
81
+ }
82
+ });
83
+
84
+ // src/config/store.ts
85
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync4, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
86
+ import { homedir as homedir2 } from "os";
87
+ import { join as join3, resolve as resolve2 } from "path";
88
+ function ntrpHome() {
89
+ return NTRP_DIR;
90
+ }
91
+ function getMemoryDir() {
92
+ const dir = join3(NTRP_DIR, "memory");
93
+ if (!existsSync3(dir)) {
94
+ mkdirSync2(dir, { recursive: true });
95
+ }
96
+ return dir;
97
+ }
98
+ var NTRP_DIR, CONFIG_PATH;
99
+ var init_store = __esm({
100
+ "src/config/store.ts"() {
101
+ "use strict";
102
+ NTRP_DIR = process.env.NTRP_HOME ? resolve2(process.env.NTRP_HOME) : join3(homedir2(), ".ntrp");
103
+ CONFIG_PATH = join3(NTRP_DIR, "config.json");
104
+ }
105
+ });
106
+
107
+ // src/config/profile.ts
108
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
109
+ import { join as join4 } from "path";
110
+ var NTRP_DIR2, PROFILE_PATH;
111
+ var init_profile = __esm({
112
+ "src/config/profile.ts"() {
113
+ "use strict";
114
+ init_store();
115
+ NTRP_DIR2 = ntrpHome();
116
+ PROFILE_PATH = join4(NTRP_DIR2, "profile.json");
117
+ }
118
+ });
119
+
120
+ // src/db/connection.ts
121
+ import { dirname, join as join5, resolve as resolve3 } from "path";
122
+ var NTRP_DIR3, DEFAULT_DB_PATH, DB_PATH_PINNED;
123
+ var init_connection = __esm({
124
+ "src/db/connection.ts"() {
125
+ "use strict";
126
+ NTRP_DIR3 = process.env.NTRP_HOME ? resolve3(process.env.NTRP_HOME) : join5(process.env.HOME ?? "", ".ntrp");
127
+ DEFAULT_DB_PATH = process.env.NTRP_DB_PATH ? resolve3(process.env.NTRP_DB_PATH) : join5(NTRP_DIR3, "ntrp.duckdb");
128
+ DB_PATH_PINNED = !!process.env.NTRP_DB_PATH;
129
+ }
130
+ });
131
+
132
+ // src/db/queries.ts
133
+ var init_queries = __esm({
134
+ "src/db/queries.ts"() {
135
+ "use strict";
136
+ init_connection();
137
+ init_formatters();
138
+ init_connection();
139
+ }
140
+ });
141
+
142
+ // src/ui/theme.ts
143
+ import chalk from "chalk";
144
+ var init_theme = __esm({
145
+ "src/ui/theme.ts"() {
146
+ "use strict";
147
+ init_formatters();
148
+ }
149
+ });
150
+
151
+ // src/services/session-analysis.ts
152
+ var init_session_analysis = __esm({
153
+ "src/services/session-analysis.ts"() {
154
+ "use strict";
155
+ init_queries();
156
+ init_profile();
157
+ init_formatters();
158
+ init_theme();
159
+ }
160
+ });
161
+
162
+ // src/conversation/handoff-draft.ts
163
+ function isShipIntent(input) {
164
+ const line = input.trim();
165
+ if (/\?\s*$/.test(line) || QUESTION_LEAD_RE.test(line)) return false;
166
+ return SHIP_INTENT_RE.test(line);
167
+ }
168
+ var QUESTION_LEAD_RE, SHIP_INTENT_RE;
169
+ var init_handoff_draft = __esm({
170
+ "src/conversation/handoff-draft.ts"() {
171
+ "use strict";
172
+ init_profile();
173
+ init_session_analysis();
174
+ QUESTION_LEAD_RE = /^\s*(what|why|how|when|where|who|which|is|are|was|were|do|does|did|explain|tell me|help me understand)\b/i;
175
+ SHIP_INTENT_RE = /\b(ship|export|deliver|write[- ]?up|board memo|action plan|turn (this|it|that) into|(draft|create|make|build|prepare|generate|send)\s+(me\s+)?(a\s+|the\s+)?hand[- ]?off|hand[- ]?off\s+(prompt|doc|document|plan))\b/i;
176
+ }
177
+ });
178
+
179
+ // src/ai/llm/providers.ts
180
+ var init_providers = __esm({
181
+ "src/ai/llm/providers.ts"() {
182
+ "use strict";
183
+ init_store();
184
+ }
185
+ });
186
+
187
+ // src/config/llm-config.ts
188
+ var init_llm_config = __esm({
189
+ "src/config/llm-config.ts"() {
190
+ "use strict";
191
+ init_providers();
192
+ init_store();
193
+ }
194
+ });
195
+
196
+ // src/ai/llm/gate.ts
197
+ var init_gate = __esm({
198
+ "src/ai/llm/gate.ts"() {
199
+ "use strict";
200
+ init_llm_config();
201
+ }
202
+ });
203
+
204
+ // src/ai/repl-api.ts
205
+ var init_repl_api = __esm({
206
+ "src/ai/repl-api.ts"() {
207
+ "use strict";
208
+ init_gate();
209
+ }
210
+ });
211
+
212
+ // src/cli/repl-globals.ts
213
+ var init_repl_globals = __esm({
214
+ "src/cli/repl-globals.ts"() {
215
+ "use strict";
216
+ }
217
+ });
218
+
219
+ // src/cli/prompts.ts
220
+ import { createInterface } from "readline/promises";
221
+ import { clearLine, cursorTo } from "readline";
222
+ import chalk2 from "chalk";
223
+ var init_prompts = __esm({
224
+ "src/cli/prompts.ts"() {
225
+ "use strict";
226
+ init_repl_globals();
227
+ init_theme();
228
+ }
229
+ });
230
+
231
+ // src/pipeline/segments.ts
232
+ var init_segments = __esm({
233
+ "src/pipeline/segments.ts"() {
234
+ "use strict";
235
+ init_connection();
236
+ init_queries();
237
+ }
238
+ });
239
+
240
+ // src/baselines/defaults.ts
241
+ var init_defaults = __esm({
242
+ "src/baselines/defaults.ts"() {
243
+ "use strict";
244
+ }
245
+ });
246
+
247
+ // src/baselines/profile-presets.ts
248
+ var init_profile_presets = __esm({
249
+ "src/baselines/profile-presets.ts"() {
250
+ "use strict";
251
+ }
252
+ });
253
+
254
+ // src/baselines/resolve.ts
255
+ var init_resolve = __esm({
256
+ "src/baselines/resolve.ts"() {
257
+ "use strict";
258
+ init_defaults();
259
+ init_profile_presets();
260
+ }
261
+ });
262
+
263
+ // src/vitals/shared.ts
264
+ var init_shared = __esm({
265
+ "src/vitals/shared.ts"() {
266
+ "use strict";
267
+ }
268
+ });
269
+
270
+ // src/vitals/freshness.ts
271
+ var init_freshness = __esm({
272
+ "src/vitals/freshness.ts"() {
273
+ "use strict";
274
+ init_defaults();
275
+ init_shared();
276
+ }
277
+ });
278
+
279
+ // src/vitals/flow-rate.ts
280
+ var init_flow_rate = __esm({
281
+ "src/vitals/flow-rate.ts"() {
282
+ "use strict";
283
+ init_defaults();
284
+ init_shared();
285
+ }
286
+ });
287
+
288
+ // src/vitals/drop-rate.ts
289
+ var init_drop_rate = __esm({
290
+ "src/vitals/drop-rate.ts"() {
291
+ "use strict";
292
+ init_defaults();
293
+ init_shared();
294
+ }
295
+ });
296
+
297
+ // src/vitals/signal-to-noise.ts
298
+ var init_signal_to_noise = __esm({
299
+ "src/vitals/signal-to-noise.ts"() {
300
+ "use strict";
301
+ init_defaults();
302
+ init_store();
303
+ init_shared();
304
+ }
305
+ });
306
+
307
+ // src/vitals/thread-depth.ts
308
+ var init_thread_depth = __esm({
309
+ "src/vitals/thread-depth.ts"() {
310
+ "use strict";
311
+ init_defaults();
312
+ init_shared();
313
+ }
314
+ });
315
+
316
+ // src/vitals/health-score.ts
317
+ var LAYERS;
318
+ var init_health_score = __esm({
319
+ "src/vitals/health-score.ts"() {
320
+ "use strict";
321
+ init_segments();
322
+ init_resolve();
323
+ init_freshness();
324
+ init_flow_rate();
325
+ init_drop_rate();
326
+ init_signal_to_noise();
327
+ init_thread_depth();
328
+ init_connection();
329
+ init_queries();
330
+ LAYERS = [
331
+ { layer: 1, signs: ["freshness"] },
332
+ { layer: 2, signs: ["flow_rate", "drop_rate"] },
333
+ { layer: 3, signs: ["signal_to_noise"] },
334
+ { layer: 4, signs: ["thread_depth"] }
335
+ ];
336
+ }
337
+ });
338
+
339
+ // src/pipeline/divergence.ts
340
+ var init_divergence = __esm({
341
+ "src/pipeline/divergence.ts"() {
342
+ "use strict";
343
+ }
344
+ });
345
+
346
+ // src/db/schema.ts
347
+ var init_schema = __esm({
348
+ "src/db/schema.ts"() {
349
+ "use strict";
350
+ init_connection();
351
+ }
352
+ });
353
+
354
+ // src/baselines/metrics-benchmarks.ts
355
+ var init_metrics_benchmarks = __esm({
356
+ "src/baselines/metrics-benchmarks.ts"() {
357
+ "use strict";
358
+ }
359
+ });
360
+
361
+ // src/metrics/classify-source.ts
362
+ var init_classify_source = __esm({
363
+ "src/metrics/classify-source.ts"() {
364
+ "use strict";
365
+ }
366
+ });
367
+
368
+ // src/metrics/helpers.ts
369
+ var init_helpers = __esm({
370
+ "src/metrics/helpers.ts"() {
371
+ "use strict";
372
+ init_metrics_benchmarks();
373
+ }
374
+ });
375
+
376
+ // src/metrics/coverage.ts
377
+ var init_coverage = __esm({
378
+ "src/metrics/coverage.ts"() {
379
+ "use strict";
380
+ init_helpers();
381
+ init_classify_source();
382
+ }
383
+ });
384
+
385
+ // src/metrics/context.ts
386
+ var init_context3 = __esm({
387
+ "src/metrics/context.ts"() {
388
+ "use strict";
389
+ init_metrics_benchmarks();
390
+ init_profile();
391
+ init_health_score();
392
+ init_queries();
393
+ init_classify_source();
394
+ init_coverage();
395
+ }
396
+ });
397
+
398
+ // src/metrics/revenue.ts
399
+ var init_revenue = __esm({
400
+ "src/metrics/revenue.ts"() {
401
+ "use strict";
402
+ init_helpers();
403
+ init_formatters();
404
+ }
405
+ });
406
+
407
+ // src/metrics/retention.ts
408
+ var init_retention = __esm({
409
+ "src/metrics/retention.ts"() {
410
+ "use strict";
411
+ init_revenue();
412
+ init_helpers();
413
+ init_metrics_benchmarks();
414
+ }
415
+ });
416
+
417
+ // src/metrics/pipeline.ts
418
+ var init_pipeline = __esm({
419
+ "src/metrics/pipeline.ts"() {
420
+ "use strict";
421
+ init_helpers();
422
+ init_formatters();
423
+ init_metrics_benchmarks();
424
+ }
425
+ });
426
+
427
+ // src/metrics/sales-efficiency.ts
428
+ var init_sales_efficiency = __esm({
429
+ "src/metrics/sales-efficiency.ts"() {
430
+ "use strict";
431
+ init_helpers();
432
+ init_formatters();
433
+ init_metrics_benchmarks();
434
+ }
435
+ });
436
+
437
+ // src/metrics/unit-economics.ts
438
+ var init_unit_economics = __esm({
439
+ "src/metrics/unit-economics.ts"() {
440
+ "use strict";
441
+ init_formatters();
442
+ }
443
+ });
444
+
445
+ // src/metrics/confidence.ts
446
+ var init_confidence = __esm({
447
+ "src/metrics/confidence.ts"() {
448
+ "use strict";
449
+ }
450
+ });
451
+
452
+ // src/metrics/periods.ts
453
+ var init_periods = __esm({
454
+ "src/metrics/periods.ts"() {
455
+ "use strict";
456
+ init_helpers();
457
+ }
458
+ });
459
+
460
+ // src/metrics/compute.ts
461
+ var init_compute = __esm({
462
+ "src/metrics/compute.ts"() {
463
+ "use strict";
464
+ init_segments();
465
+ init_queries();
466
+ init_context3();
467
+ init_revenue();
468
+ init_retention();
469
+ init_pipeline();
470
+ init_sales_efficiency();
471
+ init_unit_economics();
472
+ init_confidence();
473
+ init_periods();
474
+ init_context3();
475
+ }
476
+ });
477
+
478
+ // src/metrics/insights.ts
479
+ var init_insights = __esm({
480
+ "src/metrics/insights.ts"() {
481
+ "use strict";
482
+ init_coverage();
483
+ }
484
+ });
485
+
486
+ // src/ai/explore-mode.ts
487
+ var init_explore_mode = __esm({
488
+ "src/ai/explore-mode.ts"() {
489
+ "use strict";
490
+ init_context2();
491
+ }
492
+ });
493
+
494
+ // src/ai/llm/models-cache.ts
495
+ var CACHE_TTL_MS;
496
+ var init_models_cache = __esm({
497
+ "src/ai/llm/models-cache.ts"() {
498
+ "use strict";
499
+ init_store();
500
+ CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
501
+ }
502
+ });
503
+
504
+ // src/ai/llm/catalog.ts
505
+ var ENTRIES, byId;
506
+ var init_catalog = __esm({
507
+ "src/ai/llm/catalog.ts"() {
508
+ "use strict";
509
+ init_models_cache();
510
+ ENTRIES = [
511
+ {
512
+ id: "claude-opus-4-6",
513
+ provider: "anthropic",
514
+ tier: "high",
515
+ status: "active",
516
+ successor_id: null,
517
+ supports_tools: true,
518
+ max_context_tokens: 2e5,
519
+ display_name: "Claude Opus 4.6",
520
+ relative_cost: 3
521
+ },
522
+ {
523
+ id: "claude-sonnet-4-5-20250929",
524
+ provider: "anthropic",
525
+ tier: "medium",
526
+ status: "active",
527
+ successor_id: null,
528
+ supports_tools: true,
529
+ max_context_tokens: 2e5,
530
+ display_name: "Claude Sonnet 4.5",
531
+ relative_cost: 2
532
+ },
533
+ {
534
+ id: "claude-haiku-4-5-20251001",
535
+ provider: "anthropic",
536
+ tier: "low",
537
+ status: "active",
538
+ successor_id: null,
539
+ supports_tools: true,
540
+ max_context_tokens: 2e5,
541
+ display_name: "Claude Haiku 4.5",
542
+ relative_cost: 1
543
+ },
544
+ {
545
+ id: "gpt-4.1",
546
+ provider: "openai",
547
+ tier: "high",
548
+ status: "active",
549
+ successor_id: null,
550
+ supports_tools: true,
551
+ max_context_tokens: 1047576,
552
+ display_name: "GPT-4.1",
553
+ relative_cost: 3
554
+ },
555
+ {
556
+ id: "gpt-4.1-mini",
557
+ provider: "openai",
558
+ tier: "medium",
559
+ status: "active",
560
+ successor_id: null,
561
+ supports_tools: true,
562
+ max_context_tokens: 1047576,
563
+ display_name: "GPT-4.1 Mini",
564
+ relative_cost: 2
565
+ },
566
+ {
567
+ id: "gpt-4.1-nano",
568
+ provider: "openai",
569
+ tier: "low",
570
+ status: "active",
571
+ successor_id: null,
572
+ supports_tools: true,
573
+ max_context_tokens: 1047576,
574
+ display_name: "GPT-4.1 Nano",
575
+ relative_cost: 1
576
+ }
577
+ ];
578
+ byId = new Map(ENTRIES.map((e) => [e.id, e]));
579
+ }
580
+ });
581
+
582
+ // src/ai/llm/surfaces.ts
583
+ var init_surfaces = __esm({
584
+ "src/ai/llm/surfaces.ts"() {
585
+ "use strict";
586
+ }
587
+ });
588
+
589
+ // src/ai/llm/session-state.ts
590
+ var init_session_state = __esm({
591
+ "src/ai/llm/session-state.ts"() {
592
+ "use strict";
593
+ init_llm_config();
594
+ init_catalog();
595
+ init_surfaces();
596
+ }
597
+ });
598
+
599
+ // src/conversation/phase.ts
600
+ import chalk3 from "chalk";
601
+ function sessionHasData(ctx) {
602
+ const counts = ctx.dataset?.counts ?? {};
603
+ return Object.values(counts).some((n) => (n ?? 0) > 0);
604
+ }
605
+ function resolveConversationPhase(ctx) {
606
+ if (ctx.deliverIntent) return "deliver";
607
+ if (ctx.computeInProgress) return "compute";
608
+ if (ctx.strategistState && ctx.strategistState.step !== "awaiting_analysis") {
609
+ return "strategize";
610
+ }
611
+ if (isAnalysisReady(ctx)) return "explore";
612
+ const scope = ctx.scope;
613
+ if (scope?.confirmed_at) {
614
+ if (!sessionHasData(ctx)) return "awaiting_data";
615
+ if (ctx.stage !== "analyzed") return "awaiting_data";
616
+ }
617
+ if (scope?.intent_summary && !scope.confirmed_at) return "scope";
618
+ return "orient";
619
+ }
620
+ var init_phase = __esm({
621
+ "src/conversation/phase.ts"() {
622
+ "use strict";
623
+ init_context2();
624
+ init_repl_api();
625
+ init_explore_mode();
626
+ init_session_state();
627
+ init_theme();
628
+ }
629
+ });
630
+
631
+ // src/conversation/gap-audit.ts
632
+ var init_gap_audit = __esm({
633
+ "src/conversation/gap-audit.ts"() {
634
+ "use strict";
635
+ init_connection();
636
+ init_queries();
637
+ init_profile();
638
+ init_compute();
639
+ init_insights();
640
+ init_phase();
641
+ }
642
+ });
643
+
644
+ // src/strategies/library.ts
645
+ import { writeFileSync as writeFileSync6 } from "fs";
646
+ import { join as join6 } from "path";
647
+ import { stringify as stringifyYaml } from "yaml";
648
+ var init_library = __esm({
649
+ "src/strategies/library.ts"() {
650
+ "use strict";
651
+ init_store();
652
+ }
653
+ });
654
+
655
+ // src/io/types.ts
656
+ var init_types = __esm({
657
+ "src/io/types.ts"() {
658
+ "use strict";
659
+ }
660
+ });
661
+
662
+ // src/io/errors.ts
663
+ var init_errors = __esm({
664
+ "src/io/errors.ts"() {
665
+ "use strict";
666
+ init_types();
667
+ }
668
+ });
669
+
670
+ // src/services/strategist.ts
671
+ import { createHash } from "crypto";
672
+ var init_strategist = __esm({
673
+ "src/services/strategist.ts"() {
674
+ "use strict";
675
+ init_schema();
676
+ init_queries();
677
+ init_health_score();
678
+ init_divergence();
679
+ init_gap_audit();
680
+ init_library();
681
+ init_errors();
682
+ init_types();
683
+ init_formatters();
684
+ init_formatters();
685
+ }
686
+ });
687
+
688
+ // src/ai/llm/types.ts
689
+ var init_types2 = __esm({
690
+ "src/ai/llm/types.ts"() {
691
+ "use strict";
692
+ }
693
+ });
694
+
695
+ // src/config/install.ts
696
+ import { randomUUID as randomUUID2 } from "crypto";
697
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
698
+ import { join as join7 } from "path";
699
+ var init_install = __esm({
700
+ "src/config/install.ts"() {
701
+ "use strict";
702
+ init_store();
703
+ }
704
+ });
705
+
706
+ // src/config/progress-migrate.ts
707
+ import { existsSync as existsSync6, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync8 } from "fs";
708
+ import { join as join8 } from "path";
709
+ var init_progress_migrate = __esm({
710
+ "src/config/progress-migrate.ts"() {
711
+ "use strict";
712
+ init_store();
713
+ }
714
+ });
715
+
716
+ // src/whimsy/usage-backfill.ts
717
+ var init_usage_backfill = __esm({
718
+ "src/whimsy/usage-backfill.ts"() {
719
+ "use strict";
720
+ }
721
+ });
722
+
723
+ // src/config/progress.ts
724
+ import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync7, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "fs";
725
+ import { join as join9 } from "path";
726
+ var init_progress = __esm({
727
+ "src/config/progress.ts"() {
728
+ "use strict";
729
+ init_install();
730
+ init_progress_migrate();
731
+ init_store();
732
+ init_usage_backfill();
733
+ }
734
+ });
735
+
736
+ // src/whimsy/usage-stats.ts
737
+ var init_usage_stats = __esm({
738
+ "src/whimsy/usage-stats.ts"() {
739
+ "use strict";
740
+ init_progress();
741
+ }
742
+ });
743
+
744
+ // src/ai/llm/errors.ts
745
+ var init_errors2 = __esm({
746
+ "src/ai/llm/errors.ts"() {
747
+ "use strict";
748
+ init_types2();
749
+ }
750
+ });
751
+
752
+ // src/ai/llm/adapters/anthropic.ts
753
+ import Anthropic from "@anthropic-ai/sdk";
754
+ var init_anthropic = __esm({
755
+ "src/ai/llm/adapters/anthropic.ts"() {
756
+ "use strict";
757
+ init_errors2();
758
+ init_types2();
759
+ }
760
+ });
761
+
762
+ // src/ai/llm/adapters/openai-compat.ts
763
+ import OpenAI from "openai";
764
+ var init_openai_compat = __esm({
765
+ "src/ai/llm/adapters/openai-compat.ts"() {
766
+ "use strict";
767
+ init_errors2();
768
+ init_types2();
769
+ }
770
+ });
771
+
772
+ // src/ai/llm/http.ts
773
+ var init_http = __esm({
774
+ "src/ai/llm/http.ts"() {
775
+ "use strict";
776
+ }
777
+ });
778
+
779
+ // src/ai/llm/ranking.ts
780
+ var init_ranking = __esm({
781
+ "src/ai/llm/ranking.ts"() {
782
+ "use strict";
783
+ }
784
+ });
785
+
786
+ // src/ai/llm/discovery.ts
787
+ var init_discovery = __esm({
788
+ "src/ai/llm/discovery.ts"() {
789
+ "use strict";
790
+ init_llm_config();
791
+ init_http();
792
+ init_models_cache();
793
+ init_providers();
794
+ init_ranking();
795
+ }
796
+ });
797
+
798
+ // src/ai/llm/heal.ts
799
+ var init_heal = __esm({
800
+ "src/ai/llm/heal.ts"() {
801
+ "use strict";
802
+ init_store();
803
+ init_discovery();
804
+ init_models_cache();
805
+ }
806
+ });
807
+
808
+ // src/ai/llm/resolver.ts
809
+ var init_resolver = __esm({
810
+ "src/ai/llm/resolver.ts"() {
811
+ "use strict";
812
+ init_llm_config();
813
+ init_catalog();
814
+ init_session_state();
815
+ }
816
+ });
817
+
818
+ // src/ai/llm/failover.ts
819
+ var init_failover = __esm({
820
+ "src/ai/llm/failover.ts"() {
821
+ "use strict";
822
+ init_usage_stats();
823
+ init_anthropic();
824
+ init_openai_compat();
825
+ init_catalog();
826
+ init_discovery();
827
+ init_errors2();
828
+ init_heal();
829
+ init_models_cache();
830
+ init_providers();
831
+ init_types2();
832
+ init_resolver();
833
+ }
834
+ });
835
+
836
+ // src/ai/web-search.ts
837
+ var init_web_search = __esm({
838
+ "src/ai/web-search.ts"() {
839
+ "use strict";
840
+ init_store();
841
+ }
842
+ });
843
+
844
+ // src/ai/tool-schemas.ts
845
+ var init_tool_schemas = __esm({
846
+ "src/ai/tool-schemas.ts"() {
847
+ "use strict";
848
+ init_web_search();
849
+ }
850
+ });
851
+
852
+ // src/ai/privacy.ts
853
+ import { homedir as homedir3 } from "os";
854
+ import { join as join10 } from "path";
855
+ var AUDIT_DIR;
856
+ var init_privacy = __esm({
857
+ "src/ai/privacy.ts"() {
858
+ "use strict";
859
+ AUDIT_DIR = join10(homedir3(), ".ntrp", "audit");
860
+ }
861
+ });
862
+
863
+ // src/ai/untrusted.ts
864
+ var UNTRUSTED_MARKER_NAME, UNTRUSTED_MARKER_END_NAME, MARKER_SPOOF_PATTERN;
865
+ var init_untrusted = __esm({
866
+ "src/ai/untrusted.ts"() {
867
+ "use strict";
868
+ UNTRUSTED_MARKER_NAME = "EXTERNAL_UNTRUSTED_CONTENT";
869
+ UNTRUSTED_MARKER_END_NAME = "END_EXTERNAL_UNTRUSTED_CONTENT";
870
+ MARKER_SPOOF_PATTERN = new RegExp(
871
+ `<{2,}\\s*/?\\s*(?:${UNTRUSTED_MARKER_NAME}|${UNTRUSTED_MARKER_END_NAME})[^>]*>{2,}`,
872
+ "gi"
873
+ );
874
+ }
875
+ });
876
+
877
+ // src/ai/tool-handlers.ts
878
+ var init_tool_handlers = __esm({
879
+ "src/ai/tool-handlers.ts"() {
880
+ "use strict";
881
+ init_connection();
882
+ init_privacy();
883
+ init_web_search();
884
+ init_untrusted();
885
+ }
886
+ });
887
+
888
+ // src/ai/loop-guard.ts
889
+ var init_loop_guard = __esm({
890
+ "src/ai/loop-guard.ts"() {
891
+ "use strict";
892
+ }
893
+ });
894
+
895
+ // src/ai/thread.ts
896
+ var PRUNED_TOOL_RESULT;
897
+ var init_thread = __esm({
898
+ "src/ai/thread.ts"() {
899
+ "use strict";
900
+ PRUNED_TOOL_RESULT = JSON.stringify({
901
+ pruned: true,
902
+ note: "Old tool result cleared to free context \u2014 call the tool again if you still need it."
903
+ });
904
+ }
905
+ });
906
+
907
+ // src/data/playbook.ts
908
+ import { existsSync as existsSync8, readFileSync as readFileSync8, appendFileSync } from "fs";
909
+ import { join as join11 } from "path";
910
+ function playsPath() {
911
+ return join11(getMemoryDir(), PLAYS_FILE);
912
+ }
913
+ function getCustomPlays() {
914
+ const path = playsPath();
915
+ if (!existsSync8(path)) return [];
916
+ const out = [];
917
+ for (const line of readFileSync8(path, "utf-8").split("\n")) {
918
+ const trimmed = line.trim();
919
+ if (!trimmed) continue;
920
+ try {
921
+ const play = JSON.parse(trimmed);
922
+ out.push({ ...play, source: "learned" });
923
+ } catch {
924
+ }
925
+ }
926
+ return out;
927
+ }
928
+ function getAllPlays() {
929
+ return [...PLAYBOOK, ...getCustomPlays()];
930
+ }
931
+ function getPlaybook() {
932
+ return getAllPlays();
933
+ }
934
+ function matchTriggeredPlays(vitals2, layers) {
935
+ const bySign = new Map(vitals2.map((v) => [v.vital_sign, v]));
936
+ const out = [];
937
+ for (const layer of layers) {
938
+ for (const sign of layer.signs) {
939
+ const vital = bySign.get(sign);
940
+ if (!vital) continue;
941
+ const fires = vital.status === "red" || vital.score < VITAL_TRIGGER_THRESHOLDS[sign];
942
+ if (!fires) continue;
943
+ for (const play of getAllPlays()) {
944
+ if (play.trigger_vital_sign === sign) {
945
+ out.push({ play, vital, layer: layer.layer });
946
+ }
947
+ }
948
+ }
949
+ }
950
+ return out;
951
+ }
952
+ var PLAYBOOK, PLAYS_FILE, VITAL_TRIGGER_THRESHOLDS;
953
+ var init_playbook = __esm({
954
+ "src/data/playbook.ts"() {
955
+ "use strict";
956
+ init_store();
957
+ PLAYBOOK = [
958
+ {
959
+ id: "multi-thread-deals",
960
+ name: "Multi-Thread Your Deals",
961
+ trigger_vital_sign: "thread_depth",
962
+ trigger_condition: "thread_depth score < 2 (most deals have \u22641 active contact)",
963
+ why: "Single-threaded deals die when your one contact goes dark, changes roles, or loses budget authority. Every deal needs at least 2 active contacts to survive \u2014 and late-stage single-threading is a leading indicator of a slipped quarter.",
964
+ steps: [
965
+ "Pull single-threaded deals weighted by amount \u2014 one exposed mega-deal outranks ten small ones",
966
+ "Enrich the buying committee for each: map champion, economic buyer, and technical evaluator (enrichment waterfall or manual research)",
967
+ "Multi-thread through the existing contact first \u2014 a warm internal referral beats a cold second thread",
968
+ "Log every new contact with a role against the opportunity so thread depth is measured, not remembered",
969
+ "Install the mechanism: an alert when any deal past mid-stage has one active contact, and a job-change signal on champions so you hear about departures before the deal goes quiet"
970
+ ],
971
+ tools_that_help: ["Buying-committee enrichment (waterfall)", "Job-change signal tracking", "CRM contact roles", "Single-thread alerts"],
972
+ expected_outcome: "Thread depth score rises above threshold; single-threaded deal count drops by 50%+ within 2 weeks; zero late-stage deals with one thread"
973
+ },
974
+ {
975
+ id: "clean-dead-pipeline",
976
+ name: "Clean Dead Pipeline",
977
+ trigger_vital_sign: "freshness",
978
+ trigger_condition: "freshness score < 60",
979
+ why: "Stale accounts and zombie deals inflate your pipeline number but deliver zero revenue. They corrupt the forecast, and they hide the real coverage math \u2014 you can't fix what the CRM is lying about. Clearing them is also the cheapest pipeline you'll ever source: those records are already paid for.",
980
+ steps: [
981
+ "Split the stale pool into saveable vs already-dead: contacted-recently-enough-to-revive vs fiction to clear",
982
+ "Saveable deals: contact within 48 hours with a specific reason to talk, or move to Closed Lost \u2014 inaction is the worst choice",
983
+ "Dead-but-paid-for records: route into a signal-triggered reactivation track (funding, hiring, job-change, site-visit triggers) instead of deleting them",
984
+ "Stale organizations: re-verify ICP fit before re-working; archive what no longer fits so reps stop fishing in dead water",
985
+ "Install the mechanism: a stale-deal alert at N quiet days (calibrated to this motion's cycle), a weekly 15-minute hygiene scrub, and enrichment refresh on records that go quiet"
986
+ ],
987
+ tools_that_help: ["CRM bulk update", "Signal-based reactivation triggers", "Enrichment refresh (waterfall)", "Pipeline hygiene cadence"],
988
+ expected_outcome: "Freshness score jumps 20+ points; forecast reflects reality; reactivation track produces meetings at a fraction of cold-acquisition cost"
989
+ },
990
+ {
991
+ id: "fix-handoff-gap",
992
+ name: "Fix the Handoff Gap",
993
+ trigger_vital_sign: "drop_rate",
994
+ trigger_condition: "drop_rate score indicates >30% of marketing leads not reaching sales",
995
+ why: "Every lead that marketing generates but sales never sees is wasted budget and lost revenue. The marketing\u2192sales handoff is the #1 leak in most GTM motions \u2014 and it is almost always a systems failure (routing, sync, dead queues), not a people failure.",
996
+ steps: [
997
+ "Audit the leak by source: which lead sources exist only in marketing systems and never reach the CRM or a rep queue? The leak usually concentrates in one or two sources",
998
+ "Trace the routing path end-to-end: assignment rules, territory coverage, inactive-rep queues, and the marketing\u2192CRM sync itself \u2014 find where records fall on the floor",
999
+ "Fix the pipes: repair routing gaps, reassign orphaned queues, and dedupe/enrich records so routing has the fields it needs to route",
1000
+ "Set the SLA and instrument it: time-to-first-touch on handed-off leads, with a report someone owns",
1001
+ "Install the mechanism: an automated weekly marketing-only-leads report and an alert when any source's handoff rate degrades \u2014 so the leak can't quietly reopen"
1002
+ ],
1003
+ tools_that_help: ["Lead routing audit", "Enrichment waterfall (routing fields)", "SLA dashboard", "Handoff-degradation alerts"],
1004
+ expected_outcome: "Drop rate improves 15+ points; marketing-only lead count drops by 60%+; time-to-first-touch inside SLA"
1005
+ },
1006
+ {
1007
+ id: "retarget-effort",
1008
+ name: "Retarget Misdirected Effort",
1009
+ trigger_vital_sign: "signal_to_noise",
1010
+ trigger_condition: "signal_to_noise score < 50% (majority of activities not linked to pipeline)",
1011
+ why: "When reps spend more than half their time on activities unconnected to open pipeline, they're burning hours that could be closing deals. Persistent noise is a targeting-system problem \u2014 reps fish in the pond they can see because the account lists are stale \u2014 not a coaching problem.",
1012
+ steps: [
1013
+ "Cut noisy activity by rep and account status: dead accounts, closed deals, unlinked admin \u2014 name what dominates",
1014
+ "Fix the pond, not the fishing: rebuild rep focus lists from ICP fit and live signals (intent, hiring, funding, usage) instead of memory",
1015
+ "Route signals to reps in the channel they already work in, so the next action is the scored account, not the familiar one",
1016
+ "Set the ratio target and instrument it: 80% of weekly activities touch open pipeline or scored accounts, on a per-rep report",
1017
+ "Automate or delete the noise-generating busywork (logging, list building, manual research) so the time actually moves to pipeline"
1018
+ ],
1019
+ tools_that_help: ["Activity reports by rep", "ICP/propensity scoring", "Signal routing to rep channels", "Enrichment automation"],
1020
+ expected_outcome: "Signal-to-noise ratio improves to 70%+; rep hours shift measurably from dead accounts to scored pipeline"
1021
+ },
1022
+ {
1023
+ id: "unstick-pipeline",
1024
+ name: "Unstick the Pipeline",
1025
+ trigger_vital_sign: "flow_rate",
1026
+ trigger_condition: "flow_rate score < 50 (high average deal age or many stuck deals)",
1027
+ why: "Stuck deals block revenue and demoralize reps. A deal that hasn't moved in 14+ days (calibrate to this motion's cycle) is either dead or needs intervention \u2014 and stuck deals with past-due close dates are a forecast-credibility problem before they're a revenue problem.",
1028
+ steps: [
1029
+ "Pull stuck deals sorted by amount, and find the stage where they cluster \u2014 there is usually one stage where deals go to die",
1030
+ "For each stuck deal: name the blocker (no next step, waiting on prospect, internal approval, missing stakeholder) \u2014 'stuck' is a symptom, the blocker is the work",
1031
+ "Create a specific next action with a deadline for each; deals with no plausible next action get triaged to Closed Lost so the forecast tells the truth",
1032
+ "Fix the stage, not just the deals: add exit criteria and a required-next-step field to the stage where deals cluster",
1033
+ "Install the mechanism: an aging alert at the motion-calibrated threshold and automatic manager escalation past 2x median stage duration"
1034
+ ],
1035
+ tools_that_help: ["Deal inspection reports", "Stage exit criteria", "Aging alerts", "Manager escalation workflow"],
1036
+ expected_outcome: "Flow rate score improves 15+ points; stuck deal count drops by 40%+ within 2 weeks; the die-stage conversion measurably improves"
1037
+ },
1038
+ {
1039
+ id: "reduce-logo-churn",
1040
+ name: "Reduce Logo Churn",
1041
+ trigger_metric: "grr",
1042
+ trigger_lens: "revenue_metrics",
1043
+ trigger_condition: "GRR below motion benchmark or churned ARR elevated",
1044
+ why: "Revenue leaking from existing customers is the most expensive problem \u2014 you already paid to acquire them.",
1045
+ steps: [
1046
+ "Identify churned and at-risk accounts from retention metrics",
1047
+ "Segment churn by deal size, tenure, and product usage patterns",
1048
+ "Launch save plays for accounts showing contraction signals",
1049
+ "Audit renewal process: timing, stakeholders, and success criteria",
1050
+ "Implement early-warning triggers 90 days before renewal"
1051
+ ],
1052
+ tools_that_help: ["CS platform", "Renewal calendar", "NPS/CSAT surveys"],
1053
+ expected_outcome: "GRR improves toward motion benchmark within 2 quarters"
1054
+ },
1055
+ {
1056
+ id: "accelerate-expansion",
1057
+ name: "Accelerate Expansion",
1058
+ trigger_metric: "nrr",
1059
+ trigger_lens: "revenue_metrics",
1060
+ trigger_condition: "NRR below 100% with low expansion ARR",
1061
+ why: "Growing from installed base is cheaper than new logo acquisition \u2014 low expansion means untapped wallet share.",
1062
+ steps: [
1063
+ "List accounts with single-product adoption and upsell potential",
1064
+ "Map expansion triggers (seat growth, new use cases, tier upgrades)",
1065
+ "Assign expansion targets to CS and AE teams by account tier",
1066
+ "Create packaged upsell offers with clear ROI narratives",
1067
+ "Track expansion pipeline separately from new business"
1068
+ ],
1069
+ tools_that_help: ["Account plans", "Usage analytics", "Expansion playbooks"],
1070
+ expected_outcome: "Expansion ARR grows 20%+ quarter over quarter"
1071
+ },
1072
+ {
1073
+ id: "fix-renewal-process",
1074
+ name: "Fix the Renewal Process",
1075
+ trigger_metric: "contraction_arr",
1076
+ trigger_lens: "revenue_metrics",
1077
+ trigger_condition: "Contraction ARR > 0",
1078
+ why: "Downgrades are usually a process failure \u2014 late engagement, wrong stakeholders, or missing value proof.",
1079
+ steps: [
1080
+ "Pull all contraction events and categorize root cause",
1081
+ "Standardize renewal timeline: 120/90/60/30-day checkpoints",
1082
+ "Ensure economic buyer is engaged before renewal date",
1083
+ "Build ROI recap deck template for every renewal",
1084
+ "Escalate contractions >20% to leadership review"
1085
+ ],
1086
+ tools_that_help: ["Renewal workflow", "QBR templates", "Value realization reports"],
1087
+ expected_outcome: "Contraction ARR drops 50%+ within 2 quarters"
1088
+ },
1089
+ {
1090
+ id: "rebalance-pipeline-mix",
1091
+ name: "Rebalance Pipeline Mix",
1092
+ trigger_metric: "pipeline_coverage",
1093
+ trigger_lens: "revenue_metrics",
1094
+ trigger_condition: "Pipeline coverage red while win rate is healthy",
1095
+ why: "Strong win rate with weak coverage means qualification works but top-of-funnel is starving the machine.",
1096
+ steps: [
1097
+ "Compare pipeline created vs closed-won by source and segment",
1098
+ "Identify segments with coverage below benchmark",
1099
+ "Shift marketing and SDR effort toward under-covered segments",
1100
+ "Set weekly pipeline-created targets by rep",
1101
+ "Review discounting and stage inflation masking thin pipeline"
1102
+ ],
1103
+ tools_that_help: ["Pipeline analytics", "Marketing attribution", "Capacity planning"],
1104
+ expected_outcome: "Pipeline coverage reaches motion benchmark within 90 days"
1105
+ },
1106
+ {
1107
+ id: "compress-sales-cycle",
1108
+ name: "Compress the Sales Cycle",
1109
+ trigger_metric: "avg_sales_cycle",
1110
+ trigger_lens: "revenue_metrics",
1111
+ trigger_condition: "Avg sales cycle exceeds profile sales_cycle_days by 50%+",
1112
+ why: "Deals aging past your motion's norm tie up capacity and push revenue into future quarters.",
1113
+ steps: [
1114
+ "Analyze cycle time by stage \u2014 find where deals stall longest",
1115
+ "Implement stage-exit criteria with required next steps",
1116
+ "Introduce mutual action plans for deals past midpoint",
1117
+ "Escalate deals exceeding 2x median cycle to manager review",
1118
+ "Remove low-probability aged deals to free rep capacity"
1119
+ ],
1120
+ tools_that_help: ["Stage duration reports", "MAP templates", "Deal coaching"],
1121
+ expected_outcome: "Median cycle time drops 20%+ within one quarter"
1122
+ },
1123
+ {
1124
+ id: "improve-magic-number",
1125
+ name: "Improve Magic Number",
1126
+ trigger_metric: "magic_number",
1127
+ trigger_lens: "revenue_metrics",
1128
+ trigger_condition: "Magic number below motion benchmark (when spend data available)",
1129
+ why: "Low S&M efficiency means you're buying growth too expensively \u2014 burn rate outpaces sustainable unit economics.",
1130
+ steps: [
1131
+ "Calculate magic number by channel and segment",
1132
+ "Cut spend on channels with magic number below 0.5",
1133
+ "Double down on highest-efficiency acquisition motions",
1134
+ "Align CAC targets to motion-specific payback thresholds",
1135
+ "Review rep ramp time and quota attainment curves"
1136
+ ],
1137
+ tools_that_help: ["Finance model", "Channel ROI dashboard", "CAC by source"],
1138
+ expected_outcome: "Magic number improves toward benchmark within 2 quarters"
1139
+ }
1140
+ ];
1141
+ PLAYS_FILE = "plays.jsonl";
1142
+ VITAL_TRIGGER_THRESHOLDS = {
1143
+ freshness: 60,
1144
+ flow_rate: 50,
1145
+ drop_rate: 70,
1146
+ signal_to_noise: 50,
1147
+ thread_depth: 60
1148
+ };
1149
+ }
1150
+ });
1151
+
1152
+ // src/memory/play-outcomes.ts
1153
+ import { existsSync as existsSync9, readFileSync as readFileSync9, appendFileSync as appendFileSync2 } from "fs";
1154
+ import { join as join12 } from "path";
1155
+ import { randomUUID as randomUUID3 } from "crypto";
1156
+ var init_play_outcomes = __esm({
1157
+ "src/memory/play-outcomes.ts"() {
1158
+ "use strict";
1159
+ init_store();
1160
+ }
1161
+ });
1162
+
1163
+ // src/workflows/registry.ts
1164
+ var init_registry = __esm({
1165
+ "src/workflows/registry.ts"() {
1166
+ "use strict";
1167
+ }
1168
+ });
1169
+
1170
+ // src/ai/prompt-parts.ts
1171
+ import { existsSync as existsSync10, readFileSync as readFileSync10 } from "fs";
1172
+ import { join as join13 } from "path";
1173
+ var init_prompt_parts = __esm({
1174
+ "src/ai/prompt-parts.ts"() {
1175
+ "use strict";
1176
+ init_profile();
1177
+ init_store();
1178
+ init_playbook();
1179
+ init_play_outcomes();
1180
+ init_registry();
1181
+ }
1182
+ });
1183
+
1184
+ // src/ai/strategist-prompt.ts
1185
+ var init_strategist_prompt = __esm({
1186
+ "src/ai/strategist-prompt.ts"() {
1187
+ "use strict";
1188
+ init_prompt_parts();
1189
+ }
1190
+ });
1191
+
1192
+ // src/ai/json-response.ts
1193
+ var init_json_response = __esm({
1194
+ "src/ai/json-response.ts"() {
1195
+ "use strict";
1196
+ }
1197
+ });
1198
+
1199
+ // src/ai/strategist-validate.ts
1200
+ function extractNumbers(text) {
1201
+ const out = [];
1202
+ for (const match of text.matchAll(NUMBER_RE)) {
1203
+ const base = Number(match[1].replace(/,/g, ""));
1204
+ if (!Number.isFinite(base)) continue;
1205
+ const suffix = match[2]?.toLowerCase();
1206
+ out.push(suffix ? base * (SUFFIX_MULTIPLIER[suffix] ?? 1) : base);
1207
+ }
1208
+ return out;
1209
+ }
1210
+ function numbersMatch(a, b) {
1211
+ if (a === b) return true;
1212
+ if (a === 0 || b === 0) return Math.abs(a - b) < 0.5;
1213
+ return Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b)) <= 0.02;
1214
+ }
1215
+ function baselineAppearsInEvidence(value, evidenceNumbers) {
1216
+ const valueNumbers = extractNumbers(value);
1217
+ if (valueNumbers.length === 0) return false;
1218
+ return valueNumbers.some((v) => evidenceNumbers.some((e) => numbersMatch(v, e)));
1219
+ }
1220
+ function isKnownInstrument(measuredBy) {
1221
+ const lower = measuredBy.toLowerCase();
1222
+ return INSTRUMENT_TOKENS.some((token) => lower.includes(token));
1223
+ }
1224
+ function parseIsoDate(value) {
1225
+ if (typeof value !== "string") return null;
1226
+ const match = value.trim().match(ISO_DATE_RE);
1227
+ if (!match) return null;
1228
+ const date = /* @__PURE__ */ new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00Z`);
1229
+ return Number.isNaN(date.getTime()) ? null : date;
1230
+ }
1231
+ function toIso(date) {
1232
+ return date.toISOString().slice(0, 10);
1233
+ }
1234
+ function addDays(date, days) {
1235
+ const out = new Date(date);
1236
+ out.setUTCDate(out.getUTCDate() + days);
1237
+ return out;
1238
+ }
1239
+ function normalizeDate(value, today2, fallbackDays) {
1240
+ const parsed = parseIsoDate(value);
1241
+ if (parsed && parsed.getTime() >= today2.getTime()) {
1242
+ return { iso: toIso(parsed), repaired: false };
1243
+ }
1244
+ return { iso: toIso(addDays(today2, fallbackDays)), repaired: true };
1245
+ }
1246
+ function str(value) {
1247
+ return typeof value === "string" ? value.trim() : "";
1248
+ }
1249
+ function strArray(value) {
1250
+ if (!Array.isArray(value)) return [];
1251
+ return value.map(str).filter(Boolean);
1252
+ }
1253
+ function num(value, fallback) {
1254
+ const n = typeof value === "number" ? value : Number(value);
1255
+ return Number.isFinite(n) ? n : fallback;
1256
+ }
1257
+ function enumValue(value, allowed, fallback) {
1258
+ return typeof value === "string" && allowed.includes(value) ? value : fallback;
1259
+ }
1260
+ function hasNumber(text) {
1261
+ return extractNumbers(text).length > 0;
1262
+ }
1263
+ function validateOutcome(raw, label, evidenceNumbers, today2, fallbackDays) {
1264
+ if (!raw || typeof raw !== "object") {
1265
+ return { outcome: null, measurable: false, notes: [`${label}: missing \u2014 excluded from targets`] };
1266
+ }
1267
+ const record = raw;
1268
+ const metric = str(record.metric);
1269
+ const baseline = str(record.baseline);
1270
+ const targetRange = str(record.target_range);
1271
+ const measuredBy = str(record.measured_by);
1272
+ if (!metric) {
1273
+ return { outcome: null, measurable: false, notes: [`${label}: no metric named \u2014 excluded from targets`] };
1274
+ }
1275
+ const notes = [];
1276
+ let measurable = true;
1277
+ if (!hasNumber(baseline)) {
1278
+ measurable = false;
1279
+ notes.push(`${label} "${metric}": baseline is not a number \u2014 demoted to assumption`);
1280
+ } else if (!baselineAppearsInEvidence(baseline, evidenceNumbers)) {
1281
+ measurable = false;
1282
+ notes.push(`${label} "${metric}": baseline ${baseline} not found in grounded evidence \u2014 demoted to assumption`);
1283
+ }
1284
+ if (!hasNumber(targetRange)) {
1285
+ measurable = false;
1286
+ notes.push(`${label} "${metric}": target range has no number \u2014 demoted to assumption`);
1287
+ }
1288
+ if (!measuredBy || !isKnownInstrument(measuredBy)) {
1289
+ measurable = false;
1290
+ notes.push(`${label} "${metric}": measured_by "${measuredBy || "(empty)"}" is not a known instrument \u2014 demoted to assumption`);
1291
+ }
1292
+ const checkDate = normalizeDate(record.check_date, today2, fallbackDays);
1293
+ if (checkDate.repaired) {
1294
+ notes.push(`${label} "${metric}": check date repaired to ${checkDate.iso}`);
1295
+ }
1296
+ return {
1297
+ outcome: {
1298
+ metric,
1299
+ baseline: baseline || "unknown",
1300
+ target_range: targetRange || "unquantified",
1301
+ check_date: checkDate.iso,
1302
+ measured_by: measuredBy || "unspecified"
1303
+ },
1304
+ measurable,
1305
+ notes
1306
+ };
1307
+ }
1308
+ function validateMilestones(raw, today2, issues, workstreamTitle) {
1309
+ const out = [];
1310
+ if (Array.isArray(raw)) {
1311
+ for (const item of raw) {
1312
+ if (!item || typeof item !== "object") continue;
1313
+ const record = item;
1314
+ const label = str(record.label);
1315
+ const verification = str(record.verification);
1316
+ if (!label) continue;
1317
+ const due = normalizeDate(record.due, today2, 14);
1318
+ if (due.repaired) {
1319
+ issues.push(`Milestone "${label}" (${workstreamTitle}): due date repaired to ${due.iso}`);
1320
+ }
1321
+ if (!verification) {
1322
+ issues.push(`Milestone "${label}" (${workstreamTitle}): no verification method \u2014 flagged`);
1323
+ }
1324
+ out.push({ label, due: due.iso, verification: verification || "Verification method not specified \u2014 define before activating" });
1325
+ }
1326
+ }
1327
+ return out;
1328
+ }
1329
+ function validateDeliverables(raw, today2) {
1330
+ const out = [];
1331
+ if (Array.isArray(raw)) {
1332
+ for (const item of raw) {
1333
+ if (!item || typeof item !== "object") continue;
1334
+ const record = item;
1335
+ const label = str(record.label);
1336
+ if (!label) continue;
1337
+ out.push({
1338
+ label,
1339
+ kind: enumValue(record.kind, ["artifact", "process_change", "decision"], "artifact"),
1340
+ due: normalizeDate(record.due, today2, 21).iso
1341
+ });
1342
+ }
1343
+ }
1344
+ return out;
1345
+ }
1346
+ function validateContingency(raw, today2) {
1347
+ if (!raw || typeof raw !== "object") return null;
1348
+ const record = raw;
1349
+ const trigger = str(record.trigger);
1350
+ const fallback = str(record.fallback);
1351
+ if (!trigger || !fallback) return null;
1352
+ return {
1353
+ trigger,
1354
+ trigger_check_date: normalizeDate(record.trigger_check_date, today2, 21).iso,
1355
+ fallback
1356
+ };
1357
+ }
1358
+ function validPlayIds(value) {
1359
+ const allowed = new Set(getPlaybook().map((play) => play.id));
1360
+ return strArray(value).filter((id) => allowed.has(id));
1361
+ }
1362
+ function validateStrategistPlan(raw, opts) {
1363
+ const today2 = parseIsoDate(opts.todayIso) ?? /* @__PURE__ */ new Date();
1364
+ const evidenceNumbers = extractNumbers(opts.evidenceText);
1365
+ const issues = [];
1366
+ const demotedAssumptions = [];
1367
+ let measurableTargets = 0;
1368
+ let totalTargets = 0;
1369
+ const rawWorkstreams = Array.isArray(raw.workstreams) ? raw.workstreams : [];
1370
+ const workstreams = [];
1371
+ for (const [index, item] of rawWorkstreams.entries()) {
1372
+ if (!item || typeof item !== "object") continue;
1373
+ const record = item;
1374
+ const title = str(record.title) || `Workstream ${index + 1}`;
1375
+ const outcomeCheck = validateOutcome(record.expected_outcome, "Expected outcome", evidenceNumbers, today2, 30);
1376
+ totalTargets += outcomeCheck.outcome ? 1 : 0;
1377
+ if (outcomeCheck.measurable) measurableTargets++;
1378
+ for (const note of outcomeCheck.notes) issues.push(`${title}: ${note}`);
1379
+ if (outcomeCheck.outcome && !outcomeCheck.measurable) {
1380
+ demotedAssumptions.push(
1381
+ `Unverified expectation (${title}): ${outcomeCheck.outcome.metric} ${outcomeCheck.outcome.baseline} -> ${outcomeCheck.outcome.target_range} \u2014 quantify against grounded data before treating as a target`
1382
+ );
1383
+ }
1384
+ const leadingIndicators = [];
1385
+ if (Array.isArray(record.leading_indicators)) {
1386
+ for (const li of record.leading_indicators) {
1387
+ const check = validateOutcome(li, "Leading indicator", evidenceNumbers, today2, 14);
1388
+ if (!check.outcome) continue;
1389
+ totalTargets++;
1390
+ if (check.measurable) {
1391
+ measurableTargets++;
1392
+ leadingIndicators.push(check.outcome);
1393
+ } else {
1394
+ for (const note of check.notes) issues.push(`${title}: ${note}`);
1395
+ demotedAssumptions.push(
1396
+ `Unverified indicator (${title}): ${check.outcome.metric} \u2014 not measurable as stated`
1397
+ );
1398
+ }
1399
+ }
1400
+ }
1401
+ let milestones = validateMilestones(record.milestones, today2, issues, title);
1402
+ if (milestones.length === 0 && outcomeCheck.outcome) {
1403
+ milestones = [{
1404
+ label: `Outcome check: ${outcomeCheck.outcome.metric}`,
1405
+ due: outcomeCheck.outcome.check_date,
1406
+ verification: `${outcomeCheck.outcome.measured_by} shows ${outcomeCheck.outcome.target_range}`
1407
+ }];
1408
+ issues.push(`${title}: no dated milestones \u2014 derived one from the expected outcome`);
1409
+ }
1410
+ if (!outcomeCheck.outcome && milestones.length === 0) {
1411
+ issues.push(`${title}: no measurable outcome and no milestones \u2014 workstream demoted to assumption`);
1412
+ demotedAssumptions.push(`Dropped workstream "${title}" \u2014 had no measurable outcome or dated milestone`);
1413
+ continue;
1414
+ }
1415
+ const contingency = validateContingency(record.contingency, today2);
1416
+ if (!contingency) {
1417
+ issues.push(`${title}: contingency missing or incomplete \u2014 flagged for definition at first review`);
1418
+ }
1419
+ workstreams.push({
1420
+ order: num(record.order, workstreams.length + 1),
1421
+ title,
1422
+ problem: str(record.problem) || "Problem statement not captured",
1423
+ rationale: str(record.rationale) || "Sequence rationale not captured",
1424
+ play_ids: validPlayIds(record.play_ids),
1425
+ actions: strArray(record.actions),
1426
+ effort_hours: Math.max(0, num(record.effort_hours, 8)),
1427
+ milestones,
1428
+ deliverables: validateDeliverables(record.deliverables, today2),
1429
+ expected_outcome: outcomeCheck.outcome ?? {
1430
+ metric: "unspecified",
1431
+ baseline: "unknown",
1432
+ target_range: "unquantified",
1433
+ check_date: toIso(addDays(today2, 30)),
1434
+ measured_by: "unspecified"
1435
+ },
1436
+ leading_indicators: leadingIndicators,
1437
+ contingency: contingency ?? {
1438
+ trigger: "Define trigger at first review",
1439
+ trigger_check_date: toIso(addDays(today2, 21)),
1440
+ fallback: "Define fallback at first review"
1441
+ }
1442
+ });
1443
+ }
1444
+ if (workstreams.length === 0) return null;
1445
+ workstreams.sort((a, b) => a.order - b.order);
1446
+ workstreams.forEach((ws, i) => {
1447
+ ws.order = i + 1;
1448
+ });
1449
+ const capped = workstreams.slice(0, 5);
1450
+ if (workstreams.length > 5) {
1451
+ issues.push(`Plan proposed ${workstreams.length} workstreams \u2014 capped to 5 (focus beats coverage)`);
1452
+ }
1453
+ const rawConfidence = Math.min(1, Math.max(0, num(raw.confidence, 0.6)));
1454
+ const confidence = Math.max(0.2, rawConfidence - demotedAssumptions.length * 0.05);
1455
+ const plan = {
1456
+ title: str(raw.title) || "Untitled Strategy",
1457
+ objective: str(raw.objective) || "Objective not restated",
1458
+ summary_30k: str(raw.summary_30k) || str(raw.hypothesis) || "Executive summary not captured",
1459
+ hypothesis: str(raw.hypothesis) || "If the workstreams execute in order, the objective metrics should move within their target ranges.",
1460
+ target_segment: str(raw.target_segment) || "Whole pipeline",
1461
+ priority: enumValue(raw.priority, ["low", "medium", "high"], "medium"),
1462
+ review_cadence: str(raw.review_cadence) || "Weekly",
1463
+ confidence,
1464
+ constraints: strArray(raw.constraints),
1465
+ assumptions: [...strArray(raw.assumptions), ...demotedAssumptions],
1466
+ risks: strArray(raw.risks),
1467
+ workstreams: capped
1468
+ };
1469
+ return { plan, issues, measurableTargets, totalTargets };
1470
+ }
1471
+ var NUMBER_RE, SUFFIX_MULTIPLIER, INSTRUMENT_TOKENS, ISO_DATE_RE;
1472
+ var init_strategist_validate = __esm({
1473
+ "src/ai/strategist-validate.ts"() {
1474
+ "use strict";
1475
+ init_playbook();
1476
+ init_json_response();
1477
+ NUMBER_RE = /\$?\s*(\d[\d,]*\.?\d*)\s*(m|k|b|million|thousand|billion)?\b/gi;
1478
+ SUFFIX_MULTIPLIER = {
1479
+ k: 1e3,
1480
+ thousand: 1e3,
1481
+ m: 1e6,
1482
+ million: 1e6,
1483
+ b: 1e9,
1484
+ billion: 1e9
1485
+ };
1486
+ INSTRUMENT_TOKENS = [
1487
+ // vital signs + components
1488
+ "freshness",
1489
+ "flow_rate",
1490
+ "flow rate",
1491
+ "drop_rate",
1492
+ "drop rate",
1493
+ "signal_to_noise",
1494
+ "signal-to-noise",
1495
+ "signal to noise",
1496
+ "thread_depth",
1497
+ "thread depth",
1498
+ "health score",
1499
+ "vital",
1500
+ "gating",
1501
+ "score",
1502
+ // SaaS metrics lane
1503
+ "arr",
1504
+ "nrr",
1505
+ "grr",
1506
+ "net revenue retention",
1507
+ "gross revenue retention",
1508
+ "win rate",
1509
+ "pipeline coverage",
1510
+ "weighted pipeline",
1511
+ "velocity",
1512
+ "deal size",
1513
+ "sales cycle",
1514
+ "conversion",
1515
+ "ltv",
1516
+ "cac",
1517
+ "payback",
1518
+ "magic number",
1519
+ "churn",
1520
+ "expansion",
1521
+ "retention",
1522
+ // countable pipeline entities + states
1523
+ "count",
1524
+ "stale",
1525
+ "stuck",
1526
+ "single-threaded",
1527
+ "single threaded",
1528
+ "zombie",
1529
+ "dollar",
1530
+ "pipeline at risk",
1531
+ "opportunit",
1532
+ "deal",
1533
+ "activity",
1534
+ "activities",
1535
+ "contact",
1536
+ "lead",
1537
+ "account",
1538
+ "segment",
1539
+ "handoff",
1540
+ "past-due",
1541
+ "past due",
1542
+ // the review instrument itself
1543
+ "strategy review",
1544
+ "metric_readings",
1545
+ "vital_sign_readings",
1546
+ "entity count"
1547
+ ];
1548
+ ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})/;
1549
+ }
1550
+ });
1551
+
1552
+ // src/ai/strategist.ts
1553
+ var init_strategist2 = __esm({
1554
+ "src/ai/strategist.ts"() {
1555
+ "use strict";
1556
+ init_types2();
1557
+ init_failover();
1558
+ init_surfaces();
1559
+ init_llm_config();
1560
+ init_repl_api();
1561
+ init_tool_schemas();
1562
+ init_web_search();
1563
+ init_tool_handlers();
1564
+ init_loop_guard();
1565
+ init_thread();
1566
+ init_strategist_prompt();
1567
+ init_strategist_validate();
1568
+ }
1569
+ });
1570
+
1571
+ // src/ui/layout.ts
1572
+ var init_layout = __esm({
1573
+ "src/ui/layout.ts"() {
1574
+ "use strict";
1575
+ }
1576
+ });
1577
+
1578
+ // src/output/strategy-brief.ts
1579
+ import chalk4 from "chalk";
1580
+ var init_strategy_brief = __esm({
1581
+ "src/output/strategy-brief.ts"() {
1582
+ "use strict";
1583
+ init_theme();
1584
+ init_layout();
1585
+ }
1586
+ });
1587
+
1588
+ // src/output/llm-attribution.ts
1589
+ import chalk5 from "chalk";
1590
+ var init_llm_attribution = __esm({
1591
+ "src/output/llm-attribution.ts"() {
1592
+ "use strict";
1593
+ init_catalog();
1594
+ }
1595
+ });
1596
+
1597
+ // src/whimsy/time-milestones.ts
1598
+ var init_time_milestones = __esm({
1599
+ "src/whimsy/time-milestones.ts"() {
1600
+ "use strict";
1601
+ }
1602
+ });
1603
+
1604
+ // src/whimsy/time-perspectives.ts
1605
+ var TIME_PERSPECTIVES;
1606
+ var init_time_perspectives = __esm({
1607
+ "src/whimsy/time-perspectives.ts"() {
1608
+ "use strict";
1609
+ TIME_PERSPECTIVES = [
1610
+ { 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 },
1611
+ { id: "rush_2112", category: "music", reference_hours: 0.33, label: "2112", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 2, max_ratio: 200 },
1612
+ { id: "bohemian_rhapsody", category: "music", reference_hours: 0.1, label: "Bohemian Rhapsody", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 5, max_ratio: 500 },
1613
+ { id: "stairway", category: "music", reference_hours: 0.13, label: "Stairway to Heaven", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 5, max_ratio: 400 },
1614
+ { 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 },
1615
+ { id: "abbey_road", category: "music", reference_hours: 0.8, label: "Abbey Road", template: "\u2248 {ratio}\xD7 through {label}", min_ratio: 1, max_ratio: 200 },
1616
+ { 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 },
1617
+ { 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 },
1618
+ { 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 },
1619
+ { 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 },
1620
+ { 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 },
1621
+ { id: "blockbuster", category: "film", reference_hours: 2.1, label: "average blockbusters", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 100 },
1622
+ { 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 },
1623
+ { id: "scorsese", category: "film", reference_hours: 3.5, label: "Goodfellas", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 80 },
1624
+ { id: "godfather", category: "film", reference_hours: 6.5, label: "the Godfather saga", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 20 },
1625
+ { 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 },
1626
+ { 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 },
1627
+ { 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 },
1628
+ { 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 },
1629
+ { 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 },
1630
+ { id: "soccer_match", category: "sports", reference_hours: 1.75, label: "Premier League matches", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 150 },
1631
+ { id: "marathon", category: "sports", reference_hours: 2, label: "marathons at world-record pace", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 80 },
1632
+ { 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 },
1633
+ { id: "superbowl", category: "sports", reference_hours: 3.5, label: "Super Bowls", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 80 },
1634
+ { 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 },
1635
+ { id: "wimbledon", category: "sports", reference_hours: 5, label: "Wimbledon finals", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
1636
+ { 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 },
1637
+ { id: "olympics", category: "sports", reference_hours: 250, label: "Summer Olympics broadcast hours", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 10 },
1638
+ { 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 },
1639
+ { id: "iss_orbit", category: "cosmos", reference_hours: 1.5, label: "ISS orbits", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 200 },
1640
+ { 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 },
1641
+ { 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 },
1642
+ { 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 },
1643
+ { 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 },
1644
+ { id: "earth_rotation", category: "cosmos", reference_hours: 24, label: "Earth rotations", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.1, max_ratio: 50 },
1645
+ { 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 },
1646
+ { id: "lunar_month", category: "cosmos", reference_hours: 708, label: "a lunar cycle", template: "\u2248 {pct}% of {label}", min_ratio: 0.05, max_ratio: 2 },
1647
+ { 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 },
1648
+ { 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 },
1649
+ { id: "standup", category: "gtm", reference_hours: 0.25, label: "daily standups", template: "\u2248 {ratio}\xD7 skipped {label}", min_ratio: 4, max_ratio: 500 },
1650
+ { id: "quick_sync", category: "gtm", reference_hours: 0.5, label: "avoided 'quick syncs'", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 2, max_ratio: 200 },
1651
+ { id: "pipeline_review", category: "gtm", reference_hours: 1, label: "weekly pipeline reviews", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 200 },
1652
+ { id: "forecast_call", category: "gtm", reference_hours: 1.5, label: "forecast calls", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 150 },
1653
+ { id: "pivot_spiral", category: "gtm", reference_hours: 2, label: "spreadsheet pivot-table spirals", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 1, max_ratio: 100 },
1654
+ { 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 },
1655
+ { id: "crm_cleanup", category: "gtm", reference_hours: 6, label: "CRM hygiene sprints", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.5, max_ratio: 40 },
1656
+ { id: "qbr_prep", category: "gtm", reference_hours: 8, label: "QBR prep blocks", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 20 },
1657
+ { id: "board_deck", category: "gtm", reference_hours: 12, label: "board deck builds", template: "\u2248 {ratio}\xD7 {label}", min_ratio: 0.3, max_ratio: 30 },
1658
+ { 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 },
1659
+ { 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 }
1660
+ ];
1661
+ }
1662
+ });
1663
+
1664
+ // src/whimsy/time-bank-whimsy.ts
1665
+ var init_time_bank_whimsy = __esm({
1666
+ "src/whimsy/time-bank-whimsy.ts"() {
1667
+ "use strict";
1668
+ }
1669
+ });
1670
+
1671
+ // src/whimsy/perspective-rotation.ts
1672
+ var PERSPECTIVE_ROTATE_CALENDAR_MS;
1673
+ var init_perspective_rotation = __esm({
1674
+ "src/whimsy/perspective-rotation.ts"() {
1675
+ "use strict";
1676
+ PERSPECTIVE_ROTATE_CALENDAR_MS = 7 * 24 * 60 * 60 * 1e3;
1677
+ }
1678
+ });
1679
+
1680
+ // src/whimsy/time-bank.ts
1681
+ import chalk6 from "chalk";
1682
+ var init_time_bank = __esm({
1683
+ "src/whimsy/time-bank.ts"() {
1684
+ "use strict";
1685
+ init_progress();
1686
+ init_theme();
1687
+ init_time_milestones();
1688
+ init_time_perspectives();
1689
+ init_time_bank_whimsy();
1690
+ init_perspective_rotation();
1691
+ init_usage_stats();
1692
+ }
1693
+ });
1694
+
1695
+ // src/conversation/strategist-flow.ts
1696
+ import ora from "ora";
1697
+ import chalk7 from "chalk";
1698
+ function isStrategistIntent(input) {
1699
+ const line = input.trim();
1700
+ if (!line) return false;
1701
+ if (isShipIntent(line)) return false;
1702
+ return STRATEGIST_INTENT_RE.test(line);
1703
+ }
1704
+ function extractObjectiveSeed(input) {
1705
+ const cleaned = input.trim().replace(/^(hey|ok|okay|please|can you|could you|help me|let'?s|i want to|i'?d like to|i need to)\s+/i, "").replace(/^(build|draft|make|create|put together)\s+(me\s+)?(a\s+|the\s+)?(game\s?plan|battle\s?plan|strategy|plan|roadmap)\s*(to|for|around|on)?\s*/i, "").replace(/^strategize\s+(about|around|on|for)?\s*/i, "").trim();
1706
+ return cleaned.length >= 8 ? cleaned : input.trim();
1707
+ }
1708
+ var STRATEGIST_INTENT_RE;
1709
+ var init_strategist_flow = __esm({
1710
+ "src/conversation/strategist-flow.ts"() {
1711
+ "use strict";
1712
+ init_context2();
1713
+ init_handoff_draft();
1714
+ init_repl_api();
1715
+ init_theme();
1716
+ init_prompts();
1717
+ init_health_score();
1718
+ init_divergence();
1719
+ init_strategist();
1720
+ init_strategist2();
1721
+ init_strategy_brief();
1722
+ init_llm_attribution();
1723
+ init_time_bank();
1724
+ init_formatters();
1725
+ STRATEGIST_INTENT_RE = /\b(strateg(y|ize|ic)|game\s?plan|battle\s?plan|roadmap|(build|draft|make|create|put together)\s+(me\s+)?(a\s+|the\s+)?plan\b|plan\s+(to|for)\s+(fix|improv|reduc|recover|hit|reach|get|grow|turn)|how\s+(should|do|can)\s+we\s+(fix|approach|tackle|attack|prioritize|sequence|turn\s+(this|it)\s+around)|what\s+should\s+we\s+(do|fix|tackle|prioritize|focus\s+on)\s+(first|next)|what\s+order\s+should|where\s+(do|should)\s+we\s+start)\b/i;
1726
+ }
1727
+ });
1728
+
1729
+ // src/strategist/strategist-smoke.ts
1730
+ init_strategist_flow();
1731
+ init_phase();
1732
+ init_context2();
1733
+ init_strategist_validate();
1734
+ init_playbook();
1735
+ init_health_score();
1736
+ var failures = [];
1737
+ function assert(cond, msg) {
1738
+ if (!cond) failures.push(msg);
1739
+ }
1740
+ assert(isStrategistIntent("how should we fix drop rate before the board?"), "strategist intent: how should we fix");
1741
+ assert(isStrategistIntent("build me a game plan to recover pipeline"), "strategist intent: game plan");
1742
+ assert(isStrategistIntent("what should we prioritize first"), "strategist intent: prioritize");
1743
+ assert(!isStrategistIntent("ship a board deck"), "ship intent must not match strategist");
1744
+ assert(!isStrategistIntent("what is our NRR?"), "descriptive question must not match strategist");
1745
+ var seed = extractObjectiveSeed("help me build a plan to fix stale pipeline");
1746
+ assert(seed.includes("stale pipeline"), "objective seed strips lead-in verbs");
1747
+ function mockCtx(partial) {
1748
+ return {
1749
+ sessionId: "2026-07-03-test",
1750
+ sessionFile: "/tmp/test.json",
1751
+ oneShot: false,
1752
+ execution: { mode: "interactive", output: "terminal", color: true, progress: true, quiet: false },
1753
+ snapshot: { computeResult: null, divergences: [] },
1754
+ messages: [],
1755
+ conversation: [],
1756
+ stage: "analyzed",
1757
+ deliverables: [],
1758
+ analysis: defaultSessionAnalysis(),
1759
+ wizardDepth: 0,
1760
+ attachments: [],
1761
+ deliverIntent: false,
1762
+ computeInProgress: false,
1763
+ dataset: { counts: { opportunities: 10 } },
1764
+ ...partial
1765
+ };
1766
+ }
1767
+ assert(
1768
+ resolveConversationPhase(mockCtx({ strategistState: { step: "objective_confirm", objective: "fix freshness" } })) === "strategize",
1769
+ "objective_confirm \u2192 strategize phase"
1770
+ );
1771
+ assert(
1772
+ resolveConversationPhase(
1773
+ mockCtx({
1774
+ strategistState: { step: "awaiting_analysis", objective: "fix pipeline" },
1775
+ stage: "new",
1776
+ scope: { intent_summary: "health", primary_lens: "gtm_health", confirmed_at: (/* @__PURE__ */ new Date()).toISOString() }
1777
+ })
1778
+ ) === "awaiting_data",
1779
+ "awaiting_analysis rides normal funnel (not strategize)"
1780
+ );
1781
+ var evidence = JSON.stringify({
1782
+ vital_signs: { freshness: { score: 29, dollar_value: 31e5 } }
1783
+ });
1784
+ var today = "2026-07-03";
1785
+ var validPlan = {
1786
+ title: "Q4 Pipeline Recovery",
1787
+ objective: "Cut stale pipeline before board",
1788
+ summary_30k: "Freshness gates everything.",
1789
+ hypothesis: "Cleaning stale deals unlocks flow fixes.",
1790
+ target_segment: "Enterprise pipeline",
1791
+ priority: "high",
1792
+ review_cadence: "Weekly",
1793
+ confidence: 0.7,
1794
+ constraints: ["6 rep-hours/week"],
1795
+ assumptions: [],
1796
+ risks: ["Rep capacity"],
1797
+ workstreams: [
1798
+ {
1799
+ order: 1,
1800
+ title: "Clean dead pipeline",
1801
+ problem: "Stale deals block trust in the pipeline number",
1802
+ rationale: "Freshness is the gating vital sign",
1803
+ play_ids: ["clean-dead-pipeline"],
1804
+ actions: ["Pull stale list", "Re-engage or close"],
1805
+ effort_hours: 12,
1806
+ milestones: [{ label: "Stale list triaged", due: "2026-07-17", verification: "stale count < 40" }],
1807
+ deliverables: [{ label: "Re-engagement sequence", kind: "artifact", due: "2026-07-24" }],
1808
+ expected_outcome: {
1809
+ metric: "freshness score",
1810
+ baseline: "29",
1811
+ target_range: "45\u201355",
1812
+ check_date: "2026-08-01",
1813
+ measured_by: "freshness vital sign score"
1814
+ },
1815
+ leading_indicators: [
1816
+ {
1817
+ metric: "stale deal count",
1818
+ baseline: "120",
1819
+ target_range: "80\u201390",
1820
+ check_date: "2026-07-20",
1821
+ measured_by: "freshness entity_details stale count"
1822
+ }
1823
+ ],
1824
+ contingency: {
1825
+ trigger: "stale count flat by week 2",
1826
+ trigger_check_date: "2026-07-20",
1827
+ fallback: "Descope to top-2 segments only"
1828
+ }
1829
+ }
1830
+ ]
1831
+ };
1832
+ var validated = validateStrategistPlan(validPlan, { evidenceText: evidence + " score 29 dollar 3100000 stale 120", todayIso: today });
1833
+ assert(validated !== null, "valid plan parses");
1834
+ assert(validated.plan.workstreams.length === 1, "valid plan keeps workstream");
1835
+ assert(validated.measurableTargets >= 1, "valid plan has measurable targets");
1836
+ assert(isKnownInstrument("freshness vital sign score"), "freshness is known instrument");
1837
+ var vaguePlan = {
1838
+ ...validPlan,
1839
+ workstreams: [
1840
+ {
1841
+ ...validPlan.workstreams[0],
1842
+ expected_outcome: {
1843
+ metric: "team morale",
1844
+ baseline: "low",
1845
+ target_range: "much better",
1846
+ check_date: "2026-08-01",
1847
+ measured_by: "gut feel"
1848
+ }
1849
+ }
1850
+ ]
1851
+ };
1852
+ var demoted = validateStrategistPlan(vaguePlan, { evidenceText: evidence, todayIso: today });
1853
+ assert(demoted !== null, "vague plan still returns structure");
1854
+ assert(demoted.plan.assumptions.length > 0, "vague outcome demoted to assumptions");
1855
+ var vitals = ["freshness", "flow_rate", "thread_depth"].map((sign) => ({
1856
+ vital_sign: sign,
1857
+ score: sign === "freshness" ? 29 : sign === "flow_rate" ? 40 : 70,
1858
+ status: sign === "freshness" ? "red" : "yellow",
1859
+ dollar_value: sign === "freshness" ? 31e5 : null,
1860
+ dollar_label: sign === "freshness" ? "pipeline at risk" : null
1861
+ }));
1862
+ var triggered = matchTriggeredPlays(vitals, LAYERS);
1863
+ assert(triggered.length >= 1, "keyless skeleton triggers at least one play");
1864
+ assert(triggered[0].layer === 1, "first triggered play respects LAYERS order (freshness first)");
1865
+ var nums = extractNumbers("$3.1M stale pipeline, 120 deals");
1866
+ assert(nums.some((n) => n >= 3e6), "extractNumbers parses $3.1M");
1867
+ if (failures.length > 0) {
1868
+ console.error("FAIL strategist-smoke:");
1869
+ for (const f of failures) console.error(" -", f);
1870
+ process.exit(1);
1871
+ }
1872
+ console.log("PASS strategist-smoke");
1873
+ //# sourceMappingURL=strategist-smoke.js.map