import assert from "node:assert/strict" import { describe, test } from "node:test" import { MemoryCache } from "../pipeline/cache.ts" import { defineReferenceTools, fetchReference, type ReferenceOptions, type ReferenceSite, siteFor, slugify, stripHtml, } from "./references.ts" import { findTool } from "./tools.ts" /** * The reference tools, with no network. * * Every case below passes a stub fetch, so this file opens no socket and can * run in continuous integration beside the rest. That is also why `fetchImpl` * exists: a rule that can only be checked against a live site is a rule nobody * checks. * * The nine rules on `fetchReference` are what this file exists for. Each one * stops a specific way a model-chosen address turns a rules assistant into * something else, and each one has a case here. */ const SITE: ReferenceSite = { name: "Example FAQ", host: "faq.example.com", describes: "Community rulings for a game.", official: false, cardPath: "/cards/{slug}", } /** A stub fetch that answers from a table, and records what was asked for. */ function stubFetch( routes: Record, ) { const asked: string[] = [] const impl = (async (url: string | URL, init?: RequestInit) => { const key = String(url) asked.push(key) const route = routes[key] if (!route) return new Response("not found", { status: 404 }) const headers = new Headers() if (route.type !== undefined) headers.set("content-type", route.type) else headers.set("content-type", "text/html; charset=utf-8") if (route.location) headers.set("location", route.location) // A redirect must reach the caller rather than being followed by the stub, // or this file would test the stub instead of the rule. void init return new Response( route.status && route.status >= 300 && route.status < 400 ? null : (route.body ?? ""), { status: route.status ?? 200, headers, }, ) }) as unknown as typeof fetch return { impl, asked } } const options = (over: Partial = {}): ReferenceOptions => ({ sites: [SITE], ...over, }) describe("choosing which site owns an address", () => { test("accepts the configured host", () => { assert.equal(siteFor(new URL("https://faq.example.com/cards/x"), [SITE])?.name, "Example FAQ") }) test("accepts a subdomain of it", () => { assert.equal(siteFor(new URL("https://www.faq.example.com/x"), [SITE])?.name, "Example FAQ") }) test("refuses a site list that would allow more than its author meant", () => { // `host: "com"` reads as "every address ending in .com", because a // subdomain of it is any host under it. Nobody writes that on purpose, and // nothing about it fails visibly at read time. assert.throws(() => defineReferenceTools({ sites: [{ ...SITE, host: "com" }] }), /names no single site/) assert.throws( () => defineReferenceTools({ sites: [{ ...SITE, host: "localhost" }] }), /names no single site/, ) assert.throws(() => defineReferenceTools({ sites: [{ ...SITE, host: " " }] }), /has no host/) }) test("refuses a host that holds a path, because the writer wanted scoping", () => { // Somebody who writes "faq.example.com/cards" wanted the read kept inside // /cards. The field cannot do that, and accepting it silently leaves them // believing a restriction that is not there. assert.throws( () => defineReferenceTools({ sites: [{ ...SITE, host: "faq.example.com/cards" }] }), /holds a path or a space/, ) assert.throws( () => defineReferenceTools({ sites: [{ ...SITE, host: "faq.example.com /x" }] }), /holds a path or a space/, ) }) test("still accepts a scheme, which changes nothing", () => { assert.equal( siteFor(new URL("https://faq.example.com/x"), [{ ...SITE, host: "https://faq.example.com" }])?.name, "Example FAQ", ) }) test("refuses a host that merely ends with the same letters", () => { // "evilfaq.example.com" ends with "faq.example.com" as a STRING and is a // different host. Matching on a bare suffix hands an attacker the allowlist. assert.equal(siteFor(new URL("https://evilfaq.example.com/x"), [SITE]), null) assert.equal(siteFor(new URL("https://faq.example.com.attacker.test/x"), [SITE]), null) }) }) describe("the fetch rules", () => { test("rule 1: refuses anything that is not https", async () => { for (const url of ["http://faq.example.com/x", "file:///etc/passwd", "ftp://faq.example.com/x"]) { await assert.rejects( fetchReference(url, options({ fetchImpl: stubFetch({}).impl })), /Only https/, `${url} must be refused`, ) } }) test("rule 2: refuses a host nobody configured, and names the ones allowed", async () => { await assert.rejects( fetchReference("https://somewhere.else.test/x", options({ fetchImpl: stubFetch({}).impl })), /not a reference site.*faq\.example\.com/s, ) }) test("rule 2: refuses an address inside this network", async () => { // The classic escape. An assistant that reads an internal address becomes a // way to read the network it runs in. await assert.rejects( fetchReference("https://169.254.169.254/latest/meta-data/", options({ fetchImpl: stubFetch({}).impl })), /not a reference site/, ) }) test("rule 3: refuses a path the operator listed as disallowed", async () => { // The package reads no robots.txt. A site that disallows /api/ needs the // prefix recorded here, or a model that builds such an address gets it // fetched, and the operator who accepted the site's terms cannot honour them. const site = { ...SITE, disallowPaths: ["/api/"] } await assert.rejects( fetchReference( "https://faq.example.com/api/cards", options({ sites: [site], fetchImpl: stubFetch({}).impl }), ), /does not allow a reader to fetch/, ) }) test("rule 3: a redirect into a disallowed path is refused too", async () => { const site = { ...SITE, disallowPaths: ["/api/"] } const { impl, asked } = stubFetch({ "https://faq.example.com/ok": { status: 302, location: "https://faq.example.com/api/cards" }, }) await assert.rejects( fetchReference("https://faq.example.com/ok", options({ sites: [site], fetchImpl: impl })), /does not allow a reader to fetch/, ) assert.deepEqual(asked, ["https://faq.example.com/ok"], "the disallowed address must never be requested") }) test("rule 3: a path the operator did not refuse still reads", async () => { const site = { ...SITE, disallowPaths: ["/api/"] } const { impl } = stubFetch({ "https://faq.example.com/cards/x": { body: "

Fine.

" } }) const page = await fetchReference( "https://faq.example.com/cards/x", options({ sites: [site], fetchImpl: impl }), ) assert.match(page.text, /Fine/) }) test("rule 4: follows one redirect that stays on the allowlist", async () => { const { impl, asked } = stubFetch({ "https://faq.example.com/old": { status: 301, location: "https://faq.example.com/new" }, "https://faq.example.com/new": { body: "New

Text here.

" }, }) const page = await fetchReference("https://faq.example.com/old", options({ fetchImpl: impl })) assert.equal(page.url, "https://faq.example.com/new") assert.match(page.text, /Text here/) assert.deepEqual(asked, ["https://faq.example.com/old", "https://faq.example.com/new"]) }) test("rule 4: refuses a redirect that leaves the allowlist", async () => { // A site this project does not control decides where its redirects point, // so following one blindly hands that site the allowlist. const { impl, asked } = stubFetch({ "https://faq.example.com/away": { status: 302, location: "https://169.254.169.254/latest/" }, }) await assert.rejects( fetchReference("https://faq.example.com/away", options({ fetchImpl: impl })), /not a reference site/, ) assert.deepEqual(asked, ["https://faq.example.com/away"], "the second address must never be requested") }) test("rule 4: refuses a chain of redirects", async () => { const { impl } = stubFetch({ "https://faq.example.com/a": { status: 302, location: "https://faq.example.com/b" }, "https://faq.example.com/b": { status: 302, location: "https://faq.example.com/c" }, "https://faq.example.com/c": { body: "

End.

" }, }) await assert.rejects( fetchReference("https://faq.example.com/a", options({ fetchImpl: impl })), /redirected more than once/, ) }) test("rules 4 and 5: sends no credentials, follows no redirect itself, and carries a deadline", async () => { let seen: RequestInit | undefined const impl = (async (_url: string | URL, init?: RequestInit) => { seen = init return new Response("

Hello.

", { headers: { "content-type": "text/html" } }) }) as unknown as typeof fetch await fetchReference("https://faq.example.com/x", options({ fetchImpl: impl })) assert.equal(seen?.credentials, "omit") assert.equal(seen?.redirect, "manual") assert.ok(seen?.signal, "a fetch with no deadline can hold a reader's question open forever") const headers = (seen?.headers ?? {}) as Record assert.match(headers["user-agent"] ?? "", /rulekit/) }) test("rule 8: cuts an oversized page and says it did", async () => { const huge = `

${"word ".repeat(20_000)}

` const { impl } = stubFetch({ "https://faq.example.com/big": { body: huge } }) const page = await fetchReference( "https://faq.example.com/big", options({ fetchImpl: impl, maxBytes: 500 }), ) assert.equal(page.truncated, true) assert.ok(page.text.length <= 500, `expected at most 500 characters, got ${page.text.length}`) }) test("rule 7: refuses a response that is not a readable page", async () => { const { impl } = stubFetch({ "https://faq.example.com/x.pdf": { type: "application/pdf", body: "%PDF-1.7" }, }) await assert.rejects( fetchReference("https://faq.example.com/x.pdf", options({ fetchImpl: impl })), /not a readable page/, ) }) test("reports a failing status rather than treating the error page as an answer", async () => { const { impl } = stubFetch({ "https://faq.example.com/gone": { status: 404, body: "

Nope

" } }) await assert.rejects(fetchReference("https://faq.example.com/gone", options({ fetchImpl: impl })), /404/) }) }) describe("the reference tools", () => { test("offers no tool when no site is configured", () => { // The same rule that withholds a banned-list tool from a corpus with no // banned list. A tool that can read nothing costs a step and teaches the // model that these tools return nothing. assert.deepEqual(defineReferenceTools({ sites: [] }), []) }) test("offers both tools when a site is configured", () => { const names = defineReferenceTools(options()).map((t) => t.name) assert.deepEqual(names, ["list_references", "fetch_reference"]) }) test("names every site and whether it is official, without reading a page", async () => { const { impl, asked } = stubFetch({}) const tool = findTool(defineReferenceTools(options({ fetchImpl: impl })), "list_references") const result = (await tool?.execute({} as never)) as { sites: { name: string; official: boolean; page_pattern?: string }[] } assert.equal(result.sites[0]?.name, "Example FAQ") assert.equal(result.sites[0]?.official, false) assert.equal(result.sites[0]?.page_pattern, "https://faq.example.com/cards/{slug}") assert.deepEqual(asked, [], "naming the sites must cost no page read") }) test("rule 9: stops at the per-question cap", async () => { const { impl, asked } = stubFetch({ "https://faq.example.com/a": { body: "

A

" }, "https://faq.example.com/b": { body: "

B

" }, "https://faq.example.com/c": { body: "

C

" }, "https://faq.example.com/d": { body: "

D

" }, }) const tool = findTool( defineReferenceTools(options({ fetchImpl: impl, maxFetchesPerTurn: 3 })), "fetch_reference", ) for (const path of ["a", "b", "c"]) { const page = (await tool?.execute({ url: `https://faq.example.com/${path}` } as never)) as { error?: string } assert.equal(page.error, undefined) } const fourth = (await tool?.execute({ url: "https://faq.example.com/d" } as never)) as { error?: string } assert.match(fourth.error ?? "", /limit/) assert.equal(asked.length, 3, "the fourth address must never be requested") }) test("rule 9: a refused address still spends its share of the cap", async () => { // Otherwise a model retries its way past the limit by aiming at hosts that // fail, and each failure costs a round trip anyway. const { impl } = stubFetch({ "https://faq.example.com/a": { body: "

A

" } }) const tool = findTool( defineReferenceTools(options({ fetchImpl: impl, maxFetchesPerTurn: 1 })), "fetch_reference", ) const refused = (await tool?.execute({ url: "https://elsewhere.test/x" } as never)) as { error?: string } assert.match(refused.error ?? "", /not a reference site/) const next = (await tool?.execute({ url: "https://faq.example.com/a" } as never)) as { error?: string } assert.match(next.error ?? "", /limit/) }) test("builds a fresh cap for each turn's tools", async () => { // The count lives in the closure, so one set of tools reused across turns // would spend its budget once and refuse every question afterwards. const { impl } = stubFetch({ "https://faq.example.com/a": { body: "

A

" } }) const build = () => findTool(defineReferenceTools(options({ fetchImpl: impl, maxFetchesPerTurn: 1 })), "fetch_reference") await build()?.execute({ url: "https://faq.example.com/a" } as never) const second = (await build()?.execute({ url: "https://faq.example.com/a" } as never)) as { error?: string } assert.equal(second.error, undefined, "a new turn must start with a full budget") }) test("rule 10: reads one address once and serves the rest from the cache", async () => { const { impl, asked } = stubFetch({ "https://faq.example.com/a": { body: "

A

" } }) const cache = new MemoryCache() const call = async () => { const tool = findTool(defineReferenceTools(options({ fetchImpl: impl, cache })), "fetch_reference") return (await tool?.execute({ url: "https://faq.example.com/a" } as never)) as { text?: string } } const first = await call() const second = await call() assert.equal(first.text, second.text) assert.deepEqual(asked, ["https://faq.example.com/a"], "the second read must come from the cache") }) test("returns a refusal to the model rather than throwing", async () => { // A refused address is an ordinary result. Throwing would end the turn, and // the reader would get a failure where a corpus answer was still possible. const tool = findTool(defineReferenceTools(options({ fetchImpl: stubFetch({}).impl })), "fetch_reference") const result = (await tool?.execute({ url: "http://faq.example.com/x" } as never)) as { error?: string } assert.match(result.error ?? "", /Only https/) }) test("marks a successful read as coming from outside the corpus", async () => { // This is what the interface renders. The model writes the prose and the // model is the thing being checked, so the marker cannot come from prose. const { impl } = stubFetch({ "https://faq.example.com/cards/x": { body: "X

Body.

" }, }) const tool = findTool(defineReferenceTools(options({ fetchImpl: impl })), "fetch_reference") const result = await tool?.execute({ url: "https://faq.example.com/cards/x" } as never) assert.deepEqual(tool?.describeResult?.(result)?.source, { name: "Example FAQ", url: "https://faq.example.com/cards/x", official: false, }) }) test("marks a refused read as rejected, and names no source", async () => { // The tool hands the refusal back as an ordinary result, so the runtime // marks the step "completed". A reader watching the trace then sees a read // that never happened reported as a finished one. `rejected` is the true // word, and the interface already counts and colours it. const tool = findTool(defineReferenceTools(options({ fetchImpl: stubFetch({}).impl })), "fetch_reference") const result = await tool?.execute({ url: "https://elsewhere.test/x" } as never) const step = tool?.describeResult?.(result) assert.equal(step?.status, "rejected") assert.equal(step?.source, undefined, "a read that did not happen cites no source") assert.match(step?.label ?? "", /Refused/) }) test("marks a read stopped by the per-question cap as rejected too", async () => { // Same result for the reader: the page was not read. Reporting the first // three reads and then a silent "completed" for the fourth would say the // opposite. const { impl } = stubFetch({ "https://faq.example.com/a": { body: "

A.

" }, }) const tool = findTool( defineReferenceTools(options({ fetchImpl: impl, maxFetchesPerTurn: 1 })), "fetch_reference", ) await tool?.execute({ url: "https://faq.example.com/a" } as never) const capped = await tool?.execute({ url: "https://faq.example.com/a" } as never) assert.equal(tool?.describeResult?.(capped)?.status, "rejected") }) test("marks nothing when a tool returns something it does not recognise", async () => { const tool = findTool(defineReferenceTools(options({ fetchImpl: stubFetch({}).impl })), "fetch_reference") assert.equal(tool?.describeResult?.(null), undefined) assert.equal(tool?.describeResult?.({}), undefined) }) }) describe("reading a page without an HTML parser", () => { test("drops the furniture and keeps the article", () => { const text = stripHtml( "Promising Future" + "" + "

How does it resolve?

In two passes.

Contact
", ) assert.match(text, /Promising Future/) assert.match(text, /How does it resolve\?/) assert.match(text, /In two passes\./) assert.ok(!text.includes("track()"), "script contents are never the article") assert.ok(!text.includes("color:red"), "style contents are never the article") assert.ok(!text.includes("Home Cards"), "navigation is never the article") }) test("keeps words on either side of a block from running together", () => { assert.match(stripHtml("
  • Guard
  • Swift
  • "), /Guard\nSwift/) }) test("decodes the entities a rules page actually uses", () => { assert.equal(stripHtml("

    A & B < C "D"

    "), 'A & B < C "D"') }) test("passes plain text through untouched", () => { assert.equal(stripHtml("Rule 300.2 ", "text/plain"), "Rule 300.2 ") }) test("uses a reader the implementer supplied instead", async () => { const { impl } = stubFetch({ "https://faq.example.com/x": { body: "

    ignored

    " } }) const page = await fetchReference( "https://faq.example.com/x", options({ fetchImpl: impl, readPage: () => "my own reading" }), ) assert.equal(page.text, "my own reading") }) }) describe("slugify", () => { test("turns a printed name into a path segment", () => { assert.equal(slugify("Promising Future"), "promising-future") assert.equal(slugify("Stonewall Sentry, Awakened"), "stonewall-sentry-awakened") assert.equal(slugify(" Ka'Tel's Oath "), "ka-tel-s-oath") }) })