Files
linker/service/resolver.js
T
paulandClaude Opus 4.8 8496e55baf refactor: extract testable resolve-core + cover album routing; check.sh checks .cjs (closes task/resolver-orchestration-testable)
Source: task/resolver-orchestration-testable (plan/steward-linker-quality) — new album orchestration in resolver.js had zero node:test coverage.

- Extract the pure album/artist orchestration into service/resolve-core.js
  (resolveAll/resolveOne/pickDirect/cacheKey) taking injected search/classify
  fns; resolver.js becomes a thin server wiring the real Spotify search +
  ollama classify. No behavior change.
- Add service/resolver.test.js: self-titled artist+album tie-break, LLM-album
  -> Google fallback, kind-aware cache separation, plus gate/drop/error paths.
- scripts/check.sh: node --check now also matches *.cjs (extract.test.cjs).
- AGENTS.md Testing: note resolve-core coverage + the extract.test.cjs extractor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 00:29:59 +00:00

153 lines
6.8 KiB
JavaScript

// Tiny resolver service: candidate names -> artist/album links, for CONFIRMED names only.
//
// Zero npm deps; Node 18+ (built-in fetch). The "which words are real artists/albums" problem
// is not guessed client-side — it is gated one of two ways:
// * SPOTIFY_CLIENT_ID/SECRET set -> a candidate resolves only when Spotify has an artist OR
// album whose name matches it case-insensitively (the exact-match precision lever), linking
// to the DIRECT Spotify artist/album page. One search call covers both types.
// * OLLAMA_URL set -> a local LLM (via ollama HTTP, still zero npm deps) classifies each
// candidate as artist/album/none; the kind routes the Spotify lookup, and confirmed names
// get a Spotify direct link when available, else a Google->Bandcamp search fallback. This
// is the better-matching path.
// The two combine: with both set, the LLM gates + routes the kind and Spotify supplies direct
// links. Each result carries kind:"artist"|"album". The pure matching/link/prompt logic lives
// in lib.js + llm.js (unit-tested).
import { createServer } from "node:http";
import { readFileSync } from "node:fs";
import { pickArtist, pickAlbum } from "./lib.js";
import { buildClassifyMessages, parseClassification, DEFAULT_MODEL } from "./llm.js";
import { resolveAll as resolveAllCore } from "./resolve-core.js";
// --- minimal .env loader (no dependency) ------------------------------------
try {
const env = readFileSync(new URL("./.env", import.meta.url), "utf8");
for (const line of env.split("\n")) {
const m = line.match(/^\s*([\w.-]+)\s*=\s*(.*?)\s*$/);
if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].replace(/^["']|["']$/g, "");
}
} catch { /* no .env -> use real env / defaults */ }
const PORT = Number(process.env.PORT) || 8787;
const SPOTIFY_ID = process.env.SPOTIFY_CLIENT_ID;
const SPOTIFY_SECRET = process.env.SPOTIFY_CLIENT_SECRET;
const USE_SPOTIFY = Boolean(SPOTIFY_ID && SPOTIFY_SECRET);
const OLLAMA_URL = (process.env.OLLAMA_URL || "").replace(/\/$/, ""); // presence enables the LLM gate
const OLLAMA_MODEL = process.env.OLLAMA_MODEL || DEFAULT_MODEL;
const USE_LLM = Boolean(OLLAMA_URL);
// Cache only the network half (the Spotify direct-url lookup); resolve-core rebuilds the final
// link object per request so a name's result never depends on a stale gate decision. The key
// includes the kind hint (see resolve-core's cacheKey).
const spCache = new Map();
// --- Spotify (optional): direct-artist-link lookup --------------------------
let spToken = null;
let spTokenExp = 0;
async function spotifyToken() {
if (spToken && Date.now() < spTokenExp) return spToken;
const auth = Buffer.from(`${SPOTIFY_ID}:${SPOTIFY_SECRET}`).toString("base64");
const r = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { authorization: `Basic ${auth}`, "content-type": "application/x-www-form-urlencoded" },
body: "grant_type=client_credentials",
});
if (!r.ok) throw new Error(`spotify token http ${r.status}`);
const j = await r.json();
spToken = j.access_token;
spTokenExp = Date.now() + (j.expires_in - 60) * 1000;
return spToken;
}
// The injected `search` for resolve-core: one type=artist,album Spotify search per candidate,
// returning the exact-name-match hits as { artist, album } where each is the external Spotify url
// (string) or null. No creds -> both null (nothing links). resolve-core's pickDirect applies the
// kindHint tie-break and shapes the link; the cache (spCache) is owned by resolve-core too.
async function search(name) {
if (!USE_SPOTIFY) return { artist: null, album: null };
const token = await spotifyToken();
const url = `https://api.spotify.com/v1/search?type=artist,album&limit=5&q=${encodeURIComponent(name)}`;
const r = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
if (!r.ok) throw new Error(`spotify search http ${r.status}`);
const j = await r.json();
return {
artist: pickArtist(name, j.artists?.items)?.external_urls?.spotify ?? null,
album: pickAlbum(name, j.albums?.items)?.external_urls?.spotify ?? null,
};
}
// --- LLM gate (optional): which candidates are artists/albums? --------------
async function ollamaClassify(candidates) {
const r = await fetch(`${OLLAMA_URL}/api/chat`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
model: OLLAMA_MODEL,
messages: buildClassifyMessages(candidates),
stream: false,
format: "json",
options: { temperature: 0 },
}),
});
if (!r.ok) throw new Error(`ollama http ${r.status}`);
const j = await r.json();
return parseClassification(j.message?.content ?? "", candidates);
}
// --- resolve --------------------------------------------------------------
// Run the pure orchestration (resolve-core) with the live clients injected: the Spotify `search`,
// the ollama `classify` gate (null when no LLM is configured -> the Spotify exact-match is the
// gate), and the shared spCache.
const resolveAll = (candidates) =>
resolveAllCore(candidates, { search, classify: USE_LLM ? ollamaClassify : null, cache: spCache });
// --- HTTP -------------------------------------------------------------------
function readBody(req) {
return new Promise((resolve, reject) => {
let data = "";
req.on("data", (c) => {
data += c;
if (data.length > 1e6) { reject(new Error("body too large")); req.destroy(); }
});
req.on("end", () => resolve(data));
req.on("error", reject);
});
}
const json = (res, code, obj) => {
res.writeHead(code, { "content-type": "application/json" });
res.end(JSON.stringify(obj));
};
const server = createServer(async (req, res) => {
res.setHeader("access-control-allow-origin", "*");
res.setHeader("access-control-allow-headers", "content-type");
res.setHeader("access-control-allow-methods", "GET, POST, OPTIONS");
if (req.method === "OPTIONS") { res.writeHead(204); return res.end(); }
if (req.method === "GET" && req.url === "/health") {
return json(res, 200, { ok: true, spotify: USE_SPOTIFY, llm: USE_LLM ? OLLAMA_MODEL : false, cached: spCache.size });
}
if (req.method === "POST" && req.url === "/resolve") {
try {
const { candidates } = JSON.parse((await readBody(req)) || "{}");
if (!Array.isArray(candidates)) return json(res, 400, { error: "candidates must be an array" });
return json(res, 200, await resolveAll(candidates));
} catch (e) {
return json(res, 500, { error: e.message });
}
}
json(res, 404, { error: "not found" });
});
server.listen(PORT, () => {
const sp = USE_SPOTIFY ? "on" : "off";
const llm = USE_LLM ? OLLAMA_MODEL : "off";
console.log(`resolver listening on http://localhost:${PORT} (spotify: ${sp}, llm: ${llm})`);
if (!USE_SPOTIFY && !USE_LLM) {
console.warn(" ! no gate configured: set SPOTIFY_CLIENT_ID/SECRET and/or OLLAMA_URL, or nothing will link.");
}
});