A maintainability audit of the repo turned up two live detection defects
before it got to the dead code it was looking for. Both are fixed here, and
the guard that should have caught them is upgraded so it can.
1. The shipped proxy was quarantining ordinary prose.
`Task order / delivery order` carried bare TO/DO in a case-insensitive
alternation with no closing \b, so it matched INSIDE "tomorrow",
"tonight", "document", "download", "together"; and under the `i` flag its
[A-Z0-9]{4,} identifier matched any word, so "to production" and
"to review" read as order numbers. Verified end-to-end through the real
scanMessages(): 10 of 10 ordinary sentences QUARANTINEd at HIGH risk.
All 10 now ALLOW; all 5 real task-order forms still fire.
2. The two registries had drifted, against the deployment that matters.
`Health plan beneficiary number` diverged: Mode B recognised neither
subscriber, policy nor group identifiers, so the shipped proxy let
through 5 PHI strings the hosted demo blocked. Both registries now carry
the byte-identical union, narrowed on noise (the identifier must contain
a digit — "Policy number pending" matched before).
`PM` was NOT ported to the proxy: under `i` it fires on every clock time
("move the standup to 4 PM tomorrow"). It became a case-sensitive
`Program manager designator` rule with a digit lookbehind, added to both
registries. Proxy 33 -> 34, app 53 -> 54; all 9 doc references updated.
3. The drift guard's own header said it could not see this — "two patterns
sharing a name with different regexes still pass". It now imports both
registries and compares BEHAVIOUR across a 41-string corpus, with 15
regression anchors that must stay clean in both engines.
Also in this change, from the same audit:
- Wired lib/health/service-status.ts and lib/auth/reset-diagnostics.ts
(516 lines, built and tested, imported by nothing) into the admin-gated
/api/admin/health, which now reports `degraded` and names the failing
keys. CLAUDE.md's Session Start Protocol told every session to curl
/api/health for integration health; that endpoint returns a hardcoded
`ok`. Corrected, with 9 new tests.
- Moved /api/chat to the Postgres-backed shared rate limiter. It falls back
to the server's own OPENROUTER_API_KEY and was limited to 10/min PER
INSTANCE — the exact spend exposure rate-limit-shared.ts exists to close.
- Deleted 38 files / 6,611 lines unreachable from any of the 427 entry
points, including the lib/gateway/providers registry that called itself
"the single entry point for the streaming proxy" while stream-proxy.ts
re-implemented the same table inline.
- Removed 9 unused dependencies: 95 packages, 67.5 MB, including a full
react-native + expo tree. npm ci 861 -> 766 packages.
- Deleted an untouched create-next-app scaffold at the repo root: a
tsconfig mapping @/* to a non-existent ./src/*, a postcss config needing
a Tailwind v4 package nothing installs, and a yarn.lock beside a
package-lock named "nostalgic-raman-26ee6a". No CI job built at root.
- Updated every doc, rule and skill naming a deleted file. One handed
agents an import example that would no longer compile; CLAUDE.md's first
Critical Rule was about a dead component, and is now stated generally
(any Recharts component stays ssr:false).
- zero-trust.ts, swr-cache.ts and reset-password-state.ts are built but
unwired. They stay, each carrying an explicit `ponytail:` note naming the
decision needed — removing an unwired deny-by-default access control is a
founder call, not cleanup.
Gates: app 3,114 tests / 222 files · proxy 92 · tsc 0 · lint 0 errors
(39 warnings, at baseline) · build EXIT 0 · scan p99 0.684ms against a 10ms
budget · verify-structure PASS.
Full findings: docs/audit/DEAD-WEIGHT-AUDIT-2026-09-03.html
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018GK6NpeRNRpdzRrEP9vuyM
Summary
A code-quality and maintainability review of the whole repo. It set out to find dead code and found two live detection defects on the way — those are the reason this PR leads with
fix(detection)rather thanchore(cleanup).1. The shipped proxy was quarantining ordinary English.
Task order / delivery ordercarried bareTO/DOin a case-insensitive alternation with no closing\b, so it matched inside "tomorrow", "tonight", "document", "download", "together". Under theiflag its[A-Z0-9]{4,}identifier also matched any word, so "to production" and "to review" read as order numbers. Verified end-to-end through the realscanMessages(), not a transcribed regex:to productionto documentdownloadtomorrowto date10 of 10 ordinary sentences were held at HIGH risk. All 10 now pass; all 5 real task-order forms (
TO 0001,delivery order N0001923D0001,task order no. 88213) still fire.2. The two registries had drifted, against the deployment that matters.
Health plan beneficiary numberdiverged: Mode B — the deployment the CUI/HIPAA claim rests on — recognised neithersubscriber,policynorgroupidentifiers, so the shipped proxy let through 5 PHI strings the hosted demo blocked. Both registries now carry the byte-identical union, narrowed on noise (the identifier must contain a digit;Policy number pendingmatched before).PMwas not ported to the proxy — underiit fires on every clock time. It became a case-sensitiveProgram manager designatorrule with a digit lookbehind, added to both registries (proxy 33 → 34, app 53 → 54; all 9 doc references updated, as the repo's owndoc-countsguard required).3. The guard that should have caught this said it could not.
registry-drift.test.tscompared declared names as source text and its own header stated the ceiling: "two patterns sharing a name with different regexes still pass." It now imports both registries and compares behaviour across a 41-string corpus, with 15 regression anchors that must stay clean in both engines.The maintainability findings — 6,611 unreachable lines, 95 removable packages, an abandoned scaffold — are in the same PR because the doc corrections they force overlap the detection docs. Full findings:
docs/audit/DEAD-WEIGHT-AUDIT-2026-09-03.html.Closes #
Change type
Impact and operating considerations
Operational impact, threat-model note, and rollback plan:
Detection behaviour changes in both directions, deliberately. It widens for PHI (Mode B now blocks 5 identifier forms it previously allowed) and narrows for the task-order rule (it no longer fires on prose). The narrowing is the larger behavioural change: any deployment currently relying on that rule's output will see far fewer quarantines — which is the point, since 10/10 sampled benign sentences were tripping it. Both registries were changed together and are now asserted byte-identical in behaviour by the parity guard, so the two planes cannot diverge again silently.
Pattern floor respected. CLAUDE.md's extend-never-replace rule and the CI Compliance Pattern Guard (
ALL_PATTERNS.length >= 33) both hold: the count went up, to 34. Scan latency is unchanged — p99 0.693 ms against a 10 ms budget — despite the added lookaheads.Rate limiting.
/api/chatmoved from the per-process limiter to the Postgres-backed shared limiter. It falls back to the server's ownOPENROUTER_API_KEY, and the in-processMapgave a real ceiling of (10 × live instances), reset on every cold start — the exact spend exposurerate-limit-shared.tswas written to close. Requires migration028_rate_limit_buckets.sqlto be applied in production; until it is, the shared limiter fails open to the in-process limiter and flagsdegraded: true, so behaviour is no worse than today, never worse for a paying caller.Health endpoint.
/api/admin/healthnow returns real diagnostics. It stays admin-gated and fail-closed (404 for anonymous and non-admin, asserted in new tests), andbuildHealthReport()is value-free by construction — every signal derives from the shape or presence of configuration, never its content. The public/api/healthis untouched and still discloses nothing.Rollback. Single commit, revertable as one. No migrations, no schema changes, no environment variables added or renamed. Reverting restores the previous detection behaviour, including both defects.
Validation
npx tsc --noEmitnpm run lintnpm run test:coveragenpm run buildnpm run lintnpm run test:coveragenpm run benchResults and manual verification:
tsc --noEmitlinttest:coveragevitest.config.ts, because removing unreachable code removes uncovered lines from the denominatorbuildƒ Proxy (Middleware)presentlinttest:coveragebenchscripts/verify-structure.mjsnpm ciafter dependency removalBaseline before any change was 223 files / 3,099 tests. The net file count drops because dead tests were removed with the code they covered; the net test count rises because new guards were added.
Manual verification was done by running prompts through the real
proxy/scanner.tsentry point rather than reasoning about regexes — which is also how the task-order defect was confirmed to be a whole-prompt verdict (the scanner applies every pattern with no context gating and takes the strongest action). The before/after table above is that run. The 8 PHI strings were re-checked the same way: 0 of 8 still leak in Mode B.Review checklist
Notes for the reviewer
Scope. This is larger than a single fix because the pattern-count change forced doc updates across 9 files, and the repo's
doc-countsguard fails the build until every one is corrected. The dead-code removal is separable in principle; it is here because it touches the same rule and skill files.Deliberately left open, and why.
lib/gateway/zero-trust.ts,lib/cache/swr-cache.tsandlib/auth/reset-password-state.tsare built, tested and imported by nothing. They stay, each now carrying an explicitponytail:note naming the decision needed. Removing an unwired deny-by-default access control is a founder call, not cleanup, and wiring one into the live gateway is a behaviour change deserving its own review.Not acted on from static analysis. 20 API routes have no in-repo caller, but some of them are the product —
/api/v1/*is the endpoint customers point theirbaseURLat, and/api/events/ingestis called byproxy/webhook.tsin a different package. That triage needs access logs, not an import graph, so nothing was deleted there.Five false positives were caught and excluded before they reached the report, and are recorded in the audit so nobody re-derives them:
demo-telemetry-seed.ts(loaded by a runtime-built path in a script),lib/rate-limit.ts(the deliberate fail-open fallback inside the shared limiter), the 8lib/agent/tools/*files (side-effect registered, dynamically imported),providers/types.ts(stream-scanner.tsimportsScanAlertfrom it), andsetup-stripe.mjs(a one-shot ops script, unreferenced by design).🤖 Generated with Claude Code
https://claude.ai/code/session_018GK6NpeRNRpdzRrEP9vuyM
Generated by Claude Code