-
-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Expand file tree
/
Copy pathanalyze-patterns.mjs
More file actions
1413 lines (1284 loc) · 64.3 KB
/
Copy pathanalyze-patterns.mjs
File metadata and controls
1413 lines (1284 loc) · 64.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* analyze-patterns.mjs — Rejection Pattern Detector for career-ops
*
* Parses applications.md + all linked reports, extracts dimensions
* (archetype, seniority, remote, gaps, scores), classifies outcomes,
* and outputs structured JSON with actionable patterns.
*
* Run: node analyze-patterns.mjs (JSON to stdout)
* node analyze-patterns.mjs --summary (human-readable table)
* node analyze-patterns.mjs --min-threshold 3
* node analyze-patterns.mjs --min-vendor-n 8 (per-vendor sample floor)
* node analyze-patterns.mjs --self-test
*/
import { readFileSync, existsSync, realpathSync, writeFileSync, symlinkSync, rmSync } from 'fs';
import { join, dirname, relative, sep } from 'path';
import { fileURLToPath } from 'url';
import { load as yamlLoad } from 'js-yaml';
import { resolveColumns, parseTrackerRow, normalizeVia } from './tracker-parse.mjs';
import { getCareerOpsRoot } from './path-resolver.mjs';
const CAREER_OPS = getCareerOpsRoot();
const APPS_FILE = existsSync(join(CAREER_OPS, 'data/applications.md'))
? join(CAREER_OPS, 'data/applications.md')
: join(CAREER_OPS, 'applications.md');
const REPORTS_DIR = join(CAREER_OPS, 'reports');
const MACHINE_SUMMARY_FIELDS = new Set([
'company',
'role',
'score',
'legitimacy_tier',
'archetype',
'final_decision',
'hard_stops',
'soft_gaps',
'top_strengths',
'risk_level',
'confidence',
'next_action',
// Optional context fields accepted for future reports.
'domain',
'seniority',
'remote',
'team_size',
// Issue 1380: predicted skip/discard reasons from the agent.
'discard_reasons',
'advertised_comp',
'via',
'company_confidential',
'risk_summary',
// Work-authorization / visa-sponsorship tier from Block A (report + Machine
// Summary only). Allowlisted so it round-trips; no consumer logic yet.
'work_auth',
// Reporting line stated by the JD, verbatim (report + Machine Summary only).
// Allowlisted so it round-trips; no consumer logic yet.
'reports_to',
]);
// --- CLI args ---
const args = process.argv.slice(2);
const summaryMode = args.includes('--summary');
const minThresholdIdx = args.indexOf('--min-threshold');
const MIN_THRESHOLD = minThresholdIdx !== -1 && args[minThresholdIdx + 1] !== undefined
? (Number.isNaN(parseInt(args[minThresholdIdx + 1])) ? 5 : parseInt(args[minThresholdIdx + 1]))
: 5;
// Minimum per-vendor sample before a channel-yield recommendation fires. Kept
// modest (small trackers) but high enough that one unlucky bucket isn't a claim.
const minVendorNIdx = args.indexOf('--min-vendor-n');
const MIN_VENDOR_N = (() => {
if (minVendorNIdx === -1 || args[minVendorNIdx + 1] === undefined) return 8;
const n = parseInt(args[minVendorNIdx + 1], 10);
// Reject 0/negative: a floor of 0 makes sufficientSample always true and
// silently defeats the "don't claim on noise" guard the whole feature rests on.
return Number.isNaN(n) || n < 1 ? 8 : n;
})();
// --- Status normalization (mirrors verify-pipeline.mjs) ---
const ALIASES = {
'evaluada': 'evaluated', 'condicional': 'evaluated', 'hold': 'evaluated',
'evaluar': 'evaluated', 'verificar': 'evaluated',
'aplicado': 'applied', 'enviada': 'applied', 'aplicada': 'applied',
'applied': 'applied', 'sent': 'applied',
'respondido': 'responded',
'entrevista': 'interview',
'oferta': 'offer',
'rechazado': 'rejected', 'rechazada': 'rejected',
'contratado': 'hired', 'contratada': 'hired', 'accepted': 'hired', 'accept': 'hired',
'descartado': 'discarded', 'descartada': 'discarded',
'cerrada': 'discarded', 'cancelada': 'discarded',
'no aplicar': 'skip', 'no_aplicar': 'skip', 'monitor': 'skip', 'geo blocker': 'skip',
};
function normalizeStatus(raw) {
const clean = raw.replace(/\*\*/g, '').trim().toLowerCase()
.replace(/\s+\d{4}-\d{2}-\d{2}.*$/, '').trim();
return ALIASES[clean] || clean;
}
function classifyOutcome(status) {
const s = normalizeStatus(status);
// 'hired' is the strongest positive outcome — a landed job. It must not fall
// through to the 'pending' default, which would drag conversion rates down.
if (['hired', 'interview', 'offer', 'responded', 'applied'].includes(s)) return 'positive';
if (['rejected', 'discarded'].includes(s)) return 'negative';
if (['skip'].includes(s)) return 'self_filtered';
return 'pending'; // evaluated
}
// --- Rate denominators ---
//
// A frequency is only meaningful against the population that could have
// produced it. Both counters below exist because `enriched.length` — EVERY
// tracker row — was standing in for two much smaller populations, silently
// deflating every derived percentage and the thresholds computed from them.
//
// Entries eligible to carry a discard/skip reason. A 'pending' (Evaluated,
// never acted on) or 'positive' row has no reason to state, so counting it in
// the base only dilutes the share. Must stay in lockstep with the filter that
// guards the discard-reason harvest loop.
function discardableBase(enriched) {
return enriched.filter(e => e.outcome === 'self_filtered' || e.outcome === 'negative').length;
}
// Entries that actually carry gaps, i.e. the ones a blocker can be extracted
// from. Entries whose report has no gaps (or no report at all) can never
// contribute a blocker and must not pad the denominator.
function gapBearingBase(enriched) {
return enriched.filter(e => e.report?.gaps?.length > 0).length;
}
// Statuses that count as a submitted application for channel-yield analysis
// (drop 'evaluated' = never applied, 'skip' = self-filtered). 'hired' counts —
// a landed job was, by definition, submitted. Module-scoped so the self-test
// can assert membership and the channel-yield pass and self-test share one set.
const SUBMITTED_STATUSES = new Set(['applied', 'responded', 'interview', 'offer', 'hired', 'rejected', 'discarded']);
// Statuses that count as "advanced past screening" — STRICTER than
// outcome=='positive': a bare 'applied' (submitted, no reply yet) does NOT
// count. 'hired' is the furthest advance of all.
const ADVANCED_STATUSES = new Set(['responded', 'interview', 'offer', 'hired']);
// Print order for the CONVERSION FUNNEL summary. A status absent here is
// silently omitted from the printed funnel, so this must track states.yml.
const FUNNEL_ORDER = ['evaluated', 'applied', 'responded', 'interview', 'offer', 'hired', 'rejected', 'discarded', 'skip'];
function normalizeList(value) {
if (Array.isArray(value)) return value.map(v => String(v).trim()).filter(Boolean);
if (value === null || value === undefined || value === '') return [];
if (typeof value === 'object') return [];
return [String(value).trim()].filter(Boolean);
}
function normalizeScalar(value) {
if (typeof value === 'string') return value.trim() || null;
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
return null;
}
function parseMachineSummary(content) {
const fenceMatch = content.match(/##\s*Machine Summary\s*\n+```(?:yaml|yml|json)?\s*\n([\s\S]*?)\n```/i);
if (!fenceMatch) return null;
const raw = fenceMatch[1].trim();
if (!raw) return null;
try {
const parsed = yamlLoad(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
return Object.fromEntries(
Object.entries(parsed).filter(([key]) => MACHINE_SUMMARY_FIELDS.has(key))
);
} catch {
return null;
}
}
// --- Via channel analysis (#1596 follow-up) ---
// Pure: group submitted applications by their Via channel (agency/recruiter
// firm) and compute per-agency advance rates, plus the agency-vs-direct
// aggregate. Channel identity uses the SAME normalizeVia key as the
// merge-tracker dedup guard (tracker-parse.mjs): NFKC + Unicode letters/digits,
// so "Hays" / "HAYS " / full-width "HAYS" land in one bucket while distinct
// non-Latin agencies (リクルートAgent vs パーソルAgent) stay separate. The
// first raw spelling seen is kept for display. Rows in `submitted` whose Via
// cell is empty (legacy tracker without the column, or a blank cell — as
// opposed to the explicit `—` direct marker) belong to neither bucket; they
// are counted as `unknownVia` so agencySubmitted + directSubmitted can't
// silently undershoot the submitted total.
function buildViaChannelAnalysis(submitted, isAdvanced, minSample = MIN_VENDOR_N) {
const viaOf = (e) => String(e.via ?? '').trim();
const isDirect = (v) => v === '—' || v === '-';
const agencySubmitted = submitted.filter(e => { const v = viaOf(e); return v !== '' && !isDirect(v); });
const directSubmitted = submitted.filter(e => isDirect(viaOf(e)));
const rate = (arr) => (arr.length > 0 ? Math.round((arr.filter(isAdvanced).length / arr.length) * 100) : 0);
const byAgency = new Map();
for (const e of agencySubmitted) {
const raw = viaOf(e);
// All-symbol names (e.g. "***") normalize to '' — fall back to the
// NFKC-lowercased raw string so DISTINCT all-symbol names stay distinct
// buckets instead of merging into one shared empty key.
const key = normalizeVia(raw) || raw.normalize('NFKC').toLowerCase();
if (!byAgency.has(key)) byAgency.set(key, { agency: raw, total: 0, advanced: 0 });
const entry = byAgency.get(key);
entry.total++;
if (isAdvanced(e)) entry.advanced++;
}
const breakdown = [...byAgency.values()]
.map(d => ({
agency: d.agency,
total: d.total,
advanced: d.advanced,
advanceRate: d.total > 0 ? Math.round((d.advanced / d.total) * 100) : 0,
sufficientSample: d.total >= minSample,
}))
.sort((a, b) => b.total - a.total);
return {
minSampleForClaim: minSample,
agencySubmitted: agencySubmitted.length,
directSubmitted: directSubmitted.length,
// Coverage honesty: submitted rows with an empty Via cell (no `—` marker)
// that fall into neither bucket. Non-zero means the agency/direct split
// covers only a subset of submissions.
unknownVia: submitted.length - agencySubmitted.length - directSubmitted.length,
agencyAdvanceRate: rate(agencySubmitted),
directAdvanceRate: rate(directSubmitted),
breakdown,
};
}
// --- Tech-stack-gap extraction (shared by the analysis pass and the self-test) ---
// Canonical display spelling keyed by lowercased alias, so "react native" /
// "NODEJS" collapse into one bucket rather than one per case variant.
const TECH_CANONICAL = new Map([
'JavaScript', 'TypeScript', 'Python', 'Ruby', 'Java', 'Go', 'Rust',
'React Native', 'React', 'Angular', 'Django', 'Flask', 'Rails', 'PHP',
'Laravel', 'Symfony', 'Kotlin', 'Swift', 'C++', 'C#', '.NET', 'MongoDB',
'MySQL', 'PostgreSQL', 'Redis', 'GraphQL', 'REST', 'AWS', 'GCP', 'Azure',
'Docker', 'Kubernetes', 'Terraform', 'Supabase', 'Inngest',
].map(t => [t.toLowerCase(), t]));
TECH_CANONICAL.set('node.js', 'Node.js').set('nodejs', 'Node.js');
TECH_CANONICAL.set('vue.js', 'Vue.js').set('vuejs', 'Vue.js');
// (?<!\w) / (?!\w) lookarounds, NOT \b: a trailing \b never matches after a
// symbol edge, so "C++", "C#" and ".NET" — three of the most common stacks —
// were silently never extracted, vanishing from the tech-gap rollup and the
// "filter out roles requiring X" recommendation. Same symbol-edge fix that
// skill-extract.mjs and upskill.mjs already carry. Ordered longest-first
// (React Native before React) so the specific alternative wins at a position.
const TECH_MENTION_RE = /(?<!\w)(JavaScript|TypeScript|Python|Ruby|Java|Go|Rust|Node\.?js|React Native|React|Angular|Vue\.?js|Django|Flask|Rails|PHP|Laravel|Symfony|Kotlin|Swift|C\+\+|C#|\.NET|MongoDB|MySQL|PostgreSQL|Redis|GraphQL|REST|AWS|GCP|Azure|Docker|Kubernetes|Terraform|Supabase|Inngest)(?!\w)/gi;
/**
* Canonical tech names mentioned in a gap description.
* @param {string} description
* @returns {string[]} Canonical tech names, one entry per mention (may repeat).
*/
function extractTechMentions(description) {
const matches = String(description ?? '').match(TECH_MENTION_RE);
if (!matches) return [];
return matches.map(m => TECH_CANONICAL.get(m.toLowerCase()) || m);
}
function runSelfTest() {
const summary = parseMachineSummary(`
## Machine Summary
\`\`\`yaml
company: "Acme"
role: "Staff AI Engineer"
score: 4.4
legitimacy_tier: "High Confidence"
archetype: "AI Platform / LLMOps Engineer"
final_decision: "Apply"
hard_stops: []
soft_gaps:
- "No direct healthcare domain experience"
top_strengths:
- "Production evaluation pipelines"
risk_level: "Medium"
confidence: "High"
next_action: "Follow up on ticket #42 with tailored CV"
work_auth: "unstated"
via: "Hays"
company_confidential: true
\`\`\`
`);
const failures = [];
if (!summary) failures.push('summary was not parsed');
if (summary?.score !== 4.4) failures.push('numeric score was not parsed');
if (!Array.isArray(summary?.hard_stops) || summary.hard_stops.length !== 0) failures.push('empty list was not parsed');
if (summary?.soft_gaps?.[0] !== 'No direct healthcare domain experience') failures.push('list item was not parsed');
if (summary?.next_action !== 'Follow up on ticket #42 with tailored CV') failures.push('hash-containing scalar field was not parsed');
if (summary?.via !== 'Hays') failures.push('via was not preserved from Machine Summary');
if (summary?.company_confidential !== true) failures.push('company_confidential boolean was not preserved from Machine Summary');
if (summary?.work_auth !== 'unstated') failures.push('work_auth field was not preserved from Machine Summary');
// Backward compat (#1737): summaries without risk_summary parse as before, key simply absent.
if ('risk_summary' in (summary ?? {})) failures.push('summary without risk_summary must not gain the key');
// risk_summary preservation (#1737): the nested map must survive the
// MACHINE_SUMMARY_FIELDS allowlist intact — nested keys preserved, not
// flattened or dropped.
const riskSummary = parseMachineSummary(`
## Machine Summary
\`\`\`yaml
company: "Acme"
role: "Staff AI Engineer"
score: 4.4
legitimacy_tier: "High Confidence"
risk_summary:
legitimacy: high_confidence
classification: clear
culture: caution
interview_redflags: not_evaluated
ai_infra: not_evaluated
\`\`\`
`)?.risk_summary;
if (!riskSummary || typeof riskSummary !== 'object' || Array.isArray(riskSummary)) {
failures.push('risk_summary nested map was dropped or not parsed as a map');
} else {
if (riskSummary.legitimacy !== 'high_confidence') failures.push('risk_summary.legitimacy was not preserved');
if (riskSummary.classification !== 'clear') failures.push('risk_summary.classification was not preserved');
if (riskSummary.culture !== 'caution') failures.push('risk_summary.culture was not preserved');
if (riskSummary.interview_redflags !== 'not_evaluated') failures.push('risk_summary.interview_redflags was not preserved');
if (riskSummary.ai_infra !== 'not_evaluated') failures.push('risk_summary.ai_infra was not preserved');
}
// Vendor detection (community ATS only; white-labeled → null)
const vendorCases = [
['https://boards.greenhouse.io/acme/jobs/12345', 'greenhouse'],
['https://job-boards.eu.greenhouse.io/acme/jobs/9', 'greenhouse'],
['https://jobs.lever.co/acme/abc-def', 'lever'],
['https://jobs.ashbyhq.com/acme/uuid', 'ashby'],
['https://acme.wd1.myworkdayjobs.com/en-US/careers/job/R-1', 'workday'],
['https://careers.icims.com/jobs/9/x', 'icims'],
['https://jobs.dayforcehcm.com/en-US/co/CANDIDATEPORTAL/jobs/1', null],
['not a url', null],
['', null],
[null, null],
];
for (const [url, expected] of vendorCases) {
const got = detectVendor(url);
if (got !== expected) failures.push(`detectVendor(${JSON.stringify(url)}) → ${JSON.stringify(got)}, expected ${JSON.stringify(expected)}`);
}
// Via channel analysis (#1596): agency vs direct yield, normalized buckets.
const viaRows = [
{ via: 'Hays', normalizedStatus: 'interview' },
{ via: 'HAYS ', normalizedStatus: 'rejected' }, // same bucket as Hays
{ via: 'HAYS', normalizedStatus: 'rejected' }, // full-width → same bucket as Hays (NFKC)
{ via: 'Randstad', normalizedStatus: 'rejected' },
{ via: 'リクルートAgent', normalizedStatus: 'interview' }, // non-Latin: distinct agency...
{ via: 'パーソルAgent', normalizedStatus: 'rejected' }, // ...must NOT merge with the one above
{ via: '—', normalizedStatus: 'responded' }, // direct
{ via: '—', normalizedStatus: 'rejected' }, // direct
{ via: '', normalizedStatus: 'applied' }, // no Via column → unknownVia, neither bucket
];
const viaResult = buildViaChannelAnalysis(viaRows, (e) => ADVANCED_STATUSES.has(e.normalizedStatus), 2);
if (viaResult.agencySubmitted !== 6) failures.push(`via: agencySubmitted → ${viaResult.agencySubmitted}, expected 6`);
if (viaResult.directSubmitted !== 2) failures.push(`via: directSubmitted → ${viaResult.directSubmitted}, expected 2`);
if (viaResult.unknownVia !== 1) failures.push(`via: unknownVia → ${viaResult.unknownVia}, expected 1 (submitted row with empty Via must be counted, not silently dropped)`);
if (viaResult.directAdvanceRate !== 50) failures.push(`via: directAdvanceRate → ${viaResult.directAdvanceRate}, expected 50`);
const hays = viaResult.breakdown.find(a => a.agency === 'Hays');
if (!hays || hays.total !== 3 || hays.advanceRate !== 33) {
failures.push(`via: Hays bucket wrong (case/space/full-width variants must merge) → ${JSON.stringify(hays)}`);
}
if (!hays?.sufficientSample) failures.push('via: Hays should meet the n=2 sample bar');
const recruit = viaResult.breakdown.find(a => a.agency === 'リクルートAgent');
const persol = viaResult.breakdown.find(a => a.agency === 'パーソルAgent');
if (!recruit || !persol || recruit.total !== 1 || persol.total !== 1) {
failures.push(`via: distinct non-Latin agencies must stay separate buckets → リクルートAgent=${JSON.stringify(recruit)}, パーソルAgent=${JSON.stringify(persol)}`);
}
const randstad = viaResult.breakdown.find(a => a.agency === 'Randstad');
if (randstad?.sufficientSample) failures.push('via: Randstad (n=1) must be flagged as too small for a claim');
if (buildViaChannelAnalysis([], () => false).breakdown.length !== 0) {
failures.push('via: empty input must produce an empty breakdown');
}
// Hired status (canonical per states.yml; follow-up to PR #2050). A landed job
// is the strongest positive outcome and the furthest advance — it must not be
// mis-bucketed as 'pending' or dropped from channel yield / the funnel.
if (classifyOutcome('Hired') !== 'positive') failures.push(`hired: classifyOutcome('Hired') → ${classifyOutcome('Hired')}, expected 'positive'`);
// Every hired alias must resolve to 'hired' — testing only one lets the others regress silently.
for (const alias of ['contratado', 'contratada', 'accepted', 'accept']) {
if (normalizeStatus(alias) !== 'hired') failures.push(`hired: normalizeStatus('${alias}') → ${normalizeStatus(alias)}, expected 'hired'`);
}
if (!ADVANCED_STATUSES.has('hired')) failures.push('hired: ADVANCED_STATUSES must include hired (a hire advanced past screening)');
if (!SUBMITTED_STATUSES.has('hired')) failures.push('hired: SUBMITTED_STATUSES must include hired (a hire was submitted)');
if (!FUNNEL_ORDER.includes('hired')) failures.push('hired: FUNNEL_ORDER must include hired so it prints in the funnel');
const hiredVia = buildViaChannelAnalysis(
[{ via: 'Hays', normalizedStatus: 'hired' }, { via: 'Hays', normalizedStatus: 'rejected' }],
(e) => ADVANCED_STATUSES.has(e.normalizedStatus), 1);
const hiredHays = hiredVia.breakdown.find(a => a.agency === 'Hays');
if (!hiredHays || hiredHays.advanced !== 1 || hiredHays.advanceRate !== 50) {
failures.push(`hired: must count as advanced in channel yield (1/2 = 50%) → ${JSON.stringify(hiredHays)}`);
}
// Tech-gap extraction (regression): symbol-edge stacks were silently dropped
// because a trailing \b never matches after "+"/"#" (C++, C#, .NET).
const techHits = extractTechMentions('Requires C++, C# and .NET, plus React Native and Go');
for (const expected of ['C++', 'C#', '.NET', 'React Native', 'Go']) {
if (!techHits.includes(expected)) failures.push(`tech extraction dropped "${expected}"`);
}
// No false positives from substrings ("Go" in "Google", "Java" in "JavaScripting").
if (extractTechMentions('Google Cloud and JavaScripting skills').length !== 0) {
failures.push('tech extraction false-positived on Google/JavaScripting');
}
// Case/punctuation variants collapse to one canonical bucket.
if (extractTechMentions('nodejs, Node.js, NODEJS').some(t => t !== 'Node.js')) {
failures.push('node.js case variants failed to canonicalize');
}
// Production aggregation regressions. The fixture distinguishes the fixed
// denominator from the old full-tracker base: 3 tags among 20 eligible rows
// trigger a recommendation, while 3 among all 30 rows would not.
const baseFixture = [];
for (let i = 0; i < 20; i++) {
baseFixture.push({
outcome: i === 19 ? 'negative' : 'self_filtered',
notes: i < 3 ? `SKIP: geo-block${i === 0 ? '; SKIP: geo-block' : ''}` : '',
report: { gaps: [] },
});
}
for (let i = 0; i < 10; i++) {
baseFixture.push({ outcome: 'pending', notes: '', report: null });
}
const baseSignals = buildPatternSignals(baseFixture);
if (baseSignals.discardReasonBase !== 20) {
failures.push(`discardReasonBase counted ${baseSignals.discardReasonBase}, expected 20`);
}
if (baseSignals.blockerBase !== 0) {
failures.push(`blockerBase counted ${baseSignals.blockerBase}, expected 0 (no gaps in fixture)`);
}
const geoReason = baseSignals.discardReasonStats.find(d => d.reason === 'geo-block');
if (geoReason?.frequency !== 3 || geoReason?.percentage !== 15) {
failures.push(`discard aggregation returned ${JSON.stringify(geoReason)}, expected frequency 3 and percentage 15`);
}
if (!baseSignals.discardReasonRecommendation) {
failures.push('3 discard reasons among 20 eligible entries did not trigger a recommendation');
}
// One report whose gaps all resolve to geo-restriction is one affected entry,
// not three. The explicit count catches both missing and misclassified fixture
// descriptions instead of merely checking that no count exceeds the base.
const dupBlockerFixture = [
{ outcome: 'negative', notes: '', report: { gaps: [
{ description: 'US-only remote', severity: 'hard' },
{ description: 'Remote US only, no sponsorship', severity: 'hard' },
{ description: 'US-only residency required', severity: 'hard' },
] } },
{ outcome: 'negative', notes: '', report: { gaps: [{ description: 'US-only remote', severity: 'hard' }] } },
// Gapless rows make the fixture distinguish blockerBase (2) from the old
// full-tracker denominator (5). Restoring `/ enriched.length` must turn the
// expected 100% into 40% and fail this regression.
{ outcome: 'pending', notes: '', report: { gaps: [] } },
{ outcome: 'pending', notes: '', report: null },
{ outcome: 'positive', notes: '', report: { gaps: [] } },
];
const blockerSignals = buildPatternSignals(dupBlockerFixture);
const geoBlocker = blockerSignals.blockerAnalysis.find(b => b.blocker === 'geo-restriction');
if (geoBlocker?.frequency !== blockerSignals.blockerBase || geoBlocker?.percentage !== 100) {
failures.push(`geo blocker aggregation returned ${JSON.stringify(geoBlocker)} against base ${blockerSignals.blockerBase}, expected 2/2 (100%)`);
}
// Repeated technology mentions across one report count once per entry.
const techSignals = buildPatternSignals([{ outcome: 'negative', notes: '', report: { gaps: [
{ description: 'Java is required', severity: 'hard' },
{ description: 'Production Java and Go experience', severity: 'hard' },
] } }]);
const javaGap = techSignals.techStackGaps.find(g => g.skill === 'Java');
if (javaGap?.frequency !== 1) {
failures.push(`technology deduplication returned ${JSON.stringify(javaGap)}, expected Java frequency 1`);
}
// Empty populations must expose zero bases and no NaN-bearing stats.
const emptySignals = buildPatternSignals([]);
if (emptySignals.discardReasonBase !== 0 || emptySignals.blockerBase !== 0
|| emptySignals.discardReasonStats.length !== 0 || emptySignals.blockerAnalysis.length !== 0
|| emptySignals.discardReasonRecommendation) {
failures.push(`empty pattern signals were not empty: ${JSON.stringify(emptySignals)}`);
}
// Remote classifier (regression): the "70+" signal ends in "+", so a
// trailing \b silently dropped it and "70+ countries" postings fell to the
// weaker 'regional remote' bucket instead of 'global remote'.
if (classifyRemote('Fully remote — hiring in 70+ countries') !== 'global remote') {
failures.push('classifyRemote did not read "70+ countries" as global remote');
}
if (classifyRemote('US-only remote') !== 'geo-restricted') {
failures.push('classifyRemote geo-restricted precedence regressed');
}
// Reports-root containment: a legit link stays inside reports/, a crafted
// traversal link escapes root and must be rejected before parseReport. join()
// collapses '..' at the call site, so the candidate is already absolute here.
{
const legit = join(CAREER_OPS, 'reports', '042-acme-2026-01-01.md');
if (!withinReports(legit)) failures.push('containment: legit reports/ path wrongly rejected');
const escape = join(CAREER_OPS, 'reports/../../../etc/passwd');
if (withinReports(escape)) failures.push('containment: traversal path escaped reports/ (path-traversal guard broken)');
const sibling = join(CAREER_OPS, 'reports-evil', 'x.md');
if (withinReports(sibling)) failures.push('containment: reports-prefixed sibling dir wrongly accepted');
}
// Symlink-escape + missing-file graceful degradation (#2655). realpath
// canonicalization must reject a symlink whose target resolves OUTSIDE
// reports/ (a lexical-only guard would follow it), while a real file inside
// reports/ still passes and a missing candidate degrades gracefully (the
// downstream read returns null) rather than throwing.
{
const reportsDir = join(CAREER_OPS, 'reports');
if (existsSync(reportsDir)) {
const tag = `__co2655-${process.pid}-${Date.now()}`;
const realReport = join(reportsDir, `${tag}-real.md`);
const escapeLink = join(reportsDir, `${tag}-escape.md`);
const missing = join(reportsDir, `${tag}-missing.md`);
// Missing candidate must not throw and must stay accepted so the
// downstream read returns null (pre-#2385 existsSync-removal semantics).
try {
if (!withinReports(missing)) failures.push('containment: missing report file wrongly rejected (should degrade to a null read, not a hard skip)');
} catch (err) {
failures.push(`containment: missing report file threw instead of degrading gracefully (${err.code || err.message})`);
}
try {
writeFileSync(realReport, '# real report\n');
if (!withinReports(realReport)) failures.push('containment: real file inside reports/ wrongly rejected');
// Symlink whose target resolves outside reports/ (this module file);
// its lexical path is under reports/ but realpath escapes and must be
// rejected. symlinkSync often needs privilege on Windows — skip the
// assertion (do not fail) when the platform refuses.
let symlinkCreated = false;
try {
symlinkSync(fileURLToPath(import.meta.url), escapeLink);
symlinkCreated = true;
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'ENOSYS') {
console.log(`analyze-patterns self-test: skipping symlink-escape assertion (platform refused symlink creation: ${err.code})`);
} else {
throw err;
}
}
if (symlinkCreated && withinReports(escapeLink)) {
failures.push('containment: symlink escaping reports/ was accepted (realpath containment broken)');
}
} finally {
rmSync(realReport, { force: true });
rmSync(escapeLink, { force: true });
}
}
}
if (failures.length > 0) {
console.error(`analyze-patterns self-test failed: ${failures.join('; ')}`);
process.exit(1);
}
console.log('analyze-patterns self-test OK (Machine Summary parser + vendor detection + via channel analysis)');
process.exit(0);
}
// --- Parse applications.md ---
function parseTracker() {
if (!existsSync(APPS_FILE)) return [];
const content = readFileSync(APPS_FILE, 'utf-8');
const lines = content.split('\n');
const colmap = resolveColumns(lines);
const entries = [];
for (const line of lines) {
const row = parseTrackerRow(line, colmap);
if (row) entries.push(row);
}
return entries;
}
// Canonical reports-root containment. A tracker link resolves to a candidate
// path; accept it only if it stays inside the repo's reports/ directory. Two
// layers: a cheap lexical traversal guard (no stat) rejects a crafted link like
// reports/../../etc/passwd, which join() collapses to a repo-relative path that
// no longer starts with reports/; then realpath canonicalization rejects a
// symlink whose target escapes reports/ (a lexical-only check would follow it).
// realpathSync throws ENOENT/ENOTDIR for a not-yet-created candidate or a
// missing reports root — both are non-fatal: a missing candidate falls through
// to the downstream read (which returns null, preserving prior semantics), a
// missing root means there are simply no reports. Only genuinely unexpected
// errors rethrow, matching readTextIfExists. Identical to the guard in
// upskill.mjs so both sites behave the same.
function withinReports(candidate) {
const repoRelative = relative(CAREER_OPS, candidate).split(sep).join('/');
if (!repoRelative.startsWith('reports/') || repoRelative.includes('..')) return false;
let realRoot;
try {
realRoot = realpathSync(join(CAREER_OPS, 'reports'));
} catch (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return false;
throw err;
}
let realCandidate;
try {
realCandidate = realpathSync(candidate);
} catch (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return true;
throw err;
}
const rootWithSep = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
return realCandidate === realRoot || realCandidate.startsWith(rootWithSep);
}
// Read a file, returning null when it does not exist. A pre-flight existsSync
// costs a full stat per report and races with the read (#2385); attempting the
// read and handling the missing-file error costs the same as a bare read.
function readTextIfExists(path) {
try {
return readFileSync(path, 'utf-8');
} catch (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;
throw err;
}
}
// --- Parse a single report file ---
function parseReport(reportPath) {
const content = readTextIfExists(reportPath);
if (content === null) return null;
const report = {
company: null,
role: null,
url: null,
archetype: null,
legitimacyTier: null,
finalDecision: null,
seniority: null,
remote: null,
teamSize: null,
comp: null,
domain: null,
riskLevel: null,
confidence: null,
nextAction: null,
topStrengths: [],
discardReasons: [],
scores: {},
gaps: [],
};
const machineSummary = parseMachineSummary(content);
if (machineSummary) {
report.machineSummary = machineSummary;
report.company = normalizeScalar(machineSummary.company) || report.company;
report.role = normalizeScalar(machineSummary.role) || report.role;
report.archetype = normalizeScalar(machineSummary.archetype) || report.archetype;
report.legitimacyTier = normalizeScalar(machineSummary.legitimacy_tier) || report.legitimacyTier;
report.finalDecision = normalizeScalar(machineSummary.final_decision) || report.finalDecision;
report.domain = normalizeScalar(machineSummary.domain) || report.domain;
report.seniority = normalizeScalar(machineSummary.seniority) || report.seniority;
report.remote = normalizeScalar(machineSummary.remote) || report.remote;
report.teamSize = normalizeScalar(machineSummary.team_size) || report.teamSize;
report.riskLevel = normalizeScalar(machineSummary.risk_level) || report.riskLevel;
report.confidence = normalizeScalar(machineSummary.confidence) || report.confidence;
report.nextAction = normalizeScalar(machineSummary.next_action) || report.nextAction;
report.topStrengths = normalizeList(machineSummary.top_strengths);
report.discardReasons = normalizeList(machineSummary.discard_reasons);
if (typeof machineSummary.score === 'number') {
report.scores.global = machineSummary.score;
}
for (const hardStop of normalizeList(machineSummary.hard_stops)) {
report.gaps.push({ description: hardStop, severity: 'hard stop', mitigation: '' });
}
for (const softGap of normalizeList(machineSummary.soft_gaps)) {
report.gaps.push({ description: softGap, severity: 'soft gap', mitigation: '' });
}
}
// Strip bold markers for easier matching
const plain = content.replace(/\*\*/g, '');
// Extract Block A table (Role Summary) — works with both EN and ES headers
// Archetype cell may be labeled "Archetype", "Arquetipo", or "Detected archetype" (drift from EN translation).
const blockARegex = /\|\s*(?:Detected\s+)?(?:Archetype|Arquetipo)\s*\|\s*(.*?)\s*\|/i;
const seniorityRegex = /\|\s*(?:Seniority|Nivel|Level)\s*\|\s*(.*?)\s*\|/i;
const remoteRegex = /\|\s*(?:Remote|Remoto|Location)\s*\|\s*(.*?)\s*\|/i;
const teamRegex = /\|\s*(?:Team|Team size|Equipo)\s*\|\s*(.*?)\s*\|/i;
const compRegex = /\|\s*(?:Comp|Salary|Salario|Listed salary)\s*\|\s*(.*?)\s*\|/i;
const domainRegex = /\|\s*(?:Domain|Dominio|Industry)\s*\|\s*(.*?)\s*\|/i;
// Fallback: report header field `Archetype: ...` or `Arquetipo: ...` (newer reports use this).
const headerArchRegex = /^(?:Archetype|Arquetipo):\s*(.+?)$/im;
// Report header carries `**URL:**` between Score and PDF (see CLAUDE.md /
// Pipeline Integrity). Capture the first http(s) URL on that line for vendor
// detection; reports predating the field simply leave url null (→ unknown bucket).
const urlMatch = plain.match(/^URL:\s*(https?:\/\/\S+)/im);
if (urlMatch && !report.url) report.url = urlMatch[1].trim().replace(/[)>\].,]+$/, '');
const archMatch = plain.match(blockARegex) || plain.match(headerArchRegex);
if (archMatch && !report.archetype) report.archetype = archMatch[1].trim();
const senMatch = plain.match(seniorityRegex);
if (senMatch && !report.seniority) report.seniority = senMatch[1].trim();
const remMatch = plain.match(remoteRegex);
if (remMatch && !report.remote) report.remote = remMatch[1].trim();
const teamMatch = plain.match(teamRegex);
if (teamMatch && !report.teamSize) report.teamSize = teamMatch[1].trim();
const compMatch = plain.match(compRegex);
if (compMatch && !report.comp) report.comp = compMatch[1].trim();
const domainMatch = plain.match(domainRegex);
if (domainMatch && !report.domain) report.domain = domainMatch[1].trim();
// Extract scoring table — look for table with "Global" row (using plain, bold already stripped)
const scoreRegex = /\|\s*(?:CV Match|Match con CV)\s*\|\s*([\d.]+)\/5\s*\|/i;
const northStarRegex = /\|\s*(?:North Star)\s*\|\s*([\d.]+)\/5\s*\|/i;
const compScoreRegex = /\|\s*(?:Comp)\s*\|\s*([\d.]+)\/5\s*\|/i;
const culturalRegex = /\|\s*(?:Cultural signals|Cultural)\s*\|\s*([\d.]+)\/5\s*\|/i;
const redFlagsRegex = /\|\s*(?:Red flags)\s*\|\s*([-+]?[\d.]+)\s*\|/i;
const globalRegex = /\|\s*(?:Global)\s*\|\s*([\d.]+)\/5\s*\|/i;
const cvScoreMatch = plain.match(scoreRegex);
if (cvScoreMatch && report.scores.cvMatch === undefined) report.scores.cvMatch = parseFloat(cvScoreMatch[1]);
const nsMatch = plain.match(northStarRegex);
if (nsMatch && report.scores.northStar === undefined) report.scores.northStar = parseFloat(nsMatch[1]);
const csMatch = plain.match(compScoreRegex);
if (csMatch && report.scores.comp === undefined) report.scores.comp = parseFloat(csMatch[1]);
const culMatch = plain.match(culturalRegex);
if (culMatch && report.scores.cultural === undefined) report.scores.cultural = parseFloat(culMatch[1]);
const rfMatch = plain.match(redFlagsRegex);
if (rfMatch && report.scores.redFlags === undefined) report.scores.redFlags = parseFloat(rfMatch[1]);
const glMatch = plain.match(globalRegex);
if (glMatch && report.scores.global === undefined) report.scores.global = parseFloat(glMatch[1]);
// Extract gaps table
const gapTableRegex = /\|\s*Gap\s*\|\s*Severity\s*\|.*?\n\|[-|\s]+\n([\s\S]*?)(?:\n\n|\n##|\n\*\*|$)/i;
const gapTableMatch = content.match(gapTableRegex);
if (gapTableMatch) {
const gapRows = gapTableMatch[1].split('\n').filter(r => r.startsWith('|'));
for (const row of gapRows) {
const cols = row.split('|').map(s => s.trim()).filter(Boolean);
if (cols.length >= 2) {
const duplicate = report.gaps.some(g => g.description.toLowerCase() === cols[0].toLowerCase());
if (!duplicate) {
report.gaps.push({
description: cols[0],
severity: cols[1].toLowerCase(),
mitigation: cols[2] || '',
});
}
}
}
}
return report;
}
// --- Classify remote policy into buckets ---
function classifyRemote(raw) {
if (!raw) return 'unknown';
const lower = raw.toLowerCase();
// Order matters: check geo-restricted before general remote
if (/\b(us[- ]?only|canada[- ]?only|residents only|usa only|us residents|canada residents)\b/.test(lower)) return 'geo-restricted';
if (/\bargentina\s+remote\s+only\b/.test(lower)) return 'geo-restricted';
if (/\b(hybrid|on-?site|office|columbus|cape town|relocat)\b/.test(lower)) return 'hybrid/onsite';
// (?<!\w)/(?!\w) not \b: the "70+" signal ends in "+", and a trailing \b
// never matches after a symbol edge, so "remote in 70+ countries" fell
// through to the weaker 'regional remote' bucket. Word alternatives behave
// identically under either boundary, so this only rescues the "70+" case.
if (/(?<!\w)(global|anywhere|worldwide|no restrict|70\+|work from anywhere)(?!\w)/.test(lower)) return 'global remote';
if (/\b(remote|latam|americas|brazil|fully remote)\b/.test(lower)) return 'regional remote';
return 'unknown';
}
// --- Detect ATS vendor from a posting URL ---
// Host-only match, deliberately looser than liveness-api.mjs's resolveAtsApi()
// (which needs the full posting path to build an API URL) — a tracker report's
// URL may point at a board/careers page, not a canonical posting.
//
// SCOPE (intentional): only ATS with clean, public URL fingerprints — Greenhouse,
// Lever, Ashby, Workday, iCIMS. White-labeled ATS (UKG, Dayforce, and similar) are
// NOT detectable from the URL alone and are deferred until the community adds a
// reliable signal (e.g. confirmation-email domain). Undetected → 'unknown'.
const VENDOR_HOST_PATTERNS = [
{ id: 'greenhouse', test: (h) => /(^|\.)greenhouse\.io$/.test(h) },
{ id: 'lever', test: (h) => h === 'jobs.lever.co' || h.endsWith('.lever.co') },
{ id: 'ashby', test: (h) => h === 'jobs.ashbyhq.com' || h.endsWith('.ashbyhq.com') },
{ id: 'workday', test: (h) => h.endsWith('.myworkdayjobs.com') || h.endsWith('.myworkdaysite.com') },
{ id: 'icims', test: (h) => h.endsWith('.icims.com') },
];
function detectVendor(rawUrl) {
if (!rawUrl || typeof rawUrl !== 'string') return null;
let u;
try { u = new URL(rawUrl.trim()); } catch { return null; }
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
const host = u.hostname.toLowerCase();
for (const v of VENDOR_HOST_PATTERNS) if (v.test(host)) return v.id;
return null;
}
// --- Classify company size ---
function classifyCompanySize(teamSize) {
if (!teamSize) return 'unknown';
const lower = teamSize.toLowerCase();
// Extract numbers
const nums = lower.match(/[\d,]+/g);
if (nums) {
const max = Math.max(...nums.map(n => parseInt(n.replace(/,/g, ''))));
if (max <= 50) return 'startup';
if (max <= 500) return 'scaleup';
return 'enterprise';
}
if (/\b(small|elite|tiny|founding)\b/.test(lower)) return 'startup';
if (/\b(large|enterprise|global)\b/.test(lower)) return 'enterprise';
return 'unknown';
}
// --- Extract hard blocker keywords from gaps ---
function extractBlockerType(gap) {
const desc = gap.description.toLowerCase();
const sev = gap.severity.toLowerCase();
if (sev.includes('nice') || sev.includes('soft')) return null; // skip soft gaps
if (/\b(residency|us[- ]only|canada|location|visa|geo|country|region)\b/.test(desc)) return 'geo-restriction';
if (/\b(javascript|typescript|python|ruby|java|go|rust|node|react|angular|vue|django|flask|rails)\b/.test(desc)) return 'stack-mismatch';
if (/\b(senior|staff|lead|principal|director|manager|head)\b/.test(desc)) return 'seniority-mismatch';
if (/\b(hybrid|on-?site|office|relocat)\b/.test(desc)) return 'onsite-requirement';
return 'other';
}
/**
* Build the blocker, discard-reason, and technology signals used by both the
* production analysis and regression fixtures.
* @param {Array<object>} enriched Tracker entries enriched with outcomes/reports.
* @returns {object} Aggregated rates, population bases, and discard recommendation.
*/
function buildPatternSignals(enriched) {
const blockerCounts = new Map();
const blockerBase = gapBearingBase(enriched);
for (const e of enriched) {
if (!e.report?.gaps) continue;
const entryBlockers = new Set();
for (const gap of e.report.gaps) {
const type = extractBlockerType(gap);
if (type) entryBlockers.add(type);
}
for (const type of entryBlockers) {
blockerCounts.set(type, (blockerCounts.get(type) || 0) + 1);
}
}
const blockerAnalysis = [...blockerCounts.entries()]
.map(([blocker, frequency]) => ({
blocker,
frequency,
percentage: blockerBase ? Math.round((frequency / blockerBase) * 100) : 0,
}))
.sort((a, b) => b.frequency - a.frequency);
const discardReasonCounts = new Map();
for (const e of enriched) {
if (e.outcome !== 'self_filtered' && e.outcome !== 'negative') continue;
const notesMatch = (e.notes || '').match(/(?:DISCARD|SKIP):\s*([^,;\n]+)/gi);
if (!notesMatch) continue;
const entryReasons = new Set();
for (const match of notesMatch) {
const key = match.replace(/^(?:DISCARD|SKIP):\s*/i, '').trim().toLowerCase();
if (key) entryReasons.add(key);
}
for (const key of entryReasons) {
discardReasonCounts.set(key, (discardReasonCounts.get(key) || 0) + 1);
}
}
const discardReasonBase = discardableBase(enriched);
const discardReasonStats = [...discardReasonCounts.entries()]
.map(([reason, frequency]) => ({
reason,
frequency,
percentage: discardReasonBase ? Math.round((frequency / discardReasonBase) * 100) : 0,
}))
.sort((a, b) => b.frequency - a.frequency);
const stackGapCounts = new Map();
for (const e of enriched) {
if (e.outcome !== 'negative' && e.outcome !== 'self_filtered') continue;
if (!e.report?.gaps) continue;
const entryTechs = new Set();
for (const gap of e.report.gaps) {
for (const tech of extractTechMentions(gap.description)) entryTechs.add(tech);
}
for (const tech of entryTechs) {
stackGapCounts.set(tech, (stackGapCounts.get(tech) || 0) + 1);
}
}
const techStackGaps = [...stackGapCounts.entries()]
.map(([skill, frequency]) => ({ skill, frequency }))
.sort((a, b) => b.frequency - a.frequency)
.slice(0, 15);
const topDiscardReason = discardReasonStats[0];
const discardReasonRecommendation = topDiscardReason
&& topDiscardReason.frequency >= Math.max(3, Math.ceil(discardReasonBase * 0.15))
? {
action: `Add "${topDiscardReason.reason}" filter to modes/_custom.md to avoid wasting evaluation effort`,
reasoning: `"${topDiscardReason.reason}" is the most frequent discard reason (${topDiscardReason.frequency}x, ${topDiscardReason.percentage}% of ${discardReasonBase} eligible entries with self-filtered or negative outcomes).`,
impact: 'high',
}
: null;
return {
blockerBase,
blockerAnalysis,
discardReasonBase,
discardReasonStats,
techStackGaps,
discardReasonRecommendation,
};
}
// --- Main analysis ---
function analyze() {
const entries = parseTracker();
if (entries.length === 0) {
return { error: 'No applications found in tracker.' };
}
// Enrich entries with report data and classification
const enriched = entries.map(e => {
const reportMatch = e.report.match(/\]\(([^)]+)\)/);
// Tracker links are relative to the tracker file's own directory (see
// merge-tracker.mjs link normalization); fall back to repo root for
// legacy root-relative links. Each candidate is guarded to reports/
// before the read is attempted; parseReport returns null for a missing
// file, so no pre-flight existsSync is needed (#2385).
let reportData = null;
if (reportMatch) {
const candidates = new Set([
join(dirname(APPS_FILE), reportMatch[1]),
join(CAREER_OPS, reportMatch[1]),
]);
for (const candidate of candidates) {
if (!withinReports(candidate)) continue;
reportData = parseReport(candidate);
if (reportData) break;
}
}
const outcome = classifyOutcome(e.status);
const trackerScore = parseFloat(e.score);
const score = Number.isFinite(trackerScore)
? trackerScore
: (Number.isFinite(reportData?.scores?.global) ? reportData.scores.global : 0);
// Fallback: if report didn't have Remote field, try the notes column
const remoteSource = reportData?.remote || e.notes || '';
const teamSource = reportData?.teamSize || '';
return {
...e,
normalizedStatus: normalizeStatus(e.status),
outcome,
score,
report: reportData,
remoteBucket: classifyRemote(remoteSource),
companySize: classifyCompanySize(teamSource),
vendor: detectVendor(reportData?.url),
};
});
// Count entries beyond "Evaluated"
const beyondEvaluated = enriched.filter(e => e.normalizedStatus !== 'evaluated');
if (beyondEvaluated.length < MIN_THRESHOLD) {
return {
error: `Not enough data: ${beyondEvaluated.length}/${MIN_THRESHOLD} applications beyond "Evaluated". Keep applying and come back later.`,
current: beyondEvaluated.length,
threshold: MIN_THRESHOLD,
};
}
// --- Funnel ---
const funnel = {};
for (const e of enriched) {
const s = e.normalizedStatus;
funnel[s] = (funnel[s] || 0) + 1;
}
// --- Score comparison by outcome ---
const scoresByOutcome = { positive: [], negative: [], self_filtered: [], pending: [] };
for (const e of enriched) {
if (e.score > 0) scoresByOutcome[e.outcome].push(e.score);