diff --git a/AI.dev/PROMPTS/README.md b/AI.dev/PROMPTS/README.md new file mode 100644 index 00000000..adcbf393 --- /dev/null +++ b/AI.dev/PROMPTS/README.md @@ -0,0 +1,75 @@ +# ByteLyst Ecosystem β€” Reusable AI Prompts + +> **Location:** `AI.dev/PROMPTS/` +> **Audience:** Claude Code, Codex, Cursor, Copilot, Windsurf Cascade, Gemini, and any AI coding agent. +> **Scope:** All 37 repos in `D:\BYTELYST\CODE\` β€” common platform, product repos, tooling repos. + +--- + +## How to Use + +Copy-paste a prompt into your AI assistant, or reference it by path: + +``` +@file AI.dev/PROMPTS/roadmap-execution.md +``` + +Each prompt is **self-contained** β€” it includes the context the agent needs without +requiring you to manually explain the ecosystem every time. + +## Prompt Index + +### πŸ—ΊοΈ Planning & Roadmap + +| Prompt | Purpose | +|--------|---------| +| [roadmap-execution.md](./roadmap-execution.md) | Execute a phased roadmap with checkpoints, commits, and validation | +| [new-product-scaffold.md](./new-product-scaffold.md) | Scaffold a new ByteLyst product repo from scratch | +| [prd-to-implementation.md](./prd-to-implementation.md) | Convert a PRD into a concrete, phased implementation plan | + +### πŸ”§ Development & Debugging + +| Prompt | Purpose | +|--------|---------| +| [cross-repo-debug.md](./cross-repo-debug.md) | Systematically debug issues spanning multiple repos | +| [backend-module-crud.md](./backend-module-crud.md) | Add a complete Fastify CRUD module (types β†’ repo β†’ routes β†’ tests) | +| [platform-integration.md](./platform-integration.md) | Wire a product repo into the common platform ecosystem | +| [refactor-with-tests.md](./refactor-with-tests.md) | Safely refactor code with test-first methodology | + +### πŸ§ͺ Quality & Testing + +| Prompt | Purpose | +|--------|---------| +| [test-gap-analysis.md](./test-gap-analysis.md) | Identify and fill test coverage gaps in any repo | +| [type-safety-sweep.md](./type-safety-sweep.md) | Fix TypeScript errors across a repo or the workspace | +| [dependency-health-check.md](./dependency-health-check.md) | Audit and update dependencies across repos | + +### πŸ“¦ Release & Ops + +| Prompt | Purpose | +|--------|---------| +| [pre-release-validation.md](./pre-release-validation.md) | Full pre-release checklist: build, test, lint, security | +| [docker-production-prep.md](./docker-production-prep.md) | Prepare Docker images for production deployment | + +### πŸ“š Documentation + +| Prompt | Purpose | +|--------|---------| +| [agents-md-sync.md](./agents-md-sync.md) | Update AGENTS.md across all repos to match current state | +| [ecosystem-audit.md](./ecosystem-audit.md) | Full ecosystem health audit with actionable report | + +--- + +## Conventions + +- **Agent-agnostic:** Prompts work across Claude, Copilot, Cursor, Windsurf, Gemini. +- **Ecosystem-aware:** Each prompt embeds the key ByteLyst conventions (productId, Fastify module pattern, @bytelyst/* packages, pnpm workspace). +- **Commit-friendly:** Prompts that produce code changes include commit message guidance. +- **Incremental:** Each prompt favors small, validated, committed steps over big-bang changes. + +## Adding a New Prompt + +1. Create `AI.dev/PROMPTS/.md` +2. Include a YAML-style header with `name`, `description`, `argument-hint` +3. Add it to this index +4. Commit: `docs(prompts): add reusable prompt` diff --git a/AI.dev/PROMPTS/agents-md-sync.md b/AI.dev/PROMPTS/agents-md-sync.md new file mode 100644 index 00000000..0e50bd9c --- /dev/null +++ b/AI.dev/PROMPTS/agents-md-sync.md @@ -0,0 +1,119 @@ +--- +name: agents-md-sync +description: 'Audit and update AGENTS.md files across all ByteLyst repos to match current codebase reality β€” layout, test counts, API endpoints, packages.' +argument-hint: 'Scope, e.g. "all repos", "learning_ai_efforise only", "test counts only"' +agent: agent +--- + +# AGENTS.md Sync Prompt + +Ensure all AGENTS.md files across the ByteLyst ecosystem accurately reflect the current state of each repository. + +## Context β€” What AGENTS.md Does + +AGENTS.md is the **primary instruction file for AI coding assistants** (Claude Code, Copilot, Cursor, Windsurf, Gemini). It must be accurate because: +- AI agents read it before making changes +- Incorrect docs lead to incorrect code +- Stale test counts erode agent trust +- Wrong layout trees cause file-not-found errors + +## Standard AGENTS.md Sections + +Every ByteLyst repo should have these sections: + +1. **Project Identity** β€” product name, ID, bundle IDs, ports, ecosystem +2. **Repo Layout** β€” file tree (keep up to date!) +3. **Tech Stack** β€” frameworks, languages, tools per layer +4. **Coding Conventions** β€” MUST follow / MUST NOT do +5. **.npmrc rules** β€” never edit directly +6. **Cosmos Containers** (if backend) β€” container, partition key, purpose +7. **Build & Test Commands** β€” exact `pnpm` commands +8. **API Endpoints** (if backend) β€” method, path, description +9. **Environment Variables** β€” var, default, description +10. **Current State** (optional) β€” phases, commits, test counts +11. **Cross-Repo Automation** β€” link to CODING_AGENT_AUTOMATION_PLAYBOOK.md + +## Sync Protocol + +### Step 1: Scan Each Repo + +For each repo, programmatically verify: + +```bash +# File tree matches layout section +find . -type f -name "*.ts" -o -name "*.tsx" -o -name "*.swift" -o -name "*.kt" | head -50 + +# Test count matches +pnpm test --reporter=verbose 2>&1 | tail -5 + +# API endpoints match (backend) +grep -r "app\.\(get\|post\|patch\|put\|delete\)" backend/src/modules/*/routes.ts + +# Package count matches +ls node_modules/@bytelyst/ 2>/dev/null | wc -l + +# Cosmos containers match +grep -r "getCollection\|getContainer" backend/src/modules/*/repository.ts +``` + +### Step 2: Identify Drift + +Compare AGENTS.md content against reality: + +| Section | Check | Drift Signal | +|---------|-------|-------------| +| Repo Layout | `find` vs documented tree | New dirs/files not listed | +| Tech Stack | package.json deps | New framework not mentioned | +| Test Counts | `pnpm test` output | Count differs by >5 | +| API Endpoints | route file scan | Missing endpoints | +| Cosmos Containers | repository scan | New containers | +| Packages Used | node_modules scan | New @bytelyst/* packages | +| Ports | shared/product.json | Port mismatch | + +### Step 3: Update AGENTS.md + +For each drift found: +- Update the specific section +- Preserve all existing comments and documentation +- Keep formatting consistent with other repos + +### Step 4: Update CLAUDE.md + +If AGENTS.md changed significantly, also sync CLAUDE.md (the Claude Code-specific instruction file). + +### Step 5: Commit Per Repo + +```bash +cd +git add AGENTS.md CLAUDE.md +git commit -m "docs(agents): sync AGENTS.md with current repo state + +- Updated: +- Test count: X β†’ Y +- " +git push +``` + +## Report Format + +```markdown +## AGENTS.md Sync Report + +| Repo | Status | Sections Updated | Commit | +|------|--------|-----------------|--------| +| learning_ai_common_plat | βœ… Up to date | β€” | β€” | +| learning_ai_efforise | πŸ”„ Updated | Layout, Tests | abc123 | +| learning_ai_flowmonk | πŸ”„ Updated | API Endpoints | def456 | +| learning_ai_dev_intelli | ❌ Skipped | β€” | Needs manual review | + +### Key Findings +- +- +``` + +## Guardrails + +- **Never delete documentation** β€” only add or update +- **Preserve comments** β€” keep existing notes and explanations +- **Verify before commit** β€” run `pnpm typecheck` to ensure no doc references break +- **One repo per commit** β€” keep history clean diff --git a/AI.dev/PROMPTS/backend-module-crud.md b/AI.dev/PROMPTS/backend-module-crud.md new file mode 100644 index 00000000..a327e8d0 --- /dev/null +++ b/AI.dev/PROMPTS/backend-module-crud.md @@ -0,0 +1,246 @@ +--- +name: backend-module-crud +description: 'Add a complete Fastify CRUD module with types, repository, routes, and tests following ByteLyst conventions.' +argument-hint: 'Module name and parent repo, e.g. "habits in efforise", "workouts in peakpulse", "conversations in jarvisjr"' +agent: agent +--- + +# Backend Module CRUD Prompt + +Create a complete Fastify backend module with Zod-validated types, Cosmos repository, REST routes, and comprehensive tests. + +## Context β€” ByteLyst Backend Pattern + +Every product backend follows this module structure: +``` +backend/src/modules// +β”œβ”€β”€ types.ts # Zod schemas + TypeScript interfaces +β”œβ”€β”€ repository.ts # Cosmos DB CRUD operations +β”œβ”€β”€ routes.ts # Fastify REST endpoints +└── .test.ts # Vitest tests +``` + +**Key packages used:** +- `@bytelyst/datastore` β€” Cosmos DB abstraction (`getCollection()`) +- `@bytelyst/errors` β€” Typed HTTP errors (`BadRequestError`, `NotFoundError`, etc.) +- `@bytelyst/fastify-auth` β€” JWT auth middleware +- `zod` β€” Schema validation (service's own copy, NOT from @bytelyst/config) + +## Implementation Steps + +### 1. Create `types.ts` + +```typescript +import { z } from 'zod'; + +// ── Create schema (input from API) ── +export const createSchema = z.object({ + // Required fields + name: z.string().min(1).max(200), + // Optional fields + description: z.string().max(1000).optional(), + // Enum fields + status: z.enum(['active', 'paused', 'completed']).default('active'), +}); + +// ── Update schema (partial, for PATCH) ── +export const updateSchema = createSchema.partial(); + +// ── Full document (stored in Cosmos) ── +export const Schema = createSchema.extend({ + id: z.string().uuid(), + userId: z.string(), + productId: z.string(), + createdAt: z.string().datetime(), + updatedAt: z.string().datetime(), +}); + +// ── TypeScript types ── +export type Create = z.inferSchema>; +export type Update = z.inferSchema>; +export type = z.inferSchema>; +``` + +### 2. Create `repository.ts` + +```typescript +import { getCollection } from '../../lib/datastore.js'; +import type { Create, Update, } from './types.js'; +import { NotFoundError } from '../../lib/errors.js'; +import { randomUUID } from 'node:crypto'; + +const CONTAINER = '_'; + +function getContainer() { + return getCollection(CONTAINER); +} + +export async function create( + userId: string, + productId: string, + data: Create +): Promise<> { + const now = new Date().toISOString(); + const doc: = { + ...data, + id: randomUUID(), + userId, + productId, + createdAt: now, + updatedAt: now, + }; + const container = getContainer(); + await container.create(doc); + return doc; +} + +export async function list( + userId: string, + productId: string +): Promise<[]> { + const container = getContainer(); + return container.query({ + query: 'SELECT * FROM c WHERE c.userId = @userId AND c.productId = @productId ORDER BY c.createdAt DESC', + parameters: [ + { name: '@userId', value: userId }, + { name: '@productId', value: productId }, + ], + }); +} + +export async function getById( + id: string, + userId: string, + productId: string +): Promise<> { + const container = getContainer(); + const doc = await container.read(id, userId); + if (!doc || doc.productId !== productId) { + throw new NotFoundError(' not found'); + } + return doc; +} + +export async function update( + id: string, + userId: string, + productId: string, + data: Update +): Promise<> { + const existing = await getById(id, userId, productId); + const updated: = { + ...existing, + ...data, + updatedAt: new Date().toISOString(), + }; + const container = getContainer(); + await container.replace(id, updated, userId); + return updated; +} + +export async function delete( + id: string, + userId: string, + productId: string +): Promise { + await getById(id, userId, productId); // Verify ownership + const container = getContainer(); + await container.delete(id, userId); +} +``` + +### 3. Create `routes.ts` + +```typescript +import type { FastifyInstance } from 'fastify'; +import { createSchema, updateSchema } from './types.js'; +import * as repo from './repository.js'; +import { getUserId, getRequestProductId } from '../../lib/request-context.js'; + +export default async function Routes(app: FastifyInstance) { + // GET /api/ + app.get('/', async (req) => { + const userId = getUserId(req); + const productId = getRequestProductId(req); + return repo.list(userId, productId); + }); + + // GET /api//:id + app.get('//:id', async (req) => { + const { id } = req.params as { id: string }; + const userId = getUserId(req); + const productId = getRequestProductId(req); + return repo.getById(id, userId, productId); + }); + + // POST /api/ + app.post('/', async (req, reply) => { + const userId = getUserId(req); + const productId = getRequestProductId(req); + const data = createSchema.parse(req.body); + const entity = await repo.create(userId, productId, data); + reply.code(201); + return entity; + }); + + // PATCH /api//:id + app.patch('//:id', async (req) => { + const { id } = req.params as { id: string }; + const userId = getUserId(req); + const productId = getRequestProductId(req); + const data = updateSchema.parse(req.body); + return repo.update(id, userId, productId, data); + }); + + // DELETE /api//:id + app.delete('//:id', async (req, reply) => { + const { id } = req.params as { id: string }; + const userId = getUserId(req); + const productId = getRequestProductId(req); + await repo.delete(id, userId, productId); + reply.code(204); + }); +} +``` + +### 4. Register in `server.ts` + +```typescript +import Routes from './modules//routes.js'; +// ... +await app.register(Routes, { prefix: '/api' }); +``` + +### 5. Create tests + +Write tests covering: +- βœ… Create with valid data β†’ 201 +- βœ… Create with invalid data β†’ 400 +- βœ… List returns user's items only +- βœ… Get by ID returns correct item +- βœ… Get by ID with wrong user β†’ 404 +- βœ… Update modifies fields + updatedAt +- βœ… Delete removes item β†’ 204 +- βœ… Delete with wrong user β†’ 404 + +### 6. Validate + +```bash +cd backend +pnpm test +pnpm typecheck +pnpm build +``` + +### 7. Commit + +```bash +git add . +git commit -m "feat(): add CRUD module + +- types.ts: Zod schemas for create/update/ +- repository.ts: Cosmos CRUD with user ownership +- routes.ts: GET/POST/PATCH/DELETE endpoints +- tests: N tests covering CRUD + auth + validation" +git push +``` diff --git a/AI.dev/PROMPTS/cross-repo-debug.md b/AI.dev/PROMPTS/cross-repo-debug.md new file mode 100644 index 00000000..4841cab9 --- /dev/null +++ b/AI.dev/PROMPTS/cross-repo-debug.md @@ -0,0 +1,145 @@ +--- +name: cross-repo-debug +description: 'Systematically debug issues that span multiple ByteLyst repos, tracing from symptom to root cause across service boundaries.' +argument-hint: 'Symptom description, e.g. "auth token rejected by FlowMonk backend", "design tokens not applied in PeakPulse iOS", "platform-service 500 on /api/flags"' +agent: agent +--- + +# Cross-Repo Debug Prompt + +Systematically diagnose and fix bugs that span multiple repositories in the ByteLyst ecosystem. + +## Context β€” ByteLyst Architecture + +**Service topology:** +``` +Product clients (web/mobile) + β†’ Product backend (Fastify, port 40xx) + β†’ @bytelyst/* packages (shared libraries) + β†’ platform-service (port 4003: auth, flags, billing, etc.) + β†’ Cosmos DB (productId multi-tenancy) + β†’ Azurite (blob storage) +``` + +**Common cross-repo failure points:** +1. **Auth chain:** platform-service issues JWT β†’ product backend validates β†’ client stores +2. **Package version mismatch:** Zod, jose, or @azure/cosmos version conflicts between packages and services +3. **Config drift:** .env vars, .npmrc, or product.json out of sync +4. **API contract breaks:** platform-service endpoint changed but consumer not updated +5. **Design token gaps:** token JSON updated but generated files not regenerated/copied + +## Debug Protocol + +### Step 1: Symptom Capture + +Document: +- **What:** Exact error message, HTTP status, or unexpected behavior +- **Where:** Which repo/service/file/line +- **When:** Always, intermittent, or after a specific change +- **Who:** Which product(s) affected + +### Step 2: Trace the Call Chain + +Starting from the symptom, trace backwards: + +``` +1. Client (web/mobile) β€” check network tab, API client code +2. Product backend β€” check routes.ts, request-context.ts, auth.ts +3. Shared packages β€” check @bytelyst/* import versions +4. Platform service β€” check the module handling this request +5. Data layer β€” check Cosmos queries, partition keys, productId +``` + +For each layer, check: +- Is the service running? (`curl http://localhost:/health`) +- Are env vars set? (compare with `.env.example`) +- Are packages built? (`pnpm build` in common_plat) +- Are types aligned? (`pnpm typecheck`) + +### Step 3: Isolate + +Run targeted tests to narrow scope: +```bash +# Test the specific module +pnpm --filter @lysnrai/platform-service test -- --grep "auth" +pnpm --filter @bytelyst/auth test + +# Test the product backend +cd /backend && pnpm test + +# Typecheck across repos +cd learning_ai_common_plat && pnpm typecheck +cd && pnpm typecheck +``` + +### Step 4: Fix + +- Fix in the **lowest-level** repo first (packages β†’ services β†’ products) +- Rebuild packages if you changed a `@bytelyst/*` package: + ```bash + cd learning_ai_common_plat && pnpm build + ``` +- Reinstall in consumer repos if package API changed: + ```bash + cd && pnpm install + ``` + +### Step 5: Validate Across Repos + +After fixing: +```bash +# 1. Rebuild common platform +cd learning_ai_common_plat && pnpm build && pnpm test + +# 2. Reinstall + test affected products +cd && pnpm install && pnpm test + +# 3. Verify health endpoints +curl -s http://localhost:4003/health | jq . +curl -s http://localhost:/health | jq . +``` + +### Step 6: Commit in Correct Repos + +Commit in dependency order: +```bash +# Fix in common_plat first +cd learning_ai_common_plat +git add . && git commit -m "fix(): " && git push + +# Then fix in product repo +cd +git add . && git commit -m "fix(): " && git push +``` + +## Common Diagnosis Patterns + +### "Module not found" or import errors +- Check: Was `pnpm build` run in common_plat? +- Check: Are `file:` refs in product's `package.json` pointing to correct paths? +- Check: Is the export in the package's `src/index.ts`? + +### "Zod validation failed" or schema errors +- Check: Service uses self-contained Zod schemas in `src/lib/config.ts` (not from @bytelyst/config) +- Check: Zod version alignment between package and service + +### "401 Unauthorized" across services +- Check: JWT_SECRET matches between platform-service and product backend +- Check: Token is being forwarded in `Authorization: Bearer` header +- Check: Product backend's auth.ts re-exports correctly from @bytelyst/auth + +### Design tokens not working +- Check: Token generator was run (`pnpm --filter @bytelyst/design-tokens generate`) +- Check: Generated files were copied to consumer repos +- Check: CSS custom properties use correct product prefix (--er-*, --fm-*, --di-*, etc.) + +## Output + +For each issue found, report: +``` +### Issue: +- **Root cause:** <repo>/<file> β€” <explanation> +- **Fix:** <what was changed> +- **Commit:** `<hash>` in `<repo>` +- **Validated:** <test commands run> +``` diff --git a/AI.dev/PROMPTS/dependency-health-check.md b/AI.dev/PROMPTS/dependency-health-check.md new file mode 100644 index 00000000..d5805a4e --- /dev/null +++ b/AI.dev/PROMPTS/dependency-health-check.md @@ -0,0 +1,139 @@ +--- +name: dependency-health-check +description: 'Audit dependencies across ByteLyst repos for outdated packages, security vulnerabilities, version conflicts, and unused deps.' +argument-hint: 'Scope, e.g. "all repos", "learning_ai_common_plat only", "security audit only"' +agent: agent +--- + +# Dependency Health Check Prompt + +Audit and remediate dependency issues across the ByteLyst ecosystem. + +## Context β€” ByteLyst Dependency Conventions + +- **Package manager:** pnpm (workspace) β€” never npm or yarn +- **Heavy deps:** Use `peerDependencies` in `@bytelyst/*` packages, NOT `dependencies` +- **Workspace refs:** `"@bytelyst/<name>": "workspace:*"` for internal deps +- **Product refs:** `"@bytelyst/<name>": "file:../../learning_ai_common_plat/packages/<name>"` for product repos +- **Node version:** 22 (see `.nvmrc`) +- **Key shared deps:** `@azure/cosmos`, `jose`, `bcryptjs`, `zod`, `fastify` + +## Audit Protocol + +### Step 1: Scan Dependencies + +For each repo: +```bash +# Check for outdated packages +pnpm outdated + +# Security audit +pnpm audit + +# Check for unused dependencies +npx depcheck + +# Check for duplicate packages +pnpm why <package> +``` + +### Step 2: Classify Issues + +| Severity | Type | Action | +|----------|------|--------| +| πŸ”΄ **Critical** | Known security vulnerability (CVE) | Update immediately | +| πŸ”΄ **Critical** | Major version conflict causing runtime errors | Resolve version | +| 🟑 **High** | Outdated major version with breaking changes | Plan upgrade | +| 🟑 **High** | Unused dependency adding bundle bloat | Remove | +| πŸ”΅ **Medium** | Minor/patch updates available | Batch update | +| βšͺ **Low** | Cosmetic (deprecated warning, newer alternative) | Track for later | + +### Step 3: Check Cross-Repo Version Alignment + +Ensure these critical packages are aligned across all repos: + +| Package | Expected Range | Check | +|---------|---------------|-------| +| `typescript` | `^5.7` | All repos | +| `zod` | `^3.23` | All repos using Zod | +| `fastify` | `^5` | All backends | +| `vitest` | `^3` | All repos with tests | +| `jose` | `^5` or `^6` | Auth-related packages | +| `@azure/cosmos` | `^4` | Data layer | +| `react` | `^19` | Web/mobile clients | +| `next` | `^15` or `^16` | Next.js web apps | + +### Step 4: Safe Update Process + +#### Minor/patch updates (low risk): +```bash +pnpm update +pnpm test +pnpm typecheck +git add . && git commit -m "chore(deps): update minor/patch dependencies" && git push +``` + +#### Major updates (higher risk): +```bash +# Update one package at a time +pnpm update <package>@latest + +# Test immediately +pnpm test +pnpm typecheck +pnpm build + +# Commit separately +git add . && git commit -m "chore(deps): upgrade <package> to v<version>" && git push +``` + +#### Cross-repo updates: +```bash +# 1. Update in common_plat first +cd learning_ai_common_plat +pnpm update <package>@latest +pnpm build && pnpm test +git add . && git commit -m "chore(deps): upgrade <package>" && git push + +# 2. Then update in product repos +cd <product> +pnpm install # Picks up new versions from common_plat +pnpm test +git add . && git commit -m "chore(deps): sync <package> version" && git push +``` + +### Step 5: Report + +```markdown +## Dependency Health Check: <Scope> + +### Executive Summary +- Repos audited: N +- Critical issues: N +- Updates available: N +- Unused deps found: N + +### Critical Issues +| Repo | Package | Issue | Action | +|------|---------|-------|--------| + +### Version Alignment +| Package | Expected | Repos In Sync | Repos Mismatched | +|---------|----------|---------------|------------------| + +### Recommended Updates +| Priority | Repo | Package | Current | Target | Risk | +|----------|------|---------|---------|--------|------| + +### Unused Dependencies +| Repo | Package | Safe to Remove | +|------|---------|---------------| +``` + +## Guardrails + +- **Never update all dependencies at once** β€” do it incrementally +- **Always test after each update** β€” `pnpm test && pnpm typecheck && pnpm build` +- **Update common_plat first** β€” product repos depend on it +- **Check peerDependencies** β€” ensure package consumers are compatible +- **Don't force-resolve version conflicts** β€” understand why they exist first diff --git a/AI.dev/PROMPTS/docker-production-prep.md b/AI.dev/PROMPTS/docker-production-prep.md new file mode 100644 index 00000000..34746f2e --- /dev/null +++ b/AI.dev/PROMPTS/docker-production-prep.md @@ -0,0 +1,195 @@ +--- +name: docker-production-prep +description: 'Prepare Docker images for production deployment following ByteLyst conventions for corporate network, multi-stage builds, and security.' +argument-hint: 'Product and surface, e.g. "efforise backend", "flowmonk backend + web", "all product backends"' +agent: agent +--- + +# Docker Production Prep Prompt + +Build production-ready Docker images for ByteLyst services following network, security, and performance best practices. + +## Context β€” ByteLyst Docker Conventions + +**Critical rules from corporate network:** +- **Never use Alpine** β€” `apk` cannot bypass TLS interception; use `node:22-slim` (Debian) +- **Never use `corepack`** in Dockerfiles β€” use `npm install -g pnpm@10` or plain `npm` +- **Always add** `npm config set strict-ssl false` before any `npm install` in build stages +- **Always add** `ENV NODE_TLS_REJECT_UNAUTHORIZED=0` in build stages with native modules +- **Production images** don't need these workarounds (only build stages) + +## Dockerfile Template (Backend Service) + +```dockerfile +# ── Build Stage ──────────────────────────────────── +FROM node:22-slim AS builder + +# Corporate network workaround (build stage only) +RUN npm config set strict-ssl false +ENV NODE_TLS_REJECT_UNAUTHORIZED=0 + +WORKDIR /app + +# Install pnpm (never use corepack) +RUN npm install -g pnpm@10 + +# Copy workspace files +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY backend/package.json backend/ +COPY shared/ shared/ + +# Copy @bytelyst/* tarballs (if using prep-consumer.sh) +COPY .bytelyst-tarballs/ .bytelyst-tarballs/ + +# Install dependencies +RUN pnpm install --frozen-lockfile + +# Copy source and build +COPY backend/ backend/ +RUN cd backend && pnpm build + +# ── Production Stage ─────────────────────────────── +FROM node:22-slim AS production + +WORKDIR /app + +# Non-root user for security +RUN groupadd -r appuser && useradd -r -g appuser appuser + +# Copy only production artifacts +COPY --from=builder /app/backend/dist/ ./dist/ +COPY --from=builder /app/backend/package.json ./ +COPY --from=builder /app/shared/ ./shared/ +COPY --from=builder /app/node_modules/ ./node_modules/ + +# Security headers +ENV NODE_ENV=production + +# Health check +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD node -e "fetch('http://localhost:${PORT:-4020}/health').then(r => r.ok ? process.exit(0) : process.exit(1)).catch(() => process.exit(1))" + +# Run as non-root +USER appuser + +EXPOSE ${PORT:-4020} + +CMD ["node", "dist/server.js"] +``` + +## Preparation Steps + +### 1. Pack @bytelyst/* Dependencies + +If the Docker build doesn't have access to the sibling common_plat repo: + +```bash +cd ../learning_ai_common_plat +./scripts/prep-consumer.sh /path/to/<product> +``` + +This packs tarballs and rewrites `file:` refs in package.json. + +### 2. Create/Update docker-compose.yml + +```yaml +services: + backend: + build: + context: . + dockerfile: backend/Dockerfile + ports: + - "${PORT:-4020}:${PORT:-4020}" + env_file: ./backend/.env + restart: unless-stopped + depends_on: + platform-service: + condition: service_healthy + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://localhost:${PORT:-4020}/health')"] + interval: 30s + timeout: 3s + retries: 3 + + web: + build: + context: . + dockerfile: web/Dockerfile + ports: + - "3000:3000" + environment: + - NEXT_PUBLIC_API_URL=http://backend:${PORT:-4020} +``` + +### 3. Build & Test Locally + +```bash +# Build +docker compose build + +# Run +docker compose up -d + +# Verify health +docker compose ps +curl -s http://localhost:<port>/health | jq . + +# Check logs +docker compose logs backend --tail=20 + +# Run smoke test +curl -s http://localhost:<port>/api/<endpoint> | jq . + +# Cleanup +docker compose down +``` + +### 4. Security Scan + +```bash +# Scan the built image +docker scout cves <image> + +# Check for leaked secrets +docker history <image> --no-trunc | grep -i "secret\|key\|password" +``` + +### 5. Optimize Image Size + +```bash +# Check image size +docker images | grep <product> + +# Target: < 200MB for backend services +# If too large, check: +# - Are devDependencies excluded? (use --prod install) +# - Is the build stage copying unnecessary files? +# - Are node_modules pruned in the production stage? +``` + +### 6. Commit + +```bash +git add Dockerfile docker-compose.yml +git commit -m "chore(docker): production-ready Docker setup + +- Multi-stage build (builder + production) +- Non-root user for security +- Health check configured +- Corporate network workarounds in build stage only +- Production image: ~NMB" +git push +``` + +## Checklist + +- [ ] Base image: `node:22-slim` (never Alpine) +- [ ] No `corepack` usage +- [ ] `strict-ssl false` in build stage +- [ ] Multi-stage build (builder β†’ production) +- [ ] Non-root user in production stage +- [ ] Health check configured +- [ ] `NODE_ENV=production` in production stage +- [ ] No secrets in image layers +- [ ] `.dockerignore` excludes: node_modules, .git, .env, dist, coverage +- [ ] Image size < 200MB diff --git a/AI.dev/PROMPTS/ecosystem-audit.md b/AI.dev/PROMPTS/ecosystem-audit.md new file mode 100644 index 00000000..ad2b8179 --- /dev/null +++ b/AI.dev/PROMPTS/ecosystem-audit.md @@ -0,0 +1,148 @@ +--- +name: ecosystem-audit +description: 'Run a full health audit across the ByteLyst ecosystem β€” builds, tests, types, dependencies, config drift, and produce an actionable dashboard.' +argument-hint: 'Depth and focus, e.g. "full audit", "quick health check", "backend focus", "config drift only"' +agent: agent +--- + +# Ecosystem Audit Prompt + +Produce a comprehensive health dashboard across all ByteLyst repos with actionable findings. + +## Context β€” ByteLyst Ecosystem + +**37 repos** in `D:\BYTELYST\CODE\`, including: + +**Core platform:** +- `learning_ai_common_plat` β€” shared packages + services + +**Active products (with backends):** +- `learning_ai_efforise` (EffoRise, port 4020) +- `learning_ai_flowmonk` (FlowMonk, port 4017) +- `learning_ai_dev_intelli` (DevIntelli, port 4021) +- `learning_ai_peakpulse` (PeakPulse, port 4010) +- `learning_ai_clock` (ChronoMind, port 4011) +- `learning_ai_jarvis_jr` (JarvisJr, port 4012) +- `learning_ai_fastgap` (NomGap, port 4013) +- `learning_multimodal_memory_agents` (MindLyst, port 4014) + +**Active products (platform-only):** +- `learning_ai_auth_app` (ByteLyst Auth β€” no backend) +- `learning_ai_notes` (NoteLett) +- `learning_ai_trails` (ActionTrail) + +**Tooling & infrastructure:** +- `learning_ai_local_llms`, `learning_ai_local_memory_gpt` +- `learning_windsurf_setup`, `learning_claude_code_setup`, `learning_sidecar_setup` +- `learning_agent_monitoring_fx`, `learning_agentic_tools_portal` + +## Audit Dimensions + +### 1. Build Health +For each repo with a `package.json`: +```bash +pnpm install --frozen-lockfile # Can deps resolve? +pnpm build # Does it compile? +``` + +### 2. Type Safety +```bash +pnpm typecheck # TypeScript clean? +``` + +### 3. Test Health +```bash +pnpm test --run # All tests pass? +``` +Record: total tests, passing, failing, skipped. + +### 4. Config Consistency +Check alignment across repos: +- `.npmrc` matches canonical template? +- `.nvmrc` specifies Node 22? +- `tsconfig.json` extends base correctly? +- `.editorconfig` present? +- `shared/product.json` correct? +- `.env.example` up to date? + +### 5. Package Version Alignment +Verify shared deps are on compatible versions: +- TypeScript, Zod, Fastify, Vitest, React, Next.js +- `@bytelyst/*` packages (all on `workspace:*` or `file:`) + +### 6. Security +```bash +pnpm audit +# Check for high/critical vulnerabilities +``` + +### 7. Documentation Currency +- AGENTS.md matches current layout? +- README.md has setup instructions? +- CLAUDE.md exists? + +### 8. Git Hygiene +- Any repos with uncommitted changes? +- Any repos behind remote? +- Any repos with merge conflicts? + +## Output: Ecosystem Dashboard + +```markdown +# ByteLyst Ecosystem Health Dashboard +> Generated: <date> + +## Executive Summary +- Repos audited: N +- 🟒 Healthy: N +- 🟑 Issues: N +- πŸ”΄ Critical: N + +## Scorecard + +| Repo | Build | Types | Tests | Config | Deps | Security | Docs | Git | +|------|-------|-------|-------|--------|------|----------|------|-----| +| common_plat | βœ… | βœ… | 876/876 | βœ… | βœ… | βœ… | βœ… | clean | +| efforise | βœ… | βœ… | 65/65 | βœ… | βœ… | ⚠️ 2 | βœ… | clean | +| flowmonk | βœ… | ⚠️ 3 | 196/196 | βœ… | βœ… | βœ… | βœ… | dirty | +| ... | | | | | | | | | + +## Critical Issues (Fix First) +| Repo | Issue | Impact | Fix | +|------|-------|--------|-----| + +## Action Queue (Prioritized) +| # | Repo | Action | Effort | Impact | +|---|------|--------|--------|--------| +| 1 | ... | ... | S/M/L | High/Med/Low | + +## Config Drift Report +| Config | Expected | Drifted Repos | +|--------|----------|--------------| +| .npmrc | canonical template | <list> | +| .nvmrc | "22" | <list> | + +## Dependency Alignment +| Package | Version | Aligned | Misaligned | +|---------|---------|---------|-----------| +``` + +## Execution Tips + +- **Start with common_plat** β€” it's the foundation +- **Skip node_modules-only repos** β€” focus on active development repos +- **Parallelize where possible** β€” run independent repo checks simultaneously +- **Time-box expensive checks** β€” if `pnpm install` takes >2min, skip and note + +## Commit + +```bash +# If you fix issues during audit: +cd <repo> +git add . +git commit -m "fix(<scope>): resolve audit findings + +- <finding 1> +- <finding 2>" +git push +``` diff --git a/AI.dev/PROMPTS/new-product-scaffold.md b/AI.dev/PROMPTS/new-product-scaffold.md new file mode 100644 index 00000000..d80804d8 --- /dev/null +++ b/AI.dev/PROMPTS/new-product-scaffold.md @@ -0,0 +1,179 @@ +--- +name: new-product-scaffold +description: 'Scaffold a new ByteLyst product repo with backend, web, mobile, and full ecosystem integration.' +argument-hint: 'Product name, ID, and brief description, e.g. "TrackMate, trackmate, GPS-based workout tracker"' +agent: agent +--- + +# New Product Scaffold Prompt + +Create a new ByteLyst ecosystem product from scratch with proper platform integration, shared package usage, and consistent patterns. + +## Context β€” ByteLyst Ecosystem + +You are scaffolding a new product in the ByteLyst multi-repo ecosystem (`D:\BYTELYST\CODE\`). + +**Sibling products for reference:** +- EffoRise (`learning_ai_efforise`) β€” identity-based habit tracker +- FlowMonk (`learning_ai_flowmonk`) β€” agent-first planning platform +- DevIntelli (`learning_ai_dev_intelli`) β€” developer intelligence +- PeakPulse (`learning_ai_peakpulse`) β€” fitness tracker +- NomGap (`learning_ai_fastgap`) β€” fasting tracker + +**All products share:** +- `platform-service` (port 4003) for auth, flags, telemetry, billing +- `@bytelyst/*` packages for infrastructure +- Same Fastify module pattern, Zod validation, Vitest testing +- Design tokens from `@bytelyst/design-tokens` +- pnpm workspaces with `file:` refs to common platform + +## Scaffold Checklist + +### 1. Create Root Structure + +``` +learning_ai_<repo_name>/ +β”œβ”€β”€ backend/ # Fastify 5 product backend +β”œβ”€β”€ web/ or client/ # Next.js or Vite+React SPA +β”œβ”€β”€ mobile/ # React Native + Expo (optional) +β”œβ”€β”€ shared/ +β”‚ └── product.json # Canonical product identity +β”œβ”€β”€ docs/ +β”œβ”€β”€ scripts/ +β”‚ β”œβ”€β”€ secret-scan-repo.sh +β”‚ └── secret-scan-staged.sh +β”œβ”€β”€ .editorconfig +β”œβ”€β”€ .gitignore +β”œβ”€β”€ .npmrc # From canonical template (never hand-edit) +β”œβ”€β”€ .nvmrc # "22" +β”œβ”€β”€ .windsurfrules +β”œβ”€β”€ AGENTS.md +β”œβ”€β”€ CLAUDE.md +β”œβ”€β”€ README.md +β”œβ”€β”€ package.json # Root workspace scripts +β”œβ”€β”€ pnpm-workspace.yaml +β”œβ”€β”€ docker-compose.yml +└── tsconfig.json +``` + +### 2. Create `shared/product.json` + +```json +{ + "productId": "<product_id>", + "productName": "<ProductName>", + "productDescription": "<one-line description>", + "domain": "<product>.app", + "bundleIdIos": "com.bytelyst.<product_id>", + "bundleIdAndroid": "com.bytelyst.<product_id>", + "backendPort": <next_available_port>, + "tokenNamespace": "--<prefix>-" +} +``` + +**Port allocation:** Check existing products to find the next available port: +- EffoRise: 4020, DevIntelli: 4021, FlowMonk: 4017, PeakPulse: 4010, ChronoMind: 4011, JarvisJr: 4012, NomGap: 4013, MindLyst: 4014 + +### 3. Backend Setup + +Follow the pattern from EffoRise or FlowMonk: + +``` +backend/ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ server.ts # createServiceApp() + startService() +β”‚ β”œβ”€β”€ lib/ +β”‚ β”‚ β”œβ”€β”€ config.ts # Zod env schema (self-contained, no @bytelyst/config zod) +β”‚ β”‚ β”œβ”€β”€ product-config.ts # Read shared/product.json +β”‚ β”‚ β”œβ”€β”€ auth.ts # Re-export from @bytelyst/fastify-auth +β”‚ β”‚ β”œβ”€β”€ datastore.ts # @bytelyst/datastore bridge +β”‚ β”‚ β”œβ”€β”€ errors.ts # Re-export from @bytelyst/errors +β”‚ β”‚ β”œβ”€β”€ field-encrypt.ts # @bytelyst/field-encrypt if needed +β”‚ β”‚ β”œβ”€β”€ request-context.ts # getUserId(req), getRequestProductId(req) +β”‚ β”‚ β”œβ”€β”€ telemetry.ts # @bytelyst/backend-telemetry +β”‚ β”‚ └── feature-flags.ts # @bytelyst/backend-flags +β”‚ └── modules/ +β”‚ └── <first_module>/ # types.ts β†’ repository.ts β†’ routes.ts +β”œβ”€β”€ __tests__/ +β”œβ”€β”€ .env.example +β”œβ”€β”€ Dockerfile +β”œβ”€β”€ package.json +β”œβ”€β”€ tsconfig.json +└── vitest.config.ts +``` + +**Required `package.json` dependencies:** +```json +{ + "dependencies": { + "@bytelyst/fastify-core": "file:../../learning_ai_common_plat/packages/fastify-core", + "@bytelyst/config": "file:../../learning_ai_common_plat/packages/config", + "@bytelyst/errors": "file:../../learning_ai_common_plat/packages/errors", + "@bytelyst/datastore": "file:../../learning_ai_common_plat/packages/datastore", + "@bytelyst/auth": "file:../../learning_ai_common_plat/packages/auth", + "@bytelyst/fastify-auth": "file:../../learning_ai_common_plat/packages/fastify-auth" + } +} +``` + +### 4. Web Setup + +Use Next.js (App Router) or Vite + React. Include: +- Auth via `@bytelyst/react-auth` +- API client via `@bytelyst/api-client` +- Design tokens via `@bytelyst/design-tokens` with product namespace (`--<prefix>-*`) +- UI components via `@bytelyst/ui` +- Feature flags via `@bytelyst/feature-flag-client` + +### 5. AGENTS.md + +Follow the exact structure from sibling repos. Include: +- Project Identity table +- Repo Layout tree +- Tech Stack table +- Coding Conventions (MUST / MUST NOT) +- Cosmos Containers table +- Build & Test Commands +- Environment Variables +- Cross-Repo Automation reference + +### 6. pnpm-workspace.yaml + +```yaml +packages: + - 'backend' + - 'web' + - '../learning_ai_common_plat/packages/*' +``` + +### 7. Validation + +After scaffolding: +```bash +pnpm install +cd backend && pnpm typecheck && pnpm test && pnpm build +cd ../web && pnpm typecheck && pnpm build +``` + +### 8. Commit & Push + +```bash +git init +git add . +git commit -m "feat(<product>): scaffold product repo + +- Backend: Fastify 5, @bytelyst/* integration, first module +- Web: Next.js/Vite + React, auth + design tokens +- Shared: product.json, AGENTS.md, README.md +- Tests: initial test suite passing" +git remote add origin <remote_url> +git push -u origin main +``` + +## Guardrails + +- **Never hardcode productId** β€” always read from `shared/product.json` +- **Never use console.log** β€” use `req.log` / `app.log` +- **Never hand-edit .npmrc** β€” sync from canonical template +- **Always include tests** β€” even the scaffold should have passing tests +- **Always include AGENTS.md** β€” this is the source of truth for AI assistants diff --git a/AI.dev/PROMPTS/platform-integration.md b/AI.dev/PROMPTS/platform-integration.md new file mode 100644 index 00000000..6530bed5 --- /dev/null +++ b/AI.dev/PROMPTS/platform-integration.md @@ -0,0 +1,181 @@ +--- +name: platform-integration +description: 'Wire a product repo into the ByteLyst common platform ecosystem β€” auth, flags, telemetry, design tokens, and shared packages.' +argument-hint: 'Product repo name and integration scope, e.g. "learning_ai_efforise β€” full integration", "learning_ai_peakpulse β€” auth + flags only"' +agent: agent +--- + +# Platform Integration Prompt + +Connect a product repository to the ByteLyst common platform, wiring up auth, feature flags, telemetry, design tokens, and shared packages. + +## Context β€” Integration Architecture + +``` +Product Repo (e.g. learning_ai_efforise) +β”œβ”€β”€ backend/ ──→ @bytelyst/fastify-core, config, errors, datastore, auth, fastify-auth +β”œβ”€β”€ web/ ──→ @bytelyst/react-auth, api-client, design-tokens, ui, feature-flag-client +β”œβ”€β”€ mobile/ ──→ @bytelyst/auth-client, telemetry-client, feature-flag-client +└── shared/product.json ──→ Product identity consumed by all layers + β”‚ + β–Ό + platform-service (port 4003) + β”œβ”€β”€ Auth (JWT issue/validate) + β”œβ”€β”€ Feature flags (FNV-1a rollout) + β”œβ”€β”€ Telemetry (event ingestion) + β”œβ”€β”€ Billing (Stripe subscriptions) + └── Notifications (email, push) +``` + +## Integration Checklist + +### 1. Product Identity (`shared/product.json`) + +Ensure this file exists and is correct: +```json +{ + "productId": "<product_id>", + "productName": "<ProductName>", + "backendPort": <port>, + "tokenNamespace": "--<prefix>-" +} +``` + +### 2. Backend Integration + +#### Config (`backend/src/lib/config.ts`) +- Self-contained Zod schema (do NOT import zod from @bytelyst/config) +- Include: PORT, HOST, NODE_ENV, DB_PROVIDER, JWT_SECRET, PLATFORM_SERVICE_URL, CORS_ORIGIN + +#### Auth (`backend/src/lib/auth.ts`) +- Re-export from `@bytelyst/fastify-auth` +- Wire auth hook in `server.ts` for protected routes + +#### Datastore (`backend/src/lib/datastore.ts`) +- Re-export from `@bytelyst/datastore` +- Support `DB_PROVIDER=memory` for dev/test and `DB_PROVIDER=cosmos` for production + +#### Product Config (`backend/src/lib/product-config.ts`) +- Read `shared/product.json` +- Export `PRODUCT_ID`, `PRODUCT_NAME`, etc. + +#### Request Context (`backend/src/lib/request-context.ts`) +- `getUserId(req)` β€” extract userId from JWT +- `getRequestProductId(req)` β€” return productId from config + +#### Feature Flags (`backend/src/lib/feature-flags.ts`) +- Initialize `@bytelyst/backend-flags` with product config +- Register product-specific flags + +#### Telemetry (`backend/src/lib/telemetry.ts`) +- Initialize `@bytelyst/backend-telemetry` +- Buffer events for platform-service ingestion + +#### Diagnostics (`backend/src/lib/register-diagnostics.ts`) +- Register `/api/diagnostics/flags`, `/api/diagnostics/events` routes +- Health endpoint at `GET /health` + +### 3. Web Integration + +#### Auth (`web/src/lib/auth.ts`) +```typescript +import { createAuthContext } from '@bytelyst/react-auth'; +export const { AuthProvider, useAuth } = createAuthContext({ + platformUrl: process.env.NEXT_PUBLIC_PLATFORM_SERVICE_URL || 'http://localhost:4003', + productId: '<product_id>', +}); +``` + +#### API Client (`web/src/lib/api-helpers.ts`) +```typescript +import { createApiClient } from '@bytelyst/api-client'; +export function createProductClient(getToken: () => string | null) { + return createApiClient({ + baseUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:<port>', + getToken, + }); +} +``` + +#### Design Tokens (`web/src/app/globals.css` or `client/src/index.css`) +- Import `@bytelyst/design-tokens` CSS +- Use product namespace: `--<prefix>-*` custom properties +- Never hardcode hex colors + +#### Platform Clients +- `@bytelyst/feature-flag-client` β€” feature gating +- `@bytelyst/telemetry-client` β€” event tracking +- `@bytelyst/kill-switch-client` β€” remote kill switch +- `@bytelyst/diagnostics-client` β€” health monitoring + +### 4. Mobile Integration (if applicable) + +- `@bytelyst/auth-client` β€” login/register/token management +- `@bytelyst/telemetry-client` β€” event buffering +- `@bytelyst/feature-flag-client` β€” feature gating +- `@bytelyst/kill-switch-client` β€” remote disable +- `@bytelyst/offline-queue` β€” offline-first data sync + +### 5. pnpm Workspace Configuration + +`pnpm-workspace.yaml`: +```yaml +packages: + - 'backend' + - 'web' + - 'mobile' + - '../learning_ai_common_plat/packages/*' +``` + +`.npmrc` β€” sync from canonical template: +```bash +cd ../learning_ai_common_plat && bash scripts/sync-npmrc.sh +``` + +### 6. Docker Support + +`docker-compose.yml`: +```yaml +services: + backend: + build: ./backend + ports: + - "<port>:<port>" + env_file: ./backend/.env + depends_on: + - platform-service +``` + +### 7. Validation + +```bash +# Backend +cd backend && pnpm install && pnpm typecheck && pnpm test && pnpm build + +# Web +cd web && pnpm install && pnpm typecheck && pnpm build + +# Verify auth flow +curl -X POST http://localhost:4003/api/auth/login \ + -H "Content-Type: application/json" \ + -d '{"email":"test@example.com","password":"password"}' +# Use returned token against product backend: +curl http://localhost:<port>/health +curl http://localhost:<port>/api/<endpoint> \ + -H "Authorization: Bearer <token>" +``` + +### 8. Commit + +```bash +git add . +git commit -m "feat(platform): wire @bytelyst/* ecosystem integration + +- Auth: JWT via @bytelyst/fastify-auth + @bytelyst/react-auth +- Data: @bytelyst/datastore with memory/cosmos providers +- Flags: @bytelyst/feature-flag-client +- Telemetry: @bytelyst/telemetry-client +- Tokens: @bytelyst/design-tokens with --<prefix>-* namespace +- Tests: all passing" +git push +``` diff --git a/AI.dev/PROMPTS/prd-to-implementation.md b/AI.dev/PROMPTS/prd-to-implementation.md new file mode 100644 index 00000000..434cadb5 --- /dev/null +++ b/AI.dev/PROMPTS/prd-to-implementation.md @@ -0,0 +1,120 @@ +--- +name: prd-to-implementation +description: 'Convert a PRD into a concrete, phased implementation plan with file-level detail and dependency ordering.' +argument-hint: 'Path to PRD file or inline feature description, e.g. "docs/PRD.md", "add social fasting feature to NomGap"' +agent: agent +--- + +# PRD β†’ Implementation Plan Prompt + +Transform a Product Requirements Document into a detailed, phased implementation plan that an AI agent or developer can execute directly. + +## Context β€” ByteLyst Ecosystem + +You are planning implementation within the ByteLyst ecosystem (`D:\BYTELYST\CODE\`). + +**Architecture awareness:** +- Products have: `backend/` (Fastify 5), `web/` (Next.js or Vite+React), `mobile/` (Expo), `shared/` +- Backend modules follow: `types.ts` β†’ `repository.ts` β†’ `routes.ts` +- All data lives in Azure Cosmos DB with `productId` multi-tenancy +- Shared packages are `@bytelyst/*` from `learning_ai_common_plat/packages/` +- Platform service (port 4003) handles: auth, flags, telemetry, billing, notifications +- Design tokens provide all UI colors via CSS custom properties + +## Process + +### Step 1: PRD Analysis + +Read the PRD and extract: + +1. **Core features** β€” what must be built +2. **User flows** β€” how users interact +3. **Data model** β€” what gets stored +4. **API surface** β€” endpoints needed +5. **UI screens** β€” pages/components needed +6. **Constraints** β€” performance, security, compatibility +7. **Out of scope** β€” what to explicitly defer + +### Step 2: Dependency Mapping + +Determine what already exists: +- Which `@bytelyst/*` packages are needed? +- Does any sibling product have a similar pattern to reference? +- Are new Cosmos containers needed? +- Are new platform-service modules needed? +- Are design token additions needed? + +### Step 3: Phase Decomposition + +Break into phases following this priority order: + +1. **P0 β€” Foundation** (always first) + - Data model / Cosmos containers + - Backend types + Zod schemas + - Repository layer with basic CRUD + - Routes with auth + validation + - Initial tests + +2. **P1 β€” Core Features** + - Primary business logic + - Main API endpoints + - Web/mobile screens for primary flows + - Integration tests + +3. **P2 β€” Secondary Features** + - Less critical endpoints + - Settings, admin views + - Edge case handling + - Additional tests + +4. **P3 β€” Polish** + - Error handling refinement + - Loading states, empty states + - Accessibility + - Performance optimization + - E2E tests + +### Step 4: Generate Plan Document + +Output a `docs/IMPLEMENTATION_PLAN.md` with: + +```markdown +# <Feature Name> Implementation Plan + +> Generated from: <PRD path> +> Product: <product name> (<productId>) +> Estimated phases: N + +## Data Model + +| Container | Partition Key | Fields | Purpose | +|-----------|--------------|--------|---------| + +## API Surface + +| Method | Path | Auth | Description | +|--------|------|------|-------------| + +## Phase Breakdown + +### Phase 0: Foundation +- [ ] `backend/src/modules/<name>/types.ts` β€” Zod schemas +- [ ] `backend/src/modules/<name>/repository.ts` β€” Cosmos CRUD +- [ ] `backend/src/modules/<name>/routes.ts` β€” REST endpoints +- [ ] `backend/src/modules/<name>/<name>.test.ts` β€” Unit tests +- [ ] Register routes in `backend/src/server.ts` +**Validation:** `pnpm --filter backend test && pnpm --filter backend typecheck` +**Commit:** `feat(<module>): add <name> foundation (types, repo, routes, tests)` + +### Phase 1: Core Features +... +``` + +## Guardrails + +- **Every phase must be independently deployable** β€” no half-built features +- **Every phase includes tests** β€” minimum: unit tests for repository + routes +- **Backend first, frontend second** β€” API must exist before UI consumes it +- **Use existing patterns** β€” reference sibling product repos, don't reinvent +- **Include validation commands** β€” exact `pnpm` commands for each phase +- **Include commit messages** β€” pre-written conventional commits diff --git a/AI.dev/PROMPTS/pre-release-validation.md b/AI.dev/PROMPTS/pre-release-validation.md new file mode 100644 index 00000000..c66899f8 --- /dev/null +++ b/AI.dev/PROMPTS/pre-release-validation.md @@ -0,0 +1,157 @@ +--- +name: pre-release-validation +description: 'Run comprehensive pre-release checks across one or more ByteLyst repos: build, typecheck, test, lint, security audit, and bundle analysis.' +argument-hint: 'Repos and depth, e.g. "learning_ai_efforise full", "all backends quick", "common_plat + flowmonk"' +agent: agent +--- + +# Pre-Release Validation Prompt + +Execute a comprehensive pre-release validation workflow across ByteLyst repos with incremental fixes and commits. + +## Context β€” ByteLyst Release Conventions + +- **Build order:** common_plat packages β†’ common_plat services β†’ product backends β†’ web/mobile +- **Commit after each fix:** Keep history clean, push after each phase +- **Commit format:** `fix(scope): <issue>`, `test(scope): fix failing tests`, `style(scope): format fixes` + +## Validation Phases + +### Phase 1: Common Platform (always first) + +```bash +cd learning_ai_common_plat + +# 1. Install & build +pnpm install && pnpm build + +# 2. Type-check all packages and services +pnpm typecheck +# Fix β†’ git add . && git commit -m "fix(common): type-check fixes" && git push + +# 3. Run all tests +pnpm test +# Fix β†’ git add . && git commit -m "test(common): fix failing tests" && git push + +# 4. Security audit +pnpm audit +# Fix β†’ git add . && git commit -m "fix(common): security updates" && git push +``` + +### Phase 2: Product Backend + +```bash +cd <product>/backend + +# 1. Install & build +pnpm install && pnpm build + +# 2. Type-check +pnpm typecheck +# Fix β†’ git commit -m "fix(backend): type-check fixes" + +# 3. Tests +pnpm test +# Fix β†’ git commit -m "test(backend): fix failing tests" + +# 4. Verify health endpoint +# Start in background, test, stop: +pnpm dev & +sleep 3 +curl -s http://localhost:<port>/health | jq . +kill %1 +``` + +### Phase 3: Web Client + +```bash +cd <product>/web # or client/ + +# 1. Type-check +pnpm typecheck +# Fix β†’ git commit -m "fix(web): type-check fixes" + +# 2. Lint +pnpm lint +# Fix β†’ git commit -m "fix(web): lint fixes" + +# 3. Build (catches runtime issues) +pnpm build +# Fix β†’ git commit -m "fix(web): build fixes" + +# 4. Tests (if any) +pnpm test +# Fix β†’ git commit -m "test(web): fix failing tests" +``` + +### Phase 4: Mobile (if applicable) + +```bash +cd <product>/mobile + +# 1. Type-check +pnpm typecheck +# Fix β†’ git commit -m "fix(mobile): type-check fixes" + +# 2. Tests (if any) +pnpm test +# Fix β†’ git commit -m "test(mobile): fix failing tests" +``` + +### Phase 5: Integration Smoke Test + +```bash +# Start all services +cd <product> && docker compose up -d +sleep 10 + +# Health checks +curl -s http://localhost:4003/health | jq . +curl -s http://localhost:<product-port>/health | jq . + +# Basic auth flow +TOKEN=$(curl -s -X POST http://localhost:4003/api/auth/login \ + -H "Content-Type: application/json" \ + -d '{"email":"test@test.com","password":"password"}' | jq -r '.token') + +curl -s http://localhost:<product-port>/api/<endpoint> \ + -H "Authorization: Bearer $TOKEN" | jq . + +# Cleanup +docker compose down +``` + +## Validation Matrix + +Check all that apply: + +| Check | Backend | Web | Mobile | Platform | +|-------|---------|-----|--------|----------| +| `pnpm install` | ☐ | ☐ | ☐ | ☐ | +| `pnpm build` | ☐ | ☐ | ☐ | ☐ | +| `pnpm typecheck` | ☐ | ☐ | ☐ | ☐ | +| `pnpm test` | ☐ | ☐ | ☐ | ☐ | +| `pnpm lint` | ☐ | ☐ | ☐ | ☐ | +| `pnpm audit` | ☐ | ☐ | ☐ | ☐ | +| Health endpoint | ☐ | β€” | β€” | ☐ | +| Auth flow | ☐ | ☐ | ☐ | ☐ | + +## Report Format + +```markdown +## Pre-Release Validation: <Product> + +### Results +| Phase | Status | Issues Found | Issues Fixed | Commits | +|-------|--------|-------------|-------------|---------| +| Common Platform | βœ…/❌ | N | N | hash1, hash2 | +| Backend | βœ…/❌ | N | N | hash3 | +| Web | βœ…/❌ | N | N | hash4 | +| Mobile | βœ…/❌ | N | N | β€” | +| Integration | βœ…/❌ | N | N | β€” | + +### Blockers +- <any issues that couldn't be fixed> + +### Ready for Release: βœ… YES / ❌ NO +``` diff --git a/AI.dev/PROMPTS/refactor-with-tests.md b/AI.dev/PROMPTS/refactor-with-tests.md new file mode 100644 index 00000000..9b79a101 --- /dev/null +++ b/AI.dev/PROMPTS/refactor-with-tests.md @@ -0,0 +1,146 @@ +--- +name: refactor-with-tests +description: 'Safely refactor code with test-first methodology β€” capture behavior, refactor, verify nothing broke.' +argument-hint: 'Target module/file and refactor goal, e.g. "backend/src/modules/auth β€” extract token service", "simplify scheduler engine in FlowMonk"' +agent: agent +--- + +# Refactor with Tests Prompt + +Safely refactor code by first capturing existing behavior in tests, then restructuring while keeping all tests green. + +## Context β€” ByteLyst Conventions + +- **Test runner:** Vitest (TypeScript), pytest (Python) +- **Test location:** Same module directory or `__tests__/` +- **Never modify tests to make them pass** β€” fix the code +- **Commit format:** `refactor(scope): description` + +## Refactor Protocol + +### Step 1: Understand Current Behavior + +Before touching any code: + +1. **Read the code** β€” understand what it does, not just the structure +2. **Read existing tests** β€” understand what's already covered +3. **Run existing tests** β€” confirm they pass: + ```bash + pnpm test + pnpm typecheck + ``` +4. **Identify the API surface** β€” what do consumers depend on? + - Exported functions/types + - REST endpoint contracts + - Side effects (database writes, events emitted) + +### Step 2: Add Missing Tests (Before Refactoring) + +If test coverage is insufficient, add tests for current behavior FIRST: + +```typescript +// Capture existing behavior before refactoring +describe('<Module> β€” pre-refactor behavior capture', () => { + it('should return X when given Y', () => { + // Test current behavior, even if the implementation is ugly + }); + + it('should throw NotFoundError for missing items', () => { + // Edge cases that must be preserved + }); + + it('should include productId in all created documents', () => { + // Ecosystem invariants + }); +}); +``` + +**Commit these tests separately:** +```bash +git add . +git commit -m "test(<scope>): capture pre-refactor behavior (N tests)" +``` + +### Step 3: Plan the Refactor + +Document what will change and what must stay the same: + +- **Changing:** Internal structure, file organization, naming +- **Preserving:** API surface, behavior, test contracts +- **New patterns:** What you're moving toward (e.g., extract service class, split module) + +### Step 4: Refactor in Small Steps + +For each step: + +1. Make ONE structural change +2. Run tests: `pnpm test` +3. Run typecheck: `pnpm typecheck` +4. If tests pass β†’ commit +5. If tests fail β†’ undo and retry with smaller step + +```bash +# After each small refactor step +pnpm test && pnpm typecheck && \ +git add . && git commit -m "refactor(<scope>): <what changed>" +``` + +### Step 5: Verify Completeness + +After all refactoring: + +```bash +# Full validation +pnpm build && pnpm typecheck && pnpm test + +# Check no exports were broken +# If this is a @bytelyst/* package: +cd learning_ai_common_plat && pnpm build && pnpm test +``` + +### Step 6: Update Documentation + +If the refactor changed: +- File locations β†’ update AGENTS.md repo layout +- API surface β†’ update README.md or API docs +- Module structure β†’ update any roadmap or architecture docs + +```bash +git add . +git commit -m "docs(<scope>): update docs after <module> refactor" +git push +``` + +## Common Refactor Patterns + +### Extract Service Class +``` +Before: routes.ts has business logic mixed with HTTP handling +After: routes.ts β†’ service.ts β†’ repository.ts (routes are thin) +``` + +### Split Module +``` +Before: modules/schedule/ has 500-line routes.ts +After: modules/schedule/ + modules/schedule-entries/ (each focused) +``` + +### Extract Shared Package +``` +Before: Two products have duplicate utility code +After: New @bytelyst/* package consumed by both +``` + +### Consolidate Re-exports +``` +Before: Each file imports from @bytelyst/* directly +After: src/lib/ re-exports, internal files import from src/lib/ +``` + +## Guardrails + +- **Test first, refactor second.** Never refactor without test coverage. +- **Small commits.** Each commit should be revertible without losing other changes. +- **No behavior changes.** Refactoring changes structure, not behavior. If you're fixing bugs, that's a separate commit. +- **No export changes** without updating all consumers. +- **Run the full suite** after every commit, not just the changed module's tests. diff --git a/AI.dev/PROMPTS/roadmap-execution.md b/AI.dev/PROMPTS/roadmap-execution.md new file mode 100644 index 00000000..a060a7a1 --- /dev/null +++ b/AI.dev/PROMPTS/roadmap-execution.md @@ -0,0 +1,124 @@ +--- +name: roadmap-execution +description: 'Execute a phased roadmap with checkpoint commits, incremental validation, and progress tracking.' +argument-hint: 'Roadmap file path or inline description, e.g. "docs/ROADMAP.md", "Phase 2 of FlowMonk backend", "implement push notifications"' +agent: agent +--- + +# Roadmap Execution Prompt + +Execute a phased implementation roadmap with disciplined checkpoint commits, incremental validation, and progress tracking. + +## Context β€” ByteLyst Ecosystem + +You are working in the ByteLyst multi-repo ecosystem (`D:\BYTELYST\CODE\`). + +**Key conventions:** +- **Package manager:** pnpm (workspace). Never use npm or yarn. +- **Module system:** ESM everywhere (`"type": "module"`, `.js` extensions in imports) +- **Backend pattern:** Fastify 5 + Zod validation. Modules follow `types.ts` β†’ `repository.ts` β†’ `routes.ts` +- **Shared packages:** `@bytelyst/*` in `learning_ai_common_plat/packages/` +- **Services:** `@lysnrai/*` in `learning_ai_common_plat/services/` +- **Product identity:** Every Cosmos document MUST include `productId` field +- **Design tokens:** Never hardcode colors β€” use `@bytelyst/design-tokens` CSS custom properties +- **Commit format:** `type(scope): description` β€” types: `feat`, `fix`, `docs`, `refactor`, `test`, `chore` +- **Tests:** Vitest for TS, pytest for Python. Never modify tests to make them pass β€” fix the code. + +## Execution Protocol + +### Phase 0: Understand the Roadmap + +1. **Read the roadmap document** (if provided as file path) or parse the inline description +2. **Identify all phases/milestones** and their dependencies +3. **Estimate scope** for each phase (files touched, tests needed, risk level) +4. **Create a tracker** β€” write a `docs/IMPLEMENTATION_TRACKER.md` with: + - Phase list with `[ ]` / `[/]` / `[x]` status + - Key files to create/modify per phase + - Validation criteria per phase + - Commit message for each checkpoint + +### Phase N: Execute Each Phase + +For each phase, follow this cycle: + +#### Step 1: Plan +- List files to create or modify +- Identify which `@bytelyst/*` packages are needed +- Note any new dependencies + +#### Step 2: Implement +- Write code following the established patterns in this repo +- Use existing `src/lib/` re-exports for shared packages +- Every new API endpoint gets Zod schema validation +- Every new Cosmos container uses `productId` partition-aware queries + +#### Step 3: Test +- Add tests alongside implementation (same module directory or `__tests__/`) +- Run tests: `pnpm test` or `pnpm --filter <package> test` +- Run typecheck: `pnpm typecheck` or `pnpm --filter <package> typecheck` +- Fix any failures before proceeding + +#### Step 4: Validate +- Verify the feature works end-to-end (API β†’ UI if applicable) +- Check for regressions: run the full test suite +- Review for ecosystem compliance: + - βœ… `productId` on all Cosmos docs + - βœ… No `console.log` (use `req.log` / `app.log`) + - βœ… No `any` types + - βœ… No hardcoded colors + - βœ… No hardcoded secrets + +#### Step 5: Checkpoint Commit +```bash +git add . +git commit -m "feat(<scope>): <phase-description> + +- <key change 1> +- <key change 2> +- Tests: <N> new tests, all passing" +git push +``` + +#### Step 6: Update Tracker +- Mark the phase `[x]` in `IMPLEMENTATION_TRACKER.md` +- Add the commit hash +- Note any deferred items or follow-ups + +### Completion + +After all phases: + +1. **Run full validation:** + ```bash + pnpm build && pnpm typecheck && pnpm test + ``` +2. **Update AGENTS.md** if the repo layout, API endpoints, or test counts changed +3. **Update README.md** if new features, commands, or setup steps were added +4. **Final commit:** + ```bash + git add . + git commit -m "docs(<scope>): update docs for <roadmap-name> completion" + git push + ``` + +## Output Format + +Report progress after each phase: + +``` +## Phase N: <Name> βœ… + +**Commit:** `abc1234` +**Files changed:** 5 created, 2 modified +**Tests:** 12 new tests, all passing +**Validation:** typecheck βœ…, lint βœ…, test βœ… +**Notes:** <any deferred items or follow-ups> +``` + +## Guardrails + +- **Never skip tests.** Every phase must include test validation. +- **Never make big-bang commits.** Each phase gets its own checkpoint. +- **Never break existing tests.** If a test fails, fix the code, not the test. +- **Never hardcode values.** Use config, env vars, and design tokens. +- **Always verify before committing.** Run typecheck + test before every commit. diff --git a/AI.dev/PROMPTS/test-gap-analysis.md b/AI.dev/PROMPTS/test-gap-analysis.md new file mode 100644 index 00000000..81f80616 --- /dev/null +++ b/AI.dev/PROMPTS/test-gap-analysis.md @@ -0,0 +1,145 @@ +--- +name: test-gap-analysis +description: 'Identify test coverage gaps in a repo, prioritize by risk, and generate targeted tests for the most critical uncovered code.' +argument-hint: 'Repo name or path, e.g. "learning_ai_efforise", "learning_ai_flowmonk backend only", "all product backends"' +agent: agent +--- + +# Test Gap Analysis Prompt + +Audit test coverage in a ByteLyst repo, identify the riskiest gaps, and generate high-value tests. + +## Context β€” ByteLyst Testing Conventions + +- **Runner:** Vitest for all TypeScript code +- **Pattern:** Tests live in `__tests__/` or alongside source as `<module>.test.ts` +- **Helpers:** `buildTestApp()` via `src/test-helpers.ts` for Fastify inject testing +- **Mocks:** `@bytelyst/testing` for shared mock utilities +- **Coverage targets:** Backend 80%, Web 70%, Shared packages 90% + +## Analysis Protocol + +### Step 1: Inventory + +Scan the repo and build a map: + +``` +Source files: N files +Test files: M files +Coverage ratio: M/N (% of source files with tests) +``` + +For each source module, classify: +- βœ… Has tests +- ⚠️ Has partial tests (some functions uncovered) +- ❌ No tests +- πŸ”’ Low risk (config, types-only, re-exports) +- πŸ”΄ High risk (business logic, data mutations, auth) + +### Step 2: Prioritize Gaps + +Rank uncovered code by risk: + +| Priority | Category | Why | +|----------|----------|-----| +| **P0** | Auth/security logic | Vulnerabilities if broken | +| **P0** | Data mutation (repository.ts) | Data corruption if broken | +| **P1** | Business logic (services, engines) | Core features break | +| **P1** | API routes with validation | Contract violations | +| **P2** | Utility functions | Indirect failures | +| **P3** | UI components (rendering) | Visual but not critical | +| **P4** | Config, types, re-exports | Very low risk | + +### Step 3: Generate Tests + +For each P0/P1 gap, generate tests following this structure: + +```typescript +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +describe('<Module>', () => { + // Setup + beforeEach(() => { + // Fresh state for each test + }); + + // Happy path + it('should <expected behavior> when <condition>', async () => { + // Arrange + // Act + // Assert + }); + + // Validation + it('should reject invalid input', async () => { + // Test Zod schema validation + }); + + // Auth + it('should enforce user ownership', async () => { + // Test that user A cannot access user B's data + }); + + // Edge cases + it('should handle <edge case>', async () => { + // Empty arrays, null values, missing fields + }); + + // Error paths + it('should throw NotFoundError for missing <entity>', async () => { + // Test error handling + }); +}); +``` + +### Step 4: Run & Validate + +```bash +pnpm test --coverage +pnpm typecheck +``` + +### Step 5: Report + +Output a coverage gap report: + +```markdown +## Test Gap Analysis: <Repo> + +### Summary +- Source files: N +- Test files: M (before) β†’ M+K (after) +- Coverage: X% β†’ Y% + +### Gaps Filled (this session) +| Module | Tests Added | Risk Level | +|--------|-------------|------------| + +### Remaining Gaps +| Module | Risk Level | Effort | Suggested Next Step | +|--------|------------|--------|---------------------| + +### Recommendations +1. ... +2. ... +``` + +### Step 6: Commit + +```bash +git add . +git commit -m "test(<scope>): fill coverage gaps in <modules> + +- Added N tests across M modules +- Coverage: X% β†’ Y% +- Focus: <P0/P1 risk areas addressed>" +git push +``` + +## Anti-Patterns to Avoid + +- ❌ Don't write snapshot tests for API responses (too brittle) +- ❌ Don't test private implementation details (test behavior, not internals) +- ❌ Don't mock the thing you're testing (mock dependencies only) +- ❌ Don't write tests that always pass regardless of code changes +- ❌ Don't chase 100% coverage β€” focus on high-risk code diff --git a/AI.dev/PROMPTS/type-safety-sweep.md b/AI.dev/PROMPTS/type-safety-sweep.md new file mode 100644 index 00000000..30827231 --- /dev/null +++ b/AI.dev/PROMPTS/type-safety-sweep.md @@ -0,0 +1,137 @@ +--- +name: type-safety-sweep +description: 'Fix TypeScript errors across a repo or the full workspace with systematic triage and minimal code changes.' +argument-hint: 'Scope, e.g. "learning_ai_flowmonk", "all backends", "common_plat packages only"' +agent: agent +--- + +# Type Safety Sweep Prompt + +Systematically fix TypeScript errors across ByteLyst repos with minimal, safe changes. + +## Context β€” ByteLyst TypeScript Conventions + +- **Target:** ES2022, `moduleResolution: NodeNext` +- **Strict mode:** `strict: true` in all repos +- **Base config:** Extends `../../tsconfig.base.json` (from common_plat) +- **Module system:** ESM (`"type": "module"`) with `.js` extensions in imports +- **No `any`:** Use Zod inference, explicit types, or `unknown` with type guards + +## Sweep Protocol + +### Step 1: Run Typecheck + +```bash +# Single repo +pnpm typecheck + +# Workspace-wide +cd learning_ai_common_plat && pnpm typecheck +cd <product> && pnpm typecheck +``` + +### Step 2: Triage Errors + +Categorize each error: + +| Category | Fix Strategy | Risk | +|----------|-------------|------| +| **Missing `.js` extension** | Add `.js` to import path | Low | +| **Implicit `any`** | Add explicit type annotation | Low | +| **Missing property** | Add property to interface/schema | Medium | +| **Type mismatch** | Fix the value, not the type (usually) | Medium | +| **Package type conflict** | Check peer dep versions | High | +| **Structural break** | Needs design decision | High | + +### Step 3: Fix by Category + +#### Low-risk fixes (do first) +```typescript +// Missing .js extension +- import { foo } from './utils'; ++ import { foo } from './utils.js'; + +// Implicit any +- function handle(req, reply) { ++ function handle(req: FastifyRequest, reply: FastifyReply) { + +// Unused imports +- import { unused, used } from './types.js'; ++ import { used } from './types.js'; +``` + +#### Medium-risk fixes +```typescript +// Missing property β€” add to schema +const schema = z.object({ + name: z.string(), ++ description: z.string().optional(), // Was missing +}); + +// Type mismatch β€” fix the value +- const port: number = process.env.PORT; // string assigned to number ++ const port: number = Number(process.env.PORT) || 4003; +``` + +#### High-risk fixes (get approval first) +- Package version conflicts β†’ document and propose solution +- Structural type breaks β†’ explain what changed and why + +### Step 4: Validate + +After each batch of fixes: +```bash +pnpm typecheck # Must pass +pnpm test # Must still pass +pnpm build # Must still build +``` + +### Step 5: Commit + +Group fixes logically: +```bash +# Low-risk batch +git add . +git commit -m "fix(<scope>): resolve TypeScript errors (import extensions, explicit types)" + +# Medium-risk batch +git add . +git commit -m "fix(<scope>): fix type mismatches in <modules>" + +git push +``` + +## Common ByteLyst Type Issues + +### Zod version mismatch +**Symptom:** `Type 'z.ZodString' is not assignable to type 'z.ZodString'` +**Fix:** Services must use self-contained Zod schemas in `src/lib/config.ts`, NOT import from @bytelyst/config + +### Package export types +**Symptom:** `Cannot find module '@bytelyst/errors' or its corresponding type declarations` +**Fix:** Build the package first: `cd learning_ai_common_plat && pnpm build` + +### Fastify request types +**Symptom:** `Property 'user' does not exist on type 'FastifyRequest'` +**Fix:** Use `getUserId(req)` from `src/lib/request-context.ts` instead of `req.user` + +### Cosmos document types +**Symptom:** `Type '{ name: string }' is missing ... 'productId'` +**Fix:** Always include `productId` when creating documents + +## Report Format + +```markdown +## Type Safety Sweep: <Repo> + +| Category | Count | Fixed | Remaining | +|----------|-------|-------|-----------| +| Import extensions | N | N | 0 | +| Implicit any | N | N | 0 | +| Type mismatches | N | N | M | +| Package conflicts | N | 0 | N | +| **Total** | **X** | **Y** | **Z** | + +### Deferred Issues +- <issue>: <why deferred> (needs <decision/approval>) +```