Files
loki/scripts/test/widget-chat-concierge.ts
CatoandClaude a1f891c7e1 fix(widget-chat): the chat knows the partner programme and the course (#1026)
On bitbaum.orangecat.ch/partners/ the site chat told an applicant "we do
not have a formal partner program" and "we do not offer a course or
capstone" — both on the page it was answering from. Its facts were the
fleet map plus four studio doors; neither the partner route nor the
systems design pilot was among them.

- New doors: "Become a partner" (/partners/#join) and "Read the systems
  design pilot" (/academy/), with link keys that do not fire on a
  visitor's own "course site".
- "# The studio" facts: the partner terms as /partners/ states them, plus
  availability, the published engagement and the course modules from the
  studio's own commission.json (getStudioCommission, cached 5 min like
  the map). Placed before the projects so the budget cuts projects first.
- The keyword fallback routes partner/capstone questions to those doors
  instead of guessing from project words.


Claude-Session: https://claude.ai/code/session_01TAtbutb1k6VKYMPLVfSt92

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-03 04:08:40 -07:00

410 lines
14 KiB
TypeScript

// The widget's Chat mode answers strangers on other people's sites, from the
// public fleet map. What it must never get wrong is pinned here: it routes to
// real URLs from the map (never ones the model typed), it never offers a
// retired project, it never calls a pilot owner a client, and when no model can
// answer it STILL routes by the visitor's words instead of saying "try later".
// Run: npx tsx scripts/test/widget-chat-concierge.ts
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { FleetMap, FleetMapEntry } from "@/lib/register/map";
import {
EXPERIMENT_NAME_RE,
FACTS_BUDGET_CHARS,
STUDIO_DOORS,
displayName,
stem,
splitSpeakers,
stripMeta,
trimToLastSentence,
conciergePrompt,
conciergeSystemPrompt,
fallbackAnswer,
linksForReply,
renderConciergeFacts,
renderStudioFacts,
PARTNER_TERMS,
stageWord,
} from "@/lib/widget-chat/concierge";
const BASE = "https://loki.example";
function entry(p: Partial<FleetMapEntry> & Pick<FleetMapEntry, "slug" | "name">): FleetMapEntry {
return {
what: null,
stack: null,
layer: "product",
status: "live",
owner: "bitbaum",
since: null,
urls: { live: null, repo: null, orangecat: null, solon: null },
identity: { problem: null, solution: null, mission: null, vision: null },
roadmap: [],
changelog: [],
next: null,
now: { openRuns: 0, lastRun: null, lastLog: null },
...p,
};
}
const map: FleetMap = {
generatedAt: "2026-09-24T00:00:00Z",
thesis: "One person plus Bitcoin …",
pillars: [{ slug: "orangecat", layer: "economic", role: "Move value." }],
summary: { projects: 4, live: 2, clients: 1, inFlight: 0 },
projects: [
entry({
slug: "heidi",
name: "Heidi",
what: "Learn to understand and text in Zurich Swiss German.",
identity: {
problem: "Swiss people switch to English.",
solution: "Calibrated exposure.",
mission: null,
vision: null,
},
urls: { live: "https://heidi.example", repo: null, orangecat: null, solon: null },
}),
entry({
slug: "dogfood-bridge-test-2026-09-06b",
name: "Dogfood Bridge Test",
status: "not live",
what: "a test",
identity: { problem: "p", solution: "s", mission: null, vision: null },
}),
entry({ slug: "unwritten", name: "Unwritten", status: "not live", what: "Just a name." }),
entry({
slug: "draftapp",
name: "Draftapp",
status: "not live",
what: "A draft.",
identity: {
problem: "Drafts get lost.",
solution: "Keep them.",
mission: null,
vision: null,
},
}),
entry({
slug: "orangecat",
name: "orangecat",
what: "Your AI economic agent; Bitcoin settles.",
urls: { live: "https://orangecat.example", repo: null, orangecat: null, solon: null },
}),
entry({
slug: "aoz-housing",
name: "AOZ Housing",
what: "Housing search for refugees.",
owner: "aoz",
status: "demo",
}),
entry({
slug: "oldthing",
name: "Oldthing",
what: "Swiss German flashcards.",
status: "retired",
urls: { live: "https://old.example", repo: null, orangecat: null, solon: null },
}),
],
};
// Stage words: beta, never "live"; a pilot, never a client.
assert.equal(stageWord({ status: "live", owner: "bitbaum" }), "in beta");
assert.match(stageWord({ status: "demo", owner: "aoz" }), /pilot built with aoz/);
const facts = renderConciergeFacts(map);
assert.ok(!/client/i.test(facts), "facts never say client");
assert.ok(!facts.includes("Oldthing"), "retired projects are not offered");
assert.ok(!facts.includes("Dogfood"), "a throwaway run is not offered");
assert.ok(
!facts.includes("Unwritten"),
"a project that is not running and has no written problem is not offered",
);
assert.ok(
facts.includes("Draftapp"),
"a project that is not running but has a written profile is offered",
);
assert.ok(!facts.includes("One person"), "the map thesis (solo framing) is not fed to the model");
assert.ok(
facts.includes("Problem: Swiss people switch to English."),
"problems are included so needs can be matched",
);
assert.ok(
!/https?:\/\//.test(facts),
"no URLs in the facts: links are attached from the map, not typed by the model",
);
assert.ok(
facts.includes("* OrangeCat — "),
"pillars carry their titles, not the slug the register fell back to",
);
for (const d of STUDIO_DOORS) assert.ok(facts.includes(d.label), `studio door ${d.label} is known`);
assert.equal(displayName({ slug: "orangecat", name: "orangecat" }), "OrangeCat");
assert.equal(displayName({ slug: "heidi", name: "Heidi" }), "Heidi");
// The budget holds however large the map grows.
const huge: FleetMap = {
...map,
projects: Array.from({ length: 200 }, (_, i) =>
entry({
slug: `p${i}`,
name: `Project ${i}`,
what: "x".repeat(300),
identity: { problem: "y".repeat(300), solution: "z", mission: null, vision: null },
}),
),
};
assert.ok(renderConciergeFacts(huge).length <= FACTS_BUDGET_CHARS);
// Same throwaway pattern as the register's litter gate — two copies, kept equal here.
const here = dirname(fileURLToPath(import.meta.url));
const gate = readFileSync(join(here, "..", "ci", "check-no-experiment-litter.sh"), "utf8");
const shellRe = gate.match(/^EXPERIMENT_RE='(.+)'$/m)?.[1];
assert.equal(
EXPERIMENT_NAME_RE.source,
shellRe,
"EXPERIMENT_NAME_RE drifted from check-no-experiment-litter.sh",
);
for (const slug of ["dogfood-bridge-test-2026-09-06b", "factory-sep11-0040", "probe-x"]) {
assert.ok(EXPERIMENT_NAME_RE.test(slug), slug);
}
for (const slug of ["heidi", "kivvi", "open-accounting"])
assert.ok(!EXPERIMENT_NAME_RE.test(slug), slug);
const system = conciergeSystemPrompt(facts, { url: "https://bitbaum.example/", title: "bitbaum" });
assert.match(system, /'Cat:' or 'Loki:'/, "each agent speaks as itself, labelled");
assert.ok(
!/You are the Cat and Loki/.test(system),
"no joint persona: it is a chat the two live in",
);
assert.match(system, /Do not write URLs yourself/);
assert.match(
system,
/recommends itself in the first person/,
"an agent that fits recommends itself, not in the third person (seen live)",
);
assert.match(
system,
/never send someone there when a product fits/,
"self-serve before the closed waitlist (seen live)",
);
assert.match(system, /https:\/\/bitbaum\.example\//);
const prompt = conciergePrompt(
Array.from(
{ length: 20 },
(_, i) => ({ role: i % 2 ? "assistant" : "user", content: `turn ${i}` }) as const,
),
"hello",
);
assert.ok(
!prompt.includes("turn 7") && prompt.includes("turn 8"),
"only the last 12 turns are sent",
);
assert.ok(
prompt.endsWith("Visitor: hello\n"),
'the agents label their own lines; no joint "You:" speaker',
);
// Links come from the map, in the order the reply names them, deduped.
const links = linksForReply(
"Try Heidi first. OrangeCat can pay you; heidi again. Or join the waitlist.",
map,
BASE,
);
assert.deepEqual(
links.map((l) => l.url),
[
"https://heidi.example",
"https://orangecat.example",
"https://bitbaum.orangecat.ch/hire/#waitlist",
],
);
assert.deepEqual(
linksForReply("Oldthing was nice", map, BASE),
[],
"a retired project gets no link",
);
assert.deepEqual(
linksForReply("Visit https://evil.example now", map, BASE),
[],
"a URL in the reply is not a link",
);
// A name inside another word is not a mention.
assert.deepEqual(linksForReply("heidiland", map, BASE), []);
// The fallback still routes.
const fb = fallbackAnswer("I want to learn Swiss German", map, BASE);
assert.equal(fb.links[0]?.url, "https://heidi.example");
assert.ok(!fb.links.some((l) => l.url === "https://old.example"));
const none = fallbackAnswer("zzzz qqqq", map, BASE);
assert.equal(none.links.length, 2);
assert.ok(none.links.some((l) => l.url.endsWith("/work/")));
// Suffixes do not hide a match: "voting" is "vote", "transparently" is "transparent".
assert.equal(stem("voting"), stem("vote"));
assert.equal(stem("transparently"), stem("transparent"));
assert.equal(stem("decisions"), stem("decision"));
// Who said what: labels open messages, continuation lines stay with them, and
// text before any label is kept unattributed rather than dropped or guessed.
assert.deepEqual(
splitSpeakers("Cat: I can help you earn.\nTry OrangeCat.\n\nLoki: I can build it."),
[
{ speaker: "cat", text: "I can help you earn.\nTry OrangeCat." },
{ speaker: "loki", text: "I can build it." },
],
);
assert.deepEqual(splitSpeakers("**Loki:** Heidi fits."), [
{ speaker: "loki", text: "Heidi fits." },
]);
assert.deepEqual(splitSpeakers("Heidi fits.\nLoki: really."), [
{ speaker: null, text: "Heidi fits." },
{ speaker: "loki", text: "really." },
]);
assert.deepEqual(
splitSpeakers("Catalogue: see all"),
[{ speaker: null, text: "Catalogue: see all" }],
"'Catalogue:' is not the Cat",
);
assert.ok(!fallbackAnswer("x", map, BASE).reply.includes("assistant"));
// A speaker label is not a recommendation (seen live: "Loki: Heidi fits." put Loki first).
assert.deepEqual(
linksForReply(
"Loki: Heidi fits you.",
{
...map,
projects: [
...map.projects,
entry({
slug: "loki",
name: "loki",
urls: { live: "https://loki.example", repo: null, orangecat: null, solon: null },
}),
],
},
BASE,
).map((l) => l.label),
["Heidi"],
);
// A reply cut off mid-clause loses the half sentence, never the whole answer (seen live).
assert.equal(
trimToLastSentence("I can help you get paid. OrangeCat settles in Bitcoin, which is running, in"),
"I can help you get paid.",
);
assert.equal(trimToLastSentence("Heidi fits."), "Heidi fits.");
assert.equal(trimToLastSentence("no full stop anywhere"), "no full stop anywhere");
// A fallback model narrated its own rule-check into the answer (seen live on
// bitbaum, 2026-10-01): the checklist goes, the answer stays, word for word.
const leaked = [
"Loki: Sounds like a course site. Start with me — describe it and I will build it, OrangeCat.",
"",
"Stage used: beta.",
"No URLs written.",
'Loki first because building leads ("I want to build something cool...").',
].join("\n");
assert.equal(
stripMeta(leaked),
"Loki: Sounds like a course site. Start with me — describe it and I will build it, OrangeCat.",
);
assert.deepEqual(
splitSpeakers(stripMeta(leaked)).map((m) => m.speaker),
["loki"],
);
assert.equal(
stripMeta("- Stage: pilot\n- URLs: none\nCat: Heidi is a pilot."),
"Cat: Heidi is a pilot.",
);
// An answer that merely talks about stages, links or who answers is not meta.
for (const keep of [
"Loki: Heidi is in beta, and the link below opens it.",
"Cat: I answer first here because money leads your question.",
"Loki: No URLs are needed; tap the chip for the catalogue.",
"Format your request as a sentence or two and I will build it.",
])
assert.equal(stripMeta(keep), keep);
// The partner programme and the course (bitbaum /partners/, 2026-10-03): the
// chat told an applicant on that very page "we do not have a formal partner
// program" and "we do not offer a course", because neither was in its facts.
const studio = {
version: 1 as const,
origin: "https://bitbaum.orangecat.ch" as const,
availability: { state: "closed" as const, line: "The studio is at capacity." },
offer: {
id: "rescue",
name: "Rescue",
price: "CHF 6,500",
shape: "Two weeks, fixed",
what: "An assessment.",
},
course: {
version: "pilot-v1",
title: "Bitbaum systems design pilot",
pilot: true,
modules: [
{ id: "problem-constraints", title: "Problem and constraints" },
{ id: "deploy-handover", title: "Deployment and handover" },
],
},
feedbackToken: "fcw_x",
};
const withStudio = renderConciergeFacts(map, studio);
for (const t of PARTNER_TERMS) assert.ok(withStudio.includes(t), "partner terms are stated");
assert.ok(withStudio.includes("Bitbaum systems design pilot"), "the course is named");
assert.ok(
withStudio.includes("Problem and constraints; Deployment and handover"),
"modules listed",
);
assert.ok(withStudio.includes("CHF 6,500"), "the published engagement price is stated");
assert.ok(!/https?:\/\//.test(withStudio), "still no URLs in the facts");
assert.ok(
renderStudioFacts(null).includes(PARTNER_TERMS[0]!),
"the partner terms survive an unreachable studio contract",
);
assert.ok(
withStudio.indexOf("# The studio") < withStudio.indexOf("# Projects"),
"the studio comes before the projects, so the budget cuts projects first",
);
const hugeStudio = renderConciergeFacts(
{
...map,
projects: Array.from({ length: 400 }, (_, i) =>
entry({ slug: `p${i}`, name: `Project ${i}`, what: "x".repeat(140) }),
),
},
studio,
);
assert.ok(hugeStudio.length <= FACTS_BUDGET_CHARS);
assert.ok(hugeStudio.includes("Become a partner"), "a huge map does not push the partner door out");
assert.ok(
conciergeSystemPrompt(withStudio, {}).includes(
"Never say the partner programme or the course does not exist",
),
);
assert.deepEqual(
linksForReply(
"Loki: Partners agree their own price; start with the capstone rubric.",
map,
BASE,
).map((l) => l.label),
["Become a partner", "Read the systems design pilot"],
);
// Someone building a course website is not asking about the studio's course.
assert.ok(
!linksForReply("Loki: Sounds like a course site I can build.", map, BASE).some(
(l) => l.label === "Read the systems design pilot",
),
);
const offline = fallbackAnswer("How do partners qualify? Is there a capstone?", map, BASE);
assert.deepEqual(
offline.links.map((l) => l.label),
["Become a partner", "Read the systems design pilot"],
"with no model, a partner question still reaches the partner doors",
);
console.log("widget-chat-concierge: ok");