diff --git a/README.ar.md b/README.ar.md index 32fb0df..6e3cac2 100644 --- a/README.ar.md +++ b/README.ar.md @@ -65,16 +65,30 @@ --- -## 🚀 البدء السريع +## 🚀 التثبيت والبدء السريع -### 1. المعالج التفاعلي والحقن المباشر +اختر طريقة التثبيت المناسبة لمشروعك: +### الخيار (أ): عبر TidyFactor CLI الرسمي (الموصى به) +التثبيت الفوري دون الحاجة لتثبيت الأداة عالمياً في بيئة عملك النشطة: ```bash -# المعالج التفاعلي لإنشاء منصة ساس جديدة معزولة -npx @tidyfactor/cli-next +npx @tidyfactor/cli add next +``` +*أو في حال كانت الأداة مثبتة لديك عالمياً (`npm i -g @tidyfactor/cli`):* +```bash +tidyfactor add next +``` -# أو حقن المهارة مباشرة داخل مشروع Next.js قائم -npx @tidyfactor/cli-next add-skill +### الخيار (ب): عبر معيار مهارات الوكلاء المفتوح (skills.sh) +التثبيت العالمي المتوافق مع كافة بيئات الوكلاء ومحررات الذكاء الاصطناعي (Antigravity, Cursor, Claude Code, Windsurf, Codex): +```bash +npx skills add tidyfactor/next +``` + +### الخيار (ج): التثبيت المباشر الفردي عبر NPM +تشغيل مثبت المهارة المستقل مباشرة مع تجاوز الذاكرة المخبأة وضمان أحدث إصدار: +```bash +npx @tidyfactor/next@latest ``` ### 2. مسارات التثبيت اليدوي حسب بيئة الوكيل الذكي diff --git a/README.md b/README.md index 146232e..913d475 100644 --- a/README.md +++ b/README.md @@ -65,16 +65,30 @@ Most Next.js agent skills teach your AI how to write idiomatic code — App Rout --- -## 🚀 Quick Start +## 🚀 Installation & Quick Start -### 1. Interactive Project Wizard & Direct Injection +Choose your preferred installation method: +### Option A: Via TidyFactor CLI (Recommended) +Install directly using the official ecosystem package runner into your active workspace: ```bash -# Interactive project wizard — scaffolds a new multi-tenant SaaS project -npx @tidyfactor/cli-next +npx @tidyfactor/cli add next +``` +*Or if you have the CLI installed globally (`npm i -g @tidyfactor/cli`):* +```bash +tidyfactor add next +``` -# Or inject the skill directly into an existing Next.js repository -npx @tidyfactor/cli-next add-skill +### Option B: Via Open Agent Skills Ecosystem (skills.sh / Vercel Labs) +Install using the universal multi-agent standard across all supported IDEs (Cursor, Antigravity, Claude Code, Windsurf, Trae, Codex): +```bash +npx skills add tidyfactor/next +``` + +### Option C: Standalone Zero-Dependency Runner (NPM Direct) +Run the dedicated skill installer directly with automatic cache invalidation: +```bash +npx @tidyfactor/next@latest ``` ### 2. Workspace Installation per AI Agent diff --git a/dist/tidyfactor-next.skill b/dist/tidyfactor-next.skill deleted file mode 100644 index 04e0b0a..0000000 Binary files a/dist/tidyfactor-next.skill and /dev/null differ diff --git a/dist/tidyfactor-next/.tidyfactor b/dist/tidyfactor-next/.tidyfactor deleted file mode 100644 index 0acb3c9..0000000 --- a/dist/tidyfactor-next/.tidyfactor +++ /dev/null @@ -1,59 +0,0 @@ -{ - "ecosystem": "tidyfactor", - "track": "next", - "name": "tidyfactor-next", - "version": "1.4.0", - "npmPackage": "@alwkala/tidyfactor-next", - "github": "https://github.com/TidyFactor/Next", - "skillFile": "../tidyfactor-next-v1.3.0.skill", - "category": "saas-architecture", - "type": "multi-tenant-nextjs", - "outputs": [ - "app/", - "components/", - "lib/", - "supabase/", - "ARCHITECTURE.md" - ], - "pillars": [ - "foundation", - "security", - "data", - "application", - "quality", - "devops", - "operations" - ], - "commands": [ - "brief", - "init", - "tenant", - "rls", - "auth", - "data", - "storage", - "api", - "app", - "test", - "observe", - "deploy", - "perf", - "incident", - "audit" - ], - "visionRef": "../TidyFactor-VISION.md", - "sibling": [ - "tidyfactor-design", - "tidyfactor-cinematic", - "tidyfactor-marketing", - "tidyfactor-html", - "tidyfactor-php", - "tidyfactor-js", - "tidyfactor-htmx", - "tidyfactor-styler" - ], - "commercialPartner": "alwkala", - "website": "https://tidyfactor.com", - "docs": "https://tidyfactor.com/documentation", - "license": "Apache-2.0" -} diff --git a/dist/tidyfactor-next/AGENTS.md b/dist/tidyfactor-next/AGENTS.md deleted file mode 100644 index 045fada..0000000 --- a/dist/tidyfactor-next/AGENTS.md +++ /dev/null @@ -1,51 +0,0 @@ -# AGENTS.md — TidyFactor Next.js Architecture & Dev-Perf Engine (`tidyfactor-next`) - -Production-grade **Multi-Tenant SaaS Architecture & Development Resource Optimization Engine** following the strict **TidyFactor Skill Methodology**. Enforces locked tenant isolation on Next.js 16 and Supabase with PostgreSQL RLS as the non-negotiable security boundary, paired with an evidence-based development performance engine. - ---- - -## ⚡ Skill & 15-Stage SaaS Command Dispatchers - -This project exposes an Agentic Skill under `SKILL.md` (and `.claude-skill/SKILL.md`). The following 15 command modules covering the complete SaaS engineering lifecycle are fully implemented: - -| Stage | Command | Purpose | Reference Spec | Status | -|---|---|---|---|:---:| -| **0. Discovery** | `brief` | Pre-flight CDL SaaS discovery & stack selection | `references/commands/brief.md` | ✅ **Built** | -| **1. Foundation** | `init` | Scaffold new multi-tenant project & generate `ARCHITECTURE.md` | `references/commands/init.md` | ✅ **Built** | -| **1. Foundation** | `tenant` | Edge tenant resolution, context propagation, lifecycle | `references/commands/tenant.md` | ✅ **Built** | -| **2. Security** | `rls` | RLS policy authoring, 4-policy pattern, leak diagnosis | `references/commands/rls.md` | ✅ **Built** | -| **2. Security** | `auth` | Supabase Auth, custom JWT claims hook, RBAC/ABAC | `references/commands/auth.md` | ✅ **Built** | -| **3. Data** | `data` | Schema, migrations, transactions, constraints | `references/commands/data.md` | ✅ **Built** | -| **3. Data** | `storage` | Tenant-scoped buckets, signed URLs, storage RLS | `references/commands/storage.md` | ✅ **Built** | -| **4. Application** | `api` | Route handlers, server actions, API contracts | `references/commands/api.md` | ✅ **Built** | -| **4. Application** | `app` | App Router, React 19, RSC boundaries, Suspense | `references/commands/app.md` | ✅ **Built** | -| **5. Quality** | `test` | Unit, integration, RLS coverage, E2E security tests | `references/commands/test.md` | ✅ **Built** | -| **5. Quality** | `observe` | Tracing, tenant-scoped audit logs, health checks | `references/commands/observe.md` | ✅ **Built** | -| **6. DevOps** | `deploy` | CI/CD, environments, rollback, point-in-time backups | `references/commands/deploy.md` | ✅ **Built** | -| **6. DevOps / Perf** | `perf` | Dev & runtime performance audit, bottleneck diagnosis, safe perf | `references/commands/perf.md` | ✅ **Built** | -| **7. Operations** | `incident` | Disaster recovery, tenant leak remediation runbooks | `references/commands/incident.md` | ✅ **Built** | -| **7. Operations** | `audit` | Full-stack multi-tenant architecture & compliance audit | `references/commands/audit.md` | ✅ **Built** | - ---- - -## 🛠️ CLI Execution Modes - -- **Interactive Setup Wizard** (`npx @tidyfactor/cli-next`): Launches interactive terminal wizard to scaffold projects, select query layers (Supabase JS, Drizzle, Prisma), configure auth providers, and establish tenant resolution strategies. -- **Skill Injection Mode** (`npx @tidyfactor/cli-next add-skill`): Injects `.agents/skills/tidyfactor-next/` directly into any existing Next.js repository. -- **AI Agent Execution**: Antigravity, Claude Code, Cursor, Codex, and Windsurf execute slash commands directly via `references/commands/.md`. - ---- - -## 🛡️ Critical Architecture & SaaS Guardrails (Non-Negotiable) - -1. **Locked Tenant Isolation**: - - Shared database schema with `tenant_id uuid NOT NULL REFERENCES tenants(id)`. - - PostgreSQL Row Level Security (RLS) is the security boundary—never application-layer `WHERE` filters alone. -2. **`service_role` Key Isolation**: - - Never exposed to client bundles or browser-callable routes. Used exclusively in server-only contexts after explicit tenant re-verification. -3. **Fail-Closed Edge Resolution**: - - Middleware resolves tenant identity once at the network edge. Any resolution failure fails closed (404/403)—never falling back to an unscoped default tenant. -4. **Development Performance Rule (`audit ≠ optimize`)**: - - Diagnostic evidence required before modifying any file. Only 🟢 Green-tier optimizations apply automatically. 🟡 Yellow optimizations require evidence and developer approval. -5. **SaaS Safety Boundary**: - - Performance optimization must NEVER weaken tenant isolation, RLS, authentication, or authorization contracts. diff --git a/dist/tidyfactor-next/CHANGELOG.md b/dist/tidyfactor-next/CHANGELOG.md deleted file mode 100644 index 87db924..0000000 --- a/dist/tidyfactor-next/CHANGELOG.md +++ /dev/null @@ -1,72 +0,0 @@ -# Changelog — TidyFactor Next.js - -All notable changes to the **[@tidyfactor/next](https://www.npmjs.com/package/@tidyfactor/next)** package will be documented in this file. - -## [1.4.0] - 2026-08-29 - -### Added - Global Multi-Tier & Multi-Language Documentation Architecture -- **Rule 13 Implementation**: Two-tier documentation separation between Canonical Technical Documentation (`README.md` SSOT) and First-Class Market Localizations. -- **Universal Multi-Language Switcher**: Standardized 8-language switcher navigation bar across all documentation files (`EN`, `AR`, `FA`, `ES`, `PT`, `ZH`, `DE`, `FR`). -- **First-Class Localized Developer Adoption Guides**: `README.es.md`, `README.pt.md`, `README.fa.md`, `README.zh.md`, `README.de.md`, `README.fr.md`. -- **Automated Validation & Packaging**: Updated `tools/build-skill.js` and `tools/validate_skill.py`. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [1.3.0] - 2026-08-27 - -### Added -- **8-Tier Prioritized React 19 & Next.js 16 Runtime Performance Catalog**: Added `references/memory/react-perf-rules.md` encapsulating 40+ production rules learned from Vercel Engineering (`react-best-practices`): - - **Tier 1 (CRITICAL — Waterfalls)**: Synchronous guard evaluation before `await`, deferred `await`, `Promise.all` / dependency parallelization, route handler early promise execution, `` streaming boundaries. - - **Tier 2 (CRITICAL — Bundle Size)**: Barrel import elimination, `next/dynamic` for heavy client modules, deferred 3rd-party scripts past hydration, intent-based chunk preloading. - - **Tier 3 (HIGH — Server Performance)**: `React.cache()` request deduplication, Next.js 16 `after()` for non-blocking telemetry and audit logs, minimal RSC props serialization DTOs, Server Action auth parity. - - **Tier 4 (MEDIUM-HIGH — Client Data Fetching)**: SWR / TanStack request deduplication, passive scroll event listeners. - - **Tier 5 (MEDIUM — Re-render Optimization)**: Pure derived state in render phase (zero redundant `useEffect` mirrors), primitive `useMemo` prevention, lazy `useState` initializers, `startTransition` / `useDeferredValue`. - - **Tier 6 (MEDIUM — Rendering Performance)**: CSS `content-visibility: auto`, static JSX hoisting, explicit boolean conditions. - - **Tier 7 (LOW-MEDIUM — JavaScript Performance)**: Layout thrashing batching, `Set`/`Map` $O(1)$ lookups, `toSorted()` immutability. - - **Tier 8 (LOW — Advanced Patterns)**: `useEffectEvent` non-reactive callbacks, single app initialization pattern. -- **App Router & API Workflow Upgrades**: Updated `references/workflows/app.md` and `references/workflows/api.md` with runtime performance checklists. -- **7-Axis Quality Gate Hardening**: Upgraded Axis V (Velocity & Performance) and Axis H (Hierarchy & Boundary Clarity) in `references/memory/quality-bar.md`. - ---- - -## [1.2.0] - 2026-08-25 - -### Added -- **Contextual Decision Layer (CDL v1.0)**: Added `references/memory/decision-points.md` defining a thin arbitration protocol for resolving high-impact multi-tenant SaaS ambiguities (N1–N5: Query Layer, Tenant Resolution Mode, Auth/RBAC, Storage Security, Scope Depth). -- **Brief Command (`/brief`)**: Added `references/commands/brief.md` and `references/workflows/brief.md` for pre-flight SaaS discovery and saving baseline choices in `.tidyfactor/next-brief.md`. -- **Complete Command & Workflow Suite (15 Commands)**: Scaffolded and built all 9 missing command files and workflows (`data`, `storage`, `api`, `app`, `test`, `observe`, `deploy`, `incident`, `audit`). -- **7-Axis Multi-Tenant Quality Gate (`P/H/E/S/R/V/D`)**: Added `references/memory/quality-bar.md` with strict RLS policy rules and pre-emit self-critique stamps across all workflows. -- **Packaging & Validation Suite**: Added `bin/add-skill.js`, updated `package.json` `"bin"` mapping, and created `tools/validate_skill.py` and `tools/build-skill.js`. - ---- - -## [1.1.0] - 2026-08-18 - -### 🛠️ Added — 17 Deterministic Python Runtime Tools (`tools/`) -- **Project & Environment**: `tools/project/scan_project.py` for structured metadata, sizes, and ratio inspection. -- **Dependency Diagnostics**: `tools/dependencies/analyze_graph.py` and `tools/dependencies/find_unused.py` for non-destructive usage analysis. -- **Import Analysis**: `tools/imports/analyze_imports.py` for evidence-based `optimizePackageImports` recommendations. -- **Next.js & Security Boundary**: `tools/next/analyze_config.py` and `tools/next/scan_client_boundary.py` (detects server package leaks into client components). -- **TypeScript Compiler Diagnostics**: `tools/typescript/analyze_tsconfig.py`, `tools/typescript/explain_scope.py` (`tsc --explainFiles`), and `tools/typescript/profile.py` (`tsc --extendedDiagnostics`). -- **Cache & Watch Boundaries**: `tools/cache/analyze_cache.py` (cache-to-source ratios) and `tools/cache/watch_boundary.py` (detects large media trees inside dev watch boundaries). -- **Statistical Benchmark Engine**: `tools/benchmark/run.py` (multi-run median with 20% noise threshold) and `tools/benchmark/compare.py` (BEFORE / AFTER / DELTA percentages). -- **Host Resources**: `tools/resources/system_probe.py` (best-effort RAM/CPU/Disk) and `tools/resources/node_processes.py` (active node memory inspector). -- **Safety & Structural Validation**: `tools/validation/check_change_scope.py` (blocks changes touching DB/RLS/Auth) and `tools/validation/validate_skill.py` (verifies 100% governance compliance). - -## [1.0.0] - 2026-08-18 - -### 🚀 Initial Production Release -- **Locked Tenant Isolation Model**: Shared schema with `tenant_id uuid NOT NULL REFERENCES tenants(id)` + PostgreSQL Row Level Security (RLS) enforcement boundary. -- **4-Policy RLS Library & Leak Diagnosis**: Dedicated SELECT, INSERT, UPDATE, and DELETE policies per tenant-scoped table, role-scoped policies, and automated `pg_tables` / `pg_policies` coverage audits. -- **Supabase Custom Access Token Hook**: Server-side JWT claim injection (`tenant_id` + `role`) issued at token generation time without client manipulation. -- **Fail-Closed Edge Resolution**: Subdomain, custom domain, and session claim resolution in middleware with fail-closed (404/403) protection. -- **Pluggable Query Layer**: Choice of Supabase JS client, Drizzle ORM, or Prisma configured during `init` and locked in `ARCHITECTURE.md`. -- **Development Performance & Resource Optimization Track (`perf`)**: - - 13-phase comprehensive read-only audit with 120-point scorecard. - - 6 Bottleneck Causality Models (RAM Pressure, CPU, Disk I/O, Dependency Graph, TypeScript Scope, Watch Boundary). - - 🟢 Green / 🟡 Yellow / 🔴 Red optimization catalog with 8-step Evidence Required pipeline for Yellow items. - - Benchmark Noise Control with Cold/Warm run separation and 3-run median protocol. - - SaaS Safety Boundary ensuring performance optimizations never weaken tenant isolation or security. -- **Project Memory & ADR Log**: Generation and synchronization of `ARCHITECTURE.md` with Performance Context and Risk Log. -- **CLI Wizard & Multi-Agent Distribution**: Standalone NPX installer (`npx @tidyfactor/cli-next add-skill`), `.agents/skills/tidyfactor-next/`, `.claude-skill/`, and global IDE integration. diff --git a/dist/tidyfactor-next/LICENSE b/dist/tidyfactor-next/LICENSE deleted file mode 100644 index 8ea93e1..0000000 --- a/dist/tidyfactor-next/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - Copyright 2026 TidyFactor Ecosystem & Alwkala Digital Agency (https://alwkala.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/dist/tidyfactor-next/README.ar.md b/dist/tidyfactor-next/README.ar.md deleted file mode 100644 index 32fb0df..0000000 --- a/dist/tidyfactor-next/README.ar.md +++ /dev/null @@ -1,388 +0,0 @@ -
- -# ⚡ مهارة تايتفكتور لمعمارية ستارت أب `TidyFactor Next.js v1.4.0` -### مهارة المعمارية السحابية متعددة المستأجرين (Multi-Tenant SaaS) وتأمين البيانات ومحرك الأداء لوكلاء الذكاء الاصطناعي - -امنح وكلاء البرمجة الذكية (**Google Antigravity و Claude Code و Cursor و OpenAI Codex و Windsurf**) معمارية أمنية محكمة لا تقبل التهاون على **Next.js 16 + React 19 + Supabase** — ليتوقف وكيلك عن ارتجال عزل المستأجرين ويبدأ في فرضه حتمياً. - -[![npm version](https://img.shields.io/npm/v/@tidyfactor/next.svg?style=for-the-badge&color=000000)](https://www.npmjs.com/package/@tidyfactor/next) -[![License: Apache 2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg?style=for-the-badge)](LICENSE) -[![Tenant Isolation](https://img.shields.io/badge/Tenant%20Isolation-Postgres%20RLS-3ECF8E.svg?style=for-the-badge)](#-نموذج-عزل-المستأجرين-الصارم-locked-tenant-isolation) -[![Next.js 16 Ready](https://img.shields.io/badge/Next.js-16%20App%20Router-black.svg?style=for-the-badge)](#-لماذا-tidyfactornext) -[![Architect Score](https://img.shields.io/badge/Architect%20Score-13%2F13%20Pass%20(100%25)-green.svg?style=for-the-badge)](#-منهجية-tidyfactor-وحوكمة-الامتثال) - -[🚀 البدء السريع](#-البدء-السريع) • [🎯 لماذا TidyFactor/Next](#-لماذا-tidyfactornext) • [🔒 عزل المستأجرين](#-نموذج-عزل-المستأجرين-الصارم-locked-tenant-isolation) • [⚡ دورة حياة الأوامر الـ 15](#-دورة-حياة-أوامر-الساس-الـ-15-saas-command-lifecycle) • [🚀 محرك الأداء](#-محرك-الأداء-وتشخيص-الموارد) • [❓ الأسئلة الشائعة](#-الأسئلة-الشائعة-faq) • [📖 English Version](README.md) - -

- -

- TidyFactor Next.js Architecture Engine Showcase -

- -
- ---- - -## 📚 جدول المحتويات - -- [🎯 لماذا TidyFactor/Next](#-لماذا-tidyfactornext) -- [🚀 البدء السريع](#-البدء-السريع) -- [🌟 القيمة المعمارية المضافة](#-القيمة-المعمارية-المضافة) -- [🔒 نموذج عزل المستأجرين الصارم (Locked Tenant Isolation)](#-نموذج-عزل-المستأجرين-الصارم-locked-tenant-isolation) -- [⚡ دورة حياة أوامر الساس الـ 15 (SaaS Command Lifecycle)](#-دورة-حياة-أوامر-الساس-الـ-15-saas-command-lifecycle) -- [🚀 محرك الأداء وتشخيص الموارد (Performance Engine)](#-محرك-الأداء-وتشخيص-الموارد) - - [1. مصفوفة قواعد أداء التشغيل من هندسة فرسل (8 طبقات ذات أولوية)](#1-مصفوفة-قواعد-أداء-التشغيل-من-هندسة-فرسل-8-طبقات-ذات-أولوية) - - [2. نماذج تشخيص اختناقات بيئة التطوير الستة](#2-نماذج-تشخيص-اختناقات-بيئة-التطوير-الستة) - - [3. مستويات أمان التحسين (الأخضر / الأصفر / الأحمر)](#3-مستويات-أمان-التحسين-الأخضر--الأصفر--الأحمر) -- [🛡️ مصفوفة سياسات RLS وخطافات JWT](#%EF%B8%8F-مصفوفة-سياسات-rls-وخطافات-jwt) -- [📋 ذاكرة المشروع التشغيلية وملف `ARCHITECTURE.md`](#-ذاكرة-المشروع-التشغيلية-وملف-architecturemd) -- [❓ الأسئلة الشائعة (FAQ)](#-الأسئلة-الشائعة-faq) -- [🏛️ منظومة تايدي فاكتور الشاملة (TidyFactor Ecosystem)](#%EF%B8%8F-منظومة-تايدي-فاكتور-الشاملة-tidyfactor-ecosystem) -- [🏛️ منهجية TidyFactor وحوكمة الامتثال](#%EF%B8%8F-منهجية-tidyfactor-وحوكمة-الامتثال) -- [🤝 المساهمة والتطوير المجتمعي](#-المساهمة-والتطوير-المجتمعي) -- [👨‍💻 قنوات الدعم والتواصل](#-قنوات-الدعم-والتواصل) -- [📜 الترخيص](#-الترخيص) - ---- - -## 🎯 لماذا TidyFactor/Next - -معظم مهارات Next.js لوكلاء الذكاء الاصطناعي تركز على كتابة كود قياسي — كاصطلاحات App Router وإدارة الكاش وتحسين حجم الحزم. هذا ضروري، لكنه **لا يمنع** الوكيل الذكي من كتابة استعلام يسرب بيانات الشركة (أ) إلى لوحة تحكم الشركة (ب). - -**تعمل TidyFactor/Next على مستوى أعمق: إنها عقد معماري وأمني صارم وليست مجرد دليل لتنسيق الكود.** - -| البُعد | مهارات Next.js العامة | `tidyfactor-next` | -|---|---|---| -| **ما تعلمه للوكيل** | اصطلاحات App Router، حدود RSC، إدارة الكاش | معمارية الساس متعدد المستأجرين + حاجز أمان Postgres RLS الصلب | -| **النطاق** | **أفقي واسع**: مقتطفات برمجية صغيرة عامة | **عمودي متخصص**: تخصص كامل في تطبيقات الـ SaaS من البداية للنهاية | -| **أخطاء تمنعها حتمياً** | بطء المكونات، أحجام حزم غير محسنة | تسريب بيانات المستأجرين ونسيان شروط `WHERE tenant_id = ...` | -| **نطاق الأداء** | نصائح أداء عامة لبيئة الإنتاج | **محرك مزدوج**: 8 طبقات أداء تشغيلي + 6 نماذج لتشخيص موارد بيئة التطوير | -| **درجة الامتثال المعماري** | غير محددة | **100% Architect Score** (تطابق كامل لقواعد حوكمة تايدي فاكتور) | -| **هل يمكن دمجهما معاً؟** | ✅ | ✅ — ثبّتهما معاً؛ فهما يكملان بعضهما بدقة | - -> [!TIP] -> إذا كنت تبني تطبيق ساس (SaaS) حيث يعني تسريب البيانات بين المستأجرين مساءلة قانونية، فإن **`tidyfactor-next` هي طبقة الحماية الأساسية التي يحتاجها وكيلك الذكي** إلى جانب أفضل ممارسات رياكت العامة. - ---- - -## 🚀 البدء السريع - -### 1. المعالج التفاعلي والحقن المباشر - -```bash -# المعالج التفاعلي لإنشاء منصة ساس جديدة معزولة -npx @tidyfactor/cli-next - -# أو حقن المهارة مباشرة داخل مشروع Next.js قائم -npx @tidyfactor/cli-next add-skill -``` - -### 2. مسارات التثبيت اليدوي حسب بيئة الوكيل الذكي - -| وكيل الذكاء الاصطناعي | مسار التثبيت في مساحة العمل | -|---|---| -| **Google Antigravity** | `.agents/skills/tidyfactor-next/` أو الإعدادات العامة `~/.gemini/config/skills/` | -| **Claude Code** | `.claude-skill/skills/tidyfactor-next/` | -| **Cursor / Codex / Windsurf** | `.agents/skills/tidyfactor-next/` | - -بمجرد التثبيت، اكتب `/init` أو `/brief` داخل نافذة المحادثة مع الوكيل لاكتشاف اختيارات المشروع وتوليد ملف المعمارية الموحد `ARCHITECTURE.md`! - ---- - -## 🌟 القيمة المعمارية المضافة - -```mermaid -graph TD - UserReq["🌐 Incoming Request"] --> Edge["🛡️ Edge Middleware
(Fail-Closed Tenant Resolution)"] - Edge --> Context["📦 Tenant Context
(tenant_id + JWT Claims)"] - Context --> App["⚡ Next.js 16 App Router
(Server Components & Actions)"] - App --> Query["🔌 Pluggable Query Layer
(Supabase JS / Drizzle / Prisma)"] - Query --> Postgres["🐘 PostgreSQL Database"] - Postgres --> RLS["🔒 Row Level Security (RLS)
USING (tenant_id = auth.jwt() ->> 'tenant_id')"] - RLS --> Data["✅ Isolated Tenant Data"] -``` - -

- Fail-Closed Tenant Isolation Security Pipeline -

- -| لمهندسي الفول ستاك | لمؤسسي الشركات والمدراء التقنيين | لوكلاء البرمجة الذكية (AI Agents) | -|---|---|---| -| **عزل مستأجرين محكم**: مخطط قاعدة بيانات مشترك مع `tenant_id` وسياسات RLS، دون تعقيدات تعدد قواعد البيانات وهجرة المخططات المنفصلة. | **ضمان عدم تسريب البيانات**: حاجز أمان صلب على مستوى قاعدة البيانات؛ أخطاء الكود البرمجي لا يمكنها كشف بيانات حساب لآخر. | **موجه أوامر فائق الخفة**: يستهلك موجه `SKILL.md` حوالي 350 توكن فقط عند البداية، ويستدعي الذاكرة التشغيلية عند الطلب فقط. | -| **طبقة استعلام مرنة**: اختر Supabase JS أو Drizzle ORM أو Prisma لمرة واحدة عند التهيئة، ويلتزم بها الكود المولد بالكامل. | **خطاف JWT مخصص على السيرفر**: حقن `tenant_id` وصلاحيات الدور داخل التوكن على السيرفر، وعدم الوثوق أبداً بمدخلات العميل. | **سير عمل حتمي**: ينفذ كل أمر قائمة تحقق صارمة (Validation Checklist) لضمان جودة المخرجات. | -| **حل الهوية الصارم (Fail-Closed)**: برمجيات الـ Edge الوسيطة تحل هوية المستأجر عبر النطاق الفرعي أو النطاق المخصص أو الجلسة، وتغلق الاتصال فوراً عند الخطأ (404/403). | **معمارية حرة دون قيود**: معايير قياسية على Next.js App Router و PostgreSQL دون الاعتماد على أدوات مغلقة المصدر. | **توافق كامل بنسبة 100%**: متوافقة مع القواعد الهيكلية لمنظومة TidyFactor Skill Architect. | -| **محرك أداء قائم على الأدلة**: تشخيص اختناقات الرام والمعالج والقرص قبل تعديل الكود، مع قياس الفروقات الحسابية (DELTA). | **تكاليف استضافة قابلة للتوقع**: كشف الحزم المتضخمة وتسريبات مفاتيح السيرفر قبل النشر. | **حدود أمان الساس الصارمة**: حظر تلقائي للتحسينات التي قد تضعف سياسات RLS أو عزل البيانات. | - ---- - -## 🔒 نموذج عزل المستأجرين الصارم (Locked Tenant Isolation) - -تفرض `tidyfactor-next` سياسات عزل صارمة غير قابلة للتهاون طوال دورة حياة المشروع: - -```sql --- سياسة عزل المستأجر القياسية (النمط 1) -ALTER TABLE public.organizations ENABLE ROW LEVEL SECURITY; - -CREATE POLICY "organizations_tenant_isolation_select" ON public.organizations - FOR SELECT USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_insert" ON public.organizations - FOR INSERT WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_update" ON public.organizations - FOR UPDATE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid) - WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_delete" ON public.organizations - FOR DELETE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); -``` - -### 🚨 توجيهات الأمان غير القابلة للجدل: -1. **سياسات RLS هي حاجز الأمان الحقيقي**: وضع شرط `WHERE tenant_id = ...` في الكود هو مجرد تلميح لمحسن الاستعلامات. إذا تم تعطيل RLS، يعتبر النظام معيباً برمجياً. -2. **عزل مفتاح `service_role`**: ممنوع نهائياً من الوصول لمتصفح العميل أو الواجهات العامة. يستخدم فقط في خلفية السيرفر مع إعادة التحقق من سياق المستأجر. -3. **تمرير السياق من الـ Edge**: يتم حل هوية المستأجر مرة واحدة عند نقطة الدخول وتمريرها للأسفل، وتجنب إعادة استنتاجها عشوائياً في المكونات الداخلية. -4. **مراجعة العمليات العابرة للمستأجرين**: عمليات الدخول الإداري بالنيابة والتقارير العامة يتم عزلها واعتبارها نقاط تدقيق أمني حساسة. - ---- - -## ⚡ دورة حياة أوامر الساس الـ 15 (SaaS Command Lifecycle) - -تغطي المهارة كافة مراحل بناء منصات الساس عبر 15 أمراً تخصصياً مكتملاً بنسبة **100%**: - -| المرحلة | الأمر | نية واستخدام الأمر | ما يتم تحميله في الذاكرة | الحالة | -|---|---|---|---|:---:| -| **0. الاكتشاف** | `brief` | المقابلة الاستكشافية وتثبيت الخيارات المعمارية في كاش المشروع | `references/workflows/brief.md` + `decision-points.md` + `quality-bar.md` | ✅ **مكتمل** | -| **1. التأسيس** | `init` | توليد مشروع ساس جديد وتوثيق المعمارية في `ARCHITECTURE.md` | `references/workflows/init.md` + `spec.md` + `architecture-doc-skeleton.md` | ✅ **مكتمل** | -| **1. التأسيس** | `tenant` | حل هوية المستأجرين وسياق الـ Edge ودورة حياتهم | `references/workflows/tenant.md` + `references/memory/spec.md` | ✅ **مكتمل** | -| **2. الأمان** | `rls` | كتابة سياسات RLS بنمط السياسات الأربعة وتدقيق التسريب | `references/workflows/rls.md` + `spec.md` + `rls-patterns.md` | ✅ **مكتمل** | -| **2. الأمان** | `auth` | ضبط المصادقة وخطاف JWT والصلاحيات (RBAC/ABAC) | `references/workflows/auth.md` + `spec.md` + `auth-patterns.md` | ✅ **مكتمل** | -| **3. البيانات** | `data` | المخططات والـ Migrations والمعاملات والقيود | `references/workflows/data.md` + `references/memory/decision-points.md` | ✅ **مكتمل** | -| **3. البيانات** | `storage` | حاويات الملفات والروابط الموقعة المعزولة للمستأجر | `references/workflows/storage.md` + `references/memory/cache-storage-rules.md` | ✅ **مكتمل** | -| **4. التطبيق** | `api` | مسارات الـ Route Handlers والـ Server Actions والعقود | `references/workflows/api.md` + `client-server-boundaries.md` + `react-perf-rules.md` | ✅ **مكتمل** | -| **4. التطبيق** | `app` | معمارية App Router و React 19 والـ RSC والـ Suspense | `references/workflows/app.md` + `client-server-boundaries.md` + `react-perf-rules.md` | ✅ **مكتمل** | -| **5. الجودة** | `test` | اختبارات الوحدة وسياسات RLS والأمان والتكامل | `references/workflows/test.md` + `references/memory/quality-bar.md` | ✅ **مكتمل** | -| **5. الجودة** | `observe` | تتبع السجلات والتدقيق المعزول وفحص الصحة | `references/workflows/observe.md` + `references/memory/quality-bar.md` | ✅ **مكتمل** | -| **6. التشغيل** | `deploy` | النشر والبيئات والنسخ الاحتياطي اللحظي والـ Rollback | `references/workflows/deploy.md` + `references/memory/spec.md` | ✅ **مكتمل** | -| **6. التشغيل والأداء** | `perf` | تدقيق وتحسين أداء التطوير وتشغيل الـ React وقواعد فرسل | `references/workflows/audit-dev-perf.md` + `perf-optimization-rules.md` + `react-perf-rules.md` | ✅ **مكتمل** | -| **7. الطوارئ** | `incident` | خطط التعافي من الكوارث ومعالجة التسريب البرمجي | `references/workflows/incident.md` + `references/memory/spec.md` | ✅ **مكتمل** | -| **7. الطوارئ** | `audit` | التدقيق المعماري الشامل والامتثال لمنصات الساس | `references/workflows/audit.md` + `references/memory/quality-bar.md` | ✅ **مكتمل** | - ---- - -## 🚀 محرك الأداء وتشخيص الموارد - -### 1. مصفوفة قواعد أداء التشغيل من هندسة فرسل (8 طبقات ذات أولوية) - -تتضمن المهارة أكثر من 40 قاعدة أداء تشغيلي مقسمة لـ 8 مستويات أولوية حاسمة (`references/memory/react-perf-rules.md`): - -1. **الطبقة 1: القضاء على الشلالات الشبكية (`async-*`) [حرجة للغاية]**: تقييم الشروط المتزامنة قبل `await`، تأجيل `await` للفروع المستهلكة فقط، موازاة الاستعلامات المستقلة عبر `Promise.all()`، والتدفق التدريجي عبر ``. -2. **الطبقة 2: تحسين حجم الحزم البرمجية (`bundle-*`) [حرجة للغاية]**: منع ملفات التجميع (Barrel files)، تهيئة `optimizePackageImports`، والاستيراد الديناميكي للمكونات الثقيلة عبر `next/dynamic({ ssr: false })`. -3. **الطبقة 3: أداء جانب السيرفر (`server-*`) [عالية الأهمية]**: منع تكرار الطلبات عبر `React.cache()`، ترحيل المهام غير الحاجبة (كالتقارير والتنبيهات) إلى `after()`، وتمرير كائنات DTO مصغرة فقط عبر حدود RSC. -4. **الطبقة 4: جلب البيانات من جانب العميل (`client-*`) [متوسطة - عالية]**: منع تكرار الطلبات عبر SWR أو TanStack Query، واستخدام مستمعات التمرير السلبية (`passive listeners`). -5. **الطبقة 5: تحسين إعادة الرسم (`rerender-*`) [متوسطة]**: حساب الحالة المشتقة أثناء الرسم (Render) دون مزامنتها في `useEffect`، تجنب `useMemo` على القيم البسيطة، واستخدام `startTransition` و `useDeferredValue`. -6. **الطبقة 6: أداء الرسم والتصيير (`rendering-*`) [متوسطة]**: تطبيق `content-visibility: auto` على القوائم الطويلة، ورفع عناصر JSX الثابتة خارج دوال المكونات. -7. **الطبقة 7: أداء الجافاسكربت (`js-*`) [منخفضة - متوسطة]**: منع اضطراب تخطيط المتصفح (Layout Thrashing) بدمج عمليات القراءة والكتابة، واستخدام `Set` و `Map` للبحث السريع $O(1)$. -8. **الطبقة 8: الأنماط المتقدمة (`advanced-*`) [منخفضة]**: عزل المنطق غير التفاعلي عبر `useEffectEvent`، وتهيئة التطبيق العامة لمرة واحدة. - -### 2. نماذج تشخيص اختناقات بيئة التطوير الستة - -يعالج مسار الأداء بطء إقلاع السيرفر وبطء الـ HMR واستهلاك الرام والقرص عبر **6 نماذج سببية**: -- **النموذج A (ضغط الرام ← ضغط القرص)**: امتلاء الذاكرة وانتقال النظام للـ Swap/Pagefile. -- **النموذج B (تضخم شجرة الاعتماديات ← المعالج والرام)**: حجم `node_modules` الكبير وبطء التحليل الأولي. -- **النموذج C (بطء وسائط التخزين ← عنق زجاجة الكاش)**: بطء قراءة وكتابة مجلد `.next/cache`. -- **النموذج D (اتساع نطاق TypeScript)**: تحليل ملفات ومجلدات غير برمجية داخل `tsconfig.json`. -- **النموذج E (تكلفة أدوات الفحص ESLint)**: تشغيل قواعد `typeChecked` دون تفعيل الكاش. -- **النموذج F (تجاوز نطاق مراقبة الملفات)**: مراقبة آلاف الوسائط والملفات الثابتة غير المصدرية داخل المشروع. - -### 3. مستويات أمان التحسين (الأخضر / الأصفر / الأحمر) - -```mermaid -graph TD - Finding["🔍 Optimization Finding"] --> Tier{"Safety Classification"} - Tier -->|🟢 Green| GreenAction["✅ Apply Automatically
(Unused deps, tsconfig scope, watchIgnore)"] - Tier -->|🟡 Yellow| YellowPipeline["📋 8-Step Evidence Pipeline
(optimizePackageImports, barrel restructure)"] - Tier -->|🔴 Red| RedForbidden["🚫 Permanently Forbidden
(DB schema, RLS, Auth, Tenant Isolation)"] -``` - -- **🟢 الأخضر (آمن، يطبق تلقائياً)**: حذف الحزم غير المستخدمة، ضبط تصنيف الحزم، تضييق نطاق `tsconfig.json`، واستبعاد مجلدات الوسائط عبر `watchIgnore`. -- **🟡 الأصفر (يتطلب موافقة المطور بأدلة)**: تفعيل `optimizePackageImports` بناءً على فحص فعلي، إعادة هيكلة الاستيرادات المجمعة، وتحويل مكونات العميل لسيرفر. -- **🔴 الأحمر (محظور تماماً)**: تعديل مخطط قاعدة البيانات، سياسات RLS، تدفقات المصادقة، عزل المستأجرين، أو تعطيل كاش Next.js عالمياً. - ---- - -## 🛡️ مصفوفة سياسات RLS وخطافات JWT - -### 1. جدول عضويات المستأجرين (`tenant_memberships`) -```sql -CREATE TABLE public.tenant_memberships ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE, - user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, - role text NOT NULL DEFAULT 'member', - created_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (tenant_id, user_id) -); -ALTER TABLE public.tenant_memberships ENABLE ROW LEVEL SECURITY; - -CREATE POLICY "memberships_self_select" ON public.tenant_memberships - FOR SELECT USING (user_id = auth.uid()); -``` - -### 2. خطاف JWT المخصص في Supabase -```sql -CREATE OR REPLACE FUNCTION public.custom_access_token_hook(event jsonb) -RETURNS jsonb LANGUAGE plpgsql STABLE AS $$ -DECLARE - claims jsonb; - membership record; -BEGIN - claims := event->'claims'; - SELECT tenant_id, role INTO membership - FROM public.tenant_memberships - WHERE user_id = (event->>'user_id')::uuid - LIMIT 1; - - IF membership IS NOT NULL THEN - claims := jsonb_set(claims, '{tenant_id}', to_jsonb(membership.tenant_id)); - claims := jsonb_set(claims, '{role}', to_jsonb(membership.role)); - END IF; - RETURN event; -END; -$$; -``` - ---- - -## 📋 ذاكرة المشروع التشغيلية وملف `ARCHITECTURE.md` - -عند تشغيل أمر `/init`، تولد المهارة ملف `ARCHITECTURE.md` في جذر المشروع ليكون **المصدر المرجعي الموحد** عبر جلسات الوكلاء: -- **الخيارات المحسومة للمنظومة**: App Router و React 19 و TypeScript الصارم وسياسات RLS. -- **القرارات المتخذة لمرة واحدة**: طبقة الاستعلام (Supabase JS, Drizzle, Prisma)، استراتيجية حل هوية المستأجر، ومزود المصادقة. -- **سياق الأداء**: الاختناقات المعروفة، استراتيجية التخزين، آخر نقطة قياس وتاريخ آخر فحص مع كود الـ Commit. -- **سجل القرارات المعمارية (ADR Log)**: سجل تراكمي لتوثيق التحولات والقرارات الهامة. -- **سجل المخاطر المفتوحة والديون التقنية**: مصفوفة مرتبة حسب الأولوية (P0–P3). - ---- - -## ❓ الأسئلة الشائعة (FAQ) - -
-هل تغني هذه المهارة عن مهارات Next.js العامة مثل react-best-practices؟ -
-كلا — استخدمهما معاً. تحكم tidyfactor-next المعمارية متعددة المستأجرين وعزل البيانات وحدود RLS الصارمة. بينما تركز مهارات الممارسات العامة على تنسيق كود رياكت وتنسيقات التصميم. لا يوجد تعارض بينهما، وتدمج tidyfactor-next قواعد أداء التشغيل لفرسل مباشرة. -
- -
-ما هي بيئات وكلاء الذكاء الاصطناعي المدعومة؟ -
-Google Antigravity و Claude Code و Cursor و OpenAI Codex و Windsurf، وتعمل المهارة بنفس السلوك الحتمي عبر جميع هذه البيئات. -
- -
-هل يمكنني استخدام Drizzle ORM أو Prisma بدلاً من عميل Supabase JS؟ -
-نعم بالتأكيد. طبقة الاستعلام هي قرار يتخذ لمرة واحدة عند التهيئة عبر init أو brief، ويلتزم الكود المولد بهذا الاختيار بدقة. -
- -
-ماذا يحدث لو تم تعطيل RLS بالخطأ على أحد الجداول؟ -
-يعتبر النظام معيباً ومخترقاً بحكم التعريف. تتضمن أوامر /rls و /audit فحوصات استعلامية آلية مباشرة ضد pg_tables و pg_policies لاكتشاف وتنبيه المطور فوراً بالجداول غير المحمية. -
- -
-كيف تعمل طبقة القرار السياقي (CDL)؟ -
-تجري طبقة الـ CDL مقابلة تمهيدية سريعة لمرة واحدة عبر /brief وتحفظ الاختيارات في .tidyfactor/next-brief.md، مما يسمح للأوامر اللاحقة بالعمل بسلاسة وسرعة دون تكرار الأسئلة. -
- ---- - -## 🏛️ منظومة تايدي فاكتور الشاملة (TidyFactor Ecosystem) - -**TidyFactor** هي منظومة برمجية معيارية لمهارات وكلاء الذكاء الاصطناعي وهندسة الويب: - -``` -TidyFactor Organization (github.com/TidyFactor) -│ -├── مسارات التصميم (Design Skills) -│ ├── Cinematic → الإبهار والتجربة (صفحات تفاعلية بأسلوب Apple × Cartier) -│ ├── Design → البناء والنماذج الأولية (محرك تصميم الكود وبديل فيجما) -│ └── Styler → الإنتاج والشحن الفعلي (محرك تنسيق أطر العمل ودعم الـ RTL) -│ -├── مسارات التطوير البرمجي (Development Skills) -│ ├── HTML → المحتوى والمواقع الثابتة (محرك المواقع الثابتة مع SEO دلالي) -│ ├── HTMX → التفاعلية الخفيفة (تفاعلية تعتمد على السيرفر) -│ ├── JS → تطبيقات SPA المستقلة (تطبيقات رياكتيف بدون أطر عمل) -│ ├── PHP → المعمارية الموحدة (معمارية PHP 8.x الحديثة) -│ └── Next → منصات الساس السحابية (Next.js 16 و React 19 و Supabase RLS والأداء) -│ -└── مسارات النمو والتسويق (Growth Skills) - └── Marketing → المبيعات والنمو (التسويق المباشر واستراتيجيات الـ SEO والمحتوى) -``` - -### 📦 حزم ومستودعات المجتمع المعتمدة - -| المسار | التصنيف | مستودع GitHub | مهارة الوكيل | حزمة NPM | -| :--- | :--- | :--- | :--- | :--- | -| **Next** | Development | [`TidyFactor/Next`](https://github.com/TidyFactor/Next) | `tidyfactor-next` | [`@tidyfactor/next`](https://www.npmjs.com/package/@tidyfactor/next) | -| **Cinematic** | Design | [`TidyFactor/Cinematic`](https://github.com/TidyFactor/Cinematic) | `tidyfactor-cinematic` | [`@tidyfactor/cinematic`](https://www.npmjs.com/package/@tidyfactor/cinematic) | -| **Design** | Design | [`TidyFactor/Design`](https://github.com/TidyFactor/Design) | `tidyfactor-design` | [`@tidyfactor/design`](https://www.npmjs.com/package/@tidyfactor/design) | -| **Styler** | Design | [`TidyFactor/Styler`](https://github.com/TidyFactor/Styler) | `tidyfactor-styler` | [`@tidyfactor/styler`](https://www.npmjs.com/package/@tidyfactor/styler) | -| **HTML** | Development | [`TidyFactor/HTML`](https://github.com/TidyFactor/HTML) | `tidyfactor-html` | [`@tidyfactor/html`](https://www.npmjs.com/package/@tidyfactor/html) | -| **HTMX** | Development | [`TidyFactor/HTMX`](https://github.com/TidyFactor/HTMX) | `tidyfactor-htmx` | [`@tidyfactor/htmx`](https://www.npmjs.com/package/@tidyfactor/htmx) | -| **JS** | Development | [`TidyFactor/JS`](https://github.com/TidyFactor/JS) | `tidyfactor-js` | [`@tidyfactor/js`](https://www.npmjs.com/package/@tidyfactor/js) | -| **PHP** | Development | [`TidyFactor/PHP`](https://github.com/TidyFactor/PHP) | `tidyfactor-php` | [`@tidyfactor/php`](https://www.npmjs.com/package/@tidyfactor/php) | -| **Marketing** | Growth | [`TidyFactor/Marketing`](https://github.com/TidyFactor/Marketing) | `tidyfactor-marketing` | [`@tidyfactor/marketing`](https://www.npmjs.com/package/@tidyfactor/marketing) | - ---- - -## 🏛️ منهجية TidyFactor وحوكمة الامتثال - -تلتزم `tidyfactor-next` بجميع **القواعد الهيكلية الثماني** لمنظومة [`tidyfactor-skill-architect`](https://github.com/TidyFactor/Skill-Architect): - -1. ✅ **انضباط التوجيه (Dispatcher Discipline)**: ملف `SKILL.md` موجه أوامر خفيف يستهلك ~350 توكن فقط. -2. ✅ **مسار عمل واحد = نتيجة واحدة**: كل مسار يمتلك مخرجاً واحداً وقائمة تحقق دقيقة. -3. ✅ **ذاكرة تشغيلية نقية**: قوالب SQL وأنماط معمارية دون حشو تسويقي. -4. ✅ **بنية نظيفة**: لا توجد مجلدات فارغة أو أحادية الملف. -5. ✅ **فصل الفلسفة**: عزل الفلسفة عن ملفات التنفيذ البرمجي التشغيلية. -6. ✅ **نمو قائم على المحفزات**: إضافة الأوامر بناءً على مراحل دورة حياة الساس الحقيقية. -7. ✅ **حاجز الجودة والأمان**: استعلامات آلية لفحص سياسات RLS واكتشاف التسريب. -8. ✅ **توافق عبر المنصات**: أداء متطابق تماماً عبر Antigravity و Claude Code و Cursor و Codex. - ---- - -## 🤝 المساهمة والتطوير المجتمعي - -نرحب بمساهمات المجتمع والمطورين، ومحولات طبقات الاستعلام الإضافية، وتحسينات مسارات العمل! - -يرجى مراجعة [CONTRIBUTING.md](CONTRIBUTING.md) و [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) قبل فتح طلب سحب (Pull Request). يجب أن تلتزم التعديلات المقترحة بالقواعد الهيكلية لـ `tidyfactor-skill-architect`. - ---- - -## 👨‍💻 قنوات الدعم والتواصل - -- 🌐 **الموقع الرسمي:** [tidyfactor.com](https://tidyfactor.com/) -- 📚 **التوثيق البرمجي:** [tidyfactor.com/documentation](https://tidyfactor.com/documentation) -- 🤝 **الشريك الاستراتيجي:** [وكالة الوكالة الرقمية (Alwkala Digital Agency)](https://alwkala.com/) -- 🐙 **منظمة GitHub الرسمية:** [github.com/TidyFactor](https://github.com/TidyFactor) -- 📧 **البريد الإلكتروني:** [hello@tidyfactor.com](mailto:hello@tidyfactor.com) - ---- - -## 👨‍💻 المنظمة والتواصل والدعم - -- 🌐 **الموقع الرسمي للمنظومة:** [https://tidyfactor.com/](https://tidyfactor.com/) -- 📚 **التوثيق الرسمي المعتمد:** [https://tidyfactor.com/documentation](https://tidyfactor.com/documentation) -- 🤝 **الشريك التقني الرسمي:** [وكالة الوكالة الرقمية Alwkala](https://alwkala.com/) -- 🐙 **منظمة GitHub الرسمية:** [github.com/TidyFactor](https://github.com/TidyFactor) -- 📧 **استفسارات الأعمال والشراكات:** [hello@tidyfactor.com](mailto:hello@tidyfactor.com) -- 📱 **واتساب:** [+20 101 665 6899](https://wa.me/201016656899) -- 📞 **الهاتف:** +20 101 665 6899 -- 📍 **المقر:** القاهرة، جمهورية مصر العربية - ---- - -## 📜 الترخيص والمجتمع - -مرخصة تحت رخصة **Apache License 2.0**. حقوق النشر محفوظة (c) 2026 لصالح [منظومة TidyFactor](https://tidyfactor.com) و[وكالة الوكالة الرقمية Alwkala](https://alwkala.com). diff --git a/dist/tidyfactor-next/README.md b/dist/tidyfactor-next/README.md deleted file mode 100644 index 146232e..0000000 --- a/dist/tidyfactor-next/README.md +++ /dev/null @@ -1,388 +0,0 @@ -
- -# ⚡ TidyFactor Next.js `v1.4.0` -### The Production-Grade Multi-Tenant SaaS Architecture & Performance Skill for AI Coding Agents - -Give **Google Antigravity, Claude Code, Cursor, OpenAI Codex, or Windsurf** a locked, security-first architecture for **Next.js 16 + React 19 + Supabase** — so your agent stops improvising tenant isolation and starts enforcing it. - -[![npm version](https://img.shields.io/npm/v/@tidyfactor/next.svg?style=for-the-badge&color=000000)](https://www.npmjs.com/package/@tidyfactor/next) -[![License: Apache 2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg?style=for-the-badge)](LICENSE) -[![Tenant Isolation](https://img.shields.io/badge/Tenant%20Isolation-Postgres%20RLS-3ECF8E.svg?style=for-the-badge)](#-locked-tenant-isolation-model) -[![Next.js 16 Ready](https://img.shields.io/badge/Next.js-16%20App%20Router-black.svg?style=for-the-badge)](#-why-tidyfactornext) -[![Architect Score](https://img.shields.io/badge/Architect%20Score-13%2F13%20Pass%20(100%25)-green.svg?style=for-the-badge)](#%EF%B8%8F-tidyfactor-skill-methodology--governance) - -[🚀 Quick Start](#-quick-start) • [🎯 Why TidyFactor/Next](#-why-tidyfactornext) • [🔒 Tenant Isolation](#-locked-tenant-isolation-model) • [⚡ 15-Stage Lifecycle](#-15-stage-saas-command-lifecycle) • [🚀 Perf Engine](#-performance--optimization-engine) • [❓ FAQ](#-faq) • [📖 بالعربية](README.ar.md) - -

- -

- TidyFactor Next.js Hero Banner -

- -
- ---- - -## 📚 Table of Contents - -- [🎯 Why TidyFactor/Next](#-why-tidyfactornext) -- [🚀 Quick Start](#-quick-start) -- [🌟 Architectural Value Proposition](#-architectural-value-proposition) -- [🔒 Locked Tenant Isolation Model](#-locked-tenant-isolation-model) -- [⚡ 15-Stage SaaS Command Lifecycle](#-15-stage-saas-command-lifecycle) -- [🚀 Performance & Optimization Engine](#-performance--optimization-engine) - - [1. 8-Tier Runtime Performance Rules (Vercel Engineering)](#1-8-tier-runtime-performance-rules-vercel-engineering) - - [2. Development Environment Resource Diagnostics](#2-development-environment-resource-diagnostics) - - [3. Optimization Safety Tiers (Green / Yellow / Red)](#3-optimization-safety-tiers-green--yellow--red) -- [🛡️ RLS Policy Matrix & Auth Hooks](#%EF%B8%8F-rls-policy-matrix--auth-hooks) -- [📋 Project Memory & ARCHITECTURE.md](#-project-memory--architecturemd) -- [❓ FAQ](#-faq) -- [🏛️ The TidyFactor Ecosystem](#%EF%B8%8F-the-tidyfactor-ecosystem) -- [🏛️ TidyFactor Skill Methodology & Governance](#%EF%B8%8F-tidyfactor-skill-methodology--governance) -- [🤝 Contributing](#-contributing) -- [👨‍💻 Support](#-support) -- [📜 License](#-license) - ---- - -## 🎯 Why TidyFactor/Next - -Most Next.js agent skills teach your AI how to write idiomatic code — App Router conventions, caching APIs, and bundle-size tweaks. That is necessary, but it does **not** stop an agent from shipping a query that accidentally leaks Tenant A's data into Tenant B's dashboard. - -**TidyFactor/Next sits one layer deeper: it is an architecture and hard security contract, not just a style guide.** - -| Dimension | Generic Next.js Skills | `tidyfactor-next` | -|---|---|---| -| **What it teaches** | Idiomatic App Router, React 19 RSC boundaries, caching | Multi-tenant architecture + non-negotiable Postgres RLS boundary | -| **Scope** | **Breadth**: Many small, composable coding snippets | **Depth**: One vertical (multi-tenant SaaS), owned end-to-end | -| **Failure mode prevented** | Slow client components, suboptimal bundles | Cross-tenant data leaks, forgotten `WHERE tenant_id = ...` clauses | -| **Performance scope** | Basic production advice | **Dual engine**: 8 runtime optimization tiers + 6 dev-environment bottleneck models | -| **Governance score** | Unverified | **100% Architect Score** (passes all TidyFactor Skill Architect rules) | -| **Use together?** | ✅ | ✅ — Install both; they complement each other perfectly | - -> [!TIP] -> If you are building a SaaS where a cross-tenant data leak means a lawsuit, **`tidyfactor-next` is the foundational guardrail layer your AI agent needs** in addition to general React best practices. - ---- - -## 🚀 Quick Start - -### 1. Interactive Project Wizard & Direct Injection - -```bash -# Interactive project wizard — scaffolds a new multi-tenant SaaS project -npx @tidyfactor/cli-next - -# Or inject the skill directly into an existing Next.js repository -npx @tidyfactor/cli-next add-skill -``` - -### 2. Workspace Installation per AI Agent - -| AI Agent | Workspace Skill Path | -|---|---| -| **Google Antigravity** | `.agents/skills/tidyfactor-next/` or global `~/.gemini/config/skills/` | -| **Claude Code** | `.claude-skill/skills/tidyfactor-next/` | -| **Cursor / Codex / Windsurf** | `.agents/skills/tidyfactor-next/` | - -Once installed, invoke `/init` or `/brief` inside your AI agent to discover project baselines and scaffold your `ARCHITECTURE.md` single source of truth! - ---- - -## 🌟 Architectural Value Proposition - -```mermaid -graph TD - UserReq["🌐 Incoming Request"] --> Edge["🛡️ Edge Middleware
(Fail-Closed Tenant Resolution)"] - Edge --> Context["📦 Tenant Context
(tenant_id + JWT Claims)"] - Context --> App["⚡ Next.js 16 App Router
(Server Components & Actions)"] - App --> Query["🔌 Pluggable Query Layer
(Supabase JS / Drizzle / Prisma)"] - Query --> Postgres["🐘 PostgreSQL Database"] - Postgres --> RLS["🔒 Row Level Security (RLS)
USING (tenant_id = auth.jwt() ->> 'tenant_id')"] - RLS --> Data["✅ Isolated Tenant Data"] -``` - -

- Fail-Closed Tenant Isolation Security Pipeline -

- -| For Fullstack Engineers | For SaaS Founders & CTOs | For AI Coding Agents | -|---|---|---| -| **Locked Tenant Isolation**: Shared schema with `tenant_id` + Postgres RLS. No schema-per-tenant migration hell or multi-DB connection pooling chaos. | **Zero Data-Leak Guarantee**: Hard security boundary at the database layer; application bugs cannot expose Tenant A's records to Tenant B. | **Context-Efficient Dispatcher**: Lightweight `SKILL.md` router loads only ~350 tokens at start, pulling memory only on demand. | -| **Pluggable Query Layer**: Choose Supabase JS, Drizzle ORM, or Prisma once during `init`. All downstream code adheres strictly to your choice. | **Custom JWT Access Token Hook**: Injects verified `tenant_id` and `role` server-side at token issuance—never trusted from client input. | **Deterministic Workflows**: Every command runs against a strict, quantifiable validation checklist before shipping. | -| **Fail-Closed Resolution**: Edge middleware resolves tenant via subdomain, custom domain, or session claim, failing closed (404/403) on error. | **Zero Lock-in Architecture**: Pure Next.js App Router and PostgreSQL standards with zero black-box vendor runtime dependencies. | **100% Governance Compliance**: Fully compliant (8/8) with the official TidyFactor Skill Architect governance specification. | -| **Evidence-Based Perf Engine**: Diagnoses RAM, CPU, and Disk bottlenecks before touching code; benchmark-backed DELTA verification. | **Predictable Infrastructure Cost**: Identifies bloated client bundles and server secret leaks before deployment. | **SaaS Safety Boundary**: Automatically prohibits performance optimizations that weaken RLS or tenant isolation. | - ---- - -## 🔒 Locked Tenant Isolation Model - -`tidyfactor-next` enforces strict, non-negotiable isolation rules across the entire lifecycle: - -```sql --- Standard Tenant Isolation Policy (Pattern 1) -ALTER TABLE public.organizations ENABLE ROW LEVEL SECURITY; - -CREATE POLICY "organizations_tenant_isolation_select" ON public.organizations - FOR SELECT USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_insert" ON public.organizations - FOR INSERT WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_update" ON public.organizations - FOR UPDATE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid) - WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); - -CREATE POLICY "organizations_tenant_isolation_delete" ON public.organizations - FOR DELETE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); -``` - -### 🚨 Non-Negotiable Safety Directives: -1. **RLS is the Security Boundary**: Application-layer `WHERE tenant_id = ...` is only a query-plan hint. If RLS is disabled, the system is defective by definition. -2. **`service_role` Key Isolation**: Never exposed to client bundles or public endpoints. Used exclusively in server-only contexts with re-verified tenant context. -3. **Edge Context Propagation**: Tenant identity is resolved once at the edge and passed down—never re-derived haphazardly in deep component trees. -4. **Cross-Tenant Operations Review**: Admin impersonation, cross-tenant migrations, or platform analytics must be isolated and flagged as security review triggers. - ---- - -## ⚡ 15-Stage SaaS Command Lifecycle - -The entire SaaS engineering lifecycle is structured into 15 deterministic commands with **100% operational coverage**: - -| Stage | Command | User Intent | What It Loads | Status | -|---|---|---|---|:---:| -| **0. Discovery** | `brief` | Pre-flight CDL discovery & baseline architecture cache | `references/workflows/brief.md` + `decision-points.md` + `quality-bar.md` | ✅ **Built** | -| **1. Foundation** | `init` | Scaffold new multi-tenant project & generate `ARCHITECTURE.md` | `references/workflows/init.md` + `spec.md` + `architecture-doc-skeleton.md` | ✅ **Built** | -| **1. Foundation** | `tenant` | Tenant resolution, context propagation, lifecycle | `references/workflows/tenant.md` + `references/memory/spec.md` | ✅ **Built** | -| **2. Security** | `rls` | RLS policy authoring, 4-policy pattern, leak audit | `references/workflows/rls.md` + `spec.md` + `rls-patterns.md` | ✅ **Built** | -| **2. Security** | `auth` | Supabase Auth, custom JWT claims hook, RBAC/ABAC | `references/workflows/auth.md` + `spec.md` + `auth-patterns.md` | ✅ **Built** | -| **3. Data** | `data` | Schema, migrations, transactions, constraints | `references/workflows/data.md` + `references/memory/decision-points.md` | ✅ **Built** | -| **3. Data** | `storage` | Tenant-scoped buckets, signed URLs, storage RLS | `references/workflows/storage.md` + `references/memory/cache-storage-rules.md` | ✅ **Built** | -| **4. Application** | `api` | Route handlers, server actions, API contracts | `references/workflows/api.md` + `client-server-boundaries.md` + `react-perf-rules.md` | ✅ **Built** | -| **4. Application** | `app` | App Router, React 19, RSC boundaries, Suspense | `references/workflows/app.md` + `client-server-boundaries.md` + `react-perf-rules.md` | ✅ **Built** | -| **5. Quality** | `test` | Unit, integration, RLS coverage, E2E security tests | `references/workflows/test.md` + `references/memory/quality-bar.md` | ✅ **Built** | -| **5. Quality** | `observe` | Tracing, tenant-scoped audit logs, health checks | `references/workflows/observe.md` + `references/memory/quality-bar.md` | ✅ **Built** | -| **6. DevOps** | `deploy` | CI/CD, environments, rollback, point-in-time backups | `references/workflows/deploy.md` + `references/memory/spec.md` | ✅ **Built** | -| **6. DevOps / Perf** | `perf` | Dev & runtime performance audit, bottleneck diagnosis, safe perf | `references/workflows/audit-dev-perf.md` + `perf-optimization-rules.md` + `react-perf-rules.md` | ✅ **Built** | -| **7. Operations** | `incident` | Disaster recovery, tenant leak remediation runbooks | `references/workflows/incident.md` + `references/memory/spec.md` | ✅ **Built** | -| **7. Operations** | `audit` | Full-stack multi-tenant architecture compliance audit | `references/workflows/audit.md` + `references/memory/quality-bar.md` | ✅ **Built** | - ---- - -## 🚀 Performance & Optimization Engine - -### 1. 8-Tier Runtime Performance Rules (Vercel Engineering) - -`tidyfactor-next` encapsulates 40+ runtime optimization rules categorized into 8 impact-ranked tiers (`references/memory/react-perf-rules.md`): - -1. **Tier 1: Eliminating Waterfalls (`async-*`) [CRITICAL]**: Check synchronous conditions before `await`, defer `await` to consuming branches, parallelize independent queries with `Promise.all()`, stream async subtrees with ``. -2. **Tier 2: Bundle Size Optimization (`bundle-*`) [CRITICAL]**: Avoid barrel files, configure `optimizePackageImports`, lazy-load heavy widgets with `next/dynamic({ ssr: false })`, defer 3rd-party scripts. -3. **Tier 3: Server-Side Performance (`server-*`) [HIGH]**: Wrap per-request data fetchers with `React.cache()`, offload non-blocking telemetry and audit logs to Next.js 16 `after()`, pass only minimal serialized DTOs across the RSC $\to$ RCC boundary. -4. **Tier 4: Client-Side Data Fetching (`client-*`) [MEDIUM-HIGH]**: SWR / TanStack Query automatic deduplication, passive scroll listeners. -5. **Tier 5: Re-render Optimization (`rerender-*`) [MEDIUM]**: Pure derived state in render (never synchronize via `useEffect`), avoid `useMemo` on cheap primitives, lazy `useState` initializers, `startTransition` / `useDeferredValue`. -6. **Tier 6: Rendering Performance (`rendering-*`) [MEDIUM]**: CSS `content-visibility: auto`, hoist static JSX elements outside render, use explicit conditionals. -7. **Tier 7: JavaScript Performance (`js-*`) [LOW-MEDIUM]**: Layout thrashing prevention (batch DOM read/write), `Set`/`Map` $O(1)$ lookups, `toSorted()` immutability. -8. **Tier 8: Advanced React Patterns (`advanced-*`) [LOW]**: Extract non-reactive callback logic with `useEffectEvent`, single-mount app initialization. - -### 2. Development Environment Resource Diagnostics - -Tackles dev-server startup slowness, sluggish HMR, RAM bloat, and disk I/O through **6 Causality Models**: -- **Model A (RAM Pressure → Disk I/O)**: Memory saturation causing OS paging to swap. -- **Model B (Large Dependency Graph → CPU/RAM)**: Massive module trees slowing cold starts. -- **Model C (Slow Storage → Cache I/O)**: `.next/cache` I/O bottlenecks. -- **Model D (TypeScript Scope Overreach)**: Wide `include` scopes analyzing generated or test files. -- **Model E (ESLint / Tooling Overhead)**: `typeChecked` rules running without caching. -- **Model F (Watch Boundary Overflow)**: Thousands of media uploads monitored by file watchers. - -### 3. Optimization Safety Tiers (Green / Yellow / Red) - -```mermaid -graph TD - Finding["🔍 Optimization Finding"] --> Tier{"Safety Classification"} - Tier -->|🟢 Green| GreenAction["✅ Apply Automatically
(Unused deps, tsconfig scope, watchIgnore)"] - Tier -->|🟡 Yellow| YellowPipeline["📋 8-Step Evidence Pipeline
(optimizePackageImports, barrel restructure)"] - Tier -->|🔴 Red| RedForbidden["🚫 Permanently Forbidden
(DB schema, RLS, Auth, Tenant Isolation)"] -``` - -- **🟢 Green (Safe)**: Unused dependency cleanup, `dependencies` vs `devDependencies` correction, `tsconfig.json` scope tightening, `.gitignore` & `watchIgnore` fixes. -- **🟡 Yellow (Review Required)**: Evidence-based `optimizePackageImports`, barrel import restructuring, client-to-server component conversion. -- **🔴 Red (Permanently Forbidden)**: Modifying database schema, RLS policies, auth flows, tenant isolation models, or globally disabling caching. - ---- - -## 🛡️ RLS Policy Matrix & Auth Hooks - -### 1. `tenant_memberships` Join Model -```sql -CREATE TABLE public.tenant_memberships ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE, - user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, - role text NOT NULL DEFAULT 'member', - created_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (tenant_id, user_id) -); -ALTER TABLE public.tenant_memberships ENABLE ROW LEVEL SECURITY; - -CREATE POLICY "memberships_self_select" ON public.tenant_memberships - FOR SELECT USING (user_id = auth.uid()); -``` - -### 2. Supabase Custom Access Token Hook -```sql -CREATE OR REPLACE FUNCTION public.custom_access_token_hook(event jsonb) -RETURNS jsonb LANGUAGE plpgsql STABLE AS $$ -DECLARE - claims jsonb; - membership record; -BEGIN - claims := event->'claims'; - SELECT tenant_id, role INTO membership - FROM public.tenant_memberships - WHERE user_id = (event->>'user_id')::uuid - LIMIT 1; - - IF membership IS NOT NULL THEN - claims := jsonb_set(claims, '{tenant_id}', to_jsonb(membership.tenant_id)); - claims := jsonb_set(claims, '{role}', to_jsonb(membership.role)); - END IF; - RETURN event; -END; -$$; -``` - ---- - -## 📋 Project Memory & `ARCHITECTURE.md` - -During `/init`, the skill generates an `ARCHITECTURE.md` file in your project root. This document serves as the **Single Source of Truth** for architectural decisions across AI agent sessions: -- **Locked Platform Choices**: App Router, React 19, TypeScript strict, Postgres RLS. -- **Chosen Once Decisions**: Query layer (Supabase JS, Drizzle, Prisma), tenant resolution strategy, auth provider, role model. -- **Performance Context**: Known bottlenecks, storage strategy, active baseline, last audit timestamp & git commit SHA. -- **ADR Log**: Append-only register recording significant architectural decisions. -- **Open Risks & Tech Debt**: Prioritized register (P0–P3) tracked across `perf`, `rls`, `audit`, and `incident` commands. - ---- - -## ❓ FAQ - -
-Does this replace generic Next.js skills like react-best-practices? -
-No — use both. tidyfactor-next governs multi-tenant architecture, data isolation, and Postgres RLS security contracts. General best-practice skills focus on general React idioms and client-side styling. They do not overlap; tidyfactor-next incorporates runtime optimization rules directly. -
- -
-Which AI coding agents are supported? -
-Google Antigravity, Claude Code, Cursor, OpenAI Codex, and Windsurf are all supported with 100% behavioral parity. -
- -
-Can I use Drizzle ORM or Prisma instead of the Supabase JS client? -
-Yes. The query layer is a "chosen-once" decision made during init or brief. All generated schema models, queries, and repositories follow your confirmed choice. -
- -
-What happens if RLS is accidentally disabled on a table? -
-By this skill's definition, the system is defective. The /rls and /audit commands include automated leak-audit queries against pg_tables and pg_policies to flag unshielded tables immediately. -
- -
-How does the Contextual Decision Layer (CDL) work? -
-The CDL runs a single-round pre-flight interview via /brief and caches baseline stack choices in .tidyfactor/next-brief.md, allowing downstream commands to execute silently without repeating questions. -
- ---- - -## 🏛️ The TidyFactor Ecosystem - -**TidyFactor** is a modular web architecture and AI coding agent skill ecosystem built on clear separation of concerns across the product lifecycle: - -``` -TidyFactor Organization (github.com/TidyFactor) -│ -├── Design Skills -│ ├── Cinematic → Experience / "Wow" (Apple × Cartier Scroll-Driven Landing Pages) -│ ├── Design → Prototype / "Build" (Code-Native UI Design Engine & Figma Alternative) -│ └── Styler → Production / "Ship" (Framework Styler & RTL Polish Engine) -│ -├── Development Skills -│ ├── HTML → Content & Static (Semantic SEO & Static Platform Starter) -│ ├── HTMX → Hypermedia (Server-Driven Micro-Interactions) -│ ├── JS → Vanilla SPA (Framework-Free Reactive ES Modules) -│ ├── PHP → Server-Rendered (Modern PHP 8.x Component UI & Architecture) -│ └── Next → Multi-Tenant SaaS (Next.js 16, React 19, Supabase RLS & Dev-Perf) -│ -└── Growth Skills - └── Marketing → Growth / Revenue (Direct Response, Pillar SEO & Content Lifecycles) -``` - -### 📦 Community Package & Skill Parity - -| Track | Category | GitHub Repository | Agent Skill | NPM Package | -| :--- | :--- | :--- | :--- | :--- | -| **Next** | Development | [`TidyFactor/Next`](https://github.com/TidyFactor/Next) | `tidyfactor-next` | [`@tidyfactor/next`](https://www.npmjs.com/package/@tidyfactor/next) | -| **Cinematic** | Design | [`TidyFactor/Cinematic`](https://github.com/TidyFactor/Cinematic) | `tidyfactor-cinematic` | [`@tidyfactor/cinematic`](https://www.npmjs.com/package/@tidyfactor/cinematic) | -| **Design** | Design | [`TidyFactor/Design`](https://github.com/TidyFactor/Design) | `tidyfactor-design` | [`@tidyfactor/design`](https://www.npmjs.com/package/@tidyfactor/design) | -| **Styler** | Design | [`TidyFactor/Styler`](https://github.com/TidyFactor/Styler) | `tidyfactor-styler` | [`@tidyfactor/styler`](https://www.npmjs.com/package/@tidyfactor/styler) | -| **HTML** | Development | [`TidyFactor/HTML`](https://github.com/TidyFactor/HTML) | `tidyfactor-html` | [`@tidyfactor/html`](https://www.npmjs.com/package/@tidyfactor/html) | -| **HTMX** | Development | [`TidyFactor/HTMX`](https://github.com/TidyFactor/HTMX) | `tidyfactor-htmx` | [`@tidyfactor/htmx`](https://www.npmjs.com/package/@tidyfactor/htmx) | -| **JS** | Development | [`TidyFactor/JS`](https://github.com/TidyFactor/JS) | `tidyfactor-js` | [`@tidyfactor/js`](https://www.npmjs.com/package/@tidyfactor/js) | -| **PHP** | Development | [`TidyFactor/PHP`](https://github.com/TidyFactor/PHP) | `tidyfactor-php` | [`@tidyfactor/php`](https://www.npmjs.com/package/@tidyfactor/php) | -| **Marketing** | Growth | [`TidyFactor/Marketing`](https://github.com/TidyFactor/Marketing) | `tidyfactor-marketing` | [`@tidyfactor/marketing`](https://www.npmjs.com/package/@tidyfactor/marketing) | - ---- - -## 🏛️ TidyFactor Skill Methodology & Governance - -`tidyfactor-next` passes all **8 Architectural Governance Rules** under [`tidyfactor-skill-architect`](https://github.com/TidyFactor/Skill-Architect): - -1. ✅ **Dispatcher Discipline**: `SKILL.md` routes commands without executing tasks (~350 tokens). -2. ✅ **One Workflow = One Outcome**: Every workflow has a single deliverable with an explicit validation checklist. -3. ✅ **Operational Memory**: Pure SQL templates, schemas, and architecture rules—zero narrative prose. -4. ✅ **No Empty Structures**: Clean, flattened architecture without single-file folders. -5. ✅ **Philosophy Isolation**: Technical execution separated from marketing commentary. -6. ✅ **Trigger-Justified Growth**: Commands added per verifiable SaaS lifecycle stages. -7. ✅ **Security & Quality Bar**: Automated RLS coverage queries (`pg_tables`, `pg_policies`) and leak diagnosis. -8. ✅ **Cross-Platform Parity**: 100% identical behavior across Antigravity, Claude Code, Cursor, and Codex. - ---- - -## 🤝 Contributing - -We welcome community contributions, custom query layer adapters, and workflow refinements! - -Please read our [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) before opening a Pull Request. All proposed workflows and memory extensions must satisfy the `tidyfactor-skill-architect` governance rules. - ---- - -## 👨‍💻 Support - -- 🌐 **Website:** [tidyfactor.com](https://tidyfactor.com/) -- 📚 **Documentation:** [tidyfactor.com/documentation](https://tidyfactor.com/documentation) -- 🤝 **Commercial Partner:** [Alwkala Digital Agency](https://alwkala.com/) -- 🐙 **GitHub Organization:** [github.com/TidyFactor](https://github.com/TidyFactor) -- 📧 **Inquiries:** [hello@tidyfactor.com](mailto:hello@tidyfactor.com) - ---- - -## 👨‍💻 Organization & Support - -- 🌐 **Official Website:** [https://tidyfactor.com/](https://tidyfactor.com/) -- 📚 **Official Documentation:** [https://tidyfactor.com/documentation](https://tidyfactor.com/documentation) -- 🤝 **Official Partner Website:** [Alwkala Digital Agency](https://alwkala.com/) -- 🐙 **GitHub Organization:** [github.com/TidyFactor](https://github.com/TidyFactor) -- 📧 **Business Inquiries:** [hello@tidyfactor.com](mailto:hello@tidyfactor.com) -- 📱 **WhatsApp:** [+20 101 665 6899](https://wa.me/201016656899) -- 📞 **Phone:** +20 101 665 6899 -- 📍 **Location:** Cairo, Egypt - ---- - -## 📜 License - -Licensed under the **Apache License 2.0**. Copyright (c) 2026 [TidyFactor](https://tidyfactor.com) & [Alwkala](https://alwkala.com). diff --git a/dist/tidyfactor-next/SKILL.md b/dist/tidyfactor-next/SKILL.md deleted file mode 100644 index 00599b2..0000000 --- a/dist/tidyfactor-next/SKILL.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -name: tidyfactor-next -description: "Production multi-tenant SaaS engine on Next.js 16, React 19, TypeScript strict, and Supabase with Contextual Decision Layer (CDL). Features locked tenant isolation (tenant_id + Postgres RLS) and pluggable query layer. Trigger on commands 'brief', 'init', 'tenant', 'rls', 'auth', 'data', 'storage', 'api', 'app', 'test', 'observe', 'deploy', or requests to build a multi-tenant SaaS." ---- -# TidyFactor Next.js - -A command dispatcher for production multi-tenant SaaS on Next.js 16 and Supabase. This router declares commands and workflows without performing execution directly. - -## Commands - -| User intent | Command | What it loads | -|---|---|---| -| Strategic SaaS Discovery & Baseline Architecture | `references/commands/brief.md` | `workflows/brief.md` + `memory/decision-points.md` + `memory/quality-bar.md` | -| Scaffold a new multi-tenant project | `references/commands/init.md` | `workflows/init.md` + `memory/spec.md` | -| Tenant resolution, context, lifecycle | `references/commands/tenant.md` | `workflows/tenant.md` + `memory/spec.md` | -| RLS policy authoring, coverage audit, leak diagnosis | `references/commands/rls.md` | `workflows/rls.md` + `memory/rls-patterns.md` | -| Auth, RBAC/ABAC | `references/commands/auth.md` | `workflows/auth.md` + `memory/auth-patterns.md` | -| Schema, migrations, transactions, constraints | `references/commands/data.md` | `workflows/data.md` + `memory/decision-points.md` | -| Buckets, signed URLs, tenant-scoped storage paths | `references/commands/storage.md` | `workflows/storage.md` + `memory/cache-storage-rules.md` | -| Route handlers, server actions, API contracts | `references/commands/api.md` | `workflows/api.md` + `memory/client-server-boundaries.md` + `memory/react-perf-rules.md` | -| App Router / React 19 patterns, RSC boundaries | `references/commands/app.md` | `workflows/app.md` + `memory/client-server-boundaries.md` + `memory/react-perf-rules.md` | -| Unit/integration/RLS/E2E/security tests | `references/commands/test.md` | `workflows/test.md` + `memory/quality-bar.md` | -| Logging, tracing, audit logs, health checks | `references/commands/observe.md` | `workflows/observe.md` + `memory/quality-bar.md` | -| CI/CD, environments, secrets, rollback, backups | `references/commands/deploy.md` | `workflows/deploy.md` + `memory/spec.md` | -| Dev & Runtime performance: waterfalls, bundles, RAM, HMR | `references/commands/perf.md` | `workflows/audit-dev-perf.md` + `memory/perf-optimization-rules.md` + `memory/react-perf-rules.md` | -| Failure modes, retries, DR, recovery runbooks | `references/commands/incident.md` | `workflows/incident.md` + `memory/spec.md` | -| Structural/architecture audit of the whole project | `references/commands/audit.md` | `workflows/audit.md` + `memory/quality-bar.md` | - -Read only the command file that matches the request. Do not load all commands simultaneously. - -## Non-Negotiable Invariants - -1. **Contextual Decision Layer (CDL)**: Resolve project baselines via `/brief` or `.tidyfactor/next-brief.md` before emitting code. -2. **Locked Tenant Isolation**: Every tenant-owned table MUST include `tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE`. -3. **Forced RLS Boundary**: Every tenant table MUST have `ENABLE ROW LEVEL SECURITY` and `FORCE ROW LEVEL SECURITY`. -4. **Zero Service-Role Leaks**: Never expose `SUPABASE_SERVICE_ROLE_KEY` to client components or public API responses. -5. **7-Axis Pre-Emit Critique**: All generated code must be evaluated with `/* Pre-emit critique: P5 H5 E5 S5 R5 V5 D5 */`. diff --git a/dist/tidyfactor-next/assets/demo-architecture.html b/dist/tidyfactor-next/assets/demo-architecture.html deleted file mode 100644 index f2874f8..0000000 --- a/dist/tidyfactor-next/assets/demo-architecture.html +++ /dev/null @@ -1,207 +0,0 @@ - - - - - TidyFactor Next.js - Architecture Pipeline - - - - - - -
-
- -
-
-
🔒 Zero Data Leak Guarantee
-

Fail-Closed Tenant Isolation Pipeline

-
- -
-
-
1
-
🌐
-
Incoming Request
-
Subdomain / Custom Domain / Auth Header
-
- -
-
2
-
🛡️
-
Edge Middleware
-
Fail-closed resolution (404/403 on error)
-
- -
-
3
-
📦
-
Tenant Context
-
Verified tenant_id & role in JWT claims
-
- -
-
4
-
⚡
-
App Router
-
React 19 RSC & Server Actions
-
- -
-
5
-
🔒
-
Postgres RLS
-
Hard DB boundary via auth.jwt()
-
- -
-
6
-
✅
-
Isolated Data
-
Zero cross-tenant contamination
-
-
-
- - diff --git a/dist/tidyfactor-next/assets/demo-architecture.png b/dist/tidyfactor-next/assets/demo-architecture.png deleted file mode 100644 index eaaf5cb..0000000 Binary files a/dist/tidyfactor-next/assets/demo-architecture.png and /dev/null differ diff --git a/dist/tidyfactor-next/assets/demo-hero-dark.html b/dist/tidyfactor-next/assets/demo-hero-dark.html deleted file mode 100644 index 834d525..0000000 --- a/dist/tidyfactor-next/assets/demo-hero-dark.html +++ /dev/null @@ -1,339 +0,0 @@ - - - - - TidyFactor Next.js - Demo Hero - - - - - - -
-
- -
-
- - MULTI-TENANT SAAS • ARCHITECTURE ENGINE FOR AI AGENTS • NEXT.JS 16 + REACT 19 -
- -

- TidyFactor Next.js
- An Engineering System for Multi-Tenant SaaS -

- -

- With bulletproof Postgres RLS data isolation, fail-closed edge tenant resolution, and an evidence-based dual performance engine for AI coding agents. -

- -
-
Architectural Guide →
-
Download .skill Package
-
GitHub Repository ↗
-
NPM Package ↗
-
- -
-
-
-
-
-
-
-
bash — AI Agent Quick-Install Command
-
-
-
-
- $ - npx @tidyfactor/cli-next add-skill -
-
Copy
-
-
- -
-
-
- >_ Agent Slash Commands & Fast-Track Execution -
-
15 Operational Commands
-
- -
-
$/brief0. Discovery
-
$/init1. Scaffold
-
$/tenant1. Edge
-
$/rls2. Security
-
$/auth2. JWT
- -
$/data3. Schema
-
$/storage3. Buckets
-
$/api4. Routes
-
$/app4. React 19
-
$/test5. QA
- -
$/observe5. Logs
-
$/deploy6. CI/CD
-
$/perf6. Perf
-
$/incident7. Runbook
-
$/audit7. Compliance
-
-
-
- - diff --git a/dist/tidyfactor-next/assets/demo-hero-dark.png b/dist/tidyfactor-next/assets/demo-hero-dark.png deleted file mode 100644 index 92b1744..0000000 Binary files a/dist/tidyfactor-next/assets/demo-hero-dark.png and /dev/null differ diff --git a/dist/tidyfactor-next/assets/demo-hero-light.html b/dist/tidyfactor-next/assets/demo-hero-light.html deleted file mode 100644 index e84d512..0000000 --- a/dist/tidyfactor-next/assets/demo-hero-light.html +++ /dev/null @@ -1,319 +0,0 @@ - - - - - TidyFactor Next.js - Light Demo - - - - - - -
-
- -
-
- - MULTI-TENANT SAAS • ARCHITECTURE ENGINE FOR AI AGENTS • NEXT.JS 16 + REACT 19 -
- -

- TidyFactor Next.js
- An Engineering System for Multi-Tenant SaaS -

- -

- With bulletproof Postgres RLS data isolation, fail-closed edge tenant resolution, and an evidence-based dual performance engine for AI coding agents. -

- -
-
Architectural Guide →
-
Download .skill Package
-
GitHub Repository ↗
-
NPM Package ↗
-
- -
-
-
-
-
-
-
-
bash — AI Agent Quick-Install Command
-
-
-
-
- $ - npx @tidyfactor/cli-next add-skill -
-
Copy
-
-
- -
-
-
- >_ Agent Slash Commands & Fast-Track Execution -
-
15 Operational Commands
-
- -
-
$/brief0. Discovery
-
$/init1. Scaffold
-
$/tenant1. Edge
-
$/rls2. Security
-
$/auth2. JWT
- -
$/data3. Schema
-
$/storage3. Buckets
-
$/api4. Routes
-
$/app4. React 19
-
$/test5. QA
- -
$/observe5. Logs
-
$/deploy6. CI/CD
-
$/perf6. Perf
-
$/incident7. Runbook
-
$/audit7. Compliance
-
-
-
- - diff --git a/dist/tidyfactor-next/assets/demo-hero-light.png b/dist/tidyfactor-next/assets/demo-hero-light.png deleted file mode 100644 index b93de97..0000000 Binary files a/dist/tidyfactor-next/assets/demo-hero-light.png and /dev/null differ diff --git a/dist/tidyfactor-next/assets/github-social-preview.html b/dist/tidyfactor-next/assets/github-social-preview.html deleted file mode 100644 index 7519cfc..0000000 --- a/dist/tidyfactor-next/assets/github-social-preview.html +++ /dev/null @@ -1,405 +0,0 @@ - - - - - TidyFactor Next.js - Social Preview - - - - - - -
-
-
-
- -
-
-
-
-
- - TidyFactor Ecosystem -
- v1.3.0 RELEASE -
- -
-

TidyFactor Next.js

-

Production-grade Multi-Tenant SaaS architecture, locked Postgres RLS data isolation & dual performance engine for AI coding agents.

-
- -
-
- - Locked Postgres RLS -
-
- - Next.js 16 & React 19 -
-
- - Fail-Closed Edge Auth -
-
- - Dual Perf Engine (8-Tier + 6 Models) -
-
-
- - -
- - -
-
-
-
-
-
-
-
-
-
tenant-isolation-policy.sql
-
🔒 RLS ENFORCED
-
-
- -- Strict fail-closed tenant boundary
- ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;

- CREATE POLICY "org_tenant_isolation"
-   ON organizations FOR ALL
-   USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid)
-   WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid); -
-
- -
-
- $ - npx @tidyfactor/cli-next add-skill -
-
⚡ INSTANT INJECT
-
-
-
-
- - diff --git a/dist/tidyfactor-next/assets/github-social-preview.png b/dist/tidyfactor-next/assets/github-social-preview.png deleted file mode 100644 index 834de46..0000000 Binary files a/dist/tidyfactor-next/assets/github-social-preview.png and /dev/null differ diff --git a/dist/tidyfactor-next/assets/hero-banner.png b/dist/tidyfactor-next/assets/hero-banner.png deleted file mode 100644 index 4054a5c..0000000 Binary files a/dist/tidyfactor-next/assets/hero-banner.png and /dev/null differ diff --git a/dist/tidyfactor-next/assets/og-default.png b/dist/tidyfactor-next/assets/og-default.png deleted file mode 100644 index 834de46..0000000 Binary files a/dist/tidyfactor-next/assets/og-default.png and /dev/null differ diff --git a/dist/tidyfactor-next/bin/add-skill.js b/dist/tidyfactor-next/bin/add-skill.js deleted file mode 100644 index 9785d07..0000000 --- a/dist/tidyfactor-next/bin/add-skill.js +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env node -/** - * bin/add-skill.js — Multi-Agent Skill Installer Wrapper for tidyfactor-next - * Supports Trae, Cursor, Windsurf, Antigravity, GitHub Copilot, RooCode, OpenCode, KiloCode, Warp, and Universal. - * - * @license Apache-2.0 - */ - -const fs = require('fs'); -const path = require('path'); -const os = require('os'); - -const targetDir = process.cwd(); -const skillSource = path.resolve(__dirname, '..'); -const skillName = 'tidyfactor-next'; - -const AGENT_MAP = [ - { name: 'Trae AI IDE', dir: path.join(targetDir, '.trae', 'skills', skillName), test: path.join(targetDir, '.trae') }, - { name: 'Cursor IDE', dir: path.join(targetDir, '.cursor', 'skills', skillName), test: path.join(targetDir, '.cursor') }, - { name: 'Windsurf Cascade', dir: path.join(targetDir, '.windsurf', 'skills', skillName), test: path.join(targetDir, '.windsurf') }, - { name: 'GitHub Copilot', dir: path.join(targetDir, '.github', 'prompts', skillName), test: path.join(targetDir, '.github') }, - { name: 'RooCode', dir: path.join(targetDir, '.roo', 'skills', skillName), test: path.join(targetDir, '.roo') }, - { name: 'OpenCode / Zen', dir: path.join(targetDir, '.opencode', 'skills', skillName), test: path.join(targetDir, '.opencode') }, - { name: 'KiloCode', dir: path.join(targetDir, '.kilocode', 'skills', skillName), test: path.join(targetDir, '.kilocode') }, - { name: 'Warp Terminal', dir: path.join(targetDir, '.warp', 'skills', skillName), test: path.join(targetDir, '.warp') }, - { name: 'Kiro Spec IDE', dir: path.join(targetDir, '.kiro', 'skills', skillName), test: path.join(targetDir, '.kiro') }, - { name: 'Claude Code', dir: path.join(targetDir, '.claude', 'skills', skillName), test: path.join(targetDir, '.claude') }, - { name: 'Zed AI Agent', dir: path.join(targetDir, '.zed', 'skills', skillName), test: path.join(targetDir, '.zed') }, - { name: 'Google Antigravity/Gemini', dir: path.join(targetDir, '.agents', 'skills', skillName), test: path.join(targetDir, '.agents') }, -]; - -function copyRecursive(src, dest) { - fs.mkdirSync(dest, { recursive: true }); - const entries = fs.readdirSync(src, { withFileTypes: true }); - for (const entry of entries) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, entry.name); - if (['.git', 'node_modules', 'dist'].includes(entry.name)) continue; - if (entry.isDirectory()) { - copyRecursive(srcPath, destPath); - } else { - fs.copyFileSync(srcPath, destPath); - } - } -} - -// Determine installation targets -let mountedTargets = []; - -for (const agent of AGENT_MAP) { - if (fs.existsSync(agent.test)) { - copyRecursive(skillSource, agent.dir); - mountedTargets.push(agent.name + ' (' + path.relative(targetDir, agent.dir) + ')'); - } -} - -// Always ensure universal fallback in .agents/skills/ -const defaultDir = path.join(targetDir, '.agents', 'skills', skillName); -copyRecursive(skillSource, defaultDir); -if (!mountedTargets.some(t => t.includes('.agents'))) { - mountedTargets.push('Universal Default (.agents/skills/' + skillName + ')'); -} - -console.log('✨ Successfully injected ' + skillName + ' into:'); -mountedTargets.forEach(t => console.log(' • ' + t)); diff --git a/dist/tidyfactor-next/bin/create-kit.js b/dist/tidyfactor-next/bin/create-kit.js deleted file mode 100644 index fc1e698..0000000 --- a/dist/tidyfactor-next/bin/create-kit.js +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); -const readline = require('readline'); - -/* Lightweight Zero-Dependency ANSI formatting */ -const chalk = { - cyan: (str) => `\x1b[36m${str}\x1b[0m`, - green: (str) => `\x1b[32m${str}\x1b[0m`, - yellow: (str) => `\x1b[33m${str}\x1b[0m`, - red: (str) => `\x1b[31m${str}\x1b[0m`, - bold: (str) => `\x1b[1m${str}\x1b[0m`, - dim: (str) => `\x1b[2m${str}\x1b[0m`, -}; - -const PACKAGE_ROOT = path.resolve(__dirname, '..'); -const pkg = require(path.join(PACKAGE_ROOT, 'package.json')); - -console.log(chalk.bold(chalk.cyan(`\n======================================================`))); -console.log(chalk.bold(chalk.cyan(` TidyFactor Next.js SaaS Engine — CLI Setup (v${pkg.version})`))); -console.log(chalk.bold(chalk.cyan(`======================================================\n`))); - -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); - -const ask = (query, defaultVal) => - new Promise((resolve) => { - rl.question(chalk.yellow(`${query} `) + (defaultVal ? chalk.dim(`[${defaultVal}]: `) : ''), (answer) => { - resolve(answer.trim() || defaultVal); - }); - }); - -async function main() { - const targetDirInput = await ask('1. Target Directory to initialize Next.js SaaS architecture:', './'); - const targetDir = path.resolve(process.cwd(), targetDirInput); - - console.log(chalk.cyan('\nSelect Pluggable Query Layer:')); - console.log(' 1) Supabase JS Client + Raw SQL / RLS'); - console.log(' 2) Drizzle ORM + Supabase Postgres'); - console.log(' 3) Prisma ORM + Supabase Postgres'); - const queryChoice = await ask('Select query layer (1-3):', '1'); - - console.log(chalk.cyan('\nSelect Tenant Resolution Strategy:')); - console.log(' 1) Subdomain (e.g., tenant.app.com)'); - console.log(' 2) Custom Domain (e.g., custom.com)'); - console.log(' 3) Path Prefix (e.g., app.com/tenant)'); - console.log(' 4) Session Claim (Supabase Auth JWT)'); - const tenantChoice = await ask('Select resolution strategy (1-4):', '4'); - - console.log(chalk.cyan('\nSelect Role Model:')); - console.log(' 1) Fixed Roles (Owner, Admin, Member)'); - console.log(' 2) Custom RBAC (Role-Permissions mapping table)'); - console.log(' 3) Attribute-Based Access Control (ABAC)'); - const roleChoice = await ask('Select role model (1-3):', '1'); - - console.log(chalk.green(`\nInitializing TidyFactor Next.js SaaS Architecture in: ${targetDir}...`)); - - // Copy skill to target directory .agents/skills/tidyfactor-next - const skillDestDir = path.join(targetDir, '.agents', 'skills', 'tidyfactor-next'); - fs.mkdirSync(skillDestDir, { recursive: true }); - - const filesToCopy = ['SKILL.md', 'package.json', 'README.md', 'README.ar.md', 'LICENSE', 'brand.json', '.tidyfactor', 'AGENTS.md', 'SKILL-REGISTRY.md', 'VISION.md']; - for (const f of filesToCopy) { - const srcFile = path.join(PACKAGE_ROOT, f); - if (fs.existsSync(srcFile)) { - fs.copyFileSync(srcFile, path.join(skillDestDir, f)); - } - } - - // Copy references recursively - const copyDir = (src, dest) => { - fs.mkdirSync(dest, { recursive: true }); - for (const item of fs.readdirSync(src)) { - const srcItem = path.join(src, item); - const destItem = path.join(dest, item); - if (fs.statSync(srcItem).isDirectory()) { - copyDir(srcItem, destItem); - } else { - fs.copyFileSync(srcItem, destItem); - } - } - }; - - copyDir(path.join(PACKAGE_ROOT, 'references'), path.join(skillDestDir, 'references')); - if (fs.existsSync(path.join(PACKAGE_ROOT, 'tools'))) { - copyDir(path.join(PACKAGE_ROOT, 'tools'), path.join(skillDestDir, 'tools')); - } - - console.log(chalk.bold(chalk.green('\n✅ TidyFactor Next.js Architecture Skill installed successfully!'))); - console.log(chalk.dim(`Installed at: ${skillDestDir}`)); - console.log(chalk.cyan('\n🚀 Available Slash Commands:')); - console.log(' - /next init -> Scaffold multi-tenant project & generate ARCHITECTURE.md'); - console.log(' - /next tenant -> Edge resolution, context propagation & lifecycle'); - console.log(' - /next rls -> 4-policy RLS templates & isolation leak audit'); - console.log(' - /next auth -> Supabase Auth, custom JWT hook & RBAC'); - console.log(' - /next perf audit -> 13-phase dev performance & resource audit'); - console.log(' - /next perf diagnose -> Bottleneck classification & causality models'); - console.log(' - /next perf optimize -> Safe Green-tier optimizations with DELTA benchmarks\n'); - - rl.close(); -} - -main().catch((err) => { - console.error(chalk.red(`\n❌ Error: ${err.message}`)); - rl.close(); - process.exit(1); -}); diff --git a/dist/tidyfactor-next/brand.json b/dist/tidyfactor-next/brand.json deleted file mode 100644 index 6757bd9..0000000 --- a/dist/tidyfactor-next/brand.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "TidyFactor Next.js", - "version": "1.4.0", - "schemaVersion": "brand-core-v2", - "meta": { - "product": "TidyFactor Next.js Architecture Engine", - "tagline": "Production-Grade Multi-Tenant SaaS Architecture & Security Engine", - "description": "An opinionated, production-grade architectural framework for AI Coding Agents and senior fullstack engineers. Enforces unbreakable tenant isolation on Next.js 16 and Supabase using PostgreSQL Row Level Security (RLS) as the hard security boundary, paired with an evidence-based development performance engine and Vercel-tested runtime optimization rules.", - "version": "1.3.0", - "lastUpdated": "2026-08-27" - }, - "identity": { - "logo": { - "full": "assets/logo.svg", - "fullDark": "assets/logo-dark.svg", - "mark": "assets/logo-mark.svg", - "favicon": "assets/favicon.svg", - "minClearSpace": "1x logo-mark height on all sides", - "minSizePx": 24 - }, - "socialPreview": { - "ogImage": "assets/og-default.png", - "ogDimensions": "1200x630" - } - }, - "voice": { - "tone": "architectural, security-first, deterministic, evidence-based, unyielding on tenant isolation", - "vocabulary": { - "preferred": [ - "tenant isolation", - "row level security", - "fail-closed resolution", - "custom jwt hook", - "service_role isolation", - "pluggable query layer", - "server components", - "evidence-based optimization", - "bottleneck causality", - "noise control" - ], - "banned": [ - "simple multi-tenant", - "just add where clause", - "disable rls for now", - "pass service role to client", - "generic optimization", - "turn off cache globally", - "easy fix" - ] - }, - "principles": [ - "RLS is the security boundary; application code filtering is only a query-plan hint.", - "Service-role key never reaches client bundles or public endpoints.", - "Tenant context is resolved once at the edge and passed down explicitly.", - "Performance optimization must never weaken security, auth, or tenant boundaries.", - "Audit must precede optimization; every change requires DELTA benchmark evidence." - ] - }, - "pillars": { - "1_foundation": "Multi-Tenant Scaffolding, Edge Resolution & ARCHITECTURE.md generation", - "2_security": "4-Policy RLS Patterns, Custom JWT Claims Hook & Membership Model", - "3_data": "Shared Schema with tenant_id, Pluggable Query Layer (Supabase/Drizzle/Prisma)", - "4_application": "App Router, Server Components, Server Actions & Route Handlers", - "5_quality": "Automated RLS Coverage Audits, Security Testing & Leak Diagnosis", - "6_devops_perf": "Development Performance Audit (13 Phases), Bottleneck Classification & Safe Optimizations", - "7_operations": "Fail-Closed Recovery, Disaster Runbooks & Architecture Compliance" - } -} diff --git a/dist/tidyfactor-next/package.json b/dist/tidyfactor-next/package.json deleted file mode 100644 index e327214..0000000 --- a/dist/tidyfactor-next/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "@tidyfactor/next", - "version": "1.4.0", - "description": "TidyFactor Next.js track — production-grade multi-tenant SaaS on Next.js 16, React 19, TypeScript strict, and Supabase with CDL Contextual Decision Layer", - "main": "SKILL.md", - "bin": { - "tidyfactor-next": "bin/add-skill.js", - "add-skill": "bin/add-skill.js", - "add-next-skill": "bin/add-skill.js" - }, - "keywords": [ - "tidyfactor", - "nextjs", - "nextjs16", - "react19", - "supabase", - "multi-tenant", - "saas", - "rls", - "typescript", - "ai-agents", - "antigravity", - "claude-code", - "cursor" - ], - "author": "TidyFactor (https://tidyfactor.com)", - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "git+https://github.com/TidyFactor/Next.git" - }, - "scripts": { - "validate": "python tools/validate_skill.py", - "build": "node tools/build-skill.js", - "release": "python ../tools/release_skill.py ." - }, - "publishConfig": { - "access": "public" - }, - "files": [ - ".tidyfactor", - "AGENTS.md", - "CHANGELOG.md", - "LICENSE", - "README.ar.md", - "README.de.md", - "README.es.md", - "README.fa.md", - "README.fr.md", - "README.md", - "README.pt.md", - "README.zh.md", - "SKILL.md", - "bin", - "brand.json", - "memory", - "references", - "tools" - ] -} diff --git a/dist/tidyfactor-next/references/architecture-doc-skeleton.md b/dist/tidyfactor-next/references/architecture-doc-skeleton.md deleted file mode 100644 index 9b007a9..0000000 --- a/dist/tidyfactor-next/references/architecture-doc-skeleton.md +++ /dev/null @@ -1,87 +0,0 @@ -# ARCHITECTURE.md — - -Generated by `tidyfactor-next` → `init` command. Every later command -in this track reads this file before generating any code or making any -recommendation. Keep it current — it is the single source of truth for -decisions that would otherwise drift between sessions or between commands. - -> **Rule for all commands**: If a field below is unfilled (``), -> do NOT silently decide it. Surface the gap to the developer and route back -> to `init` to fill it before proceeding. - ---- - -## Locked platform (not chosen per-project) - -- Next.js 16, App Router, React 19, TypeScript strict -- Supabase (Postgres, Auth, Storage, Edge Functions, Realtime as needed) -- Tenant isolation: shared schema, `tenant_id` + Postgres RLS - ---- - -## Chosen once — this project (filled during `init` interview) - -- **Data/query layer:** `` -- **Tenant resolution strategy:** `` -- **Auth provider + methods:** `` -- **Role model:** `` -- **Deployment target:** `` -- **Environments:** `` - ---- - -## Domain boundaries - -> List top-level business domains and their ownership scope. -> Filled during `init` based on the product the developer describes. - -``` -Domain: - Scope: - Tables: - Tenant-scoped: yes | no (if no, document why in ADR log) -``` - ---- - -## Performance context (read by `perf` command) - -> Filled as the project grows. The `perf` command reads this section before -> running any audit phase. If unfilled, `perf` will run a discovery phase first. - -- **Known bottlenecks:** `` -- **Storage strategy:** `` -- **Large media in dev tree:** `` -- **Active perf baseline:** `` -- **Last perf audit date:** `` -- **Last perf audit git commit:** `` - ---- - -## ADR log - -> Append-only. Each entry captures a significant architectural decision so it -> is never re-debated silently in a future session. - -Format: -``` -[YYYY-MM-DD] - Decision: - Alternatives considered: - Reason: - Command: -``` - ---- - -## Open risks / tech debt - -> Tracked as they are identified by commands (`audit`, `perf`, `incident`, `rls`). -> Each entry: source command, risk description, priority (P0–P3), status. - -``` -[Source: perf | rls | audit | incident] -Risk: -Priority: P0 | P1 | P2 | P3 -Status: Open | Addressed | Accepted -``` diff --git a/dist/tidyfactor-next/references/commands/api.md b/dist/tidyfactor-next/references/commands/api.md deleted file mode 100644 index 328f657..0000000 --- a/dist/tidyfactor-next/references/commands/api.md +++ /dev/null @@ -1,11 +0,0 @@ -# Command: api - -Authors type-safe App Router Route Handlers and Next.js 16 Server Actions with tenant context resolution. - -## Loads -- `references/workflows/api.md` -- `references/memory/client-server-boundaries.md` -- `references/memory/react-perf-rules.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/app.md b/dist/tidyfactor-next/references/commands/app.md deleted file mode 100644 index eafa078..0000000 --- a/dist/tidyfactor-next/references/commands/app.md +++ /dev/null @@ -1,10 +0,0 @@ -# Command: app - -Next.js 16 App Router UI engineering, Server/Client component boundaries, layouts, and loading states. - -## Loads -- `references/workflows/app.md` -- `references/memory/client-server-boundaries.md` -- `references/memory/react-perf-rules.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` diff --git a/dist/tidyfactor-next/references/commands/audit.md b/dist/tidyfactor-next/references/commands/audit.md deleted file mode 100644 index c66eb29..0000000 --- a/dist/tidyfactor-next/references/commands/audit.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: audit - -Comprehensive multi-tenant SaaS architecture audit: RLS policies, tenant leak checks, bundle performance, and Next.js 16 compliance. - -## Loads -- `references/workflows/audit.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/auth.md b/dist/tidyfactor-next/references/commands/auth.md deleted file mode 100644 index e651a80..0000000 --- a/dist/tidyfactor-next/references/commands/auth.md +++ /dev/null @@ -1,11 +0,0 @@ -# Command: auth - -Triggers: "set up auth", "add roles", "RBAC", "who can access what", "add a -new role", "protect this route by role". - -Loads: `../workflows/auth.md` + `../memory/spec.md` + `../memory/auth-patterns.md`. - -Outcome: Supabase Auth wired per the method chosen in ARCHITECTURE.md, plus a -role model whose claims match what `rls.md`'s Pattern 2 policies already -expect (`role` in the JWT, checked alongside `tenant_id`, never instead of -it). diff --git a/dist/tidyfactor-next/references/commands/brief.md b/dist/tidyfactor-next/references/commands/brief.md deleted file mode 100644 index 195d2e1..0000000 --- a/dist/tidyfactor-next/references/commands/brief.md +++ /dev/null @@ -1,12 +0,0 @@ -# Command: brief - -Discovers and aligns project baselines for Next.js multi-tenant SaaS applications using the Contextual Decision Layer (CDL). - -## Loads -- `references/workflows/brief.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` - -## Outcome -A confirmed `.tidyfactor/next-brief.md` file capturing query layer, tenant resolution, auth model, storage security, and depth. diff --git a/dist/tidyfactor-next/references/commands/data.md b/dist/tidyfactor-next/references/commands/data.md deleted file mode 100644 index b9275b3..0000000 --- a/dist/tidyfactor-next/references/commands/data.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: data - -Schema modeling, SQL migrations, relations, and multi-tenant data constraints. - -## Loads -- `references/workflows/data.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/deploy.md b/dist/tidyfactor-next/references/commands/deploy.md deleted file mode 100644 index cb047ad..0000000 --- a/dist/tidyfactor-next/references/commands/deploy.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: deploy - -CI/CD automation, production environment setup, Supabase migration pipelines, and zero-downtime deployment. - -## Loads -- `references/workflows/deploy.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/incident.md b/dist/tidyfactor-next/references/commands/incident.md deleted file mode 100644 index b4b2b94..0000000 --- a/dist/tidyfactor-next/references/commands/incident.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: incident - -Incident diagnosis, disaster recovery runbooks, and tenant isolation leak remediation. - -## Loads -- `references/workflows/incident.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/init.md b/dist/tidyfactor-next/references/commands/init.md deleted file mode 100644 index ffd303b..0000000 --- a/dist/tidyfactor-next/references/commands/init.md +++ /dev/null @@ -1,10 +0,0 @@ -# Command: init - -Triggers: "start a new SaaS project", "scaffold a multi-tenant app", "set up -tidyfactor-next", "init". - -Loads: `../workflows/init.md` + `../memory/spec.md` + `../architecture-doc-skeleton.md`. - -Outcome: a running Next.js 16 + Supabase project with tenant isolation wired -in from commit one, and a filled-in `ARCHITECTURE.md` recording every -per-project choice so later commands don't re-ask. diff --git a/dist/tidyfactor-next/references/commands/observe.md b/dist/tidyfactor-next/references/commands/observe.md deleted file mode 100644 index b1463fc..0000000 --- a/dist/tidyfactor-next/references/commands/observe.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: observe - -Observability, structured logging, audit trails, and health-check monitoring for multi-tenant SaaS. - -## Loads -- `references/workflows/observe.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/perf.md b/dist/tidyfactor-next/references/commands/perf.md deleted file mode 100644 index 9878902..0000000 --- a/dist/tidyfactor-next/references/commands/perf.md +++ /dev/null @@ -1,136 +0,0 @@ -# Command: perf - -Runtime dispatcher for Development Performance & Resource Optimization — bottleneck diagnosis, evidence-based safe optimization, and formal benchmarking for Next.js SaaS projects. - ---- - -## Session Gate (Before ANY Phase) - -> **Read `../memory/spec.md` once per session before this command does any work.** -> It is the canonical rule set every command in this track enforces. -> The `perf` command is subordinate to the SaaS architecture contract defined there. -> Do not silently deviate from it — if an optimization seems to require deviation, surface it explicitly. - -**Then read the project's `ARCHITECTURE.md` (generated from `references/architecture-doc-skeleton.md`):** - -``` -Does ARCHITECTURE.md exist? - ├── YES → Read the "Performance context" section: - │ - Known bottlenecks (pre-existing diagnosis) - │ - Storage strategy (project filesystem vs. Supabase Storage / S3) - │ - Active perf baseline (link to last audit, if any) - │ - Last perf audit date + git commit - │ → Skip re-discovery work already documented there - │ → Use last audit as baseline if it exists and is current - │ - └── NO → Proceed, but note: - "ARCHITECTURE.md not found. Running full discovery (Phase 1). - Consider running `init` to scaffold it after this audit." -``` - -**If `ARCHITECTURE.md` has unfilled `` fields in the perf context section:** -Do not silently assume. State the gap and ask the developer to fill it before proceeding with optimization (not before auditing — a read-only audit can proceed without it). - ---- - -## Phase 0 — Intent & Mode Detection (MANDATORY SECOND GATE) - -**Before any analysis, identify the mode from the user's request:** - -| User Intent | Detected Mode | Workflow to Load | -|---|---|---| -| "perf audit", "audit performance", "audit dev performance", "تدقيق الأداء" | `AUDIT` | `../workflows/audit-dev-perf.md` | -| "what is slow", "why is dev server slow", "diagnose bottleneck", "بطيء", "ما المشكلة" | `DIAGNOSE` | `../workflows/diagnose-dev-bottleneck.md` | -| "apply safe perf", "optimize imports", "optimize deps", "clean up packages", "طبّق التحسينات" | `OPTIMIZE` | `../workflows/apply-safe-perf.md` | -| "benchmark build", "measure startup", "measure HMR", "time the build", "قياس الأداء" | `BENCHMARK` | `../workflows/benchmark-perf.md` | -| "show perf report", "perf status", "last audit results", "تقرير الأداء" | `REPORT` | See Report Mode below | - -**Critical rule enforced by this command:** -``` -audit ≠ optimize - -If the user says "the machine is slow" or "dev is slow": -→ Do NOT start modifying next.config.js -→ Start with DIAGNOSE mode: - What is slow? - When is it slow? - - Dev server startup? - - HMR rebuild? - - Production build? - - Type checking? - - Linting? - - IDE responsiveness? - - Disk active time? - - RAM pressure? -``` - ---- - -## Report Mode — Staleness Check - -When mode is `REPORT`, do NOT blindly show a cached result: - -``` -Existing audit report found? - ├── YES → Inspect: - │ - Audit Timestamp vs current date - │ - Git commit at audit time vs current HEAD (if git available) - │ - Working tree dirty? (uncommitted changes since audit?) - │ - node_modules changed? (lockfile modified after audit?) - │ ───────────────────────────────────────────────── - │ If report is < 24h old AND no significant project state change: - │ → Present existing report with staleness label: [CURRENT] - │ If report is stale OR project state changed: - │ → State: "Report is stale. Running lightweight audit." - │ → Run Phase 1–3 of audit-dev-perf.md (discovery + baseline + dep graph only) - │ - └── NO → State: "No existing audit found. Running lightweight audit." - → Run Phase 1–3 of audit-dev-perf.md -``` - -**Every report output must include a header:** -``` -Audit Report — [Project Name] -Generated: [ISO timestamp] -Git Commit: [SHA] or "git not available" -Tree State: Clean / Dirty (X uncommitted changes) -Status: CURRENT | STALE | PARTIAL (lightweight) -``` - ---- - -## What It Loads - -**Always loaded with this command:** -- `../memory/perf-optimization-rules.md` — 14-phase diagnostic anchors, bottleneck models, 120-pt scoring rubric -- `../memory/react-perf-rules.md` — 8-tier prioritized React 19 / Next.js 16 runtime performance catalog -- `../memory/safe-optimizations-catalog.md` — Green / Yellow / Red taxonomy + SaaS Safety Boundary - -**Loaded based on mode:** -- `AUDIT` / `DIAGNOSE`: also load `../memory/dependency-optimization.md` + `../memory/client-server-boundaries.md` + `../memory/cache-storage-rules.md` -- `OPTIMIZE`: also load `../memory/dependency-optimization.md` + `../memory/cache-storage-rules.md` -- `BENCHMARK`: no additional memory files - ---- - -## What It Does NOT Load - -- Do NOT load `../memory/rls-patterns.md` (RLS authoring is strictly `rls` command scope). -- Do NOT load `../memory/auth-patterns.md` (authentication is strictly `auth` command scope). -- Do NOT load `../memory/spec.md` unless a SaaS Safety Boundary check is needed (then read the boundary rules only, not the full tenant lifecycle spec). -- Do NOT route `perf` to the `rls`, `auth`, or `tenant` commands. Performance optimization operates entirely within project tooling and dependency scope — it does not modify security, RLS, or tenant architecture. - ---- - -## SaaS Safety Boundary (Non-Negotiable) - -Before any optimization is applied, verify it does not touch: -- Tenant Isolation model -- RLS policies -- RBAC / ABAC authorization -- Authentication flows -- Server-side secrets containment -- API security boundaries -- CSRF / XSS protections - -If a proposed optimization crosses this boundary, it is immediately reclassified to 🔴 Red and presented as a manual architectural recommendation only. diff --git a/dist/tidyfactor-next/references/commands/rls.md b/dist/tidyfactor-next/references/commands/rls.md deleted file mode 100644 index bbf7fec..0000000 --- a/dist/tidyfactor-next/references/commands/rls.md +++ /dev/null @@ -1,10 +0,0 @@ -# Command: rls - -Triggers: "add RLS to this table", "write the isolation policies", "audit RLS -coverage", "why is this tenant seeing another tenant's data" (isolation-leak -debugging). - -Loads: `../workflows/rls.md` + `../memory/spec.md` + `../memory/rls-patterns.md`. - -Outcome: every tenant-scoped table has RLS enabled with policies matching the -patterns in `../memory/rls-patterns.md`, and a coverage audit query confirms no gaps. diff --git a/dist/tidyfactor-next/references/commands/storage.md b/dist/tidyfactor-next/references/commands/storage.md deleted file mode 100644 index 5a85b17..0000000 --- a/dist/tidyfactor-next/references/commands/storage.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: storage - -Configures tenant-scoped Supabase Storage buckets, RLS storage policies, and upload handlers. - -## Loads -- `references/workflows/storage.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/commands/tenant.md b/dist/tidyfactor-next/references/commands/tenant.md deleted file mode 100644 index 943cd61..0000000 --- a/dist/tidyfactor-next/references/commands/tenant.md +++ /dev/null @@ -1,10 +0,0 @@ -# Command: tenant - -Triggers: "add tenant resolution", "build the tenant context", "tenant -lifecycle", "onboard a new tenant", "tenant-aware service". - -Loads: `../workflows/tenant.md` + `../memory/spec.md`. - -Outcome: tenant resolution, context propagation, and lifecycle (create / -suspend / delete) implemented per the strategy locked in ARCHITECTURE.md — -never re-deciding the resolution strategy per feature. diff --git a/dist/tidyfactor-next/references/commands/test.md b/dist/tidyfactor-next/references/commands/test.md deleted file mode 100644 index 4cc0567..0000000 --- a/dist/tidyfactor-next/references/commands/test.md +++ /dev/null @@ -1,9 +0,0 @@ -# Command: test - -Multi-tenant test suite engineering: RLS isolation tests, Vitest unit tests, and Playwright E2E. - -## Loads -- `references/workflows/test.md` -- `references/memory/decision-points.md` -- `references/memory/quality-bar.md` -- `references/memory/spec.md` diff --git a/dist/tidyfactor-next/references/memory/auth-patterns.md b/dist/tidyfactor-next/references/memory/auth-patterns.md deleted file mode 100644 index f900f84..0000000 --- a/dist/tidyfactor-next/references/memory/auth-patterns.md +++ /dev/null @@ -1,123 +0,0 @@ -# Auth Patterns - -Operational patterns for the `auth` command. Templates, not narrative. - -## Membership model (all role models sit on top of this) - -A user's relationship to a tenant is its own row, not a column on `users`. -One person can belong to multiple tenants with different roles in each. - -```sql -create table public.tenant_memberships ( - id uuid primary key default gen_random_uuid(), - tenant_id uuid not null references public.tenants(id) on delete cascade, - user_id uuid not null references auth.users(id) on delete cascade, - role text not null default 'member', - created_at timestamptz not null default now(), - unique (tenant_id, user_id) -); - -alter table public.tenant_memberships enable row level security; - -create policy "memberships_self_select" - on public.tenant_memberships for select - using (user_id = auth.uid()); -``` - -`tenant_memberships` is itself tenant-scoped data — it gets RLS via the same -Pattern 1 rules in `rls-patterns.md`, not a special case. - -## Getting `tenant_id` and `role` into the JWT - -Supabase Auth supports a Custom Access Token Hook (Postgres function invoked -at token issuance) to inject custom claims. This is the mechanism — do not -have client code separately fetch role/tenant and pass it around as -"trusted" data; only the JWT claim, set server-side by the hook, is trusted -by RLS policies. - -```sql -create or replace function public.custom_access_token_hook(event jsonb) -returns jsonb -language plpgsql -stable -as $$ -declare - claims jsonb; - membership record; -begin - claims := event->'claims'; - -- Active tenant resolved by the request (see tenant.md's edge resolution); - -- passed in via a session variable or looked up by user_id + active tenant. - select tenant_id, role into membership - from public.tenant_memberships - where user_id = (event->>'user_id')::uuid - limit 1; -- single-tenant-per-session assumption; see "Multi-tenant users" below - - if membership is not null then - claims := jsonb_set(claims, '{tenant_id}', to_jsonb(membership.tenant_id)); - claims := jsonb_set(claims, '{role}', to_jsonb(membership.role)); - end if; - - event := jsonb_set(event, '{claims}', claims); - return event; -end; -$$; -``` - -Register this in the Supabase project's Auth hook config, not just as a -loose function — an unregistered hook function silently does nothing and the -RLS policies expecting `role`/`tenant_id` claims will fail closed (safe, but -confusing to debug — check hook registration first when claims are missing). - -## Multi-tenant users (a user belonging to more than one tenant) - -The hook above picks one membership arbitrarily via `limit 1` — that's a -placeholder, not a real strategy. Pick one explicitly: - -- **Active-tenant switcher**: session carries an explicit "active tenant" - selection (cookie or user preference), hook looks up that specific - membership. Requires a token refresh on tenant switch — plan the UX for - that latency, don't silently swap tenant context mid-session without one. -- **Single-tenant-per-account**: simplest, disallow a user joining a second - tenant. Fine for consumer-ish SaaS; wrong for agency/consultant use cases - where one person legitimately works across tenants. - -Document which one the project uses in ARCHITECTURE.md — this is an ADR-log -entry, not a default to leave implicit. - -## Role model options - -- **Fixed roles** (`owner`, `admin`, `member`): role is a plain text column, - checked directly in RLS policies per Pattern 2. Simplest; fine when - permissions don't need per-resource granularity. -- **Custom RBAC** (roles map to a permissions table): add a - `role_permissions (role text, permission text)` table; RLS policies check - `exists (select 1 from role_permissions where role = (auth.jwt()->>'role') and permission = '')` - instead of a raw role-name comparison. Use when the same role needs - different permissions across tenants (e.g. a tenant customizing what - "admin" can do). -- **ABAC** (attribute-based): claims carry multiple attributes (department, - seniority, resource tags) and policies evaluate combinations. Only justify - this when fixed roles or RBAC have already proven insufficient — it's - materially harder to audit for isolation leaks, since the policy logic - itself grows the attack surface described in spec.md. - -## Route/UI-level checks are UX, not the security boundary - -Hiding a button or redirecting an unauthorized route is a UX convenience. -The RLS policy is what actually stops the read/write. Never build a -role-gated route/component without the matching RLS policy already in place -— an app-only check is bypassable by anyone calling the API/Supabase client -directly. - -## Validation checklist (used by `auth` command) - -- [ ] `tenant_memberships` table exists, RLS-enabled, unique on `(tenant_id, user_id)` -- [ ] Custom access token hook is registered in the Supabase project config, - not just defined as a loose function -- [ ] Multi-tenant-user strategy is explicit and documented in ARCHITECTURE.md - (not left as the placeholder `limit 1`) -- [ ] Every role-gated UI element has a matching RLS policy — spot-check by - calling the underlying table directly as a lower-privileged role -- [ ] Token refresh is triggered on role/tenant change (role changes don't - take effect on a stale JWT until refresh) diff --git a/dist/tidyfactor-next/references/memory/cache-storage-rules.md b/dist/tidyfactor-next/references/memory/cache-storage-rules.md deleted file mode 100644 index c431e0b..0000000 --- a/dist/tidyfactor-next/references/memory/cache-storage-rules.md +++ /dev/null @@ -1,214 +0,0 @@ -# Memory: cache-storage-rules - -Operational reference for cache scope analysis, watch boundary auditing, and the strict separation of Git hygiene from development tooling hygiene. Used in Phases 7, 8, and 9 of `../workflows/audit-dev-perf.md`. - ---- - -## Critical Conceptual Separation - -### Git Hygiene vs Dev Tooling Hygiene — Independent Scopes - -These are NOT the same. Each controls a completely different system: - -| Config | System It Controls | What Happens If Misconfigured | -|---|---|---| -| `.gitignore` | Git version control | Files accidentally committed; repo bloat | -| `tsconfig.json exclude` | TypeScript compiler & language server | TS analyzes unnecessary files; slow typecheck & IDE | -| `next.config watchOptions.ignored` | Next.js file watcher (chokidar) | Unnecessary HMR invalidations; high disk I/O | -| `next.config pageExtensions` | Next.js page resolution | Non-page files treated as routes | -| `.eslintignore` / `eslint.config ignores` | ESLint | Unnecessary files linted; slow lint pass | - -**The educational anchor rule:** -> `.next/` in `.gitignore` does NOT prevent Next.js from using it. -> `.next/` in `tsconfig exclude` prevents TypeScript from analyzing it. -> These are independent scopes and must be configured separately. - ---- - -## Git Hygiene Audit Checklist - -Inspect `.gitignore` for missing entries: - -``` -Should be in .gitignore: - ✓ .next/ - ✓ node_modules/ - ✓ .env.local - ✓ .env.*.local - ✓ .turbo/ - ✓ .eslintcache - ✓ tsconfig.tsbuildinfo - ✓ *.tsbuildinfo - -Common omissions in SaaS/LMS projects: - ? dist/ - ? out/ - ? .vercel/ - ? coverage/ - ? playwright-report/ - ? test-results/ - ? uploads/ (if user uploads stored locally — ideally moved to object storage) - ? logs/*.log - ? *.export.csv - ? *.export.json (if bulk data exports generated locally) -``` - ---- - -## Dev Tooling Hygiene Audit Checklist - -### TypeScript (`tsconfig.json`) - -Directories that should be in `exclude` but are often missing: - -```json -{ - "exclude": [ - "node_modules", - ".next", - "dist", - "out", - ".turbo", - "coverage", - "playwright-report", - "supabase/functions", // Edge Functions have their own tsconfig - "scripts", // If build scripts use different tsconfig - "**/*.test.ts", // Only if tests have separate tsconfig - "**/*.spec.ts" - ] -} -``` - -`include` should list only actual source directories, not the entire project root: - -```json -// Bad (analyzes everything): -{ "include": ["**/*"] } -{ "include": ["."] } - -// Good (analyzes only source): -{ "include": ["app", "components", "lib", "hooks", "types", "utils"] } -``` - -### Next.js File Watcher (`next.config.js`) - -```javascript -// next.config.js -module.exports = { - // Add watchOptions if large non-source directories exist in project tree - webpack: (config) => { - config.watchOptions = { - ignored: [ - '**/node_modules/**', - '**/.next/**', - '**/public/uploads/**', // If user uploads stored locally - '**/public/videos/**', // If video assets stored locally - '**/public/generated/**', // If AI or tool outputs stored here - '**/logs/**', // Application logs - '**/backups/**', // Database backups - '**/exports/**', // Bulk data exports - ] - } - return config - } -} -``` - ---- - -## Cache & Storage Analysis - -### Cache Size Benchmarks - -| Condition | .next/cache : source ratio | Assessment | -|---|---|---| -| Healthy | < 3:1 | Normal operation | -| Watch | 3:1 – 10:1 | Acceptable; older caches accumulating | -| Needs attention | 10:1 – 50:1 | Clear cache; investigate cache invalidation patterns | -| Problem | > 50:1 | Cache not being evicted; storage pressure | - -### Cache Trade-Off Model - -``` -MORE caching: - → Less rebuild work (CPU savings) - → More RAM used (module cache in memory) - → More disk space used (.next/cache) - → More disk I/O (reading cache on each startup) - -LESS caching: - → More rebuild work (CPU increase) - → Less RAM used - → Less disk space - → Slower HMR rebuilds - -Recommendation: Always depends on the PRIMARY BOTTLENECK. - RAM-constrained machine → reduce in-memory cache via --max-old-space-size - Disk I/O constrained (HDD) → NVMe upgrade beats cache tuning - CPU-constrained → maximize cache to avoid recomputation -``` - -**DO NOT disable `.next/cache` as a general optimization. It always increases rebuild work.** - ---- - -## Watch Boundary Audit — Target Patterns - -Inspect the project directory tree for these high-risk patterns, especially in SaaS/LMS projects: - -``` -HIGH RISK (watch boundary violation): - project/ - ├── public/ - │ ├── uploads/ ← user-uploaded files (images, documents, avatars) - │ ├── videos/ ← course videos, webinar recordings - │ └── generated/ ← AI-generated outputs, exported PDFs, processed images - ├── exports/ ← bulk data exports (CSV, Excel, JSON) - ├── backups/ ← database backups, snapshot files - ├── logs/ ← application log files - └── scripts/generated/ ← code generation outputs - -MEDIUM RISK: - ├── prisma/migrations/ ← SQL migration files (many of them over time) - └── supabase/migrations/ ← Supabase migration files -``` - -**Impact calculation:** -- 1,000 files in `public/uploads/` → 1,000 extra inotify/fs watch events to manage -- On HDD: each metadata stat() call is slow -- TypeScript language server may attempt to resolve type information for these files - -**Immediate action** (Green): Add to `watchOptions.ignored` in `next.config.js` -**Architectural recommendation** (present as manual): Move to `Supabase Storage / S3 / CDN` if the scale is significant - ---- - -## Architectural Escalation Template - -When `uploads/` or `videos/` inside the project tree exceed ~500 files or ~500 MB, present this escalation (never apply automatically): - -```markdown -### Architectural Recommendation: Move Media to Object Storage - -**Finding**: [X] files / [X GB] detected in `public/uploads/` inside the project filesystem. - -**Current Architecture**: - Browser → Next.js Server → Project Filesystem - -**Recommended Architecture**: - Browser → Next.js Server → Supabase Storage (or S3 / Cloudflare R2) - -**Benefits**: - - Removes thousands of files from the development file watch boundary - - Eliminates dev startup overhead from watching media files - - Provides CDN delivery for better production performance - - Scales independently of the application server - -**Migration requires**: - - Developer and architecture team review - - File storage service setup - - Upload handler changes - - URL path migration for existing stored files - -**Risk**: NOT a safe automated change — present for team decision. -``` diff --git a/dist/tidyfactor-next/references/memory/client-server-boundaries.md b/dist/tidyfactor-next/references/memory/client-server-boundaries.md deleted file mode 100644 index 840fd7a..0000000 --- a/dist/tidyfactor-next/references/memory/client-server-boundaries.md +++ /dev/null @@ -1,152 +0,0 @@ -# Memory: client-server-boundaries - -Operational reference for Client Bundle Composition Analysis and Server/Client boundary detection in Next.js App Router projects. Used during Phase 5 of `../workflows/audit-dev-perf.md`. Findings are classified only — never automatically converted. - ---- - -## The Core Question - -> What actually reaches the browser? - -Every byte in the client bundle was sent over the network and parsed by JavaScript engine. The App Router makes it possible to keep most application logic server-side — but only if boundaries are correctly enforced. - ---- - -## Server vs Client vs Shared - -``` -Server-only execution: - - Route Handlers (app/api/) - - Server Components (default in App Router) - - Server Actions ('use server') - - Middleware (edge runtime) - -Client-only execution: - - Client Components ('use client') - - Custom hooks using React state/effects - - Browser APIs (window, document, localStorage) - -Shared (runs in both contexts): - - Utility functions without environment dependencies - - Type definitions - - Constants - - Pure data transformation functions -``` - ---- - -## High-Risk Library Categories for SaaS/LMS - -These packages should NEVER reach the client bundle. Detect and flag if imported inside a Client Component. - -| Library Category | Examples | Why It Must Be Server-Only | -|---|---|---| -| **Database clients** | `@supabase/supabase-js` (service role), Drizzle ORM, Prisma Client | Contains connection strings, bypasses RLS if service role key exposed | -| **AI SDKs (server-side calls)** | `openai`, `@anthropic-ai/sdk`, `@google/generative-ai` | Contains API keys; calls must be server-side | -| **Storage SDKs** | `@aws-sdk/client-s3`, `@google-cloud/storage` | Contains access credentials | -| **Email providers** | `@sendgrid/mail`, `nodemailer`, `resend` | Contains API keys; sending from client would expose them | -| **Server-only Next.js utilities** | `next/headers`, `next/cookies`, `server-only` | Explicitly runtime-restricted | -| **Crypto/Secrets** | `jsonwebtoken`, `bcryptjs`, `crypto` (Node.js) | Server-side security operations | - -**Supabase-specific risk**: The `supabase-js` client with `serviceRoleKey` MUST only exist on the server. The anon client with `NEXT_PUBLIC_SUPABASE_ANON_KEY` is safe for browser — but it must still go through RLS. - ---- - -## Server Leak Detection Pattern - -The most common leak pattern in Next.js App Router: - -``` -lib/db.ts (server-only) - → imports from @supabase/supabase-js with service role key - -components/Dashboard.tsx - → imports from lib/db.ts - → has 'use client' directive at top - -Result: - lib/db.ts → included in client bundle - service role key → exposed in browser network tab -``` - -**Detection method:** -1. Find all files with `'use client'` directive -2. Trace their import graph -3. Check if any imported module transitively imports a server-only package -4. Flag as HIGH RISK if confirmed - ---- - -## Large UI Libraries in Client Bundle (SaaS/LMS Hotspots) - -These are expected in client bundles but should be evaluated for size: - -| Library | Expected Size | Optimization Lever | -|---|---|---| -| **lucide-react** | 1 icon ≈ 2-4 KB; 50 icons ≈ 100-200 KB | `optimizePackageImports` (Yellow) | -| **@heroicons/react** | Similar to lucide-react | Direct icon imports | -| **recharts / chart.js** | 50-150 KB minified | Dynamic import (`next/dynamic`) | -| **Monaco Editor** | 2-5 MB | Must be dynamically imported with `ssr: false` | -| **TipTap / ProseMirror** | 200-500 KB | Dynamic import; use extension tree-shaking | -| **date-fns** | v3: 10-15 KB with tree-shaking | Direct function imports only | -| **moment** | 300+ KB (no tree-shaking) | Replace with date-fns / dayjs | -| **@tanstack/react-table** | 30-50 KB | Already tree-shakeable; fine | -| **zod** | 12 KB minified | Fine on client | - ---- - -## Findings Classification - -For every finding in Phase 5: - -| Classification | Meaning | Action | -|---|---|---| -| **Safe — Server Contained** | Package confirmed server-only; no client exposure | Document; no action needed | -| **Requires Developer Review** | Suspected leak; import chain ambiguous | Present import chain; developer verifies | -| **High Risk — Confirmed Client Leak** | Server-only package confirmed in client bundle | Flag CRITICAL; never auto-convert; present remediation path | - -**Classification rule**: Do NOT automatically convert any component. Even a "High Risk" finding only becomes an action item when the developer reviews and approves the remediation plan. - ---- - -## Remediation Patterns (Present, Do Not Apply Automatically) - -### Pattern 1 — Add `server-only` package -```typescript -// lib/db.ts -import 'server-only' // throws at build time if imported in Client Component - -import { createClient } from '@supabase/supabase-js' -// ... -``` - -### Pattern 2 — Move server logic to Server Action -```typescript -// Before: logic in Client Component making API call -// After: 'use server' action extracts the server-side operation -'use server' -export async function fetchTenantData(tenantId: string) { - // Server-only logic here -} -``` - -### Pattern 3 — Dynamic import with SSR disabled -```typescript -// For large UI-only libraries (Monaco, charts) -import dynamic from 'next/dynamic' -const MonacoEditor = dynamic(() => import('@monaco-editor/react'), { ssr: false }) -``` - -### Pattern 4 — Correct `NEXT_PUBLIC_` usage -```typescript -// Only non-secret config should be NEXT_PUBLIC_ -NEXT_PUBLIC_SUPABASE_URL=... // Safe — not a secret -NEXT_PUBLIC_SUPABASE_ANON_KEY=... // Safe — anon key, RLS controls access -SUPABASE_SERVICE_ROLE_KEY=... // NEVER NEXT_PUBLIC_ — must be server-only -``` - ---- - -## SaaS Safety Boundary (Applies to All Findings) - -Any finding involving tenant isolation, RLS enforcement, or secret key exposure is automatically CRITICAL and reclassified to 🔴 Red — not addressable by the `perf` track alone. Route to `rls` or `auth` commands as appropriate. diff --git a/dist/tidyfactor-next/references/memory/decision-points.md b/dist/tidyfactor-next/references/memory/decision-points.md deleted file mode 100644 index 4c5ec3c..0000000 --- a/dist/tidyfactor-next/references/memory/decision-points.md +++ /dev/null @@ -1,51 +0,0 @@ -# Memory: decision-points (Contextual Decision Layer — CDL v1.0) - -A thin arbitration protocol for resolving high-impact architectural and multi-tenant SaaS ambiguities before code emission. - ---- - -## 🏛️ Decision Matrix (N1–N5) - -| Code | Decision Dimension | Options (Reference SSOT) | Default Fallback | Trigger / Ambiguity Condition | -|:---:|---|---|---|---| -| **N1** | **Query & ORM Layer** | • `supabase-js` (Direct PostgREST client)
• `drizzle` (Drizzle ORM over Postgres)
• `prisma` (Prisma ORM with RLS extensions) | `supabase-js` | When prompt asks to create models, repositories, or database queries without declaring the ORM. | -| **N2** | **Tenant Resolution Mode** | • `subdomain` (`tenant.app.com`)
• `path` (`app.com/t/tenant`)
• `header` (`x-tenant-id` / API Auth) | `subdomain` | When building tenant routing, auth middleware, or API contracts. | -| **N3** | **Auth & RBAC Model** | • `supabase-auth` (Built-in Auth + metadata)
• `custom-rbac` (Dedicated `roles` and `permissions` tables)
• `abac` (Attribute-based policy matrix) | `supabase-auth` + `custom-rbac` | When designing user management, team invitations, or protected routes. | -| **N4** | **Storage & Asset Security** | • `private-tenant-buckets` (Scoped paths `tenant_id/user_id/*`)
• `signed-urls` (Short-lived signed URLs for sensitive media)
• `public-cdn` (Public assets with CDN caching) | `private-tenant-buckets` | When creating upload handlers, media libraries, or bucket policies. | -| **N5** | **Output Scope & Depth** | • `sprint-feature` (Single Route / Component / RLS Policy)
• `complete-blueprint` (Full multi-tenant architecture with migration & tests) | `sprint-feature` | When user request could mean a quick helper or a complete full-stack module. | - ---- - -## ⚡ Boolean Skip Conditions (Deterministic Bypass) - -Skip interactive elicitation and proceed silently when ANY of the following are true: -1. **Cached Brief Exists**: `.tidyfactor/next-brief.md` exists and contains confirmed decisions. -2. **Explicit User Declaration**: Prompt explicitly declares query layer, tenant resolution, and auth mode (e.g., `"Use Drizzle with subdomain tenant routing"`). -3. **Direct Command Invocation**: User invokes explicit commands (e.g. `/rls`, `/perf`, `/auth`, `/data`) with concrete specifications. -4. **Maintenance / Refactor Task**: Fixes, performance optimizations (`/perf`), or RLS leak audits (`/audit`) silently preserve existing project architecture. - ---- - -## 🎯 Single-Round Batching & Priority Overflow - -When elicitation is required: -1. **Max 3 Questions**: Ask at most 3 concise questions in a single round. -2. **Priority Order**: - $$\mathbf{N1 \text{ (Query/ORM)}} > \mathbf{N2 \text{ (Tenant Mode)}} > \mathbf{N3 \text{ (Auth/RBAC)}} > \mathbf{N4 \text{ (Storage)}} > \mathbf{N5 \text{ (Scope)}}$$ -3. **Conservative Default**: Any unasked or unanswered dimensions automatically adopt the **Default Fallback**. - ---- - -## 💾 Brief Persistence Protocol - -When `/brief` runs, save confirmed decisions to `.tidyfactor/next-brief.md`: -```markdown -# Next.js Multi-Tenant SaaS Brief -- Query Layer: [supabase-js | drizzle | prisma] -- Tenant Resolution: [subdomain | path | header] -- Auth / RBAC: [supabase-auth | custom-rbac | abac] -- Storage Security: [private-tenant-buckets | signed-urls | public-cdn] -- Scope Depth: [sprint-feature | complete-blueprint] -- Confirmed At: YYYY-MM-DD -``` -All downstream workflows read `.tidyfactor/next-brief.md` first. diff --git a/dist/tidyfactor-next/references/memory/dependency-optimization.md b/dist/tidyfactor-next/references/memory/dependency-optimization.md deleted file mode 100644 index e712b44..0000000 --- a/dist/tidyfactor-next/references/memory/dependency-optimization.md +++ /dev/null @@ -1,163 +0,0 @@ -# Memory: dependency-optimization - -Operational reference for dependency graph analysis, transitive dependency evaluation, and module surface assessment. Used during Phase 3 of `../workflows/audit-dev-perf.md`. - ---- - -## Dependency Graph Mental Model - -``` -Direct Dependencies (package.json) - ↓ -Transitive Dependencies (what each dep pulls in) - ↓ -Module Surface (total modules analyzed by bundler + TypeScript) - ↓ -Client Bundle Exposure (what actually reaches the browser) - ↓ -Build Cost (compilation + analysis time per dep) -``` - -**Key insight**: Dependency COUNT is a poor proxy for dependency COST. - -``` -50 deps with 1 heavy transitive tree - > 150 deps with clean, shallow graphs - -Example: Adding `aws-sdk` v2 (one package) pulls in 400+ modules. -Example: 120 lightweight utility packages may have <200 total modules combined. -``` - ---- - -## Analysis Dimensions - -### 1. Direct Dependencies (`package.json → dependencies`) -- List all packages in `dependencies` -- Identify any that are only used in: build scripts, config files, tests, CLI tools - - These should be in `devDependencies` -- Identify packages with zero imports in source code (candidates for removal — verify before flagging) - -### 2. Transitive Dependency Surface -- For each large or suspicious package, check total modules it pulls in -- Tools to use if available: `npm ls --all`, `pnpm why `, `npx depcheck` -- Focus on packages known for heavy transitive trees: - - AWS SDK v2 (legacy, very large) - - Firebase SDK (modular v9+ is better; v8 is monolithic) - - `moment` (large; `date-fns` or `dayjs` preferred for bundle) - - `lodash` (if not imported as `lodash/function`, pulls everything) - - Full `@mui/material` (large if not tree-shaken) - -### 3. Duplicate Package Versions -- Multiple versions of same package in lockfile → bundler bundles both -- Common with: React, TypeScript utilities, `tslib`, form libraries -- Check: `npm ls ` to see all resolved versions -- Impact: Increased bundle size; potential type mismatch errors - -### 4. CommonJS vs ESM -| Condition | Impact | -|---|---| -| Package is CJS (uses `require`) | Cannot be tree-shaken; entire package is bundled | -| Package is ESM (uses `export`) | Tree-shakeable; only imported exports included | -| Package has `"exports"` field in package.json | Modern ESM-aware; tree-shaking works | -| Package lacks `"module"` or `"exports"` field | Likely CJS; verify before assuming | - -- Check: `package.json → "type": "module"` or `"exports"` field of the dependency -- Next.js handles many CJS packages automatically, but CJS still costs more in module graph traversal - -### 5. `optimizePackageImports` Applicability Criteria - -This is a **Yellow** optimization — not a blanket switch. - -Apply ONLY when ALL of the following are true: -1. The package uses barrel exports (exports many symbols from a single `index.js`) -2. The package is imported in multiple source files -3. The package appears in Next.js's own recommended list OR has been verified to work with this setting -4. Benchmarked BEFORE and AFTER to confirm positive DELTA - -Known packages that commonly benefit: -``` -lucide-react ← icon library, 1000+ icons, barrel export -@heroicons/react ← similar to lucide-react -react-icons ← massive icon library -@radix-ui/* ← individual package imports are already optimal; skip -date-fns ← v3+ is already ESM; verify before adding -``` - -Known packages to be careful with: -``` -@mui/material ← has its own tree-shaking optimizations; may conflict -lodash ← use direct imports instead: import debounce from 'lodash/debounce' -moment ← monolithic; replace with dayjs/date-fns instead of optimizePackageImports -``` - ---- - -## Barrel Import Anti-Patterns - -### What Is a Barrel Import? -```typescript -// components/index.ts (the barrel file) -export { Button } from './Button' -export { Modal } from './Modal' -export { DataTable } from './DataTable' -// ... 50 more exports - -// Usage in source code -import { Button } from 'components' // Barrel import — pulls in entire barrel -``` - -### Why It's Costly -- Bundler must resolve the barrel → load all re-exported modules → analyze each -- Even if only `Button` is used, the bundler may load `DataTable` and `Modal` first -- In large codebases: hundreds of files × deep barrel chains = large module graph - -### Recommended Pattern -```typescript -// Direct import (tree-shakeable) -import { Button } from 'components/Button' -import { Modal } from 'components/Modal' -``` - -### When NOT to change barrel imports automatically -- Barrel files that have side effects (CSS imports, module augmentation, polyfills) -- Barrel files in third-party libraries (controlled by `optimizePackageImports`) -- Internal barrel files where the team has explicitly chosen the pattern - ---- - -## Dependency Classification Table - -Use this during Phase 3 to categorize findings: - -| Finding Type | Severity | Recommended Action | Safe to Apply | -|---|---|---|---| -| Verified unused dep in `dependencies` | HIGH | Remove after grep verification | 🟢 Green (post-verification) | -| Runtime dep classified as `dependencies` but build-only | MEDIUM | Move to `devDependencies` | 🟢 Green | -| Duplicate package versions in lockfile | MEDIUM | `npm dedupe` / `pnpm dedupe` | 🟡 Yellow (verify types match) | -| Large CJS dep without ESM alternative | MEDIUM | Present alternative; developer decides | 🔴 Red (replacement) | -| Barrel import pattern in own code | LOW | Propose direct imports | 🟡 Yellow | -| `optimizePackageImports` candidate | LOW | Present evidence; developer approves | 🟡 Yellow | -| Heavy transitive tree dep (build-time only) | HIGH | Evaluate devDep move | 🟢 Green if verified | - ---- - -## Commands for Manual Dependency Analysis - -```bash -# Find unused dependencies (needs manual verification before removal) -npx depcheck - -# See full dependency tree for a specific package -npm ls --all -pnpm why - -# Check for duplicate versions -npm ls --all | grep -E "deduped|duplicated" - -# Estimate bundle impact (build analysis) -npx @next/bundle-analyzer # requires ANALYZE=true env var and config - -# Check if a package is ESM -cat node_modules//package.json | grep -E '"type"|"exports"|"module"' -``` diff --git a/dist/tidyfactor-next/references/memory/perf-optimization-rules.md b/dist/tidyfactor-next/references/memory/perf-optimization-rules.md deleted file mode 100644 index 2a6fcdd..0000000 --- a/dist/tidyfactor-next/references/memory/perf-optimization-rules.md +++ /dev/null @@ -1,280 +0,0 @@ -# Memory: perf-optimization-rules - -Operational anchors for the Development Performance & Resource Optimization Engine. Pure diagnostic criteria, scoring rubric, causality models, and priority thresholds. No narrative. - ---- - -## 14-Phase Execution Anchors - -| Phase | Name | Workflow | -|---|---|---| -| 0 | Intent & Mode Detection | `../commands/perf.md` command (pre-workflow gate) | -| 1 | Project & Environment Discovery | `../workflows/audit-dev-perf.md` | -| 2 | Baseline Contract Establishment | `../workflows/audit-dev-perf.md` + `../workflows/benchmark-perf.md` | -| 3 | Dependency Graph Analysis | `../workflows/audit-dev-perf.md` + `dependency-optimization.md` | -| 4 | Import & Tree-Shaking Analysis | `../workflows/audit-dev-perf.md` | -| 5 | Client Bundle Composition Analysis | `../workflows/audit-dev-perf.md` + `client-server-boundaries.md` | -| 6 | Next.js Architecture Audit | `../workflows/audit-dev-perf.md` | -| 7 | Git Hygiene vs Dev Tooling Hygiene | `../workflows/audit-dev-perf.md` + `cache-storage-rules.md` | -| 8 | Watch Boundary Audit | `../workflows/audit-dev-perf.md` + `cache-storage-rules.md` | -| 9 | Cache & Storage Analysis | `../workflows/audit-dev-perf.md` + `cache-storage-rules.md` | -| 10 | TypeScript Scope Audit | `../workflows/audit-dev-perf.md` | -| 11 | ESLint & Dev Tooling Overhead | `../workflows/audit-dev-perf.md` | -| 12 | Resource Bottleneck Classification | `../workflows/diagnose-dev-bottleneck.md` | -| 13 | Development Environment Assessment | `../workflows/audit-dev-perf.md` + `../workflows/diagnose-dev-bottleneck.md` | - ---- - -## Bottleneck Causality Models - -### Model A — RAM Pressure → Disk I/O Cascade -``` -RAM fills (node + IDE + browser + Docker) - → OS pages to swap/pagefile - → Swap lives on disk - → All dev ops compete with page I/O - → Result: inconsistent HMR, sluggish IDE, slow TypeScript -Fix: RAM upgrade. NVMe speeds up paging even when RAM is low. -``` - -### Model B — Large Dependency Graph → CPU/RAM -``` -Large node_modules (heavy transitive trees) - → Bundler traverses module graph on startup - → TypeScript analyzes type surface across all packages - → Result: slow cold start, slow first typecheck -Fix: Dependency hygiene. Transitive tree depth matters more than dep count. -``` - -### Model C — Slow Storage → Cache I/O Bottleneck -``` -Next.js .next/cache read/write on every HMR - → HDD: cache I/O becomes the bottleneck - → SATA SSD: improved, still noticeable - → NVMe: cache ops are near-instant -Fix: Storage upgrade. NEVER disable cache as primary fix. -``` - -### Model D — TypeScript Scope Too Wide -``` -tsconfig include covers project root or entire filesystem - → TypeScript analyzes generated files, .next, test fixtures - → Language server carries same overhead → IDE slowness -Fix: Tighten include to actual source dirs only. -``` - -### Model E — ESLint / Tooling Overhead -``` -typeChecked ESLint rules require full TSC program per lint run - → TSC + ESLint = double type analysis -Fix: Evaluate --cache flag, scope ESLint to changed files in CI. -``` - -### Model F — Watch Boundary Overflow -``` -uploads/, videos/, generated/ inside project tree - → File watcher monitors thousands of non-source files - → Cache invalidation checks on every event - → TypeScript language server watches same scope -Fix: watchIgnore for known large static/media directories. Architectural: move to object storage. -``` - ---- - -## 120-Point Scoring Rubric - -12 categories × 0–10 points each = 120 maximum. - -| # | Category | 10 (Excellent) | 5 (Needs Attention) | 0 (Poor) | -|---|---|---|---|---| -| 1 | **Dependency Hygiene** | No unused/duplicate deps; correct dev/prod classification | A few orphaned deps | Many unused; classification errors | -| 2 | **Dependency Graph Efficiency** | Shallow transitive trees; no hidden heavy packages | 1-2 heavy transitive deps | Large transitive trees causing startup overhead | -| 3 | **Import Efficiency** | Direct named imports throughout | Some barrel imports | Widespread barrel imports, no tree-shaking | -| 4 | **Tree-Shaking** | All packages ESM-compatible and tree-shaken | Mixed CJS/ESM | Heavy CJS packages blocking tree-shaking | -| 5 | **Client Bundle Composition** | Only necessary code reaches browser | 1-2 suspected server leaks | DB clients / server SDKs in client bundle | -| 6 | **Next.js Architecture** | RSC/RCC boundary optimal; no excessive providers | Occasional unnecessary `use client` | Widespread `use client` propagation | -| 7 | **Server/Client Boundaries** | Clean server-only containment | Minor leaks suspected | Confirmed server packages in client bundle | -| 8 | **Cache Management** | Cache well-scoped; watch options configured | Cache slightly oversized | .next/cache >> source size; no watch tuning | -| 9 | **Watch Boundaries** | No large non-source dirs in project tree | Small media dirs present | Thousands of user uploads/videos inside tree | -| 10 | **TypeScript Configuration** | Tight include/exclude; incremental on; no generated dirs | Slightly wide scope | Wide scope analyzing node_modules or .next | -| 11 | **ESLint / Tooling** | Efficient rules; cached where possible | A few expensive rules | typeChecked on entire codebase; no caching | -| 12 | **Project Structure** | Clean separation; no uploads/backups in source | Minor structural issues | Generated, media, and source code mixed | - ---- - -## Severity Levels - -``` -CRITICAL → Directly causing significant friction; must fix before other optimizations -HIGH → Noticeable impact; should be addressed in current sprint -MEDIUM → Worth fixing; low urgency -LOW → Minor; optional improvement -INFO → Observation only; no action required -``` - -**Priority rule**: A single CRITICAL item outweighs ten LOW items. Address bottlenecks in order of severity, not count. - ---- - -## Confidence Levels - -Every finding must carry a Confidence level. This prevents the agent from converting an inference into a verdict. - -``` -HIGH → Supported by directly measured, verified data - (grep confirmed 0 imports, file size measured, version verified) - -MEDIUM → Supported by indirect evidence or partial data - (import chain analysis, size ratio, symptom pattern) - -LOW → Inferred from project characteristics only; no direct measurement - (suspected based on project type, no host metrics) - -NOT MEASURABLE → The metric cannot be obtained in the current environment - Always accompanied by: what data is needed and how to get it -``` - -Finding format: -``` -Finding: [Observation] -Severity: [CRITICAL | HIGH | MEDIUM | LOW | INFO] -Confidence: [HIGH | MEDIUM | LOW | NOT MEASURABLE] -Evidence: - - [Specific data point] -Action Status: [APPLIED | PROPOSED | REJECTED | BLOCKED | NOT MEASURABLE] -``` - ---- - -## Action Status Taxonomy - -Every optimization finding must end with one of these statuses: - -``` -APPLIED → Change was applied; DELTA recorded -PROPOSED → Recommendation presented; awaiting developer decision -REJECTED → Developer reviewed and decided not to apply -BLOCKED → Cannot apply due to dependency on another unresolved issue -NOT MEASURABLE → Cannot assess without host-level access; manual commands provided -``` - -`NOT MEASURABLE` is not a failure state. It is a valid status that indicates the environment limit — not a broken finding. - -Example: -``` -Finding: Host-level RAM pressure cannot be measured from this environment. -Severity: INFO -Confidence: NOT MEASURABLE -Action Status: NOT MEASURABLE -To measure: Run `free -h` (Linux) or `wmic os get TotalVisibleMemorySize` (Windows) -``` - ---- - -## Dual Scoring Output Format - -Every audit produces both: - -``` -TECHNICAL SCORE: [X/120] -Overall Development Health: Excellent (≥100) / Good (80-99) / Needs Attention (60-79) / Poor (<60) - -CRITICAL BOTTLENECKS (address first, regardless of score): - 1. [Bottleneck] — CRITICAL - 2. [Bottleneck] — HIGH - -OPTIMIZATION PRIORITY: - P0 — [Immediate, behavior-preserving, low-risk] - P1 — [Requires developer review] - P2 — [Architectural change, developer decision] - P3 — [Environment / infrastructure] -``` - ---- - -## Optimization Budget Rule - -Do NOT apply or propose changes for lower-priority items while a higher-priority bottleneck remains unresolved. - -``` -P0 — Critical bottleneck (e.g., Disk I/O saturation) - ↓ Resolve first. Everything else is blocked. -P1 — High impact, low risk (e.g., large unused dependencies) - ↓ Apply after P0 confirmed resolved or not applicable. -P2 — Medium impact (e.g., barrel import restructuring) - ↓ Only after P0+P1 are addressed. -P3 — Nice to have (e.g., minor ESLint tuning, tidy imports) - ↓ Only after P0+P1+P2 are addressed. -``` - -Example violation to avoid: -``` -DO NOT: Reorder barrel imports (P2) - while 100% Disk Active Time (P0) remains unresolved. - -DO NOT: Tune ESLint config (P3) - while a server-side secret suspected in client bundle (P0) is unconfirmed. -``` - ---- - -## Hardware Baseline Reference - -> These are **Baseline References**, not diagnostic verdicts. A RAM value alone does not determine the bottleneck. The full verdict requires: Observed Memory Pressure + Paging Activity + Working Set Size + Bottleneck Confirmed in Phase 12. - -**RAM Baseline Reference:** -- 8 GB → Often insufficient for Next.js + IDE + Browser + Node + Docker running simultaneously -- 16 GB → Commonly usable; may be constrained under heavy workloads -- 32 GB → Comfortable for most full-stack SaaS development workflows -- 64 GB → Useful for AI processing, video, or very large monorepos - -> Example where 8GB works well: Small Next.js project + NVMe + no Docker + terminal-only IDE. -> Example where 32GB is insufficient: Large monorepo + HDD + Docker + Electron-based IDE. - -**Storage Baseline Reference:** -- HDD → .next/cache R/W is usually a bottleneck; not recommended for development -- SATA SSD → Acceptable for most projects; paging overhead tolerable -- NVMe SSD → Recommended; cache I/O and paging near-instant -- Network drive / WSL on Windows → Known to cause significant watch and I/O overhead - -**Measurement commands (for developer to run if environment access is limited):** -```bash -# RAM available -free -h # Linux/macOS -wmic os get TotalVisibleMemorySize # Windows - -# Storage type -cat /sys/block/sda/queue/rotational # 0 = SSD, 1 = HDD (Linux) -Get-PhysicalDisk | Select MediaType # Windows PowerShell - -# Project sizes -du -sh node_modules/ .next/ .next/cache/ # Linux/macOS -# Windows: Properties dialog on each folder - -# Dev startup timing -time npx next dev -- --port 3001 (stop after "Ready in Xs") - -# Build timing -time next build - -# TypeScript timing -time npx tsc --noEmit -``` - ---- - -## SaaS Safety Boundary (Non-Negotiable) - -Performance optimization applied by the `perf` track MUST NOT weaken: - -| Protected Concern | Source of Truth | -|---|---| -| Tenant Isolation model | `spec.md` | -| RLS policy coverage | `rls-patterns.md` (managed by `rls` command only) | -| RBAC / ABAC authorization | `auth-patterns.md` (managed by `auth` command only) | -| Authentication flows | `auth-patterns.md` | -| Server-side secret containment | `spec.md` | -| API security boundaries | API contracts & route handler scope | -| CSRF / XSS protections | Always preserved regardless of optimization | - -If a proposed optimization crosses any of these boundaries — even if measurably faster — reclassify immediately to 🔴 Red and present as a manual architectural recommendation only. diff --git a/dist/tidyfactor-next/references/memory/quality-bar.md b/dist/tidyfactor-next/references/memory/quality-bar.md deleted file mode 100644 index 9794451..0000000 --- a/dist/tidyfactor-next/references/memory/quality-bar.md +++ /dev/null @@ -1,31 +0,0 @@ -# Memory: quality-bar (Anti-Slop & Multi-Tenant SaaS Quality Gate) - - - -Enforces strict tenant isolation, zero data leakage, and architectural purity across all Next.js + Supabase deliverables. - ---- - -## 🛡️ 7-Axis Pre-Emit Self-Critique Stamp - -Every generated code block, route handler, server action, or migration must be evaluated and stamped before emission: -`/* Pre-emit critique: P5 H5 E5 S5 R5 V5 D5 */` - -| Axis | Dimension | Score 1 (Slop / Reject) | Score 5 (Production Pass) | -|:---:|---|---|---| -| **P** | **Purpose & Tenant Safety** | Ambiguous tenant isolation; leaks data across organizations. | Bulletproof RLS (`tenant_id = auth.jwt() ->> 'tenant_id'`); fail-closed resolution. | -| **H** | **Hierarchy & Boundary Clarity** | Leaks server logic into client bundles (`"use client"` abuse); bloated props over RSC wire. | Strict RSC boundaries; data fetched server-side; minimal serialized DTOs passed across boundary. | -| **E** | **Execution Completeness** | Missing error boundaries, loading states, or validation schemas. | Zod schemas, optimistic UI, complete error handling, and audit logs. | -| **S** | **Stack Native Strictness** | Next.js 12/13 legacy patterns; untyped `any` signatures. | Next.js 16 + React 19 native (`use`, Server Actions, `after()`, strict TypeScript). | -| **R** | **RLS & Security Enforcement** | Direct `service_role` use in client/route handlers without check. | `service_role` strictly restricted to internal background workers. | -| **V** | **Velocity & Performance** | Sequential waterfalls, missing `React.cache()`, un-split heavy bundles, re-render slop. | Zero waterfalls (guards before await, parallel fetches), `React.cache()` dedup, `after()` for non-blocking I/O, dynamic imports for heavy UI. | -| **D** | **Decision Alignment** | Violates confirmed `.tidyfactor/next-brief.md` stack choices. | 100% compliant with confirmed Query Layer, Tenant Mode, and Auth choices. | - ---- - -## 🚫 Non-Negotiable Multi-Tenant Security Invariants - -1. **Locked Tenant Isolation**: Every tenant-owned table MUST include `tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE`. -2. **Postgres RLS Enabled**: Every table MUST execute `ALTER TABLE ENABLE ROW LEVEL SECURITY;` and `ALTER TABLE
FORCE ROW LEVEL SECURITY;`. -3. **No Unbounded Queries**: Never emit queries without `LIMIT` and pagination constraints. -4. **Zero Secrets in Client**: Never pass `SUPABASE_SERVICE_ROLE_KEY` to client components or public route responses. diff --git a/dist/tidyfactor-next/references/memory/react-perf-rules.md b/dist/tidyfactor-next/references/memory/react-perf-rules.md deleted file mode 100644 index 019ad06..0000000 --- a/dist/tidyfactor-next/references/memory/react-perf-rules.md +++ /dev/null @@ -1,358 +0,0 @@ -# Memory: react-perf-rules (React 19 & Next.js 16 Runtime Performance Catalog) - - - -Operational memory containing the 8-tier prioritized performance rules for React 19 and Next.js 16 App Router applications. Pure patterns, schemas, anti-patterns, and correct implementations. No narrative filler. - ---- - -## 8-Tier Prioritization Matrix - -``` -┌──────────────────────────────────────────────────────────────┐ -│ Tier 1: Eliminating Waterfalls (async-*) [CRITICAL] │ -│ Tier 2: Bundle Size Optimization (bundle-*) [CRITICAL] │ -│ Tier 3: Server-Side Performance (server-*) [HIGH] │ -│ Tier 4: Client-Side Data Fetching (client-*) [MED-HIGH] │ -│ Tier 5: Re-render Optimization (rerender-*) [MEDIUM] │ -│ Tier 6: Rendering Performance (rendering-*) [MEDIUM] │ -│ Tier 7: JavaScript Performance (js-*) [LOW-MED] │ -│ Tier 8: Advanced React Patterns (advanced-*) [LOW] │ -└──────────────────────────────────────────────────────────────┘ -``` - ---- - -## Tier 1: Eliminating Waterfalls (`async-*`) — CRITICAL - -### 1.1 `async-cheap-condition-before-await` -Evaluate cheap synchronous guards (local props, session cookies, route params) before awaiting remote flags or DB queries. - -```typescript -// ❌ Incorrect: Always pays async penalty even if synchronous check fails -const flag = await getFeatureFlag('beta_pricing'); -if (flag && isEligibleUser(user)) { - renderBeta(); -} - -// ✅ Correct: Bypasses async network call on cold path -if (isEligibleUser(user)) { - const flag = await getFeatureFlag('beta_pricing'); - if (flag) renderBeta(); -} -``` - -### 1.2 `async-defer-await` -Defer `await` expressions into the exact conditional branch or code block where the data is actually used. - -```typescript -// ❌ Incorrect: Awaits query before branch decision -const auditLog = await fetchHeavyAuditLog(orgId); -if (mode === 'lightweight') { - return ; -} -return ; - -// ✅ Correct: Only awaits when entering heavy branch -if (mode === 'lightweight') { - return ; -} -const auditLog = await fetchHeavyAuditLog(orgId); -return ; -``` - -### 1.3 `async-parallel` & `async-dependencies` -Never sequence independent promises with sequential `await`. Use `Promise.all()` for independent fetches or resolve partial dependency graphs concurrently. - -```typescript -// ❌ Incorrect: Sequential network waterfall -const tenant = await getTenant(tenantId); -const subscription = await getSubscription(tenantId); -const teamMembers = await getTeamMembers(tenantId); - -// ✅ Correct: Concurrent execution -const [tenant, subscription, teamMembers] = await Promise.all([ - getTenant(tenantId), - getSubscription(tenantId), - getTeamMembers(tenantId), -]); -``` - -### 1.4 `async-api-routes` -In Route Handlers and Server Actions, initiate asynchronous promises immediately at handler start; await only when assembling response payload. - -```typescript -// ❌ Incorrect: Waterfalling auth check and queries -export async function GET(req: Request) { - const session = await auth(); - const data = await db.query(session.tenantId); - return Response.json(data); -} - -// ✅ Correct: Early promise initiation -export async function GET(req: Request) { - const sessionPromise = auth(); - // Initiate parallel tasks if possible, or await at leaf - const session = await sessionPromise; - const data = await db.query(session.tenantId); - return Response.json(data); -} -``` - -### 1.5 `async-suspense-boundaries` -Wrap slow or non-critical async RSC subtrees in `}>` to unlock progressive streaming and avoid blocking the initial HTML shell. - -```typescript -// ✅ Correct: Fast shell renders immediately; heavy data streams in -export default async function DashboardPage({ params }: PageProps) { - return ( -
-
- }> - - - }> - - -
- ); -} -``` - ---- - -## Tier 2: Bundle Size Optimization (`bundle-*`) — CRITICAL - -### 2.1 `bundle-barrel-imports` -Never import through barrel/index files for large icon or component libraries. Use direct subpath imports or Next.js `optimizePackageImports`. - -```typescript -// ❌ Incorrect: Triggers full barrel bundle resolution -import { Check, AlertTriangle, Shield } from 'lucide-react'; - -// ✅ Correct: Configured via next.config.ts or direct path -// next.config.ts: experimental: { optimizePackageImports: ['lucide-react', '@radix-ui/react-icons'] } -import { Check } from 'lucide-react'; -``` - -### 2.2 `bundle-dynamic-imports` -Dynamically import heavy, non-critical client components (charts, rich text editors, PDF viewers) with `next/dynamic`. - -```typescript -// ✅ Correct: Loaded on-demand; zero impact on main page bundle -const RichTextEditor = dynamic(() => import('@/components/editor/TipTapEditor'), { - ssr: false, - loading: () =>
-}); -``` - -### 2.3 `bundle-defer-third-party` -Defer third-party analytics, customer support widgets, and tracking scripts until after hydration. - -```typescript -// ✅ Correct: Offloads script execution past critical hydration -import Script from 'next/script'; - -