Skip to content

Commit 577e04c

Browse files
authored
fix(router): stabilize multi-agent review findings (15 mediums + cleanups) (#571)
Stabilizes 15 of 16 verified medium-severity findings from a multi-agent review (each red->green tested) plus 90+ low/info cleanups. Highlights: cross-host loader-cache leak fixed (host now in the key); trie constraint backtracking; loading:false loader isolation; prerender Passthrough+loading() passthrough detection; loud loader-cache errors; cache() TEnv + transition() type fixes; cache(profileName) removed; dead exports removed + missing re-exports added; ~3.3k lines of comment noise removed. Gate green: typecheck, 3843 unit, lint, format, full dev+prod e2e. Deferred work tracked in #567-#570, #572.
1 parent e5a3b9f commit 577e04c

230 files changed

Lines changed: 2314 additions & 5105 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.claude/comment-groups.json‎

Lines changed: 436 additions & 0 deletions
Large diffs are not rendered by default.

‎.claude/gen-comment-groups.cjs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const { execSync } = require("child_process");
2+
const fs = require("fs");
3+
const ROOT = "/Users/ivotodorov/Development/vite-rsc-2";
4+
const OUT = `${ROOT}/.claude/comment-groups.json`;
5+
6+
// Shipped source only: no tests, mocks, generated, decl, or type-check files.
7+
const cmd =
8+
"find packages/rangojs-router/src -type f \\( -name '*.ts' -o -name '*.tsx' \\) " +
9+
"! -path '*__tests__*' ! -path '*__mocks__*' ! -path '*__augment-tests__*' " +
10+
"! -name '*.test.*' ! -name '*.gen.ts' ! -name '*.d.ts' ! -name '*.check.ts' " +
11+
"! -name '*.entry.ts'";
12+
const files = execSync(cmd, { cwd: ROOT, encoding: "utf8" })
13+
.trim()
14+
.split("\n")
15+
.filter(Boolean)
16+
.sort(); // path-sorted so chunks stay directory-affine
17+
18+
const CHUNK = 18; // ~19 groups for "mass" parallelism
19+
const groups = [];
20+
for (let i = 0; i < files.length; i += CHUNK) {
21+
groups.push({ group: `g${groups.length + 1}`, files: files.slice(i, i + CHUNK) });
22+
}
23+
24+
fs.writeFileSync(OUT, JSON.stringify(groups, null, 2));
25+
console.log(`${files.length} files -> ${groups.length} groups (~${CHUNK}/group)`);
26+
console.log(`wrote ${OUT}`);

‎.claude/wf-comments.js‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
export const meta = {
2+
name: "rango-comment-reduction",
3+
description:
4+
"Haiku mass agents: strip redundant comments, keep load-bearing ones (code-as-doc)",
5+
phases: [
6+
{ title: "Reduce", detail: "one haiku agent per disjoint file group" },
7+
],
8+
};
9+
10+
const ROOT = "/Users/ivotodorov/Development/vite-rsc-2";
11+
const GROUPS_FILE = `${ROOT}/.claude/comment-groups.json`;
12+
13+
const SCHEMA = {
14+
type: "object",
15+
additionalProperties: false,
16+
properties: {
17+
group: { type: "string" },
18+
filesEdited: {
19+
type: "array",
20+
items: {
21+
type: "object",
22+
additionalProperties: false,
23+
properties: {
24+
file: { type: "string" },
25+
removed: {
26+
type: "number",
27+
description: "Approx count of comment lines removed.",
28+
},
29+
note: { type: "string" },
30+
},
31+
required: ["file", "removed"],
32+
},
33+
},
34+
untouched: {
35+
type: "array",
36+
items: { type: "string" },
37+
description: "Files left fully as-is.",
38+
},
39+
notes: { type: "string" },
40+
},
41+
required: ["group", "filesEdited", "untouched", "notes"],
42+
};
43+
44+
function prompt(group) {
45+
return `You reduce comment NOISE in one slice of @rangojs/router so the code reads as its own documentation, keeping only comments that genuinely earn their place.
46+
47+
REPO ROOT: ${ROOT}
48+
YOUR FILES: open ${GROUPS_FILE} (JSON array), find the entry where "group" === "${group}", and edit ONLY the files in its "files" array. Never touch any file outside that list.
49+
50+
GOAL: code-is-the-doc. Remove comments that add ZERO information beyond the code; keep comments that capture intent a reader cannot recover from the code alone.
51+
52+
REMOVE (these are noise):
53+
- Comments that restate the next line ("// increment i", "// loop over products", "// return the result", "// set the flag").
54+
- Redundant section/banner comments and decorative separators that only label obvious structure.
55+
- Commented-out dead code.
56+
- Obvious restatements of a parameter, type, or signature already visible.
57+
- Verbose step-by-step narration of self-evident logic.
58+
59+
KEEP (never remove — this repo deliberately values these):
60+
- Comments explaining WHY: rationale, trade-offs, why a non-obvious approach was chosen.
61+
- Non-obvious invariants and gotchas / "scar tissue" ("this started as a bug", "do NOT X because Y", "must run before Z").
62+
- Behavior not evident from the code (ordering guarantees, edge cases, platform quirks).
63+
- References to issues/PRs/specs/RFCs, and links to other modules.
64+
- JSDoc on EXPORTED functions/types/classes/consts (public API surface) and file-header doc comments that orient the reader.
65+
- Anything describing a subtle contract (cache scope, handler-first ordering, dev/prod parity, bundle hygiene).
66+
67+
NEVER TOUCH (not removable; removing them changes behavior or tooling):
68+
- Directive comments: \`@ts-expect-error\`, \`@ts-ignore\`, \`eslint-disable*\`, \`oxlint-disable*\`, \`biome-ignore\`, \`prettier-ignore\`, \`@__PURE__\`, \`c8 ignore\`, \`v8 ignore\`, \`istanbul ignore\`, and any \`@\`-prefixed pragma.
69+
- String directives \`"use client"\`, \`"use server"\`, \`"use cache"\` — these are STRINGS, not comments. Do not touch.
70+
- License/copyright headers. Type annotations. Any code, string literal, or import.
71+
72+
RULES:
73+
- Edit comments ONLY. Never change a line of code, a string, whitespace inside code, or imports. Removing a comment must not change runtime, types, or lint.
74+
- When in doubt, KEEP. Bias hard toward keeping. It is better to leave a borderline comment than to delete a load-bearing one.
75+
- No emoji/icons in any comment you leave (repo rule). Do not ADD comments.
76+
- Remove the comment line(s) cleanly; if removal leaves a doubled blank line, collapse it, but do not reflow code.
77+
78+
Set group="${group}". Report filesEdited (with approx removed count + a short note), untouched files, and any notes.`;
79+
}
80+
81+
// 19 disjoint groups (g1..g19) from gen-comment-groups.cjs. Each agent reads
82+
// its own file list out of GROUPS_FILE (scripts can't touch the filesystem).
83+
const GROUP_NAMES = Array.from({ length: 19 }, (_, i) => `g${i + 1}`);
84+
85+
log(
86+
`Comment reduction: ${GROUP_NAMES.length} haiku agents over disjoint file groups (code-as-doc, conservative).`,
87+
);
88+
89+
const results = await parallel(
90+
GROUP_NAMES.map(
91+
(name) => () =>
92+
agent(prompt(name), {
93+
label: `comments:${name}`,
94+
phase: "Reduce",
95+
schema: SCHEMA,
96+
model: "haiku",
97+
}),
98+
),
99+
);
100+
101+
return { results: results.filter(Boolean) };

‎.claude/wf-gap-review.js‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
export const meta = {
2+
name: "rango-gap-review",
3+
description:
4+
"Targeted review of surfaces the main review missed: testing module, security, cross-seam, self-diff",
5+
phases: [
6+
{ title: "Review", detail: "4 focused reviewers" },
7+
{ title: "Verify", detail: "adversarial check of high/critical findings" },
8+
],
9+
};
10+
11+
const ROOT = "/Users/ivotodorov/Development/vite-rsc-2";
12+
const PKG = "packages/rangojs-router";
13+
14+
const REVIEWS = [
15+
{
16+
key: "testing-module",
17+
label: "@rangojs/router/testing module (#533, never reviewed)",
18+
prompt: `Review the NEW consumer testing module that landed on main AFTER the original 54-reviewer pass, so it has had ZERO stabilization review.
19+
TARGETS: ${PKG}/src/testing/** (renderRoute, dispatch, runLoader/runLoaderResult, runMiddleware, collectHandle, renderHandler, flight/flight-matchers, generated-routes, vitest preset, e2e harness) and its public export map entries (./testing, ./testing/vitest, ./testing/dom, ./testing/e2e, ./testing/flight, ./testing/flight-matchers).
20+
LENSES: public API ergonomics & type-safety; correctness (do the primitives faithfully reproduce real runtime behavior, or can a test go green while proving nothing?); leaky internals; mismatches between docs/testing.md + skills/testing and the actual code. Read docs/testing.md to judge against intent.`,
21+
},
22+
{
23+
key: "security",
24+
label: "Security: actions / origin / redirect / nonce / PE",
25+
prompt: `Focused SECURITY review of the highest-risk request-handling surfaces (the original review's correctness lens touched these but no dedicated security pass ran).
26+
TARGETS: ${PKG}/src/rsc/server-action.ts, ${PKG}/src/rsc/origin-guard.ts, ${PKG}/src/rsc/progressive-enhancement.ts, ${PKG}/src/rsc/response-route-handler.ts, ${PKG}/src/rsc/nonce.ts, ${PKG}/src/browser/validate-redirect-origin.ts, ${PKG}/src/route-definition/redirect.ts, ${PKG}/src/router/content-negotiation.ts.
27+
HUNT: CSRF / origin-check bypass on actions and PE form POSTs; open-redirect (redirect target validation); SSRF; header/response splitting & smuggling; nonce/CSP weaknesses; action-argument tampering / deserialization; auth checks that can be skipped on the PE path but not JS (or vice versa); information disclosure in error responses. Cite exact file:line and a concrete attack scenario for each finding.`,
28+
},
29+
{
30+
key: "cross-seam",
31+
label: "Cross-subsystem seam interactions",
32+
prompt: `The original review was per-subsystem (9 silos), so bugs at the SEAMS between subsystems are under-covered. Hunt for interaction bugs where two correct-in-isolation subsystems combine incorrectly.
33+
TARGETS & COMBINATIONS: cache x prerender x revalidate (a cached segment under a Passthrough route, a revalidate() that crosses a cache boundary, prerender artifact + runtime cache); middleware x actions x revalidation (post-action revalidation render middleware scope, action vs route-middleware visibility); intercept x parallel x loading (an intercept slot with its own loader + loading() inside a parallel slot); loader caching x SWR x tag invalidation. Read ${PKG}/docs/internal/execution-model.md and docs/design/cache-tags-flow.md for the intended contracts, then look for combinations the contracts do not actually cover.`,
34+
},
35+
{
36+
key: "self-diff",
37+
label: "Adversarial self-review of the stabilization diff",
38+
prompt: `Adversarially review the stabilization changes on this branch for regressions, missed edge cases, or broken invariants. Run \`git -C ${ROOT} diff origin/main...HEAD\` to see the full diff (3 commits). For EACH non-trivial change, ask: does it fully fix the finding, or only the happy path? Did it introduce a regression, change an unintended behavior, or break an invariant (handler-first ordering, dev/prod parity, bundle hygiene, cache scope)? Specifically scrutinize: the trie constraintsSatisfied backtracking (does it still match every previously-matching route? any new shadowing?), the loader wrap-before-await on the loading:false path (ordering/metrics preserved?), detectPrerenderPassthrough (does awaiting thenable components change build timing or swallow a real error?), the loud loader-cache errors (no double-report?), and the dead-export removals (truly zero consumers?).`,
39+
},
40+
];
41+
42+
const FINDINGS = {
43+
type: "object",
44+
additionalProperties: false,
45+
properties: {
46+
area: { type: "string" },
47+
findings: {
48+
type: "array",
49+
items: {
50+
type: "object",
51+
additionalProperties: false,
52+
properties: {
53+
title: { type: "string" },
54+
severity: {
55+
type: "string",
56+
enum: ["critical", "high", "medium", "low", "info"],
57+
},
58+
file: { type: "string" },
59+
lines: { type: "string" },
60+
description: { type: "string" },
61+
evidence: { type: "string" },
62+
suggestion: { type: "string" },
63+
confidence: { type: "string", enum: ["high", "medium", "low"] },
64+
},
65+
required: [
66+
"title",
67+
"severity",
68+
"file",
69+
"lines",
70+
"description",
71+
"suggestion",
72+
"confidence",
73+
],
74+
},
75+
},
76+
notes: { type: "string" },
77+
},
78+
required: ["area", "findings", "notes"],
79+
};
80+
81+
const VERDICT = {
82+
type: "object",
83+
additionalProperties: false,
84+
properties: {
85+
verdict: {
86+
type: "string",
87+
enum: ["confirmed", "partial", "refuted", "needs-info"],
88+
},
89+
adjustedSeverity: {
90+
type: "string",
91+
enum: ["critical", "high", "medium", "low", "info"],
92+
},
93+
reasoning: { type: "string" },
94+
evidence: { type: "string" },
95+
},
96+
required: ["verdict", "adjustedSeverity", "reasoning", "evidence"],
97+
};
98+
99+
phase("Review");
100+
const reviewed = await pipeline(
101+
REVIEWS,
102+
(r) =>
103+
agent(
104+
`You are a senior engineer. REPO ROOT: ${ROOT}. ${r.prompt}\n\nActually read the cited files (Read/Grep). Ground every finding in a file+line you read; quote it in 'evidence'. Report 3-12 highest-signal findings; reporting a clean bill is a valid outcome. Set area="${r.key}".`,
105+
{ label: `review:${r.key}`, phase: "Review", schema: FINDINGS },
106+
),
107+
// verify high/critical findings adversarially
108+
(res, r) => {
109+
if (!res) return { area: r.key, verified: [] };
110+
const toVerify = (res.findings || []).filter(
111+
(f) => f.severity === "critical" || f.severity === "high",
112+
);
113+
const kept = (res.findings || []).filter(
114+
(f) => f.severity !== "critical" && f.severity !== "high",
115+
);
116+
return parallel(
117+
toVerify.map(
118+
(f, i) => () =>
119+
agent(
120+
`Adversarial verifier. REPO ROOT: ${ROOT}. Default to REFUTE unless the code clearly confirms it. Open ${f.file} (lines ${f.lines}), read it and callers/callees, decide confirmed/partial/refuted/needs-info and the true severity.\nCLAIM: ${f.title}\n${f.description}\nEvidence: ${f.evidence}`,
121+
{ label: `verify:${r.key}#${i}`, phase: "Verify", schema: VERDICT },
122+
)
123+
.then((v) => ({ ...f, verdict: v }))
124+
.catch(() => ({ ...f, verdict: null })),
125+
),
126+
).then((vs) => ({
127+
area: r.key,
128+
notes: res.notes,
129+
verified: [
130+
...vs,
131+
...kept.map((f) => ({
132+
...f,
133+
verdict: { verdict: "unverified-lowsev" },
134+
})),
135+
],
136+
}));
137+
},
138+
);
139+
140+
return { areas: reviewed.filter(Boolean) };

‎.gitignore‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,13 @@ lefthook-local.yml
1212

1313
# Temporary research docs
1414
MIDDLEWARE_RESEARCH.md
15-
.vite*
15+
.vite*
16+
17+
# Multi-agent review artifacts (not committed)
18+
rango-review-findings.md
19+
.claude/wf-rango-review.js
20+
.claude/gen-review-md.cjs
21+
.claude/fanout-groups.json
22+
.claude/group-findings.cjs
23+
.claude/wf-cleanup.js
24+
.claude/gen-comment-groups.cjs

‎docs/design/caching.md‎

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ lives.
1313
### ✅ Completed
1414

1515
- **Router-level cache integration** - Cache check before handler execution in `match()` and `matchPartial()`
16-
- **Cache provider in request context** - `SegmentCacheProvider` interface via AsyncLocalStorage
16+
- **Cache provider in request context** - `CacheScope` via AsyncLocalStorage
1717
- **Handle data caching** - Handles cached with segments, replayed on cache hit
1818
- **Parallel segment support** - All segments per entry (main + parallels) cached together
1919
- **In-memory store** - `MemorySegmentCacheStore` with TTL, survives HMR via `globalThis`
@@ -327,22 +327,16 @@ For `"use cache"` functions, cache keys follow the format `use-cache:{functionId
327327

328328
## Storage Backend
329329

330-
Pluggable `SegmentCacheStore` interface configured at handler level:
331-
332-
```typescript
333-
interface SegmentCacheStore {
334-
get(key: string): Promise<CachedEntryData | null>;
335-
set(key: string, data: CachedEntryData, ttl: number): Promise<void>;
336-
delete(key: string): Promise<boolean>;
337-
clear?(): Promise<void>;
338-
}
339-
340-
interface CachedEntryData {
341-
segments: SerializedSegmentData[]; // RSC-encoded components
342-
handles: Record<string, SegmentHandleData>;
343-
expiresAt: number;
344-
}
345-
```
330+
Pluggable `SegmentCacheStore` interface configured at handler level. The
331+
shapes sketched in this historical narrative predate the shipped types; for the
332+
authoritative, copy-pasteable definitions see `src/cache/types.ts`
333+
(`SegmentCacheStore`, `CacheGetResult`, `CachedEntryData`). In brief, the
334+
shipped store returns a `CacheGetResult` (data + `shouldRevalidate`) from
335+
`get()`, takes an optional `swr` on `set()`, and carries a larger optional
336+
surface (`getResponse`/`putResponse`, `getItem`/`setItem`, `invalidateTags`,
337+
`keyGenerator`, `defaults`); the shipped `CachedEntryData` is
338+
`{ segments, handles: string, expiresAt, tags?, taggedAt? }` (`handles` is a
339+
single Flight-encoded string, not a per-segment record).
346340

347341
### Handler Configuration
348342

@@ -487,7 +481,15 @@ Action: | serve | serve+reval | miss |
487481

488482
### Data Structures
489483

484+
This POC sketch carried `createdAt`/`staleAt`/`revalidationContext` and a
485+
per-segment `handles` record. The shipped `CachedEntryData`
486+
(`src/cache/types.ts`) is leaner — `{ segments, handles: string, expiresAt,
487+
tags?, taggedAt? }` — and staleness/revalidation is decided by the store
488+
(`CacheGetResult.shouldRevalidate`) rather than by fields on the entry. Treat
489+
the snippet below as the original reasoning, not the current type.
490+
490491
```typescript
492+
// Historical POC shape (see src/cache/types.ts for the shipped type)
491493
interface CachedEntryData {
492494
segments: SerializedSegmentData[];
493495
handles: Record<string, SegmentHandleData>;
@@ -656,14 +658,12 @@ cache({ ttl: 60 }, () => [
656658
```typescript
657659
// All signatures supported:
658660
function cache(children: () => RouteChildren[]): RouteChild;
659-
function cache(
660-
profileName: string,
661-
children?: () => RouteChildren[],
662-
): RouteChild;
663661
function cache(
664662
options: CacheOptions | false,
665663
children?: () => RouteChildren[],
666664
): RouteChild;
665+
// Named profiles are applied via the "use cache: <profile>" directive,
666+
// not a cache("profileName") form in the route tree.
667667

668668
interface CacheOptions {
669669
// Time-to-live in seconds (optional if store has defaults)
@@ -689,8 +689,18 @@ interface SegmentCacheStore {
689689
// Store-level defaults inherited by cache() boundaries
690690
readonly defaults?: { ttl?: number; swr?: number };
691691

692-
get(key: string): Promise<CachedEntryData | null>;
693-
set(key: string, data: CachedEntryData, ttl: number): Promise<void>;
692+
// get() returns a CacheGetResult ({ data, shouldRevalidate }), not the raw
693+
// entry; set() takes an optional swr window. See src/cache/types.ts for the
694+
// full shipped interface, including the optional response-cache
695+
// (getResponse/putResponse), "use cache" item (getItem/setItem),
696+
// invalidateTags, and keyGenerator surface.
697+
get(key: string): Promise<CacheGetResult | null>;
698+
set(
699+
key: string,
700+
data: CachedEntryData,
701+
ttl: number,
702+
swr?: number,
703+
): Promise<void>;
694704
delete(key: string): Promise<boolean>;
695705
clear?(): Promise<void>;
696706
}

0 commit comments

Comments
 (0)