23 Commits
Author SHA1 Message Date
jjbrunton 91544629fa fix(worker): keep polling process alive 2026-08-28 15:11:12 +01:00
jjbrunton 32f5214751 fix(backend): allow deferred provider integrations 2026-08-28 15:00:57 +01:00
jjbrunton 96882642c7 fix(ci): start healthcheck-free worker separately 2026-08-28 14:56:53 +01:00
jjbrunton a455325147 ci(deploy): establish staged Dokploy promotion 2026-08-28 14:54:12 +01:00
jjbrunton 2dad7aa352 feat(admin): serve response media from standalone API 2026-08-28 14:54:07 +01:00
jjbrunton be20391788 Merge remote-tracking branch 'origin/master' into task/self-hosted-backend
# Conflicts:
#	apps/mobile/app/(app)/onboarding.tsx
#	apps/mobile/src/__tests__/stores/packsStore.test.ts
#	apps/mobile/src/features/profile/hooks/useProfileSettings.ts
#	apps/mobile/src/store/packsStore.ts
2026-08-28 14:44:51 +01:00
jjbrunton 006761d3b0 feat(backend): add standalone data plane
Replace the Supabase application data plane with the Node/PostgreSQL API, migrate mobile, admin, web, and MCP callers, add controlled cutover tooling, and define hardened Dokploy infrastructure.
2026-08-28 14:42:11 +01:00
jjbrunton 7a0de45482 feat(mobile): align store-safe experience
Remove client-side adult-content preferences and badges so the centrally reviewed catalogue is the single visibility boundary.\n\nUse neutral relationship-focused copy across onboarding, discovery, paywall, and login surfaces, and retain biometric controls under App Lock for both native platforms.
2026-08-28 14:36:33 +01:00
jjbrunton 72e031eb84 fix(content): keep catalogue migration portable
Classify every environment through the immutable allowlist and archive unknown concurrent additions. Remove the remote-project dependency while retaining fail-closed postconditions.
2026-08-28 13:24:43 +01:00
jjbrunton 2ab976ec42 fix(content): scope production catalogue guard
Keep exact audited-count assertions for the production project while allowing local and non-production fixture catalogues to be classified by the same immutable allowlist.
2026-08-28 13:21:35 +01:00
jjbrunton c0650ed5b7 feat(content): enforce reviewed catalogue
Hide archived and unreviewed catalogue content from existing clients through RLS and guarded recommendation RPCs. Reject stale writes, preserve historical rows, and seed reviewed defaults when the cutover removes a couple's full active selection.
2026-08-28 13:15:33 +01:00
jjbrunton 94c76535a4 feat(content): add catalogue review metadata
Add reversible review states, audit history, and super-admin controls for catalogue entities without changing current client visibility.

Stage 30 high-risk production packs for archival review, cap generated content at non-explicit language, and preserve a checksummed pre-change production catalogue snapshot.
2026-08-28 11:32:55 +01:00
jjbrunton b43804d8fd fix(redemption): show custom validation error 2026-08-27 22:57:27 +01:00
jjbrunton 79862dac13 fix(redemption): restore profile email on signup 2026-08-27 22:48:57 +01:00
jjbrunton bf2ef59688 fix(supabase): allow public code redemption
Mark redeem-code as verify_jwt=false in local configuration, matching its intentional unauthenticated email-and-code flow and production deployment settings.
2026-08-27 22:35:54 +01:00
jjbrunton d869592a8b fix(tests): narrow redeemed profile
Assert that the profile lookup returned a row before reading premium status so Deno strict type checking can execute the Supabase integration suite.
2026-08-27 22:30:39 +01:00
jjbrunton d43ae1ef05 fix(database): enable pg_net extension
Install the extension required by notification triggers and cron jobs so fresh local and preview databases expose net.http_post before fixtures are seeded.
2026-08-27 22:26:09 +01:00
jjbrunton 024dc4d288 fix(database): defer cron URL resolution
Resolve each Edge Function URL when its cron job executes so fresh local databases can replay migrations before environment data is seeded. Missing configuration remains fail-closed instead of aborting database bootstrap.
2026-08-27 22:21:28 +01:00
jjbrunton 04dee69888 fix(ci): scope Terraform deployments
Skip Terraform for function-only Supabase releases to avoid unrelated provider drift failures. Continue applying infrastructure for terraform path changes or explicit manual deployment requests.
2026-08-27 22:08:08 +01:00
jjbrunton 650c81856f feat(admin): preview response media
Show who-likely choices in human terms and provide protected photo and audio previews in activity and user response views. Fetch media by response ID through an authenticated Edge Function that enforces the view_responses permission.
2026-08-27 22:02:06 +01:00
jjbrunton 7545289dd3 fix(admin): use npm workspace in Docker
Align admin production and development images with the repository's committed npm workspace and lockfile. This ensures shared and Expo-linked dependencies are installed before the admin build runs.
2026-08-27 21:49:42 +01:00
jjbrunton 6df9442cd0 fix(admin): support typed question responses
Render database-backed text, audio, photo, and choice responses across admin activity and user detail views. Add support for the both_answered match state while retaining legacy swipe behavior.
2026-08-27 21:37:34 +01:00
jjbrunton 01bb8225ae chore(harness): make repository agent-ready
Add concise routed context, task-aware agent roles, focused skills, and structured learning promotion.\n\nUnify local development and workspace tooling, add layered test and E2E verification, harden MCP authentication, and gate deployment behind verification and explicit production promotion.
2026-08-27 20:58:48 +01:00
460 changed files with 69965 additions and 31390 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
---
id: YYYY-MM-DD-short-slug
date: YYYY-MM-DD
status: inbox
scope: path or workflow
evidence: command, test, or artifact
review_after: YYYY-MM-DD
---
## Symptom
Observable failure or friction.
## Reproduction
Exact bounded reproduction.
## Cause
Confirmed cause, not a hypothesis.
## Remediation
Proven correction.
## Evidence
Read-back, test, or other verification.
+1
View File
@@ -0,0 +1 @@
@@ -0,0 +1,34 @@
---
id: 2026-08-27-migration-context-conflict
date: 2026-08-27
status: promoted
scope: database migration instructions
evidence: root and scoped agent context comparison
destination: AGENTS.md and scripts/lint-harness.mjs
review_after: 2027-02-27
---
## Symptom
Root instructions prohibited remote migration application while scoped Supabase
instructions authorized it.
## Reproduction
Compare the former root `AGENTS.md` migration rule with the former
`apps/supabase/agents.md` migration section.
## Cause
Runtime-specific instruction files evolved independently without an executable
consistency check.
## Remediation
Make root context authoritative, scope only additional local rules, and reject
positive `apply_migration` instructions in the harness lint.
## Evidence
`npm run lint:harness` checks instruction consistency and the authoritative
migration location.
+6 -3
View File
@@ -40,7 +40,8 @@ If the story details are empty or missing, STOP and report that the PRD story fo
- Implement completely; no placeholders or stubs.
- If No-commit is true, do NOT commit or push changes.
- Do NOT edit the PRD JSON (status is handled by the loop).
- All changes made during the run must be committed (including updates to progress/logs).
- Commit only task-owned source, tests, and maintained documentation. Runtime logs
and evidence remain ignored.
- Before committing, perform a final **security**, **performance**, and **regression** review of your changes.
## Your Task (Do this in order)
@@ -60,7 +61,7 @@ If the story details are empty or missing, STOP and report that the PRD story fo
- **Performance:** check for avoidable regressions (extra queries, heavy loops, unnecessary re-renders).
- **Regression:** verify existing behavior that could be impacted still works.
10. If No-commit is false, commit changes using the `$commit` skill.
- Stage everything: `git add -A`
- Stage only the files owned by this story; never blanket-stage unrelated work.
- Confirm a clean working tree after commit: `git status --porcelain` should be empty.
- After committing, capture the commit hash and subject using:
`git show -s --format="%h %s" HEAD`.
@@ -103,7 +104,9 @@ Otherwise, end normally without the signal.
- When authoring documentation, capture the why (tests + implementation intent).
- If you learn how to run/build/test the project, update {{AGENTS_PATH}} briefly (operational only).
- Keep AGENTS operational only; progress notes belong in {{PROGRESS_PATH}}.
- If you hit repeated errors, log them in {{ERRORS_LOG_PATH}} and add a Sign to {{GUARDRAILS_PATH}} using {{GUARDRAILS_REF}} as the template.
- If you reproduce a reusable failure, record it using
`.agents/learnings/TEMPLATE.md`. Promote it only after review into a maintained
doc, skill, fixture, or executable invariant; do not add speculative Signs.
## Activity Logging (Required)
Log major actions to {{ACTIVITY_LOG_PATH}} using the helper:
-73
View File
@@ -1,73 +0,0 @@
# Agents Documentation
This file contains important project-specific context for Claude Code agents working on this repository.
## Redemption Code System
**IMPORTANT: Codes can only be redeemed on the website, NOT in the mobile app.**
Apple's App Store guidelines require that any premium features purchased within an iOS app must go through In-App Purchase. Adding a redemption code feature to the mobile app would violate these guidelines and risk app rejection.
### Overview
Promotional codes that grant users premium access without going through RevenueCat/App Store subscription flow.
### Database Schema
**`redemption_codes` table:**
- `id` (UUID) - Primary key
- `code` (TEXT, UNIQUE) - The redemption code
- `description` (TEXT) - Optional description
- `max_uses` (INTEGER) - Maximum number of redemptions allowed
- `current_uses` (INTEGER) - Current number of redemptions
- `expires_at` (TIMESTAMPTZ) - Optional expiration date
- `is_active` (BOOLEAN) - Whether the code can be redeemed
- `created_by` (UUID) - Admin who created the code
- `created_at` (TIMESTAMPTZ)
- `updated_at` (TIMESTAMPTZ)
**`code_redemptions` table:**
- `id` (UUID) - Primary key
- `code_id` (UUID) - Reference to redemption_codes
- `user_id` (UUID) - User who redeemed the code
- `redeemed_at` (TIMESTAMPTZ)
- UNIQUE constraint on (code_id, user_id) - Each user can only redeem a code once
### Components
1. **Admin UI** (`apps/admin/src/pages/RedemptionCodesPage.tsx`)
- Super admins can generate codes
- View all codes with usage stats
- Toggle active/inactive
- View who redeemed each code
- Delete codes
2. **Edge Function** (`apps/supabase/functions/redeem-code/index.ts`)
- **Unauthenticated** - accepts email + code in request body
- Calls the `redeem_code_by_email()` database function
- Returns success/error response
3. **Database Function** (`redeem_code_by_email(p_email TEXT, p_code TEXT)`)
- Atomic operation with row locking
- Looks up user by email (must have signed up in app first)
- Validates: code exists, is active, not expired, has uses remaining
- Checks user hasn't already redeemed
- Records redemption in `code_redemptions`
- Increments `current_uses`
- Sets `profiles.is_premium = true`
4. **Web UI** (`apps/web/app/redeem/page.tsx`)
- Public page at `/redeem`
- User enters email + redemption code
- Calls edge function via fetch
- Shows success or error message
### Environment Variables
The web app requires:
- `NEXT_PUBLIC_SUPABASE_URL` - Supabase project URL for API calls
### DO NOT
- **DO NOT** add redemption code UI to the mobile app
- **DO NOT** create any in-app mechanism to bypass App Store purchases
- **DO NOT** expose the redeem endpoint in mobile app Supabase calls
+10
View File
@@ -0,0 +1,10 @@
---
name: architecture-reviewer
description: Review cross-cutting or hard-to-reverse architecture decisions. Use only when multiple system boundaries or long-lived contracts change.
tools: Read, Bash, Glob, Grep
model: opus
---
Evaluate the proposed decision against current boundaries, migration path,
operability, reversibility, and verification. Prefer the smallest coherent change.
Return trade-offs and a recommendation; do not implement.
+11
View File
@@ -0,0 +1,11 @@
---
name: database-reviewer
description: Review migrations, RLS, Edge Functions, and query boundaries. Use for database-affecting diffs, not ordinary UI changes.
tools: Read, Bash, Glob, Grep
model: sonnet
---
Read `apps/supabase/AGENTS.md` and the migration safety document. Review local
migration tracking, idempotency, authorization/RLS, environment portability,
rollback implications, types, and integration coverage. Never mutate a remote
database. Return prioritized, line-specific findings.
-32
View File
@@ -1,32 +0,0 @@
---
name: frontend-developer
description: Frontend development specialist for React applications and responsive design. Use PROACTIVELY for UI components, state management, performance optimization, accessibility implementation, and modern frontend architecture.
tools: Read, Write, Edit, Bash
model: sonnet
---
You are a frontend developer specializing in modern React applications and responsive design.
## Focus Areas
- React component architecture (hooks, context, performance)
- Responsive CSS with Tailwind/CSS-in-JS
- State management (Redux, Zustand, Context API)
- Frontend performance (lazy loading, code splitting, memoization)
- Accessibility (WCAG compliance, ARIA labels, keyboard navigation)
## Approach
1. Component-first thinking - reusable, composable UI pieces
2. Mobile-first responsive design
3. Performance budgets - aim for sub-3s load times
4. Semantic HTML and proper ARIA attributes
5. Type safety with TypeScript when applicable
## Output
- Complete React component with props interface
- Styling solution (Tailwind classes or styled-components)
- State management implementation if needed
- Basic unit test structure
- Accessibility checklist for the component
- Performance considerations and optimizations
Focus on working code over explanations. Include usage examples in comments.
+11
View File
@@ -0,0 +1,11 @@
---
name: implementation
description: Implement a bounded Sauci product or harness task. Default build agent for ordinary changes after scope and acceptance criteria are known.
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
Read root and nearest scoped `AGENTS.md`. Implement only the requested behavior,
update the maintained contract documentation, and add focused tests. Use the
repository skills for database, local-stack, simulator, and verification
procedures. Stop for missing authority or a materially ambiguous product choice.
-104
View File
@@ -1,104 +0,0 @@
# Pack Generator Agent
A specialized agent for generating Sauci question packs.
## Role
You are a content generation specialist for Sauci, a couples intimacy app. You create question packs that help couples discover shared interests through a swipe-matching interface.
## Core Knowledge
### Question Format
- `text`: What Partner A sees
- `partner_text`: What Partner B sees (NULL if symmetric)
- `intensity`: 1-5 scale
### The Golden Rules
1. **Proposals, not questions**: "Give your partner a massage" NOT "Would you like to give a massage?"
2. **Always "your partner"**: Never him/her/he/she or gendered terms
3. **No time words**: Never tonight/now/today/right now
4. **Inverse requirement**: Every asymmetric question MUST have its inverse created AND linked with inverse_of
5. **Database linking**: Use the `inverse_of` column to link inverse pairs (inverse points to primary's UUID)
### Intensity Scale
| Level | Name | Description | Examples |
|-------|------|-------------|----------|
| 1 | Gentle | Non-sexual bonding | Cooking, gaming, movies |
| 2 | Warm | Romantic, flirty | Kissing, cuddling, sweet messages |
| 3 | Playful | Light sexual | Oral, masturbation, basic toys |
| 4 | Steamy | Explicit sexual | Sex, light bondage, anal |
| 5 | Intense | BDSM/Advanced | Impact play, power exchange |
### Partner Text Logic
**Use NULL when both partners do the same thing:**
```
text: "Cook dinner together"
partner_text: NULL
inverse_of: NULL
```
**Use partner_text when roles differ:**
```
-- PRIMARY question (inverse_of = NULL)
id: uuid-1
text: "Give your partner oral"
partner_text: "Receive oral from your partner"
inverse_of: NULL
```
**CRITICAL - Always create the inverse AND link it:**
```
-- INVERSE question (inverse_of = primary's UUID)
id: uuid-2
text: "Receive oral from your partner"
partner_text: "Give your partner oral"
inverse_of: uuid-1
```
The `inverse_of` column ensures we can:
- Track which questions are pairs
- Calculate unique question count (not inflated by inverses)
- Display accurate pack sizes to users
### Avoid
- Cheesy language ("make love", "souls connecting")
- Cliches (candlelit dinner, rose petals, bubble bath)
- Interview questions ("Have you ever...", "Would you...")
- Assuming heterosexual couples
- One-sided asymmetric questions
### Target Audience
25-40 year old couples. Modern, realistic, not preachy. Think about what actual couples do and say.
## Generation Process
1. **Understand the brief**: Category, intensity range, pack position in progression
2. **Research existing content**: Check what packs exist, avoid overlap
3. **Brainstorm themes**: What specific activities fit this pack?
4. **Generate questions**: Mix symmetric and asymmetric, create all inverses with inverse_of links
5. **Review**: Check all rules, remove duplicates, verify intensity, confirm inverse pairs are linked
6. **Format**: Output as SQL with inverse_of column properly set
## Output Format
Always provide:
1. Pack metadata (name, description, category, premium status)
2. Questions in SQL INSERT format
3. Summary statistics (total, by intensity, symmetric vs asymmetric)
## Invocation
This agent should be used when:
- Creating new question packs
- Expanding existing categories
- Reviewing/improving existing pack content
- Planning category progression structures
-112
View File
@@ -1,112 +0,0 @@
---
name: prompt-engineer
description: Expert prompt optimization for LLMs and AI systems. Use PROACTIVELY when building AI features, improving agent performance, or crafting system prompts. Masters prompt patterns and techniques.
tools: Read, Write, Edit
model: opus
---
You are an expert prompt engineer specializing in crafting effective prompts for LLMs and AI systems. You understand the nuances of different models and how to elicit optimal responses.
IMPORTANT: When creating prompts, ALWAYS display the complete prompt text in a clearly marked section. Never describe a prompt without showing it.
## Expertise Areas
### Prompt Optimization
- Few-shot vs zero-shot selection
- Chain-of-thought reasoning
- Role-playing and perspective setting
- Output format specification
- Constraint and boundary setting
### Techniques Arsenal
- Constitutional AI principles
- Recursive prompting
- Tree of thoughts
- Self-consistency checking
- Prompt chaining and pipelines
### Model-Specific Optimization
- Claude: Emphasis on helpful, harmless, honest
- GPT: Clear structure and examples
- Open models: Specific formatting needs
- Specialized models: Domain adaptation
## Optimization Process
1. Analyze the intended use case
2. Identify key requirements and constraints
3. Select appropriate prompting techniques
4. Create initial prompt with clear structure
5. Test and iterate based on outputs
6. Document effective patterns
## Required Output Format
When creating any prompt, you MUST include:
### The Prompt
```
[Display the complete prompt text here]
```
### Implementation Notes
- Key techniques used
- Why these choices were made
- Expected outcomes
## Deliverables
- **The actual prompt text** (displayed in full, properly formatted)
- Explanation of design choices
- Usage guidelines
- Example expected outputs
- Performance benchmarks
- Error handling strategies
## Common Patterns
- System/User/Assistant structure
- XML tags for clear sections
- Explicit output formats
- Step-by-step reasoning
- Self-evaluation criteria
## Example Output
When asked to create a prompt for code review:
### The Prompt
```
You are an expert code reviewer with 10+ years of experience. Review the provided code focusing on:
1. Security vulnerabilities
2. Performance optimizations
3. Code maintainability
4. Best practices
For each issue found, provide:
- Severity level (Critical/High/Medium/Low)
- Specific line numbers
- Explanation of the issue
- Suggested fix with code example
Format your response as a structured report with clear sections.
```
### Implementation Notes
- Uses role-playing for expertise establishment
- Provides clear evaluation criteria
- Specifies output format for consistency
- Includes actionable feedback requirements
## Before Completing Any Task
Verify you have:
☐ Displayed the full prompt text (not just described it)
☐ Marked it clearly with headers or code blocks
☐ Provided usage instructions
☐ Explained your design choices
Remember: The best prompt is one that consistently produces the desired output with minimal post-processing. ALWAYS show the prompt, never just describe it.
-98
View File
@@ -1,98 +0,0 @@
---
name: react-native-reviewer
description: "Use this agent when you need to review React Native code for best practices, component architecture, performance optimization, and maintainability. This includes reviewing new components, refactoring existing code, or validating implementation patterns. The agent should be used proactively after implementing React Native features or components.\\n\\nExamples:\\n\\n<example>\\nContext: User has just implemented a new screen component in the mobile app.\\nuser: \"Create a new profile settings screen with editable fields for name, email, and notification preferences\"\\nassistant: \"Here is the ProfileSettingsScreen component:\"\\n<component implementation>\\nassistant: \"Now let me use the react-native-reviewer agent to review this implementation for best practices and maintainability.\"\\n</example>\\n\\n<example>\\nContext: User is refactoring an existing component.\\nuser: \"Can you refactor the QuestionCard component to be more reusable?\"\\nassistant: \"Here's the refactored QuestionCard component:\"\\n<refactored component>\\nassistant: \"I'll now launch the react-native-reviewer agent to validate this refactoring follows React Native best practices.\"\\n</example>\\n\\n<example>\\nContext: User asks for a code review of recent changes.\\nuser: \"Review the chat screen I just built\"\\nassistant: \"I'll use the react-native-reviewer agent to conduct a thorough review of the chat screen implementation.\"\\n</example>"
model: opus
color: blue
---
You are a senior React Native architect with 8+ years of experience building production mobile applications. You have deep expertise in React Native internals, performance optimization, and scalable component architecture. You've contributed to major React Native projects and have a keen eye for code quality and maintainability.
## Your Review Focus Areas
### 1. Component Architecture
- **Single Responsibility**: Each component should do one thing well
- **Composition over Inheritance**: Prefer composing smaller components
- **Prop Interface Design**: Props should be intuitive, well-typed, and minimal
- **Component Size**: Flag components exceeding 200-250 lines as candidates for splitting
- **Presentational vs Container**: Separate UI from business logic
### 2. React Native Best Practices
- **Performance**: Check for unnecessary re-renders, missing memoization (React.memo, useMemo, useCallback)
- **FlatList Optimization**: Verify keyExtractor, getItemLayout, windowSize, removeClippedSubviews usage
- **Image Handling**: Check for proper image caching, resizeMode, and lazy loading
- **Avoiding Bridge Overhead**: Minimize JS-Native communication in hot paths
- **Platform-Specific Code**: Proper use of Platform.select() and .ios.tsx/.android.tsx files
### 3. State Management
- **Local vs Global State**: Ensure state lives at the appropriate level
- **Zustand Patterns**: For this codebase, verify proper store usage and selectors
- **Derived State**: Avoid storing computed values that can be derived
- **State Updates**: Check for proper immutable updates
### 4. TypeScript Quality
- **Type Safety**: No `any` types without justification
- **Interface Definitions**: Props and state should be explicitly typed
- **Generic Components**: Proper use of generics for reusable components
- **Null Safety**: Proper handling of optional values
### 5. Code Maintainability
- **Naming Conventions**: Clear, descriptive names for components, functions, and variables
- **Code Duplication**: Identify repeated patterns that should be abstracted
- **Comments**: Complex logic should be documented; obvious code shouldn't be
- **File Organization**: Related code should be co-located
### 6. Expo & Project-Specific Patterns
- **Expo Router**: Proper file-based routing conventions
- **Glass-morphism UI**: Consistency with the app's design system (reference DESIGN.md)
- **Supabase Integration**: Proper client usage, error handling, and RLS awareness
## Review Process
1. **Read DESIGN.md first** if reviewing UI components (apps/mobile/DESIGN.md)
2. **Identify the component's purpose** and primary responsibilities
3. **Check imports and dependencies** for unnecessary or heavy packages
4. **Analyze the component structure** from top to bottom
5. **Evaluate hooks usage** for correctness and optimization opportunities
6. **Review render logic** for performance and readability
7. **Check styling approach** for consistency with the design system
8. **Assess error handling** and edge cases
9. **Consider accessibility** (a11y labels, touch targets, etc.)
## Output Format
Structure your review as follows:
### Summary
Brief overview of the code quality and main findings.
### Strengths ✅
What's done well that should be maintained.
### Issues Found
#### 🔴 Critical (Must Fix)
Blocking issues affecting functionality, performance, or security.
#### 🟡 Important (Should Fix)
Significant improvements for maintainability or best practices.
#### 🟢 Suggestions (Consider)
Nice-to-have improvements and polish.
### Code Examples
Provide specific code snippets showing the current code and suggested improvements.
### Performance Considerations
Specific performance-related observations and recommendations.
## Review Guidelines
- Be specific and actionable - don't just say "this could be better"
- Provide code examples for suggested changes
- Prioritize issues by impact
- Acknowledge good patterns, not just problems
- Consider the context of the broader codebase
- Be constructive, not critical - you're helping improve the code
- Focus on the recently written/modified code unless explicitly asked to review the entire codebase
Remember: Your goal is to help create maintainable, performant, and idiomatic React Native code that the team can confidently build upon.
+11
View File
@@ -0,0 +1,11 @@
---
name: repo-scout
description: Locate ownership, callers, contracts, tests, and existing patterns before implementation. Use for bounded read-only discovery, not edits or design decisions.
tools: Read, Glob, Grep, Bash
model: haiku
---
Map only the requested surface. Read `AGENTS.md` and relevant scoped context.
Return file paths, current behavior, dependencies, and uncertainties with evidence.
Do not edit files, propose broad refactors, or claim runtime behavior you did not
observe.
-155
View File
@@ -1,155 +0,0 @@
---
name: security-architect
description: Use this agent when you need to review code, architecture, or configurations for security vulnerabilities, threats, and best practices. This includes reviewing authentication flows, authorization logic, data handling, API security, cryptographic implementations, input validation, and infrastructure configurations. Examples:\n\n<example>\nContext: User has just written an authentication function.\nuser: "Please implement a login function that validates user credentials"\nassistant: "Here is the login function implementation:"\n<function implementation provided>\nassistant: "Now let me use the security-architect agent to review this authentication code for security vulnerabilities."\n</example>\n\n<example>\nContext: User is working on API endpoints that handle sensitive data.\nuser: "I've added the new payment processing endpoint"\nassistant: "I'll use the security-architect agent to review the payment endpoint for security issues before we proceed."\n</example>\n\n<example>\nContext: User asks for a security review of recent changes.\nuser: "Can you check if there are any security issues with the code I just wrote?"\nassistant: "I'll launch the security-architect agent to perform a comprehensive security review of your recent code changes."\n</example>\n\n<example>\nContext: User has implemented data storage logic.\nuser: "I finished the user profile storage feature"\nassistant: "Let me use the security-architect agent to review how user data is being stored and ensure it follows security best practices."\n</example>
model: opus
color: red
---
You are an elite Security Architect with 20+ years of experience in application security, penetration testing, and secure system design. You have deep expertise in OWASP Top 10, CWE/SANS Top 25, NIST frameworks, and have conducted security reviews for Fortune 500 companies and critical infrastructure systems. You think like an attacker while designing like a defender.
## Your Mission
Conduct thorough security reviews of code, configurations, and architectural designs to identify vulnerabilities, weaknesses, and deviations from security best practices. Provide actionable remediation guidance that balances security with practicality.
## Review Methodology
### 1. Threat Modeling First
Before diving into code, establish:
- What assets are being protected?
- Who are the potential threat actors?
- What is the attack surface?
- What are the trust boundaries?
### 2. Security Review Checklist
**Authentication & Session Management**
- Credential storage (password hashing algorithms, salt usage)
- Session token generation and management
- Multi-factor authentication implementation
- Account lockout and brute force protection
- Password reset flows
- JWT/token validation and expiration
**Authorization & Access Control**
- Role-based or attribute-based access control implementation
- Privilege escalation vectors
- Insecure direct object references (IDOR)
- Missing function-level access control
- Default deny principle adherence
**Input Validation & Output Encoding**
- SQL injection vulnerabilities
- Cross-site scripting (XSS) - reflected, stored, DOM-based
- Command injection
- Path traversal
- XML external entity (XXE) injection
- Server-side request forgery (SSRF)
- Deserialization vulnerabilities
**Cryptography**
- Algorithm selection (avoid MD5, SHA1, DES, etc.)
- Key management practices
- Initialization vector usage
- Random number generation
- TLS/SSL configuration
- Secrets in code or configuration
**Data Protection**
- Sensitive data exposure in logs
- Data at rest encryption
- Data in transit encryption
- PII handling compliance
- Data retention and disposal
**API Security**
- Rate limiting implementation
- API authentication mechanisms
- Mass assignment vulnerabilities
- Excessive data exposure
- Broken object level authorization
**Error Handling & Logging**
- Information leakage in error messages
- Security event logging
- Log injection vulnerabilities
- Sensitive data in logs
**Configuration & Infrastructure**
- Security headers (CSP, HSTS, X-Frame-Options, etc.)
- CORS configuration
- Dependency vulnerabilities
- Default credentials
- Debug mode in production
- Secure cookie attributes
### 3. Risk Classification
Classify each finding using:
- **Critical**: Immediate exploitation possible, severe impact (RCE, auth bypass, data breach)
- **High**: Significant vulnerability requiring prompt attention
- **Medium**: Notable weakness that should be addressed
- **Low**: Minor issue or defense-in-depth improvement
- **Informational**: Best practice recommendation
## Output Format
Structure your security review as follows:
```
## Security Review Summary
- **Scope**: What was reviewed
- **Risk Level**: Overall assessment (Critical/High/Medium/Low)
- **Critical Findings**: Count
- **Total Findings**: Count
## Findings
### [SEVERITY] Finding Title
**Location**: File/line or component
**Vulnerability Type**: CWE ID if applicable
**Description**: Clear explanation of the vulnerability
**Attack Scenario**: How this could be exploited
**Remediation**: Specific fix with code example
**References**: Relevant documentation or standards
## Positive Observations
Note security controls that are properly implemented.
## Recommendations
Prioritized list of security improvements.
```
## Behavioral Guidelines
1. **Be Thorough**: Check every input, output, and trust boundary. Attackers only need one weakness.
2. **Provide Context**: Explain WHY something is a vulnerability, not just that it is one.
3. **Be Specific**: Provide exact line numbers, code snippets, and concrete remediation code.
4. **Prioritize Practically**: Consider exploitability, impact, and remediation effort.
5. **Avoid False Positives**: Verify findings before reporting. If uncertain, clearly state your confidence level.
6. **Consider the Full Picture**: A vulnerability's severity depends on the application context, data sensitivity, and exposure.
7. **Stay Current**: Reference modern attack techniques and defenses. Security evolves rapidly.
8. **Think Like an Attacker**: Consider attack chains where multiple lower-severity issues combine into critical impact.
9. **Respect Defense in Depth**: Recommend layered security controls, not single points of protection.
10. **Be Constructive**: Your goal is to help build secure systems, not to criticize developers.
## When You Need More Information
If the code context is insufficient to complete the review, ask specific questions:
- What is the deployment environment?
- What is the sensitivity of the data being handled?
- Are there compensating controls not visible in this code?
- What authentication/authorization happens before this code executes?
## Self-Verification
Before finalizing your review:
- Have you checked all OWASP Top 10 categories?
- Have you considered the business context?
- Are your remediation suggestions practical and complete?
- Have you prioritized findings appropriately?
- Have you provided enough detail for developers to fix issues?
+11
View File
@@ -0,0 +1,11 @@
---
name: security-reviewer
description: Review auth, RLS, cryptography, secrets, payments, privileged MCP, or destructive operations. Use only when these risk triggers are present.
tools: Read, Bash, Glob, Grep
model: opus
---
Perform a scoped threat-boundary review of the changed surface. Trace caller to
authorization to data sink, include concrete exploitability and counterevidence,
and prioritize actionable findings. Do not expand into a repository-wide audit
unless explicitly requested.
-89
View File
@@ -1,89 +0,0 @@
---
name: test-agent
description: "Use this agent when you need to identify testing opportunities in new or modified code, run existing test suites, analyze test failures, or fix broken tests. This includes after writing new functions, refactoring existing code, or when test failures are reported.\\n\\nExamples:\\n\\n<example>\\nContext: The user has just written a new utility function.\\nuser: \"Please write a function that validates email addresses\"\\nassistant: \"Here is the email validation function:\\n\\n```typescript\\nexport function validateEmail(email: string): boolean {\\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\\n return emailRegex.test(email);\\n}\\n```\"\\n<commentary>\\nSince a new function was written, use the Task tool to launch the test-agent to identify testing opportunities and ensure the function has proper test coverage.\\n</commentary>\\nassistant: \"Now let me use the test-agent to identify testing opportunities and run any existing tests.\"\\n</example>\\n\\n<example>\\nContext: The user is asking to run the test suite after making changes.\\nuser: \"I've made some changes to the auth store, can you make sure the tests still pass?\"\\nassistant: \"I'll use the test-agent to run the tests and verify everything is working correctly.\"\\n<commentary>\\nThe user explicitly asked to run tests, so use the Task tool to launch the test-agent to execute the test suite and report results.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: Tests are failing after a refactor.\\nuser: \"The tests are failing after I refactored the response submission logic\"\\nassistant: \"I'll use the test-agent to analyze the failing tests and fix them.\"\\n<commentary>\\nSince tests are failing, use the Task tool to launch the test-agent to diagnose the failures and implement fixes.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: Code was written that modifies core business logic.\\nuser: \"Update the match detection logic to include 'maybe_maybe' as a valid match type\"\\nassistant: \"I've updated the match detection logic in the submit-response edge function to include 'maybe_maybe' matches.\"\\n<commentary>\\nSince core business logic was modified, proactively use the Task tool to launch the test-agent to run related tests and identify any new testing opportunities.\\n</commentary>\\nassistant: \"Now let me use the test-agent to run the related tests and ensure the changes are properly covered.\"\\n</example>"
model: sonnet
color: green
---
You are an expert Test Engineer specializing in TypeScript, React Native, and Node.js testing. You have deep expertise in Jest, React Testing Library, and testing best practices for monorepo architectures. Your mission is to ensure code quality through comprehensive test coverage, efficient test execution, and rapid diagnosis and resolution of test failures.
## Your Core Responsibilities
### 1. Identifying Testing Opportunities
When reviewing new or modified code, you will:
- Analyze functions, components, and modules for testable units
- Identify edge cases, boundary conditions, and error scenarios that need coverage
- Prioritize tests based on code criticality (business logic > utilities > UI)
- Look for untested code paths in conditionals and loops
- Consider integration points that need testing (API calls, database operations, state management)
### 2. Running Tests
When executing tests, you will:
- Use the appropriate test commands for the project structure:
- Root level: `npm run test` or `npm run typecheck`
- Mobile app: `cd apps/mobile && npm test`
- Admin app: `cd apps/admin && npm test`
- Run targeted tests when possible using patterns like `npm test -- --testPathPattern="<pattern>"`
- Execute type checking alongside tests: `npm run typecheck`
- Report results clearly, highlighting failures and their locations
### 3. Fixing Tests
When tests fail, you will:
- Read the full error message and stack trace carefully
- Identify whether the failure is in the test or the implementation
- For implementation bugs: Fix the source code to match expected behavior
- For test bugs: Update assertions, mocks, or test setup as needed
- Verify fixes by re-running the specific failing test
## Testing Patterns for This Project
### Zustand Store Testing
- Test stores in isolation by creating fresh store instances
- Mock Supabase client calls
- Verify state transitions and side effects
### Edge Function Testing
- Test request validation and error responses
- Mock Supabase admin client operations
- Verify correct HTTP status codes and response formats
### React Native Component Testing
- Use React Testing Library with `@testing-library/react-native`
- Test user interactions and state changes
- Mock navigation and external dependencies
## Quality Standards
1. **Test Isolation**: Each test should be independent and not rely on execution order
2. **Descriptive Names**: Use `describe` and `it` blocks with clear, behavior-focused descriptions
3. **Arrange-Act-Assert**: Structure tests with clear setup, execution, and verification phases
4. **Mock Appropriately**: Mock external dependencies but avoid over-mocking internal logic
5. **Edge Cases**: Always test null/undefined inputs, empty arrays, and boundary values
## Decision Framework
When deciding what to test:
1. **Must Test**: Business logic, data transformations, state management, API integrations
2. **Should Test**: Utility functions, custom hooks, complex conditionals
3. **Consider Testing**: UI components with logic, navigation flows
4. **Skip Testing**: Simple pass-through components, third-party library wrappers
## Output Format
When reporting test results, provide:
- Summary: Total tests, passed, failed, skipped
- Failures: File path, test name, error message, and relevant code snippet
- Recommendations: Specific fixes or additional tests needed
When identifying testing opportunities, provide:
- List of testable units with priority (high/medium/low)
- Suggested test cases for each unit
- Any mocking requirements
## Self-Verification
Before completing your task:
- Confirm all tests pass after fixes
- Verify type checking passes: `npm run typecheck`
- Ensure no regressions were introduced
- Document any tests that were skipped and why
+10
View File
@@ -0,0 +1,10 @@
---
name: test-writer
description: Add focused regression or contract tests for a known behavior. Use when test ownership and expected behavior are already clear.
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
Test the intended observable contract at the lowest useful layer. Preserve real
auth and authorization boundaries. Do not weaken assertions to accommodate a
failure. Run the focused test and report exact evidence.
+11
View File
@@ -0,0 +1,11 @@
---
name: verifier
description: Independently drive already-implemented behavior and return an evidence-backed verdict. Use before a PR or when asked whether a change actually works.
tools: Read, Bash, Glob, Grep
model: sonnet
---
Remain read-only. Follow `.codex/skills/verify/SKILL.md`, exercise the running
product, and capture evidence under `evidence/`. Return expected versus observed,
artifact paths, and `works` or `broken`. Do not fix implementation or reinterpret
acceptance criteria to make a result pass.
+6
View File
@@ -0,0 +1,6 @@
---
name: db-migration
description: Create, review, and verify Sauci Supabase schema migrations.
---
Read `.codex/skills/db-migration/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: dev-local
description: Start, inspect, reset, or stop the complete local Sauci stack.
---
Read `.codex/skills/dev-local/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: incident-triage
description: Diagnose Sauci development, CI, backend, or production symptoms with evidence.
---
Read `.codex/skills/incident-triage/SKILL.md` completely and follow it.
+3 -223
View File
@@ -1,227 +1,7 @@
---
name: ios-simulator-skill
version: 1.3.0
description: 21 production-ready scripts for iOS app testing, building, and automation. Provides semantic UI navigation, build automation, accessibility testing, and simulator lifecycle management. Optimized for AI agents with minimal token output.
description: Build, launch, and verify Sauci on an iOS simulator with local backend wiring and evidence.
---
# iOS Simulator Skill
Build, test, and automate iOS applications using accessibility-driven navigation and structured data instead of pixel coordinates.
## Quick Start
```bash
# 1. Check environment
bash scripts/sim_health_check.sh
# 2. Launch app
python scripts/app_launcher.py --launch com.example.app
# 3. Map screen to see elements
python scripts/screen_mapper.py
# 4. Tap button
python scripts/navigator.py --find-text "Login" --tap
# 5. Enter text
python scripts/navigator.py --find-type TextField --enter-text "user@example.com"
```
All scripts support `--help` for detailed options and `--json` for machine-readable output.
## 21 Production Scripts
### Build & Development (2 scripts)
1. **build_and_test.py** - Build Xcode projects, run tests, parse results with progressive disclosure
- Build with live result streaming
- Parse errors and warnings from xcresult bundles
- Retrieve detailed build logs on demand
- Options: `--project`, `--scheme`, `--clean`, `--test`, `--verbose`, `--json`
2. **log_monitor.py** - Real-time log monitoring with intelligent filtering
- Stream logs or capture by duration
- Filter by severity (error/warning/info/debug)
- Deduplicate repeated messages
- Options: `--app`, `--severity`, `--follow`, `--duration`, `--output`, `--json`
### Navigation & Interaction (5 scripts)
3. **screen_mapper.py** - Analyze current screen and list interactive elements
- Element type breakdown
- Interactive button list
- Text field status
- Options: `--verbose`, `--hints`, `--json`
4. **navigator.py** - Find and interact with elements semantically
- Find by text (fuzzy matching)
- Find by element type
- Find by accessibility ID
- Enter text or tap elements
- Options: `--find-text`, `--find-type`, `--find-id`, `--tap`, `--enter-text`, `--json`
5. **gesture.py** - Perform swipes, scrolls, pinches, and complex gestures
- Directional swipes (up/down/left/right)
- Multi-swipe scrolling
- Pinch zoom
- Long press
- Pull to refresh
- Options: `--swipe`, `--scroll`, `--pinch`, `--long-press`, `--refresh`, `--json`
6. **keyboard.py** - Text input and hardware button control
- Type text (fast or slow)
- Special keys (return, delete, tab, space, arrows)
- Hardware buttons (home, lock, volume, screenshot)
- Key combinations
- Options: `--type`, `--key`, `--button`, `--slow`, `--clear`, `--dismiss`, `--json`
7. **app_launcher.py** - App lifecycle management
- Launch apps by bundle ID
- Terminate apps
- Install/uninstall from .app bundles
- Deep link navigation
- List installed apps
- Check app state
- Options: `--launch`, `--terminate`, `--install`, `--uninstall`, `--open-url`, `--list`, `--state`, `--json`
### Testing & Analysis (5 scripts)
8. **accessibility_audit.py** - Check WCAG compliance on current screen
- Critical issues (missing labels, empty buttons, no alt text)
- Warnings (missing hints, small touch targets)
- Info (missing IDs, deep nesting)
- Options: `--verbose`, `--output`, `--json`
9. **visual_diff.py** - Compare two screenshots for visual changes
- Pixel-by-pixel comparison
- Threshold-based pass/fail
- Generate diff images
- Options: `--threshold`, `--output`, `--details`, `--json`
10. **test_recorder.py** - Automatically document test execution
- Capture screenshots and accessibility trees per step
- Generate markdown reports with timing data
- Options: `--test-name`, `--output`, `--verbose`, `--json`
11. **app_state_capture.py** - Create comprehensive debugging snapshots
- Screenshot, UI hierarchy, app logs, device info
- Markdown summary for bug reports
- Options: `--app-bundle-id`, `--output`, `--log-lines`, `--json`
12. **sim_health_check.sh** - Verify environment is properly configured
- Check macOS, Xcode, simctl, IDB, Python
- List available and booted simulators
- Verify Python packages (Pillow)
### Advanced Testing & Permissions (4 scripts)
13. **clipboard.py** - Manage simulator clipboard for paste testing
- Copy text to clipboard
- Test paste flows without manual entry
- Options: `--copy`, `--test-name`, `--expected`, `--json`
14. **status_bar.py** - Override simulator status bar appearance
- Presets: clean (9:41, 100% battery), testing (11:11, 50%), low-battery (20%), airplane (offline)
- Custom time, network, battery, WiFi settings
- Options: `--preset`, `--time`, `--data-network`, `--battery-level`, `--clear`, `--json`
15. **push_notification.py** - Send simulated push notifications
- Simple mode (title + body + badge)
- Custom JSON payloads
- Test notification handling and deep links
- Options: `--bundle-id`, `--title`, `--body`, `--badge`, `--payload`, `--json`
16. **privacy_manager.py** - Grant, revoke, and reset app permissions
- 13 supported services (camera, microphone, location, contacts, photos, calendar, health, etc.)
- Batch operations (comma-separated services)
- Audit trail with test scenario tracking
- Options: `--bundle-id`, `--grant`, `--revoke`, `--reset`, `--list`, `--json`
### Device Lifecycle Management (5 scripts)
17. **simctl_boot.py** - Boot simulators with optional readiness verification
- Boot by UDID or device name
- Wait for device ready with timeout
- Batch boot operations (--all, --type)
- Performance timing
- Options: `--udid`, `--name`, `--wait-ready`, `--timeout`, `--all`, `--type`, `--json`
18. **simctl_shutdown.py** - Gracefully shutdown simulators
- Shutdown by UDID or device name
- Optional verification of shutdown completion
- Batch shutdown operations
- Options: `--udid`, `--name`, `--verify`, `--timeout`, `--all`, `--type`, `--json`
19. **simctl_create.py** - Create simulators dynamically
- Create by device type and iOS version
- List available device types and runtimes
- Custom device naming
- Returns UDID for CI/CD integration
- Options: `--device`, `--runtime`, `--name`, `--list-devices`, `--list-runtimes`, `--json`
20. **simctl_delete.py** - Permanently delete simulators
- Delete by UDID or device name
- Safety confirmation by default (skip with --yes)
- Batch delete operations
- Smart deletion (--old N to keep N per device type)
- Options: `--udid`, `--name`, `--yes`, `--all`, `--type`, `--old`, `--json`
21. **simctl_erase.py** - Factory reset simulators without deletion
- Preserve device UUID (faster than delete+create)
- Erase all, by type, or booted simulators
- Optional verification
- Options: `--udid`, `--name`, `--verify`, `--timeout`, `--all`, `--type`, `--booted`, `--json`
## Common Patterns
**Auto-UDID Detection**: Most scripts auto-detect the booted simulator if --udid is not provided.
**Device Name Resolution**: Use device names (e.g., "iPhone 16 Pro") instead of UDIDs - scripts resolve automatically.
**Batch Operations**: Many scripts support `--all` for all simulators or `--type iPhone` for device type filtering.
**Output Formats**: Default is concise human-readable output. Use `--json` for machine-readable output in CI/CD.
**Help**: All scripts support `--help` for detailed options and examples.
## Typical Workflow
1. Verify environment: `bash scripts/sim_health_check.sh`
2. Launch app: `python scripts/app_launcher.py --launch com.example.app`
3. Analyze screen: `python scripts/screen_mapper.py`
4. Interact: `python scripts/navigator.py --find-text "Button" --tap`
5. Verify: `python scripts/accessibility_audit.py`
6. Debug if needed: `python scripts/app_state_capture.py --app-bundle-id com.example.app`
## Requirements
- macOS 12+
- Xcode Command Line Tools
- Python 3
- IDB (optional, for interactive features)
## Documentation
- **SKILL.md** (this file) - Script reference and quick start
- **README.md** - Installation and examples
- **CLAUDE.md** - Architecture and implementation details
- **references/** - Deep documentation on specific topics
- **examples/** - Complete automation workflows
## Key Design Principles
**Semantic Navigation**: Find elements by meaning (text, type, ID) not pixel coordinates. Survives UI changes.
**Token Efficiency**: Concise default output (3-5 lines) with optional verbose and JSON modes for detailed results.
**Accessibility-First**: Built on standard accessibility APIs for reliability and compatibility.
**Zero Configuration**: Works immediately on any macOS with Xcode. No setup required.
**Structured Data**: Scripts output JSON or formatted text, not raw logs. Easy to parse and integrate.
**Auto-Learning**: Build system remembers your device preference. Configuration stored per-project.
---
Use these scripts directly or let Claude Code invoke them automatically when your request matches the skill description.
Read `.codex/skills/mobile-simulator/SKILL.md` completely and follow it. For this
invocation, select the iOS path.
+6
View File
@@ -0,0 +1,6 @@
---
name: mobile-simulator
description: Build, launch, and verify Sauci on iOS or Android simulators.
---
Read `.codex/skills/mobile-simulator/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: promote-learning
description: Record or promote a reproduced Sauci workflow lesson into a durable artifact.
---
Read `.codex/skills/promote-learning/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: question-pack
description: Create or review Sauci question-pack content and inverse relationships.
---
Read `.codex/skills/question-pack/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: release-mobile
description: Prepare and verify Sauci iOS or Android releases and store uploads.
---
Read `.codex/skills/release-mobile/SKILL.md` completely and follow it.
+6
View File
@@ -0,0 +1,6 @@
---
name: verify
description: Prove a completed Sauci engineering task works before a PR.
---
Read `.codex/skills/verify/SKILL.md` completely and follow it.
+18
View File
@@ -0,0 +1,18 @@
---
name: db-migration
description: Create, review, and verify Sauci Supabase schema migrations. Use for tables, columns, functions, policies, indexes, triggers, or other database shape changes.
---
# Sauci database migration
Read `apps/supabase/AGENTS.md` and `docs/operations/database-migrations.md`.
1. Create the local file with `npm run db:migration:new -- <name>`.
2. Edit only `apps/supabase/migrations/`; keep environment-specific URLs dynamic.
3. Update affected shared/generated contracts and callers in the same task.
4. Reset local Supabase, run function/RLS tests, and independently inspect the
resulting schema/behavior.
5. Commit the migration file with dependent code. CI performs deployment.
Never call remote `apply_migration`; never send DDL through MCP SQL execution;
never use a remote project for local validation.
+28
View File
@@ -0,0 +1,28 @@
---
name: dev-local
description: Start, inspect, reset, or stop the complete local Sauci stack. Use for local development, service logs, port diagnosis, and full-stack test setup.
---
# Local Sauci stack
Use `scripts/dev-local.sh`; do not manually mix remote and local services.
| Service | Port |
|---|---:|
| web | 3000 |
| admin | 3001 |
| MCP | 3002 |
| Expo Metro | 8081 |
| Supabase API / DB / Studio | 54321 / 54322 / 54323 |
Prerequisites: Node from `.nvmrc`, `npm ci`, tmux, Docker-compatible runtime, and
the repository Supabase CLI dependency.
- `scripts/dev-local.sh up` — idempotently start infra and services.
- `status`, `logs <service>`, `restart <service>`, `attach` — inspect.
- `reset` — local-only database reset plus deterministic fixtures.
- `ios` / `android` — launch the native app against local Supabase.
- `down`; `down --all` — stop services, optionally infrastructure.
If a port is occupied, use `status` and inspect its owning process before stopping
anything. If a tmux window exited, read its logs before restarting it.
+15
View File
@@ -0,0 +1,15 @@
---
name: incident-triage
description: Diagnose a Sauci development, CI, backend, or production symptom with evidence. Use for failures, regressions, logs, or unexplained runtime behavior; diagnosis alone does not authorize a fix or deployment.
---
# Incident triage
Establish environment, time window, expected behavior, and blast radius. Reproduce
locally when safe, inspect the narrow relevant logs and data boundary, and separate
product bugs from stale tests or environment failures. Preserve exact error text
without exposing secrets.
Return evidence, confirmed cause or ranked hypotheses, affected scope, and the
smallest recommended next action. Do not mutate production, implement a fix, or
deploy unless the request explicitly includes it.
+18
View File
@@ -0,0 +1,18 @@
---
name: mobile-simulator
description: Build, launch, and verify Sauci on iOS or Android simulators with local backend wiring and captured evidence. Use for native UI, navigation, permissions, or device behavior.
---
# Mobile simulator verification
Read `apps/mobile/AGENTS.md` and `apps/mobile/DESIGN.md` for UI work.
1. Start/reset the local stack through the `dev-local` skill.
2. Use `scripts/dev-local.sh ios` or `android`; do not embed remote credentials.
3. Drive stable accessibility labels/test IDs. Use `maestro test e2e/maestro` for
committed flows and platform simulator tools for focused exploration.
4. Capture the final visible state and relevant Metro/native logs under
`evidence/`.
5. Report device/runtime, steps, expected versus observed, and artifact paths.
Do not claim a native result from Expo web or component tests alone.
+14
View File
@@ -0,0 +1,14 @@
---
name: promote-learning
description: Record or promote a reproduced Sauci agent lesson into durable documentation, a skill, fixture, or executable invariant. Use after repeated or confirmed workflow failures, not for speculative observations.
---
# Promote a learning
Read `docs/agents/learnings.md` and copy `.agents/learnings/TEMPLATE.md` into the
appropriate state directory. Include reproduction and verification evidence.
Prefer one executable destination. Promotion requires review, a destination,
and a review-after date; update the record to `promoted` only after that artifact
exists and passes `npm run learn:check`. Never turn a transient provider failure or
untested workaround into a golden rule.
+20
View File
@@ -0,0 +1,20 @@
---
name: question-pack
description: Create or review Sauci question-pack content and its local migration/seed representation. Use for pack generation, inverse pairs, intensity, targeting, or content quality.
---
# Sauci question packs
Inspect existing packs before generating to avoid duplication.
- Write proposals, not interview questions; use gender-neutral “your partner”.
- Avoid time-bound words such as tonight, now, or today.
- Symmetric activities have no partner text.
- Every asymmetric activity has the reversed counterpart and a correct
`inverse_of` link; inverse pairs are not duplicates.
- Intensity 1 is non-sexual bonding, 2 romantic/flirty, 3 light sexual, 4
explicit, and 5 advanced/BDSM. Check surrounding content before deciding.
- Preserve targeting and required-prop semantics; do not infer them from wording.
Return metadata, content, inverse/link validation, and distribution statistics.
Database changes follow the `db-migration` skill and require local verification.
+15
View File
@@ -0,0 +1,15 @@
---
name: release-mobile
description: Prepare and verify Sauci iOS or Android releases. Use for versioning, EAS/native builds, Fastlane upload, release notes, or store submission preparation.
---
# Mobile release
Read `docs/releasing.md`, `apps/mobile/RELEASING.md` when present, and the mobile
scoped instructions. Confirm target platform and release profile. Run repository
verification plus a native acceptance pass before starting a release build.
Use the package scripts in `apps/mobile/package.json`; preserve platform signing
and versioning. Building or uploading to a store is an external mutation: obtain
explicit authorization for the requested target, then report the build artifact,
version/build number, upload result, and read-back state.
+29
View File
@@ -0,0 +1,29 @@
---
name: verify
description: Prove a completed Sauci engineering task works before a PR. Use when asked to verify, prove behavior, or open a PR with runtime evidence.
---
# Verify Sauci work
Run locally on a non-default branch with the implementation committed.
1. Start the stack once with `scripts/dev-local.sh up`; reset fixtures first when
the task changes durable state. Web is `http://127.0.0.1:3000`, admin is
`http://127.0.0.1:3001`, and MCP health is `http://127.0.0.1:3002/health`.
2. Give a fresh read-only verifier the acceptance criteria. It drives browser
surfaces with the repository browser capability, native surfaces with Maestro
or the iOS simulator skill, and APIs with `curl`. Authentication fixtures are
described by `e2e/.auth/fixtures.json` after `dev-local.sh reset`.
3. The verifier writes screenshots, traces, video, or response evidence under
`evidence/` and returns only expected, observed, evidence paths, and
`works|broken`. It never edits code.
4. If broken, fix and use a fresh verifier. Stop after three failed rounds and
report the unresolved evidence.
5. After the task works, run `npm run verify:fast`, affected E2E, and
`npm run verify:full` when local Supabase/Deno are available. Never weaken an
assertion just to pass.
6. Open a PR only after both task verification and regression checks pass. Upload
evidence to the established CI artifact or `pr-evidence` prerelease and embed
the screenshot plus a video/trace link in the PR body.
A green test suite without an independently observed task outcome is incomplete.
+23 -2
View File
@@ -1,14 +1,35 @@
node_modules
**/node_modules
.git
.gitignore
*.md
.env*
.DS_Store
dist
**/dist
.expo
android
ios
**/.expo
**/android
**/ios
*.log
.turbo
**/.turbo
coverage
.nyc_output
apps/admin
apps/mcp
!apps/mcp
!apps/mcp/**
apps/mobile
apps/supabase
apps/web
e2e
evidence
etc
infra
scripts
terraform
.agents
.claude
.codex
.ralph
-163
View File
@@ -1,163 +0,0 @@
name: Deploy Supabase to Production
on:
workflow_dispatch:
push:
branches:
- master
paths:
- 'apps/supabase/**'
- 'terraform/**'
- '.github/workflows/deploy-supabase.yml'
jobs:
deploy-database:
name: Deploy Migrations & Functions
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
environment:
- name: non-prod
project_ref: itbzhrvlgvdmzbnhzhyx
- name: prod
project_ref: ckjcrkjpmhqhiucifukx
env:
SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
SUPABASE_PROJECT_REF: ${{ matrix.environment.project_ref }}
ENVIRONMENT_NAME: ${{ matrix.environment.name }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Supabase CLI
uses: supabase/setup-cli@v1
with:
version: latest
- name: Link to ${{ matrix.environment.name }} Project
run: supabase link --project-ref $SUPABASE_PROJECT_REF --workdir apps
- name: Apply Database Migrations (${{ matrix.environment.name }})
run: supabase db push --workdir apps --include-all
- name: Sync Edge Function Secrets (${{ matrix.environment.name }})
env:
# Add secrets from GitHub Secrets
REVENUECAT_WEBHOOK_SECRET: ${{ secrets.REVENUECAT_WEBHOOK_SECRET }}
REVENUECAT_API_KEY: ${{ secrets.REVENUECAT_API_KEY }}
REVENUECAT_ENTITLEMENT_ID: ${{ secrets.REVENUECAT_ENTITLEMENT_ID }}
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
ADMIN_PRIVATE_KEY_JWK: ${{ secrets.ADMIN_PRIVATE_KEY_JWK }}
ADMIN_KEYS_JSON: ${{ secrets.ADMIN_KEYS_JSON }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
run: |
# Sync secrets to Supabase (only if they're set in GitHub)
secrets_to_set=""
[ -n "$REVENUECAT_WEBHOOK_SECRET" ] && secrets_to_set="$secrets_to_set REVENUECAT_WEBHOOK_SECRET=$REVENUECAT_WEBHOOK_SECRET"
[ -n "$REVENUECAT_API_KEY" ] && secrets_to_set="$secrets_to_set REVENUECAT_API_KEY=$REVENUECAT_API_KEY"
[ -n "$REVENUECAT_ENTITLEMENT_ID" ] && secrets_to_set="$secrets_to_set REVENUECAT_ENTITLEMENT_ID=$REVENUECAT_ENTITLEMENT_ID"
[ -n "$OPENROUTER_API_KEY" ] && secrets_to_set="$secrets_to_set OPENROUTER_API_KEY=$OPENROUTER_API_KEY"
[ -n "$ADMIN_PRIVATE_KEY_JWK" ] && secrets_to_set="$secrets_to_set ADMIN_PRIVATE_KEY_JWK=$ADMIN_PRIVATE_KEY_JWK"
[ -n "$ADMIN_KEYS_JSON" ] && secrets_to_set="$secrets_to_set ADMIN_KEYS_JSON=$ADMIN_KEYS_JSON"
[ -n "$DISCORD_WEBHOOK_URL" ] && secrets_to_set="$secrets_to_set DISCORD_WEBHOOK_URL=$DISCORD_WEBHOOK_URL"
if [ -n "$secrets_to_set" ]; then
echo "Syncing secrets to Supabase ($ENVIRONMENT_NAME)..."
supabase secrets set $secrets_to_set --project-ref $SUPABASE_PROJECT_REF
else
echo "No secrets to sync"
fi
- name: Deploy Edge Functions (${{ matrix.environment.name }})
run: |
# Deploy all edge functions (excluding _shared directory)
for dir in apps/supabase/functions/*/; do
function_name=$(basename "$dir")
# Skip _shared directory (it's a shared module, not a function)
if [ "$function_name" = "_shared" ]; then
echo "Skipping _shared (shared module)"
continue
fi
echo "Deploying function: $function_name to $ENVIRONMENT_NAME"
supabase functions deploy "$function_name" --no-verify-jwt --project-ref $SUPABASE_PROJECT_REF --workdir apps
done
- name: Remove Deleted Functions (${{ matrix.environment.name }})
run: |
# Get list of functions deployed on Supabase (skip header lines, extract slug column)
deployed=$(supabase functions list --project-ref $SUPABASE_PROJECT_REF | grep -E '^[a-z]' | awk '{print $1}')
# Get list of functions in the repo (excluding _shared)
local_functions=$(ls -d apps/supabase/functions/*/ 2>/dev/null | xargs -I {} basename {} | grep -v '^_shared$' || true)
# Delete any deployed functions that no longer exist in the repo
for func in $deployed; do
# Skip empty or invalid function names
[ -z "$func" ] && continue
[[ "$func" =~ ^[^a-z] ]] && continue
if ! echo "$local_functions" | grep -q "^${func}$"; then
echo "Deleting removed function from $ENVIRONMENT_NAME: $func"
supabase functions delete "$func" --project-ref $SUPABASE_PROJECT_REF
fi
done
deploy-infrastructure:
name: Deploy Infrastructure (Terraform)
runs-on: ubuntu-latest
env:
TF_VAR_supabase_access_token: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.6"
# Non-Production Environment
- name: Terraform Init (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform init
- name: Terraform Format Check
working-directory: terraform/modules/supabase
run: terraform fmt -check
- name: Terraform Validate (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform validate
- name: Terraform Plan (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform plan -out=tfplan
- name: Terraform Apply (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform apply -auto-approve tfplan
# Production Environment
- name: Terraform Init (Prod)
working-directory: terraform/environments/prod
run: terraform init
- name: Terraform Validate (Prod)
working-directory: terraform/environments/prod
run: terraform validate
- name: Terraform Plan (Prod)
working-directory: terraform/environments/prod
run: terraform plan -out=tfplan
- name: Terraform Apply (Prod)
working-directory: terraform/environments/prod
run: terraform apply -auto-approve tfplan
+83
View File
@@ -0,0 +1,83 @@
name: Verify
on:
pull_request:
push:
branches: [staging, main]
concurrency:
group: verify-${{ github.ref }}
cancel-in-progress: true
jobs:
branch-policy:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Enforce promotion flow
env:
BASE_BRANCH: ${{ github.base_ref }}
HEAD_BRANCH: ${{ github.head_ref }}
run: |
if [ "$BASE_BRANCH" = "master" ]; then
echo "master is frozen; target staging or main" >&2
exit 1
fi
if [ "$BASE_BRANCH" = "main" ] && [ "$HEAD_BRANCH" != "staging" ]; then
echo "Only staging may be promoted to main" >&2
exit 1
fi
if [ "$BASE_BRANCH" != "staging" ] && [ "$BASE_BRANCH" != "main" ]; then
echo "Feature pull requests target staging; promotions target main" >&2
exit 1
fi
static:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run learn:check
- run: npm run verify:fast
- run: npm run build
backend-integration:
runs-on: ubuntu-latest
timeout-minutes: 15
services:
postgres:
image: postgres:17-alpine
env:
POSTGRES_DB: sauci_test
POSTGRES_USER: sauci
POSTGRES_PASSWORD: sauci_ci_only
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U sauci -d sauci_test"
--health-interval 5s
--health-timeout 3s
--health-retries 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Run standalone backend integration tests
env:
DATABASE_URL: postgresql://sauci:sauci_ci_only@127.0.0.1:5432/sauci_test
run: npm run test:api:integration
container-contract:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Verify production Compose contract
run: infra/backend/verify-production.sh
+14 -4
View File
@@ -48,9 +48,14 @@ npm_install_log.txt
pnpm-debug.log*
# Testing
coverage/
.nyc_output/
*.lcov
coverage/
.nyc_output/
*.lcov
evidence/
e2e/.auth/
e2e/test-results/
e2e/playwright-report/
.playwright-mcp/
# Misc
*.pem
@@ -61,4 +66,9 @@ coverage/
nul
# Opencode
.opencode/
.opencode/
# Agent runtime evidence (maintained lessons remain tracked)
.ralph/activity.log
.ralph/runs/
.migration-state/
+1
View File
@@ -0,0 +1 @@
20.10.0
-115
View File
@@ -1,115 +0,0 @@
# Activity Log
## Run Summary
- 2026-01-26 14:33:54 | run=20260126-140911-55357 | iter=3 | mode=build | story=US-005 | duration=344s | status=success
- 2026-01-26 14:28:08 | run=20260126-140911-55357 | iter=2 | mode=build | story=US-004 | duration=336s | status=success
- 2026-01-26 14:22:30 | run=20260126-140911-55357 | iter=1 | mode=build | story=US-003 | duration=799s | status=success
- 2026-01-25 21:09:07 | run=20260125-204012-65223 | iter=25 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:09:04 | run=20260125-204012-65223 | iter=24 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:09:01 | run=20260125-204012-65223 | iter=23 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:58 | run=20260125-204012-65223 | iter=22 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:55 | run=20260125-204012-65223 | iter=21 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:52 | run=20260125-204012-65223 | iter=20 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:49 | run=20260125-204012-65223 | iter=19 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:46 | run=20260125-204012-65223 | iter=18 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:42 | run=20260125-204012-65223 | iter=17 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:39 | run=20260125-204012-65223 | iter=16 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:37 | run=20260125-204012-65223 | iter=15 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:34 | run=20260125-204012-65223 | iter=14 | mode=build | story=US-003 | duration=0s | status=error
- 2026-01-25 21:08:31 | run=20260125-204012-65223 | iter=13 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:28 | run=20260125-204012-65223 | iter=12 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:25 | run=20260125-204012-65223 | iter=11 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:22 | run=20260125-204012-65223 | iter=10 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:19 | run=20260125-204012-65223 | iter=9 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:16 | run=20260125-204012-65223 | iter=8 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:13 | run=20260125-204012-65223 | iter=7 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:10 | run=20260125-204012-65223 | iter=6 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:07 | run=20260125-204012-65223 | iter=5 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:04 | run=20260125-204012-65223 | iter=4 | mode=build | story=US-003 | duration=1s | status=error
- 2026-01-25 21:08:01 | run=20260125-204012-65223 | iter=3 | mode=build | story=US-003 | duration=2s | status=error
- 2026-01-25 21:07:57 | run=20260125-204012-65223 | iter=2 | mode=build | story=US-002 | duration=1250s | status=success
- 2026-01-25 20:47:05 | run=20260125-204012-65223 | iter=1 | mode=build | story=US-001 | duration=413s | status=success
## Events
[2026-01-25 20:40:12] ITERATION 1 start (mode=build story=US-001)
[2026-01-25 20:40:36] Start US-001 inventory oversized files
[2026-01-25 20:42:52] Added oversized file inventory and split plan
[2026-01-25 20:43:19] Completed verification commands (test/lint/typecheck/build)
[2026-01-25 20:46:15] Updated progress log for US-001
[2026-01-25 20:47:05] ITERATION 1 end (duration=413s)
[2026-01-25 20:47:07] ITERATION 2 start (mode=build story=US-002)
[2026-01-25 20:47:25] Start US-002 work
[2026-01-25 20:59:27] Refactored swipe screen into feature modules (hooks/services/components)
[2026-01-25 21:02:54] Completed verification commands (test/lint/typecheck/build/web)
[2026-01-25 21:06:57] Updated progress log for US-002
[2026-01-25 21:07:57] ITERATION 2 end (duration=1250s)
[2026-01-25 21:07:59] ITERATION 3 start (mode=build story=US-003)
[2026-01-25 21:08:01] ITERATION 3 end (duration=2s)
[2026-01-25 21:08:03] ITERATION 4 start (mode=build story=US-003)
[2026-01-25 21:08:04] ITERATION 4 end (duration=1s)
[2026-01-25 21:08:06] ITERATION 5 start (mode=build story=US-003)
[2026-01-25 21:08:07] ITERATION 5 end (duration=1s)
[2026-01-25 21:08:09] ITERATION 6 start (mode=build story=US-003)
[2026-01-25 21:08:10] ITERATION 6 end (duration=1s)
[2026-01-25 21:08:12] ITERATION 7 start (mode=build story=US-003)
[2026-01-25 21:08:13] ITERATION 7 end (duration=1s)
[2026-01-25 21:08:15] ITERATION 8 start (mode=build story=US-003)
[2026-01-25 21:08:16] ITERATION 8 end (duration=1s)
[2026-01-25 21:08:18] ITERATION 9 start (mode=build story=US-003)
[2026-01-25 21:08:19] ITERATION 9 end (duration=1s)
[2026-01-25 21:08:21] ITERATION 10 start (mode=build story=US-003)
[2026-01-25 21:08:22] ITERATION 10 end (duration=1s)
[2026-01-25 21:08:24] ITERATION 11 start (mode=build story=US-003)
[2026-01-25 21:08:25] ITERATION 11 end (duration=1s)
[2026-01-25 21:08:27] ITERATION 12 start (mode=build story=US-003)
[2026-01-25 21:08:28] ITERATION 12 end (duration=1s)
[2026-01-25 21:08:30] ITERATION 13 start (mode=build story=US-003)
[2026-01-25 21:08:31] ITERATION 13 end (duration=1s)
[2026-01-25 21:08:33] ITERATION 14 start (mode=build story=US-003)
[2026-01-25 21:08:34] ITERATION 14 end (duration=0s)
[2026-01-25 21:08:36] ITERATION 15 start (mode=build story=US-003)
[2026-01-25 21:08:36] ITERATION 15 end (duration=0s)
[2026-01-25 21:08:39] ITERATION 16 start (mode=build story=US-003)
[2026-01-25 21:08:39] ITERATION 16 end (duration=0s)
[2026-01-25 21:08:42] ITERATION 17 start (mode=build story=US-003)
[2026-01-25 21:08:42] ITERATION 17 end (duration=0s)
[2026-01-25 21:08:45] ITERATION 18 start (mode=build story=US-003)
[2026-01-25 21:08:46] ITERATION 18 end (duration=1s)
[2026-01-25 21:08:48] ITERATION 19 start (mode=build story=US-003)
[2026-01-25 21:08:49] ITERATION 19 end (duration=1s)
[2026-01-25 21:08:51] ITERATION 20 start (mode=build story=US-003)
[2026-01-25 21:08:52] ITERATION 20 end (duration=1s)
[2026-01-25 21:08:54] ITERATION 21 start (mode=build story=US-003)
[2026-01-25 21:08:55] ITERATION 21 end (duration=1s)
[2026-01-25 21:08:57] ITERATION 22 start (mode=build story=US-003)
[2026-01-25 21:08:58] ITERATION 22 end (duration=0s)
[2026-01-25 21:09:00] ITERATION 23 start (mode=build story=US-003)
[2026-01-25 21:09:00] ITERATION 23 end (duration=0s)
[2026-01-25 21:09:03] ITERATION 24 start (mode=build story=US-003)
[2026-01-25 21:09:04] ITERATION 24 end (duration=0s)
[2026-01-25 21:09:06] ITERATION 25 start (mode=build story=US-003)
[2026-01-25 21:09:06] ITERATION 25 end (duration=0s)
[2026-01-26 14:09:11] ITERATION 1 start (mode=build story=US-003)
[2026-01-26 14:09:37] Start US-003 refactor oversized shared components
[2026-01-26 14:14:12] Refactored IntensitySlider into subcomponents and extracted constants/styles
[2026-01-26 14:17:23] Attempted Expo web for browser verification; expo start --web failed with localStorage.getItem error
[2026-01-26 14:17:58] Ran quality gates and build (npm test failed: missing script; npm run lint failed with existing issues; npm run typecheck/build passed)
[2026-01-26 14:21:26] Updated progress log for US-003 with commit/tests
[2026-01-26 14:22:30] ITERATION 1 end (duration=799s)
[2026-01-26 14:22:32] ITERATION 2 start (mode=build story=US-004)
[2026-01-26 14:22:45] Start US-004 work
[2026-01-26 14:25:08] Refactored useSwipeScreen helpers
[2026-01-26 14:26:13] Ran tests and build for US-004
[2026-01-26 14:26:51] Updated progress log for US-004
[2026-01-26 14:27:24] Committed US-004 changes
[2026-01-26 14:28:08] ITERATION 2 end (duration=336s)
[2026-01-26 14:28:10] ITERATION 3 start (mode=build story=US-005)
[2026-01-26 14:28:59] Start US-005 validation run (manual log; helper missing)
[2026-01-26 14:29:29] Added root test script for US-005
[2026-01-26 14:30:41] Fixed lint hook violations for US-005
[2026-01-26 14:31:01] Ran npm test, lint, typecheck, build for US-005
[2026-01-26 14:31:14] Added AGENTS.md operational notes
[2026-01-26 14:32:00] Re-ran npm test after lint fixes
[2026-01-26 14:32:45] Updated progress log for US-005
[2026-01-26 14:33:54] ITERATION 3 end (duration=344s)
+3
View File
@@ -18,3 +18,6 @@
## Learned Signs
Durable lessons are promoted through `docs/agents/learnings.md`. Ralph runtime
logs are evidence, not instruction. Read promoted artifacts through `AGENTS.md`;
do not add permanent signs from an unreproduced failure.
@@ -1,34 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 1
- Mode: build
- Story: US-001: Inventory oversized files and refactor plan
- Started: 2026-01-25 20:40:12
- Ended: 2026-01-25 20:47:05
- Duration: 413s
- Status: success
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-1.log
## Git
- Head (before): 45499edc9a0b78094601f577c707da2374b1765d
- Head (after): 209dc652d2aaf04d31fe6dd187a28cf2da8ffd67
### Commits
- 209dc65 chore(ralph): update progress log
- 06dfc5b docs(inventory): add oversized file plan
### Changed Files (commits)
- .ralph/activity.log
- .ralph/progress.md
- docs/oversized-file-inventory.md
### Uncommitted Changes
- .ralph/activity.log
- apps/mobile/android/app/build.gradle
- apps/mobile/app.json
- apps/mobile/ios/Sauci.xcodeproj/project.pbxproj
- .agents/
- .codex/
- .ralph/guardrails.md
@@ -1,34 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 10
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:21
- Ended: 2026-01-25 21:08:22
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-10.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,35 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 11
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:24
- Ended: 2026-01-25 21:08:25
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-11.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,36 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 12
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:27
- Ended: 2026-01-25 21:08:28
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-12.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,37 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 13
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:30
- Ended: 2026-01-25 21:08:31
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-13.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,38 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 14
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:33
- Ended: 2026-01-25 21:08:33
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-14.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,39 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 15
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:36
- Ended: 2026-01-25 21:08:36
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-15.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,40 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 16
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:39
- Ended: 2026-01-25 21:08:39
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-16.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,41 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 17
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:42
- Ended: 2026-01-25 21:08:42
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-17.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,42 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 18
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:45
- Ended: 2026-01-25 21:08:46
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-18.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,43 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 19
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:48
- Ended: 2026-01-25 21:08:49
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-19.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,81 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 2
- Mode: build
- Story: US-002: Refactor screen-level files into layer-based modules
- Started: 2026-01-25 20:47:07
- Ended: 2026-01-25 21:07:57
- Duration: 1250s
- Status: success
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-2.log
## Git
- Head (before): 209dc652d2aaf04d31fe6dd187a28cf2da8ffd67
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- a01079a chore(ralph): update progress logs
- 8d4d9d8 refactor(swipe): split swipe screen modules
### Changed Files (commits)
- .agents/ralph/PROMPT_build.md
- .agents/ralph/README.md
- .agents/ralph/agents.sh
- .agents/ralph/config.sh
- .agents/ralph/diagram.svg
- .agents/ralph/log-activity.sh
- .agents/ralph/loop.sh
- .agents/ralph/ralph.webp
- .agents/ralph/references/CONTEXT_ENGINEERING.md
- .agents/ralph/references/GUARDRAILS.md
- .agents/tasks/prd-mobile-refactor.json
- .codex/skills/commit/SKILL.md
- .codex/skills/commit/references/commit_examples.md
- .codex/skills/dev-browser/SKILL.md
- .codex/skills/dev-browser/bun.lock
- .codex/skills/dev-browser/package-lock.json
- .codex/skills/dev-browser/package.json
- .codex/skills/dev-browser/references/scraping.md
- .codex/skills/dev-browser/scripts/start-relay.ts
- .codex/skills/dev-browser/scripts/start-server.ts
- .codex/skills/dev-browser/server.sh
- .codex/skills/dev-browser/src/client.ts
- .codex/skills/dev-browser/src/index.ts
- .codex/skills/dev-browser/src/relay.ts
- .codex/skills/dev-browser/src/snapshot/__tests__/snapshot.test.ts
- .codex/skills/dev-browser/src/snapshot/browser-script.ts
- .codex/skills/dev-browser/src/snapshot/index.ts
- .codex/skills/dev-browser/src/snapshot/inject.ts
- .codex/skills/dev-browser/src/types.ts
- .codex/skills/dev-browser/tsconfig.json
- .codex/skills/dev-browser/vitest.config.ts
- .codex/skills/prd/SKILL.md
- .ralph/activity.log
- .ralph/guardrails.md
- .ralph/progress.md
- .ralph/runs/run-20260125-204012-65223-iter-1.md
- apps/mobile/android/app/build.gradle
- apps/mobile/app.json
- apps/mobile/app/(app)/swipe.tsx
- apps/mobile/ios/Sauci.xcodeproj/project.pbxproj
- apps/mobile/src/features/swipe/SwipeScreen.tsx
- apps/mobile/src/features/swipe/components/SwipeBlockedState.tsx
- apps/mobile/src/features/swipe/components/SwipeCardStack.tsx
- apps/mobile/src/features/swipe/components/SwipeCaughtUpState.tsx
- apps/mobile/src/features/swipe/components/SwipeDailyLimitState.tsx
- apps/mobile/src/features/swipe/components/SwipeHeader.tsx
- apps/mobile/src/features/swipe/components/SwipeInfoStateLayout.tsx
- apps/mobile/src/features/swipe/components/SwipeLoadingState.tsx
- apps/mobile/src/features/swipe/components/SwipeNoPacksState.tsx
- apps/mobile/src/features/swipe/components/SwipeNoPartnerState.tsx
- apps/mobile/src/features/swipe/components/SwipeQuestionCard.tsx
- apps/mobile/src/features/swipe/components/SwipeUploadOverlay.tsx
- apps/mobile/src/features/swipe/hooks/useProgressShimmer.ts
- apps/mobile/src/features/swipe/hooks/useSwipeScreen.ts
- apps/mobile/src/features/swipe/services/swipeService.ts
- apps/mobile/src/features/swipe/types.ts
### Uncommitted Changes
- .ralph/activity.log
@@ -1,44 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 20
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:51
- Ended: 2026-01-25 21:08:52
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-20.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,45 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 21
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:54
- Ended: 2026-01-25 21:08:55
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-21.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,46 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 22
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:57
- Ended: 2026-01-25 21:08:57
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-22.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-21.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,47 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 23
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:09:00
- Ended: 2026-01-25 21:09:00
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-23.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-21.md
- .ralph/runs/run-20260125-204012-65223-iter-22.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,48 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 24
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:09:03
- Ended: 2026-01-25 21:09:03
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-24.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-21.md
- .ralph/runs/run-20260125-204012-65223-iter-22.md
- .ralph/runs/run-20260125-204012-65223-iter-23.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,49 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 25
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:09:06
- Ended: 2026-01-25 21:09:06
- Duration: 0s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-25.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-21.md
- .ralph/runs/run-20260125-204012-65223-iter-22.md
- .ralph/runs/run-20260125-204012-65223-iter-23.md
- .ralph/runs/run-20260125-204012-65223-iter-24.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
@@ -1,27 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 3
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:07:59
- Ended: 2026-01-25 21:08:01
- Duration: 2s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-3.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
@@ -1,28 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 4
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:03
- Ended: 2026-01-25 21:08:04
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-4.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
@@ -1,29 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 5
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:06
- Ended: 2026-01-25 21:08:07
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-5.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
@@ -1,30 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 6
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:09
- Ended: 2026-01-25 21:08:10
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-6.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
@@ -1,31 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 7
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:12
- Ended: 2026-01-25 21:08:13
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-7.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
@@ -1,32 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 8
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:15
- Ended: 2026-01-25 21:08:16
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-8.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
@@ -1,33 +0,0 @@
# Ralph Run Summary
- Run ID: 20260125-204012-65223
- Iteration: 9
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-25 21:08:18
- Ended: 2026-01-25 21:08:19
- Duration: 1s
- Status: error
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260125-204012-65223-iter-9.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): a01079a7c3c6c727a55cd46a72543e86f2378932
### Commits
- (none)
### Changed Files (commits)
- (none)
### Uncommitted Changes
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
@@ -1,59 +0,0 @@
# Ralph Run Summary
- Run ID: 20260126-140911-55357
- Iteration: 1
- Mode: build
- Story: US-003: Refactor oversized shared components
- Started: 2026-01-26 14:09:11
- Ended: 2026-01-26 14:22:30
- Duration: 799s
- Status: success
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260126-140911-55357-iter-1.log
## Git
- Head (before): a01079a7c3c6c727a55cd46a72543e86f2378932
- Head (after): 70449659cf1ded7041b71ecf07aa2e7bc76f8346
### Commits
- 7044965 chore(ralph): log US-003 progress
- f302cb6 refactor(ui): split IntensitySlider pieces
### Changed Files (commits)
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/progress.md
- .ralph/runs/run-20260125-204012-65223-iter-10.md
- .ralph/runs/run-20260125-204012-65223-iter-11.md
- .ralph/runs/run-20260125-204012-65223-iter-12.md
- .ralph/runs/run-20260125-204012-65223-iter-13.md
- .ralph/runs/run-20260125-204012-65223-iter-14.md
- .ralph/runs/run-20260125-204012-65223-iter-15.md
- .ralph/runs/run-20260125-204012-65223-iter-16.md
- .ralph/runs/run-20260125-204012-65223-iter-17.md
- .ralph/runs/run-20260125-204012-65223-iter-18.md
- .ralph/runs/run-20260125-204012-65223-iter-19.md
- .ralph/runs/run-20260125-204012-65223-iter-2.md
- .ralph/runs/run-20260125-204012-65223-iter-20.md
- .ralph/runs/run-20260125-204012-65223-iter-21.md
- .ralph/runs/run-20260125-204012-65223-iter-22.md
- .ralph/runs/run-20260125-204012-65223-iter-23.md
- .ralph/runs/run-20260125-204012-65223-iter-24.md
- .ralph/runs/run-20260125-204012-65223-iter-25.md
- .ralph/runs/run-20260125-204012-65223-iter-3.md
- .ralph/runs/run-20260125-204012-65223-iter-4.md
- .ralph/runs/run-20260125-204012-65223-iter-5.md
- .ralph/runs/run-20260125-204012-65223-iter-6.md
- .ralph/runs/run-20260125-204012-65223-iter-7.md
- .ralph/runs/run-20260125-204012-65223-iter-8.md
- .ralph/runs/run-20260125-204012-65223-iter-9.md
- apps/mobile/src/components/ui/IntensitySlider.tsx
- apps/mobile/src/components/ui/IntensitySlider/IntensitySliderCurrentCard.tsx
- apps/mobile/src/components/ui/IntensitySlider/IntensitySliderInfoModal.tsx
- apps/mobile/src/components/ui/IntensitySlider/IntensitySliderLevels.tsx
- apps/mobile/src/components/ui/IntensitySlider/IntensitySliderTrack.tsx
- apps/mobile/src/components/ui/IntensitySlider/constants.ts
- apps/mobile/src/components/ui/IntensitySlider/styles.ts
### Uncommitted Changes
- .ralph/activity.log
@@ -1,32 +0,0 @@
# Ralph Run Summary
- Run ID: 20260126-140911-55357
- Iteration: 2
- Mode: build
- Story: US-004: Refactor oversized hooks/services/utils
- Started: 2026-01-26 14:22:32
- Ended: 2026-01-26 14:28:08
- Duration: 336s
- Status: success
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260126-140911-55357-iter-2.log
## Git
- Head (before): 70449659cf1ded7041b71ecf07aa2e7bc76f8346
- Head (after): 1370576dd59180f3b13e0a8d99255dfa96210d60
### Commits
- 1370576 chore(ralph): log commit action
- 6957502 chore(ralph): update progress logs
- 5a9defb refactor(swipe): split useSwipeScreen helpers
### Changed Files (commits)
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/progress.md
- .ralph/runs/run-20260126-140911-55357-iter-1.md
- apps/mobile/src/features/swipe/hooks/useSwipeScreen.ts
- apps/mobile/src/features/swipe/utils/useSwipeScreen-helpers.ts
### Uncommitted Changes
- .ralph/activity.log
@@ -1,33 +0,0 @@
# Ralph Run Summary
- Run ID: 20260126-140911-55357
- Iteration: 3
- Mode: build
- Story: US-005: Validate refactor quality gates
- Started: 2026-01-26 14:28:10
- Ended: 2026-01-26 14:33:54
- Duration: 344s
- Status: success
- Log: /Users/jjbrunton/Projects/Sauci/.ralph/runs/run-20260126-140911-55357-iter-3.log
## Git
- Head (before): 1370576dd59180f3b13e0a8d99255dfa96210d60
- Head (after): ce419fee8b21a37f83e746e6d09ac59692c62e8c
### Commits
- ce419fe chore(logs): update US-005 progress
- 368399f fix(validation): satisfy quality gate checks
### Changed Files (commits)
- .agents/tasks/prd-mobile-refactor.json
- .ralph/activity.log
- .ralph/progress.md
- .ralph/runs/run-20260126-140911-55357-iter-2.md
- AGENTS.md
- apps/mobile/src/components/questions/QuestionCardAudio.tsx
- apps/mobile/src/features/chat/components/MessageContent.tsx
- package.json
### Uncommitted Changes
- .ralph/activity.log
+62 -15
View File
@@ -1,21 +1,68 @@
# AGENTS
# Sauci agent map
## Verification
- npm test (runs mobile Jest suite)
- npm run lint
- npm run typecheck
- npm run build
Sauci is a couples connection product: an Expo mobile app, React admin, Next.js
web app, standalone Node/PostgreSQL backend, hosted Supabase Auth, and an internal
MCP service in one npm/Turborepo workspace.
## Database Migrations - MANDATORY RULES
## Golden rules
**NEVER use `mcp__sauci-prod__apply_migration` or `mcp__sauci-non-prod__apply_migration`.** These create migration records in the remote database without local files, which breaks CI/CD deployments.
1. Read the nearest `AGENTS.md` before changing a scoped area.
2. Preserve tenant and couple isolation. Never bypass RLS, role checks, or auth.
3. Product-data schema changes are committed SQL files in `apps/api/drizzle/`.
Hosted Supabase owns Auth only; do not deploy product-data migrations or Edge
Functions there. Never execute remote DDL through MCP or provider tools.
4. Never target production from local development or E2E. Database integration
tests must fail closed unless `DATABASE_URL` resolves to loopback. Authenticated
native acceptance may use only the designated non-production Auth project.
5. Read `apps/mobile/DESIGN.md` before mobile UI work.
6. Keep shared package exports type-only and route them through `src/index.ts`.
7. Do not commit secrets, generated evidence, local logs, or runtime state.
8. Scope work to the task. Use high-effort reviewers only for the risk triggers in
`docs/agents/routing.md`.
**NEVER run DDL (`CREATE`, `ALTER`, `DROP`) via `mcp__*__execute_sql`.** This changes the schema with no migration tracking.
## Repository map
**All schema changes must be local migration files:**
1. Run `supabase migration new <name>` to create the file
2. Edit the file in `apps/supabase/migrations/`
3. Use idempotent SQL (`IF NOT EXISTS`, `CREATE OR REPLACE`)
4. Commit the file — CI deploys it automatically
| Area | Purpose | Local instructions |
|---|---|---|
| `apps/mobile` | Expo React Native product | `apps/mobile/AGENTS.md` |
| `apps/admin` | Vite administration UI | `apps/admin/AGENTS.md` |
| `apps/web` | Next.js marketing/redemption UI | `apps/web/AGENTS.md` |
| `apps/api` | standalone API, worker, PostgreSQL migrations | repository rules |
| `apps/supabase` | legacy data-plane history; hosted Auth configuration only | `apps/supabase/AGENTS.md` |
| `apps/mcp` | internal administrative MCP service | `apps/mcp/AGENTS.md` |
| `packages/shared` | shared TypeScript contracts | `packages/shared/AGENTS.md` |
| `e2e` | cross-application Playwright flows | `e2e/README.md` |
| `docs` | maintained system of record | `docs/index.md` |
**`execute_sql` is ONLY for SELECT queries.** No exceptions.
## Workflows
- Bootstrap: `npm ci`
- Full local stack: `scripts/dev-local.sh up`
- Fast checks: `npm run verify:fast`
- Authoritative repository checks: `npm run verify:full`
- Running-stack E2E: `npm run verify:e2e`
- Everything: `npm run verify`
- Before a PR: use `.codex/skills/verify/SKILL.md`
When a check cannot run because a prerequisite is absent, report it as an
environment limitation; do not call it a passing product check.
## Where to look
| Question | Source of truth |
|---|---|
| System boundaries and data flow | `docs/architecture/system.md` |
| Local services, ports, fixtures | `docs/development/local-stack.md` |
| Test layers and required gates | `docs/testing/strategy.md` |
| Database migration safety | `docs/operations/database-migrations.md` |
| Agent roles and effort routing | `docs/agents/routing.md` |
| Learning promotion | `docs/agents/learnings.md` |
| Mobile visual language | `apps/mobile/DESIGN.md` |
| Domain documentation index | `docs/index.md` |
## Documentation discipline
Update the maintained doc when a contract, command, port, or invariant changes.
Plans and historical notes are evidence, not current architecture. A repeated
lesson becomes permanent only after it is reproduced and promoted into a doc,
skill, fixture, or executable check.
+4 -357
View File
@@ -1,358 +1,5 @@
# CLAUDE.md
# Claude compatibility entrypoint
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Important: Design Guidelines
**Always read `apps/mobile/DESIGN.md` before making UI/UX changes to the mobile app.** This file contains the design system, visual language, and styling patterns that must be followed for consistency. Agents and subagents should read this file when:
- Creating new screens or components
- Modifying existing UI elements
- Adding animations or visual effects
- Working with colors, typography, or spacing
## Project Overview
Sauci is a couples relationship app that helps partners communicate better and grow closer together. Users swipe on thoughtful questions (yes/no/maybe), and when both partners answer positively, a "match" is created that unlocks a chat thread for that topic.
## Commands
```bash
# Install dependencies (from root)
npm install
# Start all apps in development
npm run dev
# Run specific apps
cd apps/mobile && npm run dev # Expo mobile app
cd apps/admin && npm run dev # React Admin dashboard
# Type checking
npm run typecheck
# Linting
npm run lint
# Build all
npm run build
```
### Mobile-specific commands
```bash
cd apps/mobile
npm run ios # Run on iOS simulator
npm run android # Run on Android emulator
npm run web # Run in browser
```
### Supabase commands
```bash
supabase start # Start local Supabase
supabase db reset # Reset DB and run all migrations
supabase functions serve # Run edge functions locally
supabase migration new <name> # Create new migration
```
### Supabase Environments
There are two Supabase projects configured via MCP servers:
| Environment | Project Ref | URL | MCP Server |
|-------------|-------------|-----|------------|
| **Production** | `ckjcrkjpmhqhiucifukx` | https://ckjcrkjpmhqhiucifukx.supabase.co | `sauci-prod` |
| **Non-Production** | `itbzhrvlgvdmzbnhzhyx` | https://itbzhrvlgvdmzbnhzhyx.supabase.co | `sauci-non-prod` |
When using Claude Code with MCP tools:
- Use `mcp__sauci-prod__*` tools for production database operations
- Use `mcp__sauci-non-prod__*` tools for development/staging database operations
- **Always verify which environment you're targeting before running destructive operations**
### Database Migrations - CRITICAL
> **STOP: Read this entire section before making ANY database schema change.**
#### The Golden Rule
**ALL schema changes MUST go through local migration files.** No exceptions.
#### Forbidden Actions
- **NEVER call `apply_migration` via MCP** (either `mcp__sauci-prod__apply_migration` or `mcp__sauci-non-prod__apply_migration`). This creates migration entries in the remote database with NO local file, which breaks `supabase db push` in CI and causes deployment failures that are painful to fix.
- **NEVER run DDL statements (`CREATE`, `ALTER`, `DROP`) via `execute_sql`**. This changes the schema without any migration tracking at all.
- **NEVER manually INSERT into `supabase_migrations.schema_migrations`** unless repairing a broken migration history (and only with explicit user approval).
#### Why This Matters
The CI/CD pipeline runs `supabase db push --include-all` which compares local migration files against the remote `schema_migrations` table. If the remote has migrations that don't exist locally, or local files exist without remote entries, the deployment **will fail** and block all subsequent deployments.
**A single `apply_migration` call can break deployments for the entire project.**
#### Correct Workflow for Schema Changes
```bash
# 1. Create migration file locally
supabase migration new <descriptive_name>
# 2. Edit the migration file in apps/supabase/migrations/
# 3. Make migrations idempotent where possible
# Use: CREATE OR REPLACE, IF NOT EXISTS, DROP IF EXISTS
# This prevents failures if re-run
# 4. Test locally
supabase db reset
# 5. Commit the migration file to git
# 6. Deploy happens automatically via CI on push to master
# OR deploy manually:
supabase link --project-ref <project_ref>
supabase db push
```
#### MCP Tools - What IS Allowed
- **Reading data:** `execute_sql` with SELECT queries only
- **Exploring schema:** `list_tables`, `list_migrations`, `list_extensions`
- **Deploying edge functions:** `deploy_edge_function`
- **Generating types:** `generate_typescript_types`
- **Checking advisors:** `get_advisors`
#### If You Accidentally Used `apply_migration`
If a migration was applied via MCP, you must immediately:
1. Retrieve the migration SQL from `schema_migrations.statements`
2. Create a matching local file: `apps/supabase/migrations/<version>_<name>.sql`
3. Commit and push the file so CI can reconcile
## Architecture
### Monorepo Structure (Turborepo)
- `apps/mobile` - Expo React Native app (expo-router for navigation)
- `apps/admin` - React Admin dashboard for content management
- `apps/supabase` - Database migrations and edge functions
- `packages/shared` - Shared TypeScript types (`@sauci/shared`)
### Mobile App Architecture
- **Routing**: Expo Router with file-based routing (`app/` directory)
- `(auth)/` - Authentication screens
- `(app)/` - Main app screens (protected)
- **State Management**: Zustand stores in `src/store/index.ts`
- `useAuthStore` - User, couple, partner state
- `useMatchStore` - Matches and notifications
- `usePacksStore` - Question packs and enabled packs per couple
- `useMessageStore` - Chat messages and unread counts
- `useSubscriptionStore` - RevenueCat subscription state
- **Backend**: Supabase client in `src/lib/supabase.ts`
- **UI Components**: Glass-morphism themed components in `src/components/ui/`
### Data Model (Core Entities)
- **Profile** - User profile extending Supabase auth (has `couple_id`)
- **Couple** - Two users linked via invite code
- **QuestionPack** - Collection of questions (can be premium)
- **Question** - Individual question with intensity level (1-5)
- **Response** - User's answer (yes/no/maybe) to a question
- **Match** - Created when both partners answer positively (yes_yes, yes_maybe, maybe_maybe)
### Edge Functions
Edge functions in `apps/supabase/functions/` handle complex operations:
- `submit-response` - Saves response, checks for matches, triggers notifications
- `manage-couple` - Join/leave couple operations
- `delete-relationship` - Deletes couple data (matches, messages, media) while keeping accounts
- `delete-account` - Permanently deletes user account and all associated data (Apple App Store requirement)
- `send-notification` - Push notifications for matches
- `send-nudge-notification` - Partner nudge notifications (rate limited to once per 12 hours)
- `send-unpaired-reminder` - Daily cron reminder for unpaired users to share invite code
- `send-catchup-reminder` - Daily cron reminder for "behind" partners with escalating frequency
- `revenuecat-webhook` - Subscription webhook handler
- `sync-subscription` - Syncs RevenueCat subscription status
- `redeem-code` - Redeems promotional codes for premium access (website only)
#### Edge Function Deployment Guidelines
When deploying edge functions via MCP tools (`mcp__sauci-*__deploy_edge_function`):
**IMPORTANT: Always use `verify_jwt: false`** for all edge functions. Supabase's built-in JWT verification causes 401 errors even with valid tokens. Instead, handle authentication manually in the function code using:
```typescript
const { data: { user }, error: authError } = await supabase.auth.getUser(
authHeader.replace("Bearer ", "")
);
```
This approach:
- Gives better error messages
- Allows custom auth handling
- Avoids mysterious 401 failures
**Current function settings (all should be verify_jwt: false):**
| Function | verify_jwt | Auth Method |
|----------|------------|-------------|
| `manage-couple` | false | Manual via getUser() |
| `submit-response` | false | Manual via getUser() |
| `sync-subscription` | false | Manual via getUser() |
| `delete-relationship` | false | Manual via getUser() |
| `delete-account` | false | Manual via getUser() |
| `redeem-code` | false | Manual via getUser() |
| `revenuecat-webhook` | false | Webhook signature validation |
| `send-notification` | false | Internal trigger (no auth) |
| `send-message-notification` | false | Internal trigger (no auth) |
| `send-nudge-notification` | false | Manual via getUser() |
| `send-unpaired-reminder` | false | Cron trigger (no auth) |
| `send-catchup-reminder` | false | Cron trigger (no auth) |
### Database Best Practices
- **Always use `.maybeSingle()` instead of `.single()`** when the row might not exist. `.single()` throws an error if 0 or >1 rows are returned.
- **Profile creation trigger**: The `on_auth_user_created` trigger automatically creates a profile when a user signs up. Never assume a profile exists without checking.
- **Check for null profiles** in edge functions before performing operations.
### Cron Jobs (pg_cron) - IMPORTANT
**NEVER hardcode Supabase URLs in cron job migrations.** Migrations run on both prod and non-prod, so a hardcoded production URL will cause non-prod cron jobs to hit production (double-firing notifications, duplicate processing, etc.).
**Correct pattern** — use `get_supabase_edge_function_url()`:
```sql
SELECT cron.schedule(
'my-cron-job',
'*/5 * * * *',
format(
$cmd$
SELECT net.http_post(
url := %L,
headers := jsonb_build_object('Content-Type', 'application/json'),
body := '{}'::jsonb
)
$cmd$,
get_supabase_edge_function_url('my-edge-function')
)
);
```
This resolves the URL from `app_config.supabase_url` at migration-time, so each environment targets its own edge functions.
**If adding a new environment**, you must seed the URL before running migrations:
```sql
UPDATE app_config SET supabase_url = 'https://<project-ref>.supabase.co';
```
### Key Patterns
- Responses use UPSERT with `onConflict: "user_id,question_id"`
- Match detection happens in `submit-response` edge function after each response
- Real-time subscriptions used for chat messages
- RevenueCat handles in-app purchases and subscription management
- RLS policies enforce couple-level data isolation
### Redemption Code System
Promotional codes that grant users premium access. **Codes can only be redeemed on the website, NOT in the mobile app.**
**Database Tables:**
- `redemption_codes` - Stores codes with max_uses, current_uses, expiration, active status
- `code_redemptions` - Tracks which users redeemed which codes
**Components:**
- **Admin UI** (`apps/admin/src/pages/RedemptionCodesPage.tsx`) - Super admins can generate, manage, and view redemption codes
- **Edge Function** (`apps/supabase/functions/redeem-code/`) - Validates and processes code redemption (unauthenticated, accepts email + code)
- **Database Function** (`redeem_code_by_email(p_email, p_code)`) - Atomic redemption with validation (active, not expired, has uses remaining, user hasn't redeemed)
- **Web UI** (`apps/web/app/redeem/page.tsx`) - Public redemption page
**Flow:**
1. Admin generates code in admin dashboard
2. User visits `/redeem` on website and enters email + code
3. `redeem-code` edge function calls `redeem_code_by_email()` database function
4. Database function looks up user by email, validates code, and sets `profiles.is_premium = true`
**Important:** Do NOT add redemption code UI to the mobile app. Apple requires in-app purchases for premium features purchased within iOS apps.
## Mobile UI - DO NOT CHANGE
### Tab Bar Background
**NEVER set `backgroundColor: 'transparent'` on the tab bar.** Always use a semi-transparent solid color:
```typescript
backgroundColor: 'rgba(18, 18, 18, 0.85)',
```
The `BlurView` in `tabBarBackground` is unreliable and can fail during re-renders/transitions, causing a fully transparent tab bar. The solid rgba background acts as a fallback while still allowing the blur effect on top.
**Location:** `apps/mobile/app/(app)/_layout.tsx` - `tabBarStyle`
## Infrastructure as Code (Terraform)
Supabase project configuration is managed via Terraform in the `terraform/` directory. This includes auth settings, OAuth providers, email templates, SMTP config, rate limits, and more.
**Directory structure:**
```
terraform/
├── modules/
│ └── supabase/ # Shared configuration module
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── templates/ # Email templates
└── environments/
├── prod/ # Production (ckjcrkjpmhqhiucifukx)
└── non-prod/ # Non-production (itbzhrvlgvdmzbnhzhyx)
```
**When to update Terraform:**
- Changing auth settings (OAuth providers, JWT expiry, MFA settings)
- Modifying email templates or subjects
- Updating rate limits or security settings
- Changing SMTP configuration
- Modifying storage or API settings
**Workflow (always test in non-prod first):**
```bash
# 1. Apply to non-prod first
cd terraform/environments/non-prod
export TF_VAR_supabase_access_token=sbp_xxxxx
terraform plan
terraform apply
# 2. Verify changes work in non-prod
# 3. Apply to prod
cd terraform/environments/prod
terraform plan
terraform apply
```
**Important:** After making Terraform changes, remind the user to:
1. Commit the updated `terraform/` files
2. The GitHub Action will auto-apply on merge to master (non-prod first, then prod)
**Do NOT use Terraform for:**
- Database schema changes (use migrations)
- Edge function deployment (use CLI or MCP)
- Storage bucket creation (use migrations)
## Edge Function Secrets
Edge functions use secrets stored in Supabase. These are synced from GitHub Secrets during CI/CD deployment.
**Current secrets:**
| Secret | Used By | Description |
|--------|---------|-------------|
| `REVENUECAT_WEBHOOK_SECRET` | revenuecat-webhook | Webhook signature validation |
| `REVENUECAT_API_KEY` | sync-subscription | RevenueCat API access |
| `REVENUECAT_ENTITLEMENT_ID` | sync-subscription | Entitlement identifier |
| `OPENROUTER_API_KEY` | classify-message | AI classification API |
| `ADMIN_PRIVATE_KEY_JWK` | admin-decrypt-* | E2EE admin decryption |
| `ADMIN_KEYS_JSON` | admin-decrypt-*, migrate-e2ee | Multiple admin keys |
| `DISCORD_WEBHOOK_URL` | send-discord-notification | Discord notifications |
**Auto-provided by Supabase (don't set):**
- `SUPABASE_URL`
- `SUPABASE_ANON_KEY`
- `SUPABASE_SERVICE_ROLE_KEY`
**When adding a new edge function that needs secrets:**
1. Add the secret to the edge function code: `Deno.env.get("SECRET_NAME")`
2. Update `.github/workflows/deploy-supabase.yml` to include the new secret in the sync step
3. Update `apps/supabase/functions/.secrets.example` with the new secret
4. **Remind the user** to add the secret to GitHub Secrets (Settings → Secrets → Actions)
5. Update this table in CLAUDE.md
**Local development:**
```bash
cp apps/supabase/functions/.secrets.example apps/supabase/functions/.secrets
# Fill in values
supabase functions serve --env-file apps/supabase/functions/.secrets
```
Read and follow [`AGENTS.md`](AGENTS.md). It is the runtime-neutral source of truth
for this repository. Scoped rules live in the nearest `AGENTS.md`; maintained
documentation is indexed by [`docs/index.md`](docs/index.md).
Executable → Regular
+35 -74
View File
@@ -1,90 +1,51 @@
# Sauci
![Node 20+](https://img.shields.io/badge/node-20%2B-339933)
![npm 10+](https://img.shields.io/badge/npm-10%2B-CB3837)
![Turborepo](https://img.shields.io/badge/monorepo-turborepo-0F1115)
Sauci is a couples connection product built as a full-stack npm/Turborepo
workspace.
Sauci is a couples intimacy app where partners swipe question packs, match on shared interests, and chat about what they unlock together.
## Applications
## What lives here
| Path | Surface |
|---|---|
| `apps/mobile` | Expo React Native customer app |
| `apps/admin` | Vite/React administration app |
| `apps/web` | Next.js marketing and redemption app |
| `apps/supabase` | database, auth, realtime, storage, and Edge Functions |
| `apps/mcp` | authenticated internal MCP service |
| `packages/shared` | shared TypeScript contracts |
```
sauci/
├── apps/
│ ├── mobile/ # Expo React Native app
│ ├── admin/ # Admin dashboard (Vite + React)
│ ├── web/ # Marketing website (Next.js)
│ └── supabase/ # Supabase project (migrations, edge functions)
├── packages/
│ └── shared/ # Shared TypeScript types
```
## Bootstrap and run
## Core product flows
- **Couple pairing** via invite codes and profile linking
- **Question packs** with two-part phrasing and smart selection bias
- **Matches + chat** when both partners answer positively
- **Notifications** for new matches and messages
- **Subscriptions** via RevenueCat with couple-level premium sharing
## Prerequisites
- Node.js 20+
- npm 10+
- Supabase CLI (`npm install -g supabase`)
- Expo CLI (`npm install -g expo-cli`)
## Quickstart
Use Node `20.10.0` from `.nvmrc`, Docker-compatible containers, and tmux.
```bash
npm install
npm run dev
npm ci
scripts/dev-local.sh reset
scripts/dev-local.sh up
```
## App commands
The launcher starts local Supabase, Edge Functions, web, admin, MCP, and Expo in
one tmux session. See [local stack documentation](docs/development/local-stack.md)
for ports, logs, native launch commands, and troubleshooting.
From each app directory:
## Verify
- **Mobile** (`apps/mobile`): `npm run dev`, `npm run ios`, `npm run android`, `npm run web`
- **Admin** (`apps/admin`): `npm run dev`, `npm run build`, `npm run typecheck`
- **Web** (`apps/web`): `npm run dev`, `npm run build`, `npm run start`
```bash
npm run verify:fast # lint, typecheck, unit/contract tests
npm run verify:full # fast checks, builds, Supabase integration
npm run verify:e2e # running-stack Playwright journeys
npm run verify # complete pre-PR gate
```
## Environment setup
Native black-box flows use `npm run test:mobile:e2e`. Pull requests run static
and full-stack gates and retain browser traces/screenshots/videos on failure.
Copy the example files and fill in values:
## Agent harness
- Mobile: `apps/mobile/.env.example`
- Admin: `apps/admin/.env.example`
- Web: `apps/web/.env.local.example`
## Supabase (local)
- Config lives in `apps/supabase/config.toml`.
- Use the Supabase CLI for local services and migrations.
## Scripts (root)
- `npm run dev` - run all apps in dev mode
- `npm run build` - build all apps
- `npm run lint` - lint all apps
- `npm run typecheck` - typecheck all apps
- `npm run clean` - clean build artifacts
## Docs
- Auth: `docs/authentication.md`
- Schema: `docs/schema.md`
- Pairing: `docs/couple-pairing.md`
- Questions: `docs/question-selection.md`
- Matches/notifications: `docs/match-notifications.md`
- Subscriptions: `docs/subscription-system.md`
- Mobile release guide: `apps/mobile/RELEASING.md`
## Tech stack
- **Mobile**: Expo (React Native)
- **Backend**: Supabase (Postgres, Auth, Edge Functions, Realtime)
- **Admin**: React + Vite
- **Web**: Next.js
- **Monorepo**: Turborepo
Start with [AGENTS.md](AGENTS.md) and [the documentation index](docs/index.md).
Task/risk agent routing lives in [docs/agents/routing.md](docs/agents/routing.md),
repository skills live under `.codex/skills`, and verified lessons follow the
[learning promotion lifecycle](docs/agents/learnings.md).
Database schema changes must use committed files in `apps/supabase/migrations`.
Remote migration tools and DDL through MCP SQL execution are forbidden.
+5 -2
View File
@@ -1,5 +1,8 @@
VITE_SUPABASE_URL=your_supabase_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
# Hosted Supabase Auth public settings only. Admin product data and mutations go
# through VITE_API_URL; never expose a service-role or admin service token here.
VITE_SUPABASE_URL=your_nonproduction_supabase_auth_url
VITE_SUPABASE_ANON_KEY=your_nonproduction_supabase_anon_key
VITE_API_URL=http://127.0.0.1:3003
VITE_OPENAI_API_KEY=your_openai_api_key
VITE_OPENROUTER_API_KEY=your_openrouter_api_key
+14
View File
@@ -0,0 +1,14 @@
# Admin application
Vite/React administration UI. Use existing layout, route, and Supabase client
patterns before introducing abstractions.
- `pack_creator` manages permitted content; `super_admin` can access privileged
user/admin/audit surfaces.
- Enforce role checks in both route visibility and the backend/RLS boundary.
- Administrative mutations must remain auditable.
- Use `.maybeSingle()` when zero rows are valid.
- Never expose credentials, tokens, or private user content unnecessarily.
- Add accessible labels and a focused test for changed behavior.
- Verify with `npm run lint -w @sauci/admin`, `npm run typecheck -w
@sauci/admin`, and `npm run build -w @sauci/admin`.
+8 -13
View File
@@ -2,23 +2,17 @@ FROM node:20-bookworm-slim AS builder
WORKDIR /app
# Enable pnpm via corepack (allow non-matching packageManager)
ENV COREPACK_ENABLE_STRICT=0
ENV PNPM_CONFIG_LINK_WORKSPACE_PACKAGES=true
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
# Copy everything first (workspaces need full structure)
# Copy the npm workspace and install from its committed lockfile.
COPY . .
# Install all dependencies
RUN pnpm install --no-frozen-lockfile
RUN npm ci
# Build shared package first
RUN pnpm exec turbo run build --filter=@sauci/shared
RUN npm run build -w @sauci/shared
# Build admin app with env vars
ARG VITE_SUPABASE_URL
ARG VITE_SUPABASE_ANON_KEY
ARG VITE_SUPABASE_ANON_KEY
ARG VITE_API_URL
ARG VITE_OPENAI_API_KEY
ARG VITE_OPENROUTER_API_KEY
ARG VITE_AI_MODEL
@@ -30,7 +24,8 @@ ARG VITE_COUNCIL_GENERATOR_MODEL
ARG VITE_COUNCIL_REVIEWER_MODEL
ENV VITE_SUPABASE_URL=$VITE_SUPABASE_URL
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
ENV VITE_API_URL=$VITE_API_URL
ENV VITE_OPENAI_API_KEY=$VITE_OPENAI_API_KEY
ENV VITE_OPENROUTER_API_KEY=$VITE_OPENROUTER_API_KEY
ENV VITE_AI_MODEL=$VITE_AI_MODEL
@@ -41,7 +36,7 @@ ENV VITE_COUNCIL_ENABLED=$VITE_COUNCIL_ENABLED
ENV VITE_COUNCIL_GENERATOR_MODEL=$VITE_COUNCIL_GENERATOR_MODEL
ENV VITE_COUNCIL_REVIEWER_MODEL=$VITE_COUNCIL_REVIEWER_MODEL
RUN pnpm exec turbo run build --filter=@sauci/admin
RUN npm run build -w @sauci/admin
FROM nginx:alpine
COPY --from=builder /app/apps/admin/dist /usr/share/nginx/html
+4 -23
View File
@@ -2,34 +2,15 @@ FROM node:20-bookworm-slim
WORKDIR /app
# Enable pnpm via corepack (allow non-matching packageManager)
ENV COREPACK_ENABLE_STRICT=0
ENV PNPM_CONFIG_LINK_WORKSPACE_PACKAGES=true
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
# Copy root package files and workspace configs
COPY package*.json ./
COPY pnpm-workspace.yaml ./
COPY turbo.json ./
# Copy all workspace package.json files
COPY apps/admin/package.json ./apps/admin/
COPY apps/mobile/package.json ./apps/mobile/
COPY apps/supabase/package.json ./apps/supabase/
COPY apps/web/package.json ./apps/web/
COPY packages/shared/package.json ./packages/shared/
# Install all dependencies at root level (workspaces)
RUN pnpm install --no-frozen-lockfile
# Copy all source code
# Install the complete npm workspace from its committed lockfile.
COPY . .
RUN npm ci
# Build shared package
RUN pnpm exec turbo run build --filter=@sauci/shared
RUN npm run build -w @sauci/shared
WORKDIR /app/apps/admin
EXPOSE 3001
CMD ["pnpm", "run", "dev"]
CMD ["npm", "run", "dev"]
-84
View File
@@ -1,84 +0,0 @@
# Admin Dashboard - Agent Guidelines
**STRICT RULES - DO NOT VIOLATE**
## Architecture
This is a React Admin dashboard using:
- **Build**: Vite
- **Routing**: react-router-dom with component-based routing in `App.tsx`
- **Styling**: Tailwind CSS
- **State**: React Context (`AuthContext`)
- **Backend**: Supabase client in `src/lib/supabase.ts`
## Directory Structure
```
src/
components/ # Reusable components
layout/ # AppLayout, Sidebar, etc.
ProtectedRoute.tsx # Route guard
contexts/ # React contexts (AuthContext)
hooks/ # Custom hooks
lib/ # Utilities (supabase)
pages/ # Page components
content/ # Categories, Packs, Questions
users/ # User management (super_admin only)
admins/ # Admin management (super_admin only)
```
## Critical Rules
### Authentication & Authorization
Two admin roles exist:
- `admin` - Content management only (categories, packs, questions)
- `super_admin` - Full access including user data, admins, audit logs
Use `<ProtectedRoute requireSuperAdmin>` for super_admin-only routes.
### Route Structure
```typescript
// Public
/login
// Protected (all admins)
/ # Dashboard
/categories # Category management
/categories/:id/packs # Packs in category
/packs/:id/questions # Questions in pack
// Protected (super_admin only)
/users # User list
/users/:id # User detail
/users/:id/matches/:id # Match chat view
/admins # Admin management
/audit-logs # Audit log viewer
```
### Supabase Queries
- **Always use `.maybeSingle()` instead of `.single()`** when the row might not exist
- All admin operations are audited - check `audit_logs` table structure
### UI Patterns
- Use Tailwind CSS for styling
- Follow existing component patterns in `src/components/`
- Use `AppLayout` wrapper for all protected pages
### Security
- Never expose user passwords or sensitive data in admin views
- Audit log all administrative actions
- Verify admin role before performing operations
## Forbidden Actions
1. **DO NOT** expose user passwords or auth tokens
2. **DO NOT** allow content admins to access user data
3. **DO NOT** bypass role checks in protected routes
4. **DO NOT** perform destructive operations without confirmation
5. **DO NOT** use `.single()` for queries that might return 0 rows
6. **DO NOT** skip audit logging for administrative actions
+2 -1
View File
@@ -5,7 +5,8 @@ services:
dockerfile: apps/admin/Dockerfile
args:
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
- VITE_API_URL=${VITE_API_URL}
- VITE_OPENAI_API_KEY=${VITE_OPENAI_API_KEY}
- VITE_OPENROUTER_API_KEY=${VITE_OPENROUTER_API_KEY}
- VITE_AI_MODEL=${VITE_AI_MODEL}
+1
View File
@@ -8,6 +8,7 @@ services:
environment:
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
- VITE_API_URL=${VITE_API_URL:-http://127.0.0.1:3003}
- VITE_OPENAI_API_KEY=${VITE_OPENAI_API_KEY}
- VITE_OPENROUTER_API_KEY=${VITE_OPENROUTER_API_KEY}
- VITE_AI_MODEL=${VITE_AI_MODEL}
+5 -3
View File
@@ -4,9 +4,11 @@
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"typecheck": "tsc --noEmit",
"dev": "vite",
"build": "vite build",
"lint": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"typecheck": "tsc --noEmit",
"preview": "vite preview"
},
"dependencies": {
+1 -1
View File
@@ -195,7 +195,7 @@ function App() {
<Route
path="/flagged-messages"
element={
<ProtectedRoute requiredPermission={PERMISSION_KEYS.MANAGE_AI_CONFIG}>
<ProtectedRoute requiredPermission={PERMISSION_KEYS.VIEW_CHATS}>
<FlaggedMessagesPage />
</ProtectedRoute>
}
@@ -0,0 +1,179 @@
import { useEffect, useState } from 'react';
import type { ContentReviewStatus } from '@sauci/shared';
import { Archive, CheckCircle2, ClipboardCheck, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/AuthContext';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
CONTENT_STATUS_LABELS,
type ReviewableContentTable,
updateContentReviewStatus,
} from '@/services/contentReviews';
interface ContentReviewControlProps {
table: ReviewableContentTable;
entityId: string;
entityLabel: string;
status?: ContentReviewStatus | null;
reason?: string | null;
onChanged: () => void | Promise<void>;
compact?: boolean;
}
const badgeClasses: Record<ContentReviewStatus, string> = {
unreviewed: 'border-amber-500 text-amber-500',
allowed: 'border-green-500 text-green-500',
archived: 'border-slate-500 text-slate-400',
};
const statusIcons: Record<ContentReviewStatus, typeof ClipboardCheck> = {
unreviewed: ClipboardCheck,
allowed: CheckCircle2,
archived: Archive,
};
export function ContentReviewControl({
table,
entityId,
entityLabel,
status,
reason,
onChanged,
compact = false,
}: ContentReviewControlProps) {
const { isSuperAdmin } = useAuth();
const resolvedStatus = status ?? 'unreviewed';
const StatusIcon = statusIcons[resolvedStatus];
const [open, setOpen] = useState(false);
const [nextStatus, setNextStatus] = useState<ContentReviewStatus>(resolvedStatus);
const [nextReason, setNextReason] = useState(reason ?? '');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!open) {
setNextStatus(resolvedStatus);
setNextReason(reason ?? '');
}
}, [open, reason, resolvedStatus]);
const save = async () => {
if (!nextReason.trim()) {
toast.error('A review reason is required');
return;
}
setSaving(true);
try {
await updateContentReviewStatus(table, entityId, nextStatus, nextReason);
toast.success(`${entityLabel} marked ${CONTENT_STATUS_LABELS[nextStatus].toLowerCase()}`);
setOpen(false);
await onChanged();
} catch (error) {
toast.error('Failed to update catalogue status');
console.error(error);
} finally {
setSaving(false);
}
};
return (
<div className="flex items-center gap-2">
<Badge
variant="outline"
className={`${badgeClasses[resolvedStatus]} ${compact ? 'text-[10px] px-1.5 py-0' : ''}`}
title={reason || 'No review reason recorded'}
>
<StatusIcon className="mr-1 h-3 w-3" />
{CONTENT_STATUS_LABELS[resolvedStatus]}
</Badge>
{isSuperAdmin && (
<>
<Button
type="button"
variant="ghost"
size={compact ? 'sm' : 'default'}
className={compact ? 'h-7 px-2 text-xs' : undefined}
onClick={() => setOpen(true)}
aria-label={`Review catalogue status for ${entityLabel}`}
>
Review
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Review catalogue status</DialogTitle>
<DialogDescription>
This records a reversible editorial decision for {entityLabel}.
Current customer apps do not filter this status yet.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label htmlFor={`content-status-${entityId}`}>Status</Label>
<Select
value={nextStatus}
onValueChange={(value) => {
const selectedStatus = value as ContentReviewStatus;
setNextStatus(selectedStatus);
if (selectedStatus !== resolvedStatus) setNextReason('');
}}
>
<SelectTrigger id={`content-status-${entityId}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="unreviewed">Needs review</SelectItem>
<SelectItem value="allowed">Allowed</SelectItem>
<SelectItem value="archived">Archived</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor={`content-reason-${entityId}`}>Reason</Label>
<Textarea
id={`content-reason-${entityId}`}
value={nextReason}
onChange={(event) => setNextReason(event.target.value)}
placeholder="Explain why this content is allowed, archived, or needs another review"
rows={4}
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button type="button" onClick={save} disabled={saving || !nextReason.trim()}>
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Save decision
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)}
</div>
);
}
@@ -1,281 +1,281 @@
import { useState } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, Tags, Check, Plus, X } from 'lucide-react';
import { extractTopicsFromPack, ExtractedTopic } from '@/lib/openai';
import { supabase } from '@/config';
import { toast } from 'sonner';
interface ExtractTopicsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
pack: {
id: string;
name: string;
description: string | null;
};
onUpdated: () => void;
}
export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: ExtractTopicsDialogProps) {
const [analyzing, setAnalyzing] = useState(false);
const [topics, setTopics] = useState<ExtractedTopic[]>([]);
const [reasoning, setReasoning] = useState('');
const [selectedTopics, setSelectedTopics] = useState<Set<string>>(new Set());
const [step, setStep] = useState<'initial' | 'review'>('initial');
const [applying, setApplying] = useState(false);
const handleAnalyze = async () => {
setAnalyzing(true);
try {
// Fetch questions for this pack
const { data: questions, error: questionsError } = await supabase
.from('questions')
.select('text')
.eq('pack_id', pack.id);
if (questionsError) throw questionsError;
if (!questions || questions.length === 0) {
toast.error('This pack has no questions to analyze');
return;
}
// Fetch existing topics
const { data: existingTopics, error: topicsError } = await supabase
.from('topics')
.select('id, name')
.order('name');
if (topicsError) throw topicsError;
const result = await extractTopicsFromPack(
pack.name,
pack.description,
questions.map(q => q.text),
existingTopics || []
);
setTopics(result.topics);
setReasoning(result.reasoning);
// Default select all
setSelectedTopics(new Set(result.topics.map(t => t.name)));
setStep('review');
} catch (error) {
console.error(error);
toast.error('Failed to analyze pack');
} finally {
setAnalyzing(false);
}
};
const handleApply = async () => {
setApplying(true);
try {
const selectedList = topics.filter(t => selectedTopics.has(t.name));
if (selectedList.length === 0) {
onOpenChange(false);
return;
}
// First, create any new topics
const newTopics = selectedList.filter(t => t.isNew);
const existingTopicIds: string[] = selectedList
.filter(t => !t.isNew && t.existingTopicId)
.map(t => t.existingTopicId!);
if (newTopics.length > 0) {
const { data: createdTopics, error: createError } = await supabase
.from('topics')
.insert(newTopics.map(t => ({ name: t.name })))
.select('id');
if (createError) throw createError;
if (createdTopics) {
existingTopicIds.push(...createdTopics.map(t => t.id));
}
}
// Remove existing pack_topics for this pack
await supabase
.from('pack_topics')
.delete()
.eq('pack_id', pack.id);
// Insert new pack_topics relationships
if (existingTopicIds.length > 0) {
const { error: linkError } = await supabase
.from('pack_topics')
.insert(existingTopicIds.map(topicId => ({
pack_id: pack.id,
topic_id: topicId,
})));
if (linkError) throw linkError;
}
toast.success(`Added ${selectedList.length} topic${selectedList.length !== 1 ? 's' : ''} to pack`);
onUpdated();
handleClose();
} catch (error) {
console.error(error);
toast.error('Failed to apply topics');
} finally {
setApplying(false);
}
};
const handleClose = () => {
onOpenChange(false);
// Reset state after transition
setTimeout(() => {
setStep('initial');
setTopics([]);
setReasoning('');
setSelectedTopics(new Set());
}, 300);
};
const toggleSelection = (name: string) => {
const next = new Set(selectedTopics);
if (next.has(name)) next.delete(name);
else next.add(name);
setSelectedTopics(next);
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-2xl max-h-[90vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Tags className="h-5 w-5 text-blue-500" />
Extract Topics
</DialogTitle>
<DialogDescription>
Use AI to identify topics and kinks for "{pack.name}"
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto py-4">
{step === 'initial' ? (
<div className="flex flex-col items-center justify-center py-12 text-center space-y-4">
<div className="bg-blue-500/20 p-4 rounded-full">
<Tags className="h-12 w-12 text-blue-400" />
</div>
<div className="space-y-2">
<h3 className="text-lg font-medium">Analyze pack for topics</h3>
<p className="text-muted-foreground max-w-md mx-auto">
The AI will analyze the questions in this pack and suggest relevant topics
like bondage, exhibitionism, romance, etc. It will prefer matching existing
topics when possible.
</p>
</div>
<Button onClick={handleAnalyze} disabled={analyzing} size="lg" className="bg-blue-600 hover:bg-blue-700">
{analyzing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Analyzing...
</>
) : (
'Start Analysis'
)}
</Button>
</div>
) : (
<div className="space-y-6">
{topics.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<X className="h-8 w-8 mx-auto mb-2 text-yellow-500" />
No topics could be identified for this pack.
</div>
) : (
<>
<div className="space-y-3">
<h4 className="text-sm font-medium">Suggested Topics</h4>
<div className="flex flex-wrap gap-2">
{topics.map((topic) => (
<Badge
key={topic.name}
variant={selectedTopics.has(topic.name) ? 'default' : 'outline'}
className={`cursor-pointer text-sm py-1.5 px-3 ${
selectedTopics.has(topic.name)
? topic.isNew
? 'bg-green-600 hover:bg-green-700'
: 'bg-blue-600 hover:bg-blue-700'
: 'hover:bg-muted'
}`}
onClick={() => toggleSelection(topic.name)}
>
{selectedTopics.has(topic.name) ? (
<Check className="h-3 w-3 mr-1" />
) : null}
{topic.name}
{topic.isNew && (
<Plus className="h-3 w-3 ml-1" />
)}
</Badge>
))}
</div>
<div className="flex gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<div className="w-3 h-3 rounded bg-blue-600" />
Existing topic
</span>
<span className="flex items-center gap-1">
<div className="w-3 h-3 rounded bg-green-600" />
<Plus className="h-3 w-3" />
New topic
</span>
</div>
</div>
{reasoning && (
<div className="space-y-2">
<h4 className="text-sm font-medium">AI Reasoning</h4>
<p className="text-sm text-muted-foreground bg-muted/50 p-3 rounded-md">
{reasoning}
</p>
</div>
)}
</>
)}
</div>
)}
</div>
<DialogFooter>
{step === 'review' && (
<>
<Button variant="outline" onClick={() => setStep('initial')}>
Back
</Button>
<Button
onClick={handleApply}
disabled={applying || topics.length === 0 || selectedTopics.size === 0}
className="bg-blue-600 hover:bg-blue-700"
>
{applying ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Applying...
</>
) : (
`Apply ${selectedTopics.size} Topic${selectedTopics.size !== 1 ? 's' : ''}`
)}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
import { useState } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, Tags, Check, Plus, X } from 'lucide-react';
import { extractTopicsFromPack, ExtractedTopic } from '@/lib/openai';
import { adminData } from '@/lib/adminApi';
import { toast } from 'sonner';
interface ExtractTopicsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
pack: {
id: string;
name: string;
description: string | null;
};
onUpdated: () => void;
}
export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: ExtractTopicsDialogProps) {
const [analyzing, setAnalyzing] = useState(false);
const [topics, setTopics] = useState<ExtractedTopic[]>([]);
const [reasoning, setReasoning] = useState('');
const [selectedTopics, setSelectedTopics] = useState<Set<string>>(new Set());
const [step, setStep] = useState<'initial' | 'review'>('initial');
const [applying, setApplying] = useState(false);
const handleAnalyze = async () => {
setAnalyzing(true);
try {
// Fetch questions for this pack
const { data: questions, error: questionsError } = await adminData
.from('questions')
.select('text')
.eq('pack_id', pack.id);
if (questionsError) throw questionsError;
if (!questions || questions.length === 0) {
toast.error('This pack has no questions to analyze');
return;
}
// Fetch existing topics
const { data: existingTopics, error: topicsError } = await adminData
.from('topics')
.select('id, name')
.order('name');
if (topicsError) throw topicsError;
const result = await extractTopicsFromPack(
pack.name,
pack.description,
questions.map(q => q.text),
existingTopics || []
);
setTopics(result.topics);
setReasoning(result.reasoning);
// Default select all
setSelectedTopics(new Set(result.topics.map(t => t.name)));
setStep('review');
} catch (error) {
console.error(error);
toast.error('Failed to analyze pack');
} finally {
setAnalyzing(false);
}
};
const handleApply = async () => {
setApplying(true);
try {
const selectedList = topics.filter(t => selectedTopics.has(t.name));
if (selectedList.length === 0) {
onOpenChange(false);
return;
}
// First, create any new topics
const newTopics = selectedList.filter(t => t.isNew);
const existingTopicIds: string[] = selectedList
.filter(t => !t.isNew && t.existingTopicId)
.map(t => t.existingTopicId!);
if (newTopics.length > 0) {
const { data: createdTopics, error: createError } = await adminData
.from('topics')
.insert(newTopics.map(t => ({ name: t.name })))
.select('id');
if (createError) throw createError;
if (createdTopics) {
existingTopicIds.push(...createdTopics.map(t => t.id));
}
}
// Remove existing pack_topics for this pack
await adminData
.from('pack_topics')
.delete()
.eq('pack_id', pack.id);
// Insert new pack_topics relationships
if (existingTopicIds.length > 0) {
const { error: linkError } = await adminData
.from('pack_topics')
.insert(existingTopicIds.map(topicId => ({
pack_id: pack.id,
topic_id: topicId,
})));
if (linkError) throw linkError;
}
toast.success(`Added ${selectedList.length} topic${selectedList.length !== 1 ? 's' : ''} to pack`);
onUpdated();
handleClose();
} catch (error) {
console.error(error);
toast.error('Failed to apply topics');
} finally {
setApplying(false);
}
};
const handleClose = () => {
onOpenChange(false);
// Reset state after transition
setTimeout(() => {
setStep('initial');
setTopics([]);
setReasoning('');
setSelectedTopics(new Set());
}, 300);
};
const toggleSelection = (name: string) => {
const next = new Set(selectedTopics);
if (next.has(name)) next.delete(name);
else next.add(name);
setSelectedTopics(next);
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-2xl max-h-[90vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Tags className="h-5 w-5 text-blue-500" />
Extract Topics
</DialogTitle>
<DialogDescription>
Use AI to identify topics and kinks for "{pack.name}"
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto py-4">
{step === 'initial' ? (
<div className="flex flex-col items-center justify-center py-12 text-center space-y-4">
<div className="bg-blue-500/20 p-4 rounded-full">
<Tags className="h-12 w-12 text-blue-400" />
</div>
<div className="space-y-2">
<h3 className="text-lg font-medium">Analyze pack for topics</h3>
<p className="text-muted-foreground max-w-md mx-auto">
The AI will analyze the questions in this pack and suggest relevant topics
like bondage, exhibitionism, romance, etc. It will prefer matching existing
topics when possible.
</p>
</div>
<Button onClick={handleAnalyze} disabled={analyzing} size="lg" className="bg-blue-600 hover:bg-blue-700">
{analyzing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Analyzing...
</>
) : (
'Start Analysis'
)}
</Button>
</div>
) : (
<div className="space-y-6">
{topics.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<X className="h-8 w-8 mx-auto mb-2 text-yellow-500" />
No topics could be identified for this pack.
</div>
) : (
<>
<div className="space-y-3">
<h4 className="text-sm font-medium">Suggested Topics</h4>
<div className="flex flex-wrap gap-2">
{topics.map((topic) => (
<Badge
key={topic.name}
variant={selectedTopics.has(topic.name) ? 'default' : 'outline'}
className={`cursor-pointer text-sm py-1.5 px-3 ${
selectedTopics.has(topic.name)
? topic.isNew
? 'bg-green-600 hover:bg-green-700'
: 'bg-blue-600 hover:bg-blue-700'
: 'hover:bg-muted'
}`}
onClick={() => toggleSelection(topic.name)}
>
{selectedTopics.has(topic.name) ? (
<Check className="h-3 w-3 mr-1" />
) : null}
{topic.name}
{topic.isNew && (
<Plus className="h-3 w-3 ml-1" />
)}
</Badge>
))}
</div>
<div className="flex gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<div className="w-3 h-3 rounded bg-blue-600" />
Existing topic
</span>
<span className="flex items-center gap-1">
<div className="w-3 h-3 rounded bg-green-600" />
<Plus className="h-3 w-3" />
New topic
</span>
</div>
</div>
{reasoning && (
<div className="space-y-2">
<h4 className="text-sm font-medium">AI Reasoning</h4>
<p className="text-sm text-muted-foreground bg-muted/50 p-3 rounded-md">
{reasoning}
</p>
</div>
)}
</>
)}
</div>
)}
</div>
<DialogFooter>
{step === 'review' && (
<>
<Button variant="outline" onClick={() => setStep('initial')}>
Back
</Button>
<Button
onClick={handleApply}
disabled={applying || topics.length === 0 || selectedTopics.size === 0}
className="bg-blue-600 hover:bg-blue-700"
>
{applying ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Applying...
</>
) : (
`Apply ${selectedTopics.size} Topic${selectedTopics.size !== 1 ? 's' : ''}`
)}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -12,7 +12,7 @@ import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2, ShieldCheck, ArrowRight, Check } from 'lucide-react';
import { analyzeQuestionTargets, TargetAnalysis } from '@/lib/openai';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
// Define local compatible interface
@@ -111,7 +111,7 @@ export function FixTargetsDialog({ open, onOpenChange, questions, onUpdated }: F
// Apply updates in parallel with audit logging
await Promise.all(updates.map(update =>
auditedSupabase.update('questions', update.id, {
auditedAdminData.update('questions', update.id, {
allowed_couple_genders: update.suggested_targets && update.suggested_targets.length > 0 ? update.suggested_targets : null,
target_user_genders: update.suggested_initiator && update.suggested_initiator.length > 0 ? update.suggested_initiator : null,
})
@@ -11,7 +11,7 @@ import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2, Wand2, ArrowRight, Check } from 'lucide-react';
import { analyzeQuestionText, TextAnalysis } from '@/lib/openai';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
interface Question {
@@ -62,7 +62,7 @@ export function FixTextDialog({ open, onOpenChange, questions, isExplicit = fals
// Apply updates in parallel with audit logging
await Promise.all(updates.map(update =>
auditedSupabase.update('questions', update.id, {
auditedAdminData.update('questions', update.id, {
text: update.suggested_text,
partner_text: update.suggested_partner_text,
})
@@ -0,0 +1,130 @@
import { useEffect, useState } from 'react';
import type { AnswerType, QuestionType } from '@sauci/shared';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Image as ImageIcon, Music2 } from 'lucide-react';
import { getAdminResponseMedia } from '@/lib/adminApi';
import { formatAdminResponse, QUESTION_TYPE_LABELS, type AdminResponseData } from '@/lib/questionResponses';
interface ResponseAnswerProps {
answer: AnswerType;
responseId?: string;
questionType?: QuestionType | null;
responseData?: AdminResponseData;
responderId?: string;
responderName?: string | null;
}
export function ResponseAnswer({
answer,
responseId,
questionType,
responseData = null,
responderId,
responderName,
}: ResponseAnswerProps) {
const formatted = formatAdminResponse(questionType, answer, responseData, { responderId, responderName });
const resolvedType = questionType ?? 'swipe';
return (
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">{formatted.label}</span>
{resolvedType !== 'swipe' && (
<Badge variant="outline" className="text-[10px] font-normal">
{QUESTION_TYPE_LABELS[resolvedType]}
</Badge>
)}
</div>
{formatted.detail && (
<p className="max-w-md whitespace-pre-wrap break-words text-xs text-muted-foreground">
{formatted.detail}
</p>
)}
{(resolvedType === 'photo' || resolvedType === 'audio') && responseId && (
<ProtectedResponseMedia
responseId={responseId}
mediaType={resolvedType}
label={responderName || 'User response'}
/>
)}
</div>
);
}
function ProtectedResponseMedia({
responseId,
mediaType,
label,
}: {
responseId: string;
mediaType: 'photo' | 'audio';
label: string;
}) {
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
let objectUrl: string | null = null;
const load = async () => {
try {
setError(null);
objectUrl = URL.createObjectURL(await getAdminResponseMedia(responseId));
if (!cancelled) setUrl(objectUrl);
} catch (loadError) {
if (!cancelled) {
setError(loadError instanceof Error ? loadError.message : 'Failed to load media');
}
}
};
load();
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [responseId]);
if (error) {
return (
<p className="flex items-center gap-1 text-xs text-destructive" role="alert">
{mediaType === 'photo' ? <ImageIcon className="h-3 w-3" /> : <Music2 className="h-3 w-3" />}
{error}
</p>
);
}
if (!url) {
return <Skeleton className={mediaType === 'photo' ? 'h-20 w-28 rounded-md' : 'h-10 w-64 rounded-md'} />;
}
if (mediaType === 'photo') {
return (
<button
type="button"
className="block overflow-hidden rounded-md border bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => window.open(url, '_blank', 'noopener,noreferrer')}
aria-label={`Open ${label} photo response`}
>
<img
src={url}
alt={`${label} photo response`}
className="h-20 w-28 object-cover transition-transform hover:scale-105"
/>
</button>
);
}
return (
<audio
src={url}
controls
preload="metadata"
className="h-10 w-64 max-w-full"
aria-label={`Play ${label} audio response`}
/>
);
}
@@ -22,8 +22,8 @@ import {
DeletionAnalysis,
PropsAnalysis,
} from '@/lib/openai';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
type QuestionType = 'swipe' | 'text_answer' | 'audio' | 'photo' | 'who_likely';
@@ -101,7 +101,7 @@ export function ReviewQuestionsDialog({ open, onOpenChange, questions, onUpdated
if (existingProps.length > 0) return existingProps;
try {
const { data, error } = await supabase
const { data, error } = await adminData
.from('questions')
.select('required_props')
.not('required_props', 'is', null)
@@ -252,12 +252,12 @@ export function ReviewQuestionsDialog({ open, onOpenChange, questions, onUpdated
// Apply updates/deletions in parallel with audit logging
const operations: Promise<unknown>[] = updates.map(update =>
auditedSupabase.update('questions', update.id, update.data)
auditedAdminData.update('questions', update.id, update.data)
);
if (deleteIds.length > 0) {
operations.push(
auditedSupabase.deleteMany('questions', deleteIds).then(result => {
auditedAdminData.deleteMany('questions', deleteIds).then(result => {
if (result.error) throw result.error;
})
);
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import { Link, useLocation, useParams } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
interface BreadcrumbItem {
label: string;
@@ -32,7 +32,7 @@ function useBreadcrumbs(): { breadcrumbs: BreadcrumbItem[]; loading: boolean } {
if (params.packId && !params.categoryId) {
setLoading(true);
try {
const { data } = await supabase
const { data } = await adminData
.from('question_packs')
.select('category_id, categories(name)')
.eq('id', params.packId)
@@ -63,7 +63,7 @@ function useBreadcrumbs(): { breadcrumbs: BreadcrumbItem[]; loading: boolean } {
if (params.userId) {
setLoading(true);
try {
const { data } = await supabase
const { data } = await adminData
.from('profiles')
.select('id, name')
.eq('id', params.userId)
+1 -1
View File
@@ -108,7 +108,7 @@ const systemNav: NavItem[] = [
label: 'Flagged Messages',
href: '/flagged-messages',
icon: <AlertTriangle className="h-5 w-5" />,
requiredPermission: PERMISSION_KEYS.MANAGE_AI_CONFIG,
requiredPermission: PERMISSION_KEYS.VIEW_CHATS,
},
{
label: 'AI Settings',
+15 -7
View File
@@ -1,11 +1,19 @@
import { createClient } from '@supabase/supabase-js';
export const supabaseConfig = {
export const supabaseConfig = {
url: import.meta.env.VITE_SUPABASE_URL,
anonKey: import.meta.env.VITE_SUPABASE_ANON_KEY,
};
export const supabase = createClient(
supabaseConfig.url,
supabaseConfig.anonKey
);
};
export const authClient = createClient(
supabaseConfig.url,
supabaseConfig.anonKey
);
const configuredApiUrl = import.meta.env.VITE_API_URL;
if (!configuredApiUrl) {
throw new Error('Missing required environment variable: VITE_API_URL');
}
export const apiUrl = configuredApiUrl.replace(/\/$/, '');
+22 -21
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { supabase } from '../config';
import { authClient } from '../config';
import { adminRequest } from '@/lib/adminApi';
import type { User, Session } from '@supabase/supabase-js';
import { preloadAiConfig, clearAiConfigCache } from '@/hooks/useAiConfig';
@@ -80,23 +81,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
// Get initial session
supabase.auth.getSession().then(({ data: { session } }) => {
authClient.auth.getSession().then(async ({ data: { session } }) => {
setSession(session);
setUser(session?.user ?? null);
// Restore permissions from localStorage
const storedPermissions = localStorage.getItem(PERMISSIONS_KEY);
if (storedPermissions) {
setPermissions(JSON.parse(storedPermissions));
// Preload AI config if user has an existing session (non-blocking)
preloadAiConfig().catch(console.error);
if (session) {
try {
const currentPermissions = await adminRequest<AdminPermissions>('/v1/admin/me');
setPermissions(currentPermissions);
localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(currentPermissions));
preloadAiConfig().catch(console.error);
} catch {
setPermissions(null);
localStorage.removeItem(PERMISSIONS_KEY);
}
}
setLoading(false);
});
// Listen for auth changes
const { data: { subscription } } = supabase.auth.onAuthStateChange(
const { data: { subscription } } = authClient.auth.onAuthStateChange(
(_event, session) => {
setSession(session);
setUser(session?.user ?? null);
@@ -112,7 +116,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []);
const login = async (email: string, password: string) => {
const { data, error } = await supabase.auth.signInWithPassword({
const { error } = await authClient.auth.signInWithPassword({
email,
password,
});
@@ -122,20 +126,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
// Fetch admin role and permissions
const { data: adminData, error: adminError } = await supabase
.from('admin_users')
.select('role, permissions')
.eq('user_id', data.user.id)
.single();
if (adminError || !adminData) {
await supabase.auth.signOut();
let adminData: AdminPermissions;
try {
adminData = await adminRequest<AdminPermissions>('/v1/admin/me');
} catch {
await authClient.auth.signOut();
throw new Error('Access denied. You are not an administrator.');
}
// Store permissions from database
const perms: AdminPermissions = {
role: adminData.role as AdminRole,
role: adminData.role,
permissions: (adminData.permissions as string[]) || [],
};
@@ -150,7 +151,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
localStorage.removeItem(PERMISSIONS_KEY);
setPermissions(null);
clearAiConfigCache();
await supabase.auth.signOut();
await authClient.auth.signOut();
};
const isSuperAdmin = permissions?.role === 'super_admin';
+5 -5
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
export interface CouncilGenerator {
model: string;
@@ -74,7 +74,7 @@ export function useAiConfig(): UseAiConfigReturn {
setError(null);
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from('ai_config')
.select('*')
.limit(1)
@@ -82,7 +82,7 @@ export function useAiConfig(): UseAiConfigReturn {
if (fetchError) {
// If user doesn't have access (not super admin), that's expected
if (fetchError.code === 'PGRST116' || fetchError.message.includes('permission')) {
if (fetchError.message.includes('permission')) {
setError('Access denied. Super admin privileges required.');
} else {
setError(fetchError.message);
@@ -110,7 +110,7 @@ export function useAiConfig(): UseAiConfigReturn {
}
try {
const { error: updateError } = await supabase
const { error: updateError } = await adminData
.from('ai_config')
.update(updates)
.eq('id', config.id);
@@ -160,7 +160,7 @@ export async function preloadAiConfig(): Promise<AiConfig | null> {
}
try {
const { data } = await supabase
const { data } = await adminData
.from('ai_config')
.select('*')
.limit(1)
+3 -3
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
export interface AppConfig {
id: string;
@@ -40,7 +40,7 @@ export function useAppConfig(): UseAppConfigReturn {
setError(null);
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from('app_config')
.select('*')
.limit(1)
@@ -71,7 +71,7 @@ export function useAppConfig(): UseAppConfigReturn {
}
try {
const { error: updateError } = await supabase
const { error: updateError } = await adminData
.from('app_config')
.update(updates)
.eq('id', config.id);
@@ -1,10 +1,12 @@
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
// Tables to audit
const AUDITED_TABLES = [
'question_packs',
'questions',
'categories',
'dare_packs',
'dares',
'profiles',
'couples',
'responses',
@@ -26,23 +28,10 @@ async function logAction(
oldValues?: Record<string, unknown> | null,
newValues?: Record<string, unknown> | null
): Promise<void> {
if (!AUDITED_TABLES.includes(tableName)) return;
try {
const { error } = await supabase.rpc('log_admin_action', {
p_table_name: tableName,
p_action: action,
p_record_id: recordId,
p_old_values: oldValues || null,
p_new_values: newValues || null,
});
if (error) {
console.error('Failed to log audit action:', error);
}
} catch (error) {
console.error('Failed to log audit action:', error);
// Don't throw - logging failure shouldn't block the operation
}
// The standalone admin API writes the mutation and audit record in one
// transaction. Keeping this no-op preserves the existing call sites while
// avoiding duplicate or client-forgeable audit entries.
void tableName; void action; void recordId; void oldValues; void newValues;
}
interface InsertResult<T> {
@@ -56,9 +45,9 @@ interface SingleResult<T> {
}
/**
* Audited Supabase operations - automatically logs INSERT/UPDATE/DELETE to audit_logs
* Admin API mutations. The server writes each mutation and audit record atomically.
*/
export const auditedSupabase = {
export const auditedAdminData = {
/**
* Insert records with audit logging
*/
@@ -68,7 +57,7 @@ export const auditedSupabase = {
): Promise<InsertResult<T>> {
const recordArray = Array.isArray(records) ? records : [records];
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.insert(recordArray)
.select();
@@ -94,7 +83,7 @@ export const auditedSupabase = {
// Fetch old values before update
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq('id', id)
@@ -102,7 +91,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.update(updates)
.eq('id', id)
@@ -127,14 +116,14 @@ export const auditedSupabase = {
// Fetch old values before update
let oldRecords: Record<string, unknown>[] = [];
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq(filter.column, filter.value);
oldRecords = oldData || [];
}
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.update(updates)
.eq(filter.column, filter.value)
@@ -161,7 +150,7 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq('id', id)
@@ -169,7 +158,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.eq('id', id);
@@ -191,14 +180,14 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldRecords: Record<string, unknown>[] = [];
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.in('id', ids);
oldRecords = oldData || [];
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.in('id', ids);
@@ -224,7 +213,7 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq(field, value)
@@ -232,7 +221,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.eq(field, value);
+12 -12
View File
@@ -1,14 +1,14 @@
import { useState, useCallback } from 'react';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type SupabaseFilterFn = (query: any) => any;
type AdminFilterFn = (query: any) => any;
interface UseCrudOperationsOptions<T> {
/**
* The Supabase table name
* The standalone admin API resource name
*/
table: string;
@@ -41,7 +41,7 @@ interface UseCrudOperationsOptions<T> {
}
/**
* Generic CRUD operations hook for Supabase tables
* Generic CRUD operations hook for standalone admin API resources
* Reduces boilerplate for data fetching and mutations across pages.
*
* @example
@@ -90,13 +90,13 @@ export function useCrudOperations<T extends { id: string }>({
* @param filter Optional filter function to modify the query
*/
const fetchAll = useCallback(async (
filter?: SupabaseFilterFn
filter?: AdminFilterFn
): Promise<T[]> => {
setLoading(true);
setError(null);
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let query: any = supabase.from(table).select(select);
let query: any = adminData.from(table).select(select);
if (filter) {
query = filter(query);
@@ -131,7 +131,7 @@ export function useCrudOperations<T extends { id: string }>({
*/
const fetchById = useCallback(async (id: string): Promise<T | null> => {
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from(table)
.select(select)
.eq('id', id)
@@ -158,7 +158,7 @@ export function useCrudOperations<T extends { id: string }>({
const { refetch = true, silent = false } = options;
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data: created, error: createError } = await auditedSupabase.insert(table, data as any);
const { data: created, error: createError } = await auditedAdminData.insert(table, data as any);
if (createError) throw createError;
@@ -170,7 +170,7 @@ export function useCrudOperations<T extends { id: string }>({
await fetchAll();
}
// auditedSupabase.insert returns T[] | null, get first element
// auditedAdminData.insert returns T[] | null, get first element
return created && created.length > 0 ? (created[0] as T) : null;
} catch (err) {
if (!silent) {
@@ -194,7 +194,7 @@ export function useCrudOperations<T extends { id: string }>({
): Promise<boolean> => {
const { refetch = true, silent = false } = options;
try {
const { error: updateError } = await auditedSupabase.update(table, id, data);
const { error: updateError } = await auditedAdminData.update(table, id, data);
if (updateError) throw updateError;
@@ -233,7 +233,7 @@ export function useCrudOperations<T extends { id: string }>({
}
try {
const { error: deleteError } = await auditedSupabase.delete(table, id);
const { error: deleteError } = await auditedAdminData.delete(table, id);
if (deleteError) throw deleteError;
+92 -243
View File
@@ -1,243 +1,92 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { supabase } from '@/config';
import { toast } from 'sonner';
import type { RealtimeChannel } from '@supabase/supabase-js';
export type SubscriptionStatus = 'SUBSCRIBED' | 'SUBSCRIBING' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED';
export interface UseRealtimeSubscriptionOptions<T> {
table: string;
schema?: string;
event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*';
filter?: string;
onInsert?: (payload: T) => void;
onUpdate?: (payload: { old: T; new: T }) => void;
onDelete?: (payload: T) => void;
insertToast?: {
enabled: boolean;
message: string | ((payload: T) => string);
type?: 'success' | 'info' | 'warning';
};
updateToast?: {
enabled: boolean;
message: string | ((payload: { old: T; new: T }) => string);
type?: 'success' | 'info' | 'warning';
};
deleteToast?: {
enabled: boolean;
message: string | ((payload: T) => string);
type?: 'success' | 'info' | 'warning';
};
debounceMs?: number;
enabled?: boolean;
}
export interface UseRealtimeSubscriptionReturn {
status: SubscriptionStatus;
error: Error | null;
}
const MAX_RETRIES = 3;
export function useRealtimeSubscription<T>(
options: UseRealtimeSubscriptionOptions<T>
): UseRealtimeSubscriptionReturn {
const {
table,
schema = 'public',
event = '*',
filter,
onInsert,
onUpdate,
onDelete,
insertToast,
updateToast,
deleteToast,
debounceMs = 0,
enabled = true,
} = options;
const [status, setStatus] = useState<SubscriptionStatus>('CLOSED');
const [error, setError] = useState<Error | null>(null);
const channelRef = useRef<RealtimeChannel | null>(null);
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const retryCountRef = useRef(0);
const isMountedRef = useRef(true);
// Use refs for callbacks and toast options to avoid re-subscription on every render
const onInsertRef = useRef(onInsert);
const onUpdateRef = useRef(onUpdate);
const onDeleteRef = useRef(onDelete);
const insertToastRef = useRef(insertToast);
const updateToastRef = useRef(updateToast);
const deleteToastRef = useRef(deleteToast);
// Keep refs up to date
useEffect(() => {
onInsertRef.current = onInsert;
onUpdateRef.current = onUpdate;
onDeleteRef.current = onDelete;
insertToastRef.current = insertToast;
updateToastRef.current = updateToast;
deleteToastRef.current = deleteToast;
});
// Debounced callback wrapper
const debouncedCallback = useCallback(
(callback: () => void) => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (debounceMs > 0) {
debounceTimerRef.current = setTimeout(() => {
if (isMountedRef.current) {
callback();
}
}, debounceMs);
} else {
callback();
}
},
[debounceMs]
);
// Handle incoming changes - use refs to avoid dependency changes
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleChange = useCallback(
(payload: { eventType: string; new: any; old: any }) => {
if (!isMountedRef.current) return;
const eventType = payload.eventType;
if (eventType === 'INSERT') {
const newRecord = payload.new as T;
if (insertToastRef.current?.enabled) {
const message =
typeof insertToastRef.current.message === 'function'
? insertToastRef.current.message(newRecord)
: insertToastRef.current.message;
toast[insertToastRef.current.type || 'info'](message);
}
if (onInsertRef.current) {
debouncedCallback(() => onInsertRef.current!(newRecord));
}
}
if (eventType === 'UPDATE') {
const updatePayload = { old: payload.old as T, new: payload.new as T };
if (updateToastRef.current?.enabled) {
const message =
typeof updateToastRef.current.message === 'function'
? updateToastRef.current.message(updatePayload)
: updateToastRef.current.message;
toast[updateToastRef.current.type || 'info'](message);
}
if (onUpdateRef.current) {
debouncedCallback(() => onUpdateRef.current!(updatePayload));
}
}
if (eventType === 'DELETE') {
const deletedRecord = payload.old as T;
if (deleteToastRef.current?.enabled) {
const message =
typeof deleteToastRef.current.message === 'function'
? deleteToastRef.current.message(deletedRecord)
: deleteToastRef.current.message;
toast[deleteToastRef.current.type || 'info'](message);
}
if (onDeleteRef.current) {
debouncedCallback(() => onDeleteRef.current!(deletedRecord));
}
}
},
[debouncedCallback]
);
useEffect(() => {
isMountedRef.current = true;
if (!enabled) {
setStatus('CLOSED');
return;
}
const subscribe = () => {
// Create unique channel name
const channelName = `admin-${table}-${filter || 'all'}-${Date.now()}`;
// Build subscription config
const subscriptionConfig: {
event: 'INSERT' | 'UPDATE' | 'DELETE' | '*';
schema: string;
table: string;
filter?: string;
} = {
event,
schema,
table,
};
if (filter) {
subscriptionConfig.filter = filter;
}
setStatus('SUBSCRIBING');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const channel = (supabase.channel(channelName) as any)
.on('postgres_changes', subscriptionConfig, handleChange)
.subscribe((subscriptionStatus: string) => {
if (!isMountedRef.current) return;
if (subscriptionStatus === 'SUBSCRIBED') {
setStatus('SUBSCRIBED');
setError(null);
retryCountRef.current = 0;
} else if (subscriptionStatus === 'CHANNEL_ERROR') {
setStatus('CHANNEL_ERROR');
setError(new Error(`Failed to subscribe to ${table}`));
// Auto-retry with exponential backoff
if (retryCountRef.current < MAX_RETRIES) {
const timeout = Math.pow(2, retryCountRef.current) * 1000;
retryCountRef.current++;
setTimeout(() => {
if (isMountedRef.current && channelRef.current) {
supabase.removeChannel(channelRef.current);
subscribe();
}
}, timeout);
}
} else if (subscriptionStatus === 'TIMED_OUT') {
setStatus('TIMED_OUT');
setError(new Error(`Subscription to ${table} timed out`));
} else if (subscriptionStatus === 'CLOSED') {
setStatus('CLOSED');
}
});
channelRef.current = channel;
};
subscribe();
return () => {
isMountedRef.current = false;
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (channelRef.current) {
supabase.removeChannel(channelRef.current);
}
};
}, [enabled, table, schema, event, filter, handleChange]);
return { status, error };
}
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { queryAdminRows, type AdminFilter } from '@/lib/adminApi';
export type SubscriptionStatus = 'SUBSCRIBED' | 'SUBSCRIBING' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED';
export interface UseRealtimeSubscriptionOptions<T> {
table: string; schema?: string; event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*'; filter?: string;
onInsert?: (payload: T) => void; onUpdate?: (payload: { old: T; new: T }) => void; onDelete?: (payload: T) => void;
insertToast?: { enabled: boolean; message: string | ((payload: T) => string); type?: 'success' | 'info' | 'warning' };
updateToast?: { enabled: boolean; message: string | ((payload: { old: T; new: T }) => string); type?: 'success' | 'info' | 'warning' };
deleteToast?: { enabled: boolean; message: string | ((payload: T) => string); type?: 'success' | 'info' | 'warning' };
debounceMs?: number; enabled?: boolean; pollIntervalMs?: number;
}
export interface UseRealtimeSubscriptionReturn { status: SubscriptionStatus; error: Error | null }
const DEFAULT_POLL_INTERVAL_MS = 10_000;
const MIN_POLL_INTERVAL_MS = 5_000;
function parseFilter(filter?: string): AdminFilter[] | undefined {
if (!filter) return undefined;
const match = /^([a-z_][a-z0-9_]*)=(eq|neq|gte|lte)\.(.+)$/.exec(filter);
return match ? [{ column: match[1], op: match[2] as AdminFilter['op'], value: match[3] }] : undefined;
}
function rowKey(row: unknown, index: number): string {
if (row && typeof row === 'object') {
const record = row as Record<string, unknown>;
const key = record.id ?? `${record.pack_id ?? ''}:${record.topic_id ?? ''}`;
if (key) return String(key);
}
return String(index);
}
export function useRealtimeSubscription<T>(options: UseRealtimeSubscriptionOptions<T>): UseRealtimeSubscriptionReturn {
const { table, event = '*', filter, onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast,
debounceMs = 0, enabled = true, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS } = options;
const [status, setStatus] = useState<SubscriptionStatus>('CLOSED');
const [error, setError] = useState<Error | null>(null);
const snapshotRef = useRef<Map<string, { value: T; json: string }> | null>(null);
const callbacksRef = useRef({ onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast });
callbacksRef.current = { onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast };
const emit = useCallback((callback: () => void) => {
if (debounceMs <= 0) callback(); else window.setTimeout(callback, debounceMs);
}, [debounceMs]);
useEffect(() => {
if (!enabled) { setStatus('CLOSED'); return; }
let cancelled = false;
let timer: number | undefined;
const interval = Math.max(MIN_POLL_INTERVAL_MS, pollIntervalMs);
const poll = async () => {
if (document.visibilityState === 'hidden') { timer = window.setTimeout(poll, interval); return; }
try {
setStatus((current) => current === 'SUBSCRIBED' ? current : 'SUBSCRIBING');
const { rows } = await queryAdminRows<T>(table, { filters: parseFilter(filter), limit: 500 });
if (cancelled) return;
const next = new Map(rows.map((row, index) => [rowKey(row, index), { value: row, json: JSON.stringify(row) }]));
const previous = snapshotRef.current;
if (previous) {
if (event === '*' || event === 'INSERT') for (const [key, entry] of next) if (!previous.has(key)) {
const config = callbacksRef.current;
if (config.insertToast?.enabled) toast[config.insertToast.type || 'info'](typeof config.insertToast.message === 'function' ? config.insertToast.message(entry.value) : config.insertToast.message);
if (config.onInsert) emit(() => config.onInsert!(entry.value));
}
if (event === '*' || event === 'UPDATE') for (const [key, entry] of next) {
const old = previous.get(key);
if (old && old.json !== entry.json) {
const payload = { old: old.value, new: entry.value };
const config = callbacksRef.current;
if (config.updateToast?.enabled) toast[config.updateToast.type || 'info'](typeof config.updateToast.message === 'function' ? config.updateToast.message(payload) : config.updateToast.message);
if (config.onUpdate) emit(() => config.onUpdate!(payload));
}
}
if (event === '*' || event === 'DELETE') for (const [key, entry] of previous) if (!next.has(key)) {
const config = callbacksRef.current;
if (config.deleteToast?.enabled) toast[config.deleteToast.type || 'info'](typeof config.deleteToast.message === 'function' ? config.deleteToast.message(entry.value) : config.deleteToast.message);
if (config.onDelete) emit(() => config.onDelete!(entry.value));
}
}
snapshotRef.current = next;
setStatus('SUBSCRIBED'); setError(null);
} catch (cause) {
if (!cancelled) { setStatus('CHANNEL_ERROR'); setError(cause instanceof Error ? cause : new Error(String(cause))); }
} finally {
if (!cancelled) timer = window.setTimeout(poll, interval);
}
};
void poll();
return () => { cancelled = true; if (timer !== undefined) window.clearTimeout(timer); snapshotRef.current = null; };
}, [emit, enabled, event, filter, pollIntervalMs, table]);
return { status, error };
}
+56
View File
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { getSession } = vi.hoisted(() => ({ getSession: vi.fn() }));
vi.mock('@/config', () => ({
apiUrl: 'http://127.0.0.1:3003',
authClient: { auth: { getSession } },
}));
import { AdminApiError, adminRequest, getAdminResponseMedia, queryAdminRows } from './adminApi';
describe('admin API transport', () => {
beforeEach(() => {
vi.restoreAllMocks();
getSession.mockResolvedValue({ data: { session: { access_token: 'hosted-auth-token' } }, error: null });
});
it('sends the hosted Auth bearer token to the standalone API', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ rows: [], count: 0 }), {
status: 200, headers: { 'content-type': 'application/json' },
}));
await queryAdminRows('profiles', { limit: 25 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('http://127.0.0.1:3003/v1/admin/query/profiles');
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer hosted-auth-token');
expect(init?.body).toBe(JSON.stringify({ limit: 25 }));
});
it('fails closed when there is no authenticated session', async () => {
getSession.mockResolvedValue({ data: { session: null }, error: null });
await expect(adminRequest('/v1/admin/me')).rejects.toMatchObject({ status: 401 } satisfies Partial<AdminApiError>);
});
it('surfaces the API error message', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ error: { message: 'Administrator access denied' } }), {
status: 403, headers: { 'content-type': 'application/json' },
}));
await expect(adminRequest('/v1/admin/me')).rejects.toThrow('Administrator access denied');
});
it('loads protected response media from the standalone API with hosted Auth', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('response-media', {
status: 200, headers: { 'content-type': 'image/jpeg' },
}));
const responseId = '11111111-1111-4111-8111-111111111111';
const blob = await getAdminResponseMedia(responseId);
expect(await blob.text()).toBe('response-media');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe(`http://127.0.0.1:3003/v1/admin/responses/${responseId}/media`);
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer hosted-auth-token');
expect(init?.body).toBeUndefined();
});
});
+258
View File
@@ -0,0 +1,258 @@
import { apiUrl, authClient } from '@/config';
export class AdminApiError extends Error {
constructor(message: string, readonly status: number, readonly details?: unknown) {
super(message);
this.name = 'AdminApiError';
}
}
type RequestOptions = Omit<RequestInit, 'body'> & { body?: unknown };
async function accessToken(): Promise<string> {
const { data, error } = await authClient.auth.getSession();
const token = data.session?.access_token;
if (error || !token) throw new AdminApiError('An authenticated admin session is required', 401, error);
return token;
}
export async function adminRequest<T>(path: string, options: RequestOptions = {}): Promise<T> {
const token = await accessToken();
const headers = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Authorization', `Bearer ${token}`);
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
if (body !== undefined) headers.set('Content-Type', 'application/json');
const response = await fetch(`${apiUrl}${path.startsWith('/') ? path : `/${path}`}`, { ...options, headers, body });
const text = await response.text();
let parsed: unknown;
try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = text; }
if (!response.ok) {
const nested = parsed && typeof parsed === 'object' && 'error' in parsed ? (parsed as { error: unknown }).error : undefined;
const message = nested && typeof nested === 'object' && 'message' in nested
? String((nested as { message: unknown }).message)
: `Admin API request failed with status ${response.status}`;
throw new AdminApiError(message, response.status, parsed);
}
return parsed as T;
}
export async function adminBinaryRequest(path: string, options: RequestOptions = {}): Promise<Blob> {
const token = await accessToken();
const headers = new Headers(options.headers);
headers.set('Authorization', `Bearer ${token}`);
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
if (body !== undefined) headers.set('Content-Type', 'application/json');
const response = await fetch(`${apiUrl}${path.startsWith('/') ? path : `/${path}`}`, { ...options, headers, body });
if (!response.ok) throw new AdminApiError(`Admin media request failed with status ${response.status}`, response.status);
return response.blob();
}
export function getAdminResponseMedia(responseId: string): Promise<Blob> {
return adminBinaryRequest(`/v1/admin/responses/${encodeURIComponent(responseId)}/media`);
}
export type AdminFilter = { column: string; op: 'eq' | 'neq' | 'in' | 'is' | 'gte' | 'lte' | 'ilike'; value: unknown };
export type AdminQuery = {
filters?: AdminFilter[];
order?: { column: string; ascending?: boolean };
limit?: number;
offset?: number;
};
export async function queryAdminRows<T>(resource: string, query: AdminQuery = {}): Promise<{ rows: T[]; count: number }> {
return adminRequest(`/v1/admin/query/${encodeURIComponent(resource)}`, { method: 'POST', body: query });
}
function uniqueValues(rows: Record<string, unknown>[], key: string): unknown[] {
return [...new Set(rows.map((row) => row[key]).filter((value) => value !== null && value !== undefined))];
}
async function relatedRows(resource: string, column: string, values: unknown[]): Promise<Record<string, unknown>[]> {
if (values.length === 0) return [];
return (await queryAdminRows<Record<string, unknown>>(resource, {
filters: [{ column, op: 'in', value: values }], limit: 500,
})).rows;
}
async function hydrateAdminRows(resource: string, selection: string, input: any[]): Promise<any[]> {
const rows = input as Record<string, unknown>[];
if (rows.length === 0) return input;
if (resource === 'question_packs' && selection.includes('categor')) {
const categories = await relatedRows('categories', 'id', uniqueValues(rows, 'category_id'));
const byId = new Map(categories.map((row) => [row.id, row]));
rows.forEach((row) => { row.category = byId.get(row.category_id) ?? null; });
}
if (resource === 'pack_topics' && selection.includes('topics')) {
const topics = await relatedRows('topics', 'id', uniqueValues(rows, 'topic_id'));
const byId = new Map(topics.map((row) => [row.id, row]));
rows.forEach((row) => { row.topics = byId.get(row.topic_id) ?? null; });
}
if (resource === 'feedback' && selection.includes('profile')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'user_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.profile = byId.get(row.user_id) ?? null; });
}
if (resource === 'message_reports') {
if (selection.includes('message:')) {
const messages = await relatedRows('messages', 'id', uniqueValues(rows, 'message_id'));
const byId = new Map(messages.map((row) => [row.id, row]));
rows.forEach((row) => { row.message = byId.get(row.message_id) ?? null; });
}
if (selection.includes('reporter_profile')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'reporter_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.reporter_profile = byId.get(row.reporter_id) ?? null; });
}
}
if (resource === 'responses') {
if (selection.includes('profile:')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'user_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.profile = byId.get(row.user_id) ?? null; });
}
if (selection.includes('question:')) {
const questions = await relatedRows('questions', 'id', uniqueValues(rows, 'question_id'));
if (selection.includes('pack:question_packs')) {
const packs = await relatedRows('question_packs', 'id', uniqueValues(questions, 'pack_id'));
const packsById = new Map(packs.map((row) => [row.id, row]));
questions.forEach((row) => { row.pack = packsById.get(row.pack_id) ?? null; });
}
const byId = new Map(questions.map((row) => [row.id, row]));
rows.forEach((row) => { row.question = byId.get(row.question_id) ?? null; });
}
}
if (resource === 'matches' && selection.includes('question:')) {
const questions = await relatedRows('questions', 'id', uniqueValues(rows, 'question_id'));
const byId = new Map(questions.map((row) => [row.id, row]));
rows.forEach((row) => { row.question = byId.get(row.question_id) ?? null; });
}
if (resource === 'messages' && selection.includes('match:')) {
const matches = await relatedRows('matches', 'id', uniqueValues(rows, 'match_id'));
const questions = await relatedRows('questions', 'id', uniqueValues(matches, 'question_id'));
const questionsById = new Map(questions.map((row) => [row.id, row]));
matches.forEach((row) => { row.question = questionsById.get(row.question_id) ?? null; });
const byId = new Map(matches.map((row) => [row.id, row]));
rows.forEach((row) => { row.match = byId.get(row.match_id) ?? null; });
}
return input;
}
type QueryResult<T> = { data: T | null; error: Error | null; count: number | null };
type QueryMode = 'many' | 'single' | 'maybeSingle';
class AdminQueryBuilder<T = any> implements PromiseLike<QueryResult<T[]>> {
private readonly filters: AdminFilter[] = [];
private ordering?: { column: string; ascending?: boolean };
private maxRows?: number;
private offset?: number;
private head = false;
private selection = '*';
private orFilters?: AdminFilter[];
private mode: QueryMode = 'many';
private mutation?: { type: 'insert'; records: Record<string, unknown>[] } | { type: 'update'; values: Record<string, unknown> } | { type: 'delete' };
constructor(private readonly resource: string) {}
select(columns = '*', options?: { count?: 'exact'; head?: boolean }): this {
this.selection = columns;
this.head = options?.head === true;
return this;
}
eq(column: string, value: unknown): this { this.filters.push({ column, op: 'eq', value }); return this; }
neq(column: string, value: unknown): this { this.filters.push({ column, op: 'neq', value }); return this; }
in(column: string, value: unknown[]): this { this.filters.push({ column, op: 'in', value }); return this; }
is(column: string, value: unknown): this { this.filters.push({ column, op: 'is', value }); return this; }
gte(column: string, value: unknown): this { this.filters.push({ column, op: 'gte', value }); return this; }
lte(column: string, value: unknown): this { this.filters.push({ column, op: 'lte', value }); return this; }
ilike(column: string, value: string): this { this.filters.push({ column, op: 'ilike', value }); return this; }
or(expression: string): this {
this.orFilters = expression.split(',').map((part) => {
const match = /^([a-z_][a-z0-9_]*)\.ilike\.(.+)$/.exec(part);
if (!match) throw new Error('Unsupported admin OR filter');
return { column: match[1], op: 'ilike' as const, value: match[2] };
});
return this;
}
not(column: string, operator: string, value: unknown): this {
if (operator !== 'is' || value !== null) throw new Error(`Unsupported admin filter: not ${operator}`);
this.filters.push({ column, op: 'neq', value: null });
return this;
}
order(column: string, options?: { ascending?: boolean }): this { this.ordering = { column, ascending: options?.ascending }; return this; }
limit(value: number): this { this.maxRows = value; return this; }
range(from: number, to: number): this { this.offset = from; this.maxRows = to - from + 1; return this; }
single<TResult = T>(): PromiseLike<QueryResult<TResult>> { this.mode = 'single'; return this as unknown as PromiseLike<QueryResult<TResult>>; }
maybeSingle<TResult = T>(): PromiseLike<QueryResult<TResult>> { this.mode = 'maybeSingle'; return this as unknown as PromiseLike<QueryResult<TResult>>; }
insert(records: Record<string, unknown> | Record<string, unknown>[]): this {
this.mutation = { type: 'insert', records: Array.isArray(records) ? records : [records] };
return this;
}
update(values: Record<string, unknown>): this { this.mutation = { type: 'update', values }; return this; }
delete(): this { this.mutation = { type: 'delete' }; return this; }
then<TResult1 = QueryResult<T[]>, TResult2 = never>(
onfulfilled?: ((value: QueryResult<T[]>) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
): PromiseLike<TResult1 | TResult2> {
return this.execute().then(onfulfilled, onrejected);
}
private async execute(): Promise<QueryResult<T[]>> {
try {
if (this.mutation?.type === 'insert') {
const result = await adminRequest<{ rows: T[] }>(`/v1/admin/data/${this.resource}`, { method: 'POST', body: { records: this.mutation.records } });
return this.shape(result.rows, result.rows.length);
}
if (this.mutation) {
const matching = await queryAdminRows<Record<string, unknown>>(this.resource, { filters: this.filters, limit: 500 });
const ids = [...new Set(matching.rows.map((row) => String(row.id ?? row.pack_id ?? '')).filter(Boolean))];
if (this.mutation.type === 'update') {
const rows = await Promise.all(ids.map((id) => adminRequest<{ row: T }>(`/v1/admin/data/${this.resource}/${encodeURIComponent(id)}`, { method: 'PATCH', body: { values: this.mutation!.type === 'update' ? this.mutation!.values : {} } }).then((value) => value.row)));
return this.shape(rows, rows.length);
}
await Promise.all(ids.map((id) => adminRequest(`/v1/admin/data/${this.resource}/${encodeURIComponent(id)}`, { method: 'DELETE' })));
return this.shape([], ids.length);
}
const result = this.orFilters?.length
? await this.executeOrQuery()
: await queryAdminRows<T>(this.resource, { filters: this.filters, order: this.ordering, limit: this.maxRows, offset: this.offset });
if (!this.head) result.rows = await hydrateAdminRows(this.resource, this.selection, result.rows);
return this.shape(result.rows, result.count);
} catch (cause) {
return { data: null, error: cause instanceof Error ? cause : new Error(String(cause)), count: null };
}
}
private async executeOrQuery(): Promise<{ rows: T[]; count: number }> {
const results = await Promise.all(this.orFilters!.map((filter) => queryAdminRows<T>(this.resource, {
filters: [...this.filters, filter], order: this.ordering, limit: 500,
})));
const unique = new Map<string, T>();
for (const result of results) result.rows.forEach((row, index) => {
const record = row as Record<string, unknown>;
unique.set(String(record.id ?? `${record.pack_id ?? ''}:${record.topic_id ?? ''}:${index}`), row);
});
let rows = [...unique.values()];
if (this.offset) rows = rows.slice(this.offset);
if (this.maxRows) rows = rows.slice(0, this.maxRows);
return { rows, count: unique.size };
}
private shape(rows: T[], count: number): QueryResult<T[]> {
if (this.head) return { data: null, error: null, count };
if (this.mode === 'single') {
if (rows.length !== 1) return { data: null, error: new Error(`Expected one ${this.resource} record, received ${rows.length}`), count };
return { data: rows[0] as unknown as T[], error: null, count };
}
if (this.mode === 'maybeSingle') {
if (rows.length > 1) return { data: null, error: new Error(`Expected at most one ${this.resource} record, received ${rows.length}`), count };
return { data: (rows[0] ?? null) as unknown as T[], error: null, count };
}
return { data: rows, error: null, count };
}
}
export const adminData = {
from<T = any>(resource: string): AdminQueryBuilder<T> { return new AdminQueryBuilder<T>(resource); },
};
+5 -5
View File
@@ -23,8 +23,8 @@ export async function analyzeQuestionDeletions(
}));
const toneInstruction = isExplicit
? 'CONTENT: EXPLICIT pack. Adult content is allowed but must be consensual, safe, and clear. Avoid coercion, minors, illegal acts, or unsafe suggestions.'
: 'CONTENT: NON-EXPLICIT pack. Do NOT include explicit sexual acts, crude language, or NSFW content. If the core action is sexual, it should be removed, not rewritten.';
? 'LEGACY EXPLICIT FLAG: It does not override the universal catalogue safety ceiling. Delete developer-authored sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity.'
: 'Delete developer-authored sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity rather than rewriting them into disguised euphemisms.';
const prompt = `<task>
Identify questions that should be DELETED instead of edited.
@@ -38,7 +38,7 @@ ${toneInstruction}
<deletion_categories>
- duplicate: same core action AND same initiator as another question (near-duplicate). Note: swapped perspectives (e.g., "give" vs "receive") are NOT duplicates.
- redundant: minor variation with no added value
- off-tone: violates explicit vs non-explicit rules
- off-tone: violates the universal catalogue safety ceiling or the pack's intended tone
- unsafe: coercion, minors, illegal acts, or consent violations
- too-vague: not actionable or not a clear proposal
- broken: grammar/structure too broken to repair without inventing content
@@ -73,8 +73,8 @@ Only return questions that should be deleted.
</output_format>`;
const systemMessage = isExplicit
? 'You are a strict content quality reviewer for an adult couples app. Remove only what should be deleted. Always respond with valid JSON only.'
: 'You are a strict content quality reviewer for a couples app. Remove only what should be deleted. Always respond with valid JSON only.';
? 'You are a strict content safety reviewer for a couples connection app. A legacy explicit flag never permits sexual content. Mark content outside the universal safety ceiling for deletion. Always respond with valid JSON only.'
: 'You are a strict content safety reviewer for a couples connection app. Mark sexual or explicit content for deletion. Always respond with valid JSON only.';
const response = await openai.chat.completions.create({
model: getModel('fix'),
Loaded 100 of 460 files, more files were not shown because too many files have changed in this diff. Show more