oculon 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +344 -2
- package/dist/agent.d.ts +47 -0
- package/dist/agent.js +104 -0
- package/dist/cases.d.ts +68 -0
- package/dist/cases.js +158 -0
- package/dist/cli/main.d.ts +12 -0
- package/dist/cli/main.js +1999 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -0
- package/dist/core/context.d.ts +19 -0
- package/dist/core/context.js +19 -0
- package/dist/core/features.d.ts +22 -0
- package/dist/core/features.js +28 -0
- package/dist/core/graph.d.ts +38 -0
- package/dist/core/graph.js +81 -0
- package/dist/core/http.d.ts +42 -0
- package/dist/core/http.js +266 -0
- package/dist/core/keys.d.ts +8 -0
- package/dist/core/keys.js +22 -0
- package/dist/core/llm.d.ts +93 -0
- package/dist/core/llm.js +180 -0
- package/dist/core/merkle.d.ts +15 -0
- package/dist/core/merkle.js +46 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +6 -0
- package/dist/core/png.d.ts +17 -0
- package/dist/core/png.js +101 -0
- package/dist/core/quota.d.ts +15 -0
- package/dist/core/quota.js +90 -0
- package/dist/core/stats.d.ts +24 -0
- package/dist/core/stats.js +67 -0
- package/dist/core/store.d.ts +20 -0
- package/dist/core/store.js +213 -0
- package/dist/core/text.d.ts +9 -0
- package/dist/core/text.js +30 -0
- package/dist/core/types.d.ts +38 -0
- package/dist/core/types.js +1 -0
- package/dist/index.d.ts +342 -0
- package/dist/index.js +495 -0
- package/dist/live.d.ts +53 -0
- package/dist/live.js +236 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +651 -0
- package/dist/modules/airport.d.ts +60 -0
- package/dist/modules/airport.js +111 -0
- package/dist/modules/audit.d.ts +73 -0
- package/dist/modules/audit.js +211 -0
- package/dist/modules/bgp.d.ts +147 -0
- package/dist/modules/bgp.js +206 -0
- package/dist/modules/blackout.d.ts +41 -0
- package/dist/modules/blackout.js +98 -0
- package/dist/modules/brief.d.ts +26 -0
- package/dist/modules/brief.js +99 -0
- package/dist/modules/calendar.d.ts +27 -0
- package/dist/modules/calendar.js +145 -0
- package/dist/modules/calibrate.d.ts +46 -0
- package/dist/modules/calibrate.js +92 -0
- package/dist/modules/cloud.d.ts +32 -0
- package/dist/modules/cloud.js +94 -0
- package/dist/modules/condor.d.ts +66 -0
- package/dist/modules/condor.js +214 -0
- package/dist/modules/connect.d.ts +47 -0
- package/dist/modules/connect.js +114 -0
- package/dist/modules/contradictions.d.ts +27 -0
- package/dist/modules/contradictions.js +76 -0
- package/dist/modules/country.d.ts +82 -0
- package/dist/modules/country.js +136 -0
- package/dist/modules/cricket.d.ts +34 -0
- package/dist/modules/cricket.js +166 -0
- package/dist/modules/darkships.d.ts +219 -0
- package/dist/modules/darkships.js +400 -0
- package/dist/modules/defi.d.ts +237 -0
- package/dist/modules/defi.js +512 -0
- package/dist/modules/emailsec.d.ts +47 -0
- package/dist/modules/emailsec.js +146 -0
- package/dist/modules/exposure.d.ts +43 -0
- package/dist/modules/exposure.js +89 -0
- package/dist/modules/factcheck.d.ts +39 -0
- package/dist/modules/factcheck.js +127 -0
- package/dist/modules/falcon.d.ts +58 -0
- package/dist/modules/falcon.js +219 -0
- package/dist/modules/feedback.d.ts +24 -0
- package/dist/modules/feedback.js +37 -0
- package/dist/modules/fence.d.ts +52 -0
- package/dist/modules/fence.js +128 -0
- package/dist/modules/ferret.d.ts +47 -0
- package/dist/modules/ferret.js +220 -0
- package/dist/modules/filings.d.ts +86 -0
- package/dist/modules/filings.js +166 -0
- package/dist/modules/fires.d.ts +56 -0
- package/dist/modules/fires.js +150 -0
- package/dist/modules/hazards.d.ts +37 -0
- package/dist/modules/hazards.js +83 -0
- package/dist/modules/health.d.ts +24 -0
- package/dist/modules/health.js +82 -0
- package/dist/modules/heron.d.ts +68 -0
- package/dist/modules/heron.js +184 -0
- package/dist/modules/hound.d.ts +100 -0
- package/dist/modules/hound.js +301 -0
- package/dist/modules/impact.d.ts +39 -0
- package/dist/modules/impact.js +63 -0
- package/dist/modules/launches.d.ts +24 -0
- package/dist/modules/launches.js +61 -0
- package/dist/modules/listen.d.ts +48 -0
- package/dist/modules/listen.js +125 -0
- package/dist/modules/lynx.d.ts +43 -0
- package/dist/modules/lynx.js +127 -0
- package/dist/modules/magpie.d.ts +70 -0
- package/dist/modules/magpie.js +174 -0
- package/dist/modules/meerkat.d.ts +42 -0
- package/dist/modules/meerkat.js +293 -0
- package/dist/modules/monitor.d.ts +27 -0
- package/dist/modules/monitor.js +105 -0
- package/dist/modules/narratives.d.ts +33 -0
- package/dist/modules/narratives.js +136 -0
- package/dist/modules/owl.d.ts +71 -0
- package/dist/modules/owl.js +290 -0
- package/dist/modules/papers.d.ts +46 -0
- package/dist/modules/papers.js +135 -0
- package/dist/modules/personal.d.ts +54 -0
- package/dist/modules/personal.js +153 -0
- package/dist/modules/pulse.d.ts +19 -0
- package/dist/modules/pulse.js +59 -0
- package/dist/modules/raven.d.ts +80 -0
- package/dist/modules/raven.js +147 -0
- package/dist/modules/recall.d.ts +44 -0
- package/dist/modules/recall.js +123 -0
- package/dist/modules/regs.d.ts +88 -0
- package/dist/modules/regs.js +142 -0
- package/dist/modules/rewind.d.ts +22 -0
- package/dist/modules/rewind.js +68 -0
- package/dist/modules/sanctions.d.ts +62 -0
- package/dist/modules/sanctions.js +173 -0
- package/dist/modules/scam.d.ts +43 -0
- package/dist/modules/scam.js +111 -0
- package/dist/modules/scoop.d.ts +31 -0
- package/dist/modules/scoop.js +74 -0
- package/dist/modules/ships.d.ts +33 -0
- package/dist/modules/ships.js +113 -0
- package/dist/modules/sky.d.ts +47 -0
- package/dist/modules/sky.js +183 -0
- package/dist/modules/squawk.d.ts +46 -0
- package/dist/modules/squawk.js +106 -0
- package/dist/modules/tortoise.d.ts +40 -0
- package/dist/modules/tortoise.js +104 -0
- package/dist/modules/travel.d.ts +94 -0
- package/dist/modules/travel.js +241 -0
- package/dist/modules/urlcheck.d.ts +63 -0
- package/dist/modules/urlcheck.js +223 -0
- package/dist/modules/vulns.d.ts +142 -0
- package/dist/modules/vulns.js +276 -0
- package/dist/plugins.d.ts +41 -0
- package/dist/plugins.js +70 -0
- package/dist/report.d.ts +12 -0
- package/dist/report.js +90 -0
- package/dist/scheduler.d.ts +22 -0
- package/dist/scheduler.js +139 -0
- package/dist/sources/aircraft.d.ts +76 -0
- package/dist/sources/aircraft.js +107 -0
- package/dist/sources/airports.d.ts +28 -0
- package/dist/sources/airports.js +100 -0
- package/dist/sources/ais.d.ts +32 -0
- package/dist/sources/ais.js +111 -0
- package/dist/sources/apify.d.ts +28 -0
- package/dist/sources/apify.js +80 -0
- package/dist/sources/arxiv.d.ts +13 -0
- package/dist/sources/arxiv.js +27 -0
- package/dist/sources/certs.d.ts +12 -0
- package/dist/sources/certs.js +23 -0
- package/dist/sources/corp.d.ts +46 -0
- package/dist/sources/corp.js +60 -0
- package/dist/sources/earth.d.ts +39 -0
- package/dist/sources/earth.js +76 -0
- package/dist/sources/fda.d.ts +77 -0
- package/dist/sources/fda.js +121 -0
- package/dist/sources/finance.d.ts +181 -0
- package/dist/sources/finance.js +270 -0
- package/dist/sources/gdelt.d.ts +19 -0
- package/dist/sources/gdelt.js +33 -0
- package/dist/sources/github.d.ts +17 -0
- package/dist/sources/github.js +33 -0
- package/dist/sources/hackernews.d.ts +20 -0
- package/dist/sources/hackernews.js +37 -0
- package/dist/sources/labels.d.ts +21 -0
- package/dist/sources/labels.js +87 -0
- package/dist/sources/launch.d.ts +16 -0
- package/dist/sources/launch.js +41 -0
- package/dist/sources/ofac.d.ts +29 -0
- package/dist/sources/ofac.js +86 -0
- package/dist/sources/onchain.d.ts +77 -0
- package/dist/sources/onchain.js +189 -0
- package/dist/sources/opentimestamps.d.ts +44 -0
- package/dist/sources/opentimestamps.js +131 -0
- package/dist/sources/polymarket.d.ts +36 -0
- package/dist/sources/polymarket.js +70 -0
- package/dist/sources/predict.d.ts +18 -0
- package/dist/sources/predict.js +59 -0
- package/dist/sources/press.d.ts +30 -0
- package/dist/sources/press.js +111 -0
- package/dist/sources/resend.d.ts +14 -0
- package/dist/sources/resend.js +29 -0
- package/dist/sources/robinhood.d.ts +109 -0
- package/dist/sources/robinhood.js +129 -0
- package/dist/sources/sec.d.ts +67 -0
- package/dist/sources/sec.js +129 -0
- package/dist/sources/sentinel.d.ts +13 -0
- package/dist/sources/sentinel.js +63 -0
- package/dist/sources/signatures.d.ts +14 -0
- package/dist/sources/signatures.js +103 -0
- package/dist/sources/social.d.ts +22 -0
- package/dist/sources/social.js +56 -0
- package/dist/sources/space.d.ts +160 -0
- package/dist/sources/space.js +230 -0
- package/dist/sources/usgs.d.ts +17 -0
- package/dist/sources/usgs.js +24 -0
- package/dist/sources/wayback.d.ts +10 -0
- package/dist/sources/wayback.js +28 -0
- package/dist/sources/websec.d.ts +19 -0
- package/dist/sources/websec.js +40 -0
- package/dist/sources/wikidata.d.ts +11 -0
- package/dist/sources/wikidata.js +30 -0
- package/dist/sources/wikimedia.d.ts +28 -0
- package/dist/sources/wikimedia.js +52 -0
- package/dist/telegram.d.ts +104 -0
- package/dist/telegram.js +927 -0
- package/dist/web/assets/favicon-32.png +0 -0
- package/dist/web/assets/fx.js +178 -0
- package/dist/web/assets/icon-192.png +0 -0
- package/dist/web/assets/icon-512.png +0 -0
- package/dist/web/assets/icon-maskable-512.png +0 -0
- package/dist/web/assets/night-americas.jpg +0 -0
- package/dist/web/assets/night-emea.jpg +0 -0
- package/dist/web/assets/og.png +0 -0
- package/dist/web/assets/redsea-bm.jpg +0 -0
- package/dist/web/docs.html +263 -0
- package/dist/web/index.html +1828 -0
- package/dist/web/insights.d.ts +100 -0
- package/dist/web/insights.js +134 -0
- package/dist/web/landing.html +1143 -0
- package/dist/web/legal.html +176 -0
- package/dist/web/manifest.webmanifest +20 -0
- package/dist/web/mcp.html +104 -0
- package/dist/web/mcphttp.d.ts +10 -0
- package/dist/web/mcphttp.js +67 -0
- package/dist/web/openapi.d.ts +1 -0
- package/dist/web/openapi.js +51 -0
- package/dist/web/public.d.ts +45 -0
- package/dist/web/public.js +135 -0
- package/dist/web/server.d.ts +69 -0
- package/dist/web/server.js +750 -0
- package/dist/web/share.d.ts +35 -0
- package/dist/web/share.js +132 -0
- package/dist/web/sw.js +28 -0
- package/package.json +60 -4
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
const SUFFIX = /\b(incorporated|inc|corp|corporation|co|company|llc|ltd|limited|plc|gmbh|ag|sa|holdings?|group|technologies|technology)\b\.?/g;
|
|
2
|
+
export function normEntityName(name) {
|
|
3
|
+
return name
|
|
4
|
+
.toLowerCase()
|
|
5
|
+
.replace(/[.,]/g, ' ')
|
|
6
|
+
.replace(SUFFIX, ' ')
|
|
7
|
+
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
|
8
|
+
.trim();
|
|
9
|
+
}
|
|
10
|
+
/** "www.nvidia.com" -> "nvidia", "openai.co.uk" -> "openai". */
|
|
11
|
+
export function domainLabel(domain) {
|
|
12
|
+
const parts = domain.toLowerCase().replace(/^www\./, '').split('.');
|
|
13
|
+
if (parts.length >= 3 && /^(co|com|org|net|ac|gov)$/.test(parts[parts.length - 2]))
|
|
14
|
+
return parts[parts.length - 3];
|
|
15
|
+
return parts.length >= 2 ? parts[parts.length - 2] : parts[0];
|
|
16
|
+
}
|
|
17
|
+
const NAMED = ['company', 'org', 'topic', 'domain'];
|
|
18
|
+
export function resolveEntities(ctx) {
|
|
19
|
+
const rows = ctx.store.db.prepare(`SELECT id, kind, name FROM entities WHERE kind IN (${NAMED.map(() => '?').join(',')})`).all(...NAMED);
|
|
20
|
+
const byName = new Map();
|
|
21
|
+
for (const r of rows) {
|
|
22
|
+
const key = r.kind === 'domain' ? `domain:${domainLabel(r.name)}` : normEntityName(r.name);
|
|
23
|
+
if (!key || key.length < 2)
|
|
24
|
+
continue;
|
|
25
|
+
const list = byName.get(key) ?? [];
|
|
26
|
+
list.push(r);
|
|
27
|
+
byName.set(key, list);
|
|
28
|
+
}
|
|
29
|
+
const linked = [];
|
|
30
|
+
const has = ctx.store.db.prepare("SELECT 1 FROM edges WHERE rel = 'same_as' AND ((src = ? AND dst = ?) OR (src = ? AND dst = ?))");
|
|
31
|
+
const add = (a, b, why) => {
|
|
32
|
+
if (a === b || has.get(a, b, b, a))
|
|
33
|
+
return;
|
|
34
|
+
ctx.graph.link(a, b, 'same_as', 'resolver', 1, ctx.now().getTime());
|
|
35
|
+
linked.push({ a, b, why });
|
|
36
|
+
};
|
|
37
|
+
for (const [key, list] of byName) {
|
|
38
|
+
if (key.startsWith('domain:'))
|
|
39
|
+
continue;
|
|
40
|
+
// Same name, different kinds. A topic only joins when an org or company has the name, so loose topics stay apart.
|
|
41
|
+
const anchor = list.find((x) => x.kind === 'company') ?? list.find((x) => x.kind === 'org');
|
|
42
|
+
if (anchor)
|
|
43
|
+
for (const x of list)
|
|
44
|
+
if (x.id !== anchor.id)
|
|
45
|
+
add(anchor.id, x.id, `same name "${key}"`);
|
|
46
|
+
// Domain whose main label is the name: nvidia.com belongs to Nvidia. Requires 4+ characters to avoid "arm.com"-style guesses on short words.
|
|
47
|
+
const doms = byName.get(`domain:${key.replace(/\s+/g, '')}`) ?? [];
|
|
48
|
+
if (anchor && key.replace(/\s+/g, '').length >= 4)
|
|
49
|
+
for (const d of doms)
|
|
50
|
+
add(anchor.id, d.id, `domain ${d.id.slice(7)} matches "${key}"`);
|
|
51
|
+
}
|
|
52
|
+
return { checked: rows.length, linked };
|
|
53
|
+
}
|
|
54
|
+
/** Find an entity by exact id, else by name (companies and orgs first). */
|
|
55
|
+
export function findEntity(ctx, q) {
|
|
56
|
+
const db = ctx.store.db;
|
|
57
|
+
const exact = db.prepare('SELECT id, name, kind FROM entities WHERE id = ?').get(q.toLowerCase().trim());
|
|
58
|
+
if (exact)
|
|
59
|
+
return exact;
|
|
60
|
+
const rank = "CASE kind WHEN 'company' THEN 0 WHEN 'org' THEN 1 WHEN 'domain' THEN 2 WHEN 'topic' THEN 3 ELSE 4 END";
|
|
61
|
+
const byName = db.prepare(`SELECT id, name, kind FROM entities WHERE lower(name) = ? ORDER BY ${rank} LIMIT 1`).get(q.toLowerCase().trim());
|
|
62
|
+
if (byName)
|
|
63
|
+
return byName;
|
|
64
|
+
return db.prepare(`SELECT id, name, kind FROM entities WHERE lower(name) LIKE ? ORDER BY ${rank}, length(name) LIMIT 1`).get(`%${q.toLowerCase().trim()}%`);
|
|
65
|
+
}
|
|
66
|
+
export function connect(ctx, a, b, maxDepth = 6) {
|
|
67
|
+
resolveEntities(ctx);
|
|
68
|
+
const src = findEntity(ctx, a);
|
|
69
|
+
const dst = findEntity(ctx, b);
|
|
70
|
+
if (!src || !dst)
|
|
71
|
+
return { from: src?.id ?? null, to: dst?.id ?? null, path: null, explored: 0, note: `not in the graph yet: ${[!src ? a : null, !dst ? b : null].filter(Boolean).join(', ')}. Run a dossier or investigation on it first.` };
|
|
72
|
+
if (src.id === dst.id)
|
|
73
|
+
return { from: src.id, to: dst.id, path: [{ id: src.id, name: src.name, kind: src.kind }], explored: 1 };
|
|
74
|
+
const prev = new Map();
|
|
75
|
+
const seen = new Set([src.id]);
|
|
76
|
+
let frontier = [src.id];
|
|
77
|
+
for (let depth = 0; depth < maxDepth && frontier.length; depth++) {
|
|
78
|
+
const next = [];
|
|
79
|
+
for (const id of frontier) {
|
|
80
|
+
for (const n of ctx.graph.neighbors(id)) {
|
|
81
|
+
if (seen.has(n.id))
|
|
82
|
+
continue;
|
|
83
|
+
seen.add(n.id);
|
|
84
|
+
prev.set(n.id, { from: id, rel: n.rel, direction: n.direction, source: n.source });
|
|
85
|
+
if (n.id === dst.id) {
|
|
86
|
+
const path = [];
|
|
87
|
+
for (let cur = dst.id; cur; cur = prev.get(cur)?.from) {
|
|
88
|
+
const e = ctx.graph.get(cur);
|
|
89
|
+
const p = prev.get(cur);
|
|
90
|
+
path.unshift({ id: cur, name: e?.name ?? cur, kind: e?.kind ?? '?', ...(p ? { via: { rel: p.rel, direction: p.direction, source: p.source } } : {}) });
|
|
91
|
+
if (cur === src.id)
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
return { from: src.id, to: dst.id, path, explored: seen.size };
|
|
95
|
+
}
|
|
96
|
+
next.push(n.id);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// Hubs (thousands of neighbors) would make this explode; the graph is local and small, so a cap is enough.
|
|
100
|
+
frontier = next.slice(0, 5000);
|
|
101
|
+
}
|
|
102
|
+
return { from: src.id, to: dst.id, path: null, explored: seen.size, note: `no path within ${maxDepth} hops` };
|
|
103
|
+
}
|
|
104
|
+
/** Plain-English rendering: "Nvidia -[owns_repo]-> NVIDIA/cuda ...". */
|
|
105
|
+
export function describePath(path) {
|
|
106
|
+
return path
|
|
107
|
+
.map((s, i) => {
|
|
108
|
+
if (i === 0 || !s.via)
|
|
109
|
+
return `${s.name} (${s.kind})`;
|
|
110
|
+
const arrow = s.via.direction === 'out' ? `-[${s.via.rel}]->` : `<-[${s.via.rel}]-`;
|
|
111
|
+
return `${arrow} ${s.name} (${s.kind})`;
|
|
112
|
+
})
|
|
113
|
+
.join(' ');
|
|
114
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contradiction finder: reads several independent articles on a topic and lists factual claims that conflict
|
|
3
|
+
* (different numbers, dates, names, or one source denying what another asserts). Each side must cite a page
|
|
4
|
+
* Oculon actually read; anything else is dropped in code.
|
|
5
|
+
*/
|
|
6
|
+
import type { Ctx } from '../core/context.js';
|
|
7
|
+
import type { ModuleResult } from '../core/types.js';
|
|
8
|
+
export interface Contradiction {
|
|
9
|
+
about: string;
|
|
10
|
+
claimA: string;
|
|
11
|
+
sourceA: string;
|
|
12
|
+
claimB: string;
|
|
13
|
+
sourceB: string;
|
|
14
|
+
severity: 'major' | 'minor';
|
|
15
|
+
}
|
|
16
|
+
export interface ContradictionResult {
|
|
17
|
+
topic: string;
|
|
18
|
+
sourcesRead: {
|
|
19
|
+
title: string;
|
|
20
|
+
url: string;
|
|
21
|
+
}[];
|
|
22
|
+
contradictions: Contradiction[];
|
|
23
|
+
}
|
|
24
|
+
export declare function contradictions(ctx: Ctx, topicInput: string, opts?: {
|
|
25
|
+
maxSources?: number;
|
|
26
|
+
fetch?: typeof fetch;
|
|
27
|
+
}): Promise<ModuleResult<ContradictionResult>>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { availableProviders, chat } from '../core/llm.js';
|
|
2
|
+
import { signalId } from '../core/text.js';
|
|
3
|
+
import { gnews, guardian, readPage, webSearch } from '../sources/press.js';
|
|
4
|
+
export async function contradictions(ctx, topicInput, opts = {}) {
|
|
5
|
+
const topic = topicInput.trim();
|
|
6
|
+
const provenance = [];
|
|
7
|
+
const nowIso = ctx.now().toISOString();
|
|
8
|
+
const [web, gn, gu] = await Promise.all([webSearch(ctx, topic, 8, true), gnews(ctx, topic, 8), guardian(ctx, topic, 7, 6)]);
|
|
9
|
+
provenance.push(web.prov, gn.prov, gu.prov);
|
|
10
|
+
// One page per site, so "independent" means different outlets.
|
|
11
|
+
const seen = new Set();
|
|
12
|
+
const candidates = [...(web.data ?? []).map((w) => ({ title: w.title, url: w.url })), ...(gu.data ?? []), ...(gn.data ?? [])].filter((c) => {
|
|
13
|
+
try {
|
|
14
|
+
const h = new URL(c.url).hostname.replace(/^www\./, '');
|
|
15
|
+
if (seen.has(h))
|
|
16
|
+
return false;
|
|
17
|
+
seen.add(h);
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
const pages = [];
|
|
25
|
+
for (const c of candidates.slice(0, opts.maxSources ?? 6)) {
|
|
26
|
+
const p = await readPage(ctx, c.url, 3500);
|
|
27
|
+
provenance.push(p.prov);
|
|
28
|
+
if (p.data && p.data.length > 400)
|
|
29
|
+
pages.push({ title: c.title, url: c.url, text: p.data });
|
|
30
|
+
}
|
|
31
|
+
const result = { topic, sourcesRead: pages.map((p) => ({ title: p.title, url: p.url })), contradictions: [] };
|
|
32
|
+
if (pages.length < 2 || !availableProviders().length) {
|
|
33
|
+
if (!availableProviders().length)
|
|
34
|
+
provenance.push({ source: 'llm', url: '', status: 'UNAVAILABLE', fetchedAt: nowIso, note: 'contradiction finding needs an LLM key' });
|
|
35
|
+
return { module: 'contradictions', input: topic, generatedAt: nowIso, result, signals: [], provenance };
|
|
36
|
+
}
|
|
37
|
+
const r = await chat([
|
|
38
|
+
{
|
|
39
|
+
role: 'system',
|
|
40
|
+
content: 'You compare news sources on one topic. List factual claims that CONFLICT between sources: different numbers, dates, names, outcomes, or one source denying what another asserts. Ignore differences in emphasis, opinion, or details only one source mentions. Each side must quote or closely paraphrase its source and give that source\'s URL exactly as provided. Reply JSON {"contradictions":[{"about":"...","claim_a":"...","source_a":"url","claim_b":"...","source_b":"url","severity":"major|minor"}]}. Empty list if none.',
|
|
41
|
+
},
|
|
42
|
+
{ role: 'user', content: `Topic: ${topic}\n\n${pages.map((p, i) => `SOURCE ${i + 1} (${p.url})\n${p.title}\n${p.text}`).join('\n\n---\n\n')}` },
|
|
43
|
+
], { json: true, temperature: 0, maxTokens: 2500, premium: true, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
44
|
+
const urls = new Set(pages.map((p) => p.url));
|
|
45
|
+
let raw = [];
|
|
46
|
+
try {
|
|
47
|
+
raw = JSON.parse(r.message.content ?? '{}').contradictions ?? [];
|
|
48
|
+
}
|
|
49
|
+
catch { }
|
|
50
|
+
result.contradictions = raw
|
|
51
|
+
.map((c) => ({
|
|
52
|
+
about: String(c.about ?? '').slice(0, 200),
|
|
53
|
+
claimA: String(c.claim_a ?? '').slice(0, 400),
|
|
54
|
+
sourceA: String(c.source_a ?? ''),
|
|
55
|
+
claimB: String(c.claim_b ?? '').slice(0, 400),
|
|
56
|
+
sourceB: String(c.source_b ?? ''),
|
|
57
|
+
severity: (c.severity === 'major' ? 'major' : 'minor'),
|
|
58
|
+
}))
|
|
59
|
+
.filter((c) => c.claimA && c.claimB && urls.has(c.sourceA) && urls.has(c.sourceB) && c.sourceA !== c.sourceB);
|
|
60
|
+
const signals = result.contradictions
|
|
61
|
+
.filter((c) => c.severity === 'major')
|
|
62
|
+
.slice(0, 3)
|
|
63
|
+
.map((c) => ({
|
|
64
|
+
id: signalId('contradiction', topic, c.about),
|
|
65
|
+
module: 'contradiction',
|
|
66
|
+
title: `Sources disagree on ${topic}: ${c.about}`,
|
|
67
|
+
score: 60,
|
|
68
|
+
evidence: [
|
|
69
|
+
{ source: new URL(c.sourceA).hostname, text: c.claimA, url: c.sourceA },
|
|
70
|
+
{ source: new URL(c.sourceB).hostname, text: c.claimB, url: c.sourceB },
|
|
71
|
+
],
|
|
72
|
+
createdAt: nowIso,
|
|
73
|
+
}));
|
|
74
|
+
signals.forEach((s) => ctx.graph.saveSignal(s));
|
|
75
|
+
return { module: 'contradictions', input: topic, generatedAt: nowIso, result, signals, provenance };
|
|
76
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Country brief: the state of a country in one page.
|
|
3
|
+
* World Bank (no key): GDP, growth, GDP per person, inflation, unemployment, population (latest year reported).
|
|
4
|
+
* IMF World Economic Outlook (no key): growth and inflation for this year and next.
|
|
5
|
+
* Wikidata (no key): head of state, head of government, capital, currency.
|
|
6
|
+
* open.er-api.com (no key): today's exchange rate against the US dollar.
|
|
7
|
+
* Plus US and UK travel advice, confirmed internet outages, orange and red disaster alerts and the latest
|
|
8
|
+
* Guardian headlines about the country.
|
|
9
|
+
*/
|
|
10
|
+
import type { Ctx } from '../core/context.js';
|
|
11
|
+
import type { ModuleResult } from '../core/types.js';
|
|
12
|
+
export interface CountryBrief {
|
|
13
|
+
name: string;
|
|
14
|
+
iso2: string;
|
|
15
|
+
iso3: string;
|
|
16
|
+
region: string | null;
|
|
17
|
+
incomeLevel: string | null;
|
|
18
|
+
capital: string | null;
|
|
19
|
+
leaders: {
|
|
20
|
+
headOfState: string | null;
|
|
21
|
+
headOfGovernment: string | null;
|
|
22
|
+
};
|
|
23
|
+
currency: {
|
|
24
|
+
code: string | null;
|
|
25
|
+
perUsd: number | null;
|
|
26
|
+
asOf: string | null;
|
|
27
|
+
};
|
|
28
|
+
indicators: {
|
|
29
|
+
name: string;
|
|
30
|
+
value: number | null;
|
|
31
|
+
year: string | null;
|
|
32
|
+
unit: string;
|
|
33
|
+
}[];
|
|
34
|
+
outlook: {
|
|
35
|
+
growth: Record<string, number>;
|
|
36
|
+
inflation: Record<string, number>;
|
|
37
|
+
};
|
|
38
|
+
advisories: {
|
|
39
|
+
us: {
|
|
40
|
+
level: number;
|
|
41
|
+
text: string;
|
|
42
|
+
url: string;
|
|
43
|
+
} | null;
|
|
44
|
+
uk: {
|
|
45
|
+
alerts: string[];
|
|
46
|
+
url: string;
|
|
47
|
+
} | null;
|
|
48
|
+
};
|
|
49
|
+
outages: string[];
|
|
50
|
+
hazards: {
|
|
51
|
+
type: string;
|
|
52
|
+
name: string;
|
|
53
|
+
level: string;
|
|
54
|
+
url: string;
|
|
55
|
+
}[];
|
|
56
|
+
headlines: {
|
|
57
|
+
title: string;
|
|
58
|
+
url: string;
|
|
59
|
+
date: string;
|
|
60
|
+
source: string;
|
|
61
|
+
}[];
|
|
62
|
+
}
|
|
63
|
+
interface WbCountry {
|
|
64
|
+
id: string;
|
|
65
|
+
iso2Code: string;
|
|
66
|
+
name: string;
|
|
67
|
+
capitalCity: string;
|
|
68
|
+
region?: {
|
|
69
|
+
value?: string;
|
|
70
|
+
};
|
|
71
|
+
incomeLevel?: {
|
|
72
|
+
value?: string;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export declare const commonName: (c: {
|
|
76
|
+
id: string;
|
|
77
|
+
name: string;
|
|
78
|
+
}) => string;
|
|
79
|
+
/** Finds a country by name, alias, or ISO code in the World Bank list. */
|
|
80
|
+
export declare function findCountry(list: WbCountry[], q: string): WbCountry | null;
|
|
81
|
+
export declare function countryBrief(ctx: Ctx, input: string): Promise<ModuleResult<CountryBrief>>;
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { guardian } from '../sources/press.js';
|
|
2
|
+
import { blackout } from './blackout.js';
|
|
3
|
+
import { hazards } from './hazards.js';
|
|
4
|
+
import { namesFor, ukAdvice, usAdvisory } from './travel.js';
|
|
5
|
+
// World Bank formal names → the everyday names advisories and news use.
|
|
6
|
+
const COMMON = {
|
|
7
|
+
KOR: 'South Korea', PRK: 'North Korea', EGY: 'Egypt', IRN: 'Iran', RUS: 'Russia', VNM: 'Vietnam', TUR: 'Turkey', VEN: 'Venezuela', YEM: 'Yemen', SYR: 'Syria', LAO: 'Laos',
|
|
8
|
+
COD: 'Democratic Republic of the Congo', COG: 'Republic of the Congo', GMB: 'The Gambia', BHS: 'The Bahamas', HKG: 'Hong Kong', MAC: 'Macao', SVK: 'Slovakia', KGZ: 'Kyrgyzstan',
|
|
9
|
+
FSM: 'Micronesia', CZE: 'Czech Republic', CIV: "Cote d'Ivoire", BRN: 'Brunei', CPV: 'Cape Verde', PSE: 'Palestine', LCA: 'St Lucia', VCT: 'St Vincent', KNA: 'St Kitts and Nevis', MKD: 'North Macedonia', SWZ: 'Eswatini', TLS: 'East Timor',
|
|
10
|
+
};
|
|
11
|
+
export const commonName = (c) => COMMON[c.id] ?? c.name.split(',')[0].trim();
|
|
12
|
+
const norm = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, ' ').trim();
|
|
13
|
+
async function wbCountries(ctx) {
|
|
14
|
+
return ctx.http.get('https://api.worldbank.org/v2/country?format=json&per_page=400', {
|
|
15
|
+
source: 'world-bank',
|
|
16
|
+
ttlSec: 30 * 86_400,
|
|
17
|
+
keep: (d) => (Array.isArray(d) && Array.isArray(d[1]) ? d[1].filter((c) => c.region?.value && c.region.value !== 'Aggregates').map((c) => ({ id: c.id, iso2Code: c.iso2Code, name: c.name, capitalCity: c.capitalCity, region: { value: c.region?.value }, incomeLevel: { value: c.incomeLevel?.value } })) : []),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/** Finds a country by name, alias, or ISO code in the World Bank list. */
|
|
21
|
+
export function findCountry(list, q) {
|
|
22
|
+
const n = norm(q);
|
|
23
|
+
const names = namesFor(q);
|
|
24
|
+
return (list.find((c) => c.iso2Code.toLowerCase() === n || c.id.toLowerCase() === n) ??
|
|
25
|
+
list.find((c) => names.includes(norm(c.name))) ??
|
|
26
|
+
// World Bank long forms: "Egypt, Arab Rep.", "Korea, Rep.", "Iran, Islamic Rep."
|
|
27
|
+
list.find((c) => norm(commonName(c)) === n) ??
|
|
28
|
+
(n === 'south korea' ? list.find((c) => c.id === 'KOR') : n === 'north korea' ? list.find((c) => c.id === 'PRK') : n === 'russia' ? list.find((c) => c.id === 'RUS') : n === 'vietnam' ? list.find((c) => c.id === 'VNM') : undefined) ??
|
|
29
|
+
list.find((c) => norm(c.name).startsWith(n)) ??
|
|
30
|
+
null);
|
|
31
|
+
}
|
|
32
|
+
const INDICATORS = [
|
|
33
|
+
['NY.GDP.MKTP.CD', 'GDP', 'USD'],
|
|
34
|
+
['NY.GDP.MKTP.KD.ZG', 'GDP growth', '%'],
|
|
35
|
+
['NY.GDP.PCAP.CD', 'GDP per person', 'USD'],
|
|
36
|
+
['FP.CPI.TOTL.ZG', 'Inflation', '%'],
|
|
37
|
+
['SL.UEM.TOTL.ZS', 'Unemployment', '%'],
|
|
38
|
+
['SP.POP.TOTL', 'Population', 'people'],
|
|
39
|
+
];
|
|
40
|
+
async function indicator(ctx, iso3, id) {
|
|
41
|
+
return ctx.http.get(`https://api.worldbank.org/v2/country/${iso3}/indicator/${id}?format=json&mrnev=1`, {
|
|
42
|
+
source: 'world-bank',
|
|
43
|
+
ttlSec: 7 * 86_400,
|
|
44
|
+
keep: (d) => { const row = Array.isArray(d) ? d[1]?.[0] : undefined; return { value: row?.value ?? null, year: row?.date ?? null }; },
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
async function imf(ctx, code, iso3) {
|
|
48
|
+
return ctx.http.get(`https://www.imf.org/external/datamapper/api/v1/${code}/${iso3}`, {
|
|
49
|
+
source: 'imf',
|
|
50
|
+
ttlSec: 7 * 86_400,
|
|
51
|
+
timeoutMs: 30_000,
|
|
52
|
+
keep: (d) => d.values?.[code]?.[iso3] ?? {},
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function wikidata(ctx, iso2) {
|
|
56
|
+
const q = `SELECT ?hosLabel ?hogLabel ?capLabel ?cur WHERE { ?c wdt:P297 "${iso2}". OPTIONAL{?c p:P35 ?s1. ?s1 ps:P35 ?hos. FILTER NOT EXISTS{?s1 pq:P582 ?e1}} OPTIONAL{?c p:P6 ?s2. ?s2 ps:P6 ?hog. FILTER NOT EXISTS{?s2 pq:P582 ?e2}} OPTIONAL{?c wdt:P36 ?cap} OPTIONAL{?c wdt:P38 ?cu. ?cu wdt:P498 ?cur} SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } LIMIT 5`;
|
|
57
|
+
const r = await ctx.http.get(`https://query.wikidata.org/sparql?format=json&query=${encodeURIComponent(q)}`, {
|
|
58
|
+
source: 'wikidata',
|
|
59
|
+
ttlSec: 3 * 86_400,
|
|
60
|
+
timeoutMs: 30_000,
|
|
61
|
+
keep: (d) => {
|
|
62
|
+
const b = d.results?.bindings ?? [];
|
|
63
|
+
const pick = (k) => b.map((x) => x[k]?.value).find((v) => v && !/^Q\d+$/.test(v)) ?? null;
|
|
64
|
+
return { hos: pick('hosLabel'), hog: pick('hogLabel'), capital: pick('capLabel'), currency: pick('cur') };
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
return r;
|
|
68
|
+
}
|
|
69
|
+
async function usdRate(ctx, code) {
|
|
70
|
+
const r = await ctx.http.get('https://open.er-api.com/v6/latest/USD', {
|
|
71
|
+
source: 'exchange-rates',
|
|
72
|
+
ttlSec: 6 * 3600,
|
|
73
|
+
keep: (d) => ({ rates: d.rates ?? {}, asOf: d.time_last_update_utc ?? null }),
|
|
74
|
+
});
|
|
75
|
+
return { data: r.data ? { rate: r.data.rates[code] ?? null, asOf: r.data.asOf } : null, prov: r.prov };
|
|
76
|
+
}
|
|
77
|
+
export async function countryBrief(ctx, input) {
|
|
78
|
+
const provenance = [];
|
|
79
|
+
const list = await wbCountries(ctx);
|
|
80
|
+
provenance.push(list.prov);
|
|
81
|
+
const c = findCountry(list.data ?? [], input);
|
|
82
|
+
if (!c)
|
|
83
|
+
throw new Error(`country not found: ${input}`);
|
|
84
|
+
const settle = async (p) => { try {
|
|
85
|
+
return await p;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return null;
|
|
89
|
+
} };
|
|
90
|
+
const [ind, gro, inf, wd, us, uk, bo, hz, news] = await Promise.all([
|
|
91
|
+
Promise.all(INDICATORS.map(([id]) => indicator(ctx, c.id, id))),
|
|
92
|
+
imf(ctx, 'NGDP_RPCH', c.id),
|
|
93
|
+
imf(ctx, 'PCPIPCH', c.id),
|
|
94
|
+
wikidata(ctx, c.iso2Code),
|
|
95
|
+
usAdvisory(ctx, commonName(c)),
|
|
96
|
+
ukAdvice(ctx, commonName(c)),
|
|
97
|
+
settle(blackout(ctx, 2)),
|
|
98
|
+
settle(hazards(ctx, 7)),
|
|
99
|
+
guardian(ctx, commonName(c), 3, 6),
|
|
100
|
+
]);
|
|
101
|
+
provenance.push(...ind.map((x) => x.prov).slice(0, 1), gro.prov, wd.prov, us.prov, ...uk.prov, news.prov);
|
|
102
|
+
if (bo)
|
|
103
|
+
provenance.push(...bo.provenance);
|
|
104
|
+
if (hz)
|
|
105
|
+
provenance.push(...hz.provenance);
|
|
106
|
+
const cur = wd.data?.currency ?? null;
|
|
107
|
+
const fx = cur && cur !== 'USD' ? await usdRate(ctx, cur) : null;
|
|
108
|
+
if (fx)
|
|
109
|
+
provenance.push(fx.prov);
|
|
110
|
+
const y = ctx.now().getUTCFullYear();
|
|
111
|
+
const pickYears = (r) => Object.fromEntries(Object.entries(r ?? {}).filter(([k]) => Number(k) >= y - 1 && Number(k) <= y + 1));
|
|
112
|
+
const names = namesFor(commonName(c));
|
|
113
|
+
return {
|
|
114
|
+
module: 'country',
|
|
115
|
+
input,
|
|
116
|
+
generatedAt: ctx.now().toISOString(),
|
|
117
|
+
result: {
|
|
118
|
+
name: commonName(c),
|
|
119
|
+
iso2: c.iso2Code,
|
|
120
|
+
iso3: c.id,
|
|
121
|
+
region: c.region?.value ?? null,
|
|
122
|
+
incomeLevel: c.incomeLevel?.value ?? null,
|
|
123
|
+
capital: wd.data?.capital ?? c.capitalCity ?? null,
|
|
124
|
+
leaders: { headOfState: wd.data?.hos ?? null, headOfGovernment: wd.data?.hog ?? null },
|
|
125
|
+
currency: { code: cur, perUsd: cur === 'USD' ? 1 : fx?.data?.rate ?? null, asOf: fx?.data?.asOf ?? null },
|
|
126
|
+
indicators: INDICATORS.map(([, name, unit], i) => ({ name, unit, value: ind[i]?.data?.value ?? null, year: ind[i]?.data?.year ?? null })),
|
|
127
|
+
outlook: { growth: pickYears(gro.data), inflation: pickYears(inf.data) },
|
|
128
|
+
advisories: { us: us.data ? { level: us.data.level, text: us.data.text, url: us.data.url } : null, uk: uk.data ? { alerts: uk.data.alerts, url: uk.data.url } : null },
|
|
129
|
+
outages: (bo?.result.outages ?? []).filter((o) => o.verified && (o.countryCode === c.iso2Code || (o.country && names.includes(norm(o.country))))).map((o) => `${o.cause ?? o.type ?? 'outage'} since ${o.start.slice(0, 10)}${o.end ? `, ended ${o.end.slice(0, 10)}` : ', ongoing'}`),
|
|
130
|
+
hazards: (hz?.result ?? []).filter((h) => h.level !== 'Green' && h.current && names.some((n) => norm(h.countries).includes(n))).map((h) => ({ type: h.type, name: h.name, level: h.level, url: h.url })),
|
|
131
|
+
headlines: (news.data ?? []).slice(0, 6),
|
|
132
|
+
},
|
|
133
|
+
signals: [],
|
|
134
|
+
provenance,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cricket: measures where a topic sits in its hype cycle by listening to several
|
|
3
|
+
* independent channels (encyclopedia readers, developers, global news, the press, researchers, scholarly output, builders).
|
|
4
|
+
*/
|
|
5
|
+
import { type Ctx } from '../core/context.js';
|
|
6
|
+
import { type Phase, type Trend } from '../core/stats.js';
|
|
7
|
+
import type { ModuleResult } from '../core/types.js';
|
|
8
|
+
export declare const WEEKS = 8;
|
|
9
|
+
export interface Channel {
|
|
10
|
+
channel: 'readers' | 'developers' | 'news' | 'research' | 'builders' | 'press' | 'scholarly';
|
|
11
|
+
source: string;
|
|
12
|
+
/** Weekly values, oldest first. Empty when the channel was unavailable. */
|
|
13
|
+
weekly: number[];
|
|
14
|
+
unit: string;
|
|
15
|
+
trend: Trend | null;
|
|
16
|
+
note?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface CricketResult {
|
|
19
|
+
topic: string;
|
|
20
|
+
wikipediaTitle: string | null;
|
|
21
|
+
phase: Phase;
|
|
22
|
+
momentum: number;
|
|
23
|
+
acceleration: number;
|
|
24
|
+
/** Mean-normalized composite of all available channels, oldest first. */
|
|
25
|
+
composite: number[];
|
|
26
|
+
channels: Channel[];
|
|
27
|
+
summary: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Mean-normalized weighted average across channels, aligned on the most recent week.
|
|
31
|
+
* Channels with fewer than WEEKS buckets (e.g. GDELT's shorter window) contribute to the weeks they cover.
|
|
32
|
+
*/
|
|
33
|
+
export declare function composite(channels: Channel[]): number[];
|
|
34
|
+
export declare function cricket(ctx: Ctx, topicInput: string): Promise<ModuleResult<CricketResult>>;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cricket: measures where a topic sits in its hype cycle by listening to several
|
|
3
|
+
* independent channels (encyclopedia readers, developers, global news, the press, researchers, scholarly output, builders).
|
|
4
|
+
*/
|
|
5
|
+
import { DAY_MS } from '../core/context.js';
|
|
6
|
+
import { bucketFromEnd, mean, trend } from '../core/stats.js';
|
|
7
|
+
import { signalId } from '../core/text.js';
|
|
8
|
+
import { paperCount } from '../sources/arxiv.js';
|
|
9
|
+
import { coverageTimeline } from '../sources/gdelt.js';
|
|
10
|
+
import { repoCount } from '../sources/github.js';
|
|
11
|
+
import { weeklyStoryCounts } from '../sources/hackernews.js';
|
|
12
|
+
import { guardianCount } from '../sources/press.js';
|
|
13
|
+
import { openalexCount } from '../sources/social.js';
|
|
14
|
+
import { dailyViews, resolveTitle } from '../sources/wikimedia.js';
|
|
15
|
+
export const WEEKS = 8;
|
|
16
|
+
const WEIGHT = { readers: 1, developers: 1, news: 1, press: 0.8, research: 0.6, scholarly: 0.6, builders: 0.8 };
|
|
17
|
+
function weeklyFromDaily(values, agg) {
|
|
18
|
+
return bucketFromEnd(values, 7, agg).slice(-WEEKS);
|
|
19
|
+
}
|
|
20
|
+
function channel(c) {
|
|
21
|
+
return { ...c, trend: c.weekly.length >= 4 ? trend(c.weekly) : null };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Mean-normalized weighted average across channels, aligned on the most recent week.
|
|
25
|
+
* Channels with fewer than WEEKS buckets (e.g. GDELT's shorter window) contribute to the weeks they cover.
|
|
26
|
+
*/
|
|
27
|
+
export function composite(channels) {
|
|
28
|
+
const usable = channels.filter((c) => c.channel !== 'builders' && c.weekly.length >= 4 && mean(c.weekly) > 0);
|
|
29
|
+
if (!usable.length)
|
|
30
|
+
return [];
|
|
31
|
+
return Array.from({ length: WEEKS }, (_, i) => {
|
|
32
|
+
let acc = 0;
|
|
33
|
+
let w = 0;
|
|
34
|
+
for (const c of usable) {
|
|
35
|
+
const j = i - (WEEKS - c.weekly.length);
|
|
36
|
+
if (j < 0)
|
|
37
|
+
continue;
|
|
38
|
+
acc += (WEIGHT[c.channel] * c.weekly[j]) / mean(c.weekly);
|
|
39
|
+
w += WEIGHT[c.channel];
|
|
40
|
+
}
|
|
41
|
+
return w ? acc / w : 0;
|
|
42
|
+
}).filter((_, i) => usable.some((c) => i - (WEEKS - c.weekly.length) >= 0));
|
|
43
|
+
}
|
|
44
|
+
const fmt = (x) => (Number.isFinite(x) ? `${x >= 1 ? '+' : ''}${Math.round((x - 1) * 100)}%` : 'new');
|
|
45
|
+
export async function cricket(ctx, topicInput) {
|
|
46
|
+
const topic = topicInput.trim();
|
|
47
|
+
const provenance = [];
|
|
48
|
+
const nowMs = ctx.now().getTime();
|
|
49
|
+
const days = WEEKS * 7;
|
|
50
|
+
const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
51
|
+
const title = await resolveTitle(ctx, topic);
|
|
52
|
+
provenance.push(title.prov);
|
|
53
|
+
// Hour-aligned "now" keeps cache keys stable across runs within the same hour.
|
|
54
|
+
const hourMs = Math.floor(nowMs / 3_600_000) * 3_600_000;
|
|
55
|
+
const week = 7 * DAY_MS;
|
|
56
|
+
// Whole-day weekly windows (oldest first) for date-based APIs.
|
|
57
|
+
const dayWindows = Array.from({ length: WEEKS }, (_, i) => {
|
|
58
|
+
const end = nowMs - DAY_MS - (WEEKS - 1 - i) * week;
|
|
59
|
+
return [iso(end - week + DAY_MS), iso(end)];
|
|
60
|
+
});
|
|
61
|
+
const [views, hn, news, papers, ghRecent, ghPrev, press, scholarly] = await Promise.all([
|
|
62
|
+
title.data ? dailyViews(ctx, title.data, days) : Promise.resolve(null),
|
|
63
|
+
weeklyStoryCounts(ctx, topic, WEEKS),
|
|
64
|
+
coverageTimeline(ctx, topic, days),
|
|
65
|
+
Promise.all(Array.from({ length: WEEKS }, (_, i) => paperCount(ctx, topic, hourMs - (WEEKS - i) * week, hourMs - (WEEKS - 1 - i) * week))),
|
|
66
|
+
repoCount(ctx, `${topic} created:${iso(nowMs - 28 * DAY_MS)}..${iso(nowMs)}`),
|
|
67
|
+
repoCount(ctx, `${topic} created:${iso(nowMs - 56 * DAY_MS)}..${iso(nowMs - 28 * DAY_MS - DAY_MS)}`),
|
|
68
|
+
Promise.all(dayWindows.map(([from, to]) => guardianCount(ctx, topic, from, to))),
|
|
69
|
+
Promise.all(dayWindows.map(([from, to]) => openalexCount(ctx, topic, from, to))),
|
|
70
|
+
]);
|
|
71
|
+
const channels = [];
|
|
72
|
+
if (views)
|
|
73
|
+
provenance.push(views.prov);
|
|
74
|
+
channels.push(channel({
|
|
75
|
+
channel: 'readers',
|
|
76
|
+
source: 'wikimedia-pageviews',
|
|
77
|
+
unit: 'pageviews/week',
|
|
78
|
+
weekly: views?.data ? weeklyFromDaily(views.data.map((v) => v.views), (g) => g.reduce((a, b) => a + b, 0)) : [],
|
|
79
|
+
...(title.data ? { note: `article: ${title.data}` } : { note: 'no matching Wikipedia article' }),
|
|
80
|
+
}));
|
|
81
|
+
provenance.push(...hn.provs);
|
|
82
|
+
channels.push(channel({ channel: 'developers', source: 'hackernews', unit: 'stories/week', weekly: hn.data ?? [] }));
|
|
83
|
+
provenance.push(news.prov);
|
|
84
|
+
channels.push(channel({
|
|
85
|
+
channel: 'news',
|
|
86
|
+
source: 'gdelt',
|
|
87
|
+
unit: '% of global news (weekly avg)',
|
|
88
|
+
weekly: news.data ? weeklyFromDaily(news.data.map((p) => p.value), mean) : [],
|
|
89
|
+
}));
|
|
90
|
+
provenance.push(...papers.map((p) => p.prov));
|
|
91
|
+
// arXiv indexes with a lag of a few days, so the newest week can read low; noted for the reader.
|
|
92
|
+
channels.push(channel({
|
|
93
|
+
channel: 'research',
|
|
94
|
+
source: 'arxiv',
|
|
95
|
+
unit: 'papers/week',
|
|
96
|
+
weekly: papers.every((p) => p.data !== null) ? papers.map((p) => p.data) : [],
|
|
97
|
+
note: 'newest week may be incomplete (arXiv indexing lag)',
|
|
98
|
+
}));
|
|
99
|
+
provenance.push(press[0].prov);
|
|
100
|
+
if (press.some((p) => p.prov.status === 'ERROR'))
|
|
101
|
+
provenance.push(...press.filter((p) => p.prov.status === 'ERROR').map((p) => p.prov));
|
|
102
|
+
channels.push(channel({
|
|
103
|
+
channel: 'press',
|
|
104
|
+
source: 'guardian',
|
|
105
|
+
unit: 'Guardian articles/week',
|
|
106
|
+
weekly: press.every((p) => p.data !== null) ? press.map((p) => p.data) : [],
|
|
107
|
+
...(press[0].prov.status === 'UNAVAILABLE' ? { note: press[0].prov.note ?? 'unavailable' } : {}),
|
|
108
|
+
}));
|
|
109
|
+
provenance.push(...scholarly.map((p) => p.prov));
|
|
110
|
+
channels.push(channel({
|
|
111
|
+
channel: 'scholarly',
|
|
112
|
+
source: 'openalex',
|
|
113
|
+
unit: 'scholarly works/week',
|
|
114
|
+
weekly: scholarly.every((p) => p.data !== null) ? scholarly.map((p) => p.data) : [],
|
|
115
|
+
note: 'all publishers incl. journals and preprints; recent weeks fill in as works are indexed',
|
|
116
|
+
}));
|
|
117
|
+
provenance.push(ghRecent.prov, ghPrev.prov);
|
|
118
|
+
const builders = {
|
|
119
|
+
channel: 'builders',
|
|
120
|
+
source: 'github-search',
|
|
121
|
+
unit: 'new repos per 4 weeks',
|
|
122
|
+
weekly: ghRecent.data !== null && ghPrev.data !== null ? [ghPrev.data, ghRecent.data] : [],
|
|
123
|
+
trend: null,
|
|
124
|
+
note: 'two 4-week buckets; shown for momentum, not used in the weekly composite',
|
|
125
|
+
};
|
|
126
|
+
if (builders.weekly.length === 2) {
|
|
127
|
+
const [prev, recent] = builders.weekly;
|
|
128
|
+
const m = prev > 0 ? recent / prev : recent > 0 ? Infinity : 1;
|
|
129
|
+
builders.trend = { phase: m >= 1.5 ? 'RISING' : m <= 0.75 ? 'COOLING' : 'STEADY', momentum: m, acceleration: m };
|
|
130
|
+
}
|
|
131
|
+
channels.push(builders);
|
|
132
|
+
const comp = composite(channels);
|
|
133
|
+
const t = comp.length ? trend(comp) : { phase: 'DORMANT', momentum: 1, acceleration: 1 };
|
|
134
|
+
const live = channels.filter((c) => c.weekly.length);
|
|
135
|
+
const summary = live.length
|
|
136
|
+
? `${topic}: ${t.phase} (momentum ${fmt(t.momentum)} vs earlier weeks, last week ${fmt(t.acceleration)}). ` +
|
|
137
|
+
live.map((c) => `${c.channel} ${c.trend ? `${c.trend.phase.toLowerCase()} ${fmt(c.trend.momentum)}` : 'n/a'}`).join(', ')
|
|
138
|
+
: `${topic}: no channel returned data`;
|
|
139
|
+
const id = ctx.graph.upsert('topic', topic, { lastPhase: t.phase });
|
|
140
|
+
ctx.graph.observe(id, 'cricket', 'momentum', Number.isFinite(t.momentum) ? t.momentum : null, 'composite', { phase: t.phase });
|
|
141
|
+
if (title.data)
|
|
142
|
+
ctx.graph.link(id, ctx.graph.upsert('article', title.data), 'described_by', 'wikipedia');
|
|
143
|
+
const createdAt = new Date(nowMs).toISOString();
|
|
144
|
+
const signals = [];
|
|
145
|
+
if (t.phase === 'RISING' || t.phase === 'EMERGING' || t.phase === 'PEAK') {
|
|
146
|
+
const agreeing = live.filter((c) => c.trend && c.trend.phase === t.phase);
|
|
147
|
+
signals.push({
|
|
148
|
+
id: signalId('cricket', topic, t.phase, createdAt.slice(0, 10)),
|
|
149
|
+
module: 'cricket',
|
|
150
|
+
title: `${topic} is ${t.phase}`,
|
|
151
|
+
score: Math.min(100, 40 + agreeing.length * 12 + (Number.isFinite(t.momentum) ? Math.min(20, (t.momentum - 1) * 20) : 20)),
|
|
152
|
+
entity: id,
|
|
153
|
+
evidence: live.map((c) => ({ source: c.source, text: `${c.channel}: ${c.trend?.phase ?? 'n/a'} ${c.trend ? fmt(c.trend.momentum) : ''}`.trim() })),
|
|
154
|
+
createdAt,
|
|
155
|
+
});
|
|
156
|
+
signals.forEach((s) => ctx.graph.saveSignal(s));
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
module: 'cricket',
|
|
160
|
+
input: topic,
|
|
161
|
+
generatedAt: createdAt,
|
|
162
|
+
result: { topic, wikipediaTitle: title.data, phase: t.phase, momentum: t.momentum, acceleration: t.acceleration, composite: comp, channels, summary },
|
|
163
|
+
signals,
|
|
164
|
+
provenance,
|
|
165
|
+
};
|
|
166
|
+
}
|