# Arete Developer Guide

> Comprehensive development guide for the Arete (Personal Development) domain
> libraries.

This guide covers local development setup, building, testing, debugging, and
common development tasks for all 11 Arete libraries.

---

## Prerequisites

### Required Software

| Tool       | Version    | Purpose                                  |
| ---------- | ---------- | ---------------------------------------- |
| Node.js    | >= 20.0    | JavaScript runtime                       |
| pnpm       | >= 10.0    | Package manager                          |
| Nx         | (via pnpm) | Monorepo task runner                     |
| PostgreSQL | 15+        | Required for database schema development |

### Installation

```bash
# From the repository root
pnpm install
```

### Database Setup (for @arete/core development)

`@arete/core` defines 42 Drizzle ORM tables with PostgreSQL-specific features
(triggers, GIN indexes, aggregation functions). To work on database schema code
or run integration tests that touch the database:

```bash
# Start the development PostgreSQL instance
docker compose -f docker/docker-compose.dev.yml up -d

# The arete tables use the oshun_dev database
# Connection: postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
```

For pure domain logic development (habits, goals, gamification, etc.), no
database is needed. The feature libraries contain stateless functions that
operate on typed data structures.

---

## Project Structure

All Arete libraries live under `libs/arete/`:

```
libs/arete/
  core/           @arete/core           Core schemas, DB schema, seeds
  habits/         @arete/habits         Comprehensive habit engine (10 modules)
  goals/          @arete/goals          Goal management (8 modules)
  journal/        @arete/journal        Journaling and reflection (9 modules)
  time/           @arete/time           Time management (9 modules)
  vision/         @arete/vision         Vision and purpose (6 modules)
  balance/        @arete/balance        Life balance and wellness (7 modules)
  seven-habits/   @arete/seven-habits   Covey's 7 Habits framework (8 modules)
  affirmations/   @arete/affirmations   Affirmation engine (2 modules)
  gamification/   @arete/gamification   Gamification engine (8 modules)
  ai-coach/       @arete/ai-coach       AI-powered coaching (5 modules)
```

### Library Dependency Graph

```
@arete/core (foundation: Zod schemas, Drizzle tables, seeds)
  |
  +-- @arete/habits         (peer: core)
  +-- @arete/goals          (peer: core)
  +-- @arete/journal        (peer: core)
  +-- @arete/time           (peer: core)
  +-- @arete/vision         (peer: core)
  +-- @arete/balance        (peer: core)
  +-- @arete/seven-habits   (peer: core)
  +-- @arete/affirmations   (peer: core)
  |
  +-- @arete/gamification   (peer: core) - cross-cutting
  +-- @arete/ai-coach       (peer: core) - cross-cutting
```

All feature libraries depend on `@arete/core` as a peer dependency.
`@arete/gamification` and `@arete/ai-coach` sit on top of the feature layer and
provide cross-cutting functionality.

### Per-Library File Layout

Each library follows a flat module structure:

```
libs/arete/{library}/
  src/
    index.ts              Public API barrel export
    {module}.ts           Module implementation
    {module}.spec.ts      Module tests
  package.json
  project.json
  tsconfig.json
  tsconfig.lib.json
  tsconfig.spec.json
  vitest.config.ts
```

Unlike Euterpe which uses sub-directories per module, Arete libraries place
module files directly in `src/`. For example, `@arete/habits` has `src/crud.ts`,
`src/habit-loop.ts`, `src/four-laws.ts`, etc.

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @arete/core
pnpm nx build @arete/habits
pnpm nx build @arete/goals
```

### Build All Arete Libraries

```bash
pnpm nx run-many --target=build --projects=tag:scope:arete
```

### Build Configuration

| Setting       | Value                             |
| ------------- | --------------------------------- |
| Executor      | `@nx/js:tsc`                      |
| Output        | `dist/libs/arete/{library}/`      |
| Module format | ESM (`"type": "module"`)          |
| Declarations  | Generated (`.d.ts` + `.d.ts.map`) |

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @arete/core
pnpm nx test @arete/habits
pnpm nx test @arete/goals
pnpm nx test @arete/journal
pnpm nx test @arete/time
pnpm nx test @arete/balance
pnpm nx test @arete/gamification
pnpm nx test @arete/ai-coach
```

### Run All Arete Tests

```bash
pnpm nx run-many --target=test --projects=tag:scope:arete
```

### Test Configuration

All libraries use Vitest via the `@nx/vite:test` executor:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

### Test Count

The domain has 74 test files across all 11 libraries. Each module typically has
a dedicated spec file (e.g., `crud.spec.ts`, `habit-loop.spec.ts`,
`four-laws.spec.ts`).

### Running Tests with Coverage

```bash
pnpm nx test @arete/habits -- --coverage
```

### Running a Specific Test File

```bash
pnpm nx test @arete/habits -- --testPathPattern="streaks"
```

### Writing Tests

Arete tests follow a standard pattern for domain logic:

```typescript
// src/streaks.spec.ts
import { describe, it, expect } from 'vitest';
import { calculateStreak, StreakConfig } from './streaks.js';

describe('Streaks', () => {
  const config: StreakConfig = {
    forgivenessDays: 1,
    minimumCompletionsPerDay: 1,
  };

  describe('calculateStreak', () => {
    it('should count consecutive days with completions', () => {
      const completions = [
        { date: '2025-01-01', count: 1 },
        { date: '2025-01-02', count: 2 },
        { date: '2025-01-03', count: 1 },
      ];
      const streak = calculateStreak(completions, config);
      expect(streak.currentStreak).toBe(3);
    });

    it('should use forgiveness days for missed days', () => {
      const completions = [
        { date: '2025-01-01', count: 1 },
        // Jan 2 missed (forgiveness day)
        { date: '2025-01-03', count: 1 },
      ];
      const streak = calculateStreak(completions, config);
      expect(streak.currentStreak).toBe(3);
    });
  });
});
```

---

## Linting

```bash
# Lint a single library
pnpm nx lint @arete/core

# Lint all Arete libraries
pnpm nx run-many --target=lint --projects=tag:scope:arete
```

---

## Common Development Tasks

### Adding a New Module to an Existing Library

For example, adding a new `community` module to `@arete/habits`:

1. Create the implementation file `libs/arete/habits/src/community.ts`
2. Create the test file `libs/arete/habits/src/community.spec.ts`
3. Export from `libs/arete/habits/src/index.ts`:

```typescript
export * from './community.js';
```

4. Verify:

```bash
pnpm nx build @arete/habits
pnpm nx test @arete/habits
pnpm nx lint @arete/habits
```

### Adding a New Arete Library

1. Create the directory structure under `libs/arete/{new-lib}/`
2. Create `project.json`:

```json
{
  "name": "@arete/{new-lib}",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/arete/{new-lib}/src",
  "projectType": "library",
  "tags": ["scope:arete", "layer:domain", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/arete/{new-lib}",
        "main": "libs/arete/{new-lib}/src/index.ts",
        "tsConfig": "libs/arete/{new-lib}/tsconfig.lib.json",
        "assets": []
      }
    },
    "lint": { "executor": "@nx/eslint:lint" },
    "test": {
      "executor": "@nx/vite:test",
      "options": {
        "configFile": "libs/arete/{new-lib}/vitest.config.ts"
      }
    }
  }
}
```

3. Create `package.json` with `@arete/core` as a peer dependency:

```json
{
  "name": "@arete/{new-lib}",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "import": "./src/index.js",
      "types": "./src/index.d.ts"
    }
  },
  "dependencies": {},
  "peerDependencies": {
    "@arete/core": "workspace:*"
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

4. Run `pnpm install`.

### Adding Zod Schemas to Core

When extending `@arete/core` with new validation schemas:

1. Define the Zod schema in `libs/arete/core/src/schemas.ts`
2. Export the schema and inferred type:

```typescript
import { z } from 'zod';

export const NewFeatureSchema = z.object({
  id: z.string().uuid(),
  userId: z.string().uuid(),
  name: z.string().min(1).max(200),
  category: z.enum(['category1', 'category2']),
  createdAt: z.date(),
});

export type NewFeature = z.infer<typeof NewFeatureSchema>;
```

3. Add corresponding Drizzle ORM table in `libs/arete/core/src/db-schema.ts`
4. Add to the `ALL_ARETE_TABLES` array

### Adding Database Tables to Core

When adding new Drizzle ORM tables:

1. Define the table in `libs/arete/core/src/db-schema.ts` using the `arete_`
   prefix:

```typescript
import { pgTable, uuid, varchar, timestamp, pgEnum } from 'drizzle-orm/pg-core';

export const areteNewFeatureStatusEnum = pgEnum('arete_new_feature_status', [
  'active',
  'paused',
  'completed',
]);

export const areteNewFeature = pgTable('arete_new_features', {
  id: uuid('id').primaryKey().defaultRandom(),
  userId: uuid('user_id').notNull(),
  name: varchar('name', { length: 200 }).notNull(),
  status: areteNewFeatureStatusEnum('status').default('active'),
  createdAt: timestamp('created_at').defaultNow(),
});
```

2. Add relations if needed
3. Add to `ALL_ARETE_TABLES`, `ALL_ARETE_RELATIONS`, and `ALL_ARETE_ENUMS`
   arrays
4. Add seed data in `libs/arete/core/src/db-seed.ts`

---

## Key Patterns and Conventions

### Evidence-Based Frameworks

Arete libraries are built around established personal development frameworks.
When adding new functionality, identify the underlying framework or research
base:

- **Habits:** James Clear's Atomic Habits, BJ Fogg's Tiny Habits
- **Goals:** SMART criteria, OKRs, WOOP mental contrasting, 12 Week Year
- **Time:** Eisenhower Matrix, GTD, Pomodoro, Cal Newport's Deep Work
- **Balance:** Wheel of Life, PERMA (Positive Psychology), Wellness Dimensions
- **Seven Habits:** Stephen Covey's 7 Habits framework
- **Journal:** CBT thought records, Julia Cameron's Morning Pages, gratitude
  research

### Module Export Pattern

All Arete libraries use direct exports (not namespace exports):

```typescript
// src/index.ts
export * from './crud.js';
export * from './habit-loop.js';
export * from './four-laws.js';
```

This means consumers import directly:

```typescript
import { createHabit, HabitLoop, analyzeFourLaws } from '@arete/habits';
```

### Zod-First Schema Design

The core library uses Zod schemas as the single source of truth for types.
TypeScript types are inferred from Zod schemas using `z.infer<>`:

```typescript
const HabitSchema = z.object({
  /* ... */
});
type Habit = z.infer<typeof HabitSchema>;
```

Never define standalone TypeScript interfaces for data models that should be
validated. Always derive them from Zod schemas.

### Database Conventions

- Table prefix: `arete_` for all tables
- Enum prefix: `arete_` for all PostgreSQL enum types
- Foreign keys: Use cascading deletes where appropriate
- Timestamps: Use `timestamp('created_at').defaultNow()` and
  `timestamp('updated_at')` on all tables
- IDs: Use `uuid('id').primaryKey().defaultRandom()`

### PostgreSQL-Specific Features

`@arete/core` leverages PostgreSQL features:

- **Triggers:** `STREAK_CALCULATION_TRIGGER_SQL` auto-recalculates streak counts
  on habit completion inserts
- **Aggregation functions:** `arete_total_completions`, `arete_average_mood`,
  `arete_goal_completion_rate`, etc.
- **GIN indexes:** Full-text search on journal entry content and titles via
  `JOURNAL_FULLTEXT_INDEX_SQL`
- **JSONB columns:** Flexible data storage for configurations and metadata

### Gamification Constants

`@arete/gamification` defines specific numeric constants:

- **20 levels** with an XP curve
- **50+ badges** with tiers (bronze, silver, gold, platinum)
- **Multiple currencies:** XP, coins, gems with multipliers

When adding new gamification content, maintain consistency with these existing
ranges.

---

## Debugging Tips

### Zod Validation Errors

If Zod throws a `ZodError`, inspect `.errors` for detailed path information:

```typescript
try {
  HabitSchema.parse(data);
} catch (error) {
  if (error instanceof z.ZodError) {
    console.error(error.errors);
    // [{ path: ['name'], message: 'String must contain at least 1 character(s)' }]
  }
}
```

### Drizzle ORM Type Errors

If TypeScript complains about Drizzle table types, verify:

1. `drizzle-orm` version matches the workspace catalog version
2. The table definition uses the correct column type imports from
   `drizzle-orm/pg-core`
3. Relations reference valid table definitions

### Import Path Extensions

Arete uses ESM. All import paths must include `.js` extensions:

```typescript
// Correct
import { createHabit } from './crud.js';

// Incorrect (will fail at runtime)
import { createHabit } from './crud';
```

### Circular Dependencies

If you encounter circular import issues between modules within a library, check
whether two modules are importing from each other. Extract shared types into a
separate `types.ts` file that both modules can import.

### Testing Date-Dependent Logic

Many Arete modules depend on dates (streaks, daily plans, time tracking). Use
Vitest's `vi.useFakeTimers()` to control time in tests:

```typescript
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';

describe('Daily Planning', () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2025-06-15T09:00:00'));
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('should create plan for today', () => {
    const plan = createDailyPlan();
    expect(plan.date).toBe('2025-06-15');
  });
});
```

### Running Only Failed Tests

```bash
pnpm nx test @arete/habits -- --reporter=verbose --bail=1
```

---

## Project Configuration Reference

### Tags

All Arete libraries use: `["scope:arete", "layer:domain", "type:lib"]`

### Executors

| Target | Executor          |
| ------ | ----------------- |
| build  | `@nx/js:tsc`      |
| lint   | `@nx/eslint:lint` |
| test   | `@nx/vite:test`   |

### Core Dependencies

| Dependency    | Used By       | Purpose            |
| ------------- | ------------- | ------------------ |
| `zod`         | `@arete/core` | Validation schemas |
| `drizzle-orm` | `@arete/core` | Database ORM       |
| `vitest`      | All           | Testing framework  |

### Environment Variables

For database-related development on `@arete/core`:

```bash
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
```

No environment variables are needed for feature library development.

---

## Related Documentation

- [Arete Domain README](./README.md) - Domain overview, architecture, and
  library descriptions
- [CLAUDE.md](/CLAUDE.md) - Repository-wide development guidelines
