Repository navigation
Expand file tree
/
Copy pathhook.js
More file actions
143 lines (127 loc) · 4.77 KB
/
Copy pathhook.js
File metadata and controls
143 lines (127 loc) · 4.77 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
#!/usr/bin/env node
import { parseTranscript, scoreSession, descriptorFor } from './engine.js';
import {
getDB, getDefaultUser, getOrCreateUser, saveSession, updateSession,
getSessionByTranscript, sumXpExcept, getTotalXP, hasSessionOnDate, countSessions,
getActiveTitle, saveActiveTitle, clearActiveTitle, reconcileFromCloud,
} from './db.js';
import { levelFor, nextLevelOf, progressToNext } from './levels.js';
import { checkAchievements } from './achievements.js';
import { applyQuestBonus } from './questBonus.js';
import { renderOverlay } from './overlay.js';
import { updateProfile, fetchProfile, hasCloudConfig } from './sync.js';
import { loadConfig } from './config.js';
import { rollTitle, isActiveTitle } from './titles.js';
function readStdin() {
return new Promise((resolve) => {
if (process.stdin.isTTY) return resolve('');
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (c) => { data += c; });
process.stdin.on('end', () => resolve(data));
process.stdin.on('error', () => resolve(data));
});
}
async function main() {
const raw = await readStdin();
let payload = {};
try { payload = raw ? JSON.parse(raw) : {}; } catch { payload = {}; }
const db = getDB();
let user = getDefaultUser(db);
if (!user) user = getOrCreateUser(db, 'player');
// Pull cloud baseline before scoring so a second machine / reinstall
// catches up to the cloud total instead of clobbering it on PATCH.
if (hasCloudConfig()) {
const cfg = loadConfig();
if (cfg.claimed_username && cfg.owner_token) {
try {
const r = await fetchProfile(cfg.claimed_username);
if (r.ok && r.row) {
reconcileFromCloud(db, user.id, {
totalXP: r.row.total_xp || 0,
sessionCount: r.row.session_count || 0,
});
}
} catch { /* network hiccup — skip silently, regular sync below will retry */ }
}
}
const transcriptPath = payload.transcript_path || null;
const signals = parseTranscript(transcriptPath);
const yDate = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
const streakActive = hasSessionOnDate(db, user.id, yDate);
const base = scoreSession(signals, streakActive);
const { xp: sessionScore, breakdown } = applyQuestBonus({
db,
userId: user.id,
signals,
baseXP: base.xp,
breakdown: base.breakdown,
});
const existing = getSessionByTranscript(db, user.id, transcriptPath);
let xpGained, newXP;
if (existing) {
xpGained = Math.max(0, sessionScore - existing.xp_gained);
newXP = sumXpExcept(db, user.id, existing.id) + sessionScore;
} else {
xpGained = sessionScore;
newXP = getTotalXP(db, user.id) + sessionScore;
}
const prevXP = newXP - xpGained;
const prevLevel = levelFor(prevXP);
const newLevel = levelFor(newXP);
if (existing) {
updateSession(db, existing.id, sessionScore, breakdown, newXP, newLevel.level);
} else {
saveSession(db, user.id, sessionScore, breakdown, newXP, newLevel.level, transcriptPath);
}
const newAchievements = checkAchievements(db, user.id, signals, newXP, newLevel);
let loot = null;
const existingTitle = getActiveTitle(db, user.id);
if (existingTitle && !isActiveTitle(existingTitle.title, existingTitle.expiresAt)) {
clearActiveTitle(db, user.id);
}
const drop = rollTitle();
if (drop) {
saveActiveTitle(db, user.id, drop.title, drop.expiresAt);
loot = { title: drop.title, expiresAt: drop.expiresAt, isNew: true };
} else {
const current = getActiveTitle(db, user.id);
if (current && isActiveTitle(current.title, current.expiresAt)) {
loot = { title: current.title, expiresAt: current.expiresAt, isNew: false };
}
}
const overlay = renderOverlay({
xpGained,
breakdown,
descriptor: descriptorFor(signals),
level: newLevel.level,
levelInfo: newLevel,
progressPercent: progressToNext(newXP, newLevel),
nextLevelInfo: nextLevelOf(newLevel),
newAchievements,
levelUp: newLevel.level > prevLevel.level,
loot,
});
process.stderr.write('\n' + overlay + '\n\n');
if (hasCloudConfig()) {
const cfg = loadConfig();
const claimedUsername = cfg.claimed_username;
const ownerToken = cfg.owner_token;
if (claimedUsername && ownerToken) {
const res = await updateProfile({
username: claimedUsername,
ownerToken,
totalXP: newXP,
level: newLevel.level,
sessionCount: countSessions(db, user.id),
activeTitle: loot ? loot.title : null,
titleExpiresAt: loot ? loot.expiresAt : null,
});
if (!res.ok) process.stderr.write(`[claudexp] cloud sync failed: ${res.reason}\n`);
}
}
}
main().catch((err) => {
try { process.stderr.write(`[claudexp] hook error: ${err?.message || err}\n`); } catch {}
process.exit(0);
});