From 04239f78611fb4e2ce31a58c10fee93dd2d5902d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 3 Jan 2026 20:15:33 +0000 Subject: [PATCH 1/3] Initial plan From 0ab852d227088503da4111be3691ffb0f9afd2dc Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 3 Jan 2026 20:17:49 +0000 Subject: [PATCH 2/3] Initial plan: Fix README styles documentation Co-authored-by: johndoe6345789 <224850594+johndoe6345789@users.noreply.github.com> --- .github/COPILOT_ANALYSIS.md | 402 +- .github/COPILOT_SDLC_SUMMARY.md | 864 +- .github/PULL_REQUEST_TEMPLATE.md | 486 +- .github/TEMPLATES.md | 686 +- .github/copilot-instructions.md | 494 +- .../deploy/6-deploy-ci-local.prompt.md | 34 +- .../deploy/6-deploy-production.prompt.md | 70 +- .../backend/3-impl-database.prompt.md | 44 +- .../backend/3-impl-dbal-entity.prompt.md | 52 +- .../backend/3-impl-lua-script.prompt.md | 72 +- .../backend/3-impl-migration.prompt.md | 78 +- .../frontend/3-impl-component.prompt.md | 54 +- .../frontend/3-impl-feature.prompt.md | 64 +- .../frontend/3-impl-package.prompt.md | 56 +- .../maintain/7-maintain-debug.prompt.md | 88 +- .../maintain/7-maintain-performance.prompt.md | 92 +- .../maintain/7-maintain-refactor.prompt.md | 108 +- .../maintain/7-maintain-security.prompt.md | 108 +- .github/prompts/misc/EEK-STUCK.md | 6 +- .github/prompts/misc/LAMBDA_PROMPT.md | 2 +- .github/prompts/test/4-test-run.prompt.md | 76 +- .github/prompts/test/4-test-write.prompt.md | 52 +- .github/prompts/workflow/0-kickstart.md | 142 +- .../prompts/workflow/1-plan-feature.prompt.md | 42 +- .../workflow/2-design-component.prompt.md | 52 +- .../prompts/workflow/5-review-code.prompt.md | 70 +- .../prompts/workflow/8-docs-feature.prompt.md | 70 +- .github/workflows/README.md | 1142 +- config/lint/eslint.config.js | 94 +- config/misc/json/components.json | 40 +- config/misc/json/renovate.json | 12 +- config/misc/json/runtime.config.json | 4 +- config/package-lock.json | 3302 ++-- config/package.json | 78 +- config/test/playwright.config.ts | 84 +- config/test/vite.config.ts | 2 +- config/test/vitest.config.ts | 76 +- dbal/README.md | 94 +- dbal/development/package.json | 92 +- .../lua-script/store/in-memory-store.ts | 18 +- .../src/core/entities/lua-script/types.ts | 98 +- .../entities/package/store/in-memory-store.ts | 20 +- .../src/core/entities/package/types.ts | 64 +- .../package/validation/validate-id.ts | 18 +- .../validation/validate-package-create.ts | 18 +- .../validation/validate-package-update.ts | 18 +- .../entities/page/store/in-memory-store.ts | 20 +- .../src/core/entities/page/types.ts | 106 +- .../entities/page/validation/validate-id.ts | 18 +- .../page/validation/validate-page-create.ts | 18 +- .../page/validation/validate-page-update.ts | 18 +- .../entities/session/store/in-memory-store.ts | 20 +- .../src/core/entities/session/types.ts | 54 +- .../session/validation/validate-id.ts | 18 +- .../validation/validate-session-create.ts | 18 +- .../validation/validate-session-update.ts | 18 +- dbal/development/src/core/entities/types.ts | 128 +- .../entities/user/store/in-memory-store.ts | 22 +- .../src/core/entities/user/types.ts | 58 +- .../entities/user/validation/validate-id.ts | 18 +- .../user/validation/validate-user-create.ts | 18 +- .../user/validation/validate-user-update.ts | 18 +- .../workflow/store/in-memory-store.ts | 18 +- .../src/core/entities/workflow/types.ts | 60 +- .../workflow/validation/validate-id.ts | 18 +- .../validation/validate-workflow-create.ts | 18 +- .../validation/validate-workflow-update.ts | 18 +- .../foundation/validation/is-valid-email.ts | 10 +- dbal/development/src/core/types.ts | 44 +- .../validation/entities/lua-script/types.ts | 2 +- .../core/validation/entities/package/types.ts | 2 +- .../src/core/validation/entities/types.ts | 36 +- .../src/core/validation/is-valid-email.ts | 18 +- .../src/core/validation/is-valid-semver.ts | 18 +- .../src/core/validation/is-valid-slug.ts | 18 +- .../src/core/validation/is-valid-username.ts | 18 +- dbal/development/tests/blob/index.test.ts | 76 +- .../tests/core/client-batch.test.ts | 282 +- .../tests/core/client-lua-scripts.test.ts | 250 +- .../tests/core/client-workflows.test.ts | 250 +- .../tests/core/entities/lua-script.test.ts | 172 +- .../tests/core/entities/session.test.ts | 164 +- ...alidate-component-hierarchy-create.test.ts | 54 +- ...alidate-component-hierarchy-update.test.ts | 38 +- .../validate-credential-create.test.ts | 48 +- .../validate-credential-update.test.ts | 38 +- .../validate-lua-script-create.test.ts | 58 +- .../validate-lua-script-update.test.ts | 40 +- .../package/validate-package-create.test.ts | 56 +- .../package/validate-package-update.test.ts | 40 +- .../page/validate-page-create.test.ts | 72 +- .../page/validate-page-update.test.ts | 56 +- .../session/validate-session-create.test.ts | 48 +- .../session/validate-session-update.test.ts | 38 +- .../user/validate-user-create.test.ts | 68 +- .../user/validate-user-update.test.ts | 60 +- .../validation/entities/validate-id.test.ts | 26 +- .../workflow/validate-workflow-create.test.ts | 56 +- .../workflow/validate-workflow-update.test.ts | 38 +- .../predicates/string/is-valid-email.test.ts | 42 +- .../predicates/string/is-valid-semver.test.ts | 28 +- .../predicates/string/is-valid-slug.test.ts | 42 +- .../predicates/string/is-valid-title.test.ts | 32 +- .../string/is-valid-username.test.ts | 42 +- .../predicates/type/is-plain-object.test.ts | 28 +- .../predicates/type/is-valid-date.test.ts | 34 +- .../predicates/type/is-valid-level.test.ts | 32 +- .../predicates/type/is-valid-uuid.test.ts | 26 +- dbal/development/tsconfig.json | 56 +- dbal/docs/AGENTS.md | 1208 +- dbal/docs/BEFORE_AFTER.md | 264 +- dbal/docs/PROJECT.md | 308 +- dbal/docs/README.md | 874 +- dbal/docs/README_INDEX.md | 170 +- dbal/docs/RESTRUCTURE_SUMMARY.md | 246 +- dbal/docs/S3_CONFIGURATION.md | 418 +- dbal/production/build-config/CMakeLists.txt | 208 +- .../build-config/CMakeUserPresets.json | 16 +- dbal/production/build-config/conanfile.txt | 34 +- dbal/production/docs/CVE_ANALYSIS.md | 630 +- .../production/docs/CVE_COMPARISON_SUMMARY.md | 352 +- dbal/production/docs/IMPLEMENTATION_STATUS.md | 236 +- dbal/production/docs/PHASE3_DAEMON.md | 946 +- dbal/production/docs/README.Docker.md | 516 +- dbal/production/docs/README.Linting.md | 632 +- dbal/production/docs/README.md | 868 +- dbal/production/docs/SECURITY_TESTING.md | 350 +- dbal/production/lint-config/lint.sh | 330 +- dbal/shared/api/versioning/compat.md | 372 +- .../docs/CAPABILITIES_IMPLEMENTATION.md | 60 +- dbal/shared/docs/CVE_ANALYSIS_2025_12.md | 4620 +++--- dbal/shared/docs/IMPLEMENTATION_SUMMARY.md | 1056 +- dbal/shared/docs/PHASE2_COMPLETE.md | 842 +- dbal/shared/docs/PHASE2_IMPLEMENTATION.md | 1030 +- dbal/shared/docs/QUICK_START.md | 794 +- dbal/shared/docs/SPARK_INTEGRATION.md | 1028 +- dbal/shared/tools/BUILD_ASSISTANT_README.md | 448 +- dbal/shared/tools/cpp-build-assistant.ts | 40 +- dbal/shared/tools/cpp-build-assistant/cli.ts | 250 +- .../tools/cpp-build-assistant/config.ts | 40 +- .../tools/cpp-build-assistant/dependencies.ts | 94 +- .../shared/tools/cpp-build-assistant/index.ts | 122 +- .../tools/cpp-build-assistant/logging.ts | 36 +- .../tools/cpp-build-assistant/runner.ts | 20 +- .../shared/tools/cpp-build-assistant/types.ts | 22 +- .../tools/cpp-build-assistant/workflow.ts | 308 +- dbal/shared/ui/DaemonPage.tsx | 36 +- dbal/shared/ui/status.ts | 26 +- deployment/README.md | 672 +- deployment/scripts/init-db.sh | 62 +- deployment/scripts/start.sh | 304 +- frontends/cli/CMakeLists.txt | 70 +- frontends/cli/README.md | 228 +- frontends/cli/conanfile.txt | 32 +- frontends/dbal/.eslintrc.json | 8 +- frontends/dbal/README.md | 50 +- frontends/dbal/app/api/status/route.ts | 12 +- frontends/dbal/app/layout.tsx | 66 +- frontends/dbal/app/page.tsx | 14 +- frontends/dbal/e2e/README.md | 40 +- frontends/dbal/e2e/smoke.spec.ts | 52 +- frontends/dbal/next.config.ts | 14 +- frontends/dbal/package-lock.json | 13160 ++++++++-------- frontends/dbal/package.json | 66 +- frontends/dbal/playwright.config.ts | 56 +- frontends/dbal/src/DaemonPage.tsx | 216 +- frontends/dbal/src/ServerStatusPanel.tsx | 212 +- frontends/dbal/src/index.ts | 2 +- frontends/dbal/src/status.ts | 94 +- frontends/dbal/tailwind.config.ts | 42 +- frontends/dbal/tsconfig.json | 18 +- frontends/dbal/tsconfig.playwright.json | 16 +- frontends/nextjs/.prettierrc.json | 20 +- frontends/nextjs/next.config.ts | 226 +- frontends/nextjs/src/README.md | 142 +- .../app/[tenant]/[package]/[...slug]/page.tsx | 436 +- .../src/app/[tenant]/[package]/layout.tsx | 190 +- .../src/app/[tenant]/[package]/page.tsx | 138 +- .../app/[tenant]/[package]/tenant-context.tsx | 250 +- .../nextjs/src/app/api/dbal/ping/route.ts | 26 +- .../nextjs/src/app/api/dbal/schema/route.ts | 418 +- .../src/app/api/packages/index/route.ts | 66 +- .../nextjs/src/app/api/v1/[...slug]/route.ts | 338 +- .../nextjs/src/app/ui/[[...slug]]/page.tsx | 146 +- .../src/components/PackageStyleLoader.tsx | 90 +- frontends/nextjs/src/components/README.md | 646 +- .../ui-page-renderer/UIPageRenderer.tsx | 102 +- .../src/components/ui-page-renderer/index.ts | 2 +- frontends/nextjs/src/hooks/README.md | 486 +- frontends/nextjs/src/hooks/auth/auth-store.ts | 274 +- .../src/hooks/use-dbal/use-cached-data.ts | 142 +- .../nextjs/src/hooks/use-dbal/use-dbal.ts | 60 +- .../nextjs/src/hooks/use-dbal/use-kv-store.ts | 204 +- frontends/nextjs/src/lib/README.md | 382 +- frontends/nextjs/src/lib/db/core/types.ts | 196 +- .../db/packages/data/get/get-package-data.ts | 28 +- .../lib/db/packages/data/set-package-data.ts | 34 +- frontends/nextjs/src/lib/hooks/index.ts | 2 +- .../nextjs/src/lib/hooks/use-rest-api.ts | 710 +- .../src/lib/packages/core/package-types.ts | 86 +- frontends/nextjs/src/middleware.ts | 102 +- frontends/nextjs/src/styles/README.md | 122 +- frontends/nextjs/src/tests/README.md | 66 +- .../nextjs/src/theme/types/components.d.ts | 146 +- frontends/nextjs/src/theme/types/layout.d.ts | 130 +- frontends/nextjs/src/theme/types/palette.d.ts | 144 +- frontends/nextjs/src/theme/types/theme.d.ts | 20 +- frontends/nextjs/src/types/README.md | 96 +- frontends/nextjs/src/types/dbal.d.ts | 30 +- frontends/nextjs/src/types/dbal/blob.d.ts | 24 +- .../nextjs/src/types/dbal/core-config.d.ts | 98 +- .../nextjs/src/types/dbal/core-types.d.ts | 22 +- frontends/nextjs/src/types/dbal/kv-store.d.ts | 24 +- .../src/types/dbal/tenant-aware-blob.d.ts | 16 +- .../nextjs/src/types/dbal/tenant-context.d.ts | 30 +- .../nextjs/src/types/module-overrides.d.ts | 18 +- .../nextjs/src/types/monaco-editor-react.d.ts | 62 +- frontends/nextjs/src/types/utility-types.d.ts | 120 +- frontends/nextjs/tsconfig.json | 138 +- frontends/nextjs/vitest.config.ts | 78 +- frontends/qt6/CMakeLists.txt | 84 +- frontends/qt6/MaterialMapping.md | 122 +- frontends/qt6/README.md | 88 +- frontends/qt6/conanfile.txt | 42 +- .../qt6/packages/analytics/metadata.json | 14 +- frontends/qt6/packages/blog/metadata.json | 14 +- frontends/qt6/packages/breakout/metadata.json | 14 +- .../qt6/packages/connection-hub/metadata.json | 14 +- .../qt6/packages/escape-room/metadata.json | 14 +- frontends/qt6/packages/forum/metadata.json | 14 +- .../qt6/packages/frontpage/metadata.json | 14 +- frontends/qt6/packages/gallery/metadata.json | 14 +- .../qt6/packages/god-panel/metadata.json | 14 +- .../qt6/packages/guestbook/metadata.json | 14 +- frontends/qt6/packages/login/metadata.json | 14 +- .../qt6/packages/marketplace/metadata.json | 14 +- .../qt6/packages/microthread/metadata.json | 14 +- .../qt6/packages/music-player/metadata.json | 14 +- .../packages/package-manager/metadata.json | 14 +- .../qt6/packages/profile-page/metadata.json | 14 +- .../qt6/packages/retro-games/metadata.json | 14 +- .../qt6/packages/snake-game/metadata.json | 14 +- .../qt6/packages/storybook/metadata.json | 14 +- .../qt6/packages/supergod-panel/metadata.json | 14 +- .../qt6/packages/user-settings/metadata.json | 14 +- .../qt6/packages/watchtower/metadata.json | 14 +- prisma/README.md | 206 +- prisma/schema-registry.json | 8 +- schemas/README.md | 132 +- .../package-schemas/ASSETS_SCHEMA_SUMMARY.md | 1136 +- schemas/package-schemas/CHANGES_APPLIED.md | 712 +- .../package-schemas/IMPROVEMENTS_SUMMARY.md | 1984 +-- schemas/package-schemas/QUICKSTART.md | 1098 +- schemas/package-schemas/REVIEW_SUMMARY.md | 1078 +- .../SCRIPT_SCHEMA_DEEP_DIVE.md | 1492 +- schemas/package-schemas/VERSIONING.md | 1114 +- schemas/package-schemas/examples/README.md | 466 +- .../examples/advanced-features/api/rest.json | 464 +- .../components/dashboard.json | 414 +- .../config/feature-flags.json | 436 +- .../advanced-features/entities/advanced.json | 362 +- .../events/event-sourcing.json | 460 +- .../advanced-features/forms/multi-step.json | 546 +- .../jobs/scheduled-tasks.json | 476 +- .../migrations/complex-schema.json | 854 +- .../examples/advanced-features/package.json | 28 +- .../advanced-features/permissions/abac.json | 710 +- .../advanced-features/scripts/automation.json | 672 +- .../styles/design-system.json | 480 +- .../advanced-features/types/advanced.json | 456 +- .../advanced-features/validation/complex.json | 690 +- .../examples/complete-package/api/routes.json | 376 +- .../complete-package/assets/assets.json | 488 +- .../complete-package/components/ui.json | 378 +- .../complete-package/config/settings.json | 192 +- .../complete-package/entities/schema.json | 360 +- .../complete-package/events/handlers.json | 164 +- .../complete-package/forms/user-form.json | 298 +- .../examples/complete-package/jobs/tasks.json | 172 +- .../migrations/001_initial.json | 352 +- .../examples/complete-package/package.json | 60 +- .../complete-package/permissions/rbac.json | 314 +- .../complete-package/scripts/functions.json | 1138 +- .../complete-package/styles/tokens.json | 234 +- .../complete-package/types/index.json | 256 +- .../validation/validators.json | 160 +- .../examples/minimal-package/api/index.json | 12 +- .../minimal-package/components/index.json | 12 +- .../minimal-package/config/index.json | 10 +- .../minimal-package/entities/index.json | 12 +- .../minimal-package/entities/schema.json | 58 +- .../minimal-package/events/index.json | 10 +- .../examples/minimal-package/forms/index.json | 10 +- .../examples/minimal-package/jobs/index.json | 10 +- .../minimal-package/migrations/index.json | 10 +- .../examples/minimal-package/package.json | 18 +- .../minimal-package/permissions/index.json | 10 +- .../minimal-package/scripts/functions.json | 94 +- .../minimal-package/scripts/index.json | 12 +- .../minimal-package/styles/index.json | 12 +- .../examples/minimal-package/types/index.json | 12 +- .../minimal-package/validation/index.json | 12 +- schemas/package-schemas/stdlib_schema.json | 432 +- schemas/package-schemas/tests/README.md | 574 +- schemas/package-schemas/tests/test-cases.json | 838 +- schemas/package-schemas/typescript/README.md | 1008 +- .../typescript/generate-types.sh | 354 +- .../typescript/metabuilder-schemas.d.ts | 1238 +- scripts/README-triage.md | 494 +- scripts/README.md | 286 +- scripts/generate-package.ts | 1166 +- scripts/test-triage-logic.sh | 472 +- scripts/triage-duplicate-issues.sh | 728 +- services/media_daemon/README.md | 230 +- .../media_daemon/build-config/CMakeLists.txt | 318 +- .../media_daemon/build-config/conanfile.txt | 30 +- spec/KNOWN_ISSUES.md | 84 +- spec/QUICK_REFERENCE.md | 478 +- storybook/.storybook/preview.tsx | 160 +- storybook/README.md | 448 +- storybook/STYLES_INTEGRATION.md | 672 +- storybook/package-lock.json | 9998 ++++++------ storybook/package.json | 66 +- storybook/public/storybook.config.json | 148 +- storybook/src/mocks/data/dashboard.json | 254 +- storybook/src/mocks/data/data_table.json | 176 +- storybook/src/mocks/data/nav_menu.json | 264 +- storybook/src/mocks/data/ui_level4.json | 238 +- storybook/src/mocks/data/ui_login.json | 162 +- storybook/src/mocks/data/user_manager.json | 232 +- storybook/src/mocks/json-loader.ts | 258 +- storybook/src/mocks/packages/index.ts | 118 +- storybook/src/mocks/schema.ts | 176 +- storybook/src/stories/Components.stories.tsx | 430 +- .../src/stories/DesignSystem.stories.tsx | 852 +- storybook/src/stories/UIHome.stories.tsx | 340 +- storybook/src/stories/UILevel2.stories.tsx | 500 +- storybook/src/stories/UILevel3.stories.tsx | 662 +- storybook/src/stories/UILevel4.stories.tsx | 1122 +- storybook/src/styles/StylesPanel.tsx | 382 +- storybook/src/styles/compiler.ts | 1074 +- storybook/src/utils/loadPackageComponents.ts | 204 +- storybook/storybook-config.schema.json | 196 +- storybook/storybook.config.json | 148 +- storybook/tsconfig.json | 52 +- storybook/tsconfig.node.json | 22 +- storybook/vite.config.ts | 26 +- 347 files changed, 53031 insertions(+), 53031 deletions(-) diff --git a/.github/COPILOT_ANALYSIS.md b/.github/COPILOT_ANALYSIS.md index 734e78311..a8b3376e4 100644 --- a/.github/COPILOT_ANALYSIS.md +++ b/.github/COPILOT_ANALYSIS.md @@ -1,201 +1,201 @@ -# Copilot Instructions Update Summary - -## Generated: December 25, 2025 - -### File Updated -`.github/copilot-instructions.md` - **~160 lines** of concise, actionable guidance for AI coding agents - -### Analysis Approach - -1. **Examined existing instructions** - - `dbal/docs/AGENTS.md` (605 lines) - DBAL-specific agent development guide - - `.github/copilot-instructions.md` (existing) - Original generic guidance - -2. **Analyzed codebase patterns** through: - - Database schema (`prisma/schema.prisma`) - Multi-tenant data model - - Core libs: `database.ts`, `package-loader.ts`, `declarative-component-renderer.ts` - - Test patterns: `schema-utils.test.ts` (441 lines, 63 parameterized tests) - - Package system: `/packages/*/seed/` structure across 8 packages - - Component patterns: `RenderComponent.tsx` (generic declarative renderer) - - Security: `password-utils.ts`, `secure-db-layer.ts`, `sandboxed-lua-engine.ts` - -3. **Discovered critical knowledge gaps** in original instructions: - - No mention of DBAL architecture (critical for full codebase understanding) - - Missing package loader workflow (`initializePackageSystem()`) - - No guidance on parameterized testing pattern (100+ tests using `it.each()`) - - Incomplete database pattern description - - No mention of Fengari Lua integration specifics - -## What's New in Updated Instructions - -### 1. Architecture Overview Section -**Why it matters**: Developers need to understand the 5-level permission system, DBAL's dual implementation (TS + C++), and multi-tenancy from day one. - -``` -- 5-Level Permission System: Public → User → Admin → God → Supergod -- DBAL: TypeScript SDK + C++ daemon with YAML contracts for language-agnostic APIs -- Declarative Components: RenderComponent pattern for JSON-driven UIs -- Package System: `/packages/{name}/seed/` self-contained modules -- Multi-Tenancy: All queries filter by tenantId -``` - -### 2. Critical Patterns (5 core patterns) -**Why this section**: Previous instructions mixed patterns with conventions. These are the "must understand" patterns: - -1. **API-First DBAL** - YAML → Types → TypeScript adapter → C++ adapter → Conformance tests -2. **Generic Components** - `RenderComponent` with config instead of hardcoded TSX -3. **Package Seeds** - `packages/{name}/seed/metadata.json` auto-loaded by `initializePackageSystem()` -4. **Database Helpers** - Always use `Database.*` methods, never raw Prisma -5. **Lua Sandboxing** - Scripts isolated, no `os`/`io`/`require` access - -### 3. Test Patterns with Real Examples -**Why new**: Original instructions said "write tests" without showing the actual pattern used in this codebase. - -```typescript -// Actual pattern from schema-utils.test.ts -it.each([ - { input: 'case1', expected: 'result1' }, - { input: 'case2', expected: 'result2' }, -])('should handle $input', ({ input, expected }) => { - expect(myFunction(input)).toBe(expected) -}) -``` - -### 4. DBAL-Specific Guidance -**Why critical**: DBAL is 20% of the codebase. Agents need to know: -- TypeScript impl = fast iteration -- C++ impl = production security -- Conformance tests = guarantee parity -- YAML schemas = source of truth - -### 5. Multi-Tenant Safety Patterns -**Why essential**: Multi-tenancy bugs are catastrophic. Explicit examples: - -```typescript -// ❌ Never - exposes all tenants' data -const data = await Database.getData() - -// ✅ Always - isolates by tenant -const data = await Database.getData({ tenantId: user.tenantId }) -``` - -## Discoverable Patterns Documented - -### 1. Package Loading Workflow -``` -initializePackageSystem() - ↓ -buildPackageRegistry() [reads /packages directory] - ↓ -exportAllPackagesForSeed() [extracts components, scripts, metadata] - ↓ -loadPackageComponents() [registers with declarative renderer] - ↓ -Package data available at runtime -``` - -### 2. Seed Data Initialization -- `src/seed-data/` directory with modular files: `users.ts`, `components.ts`, `workflows.ts`, `scripts.ts`, `pages.ts`, `packages.ts` -- Each module has `initialize*()` async function -- Called from `initializeAllSeedData()` in `App.tsx` on startup - -### 3. Test Coverage Enforcement -- Auto-generated coverage report: `FUNCTION_TEST_COVERAGE.md` -- Check function coverage: `npm run test:check-functions` -- Coverage report: `npm run test:coverage:report` -- Parameterized test pattern reduces code duplication by ~60% - -### 4. Component Size Limits -- Hard limit: 150 LOC (except `RenderComponent.tsx` which uses recursive pattern) -- Enforced by code review and linting patterns -- Solution: Use generic `RenderComponent` + JSON config - -## Connecting to Key Files - -Instructions now reference: - -| File | Purpose | Why Referenced | -|------|---------|-----------------| -| `dbal/docs/AGENTS.md` | DBAL development guide | Critical for DBAL changes | -| `src/lib/database.ts` | Database operations | 1200+ LOC utility wrapper, required for all DB access | -| `src/components/RenderComponent.tsx` | Generic renderer | 221 LOC example of declarative UI pattern | -| `src/lib/schema-utils.test.ts` | Test examples | 63 tests showing parameterized pattern | -| `docs/architecture/5-level-system.md` | Permission model | Understanding multi-level access control | -| `docs/architecture/packages.md` | Package system | Understanding modular package structure | -| `prisma/schema.prisma` | Data model | Multi-tenant schema structure | - -## Sections Retained from Original - -✅ Component size limits (< 150 LOC) -✅ Functional components with hooks -✅ `@/` absolute paths with shadcn/ui -✅ Tailwind-only styling -✅ SHA-512 password hashing -✅ Sandbox Lua execution -✅ Database-driven configuration preference - -## New Guidance Not in Original - -✅ DBAL dual-implementation architecture -✅ Parameterized test patterns with examples -✅ Package loader workflow -✅ Multi-tenant query patterns (explicit examples) -✅ Conformance test process for DBAL -✅ API-First development (YAML → Types → Impl) -✅ Fengari Lua integration specifics -✅ Common mistakes with fixes - -## How Agents Should Use This - -1. **On startup**: Read "Architecture Overview" to understand the 4 pillars -2. **Before implementation**: Check "Critical Patterns" (5 patterns) + relevant section -3. **During code review**: Run through "Common Mistakes" checklist -4. **When fixing bugs**: Check "DBAL-Specific Guidance" if involving DBAL changes -5. **When writing tests**: Copy pattern from "Test Patterns" section -6. **When unsure**: Check "Questions to Ask" (7 questions) - -## Example Use Cases - -### Adding a new database entity -1. Read: API-First DBAL Development pattern -2. Check: DBAL-Specific Guidance (YAML → Types → Adapters) -3. Reference: `dbal/docs/AGENTS.md` for detailed workflow - -### Creating a new component feature -1. Read: Generic Component Rendering pattern -2. Reference: `RenderComponent.tsx` example -3. Build: JSON config + use `RenderComponent` instead of TSX - -### Fixing multi-tenancy bug -1. Read: Multi-Tenant Safety section -2. Check: "Common Mistakes" #2 (forgetting tenantId filter) -3. Verify: Query includes `where('tenantId', currentTenant.id)` - -### Adding test coverage -1. Reference: "Test Patterns" section with `it.each()` example -2. Run: `npm run test:check-functions` to verify coverage -3. Generate: `npm run test:coverage:report` - -## Metrics - -- **Length**: ~160 lines (vs. original ~110 lines, +45% with critical new sections) -- **Specificity**: 7 code examples (vs. 0 in original) -- **Patterns documented**: 12 discoverable patterns extracted from codebase -- **Common mistakes**: 6 explicit anti-patterns with solutions -- **Key files referenced**: 9 files with specific line numbers -- **Action items**: 7 specific questions to ask - -## Files to Review - -Agents should prioritize these when onboarding: - -1. **Start**: `docs/architecture/5-level-system.md` (understand permissions) -2. **Then**: `docs/architecture/packages.md` (understand modularity) -3. **Then**: `src/lib/database.ts` (understand DB pattern) -4. **Then**: `dbal/docs/AGENTS.md` (if working on DBAL) -5. **Always**: `FUNCTION_TEST_COVERAGE.md` (for test requirements) - ---- - -**Status**: ✅ Ready for AI agents to use -**Last Updated**: December 25, 2025 +# Copilot Instructions Update Summary + +## Generated: December 25, 2025 + +### File Updated +`.github/copilot-instructions.md` - **~160 lines** of concise, actionable guidance for AI coding agents + +### Analysis Approach + +1. **Examined existing instructions** + - `dbal/docs/AGENTS.md` (605 lines) - DBAL-specific agent development guide + - `.github/copilot-instructions.md` (existing) - Original generic guidance + +2. **Analyzed codebase patterns** through: + - Database schema (`prisma/schema.prisma`) - Multi-tenant data model + - Core libs: `database.ts`, `package-loader.ts`, `declarative-component-renderer.ts` + - Test patterns: `schema-utils.test.ts` (441 lines, 63 parameterized tests) + - Package system: `/packages/*/seed/` structure across 8 packages + - Component patterns: `RenderComponent.tsx` (generic declarative renderer) + - Security: `password-utils.ts`, `secure-db-layer.ts`, `sandboxed-lua-engine.ts` + +3. **Discovered critical knowledge gaps** in original instructions: + - No mention of DBAL architecture (critical for full codebase understanding) + - Missing package loader workflow (`initializePackageSystem()`) + - No guidance on parameterized testing pattern (100+ tests using `it.each()`) + - Incomplete database pattern description + - No mention of Fengari Lua integration specifics + +## What's New in Updated Instructions + +### 1. Architecture Overview Section +**Why it matters**: Developers need to understand the 5-level permission system, DBAL's dual implementation (TS + C++), and multi-tenancy from day one. + +``` +- 5-Level Permission System: Public → User → Admin → God → Supergod +- DBAL: TypeScript SDK + C++ daemon with YAML contracts for language-agnostic APIs +- Declarative Components: RenderComponent pattern for JSON-driven UIs +- Package System: `/packages/{name}/seed/` self-contained modules +- Multi-Tenancy: All queries filter by tenantId +``` + +### 2. Critical Patterns (5 core patterns) +**Why this section**: Previous instructions mixed patterns with conventions. These are the "must understand" patterns: + +1. **API-First DBAL** - YAML → Types → TypeScript adapter → C++ adapter → Conformance tests +2. **Generic Components** - `RenderComponent` with config instead of hardcoded TSX +3. **Package Seeds** - `packages/{name}/seed/metadata.json` auto-loaded by `initializePackageSystem()` +4. **Database Helpers** - Always use `Database.*` methods, never raw Prisma +5. **Lua Sandboxing** - Scripts isolated, no `os`/`io`/`require` access + +### 3. Test Patterns with Real Examples +**Why new**: Original instructions said "write tests" without showing the actual pattern used in this codebase. + +```typescript +// Actual pattern from schema-utils.test.ts +it.each([ + { input: 'case1', expected: 'result1' }, + { input: 'case2', expected: 'result2' }, +])('should handle $input', ({ input, expected }) => { + expect(myFunction(input)).toBe(expected) +}) +``` + +### 4. DBAL-Specific Guidance +**Why critical**: DBAL is 20% of the codebase. Agents need to know: +- TypeScript impl = fast iteration +- C++ impl = production security +- Conformance tests = guarantee parity +- YAML schemas = source of truth + +### 5. Multi-Tenant Safety Patterns +**Why essential**: Multi-tenancy bugs are catastrophic. Explicit examples: + +```typescript +// ❌ Never - exposes all tenants' data +const data = await Database.getData() + +// ✅ Always - isolates by tenant +const data = await Database.getData({ tenantId: user.tenantId }) +``` + +## Discoverable Patterns Documented + +### 1. Package Loading Workflow +``` +initializePackageSystem() + ↓ +buildPackageRegistry() [reads /packages directory] + ↓ +exportAllPackagesForSeed() [extracts components, scripts, metadata] + ↓ +loadPackageComponents() [registers with declarative renderer] + ↓ +Package data available at runtime +``` + +### 2. Seed Data Initialization +- `src/seed-data/` directory with modular files: `users.ts`, `components.ts`, `workflows.ts`, `scripts.ts`, `pages.ts`, `packages.ts` +- Each module has `initialize*()` async function +- Called from `initializeAllSeedData()` in `App.tsx` on startup + +### 3. Test Coverage Enforcement +- Auto-generated coverage report: `FUNCTION_TEST_COVERAGE.md` +- Check function coverage: `npm run test:check-functions` +- Coverage report: `npm run test:coverage:report` +- Parameterized test pattern reduces code duplication by ~60% + +### 4. Component Size Limits +- Hard limit: 150 LOC (except `RenderComponent.tsx` which uses recursive pattern) +- Enforced by code review and linting patterns +- Solution: Use generic `RenderComponent` + JSON config + +## Connecting to Key Files + +Instructions now reference: + +| File | Purpose | Why Referenced | +|------|---------|-----------------| +| `dbal/docs/AGENTS.md` | DBAL development guide | Critical for DBAL changes | +| `src/lib/database.ts` | Database operations | 1200+ LOC utility wrapper, required for all DB access | +| `src/components/RenderComponent.tsx` | Generic renderer | 221 LOC example of declarative UI pattern | +| `src/lib/schema-utils.test.ts` | Test examples | 63 tests showing parameterized pattern | +| `docs/architecture/5-level-system.md` | Permission model | Understanding multi-level access control | +| `docs/architecture/packages.md` | Package system | Understanding modular package structure | +| `prisma/schema.prisma` | Data model | Multi-tenant schema structure | + +## Sections Retained from Original + +✅ Component size limits (< 150 LOC) +✅ Functional components with hooks +✅ `@/` absolute paths with shadcn/ui +✅ Tailwind-only styling +✅ SHA-512 password hashing +✅ Sandbox Lua execution +✅ Database-driven configuration preference + +## New Guidance Not in Original + +✅ DBAL dual-implementation architecture +✅ Parameterized test patterns with examples +✅ Package loader workflow +✅ Multi-tenant query patterns (explicit examples) +✅ Conformance test process for DBAL +✅ API-First development (YAML → Types → Impl) +✅ Fengari Lua integration specifics +✅ Common mistakes with fixes + +## How Agents Should Use This + +1. **On startup**: Read "Architecture Overview" to understand the 4 pillars +2. **Before implementation**: Check "Critical Patterns" (5 patterns) + relevant section +3. **During code review**: Run through "Common Mistakes" checklist +4. **When fixing bugs**: Check "DBAL-Specific Guidance" if involving DBAL changes +5. **When writing tests**: Copy pattern from "Test Patterns" section +6. **When unsure**: Check "Questions to Ask" (7 questions) + +## Example Use Cases + +### Adding a new database entity +1. Read: API-First DBAL Development pattern +2. Check: DBAL-Specific Guidance (YAML → Types → Adapters) +3. Reference: `dbal/docs/AGENTS.md` for detailed workflow + +### Creating a new component feature +1. Read: Generic Component Rendering pattern +2. Reference: `RenderComponent.tsx` example +3. Build: JSON config + use `RenderComponent` instead of TSX + +### Fixing multi-tenancy bug +1. Read: Multi-Tenant Safety section +2. Check: "Common Mistakes" #2 (forgetting tenantId filter) +3. Verify: Query includes `where('tenantId', currentTenant.id)` + +### Adding test coverage +1. Reference: "Test Patterns" section with `it.each()` example +2. Run: `npm run test:check-functions` to verify coverage +3. Generate: `npm run test:coverage:report` + +## Metrics + +- **Length**: ~160 lines (vs. original ~110 lines, +45% with critical new sections) +- **Specificity**: 7 code examples (vs. 0 in original) +- **Patterns documented**: 12 discoverable patterns extracted from codebase +- **Common mistakes**: 6 explicit anti-patterns with solutions +- **Key files referenced**: 9 files with specific line numbers +- **Action items**: 7 specific questions to ask + +## Files to Review + +Agents should prioritize these when onboarding: + +1. **Start**: `docs/architecture/5-level-system.md` (understand permissions) +2. **Then**: `docs/architecture/packages.md` (understand modularity) +3. **Then**: `src/lib/database.ts` (understand DB pattern) +4. **Then**: `dbal/docs/AGENTS.md` (if working on DBAL) +5. **Always**: `FUNCTION_TEST_COVERAGE.md` (for test requirements) + +--- + +**Status**: ✅ Ready for AI agents to use +**Last Updated**: December 25, 2025 diff --git a/.github/COPILOT_SDLC_SUMMARY.md b/.github/COPILOT_SDLC_SUMMARY.md index f6fa8d583..c6f52ac92 100644 --- a/.github/COPILOT_SDLC_SUMMARY.md +++ b/.github/COPILOT_SDLC_SUMMARY.md @@ -1,432 +1,432 @@ -# GitHub Copilot SDLC Integration Summary - -## Overview - -MetaBuilder's GitHub workflows are comprehensively integrated with **GitHub Copilot** to assist throughout the entire Software Development Lifecycle (SDLC). This document provides an overview of how Copilot enhances each phase of development. - -## SDLC Phase Coverage - -### ✅ Phase 1: Planning & Design - -**Workflows:** -- `planning.yml` - Architecture review, PRD alignment, implementation guidance - -**Copilot Features:** -- ✅ **Architecture Review**: Analyzes feature requests against declarative-first principles -- ✅ **PRD Alignment**: Checks if features align with project mission (95% declarative, multi-tenant) -- ✅ **Design Checklist**: Provides comprehensive checklist for feature planning -- ✅ **Multi-Tenant Validation**: Ensures tenant isolation is considered -- ✅ **Permission Level Planning**: Validates which levels (1-5) should access the feature -- ✅ **Declarative Assessment**: Suggests JSON/Lua approaches over TypeScript -- ✅ **Package Structure Guidance**: Recommends package-based implementation when appropriate - -**How It Works:** -1. Developer creates issue with `enhancement` or `feature-request` label -2. Workflow automatically analyzes the request -3. Provides architectural suggestions and questions -4. Creates design checklist -5. Suggests PRD concepts to review -6. When labeled `ready-to-implement`, provides step-by-step implementation plan - -**Example:** -```markdown -Issue: "Add real-time notifications system" -↓ -Copilot suggests: -- Implement as declarative component with JSON + Lua -- Store notification config in database -- Consider tenant-specific notification preferences -- Plan for Level 2+ permission access -- Create /packages/notifications/ structure -``` - ---- - -### ✅ Phase 2: Development - -**Workflows:** -- `development.yml` - Continuous quality feedback, architectural compliance, refactoring suggestions - -**Copilot Features:** -- ✅ **Real-Time Code Metrics**: Tracks TypeScript vs JSON/Lua ratio -- ✅ **Component Size Monitoring**: Flags files exceeding 150 LOC -- ✅ **Architectural Compliance**: Validates adherence to declarative principles -- ✅ **Refactoring Opportunities**: Identifies code that could be more declarative -- ✅ **Configuration Detection**: Finds hardcoded values that should be in database -- ✅ **@copilot Mentions**: Responds to developer questions with contextual guidance -- ✅ **Pattern Recognition**: Suggests generic renderers over hardcoded components -- ✅ **Seed Data Validation**: Checks if database changes have corresponding seed updates - -**How It Works:** -1. Developer pushes to feature branch -2. Workflow analyzes code changes -3. Calculates declarative ratio (JSON + Lua / Total TS files) -4. Identifies large components, hardcoded values, new TSX files -5. Posts feedback comment with metrics and suggestions -6. Updates on each push with latest analysis - -**Metrics Tracked:** -- Total TypeScript files -- Files exceeding 150 LOC -- JSON configuration files -- Lua scripts -- Declarative ratio percentage -- Hardcoded constants -- New component files - -**Example:** -``` -Push to feature/notifications -↓ -Copilot reports: -- TypeScript files: 45 -- Files >150 LOC: 2 ⚠️ -- JSON config files: 12 -- Lua scripts: 8 -- Declarative ratio: 44.4% -- Suggestion: NotificationPanel.tsx (180 LOC) could be split -- Suggestion: Move hardcoded notification types to database -``` - ---- - -### ✅ Phase 3: Testing & Code Review - -**Workflows:** -- `ci.yml` - Lint, build, E2E tests -- `code-review.yml` - Automated security and quality review - -**Copilot Features:** -- ✅ **Security Scanning**: Detects eval(), innerHTML, XSS risks -- ✅ **Code Quality Checks**: Identifies console.log, debugger, any types -- ✅ **Best Practice Validation**: React hooks, empty dependencies -- ✅ **File Size Warnings**: Flags large changesets -- ✅ **Auto-Approval**: Approves PRs with no blocking issues -- ✅ **Label Management**: Adds appropriate labels (needs-changes, ready-for-review) -- ✅ **Lint Error Reporting**: Displays ESLint issues inline -- ✅ **Test Validation**: Ensures E2E tests pass - -**Review Criteria:** -- Security vulnerabilities (eval, innerHTML, dangerouslySetInnerHTML) -- Debug code (console.log, debugger) -- Type safety (any types) -- React best practices (useEffect dependencies) -- File sizes (>500 lines) -- Lint errors - -**Example:** -``` -PR opened: "Add notifications" -↓ -Copilot reviews: -✅ No security issues -⚠️ Warning: Console.log in NotificationService.tsx -💡 Suggestion: Replace 'any' types with specific interfaces -⚠️ Warning: NotificationPanel.tsx has 180 additions -✅ Status: APPROVED (fix warnings before merge) -``` - ---- - -### ✅ Phase 4: Integration & Merge - -**Workflows:** -- `pr-management.yml` - PR labeling, description validation, issue linking -- `merge-conflict-check.yml` - Conflict detection -- `auto-merge.yml` - Automated merging - -**Copilot Features:** -- ✅ **Auto-Labeling**: Categorizes PRs by affected areas (ui, tests, docs, workflows) -- ✅ **Size Classification**: Labels as small/medium/large -- ✅ **Description Quality**: Validates PR has adequate description -- ✅ **Issue Linking**: Connects PRs to related issues -- ✅ **Conflict Detection**: Alerts when merge conflicts exist with @copilot mention -- ✅ **Auto-Merge**: Merges approved PRs that pass all checks -- ✅ **Branch Cleanup**: Deletes branches after successful merge - -**How It Works:** -1. PR is opened/updated -2. Auto-labeled based on changed files -3. Description validated for quality -4. Related issues linked automatically -5. Conflicts checked against base branch -6. Once approved + tests pass → auto-merged -7. Branch deleted automatically - ---- - -### ✅ Phase 5: Deployment - -**Workflows:** -- `deployment.yml` - Pre-deployment validation, health checks, monitoring - -**Copilot Features:** -- ✅ **Pre-Deployment Validation**: Schema validation, security audit, size check -- ✅ **Breaking Change Detection**: Identifies commits with breaking changes -- ✅ **Deployment Notes**: Auto-generates categorized release notes -- ✅ **Health Checks**: Verifies build integrity and critical files -- ✅ **Deployment Tracking**: Creates monitoring issues for releases -- ✅ **Security Audit**: Scans dependencies for vulnerabilities -- ✅ **Environment Validation**: Checks required configuration exists - -**Deployment Checklist:** -- Database schema validity -- Security vulnerabilities (npm audit) -- Build size optimization -- Environment configuration -- Breaking changes documented -- Health check verification - -**Example:** -``` -Release: v2.0.0 -↓ -Copilot generates: -- Deployment Summary with categorized commits -- Breaking changes alert (2 found) -- New features list (8) -- Bug fixes list (12) -- Creates tracking issue with 48hr monitoring plan -- Health checks: ✅ All passed -``` - ---- - -### ✅ Phase 6: Maintenance & Operations - -**Workflows:** -- `issue-triage.yml` - Issue categorization, auto-fix suggestions -- `dependabot.yml` - Dependency updates - -**Copilot Features:** -- ✅ **Automatic Triage**: Categorizes issues by type and priority -- ✅ **AI-Fixable Detection**: Identifies issues suitable for automated fixes -- ✅ **Good First Issue**: Flags beginner-friendly issues -- ✅ **Auto-Fix Branch Creation**: Creates branches for automated fixes -- ✅ **Dependency Monitoring**: Daily npm updates, weekly devcontainer updates -- ✅ **Security Vulnerability Tracking**: Auto-creates issues for critical CVEs - -**Issue Categories:** -- Type: bug, enhancement, documentation, testing, security, performance -- Priority: high, medium, low -- Difficulty: good first issue -- Automation: ai-fixable, auto-fix - ---- - -## Copilot Interaction Patterns - -### 1. In Issues - -**Mention Patterns:** -```markdown -@copilot implement this issue -@copilot review the architecture -@copilot suggest testing strategy -@copilot help with database schema -@copilot fix this issue -``` - -**Response:** Context-aware guidance based on: -- Copilot Instructions (.github/copilot-instructions.md) -- docs/getting-started/PRD.md project mission -- Existing package structure -- Architectural principles - -### 2. In Pull Requests - -**Automatic Feedback:** -- Code metrics on every push -- Refactoring suggestions -- Architectural compliance -- Security review -- Quality assessment - -**Mention for:** -- Specific implementation questions -- Refactoring guidance -- Testing approaches -- Architectural decisions - -### 3. In Your IDE - -**Context Files:** -- `.github/copilot-instructions.md` - Comprehensive project guidelines -- `docs/getting-started/PRD.md` - Feature context and project mission -- `/packages/*/seed/` - Existing patterns to follow -- `prisma/schema.prisma` - Database structure - -**Best Practices:** -- Reference docs/getting-started/PRD.md when asking about features -- Show existing patterns when requesting new code -- Ask about architectural decisions before implementing -- Request declarative approaches explicitly - ---- - -## Measurement & Metrics - -### Code Quality Metrics - -**Tracked Automatically:** -- Declarative ratio: `(JSON files + Lua scripts) / TypeScript files * 100%` -- Component size: Files exceeding 150 LOC -- TypeScript usage: Total .ts/.tsx files -- Configuration: Database-driven vs hardcoded - -**Goals:** -- Declarative ratio: >50% -- Component size: <150 LOC -- TypeScript: Minimal (infrastructure only) -- Configuration: 100% database-driven - -### SDLC Coverage Metrics - -**Phase Coverage:** -- ✅ Planning: Architecture review, PRD alignment -- ✅ Development: Continuous feedback, refactoring -- ✅ Testing: Security scan, quality checks -- ✅ Integration: Auto-merge, conflict resolution -- ✅ Deployment: Validation, health checks -- ✅ Maintenance: Triage, auto-fix, dependencies - -**Coverage: 100% of SDLC phases** - -### Automation Metrics - -**Automated Actions:** -- Issue triage and labeling -- PR categorization -- Code review and approval -- Merge and branch cleanup -- Deployment validation -- Security vulnerability tracking -- Dependency updates - -**Human Intervention Required:** -- Final approval for deployment -- Resolution of blocking issues -- Complex architectural decisions -- Multi-tenant design considerations - ---- - -## Configuration Files - -### 1. Copilot Instructions -**File:** `.github/copilot-instructions.md` - -**Contains:** -- Project context and architecture -- Code conventions (TS, React, Lua, Prisma) -- Development workflow guidance -- Security considerations -- Common patterns and examples -- Integration with workflows -- Useful commands - -### 2. Workflow Definitions -**Directory:** `.github/workflows/` - -**Files:** -- `ci.yml` - CI/CD pipeline -- `code-review.yml` - Automated review -- `auto-merge.yml` - Merge automation -- `issue-triage.yml` - Issue management -- `pr-management.yml` - PR automation -- `merge-conflict-check.yml` - Conflict detection -- `planning.yml` - Planning assistance *(NEW)* -- `development.yml` - Development feedback *(NEW)* -- `deployment.yml` - Deployment automation *(NEW)* - -### 3. Documentation -**Files:** -- `.github/workflows/README.md` - Workflow documentation -- `docs/getting-started/PRD.md` - Product requirements -- `docs/security/SECURITY.md` - Security policies -- `docs/README.md` - Project overview - ---- - -## Benefits - -### For Developers - -1. **Faster Onboarding**: Copilot guides new developers with architectural principles -2. **Consistent Quality**: Automated checks enforce coding standards -3. **Reduced Review Time**: Many issues caught automatically -4. **Better Architecture**: Continuous feedback on declarative principles -5. **Security Awareness**: Proactive vulnerability detection -6. **Learning Tool**: Suggestions teach best practices - -### For Teams - -1. **Standardized Process**: Every issue/PR follows same workflow -2. **Knowledge Sharing**: Architectural principles documented and enforced -3. **Reduced Technical Debt**: Refactoring suggestions identify improvement areas -4. **Faster Iteration**: Auto-merge reduces bottlenecks -5. **Better Tracking**: Deployment and issue tracking automated -6. **Visibility**: Metrics show declarative ratio and code quality trends - -### For the Project - -1. **Architectural Integrity**: Maintains 95% declarative goal -2. **Scalability**: Package-based structure enforced -3. **Multi-Tenant Safety**: Tenant considerations validated -4. **Security**: Continuous vulnerability monitoring -5. **Documentation**: Auto-generated release notes and tracking -6. **Quality**: Consistent enforcement of 150 LOC limit - ---- - -## Future Enhancements - -### Potential Additions - -1. **Copilot Workspace Integration**: Direct IDE integration with workflow context -2. **AI-Generated Tests**: Auto-generate E2E tests from issue descriptions -3. **Performance Monitoring**: Track bundle size, render performance over time -4. **Accessibility Checks**: Automated a11y validation in PRs -5. **Visual Regression Testing**: Screenshot comparison for UI changes -6. **Lua Linting**: Custom linter for Lua scripts following project patterns -7. **Package Validation**: Verify package structure meets standards -8. **Multi-Tenant Testing**: Automated tenant isolation verification - -### Metrics Dashboard - -**Potential Features:** -- Declarative ratio trend over time -- Average component size -- PR merge time -- Auto-fix success rate -- Security vulnerability resolution time -- Test coverage trends -- Deployment frequency - ---- - -## Conclusion - -MetaBuilder's GitHub workflows provide **comprehensive GitHub Copilot integration across all SDLC phases**: - -✅ **Planning** - Architecture review and PRD alignment -✅ **Development** - Continuous quality feedback and refactoring -✅ **Testing** - Security scanning and quality validation -✅ **Integration** - Auto-labeling, review, and merge -✅ **Deployment** - Validation, health checks, and tracking -✅ **Maintenance** - Issue triage, auto-fix, and dependency management - -**Key Achievements:** -- 100% SDLC phase coverage -- Automated enforcement of declarative-first principles -- Context-aware @copilot assistance throughout development -- Comprehensive metrics tracking (declarative ratio, component size) -- Security-first approach with continuous vulnerability monitoring -- Self-documenting with auto-generated deployment notes - -**Documentation:** -- Copilot Instructions: `.github/copilot-instructions.md` -- Workflow Guide: `.github/workflows/README.md` -- This Summary: `.github/COPILOT_SDLC_SUMMARY.md` - -The workflows ensure that GitHub Copilot can assist developers at every stage, from initial planning through deployment and maintenance, while maintaining the project's architectural integrity and quality standards. +# GitHub Copilot SDLC Integration Summary + +## Overview + +MetaBuilder's GitHub workflows are comprehensively integrated with **GitHub Copilot** to assist throughout the entire Software Development Lifecycle (SDLC). This document provides an overview of how Copilot enhances each phase of development. + +## SDLC Phase Coverage + +### ✅ Phase 1: Planning & Design + +**Workflows:** +- `planning.yml` - Architecture review, PRD alignment, implementation guidance + +**Copilot Features:** +- ✅ **Architecture Review**: Analyzes feature requests against declarative-first principles +- ✅ **PRD Alignment**: Checks if features align with project mission (95% declarative, multi-tenant) +- ✅ **Design Checklist**: Provides comprehensive checklist for feature planning +- ✅ **Multi-Tenant Validation**: Ensures tenant isolation is considered +- ✅ **Permission Level Planning**: Validates which levels (1-5) should access the feature +- ✅ **Declarative Assessment**: Suggests JSON/Lua approaches over TypeScript +- ✅ **Package Structure Guidance**: Recommends package-based implementation when appropriate + +**How It Works:** +1. Developer creates issue with `enhancement` or `feature-request` label +2. Workflow automatically analyzes the request +3. Provides architectural suggestions and questions +4. Creates design checklist +5. Suggests PRD concepts to review +6. When labeled `ready-to-implement`, provides step-by-step implementation plan + +**Example:** +```markdown +Issue: "Add real-time notifications system" +↓ +Copilot suggests: +- Implement as declarative component with JSON + Lua +- Store notification config in database +- Consider tenant-specific notification preferences +- Plan for Level 2+ permission access +- Create /packages/notifications/ structure +``` + +--- + +### ✅ Phase 2: Development + +**Workflows:** +- `development.yml` - Continuous quality feedback, architectural compliance, refactoring suggestions + +**Copilot Features:** +- ✅ **Real-Time Code Metrics**: Tracks TypeScript vs JSON/Lua ratio +- ✅ **Component Size Monitoring**: Flags files exceeding 150 LOC +- ✅ **Architectural Compliance**: Validates adherence to declarative principles +- ✅ **Refactoring Opportunities**: Identifies code that could be more declarative +- ✅ **Configuration Detection**: Finds hardcoded values that should be in database +- ✅ **@copilot Mentions**: Responds to developer questions with contextual guidance +- ✅ **Pattern Recognition**: Suggests generic renderers over hardcoded components +- ✅ **Seed Data Validation**: Checks if database changes have corresponding seed updates + +**How It Works:** +1. Developer pushes to feature branch +2. Workflow analyzes code changes +3. Calculates declarative ratio (JSON + Lua / Total TS files) +4. Identifies large components, hardcoded values, new TSX files +5. Posts feedback comment with metrics and suggestions +6. Updates on each push with latest analysis + +**Metrics Tracked:** +- Total TypeScript files +- Files exceeding 150 LOC +- JSON configuration files +- Lua scripts +- Declarative ratio percentage +- Hardcoded constants +- New component files + +**Example:** +``` +Push to feature/notifications +↓ +Copilot reports: +- TypeScript files: 45 +- Files >150 LOC: 2 ⚠️ +- JSON config files: 12 +- Lua scripts: 8 +- Declarative ratio: 44.4% +- Suggestion: NotificationPanel.tsx (180 LOC) could be split +- Suggestion: Move hardcoded notification types to database +``` + +--- + +### ✅ Phase 3: Testing & Code Review + +**Workflows:** +- `ci.yml` - Lint, build, E2E tests +- `code-review.yml` - Automated security and quality review + +**Copilot Features:** +- ✅ **Security Scanning**: Detects eval(), innerHTML, XSS risks +- ✅ **Code Quality Checks**: Identifies console.log, debugger, any types +- ✅ **Best Practice Validation**: React hooks, empty dependencies +- ✅ **File Size Warnings**: Flags large changesets +- ✅ **Auto-Approval**: Approves PRs with no blocking issues +- ✅ **Label Management**: Adds appropriate labels (needs-changes, ready-for-review) +- ✅ **Lint Error Reporting**: Displays ESLint issues inline +- ✅ **Test Validation**: Ensures E2E tests pass + +**Review Criteria:** +- Security vulnerabilities (eval, innerHTML, dangerouslySetInnerHTML) +- Debug code (console.log, debugger) +- Type safety (any types) +- React best practices (useEffect dependencies) +- File sizes (>500 lines) +- Lint errors + +**Example:** +``` +PR opened: "Add notifications" +↓ +Copilot reviews: +✅ No security issues +⚠️ Warning: Console.log in NotificationService.tsx +💡 Suggestion: Replace 'any' types with specific interfaces +⚠️ Warning: NotificationPanel.tsx has 180 additions +✅ Status: APPROVED (fix warnings before merge) +``` + +--- + +### ✅ Phase 4: Integration & Merge + +**Workflows:** +- `pr-management.yml` - PR labeling, description validation, issue linking +- `merge-conflict-check.yml` - Conflict detection +- `auto-merge.yml` - Automated merging + +**Copilot Features:** +- ✅ **Auto-Labeling**: Categorizes PRs by affected areas (ui, tests, docs, workflows) +- ✅ **Size Classification**: Labels as small/medium/large +- ✅ **Description Quality**: Validates PR has adequate description +- ✅ **Issue Linking**: Connects PRs to related issues +- ✅ **Conflict Detection**: Alerts when merge conflicts exist with @copilot mention +- ✅ **Auto-Merge**: Merges approved PRs that pass all checks +- ✅ **Branch Cleanup**: Deletes branches after successful merge + +**How It Works:** +1. PR is opened/updated +2. Auto-labeled based on changed files +3. Description validated for quality +4. Related issues linked automatically +5. Conflicts checked against base branch +6. Once approved + tests pass → auto-merged +7. Branch deleted automatically + +--- + +### ✅ Phase 5: Deployment + +**Workflows:** +- `deployment.yml` - Pre-deployment validation, health checks, monitoring + +**Copilot Features:** +- ✅ **Pre-Deployment Validation**: Schema validation, security audit, size check +- ✅ **Breaking Change Detection**: Identifies commits with breaking changes +- ✅ **Deployment Notes**: Auto-generates categorized release notes +- ✅ **Health Checks**: Verifies build integrity and critical files +- ✅ **Deployment Tracking**: Creates monitoring issues for releases +- ✅ **Security Audit**: Scans dependencies for vulnerabilities +- ✅ **Environment Validation**: Checks required configuration exists + +**Deployment Checklist:** +- Database schema validity +- Security vulnerabilities (npm audit) +- Build size optimization +- Environment configuration +- Breaking changes documented +- Health check verification + +**Example:** +``` +Release: v2.0.0 +↓ +Copilot generates: +- Deployment Summary with categorized commits +- Breaking changes alert (2 found) +- New features list (8) +- Bug fixes list (12) +- Creates tracking issue with 48hr monitoring plan +- Health checks: ✅ All passed +``` + +--- + +### ✅ Phase 6: Maintenance & Operations + +**Workflows:** +- `issue-triage.yml` - Issue categorization, auto-fix suggestions +- `dependabot.yml` - Dependency updates + +**Copilot Features:** +- ✅ **Automatic Triage**: Categorizes issues by type and priority +- ✅ **AI-Fixable Detection**: Identifies issues suitable for automated fixes +- ✅ **Good First Issue**: Flags beginner-friendly issues +- ✅ **Auto-Fix Branch Creation**: Creates branches for automated fixes +- ✅ **Dependency Monitoring**: Daily npm updates, weekly devcontainer updates +- ✅ **Security Vulnerability Tracking**: Auto-creates issues for critical CVEs + +**Issue Categories:** +- Type: bug, enhancement, documentation, testing, security, performance +- Priority: high, medium, low +- Difficulty: good first issue +- Automation: ai-fixable, auto-fix + +--- + +## Copilot Interaction Patterns + +### 1. In Issues + +**Mention Patterns:** +```markdown +@copilot implement this issue +@copilot review the architecture +@copilot suggest testing strategy +@copilot help with database schema +@copilot fix this issue +``` + +**Response:** Context-aware guidance based on: +- Copilot Instructions (.github/copilot-instructions.md) +- docs/getting-started/PRD.md project mission +- Existing package structure +- Architectural principles + +### 2. In Pull Requests + +**Automatic Feedback:** +- Code metrics on every push +- Refactoring suggestions +- Architectural compliance +- Security review +- Quality assessment + +**Mention for:** +- Specific implementation questions +- Refactoring guidance +- Testing approaches +- Architectural decisions + +### 3. In Your IDE + +**Context Files:** +- `.github/copilot-instructions.md` - Comprehensive project guidelines +- `docs/getting-started/PRD.md` - Feature context and project mission +- `/packages/*/seed/` - Existing patterns to follow +- `prisma/schema.prisma` - Database structure + +**Best Practices:** +- Reference docs/getting-started/PRD.md when asking about features +- Show existing patterns when requesting new code +- Ask about architectural decisions before implementing +- Request declarative approaches explicitly + +--- + +## Measurement & Metrics + +### Code Quality Metrics + +**Tracked Automatically:** +- Declarative ratio: `(JSON files + Lua scripts) / TypeScript files * 100%` +- Component size: Files exceeding 150 LOC +- TypeScript usage: Total .ts/.tsx files +- Configuration: Database-driven vs hardcoded + +**Goals:** +- Declarative ratio: >50% +- Component size: <150 LOC +- TypeScript: Minimal (infrastructure only) +- Configuration: 100% database-driven + +### SDLC Coverage Metrics + +**Phase Coverage:** +- ✅ Planning: Architecture review, PRD alignment +- ✅ Development: Continuous feedback, refactoring +- ✅ Testing: Security scan, quality checks +- ✅ Integration: Auto-merge, conflict resolution +- ✅ Deployment: Validation, health checks +- ✅ Maintenance: Triage, auto-fix, dependencies + +**Coverage: 100% of SDLC phases** + +### Automation Metrics + +**Automated Actions:** +- Issue triage and labeling +- PR categorization +- Code review and approval +- Merge and branch cleanup +- Deployment validation +- Security vulnerability tracking +- Dependency updates + +**Human Intervention Required:** +- Final approval for deployment +- Resolution of blocking issues +- Complex architectural decisions +- Multi-tenant design considerations + +--- + +## Configuration Files + +### 1. Copilot Instructions +**File:** `.github/copilot-instructions.md` + +**Contains:** +- Project context and architecture +- Code conventions (TS, React, Lua, Prisma) +- Development workflow guidance +- Security considerations +- Common patterns and examples +- Integration with workflows +- Useful commands + +### 2. Workflow Definitions +**Directory:** `.github/workflows/` + +**Files:** +- `ci.yml` - CI/CD pipeline +- `code-review.yml` - Automated review +- `auto-merge.yml` - Merge automation +- `issue-triage.yml` - Issue management +- `pr-management.yml` - PR automation +- `merge-conflict-check.yml` - Conflict detection +- `planning.yml` - Planning assistance *(NEW)* +- `development.yml` - Development feedback *(NEW)* +- `deployment.yml` - Deployment automation *(NEW)* + +### 3. Documentation +**Files:** +- `.github/workflows/README.md` - Workflow documentation +- `docs/getting-started/PRD.md` - Product requirements +- `docs/security/SECURITY.md` - Security policies +- `docs/README.md` - Project overview + +--- + +## Benefits + +### For Developers + +1. **Faster Onboarding**: Copilot guides new developers with architectural principles +2. **Consistent Quality**: Automated checks enforce coding standards +3. **Reduced Review Time**: Many issues caught automatically +4. **Better Architecture**: Continuous feedback on declarative principles +5. **Security Awareness**: Proactive vulnerability detection +6. **Learning Tool**: Suggestions teach best practices + +### For Teams + +1. **Standardized Process**: Every issue/PR follows same workflow +2. **Knowledge Sharing**: Architectural principles documented and enforced +3. **Reduced Technical Debt**: Refactoring suggestions identify improvement areas +4. **Faster Iteration**: Auto-merge reduces bottlenecks +5. **Better Tracking**: Deployment and issue tracking automated +6. **Visibility**: Metrics show declarative ratio and code quality trends + +### For the Project + +1. **Architectural Integrity**: Maintains 95% declarative goal +2. **Scalability**: Package-based structure enforced +3. **Multi-Tenant Safety**: Tenant considerations validated +4. **Security**: Continuous vulnerability monitoring +5. **Documentation**: Auto-generated release notes and tracking +6. **Quality**: Consistent enforcement of 150 LOC limit + +--- + +## Future Enhancements + +### Potential Additions + +1. **Copilot Workspace Integration**: Direct IDE integration with workflow context +2. **AI-Generated Tests**: Auto-generate E2E tests from issue descriptions +3. **Performance Monitoring**: Track bundle size, render performance over time +4. **Accessibility Checks**: Automated a11y validation in PRs +5. **Visual Regression Testing**: Screenshot comparison for UI changes +6. **Lua Linting**: Custom linter for Lua scripts following project patterns +7. **Package Validation**: Verify package structure meets standards +8. **Multi-Tenant Testing**: Automated tenant isolation verification + +### Metrics Dashboard + +**Potential Features:** +- Declarative ratio trend over time +- Average component size +- PR merge time +- Auto-fix success rate +- Security vulnerability resolution time +- Test coverage trends +- Deployment frequency + +--- + +## Conclusion + +MetaBuilder's GitHub workflows provide **comprehensive GitHub Copilot integration across all SDLC phases**: + +✅ **Planning** - Architecture review and PRD alignment +✅ **Development** - Continuous quality feedback and refactoring +✅ **Testing** - Security scanning and quality validation +✅ **Integration** - Auto-labeling, review, and merge +✅ **Deployment** - Validation, health checks, and tracking +✅ **Maintenance** - Issue triage, auto-fix, and dependency management + +**Key Achievements:** +- 100% SDLC phase coverage +- Automated enforcement of declarative-first principles +- Context-aware @copilot assistance throughout development +- Comprehensive metrics tracking (declarative ratio, component size) +- Security-first approach with continuous vulnerability monitoring +- Self-documenting with auto-generated deployment notes + +**Documentation:** +- Copilot Instructions: `.github/copilot-instructions.md` +- Workflow Guide: `.github/workflows/README.md` +- This Summary: `.github/COPILOT_SDLC_SUMMARY.md` + +The workflows ensure that GitHub Copilot can assist developers at every stage, from initial planning through deployment and maintenance, while maintaining the project's architectural integrity and quality standards. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 401db087c..7728b27a2 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,243 +1,243 @@ -## Description - - - -## Related Issue - - -Fixes # - -## Type of Change - - - -- [ ] 🐛 Bug fix (non-breaking change that fixes an issue) -- [ ] ✨ New feature (non-breaking change that adds functionality) -- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected) -- [ ] 📚 Documentation update -- [ ] 🎨 UI/UX improvement -- [ ] ♻️ Code refactoring (no functional changes) -- [ ] ⚡ Performance improvement -- [ ] ✅ Test additions or updates -- [ ] 🔧 Configuration/tooling change -- [ ] 📦 Package system change -- [ ] 🔒 Security fix - -## Component/Area Affected - - - -- [ ] Frontend (Next.js UI) -- [ ] Backend (API/Auth) -- [ ] Database (Prisma/Schema) -- [ ] DBAL (TypeScript/C++) -- [ ] Package System -- [ ] Lua Scripting -- [ ] Multi-Tenant System -- [ ] Permission System (Levels 1-6) -- [ ] Workflows -- [ ] Documentation -- [ ] Testing -- [ ] CI/CD -- [ ] Other: - -## Changes Made - - - -### Code Changes -- -- - -### Database Changes -- [ ] Schema changes (Prisma migrations) -- [ ] Seed data updates -- [ ] DBAL contract changes (YAML) - -### Configuration Changes -- [ ] Environment variables -- [ ] Build configuration -- [ ] Package dependencies - -## Testing - - - -### Test Coverage -- [ ] Unit tests added/updated -- [ ] Integration tests added/updated -- [ ] E2E tests added/updated -- [ ] No tests needed (documentation, config, etc.) - -### Test Commands Run -```bash -# Example: -# npm run lint -# npm run typecheck -# npm run test:unit -- --run -# npm run test:e2e -``` - -### Manual Testing - -- [ ] Tested locally -- [ ] Tested in development environment -- [ ] Tested with different user permission levels -- [ ] Tested multi-tenant scenarios - -## Screenshots/Recordings - - - -### Before - - -### After - - -## Architecture & Design Decisions - - - -### Data-Driven Approach -- [ ] Changes follow MetaBuilder's data-driven (JSON/Lua) architecture -- [ ] Declarative components used instead of hardcoded JSX where applicable -- [ ] DBAL used for database operations (not raw Prisma) - -### Multi-Tenancy -- [ ] All queries include `tenantId` filtering -- [ ] Tenant isolation verified -- [ ] N/A - No database queries - -### Permission System -- [ ] Permission checks implemented at correct levels -- [ ] AuthGate or canAccessLevel used where needed -- [ ] N/A - No permission-sensitive features - -### Package System -- [ ] Package metadata follows correct structure (metadata.json, components.json) -- [ ] Package uses snake_case naming and semver versioning -- [ ] Dependencies declared in package metadata -- [ ] N/A - No package changes - -### Security -- [ ] Input validation implemented -- [ ] No XSS vulnerabilities introduced -- [ ] No SQL injection vulnerabilities -- [ ] Passwords hashed with SHA-512 (if applicable) -- [ ] Lua sandbox restrictions maintained (if applicable) -- [ ] No secrets committed to code - -## Breaking Changes - - - -**Breaking Changes:** Yes / No - - - -## Migration Steps - - - -```bash -# Commands needed to migrate: -# npm run db:generate -# npm run db:migrate -``` - -## Documentation - - - -- [ ] README.md updated -- [ ] API documentation updated -- [ ] Architecture docs updated (docs/architecture/) -- [ ] Code comments added/updated -- [ ] Migration guide created (if breaking change) -- [ ] No documentation needed - -## Pre-Submission Checklist - - - -### Code Quality -- [ ] Code follows project conventions (one lambda per file, MUI not Radix/Tailwind) -- [ ] ESLint passes (`npm run lint`) -- [ ] TypeScript compiles (`npm run typecheck`) -- [ ] No console errors or warnings -- [ ] Code is DRY (Don't Repeat Yourself) - -### Testing & Verification -- [ ] All tests pass (`npm run test:unit -- --run`) -- [ ] Test coverage for new code meets standards -- [ ] E2E tests pass (if applicable) -- [ ] Manual testing completed -- [ ] Tested across different browsers (if UI change) - -### Database & Schema -- [ ] Prisma schema validated (`npx prisma validate`) -- [ ] Database migrations tested -- [ ] DBAL conformance tests pass (if DBAL changes) -- [ ] N/A - No database changes - -### Security -- [ ] Security vulnerabilities checked -- [ ] No sensitive data in commits -- [ ] Input validation implemented -- [ ] CSRF/XSS protections in place (if applicable) - -### MetaBuilder-Specific -- [ ] Changes align with data-driven architecture principles -- [ ] Multi-tenant safety verified (tenantId filtering) -- [ ] Permission checks implemented correctly -- [ ] DBAL used instead of raw Prisma (where applicable) -- [ ] Generic components used where possible (RenderComponent) - -### Review -- [ ] Self-reviewed code changes -- [ ] Added TODO comments for deferred work (if any) -- [ ] Commit messages are clear and descriptive -- [ ] PR title is descriptive -- [ ] No unrelated changes included - -## Additional Notes - - - -## Deployment Considerations - - - -- [ ] No special deployment steps needed -- [ ] Requires environment variable changes -- [ ] Requires database migration -- [ ] Requires cache invalidation -- [ ] Requires server restart -- [ ] Other: - -## Reviewer Notes - - - -**Focus Areas:** -- -- - -**Questions for Reviewers:** -- -- - ---- - - +## Description + + + +## Related Issue + + +Fixes # + +## Type of Change + + + +- [ ] 🐛 Bug fix (non-breaking change that fixes an issue) +- [ ] ✨ New feature (non-breaking change that adds functionality) +- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] 📚 Documentation update +- [ ] 🎨 UI/UX improvement +- [ ] ♻️ Code refactoring (no functional changes) +- [ ] ⚡ Performance improvement +- [ ] ✅ Test additions or updates +- [ ] 🔧 Configuration/tooling change +- [ ] 📦 Package system change +- [ ] 🔒 Security fix + +## Component/Area Affected + + + +- [ ] Frontend (Next.js UI) +- [ ] Backend (API/Auth) +- [ ] Database (Prisma/Schema) +- [ ] DBAL (TypeScript/C++) +- [ ] Package System +- [ ] Lua Scripting +- [ ] Multi-Tenant System +- [ ] Permission System (Levels 1-6) +- [ ] Workflows +- [ ] Documentation +- [ ] Testing +- [ ] CI/CD +- [ ] Other: + +## Changes Made + + + +### Code Changes +- +- + +### Database Changes +- [ ] Schema changes (Prisma migrations) +- [ ] Seed data updates +- [ ] DBAL contract changes (YAML) + +### Configuration Changes +- [ ] Environment variables +- [ ] Build configuration +- [ ] Package dependencies + +## Testing + + + +### Test Coverage +- [ ] Unit tests added/updated +- [ ] Integration tests added/updated +- [ ] E2E tests added/updated +- [ ] No tests needed (documentation, config, etc.) + +### Test Commands Run +```bash +# Example: +# npm run lint +# npm run typecheck +# npm run test:unit -- --run +# npm run test:e2e +``` + +### Manual Testing + +- [ ] Tested locally +- [ ] Tested in development environment +- [ ] Tested with different user permission levels +- [ ] Tested multi-tenant scenarios + +## Screenshots/Recordings + + + +### Before + + +### After + + +## Architecture & Design Decisions + + + +### Data-Driven Approach +- [ ] Changes follow MetaBuilder's data-driven (JSON/Lua) architecture +- [ ] Declarative components used instead of hardcoded JSX where applicable +- [ ] DBAL used for database operations (not raw Prisma) + +### Multi-Tenancy +- [ ] All queries include `tenantId` filtering +- [ ] Tenant isolation verified +- [ ] N/A - No database queries + +### Permission System +- [ ] Permission checks implemented at correct levels +- [ ] AuthGate or canAccessLevel used where needed +- [ ] N/A - No permission-sensitive features + +### Package System +- [ ] Package metadata follows correct structure (metadata.json, components.json) +- [ ] Package uses snake_case naming and semver versioning +- [ ] Dependencies declared in package metadata +- [ ] N/A - No package changes + +### Security +- [ ] Input validation implemented +- [ ] No XSS vulnerabilities introduced +- [ ] No SQL injection vulnerabilities +- [ ] Passwords hashed with SHA-512 (if applicable) +- [ ] Lua sandbox restrictions maintained (if applicable) +- [ ] No secrets committed to code + +## Breaking Changes + + + +**Breaking Changes:** Yes / No + + + +## Migration Steps + + + +```bash +# Commands needed to migrate: +# npm run db:generate +# npm run db:migrate +``` + +## Documentation + + + +- [ ] README.md updated +- [ ] API documentation updated +- [ ] Architecture docs updated (docs/architecture/) +- [ ] Code comments added/updated +- [ ] Migration guide created (if breaking change) +- [ ] No documentation needed + +## Pre-Submission Checklist + + + +### Code Quality +- [ ] Code follows project conventions (one lambda per file, MUI not Radix/Tailwind) +- [ ] ESLint passes (`npm run lint`) +- [ ] TypeScript compiles (`npm run typecheck`) +- [ ] No console errors or warnings +- [ ] Code is DRY (Don't Repeat Yourself) + +### Testing & Verification +- [ ] All tests pass (`npm run test:unit -- --run`) +- [ ] Test coverage for new code meets standards +- [ ] E2E tests pass (if applicable) +- [ ] Manual testing completed +- [ ] Tested across different browsers (if UI change) + +### Database & Schema +- [ ] Prisma schema validated (`npx prisma validate`) +- [ ] Database migrations tested +- [ ] DBAL conformance tests pass (if DBAL changes) +- [ ] N/A - No database changes + +### Security +- [ ] Security vulnerabilities checked +- [ ] No sensitive data in commits +- [ ] Input validation implemented +- [ ] CSRF/XSS protections in place (if applicable) + +### MetaBuilder-Specific +- [ ] Changes align with data-driven architecture principles +- [ ] Multi-tenant safety verified (tenantId filtering) +- [ ] Permission checks implemented correctly +- [ ] DBAL used instead of raw Prisma (where applicable) +- [ ] Generic components used where possible (RenderComponent) + +### Review +- [ ] Self-reviewed code changes +- [ ] Added TODO comments for deferred work (if any) +- [ ] Commit messages are clear and descriptive +- [ ] PR title is descriptive +- [ ] No unrelated changes included + +## Additional Notes + + + +## Deployment Considerations + + + +- [ ] No special deployment steps needed +- [ ] Requires environment variable changes +- [ ] Requires database migration +- [ ] Requires cache invalidation +- [ ] Requires server restart +- [ ] Other: + +## Reviewer Notes + + + +**Focus Areas:** +- +- + +**Questions for Reviewers:** +- +- + +--- + + diff --git a/.github/TEMPLATES.md b/.github/TEMPLATES.md index 31ab60c32..e50ce893b 100644 --- a/.github/TEMPLATES.md +++ b/.github/TEMPLATES.md @@ -1,343 +1,343 @@ -# Issue and Pull Request Templates - -This document describes the issue and PR templates available for MetaBuilder and how to use them effectively. - -## Overview - -MetaBuilder uses structured templates to ensure consistent, high-quality issues and pull requests. These templates are specifically designed for MetaBuilder's data-driven, multi-tenant architecture. - -## Issue Templates - -### Available Templates - -#### 🐛 Bug Report (`bug_report.yml`) -Use this template to report bugs or unexpected behavior. - -**Key Features:** -- Environment details capture (OS, Node version, browser, database) -- Severity levels (Critical, High, Medium, Low) -- Component categorization -- Reproducible steps -- Pre-submission checklist - -**Best For:** -- Application crashes or errors -- Features not working as expected -- Performance issues -- UI/UX bugs - -#### ✨ Feature Request (`feature_request.yml`) -Request new features or enhancements aligned with MetaBuilder's architecture. - -**Key Features:** -- Problem statement and solution proposal -- Target user permission levels (Level 1-6) -- Priority assessment -- Use case descriptions -- Technical considerations -- Contribution willingness - -**Best For:** -- New feature ideas -- Improvements to existing features -- API enhancements -- User experience improvements - -#### 📚 Documentation (`documentation.yml`) -Report documentation issues or request improvements. - -**Key Features:** -- Documentation type categorization -- Location/path specification -- Suggested improvements -- Documentation area targeting - -**Best For:** -- Missing documentation -- Outdated information -- Unclear explanations -- Broken links or typos -- Missing code examples - -#### 📦 Package Request (`package_request.yml`) -Request new packages for MetaBuilder's package system. - -**Key Features:** -- Package naming (snake_case convention) -- Package type selection -- Minimum permission level -- Component and Lua script planning -- Database schema requirements -- Multi-tenant consideration - -**Best For:** -- New package ideas -- Package integrations -- Package improvements -- Community packages - -**Special Considerations:** -- Package names must use snake_case -- Must specify multi-tenant requirements -- Should include Lua script needs (MetaBuilder is 95% JSON/Lua) -- Must declare dependencies - -#### 🔧 DBAL Issue (`dbal_issue.yml`) -Report issues with the Database Abstraction Layer. - -**Key Features:** -- Implementation selection (TypeScript/C++) -- Operation type categorization -- Conformance test status -- Implementation parity checks -- Severity levels - -**Best For:** -- DBAL TypeScript SDK issues (`dbal/ts/`) -- DBAL C++ daemon issues (`dbal/production/`) -- YAML contract problems (`api/schema/`) -- Conformance test failures -- Implementation inconsistencies - -**Special Considerations:** -- Check YAML schema definitions first -- Run conformance tests if applicable -- Verify tenant isolation -- Note if both implementations behave differently - -### Template Configuration (`config.yml`) - -The config file provides: -- Documentation links -- Community discussion links -- Private security reporting -- Disables blank issues to ensure structure - -## Pull Request Template - -### Structure - -The PR template (`PULL_REQUEST_TEMPLATE.md`) includes comprehensive sections: - -#### 1. Basic Information -- Description of changes -- Related issue linking -- Type of change -- Component/area affected - -#### 2. Changes Made -- Detailed list of code changes -- Database/schema changes -- Configuration changes - -#### 3. Testing -- Test coverage (unit, integration, E2E) -- Manual testing verification -- Permission level testing -- Multi-tenant scenario testing - -#### 4. Architecture & Design Decisions - -**Data-Driven Approach:** -- Verify JSON/Lua architecture alignment -- Use of declarative components -- DBAL usage for database operations - -**Multi-Tenancy:** -- TenantId filtering verification -- Tenant isolation checks - -**Permission System:** -- Permission checks at correct levels -- AuthGate/canAccessLevel usage - -**Package System:** -- Metadata structure compliance -- Naming conventions (snake_case, semver) -- Dependency declarations - -**Security:** -- Input validation -- XSS/SQL injection checks -- Password hashing (SHA-512) -- Lua sandbox restrictions -- No secrets in code - -#### 5. Breaking Changes -- Migration steps -- Impact assessment -- Upgrade guide - -#### 6. Documentation -- README updates -- API documentation -- Architecture docs -- Migration guides - -#### 7. Pre-Submission Checklist - -**Code Quality:** -- Follows conventions (one lambda per file) -- Uses MUI (not Radix/Tailwind) -- ESLint passes -- TypeScript compiles - -**Testing:** -- All tests pass -- Test coverage adequate -- E2E tests pass (if applicable) -- Cross-browser testing (if UI) - -**Database & Schema:** -- Prisma schema validated -- Migrations tested -- DBAL conformance tests pass - -**Security:** -- Vulnerabilities checked -- Input validation implemented -- No sensitive data committed - -**MetaBuilder-Specific:** -- Data-driven architecture alignment -- Multi-tenant safety verified -- Permission checks correct -- DBAL used (not raw Prisma) -- Generic components where possible - -#### 8. Additional Sections -- Deployment considerations -- Reviewer notes -- Focus areas for review - -## Using the Templates - -### Creating an Issue - -1. Go to the [Issues page](https://github.com/johndoe6345789/metabuilder/issues) -2. Click "New issue" -3. Select the appropriate template -4. Fill in all required fields (marked with red asterisk) -5. Complete the pre-submission checklist -6. Submit the issue - -### Creating a Pull Request - -1. Push your branch to GitHub -2. Navigate to the repository -3. Click "Pull requests" → "New pull request" -4. Select your branch -5. The PR template will auto-populate -6. Fill in all sections thoroughly -7. Mark checkboxes in the pre-submission checklist -8. Submit the PR - -### Template Tips - -**For Issues:** -- Be specific and detailed -- Include reproduction steps for bugs -- Provide environment details -- Search for duplicates first -- Check documentation before submitting - -**For PRs:** -- Link related issues -- Include screenshots for UI changes -- Document breaking changes clearly -- Run all tests before submitting -- Complete the entire checklist -- Focus on minimal, surgical changes - -## MetaBuilder-Specific Guidelines - -### Data-Driven Architecture -MetaBuilder is 95% JSON/Lua, not TypeScript. When contributing: -- Prefer JSON/Lua configuration over hardcoded TS -- Use `RenderComponent` for declarative UI -- Add Lua scripts to `packages/*/seed/scripts/` -- Keep TypeScript as adapters/wrappers - -### Multi-Tenancy -All contributions must respect tenant isolation: -- Include `tenantId` in all queries -- Use `Database` class methods, not raw Prisma -- Test with multiple tenants -- Document tenant-specific behavior - -### Permission System (Levels 1-6) -- Level 1: Public (no auth) -- Level 2: User (basic auth) -- Level 3: Moderator (content moderation) -- Level 4: Admin (user management) -- Level 5: God (system config, packages) -- Level 6: Supergod (full system control) - -When adding features, specify the minimum required level and use `canAccessLevel()` checks. - -### Package System -Packages follow strict conventions: -- Name: `snake_case` (e.g., `blog_engine`) -- Version: Semver (e.g., `1.2.3`) -- Structure: `packages/{name}/seed/` with `metadata.json`, `components.json` -- Lua scripts in `packages/{name}/seed/scripts/` -- Optional React components in `packages/{name}/src/` - -### DBAL (Database Abstraction Layer) -- TypeScript implementation: `dbal/ts/` (development) -- C++ implementation: `dbal/production/` (production) -- YAML contracts: `api/schema/` (source of truth) -- Always update YAML first -- Run conformance tests: `python tools/conformance/run_all.py` -- Ensure both implementations behave identically - -## Best Practices - -### Issue Reporting -1. **Search first**: Check if the issue already exists -2. **Be specific**: Provide exact steps and details -3. **Be respectful**: Follow the code of conduct -4. **Be patient**: Maintainers will respond when available -5. **Follow up**: Provide additional info if requested - -### Pull Requests -1. **Small changes**: Keep PRs focused and minimal -2. **Test thoroughly**: Run all tests and linters -3. **Document well**: Update docs with changes -4. **Follow conventions**: Match existing code style -5. **Respond quickly**: Address review feedback promptly - -### Security -- **Never commit secrets**: No API keys, passwords, tokens -- **Report privately**: Use GitHub Security Advisories for vulnerabilities -- **Hash passwords**: Always use SHA-512 via `password-utils.ts` -- **Validate input**: Never trust user input -- **Sandbox Lua**: Maintain Lua script restrictions - -## Getting Help - -If you have questions about the templates or contribution process: - -1. **Documentation**: Check [docs/](../docs/) for guides -2. **Discussions**: Ask in [GitHub Discussions](https://github.com/johndoe6345789/metabuilder/discussions) -3. **Examples**: Look at existing issues and PRs -4. **Workflow Guide**: See `.github/prompts/0-kickstart.md` - -## Template Maintenance - -These templates are living documents. If you find: -- Missing fields or options -- Unclear instructions -- Better ways to structure -- New categories needed - -Please submit an issue with the "documentation" template to suggest improvements! - -## Related Files - -- **Workflow Guide**: `.github/prompts/0-kickstart.md` -- **Contributing**: `README.md` → Contributing section -- **Architecture**: `docs/architecture/` -- **DBAL Guide**: `dbal/docs/AGENTS.md` -- **UI Standards**: `UI_STANDARDS.md` -- **Copilot Instructions**: `.github/copilot-instructions.md` +# Issue and Pull Request Templates + +This document describes the issue and PR templates available for MetaBuilder and how to use them effectively. + +## Overview + +MetaBuilder uses structured templates to ensure consistent, high-quality issues and pull requests. These templates are specifically designed for MetaBuilder's data-driven, multi-tenant architecture. + +## Issue Templates + +### Available Templates + +#### 🐛 Bug Report (`bug_report.yml`) +Use this template to report bugs or unexpected behavior. + +**Key Features:** +- Environment details capture (OS, Node version, browser, database) +- Severity levels (Critical, High, Medium, Low) +- Component categorization +- Reproducible steps +- Pre-submission checklist + +**Best For:** +- Application crashes or errors +- Features not working as expected +- Performance issues +- UI/UX bugs + +#### ✨ Feature Request (`feature_request.yml`) +Request new features or enhancements aligned with MetaBuilder's architecture. + +**Key Features:** +- Problem statement and solution proposal +- Target user permission levels (Level 1-6) +- Priority assessment +- Use case descriptions +- Technical considerations +- Contribution willingness + +**Best For:** +- New feature ideas +- Improvements to existing features +- API enhancements +- User experience improvements + +#### 📚 Documentation (`documentation.yml`) +Report documentation issues or request improvements. + +**Key Features:** +- Documentation type categorization +- Location/path specification +- Suggested improvements +- Documentation area targeting + +**Best For:** +- Missing documentation +- Outdated information +- Unclear explanations +- Broken links or typos +- Missing code examples + +#### 📦 Package Request (`package_request.yml`) +Request new packages for MetaBuilder's package system. + +**Key Features:** +- Package naming (snake_case convention) +- Package type selection +- Minimum permission level +- Component and Lua script planning +- Database schema requirements +- Multi-tenant consideration + +**Best For:** +- New package ideas +- Package integrations +- Package improvements +- Community packages + +**Special Considerations:** +- Package names must use snake_case +- Must specify multi-tenant requirements +- Should include Lua script needs (MetaBuilder is 95% JSON/Lua) +- Must declare dependencies + +#### 🔧 DBAL Issue (`dbal_issue.yml`) +Report issues with the Database Abstraction Layer. + +**Key Features:** +- Implementation selection (TypeScript/C++) +- Operation type categorization +- Conformance test status +- Implementation parity checks +- Severity levels + +**Best For:** +- DBAL TypeScript SDK issues (`dbal/ts/`) +- DBAL C++ daemon issues (`dbal/production/`) +- YAML contract problems (`api/schema/`) +- Conformance test failures +- Implementation inconsistencies + +**Special Considerations:** +- Check YAML schema definitions first +- Run conformance tests if applicable +- Verify tenant isolation +- Note if both implementations behave differently + +### Template Configuration (`config.yml`) + +The config file provides: +- Documentation links +- Community discussion links +- Private security reporting +- Disables blank issues to ensure structure + +## Pull Request Template + +### Structure + +The PR template (`PULL_REQUEST_TEMPLATE.md`) includes comprehensive sections: + +#### 1. Basic Information +- Description of changes +- Related issue linking +- Type of change +- Component/area affected + +#### 2. Changes Made +- Detailed list of code changes +- Database/schema changes +- Configuration changes + +#### 3. Testing +- Test coverage (unit, integration, E2E) +- Manual testing verification +- Permission level testing +- Multi-tenant scenario testing + +#### 4. Architecture & Design Decisions + +**Data-Driven Approach:** +- Verify JSON/Lua architecture alignment +- Use of declarative components +- DBAL usage for database operations + +**Multi-Tenancy:** +- TenantId filtering verification +- Tenant isolation checks + +**Permission System:** +- Permission checks at correct levels +- AuthGate/canAccessLevel usage + +**Package System:** +- Metadata structure compliance +- Naming conventions (snake_case, semver) +- Dependency declarations + +**Security:** +- Input validation +- XSS/SQL injection checks +- Password hashing (SHA-512) +- Lua sandbox restrictions +- No secrets in code + +#### 5. Breaking Changes +- Migration steps +- Impact assessment +- Upgrade guide + +#### 6. Documentation +- README updates +- API documentation +- Architecture docs +- Migration guides + +#### 7. Pre-Submission Checklist + +**Code Quality:** +- Follows conventions (one lambda per file) +- Uses MUI (not Radix/Tailwind) +- ESLint passes +- TypeScript compiles + +**Testing:** +- All tests pass +- Test coverage adequate +- E2E tests pass (if applicable) +- Cross-browser testing (if UI) + +**Database & Schema:** +- Prisma schema validated +- Migrations tested +- DBAL conformance tests pass + +**Security:** +- Vulnerabilities checked +- Input validation implemented +- No sensitive data committed + +**MetaBuilder-Specific:** +- Data-driven architecture alignment +- Multi-tenant safety verified +- Permission checks correct +- DBAL used (not raw Prisma) +- Generic components where possible + +#### 8. Additional Sections +- Deployment considerations +- Reviewer notes +- Focus areas for review + +## Using the Templates + +### Creating an Issue + +1. Go to the [Issues page](https://github.com/johndoe6345789/metabuilder/issues) +2. Click "New issue" +3. Select the appropriate template +4. Fill in all required fields (marked with red asterisk) +5. Complete the pre-submission checklist +6. Submit the issue + +### Creating a Pull Request + +1. Push your branch to GitHub +2. Navigate to the repository +3. Click "Pull requests" → "New pull request" +4. Select your branch +5. The PR template will auto-populate +6. Fill in all sections thoroughly +7. Mark checkboxes in the pre-submission checklist +8. Submit the PR + +### Template Tips + +**For Issues:** +- Be specific and detailed +- Include reproduction steps for bugs +- Provide environment details +- Search for duplicates first +- Check documentation before submitting + +**For PRs:** +- Link related issues +- Include screenshots for UI changes +- Document breaking changes clearly +- Run all tests before submitting +- Complete the entire checklist +- Focus on minimal, surgical changes + +## MetaBuilder-Specific Guidelines + +### Data-Driven Architecture +MetaBuilder is 95% JSON/Lua, not TypeScript. When contributing: +- Prefer JSON/Lua configuration over hardcoded TS +- Use `RenderComponent` for declarative UI +- Add Lua scripts to `packages/*/seed/scripts/` +- Keep TypeScript as adapters/wrappers + +### Multi-Tenancy +All contributions must respect tenant isolation: +- Include `tenantId` in all queries +- Use `Database` class methods, not raw Prisma +- Test with multiple tenants +- Document tenant-specific behavior + +### Permission System (Levels 1-6) +- Level 1: Public (no auth) +- Level 2: User (basic auth) +- Level 3: Moderator (content moderation) +- Level 4: Admin (user management) +- Level 5: God (system config, packages) +- Level 6: Supergod (full system control) + +When adding features, specify the minimum required level and use `canAccessLevel()` checks. + +### Package System +Packages follow strict conventions: +- Name: `snake_case` (e.g., `blog_engine`) +- Version: Semver (e.g., `1.2.3`) +- Structure: `packages/{name}/seed/` with `metadata.json`, `components.json` +- Lua scripts in `packages/{name}/seed/scripts/` +- Optional React components in `packages/{name}/src/` + +### DBAL (Database Abstraction Layer) +- TypeScript implementation: `dbal/ts/` (development) +- C++ implementation: `dbal/production/` (production) +- YAML contracts: `api/schema/` (source of truth) +- Always update YAML first +- Run conformance tests: `python tools/conformance/run_all.py` +- Ensure both implementations behave identically + +## Best Practices + +### Issue Reporting +1. **Search first**: Check if the issue already exists +2. **Be specific**: Provide exact steps and details +3. **Be respectful**: Follow the code of conduct +4. **Be patient**: Maintainers will respond when available +5. **Follow up**: Provide additional info if requested + +### Pull Requests +1. **Small changes**: Keep PRs focused and minimal +2. **Test thoroughly**: Run all tests and linters +3. **Document well**: Update docs with changes +4. **Follow conventions**: Match existing code style +5. **Respond quickly**: Address review feedback promptly + +### Security +- **Never commit secrets**: No API keys, passwords, tokens +- **Report privately**: Use GitHub Security Advisories for vulnerabilities +- **Hash passwords**: Always use SHA-512 via `password-utils.ts` +- **Validate input**: Never trust user input +- **Sandbox Lua**: Maintain Lua script restrictions + +## Getting Help + +If you have questions about the templates or contribution process: + +1. **Documentation**: Check [docs/](../docs/) for guides +2. **Discussions**: Ask in [GitHub Discussions](https://github.com/johndoe6345789/metabuilder/discussions) +3. **Examples**: Look at existing issues and PRs +4. **Workflow Guide**: See `.github/prompts/0-kickstart.md` + +## Template Maintenance + +These templates are living documents. If you find: +- Missing fields or options +- Unclear instructions +- Better ways to structure +- New categories needed + +Please submit an issue with the "documentation" template to suggest improvements! + +## Related Files + +- **Workflow Guide**: `.github/prompts/0-kickstart.md` +- **Contributing**: `README.md` → Contributing section +- **Architecture**: `docs/architecture/` +- **DBAL Guide**: `dbal/docs/AGENTS.md` +- **UI Standards**: `UI_STANDARDS.md` +- **Copilot Instructions**: `.github/copilot-instructions.md` diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5f192145b..c330b9558 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,247 +1,247 @@ -# GitHub Copilot Instructions for MetaBuilder - -## Architecture Overview - -MetaBuilder is a **data-driven, multi-tenant platform** with 95% functionality in JSON/Lua, not TypeScript. The system combines: - -- **6-Level Permission System**: Public → User → Moderator → Admin → God → Supergod access hierarchies -- **DBAL (Database Abstraction Layer)**: TypeScript SDK + C++ daemon, language-agnostic via YAML contracts -- **Declarative Components**: Render complex UIs from JSON configuration using `RenderComponent` -- **Package System**: Self-contained modules in `/packages/{name}/seed/` with metadata, components, scripts -- **Multi-Source Package Repos**: Support for local and remote package registries via `PackageSourceManager` -- **Multi-Tenancy**: All data queries filter by `tenantId`; each tenant has isolated configurations - -## 0-kickstart Operating Rules - -Follow `.github/prompts/0-kickstart.md` as the current workflow source of truth. Key rules: -- Work through `.github/prompts/` as needed; start with `0-kickstart.md`. -- Commit as you go with descriptive messages; default to trunking on `main`. -- Use `act` to diagnose GitHub workflow issues locally. -- Keep unit tests parameterized; create new test files where possible; use 1:1 source-to-test naming. -- Leave TODO comments for missing functionality. -- Check `docs/todo/` before starting. -- One lambda per file; classes only serve as containers for related lambdas (see `.github/prompts/LAMBDA_PROMPT.md`). -- Route data access through DBAL; treat it as the trusted layer. -- Design for flexibility, modularity, and containerization. -- See `docs/RADIX_TO_MUI_MIGRATION.md` for UI migration guidance. - -## Critical Patterns - -### 1. API-First DBAL Development -When adding features to DBAL: -1. **Define in YAML first**: `api/schema/entities/*.yaml` and `api/schema/operations/*.yaml` -2. **Generate types**: `python tools/codegen/gen_types.py` (creates TS and C++ types) -3. **Implement adapters**: TypeScript (`ts/src/adapters/`) for speed, C++ (`cpp/src/adapters/`) for security -4. **Add conformance tests**: `common/contracts/*_tests.yaml` (runs on both implementations to guarantee parity) -5. Never add fields/operations directly in code without updating YAML source of truth - -**Why**: C++ daemon isolates credentials (users never see DB URLs), enforces row-level security, and protects against malicious queries. - -### 2. Generic Component Rendering -Instead of hardcoded components, use declarative config: -```tsx -// ❌ Wrong: Hardcoded - - -// ✅ Right: Declarative - -``` -See: `RenderComponent.tsx`, `declarative-component-renderer.ts` - -### 3. Package Seed Data Structure -Each package auto-loads on init: -``` -packages/{name}/ -├── seed/ -│ ├── metadata.json # Package info, exports, dependencies, minLevel -│ ├── components.json # Component definitions -│ ├── scripts/ # Lua scripts organized by function -│ └── index.ts # Exports packageSeed object -├── src/ # Optional React components -└── static_content/ # Assets (images, etc.) -``` -Loaded by `initializePackageSystem()` → `buildPackageRegistry()` → `exportAllPackagesForSeed()` - -### 3a. Multi-Source Package Repositories -Packages can come from multiple sources: -```typescript -import { createPackageSourceManager, LocalPackageSource, RemotePackageSource } from '@/lib/packages/package-glue' - -const manager = createPackageSourceManager({ - enableRemote: true, - remoteUrl: 'https://registry.metabuilder.dev/api/v1', - conflictResolution: 'priority' // or 'latest-version', 'local-first', 'remote-first' -}) - -const packages = await manager.fetchMergedIndex() -const pkg = await manager.loadPackage('dashboard') -``` -See: `docs/packages/package-sources.md`, `package-glue/sources/` - -### 4. Database Helpers Pattern -Always use `Database` class methods, never raw Prisma: -```typescript -// ✅ Right -const users = await Database.getUsers() -await Database.setSchemas(schemas) - -// ❌ Wrong -const users = await prisma.user.findMany() -``` -See: `src/lib/database.ts` (1200+ LOC utility wrapper) - -### 5. Lua Sandbox Execution -Lua scripts run in isolated sandbox without access to `os`, `io`, `require`: -```typescript -// Sandbox context provided in script -function validateEmail(email) - -- No file I/O, no system access, no external requires - return string.match(email, "^[^@]+@[^@]+$") ~= nil -end -``` -Always test scripts with `DeclarativeComponentRenderer.executeLuaScript()` - -## Code Conventions - -### UI Components & Styling - -**⚠️ CRITICAL: This project does NOT use Radix UI or Tailwind CSS** - -- ❌ **NEVER import from `@radix-ui/*`** - These dependencies have been removed -- ❌ **NEVER use Tailwind utility classes** in `className` props -- ✅ **ALWAYS use Material-UI** (`@mui/material`) for UI components -- ✅ **Use MUI's `sx` prop** for inline styles with theme access -- ✅ **Create `.module.scss` files** for component-specific custom styles -- ✅ **Use `@mui/icons-material`** for icons, not lucide-react or heroicons - -```tsx -// ❌ Wrong: Using Radix UI or Tailwind -import { Dialog } from '@radix-ui/react-dialog' - - -// ✅ Right: Using Material-UI -import { Dialog, Button } from '@mui/material' - -Content -``` - -**Component Mapping:** -- Radix Dialog → MUI Dialog -- Radix Select → MUI Select -- Radix Checkbox → MUI Checkbox -- Radix Switch → MUI Switch -- Tailwind classes → MUI `sx` prop or SCSS modules - -**See:** `UI_STANDARDS.md` and `docs/UI_MIGRATION.md` for complete reference - -### TypeScript/React -- One lambda per file; classes are containers for related lambdas. -- Keep files small and focused; split by responsibility when they grow. -- Use `@/` absolute paths -- Functional components with hooks; avoid class components -- Test files next to source with matching names: `utils.ts` + `utils.test.ts`, using parameterized `it.each()` - -### Tests -All functions need coverage with parameterized tests: -```typescript -// From schema-utils.test.ts: 63 tests for 14 functions -it.each([ - { input: 'case1', expected: 'result1' }, - { input: 'case2', expected: 'result2' }, -])('should handle $input', ({ input, expected }) => { - expect(myFunction(input)).toBe(expected) -}) -``` -Run `npm run test:coverage:report` to auto-generate coverage markdown. - -### Database -- Schema in `prisma/schema.prisma`, always run `npm run db:generate` after changes -- Hash passwords with SHA-512 (see `password-utils.ts`) -- Queries must include `where('tenantId', currentTenant.id)` for multi-tenancy - -### Styling -Material-UI with SASS; theme in `src/theme/mui-theme.ts` with light/dark mode support. Font families: IBM Plex Sans (body), Space Grotesk (headings), JetBrains Mono (code). Use MUI's `sx` prop for inline styles or create `.module.scss` files for custom component styles. - -## Development Checklist - -**Before implementing**: Check `docs/` and `docs/todo/`, and review `.github/prompts/0-kickstart.md` for current workflow rules. - -**During implementation**: -1. Define database schema changes first (Prisma) -2. Add seed data to `src/seed-data/` or package `/seed/` -3. Use generic renderers (`RenderComponent`) not hardcoded JSX -4. Add Lua scripts in `src/lib/lua-snippets.ts` or package `/seed/scripts/` -5. Keep one lambda per file and split as needed -6. Add parameterized tests in `.test.ts` files with matching names - -**Before commit**: -- `npm run lint:fix` (fixes ESLint issues) -- `npm test -- --run` (all tests pass) -- `npm run test:coverage:report` (verify new functions have tests) -- `npm run test:e2e` (critical workflows still work) -- Use `npm run act:diagnose` or `npm run act` when investigating CI/workflow failures -- Commit with a descriptive message on `main` unless a PR workflow is explicitly required - -## Multi-Tenant Safety - -Every query must filter by tenant: -```typescript -// ❌ Never -const data = await Database.getData() - -// ✅ Always -const data = await Database.getData({ tenantId: user.tenantId }) -``` - -Permission checks cascade from lowest level: -```typescript -if (user.level >= 3) { // Admin and above - showAdminPanel() -} -``` - -## DBAL-Specific Guidance - -**TypeScript DBAL**: Fast iteration, development use. Located in `dbal/ts/src/`. -**C++ DBAL Daemon**: Production security, credential protection. Located in `dbal/production/src/`. -**Conformance Tests**: Guarantee both implementations behave identically. Update `common/contracts/` when changing YAML schemas. - -If fixing a DBAL bug: -1. Verify the bug exists in YAML schema definition -2. Reproduce in TypeScript implementation first (faster feedback loop) -3. Apply fix to both TS and C++ adapters -4. Add/update conformance test in `common/contracts/` -5. Verify both implementations pass test: `python tools/conformance/run_all.py` - -## Common Mistakes - -❌ **Hardcoding values in TSX** → Move to database or YAML config -❌ **Forgetting tenantId filter** → Breaks multi-tenancy -❌ **Adding fields without Prisma generate** → Type errors in DB helper -❌ **Plain JS loops over Fengari tables** → Use Lua, not TS, for Lua data -❌ **Multiple lambdas per file** → Split into single-lambda files and wrap with a class only when needed -❌ **New function without test** → `npm run test:check-functions` will fail -❌ **Missing TODO for unfinished behavior** → Leave a TODO comment where functionality is pending - -## Key Files - -- **Architecture**: `docs/architecture/5-level-system.md` (permissions), `docs/architecture/packages.md` (packages) -- **Components**: `src/components/RenderComponent.tsx` (generic renderer), `src/lib/declarative-component-renderer.ts` -- **Database**: `src/lib/database.ts` (all DB operations), `prisma/schema.prisma` (schema) -- **Packages**: `src/lib/package-loader.ts` (initialization), `packages/*/seed/` (definitions) -- **Tests**: `src/lib/schema-utils.test.ts` (parameterized pattern), `FUNCTION_TEST_COVERAGE.md` (auto-generated report) -- **DBAL**: `dbal/docs/AGENTS.md` (detailed DBAL agent guide), `api/schema/` (YAML contracts) - -## Questions to Ask - -1. Is this hardcoded value better in database? -2. Could a generic component render this instead of custom TSX? -3. Does this query filter by tenantId? -4. Could Lua handle this without code changes? -5. Is this one lambda per file (and test file name matches)? -6. Does this function have a parameterized test? -7. Is this DBAL change reflected in YAML schema first? +# GitHub Copilot Instructions for MetaBuilder + +## Architecture Overview + +MetaBuilder is a **data-driven, multi-tenant platform** with 95% functionality in JSON/Lua, not TypeScript. The system combines: + +- **6-Level Permission System**: Public → User → Moderator → Admin → God → Supergod access hierarchies +- **DBAL (Database Abstraction Layer)**: TypeScript SDK + C++ daemon, language-agnostic via YAML contracts +- **Declarative Components**: Render complex UIs from JSON configuration using `RenderComponent` +- **Package System**: Self-contained modules in `/packages/{name}/seed/` with metadata, components, scripts +- **Multi-Source Package Repos**: Support for local and remote package registries via `PackageSourceManager` +- **Multi-Tenancy**: All data queries filter by `tenantId`; each tenant has isolated configurations + +## 0-kickstart Operating Rules + +Follow `.github/prompts/0-kickstart.md` as the current workflow source of truth. Key rules: +- Work through `.github/prompts/` as needed; start with `0-kickstart.md`. +- Commit as you go with descriptive messages; default to trunking on `main`. +- Use `act` to diagnose GitHub workflow issues locally. +- Keep unit tests parameterized; create new test files where possible; use 1:1 source-to-test naming. +- Leave TODO comments for missing functionality. +- Check `docs/todo/` before starting. +- One lambda per file; classes only serve as containers for related lambdas (see `.github/prompts/LAMBDA_PROMPT.md`). +- Route data access through DBAL; treat it as the trusted layer. +- Design for flexibility, modularity, and containerization. +- See `docs/RADIX_TO_MUI_MIGRATION.md` for UI migration guidance. + +## Critical Patterns + +### 1. API-First DBAL Development +When adding features to DBAL: +1. **Define in YAML first**: `api/schema/entities/*.yaml` and `api/schema/operations/*.yaml` +2. **Generate types**: `python tools/codegen/gen_types.py` (creates TS and C++ types) +3. **Implement adapters**: TypeScript (`ts/src/adapters/`) for speed, C++ (`cpp/src/adapters/`) for security +4. **Add conformance tests**: `common/contracts/*_tests.yaml` (runs on both implementations to guarantee parity) +5. Never add fields/operations directly in code without updating YAML source of truth + +**Why**: C++ daemon isolates credentials (users never see DB URLs), enforces row-level security, and protects against malicious queries. + +### 2. Generic Component Rendering +Instead of hardcoded components, use declarative config: +```tsx +// ❌ Wrong: Hardcoded + + +// ✅ Right: Declarative + +``` +See: `RenderComponent.tsx`, `declarative-component-renderer.ts` + +### 3. Package Seed Data Structure +Each package auto-loads on init: +``` +packages/{name}/ +├── seed/ +│ ├── metadata.json # Package info, exports, dependencies, minLevel +│ ├── components.json # Component definitions +│ ├── scripts/ # Lua scripts organized by function +│ └── index.ts # Exports packageSeed object +├── src/ # Optional React components +└── static_content/ # Assets (images, etc.) +``` +Loaded by `initializePackageSystem()` → `buildPackageRegistry()` → `exportAllPackagesForSeed()` + +### 3a. Multi-Source Package Repositories +Packages can come from multiple sources: +```typescript +import { createPackageSourceManager, LocalPackageSource, RemotePackageSource } from '@/lib/packages/package-glue' + +const manager = createPackageSourceManager({ + enableRemote: true, + remoteUrl: 'https://registry.metabuilder.dev/api/v1', + conflictResolution: 'priority' // or 'latest-version', 'local-first', 'remote-first' +}) + +const packages = await manager.fetchMergedIndex() +const pkg = await manager.loadPackage('dashboard') +``` +See: `docs/packages/package-sources.md`, `package-glue/sources/` + +### 4. Database Helpers Pattern +Always use `Database` class methods, never raw Prisma: +```typescript +// ✅ Right +const users = await Database.getUsers() +await Database.setSchemas(schemas) + +// ❌ Wrong +const users = await prisma.user.findMany() +``` +See: `src/lib/database.ts` (1200+ LOC utility wrapper) + +### 5. Lua Sandbox Execution +Lua scripts run in isolated sandbox without access to `os`, `io`, `require`: +```typescript +// Sandbox context provided in script +function validateEmail(email) + -- No file I/O, no system access, no external requires + return string.match(email, "^[^@]+@[^@]+$") ~= nil +end +``` +Always test scripts with `DeclarativeComponentRenderer.executeLuaScript()` + +## Code Conventions + +### UI Components & Styling + +**⚠️ CRITICAL: This project does NOT use Radix UI or Tailwind CSS** + +- ❌ **NEVER import from `@radix-ui/*`** - These dependencies have been removed +- ❌ **NEVER use Tailwind utility classes** in `className` props +- ✅ **ALWAYS use Material-UI** (`@mui/material`) for UI components +- ✅ **Use MUI's `sx` prop** for inline styles with theme access +- ✅ **Create `.module.scss` files** for component-specific custom styles +- ✅ **Use `@mui/icons-material`** for icons, not lucide-react or heroicons + +```tsx +// ❌ Wrong: Using Radix UI or Tailwind +import { Dialog } from '@radix-ui/react-dialog' + + +// ✅ Right: Using Material-UI +import { Dialog, Button } from '@mui/material' + +Content +``` + +**Component Mapping:** +- Radix Dialog → MUI Dialog +- Radix Select → MUI Select +- Radix Checkbox → MUI Checkbox +- Radix Switch → MUI Switch +- Tailwind classes → MUI `sx` prop or SCSS modules + +**See:** `UI_STANDARDS.md` and `docs/UI_MIGRATION.md` for complete reference + +### TypeScript/React +- One lambda per file; classes are containers for related lambdas. +- Keep files small and focused; split by responsibility when they grow. +- Use `@/` absolute paths +- Functional components with hooks; avoid class components +- Test files next to source with matching names: `utils.ts` + `utils.test.ts`, using parameterized `it.each()` + +### Tests +All functions need coverage with parameterized tests: +```typescript +// From schema-utils.test.ts: 63 tests for 14 functions +it.each([ + { input: 'case1', expected: 'result1' }, + { input: 'case2', expected: 'result2' }, +])('should handle $input', ({ input, expected }) => { + expect(myFunction(input)).toBe(expected) +}) +``` +Run `npm run test:coverage:report` to auto-generate coverage markdown. + +### Database +- Schema in `prisma/schema.prisma`, always run `npm run db:generate` after changes +- Hash passwords with SHA-512 (see `password-utils.ts`) +- Queries must include `where('tenantId', currentTenant.id)` for multi-tenancy + +### Styling +Material-UI with SASS; theme in `src/theme/mui-theme.ts` with light/dark mode support. Font families: IBM Plex Sans (body), Space Grotesk (headings), JetBrains Mono (code). Use MUI's `sx` prop for inline styles or create `.module.scss` files for custom component styles. + +## Development Checklist + +**Before implementing**: Check `docs/` and `docs/todo/`, and review `.github/prompts/0-kickstart.md` for current workflow rules. + +**During implementation**: +1. Define database schema changes first (Prisma) +2. Add seed data to `src/seed-data/` or package `/seed/` +3. Use generic renderers (`RenderComponent`) not hardcoded JSX +4. Add Lua scripts in `src/lib/lua-snippets.ts` or package `/seed/scripts/` +5. Keep one lambda per file and split as needed +6. Add parameterized tests in `.test.ts` files with matching names + +**Before commit**: +- `npm run lint:fix` (fixes ESLint issues) +- `npm test -- --run` (all tests pass) +- `npm run test:coverage:report` (verify new functions have tests) +- `npm run test:e2e` (critical workflows still work) +- Use `npm run act:diagnose` or `npm run act` when investigating CI/workflow failures +- Commit with a descriptive message on `main` unless a PR workflow is explicitly required + +## Multi-Tenant Safety + +Every query must filter by tenant: +```typescript +// ❌ Never +const data = await Database.getData() + +// ✅ Always +const data = await Database.getData({ tenantId: user.tenantId }) +``` + +Permission checks cascade from lowest level: +```typescript +if (user.level >= 3) { // Admin and above + showAdminPanel() +} +``` + +## DBAL-Specific Guidance + +**TypeScript DBAL**: Fast iteration, development use. Located in `dbal/ts/src/`. +**C++ DBAL Daemon**: Production security, credential protection. Located in `dbal/production/src/`. +**Conformance Tests**: Guarantee both implementations behave identically. Update `common/contracts/` when changing YAML schemas. + +If fixing a DBAL bug: +1. Verify the bug exists in YAML schema definition +2. Reproduce in TypeScript implementation first (faster feedback loop) +3. Apply fix to both TS and C++ adapters +4. Add/update conformance test in `common/contracts/` +5. Verify both implementations pass test: `python tools/conformance/run_all.py` + +## Common Mistakes + +❌ **Hardcoding values in TSX** → Move to database or YAML config +❌ **Forgetting tenantId filter** → Breaks multi-tenancy +❌ **Adding fields without Prisma generate** → Type errors in DB helper +❌ **Plain JS loops over Fengari tables** → Use Lua, not TS, for Lua data +❌ **Multiple lambdas per file** → Split into single-lambda files and wrap with a class only when needed +❌ **New function without test** → `npm run test:check-functions` will fail +❌ **Missing TODO for unfinished behavior** → Leave a TODO comment where functionality is pending + +## Key Files + +- **Architecture**: `docs/architecture/5-level-system.md` (permissions), `docs/architecture/packages.md` (packages) +- **Components**: `src/components/RenderComponent.tsx` (generic renderer), `src/lib/declarative-component-renderer.ts` +- **Database**: `src/lib/database.ts` (all DB operations), `prisma/schema.prisma` (schema) +- **Packages**: `src/lib/package-loader.ts` (initialization), `packages/*/seed/` (definitions) +- **Tests**: `src/lib/schema-utils.test.ts` (parameterized pattern), `FUNCTION_TEST_COVERAGE.md` (auto-generated report) +- **DBAL**: `dbal/docs/AGENTS.md` (detailed DBAL agent guide), `api/schema/` (YAML contracts) + +## Questions to Ask + +1. Is this hardcoded value better in database? +2. Could a generic component render this instead of custom TSX? +3. Does this query filter by tenantId? +4. Could Lua handle this without code changes? +5. Is this one lambda per file (and test file name matches)? +6. Does this function have a parameterized test? +7. Is this DBAL change reflected in YAML schema first? diff --git a/.github/prompts/deploy/6-deploy-ci-local.prompt.md b/.github/prompts/deploy/6-deploy-ci-local.prompt.md index 2d2236003..c13acd47e 100644 --- a/.github/prompts/deploy/6-deploy-ci-local.prompt.md +++ b/.github/prompts/deploy/6-deploy-ci-local.prompt.md @@ -1,17 +1,17 @@ -# Run GitHub Actions Locally - -Run from `frontends/nextjs/`. - -Run the full CI pipeline locally using act to validate changes before pushing. - -```bash -npm run act -``` - -If specific jobs fail, debug with: -- `npm run act:lint` - ESLint only -- `npm run act:typecheck` - TypeScript validation -- `npm run act:build` - Production build -- `npm run act:e2e` - End-to-end tests - -Use `npm run act:diagnose` to check setup issues without Docker. +# Run GitHub Actions Locally + +Run from `frontends/nextjs/`. + +Run the full CI pipeline locally using act to validate changes before pushing. + +```bash +npm run act +``` + +If specific jobs fail, debug with: +- `npm run act:lint` - ESLint only +- `npm run act:typecheck` - TypeScript validation +- `npm run act:build` - Production build +- `npm run act:e2e` - End-to-end tests + +Use `npm run act:diagnose` to check setup issues without Docker. diff --git a/.github/prompts/deploy/6-deploy-production.prompt.md b/.github/prompts/deploy/6-deploy-production.prompt.md index 40a705101..6864f65f4 100644 --- a/.github/prompts/deploy/6-deploy-production.prompt.md +++ b/.github/prompts/deploy/6-deploy-production.prompt.md @@ -1,35 +1,35 @@ -# Deploy Application - -Deploy MetaBuilder to production: - -## Pre-Deployment Checks (from `frontends/nextjs/`) -```bash -npm run act # Full CI locally -npm run build # Verify build succeeds -npm run typecheck # No type errors -``` - -## Docker Deployment (from repo root) -```bash -# Development -docker-compose -f deployment/docker-compose.development.yml up - -# Production -docker-compose -f deployment/docker-compose.production.yml up -d -``` - -## Database Migration (from `frontends/nextjs/`) -```bash -npm run db:migrate # Apply migrations -``` - -## Environment Variables -Required in production: -- `DATABASE_URL` - Database connection string -- `NODE_ENV=production` - -## Post-Deployment -1. Verify health endpoints -2. Check logs for errors -3. Test critical user flows -4. Monitor tenant isolation working correctly +# Deploy Application + +Deploy MetaBuilder to production: + +## Pre-Deployment Checks (from `frontends/nextjs/`) +```bash +npm run act # Full CI locally +npm run build # Verify build succeeds +npm run typecheck # No type errors +``` + +## Docker Deployment (from repo root) +```bash +# Development +docker-compose -f deployment/docker-compose.development.yml up + +# Production +docker-compose -f deployment/docker-compose.production.yml up -d +``` + +## Database Migration (from `frontends/nextjs/`) +```bash +npm run db:migrate # Apply migrations +``` + +## Environment Variables +Required in production: +- `DATABASE_URL` - Database connection string +- `NODE_ENV=production` + +## Post-Deployment +1. Verify health endpoints +2. Check logs for errors +3. Test critical user flows +4. Monitor tenant isolation working correctly diff --git a/.github/prompts/implement/backend/3-impl-database.prompt.md b/.github/prompts/implement/backend/3-impl-database.prompt.md index d7f77e069..47badbb98 100644 --- a/.github/prompts/implement/backend/3-impl-database.prompt.md +++ b/.github/prompts/implement/backend/3-impl-database.prompt.md @@ -1,22 +1,22 @@ -# Database Query Pattern - -Always use the `Database` class wrapper, never raw Prisma: - -Run app commands from `frontends/nextjs/`. - -```typescript -// ✅ Correct - with tenant isolation -const users = await Database.getUsers({ tenantId: user.tenantId }) -await Database.setSchemas(schemas, { tenantId }) - -// ❌ Wrong - raw Prisma, no tenant filter -const users = await prisma.user.findMany() -``` - -After schema changes in `prisma/schema.prisma`: -```bash -npm run db:generate # Regenerate Prisma client -npm run db:push # Push to database -``` - -Key file: `frontends/nextjs/src/lib/database.ts` +# Database Query Pattern + +Always use the `Database` class wrapper, never raw Prisma: + +Run app commands from `frontends/nextjs/`. + +```typescript +// ✅ Correct - with tenant isolation +const users = await Database.getUsers({ tenantId: user.tenantId }) +await Database.setSchemas(schemas, { tenantId }) + +// ❌ Wrong - raw Prisma, no tenant filter +const users = await prisma.user.findMany() +``` + +After schema changes in `prisma/schema.prisma`: +```bash +npm run db:generate # Regenerate Prisma client +npm run db:push # Push to database +``` + +Key file: `frontends/nextjs/src/lib/database.ts` diff --git a/.github/prompts/implement/backend/3-impl-dbal-entity.prompt.md b/.github/prompts/implement/backend/3-impl-dbal-entity.prompt.md index 0a4b48675..4ad455dcb 100644 --- a/.github/prompts/implement/backend/3-impl-dbal-entity.prompt.md +++ b/.github/prompts/implement/backend/3-impl-dbal-entity.prompt.md @@ -1,26 +1,26 @@ -# Add DBAL Entity - -Run DBAL commands from `dbal/`. - -Add a new entity to the DBAL following the API-first approach: - -1. **Define entity** in `dbal/shared/api/schema/entities/{name}.yaml`: -```yaml -entity: EntityName -version: "1.0" -fields: - id: { type: uuid, primary: true, generated: true } - # Add fields... -``` - -2. **Define operations** in `dbal/shared/api/schema/operations/{name}.ops.yaml` - -3. **Generate types**: `python tools/codegen/gen_types.py` - -4. **Implement adapters** in both: - - `dbal/development/src/adapters/` - - `dbal/production/src/adapters/` - -5. **Add conformance tests** in `dbal/shared/common/contracts/{name}_tests.yaml` - -6. **Verify**: `python tools/conformance/run_all.py` +# Add DBAL Entity + +Run DBAL commands from `dbal/`. + +Add a new entity to the DBAL following the API-first approach: + +1. **Define entity** in `dbal/shared/api/schema/entities/{name}.yaml`: +```yaml +entity: EntityName +version: "1.0" +fields: + id: { type: uuid, primary: true, generated: true } + # Add fields... +``` + +2. **Define operations** in `dbal/shared/api/schema/operations/{name}.ops.yaml` + +3. **Generate types**: `python tools/codegen/gen_types.py` + +4. **Implement adapters** in both: + - `dbal/development/src/adapters/` + - `dbal/production/src/adapters/` + +5. **Add conformance tests** in `dbal/shared/common/contracts/{name}_tests.yaml` + +6. **Verify**: `python tools/conformance/run_all.py` diff --git a/.github/prompts/implement/backend/3-impl-lua-script.prompt.md b/.github/prompts/implement/backend/3-impl-lua-script.prompt.md index b8d97e12c..8cffccf7e 100644 --- a/.github/prompts/implement/backend/3-impl-lua-script.prompt.md +++ b/.github/prompts/implement/backend/3-impl-lua-script.prompt.md @@ -1,36 +1,36 @@ -# Write Lua Business Logic - -Add business logic as a sandboxed Lua script: - -## Create Script -Location: `packages/{pkg}/seed/scripts/` or `src/lib/lua-snippets.ts` - -```lua --- Sandbox restrictions: NO os, io, require, loadfile -function validateInput(value) - if not value or value == "" then - return false, "Value required" - end - return true, nil -end -``` - -## Register Script -```typescript -renderer.registerLuaScript('validate_input', { - code: luaCode, - parameters: [{ name: 'value', type: 'string' }], - returnType: 'boolean' -}) -``` - -## Execute Script -```typescript -const result = await renderer.executeLuaScript('validate_input', [userInput]) -``` - -## When to Use Lua -- Validation rules -- Data transformation -- Conditional rendering logic -- Business rules that change frequently +# Write Lua Business Logic + +Add business logic as a sandboxed Lua script: + +## Create Script +Location: `packages/{pkg}/seed/scripts/` or `src/lib/lua-snippets.ts` + +```lua +-- Sandbox restrictions: NO os, io, require, loadfile +function validateInput(value) + if not value or value == "" then + return false, "Value required" + end + return true, nil +end +``` + +## Register Script +```typescript +renderer.registerLuaScript('validate_input', { + code: luaCode, + parameters: [{ name: 'value', type: 'string' }], + returnType: 'boolean' +}) +``` + +## Execute Script +```typescript +const result = await renderer.executeLuaScript('validate_input', [userInput]) +``` + +## When to Use Lua +- Validation rules +- Data transformation +- Conditional rendering logic +- Business rules that change frequently diff --git a/.github/prompts/implement/backend/3-impl-migration.prompt.md b/.github/prompts/implement/backend/3-impl-migration.prompt.md index 99248bd75..12fdb8ed0 100644 --- a/.github/prompts/implement/backend/3-impl-migration.prompt.md +++ b/.github/prompts/implement/backend/3-impl-migration.prompt.md @@ -1,39 +1,39 @@ -# Add Database Migration - -Add or modify database schema: - -Run app commands from `frontends/nextjs/` unless a step says otherwise. - -## 1. Update Schema -Edit `prisma/schema.prisma`: -```prisma -model NewEntity { - id String @id @default(cuid()) - name String - tenantId String // Required for multi-tenancy - tenant Tenant @relation(fields: [tenantId], references: [id]) - createdAt BigInt -} -``` - -## 2. Generate & Apply -```bash -npm run db:generate # Update Prisma client -npm run db:push # Push to dev database -# OR for production: -npx prisma migrate dev --name describe_change -npm run db:migrate # Apply in production -``` - -## 3. Add Database Wrapper Methods -In `src/lib/database.ts`: -```typescript -static async getNewEntities(filter: { tenantId: string }) { - return prisma.newEntity.findMany({ - where: { tenantId: filter.tenantId } - }) -} -``` - -## 4. Update DBAL (if applicable) -Add entity to `dbal/shared/api/schema/entities/` +# Add Database Migration + +Add or modify database schema: + +Run app commands from `frontends/nextjs/` unless a step says otherwise. + +## 1. Update Schema +Edit `prisma/schema.prisma`: +```prisma +model NewEntity { + id String @id @default(cuid()) + name String + tenantId String // Required for multi-tenancy + tenant Tenant @relation(fields: [tenantId], references: [id]) + createdAt BigInt +} +``` + +## 2. Generate & Apply +```bash +npm run db:generate # Update Prisma client +npm run db:push # Push to dev database +# OR for production: +npx prisma migrate dev --name describe_change +npm run db:migrate # Apply in production +``` + +## 3. Add Database Wrapper Methods +In `src/lib/database.ts`: +```typescript +static async getNewEntities(filter: { tenantId: string }) { + return prisma.newEntity.findMany({ + where: { tenantId: filter.tenantId } + }) +} +``` + +## 4. Update DBAL (if applicable) +Add entity to `dbal/shared/api/schema/entities/` diff --git a/.github/prompts/implement/frontend/3-impl-component.prompt.md b/.github/prompts/implement/frontend/3-impl-component.prompt.md index 4682eccd5..d40f93b16 100644 --- a/.github/prompts/implement/frontend/3-impl-component.prompt.md +++ b/.github/prompts/implement/frontend/3-impl-component.prompt.md @@ -1,27 +1,27 @@ -# Add Declarative Component - -Add a new component using the declarative pattern (not hardcoded TSX): - -1. **Define in package** `packages/{pkg}/seed/components.json`: -```json -{ - "type": "MyComponent", - "category": "ui", - "label": "My Component", - "props": [ - { "name": "title", "type": "string", "required": true } - ], - "config": { - "layout": "vertical", - "styling": { "className": "myComponentRoot" } - } -} -``` - -Note: `styling.className` should reference a real CSS class (SCSS/modules), not Tailwind utility classes. - -2. **Register** via `DeclarativeComponentRenderer.registerComponentConfig()` - -3. **Render** using `` - -Keep components under 150 LOC. Use composition for complex UIs. +# Add Declarative Component + +Add a new component using the declarative pattern (not hardcoded TSX): + +1. **Define in package** `packages/{pkg}/seed/components.json`: +```json +{ + "type": "MyComponent", + "category": "ui", + "label": "My Component", + "props": [ + { "name": "title", "type": "string", "required": true } + ], + "config": { + "layout": "vertical", + "styling": { "className": "myComponentRoot" } + } +} +``` + +Note: `styling.className` should reference a real CSS class (SCSS/modules), not Tailwind utility classes. + +2. **Register** via `DeclarativeComponentRenderer.registerComponentConfig()` + +3. **Render** using `` + +Keep components under 150 LOC. Use composition for complex UIs. diff --git a/.github/prompts/implement/frontend/3-impl-feature.prompt.md b/.github/prompts/implement/frontend/3-impl-feature.prompt.md index 81009aa96..a96d64d5a 100644 --- a/.github/prompts/implement/frontend/3-impl-feature.prompt.md +++ b/.github/prompts/implement/frontend/3-impl-feature.prompt.md @@ -1,32 +1,32 @@ -# Implement Feature - -Implement following MetaBuilder conventions: - -Run app commands from `frontends/nextjs/` unless a step says otherwise. - -## Implementation Order -1. **Schema first**: Update `prisma/schema.prisma` if needed - ```bash - npm run db:generate && npm run db:push - ``` - -2. **DBAL contracts**: If new entity/operation, update YAML in `dbal/shared/api/schema/` - -3. **Database layer**: Add methods to `Database` class in `src/lib/database.ts` - -4. **Business logic**: - - Simple validation → Lua script - - Complex logic → TypeScript in `src/lib/` - -5. **UI components**: - - Declarative → `packages/*/seed/components.json` - - React → `src/components/` (< 150 LOC) - -6. **Tests**: Parameterized tests next to source files - -## Checklist -- [ ] tenantId filtering on all queries -- [ ] Permission level check -- [ ] Component under 150 LOC -- [ ] No hardcoded values (use DB/config) -- [ ] Tests with `it.each()` pattern +# Implement Feature + +Implement following MetaBuilder conventions: + +Run app commands from `frontends/nextjs/` unless a step says otherwise. + +## Implementation Order +1. **Schema first**: Update `prisma/schema.prisma` if needed + ```bash + npm run db:generate && npm run db:push + ``` + +2. **DBAL contracts**: If new entity/operation, update YAML in `dbal/shared/api/schema/` + +3. **Database layer**: Add methods to `Database` class in `src/lib/database.ts` + +4. **Business logic**: + - Simple validation → Lua script + - Complex logic → TypeScript in `src/lib/` + +5. **UI components**: + - Declarative → `packages/*/seed/components.json` + - React → `src/components/` (< 150 LOC) + +6. **Tests**: Parameterized tests next to source files + +## Checklist +- [ ] tenantId filtering on all queries +- [ ] Permission level check +- [ ] Component under 150 LOC +- [ ] No hardcoded values (use DB/config) +- [ ] Tests with `it.each()` pattern diff --git a/.github/prompts/implement/frontend/3-impl-package.prompt.md b/.github/prompts/implement/frontend/3-impl-package.prompt.md index 9bbcb6c09..2ddb6be86 100644 --- a/.github/prompts/implement/frontend/3-impl-package.prompt.md +++ b/.github/prompts/implement/frontend/3-impl-package.prompt.md @@ -1,28 +1,28 @@ -# Create New Package - -Create a new MetaBuilder package with the standard structure: - -``` -packages/{name}/ -├── seed/ -│ ├── metadata.json # Package info, version, dependencies -│ ├── components.json # Component definitions -│ └── scripts/ # Lua scripts (optional) -├── static_content/ # Assets (optional) -└── tests/ - └── README.md -``` - -Required metadata.json format: -```json -{ - "packageId": "{name}", - "name": "Display Name", - "version": "1.0.0", - "description": "Package description", - "author": "MetaBuilder", - "category": "ui", - "dependencies": [], - "exports": { "components": [] } -} -``` +# Create New Package + +Create a new MetaBuilder package with the standard structure: + +``` +packages/{name}/ +├── seed/ +│ ├── metadata.json # Package info, version, dependencies +│ ├── components.json # Component definitions +│ └── scripts/ # Lua scripts (optional) +├── static_content/ # Assets (optional) +└── tests/ + └── README.md +``` + +Required metadata.json format: +```json +{ + "packageId": "{name}", + "name": "Display Name", + "version": "1.0.0", + "description": "Package description", + "author": "MetaBuilder", + "category": "ui", + "dependencies": [], + "exports": { "components": [] } +} +``` diff --git a/.github/prompts/maintain/7-maintain-debug.prompt.md b/.github/prompts/maintain/7-maintain-debug.prompt.md index b052437f8..3848348df 100644 --- a/.github/prompts/maintain/7-maintain-debug.prompt.md +++ b/.github/prompts/maintain/7-maintain-debug.prompt.md @@ -1,44 +1,44 @@ -# Debug Issue - -Systematic debugging approach for MetaBuilder: - -Run app commands from `frontends/nextjs/`. Run DBAL conformance from `dbal/`. - -## 1. Identify Layer -- **UI**: Check browser console, React DevTools -- **API/Data**: Check `Database` class calls -- **DBAL**: Check YAML schema matches implementation -- **Lua**: Check sandbox execution logs - -## 2. Common Issues - -### "Cannot read property" in component -→ Check if data query includes `tenantId` - -### Type errors after schema change -```bash -npm run db:generate # Regenerate Prisma types -``` - -### DBAL TypeScript/C++ divergence -```bash -python tools/conformance/run_all.py # Find which test fails -``` - -### Lua script fails silently -→ Check for forbidden APIs: `os`, `io`, `require`, `loadfile` - -## 3. Logging -```typescript -// Database queries -console.log('[DB]', query, { tenantId }) - -// Lua execution -const result = await renderer.executeLuaScript(id, params) -console.log('[Lua]', { result, logs: result.logs }) -``` - -## 4. Test in Isolation -```bash -npm run test:unit -- path/to/test.ts -``` +# Debug Issue + +Systematic debugging approach for MetaBuilder: + +Run app commands from `frontends/nextjs/`. Run DBAL conformance from `dbal/`. + +## 1. Identify Layer +- **UI**: Check browser console, React DevTools +- **API/Data**: Check `Database` class calls +- **DBAL**: Check YAML schema matches implementation +- **Lua**: Check sandbox execution logs + +## 2. Common Issues + +### "Cannot read property" in component +→ Check if data query includes `tenantId` + +### Type errors after schema change +```bash +npm run db:generate # Regenerate Prisma types +``` + +### DBAL TypeScript/C++ divergence +```bash +python tools/conformance/run_all.py # Find which test fails +``` + +### Lua script fails silently +→ Check for forbidden APIs: `os`, `io`, `require`, `loadfile` + +## 3. Logging +```typescript +// Database queries +console.log('[DB]', query, { tenantId }) + +// Lua execution +const result = await renderer.executeLuaScript(id, params) +console.log('[Lua]', { result, logs: result.logs }) +``` + +## 4. Test in Isolation +```bash +npm run test:unit -- path/to/test.ts +``` diff --git a/.github/prompts/maintain/7-maintain-performance.prompt.md b/.github/prompts/maintain/7-maintain-performance.prompt.md index 4c1be2077..c027a2de4 100644 --- a/.github/prompts/maintain/7-maintain-performance.prompt.md +++ b/.github/prompts/maintain/7-maintain-performance.prompt.md @@ -1,46 +1,46 @@ -# Performance Optimization - -Optimize MetaBuilder performance: - -Run performance scripts from `frontends/nextjs/` after `npm run build` (requires `tsx` via `npx`). - -## Identify Bottlenecks -```bash -npx tsx ../../tools/analyze-render-performance.ts -npx tsx ../../tools/analyze-bundle-size.ts -npx tsx ../../tools/check-performance-budget.ts -``` - -## Common Optimizations - -### 1. Database Queries -```typescript -// ❌ N+1 query -for (const user of users) { - const tenant = await Database.getTenant(user.tenantId) -} - -// ✅ Batch query -const users = await Database.getUsersWithTenants({ tenantId }) -``` - -### 2. Component Rendering -```tsx -// ❌ Re-renders on every parent render -function List({ items }) { - return items.map(item => ) -} - -// ✅ Memoized -const MemoizedItem = React.memo(Item) -function List({ items }) { - return items.map(item => ) -} -``` - -### 3. Bundle Size -- Use dynamic imports for large components -- Check `docs/reports/size-limits-report.json` - -### 4. Lua Script Caching -Scripts are compiled once - avoid registering repeatedly +# Performance Optimization + +Optimize MetaBuilder performance: + +Run performance scripts from `frontends/nextjs/` after `npm run build` (requires `tsx` via `npx`). + +## Identify Bottlenecks +```bash +npx tsx ../../tools/analyze-render-performance.ts +npx tsx ../../tools/analyze-bundle-size.ts +npx tsx ../../tools/check-performance-budget.ts +``` + +## Common Optimizations + +### 1. Database Queries +```typescript +// ❌ N+1 query +for (const user of users) { + const tenant = await Database.getTenant(user.tenantId) +} + +// ✅ Batch query +const users = await Database.getUsersWithTenants({ tenantId }) +``` + +### 2. Component Rendering +```tsx +// ❌ Re-renders on every parent render +function List({ items }) { + return items.map(item => ) +} + +// ✅ Memoized +const MemoizedItem = React.memo(Item) +function List({ items }) { + return items.map(item => ) +} +``` + +### 3. Bundle Size +- Use dynamic imports for large components +- Check `docs/reports/size-limits-report.json` + +### 4. Lua Script Caching +Scripts are compiled once - avoid registering repeatedly diff --git a/.github/prompts/maintain/7-maintain-refactor.prompt.md b/.github/prompts/maintain/7-maintain-refactor.prompt.md index 8809a073a..b09ae4cc1 100644 --- a/.github/prompts/maintain/7-maintain-refactor.prompt.md +++ b/.github/prompts/maintain/7-maintain-refactor.prompt.md @@ -1,54 +1,54 @@ -# Refactor Large Component - -Break down a component exceeding 150 LOC: - -## 1. Identify Split Points -- Separate data fetching from rendering -- Extract repeated patterns into sub-components -- Move business logic to Lua or utility functions - -## 2. Refactoring Patterns - -### Extract Child Components -```tsx -// Before: 200 LOC monolith -function BigComponent() { /* everything */ } - -// After: Composed -function BigComponent() { - return ( - -
- -