-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-tracker.mjs
More file actions
241 lines (206 loc) · 7.21 KB
/
merge-tracker.mjs
File metadata and controls
241 lines (206 loc) · 7.21 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
#!/usr/bin/env node
/**
* merge-tracker.mjs — Merge TSV additions into applications.md
*
* Reads TSV files from batch/tracker-additions/
* Merges into data/applications.md with dedup and update-in-place
*
* Usage:
* node merge-tracker.mjs [--dry-run] [--verify]
*/
import { readdir, readFile, writeFile, mkdir, rename } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { existsSync } from 'node:fs';
const DRY_RUN = process.argv.includes('--dry-run');
const VERIFY = process.argv.includes('--verify');
const TRACKER_PATH = existsSync('data/applications.md')
? 'data/applications.md'
: 'applications.md';
const ADDITIONS_DIR = 'batch/tracker-additions';
const MERGED_DIR = join(ADDITIONS_DIR, 'merged');
// Canonical statuses
const VALID_STATUSES = [
'Evaluated', 'Applied', 'Responded', 'Interview',
'Offer', 'Rejected', 'Discarded', 'SKIP',
];
const STATUS_ALIASES = {
'eval': 'Evaluated', 'reviewed': 'Evaluated',
'submitted': 'Applied', 'sent': 'Applied',
'reply': 'Responded', 'replied': 'Responded',
'interviewing': 'Interview', 'phone screen': 'Interview',
'technical': 'Interview', 'onsite': 'Interview',
'offered': 'Offer',
'declined by company': 'Rejected', 'no': 'Rejected',
'withdrawn': 'Discarded', 'closed': 'Discarded', 'expired': 'Discarded',
'no apply': 'SKIP', 'pass': 'SKIP',
};
function validateStatus(raw) {
const trimmed = raw.trim().replace(/\*\*/g, '');
if (VALID_STATUSES.includes(trimmed)) return trimmed;
const lower = trimmed.toLowerCase();
if (STATUS_ALIASES[lower]) return STATUS_ALIASES[lower];
console.warn(` Warning: Unknown status "${trimmed}", defaulting to "Evaluated"`);
return 'Evaluated';
}
function normalizeCompany(name) {
return name.trim().toLowerCase().replace(/[^a-z0-9]/g, '');
}
function fuzzyRoleMatch(a, b) {
const wordsA = a.toLowerCase().split(/\s+/).filter(w => w.length > 3);
const wordsB = b.toLowerCase().split(/\s+/).filter(w => w.length > 3);
const shared = wordsA.filter(w => wordsB.includes(w));
return shared.length >= 2;
}
function isScoreLike(val) {
return /^\d+\.?\d*\/5$/.test(val.trim()) || val.trim() === 'N/A' || val.trim() === 'DUP';
}
function isStatusLike(val) {
const clean = val.trim().replace(/\*\*/g, '');
return VALID_STATUSES.includes(clean) || STATUS_ALIASES[clean.toLowerCase()] !== undefined;
}
function parseTSV(line) {
const cols = line.split('\t').map(c => c.trim());
if (cols.length < 8) return null;
// Detect column order: status and score might be swapped
let num, date, company, role, status, score, pdf, report, notes;
if (cols.length >= 9) {
[num, date, company, role] = cols.slice(0, 4);
// Columns 4 and 5 could be status/score or score/status
if (isScoreLike(cols[4]) && isStatusLike(cols[5])) {
score = cols[4]; status = cols[5];
} else {
status = cols[4]; score = cols[5];
}
[pdf, report, notes] = cols.slice(6, 9);
} else {
[num, date, company, role, status, score, pdf, report] = cols;
notes = '';
}
return {
num: num.replace(/^#/, ''),
date,
company,
role,
status: validateStatus(status || 'Evaluated'),
score: score || 'N/A',
pdf: pdf || '',
report: report || '',
notes: notes || '',
};
}
async function main() {
// Read tracker
if (!existsSync(TRACKER_PATH)) {
console.error(`Tracker not found: ${TRACKER_PATH}`);
console.log('Run sadhak to create the tracker first.');
process.exit(1);
}
const trackerContent = await readFile(TRACKER_PATH, 'utf-8');
const trackerLines = trackerContent.split('\n');
// Find header separator line
const sepIndex = trackerLines.findIndex(l => /^\|[-\s|]+\|$/.test(l));
if (sepIndex === -1) {
console.error('Could not find tracker table header separator.');
process.exit(1);
}
// Parse existing entries
const existingEntries = [];
for (let i = sepIndex + 1; i < trackerLines.length; i++) {
const line = trackerLines[i].trim();
if (!line || !line.startsWith('|')) continue;
const cols = line.split('|').map(c => c.trim()).filter(Boolean);
if (cols.length >= 4) {
existingEntries.push({
lineIndex: i,
num: cols[0]?.replace(/^#/, ''),
company: cols[2],
role: cols[3],
score: cols[4],
});
}
}
// Read TSV additions
if (!existsSync(ADDITIONS_DIR)) {
console.log('No additions directory found.');
return;
}
const files = (await readdir(ADDITIONS_DIR))
.filter(f => f.endsWith('.tsv'))
.sort();
if (files.length === 0) {
console.log('No TSV files to merge.');
return;
}
console.log(`Found ${files.length} TSV file(s) to merge.`);
let added = 0;
let updated = 0;
let skipped = 0;
const newLines = [];
for (const file of files) {
const content = (await readFile(join(ADDITIONS_DIR, file), 'utf-8')).trim();
if (!content) continue;
const entry = parseTSV(content);
if (!entry) {
console.warn(` Skipping ${file}: could not parse`);
skipped++;
continue;
}
// Check for duplicates
const normCompany = normalizeCompany(entry.company);
const dup = existingEntries.find(e =>
e.num === entry.num ||
(normalizeCompany(e.company) === normCompany && fuzzyRoleMatch(e.role, entry.role))
);
if (dup) {
// Update in place if new score is higher
const existingScore = parseFloat(dup.score);
const newScore = parseFloat(entry.score);
if (!isNaN(newScore) && !isNaN(existingScore) && newScore > existingScore) {
const newLine = `| ${entry.num} | ${entry.date} | ${entry.company} | ${entry.role} | ${entry.score} | ${entry.status} | ${entry.pdf} | ${entry.report} | Re-evaluated: ${entry.notes} |`;
trackerLines[dup.lineIndex] = newLine;
updated++;
console.log(` Updated: ${entry.company} — ${entry.role} (${existingScore} → ${newScore})`);
} else {
skipped++;
console.log(` Skipped (duplicate): ${entry.company} — ${entry.role}`);
}
} else {
// New entry
const newLine = `| ${entry.num} | ${entry.date} | ${entry.company} | ${entry.role} | ${entry.score} | ${entry.status} | ${entry.pdf} | ${entry.report} | ${entry.notes} |`;
newLines.push(newLine);
added++;
console.log(` Added: ${entry.company} — ${entry.role} (${entry.score})`);
}
}
// Insert new lines after header separator
if (newLines.length > 0) {
trackerLines.splice(sepIndex + 1, 0, ...newLines);
}
// Write tracker
if (!DRY_RUN) {
await writeFile(TRACKER_PATH, trackerLines.join('\n'));
// Move processed TSVs to merged/
await mkdir(MERGED_DIR, { recursive: true });
for (const file of files) {
await rename(
join(ADDITIONS_DIR, file),
join(MERGED_DIR, file)
);
}
}
console.log(`\nSummary: ${added} added, ${updated} updated, ${skipped} skipped${DRY_RUN ? ' (DRY RUN)' : ''}`);
// Optional verify
if (VERIFY && !DRY_RUN) {
const { execSync } = await import('node:child_process');
console.log('\nRunning verification...');
try {
execSync('node verify-pipeline.mjs', { stdio: 'inherit' });
} catch {
process.exit(1);
}
}
}
main().catch(err => {
console.error('Merge failed:', err.message);
process.exit(1);
});