Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ DIGEST_ROLE_ID=digest_role_id_here
# ROLE_B_ID=optional_role_b_id
# ROLE_C_ID=optional_role_c_id

# Onboarding
# ONBOARDING_ENABLED=false
# ONBOARDING_LEVEL_0_ROLE_ID=onboarding_level_0_role_id_here
# ONBOARDING_LEVEL_1_ROLE_ID=onboarding_level_1_role_id_here
# ONBOARDING_LEVEL_2_ROLE_ID=onboarding_level_2_role_id_here
# ONBOARDING_LEVEL_3_ROLE_ID=onboarding_level_3_role_id_here

# Data Persistence (OPTIONAL)
# Local development defaults to current directory
# Docker deployments should use /app/data for persistence
Expand Down
7 changes: 7 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ REGULAR_ROLE_ID=1383170370634514544
TAG_ACCESS_ROLE_ID=1502128862224711805
DIGEST_ROLE_ID=1561474157479207032

# Onboarding
ONBOARDING_ENABLED=false
ONBOARDING_LEVEL_0_ROLE_ID=1577799059291504831
ONBOARDING_LEVEL_1_ROLE_ID=1577799118376534076
ONBOARDING_LEVEL_2_ROLE_ID=1577799149976293426
ONBOARDING_LEVEL_3_ROLE_ID=1577799178690498740

# Other
GUIDES_TRACKER_PATH=/app/data/guides-tracker.json
ADVENT_OF_CODE_TRACKER_PATH=/app/data/advent-of-code-tracker.json
Expand Down
7 changes: 7 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ REGULAR_ROLE_ID=your-regular-role-id
TAG_ACCESS_ROLE_ID=your-tag-access-role-id
DIGEST_ROLE_ID=your-digest-role-id

# Onboarding
ONBOARDING_ENABLED=false
ONBOARDING_LEVEL_0_ROLE_ID=onboarding_level_0_role_id_here
ONBOARDING_LEVEL_1_ROLE_ID=onboarding_level_1_role_id_here
ONBOARDING_LEVEL_2_ROLE_ID=onboarding_level_2_role_id_here
ONBOARDING_LEVEL_3_ROLE_ID=onboarding_level_3_role_id_here

# Other
GUIDES_TRACKER_PATH=guides-tracker.json
ADVENT_OF_CODE_TRACKER_PATH=test-advent-tracker.json
Expand Down
216 changes: 216 additions & 0 deletions docs/spec/onboarding.item-1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
# Onboarding — Item 1 Implementation Spec: Level Foundation

- **Issue:** #158 (epic #157, child item 1)
- **Business spec:** `docs/spec/onboarding.md`, plan `docs/spec/onboarding.plan.md` (branch `chore/spec-onboarding`)
- **Implementation branch:** `feat/158/level-foundation`, cut from `main`
- **PR:** title `feat(#158): level foundation — member progress, level roles, configuration`, body `Closes #158`
- **Status:** finalized — all decisions confirmed by the maintainer

## 1. Goal

Build the shared base for onboarding: stored member progress, level roles, configuration behind a feature flag, the pure level-transition function, the role applier, exemption rules, and join/leave listeners. Nothing visible changes for members while the flag is off.

## 2. Acceptance criteria

- [ ] With onboarding disabled (`ONBOARDING_ENABLED` not `'true'`), the bot does nothing onboarding related.
- [ ] With onboarding enabled, a new member receives the level 0 role on join; a bot receives nothing.
- [ ] A member at level N holds exactly the roles for levels 0 to N; applying a level removes the roles above it.
- [ ] Levels change one at a time, strictly in order, never skip; the only ways down are 3 → 2 or a forced reset to 0.
- [ ] Applying the same level twice changes nothing (idempotent).
- [ ] Bots are never given a level and never made dormant; moderators gain levels like anyone else but are never made dormant.
- [ ] Unit tests cover the level transitions and the exemption rules.

## 3. Locked decisions

1. **One table.** `member_progress` only; no separate dormancy table. Progress reads are PK lookups, so a `dormant` bool does not slow them. Splitting would force cross-table consistency (dormant implies level 0) for no gain at single-guild SQLite scale.
2. **Minimal env surface.** Only the vars item 1 reads: `ONBOARDING_ENABLED` and `ONBOARDING_LEVEL_0_ROLE_ID` … `ONBOARDING_LEVEL_3_ROLE_ID`. Channel IDs and `ONBOARDING_VC_REGULAR_ROLE_ID` are added by the items that first use them (items 3, 4, 6, 9).
3. **Leave handling.** `GuildMemberRemove` only stamps `leftAt`. Deleting rows whose `leftAt` is older than 7 days belongs to item 8.
4. **Reusable constants.** `Level` and `LevelEvent` are `as const` objects in `constants.ts` (no enums, per AGENTS.md).
5. **Errors throw.** Handlers throw wrapped errors; the event loader (`load-events.ts`) catches and logs them. One exception: stamping `leftAt` uses `updateMany`, because an untracked member leaving is a no-op, not a failure.
6. **Migration via `pnpm migrate:dev`** — no hand-written SQL.
7. **Join listener applies the existing row's level** (deviation from the plan text, which says apply 0 unconditionally): a new joiner's row is created at level 0, so they get exactly level 0; a member with an existing row (rejoin before item 8 lands) is not stripped of roles. Roles are applied before the row is written, and `leftAt` is cleared on rejoin.

## 4. Data model

New Prisma model in `prisma/schema.prisma`, plus a migration generated with `pnpm migrate:dev`:

```prisma
model MemberProgress {
userId String @id
level Int @default(0)
lastActivityAt DateTime?
lastEvaluatedAt DateTime?
dormant Boolean @default(false)
leftAt DateTime?
createdAt DateTime @default(now())

@@map("member_progress")
}
```

| Column | Type | Why |
| ----------------- | ----------------------- | ----------------------------------------------------------------------------------------------- |
| `userId` | String, PK | Discord user ID; one row per member (the bot serves one guild). |
| `level` | Int, default 0 | Current level 0–3. Discord roles are the enforcement source of truth; this is the bot's record. |
| `lastActivityAt` | DateTime? | Written by item 2, read by items 5/6. Null for a new joiner. |
| `lastEvaluatedAt` | DateTime? | Stamped by item 5's monthly evaluation. |
| `dormant` | Boolean, default false | Set by item 6. |
| `leftAt` | DateTime? | Stamped by this item's remove listener; cleared on rejoin, deleted after 7 days (item 8). |
| `createdAt` | DateTime, default now() | Row creation time. |

The three columns only read by later items are defined now so the migration lands once. After the schema change, run `pnpm prisma:generate` so `prisma.memberProgress` exists.

## 5. Configuration (`src/env.ts`)

Replace the stub block:

```ts
onboarding: {
channelId: optionalEnv('ONBOARDING_CHANNEL_ID'),
roleId: optionalEnv('ONBOARDING_ROLE_ID'),
},
```

with:

```ts
onboarding: {
enabled: optionalEnv('ONBOARDING_ENABLED') === 'true',
roleIds: {
level0: optionalEnv('ONBOARDING_LEVEL_0_ROLE_ID'),
level1: optionalEnv('ONBOARDING_LEVEL_1_ROLE_ID'),
level2: optionalEnv('ONBOARDING_LEVEL_2_ROLE_ID'),
level3: optionalEnv('ONBOARDING_LEVEL_3_ROLE_ID'),
},
},
```

| Env var | Config path | Read by |
| ----------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------- |
| `ONBOARDING_ENABLED` | `config.onboarding.enabled` | Both member listeners (feature flag; `'true'` only). |
| `ONBOARDING_LEVEL_0_ROLE_ID` … `ONBOARDING_LEVEL_3_ROLE_ID` | `config.onboarding.roleIds.level0` … `.level3` | `applyLevelRoles`. |

All values are optional so the bot still starts with the flag off. `.env*` files are not touched (AGENTS.md); the new vars are documented here and in `src/env.ts` only. When `ONBOARDING_ENABLED` is `'true'` but any level role var is missing, `src/env.ts` logs a startup warning naming the missing vars; runtime behavior is unchanged (`applyLevelRoles` still throws, section 7.4).

## 6. Files

```
prisma/schema.prisma MODIFY add MemberProgress model
prisma/migrations/<ts>_add_member_progress/ NEW generated by pnpm migrate:dev
src/env.ts MODIFY onboarding config block (section 5)
src/index.ts MODIFY add GatewayIntentBits.GuildMembers to intents
src/common/events/index.ts MODIFY register the two member events
src/features/onboarding/constants.ts NEW Level + LevelEvent as const objects
src/features/onboarding/level.ts NEW nextLevel()
src/features/onboarding/level.test.ts NEW
src/features/onboarding/roles.ts NEW applyLevelRoles()
src/features/onboarding/roles.test.ts NEW
src/features/onboarding/exemptions.ts NEW exemption rules
src/features/onboarding/exemptions.test.ts NEW
src/features/onboarding/member-events.ts NEW GuildMemberAdd + GuildMemberRemove
src/features/onboarding/index.ts DELETE stub command; not registered in src/common/commands/index.ts
src/features/onboarding/component.ts DELETE only referenced by the stub
```

Before deleting the stubs, grep to confirm nothing imports `features/onboarding/index.js`, `features/onboarding/component.js`, `onboardingCommand`, or `containerComponent` outside those two files.

## 7. Module specs

### 7.1 `constants.ts` — reusable level vocabulary

```ts
export const Level = {
NewJoiner: 0,
AgreedToRules: 1,
Regular: 2,
HighlyActive: 3,
} as const;
export type Level = (typeof Level)[keyof typeof Level];

export const isLevel = (value: number): value is Level => {
return (Object.values(Level) as number[]).includes(value);
};

export const LevelEvent = {
Agree: 'agree',
ActivityRequirementMet: 'activity-requirement-met',
ActivityRequirementNotMet: 'activity-requirement-not-met',
ForcedReset: 'forced-reset',
} as const;
export type LevelEvent = (typeof LevelEvent)[keyof typeof LevelEvent];
```

`LevelEvent` names the four spec triggers; items 3, 5 and 6–7 call `nextLevel` with them.

### 7.2 `level.ts` — pure transition function

`nextLevel(current: Level, event: LevelEvent): Level` — exhaustive switch, no Discord or DB involved:

| current | event | next |
| --------------------- | --------------------------- | --------- |
| 0 | `Agree` | 1 |
| 1 | `ActivityRequirementMet` | 2 |
| 2 | `ActivityRequirementMet` | 3 |
| 3 | `ActivityRequirementNotMet` | 2 |
| any | `ForcedReset` | 0 |
| any other combination | — | unchanged |

### 7.3 `exemptions.ts` — pure exemption rules

```ts
isExemptFromLevels(user: User): boolean // true when user.bot
isExemptFromDormancy(member, moderatorRoleIds: string[]): boolean
// true when the member is a bot or holds any of the given moderator role IDs
```

Role IDs are passed as parameters (not read from globals) so tests need no Discord objects. Callers pass `config.roleIds.moderators`.

### 7.4 `roles.ts` — idempotent role applier

`applyLevelRoles(member: GuildMember, target: Level): Promise<void>`

1. Build the ordered role-ID list `[level0, level1, level2, level3]` from config; throw if any is unset while onboarding is enabled.
2. Keep: `roleIds.slice(0, target + 1)` — add each missing role via the existing `addRoleToUser` util (skips when already present, throws a wrapped error on failure).
3. Remove: `roleIds.slice(target + 1)` — remove only when `member.roles.cache.has(roleId)`; wrap failures in a thrown error with role/member context.
4. Throw when a configured role ID is not found in the guild.

Never touches channel permission overwrites.

### 7.5 `member-events.ts` — join/leave listeners

Both listeners return immediately unless `config.onboarding.enabled`, and both skip members for whom `isExemptFromLevels(member.user)` is true.

- `GuildMemberAdd`: `findUnique({ where: { userId } })`, apply `applyLevelRoles(member, target)` where `target` is the existing row's level when `isLevel(row.level)` holds, else `Level.NewJoiner`; only then `upsert({ where: { userId }, update: { leftAt: null }, create: { userId, level: Level.NewJoiner } })`. Roles are applied before the row is persisted so a role failure leaves no divergent progress row; `leftAt` is cleared on rejoin (see section 4).
- `GuildMemberRemove`: `prisma.memberProgress.updateMany({ where: { userId }, data: { leftAt: new Date() } })`.

Register both in `src/common/events/index.ts`.

## 8. Tests

Colocated `*.test.ts` files using `node:test` + `node:assert/strict`. Discord objects are mocked as plain objects cast to their types (style of `src/features/tags/prune-tags.test.ts`).

- `level.test.ts`: every changing transition in the table above; representative no-change cases (e.g. `ActivityRequirementMet` at level 0 stays 0 — no skipping); `ForcedReset` from each level; repeating an event that no longer applies is a no-op; `isLevel` accepts exactly the defined levels 0–3.
- `exemptions.test.ts`: a bot user is exempt from levels, a human is not; a bot member and a member holding a moderator role are exempt from dormancy, a plain member is not.
- `roles.test.ts`: sets the required env vars before importing `env.js` (which exits the process on missing vars), so the test is independent of `.env*` files. Covers adding exactly the roles for levels 0..target, removing only held roles above the target, idempotent re-application of the same level, and the throws for incomplete config, a role missing from the guild, and a failed removal.

## 9. Verification

```bash
pnpm migrate:dev # generates the migration (prisma CLI reads DATABASE_URL itself; never read .env* files)
pnpm prisma:generate
pnpm test
pnpm typecheck
pnpm lint
pnpm fmt:check
pnpm build
```

## 10. Out of scope

Granting any level above 0, activity tracking, the `/onboarding` command, backfilling existing members, channel-permission changes in Discord (moderators do those), the 7-day retention deletion (item 8), and all channel-ID env vars.

## 11. Risks

- **GuildMembers intent** is privileged; it must be enabled in the Discord developer portal before the listeners fire in production.
- **Role hierarchy:** role add/remove fails when the bot's highest role is not above the target; errors are thrown and logged by the event loader.
- **Stub deletion** is safe only if nothing imports it — verified by grep before deleting (the stub command is not registered in `src/common/commands/index.ts`).
10 changes: 10 additions & 0 deletions prisma/migrations/20261203173930_add_member_progress/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE "member_progress" (
"userId" TEXT NOT NULL PRIMARY KEY,
"level" INTEGER NOT NULL DEFAULT 0,
"lastActivityAt" DATETIME,
"lastEvaluatedAt" DATETIME,
"dormant" BOOLEAN NOT NULL DEFAULT false,
"leftAt" DATETIME,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
14 changes: 14 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,17 @@ model AdventOfCode {
@@id([year, day])
@@map("advent_of_code")
}

// Onboarding progress of one member. Roles are not stored here; Discord is
// the source of truth for roles, this row is the bot's record.
model MemberProgress {
userId String @id
level Int @default(0)
lastActivityAt DateTime?
lastEvaluatedAt DateTime?
dormant Boolean @default(false)
leftAt DateTime?
createdAt DateTime @default(now())

@@map("member_progress")
}
6 changes: 6 additions & 0 deletions src/common/events/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { guildCreateEvent } from '@/features/guild-create/index.js';
import { hasVarEvent } from '@/features/has-var/index.js';
import {
guildMemberAddEvent,
guildMemberRemoveEvent,
} from '@/features/onboarding/member-events.js';
import { interactionCreateEvent } from '@/features/interaction-create/index.js';
import { readyEvent } from '@/features/ready/index.js';
import type { DiscordEvent } from './types.js';
Expand All @@ -12,6 +16,8 @@ import { quoteEvent } from '@/features/quote/index.js';
export const events: DiscordEvent[] = [
readyEvent,
guildCreateEvent,
guildMemberAddEvent,
guildMemberRemoveEvent,
hasVarEvent,
interactionCreateEvent,
spamDetection,
Expand Down
32 changes: 30 additions & 2 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// oxlint-disable id-length
import '@/loadEnvFile.js';
import { Level } from '@/features/onboarding/constants.js';
import { createLogger } from '@/util/logger.js';

const logger = createLogger('env');
Expand All @@ -18,6 +19,30 @@ function requireEnv(key: string): string {
return value;
}

function mapEnvVars(
envVars: Record<Level, string>,
read: (key: string) => string | undefined
): Record<Level, string | undefined> {
return Object.fromEntries(
Object.entries(envVars).map(
([level, envVar]): [string, string | undefined] => [level, read(envVar)]
)
) as Record<Level, string | undefined>;
}

// Single source for the onboarding level role env vars, keyed by level:
// config.onboarding.roleIds is built from this map, so the two cannot drift.
// When onboarding is enabled the vars are required, so a missing one stops
// startup via requireEnv.
const onboardingLevelRoleEnvVars: Record<Level, string> = {
[Level.NewJoiner]: 'ONBOARDING_LEVEL_0_ROLE_ID',
[Level.AgreedToRules]: 'ONBOARDING_LEVEL_1_ROLE_ID',
[Level.Regular]: 'ONBOARDING_LEVEL_2_ROLE_ID',
[Level.HighlyActive]: 'ONBOARDING_LEVEL_3_ROLE_ID',
};

const onboardingEnabled = optionalEnv('ONBOARDING_ENABLED') === 'true';

// Single source of truth for all configuration
export const config = {
discord: {
Expand Down Expand Up @@ -51,8 +76,11 @@ export const config = {
archiveCategory: requireEnv('ARCHIVE_CATEGORY_ID'),
},
onboarding: {
channelId: optionalEnv('ONBOARDING_CHANNEL_ID'),
roleId: optionalEnv('ONBOARDING_ROLE_ID'),
enabled: onboardingEnabled,
roleIds: mapEnvVars(
onboardingLevelRoleEnvVars,
onboardingEnabled ? requireEnv : optionalEnv
),
},
databaseUrl: requireEnv('DATABASE_URL'),
};
Expand Down
22 changes: 0 additions & 22 deletions src/features/onboarding/component.ts

This file was deleted.

Loading
Loading