mirror of
https://github.com/bitbaum/truthseeker.git
synced 2026-12-04 02:37:06 +01:00
* chore: add a formatter, matching the style this repo already writes singleQuote=false was chosen by counting this repo's own imports, not by fleet decree. The fleet is genuinely split and the two repos that already had a .prettierrc disagreed with each other, so there was no standard to restore. Quote style does not cross repo boundaries; having a gate does. Markdown is ignored for now — prettier rewraps prose, which would bury the real diff. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * style: format with prettier (13 files) Mechanical. No behaviour change. This SHA is listed in .git-blame-ignore-revs so `git blame` skips it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore: teach git blame to skip the reformat Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
177 lines
6.3 KiB
TypeScript
177 lines
6.3 KiB
TypeScript
// CLI variant of /api/analyze. No dev server needed — runs the same
|
|
// pipeline against a URL passed on argv and writes the analysis as
|
|
// Markdown to analyses/<slug>.md so the output is reviewable + committable.
|
|
//
|
|
// Usage:
|
|
// GROQ_API_KEY=gsk_... npm run analyze -- "https://example.com/article"
|
|
// or, with .env.local present:
|
|
// npm run analyze -- "https://example.com/article"
|
|
//
|
|
// Any vendor in the chain will do — OPENROUTER_API_KEY alone is a complete
|
|
// configuration. This script asks lib/llm which keys count rather than naming
|
|
// one, so the next vendor the fleet chain gains works here on the day it lands.
|
|
|
|
import { readFileSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
import { join } from "path";
|
|
import { analyzeUrl, analyzeText, type AnalysisResult } from "../src/lib/analysis";
|
|
import { configuredLinks, noProviderMessage } from "../src/lib/llm";
|
|
|
|
function loadDotEnvLocal(): void {
|
|
const path = join(process.cwd(), ".env.local");
|
|
if (!existsSync(path)) return;
|
|
const raw = readFileSync(path, "utf-8");
|
|
for (const line of raw.split("\n")) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
const eq = trimmed.indexOf("=");
|
|
if (eq <= 0) continue;
|
|
const key = trimmed.slice(0, eq).trim();
|
|
let value = trimmed.slice(eq + 1).trim();
|
|
// Strip simple surrounding quotes.
|
|
if (
|
|
(value.startsWith('"') && value.endsWith('"')) ||
|
|
(value.startsWith("'") && value.endsWith("'"))
|
|
) {
|
|
value = value.slice(1, -1);
|
|
}
|
|
if (!process.env[key]) process.env[key] = value;
|
|
}
|
|
}
|
|
|
|
function slugFromUrl(url: string): string {
|
|
try {
|
|
const u = new URL(url);
|
|
const path = u.pathname.replace(/^\/+|\/+$/g, "").replace(/[^a-zA-Z0-9-]+/g, "-");
|
|
const host = u.hostname.replace(/^www\./, "");
|
|
const date = new Date().toISOString().slice(0, 10);
|
|
return `${date}-${host}-${path || "root"}`.slice(0, 100).toLowerCase();
|
|
} catch {
|
|
return new Date().toISOString().slice(0, 10) + "-analysis";
|
|
}
|
|
}
|
|
|
|
function renderMarkdown(url: string, result: AnalysisResult): string {
|
|
const a = result.analysis;
|
|
const lines: string[] = [];
|
|
const meta = [a.author, a.publication, a.publication_date].filter(Boolean).join(" · ");
|
|
lines.push(`# ${a.title}`);
|
|
lines.push("");
|
|
if (meta) lines.push(`*${meta} · ${a.language}*`);
|
|
lines.push("");
|
|
lines.push(`**Source:** ${url}`);
|
|
lines.push("");
|
|
lines.push("## Summary");
|
|
lines.push("");
|
|
lines.push(a.summary);
|
|
lines.push("");
|
|
lines.push("## Core claims");
|
|
lines.push("");
|
|
for (const c of a.core_claims) {
|
|
const flags = `${c.type} · ${c.evidence_quality}${c.supported_in_article ? " · supported" : " · unsupported"}`;
|
|
lines.push(`- **${c.claim}**`);
|
|
lines.push(` — *${flags}*`);
|
|
}
|
|
lines.push("");
|
|
lines.push("## First-principles critique");
|
|
lines.push("");
|
|
lines.push(a.first_principles_critique);
|
|
lines.push("");
|
|
if (a.named_sources.length > 0) {
|
|
lines.push("## Named sources");
|
|
lines.push("");
|
|
for (const s of a.named_sources) {
|
|
lines.push(`- **${s.name}** — ${s.role}`);
|
|
if (s.attributed_claim) lines.push(` ↳ ${s.attributed_claim}`);
|
|
}
|
|
lines.push("");
|
|
}
|
|
lines.push("## Biases to consider");
|
|
lines.push("");
|
|
lines.push(a.biases_to_consider);
|
|
lines.push("");
|
|
lines.push("## What would change this assessment");
|
|
lines.push("");
|
|
lines.push(a.what_would_change_assessment);
|
|
lines.push("");
|
|
lines.push("---");
|
|
lines.push("");
|
|
const truncNote = result.truncated ? " (truncated — article was longer)" : "";
|
|
lines.push(
|
|
`*Generated by truthseeker · ${result.fetched.textLength.toLocaleString()} chars examined${truncNote} · ${result.durationMs}ms*`,
|
|
);
|
|
return lines.join("\n");
|
|
}
|
|
|
|
// Two modes:
|
|
// 1. URL only: npm run analyze -- "https://..."
|
|
// 2. Pre-fetched text: npm run analyze -- "https://..." --text path/to/article.txt
|
|
//
|
|
// Mode 2 is the escape hatch for bot-gated sites (Republik, paywalls, etc.) —
|
|
// retrieve the body in a logged-in browser, save it to a file, pass it in.
|
|
// The URL still rides along so the resulting analysis attributes the source
|
|
// correctly.
|
|
function parseArgs(argv: string[]): { url: string; textFile?: string } {
|
|
const args = argv.slice(2);
|
|
let url: string | undefined;
|
|
let textFile: string | undefined;
|
|
for (let i = 0; i < args.length; i++) {
|
|
const a = args[i];
|
|
if (a === "--text" || a === "-t") {
|
|
textFile = args[++i];
|
|
} else if (!url && !a.startsWith("-")) {
|
|
url = a;
|
|
}
|
|
}
|
|
if (!url) {
|
|
console.error("Usage:");
|
|
console.error(" npm run analyze -- <url> (fetches the URL directly)");
|
|
console.error(" npm run analyze -- <url> --text <file.txt> (uses pre-fetched body)");
|
|
process.exit(1);
|
|
}
|
|
return { url, textFile };
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
loadDotEnvLocal();
|
|
|
|
const { url, textFile } = parseArgs(process.argv);
|
|
|
|
// Fail before the fetch, not after: an article download is ~20s of waiting
|
|
// that cannot produce anything without a vendor behind it. WHICH keys count
|
|
// is lib/llm's answer, not this script's — a second copy of that list here is
|
|
// what made an OpenRouter-only environment, which the HTTP route serves
|
|
// happily, exit 1 at this line.
|
|
if (configuredLinks().length === 0) {
|
|
console.error(`Error: ${noProviderMessage()}. Add one to .env.local or your environment.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const start = Date.now();
|
|
let result: AnalysisResult;
|
|
if (textFile) {
|
|
console.log(`Analyzing pre-fetched text from: ${textFile}`);
|
|
console.log(`Source URL (for attribution): ${url}`);
|
|
if (!existsSync(textFile)) {
|
|
console.error(`Error: text file not found at ${textFile}`);
|
|
process.exit(1);
|
|
}
|
|
const text = readFileSync(textFile, "utf-8");
|
|
result = await analyzeText({ url, title: null, text });
|
|
} else {
|
|
console.log(`Fetching + analyzing: ${url}`);
|
|
result = await analyzeUrl(url);
|
|
}
|
|
console.log(`Done in ${result.durationMs}ms (wall: ${Date.now() - start}ms)`);
|
|
|
|
const outDir = join(process.cwd(), "analyses");
|
|
if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true });
|
|
const outPath = join(outDir, `${slugFromUrl(url)}.md`);
|
|
writeFileSync(outPath, renderMarkdown(url, result), "utf-8");
|
|
console.log(`Wrote ${outPath}`);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e instanceof Error ? e.message : e);
|
|
process.exit(1);
|
|
});
|