Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
fa7d614
feat(tc-reference): safer backups, undoable restore, phrase guard, 6-…
claude Nov 21, 2026
a802338
content(tc-reference): deepen TC101-TC109 and add distress/safety Hel…
claude Nov 21, 2026
bc7ea9e
Merge branch 'worktree-agent-a51290226d210982f' into claude/project-t…
claude Nov 21, 2026
4cd72e4
Refresh saved-phrase snapshot to cover the new TC101–TC109 and TC098 …
claude Nov 21, 2026
9ecfb6e
Link card cross-references to the cards they cite
claude Nov 21, 2026
14a3586
Group the Library's large categories into named runs
claude Nov 21, 2026
a69dbfd
Show the header title only after the page title scrolls away
claude Nov 21, 2026
939b07f
Use one phrase typeface and tint the best line green
claude Nov 21, 2026
72f05c2
perf(tc-reference): faster Phrase Bank first paint, CI budgets, axe s…
claude Nov 21, 2026
5ddd77b
Merge branch 'worktree-agent-ac7f85bf5f6990733' into claude/project-t…
claude Nov 21, 2026
51a4ad4
Merge branch 'worktree-agent-adbf7cb018f1a5549' into claude/project-t…
claude Nov 21, 2026
a2fb454
Hold the distress Help situation and safety wording for clinical review
claude Nov 21, 2026
ee1a57a
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 21, 2026
d8e462d
Wait for fades before axe scans; re-base the bundle budget after the …
claude Nov 21, 2026
a8d547e
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 21, 2026
0634bfd
Fix review findings: stale restore snapshot, Android backup sharing, …
claude Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/code-review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ jobs:
- name: Build production app
run: pnpm --filter @workspace/tc-reference build

- name: Check bundle size budgets
run: pnpm --filter @workspace/tc-reference run budget

- name: Run Automated Code Reviewer
env:
CODE_REVIEW_SKIP_CHECKS: "1"
Expand Down
30 changes: 26 additions & 4 deletions artifacts/tc-reference/card-text-index-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,49 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
import type { Plugin } from "vite";
import type { CardData } from "./src/lib/card-types";
import { projectCardText } from "./src/lib/card-text-index-build";
import {
projectCardText,
type CardTextEntry,
} from "./src/lib/card-text-index-build";
import { aggregatePhrases } from "./src/lib/phrase-aggregate";

const VIRTUAL_ID = "virtual:card-text-index";
const RESOLVED_ID = "\0" + VIRTUAL_ID;
const SUMMARY_ID = "virtual:phrase-bank-summary";
const RESOLVED_SUMMARY_ID = "\0" + SUMMARY_ID;

/** The totals in `virtual:phrase-bank-summary`, from the same aggregation. */
export function phraseBankSummary(index: Record<string, CardTextEntry>): {
phraseCount: number;
} {
// Titles do not affect the count.
return { phraseCount: aggregatePhrases(index, (cardId) => cardId).length };
}

/**
* Builds `virtual:card-text-index`: the search / phrase text of every card
* as one small module. The app imports it dynamically, so it becomes its own
* chunk that the service worker precaches with the app shell (card chunks
* themselves stay runtime-cached). Card sources are loaded with Node's
* TypeScript type stripping; they only use type imports.
*
* Also builds `virtual:phrase-bank-summary`, a few bytes of totals the Phrase
* Bank imports statically so its intro paints before the index arrives.
*/
export function cardTextIndexPlugin(cardsDir: string): Plugin {
return {
name: "tc-card-text-index",
resolveId(id) {
return id === VIRTUAL_ID ? RESOLVED_ID : undefined;
if (id === VIRTUAL_ID) return RESOLVED_ID;
if (id === SUMMARY_ID) return RESOLVED_SUMMARY_ID;
return undefined;
},
async load(id) {
if (id !== RESOLVED_ID) return undefined;
if (id !== RESOLVED_ID && id !== RESOLVED_SUMMARY_ID) return undefined;
const files = (await readdir(cardsDir))
.filter((file) => /^TC\d{3}\.ts$/.test(file))
.sort();
const index: Record<string, unknown> = {};
const index: Record<string, CardTextEntry> = {};
for (const file of files) {
const fullPath = path.join(cardsDir, file);
this.addWatchFile(fullPath);
Expand All @@ -38,6 +57,9 @@ export function cardTextIndexPlugin(cardsDir: string): Plugin {
if (!card) throw new Error(`${file} does not export ${cardId}`);
index[cardId] = projectCardText(card);
}
if (id === RESOLVED_SUMMARY_ID) {
return `export default ${JSON.stringify(phraseBankSummary(index))};`;
}
// JSON.parse of a string literal parses faster than an object literal.
return `export default JSON.parse(${JSON.stringify(JSON.stringify(index))});`;
},
Expand Down
97 changes: 97 additions & 0 deletions artifacts/tc-reference/e2e/a11y.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { createRequire } from "node:module";
import type { Page } from "@playwright/test";
import { test, expect, MAIN_ROUTES } from "./fixtures";

// axe-core runs inside the page. The production CSP (rightly) blocks
// injected scripts, so this spec alone bypasses it to add the engine.
test.use({ bypassCSP: true });

const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");

interface AxeViolation {
id: string;
impact: string | null;
help: string;
nodes: { target: string[]; html: string }[];
}

/** Wait for the route's lazy chunks and data loaders to settle. */
async function settle(page: Page) {
await expect(page.getByRole("heading", { level: 1 }).first()).toBeVisible();
await expect(page.locator('[aria-busy="true"]')).toHaveCount(0);
await expect(
page.getByRole("status").filter({ hasText: /^Loading/ }),
).toHaveCount(0);
// Let fades finish (e.g. the header title), so axe never samples colour
// contrast halfway through a transition.
await expect
.poll(() =>
page.evaluate(
() =>
document
.getAnimations()
.filter(
(a) =>
a.playState === "running" &&
a.effect?.getTiming().iterations !== Infinity,
).length,
),
)
.toBe(0);
}

async function runAxe(
page: Page,
runOnly: { type: "tag" | "rule"; values: string[] },
): Promise<string[]> {
if (!(await page.evaluate(() => "axe" in window))) {
await page.addScriptTag({ path: axePath });
}
const violations = await page.evaluate(async (only) => {
const axe = (
window as unknown as {
axe: {
run: (
ctx: Document,
opts: object,
) => Promise<{ violations: AxeViolation[] }>;
};
}
).axe;
const result = await axe.run(document, { runOnly: only });
return result.violations;
}, runOnly);
return violations.flatMap((v) =>
v.nodes.map(
(n) =>
`${v.id} (${v.impact}): ${n.target.join(" ")} ${n.html.slice(0, 120)}`,
),
);
}

for (const route of MAIN_ROUTES) {
test(`${route} passes the basic axe scan and label-in-name`, async ({
page,
}) => {
await page.goto(route);
await settle(page);

// WCAG 2.x A/AA rules that axe reports with certainty.
expect(
await runAxe(page, {
type: "tag",
values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"],
}),
).toEqual([]);

// Visible label text must be part of the accessible name (WCAG 2.5.3),
// so voice-control users can say what they see. Experimental in axe, so
// it only runs when named.
expect(
await runAxe(page, {
type: "rule",
values: ["label-content-name-mismatch"],
}),
).toEqual([]);
});
}
4 changes: 3 additions & 1 deletion artifacts/tc-reference/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p e2e/tsconfig.json",
"test": "node scripts/ensure-downloads.mjs && vitest run --config vitest.config.ts",
"test:full": "pnpm run generate:downloads && vitest run --config vitest.config.ts",
"test:e2e": "playwright test --trace off"
"test:e2e": "playwright test --trace off",
"budget": "node scripts/check-bundle-budget.mjs"
},
"devDependencies": {
"@fontsource/inter": "^5.3.0",
Expand All @@ -25,6 +26,7 @@
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@vitejs/plugin-react": "catalog:",
"axe-core": "4.13.0",
"jsdom": "^30.1.3",
"lucide-react": "catalog:",
"minisearch": "7.2.0",
Expand Down
82 changes: 82 additions & 0 deletions artifacts/tc-reference/scripts/check-bundle-budget.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Fails when a key production chunk grows past its gzip budget. Run after
// `pnpm run build`. Budgets sit about 10% above the sizes when they were set,
// so ordinary edits pass and a regression (a new heavy import in the entry,
// a dependency landing in vendor, the text index doubling) stops CI.
// Raising a budget is fine when the growth is intended: say why in the PR.
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { gzipSync } from "node:zlib";

const KB = 1024;
// gzip -9 bytes (KiB), about 10% above the build of 2026-11-21 after the
// design round: entry 34.3, vendor 59.4, main CSS 12.7, card text index 178.5.
export const BUDGETS = {
"entry JS": 38 * KB,
"vendor JS": 66 * KB,
"main CSS": 14 * KB,
"card-text-data JS": 196 * KB,
};

const root = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"dist",
"public",
);

/** The budgeted files, found through Vite's build manifest. */
export function budgetedFiles(manifest) {
const entry = manifest["index.html"];
if (!entry?.file) throw new Error("manifest has no index.html entry");
const vendor = Object.values(manifest).find((chunk) =>
/^assets\/vendor-[^/]+\.js$/.test(chunk.file),
);
const textIndex = manifest["virtual:card-text-index"];
const css = entry.css?.[0];
const files = {
"entry JS": entry.file,
"vendor JS": vendor?.file,
"main CSS": css,
"card-text-data JS": textIndex?.file,
};
for (const [label, file] of Object.entries(files)) {
if (!file) throw new Error(`build manifest has no ${label} chunk`);
}
return files;
}

export function checkBudgets(readFile, manifest) {
const rows = [];
for (const [label, file] of Object.entries(budgetedFiles(manifest))) {
const gzip = gzipSync(readFile(file), { level: 9 }).length;
rows.push({ label, file, gzip, budget: BUDGETS[label] });
}
return rows;
}

const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : "";
if (invokedPath === fileURLToPath(import.meta.url)) {
const manifest = JSON.parse(
readFileSync(path.join(root, ".vite", "manifest.json"), "utf8"),
);
const rows = checkBudgets(
(file) => readFileSync(path.join(root, file)),
manifest,
);
let failed = false;
for (const { label, file, gzip, budget } of rows) {
const over = gzip > budget;
failed ||= over;
const pct = ((gzip / budget) * 100).toFixed(0);
console.log(
`${over ? "OVER" : "ok "} ${label.padEnd(18)} ${(gzip / KB).toFixed(1).padStart(6)} KB gz / ${(budget / KB).toFixed(1)} KB (${pct}%) ${file}`,
);
}
if (failed) {
console.error(
"\nBundle budget exceeded. Trim the growth, or raise the budget in scripts/check-bundle-budget.mjs and explain why in the PR.",
);
process.exit(1);
}
}
14 changes: 14 additions & 0 deletions artifacts/tc-reference/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ const securityHeaders = (scriptHashes) => ({
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
});

// HSTS only means something over HTTPS: browsers ignore it on plain http, and
// sending it from localhost could pin a developer's machine to https. Railway
// terminates TLS at its edge and forwards the original scheme.
const HSTS = "max-age=31536000; includeSubDomains";

/** True when the client reached us over HTTPS (directly or via the proxy). */
export function arrivedOverHttps(req) {
if (req.socket?.encrypted) return true;
const forwarded = req.headers["x-forwarded-proto"];
const value = Array.isArray(forwarded) ? forwarded[0] : (forwarded ?? "");
return value.split(",")[0].trim().toLowerCase() === "https";
}

function setHeaders(res, pathname, headers) {
for (const [name, value] of Object.entries(headers)) {
res.setHeader(name, value);
Expand Down Expand Up @@ -124,6 +137,7 @@ export function createRequestHandler(root = defaultRoot) {
res.end(req.method === "HEAD" ? undefined : indexHtml);
};
return (req, res) => {
if (arrivedOverHttps(req)) res.setHeader("Strict-Transport-Security", HSTS);
req.headers["accept-encoding"] = acceptableEncodings(
req.headers["accept-encoding"],
);
Expand Down
28 changes: 26 additions & 2 deletions artifacts/tc-reference/src/components/app-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useTheme } from "@/lib/theme";
import { usePdf } from "@/lib/pdf-context";
import { LIBRARY_CATEGORIES } from "@/lib/data";
import { useScrollDirection } from "@/hooks/use-scroll-direction";
import { useHeaderTitleShown } from "@/lib/page-title";
// Lazily loaded — global search builds its cached aggregate index only after a
// user enters a query.
const SearchModal = lazy(() =>
Expand Down Expand Up @@ -122,6 +123,15 @@ export function AppHeader() {
// scroll up or near the top. The shared hook clamps iOS
// overscroll so rubber banding can't make the header flicker.
const scrollingDown = useScrollDirection(56, 10, location) === "down";
// iOS large-title pattern: while the page's own big title is on screen the
// header leaves the name out, then fades it in once that title scrolls
// away. Pages without one (the Library) keep the header title throughout.
const { hasPageTitle, shown: titleShown } = useHeaderTitleShown();
const titleFade: React.CSSProperties = {
opacity: titleShown ? 1 : 0,
transform: titleShown ? "none" : "translateY(4px)",
transition: "opacity 180ms ease, transform 180ms ease",
};

const cardId = location.startsWith("/card/")
? location.replace("/card/", "").split("?")[0]
Expand Down Expand Up @@ -255,13 +265,17 @@ export function AppHeader() {
{cardId}
</span>
)}
{/* Stays the page h1 for assistive tech; drawn only once the
card's own large title has scrolled away */}
<h1
className="font-bold leading-tight truncate"
style={{
color: "var(--fg-90)",
fontSize: 15.5,
...titleFade,
}}
data-testid="card-title"
data-title-shown={titleShown}
>
{cardMeta?.cardTitle ?? "Card not found"}
</h1>
Expand Down Expand Up @@ -329,9 +343,15 @@ export function AppHeader() {
/>
</span>
<div className="min-w-0 leading-none">
{/* The app name. From md up the sidebar already carries it */}
<p
className="text-[11px] font-bold tracking-[0.12em] uppercase leading-none mb-[3px]"
style={{ color: "var(--brand-text)" }}
className="md:hidden text-[11px] font-bold tracking-[0.12em] uppercase leading-none mb-[3px]"
style={{
color: "var(--brand-text)",
// Centred on the icon while the page title is away
transform: titleShown ? "none" : "translateY(7px)",
transition: "transform 180ms ease",
}}
data-testid="library-subtitle"
>
TC Reference
Expand All @@ -341,8 +361,12 @@ export function AppHeader() {
style={{
color: "var(--fg-90)",
fontSize: 17,
...titleFade,
}}
// The page's own h1 names it; this copy is visual only
aria-hidden={hasPageTitle || undefined}
data-testid="library-title"
data-title-shown={titleShown}
>
{pageTitle}
</TitleTag>
Expand Down
2 changes: 1 addition & 1 deletion artifacts/tc-reference/src/components/app-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export function AppLayout({ children }: AppLayoutProps) {
className="block text-[16px] font-bold leading-tight"
style={{ color: "var(--fg-90)" }}
>
TC Library
TC Reference
</span>
<span
className="block text-[11px] font-medium mt-0.5"
Expand Down
Loading
Loading