Repository source: docs/plans/code_quality_review_findings_v1.md
Code Quality Review — Findings v1
Raw results from the first tooling pass of the code quality review checklist. Snapshot: main at b50af91 (2026-11-10). No code was changed in this pass. Every finding has a proposed decision; nothing gets removed until the maintainer confirms it.
Decisions: fix (a real bug), remove (confirmed dead), review (probably dead or worth changing; needs a judgment call), keep (intentional; add a note per the intentional-duplicate rule), false positive (the tool got it wrong).
The earlier cleanup audit findings were read first. Nothing below repeats an item it already closed.
Summary
Current state and how to rerun the tools: handoff.
This is the first pass, 2026-11-10. What happened afterwards, decision by decision, is under Decisions and outcomes, and the mistakes to avoid next time are under Lessons for the next pass.
1 real bug:
DedalusPostAnalyzerthrows a class that doesn't exist.~25 dead methods, properties, and constants in
src/, plus 1 dead template. All checked by hand for string-based and dynamic uses.~30 methods in
src/reached only by tests. Some are test hooks (keep); others are leftover API (review).Duplication is low: 0.88% of lines (30 clones of 15+ lines). Two clusters are worth merging.
Size:
Application::handleis a single 1,083-line method. 32 methods are over 100 lines.Security spot checks found no problems. Every shell command checked escapes its arguments, and no unescaped template output carries user text. One inconsistency is noted.
Feature flags: all 36 are read somewhere. Which ones are permanently on can only be decided from production settings (maintainer input needed).
1. Fix
| Where | Problem | Proposed fix |
|---|---|---|
src/ForumRewrite/Analysis/DedalusPostAnalyzer.php:115,120 | new RuntimeException(...) inside namespace ForumRewrite\Analysis with no use RuntimeException;. It resolves to ForumRewrite\Analysis\RuntimeException, which doesn't exist. When the post-analysis prompt file is missing or empty, PHP raises a fatal "class not found" Error instead of the intended message, and catch (RuntimeException) blocks won't catch it. | Add use RuntimeException;. One line. |
2. Dead code in src/: no callers anywhere
Each was confirmed with a repo-wide search for the name, including string uses, templates, and JS. The search found no variable-method calls ($obj->$name()) or call_user_func in src/.
| Where | What | Proposed |
|---|---|---|
Http/BoardPageController.php:184 welcome(), :205 random() | QDB pages, superseded by Qdb/QdbExperience::welcome()/random(), which render the same templates | remove |
Http/ComposeAndAccountKeyController.php:73 composeThreadCompact() | no route calls it | remove |
Http/ProfilePageController.php:284 identityScripts() (private) | copy of Application::identityScripts(), never called here | remove |
Activity/ActivityService.php:888 primeCommitEvidence() | no callers | remove |
Docs/DocsPublication.php:295 assertPublicationInputs() | no callers | remove |
Host/HighTrafficRenderInput.php:35 sharedPath() | no callers | remove |
ReadModel/ProfileRepository.php:155 hasPendingDirectoryProfiles() | no callers | remove |
ReadModel/ThreadRepository.php:95 allReplyPostsByThreadId() | no callers | remove |
ReadModel/VerifiedAttribution.php:171 effectiveProfileSlug() | no callers | remove |
ReadModel/ViewerTagLookup.php:71 resetMemo() | no callers, not even tests | remove |
Retraction/CommitMap.php:212 isRecordPath() | no callers. A different ArchiveRecordCatalog::isRecordPath() is the one in use. | remove |
Scoring/SqliteFastScoreStore.php:538 workCounts() | no callers | remove |
Scoring/FastScoringConfig.php:81 headers() (private) | never called | remove |
Scoring/FastScoreStore.php find, latestScoredForPostContent, save | interface methods never called through the interface | review: callers may use the concrete class; decide whether the interface is still needed |
Agent/AgentReplyGenerationStore.php:32–57 (5 methods) | same pattern: interface methods with no callers through the interface | review, same question |
SiteConfig.php:27,32,37 unicodeAuthoredTextEnabled, emojiAuthoredTextEnabled, appVersionNotificationEnabled | static helpers, unused. The same-named values elsewhere come from feature flags. | remove |
ReadModel/TagPage.php:12, ReadModel/ThreadSearchPage.php:16 SIZE | constants never read. Both alias ThreadKeysetPage::SIZE. | remove |
Agent/AgentReplyFulfillmentService.php:28 $featureFlags | constructor property never read | review (also simplifies the constructor) |
Http/ForteBoardController.php:39, Llm/ExchangeVisibility.php:9, Llm/LlmExchangeRecorder.php:14, Qdb/QdbBoardPolicy.php:19 $repositoryRoot | constructor property never read | review |
Feedback/FeedbackItem.php:25 $sections | written, never read | review |
Canonical/ThreadLabelRecord.php:21–22, ThreadSubjectRecord.php:18–19 $actionAt, $intentId | parsed record fields never read | keep: parsers keep every header of a canonical record on purpose. Add a one-line comment on the record classes. |
Dead template
| Where | What | Proposed |
|---|---|---|
templates/pages/private_messages.php | not rendered anywhere. The mailbox page now uses private_message_list.php and private_message_conversation.php (see PrivateMessagePageController). | remove |
3. Reached only by tests
PHPStan was run with a "tests" exclusion, so these have callers only under tests/.
Keep (test hooks, named as such): SiteProfileRegistry::setProfilesForTesting, DeploymentSettings::resetForTesting, AssetFingerprint::resetHashCache, SignatureCheckCache::disable. Suggestion: add @internal for tests so the next pass skips them.
Review (look like leftover API that only tests still exercise):
Application::noStoreTimingHeaders,mergeResultTimings,activityCommitManifest: probably left behind when routes were extracted into controllers in Phase 2 of the earlier audit.LocalWriteService::setFeatureFlag: the real path isToolsPageControllerplus signed records.StaticArtifactBuilder::buildSingleRoute,StaticArtifactInvalidator::invalidateProfilePrivateMessageStore::markSeenThrough,conversationFor;PrivateMessageMailboxService::conversationImageBackup::cachedBytes,copyTree;ContentImportPlanner::dependencyVisitsPostRecord::rendersMarkdown,ViewerSession::isSignedIn,TagGrouping::limitPreview,PresentationSlotRegistry::all,ApiRouteCatalog::paths,PlatformDocsCatalog::resolvePath,PrivateConfigSchema::keysOmittedFromTemplateAgentResponseTask::defaultGenerationInput,SqliteAgentReplyGenerationStore::claimNextRequested,DedalusPostAnalyzer::decodeCompletionPayload,CommitEvidenceLookup::manifestReads/processes,FastScoreResult::scored,SqliteFastScoreStore::latestScoredForPostContentRecord fields read only by tests:
OperatorGrantRecord::$targetUsername,PostReactionRecord::$operation/$reason/$actionAt/$intentId,ThreadSubjectRecord::$operation/$reason,PublicKeyRecord::$fingerprint,SiteFeatureFlagsRecord::$updatedAt. These are keep for the same reason as above.
For each "review" item, the choice is: remove the method and its test, or keep it with a note saying why (for example, "diagnostic accessor used by benchmarks").
4. Assets, templates, scripts
Theme CSS (
theme-*.css): false positive.View/ThemeRegistrybuilds/assets/theme-<name>.cssfrom the registry, so a name search can't find them. Suggestion: a comment inpublic/assets/or a test asserting everytheme-*.csshas a registry entry, so this doesn't come up again.OpenPGP bundles: keep, documented in PR #139.
Scripts with no reference in
./v3, code, or reference docs:markdown_list_corpus_audit.py,markdown_task_corpus_audit.py: keep. Markdown renderer audit tools, still in use while the renderer is extended (maintainer, 2026-11-10); documented in their plan acceptance docs, which this scan skipped. Docstrings now say so (#156).import_scripture_source.py: documented inresources/scripture/README.md. Keep.qdb_archive_import_run.php: documented indocs/runbooks/qdb_archive_import.md. Keep.
Script triplets
publish_text.{php,pl,py}andstress_probe.{php,pl,py}: keep. Intentional (maintainer, 2026-11-10) and expected to grow; seedocs/reference/multi_language_scripts.md.
5. Duplication (jscpd, clones of 15+ lines / 100+ tokens)
Total: 851 duplicated lines out of 96,632 (0.88%).
Worth merging:
templates/partials/post_card.php↔thread_root_card.php: four clones, about 165 lines in total (header, meta, actions, footer). This is the biggest cluster. Shared partials would keep the two cards from drifting apart.Llm/AnthropicStructuredChatProvider.php↔OpenAiCompatibleStructuredChatProvider.php: three clones, about 110 lines (request, retry, and decode helpers). Candidate for a shared base or trait.
Smaller, lower priority:
scripts/delete_record.php↔thread_attributes.php↔archive_thread.php: record-file helpers (55 and 48 lines). Done: moved, unchanged, toscripts/lib/record_files.php, along with the copies inimport_repository_archive.phpandaudit_post_signatures.php.public/assets/paned_board_reader.js↔paned_users_reader.js↔paned_activity_reader.js: pane navigation (46 and 23 lines).Agent/SqliteAgentReplyGenerationStore.php↔Analysis/SqlitePostAnalysisStore.php: store boilerplate (34 lines).Repeats within a single file:
TagApiController(thread vs post tag, 28+28),WritePostAndIdentityApiController(3 × ~20),ProfilePresentationContent(30).theme_toggle.js↔thread_density_toggle.js(31 lines). Keep: sharing ~30 lines of menu keyboard handling would add an asset and a load-order dependency to every page, which costs more than the duplication.
6. Size
Longest methods in src/:
| Lines | Method |
|---|---|
| 1,083 | Application::handle |
| 333 | FeatureFlagRegistry::all (data table, fine) |
| 185 | Import/RepositoryArchive::extract |
| 172 | ReadModel/ReadModelSchema::statements (SQL list, fine) |
| 172 | Import/ContentImportPlanner::plan |
| 169 | Agent/AgentReplyFulfillmentService::publishForPost |
| 166 | Host/FrontController::handleRequest |
| 164 | Http/ForteActivityController::board |
| 160 | ReadModel/ReadModelBuilder::indexActivity |
Application::handle is the route dispatcher left after the Phase 2 extractions. Turning it into a route table is the natural next step for that file. LocalWriteService.php (5,073 lines) is large but split into many methods; split it by record type, as its own Railspike cycle.
7. Quick quality checks
| Check | Result |
|---|---|
declare(strict_types=1) missing in src/ | 0 files |
TODO/FIXME/XXX/HACK in src/ | 0 as whole words. The checklist's 257 was a loose case-insensitive substring count; it was mostly "legacy" (119 whole-word hits, largely the six intentional Legacy* compatibility classes) plus substring noise. Nothing to triage. |
Empty catch {} in src/ | 6. All are best-effort calls such as reporting, cache, or optional image lookup. Review: add a comment to each saying the failure is ignored on purpose. |
@ error suppression in src/ | 155, mostly @file_get_contents/@unlink/@mkdir with the return value checked. No action unless one turns up an unchecked result. |
| Shell commands built from strings | All 6 that concatenate a command string were traced: every caller passes literals or escapeshellarged arguments. No bug. The string-argument helpers (runGit(string $arguments), codebaseGitValue(string $arguments)) are easy to misuse later; consider array arguments, like LocalWriteService::runGitCommand(array $args). |
| Unescaped template output | 38 bare <?= $var ?>. All are numbers, fixed literals, or HTML already built by the renderer. One inconsistency: partials/feedback.php escapes $error but not $notice. Every notice today is a server-side literal, so it isn't exploitable, but escaping both would remove the trap. |
8. Needs maintainer input
Feature flags permanently on everywhere: keep. Flags exist to switch off a buggy feature and to let future instances leave a feature out, so "on everywhere" is not a reason to remove one (Ilya, 2026-11-10). All 36 are read by code.
Interface-only methods (
FastScoreStore,AgentReplyGenerationStore): delete and use the classes directly (Ilya, 2026-11-14); done in #223.
Suggested next PRs
Add
use RuntimeException;toDedalusPostAnalyzer, and escape$noticeinfeedback.php. Tiny, behavior-safe.Remove the "remove" rows in section 2 plus the dead template. One commit per subsystem.
Add notes for the "keep" items (record fields, test hooks, theme CSS loading).
Go through the "review" items in section 3 together.
Later, each as its own Railspike cycle: shared card partials, a shared LLM provider base, and a route table for
Application::handle.
Appendix: how this was run
The tools ran from a scratch directory. Nothing was added to the project. Composer couldn't reach GitHub from the sandbox, so the tools were cloned directly.
git clone --depth 1 https://github.com/phpstan/phpstan # provides phpstan.phar (2.1.x)
git clone --depth 1 https://github.com/shipmonk-rnd/dead-code-detector
# dead.neon: includes dcd/rules.neon; level 0; paths src, tests, templates, scripts, public (excluding public/assets);
# shipmonkDeadCode.detect deadMethods/deadConstants/deadEnumCases; usageExcluders.tests on tests/
php -d memory_limit=6G phpstan.phar analyse -c dead.neon -a dcd_autoload.php --error-format=raw
npx jscpd@4 src public/assets templates scripts --min-lines 15 --min-tokens 100 \
--ignore "**/openpgp*.js,**/qrcode-generator.js,**/*.map"
dcd_autoload.php registers a PSR-4 loader for ShipMonk\PHPStan\DeadCode\ → dcd/src/ and requires v3's autoload.php. It must be passed with -a, not bootstrapFiles, because the extension's services are loaded before bootstrap files run.
Known blind spot: the detector treats every tests/*Test.php method as unused because it doesn't recognise v3's own test runner. Those ~2,000 hits were ignored.
Doc review of the open decisions (2026-11-10)
A second pass read every doc, including docs/plans/, for each open item and for the code removed in #146.
Decision 7 (source map): keep serving it.
firefox_console_warnings_causes_v1.mdadded the map on purpose so DevTools stops logging a 404. The v6 bundle'ssourceMappingURLpoints to it, and production serves it (200). Browsers fetch maps only with DevTools open, so visitors don't pay for it.page_asset_performance_inventory.mdalready notes that static releases don't copy it.Decision 8 (one-time scripts): all three are live
./v3commands.inject_approval.phpis./v3 approval seed|approve(also used bytests/browser/calendar.mjs).backfill_unicode_risk.phpis./v3 unicode-risk-backfill, whichtask_queue_candidate_catalog.mdsays to rerun whenUNICODE_RISK_SCHEMA_VERSIONchanges.bake_legacy_timestamps.phpis./v3 bake-timestamps. Keep all three.Decision 2 (test-only methods): the plans confirm several ratings.
buildSingleRoutewas the on-miss static build until it was removed on purpose on Sep 21 (fee91dee), when builds left the request path.cachedByteswas added for the codebase-sizes page and later wrapped bycachedArchive.markSeenThroughwas the Step 3 contract for DM unread.setFeatureFlagis described as "the only feature-flag write path" in the flag rebuild fix. No doc changes a rating band.Decision 3 (interfaces): no doc gives a reason for
FastScoreStoreorAgentReplyGenerationStore, and nothing outsidesrc/implements them. No change.Decision 4 (unread properties): no doc mentions them. No change.
Removed in #146, still described in older plans:
qdb_classic_urls_checklist.mdsays QDB/addrenders throughcomposeThreadCompact(); it now goes throughQdbExperience, and the QDB tests pass.site_feature_flags_slices_v1.mdasked to keep theSiteConfigflag helpers as compatibility wrappers during its first slice; later slices moved every caller, so removing them was safe.ui_messages_step2_feature_description.mdalready calledpages/private_messages.phpunreachable. These are history and stay as written.
Correctness pass (2026-11-10)
Checklist §2.3 and §2.4: read-only scans of src/ and scripts/, then a hand trace of every hit that could reach user input or lose data.
One real bug, fixed in #162. ./v3 purge-history didn't check its journal writes. A failed refs-before.txt write let the purge continue, and a later restore then restored zero refs, cleared the journal and reported success. A failed phase write could leave a pruned repository marked restorable. Both writes now throw, and restore refuses an empty record.
SQL built from strings: no problems. 58 queries put PHP values into SQL text. Each value is one of these:
a placeholder list
a fixed fragment
an
int(enforced bystrict_types)a value checked against an allowed list (
ActivityService::activitySortSql, sort direction, mailbox column)
Page numbers go through PageNavigation::pageNumber, which accepts at most 6 digits. QDB search casts with (int) but clamps to the page count before building the offset.
File paths from requests: no problems.
Source viewer: an explicit list of record paths, then the real path must stay inside the repository.
Docs downloads: refuse
.., encoded slashes and dot segments.Images: a 64-character hash, re-checked against the file's checksum.
Assets: a strict name pattern, and the real path must sit directly in
assets/.High-traffic cache: only routes that pass
HighTrafficRoute::canonical.Feature-flag records:
[A-Za-z0-9._-]with no.., then the in-repository check.
git and gpg failures: no problems. Every call whose result matters checks the exit code (proc_get_status, exec exit argument or proc_close status), throws on short output, or fails closed. For example, RetractionAuthority refuses the actor when git returns nothing. SourceLabelRemoval reads an empty symbolic-ref result on purpose, as a detached HEAD.
Ignored write results: apart from the purge journal, the unchecked writes are best-effort logs (@), temporary files where the next step fails loudly, or lock releases. One is low priority and left as is:
ReadModelStaleMarker::mark()ignores a failed write. Every caller has just made a commit the read model hasn't seen, andensureReadModelalso rebuilds on a repository head mismatch, so a lost marker still leads to a rebuild.
Not covered: read-side false/null returns. Most are deliberate (string) casts with a default, so a useful scan needs a type checker (a higher PHPStan level), not grep.
Decisions and outcomes (2026-11-14)
Each decision was posted and answered in the ZenMemes review thread. Merge states were checked on 2026-11-14.
| # | Decision | Outcome | PR |
|---|---|---|---|
| 1 | Feature flags that are on everywhere | Keep all. A flag switches off a buggy feature and lets a future instance leave a feature out. | records: #153 |
| 2 | Methods only tests call | 13 rated 0.3 or lower removed; 5 test hooks kept and marked @internal. Of the middle eight, 3 removed, 3 kept with notes, 2 held (below). | #223, #227 (open) |
| 3 | Interfaces with one implementation | Deleted; callers use SqliteFastScoreStore and SqliteAgentReplyGenerationStore. | #223 (open) |
| 4 | Constructor values nothing reads | $featureFlags and $sections removed. Every $repositoryRoot kept ("it may come in handy"). | #227 (open) |
| 5 | Markdown audit scripts | Keep. They're live tools while the renderer is still being extended. | #156 |
| 6 | Scripts in three languages | Keep and document; more sets are planned. | #153 |
| 7 | OpenPGP source map | Keep serving it. It was added on purpose to stop a DevTools 404. | #158 |
| 8 | Root notes and one-time scripts | Notes moved into docs/plans/, todo.txt stays at the root. The three "one-time" scripts are live ./v3 commands and stay. | #156, #158, #159 |
Decision 2, middle eight, final calls:
Kept, with a note:
LocalWriteService::setFeatureFlag(the fallback for when records can't be signed),PostRecord::rendersMarkdown,ViewerSession::isSignedIn.Removed:
PrivateMessageStore::markSeenThrough,ImageBackup::cachedBytes,FastScoreResult::scored.Held, waiting on the maintainer:
StaticArtifactBuilder::buildSingleRouteandPresentationSlotRegistry::all. The maintainer approved removing both on a re-rating that missed their test use.buildSingleRouterenders one static page for 9 test files and fixtures, and is the entry point for a path-safety test.all()drives a test that checks every slot definition. The recommendation is now to keep both as@internaltest hooks.
Bugs found and fixed across the review, all merged: the missing RuntimeException import (#143), high-traffic mode not refreshing a thread after a reply (#147), GpgAvailabilityTest never running because it wasn't registered (#158), and history purge ignoring failed journal writes (#162).
Baseline failures seen on main during this work, not caused by the review: WriteApiSmokeTest::testLlmExchangeLinksAppearOnlyOnTheirPostDetailPages and LocalAppSmokeTest::testThreadCardWrapsMediaEmbedPreviewInDiv (failing on 9122adf0, 2026-11-14). Both pass on main as of 96462cfd (2026-11-17).
Server and browser text rules (2026-11-17)
Checklist §2.2, first pair. Cycle record: unicode_text_rule_parity.
UnicodeTextPolicy and isAllowedVisibleUnicodeCharacter in browser_signing.js are hand-synced twins with the same checks in the same order. A scan ran every code point through both sides in ASCII, Unicode and emoji modes. The browser was never stricter than the server, and the server accepts every text the browser rewrites.
Fixed: in ASCII mode the browser let 30 control characters through (C0 apart from tab, LF and CR, plus DEL), which the server then rejected. Pasted IRC colour and bold codes hit this. The browser now uses the server's range.
UnicodeTextRuleParityTestruns one corpus through both sides in all three modes, and fails if they drift apart again.Decision for the maintainer: Unicode version drift. The server's PCRE2 10.42 knows Unicode 14; current browsers know Unicode 16 or 17. About 15,000 newer characters, including emoji such as 🫨 and 🪿, pass the browser and are then rejected by the server as "control or format characters". The code agrees; the runtimes don't.
Left alone: the server trims outer
U+0000andU+000Band the browser does not, and a server withoutintlrejects every combining mark.
Lessons for the next pass
These caused real mistakes during this review.
List test callers before rating a member. The decision 2 ratings counted only production callers. Four "remove" calls turned out to be test seams:
limitPreview(a reference algorithm) andcopyTree(a fixture helper) moved totests/Support/, andbuildSingleRouteandPresentationSlotRegistry::allare held. For each candidate, ask what its tests use it for, not just whether production calls it.Run deletion searches without a display limit, and include strings. One search cut off its own output and missed a test caller. Another missed a method named in a
ReflectionMethodstring. Both surfaced only as test failures.Search every place a reference can live. The first pass skipped
docs/plans/, the./v3launcher's${ROOT}/scripts/...paths and provenance notes, and nearly removed live tools. These are now covered: the checklist's search rule,scripts/README.mdandScriptsIndexTest.Check that a new test actually runs.
tests/run.phplists test files explicitly;GpgAvailabilityTestwas reported as passing without ever running.TestFileRegistrationTestnow catches this.Check a PR's merge state before pushing to its branch. Twice, commits went to a branch whose PR had already merged and were stranded (restored in #160 and #163). Start a new branch from
origin/maininstead.Replay a test failure on
mainbefore calling it pre-existing, then look at why. The five "pre-existing" HighTraffic failures turned out to be a production bug (#147).