---
name: architecture-guidance
description: Provides guidance on design decisions, architecture choices, and implementation approaches that align with the project's approved tech stack and patterns.
title: architecture-guidance
canonical_url: https://skilld.dev/gh/corey-alix/dwp-hours/architecture-guidance
last_updated: 2026-10-07T01:30:59.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install corey-alix/dwp-hours/architecture-guidance`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/architecture-guidance`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/corey-alix/dwp-hours/architecture-guidance) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/architecture-guidance`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/architecture-guidance --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/architecture-guidance --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Architecture and Design Guidance

## Description

Provides guidance on design decisions, architecture choices, and implementation approaches that align with the project's approved tech stack and patterns.

## Trigger

Activated when users ask about design decisions, architecture choices, or implementation approaches.

## Response Pattern

1. Reference existing codebase patterns and conventions
2. Suggest solutions that align with the approved tech stack (vanilla TS, Express, sql.js)
3. Consider WSL compatibility requirements for database choices
4. Follow established API patterns and frontend structure
5. Explain trade-offs and rationale for recommendations

## Examples

- "How should I structure this new API endpoint?"
- "What's the best way to handle this frontend state?"
- "Should I use a different database approach?"

## Additional Context

This skill ensures architectural decisions maintain consistency with the project's vanilla TypeScript approach and WSL compatibility requirements.

## High-Level Architecture Overview

### Technology Stack

- **Frontend**: Vanilla HTML, CSS, and TypeScript (no frameworks)
- **Backend**: Node.js with Express.js framework
- **Database**: SQLite with sql.js driver for WSL compatibility
- **ORM**: TypeORM with DataMapper pattern
- **Development Server**: http-serve for local development
- **Build System**: TypeScript compilation with npm scripts
- **Testing**: Vitest (unit), Playwright (E2E)

### Database Schema

The application uses TypeORM entities for data persistence:

- `Employee`: Employee information and authentication
- `PtoEntry`: PTO time-off entries with date ranges and hours
- `Acknowledgement`: Monthly review acknowledgements
- Additional entities for admin panel functionality

#### Core Tables

**employees**

- `id` (INTEGER PRIMARY KEY): Auto-incrementing employee ID
- `name` (TEXT): Employee full name
- `identifier` (TEXT UNIQUE): Unique employee identifier
- `pto_rate` (REAL): PTO accrual rate per hour (default 0.71)
- `carryover_hours` (REAL): Carried over PTO hours from previous year
- `hire_date` (DATE): Employee hire date
- `role` (TEXT): Employee role (default 'Employee')
- `hash` (TEXT): Password hash for authentication

**pto_entries**

- `id` (INTEGER PRIMARY KEY): Auto-incrementing entry ID
- `employee_id` (INTEGER): Foreign key to employees table
- `date` (TEXT): Date of PTO entry (YYYY-MM-DD format)
- `type` (TEXT): PTO type ('Sick', 'PTO', 'Bereavement', 'Jury Duty')
- `hours` (REAL): Hours used
- `created_at` (DATETIME): Entry creation timestamp

**monthly_hours**

- `id` (INTEGER PRIMARY KEY): Auto-incrementing record ID
- `employee_id` (INTEGER): Foreign key to employees table
- `month` (TEXT): Month in YYYY-MM format
- `hours_worked` (REAL): Total hours worked in the month
- `submitted_at` (DATETIME): Submission timestamp

**acknowledgements**

- `id` (INTEGER PRIMARY KEY): Auto-incrementing acknowledgement ID
- `employee_id` (INTEGER): Foreign key to employees table
- `month` (TEXT): Month in YYYY-MM format
- `acknowledged_at` (DATETIME): Acknowledgement timestamp

**admin_acknowledgements**

- `id` (INTEGER PRIMARY KEY): Auto-incrementing admin acknowledgement ID
- `employee_id` (INTEGER): Foreign key to employees table
- `month` (TEXT): Month in YYYY-MM format
- `admin_id` (INTEGER): Foreign key to employees table (admin who acknowledged)
- `acknowledged_at` (DATETIME): Admin acknowledgement timestamp

**sessions**

- `token` (TEXT PRIMARY KEY): Session token
- `employee_id` (INTEGER): Foreign key to employees table
- `expires_at` (DATETIME): Session expiration timestamp

#### Database Constraints and Indexes

- Foreign key constraints enforce referential integrity
- Unique constraints on employee identifiers and session tokens
- Performance indexes on foreign keys and commonly queried fields
- CHECK constraints on PTO entry types

### ORM Patterns

#### TypeORM Configuration

- **Driver**: sql.js for WSL compatibility
- **Synchronization**: Disabled (`synchronize: false`) - schema managed manually via SQL files
- **Auto-save**: Enabled for automatic database persistence
- **Logging**: Disabled in production

#### Entity Design Patterns

- **Active Record Pattern**: Not used - Data Mapper pattern preferred
- **Repository Pattern**: Used through TypeORM repositories for data access
- **Entity Relationships**:
  - `@OneToMany` for parent-child relationships (Employee → PTO entries)
  - `@ManyToOne` with `@JoinColumn` for foreign key relationships
  - Lazy loading by default, explicit joins for complex queries

#### Data Access Layer (DAL)

- **Repository Injection**: DAL classes receive DataSource and create repositories
- **Business Logic Separation**: Validation and calculations in dedicated modules
- **Transaction Management**: Explicit transactions for multi-table operations
- **Query Building**: TypeORM query builder for complex queries with joins and conditions

#### Common ORM Usage Patterns

```typescript
// Repository usage
const employeeRepo = dataSource.getRepository(Employee);
const ptoEntryRepo = dataSource.getRepository(PtoEntry);

// Simple queries
const employee = await employeeRepo.findOne({ where: { id: employeeId } });

// Relations loading
const employeeWithEntries = await employeeRepo.findOne({
  where: { id: employeeId },
  relations: ["ptoEntries"],
});

// Complex queries with joins
const entries = await ptoEntryRepo.find({
  where: { employee: { id: employeeId } },
  relations: ["employee"],
});
```

### Service Layer Architecture

To maintain separation of concerns and improve testability, components must not directly instantiate or use APIClient. Instead, implement a service layer with dependency injection:

#### Service Layer Pattern

```typescript
// Service interface
interface IEmployeeService {
  getEmployees(): Promise<Employee[]>;
  updateEmployee(id: number, data: Partial<Employee>): Promise<Employee>;
}

// Service implementation
class EmployeeService implements IEmployeeService {
  constructor(private apiClient: APIClient) {}

  async getEmployees(): Promise<Employee[]> {
    return this.apiClient.get("/api/employees");
  }
}

// Component with injected service
class AdminEmployeesPage extends BaseComponent {
  constructor(private employeeService: IEmployeeService) {
    super();
  }

  async loadData() {
    const employees = await this.employeeService.getEmployees();
    // render employees
  }
}
```

#### Dependency Injection

- **Container**: Use a simple DI container for service registration and resolution
- **Injection**: Services injected into components via constructors
- **Mocking**: Services easily mockable for unit testing
- **Benefits**: Loose coupling, improved testability, clear dependencies

#### Prohibited Patterns

- ❌ Direct APIClient instantiation in components
- ❌ HTTP logic mixed with UI logic
- ❌ Components making API calls directly
- ❌ Imperative DOM manipulation for responsive layouts
- ❌ JavaScript-based media query handling
- ❌ Global singletons and side effects
- ❌ Implicit state sharing through localStorage/globals
- ❌ Overuse of event delegation creating "event soup"
- ❌ UI messages mixed with business logic
- ❌ Hardcoded feature flags in code

#### Recommended Patterns

- ✅ Service interfaces for abstraction
- ✅ Dependency injection for loose coupling
- ✅ CSS-driven responsive layouts with grid/flexbox
- ✅ Declarative templates with attribute-based mode switching
- ✅ Context providers for scoped state management
- ✅ Component-level state with explicit dependencies
- ✅ Targeted event listeners with proper cleanup
- ✅ Custom events for component communication
- ✅ Pure business rules returning structured data
- ✅ Localization layer for UI messages
- ✅ Runtime configuration for feature flags
- ✅ Build-time flag elimination
- ✅ Event-driven data flow with service injection
- ✅ Pure business logic in services

### Automated Systems

- **Monthly Reminder Scheduler**: Sends reminders for monthly PTO reviews
- **Daily Follow-up System**: Handles follow-up notifications and automated processes

### Key Architectural Principles

- **Vanilla Approach**: No heavy frameworks, keeping the codebase lightweight and maintainable
- **WSL Compatibility**: Database and development setup work seamlessly in Windows Subsystem for Linux
- **Separation of Concerns**: Clear boundaries between frontend components, API endpoints, and business logic
- **Service Layer**: Components must use injected services instead of direct APIClient usage
- **Event-Driven Architecture**: Components dispatch custom events for data requests, parent components handle API calls and data injection
- **Component Isolation**: Web components should be data-agnostic and testable without direct API dependencies
- **Type Safety**: Full TypeScript coverage for reliability and developer experience
- **Testability**: Architecture designed to support comprehensive unit and E2E testing with mockable services
- **Domain/Presentation Separation**: Business rules return structured data (message keys), not UI strings. A dedicated messages module owns all user-facing text.

### Business Rules / Messages Separation

Business rules (`shared/businessRules.ts`) must be pure domain logic — no UI strings, no message formatting. All user-facing text lives in `shared/messages.ts`.

#### Three-Layer Architecture

| Layer        | Module                    | Returns                                                    | Knows about UI strings?       |
| ------------ | ------------------------- | ---------------------------------------------------------- | ----------------------------- |
| **Domain**   | `shared/businessRules.ts` | Structured error objects: `{ field, messageKey, params? }` | No — returns keys only        |
| **Messages** | `shared/messages.ts`      | Formatted English strings                                  | Yes — owns all UI text        |
| **Consumer** | Components / Server       | Calls `resolveMessage(error.messageKey, error.params)`     | Bridges domain → presentation |

#### Validation Functions

Validation functions return structured error objects with `messageKey` strings (not formatted messages):

```typescript
// ✅ Correct — returns messageKey for consumer to resolve
export function validateHours(hours: number): ValidationError | null {
  if (typeof hours !== "number" || isNaN(hours) || hours === 0) {
    return { field: "hours", messageKey: "hours.invalid" };
  }
  return null;
}

// ❌ Prohibited — accessing message constants from businessRules.ts
export function checkThreshold(): string | null {
  return VALIDATION_MESSAGES["some.key"]; // Don't do this
}
```

#### Warning/Threshold Functions

Functions that produce warnings return messageKey strings (not formatted text):

```typescript
// ✅ Returns key — consumer calls resolveMessage()
export function checkSickDayThreshold(
  used: number,
  requested: number,
): string | null {
  if (used + requested > SICK_HOURS_BEFORE_PTO) {
    return "sick.pto_required_after_threshold";
  }
  return null;
}
```

#### Structured Violations (Import/Overuse)

Functions producing dynamic violation strings return structured objects with `messageKey` + `params`:

```typescript
// ✅ Structured — consumer calls resolveMessage(v.messageKey, v.params)
interface StructuredViolation {
  messageKey: string;
  params?: Record<string, string | number>;
}

violations.push({
  messageKey: "import.exceed_annual_limit",
  params: { type: "Sick", projected: 28, limit: 24 },
});
```

#### Consumer Pattern

```typescript
// Component / server resolves message at point of display
import { resolveMessage } from "../shared/messages.js";

const msg = resolveMessage(error.messageKey, error.params);
// → "Sick hours would reach 28h, exceeding 24h annual limit"
```

#### `resolveMessage()` API

```typescript
function resolveMessage(
  key: string,
  params?: Record<string, string | number>,
): string;
```

- Looks up `key` in all message catalogs (validation, success, notification, ui-error)
- Substitutes `{placeholder}` tokens with `params` values
- Returns raw `key` as fallback if not found (aids debugging)
- Single choke-point for future i18n (swap lookup to locale-specific catalog)

#### Prohibited Patterns

- ❌ Importing `VALIDATION_MESSAGES` or any message constant in `businessRules.ts`
- ❌ Business rule functions returning formatted English strings
- ❌ Inline string construction in domain logic (template literals with user text)
- ❌ `formatLockedMessage()` / `formatMonthNotEndedMessage()` style helpers in businessRules

#### Migration Reference

See `TASKS/business-rules-separation.md` for the full implementation plan including all message keys, affected files, and migration patterns.

### Context Protocol

The application uses a lightweight context protocol for dependency injection into web components. Context providers wrap subtrees and intercept bubbling `context-request` events.

#### Providing Context

In `App.run()`, context providers wrap `#app-wrapper`:

```typescript
import { createContextProvider, CONTEXT_KEYS } from "./shared/context.js";

const provider = createContextProvider(
  CONTEXT_KEYS.NOTIFICATIONS,
  notifications,
);
provider.style.display = "contents";
parentElement.insertBefore(provider, appWrapper);
provider.appendChild(appWrapper);
```

#### Consuming Context

Components consume context in `connectedCallback()`:

```typescript
import { consumeContext, CONTEXT_KEYS } from "../../shared/context.js";
import type { TraceListener } from "../../controller/TraceListener.js";

class MyPage extends BaseComponent {
  private _notifications: TraceListener | null = null;

  connectedCallback() {
    super.connectedCallback();
    consumeContext<TraceListener>(this, CONTEXT_KEYS.NOTIFICATIONS, (svc) => {
      this._notifications = svc;
    });
  }

  private handleError(msg: string): void {
    this._notifications?.error(msg); // nullable — safe in unit tests without provider
  }
}
```

#### Well-Known Context Keys

| Key             | Value Type               | Purpose              |
| --------------- | ------------------------ | -------------------- |
| `NOTIFICATIONS` | `TraceListener`          | Toast notifications  |
| `DEBUG`         | `DebugConsoleController` | Debug console bridge |

#### Context vs Constructor Injection

- **Context protocol**: For web components (DOM elements) that need shared services.
- **Constructor injection**: For plain classes like `UIManager` that are not custom elements.

### Event Delegation and `data-action` Convention

#### Standard Target Resolution

Use `BaseComponent.resolveAction(e)` to resolve the `data-action` attribute from a delegated event:

```typescript
protected handleDelegatedClick(e: Event): void {
  const hit = this.resolveAction(e);
  if (!hit) return;

  switch (hit.action) {
    case "approve":
      this.handleApprove(hit.target);
      break;
    case "reject":
      this.handleReject(hit.target);
      break;
  }
}
```

#### HTML Markup

Actionable elements carry `data-action` and optional `data-*` attributes:

```html
<button data-action="approve" data-request-id="42">Approve</button>
<button data-action="reject" data-request-id="42">Reject</button>
```

#### When to Use Delegation vs Direct Listeners

| Scenario                  | Pattern                          |
| ------------------------- | -------------------------------- |
| Dynamic/repeated content  | Delegation via `data-action`     |
| Static buttons/controls   | Direct `addListener()`           |
| Cross-component data flow | Custom events                    |
| External events (window)  | `addListener()` + `addCleanup()` |

### Custom Event Catalog

All custom events are cataloged in `client/shared/events.ts` with typed detail interfaces.

#### Naming Conventions

| Pattern             | Usage                     | Example             |
| ------------------- | ------------------------- | ------------------- |
| `noun-verb`         | Action completed          | `employee-submit`   |
| `noun-data-request` | Component needs data      | `pto-data-request`  |
| `noun-changed`      | State change notification | `selection-changed` |

#### Typed Dispatch

```typescript
import { dispatchTypedEvent } from "../../shared/events.js";

dispatchTypedEvent(this, "employee-submit", { employee: { name: "Jane" } });
```

### Two-Click Confirmation Pattern

For destructive or important actions, use `ConfirmationController` from `client/shared/confirmation-mixin.ts`:

```typescript
import { ConfirmationController } from "../../shared/confirmation-mixin.js";

class MyComponent extends BaseComponent {
  private _confirm = new ConfirmationController();

  disconnectedCallback() {
    this._confirm.clearAll();
    super.disconnectedCallback();
  }

  protected handleDelegatedClick(e: Event): void {
    const hit = this.resolveAction(e);
    if (!hit) return;

    if (hit.action === "delete") {
      this._confirm.handleClick(hit.target as HTMLButtonElement, () => {
        this.executeDelete(hit.target);
      });
    }
  }
}
```

For conditional confirmation (only confirm under certain conditions):

```typescript
this._confirm.handleConditionalClick(
  btn,
  hasNegativeBalance, // only require confirmation when true
  () => this.executeApprove(requestId),
);
```

### StorageService Abstraction

Components that persist UI preferences (expanded state, selected month, etc.) use the `StorageService` interface from `client/shared/storage.ts`:

```typescript
import type { StorageService } from "../../shared/storage.js";
import { LocalStorageAdapter } from "../../shared/storage.js";

class MyComponent extends BaseComponent {
  private _storage: StorageService = new LocalStorageAdapter();

  // Setter for test injection
  set storage(svc: StorageService) {
    this._storage = svc;
  }
}
```

Tests inject `InMemoryStorage` instead of mocking `localStorage` globals.

### State Management Patterns

The application follows a layered state management approach — no global stores, no raw `localStorage` access outside the `StorageService` abstraction.

#### State Hierarchy (prefer higher over lower)

| Priority | Mechanism             | Scope                        | Use Case                                              |
| -------- | --------------------- | ---------------------------- | ----------------------------------------------------- |
| 1        | Context Protocol      | Subtree (DOM-scoped)         | Shared services: notifications, debug console         |
| 2        | Custom Events         | Parent ↔ child communication | Data requests, selection changes, action dispatches   |
| 3        | Component Properties  | Single component             | Attributes, setters, internal state                   |
| 4        | StorageService        | Persistent (localStorage)    | UI preferences, cached user identity                  |
| 5        | ~~Global singletons~~ | ~~Window / module scope~~    | **Prohibited** — use context or constructor injection |

#### Context Protocol (`client/shared/context.ts`)

Lightweight dependency injection for web components. A `ContextProvider<T>` element wraps a DOM subtree and intercepts bubbling `context-request` events from descendants.

**Providing context** (typically in `App.run()`):

```typescript
const provider = createContextProvider(
  CONTEXT_KEYS.NOTIFICATIONS,
  notificationService,
);
provider.style.display = "contents";
parentElement.insertBefore(provider, appWrapper);
provider.appendChild(appWrapper);
```

**Consuming context** (in any descendant component):

```typescript
connectedCallback() {
  super.connectedCallback();
  consumeContext<TraceListener>(this, CONTEXT_KEYS.NOTIFICATIONS, (svc) => {
    this._notifications = svc;
  });
}
```

**Well-known context keys** (`CONTEXT_KEYS`):

| Key             | Type                     | Purpose              |
| --------------- | ------------------------ | -------------------- |
| `NOTIFICATIONS` | `TraceListener`          | Toast notifications  |
| `DEBUG`         | `DebugConsoleController` | Debug console bridge |

Adding a new context: define a key in `CONTEXT_KEYS`, wrap the subtree with `createContextProvider()`, and consume with `consumeContext()`.

#### Event-Based Communication (`client/shared/events.ts`)

Components communicate through typed custom events — never through shared mutable state.

- **`noun-verb`** — action completed: `employee-submit`
- **`noun-data-request`** — component needs data: `pto-data-request`
- **`noun-changed`** — state notification: `selection-changed`, `auth-state-changed`

Use `dispatchTypedEvent()` for type-safe dispatch. Parent components listen and orchestrate API calls / data injection.

#### StorageService Injection

All `localStorage` access must go through `StorageService` — never call `localStorage` directly.

**Constructor injection** (for plain classes like `AuthService`):

```typescript
class AuthService {
  private storage: StorageService;
  constructor(api?: APIClient, storage?: StorageService) {
    this.storage = storage ?? new LocalStorageAdapter();
  }
}
```

**Property injection** (for web components):

```typescript
class MyComponent extends BaseComponent {
  private _storage: StorageService = new LocalStorageAdapter();
  set storage(svc: StorageService) {
    this._storage = svc;
  }
}
```

**Test isolation**: Inject `InMemoryStorage` — no global mocking required, no cross-test contamination.

#### Prohibited State Patterns

- ❌ Raw `localStorage` / `sessionStorage` calls outside `StorageService`
- ❌ Global singletons (`window.appState`, module-level mutable objects)
- ❌ Constructor side-effects (fetching data, subscribing to events in constructors)
- ❌ Implicit state sharing between components through DOM globals
- ❌ Mutable shared references passed by identity between components
