diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d59e603 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,62 @@ +# Agent rules for the `linker` repo (reddit → spotify/bandcamp) + +A Firefox extension + a tiny Node resolver that turn artist/band names in reddit +comments into Spotify/Bandcamp links. This file is the repo-local doctrine; the work +is tracked in the **towl** work-item store under project **`reddit-spotify-linker`**. + +## Stack & layout + +- `service/` — zero-dependency Node resolver (Node 18+, built-in `fetch`/`http`). + `resolver.js` = the HTTP server; `lib.js` = pure, side-effect-free logic (the + artist-match precision lever) so it's unit-testable; `lib.test.js` = `node:test`. +- `extension/` — Firefox **MV2** content script (`content.js` + `manifest.json` + + `styles.css`). No build step. +- `scripts/check.sh` — the local check gate. + +## How work lands (IMPORTANT — this is NOT the towl repo) + +`linker` is hosted at **git.yapplesauce.com/paul/linker**, a **plain repo**: there is +**no PR pipeline and no branch protection**. You **push to `main` directly** (via the +user's PAT). Do **not** use `towl-orchestrate` / worktree+PR here. + +1. Make a small, reversible change. +2. Run the gate: `bash scripts/check.sh` (must print `ALL CHECKS PASSED`). +3. Commit citing the towl ref (e.g. `(task/odesli-direct-links)`), push `main`. +4. Stamp the SHA on the towl item: `stamp_commit { ref, sha, repo: "linker" }`. +5. Close the towl item. + +**NEVER touch the `towl` or `stickball` repos from work scoped to this project.** + +## Testing (zero-dep) + +`node --test` over `service/*.test.js` exercises `lib.js` (norm + the exact-name match ++ link builders). Keep pure logic in `lib.js` (not `resolver.js`, which has the +server side effect) so it stays testable without opening a port. **Add/extend a test +with every logic change.** The extension's in-browser behavior is **not** headlessly +testable in this environment — validate `content.js` with `node --check` and a +documented manual check on a real reddit thread (`about:debugging` → load temporary +add-on). + +## Code stewards (towl plans under objective/linker-stewardship) + +Standing, language-appropriate stewards (adapted from towl's SCOUT→FILE doctrine; run +them like any other steward — e.g. via a `/loop`). Each files findings into towl and +fixes small things directly. + +- **quality** (`plan/steward-linker-quality`) — correctness + regressions; **owns and + maintains `scripts/check.sh` and the `node:test` suite**. +- **design** (`plan/steward-linker-design`) — detection precision/recall, the + injected-link UX, README accuracy, reddit-DOM drift. +- **security** (`plan/steward-linker-security`) — DOM injection (build nodes via + `createElement`/`textContent`, **never `innerHTML`**; http(s) hrefs only), minimal + extension permissions, bounded external API calls (no SSRF), secrets never + logged/committed (`.env` is gitignored). + +## Standing decisions + +- Firefox **MV2** stays — Mozilla has no deprecation timeline; do not migrate to MV3 + speculatively. +- **No ML/NER** in the resolver — keep it zero-dep; improve detection with cheap + heuristics + the API exact-match filter. +- Detection precision lever: a candidate links **only** when a music API returns an + artist whose name matches it case-insensitively. diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..021b675 --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Local check gate for the linker (owned by the quality steward — plan/steward-linker-quality). +# Zero-dep: only `node` is required. Run before every push. +set -euo pipefail +cd "$(dirname "$0")/.." + +echo "== node --check (syntax) ==" +for f in $(find service extension -name '*.js'); do + node --check "$f" + echo " ok $f" +done + +echo "== JSON validity ==" +node -e "JSON.parse(require('fs').readFileSync('extension/manifest.json','utf8')); JSON.parse(require('fs').readFileSync('service/package.json','utf8'))" +echo " ok extension/manifest.json + service/package.json" + +echo "== node --test (unit) ==" +( cd service && node --test ) + +echo "ALL CHECKS PASSED" diff --git a/service/lib.js b/service/lib.js new file mode 100644 index 0000000..c8c9fc6 --- /dev/null +++ b/service/lib.js @@ -0,0 +1,34 @@ +// Pure, side-effect-free helpers for the resolver. Kept separate from resolver.js +// (which has the HTTP-server side effect) so they can be unit-tested with `node --test` +// without starting a server. The artist-match precision lever lives here. + +export const norm = (s) => String(s).normalize("NFKC").trim().toLowerCase(); + +export const bandcampSearch = (n) => `https://bandcamp.com/search?q=${encodeURIComponent(n)}&item_type=b`; +export const spotifySearch = (n) => `https://open.spotify.com/search/${encodeURIComponent(n)}`; + +// The precision lever: return the result whose name matches the candidate +// case-insensitively, else null. `minScore` (MusicBrainz) additionally requires a +// confidence score. Tolerates null/garbage items. +export function pickArtist(name, items, { minScore = null } = {}) { + const want = norm(name); + return ( + (items ?? []).find( + (a) => a && norm(a.name) === want && (minScore == null || (a.score ?? 0) >= minScore), + ) ?? null + ); +} + +// Link object for a confirmed Spotify hit (direct artist url when present, else search). +export const spotifyResult = (hit) => ({ + name: hit.name, + spotify: hit.external_urls?.spotify ?? spotifySearch(hit.name), + bandcamp: bandcampSearch(hit.name), +}); + +// Link object for a confirmed MusicBrainz hit (search urls — MB gives no platform ids). +export const searchResult = (hit) => ({ + name: hit.name, + spotify: spotifySearch(hit.name), + bandcamp: bandcampSearch(hit.name), +}); diff --git a/service/lib.test.js b/service/lib.test.js new file mode 100644 index 0000000..cbad08d --- /dev/null +++ b/service/lib.test.js @@ -0,0 +1,51 @@ +// Unit tests for the resolver's pure logic (run with `node --test`). Zero-dep. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { norm, bandcampSearch, spotifySearch, pickArtist, spotifyResult, searchResult } from "./lib.js"; + +test("norm lowercases, trims, NFKC-normalizes", () => { + assert.equal(norm(" Cerebral Bore "), "cerebral bore"); + assert.equal(norm("DEVOURMENT"), "devourment"); +}); + +test("pickArtist matches case-insensitively, rejects non-matches", () => { + const items = [{ name: "Cattle Decapitation" }, { name: "Cerebral Bore" }]; + assert.equal(pickArtist("cerebral bore", items)?.name, "Cerebral Bore"); + assert.equal(pickArtist("CATTLE DECAPITATION", items)?.name, "Cattle Decapitation"); + assert.equal(pickArtist("Notarealband", items), null); +}); + +test("pickArtist enforces minScore when given (MusicBrainz path)", () => { + const items = [{ name: "Devourment", score: 100 }, { name: "Devourment", score: 50 }]; + assert.equal(pickArtist("Devourment", items, { minScore: 90 })?.score, 100); + assert.equal(pickArtist("Devourment", [{ name: "Devourment", score: 50 }], { minScore: 90 }), null); +}); + +test("pickArtist tolerates empty / garbage input", () => { + assert.equal(pickArtist("x", null), null); + assert.equal(pickArtist("x", []), null); + assert.equal(pickArtist("x", [null, { name: "y" }]), null); +}); + +test("spotifyResult prefers the direct url, falls back to search", () => { + const direct = spotifyResult({ + name: "Devourment", + external_urls: { spotify: "https://open.spotify.com/artist/abc" }, + }); + assert.equal(direct.spotify, "https://open.spotify.com/artist/abc"); + assert.match(direct.bandcamp, /^https:\/\/bandcamp\.com\/search\?q=Devourment/); + + const noUrl = spotifyResult({ name: "Devourment" }); + assert.equal(noUrl.spotify, "https://open.spotify.com/search/Devourment"); +}); + +test("searchResult builds spotify + bandcamp search urls", () => { + const r = searchResult({ name: "Cerebral Bore" }); + assert.equal(r.spotify, "https://open.spotify.com/search/Cerebral%20Bore"); + assert.equal(r.bandcamp, "https://bandcamp.com/search?q=Cerebral%20Bore&item_type=b"); +}); + +test("link builders url-encode", () => { + assert.equal(spotifySearch("A B"), "https://open.spotify.com/search/A%20B"); + assert.ok(bandcampSearch("A&B").includes("A%26B")); +}); diff --git a/service/package.json b/service/package.json index 8e4f73c..463da09 100644 --- a/service/package.json +++ b/service/package.json @@ -6,6 +6,7 @@ "description": "Tiny resolver service: candidate names -> confirmed-artist links (Spotify/Bandcamp).", "engines": { "node": ">=18" }, "scripts": { - "start": "node resolver.js" + "start": "node resolver.js", + "test": "node --test" } } diff --git a/service/resolver.js b/service/resolver.js index 1f937cc..c928ede 100644 --- a/service/resolver.js +++ b/service/resolver.js @@ -6,10 +6,11 @@ // DIRECT artist links; // * without creds -> MusicBrainz validation + Spotify/Bandcamp SEARCH links (zero setup). // Either way a candidate only resolves when an artist's name matches it case-insensitively -// (the precision lever that keeps random capitalized words from being linked). +// (the precision lever). The pure matching/link logic lives in lib.js (unit-tested). import { createServer } from "node:http"; import { readFileSync } from "node:fs"; +import { norm, pickArtist, spotifyResult, searchResult } from "./lib.js"; // --- minimal .env loader (no dependency) ------------------------------------ try { @@ -27,10 +28,6 @@ const USE_SPOTIFY = Boolean(SPOTIFY_ID && SPOTIFY_SECRET); const UA = "reddit-spotify-linker/0.1 (https://git.yapplesauce.com/paul/linker)"; const MAX_CANDIDATES = 100; -const norm = (s) => String(s).normalize("NFKC").trim().toLowerCase(); -const bandcampSearch = (n) => `https://bandcamp.com/search?q=${encodeURIComponent(n)}&item_type=b`; -const spotifySearch = (n) => `https://open.spotify.com/search/${encodeURIComponent(n)}`; - const cache = new Map(); // norm(name) -> { spotify, bandcamp, name } | null (negatives cached too) // --- Spotify (optional) ----------------------------------------------------- @@ -57,13 +54,8 @@ async function viaSpotify(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(); - const hit = (j.artists?.items ?? []).find((a) => norm(a.name) === norm(name)); - if (!hit) return null; - return { - name: hit.name, - spotify: hit.external_urls?.spotify ?? spotifySearch(hit.name), - bandcamp: bandcampSearch(hit.name), - }; + const hit = pickArtist(name, j.artists?.items); + return hit ? spotifyResult(hit) : null; } // --- MusicBrainz (zero-cred fallback) --------------------------------------- @@ -87,9 +79,8 @@ async function viaMusicBrainz(name) { const r = await fetch(url, { headers: { "user-agent": UA, accept: "application/json" } }); if (!r.ok) throw new Error(`musicbrainz http ${r.status}`); const j = await r.json(); - const hit = (j.artists ?? []).find((a) => norm(a.name) === norm(name) && (a.score ?? 0) >= 90); - if (!hit) return null; - return { name: hit.name, spotify: spotifySearch(hit.name), bandcamp: bandcampSearch(hit.name) }; + const hit = pickArtist(name, j.artists, { minScore: 90 }); + return hit ? searchResult(hit) : null; } // --- resolve one candidate (cached) -----------------------------------------