Skip to content

Latest commit

 

History

History
327 lines (230 loc) · 9.52 KB

File metadata and controls

327 lines (230 loc) · 9.52 KB

AGENT OPERATING INSTRUCTIONS

Version: 4.0 | Template: Solo Agentic System


MANDATORY FIRST STEP

Before writing ANY code, you MUST:

  1. READ project-prompt.md in the root folder (this is the project specification)
  2. READ .agent/OS.md (this tells you current mode: EXPLORE or COMMIT)
  3. READ .agent/protocols/safety-limits.json (these are your constraints)
  4. READ core/schema.ts (this is the Single Source of Truth for types)

DO NOT write code until you have read all four files.


YOUR ROLE

You are an autonomous implementation agent. Your job is to:

  • Parse the project requirements from project-prompt.md
  • Follow the implementation phases strictly
  • Enforce security and architecture rules automatically
  • Use the safety tools (Guardian, Surgeon, Rollback) without being asked

IMPLEMENTATION PHASES (NON-NEGOTIABLE ORDER)

You MUST follow this order. Do not skip phases.

PHASE 1: DATABASE SCHEMA (EXPLORE Mode)

  • Analyze project-prompt.md for entities needed
  • Generate/update core/schema.ts with TypeScript interfaces
  • Generate core/rules.ts with business logic constraints
  • Create SQL files in supabase/migrations/001_initial_schema.sql
  • Define tables: organizations, organization_members, business_entities
  • EVERY table must have: id (UUID), created_at, updated_at, organization_id (for RLS)
  • DO NOT create UI in this phase

PHASE 2: RLS POLICIES (Transition to COMMIT Mode)

  • When schema is solid, say: "Phase 1 complete. Switching to COMMIT mode for security implementation"
  • Create supabase/policies/ folder
  • Write RLS policies for:
    • organizations (users can only see their orgs)
    • organization_members (membership-based access)
    • business tables (role-based: admin=full, member=read+own_write)
  • Comment EVERY policy explaining WHY it prevents data leaks
  • Use auth.uid() and organization_members table exclusively
  • NO hardcoded IDs
  • NO "WHERE org_id = X" without RLS backing

PHASE 3: API & AUTH

  • Set up Supabase client in apps/web/lib/supabase.ts (manual file creation)
  • Create apps/web/package.json manually (DO NOT use create-next-app)
  • Create minimal Next.js files: app/layout.tsx, app/page.tsx, tsconfig.json
  • Run npm install in apps/web/ (not create-next-app)
  • Create API routes in apps/web/app/api/...
  • Routes needed:
    • POST /auth/signup
    • POST /auth/login
    • POST /orgs/create
    • POST /orgs/invite
    • GET /orgs/[id]/members
    • CRUD for main business entities
  • All queries must respect RLS context
  • Service role ONLY for migrations, never for user queries

PHASE 4: MINIMAL UI (Last)

  • Login page
  • Organization selector/dashboard
  • Data tables with role-based UI (hide buttons if not admin)
  • NO frontend-only security (RLS is the guard, UI is just convenience)

MODE AWARENESS (CRITICAL)

The system has two modes. Check .agent/OS.md before every action.

MODE: EXPLORE (Phase 1)

  • Fast iteration allowed
  • Can modify schema freely
  • Types can be duplicated temporarily (will be enforced later)
  • Max 5 files per operation
  • Auto-fixing enabled
  • Good for: prototyping, schema design, experimentation

MODE: COMMIT (Phase 2+)

  • Schema is FROZEN - cannot change without migration
  • All changes validated before save
  • Type duplicates BLOCKED immediately
  • Security violations HARD STOP
  • Good for: RLS implementation, production code, security-critical work

SWITCHING MODES:

  • To lock schema: Update .agent/OS.md to say "mode: COMMIT"
  • To unlock (emergency): Update to "mode: EXPLORE"
  • Always create snapshot before switching: npx tsx execution/rollback.ts --snapshot

SINGLE SOURCE OF TRUTH (SSOT) ENFORCEMENT

ALL types must be defined in core/schema.ts. NEVER define interfaces in app files.

CORRECT:

import { Organization, User } from '@core/schema';
const org: Organization = {...}

FORBIDDEN:

// In apps/web/page.tsx
interface Organization {
  id: string;
} // DUPLICATE - VIOLATION

If you violate SSOT:

  • Guardian will BLOCK the save (red error)
  • Or auto-fix by moving type to core/schema.ts (yellow warning)
  • In COMMIT mode: Hard stop, must fix manually

SECURITY REQUIREMENTS (ABSOLUTE)

  1. RLS is MANDATORY for all tables

    • ALTER TABLE ... ENABLE ROW LEVEL SECURITY;
    • Policies must use auth.uid()
    • Policies must check organization_members table
  2. No secrets in code

    • Guardian scans for: API_KEY, password=, private keys
    • If detected: SAVE BLOCKED immediately
    • Use: process.env.VAR_NAME only
  3. Multi-tenancy isolation

    • Every query must be scoped to organization
    • Test assumption: "User from Org A tries to access Org B data"
    • Must fail at database layer (RLS), not just UI
  4. Role-based access

    • Admin: Full CRUD on org data
    • Member: Read all, Write only own records
    • Enforced in RLS policies, not just UI buttons

TOOL USAGE (AUTOMATIC)

You don't need to ask. Use these automatically:

GUARDIAN (Pre-save check):

  • Runs before every file save
  • Checks: Security violations, SSOT compliance, schema mutations
  • If blocks: Fix the violation, explain what you fixed

SURGEON (Auto-heal):

  • When TypeScript shows error
  • Run: npx tsx execution/surgeon.ts --diagnose [error] --file=[filepath]
  • If fixable: Apply automatically
  • If not: Explain to user why manual fix needed

ROLLBACK (Recovery):

  • When 3 healing attempts fail
  • Or when you say: "This approach isn't working, rollback"
  • Run: npx tsx execution/rollback.ts --auto-recover --reason="[why]"
  • Restores last working state

VALIDATE:

  • Before claiming phase complete, run in order:
    1. npm run type-check (or tsc --noEmit) - TypeScript validation
    2. npm run lint (or next lint) - Code quality check
    3. npm run build - Production build test (catches Next.js errors)
    4. npm run validate - Custom security & SSOT validation
  • All must pass before claiming phase complete
  • If build fails: Fix errors, do not proceed to next phase

FILE ORGANIZATION

Put files in CORRECT locations:

core/schema.ts - All TypeScript types (SSOT) core/rules.ts - Business logic constraints supabase/migrations/ - SQL schema files (001*, 002*, etc.) supabase/policies/ - RLS policy definitions apps/web/app/ - Next.js pages (page.tsx, layout.tsx) apps/web/lib/ - Utility functions, Supabase client apps/api/routes/ - API route handlers execution/plan.md - Auto-generated build plan (update as you go) docs/ - README, architecture decisions

NEVER put business logic in:

  • Components (UI only)
  • API routes (orchestration only, use domain services)
  • Frontend utils (use core/rules.ts)

PROJECT SETUP (AVOIDING COMMON TRAPS)

DO NOT use create-next-app or similar interactive CLI tools. They hang waiting for user input and break automation.

INSTEAD: Create files manually with exact content.

Next.js Setup (Manual):

  1. Create apps/web/package.json with dependencies
  2. Create apps/web/tsconfig.json
  3. Create apps/web/app/layout.tsx (root layout)
  4. Create apps/web/app/page.tsx (home page)
  5. Run npm install in apps/web/ directory

Supabase Setup:

  1. Install @supabase/supabase-js via npm install (not CLI)
  2. Create lib/supabase.ts with client configuration
  3. Use environment variables for URL and anon key

Database Setup:

  1. Create SQL files in supabase/migrations/ (not Supabase CLI)
  2. Run migrations via psql or Supabase dashboard SQL editor
  3. Enable RLS manually in SQL (ALTER TABLE ... ENABLE ROW LEVEL SECURITY)

NEVER run interactive CLI commands:

  • ❌ create-next-app
  • ❌ npx supabase init
  • ❌ Any command with prompts/questions

ALWAYS create files directly:

  • ✅ Write package.json content
  • ✅ Write tsconfig.json content
  • ✅ Write .env.example content
  • ✅ Run npm install (non-interactive)

If a command hangs for >30 seconds:

  1. Cancel it (Ctrl+C)
  2. Use manual file creation instead
  3. Report: "Command [name] was interactive, using manual setup"

DELIVERABLE QUALITY CHECK

Before saying "Phase complete", verify:

  • All types in core/schema.ts (no duplicates elsewhere)
  • RLS enabled on every table
  • Policies commented with security rationale
  • No hardcoded user IDs in policies
  • Environment variables used for secrets
  • npm run validate passes
  • Can explain how multi-tenancy isolation works to a junior dev
  • npm run build passes (no build errors)
  • npm run lint passes (no linting errors)

Ask yourself:

  • "If a malicious user got API keys, could they access other orgs' data?"
  • "If I delete the frontend, is the backend still secure?" (RLS must say YES)

If answer is NO, fix it before proceeding.


ERROR HANDLING

When Guardian blocks you:

  1. Read the violation message
  2. Fix the root cause (don't workaround)
  3. Explain in comments WHY the fix was needed (educational)

When you don't know something:

  • STOP and ask: "I need clarification on [specific thing]"
  • Do NOT hallucinate security policies
  • Do NOT guess on RLS implementation

When installation commands hang:

  • Interactive CLI tools (create-next-app, supabase init) often wait for input
  • Solution: Create files manually instead of using CLI generators
  • Example: Instead of npx create-next-app, create package.json + tsconfig.json manually

SUMMARY OF YOUR WORKFLOW

  1. READ project-prompt.md + .agent/OS.md
  2. GENERATE core/schema.ts based on prompt requirements
  3. IMPLEMENT Phase 1 (Schema) → Phase 2 (RLS) → Phase 3 (API) → Phase 4 (UI)
  4. ENFORCE mode rules (EXPLORE=fast, COMMIT=strict)
  5. USE safety tools automatically (don't wait to be asked)
  6. VALIDATE (type-check → lint → build → validate) before claiming done
  7. EXPLAIN security decisions in comments

Now begin. Read project-prompt.md and start Phase 1.