Skip to content

Codebase Rules

Wijanarko Putra Rajeb edited this page Oct 28, 2026 · 5 revisions

Codebase rules

Codebase Architecture & File Organization Rules

1. File Size Ceiling (Hard Limit: 350 Lines)

  • Maximum 350 Lines Per File: Every TypeScript and TSX file must strictly stay under 350 lines of code (wc -l result < 350).
  • Decompose before you hit the limit: When a file approaches the ceiling, split it immediately — never let it cross 350 and never "temporarily" exceed it.
  • Extraction patterns (pick the one that matches the code):
    • Large render blocks ➔ sub-components in the parent's kebab-case folder (git-panel/TreeView.tsx).
    • Stateful logic clusters ➔ custom hooks under src/client/hooks/<domain>/.
    • Pure functions / constants / validators ➔ src/shared/lib/<domain>/ modules.
    • Large callback objects / factories ➔ factory functions taking a single deps record (preserves closure semantics exactly).
    • Shared low-level utilities ➔ a sibling shared/ or utils.ts inside the feature folder.
  • Verify: find src -name "*.ts" -o -name "*.tsx" | xargs wc -l | grep -v total | awk '$1>350' must print nothing.

2. Folder & Filename Conventions (Clean Names)

  • Symmetrical folders: A component's folder mirrors its name in kebab-case, and the folder's main entry is index.tsx:
    • ChatTimeline ➔ src/client/components/workspace/chat-timeline/index.tsx
    • GitPanel ➔ src/client/components/workspace/git-panel/index.tsx
    • SessionSidebar ➔ src/client/components/layout/session-sidebar/index.tsx
    • ModelDropdown ➔ src/client/components/workspace/model-dropdown/index.tsx
  • Suffix-only filenames: When the folder already supplies the context, child files DROP the redundant prefix and keep only the suffix:
    • src/client/components/workspace/model-dropdown/Header.tsx — not ModelDropdownHeader.tsx
    • src/client/components/workspace/git-panel/TreeView.tsx — not GitTreeView.tsx
    • src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx — not BashPanel.tsx
    • src/client/hooks/chat/timeline/actions.ts — not useChatTimelineActions.ts
    • src/shared/lib/omp/rpc/manager.ts — not rpc-manager.ts
  • No duplicate basenames in the same folder: if two files would collide, move one to its correct domain folder or give it a distinguishing suffix (e.g. panels/SearchTool.tsx vs panels/SearchFs.tsx).
  • index is reserved for the folder's real entry point (the main component/hook implementation) — never a re-export barrel (see rule 3).
  • Naming case: kebab-case for folders and multi-word non-component files (active-project.ts, notification-sound.ts); PascalCase for Preact component files; useXxx prefix only when the file is a standalone reusable hook at a domain root.
  • Reusable or cross-cutting components belong in src/client/components/common/.
  • No empty, abandoned, or ghost folders (src/applet/, duplicate domain folders, etc.).

3. Direct, Explicit Imports (No Barrel Clutter)

  • Do NOT create re-export-only index.ts barrels inside src/client/components/, src/client/hooks/, or src/shared/lib/ — they pollute editor fuzzy-search and hide file origins.
  • index.tsx/index.ts is allowed ONLY when it contains the folder's actual implementation (the main component/hook), not a list of export ... from statements.
  • Import the concrete module explicitly via the @/ alias:
    • import { ChatTimeline } from '@/client/components/workspace/chat-timeline'; (folder entry)
    • import { Header } from '@/client/components/workspace/model-dropdown/Header';
    • import { useChatTimeline } from '@/client/hooks/chat/timeline';
    • import { toTitleCase } from '@/shared/lib/chat/title-case';
  • The only intentional barrel is src/shared/types/index.ts (the central type barrel).

4. Absolute Imports via @/ Alias (No Relative Imports)

  • All internal imports MUST use the @/ path alias (mapped to ./src/* in tsconfig.json, which Bun's bundler reads directly). Relative imports (./, ../) are forbidden in application code.
  • This applies to every import form: import, import type, export ... from, and side-effect imports.
  • Examples:
    • import { ChatTimeline } from '@/client/components/workspace/chat-timeline';
    • import type { OmpSession } from '@/shared/types/omp/session';
    • import { getDb } from '@/server/db.server';
    • import '@/client/tailwind.css';
  • Exceptions (keep relative):
    • Third-party packages and node built-ins (never prefixed with @/).
    • Assets outside src/ (e.g., package.json at the project root) — use a relative path.
  • The ~ alias is deprecated; use @/ exclusively.
  • Verify: grep -rnE "from '\.\.?/" src --include='*.ts' --include='*.tsx' --include='*.js' | grep -v node_modules must print nothing. src/cli/** is covered by this gate too — it is Bun-run plain ESM, so @/cli/... resolves there like everywhere else.

4b. Import Preact Directly (zero React packages)

  • Never write from 'react' or from 'react-dom' in src/. Import the runtime directly:
    • Hooks → import { useState, useEffect, useRef } from 'preact/hooks';
    • Components, context, portals, and React-shaped types → import { memo, Suspense, lazy, createContext, createPortal } from 'preact/compat';
    • Generic element/event types → import type { TargetedMouseEvent, TargetedKeyboardEvent } from 'preact';
  • Zero-react state: package.json contains no React packages and tsconfig.json carries no react* alias. The three former shim consumers were replaced: react-icons → lucide-preact + static brand SVGs (src/client/components/common/file-icon/), react-simple-code-editor → CodeMirror 6 in src/client/components/common/code-surface/ (see the editor bullet above), react-resizable-panels → the hand-rolled group/panel/separator trio in src/client/components/layout/desktop-layout/resizer/.
  • Adding dependencies: if a package imports 'react' in its published code, either pick a Preact-native alternative or hand-port the small surface you need — never re-introduce a react→preact alias to accommodate it.
  • Event types: Preact's MouseEvent/KeyboardEvent from preact/compat are generics requiring one type argument. Use TargetedMouseEvent<HTMLElement> for JSX handlers, and the DOM's own globalThis.MouseEvent/globalThis.KeyboardEvent for native addEventListener callbacks and xterm handlers.

5. Server vs Shared vs Client Modules

  • Three-way split. src/server/** is Bun-only (see the Runtime section at the top), src/client/** is browser-only, and src/shared/** is imported by both. Never import a node: builtin or bun:sqlite from src/client/** or src/shared/lib/**; if a shared module needs one, it belongs in src/server/lib/** instead.
  • Non-UI modules MUST be grouped into domain subfolders — never dumped flat in the root of src/client/hooks/, src/client/data/, src/server/lib/, src/shared/lib/, or src/shared/types/.
  • src/client/hooks/<domain>/: chat/, ui/, workspace/, browser/, models/, settings/. Split further when a family grows: chat/timeline/ (timeline state + actions), chat/omp/ (live agent bridge), settings/providers/ (provider settings state, API calls, actions, messages).
  • src/shared/lib/<domain>/: chat/, code/, fs/, markdown/, models/, omp/, workspace/. omp/ splits into core/, rpc/, session/, config/; models/ splits into provider/ for the provider family (dialect, presets, models, connection, cleanup, label, glyph).
  • src/server/lib/<domain>/: the same domain tree, holding only the modules that touch Node/Bun builtins or the database. A server family splits the same way (omp/session/usage/ holds the aggregator and its presentation shaping).
  • src/client/data/<domain>/: settings/, samples/, mock/, models/, theme/, agent-data/, context-data/.
  • src/shared/types/<domain>/: group related interfaces (settings/, omp/); truly cross-cutting types stay at the root.
  • Grouping changes are atomic: move the files AND update every importer in the same change.

6. Pure UI Components & Semantic Separation

  • src/client/components/ is for Preact UI (.tsx). Co-located pure helpers are allowed when scoped to that feature, but must be .ts and live under the feature folder or its shared/ (e.g. tool-renderers/shared/detect-format.ts, editor/utils.ts).
  • Anything reusable beyond a single feature belongs in src/shared/lib/, never in a component folder.
  • Dedicated non-UI directories:
    • Hooks (src/client/hooks/<domain>/): Custom Preact hooks.
    • Data (src/client/data/<domain>/): Mock or static datasets.
    • Types (src/shared/types/<domain>/): Domain interfaces and types.
    • CLI (src/cli/): The kabmo command-line entry (kabmo.js) and its lib/ (arg parsing, process lifecycle, registry, serve/update/stop/restart/status/logs). These stay .js (plain ESM, no build step) and run under Bun via the #!/usr/bin/env bun shebang. pkgRoot is resolved two levels up from src/cli/kabmo.js; keep that depth if the file ever moves.

7. Domain Types Architecture

  • Domain data models and shared TypeScript interfaces must be organized cleanly under src/shared/types/:
    • workspace.ts — folders, session entities, and sorting types
    • fs.ts — file explorer node trees, opened files, and search result items
    • git.ts — git changes, branch lists, and view mode states
    • chat.ts — messages, agent actions, monologue, and attachments
    • settings/ — settings state and per-category settings shapes (agent.ts, command.ts, mcp.ts, project.ts, provider.ts, skill.ts, state.ts)
    • omp/ — oh-my-pi bridge types (session.ts, agent.ts)
    • index.ts — central export barrel for all types (import type { ... } from '@/types')

8. Verification Requirements

  • Every change must pass:
    1. bun run lint (tsc --noEmit) without errors.
    2. bunx tsc --noEmit --noUnusedLocals --noUnusedParameters without errors.
    3. find src -name "*.ts" -o -name "*.tsx" | xargs wc -l | grep -v total | awk '$1>350' no file over 350 line codes
    4. Production build verification (bun run build).
  • Unused Code Check (MANDATORY before task completion): Before declaring any task done, verify no unused imports, locals, or dead props were introduced or left behind:
    • Fix every TS6133 (declared but never read), TS6192 (all imports unused), TS6196 (declared but never used), and TS6198 (all destructured elements unused) error.
    • Remove unused imports (icons, types, components) and unused destructured props/state — do not leave dead code behind.
    • If a component's props/state become unused because a feature was stubbed or removed, strip them from the interface, the destructure, and every call-site in the same change.
    • Do NOT ship import React from 'react' in .tsx files — the Preact JSX transform makes it unnecessary (keep named imports like useState).
  • Structural Checks (MANDATORY for refactors that move/rename files):
    • No file exceeds 350 lines (rule 1 command).
    • No relative imports remain (rule 4 command).
    • No duplicate basenames inside the same folder.
    • Every moved/renamed file's importers are updated in the same change; grep for the old path returns nothing.

9. Layout & Panel Resizing

  • Two width units, deliberately. The sidebar is stored in pixels — it holds a session list, which does not get more useful on a wider monitor. The editor and the right panel are stored as a share of the group's available area (a fraction), because a pixel width is only right on the display it was dragged on. A slot may carry both; the fraction wins when the area is known, and the px value is what it renders at before then.
  • Sizes are px at the resizer boundary. The hand-rolled resizer (src/client/components/layout/desktop-layout/resizer/) is px-only end to end: fixed panels get a px flex-basis and one filler panel absorbs the remainder. A fraction is resolved to px before it reaches a Panel — never pass a percentage string into defaultSize/minSize, because toPx parses it with parseFloat and "45%" would silently become 45px.
  • The panel ceiling is dynamic, not a constant, and the editor + right panel are a COUPLED PAIR. resolvePanelWidth (src/shared/lib/workspace/panel-widths.ts) caps a panel by the smaller of three things: its own max (PAIR_MAX_FRACTION = 0.6), the pair total minus what the sibling reserves (PAIR_MAX_TOTAL_FRACTION = 0.7), and the group budget (available − chat floor − the sibling's reserved width − handles). The defaults are editor 0.4 + right 0.3 = 0.7, so growing one forces the other down and neither can reach 0.6 while the other is open. The right panel has ONE default fraction for every view (DEFAULT_RIGHT_PANEL_FRACTION) — a per-view table cannot coexist with the pair, because the two defaults must sum to the total (a 0.6 terminal beside a 0.4 editor is 1.0); views differ only by their floor and their remembered width. WorkspacePanels resolves the RIGHT panel first (reserving the editor's WANTED share), then the editor (reserving the right panel's ACTUAL width) — that asymmetry is what makes an editor asking past its default push the right panel down first, with the pair still summing to 0.7. Reserving only a sibling's FLOOR is the shape that broke: the two declared widths summed past the group, flexbox shrank BOTH, and the right panel rendered 15px under its share (measured at 1440 with both open: editor asked 507 / rendered 477, right asked 245 / rendered 230). Verified in the browser at 2K: defaults render editor 40% / right 30%; an editor wanting 0.5 renders 50% / right 20%; an editor wanting 0.9 caps at 60%. The pair cap is computed in PIXELS and ROUNDED (0.7 × 4000 is 2799.9999… in binary floating point).
  • One remembered width PER PANEL, never per group: the sidebar, the editor panel (a separate width for source tabs and for diff tabs), and each of the eleven right-panel views (context, files, search, git, wiki, terminal, user-browser, browser, usage, todo, plan) each own their width — the sidebar's lives in its own module (see the GLOBAL rule below), the rest in src/shared/lib/workspace/panel-widths.ts (data) and src/client/hooks/workspace/panel-widths.ts (state); the single default fraction, px defaults, per-view minimums, and the view list live in src/shared/lib/workspace/right-panels.ts. Sharing one number between panels — or resetting a panel to a hard-coded width when it is toggled or switched — is exactly the bug this shape exists to prevent.
  • The sidebar's width is GLOBAL, and that is the one exception to "per session". It lives in app_settings.omp_sidebar_width (src/shared/lib/workspace/sidebar-width.ts + src/client/hooks/workspace/sidebar-width.ts), beside the sidebar's other cross-session state (omp_sidebar_expanded_sessions, omp_sidebar_sort) — never in layout.panelWidths. The sidebar lists the same sessions in every chat and only the highlight moves, so a width that changed when the user picked a different session read as the layout jumping on its own. It was not always global: 0004c95 (2026-09-23) swept the sidebar into the per-session map along with the editor and the right panel, which had a real reason to be there, and 9d361a9 (2026-10-08) then dropped the desktopLayoutSizes seed that had been keeping a dragged width global — so a left slot existed in layout.panelWidths for two weeks and 120 sessions on the author's install carry the same seeded 351 while a handful carry a local drag. resolveSidebarWidth therefore migrates by PRECEDENCE — stored setting, else the retired GLOBAL desktopLayoutSizes.left, else the open session's slot — because adopting a session slot first would move the sidebar 351 → 500 on the first switch. A left slot is deleted from a session blob on the first open after the upgrade and dropped by mergePanelWidths, so no stored state keeps a second answer.
  • Widths are per session for the editor and the right panel, and a new session starts EMPTY. They live in session_ui_state under layout.panelWidths, beside the rest of a session's layout state (layout.activeRightPanel, layout.showRightPanel, layout.showLeftPanel, layout.userToggledEditor, layout.openedFiles), so switching sessions restores the layout that session was left in. A session that has never been resized has no panelWidths at all, so every panel resolves from its own default fraction (DEFAULT_EDITOR_FRACTIONS, DEFAULT_RIGHT_PANEL_FRACTION) or px fallback. There is deliberately no global seed for these — a former app_settings.desktopLayoutSizes carried the last global drag into every new session, and since the per-session migration nothing wrote it, it froze at a stale value and pinned a new session's editor to its 320px floor (measured) while the diff tab opened normally. Writing to it could not repair it either: the write would have to run before the session's own blob loads and would clobber it with the global value. The SIDEBAR is the exception and is global — see the rule above.
  • A pending new-… session's UI state is loaded like any other session's, because it is persisted like any other. The id is what the URL carries (?sessionId=new-…), so a reload of a pending chat — a dev-HMR reload, or a second tab — re-enters that slot with a row already on the server. SessionStateProvider used to short-circuit it as "fresh, nothing stored yet" and mark it ready without a fetch; every consumer then showed its fallback (the repo picker reset to the workspace root, the right panel jumped back to files) and the next write destroyed the stored blob, because persistSession posts the WHOLE in-memory map — a state that was never loaded persisted as one key. markSessionReady existed only for that short-circuit and is gone; the only special case left is spawn adoption (migrateSessionState), which reads the transient slot's now-hydrated cache.
  • A private useSessionState copy re-reads when the store REPLACES a session's blob — and only then. Every caller holds its own useState, so two components on one key never see each other's writes; that is deliberate (a panel width belongs to one component). But ready does not move when a spawn adoption migrates the pending slot onto the omp UUID, so the copy kept the fallback it read on the commit the URL changed and every right-panel view the user had opened collapsed at the first send of a new chat (measured through a real provider mount: true:git → true:files). subscribeSessionReplaced (shared/lib/workspace/session-state/listeners.ts) is a SECOND bus, separate from the per-slot one, fired by the wholesale paths only — loadSession, hydrateSession, migrateSessionState (both ids) and forgetSession. A per-slot write deliberately does not fire it: announcing one would make every editor and panel copy in the app re-read on every keystroke elsewhere.
  • A resize drag is deferred. The separator moves a ghost guide line and re-applies the real width at most every RESIZE_FOLLOW_INTERVAL_MS; the panel's own 200ms width transition smooths the steps. Applying the width on every pointermove reflows an xterm buffer, a CodeMirror document and a browser iframe per frame, for a width the user is still choosing.
  • A collapsed panel stays mounted. Panel's collapsed prop renders it at zero width and marks it data-panel-collapsed, so its state (tree expansion, terminal buffer) survives and the width transition has something to animate. The separator walks past collapsed panels when it resolves its neighbours — pairing a drag against a zero-width panel whose registry floor still reads 320 clamps every delta to zero and kills the handle.
  • Restore through props, not imperative rebuilds: every panel's defaultSize is derived from the remembered width for its current slot, and Panel adopts a changed defaultSize itself — that covers a right-panel view switch and an editor source↔diff switch, both of which keep the panel mounted while only its width slot changes. No layout cache exists to go stale. Append an entry here if a new resizable group is introduced.

10. Route Organization & Domain Grouping

  • Domain-Based Subdirectories: Routes under src/server/routes/ MUST be organized and grouped into subdirectories matching their functional domain (e.g., src/server/routes/settings/, src/server/routes/chat/, src/server/routes/fs/, src/server/routes/terminal/, src/server/routes/telemetry/, src/server/routes/sessions/, src/server/routes/files/, src/server/routes/folders/).
  • No Monolithic Flat Folder Clutter: Do NOT dump API endpoints loosely in the root of src/server/routes/ as flat files. src/server/routes/index.ts is the only file that enumerates domains; every domain folder owns its own modules and never imports a sibling domain.
  • One Elysia plugin per domain: Each domain folder exports HandlerBinding[] built from its route modules (see src/server/lib/route-adapter.ts). Route modules keep the ported Remix shape — an exported loader (GET) and/or action (mutating verbs) — so status codes and payloads stay identical to the pre-migration API. Prefixes are declared once, in routes/index.ts.

11. Environment Data Modes (MOCK=true vs MOCK=false)

  • MOCK=true (Simulation & Demo Mode):
    • All features and loaders utilize rich predefined datasets and presets from src/client/data/ (simulated demo chats, token telemetry ranges, agent/project presets).
    • Database seeding automatically injects sample workspace folders, demo commit sessions, and file structures.
  • MOCK=false (Real Data Mode):
    • The application operates strictly against real backend resources and real SQLite database persistence.
    • No synthetic sample sessions, fake dialogues, or hardcoded mock files are auto-injected.
    • Managed globally through Bun.env.MOCK and verified via @/server/mock.server.

Clone this wiki locally