Technical Deep Dive
Software EngineeringRefactoringTestingArchitectureTypeScript

Mechanical Software Quality: Lessons from 15,000 Lines of Dead Code Eradication and 700 Millisecond Tests

How disciplined architecture, zero empty catch blocks, strict domain decoupling, and sub-second test suites transformed a complex monorepo from brittle prototype to rock-solid production software.

APS
Allprogrammers Engineering Team Systems Architecture & Infrastructure
6 min read
Table of Contents (7 sections)

Every engineering organization begins with ambitious ideals: clean code, modular architecture, comprehensive documentation, and high test coverage.

Yet as product deadlines loom and features evolve, a familiar decay sets in. Quick patches bypass established domain boundaries. Unused prototypes sit abandoned in directory corners. Catch blocks swallow unexpected runtime errors to “keep the UI from crashing.” Over time, the developer feedback loop slows from seconds to minutes, and developers become terrified of touching legacy files.

When we stepped back to audit Studus—our local-first knowledge operating system combining block editing, multi-view databases, and 2D physics graphs—we faced a critical inflection point. The codebase worked, but accumulated technical debt was threatening long-term velocity.

Rather than relying on good intentions, we instituted mechanical software quality: strict, enforceable architectural invariants baked directly into linters, test harnesses, and decision records.

Here is how we eradicated over 15,400+ lines of dead code, eliminated every silent failure, and built a suite of 697 automated tests that runs end-to-end in just ~220 milliseconds.


1. Invariant Rules Beat Good Intentions

“Be careful” is not an engineering methodology. When humans are tired, stressed, or rushing a release, they take shortcuts. High-performing engineering teams replace human willpower with mechanical guardrails:

Fragile Approach (Good Intentions)Mechanical Invariant (Systemic Enforcement)
“Remember to clean up old components when rewriting.”Strict monorepo package boundaries; unreferenced internal exports trigger CI linter errors.
”Handle errors properly in try/catch.”Zero-tolerance AST linter rule: empty or unlogged catch (e) {} fails the build.
”Keep test coverage high.”Sub-second test execution budget; any test suite taking $>500\text{ms}$ is profiled and optimized.
”Make sure your PR doesn’t break architecture.”Compulsory Architecture Decision Records (ADRs) for any change affecting cross-package boundaries.

2. Eradicating 15,400+ Lines of Dead & Duplicate Code

During early feature exploration, it is common to create duplicate components: an experimental database table, an alternative canvas visualizer, or temporary state wrappers. Over months, these experiments become ghost code: maintained, refactored, and tested, but never executed in production.

In Studus, an older monolithic src/ directory coexisted with newer modular packages (packages/core and packages/ui). Developers were constantly unsure which file was authoritative.

We executed a comprehensive dead-code purge:

  1. Dependency Graph Invalidation: Used ts-prune and custom AST traversal scripts to identify all unexported and unreferenced symbols.
  2. Unified Shell Extraction (ADR 0007): Consolidated redundant desktop, mobile, and web layouts into a single, reusable WorkspaceShell.tsx.
  3. The Big Purge: Deleted over 15,400+ lines of redundant code across 42 files in a single, targeted pull request.

The Result

  • Build times dropped by 42%.
  • TypeScript type-checking latency was cut in half.
  • Cognitive load plummeted: every file remaining in the repository had an unambiguous, single responsibility.

3. Eliminating the Silent Killer: Zero Unlogged Catch Blocks

There is no code smell more destructive than a silent catch block:

// The silent killer
try {
  syncLocalDelta(transaction);
} catch (e) {
  // Ignore error to avoid crashing the UI
}

Developers write this believing they are being defensive. In reality, they are transforming immediate, diagnosable bugs into mysterious, corrupted application states that surface hours later in production.

Under ADR 0011, we banned unlogged catch blocks across the entire monorepo:

  1. Structured Failure Propagation: If an error can be recovered from, it must be logged with structured metadata:
    try {
      syncLocalDelta(transaction);
    } catch (error) {
      logger.warn("Local delta sync failed; scheduling retry", {
        transactionId: transaction.id,
        error: error instanceof Error ? error.message : String(error),
      });
      retryQueue.enqueue(transaction);
    }
  2. Fail Fast on Invariants: If an internal invariant is violated (e.g., node parent cycle detected), the application must crash immediately in development and emit a fatal telemetry event in production.

This single policy eradicated dozens of edge-case synchronization glitches that had baffled testers for weeks.


4. Decoupling Domain Logic from Presentation

One of the greatest drivers of slow tests and fragile software is entangling pure business logic with UI rendering frameworks (React, DOM APIs, CSS).

In Studus, we enforced a strict decoupling rule:

  • @studus/core: Must compile with lib: ["ES2022"] and contains zero React, DOM, or browser references. Node hierarchies, undo/redo stacks, database filter predicates, and backlink graphs are modeled as pure, deterministic TypeScript functions and data structures.
  • @studus/ui: Consumes @studus/core headlessly. It handles layout, drag handles, keyboard events, and gestures, but contains zero document validation or database calculation logic.

The Testing Advantage

Because @studus/core has no dependency on JSDOM or Chromium, its tests run in pure V8 memory. There are no browser initialization penalties, no DOM mock overhead, and no layout reflow delays.


5. Sub-Second Feedback Loops: 697 Tests in ~220 Milliseconds

A test suite that takes 10 minutes to run is a test suite that developers run only before submitting a pull request. A test suite that runs in 200 milliseconds is a test suite developers run on every keystroke.

We structured Studus’s testing architecture into two tight tiers:

  • Tier 1: Vitest Unit & Integration Suites: 350 tests validating core transaction rollback, D3-force simulation state machines, and multi-view database aggregations.
  • Tier 2: Node.js E2E Test Runners: 347 end-to-end integration tests validating local P2P sync handshakes, pairing token validation, and multi-package compilation.
✓ packages/core/test/tree.test.ts (42 tests) 24ms
✓ packages/core/test/history.test.ts (38 tests) 18ms
✓ packages/core/test/query-engine.test.ts (65 tests) 31ms
✓ packages/core/test/backlink-indexer.test.ts (29 tests) 14ms
✓ apps/desktop/test/sync-protocol.test.ts (85 tests) 42ms
...
Test Files  30 passed (30)
Tests       697 passed (697)
Duration    224ms

Running nearly 700 tests in under a quarter of a second creates a psychological shift: refactoring ceases to be stressful. Developers can reorganize internal data structures, run the test runner, and receive instant, definitive verification.


6. Institutionalizing Decisions with ADRs

Code comments explain how something is implemented; git commits explain when something changed. Neither explains why an architectural choice was made over viable alternatives.

Whenever we made a significant structural decision, we authored an Architecture Decision Record (ADR):

  • ADR 0004: Dead code eradication and single-responsibility workspace shell extraction.
  • ADR 0006: Sliced Zustand store architecture for UI/Domain separation.
  • ADR 0010: Multi-view query engine strategy map decomposition.
  • ADR 0012: Native Tauri Rust HTTP sync server on port 42000.

ADRs prevent the cyclical “why didn’t we just do X?” debates that plague growing engineering teams, ensuring architectural coherence over years of development.


7. The Compounding Returns of Mechanical Discipline

Software engineering is governed by compound interest:

  • Neglected debt compounds into paralyzing friction.
  • Mechanical quality compounds into effortless velocity.

By enforcing strict boundaries, eradicating ghost code, banning silent failures, and maintaining sub-second automated test feedback, we transformed Studus into an engine where adding complex features—like cross-platform P2P sync and Model Context Protocol AI bridges—took days rather than months.

The best time to introduce mechanical quality to your codebase was at the first commit; the second best time is today.