Repository navigation
Codebase Rules
Wijanarko Putra Rajeb edited this page Oct 28, 2026
·
5 revisions
-
Maximum 350 Lines Per File: Every TypeScript and TSX file must strictly stay under 350 lines of code (
wc -lresult< 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
depsrecord (preserves closure semantics exactly). - Shared low-level utilities ➔ a sibling
shared/orutils.tsinside the feature folder.
- Large render blocks ➔ sub-components in the parent's kebab-case folder (
-
Verify:
find src -name "*.ts" -o -name "*.tsx" | xargs wc -l | grep -v total | awk '$1>350'must print nothing.
-
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— notModelDropdownHeader.tsx -
src/client/components/workspace/git-panel/TreeView.tsx— notGitTreeView.tsx -
src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx— notBashPanel.tsx -
src/client/hooks/chat/timeline/actions.ts— notuseChatTimelineActions.ts -
src/shared/lib/omp/rpc/manager.ts— notrpc-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.tsxvspanels/SearchFs.tsx). -
indexis 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;useXxxprefix 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.).
- Do NOT create re-export-only
index.tsbarrels insidesrc/client/components/,src/client/hooks/, orsrc/shared/lib/— they pollute editor fuzzy-search and hide file origins. -
index.tsx/index.tsis allowed ONLY when it contains the folder's actual implementation (the main component/hook), not a list ofexport ... fromstatements. - 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).
-
All internal imports MUST use the
@/path alias (mapped to./src/*intsconfig.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.jsonat the project root) — use a relative path.
- Third-party packages and node built-ins (never prefixed with
- The
~alias is deprecated; use@/exclusively. -
Verify:
grep -rnE "from '\.\.?/" src --include='*.ts' --include='*.tsx' --include='*.js' | grep -v node_modulesmust print nothing.src/cli/**is covered by this gate too — it is Bun-run plain ESM, so@/cli/...resolves there like everywhere else.
-
Never write
from 'react'orfrom 'react-dom'insrc/. 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';
- Hooks →
-
Zero-react state: package.json contains no React packages and
tsconfig.jsoncarries noreact*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 insrc/client/components/common/code-surface/(see the editor bullet above),react-resizable-panels→ the hand-rolled group/panel/separator trio insrc/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/KeyboardEventfrompreact/compatare generics requiring one type argument. UseTargetedMouseEvent<HTMLElement>for JSX handlers, and the DOM's ownglobalThis.MouseEvent/globalThis.KeyboardEventfor nativeaddEventListenercallbacks and xterm handlers.
-
Three-way split.
src/server/**is Bun-only (see the Runtime section at the top),src/client/**is browser-only, andsrc/shared/**is imported by both. Never import anode:builtin orbun:sqlitefromsrc/client/**orsrc/shared/lib/**; if a shared module needs one, it belongs insrc/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/, orsrc/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 intocore/,rpc/,session/,config/;models/splits intoprovider/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.
-
src/client/components/is for Preact UI (.tsx). Co-located pure helpers are allowed when scoped to that feature, but must be.tsand live under the feature folder or itsshared/(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/): Thekabmocommand-line entry (kabmo.js) and itslib/(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 bunshebang.pkgRootis resolved two levels up fromsrc/cli/kabmo.js; keep that depth if the file ever moves.
-
Hooks (
- 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')
-
- Every change must pass:
-
bun run lint(tsc --noEmit) without errors. -
bunx tsc --noEmit --noUnusedLocals --noUnusedParameterswithout errors. -
find src -name "*.ts" -o -name "*.tsx" | xargs wc -l | grep -v total | awk '$1>350'no file over 350 line codes - 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), andTS6198(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.tsxfiles — the Preact JSX transform makes it unnecessary (keep named imports likeuseState).
- Fix every
-
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.
- 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 aPanel— never pass a percentage string intodefaultSize/minSize, becausetoPxparses it withparseFloatand"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.WorkspacePanelsresolves 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 × 4000is2799.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 insrc/shared/lib/workspace/panel-widths.ts(data) andsrc/client/hooks/workspace/panel-widths.ts(state); the single default fraction, px defaults, per-view minimums, and the view list live insrc/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 inlayout.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, and9d361a9(2026-10-08) then dropped thedesktopLayoutSizesseed that had been keeping a dragged width global — so aleftslot existed inlayout.panelWidthsfor two weeks and 120 sessions on the author's install carry the same seeded 351 while a handful carry a local drag.resolveSidebarWidththerefore migrates by PRECEDENCE — stored setting, else the retired GLOBALdesktopLayoutSizes.left, else the open session's slot — because adopting a session slot first would move the sidebar 351 → 500 on the first switch. Aleftslot is deleted from a session blob on the first open after the upgrade and dropped bymergePanelWidths, 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_stateunderlayout.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 nopanelWidthsat 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 formerapp_settings.desktopLayoutSizescarried 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.SessionStateProviderused 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 tofiles) and the next write destroyed the stored blob, becausepersistSessionposts the WHOLE in-memory map — a state that was never loaded persisted as one key.markSessionReadyexisted 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
useSessionStatecopy re-reads when the store REPLACES a session's blob — and only then. Every caller holds its ownuseState, so two components on one key never see each other's writes; that is deliberate (a panel width belongs to one component). Butreadydoes 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) andforgetSession. 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 everypointermovereflows 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'scollapsedprop renders it at zero width and marks itdata-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
defaultSizeis derived from the remembered width for its current slot, andPaneladopts a changeddefaultSizeitself — 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.
-
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.tsis 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 (seesrc/server/lib/route-adapter.ts). Route modules keep the ported Remix shape — an exportedloader(GET) and/oraction(mutating verbs) — so status codes and payloads stay identical to the pre-migration API. Prefixes are declared once, inroutes/index.ts.
-
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.
- All features and loaders utilize rich predefined datasets and presets from
-
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.MOCKand verified via@/server/mock.server.
Using Kabmo
How it is built
- Architecture
- Runtime and toolchain
- App shell and layout
- Chat stream and tools
- omp engine and settings
- Plugins, skills and automation
- Desktop integration
- Workspace panels
- Providers
- Harnesses
- Tool panels
Shipping it
History