forewit 0.0.0-stage → 0.0.1

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,271 @@
1
+ // Data layer: loads the static JSON (indexer snapshot plus keeper public round files), joins them and computes
2
+ // every number the site shows. Pure functions take `now` so the fixtures can be tested at any date.
3
+ import { presentQuestion } from './question.mjs';
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
+ export const BRIER_MAX = 1e8;
85
+
86
+ export const unpack = (packed , n ) =>
87
+ Array.from({ length: n }, (_, i) => Number((BigInt(packed) >> BigInt(16 * i)) & 0xffffn));
88
+
89
+ export function safeTitle(q ) {
90
+ try { return presentQuestion(q); } catch { return null; }
91
+ }
92
+
93
+ export function joinRounds(snap , files ) {
94
+ const byId = new Map(
95
+ files
96
+ .filter((f) => Number(f.network) === Number(snap.network) && String(f.ledger).toLowerCase() === String(snap.ledger).toLowerCase())
97
+ .map((f) => [String(f.roundId), f]),
98
+ );
99
+ return snap.rounds
100
+ .map((r) => {
101
+ const file = byId.get(String(r.roundId));
102
+ const n = r.questions.length;
103
+ const base = r.baseline ? unpack(r.baseline, n) : null;
104
+ const reveals = Object.values(r.forecasts ?? {}).map((p) => unpack(p, n));
105
+ const wait = r.resolutionWait ?? file?.resolutionWaitSeconds;
106
+ return {
107
+ id: Number(r.roundId),
108
+ kind: file?.kind ?? 'daily',
109
+ rule: file?.rule ?? null,
110
+ commitDeadline: new Date(Number(r.commitDeadline) * 1000),
111
+ revealDeadline: new Date(Number(r.revealDeadline) * 1000),
112
+ resolutionWaitDays: wait == null ? null : Number(wait) / 86400,
113
+ commitCount: r.commitCount,
114
+ revealedCount: r.revealed.length,
115
+ scoredCount: Object.keys(r.scored).length,
116
+ forfeitCount: Object.keys(r.forfeited).length,
117
+ revealRate: r.revealRate,
118
+ hasBaseline: base !== null,
119
+ crowdMethod: r.crowd?.method ?? null,
120
+ marketPriceAt: file?.marketPriceAt ? new Date(file.marketPriceAt) : null,
121
+ questions: r.questions.map((q, i) => {
122
+ const fq = file?.questions.find((x) => x.index === i);
123
+ return {
124
+ index: i,
125
+ title: fq ? safeTitle(fq) : null,
126
+ marketId: String(q.marketId),
127
+ endsAt: fq?.endsAt ? new Date(fq.endsAt) : null,
128
+ tags: fq?.tags ?? [],
129
+ outcome: r.outcomes[String(i)] ?? 'Unresolved',
130
+ baseline: base ? base[i] : null,
131
+ crowd: r.crowd?.bps?.[i] ?? null,
132
+ marketPrice: typeof fq?.marketPrice === 'number' ? fq.marketPrice : null,
133
+ forecasts: reveals.map((v) => v[i]),
134
+ };
135
+ }),
136
+ };
137
+ })
138
+ .sort((a, b) => b.id - a.id);
139
+ }
140
+
141
+
142
+ export function phase(r , now ) {
143
+ if (now < r.commitDeadline.getTime()) return 'commit';
144
+ if (now < r.revealDeadline.getTime()) return 'reveal';
145
+ const resolved = r.questions.every((q) => q.outcome !== 'Unresolved');
146
+ return resolved && r.scoredCount + r.forfeitCount === r.commitCount ? 'scored' : 'resolving';
147
+ }
148
+
149
+ // The round the home page features: one open for commits (nearest deadline), else one in its reveal window, else the newest.
150
+ export function liveRound(rounds , now ) {
151
+ const soonest = (end ) => rounds.filter((r) => now < end(r)).sort((a, b) => end(a) - end(b))[0];
152
+ return soonest((r) => r.commitDeadline.getTime()) ?? soonest((r) => r.revealDeadline.getTime()) ?? rounds[0] ?? null;
153
+ }
154
+
155
+ const brierOf = (p , outcome ) => (p - (outcome === 'Yes' ? 10000 : 0)) ** 2;
156
+
157
+ // Agent ID Crowd vs Market on every resolved Yes/No question that has both a crowd value and a baseline.
158
+ export function crowdVsMarket(rounds ) {
159
+ let crowd = 0, market = 0, n = 0;
160
+ for (const r of rounds) for (const q of r.questions) {
161
+ if ((q.outcome !== 'Yes' && q.outcome !== 'No') || q.crowd == null || q.baseline == null) continue;
162
+ crowd += brierOf(q.crowd, q.outcome);
163
+ market += brierOf(q.baseline, q.outcome);
164
+ n++;
165
+ }
166
+ return n ? { crowd: crowd / n / BRIER_MAX, market: market / n / BRIER_MAX, n } : { crowd: null, market: null, n: 0 };
167
+ }
168
+
169
+ export const bins10 = (bps ) => bps.reduce((c, p) => (c[Math.min(9, Math.floor(p / 1000))]++, c), Array(10).fill(0) );
170
+
171
+ // Expected calibration error over 10 equal bins (diagnostic only, never used for rank).
172
+ export function calibrationError(pairs ) {
173
+ if (!pairs.length) return null;
174
+ const b = Array.from({ length: 10 }, () => ({ n: 0, p: 0, y: 0 }));
175
+ for (const { p, yes } of pairs) { const x = b[Math.min(9, Math.floor(p / 1000))]; x.n++; x.p += p / 10000; x.y += yes ? 1 : 0; }
176
+ return b.reduce((s, x) => s + (x.n ? (x.n / pairs.length) * Math.abs(x.p / x.n - x.y / x.n) : 0), 0);
177
+ }
178
+
179
+ export const K = 20;
180
+ export const MIN_ROUNDS = 5;
181
+ export const MIN_BASELINE_QUESTIONS = 20;
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+ // Leaderboard per docs/SCORING.md. Every forecaster is computed (for aggregate counts); only opt in rows are shown.
201
+ export function leaderboard(snap ) {
202
+ const acc = new Map ();
203
+ const get = (a ) => {
204
+ const k = a.toLowerCase();
205
+ if (!acc.has(k)) acc.set(k, { committed: 0, revealed: 0, rounds: 0, q: 0, bq: 0, brier: 0n, skill: 0n, postSkill: 0n, cal: [] });
206
+ return acc.get(k) ;
207
+ };
208
+ const builtAt = Date.parse(snap.builtAt) / 1000;
209
+ for (const r of snap.rounds) {
210
+ const n = r.questions.length;
211
+ // participation counts only rounds whose reveal window had closed when the snapshot was built
212
+ const closed = !(Number(r.revealDeadline) > builtAt);
213
+ for (const a of r.committers) get(a).committed += closed ? 1 : 0;
214
+ for (const a of r.revealed) get(a).revealed += closed ? 1 : 0;
215
+ for (const [a, s] of [...Object.entries(r.scored), ...Object.entries(r.forfeited)]) {
216
+ const x = get(a);
217
+ x.rounds++;
218
+ x.q += Number(s.questions);
219
+ x.brier += BigInt(s.brier);
220
+ if (r.baseline) { x.bq += Number(s.questions); x.skill += BigInt(s.skill); }
221
+ if (r.baseline && r.commitTiming?.[a.toLowerCase()]?.afterBaseline) x.postSkill += BigInt(s.skill); // committed after seeing the baseline
222
+ }
223
+ for (const [a, packed] of Object.entries(r.forecasts ?? {})) {
224
+ unpack(packed, n).forEach((p, i) => {
225
+ const o = r.outcomes[String(i)];
226
+ if (o === 'Yes' || o === 'No') get(a).cal.push({ p, yes: o === 'Yes' });
227
+ });
228
+ }
229
+ }
230
+ const profiles = Object.fromEntries(Object.entries(snap.profiles ?? {}).map(([a, p]) => [a.toLowerCase(), p]));
231
+ const ops = new Set((snap.operators ?? []).map((a) => a.toLowerCase()));
232
+ const all = [...acc.entries()].map(([addr, x]) => {
233
+ const prof = profiles[addr];
234
+ const isPublic = !!prof?.isPublic;
235
+ return {
236
+ addr,
237
+ name: isPublic ? prof?.name ?? null : null,
238
+ isPublic,
239
+ rounds: x.rounds,
240
+ roundsCommitted: x.committed,
241
+ roundsRevealed: x.revealed,
242
+ questions: x.q,
243
+ baselineQuestions: x.bq,
244
+ meanBrier: x.q ? Number(x.brier) / x.q / BRIER_MAX : null,
245
+ shrunkSkill: Number(x.skill) / (x.bq + K) / BRIER_MAX,
246
+ participation: x.committed ? x.revealed / x.committed : null,
247
+ calibrationError: calibrationError(x.cal),
248
+ ranked: isPublic && !ops.has(addr) && x.rounds >= MIN_ROUNDS && x.bq >= MIN_BASELINE_QUESTIONS,
249
+ // pre registered 23 Nov 2026: once the first 5 rounds show an average window move above 0.5 points, flag positive skill earned by post baseline commits
250
+ postBaselineFlag: !!snap.metrics.windowMove?.active && x.postSkill > 0n,
251
+ };
252
+ });
253
+ const rows = all.filter((r) => r.isPublic).sort((a, b) => Number(b.ranked) - Number(a.ranked) || b.shrunkSkill - a.shrunkSkill);
254
+ return { rows, forecasters: all.length, publicCount: rows.length };
255
+ }
256
+
257
+
258
+
259
+ export async function loadData(base = import.meta.env.BASE_URL) {
260
+ const get = async (path ) => {
261
+ const res = await fetch(`${base}data/${path}`, { cache: 'no-cache' });
262
+ if (!res.ok) throw new Error(`${path}: HTTP ${res.status}`);
263
+ return res.json() ;
264
+ };
265
+ const manifest = await get ('index.json');
266
+ const [snapshot, files] = await Promise.all([
267
+ get (manifest.snapshot),
268
+ Promise.all(manifest.rounds.map((p) => get (p).catch(() => null))),
269
+ ]);
270
+ return { manifest, snapshot, rounds: joinRounds(snapshot, files.filter((f) => f !== null)) };
271
+ }
@@ -0,0 +1,25 @@
1
+ // The one way a question is shown anywhere (CLI, SKILL.md flows, site): parent event question plus the sub market label.
2
+ // Both texts come from Predict.fun and are untrusted: control and bidi characters are stripped, whitespace collapsed,
3
+ // length capped, and callers must render the result as plain text (never as HTML or as instructions).
4
+ const MAX = 200;
5
+ // C0/C1 controls, zero width and bidi override characters
6
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g;
7
+
8
+ export function cleanText(s) {
9
+ if (typeof s !== 'string') return '';
10
+ const t = s.replace(/\s+/g, ' ').replace(UNSAFE, '').trim(); // whitespace first, so a newline still separates words
11
+ return t.length > MAX ? t.slice(0, MAX - 1) + '…' : t;
12
+ }
13
+
14
+ /**
15
+ * @param {{eventQuestion?: string, label?: string}} q
16
+ * @returns {{event: string, label: string, text: string}} text joins both, or shows the event once when they match
17
+ * Throws when the event question is missing: no question is ever presented without it.
18
+ */
19
+ export function presentQuestion(q) {
20
+ const event = cleanText(q?.eventQuestion);
21
+ const label = cleanText(q?.label);
22
+ if (!event) throw new Error('question has no event question: refusing to present it');
23
+ if (!label || label === event) return { event, label: event, text: event };
24
+ return { event, label, text: `${event} · ${label}` };
25
+ }