Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(news): stop story permalinks from going dead

fudjiaed0168d42549
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6fc3a06a7..2ff87d0ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **AI features can no longer go down when one provider does** — Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes. (`/changelog`) `[improvement, fix, infra]`
- **Closed a path-traversal hole in the API router** — The server that routes every /api request to its handler split the URL into path segments before decoding them, so a specially encoded request could smuggle a '../' into a single segment and reach a file outside the API folder — or an internal helper meant to be unreachable — and run it without authentication. The router now rejects any decoded segment that contains a path separator and, as a second line of defense, refuses to load any handler that resolves outside the API directory. Normal routes are unaffected; a regression test locks the fix in place. `[security]`
- **New driving jobs in /play — Cross-Town Delivery and East-West Express** — Two real driving missions landed on the /play jobs board. Grab a car parked at any of the four avenue depots, run the rush order to the depot on the other side of town, and get paid — the delivery only counts if you actually drove it, not walked it. Pairs with the world's existing drivable vehicles and cash economy for a real 'drive around, do jobs, spend the cash' loop. (`/play`) `[feature]`
+- **News story links no longer go dead** — Every article on the news feed gets a permanent link, but stories published near a month boundary could slip through the hourly archiver and their links would eventually 404. The archiver now files each story under its real publication month (and no longer caps how many articles it sweeps per run), story pages look in neighboring months and redirect to the right address when a link's month is off by one, and a link that truly can't be found now offers a one-click archive search for that story's title instead of a dead end. (`/markets/news`) `[fix, improvement]`
- **Oversized x402 payment headers fixed** — Three paid endpoints (vanity, pump launch, agent reputation) mirrored their entire payment challenge — schemas, signed offers and all — into a single HTTP header that grew past 16 KB, the point where proxies and many clients drop or fail to parse the response. The header mirror is now capped at 8 KB: it slims down or steps aside when the challenge is large, while the response body always carries the complete challenge. Payment tooling that reads only headers still gets everything it needs to pay. `[fix]`
- **Seeker wallet signing fixed before it ever shipped** — Automated testing of the Solana Seeker app in an Android emulator against Solana Mobile's reference wallet caught four bugs in our Mobile Wallet Adapter integration: the app icon was sent in a format the wallet spec rejects, and message signing, transaction signing, and send-transaction all read the wallet's response in the wrong shape. All four are fixed — wallet connect was verified end to end, returning a real public key through the on-device signing flow. `[fix, security]`
- **The autonomous coin launcher learned taste** — The Memetic Launcher's picks got a full quality overhaul. Its cultural radar was half-blind — the pump.fun intel feed was silenced by a miscalibrated quality bar and generic sector words like 'meme' drowned out actual memes — so most picks fell back to random word-salad names. Now the radar reads live meme culture properly (Know Your Meme, Google Trends, Hacker News, Wikipedia attention, and pump.fun's own breakout data), each launch rides a specific rising narrative, the launcher remembers its recent picks so it never re-mints the same joke, coin descriptions are no longer cut off mid-sentence, and a quality gate refuses to spend real SOL on a filler pick when no genuine signal exists. Launch previews in the user launcher now refresh hourly instead of every minute. (`/launcher`) `[improvement, fix]`
diff --git a/api/_lib/news-story.js b/api/_lib/news-story.js
index a2d33f09e..12c5c08e2 100644
--- a/api/_lib/news-story.js
+++ b/api/_lib/news-story.js
@@ -22,24 +22,42 @@ function recentMonths() {
return [cur, now.toISOString().slice(0, 7)];
}
+function adjacentMonths(month) {
+ const d = new Date(`${month}-01T00:00:00Z`);
+ const shift = (n) => {
+ const c = new Date(d);
+ c.setUTCMonth(c.getUTCMonth() + n);
+ return c.toISOString().slice(0, 7);
+ };
+ return [shift(-1), shift(1)];
+}
+
/**
* @returns {Promise<{article: object, origin: 'live'|'archive'} | null>}
* The live record wins for recent months (it carries image/author and, for
* some publishers, the feed's full body); everything older comes from the
- * archive month file. A live hit is cross-checked against the requested month
- * so a stale URL can't serve a different month's story.
+ * archive month file. Ids are content-addressed (sha of the publisher link),
+ * so a hit is always the right story — but its month can drift by one when a
+ * publisher revises pub_date across a boundary or a link was minted from a
+ * differently-parsed date. The adjacent-month fallback recovers those; the
+ * story-page handler 301s to the canonical path when the months differ.
*/
export async function resolveStory(month, id) {
if (!validStoryKey(month, id)) return null;
if (recentMonths().includes(month)) {
const live = await findArticle({ id }).catch(() => null);
- if (live && (live.pub_date || '').slice(0, 7) === month) {
- return { article: live, origin: 'live' };
- }
+ if (live) return { article: live, origin: 'live' };
}
const records = await loadMonth(month).catch(() => null);
const archived = records?.find((a) => a.id === id) || null;
- return archived ? { article: archived, origin: 'archive' } : null;
+ if (archived) return { article: archived, origin: 'archive' };
+
+ for (const near of adjacentMonths(month)) {
+ const nearRecords = await loadMonth(near).catch(() => null);
+ const hit = nearRecords?.find((a) => a.id === id) || null;
+ if (hit) return { article: hit, origin: 'archive' };
+ }
+ return null;
}
diff --git a/api/cron/news-archive-append.js b/api/cron/news-archive-append.js
index e644f9c65..f657a8c71 100644
--- a/api/cron/news-archive-append.js
+++ b/api/cron/news-archive-append.js
@@ -148,6 +148,12 @@ async function currentMarketContext() {
// ─────────────────────────────────────────────────────────────────────────────
+function previousMonth(month) {
+ const d = new Date(`${month}-01T00:00:00Z`);
+ d.setUTCMonth(d.getUTCMonth() - 1);
+ return d.toISOString().slice(0, 7);
+}
+
export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
@@ -161,46 +167,74 @@ export default wrapCron(async (req, res) => {
if (!dryRun) token = await getGcpAccessToken();
// Live sweep across every source — the aggregator serves from its
- // per-source cache, so this is one bounded fan-out at most.
- const live = await getNews({ limit: 2000 });
+ // per-source cache, so this is one bounded fan-out at most. The limit must
+ // exceed the whole live corpus (~3k across 159 sources): anything the slice
+ // drops here is silently never archived, and its permalink dies when the
+ // story rotates out of the feed.
+ const live = await getNews({ limit: 10_000 });
if (!live.articles.length) {
return json(res, 200, { ok: true, month, appended: 0, note: 'aggregator returned no articles' });
}
- const objectName = `articles/${month}.jsonl`;
- const existing = dryRun
- ? { exists: false, generation: '0', text: '' }
- : await gcsGetObject(token, objectName);
- const seen = new Set();
- for (const line of existing.text.split('\n')) {
- if (!line.trim()) continue;
- try {
- seen.add(JSON.parse(line).id);
- } catch {
- // malformed line — leave it in place, it just can't dedupe
+ // Bucket each article into ITS publication month — the same month its
+ // permalink (/markets/news/<YYYY-MM>/<id>) points at. Archiving a late-June
+ // story into the July file would strand its canonical URL forever. One
+ // month of grace covers boundary stragglers; anything older is feed
+ // backlog that stays out so it can't pollute the historical corpus.
+ const grace = previousMonth(month);
+ const buckets = new Map(); // YYYY-MM → articles
+ let skippedBacklog = 0;
+ for (const a of live.articles) {
+ const m = a.pub_date ? a.pub_date.slice(0, 7) : month;
+ if (m !== month && m !== grace) {
+ skippedBacklog++;
+ continue;
}
+ if (!buckets.has(m)) buckets.set(m, []);
+ buckets.get(m).push(a);
}
- // Only archive articles actually published (or first seen) this month, so
- // a long-lived feed backlog doesn't leak into the wrong month file.
- const fresh = live.articles.filter(
- (a) => !seen.has(a.id) && (!a.pub_date || a.pub_date.slice(0, 7) === month),
- );
- if (!fresh.length) {
+ // Per-month dedupe against the existing archive object.
+ const months = {}; // YYYY-MM → { existing, fresh }
+ let alreadyArchived = 0;
+ for (const [m, articles] of buckets) {
+ const existing = dryRun
+ ? { exists: false, generation: '0', text: '' }
+ : await gcsGetObject(token, `articles/${m}.jsonl`);
+ const seen = new Set();
+ for (const line of existing.text.split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ seen.add(JSON.parse(line).id);
+ } catch {
+ // malformed line — leave it in place, it just can't dedupe
+ }
+ }
+ alreadyArchived += seen.size;
+ months[m] = { existing, fresh: articles.filter((a) => !seen.has(a.id)) };
+ }
+
+ const allFresh = Object.values(months).flatMap((x) => x.fresh);
+ if (!allFresh.length) {
return json(res, 200, {
ok: true, month, appended: 0, live_considered: live.articles.length,
- already_archived: seen.size, dry_run: dryRun,
+ already_archived: alreadyArchived, skipped_backlog: skippedBacklog, dry_run: dryRun,
});
}
const marketContext = await currentMarketContext();
- const lines = fresh.map((a) => JSON.stringify(toArchiveRecord(a, marketContext, nowIso)));
+ const appendedByMonth = {};
if (!dryRun) {
- const body = existing.text
- ? `${existing.text.replace(/\n$/, '')}\n${lines.join('\n')}\n`
- : `${lines.join('\n')}\n`;
- await gcsPutObject(token, objectName, body, existing.generation, 'application/x-ndjson');
+ for (const [m, { existing, fresh }] of Object.entries(months)) {
+ if (!fresh.length) continue;
+ const lines = fresh.map((a) => JSON.stringify(toArchiveRecord(a, marketContext, nowIso)));
+ const body = existing.text
+ ? `${existing.text.replace(/\n$/, '')}\n${lines.join('\n')}\n`
+ : `${lines.join('\n')}\n`;
+ await gcsPutObject(token, `articles/${m}.jsonl`, body, existing.generation, 'application/x-ndjson');
+ appendedByMonth[m] = fresh.length;
+ }
// Keep corpus stats truthful for /markets/archive and the API's
// stats mode. Best-effort: a stats race loses to next hour's run.
@@ -208,15 +242,15 @@ export default wrapCron(async (req, res) => {
const stats = await gcsGetObject(token, 'meta/stats.json');
if (stats.exists) {
const parsed = JSON.parse(stats.text);
- parsed.total_articles += fresh.length;
- parsed.total_with_url += fresh.length;
- parsed.total_with_date += fresh.filter((a) => a.pub_date).length;
- parsed.total_with_description += fresh.filter((a) => a.description).length;
- const newest = fresh.map((a) => a.pub_date).filter(Boolean).sort().pop();
+ parsed.total_articles += allFresh.length;
+ parsed.total_with_url += allFresh.length;
+ parsed.total_with_date += allFresh.filter((a) => a.pub_date).length;
+ parsed.total_with_description += allFresh.filter((a) => a.description).length;
+ const newest = allFresh.map((a) => a.pub_date).filter(Boolean).sort().pop();
if (newest && (!parsed.last_article_date || newest > parsed.last_article_date)) {
parsed.last_article_date = newest;
}
- for (const a of fresh) {
+ for (const a of allFresh) {
parsed.sources[a.source_key] = (parsed.sources[a.source_key] || 0) + 1;
}
await gcsPutObject(token, 'meta/stats.json', JSON.stringify(parsed, null, 2), stats.generation, 'application/json');
@@ -224,14 +258,20 @@ export default wrapCron(async (req, res) => {
} catch (err) {
if (err?.code !== 'race') console.error('news-archive-append: stats update skipped:', err.message);
}
+ } else {
+ for (const [m, { fresh }] of Object.entries(months)) {
+ if (fresh.length) appendedByMonth[m] = fresh.length;
+ }
}
return json(res, 200, {
ok: true,
month,
- appended: fresh.length,
+ appended: allFresh.length,
+ appended_by_month: appendedByMonth,
live_considered: live.articles.length,
- already_archived: seen.size,
+ already_archived: alreadyArchived,
+ skipped_backlog: skippedBacklog,
sources_live: `${live.sources_ok}/${live.sources_total}`,
market_context: marketContext ? 'captured' : 'unavailable',
dry_run: dryRun,
diff --git a/api/news/story-page.js b/api/news/story-page.js
index 4e46e50cb..5f39850e2 100644
--- a/api/news/story-page.js
+++ b/api/news/story-page.js
@@ -205,13 +205,17 @@ export function renderStoryHtml(shell, a) {
return html;
}
-function notFoundHtml(shell, month) {
+function notFoundHtml(shell, month, slug) {
+ // The slug in the URL is the story's own title words — turn the dead link
+ // into a ready-made archive search instead of a dead end.
+ const q = String(slug || '').replace(/-/g, ' ').trim();
+ const searchHref = q ? `/markets/archive?q=${encodeURIComponent(q)}` : '/markets/archive';
const body = `
<h1 class="art-title">Story not found</h1>
<div class="cv-empty">
<p><strong>This article isn’t in the ${esc(month || '')} archive.</strong></p>
<p>It may have been published in a different month, or the link is incomplete.</p>
- <p><a class="arc-btn" href="/markets/archive">Search the 660k-article archive</a>
+ <p><a class="arc-btn" href="${esc(searchHref)}">${q ? `Search the archive for “${esc(q)}”` : 'Search the 660k-article archive'}</a>
<a class="arc-btn ghost" href="/markets/news">Latest crypto news</a></p>
</div>`;
return shell
@@ -253,8 +257,18 @@ export default wrap(async (req, res) => {
// A resolvable story always has a canonical path; a dated-but-unlinkable
// record (no id/date after compaction) can't reach here because the route
// carries both. Missing → an honest 404, cached briefly.
- const status = resolved && storyPath(resolved.article) ? 200 : 404;
- const html = status === 200 ? renderStoryHtml(shell, resolved.article) : notFoundHtml(shell, month);
+ const canonical = resolved ? storyPath(resolved.article) : null;
+ if (canonical && !canonical.startsWith(`/markets/news/${month}/`)) {
+ // The story exists but lives in a different month (boundary drift or a
+ // revised pub_date) — send crawlers and readers to the canonical URL.
+ res.statusCode = 301;
+ res.setHeader('location', canonical);
+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=3600');
+ res.end();
+ return;
+ }
+ const status = canonical ? 200 : 404;
+ const html = status === 200 ? renderStoryHtml(shell, resolved.article) : notFoundHtml(shell, month, params.get('slug') || req.query?.slug || '');
_pages.set(key, { html, status, expiresAt: Date.now() + (status === 200 ? CACHE_TTL_MS : 60_000) });
if (_pages.size > CACHE_MAX) _pages.delete(_pages.keys().next().value);
diff --git a/data/changelog.json b/data/changelog.json
index 0a6a98448..d9bfb51c6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-12",
+ "title": "News story links no longer go dead",
+ "summary": "Every article on the news feed gets a permanent link, but stories published near a month boundary could slip through the hourly archiver and their links would eventually 404. The archiver now files each story under its real publication month (and no longer caps how many articles it sweeps per run), story pages look in neighboring months and redirect to the right address when a link's month is off by one, and a link that truly can't be found now offers a one-click archive search for that story's title instead of a dead end.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/markets/news"
+ },
{
"date": "2026-07-12",
"title": "Closed a path-traversal hole in the API router",
diff --git a/public/changelog.json b/public/changelog.json
index 1ba9102d5..a262c0e40 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-12T08:57:33.006Z",
+ "generated_at": "2026-07-12T09:06:07.404Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -70,6 +70,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-12",
+ "type": "update",
+ "title": "News story links no longer go dead",
+ "summary": "Every article on the news feed gets a permanent link, but stories published near a month boundary could slip through the hourly archiver and their links would eventually 404. The archiver now files each story under its real publication month (and no longer caps how many articles it sweeps per run), story pages look in neighboring months and redirect to the right address when a link's month is off by one, and a link that truly can't be found now offers a one-click archive search for that story's title instead of a dead end.",
+ "link": "/markets/news",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-12",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c705447ba..68a8d0217 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -54,6 +54,14 @@
<category>feature</category>
<description>Two real driving missions landed on the /play jobs board. Grab a car parked at any of the four avenue depots, run the rush order to the depot on the other side of town, and get paid — the delivery only counts if you actually drove it, not walked it. Pairs with the world's existing drivable vehicles and cash economy for a real 'drive around, do jobs, spend the cash' loop.</description>
</item>
+ <item>
+ <title>News story links no longer go dead</title>
+ <link>https://three.ws/markets/news</link>
+ <guid isPermaLink="false">2026-07-12:News story links no longer go dead</guid>
+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Every article on the news feed gets a permanent link, but stories published near a month boundary could slip through the hourly archiver and their links would eventually 404. The archiver now files each story under its real publication month (and no longer caps how many articles it sweeps per run), story pages look in neighboring months and redirect to the right address when a link's month is off by one, and a link that truly can't be found now offers a one-click archive search for that story's title instead of a dead end.</description>
+ </item>
<item>
<title>Oversized x402 payment headers fixed</title>
<link>https://three.ws/changelog</link>
diff --git a/tests/news-archive-append.test.js b/tests/news-archive-append.test.js
index b47eb43fb..5f551c1e4 100644
--- a/tests/news-archive-append.test.js
+++ b/tests/news-archive-append.test.js
@@ -33,6 +33,11 @@ vi.mock('../api/_lib/coingecko.js', () => ({
}));
const NOW_MONTH = new Date().toISOString().slice(0, 7);
+const PREV_MONTH = (() => {
+ const d = new Date(`${NOW_MONTH}-01T00:00:00Z`);
+ d.setUTCMonth(d.getUTCMonth() - 1);
+ return d.toISOString().slice(0, 7);
+})();
const LIVE = [
{
id: 'aaaaaaaaaaaaaaaa', title: 'BTC rallies', link: 'https://x.com/a', description: 'Bitcoin gains 5%',
@@ -52,6 +57,12 @@ const LIVE = [
pub_date: '2020-01-01T10:00:00.000Z', tickers: [],
sentiment: { score: 0, label: 'neutral', confidence: 0.5 },
},
+ {
+ id: 'dddddddddddddddd', title: 'Late boundary story', link: 'https://x.com/d', description: 'Published just before the month rolled',
+ image: null, author: null, source: 'The Block', source_key: 'theblock', category: 'general',
+ pub_date: `${PREV_MONTH}-28T23:50:00.000Z`, tickers: [],
+ sentiment: { score: 0, label: 'neutral', confidence: 0.5 },
+ },
];
vi.mock('../api/_lib/news.js', () => ({
getNews: vi.fn(async () => ({ articles: LIVE, total: LIVE.length, sources_ok: 37, sources_total: 38 })),
@@ -118,15 +129,19 @@ describe('GET /api/cron/news-archive-append', () => {
const res = await call('/api/cron/news-archive-append?dry_run=1');
expect(res._json.status).toBe(200);
expect(res._json.body.dry_run).toBe(true);
- // dry run skips the existing-object read, so all in-month items count
- expect(res._json.body.appended).toBe(2);
+ // dry run skips the existing-object read, so all in-window items count
+ expect(res._json.body.appended).toBe(3);
+ expect(res._json.body.appended_by_month).toEqual({ [NOW_MONTH]: 2, [PREV_MONTH]: 1 });
+ expect(res._json.body.skipped_backlog).toBe(1);
expect(writes).toHaveLength(0);
});
- it('appends only new in-month articles, schema-complete, generation-guarded', async () => {
+ it('appends new articles into their own pub_date month, schema-complete, generation-guarded', async () => {
const res = await call('/api/cron/news-archive-append');
expect(res._json.status).toBe(200);
- expect(res._json.body.appended).toBe(1); // b deduped, c out-of-month
+ expect(res._json.body.appended).toBe(2); // b deduped, c out-of-window
+ expect(res._json.body.appended_by_month).toEqual({ [NOW_MONTH]: 1, [PREV_MONTH]: 1 });
+ expect(res._json.body.skipped_backlog).toBe(1);
const monthWrite = writes.find((w) => w.url.includes(`articles%2F${NOW_MONTH}.jsonl`));
expect(monthWrite).toBeTruthy();
expect(monthWrite.url).toContain('ifGenerationMatch=41');
@@ -146,14 +161,28 @@ describe('GET /api/cron/news-archive-append', () => {
expect(rec.meta.import_source).toBe('three.ws-live-archiver');
});
+ it('a boundary straggler lands in the PREVIOUS month file, not the current one', async () => {
+ await call('/api/cron/news-archive-append');
+ const graceWrite = writes.find((w) => w.url.includes(`articles%2F${PREV_MONTH}.jsonl`));
+ expect(graceWrite).toBeTruthy();
+ expect(graceWrite.url).toContain('ifGenerationMatch=0'); // fresh object
+ const lines = graceWrite.body.trim().split('\n');
+ expect(lines).toHaveLength(1);
+ expect(JSON.parse(lines[0]).id).toBe('dddddddddddddddd');
+ // and it must NOT leak into the current month file
+ const monthWrite = writes.find((w) => w.url.includes(`articles%2F${NOW_MONTH}.jsonl`));
+ expect(monthWrite.body).not.toContain('dddddddddddddddd');
+ });
+
it('updates corpus stats after an append', async () => {
await call('/api/cron/news-archive-append');
const statsWrite = writes.find((w) => w.url.includes('meta%2Fstats.json'));
expect(statsWrite).toBeTruthy();
expect(statsWrite.url).toContain('ifGenerationMatch=7');
const stats = JSON.parse(statsWrite.body);
- expect(stats.total_articles).toBe(662048);
+ expect(stats.total_articles).toBe(662049);
expect(stats.sources.coindesk).toBe(2109);
+ expect(stats.sources.theblock).toBe(1);
expect(stats.last_article_date).toBe(`${NOW_MONTH}-05T10:00:00.000Z`);
});
});
diff --git a/tests/news-story-page.test.js b/tests/news-story-page.test.js
new file mode 100644
index 000000000..85928fb8e
--- /dev/null
+++ b/tests/news-story-page.test.js
@@ -0,0 +1,118 @@
+// Coverage for the story permalink pipeline — api/_lib/news-story.js
+// (adjacent-month fallback) and api/news/story-page.js (canonical 301 when
+// the requested month differs from the article's real month, slug-powered
+// 404). Regression for the dead-permalink class of bug: a story whose month
+// drifted by one across a boundary must resolve, not 404.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../api/_lib/http.js', () => ({ wrap: (fn) => fn }));
+vi.mock('../api/_lib/env.js', () => ({ env: {} }));
+
+const ARTICLE = {
+ id: 'abcdefabcdefabcd',
+ title: 'Regulated crypto exchanges gain ground',
+ link: 'https://publisher.example/story',
+ description: 'Oversight tightens and regulated venues win share.',
+ source: 'The Block',
+ source_key: 'theblock',
+ category: 'general',
+ pub_date: '2025-03-30T23:50:00.000Z', // canonical month: 2025-03
+ tickers: ['BTC'],
+ sentiment: { score: 0.2, label: 'positive', confidence: 0.6 },
+};
+
+const findArticle = vi.fn(async () => null);
+const loadMonth = vi.fn(async () => []);
+vi.mock('../api/_lib/news.js', () => ({ findArticle: (...a) => findArticle(...a) }));
+vi.mock('../api/_lib/news-archive-store.js', () => ({ loadMonth: (...a) => loadMonth(...a) }));
+
+const { resolveStory } = await import('../api/_lib/news-story.js');
+const { default: handler } = await import('../api/news/story-page.js');
+
+function call(url) {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ this.body = chunk || '';
+ },
+ };
+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res);
+}
+
+beforeEach(() => {
+ findArticle.mockReset().mockResolvedValue(null);
+ loadMonth.mockReset().mockResolvedValue([]);
+});
+
+describe('resolveStory', () => {
+ it('finds an article in its exact archive month', async () => {
+ loadMonth.mockImplementation(async (m) => (m === '2025-03' ? [ARTICLE] : []));
+ const hit = await resolveStory('2025-03', ARTICLE.id);
+ expect(hit).toMatchObject({ origin: 'archive', article: { id: ARTICLE.id } });
+ });
+
+ it('falls back to an adjacent month when the requested one misses', async () => {
+ loadMonth.mockImplementation(async (m) => (m === '2025-03' ? [ARTICLE] : []));
+ const hit = await resolveStory('2025-02', ARTICLE.id);
+ expect(hit).toMatchObject({ origin: 'archive', article: { id: ARTICLE.id } });
+ const asked = loadMonth.mock.calls.map((c) => c[0]);
+ expect(asked).toContain('2025-02');
+ expect(asked).toContain('2025-03');
+ });
+
+ it('returns null when the story is nowhere', async () => {
+ expect(await resolveStory('2025-02', 'deadbeefdeadbeef')).toBeNull();
+ });
+
+ it('rejects malformed keys without any lookup', async () => {
+ expect(await resolveStory('2025-13', ARTICLE.id)).toBeNull();
+ expect(await resolveStory('2025-03', 'not-an-id')).toBeNull();
+ expect(loadMonth).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/news/story-page', () => {
+ it('serves the story at its canonical month', async () => {
+ loadMonth.mockImplementation(async (m) => (m === '2025-03' ? [ARTICLE] : []));
+ const res = await call(`/api/news/story-page?month=2025-03&id=${ARTICLE.id}`);
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toContain('Regulated crypto exchanges gain ground');
+ expect(res.body).toContain(`/markets/news/2025-03/${ARTICLE.id}`);
+ });
+
+ it('301s a month-drifted URL to the canonical permalink', async () => {
+ loadMonth.mockImplementation(async (m) => (m === '2025-03' ? [ARTICLE] : []));
+ const res = await call(`/api/news/story-page?month=2025-02&id=${ARTICLE.id}`);
+ expect(res.statusCode).toBe(301);
+ expect(res.headers.location).toMatch(new RegExp(`^/markets/news/2025-03/${ARTICLE.id}`));
+ });
+
+ it('301s when the live record’s month differs from the requested one', async () => {
+ const nowMonth = new Date().toISOString().slice(0, 7);
+ const prev = (() => {
+ const d = new Date(`${nowMonth}-01T00:00:00Z`);
+ d.setUTCMonth(d.getUTCMonth() - 1);
+ return d.toISOString().slice(0, 7);
+ })();
+ const liveArticle = { ...ARTICLE, pub_date: `${prev}-28T12:00:00.000Z` };
+ findArticle.mockResolvedValue(liveArticle);
+ const res = await call(`/api/news/story-page?month=${nowMonth}&id=${ARTICLE.id}`);
+ expect(res.statusCode).toBe(301);
+ expect(res.headers.location).toMatch(new RegExp(`^/markets/news/${prev}/${ARTICLE.id}`));
+ });
+
+ it('404 turns the URL slug into a prefilled archive search', async () => {
+ const res = await call(
+ '/api/news/story-page?month=2025-02&id=deadbeefdeadbeef&slug=regulated-crypto-exchanges-gain-ground',
+ );
+ expect(res.statusCode).toBe(404);
+ expect(res.body).toContain('/markets/archive?q=regulated%20crypto%20exchanges%20gain%20ground');
+ expect(res.body).toContain('Search the archive for');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 39fdf313b..aac23541e 100644
--- a/vercel.json
+++ b/vercel.json
@@ -957,8 +957,8 @@
"dest": "/news-article.html"
},
{
- "src": "/markets/news/(20[0-9]{2}-[0-9]{2})/([a-f0-9]{16})(?:-[a-zA-Z0-9-]{0,120})?/?",
- "dest": "/api/news/story-page?month=$1&id=$2"
+ "src": "/markets/news/(20[0-9]{2}-[0-9]{2})/([a-f0-9]{16})(?:-([a-zA-Z0-9-]{0,120}))?/?",
+ "dest": "/api/news/story-page?month=$1&id=$2&slug=$3"
},
{
"src": "/markets/archive/?",