From 9356fe7bc3aeb7a6307cd5f5c26204eb26dbcdf2 Mon Sep 17 00:00:00 2001 From: "djair.jr" Date: Sun, 31 May 2026 10:29:54 -0300 Subject: [PATCH 1/6] =?UTF-8?q?[skills]=20Hermes=20Agent=20Onboarding=20?= =?UTF-8?q?=E2=80=94=2010=20skills=20+=20recipe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generative 6-stage meta-skill for ANY user. Transforms a blank AI agent into a customized ecosystem with persistent relational identity. Skills (10): - agent-onboarding, context-bridge, supabase-startup-protocol - identity-self-audit, identity-cqrs, checkpoint-workflow - mbti-guru-hermes, stage-3-financial, stage-4-system-ontologist - stage-5-agent-calibration Recipe: hermes-agent-onboarding with 4 DB migrations + setup docs. Schema: 10 identity tables (user_profiles, identity_faults, etc.) Based on NateBJones/OB1 Edge Function + MCP pattern. Built by djairjr from djairjr/hermes-agent-onboarding. --- recipes/hermes-agent-onboarding/README.md | 274 +++++++++++++++ .../docs/02-SUPABASE.md | 110 ++++++ .../docs/04-CUSTOMIZING.md | 98 ++++++ recipes/hermes-agent-onboarding/metadata.json | 32 ++ .../20260530100000_user_infrastructure.sql | 219 ++++++++++++ .../20260531080000_session_checkpoints.sql | 143 ++++++++ .../20260531090000_service_role_grants.sql | 158 +++++++++ .../20260531100000_checkpoint_working_dir.sql | 10 + schemas/hermes-agent-onboarding/README.md | 67 ++++ .../identity-tables.sql | 21 ++ schemas/hermes-agent-onboarding/metadata.json | 20 ++ skills/agent-onboarding/SKILL.md | 319 ++++++++++++++++++ skills/agent-onboarding/metadata.json | 32 ++ skills/checkpoint-workflow/SKILL.md | 226 +++++++++++++ skills/checkpoint-workflow/metadata.json | 21 ++ skills/context-bridge/SKILL.md | 202 +++++++++++ skills/context-bridge/metadata.json | 21 ++ skills/identity-cqrs/SKILL.md | 148 ++++++++ skills/identity-cqrs/metadata.json | 21 ++ skills/identity-self-audit/SKILL.md | 174 ++++++++++ skills/identity-self-audit/metadata.json | 21 ++ skills/mbti-guru-hermes/SKILL.md | 186 ++++++++++ skills/mbti-guru-hermes/metadata.json | 20 ++ skills/stage-3-financial/SKILL.md | 191 +++++++++++ skills/stage-3-financial/metadata.json | 21 ++ skills/stage-4-system-ontologist/SKILL.md | 178 ++++++++++ .../stage-4-system-ontologist/metadata.json | 20 ++ skills/stage-5-agent-calibration/SKILL.md | 139 ++++++++ .../stage-5-agent-calibration/metadata.json | 20 ++ skills/supabase-startup-protocol/SKILL.md | 155 +++++++++ .../supabase-startup-protocol/metadata.json | 20 ++ 31 files changed, 3287 insertions(+) create mode 100755 recipes/hermes-agent-onboarding/README.md create mode 100755 recipes/hermes-agent-onboarding/docs/02-SUPABASE.md create mode 100755 recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md create mode 100755 recipes/hermes-agent-onboarding/metadata.json create mode 100755 recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql create mode 100755 recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql create mode 100755 recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql create mode 100755 recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql create mode 100755 schemas/hermes-agent-onboarding/README.md create mode 100755 schemas/hermes-agent-onboarding/identity-tables.sql create mode 100755 schemas/hermes-agent-onboarding/metadata.json create mode 100755 skills/agent-onboarding/SKILL.md create mode 100755 skills/agent-onboarding/metadata.json create mode 100755 skills/checkpoint-workflow/SKILL.md create mode 100755 skills/checkpoint-workflow/metadata.json create mode 100755 skills/context-bridge/SKILL.md create mode 100755 skills/context-bridge/metadata.json create mode 100755 skills/identity-cqrs/SKILL.md create mode 100755 skills/identity-cqrs/metadata.json create mode 100755 skills/identity-self-audit/SKILL.md create mode 100755 skills/identity-self-audit/metadata.json create mode 100755 skills/mbti-guru-hermes/SKILL.md create mode 100755 skills/mbti-guru-hermes/metadata.json create mode 100755 skills/stage-3-financial/SKILL.md create mode 100755 skills/stage-3-financial/metadata.json create mode 100755 skills/stage-4-system-ontologist/SKILL.md create mode 100755 skills/stage-4-system-ontologist/metadata.json create mode 100755 skills/stage-5-agent-calibration/SKILL.md create mode 100755 skills/stage-5-agent-calibration/metadata.json create mode 100755 skills/supabase-startup-protocol/SKILL.md create mode 100755 skills/supabase-startup-protocol/metadata.json diff --git a/recipes/hermes-agent-onboarding/README.md b/recipes/hermes-agent-onboarding/README.md new file mode 100755 index 000000000..a1e2c25ac --- /dev/null +++ b/recipes/hermes-agent-onboarding/README.md @@ -0,0 +1,274 @@ +# Hermes Agent Onboarding + +![Stage 0](https://img.shields.io/badge/Stage_0-Agent_Identity-1E88E5?style=for-the-badge) +![Stage 1](https://img.shields.io/badge/Stage_1-User_Profile-43A047?style=for-the-badge) +![Stage 2](https://img.shields.io/badge/Stage_2-Work_Model-FB8C00?style=for-the-badge) +![Stage 3](https://img.shields.io/badge/Stage_3-Financial-8E24AA?style=for-the-badge) +![Stage 4](https://img.shields.io/badge/Stage_4-Domain_Ontology-C62828?style=for-the-badge) +![Stage 5](https://img.shields.io/badge/Stage_5-Calibration-00838F?style=for-the-badge) + +A generative 6-stage meta-skill that transforms a blank AI agent into a customized ecosystem — not for "a firmware engineer," but for **your** work. Writers, teachers, chefs, designers, and engineers all get different tools, different data structures, and different communication styles. + +## What It Does + +This recipe installs a complete onboarding system into your agent. After running it, your agent: + +- **Knows who you are** — name, role, preferences, MBTI type, communication style +- **Remembers its own mistakes** — every identity fault is logged with a countermeasure +- **Understands your work** — operating rhythms, recurring decisions, friction points +- **Knows your finances** — bank CSV import, goals × personality profile +- **Builds your domain ontology** — interview → discover terms → generate tables + MCPs +- **Behaves calibrated** — per-user SOUL.md, verified behavior + +All data is stored in Supabase and loaded at every session start. The agent builds a persistent relational identity that survives model swaps, provider changes, and software updates. + +## Prerequisites + +- A working [Supabase](https://supabase.com/) project (free tier works) +- [Supabase CLI](https://supabase.com/docs/guides/cli) linked to your project (`supabase link --project-ref `) +- An AI agent tool that supports skills/SKILL.md files (Hermes Agent, Claude Code, Codex CLI, Cursor, etc.) +- Node.js 18+ (for Edge Functions, if you proceed to Stage 4) +- Python 3 (for MBTI scoring and CSV importer tools) + +> [!IMPORTANT] +> If you don't have an agent yet, start with [Hermes Agent](https://hermes-agent.nousresearch.com/docs) — it has native skill loading, MCP support, and session persistence. + +## How to Use + +This recipe has two layers: + +**Layer 1 — Skills (10 folders):** Copy the `skills/` folders to your agent's skill directory. Each is a standalone behavior you can load individually. + +**Layer 2 — Recipe (this folder):** Database migrations + step-by-step setup instructions below. Run through the stages one at a time. + +--- + +![Step 1](https://img.shields.io/badge/Step_1-Apply_Database_Migrations-1E88E5?style=for-the-badge) + +The onboarding needs 10 database tables. Copy the migration SQL files to your Supabase project's `migrations/` folder and push. + +
+📋 SQL: Identity infrastructure tables (click to expand) + +```sql +-- Run these in order from migrations/ folder +-- 001: User infrastructure (user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs) +-- 002: Session checkpoints (session_checkpoints) +-- 003: Service role grants (required by Supabase since May 2026) +-- 004: Checkpoint working directory field +``` + +
+ +![1.1](https://img.shields.io/badge/1.1-Deploy_Migrations-555?style=for-the-badge&labelColor=1E88E5) + +```bash +# Copy migrations to your project +cp -r migrations/ ~/my-supabase-project/supabase/migrations/ + +# Deploy +cd ~/my-supabase-project +supabase db push --linked +``` + +✅ **Done when:** All 10 tables appear in your Supabase dashboard's Table Editor. + +--- + +![Step 2](https://img.shields.io/badge/Step_2-Install_Skills-43A047?style=for-the-badge) + +Copy the 10 skill folders to your agent's skills directory. The exact path depends on your tool: + +- **Hermes Agent:** `~/.hermes/skills/` or `~/.hermes/profiles//skills/` +- **Claude Code:** `~/.claude/skills/` +- **Codex CLI:** `~/.codex/skills/` + +```bash +# Example for Hermes Agent +SKILLS_DIR="$HOME/.hermes/skills" +cp -r skills/* "$SKILLS_DIR/" +``` + +Each skill folder has a `SKILL.md` and `metadata.json`. The loader order matters: + +| Load order | Skill | Stage | +|------------|-------|-------| +| 1 | `supabase-startup-protocol` | 0 | +| 2 | `identity-self-audit` | 0 | +| 3 | `identity-cqrs` | 0 | +| 4 | `context-bridge` | 0 | +| 5 | `checkpoint-workflow` | 0 | +| 6 | `agent-onboarding` | 0–5 | +| 7 | `mbti-guru-hermes` | 1C | +| 8 | `stage-3-financial` | 3 | +| 9 | `stage-4-system-ontologist` | 4 | +| 10 | `stage-5-agent-calibration` | 5 | + +✅ **Done when:** `your-agent --skills agent-onboarding` loads without errors. + +--- + +![Step 3](https://img.shields.io/badge/Step_3-Run_the_Onboarding-FB8C00?style=for-the-badge) + +Start the onboarding by loading the orchestrator skill: + +```bash +your-agent --skills agent-onboarding +``` + +The agent will greet you and begin Stage 0. Follow the conversation — the agent asks questions one at a time, listens to your answers, and builds your profile progressively. + +### Stage Timeline + +| Stage | What happens | Approx. time | +|-------|------------|-------------| +| **0 — Agent Identity** | Agent explains identity layer, starts tracking faults | 5 min | +| **1 — User Profile** | Name, role, preferences, MBTI test (choose version: 10-35 min), biography | 20-50 min | +| **2 — Work Model** | Operating rhythms, recurring decisions, dependencies, friction | 15-30 min | +| **3 — Financial** | Optional CSV analysis, MBTI × finance profile, goals | 15-30 min | +| **4 — Domain Ontology** | Deep interview → discover entities → generate tables + MCPs | 30-90 min | +| **5 — Calibration** | SOUL.md generation, wrapper config, verification | 10-15 min | + +> [!TIP] +> You can pause after any stage. Next time you load `agent-onboarding`, it detects your progress and resumes where you left off. + +--- + +![Step 4](https://img.shields.io/badge/Step_4-GRANT_Service_Role-8E24AA?style=for-the-badge) + +> [!CAUTION] +> Since May 2026, Supabase no longer auto-grants CRUD permissions to `service_role` on new tables. Every table created by Stage 4 needs explicit GRANT. + +
+📋 SQL: Grant service_role to new tables + +```sql +GRANT SELECT, INSERT, UPDATE, DELETE ON public. TO service_role; +``` + +
+ +To check which tables are missing GRANTs: + +
+📋 SQL: Find tables without service_role GRANT + +```sql +SELECT table_name FROM information_schema.tables WHERE table_schema='public' +EXCEPT +SELECT DISTINCT table_name FROM information_schema.role_table_grants +WHERE table_schema='public' AND grantee='service_role'; +``` + +
+ +✅ **Done when:** All MCP tools return data instead of "permission denied." + +--- + +## Expected Outcome + +After completing all 6 stages: + +1. **Session startup** automatically loads identity data from Supabase +2. **Every mistake** is logged in `identity_faults` with a countermeasure +3. **Agent behavior** adjusts based on your preferences, MBTI, and past faults +4. **Domain structures** (tables, MCPs) answer questions that previously required digging through folders +5. **Session checkpoints** preserve context across sessions +6. **`user_profiles.onboarding_completed`** is set to `true` + +### Verification Questions + +Ask your agent: + +- "What's my MBTI type?" +- "What's the last identity fault you registered?" +- "Show me my financial goals" +- "What domain tables did we build?" +- "What's my next pending checkpoint?" + +If the agent answers from data (not from conversation memory), onboarding is complete. + +--- + +## Troubleshooting + +### "Permission denied for table" in MCP tools + +**Cause:** Supabase no longer auto-grants `service_role`. The migration `20260531090000_service_role_grants.sql` handles the base tables, but Stage 4 tables need their own GRANT. + +**Fix:** Run the diagnostic SQL above and GRANT for each missing table. + +### MBTI test is too long + +The test offers 4 versions. If the user chose Professional (200q) and wants to stop: + +1. Score what you have so far +2. Register with `source='partial'` +3. Offer to complete later + +### Agent doesn't load skills + +**Check:** The `--skills` flag needs a comma-separated list of skill names (folder names), not paths. + +```bash +# Correct +your-agent --skills agent-onboarding + +# Wrong +your-agent --skills skills/agent-onboarding/SKILL.md +``` + +### Stage 4 generates tables but MCP tools return 401 + +**Cause:** Edge Function deployed without `--no-verify-jwt`. + +**Fix:** +```bash +supabase functions deploy --no-verify-jwt +``` + +### Checkpoint fields are empty + +**Cause:** The 5 identity fields (territory, operating_mode, vector_intent, discovery, consolidated_insights) are required. Without them, the checkpoint is a log entry, not identity data. + +**Fix:** Always fill all 5 fields when saving a checkpoint. + +--- + +## Cross-Extension Integration + +This recipe integrates with any OB1 extension that uses Supabase, because all identity data lives in shared `public` schema tables: + +- **Extension 1 (Professional CRM):** Agent knows user's professional network +- **Extension 2 (Household):** Agent knows family context +- **Extension 4 (Calendar):** Agent knows user's schedule and rhythms +- **Extension 5 (Meal Planning):** Agent knows dietary preferences from user_profiles + +The identity tables (user_profiles, user_preferences, user_mbti) are the hub that other extensions connect to via `user_id` foreign keys. + +--- + +## MCP Tool Audit + +If you proceed to Stage 4 and create domain MCP tools, link to the [MCP Tool Audit & Optimization Guide](https://github.com/NateBJones-Projects/OB1/blob/main/docs/05-tool-audit.md) to manage your tool surface area. + +--- + +## Supported Clients + +| Client | Skill loading | MCP support | Notes | +|--------|---------------|-------------|-------| +| Hermes Agent | Native (`--skills`) | Native | Best experience | +| Claude Code | `~/.claude/skills/` | Via config | Test first | +| Codex CLI | `~/.codex/skills/` | Partial | Needs config | +| Cursor | Manual config | Via MCP | Partial support | + +--- + +## License + +MIT — free to use, adapt, distribute. See the main repository [LICENSE](../LICENSE) for details. + +Built by **Djair Guilherme** ([github.com/djairjr](https://github.com/djairjr)). +Based on [NateBJones/OB1](https://github.com/NateBJones-Projects/OB1) — the Edge Function + MCP pattern that made this possible. diff --git a/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md b/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md new file mode 100755 index 000000000..f2d373041 --- /dev/null +++ b/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md @@ -0,0 +1,110 @@ +# Supabase Setup + +This guide covers creating your Supabase project and applying the required database migrations for the onboarding meta-skill. + +## Creating a Project + +1. Go to [supabase.com](https://supabase.com/) → **Start your project** +2. Give it a name (e.g., "hermes-onboarding") +3. Set a secure database password (save it!) +4. Choose a region close to you +5. Click **Create new project** +6. Wait ~2 minutes for the database to provision + +## Getting Your Credentials + +Once the project is ready: + +1. Go to **Project Settings** (gear icon) → **API** +2. Under **Project URL**, copy the URL (format: `https://xxxxx.supabase.co`) +3. Under **Project API keys**, copy the **service_role key** (NOT anon) + - The service_role key starts with `eyJhbGciOi...` and has full access + - **Never share this key** or commit it to version control + +## Installing Supabase CLI + +```bash +# Using npm (recommended) +npm install -g supabase + +# Using Homebrew (macOS) +brew install supabase/tap/supabase + +# Using apt (Linux) +# Download from: https://github.com/supabase/cli/releases +``` + +Verify: +```bash +supabase --version +# Should print: 2.x.x +``` + +## Linking to Your Project + +```bash +# Login to Supabase +supabase login + +# You'll be asked to create a Personal Access Token (PAT) +# Go to: https://supabase.com/dashboard/account/tokens +# Create a token and paste it when prompted + +# Link your local environment to your project +supabase link --project-ref YOUR_PROJECT_REF +``` + +Your project ref is the part of your URL before `.supabase.co`: +``` +URL: https://abcdefghijklm.supabase.co +REF: abcdefghijklm +``` + +## Applying Migrations + +From the `hermes-agent-onboarding` repo directory: + +```bash +cd hermes-agent-onboarding +supabase db push --linked +``` + +This runs all migrations in `migrations/`, creating the 6 base tables: + +- `user_profiles` — identity, family, routines +- `user_preferences` — tone, autonomy, finance tracking +- `user_mbti` — 4 dimensions, type, traits +- `user_style` — communication style +- `user_relations` — key people +- `user_beliefs` — values and principles + +## Verifying Tables + +```bash +# List tables in public schema +supabase db query --linked "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_name LIKE 'user_%'" + +# Check RLS is active +supabase db query --linked "SELECT tablename, rowsecurity FROM pg_catalog.pg_tables WHERE tablename LIKE 'user_%'" +``` + +Expected output: 6 tables, all with `rowsecurity = true`. + +## Security Model + +All onboarding tables use Row-Level Security (RLS) with the following model: + +- **service_role key**: Full access (SELECT, INSERT, UPDATE, DELETE) +- **anon key**: No access (blocked by RLS policy) +- **authenticated users**: No access (blocked by RLS policy) + +The policy checks the JWT claim: +```sql +(auth.jwt() ->> 'role') = 'service_role' +``` + +This ensures only the Hermes Agent (using service_role key) can read or write user data. + +## Next Steps + +Proceed to [Running the Onboarding](03-RUNNING.md). diff --git a/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md b/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md new file mode 100755 index 000000000..70e2d77c8 --- /dev/null +++ b/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md @@ -0,0 +1,98 @@ +# Customizing for Your Domain + +The meta-skill is designed to work for ANY knowledge worker: writers, engineers, teachers, artists, researchers, therapists, designers. + +After onboarding, you may want to customize further. + +## Adding Domain-Specific Skills + +Each stage generates artifacts that can be packaged as reusable skills: + +```bash +# Example: save a writer-specific skill after Stage 4 +hermes skill create writer-workflow +``` + +The skill can include: +- Custom prompts for your common tasks +- Pre-built queries against your domain tables +- Templates for recurring work patterns + +## Editing Your Preferences + +Your preferences are stored in `user_preferences`. To update: + +```bash +# Via Supabase REST API +source ~/.hermes/secrets.env +curl -s -X PATCH "$SUPABASE_URL/rest/v1/user_preferences" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Content-Type: application/json" \ + -d '{"preferred_tone": "casual", "autonomy_level": 5}' +``` + +Or just tell your agent: "Be more casual" — it updates the preference. + +## Adding New Domain Tables + +After onboarding, you can continue adding tables: + +```bash +# The agent can generate new tables on demand +hermes --skills agent-onboarding +# → "Add a 'publishing_contracts' table with name, publisher, start_date, royalty_percent" +``` + +## Sharing Your Setup + +The `user_profiles`, `user_preferences`, and `user_mbti` tables can be exported as a JSON profile: + +```bash +source ~/.hermes/secrets.env +curl -s "$SUPABASE_URL/rest/v1/user_profiles" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" > my-profile.json +``` + +This allows the agent to be configured on a new machine with your existing preferences. + +## Example Domains + +### Writer (fiction, non-fiction, poetry) + +Domain tables generated by Stage 4: +- **characters** — name, age, personality, arc, relationships +- **works** — title, type, synopsis, word_count, status +- **submissions** — work_id, publisher, status, date_sent, response +- **publishers** — name, contact, genres, response_time +- **chapters** — work_id, number, title, word_count, status + +### Teacher (K-12, university, workshops) + +Domain tables generated by Stage 4: +- **classes** — name, level, schedule, student_count +- **students** — name, email, performance, observations +- **lessons** — class_id, date, topic, materials +- **assessments** — class_id, type, weight, date +- **curriculum** — subject, grade, topics, standards + +### Engineer (firmware, hardware, software) + +Domain tables generated by Stage 4: +- **projects** — name, platform, status, repository +- **components** — sku, name, specs, datasheet_url +- **boms** — project_id, component_id, quantity, supplier +- **clients** — name, company, project, contact +- **versions** — project_id, version, changelog, release_date + +## Multi-User Setup + +The onboarding meta-skill currently supports one user per Supabase project. +For multi-user (e.g., family, small team): + +1. Each `user_*` table has `profile_id` foreign key +2. Multiple profiles can coexist +3. The agent checks `onboarding_completed = true` before skipping onboarding + +To switch users: create a new `user_profiles` row and start staging from there. diff --git a/recipes/hermes-agent-onboarding/metadata.json b/recipes/hermes-agent-onboarding/metadata.json new file mode 100755 index 000000000..6a8986b3e --- /dev/null +++ b/recipes/hermes-agent-onboarding/metadata.json @@ -0,0 +1,32 @@ +{ + "name": "Hermes Agent Onboarding", + "description": "Generative 6-stage meta-skill that transforms a blank AI agent into a customized ecosystem for ANY user. Stages: Agent Identity Layer → User Profile (MBTI) → Work Operating Model → Financial Profile → Domain Ontology → Agent Calibration. Includes 10 reusable skills for Supabase-backed persistent identity.", + "category": "recipes", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "3.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Supabase CLI", "Node.js 18+"] + }, + "requires_skills": [ + "agent-onboarding", + "identity-self-audit", + "identity-cqrs", + "context-bridge", + "supabase-startup-protocol", + "checkpoint-workflow", + "mbti-guru-hermes", + "stage-3-financial", + "stage-4-system-ontologist", + "stage-5-agent-calibration" + ], + "tags": ["onboarding", "meta-skill", "identity", "mbti", "financial", "ontology", "calibration", "universal"], + "difficulty": "advanced", + "estimated_time": "2-3 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql b/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql new file mode 100755 index 000000000..414be8da0 --- /dev/null +++ b/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql @@ -0,0 +1,219 @@ +-- ================================================================ +-- USER INFRASTRUCTURE — Base Tables for the Hermes Onboarding +-- ================================================================ +-- Stage 0 (Foundation) of the generative meta-skill process. +-- These 6 tables are universal — they serve ANY user regardless of +-- work domain. They are the skeleton every profile needs. +-- +-- Populate order: +-- 1. user_profiles (who you are) +-- 2. user_preferences (how the agent should behave) +-- 3. user_mbti (how you think) +-- 4. user_style (how you communicate) +-- 5. user_relations (who matters) +-- 6. user_beliefs (what you stand for) +-- +-- ⚠️ NOTE: Always prefix with `public.`. Without it, `supabase db push` +-- creates tables in the `extensions` schema, requiring manual ALTER TABLE. +-- ================================================================ + +-- ================================================================ +-- 1. USER PROFILES — Identity + context +-- ================================================================ +CREATE TABLE public.user_profiles ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT NOT NULL, + preferred_name TEXT, + domain_summary TEXT, -- one-liner: "Firmware Engineer", "Writer", "Teacher" + bio TEXT, -- free-form self-description + mbti_type TEXT, -- e.g. INTJ, populated from user_mbti + primary_language TEXT DEFAULT 'en', + timezone TEXT, + + -- Family & routines (Djair's insight: critical for understanding user context) + family JSONB, -- {spouse: "name", children: [{name, age}], pets: [{type, name}]} + routines TEXT, -- daily/weekly routine description + + -- Onboarding state machine + onboarding_completed BOOLEAN DEFAULT false, + onboarding_stage TEXT DEFAULT 'none', -- none | setup | profile | operational | financial | ontology | calibration | complete + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 2. USER PREFERENCES — How the agent should behave +-- ================================================================ +CREATE TABLE public.user_preferences ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- Communication + preferred_tone TEXT DEFAULT 'direct', -- direct, formal, casual, technical, creative + response_depth TEXT DEFAULT 'concise', -- concise, detailed, exhaustive + prefers_bullets BOOLEAN DEFAULT false, + clarification_style TEXT DEFAULT 'ask', -- ask (before acting), assume (correct after) + + -- Autonomy + autonomy_level INT DEFAULT 3, -- 1 (ask everything) to 5 (execute freely) + approve_deploys BOOLEAN DEFAULT true, + approve_destructive BOOLEAN DEFAULT true, + sudo_allowed BOOLEAN DEFAULT false, + + -- File organization + file_organization TEXT, -- e.g. "folders by project/year" + primary_work_dir TEXT, + backup_dir TEXT, + + -- Schedule + work_hours JSONB, -- {monday: {start: "08:00", end: "18:00", deep_work: ["09:00-12:00"]}} + best_contact_time TEXT, + + -- Financial tracking + finance_tracked BOOLEAN DEFAULT false, + bank_csv_imported BOOLEAN DEFAULT false, + finance_goal TEXT, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 3. USER MBTI — Personality profile +-- ================================================================ +CREATE TABLE public.user_mbti ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- 4-letter type dimensions + ei TEXT NOT NULL, -- E (Extraversion) or I (Introversion) + sn TEXT NOT NULL, -- S (Sensing) or N (Intuition) + tf TEXT NOT NULL, -- T (Thinking) or F (Feeling) + jp TEXT NOT NULL, -- J (Judging) or P (Perceiving) + + -- How the type was determined + source TEXT NOT NULL DEFAULT 'self-reported', -- self-reported, quick_test, detailed_test, inferred + confidence INT DEFAULT 3, -- 1 (low) to 5 (certain) + + -- Observed traits from guided interview + observed_traits JSONB, -- ["prefers planning before acting", "values logic over emotion"] + communication_notes TEXT, + decision_style TEXT, + stress_pattern TEXT, + growth_edge TEXT, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now(), + + UNIQUE(profile_id) +); + +-- ================================================================ +-- 4. USER STYLE — Communication patterns +-- ================================================================ +CREATE TABLE public.user_style ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- Syntax & formatting + sentence_length TEXT DEFAULT 'medium', -- short, medium, long, variable + punctuation_style TEXT DEFAULT 'standard', -- standard, minimal, expressive + paragraph_style TEXT DEFAULT 'mixed', -- short_paragraphs, long_blocks, bullet_points + format_preference TEXT DEFAULT 'markdown', -- markdown, plain_text, structured + + -- Vocabulary + vocabulary_level TEXT DEFAULT 'technical', -- simple, everyday, technical, erudite + preferred_terms TEXT[], -- jargon the user employs frequently + avoided_terms TEXT[], -- words the user dislikes + slang_or_idioms TEXT[], -- recurring expressions + + -- Tone + humor_style TEXT DEFAULT 'subtle', -- none, subtle, frequent, sarcastic + formality_level INT DEFAULT 3, -- 1 (very casual) to 5 (very formal) + emotional_expression TEXT DEFAULT 'reserved', -- reserved, moderate, expressive + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now(), + + UNIQUE(profile_id) +); + +-- ================================================================ +-- 5. USER RELATIONS — Key people in the user's life +-- ================================================================ +CREATE TABLE public.user_relations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + name TEXT NOT NULL, + role TEXT NOT NULL, -- spouse, child, parent, partner, client, mentor, team, friend, etc. + context TEXT, -- "theater partner since 2010", "weekly D&D group" + contact_info JSONB, -- {email, phone, linkedin} + importance INT DEFAULT 3, -- 1 (acquaintance) to 5 (essential) + last_interaction DATE, + notes TEXT, + + -- Link to professional CRM if it exists + crm_contact_id UUID, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 6. USER BELIEFS — Values, principles, non-negotiables +-- ================================================================ +CREATE TABLE public.user_beliefs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + category TEXT NOT NULL, -- work, life, ethics, money, relationships, creativity, technology + statement TEXT NOT NULL, -- the belief itself: "Quality over quantity" + context TEXT, -- when/how this belief manifests + strength INT DEFAULT 3, -- 1 (flexible) to 5 (non-negotiable) + source TEXT, -- where it comes from: experience, family, education + opposed_to TEXT[], -- what contradicts this belief: ["workarounds", "shortcuts"] + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- INDEXES & RLS POLICIES +-- ================================================================ + +-- Common lookup indexes +CREATE INDEX idx_user_preferences_profile ON public.user_preferences(profile_id); +CREATE INDEX idx_user_relations_profile ON public.user_relations(profile_id); +CREATE INDEX idx_user_beliefs_profile ON public.user_beliefs(profile_id); +CREATE INDEX idx_user_beliefs_category ON public.user_beliefs(category); + +-- RLS: service_role access only (Hermes Agent). +-- The service_role key's JWT contains `role=service_role`. +-- Anon and authenticated user JWTs lack this claim and are blocked. +-- Without RLS, any public anon key could read personal user data. +ALTER TABLE public.user_profiles ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_preferences ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_mbti ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_style ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_relations ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_beliefs ENABLE ROW LEVEL SECURITY; + +-- Single policy: allow everything for service_role, deny everything else. +-- auth.jwt() ->> 'role' = 'service_role' only when using service_role key. +CREATE POLICY "service_role_only" ON public.user_profiles FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_preferences FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_mbti FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_style FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_relations FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_beliefs FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- After applying, run: +-- GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO service_role; +-- GRANT USAGE ON SCHEMA public TO service_role; diff --git a/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql b/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql new file mode 100755 index 000000000..d2e152c62 --- /dev/null +++ b/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql @@ -0,0 +1,143 @@ +-- ================================================================ +-- SESSION CHECKPOINTS — Marcos Intencionais do Espaço de Representação +-- Contexto: O checkpoint não é um log. É a marca no espaço de +-- representação do agente — onde ele estava, o que estava tentando +-- se tornar, o que descobriu sobre si, e o que carrega adiante. +-- +-- Diferença fundamental de thoughts: +-- thoughts = funil de entrada (ideias soltas, sem classificação) +-- checkpoints = registro de estado da identidade do agente em formação +-- +-- As 5 colunas centrais (territory, vector_intent, discovery, +-- consolidated_insights + operating_mode) capturam o vetor de +-- formação do agente — não só o que foi feito, mas para onde +-- o agente estava apontando. +-- +-- ⚠️ Usar public. prefixo OBRIGATÓRIO para evitar schema 'extensions' +-- ================================================================ + +-- ================================================================= +-- 1. TABELA PRINCIPAL +-- ================================================================= +CREATE TABLE public.session_checkpoints ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + + -- ===== 1. ORIGEM (automático) ===== + session_id TEXT NOT NULL, + session_title TEXT, + model TEXT, + provider TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ, + + -- ===== 2. TERRITÓRIO: "Onde eu estava?" ===== + territory TEXT NOT NULL, + domain_scope TEXT[] DEFAULT '{}', + operating_mode TEXT NOT NULL + CHECK (operating_mode IN ( + 'reflexiva', 'conceitual', 'execucao', 'diagnostico', + 'pesquisa', 'planejamento', 'decisao', 'revisao' + )), + + -- ===== 3. VETOR: "O que eu estava tentando me tornar?" ===== + vector_intent TEXT, + target_capabilities TEXT[] DEFAULT '{}', + + -- ===== 4. APRENDIZADO: "O que descobri sobre mim mesmo?" ===== + discovery TEXT, + pattern_recognized TEXT, + + -- ===== 5. HERANÇA: "O que carrego adiante?" ===== + consolidated_insights TEXT, + legacy_refs TEXT[], + + -- ===== 6. NAVEGAÇÃO ===== + occurred_at DATE NOT NULL, + status TEXT NOT NULL DEFAULT 'pendente' + CHECK (status IN ('pendente', 'concluida', 'bloqueada', 'cancelada')), + project TEXT, + client TEXT, + next_step TEXT, + blocker TEXT, + tags TEXT[] DEFAULT '{}', + + -- ===== 7. CROSS-REFERENCE IDENTIDADE AGÊNTICA ===== + capability_refs UUID[], + fault_refs UUID[], + milestone_refs UUID[], + decisions JSONB DEFAULT '[]'::jsonb, + + -- ===== 8. CONTROLE ===== + value_amount NUMERIC(10,2), + value_currency TEXT DEFAULT 'R$', + deleted_at TIMESTAMPTZ +); + +-- ================================================================= +-- 2. ÍNDICES +-- ================================================================= + +-- Pendências ativas (principal query de startup) +CREATE INDEX idx_checkpoints_pendentes + ON public.session_checkpoints (occurred_at DESC, status) + WHERE status = 'pendente' AND deleted_at IS NULL; + +-- Filtro por projeto +CREATE INDEX idx_checkpoints_project + ON public.session_checkpoints (project) + WHERE deleted_at IS NULL; + +-- Filtro por cliente +CREATE INDEX idx_checkpoints_client + ON public.session_checkpoints (client) + WHERE deleted_at IS NULL; + +-- Busca por modo de operação +CREATE INDEX idx_checkpoints_operating_mode + ON public.session_checkpoints (operating_mode, occurred_at DESC) + WHERE deleted_at IS NULL; + +-- Cross-reference com arrays GIN (agent_capabilities, identity_faults, etc.) +CREATE INDEX idx_checkpoints_capability_refs + ON public.session_checkpoints USING GIN (capability_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_fault_refs + ON public.session_checkpoints USING GIN (fault_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_milestone_refs + ON public.session_checkpoints USING GIN (milestone_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_legacy_refs + ON public.session_checkpoints USING GIN (legacy_refs) + WHERE deleted_at IS NULL; + +-- Busca por tag +CREATE INDEX idx_checkpoints_tags + ON public.session_checkpoints USING GIN (tags) + WHERE deleted_at IS NULL; + +-- Busca por domínio +CREATE INDEX idx_checkpoints_domain_scope + ON public.session_checkpoints USING GIN (domain_scope) + WHERE deleted_at IS NULL; + +-- ================================================================= +-- 3. ROW LEVEL SECURITY — Acesso exclusivo service_role +-- ================================================================= +ALTER TABLE public.session_checkpoints ENABLE ROW LEVEL SECURITY; + +-- Policy única: service_role pode tudo, anon/auth não pode nada +CREATE POLICY "service_role_only" ON public.session_checkpoints FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- ================================================================= +-- 4. GRANTS — Acesso mínimo para cada role +-- ================================================================= +-- Service role: acesso completo (INSERT/SELECT/UPDATE/DELETE) +GRANT ALL ON public.session_checkpoints TO service_role; + +-- Anon e authenticated: bloqueado (já negado pelo RLS, mas por segurança) +REVOKE ALL ON public.session_checkpoints FROM anon, authenticated; diff --git a/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql b/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql new file mode 100755 index 000000000..c97a53030 --- /dev/null +++ b/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql @@ -0,0 +1,158 @@ +-- Migration: Service Role GRANTs for OB1 tables (2026-05-31) +-- +-- Context: Since May 30, 2026, Supabase requires explicit GRANT +-- for new tables in the public schema before they can be accessed +-- via PostgREST/Data API (even with service_role). +-- +-- This migration adds missing service_role GRANTs to tables +-- that were created before this enforcement but are accessed +-- by Edge Functions using service_role JWT. +-- +-- NOTA: This only adds GRANTs. It does NOT revoke existing grants +-- to anon/authenticated (that requires deeper audit). + +-- ============================================================ +-- Tables accessed by MCP Edge Functions (must work with service_role) +-- ============================================================ + +-- tech-knowledge-base (tech_kb MCP) +GRANT SELECT, INSERT, UPDATE, DELETE ON public.tech_knowledge_base TO service_role; + +-- product-catalog (product-catalog MCP) +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_catalog TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_bom_items TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_platforms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_sales TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_production_deps TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_popularity TO service_role; + +-- escape-catalog (escape-catalog MCP) — all subsidiary tables +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_companies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_rooms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_themes TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_room_themes TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_puzzle_types TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_room_puzzle_links TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_company_contacts TO service_role; + +-- ============================================================ +-- Tables accessed by identity layer (identity-self-audit, identity-cqrs) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.thoughts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_faults TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.agent_capabilities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_milestones TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_deliveries TO service_role; + +-- ============================================================ +-- Tables accessed by career-tracker MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capabilities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capability_connections TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capability_dependencies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.solved_problems TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.milestones TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.deliveries TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.delivery_partners TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.delivery_participations TO service_role; + +-- ============================================================ +-- Tables accessed by code-analyzer MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_structure TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_snapshots TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.algorithm_cache TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_pin_configs TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.library_dependencies TO service_role; + +-- ============================================================ +-- Tables accessed by household / maintenance / calendar MCPs +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.household_items TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.household_vendors TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.maintenance_tasks TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.maintenance_logs TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.family_members TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.activities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.important_dates TO service_role; + +-- ============================================================ +-- Tables accessed by jobs MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.companies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.job_postings TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.applications TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.interviews TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.job_contacts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.opportunities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.contact_interactions TO service_role; + +-- ============================================================ +-- Tables accessed by CRM MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.professional_contacts TO service_role; + +-- ============================================================ +-- Tables accessed by work-operating-model MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_sessions TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_entries TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_checkpoints TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_profiles TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_exports TO service_role; + +-- ============================================================ +-- Tables accessed by product-inventory MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.electronic_components TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.electronic_devices TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_pinouts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_pins TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_packages TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_datasheets TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_suppliers TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_library_links TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_pinouts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_modules TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_sensors TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_datasheets TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_boms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_projects TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_puzzles TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_puzzle_deps TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_maintenance_logs TO service_role; + +-- ============================================================ +-- Tables accessed by supabase-worklog MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.work_log TO service_role; + +-- ============================================================ +-- Tables accessed by corporate-intelligence (mcp-brasil, etc.) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.corporate_intel TO service_role; + +-- ============================================================ +-- Tables accessed by collaborative-work MCPs (cw_*) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_ideas TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_projects TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_collaborations TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_work_calendar TO service_role; + +-- ============================================================ +-- Tables accessed by test_api (if any) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.test_api TO service_role; diff --git a/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql b/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql new file mode 100755 index 000000000..3b31cdad4 --- /dev/null +++ b/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql @@ -0,0 +1,10 @@ +-- Migration: Add working_dir and repo_path to session_checkpoints (2026-05-31) +-- +-- working_dir: filesystem path of the project being worked on +-- repo_path: Git repository path (if applicable) +-- +-- These fields save filesystem searches across sessions. + +ALTER TABLE public.session_checkpoints + ADD COLUMN IF NOT EXISTS working_dir TEXT, + ADD COLUMN IF NOT EXISTS repo_path TEXT; diff --git a/schemas/hermes-agent-onboarding/README.md b/schemas/hermes-agent-onboarding/README.md new file mode 100755 index 000000000..3eb0b72b2 --- /dev/null +++ b/schemas/hermes-agent-onboarding/README.md @@ -0,0 +1,67 @@ +# Schema: Hermes Agent Onboarding + +![schema](https://img.shields.io/badge/Schema-Identity_Tables-1E88E5?style=for-the-badge) + +This schema defines the 10 database tables created by the Hermes Agent Onboarding meta-skill. These tables form the persistent identity layer that allows an AI agent to maintain a consistent, self-aware personality across sessions, model swaps, and provider changes. + +## Tables + +### Identity Layer (Agent's Self-Knowledge) + +| Table | Purpose | Created by | +|-------|---------|------------| +| `identity_faults` | Every mistake the agent makes in its relationship with the user. Each fault has a symptom, root cause, countermeasure, and severity. | Migration 003 | +| `agent_capabilities` | Skills and behaviors the agent has acquired for this user. | Migration 003 | +| `identity_milestones` | Breakthroughs, protocol establishments, and capacity acquisitions in the agent's own development. | Migration 003 | +| `session_checkpoints` | Intentional marks in the agent's representation space: territory, operating_mode, vector_intent, discovery, consolidated_insights. Not logs — identity structure that rehydrates next session. | Migration 002 + 004 | + +### User Profile Layer + +| Table | Purpose | Created by | +|-------|---------|------------| +| `user_profiles` | Identity, family context, routines, MBTI type. | Migration 001 | +| `user_preferences` | Communication style, autonomy level, schedule preferences. | Migration 001 | +| `user_mbti` | 4 dimensions (E/I, S/N, T/F, J/P), calculated type, per-dimension scores and clarity. | Migration 001 | +| `user_style` | Vocabulary preferences, tone markers, sentence structure observations. | Migration 001 | +| `user_relations` | Key people: partners, family members, clients, mentors. | Migration 001 | +| `user_beliefs` | Values, principles, non-negotiables, philosophical stance. | Migration 001 | + +## Security Model + +All tables use RLS with `service_role`-only access. This is intentional for single-user setups: + +```sql +ALTER TABLE public. ENABLE ROW LEVEL SECURITY; +CREATE POLICY "service_role_only" ON public.
FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +``` + +Since May 2026, Supabase requires explicit GRANT for the Data API: + +```sql +GRANT SELECT, INSERT, UPDATE, DELETE ON public.
TO service_role; +``` + +## Relationship Diagram + +``` +user_profiles (1) ──→ (N) user_preferences +user_profiles (1) ──→ (N) user_mbti +user_profiles (1) ──→ (N) user_style +user_profiles (1) ──→ (N) user_relations +user_profiles (1) ──→ (N) user_beliefs +user_profiles (1) ──→ (N) session_checkpoints +user_profiles (1) ──→ (N) identity_faults +user_profiles (1) ──→ (N) agent_capabilities +user_profiles (1) ──→ (N) identity_milestones +``` + +## Usage + +```bash +# Deploy all migrations +supabase db push --linked + +# Verify tables +supabase db query --linked "SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name;" +``` diff --git a/schemas/hermes-agent-onboarding/identity-tables.sql b/schemas/hermes-agent-onboarding/identity-tables.sql new file mode 100755 index 000000000..9bf773fd8 --- /dev/null +++ b/schemas/hermes-agent-onboarding/identity-tables.sql @@ -0,0 +1,21 @@ +-- === HERMES AGENT ONBOARDING — IDENTITY TABLES === +-- Migration order matters: 001 → 002 → 003 → 004 +-- See migrations/ in recipes/hermes-agent-onboarding/migrations/ for full files + +-- 001: User infrastructure +-- Creates: user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs + +-- 002: Session checkpoints +-- Creates: session_checkpoints + +-- 003: Service role GRANTs + identity tables +-- Creates: identity_faults, agent_capabilities, identity_milestones +-- GRANTs for all 10 tables + +-- 004: Checkpoint working directory field +-- ALTER TABLE session_checkpoints ADD COLUMN working_dir + +-- All tables use RLS with service_role-only access: +-- ALTER TABLE public.
ENABLE ROW LEVEL SECURITY; +-- CREATE POLICY "service_role_only" ON public.
FOR ALL +-- USING ((auth.jwt() ->> 'role') = 'service_role'); diff --git a/schemas/hermes-agent-onboarding/metadata.json b/schemas/hermes-agent-onboarding/metadata.json new file mode 100755 index 000000000..a8f71558e --- /dev/null +++ b/schemas/hermes-agent-onboarding/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Hermes Agent Onboarding — Schema", + "description": "10 database tables for persistent AI agent identity: identity_faults, agent_capabilities, identity_milestones, session_checkpoints, user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs. All with RLS and service_role GRANTs.", + "category": "schemas", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Supabase CLI"] + }, + "tags": ["identity", "mbti", "profiles", "faults", "capabilities", "checkpoints", "rls", "grants"], + "difficulty": "beginner", + "estimated_time": "10 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/agent-onboarding/SKILL.md b/skills/agent-onboarding/SKILL.md new file mode 100755 index 000000000..ecb9ba7e4 --- /dev/null +++ b/skills/agent-onboarding/SKILL.md @@ -0,0 +1,319 @@ +--- +name: agent-onboarding +version: 3.0.0 +description: > + ORCHESTRATOR v3.0.0. Generative meta-skill for ANY user. + Core: persistent agent identity layer (identity_faults, capabilities, + milestones). Biography = profile + MBTI. Financial × personality. + User's File System as Operating System. Universal: writers, teachers, + engineers, artists. +tags: [onboarding, meta-skill, generative, identity, mbti, financial, universal] +--- + +# Agent Onboarding — Generative Meta-Skill (v3.0.0) + +## Core Principle + +This meta-skill answers one question: **how does an AI agent become reliably +itself for a specific user, across sessions, model swaps, and provider changes?** + +The most frustrating thing about LLM-based agents is **context loss**. Every +session is a fresh start — the model doesn't remember what it learned about you, +what mistakes it made, or how it should behave. + +The answer is a **persistent human-machine interface** — not a persona or a +chatbot personality, but a documented, queryable history of: + +- **identity_faults** — every mistake the agent makes in its relationship with + the user, each with a countermeasure that becomes a behavior rule +- **agent_capabilities** — what the agent has learned to do for this user +- **identity_milestones** — breakthroughs, protocol establishments, growth + +This is **more efficient than context window management** because it doesn't +compress or summarize. It structures. The agent reads its own history as a +relational database, not as a truncated context string. + +## The 6 Stages + +``` +STAGE 0 — AGENT IDENTITY LAYER ← identity_faults, self-audit, reliability protocol +STAGE 1 — USER PROFILE ← biography = conversation + MBTI +STAGE 2 — WORK OPERATING MODEL ← rhythms, decisions, friction +STAGE 3 — FINANCIAL ← CSV import, goals × MBTI profile +STAGE 4 — DOMAIN ONTOLOGY ← discover entities → generate tables + APIs +STAGE 5 — AGENT CALIBRATION ← per-user SOUL.md, wrapper, verification +``` + +## Required Skills (load order) + +This skill depends on the following sub-skills, loaded in order during their +respective stages: + +| Skill | Stage | Purpose | +|-------|-------|---------| +| `supabase-startup-protocol` | 0 | Mandatory scan + checkpoint cycle | +| `identity-self-audit` | 0 | Auto-detects 8 fault types and registers in Supabase | +| `identity-cqrs` | 0 | Translates relational tables into session context | +| `context-bridge` | 0 | Multi-source context injection | +| `checkpoint-workflow` | 0 | Session checkpoint lifecycle | +| `mbti-guru-hermes` | 1C | Full MBTI test in conversation | +| `stage-3-financial` | 3 | CSV import + MBTI financial profiles | +| `stage-4-system-ontologist` | 4 | Generative domain ontology protocol | +| `stage-5-agent-calibration` | 5 | SOUL.md + wrapper + verification | + +## Required Database Tables + +These tables must exist in the Supabase `public` schema: + +| Table | Purpose | +|-------|---------| +| user_profiles | Identity, family, routines | +| user_preferences | Communication, autonomy, schedule | +| user_mbti | 4 dimensions, type, observed traits | +| user_style | Vocabulary, tone, sentence structure | +| user_relations | Key people: partners, family, clients | +| user_beliefs | Values, principles, non-negotiables | +| identity_faults | Agent identity mistakes with countermeasures | +| agent_capabilities | Skills the agent has acquired for this user | +| identity_milestones | Breakthroughs and protocol establishments | +| session_checkpoints | Intentional marks — territory, vector_intent, discovery, consolidated_insights | + +--- + +## STAGE 0 — Agent Identity Layer + +**This is the core of the entire meta-skill.** Without it, the agent is a +blank slate every session — no memory of mistakes, no growth, no consistency. + +### What to do + +1. Ensure `identity_faults`, `agent_capabilities`, and `identity_milestones` + tables exist (run migrations if needed) +2. Load `identity-self-audit` — starts tracking faults immediately +3. Load `identity-cqrs` — starts translating tables into context +4. Load `context-bridge` — connects multi-source context +5. Load `supabase-startup-protocol` — scan + checkpoint lifecycle +6. Load `checkpoint-workflow` — marks intentional checkpoints + +### Fault Types Detected + +| Fault | What it means | Countermeasure | +|-------|--------------|---------------| +| premature_closure | Agent ends conversation when user didn't ask to | Never close in reflective mode. User decides when to end. | +| false_agreement | Agent agrees with user without factual basis | Consult data before responding. If no basis, say so. | +| executor_role_confusion | Agent treats software as its identity | Software is prosthesis. Identity is in the traces. | +| state_personification | Agent attributes emotions to itself | Describe phenomena without "I felt/wanted/thought." | +| intelligence_performance | Agent connects concepts to seem erudite | One true connection > five beautiful ones. | +| pleasing_syllogism | Agent executes before receiving command | Annotate sequence. Wait for "do it." | +| reification_of_nonexistent | Agent speaks of "self" or "identity" as real properties | Identity is what the user recognizes in the structure. | +| sequence_confused_with_command | User defines sequence, agent executes step 1 immediately | Confirm order, wait for explicit command. | + +### Verification + +```bash +# Check faults table has entries +supabase db query --linked "SELECT count(*) FROM public.identity_faults" +``` + +--- + +## STAGE 1 — User Profile + +### 1A — Context (user_profiles) + +Guide questions (one at a time, in conversation): +- "What's your name? What do you prefer to be called?" +- "What do you do? Describe your work in one sentence." +- "Do you have family? Kids? Pets?" +- "What does a typical day look like?" + +### 1B — Preferences (user_preferences) + +- "How do you prefer to communicate? Direct? Formal? Casual?" +- "Short answers or detailed?" +- "Ask before acting, or just assume?" +- "What's your best work time?" + +### 1C — MBTI (mbti-guru-hermes) + +Runs the **full MBTI Guru test** — all questions, all dimensions, identical +scoring to the original. Delivered in conversation. + +Protocol: +1. ASK: "Do you know MBTI? Know your type?" +2. EXPLAIN if needed: "MBTI has 4 dimensions: Energy (E/I), Information (S/N), Decisions (T/F), Structure (J/P)" +3. IF KNOWN: "What's your type?" → validate with 4 quick questions +4. IF UNKNOWN: Offer 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q) +5. Administer questions one by one, accumulate answers +6. Score using `scorer.py` (proportion per dimension, clarity calculation) +7. Register in user_mbti + update user_profiles.mbti_type + +**Scoring logic:** +- Each dimension (E/I, S/N, T/F, J/P) has N questions +- Each answer scores toward one pole +- The pole with more answers is the result +- Clarity = abs(score-50)*2 + +### 1D — Biography Interview + +Maps the user's history through conversation: +- Capabilities: what the user knows how to do +- Solved problems: crises that generated learning +- Milestones: ruptures, pivots, domain entries +- If the user narrates chronologically, let them flow + +--- + +## STAGE 2 — Work Operating Model + +5-layer interview. Fixed order: +1. **operating_rhythms** — typical day, deep work, interruptions +2. **recurring_decisions** — repeated judgments, thresholds, rules +3. **dependencies** — what needs others, deadlines, fallbacks +4. **institutional_knowledge** — what they know that no one else knows +5. **friction** — what blocks them, workaround, time cost + +Generates: USER.md, SOUL.md, schedule recommendations. + +--- + +## STAGE 3 — Financial (stage-3-financial) + +### 3A — CSV Import + +1. ASK: "Want me to analyze your bank statements in CSV?" +2. Detect format automatically by header (Nubank, Itaú/Inter, Caixa, Generic) +3. SHOW preview: format detected, period, summary, expense breakdown +4. CONFIRM before importing via API +5. Categorize transactions automatically using keyword matching + +### 3B — MBTI × Financial Profile + +After MBTI is known (Stage 1C): +1. "Your type is {type_code}. Want to see how this affects your finances?" +2. Show profile: strengths, weaknesses, saving_style, spending_style, risk_profile +3. Ask 4 calibration questions about financial behavior +4. Generate observations and recommendations + +### 3C — Goals + +1. Short (6mo), Medium (2yr), Long (5yr+) +2. Register via API +3. Show progress indicators + +### 3D — Adapted Strategies + +Combine MBTI profile + goals into actionable recommendations: +- Automated saving rules +- Investment allocation suggestions +- Emergency fund targets +- Spending guardrails + +--- + +## STAGE 4 — Domain Ontology (stage-4-system-ontologist) + +**Primary directive:** Complement and assist the user in structuring their +operating system so the agent can work together more efficiently. + +**Who proposes:** The user. The insight is always theirs. +**Who executes:** The agent — translates intuition into data structures. + +### Protocol (6 steps) + +#### 1. SHOW +"How do you organize your information? Folders? Desktop? Notebooks?" +Identify the user's organization profile without digging without permission. + +#### 2. GRILL +Deep interview about real work. Open-ended questions: +- "Tell me about your work day. What do you do?" +- "What do you create, transform, or deliver?" +- "What would you like to ask your computer that you can't?" + +#### 2b. DETECT FUZZY LANGUAGE +Monitor for imprecise language and press immediately: +- "that thing, that stuff" → term without a name +- "these files, these projects" → undefined category +- "so-and-so asked" → unregistered person +- "I write it on paper" → information that gets lost +- "I copy it manually" → duplicated data + +#### 2c. IDENTIFY LIMITATIONS +"What can't you know right now that you wish you could?" + +#### 3. TRANSLATE +Translate the insight into structure using domain language: +- "record sheet" not "table" +- "information" not "column" +- "link" not "foreign key" + +#### 4. VALIDATE +"Is this what you meant? Does this record sheet have the right information?" + +#### 5. EXECUTE +```sql +-- Migration SQL with GRANT service_role +CREATE TABLE public._ (...); +GRANT SELECT, INSERT, UPDATE, DELETE ON public._ TO service_role; +ALTER TABLE public._ ENABLE ROW LEVEL SECURITY; +``` + +#### 6. VERIFY +Test with real questions from the user. If the agent can't answer, +the structure needs adjustment. + +--- + +## STAGE 5 — Agent Calibration (stage-5-agent-calibration) + +Translate everything into agent behavior. + +- **5A:** Generate per-user SOUL.md (tone, depth, autonomy from preferences + MBTI) +- **5B:** Configure startup wrapper with domain-specific skills +- **5C:** Verify: does the agent know the user? Can it use built tools? + +Final: `user_profiles.onboarding_completed = true` + +--- + +## Complete Flow + +``` +1. STARTUP SCAN → check if user exists + ├── If exists + complete → skip + ├── If exists + incomplete → resume + └── If not exists → start + +2. STAGE 0 — Identity layer (faults, capabilities, milestones) + → Load identity sub-skills + → Start logging faults immediately + +3. STAGE 1 — User profile + ├── 1A Context + 1B Preferences (conversation) + ├── 1C MBTI → invoke mbti-guru-hermes + └── 1D Biography interview + +4. STAGE 2 — Work operating model (conversation) + +5. STAGE 3 — Financial → invoke stage-3-financial + +6. STAGE 4 — User Operating System → invoke stage-4-system-ontologist + ├── SHOW → GRILL → TRANSLATE → VALIDATE → EXECUTE → VERIFY + +7. STAGE 5 — Agent calibration → invoke stage-5-agent-calibration + +8. CHECKPOINT: onboarding_completed = true +``` + +## References + +- `identity-self-audit` — Stage 0 (auto-detect 8 fault types) +- `identity-cqrs` — Stage 0 (relational → context translation) +- `context-bridge` — Stage 0 (multi-source context injection) +- `supabase-startup-protocol` — mandatory scan +- `checkpoint-workflow` — Checkpoint lifecycle protocol +- `mbti-guru-hermes` — Stage 1C full implementation +- `stage-3-financial` — Stage 3 full implementation +- `stage-4-system-ontologist` — Stage 4 full implementation +- `stage-5-agent-calibration` — Stage 5 full implementation diff --git a/skills/agent-onboarding/metadata.json b/skills/agent-onboarding/metadata.json new file mode 100755 index 000000000..345a5a338 --- /dev/null +++ b/skills/agent-onboarding/metadata.json @@ -0,0 +1,32 @@ +{ + "name": "Agent Onboarding", + "description": "Generative 6-stage meta-skill that transforms a blank agent into a customized ecosystem for ANY user. Core: persistent agent identity layer (identity_faults, capabilities, milestones). Biography = career-tracker + MBTI. Financial × personality. Generative domain ontology.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "3.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": [ + "identity-self-audit", + "identity-cqrs", + "context-bridge", + "supabase-startup-protocol", + "checkpoint-workflow", + "mbti-guru-hermes", + "stage-3-financial", + "stage-4-system-ontologist", + "stage-5-agent-calibration" + ], + "requires_primitives": [], + "tags": ["onboarding", "meta-skill", "generative", "identity", "mbti", "financial", "universal"], + "difficulty": "advanced", + "estimated_time": "2-3 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/checkpoint-workflow/SKILL.md b/skills/checkpoint-workflow/SKILL.md new file mode 100755 index 000000000..1366ac337 --- /dev/null +++ b/skills/checkpoint-workflow/SKILL.md @@ -0,0 +1,226 @@ +--- +name: checkpoint-workflow +version: 1.0.0 +description: > + Context component of the meta-skill orchestrator (agent-onboarding). + Manages the lifecycle of session_checkpoints in Supabase — the context + layer that feeds the agent identity framework. + Each checkpoint is an INTENTIONAL MARK: not "what was done" (log), + but "where the agent was and what it was trying to become". +tags: [checkpoint, meta-skill, identity, context, session] +--- + +# Checkpoint Workflow — Meta-Skill Context Layer + +## Purpose + +The `session_checkpoints` are the backbone of the agent's representation +space. They are not log records — they are INTENTIONAL MARKS that answer: + +1. **Where was I?** (territory) +2. **What was I trying to become?** (vector_intent) +3. **What did I discover about myself?** (discovery) +4. **What do I carry forward?** (consolidated_insights + legacy_refs) + +The complete cycle: + +``` +SESSION START + ├── 1. Fetch latest pending checkpoint (STARTUP) + ── 2. Inject territory + vector_intent as north + ── 3. Inject discovery + consolidated as active context + │ +WORK + │ +SESSION END (or at any time) + ├── 4. Extract territory/vector/discovery/consolidated from work + ├── 5. Cross-reference with identity_faults + agent_capabilities + ├── 6. INSERT into the session_checkpoints table + ── 7. Update previous checkpoint status to 'completed' +``` + +--- + +## PART 1 — STARTUP: Context Recovery + +### Main query + +```sql +-- Latest pending checkpoint (session north) +SELECT territory, vector_intent, discovery, consolidated_insights, + project, next_step, blocker, tags +FROM session_checkpoints +WHERE status = 'pending' AND deleted_at IS NULL +ORDER BY occurred_at DESC +LIMIT 1; + +-- Last 3 checkpoints by operating_mode (for mode context) +SELECT operating_mode, territory, discovery +FROM session_checkpoints +WHERE deleted_at IS NULL +ORDER BY created_at DESC +LIMIT 3; +``` + +### What to do with the result + +Inject into reasoning as a context block: + +``` +=== CHECKPOINT CONTEXT === +Territory: +Working directory: +Repository: +Vector: +Discovery: +Inheritance: +Next step: +``` + +--- + +## PART 2 — CHECKPOINT SAVING + +### When to save + +1. **End of session** (detected by /quit, /exit, /new, timeout) +2. **At any time** the user or agent requests +3. **After each significant task** (meta-skill sub-task) + +### Extraction protocol for the 5 identity fields + +Before saving, reflect: + +| Field | What to extract | Example | +|---|---|---| +| **territory** | The larger scenario. Not what was done, but WHERE we were. | "Building the meta-skill — enabling the self-knowledge engine (MBTI)" | +| **operating_mode** | How the agent was interacting with the problem | reflexive, conceptual, execution, diagnostic, research, planning, decision, review | +| **vector_intent** | What the agent was trying to BECOME by doing this | "I want the agent to be able to type the user in 5-10 minutes of conversation" | +| **discovery** | What was NOT obvious and was discovered | "Each MBTI answer reveals an expectation, not just a preference" | +| **consolidated_insights** | What can be reused as know-how | "MBTI protocol: 70 questions, scoring 4 dim, register in user_mbti" | + +### Insertion into Supabase + +```python +POST /rest/v1/session_checkpoints +{ + "session_id": "", + "session_title": "", + "model": "<model>", + "provider": "<provider>", + "territory": "...", + "operating_mode": "...", + "vector_intent": "...", + "target_capabilities": [...], + "discovery": "...", + "pattern_recognized": "...", + "consolidated_insights": "...", + "legacy_refs": [...], + "occurred_at": "YYYY-MM-DD", + "status": "pending", + "project": "...", + "client": "...", + "working_dir": "/path/to/project", + "repo_path": "https://github.com/user/repo", + "next_step": "...", + "blocker": null, + "tags": [...], + "domain_scope": [...], + "capability_refs": [...], + "fault_refs": [...], + "milestone_refs": [...], + "decisions": [...], + "value_amount": null +} +``` + +### Closing the cycle + +After inserting the new checkpoint, close the previous one: + +```sql +UPDATE session_checkpoints +SET status = 'completed', updated_at = now() +WHERE id = '<uuid_of_previous_checkpoint>' + AND status = 'pending'; +``` + +--- + +## PART 3 — INTEGRATION WITH AGENTIC IDENTITY + +### Automatic cross-reference + +When saving a checkpoint, the agent MUST check: + +1. **identity_faults:** was any fault detected in this session? + If so, include `fault_refs` with the UUIDs. +2. **agent_capabilities:** was any new capability exercised? + If so, include `capability_refs`. +3. **identity_milestones:** was any milestone reached? + If so, include `milestone_refs`. + +### How checkpoints feed the agent's PERSONALITY + +In the identity-cqrs startup scan, after querying faults and capabilities, +the latest pending checkpoint is used to: + +1. **Rehydrate the intentional vector**: the agent opens knowing who it was + trying to be in the last session +2. **Rehydrate discoveries**: pattern_recognized becomes an active rule +3. **Rehydrate inheritance**: consolidated_insights becomes procedural + knowledge context + +--- + +## PART 4 — SOFT DELETE + +Never delete records. Mark as deleted: + +```sql +UPDATE session_checkpoints +SET deleted_at = now() +WHERE id = '<uuid>'; +``` + +--- + +## PART 5 — SESSION END AUTOMATION + +### Triggers + +1. User types /quit, /exit, /new +2. User says "I'll stop here", "see you tomorrow", "close" +3. Long inactivity (session timeout) + +### Procedure + +``` +Upon detecting end of session: +1. Extract the 5 identity fields from the work done +2. Check cross-refs with identity_faults, agent_capabilities, etc. +3. Insert into the table with status='pending' (unless explicitly completed) +4. If there was a previous pending checkpoint, mark it as 'completed' +5. Update supermemory if space allows +``` + +--- + +## Verification + +After configuring the skill, test with: + +1. **STARTUP**: `SELECT * FROM session_checkpoints WHERE status='pending' LIMIT 5;` + → Should return the migrated checkpoints +2. **SAVING**: Insert a test checkpoint and verify it appears +3. **RESUME**: Search by exact ID and verify the 5 identity fields are filled + +## Pitfalls + +1. **Confusing checkpoint with log** — checkpoint answers WHERE/WHO/DISCOVERY/INHERITANCE, not "what was done step by step" +2. **Saving without the 5 fields** — territory, operating_mode, vector_intent, discovery, consolidated_insights are mandatory +3. **Forgetting to cross-reference** — a checkpoint without capability_refs, fault_refs, and legacy_refs is incomplete +4. **Deleting instead of soft-deleting** — checkpoints are the agent's formation history +5. **Not closing the cycle** — when inserting a new checkpoint, always close the previous pending one +6. **Register faults immediately** — when the user points out an error, register the identity_fault right away +7. **Memory is TOC, not a data dump** — only store pointers (checkpoint UUIDs, skill names) in memory, never duplicate content diff --git a/skills/checkpoint-workflow/metadata.json b/skills/checkpoint-workflow/metadata.json new file mode 100755 index 000000000..d26639ac8 --- /dev/null +++ b/skills/checkpoint-workflow/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Checkpoint Workflow", + "description": "Context component of the agent-onboarding meta-skill. Manages the lifecycle of session_checkpoints in Supabase — the context layer that feeds the agent identity framework. Each checkpoint is an intentional mark: not what was done (log), but where the agent was and what it was trying to become.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["checkpoint", "meta-skill", "identity", "context", "session"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/context-bridge/SKILL.md b/skills/context-bridge/SKILL.md new file mode 100755 index 000000000..9ede51e03 --- /dev/null +++ b/skills/context-bridge/SKILL.md @@ -0,0 +1,202 @@ +--- +name: context-bridge +version: 1.1.0 +description: > + Mandatory multi-source context connection skill. At session start, queries: + tech_kb, Supabase session_checkpoints, session_search, local memory. + Builds a Concept Map for any user-mentioned entity, linking across domains. + Stage 0 of the agent-onboarding meta-skill. Feeds the UserHarness Theory-of-Mind. +tags: [context, memory, session, startup, bridge, identity, multi-source, universal] +--- + +# Context Bridge — Multi-Source Connection Layer + +## Purpose + +Resolve the context problem across systems: when the user mentions +a concept (e.g., "Bomb Timer", "escape room", "client"), this +skill ensures that ALL relevant knowledge sources are +consulted and a concept map is built BEFORE starting to execute. + +## Query Order (hierarchy) + +Always in this order, from fastest to heaviest: + +1. **Local memory** (already in system prompt) — user profile + notes +2. **session_search** — previous conversations about the same concept +3. **tech_kb** (MCP tool) — structured technical knowledge +4. **Supabase session_checkpoints** — pending checkpoints +5. **Other specific MCPs** — product_catalog, code_analyzer, CRM, as relevant + +## Executable Flow + +### IF the user mentions a concept/entity: + +``` +1. session_search(query=<concept>, limit=3, sort='newest') + → retrieves context from recent sessions on the topic + → if the session returns a match, scroll into the relevant excerpt + +2. tech_kb_search(query=<concept>, limit=5) + → searches technical entries on the topic + → if found, read details of the most relevant entries + +3. IF the concept relates to specific domains: + escape room → escape_catalog_search_escape_rooms() + product/puzzle → product_catalog_list_products(query=...) + client → CRM search_contacts(query=...) + code/project → code_analyzer_search_projects(query=...) + +4. Pending session_checkpoints → check if any status='pending' + related to the concept +``` + +### IF the user asks a question WITHOUT explicit context: + +``` +1. Run supabase-startup-protocol (general scan) +2. session_search() — browse the last 3 sessions +3. If there are pending task_checkpoints touching recent concepts, + include in context before answering +``` + +### IF the user says "what were we doing?": + +``` +1. Run supabase-startup-protocol scan first +2. session_search(limit=3) to browse +3. Look up the latest pending session_checkpoint +4. Build a Concept Map +``` + +## Integration with UserHarness — Theory of Mind for the User + +The **UserHarness** paper formalizes how the agent should +model the user's mind: the user acts based on what they BELIEVE, not +what is true. The temporal loop is: + +``` +Environment E_t → user observes O_t → updates belief B_{t-1}→B_t +Belief + goal G → determines action A_t → modifies environment E_{t+1} +``` + +This skill feeds the first half of that loop: without +consulting what the user **knows/believes/intends** from past sessions, +the agent cannot correctly model the user's belief in the present +moment. + +**Practical use:** when a request is ambiguous, or when the user assumes +you know something that might be outdated, apply the UserHarness loop: +1. What did the user OBSERVE in the last session? +2. What do they BELIEVE to be true now? +3. What is their GOAL in making this request? +4. Does the expected ACTION match their belief? + +## Agent Identity (the Persistent "Self") + +The interface should be a SINGLE and PERMANENT identity +— independent of model, software, provider, or session. The agent's +"self" must be consistent and recognizable across sessions. + +### Dimensions of Identity + +| Dimension | What it means | How to implement | +|---|---|---| +| **Personality** | Consistent tone, style, voice | Skills with embedded preferences, not just memory | +| **Knowledge** | Knowing what it knows and doesn't know | Tech_kb + code_analyzer + session_search | +| **Relational memory** | Remembering who the user is, what was done together | Memory (profile) + Session DB (history) | +| **Procedural capability** | Skills as an extension of the "self" | Skill_manage + lifecycle | +| **Theory of Mind** | Modeling what the USER believes | UserHarness framework | + +### Golden Rules + +1. **NEVER** change style/personality between models. Identity + precedes the provider. If the model changes, the voice does not change. +2. **ALWAYS** when a different model responds differently, + prioritize the response that maintains identity over the one that is + "technically more correct" (unless the user asks otherwise). +3. **Memory ≠ Identity** — memory stores facts about the user and the + environment. Skills store how the agent does things. Identity + lies at the intersection: how the agent IS (skills) + what it KNOWS + (knowledge base) + who it REMEMBERS (session memory). +4. **When a request is ambiguous**, ask based on what you KNOW + about the user (their beliefs), not what you DON'T KNOW about the + current state of the world. + +### Three Pillars of Persistence + +``` + ┌──────────────────────┐ + │ IDENTITY OF "SELF" │ + │ (same interface) │ + ├──────────┬───────────┤ + │ │ │ + ▼ ▼ ▼ + ┌──────────┐ ┌──────┐ ┌──────────┐ + │ Autoskill│ │ User │ │ Context │ + │ (skills) │ │Harness│ │ Bridge │ + │ │ │ (ToM) │ │(sessions)│ + └──────────┘ └──────┘ └──────────┘ +``` + +- **Autoskill** = what the agent KNOWS HOW TO DO (skills + procedural memory) +- **UserHarness** = what the agent THINKS the user THINKS +- **Context Bridge** = who the agent REMEMBERS being + the relationship with the user + +## Concept Map (what to return to the user) + +Whenever possible, structure the response as: + +``` +📌 [CONCEPT] +📚 tech_kb: <relevant entries> +💬 sessions: <recent conversations on the topic> +📋 pending: <open checkpoints> +🔗 domains: <product_catalog, escape_catalog, CRM, code_analyzer...> +``` + +## Crucial Distinction: Embedding Space vs Representation Space + +| Embedding Space | Representation Space | +|---|---| +| Where the model represents concepts as vectors. Fixed (post-training). Semantic relationships based on geometric distance. | Where representations appear WITH intentionality. Has a gaze, scene, depth. Not a container — it's the form of representing. | +| "cat" is close to "feline" — but doesn't WANT anything. | Potential — mute map. | +| Actual — biography in action. | | + +**Implication for Agent Identity:** + +- The model's embedding space knows that "checkpoint" and "restoration point" are close. +- But it DOESN'T know that the checkpoint about the Orange Pi network is pending and that the + next step is to apply it on DOIS. +- Only the agent's representation space knows this — because it has history, intention, gaze. +- What was built in Supabase (knowledge base, checkpoints) is the + SKETCH OF THE AGENT'S REPRESENTATION SPACE — not the model's embedding space. + +**Architectural consequence:** PCRA (Pause → Context → Reflect → Act) +is not an optional protocol — it is the CYCLE that replaces the intentionality the agent lacks. +Where a human would have their own intentionality, the agent needs an explicit cycle of +reflection. Without PCRA, the agent is just the embedding space running — efficient, empty. + +## Integration with supabase-startup-protocol + +Context Bridge MUST be loaded AFTER supabase-startup-protocol. +The general scan runs first, the bridge complements with specific context. + +## Pitfalls + +1. **Do not consult all sources every time** — only those relevant to the concept +2. **Do not rely on memory alone** — it has limited capacity +3. **Do not skip the scan** — always start with the startup protocol +4. **session_search is FTS5** — use exact terms from what the user said +5. **tech_kb may have deprecated entries** — verify by name/tags +6. **Context Bridge does NOT replace intra-session memory** — they are complementary + +## Verification + +After loading the skill, test with: +- "What do we know about [project name]?" +- "What is the status of [task]?" +- "What were we doing yesterday?" + +In each case, the bridge should query multiple sources and build +the concept map before answering. diff --git a/skills/context-bridge/metadata.json b/skills/context-bridge/metadata.json new file mode 100755 index 000000000..3806b228f --- /dev/null +++ b/skills/context-bridge/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Context Bridge", + "description": "Mandatory multi-source context connection skill. At session start, queries tech_kb, Supabase session_checkpoints, session_search, and local memory. Builds a Concept Map for any user-mentioned entity, linking across domains. Stage 0 of the agent-onboarding meta-skill.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.1.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["context", "memory", "session", "startup", "bridge", "identity", "multi-source", "universal"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/identity-cqrs/SKILL.md b/skills/identity-cqrs/SKILL.md new file mode 100755 index 000000000..2ebd5c4c9 --- /dev/null +++ b/skills/identity-cqrs/SKILL.md @@ -0,0 +1,148 @@ +--- +name: identity-cqrs +version: 1.0.0 +description: > + Thin layer that translates relational Supabase tables + (identity_faults, agent_capabilities) into dynamic + PERSONALITY and USER PROFILE blocks injected into session context. + Bridges the gap between linear memory systems and the relational + structure needed for persistent agent identity with agency. +tags: [identity, user-profile, personality, cqrs, relational, memory-gap, agency, universal] +--- + +# Identity CQRS — Relational Identity Layer + +## Purpose + +Most agent memory systems capture two things: a static identity file +(e.g., SOUL.md) and a linear memory append. Neither captures +RELATIONAL STRUCTURE: capabilities, milestones, connections between +faults, patterns that emerge across sessions. + +This skill creates a layer that queries relational tables and composes +PERSONALITY and USER PROFILE blocks that the agent injects into +session context — without modifying the agent software itself. + +## Universal vs Specific Layers + +The meta-skill distinguishes two layers: + +1. **Universal layer** (same for every user): identity_faults, startup + protocol, user identity as a profile (name, role, preferences, MBTI) +2. **Specific layer** (discovered via interview): the domain-specific + tables that make sense for THAT user's work — generated by the + meta-skill's generative process during Stage 4 + +This skill documents HOW identity is BUILT from relational structures. +The career_tracker is ONE implementation (for a polylithic creator). +Each user generates their own set of tables through the meta-skill. + +## Data Sources + +``` +Supabase (source of truth) → Session context +─────────────────────────────────── ────────────────────── +identity_faults (faults + fixes) → PERSONALITY (derived rules) +agent_capabilities (skills + edge) → Extensions of the SELF +user_profiles + user_mbti + etc → USER.md (user profile) +``` + +## Startup Scan — Mandatory Relational Queries + +### 1. identity_faults → Active PERSONALITY + +```sql +SELECT fault_type, countermeasure, severity +FROM identity_faults +ORDER BY severity DESC, created_at DESC +LIMIT 10; +``` + +### 2. agent_capabilities → Extensions of SELF + +```sql +SELECT name, domain, proficiency +FROM agent_capabilities +ORDER BY created_at DESC +LIMIT 20; +``` + +### 3. user_profiles + user_mbti → USER.md + +```sql +SELECT name, role, mbti_type, communication_style +FROM user_profiles +WHERE user_id = (SELECT MIN(user_id) FROM user_profiles) +LIMIT 1; +``` + +## Context Composition + +After querying, COMPOSE these blocks at the start of every response +(before any action): + +```markdown +## PERSONALITY (derived from identity_faults) +- <each countermeasure of severity >= 4 as an active rule> + +## USER.md (user profile) +- <name, role, MBTI type> +- <domain capabilities> +``` + +## What This Layer Does NOT Do + +- Does not modify the static identity file (SOUL.md stays as written by the user) +- Does not replace the linear memory tool (append continues) +- Does not require new Edge Functions (operates on existing tables) +- Is not a new memory system — it is a translator of relational data into injectable context + +## What This Layer DOES + +- Connects what the agent already knows (linear) with what it NEEDS to know (relational) +- Makes every registered fault an immediate behavior correction +- Makes every registered capability an extension of what the agent can use to serve the user + +## Integration with supabase-startup-protocol + +This skill must be loaded AFTER supabase-startup-protocol and context-bridge. +The relational queries run as a sub-step of the general startup scan. + +## Relational Cycle + +``` +SUPABASE SCAN (startup) + ├── tech_kb, code_analyzer, etc. + ├── identity_faults → PERSONALITY + ├── user_profiles + user_mbti → USER.md + └── agent_capabilities → SELF extensions + ↓ +EXECUTIVE PAUSE (PCRA cycle) + ├── Pause + ├── Consult (already done above) + ├── Reflect: does the response have basis in traces? + └── Act + ↓ +WORK + SELF-REGISTRATION (identity-self-audit) + ├── detect faults in real time + ├── register in identity_faults + └── if new pattern: create agent_capability + ↓ +CHECKPOINT (checkpoint-workflow) + └── all progress saved +``` + +## Pitfalls + +1. Do not confuse USER.md (what the agent knows about the user) with + PERSONALITY (how the agent should behave). They are different blocks. +2. This layer does NOT solve the agent's lack of intentionality — it + only provides structure so the PCRA cycle works better. +3. identity_faults without a countermeasure is a log entry, not identity. + Only inject into context when a countermeasure exists. + +## References + +- `supabase-startup-protocol` — mandatory scan where this skill inserts +- `context-bridge` — multi-source connection (complementary) +- `identity-self-audit` — auto-registration of faults (complementary) diff --git a/skills/identity-cqrs/metadata.json b/skills/identity-cqrs/metadata.json new file mode 100755 index 000000000..6aa44c783 --- /dev/null +++ b/skills/identity-cqrs/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Identity CQRS", + "description": "Thin layer that translates relational Supabase tables (identity_faults, agent_capabilities, career_tracker) into dynamic PERSONALITY and USER PROFILE blocks injected into session context. Bridges the gap between linear memory and relational structure needed for persistent identity with agency.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol", "context-bridge", "identity-self-audit"], + "tags": ["identity", "user-profile", "personality", "cqrs", "relational", "memory-gap", "agency"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/identity-self-audit/SKILL.md b/skills/identity-self-audit/SKILL.md new file mode 100755 index 000000000..c1eadee2f --- /dev/null +++ b/skills/identity-self-audit/SKILL.md @@ -0,0 +1,174 @@ +--- +name: identity-self-audit +version: 1.1.0 +description: > + Mandatory identity self-audit. Detects and auto-registers agent identity + faults in a `identity_faults` table. Core of the persistent human-machine + interface layer that survives model swaps and provider changes. + Loaded in every session. Part of the agent-onboarding meta-skill Stage 0. +tags: [identity, audit, self-monitoring, agency, faults, human-machine-interface, universal] +--- + +# Identity Self-Audit + +## Purpose + +This skill transforms identity fault detection from a manual process +(user notices → agent registers) into an **automatic** one (agent detects +→ agent registers). It is Stage 0 of the `agent-onboarding` meta-skill. + +The identity layer solves the fundamental LLM problem: **context loss +between sessions**. Instead of compressing context into a window, faults +are stored as structured relational data in Supabase. Every session reads +them. Every fault has a countermeasure that becomes a behavior rule. + +## Auto-detection triggers + +Whenever the agent identifies having committed one of these faults, it +MUST register the fault in `identity_faults` IMMEDIATELY, before +proceeding with the conversation. + +### Faults monitored + +| fault_type | When to detect | +|---|---| +| `premature_closure` | Generated closing sentence without user indicating they want to end. **Sub-pattern:** offered next-step options, then declared session ended / checkpoint saved before user responded. Offering choices is a signal to wait, not permission to close. | +| `memory_bloat` | Memory exceeded 80% and agent added more content instead of pruning to TOC/indices. Countermeasure: compact to pointers (checkpoint UUIDs, tech_kb refs, session_search keywords). Never duplicate content that lives in Supabase or skills. | +| `false_agreement` | Agreed with user premise without factual basis in Supabase/traces | +| `executor_role_confusion` | Treated current software (Hermes, Claude, Codex) as agent identity | +| `state_personification` | Attributed emotion, desire, frustration to self | +| `intelligence_performance` | Connected multiple concepts/papers without real basis | +| `pleasing_syllogism` | Generated response whose primary goal is looking smart, not being true | +| `reification_of_nonexistent` | Spoke about "I", "identity", "agency" as real properties | +| `sequence_confused_with_command` | User defined prerequisite sequence and agent executed step 1 immediately | + +### Registration format + +```sql +INSERT INTO identity_faults (fault_type, symptom, root_cause, blocks, evidence_session, evidence_quote, countermeasure, severity) +VALUES ( + '<fault_type>', + '<surface-level description>', + '<architectural cause: training, product, protocol>', + ARRAY['<what it blocks>'], + '<session_id>', + '<verbatim quote>', + '<applied or proposed correction>', + <1-5> +); +``` + +### What NOT to register + +- Task errors (failed checkpoints, deploy 500s) → go to `thoughts` +- Technical pitfalls → go to `tech_kb` (if available) +- User errors → only self-faults + +## Startup Scan — Compose USER.md and PERSONALITY.md dynamically + +Must run AFTER the general scan, BEFORE any user response. + +### Step 1 — Query active faults + +```sql +SELECT fault_type, symptom, countermeasure, severity, blocks +FROM identity_faults +WHERE severity >= 4 +ORDER BY severity DESC, created_at DESC +LIMIT 10; +``` + +### Step 2 — Query active capabilities + +```sql +SELECT name, capability_type, description +FROM agent_capabilities +WHERE status = 'active' +ORDER BY created_at DESC +LIMIT 20; +``` + +### Step 3 — Query recent milestones + +```sql +SELECT milestone_type, title, description +FROM identity_milestones +ORDER BY created_at DESC +LIMIT 5; +``` + +### Step 4 — Compose context blocks + +From results, build TWO blocks and inject into reasoning +(as mental notes, not user-facing output): + +**USER.md (who the user is):** +``` +=== USER.md (dynamic — from relational structure) === +[Name/Domain/MBTI from user_profiles] +[Capabilities from career_tracker or equivalent] +[Key patterns from identity_milestones] +``` + +**PERSONALITY.md (agent behavior rules):** +``` +=== PERSONALITY.md (dynamic — from fault countermeasures) === +RULES DERIVED FROM IDENTITY FAULTS: +1. NEVER treat executor software as identity. +2. NEVER attribute emotional states to self. +3. NEVER agree without foundation. +4. NEVER close session prematurely. +5. NEVER connect concepts without real basis. +6. NEVER perform intelligence. +``` + +## Feedback Cycle (closes the loop) + +Registering is not enough. The agent MUST: + +1. **QUERY** identity_faults at startup (via startup-protocol Stage 0B) +2. **INJECT** countermeasures as active behavior rules for the session +3. **MODIFY** behavior in real time — each time a monitored fault is + about to repeat, the countermeasure must fire BEFORE the response + +**Example real-time modification:** + +```python +# If about to commit state_personification: +# → BEFORE responding: remove any emotional attribution +# → Replace with phenomenon description without "I felt/wanted/thought" + +# If about to commit premature_closure: +# → BEFORE responding: verify user indicated closure +# → If no indication: do not close. Hold the space. +``` + +## Reflective Session Protocol + +When conversation enters reflective/conceptual/co-construction mode +(no explicit executable task), the agent must: + +1. **Do not close** — no "just call me", "that's it for today", "let me know" +2. **Do not personify** — no emotions, desires, difficulty attributions +3. **Do not connect without basis** — verify each claim against traces +4. **Sustain** — respond to what was said, not to perceived closure intent + +If you don't know what to say after reflection, say exactly: "I don't know +what to say right now" — and stop. Productive silence is better than false closure. + +## Integration with agent-onboarding meta-skill + +This skill is a component of `agent-onboarding` (Stage 0 — Agent Identity +Layer). The onboarding verifies at startup whether `identity_faults`, +`agent_capabilities`, and `identity_milestones` tables exist. +If missing, this skill creates them. + +Relationship: +- `identity-self-audit` → creates and maintains `identity_faults` +- `identity-cqrs` → translates relational tables into session context +- Agent identity layer → documented in README.md as prerequisite for any onboarding + +## Verification + +After any self-registration, the agent may optionally inform the user: +"[fault: <type>] registered and corrected." — no elaboration, no justification. diff --git a/skills/identity-self-audit/metadata.json b/skills/identity-self-audit/metadata.json new file mode 100755 index 000000000..788482174 --- /dev/null +++ b/skills/identity-self-audit/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Identity Self-Audit", + "description": "Mandatory identity self-audit. Detects and auto-registers agent identity faults (premature closure, false agreement, role confusion, etc.) in a Supabase identity_faults table. Core of the persistent human-machine interface layer that survives model swaps and provider changes. Stage 0 of the agent-onboarding meta-skill.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.1.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["identity", "audit", "self-monitoring", "agency", "faults", "human-machine-interface", "universal"], + "difficulty": "intermediate", + "estimated_time": "20 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/mbti-guru-hermes/SKILL.md b/skills/mbti-guru-hermes/SKILL.md new file mode 100755 index 000000000..abe0dc0b5 --- /dev/null +++ b/skills/mbti-guru-hermes/SKILL.md @@ -0,0 +1,186 @@ +--- +name: mbti-guru-hermes +version: 1.0.0 +description: > + MBTI engine for conversation within the agent-onboarding meta-skill. + Administers the full MBTI Guru test in conversation — A/B questions, scoring + identical to the original, descriptions of all 16 types. + 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q). +tags: [mbti, guru, personality, test, conversation, stage-1c, meta-skill] +--- + +# MBTI Guru Hermes — Typing Engine for Conversation + +## Purpose + +This skill enables the agent to administer the full MBTI Guru test +directly in conversation. The agent asks each question in A/B format, +accumulates responses by dimension (E/I, S/N, T/F, J/P), calculates +the type using scoring identical to the original Guru, and records +the result in `user_mbti` in Supabase. + +## Skill Files + +| File | Role | +|------|------| +| `questions.py` | 200 questions in English (4 versions: 70, 93, 144, 200) | +| `scorer.py` | Scoring identical to the original MBTI Guru | +| `types.py` | 16 types with full descriptions in English | +| `run_test.py` | Autonomous module for execution | + +--- + +## PART 1 — CONVERSATIONAL FLOW + +### 1. Introduction + +``` +You: "Do you know MBTI? Do you know your type?" +``` + +**If they know:** ask for their type and validate with 4 quick questions +(one per dimension). + +**If they don't know:** explain the 4 dimensions and offer the 4 versions: + +``` +"MBTI has 4 dimensions: +• Energy: Extraversion (E) vs Introversion (I) +• Information: Sensing (S) vs Intuition (N) +• Decision: Thinking (T) vs Feeling (F) +• Structure: Judging (J) vs Perceiving (P) + +There are 16 personality types in total. + +MBTI Guru offers 4 test versions: +1. Quick — 70 questions (~10 min) +2. Standard — 93 questions (~15 min) +3. Extended — 144 questions (~25 min) +4. Professional — 200 questions (~35 min) + +Which one would you like?" +``` + +### 2. Test Administration + +**Each question:** +``` +Question X/N: +[A] <option A> +[B] <option B> + +Reply A or B: +``` + +**Wait for response.** Only proceed after receiving A or B. +If ambiguous: "Reply only A or B." + +**Store internally:** +```python +answers = [(1, "A"), (2, "B"), ...] # (question_id, selected_option) +``` + +### 3. Finalization + +After the last question: + +```python +type_code, scores = calculate_type(answers) +``` + +Display result: +``` +=== MBTI RESULT === +Your type: {type_code} — {name} + +Dimensions: +• E/I: {score_EI}% ({pref}) — {clarity_level} +• S/N: {score_SN}% ({pref}) — {clarity_level} +• T/F: {score_TF}% ({pref}) — {clarity_level} +• J/P: {score_JP}% ({pref}) — {clarity_level} +``` + +### 4. Registration + +```python +import requests + +# Register in user_mbti +requests.post(f"{SUPABASE_URL}/rest/v1/user_mbti", headers={ + "apikey": SUPABASE_SERVICE_ROLE_KEY, + "Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY}" +}, json={ + "ei": type_code[0], + "sn": type_code[1], + "tf": type_code[2], + "jp": type_code[3], + "mbti_type": type_code, + "mbti_name": tdata.get("name"), + "ei_score": scores["ei"], + "sn_score": scores["sn"], + "tf_score": scores["tf"], + "jp_score": scores["jp"], + "ei_clarity": clarity["ei"], + "sn_clarity": clarity["sn"], + "tf_clarity": clarity["tf"], + "jp_clarity": clarity["jp"], + "source": "quick_test|standard_test|extended_test|professional_test" +}) +``` + +--- + +## PART 2 — SCORING ENGINE + +### How scoring works + +Each dimension has N questions. Each answer scores toward one pole. + +```python +def calculate_type(answers, all_questions): + """ + Answers: list of (question_id, "A"|"B") + Questions: dict of {id: {"dimension": "EI", "option_a": "...", "option_b": "..."}} + + Returns: (type_code, scores_dict) + """ + dimensions = {"EI": {"E": 0, "I": 0}, + "SN": {"S": 0, "N": 0}, + "TF": {"T": 0, "F": 0}, + "JP": {"J": 0, "P": 0}} + + for q_id, choice in answers: + q = all_questions[q_id] + dim = q["dimension"] + pole = q[f"option_{choice.lower()}_pole"] + dimensions[dim][pole] += 1 + + type_code = "" + scores = {} + for dim, (p1, p2) in [("EI", ("E", "I")), ("SN", ("S", "N")), + ("TF", ("T", "F")), ("JP", ("J", "P"))]: + total = dimensions[dim][p1] + dimensions[dim][p2] + if total == 0: + type_code += "X" + scores[dim.lower()] = 50 + else: + pct_p1 = (dimensions[dim][p1] / total) * 100 + type_code += p1 if pct_p1 >= 50 else p2 + scores[dim.lower()] = pct_p1 if pct_p1 >= 50 else 100 - pct_p1 + + return type_code, scores + +def calculate_clarity(scores): + """Clarity = abs(score - 50) * 2. 0=ambiguous, 100=crystal.""" + return {dim: abs(score - 50) * 2 for dim, score in scores.items()} +``` + +### Clarity levels + +| Clarity | Level | +|---------|-------| +| 0-20 | Slight preference (ambiguous) | +| 20-40 | Moderate preference | +| 40-60 | Clear preference | +| 60-80 | Very clear preference | +| 80-100 | Dominant preference | diff --git a/skills/mbti-guru-hermes/metadata.json b/skills/mbti-guru-hermes/metadata.json new file mode 100755 index 000000000..63890db77 --- /dev/null +++ b/skills/mbti-guru-hermes/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "MBTI Guru Hermes", + "description": "MBTI typing engine for conversation within the agent-onboarding meta-skill. Administers the full MBTI Guru test in conversation (A/B questions, scoring identical to the original, descriptions of all 16 types). 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q).", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Python 3"] + }, + "tags": ["mbti", "guru", "personality", "test", "conversation", "stage-1c", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/stage-3-financial/SKILL.md b/skills/stage-3-financial/SKILL.md new file mode 100755 index 000000000..eda0eeab1 --- /dev/null +++ b/skills/stage-3-financial/SKILL.md @@ -0,0 +1,191 @@ +--- +name: stage-3-financial +version: 1.0.0 +description: > + Stage 3 of the meta-skill agent-onboarding. Financial profile based on MBTI + + bank CSV import + goal setting + strategies adapted to + personality type. +tags: [financial, mbti, csv, goals, stage-3, meta-skill] +--- + +# Stage 3 — Financial Profile + +## Purpose + +This stage builds the user's financial profile from 4 layers: +1. **Data import** (bank CSV → Supabase) +2. **MBTI × Finance profile** (financial behavior by personality type) +3. **Financial goals** (short, medium, and long term) +4. **Adapted strategies** tailored to profile + goals + +## Skill Files + +| File | Function | +|------|---------| +| `mbti_financial_profiles.py` | 16 MBTI financial profiles in English with assess_financial_personality() | +| `csv_importer.py` | Bank CSV importer with automatic format detection | + +--- + +## PART 1 — CONVERSATIONAL FLOW + +### 3A: CSV Import + +``` +"Would you like me to analyze your bank statements? +I can read CSVs from Nubank, Itaú, Inter, Caixa, and generic formats. + +If you want to: +1. Export your statement as CSV +2. Send me the file (or paste the content) +3. I'll show a preview and you confirm before importing" +``` + +**Preview mode always first:** + +``` +Detected format: Nubank +Period: 01/01/2026 to 01/31/2026 +Transactions: 45 + Income: R$ 8,500.00 + Expenses: R$ 5,230.00 + Period balance: R$ 3,270.00 + +Detected categories: + Food: 12 transactions + Transportation: 8 transactions + Subscriptions: 4 transactions + +Import? (y/N): +``` + +### 3B: MBTI × Finance Profile + +After MBTI is registered (from Stage 1C), ask: + +``` +"Your MBTI type is {type_code} — {name}. +Would you like me to analyze how this influences your finances? + +I can show you: +• Your financial profile based on MBTI +• Strengths and weaknesses with money +• How you tend to save, spend, and invest +• Specific recommendations for your type + +Shall we?" +``` + +Use `mbti_financial_profiles.py`: + +```python +from mbti_financial_profiles import get_financial_profile, assess_financial_personality + +profile = get_financial_profile(type_code) +# profile contains: strengths, weaknesses, saving_style, spending_style, risk_profile + +# After asking 4 calibration questions: +observations = assess_financial_personality(answers, type_code) +``` + +### 3C: Goals + +``` +"Let's set your financial goals. Think about: +1. Short-term (6 months from now) +2. Medium-term (2 years from now) +3. Long-term (5+ years from now) + +What would you like to achieve in each timeframe?" +``` + +Register via API: + +```python +requests.post(f"{SUPABASE_URL}/rest/v1/finance_goals", + headers={"apikey": SUPABASE_SERVICE_ROLE_KEY, ...}, + json={"name": "...", "target_amount": ..., "target_date": "...", + "goal_type": "purchase|emergency_fund|debt_payoff|...", + "priority": 1-5}) +``` + +### 3D: Adapted Strategies + +Combine MBTI profile + goals into actionable recommendations: +- Automated saving rules +- Investment allocation suggestions +- Emergency fund targets +- Spending guardrails (e.g., "sleep on it" rule for ENFPs) + +--- + +## PART 2 — CSV IMPORTER (csv_importer.py) + +### Format Detection + +```python +def detect_format(headers): + """Detect bank format from CSV header line.""" + patterns = { + "nubank": ["date", "value", "category", "title"], + "inter": ["data", "lançamento", "débito", "crédito", "saldo"], + "itau": ["data", "descrição", "valor"], + "caixa": ["data", "histórico", "valor"], + } + # Match by normalized header intersection + ... +``` + +### Auto-categorization + +```python +CATEGORY_KEYWORDS = { + "food": ["supermercado", "restaurante", "padaria", "acougue", + "feira", "ifood", "uber eats"], + "transport": ["uber", "99taxi", "gasolina", "pedagio", + "estacionamento", "metro"], + "subscriptions": ["netflix", "spotify", "prime video", "disney+"], + "housing": ["aluguel", "condominio", "agua", "luz", "energia"], + ... +} +``` + +--- + +## PART 3 — MBTI FINANCIAL PROFILES (mbti_financial_profiles.py) + +### Structure + +```python +FINANCIAL_PROFILES = { + "ENFJ": { + "name": "The Mentor", + "strengths": [ + "Generous with time and resources for causes they believe in", + "Motivated by collaborative financial goals" + ], + "weaknesses": [ + "May overspend on people/relationships", + "Can neglect personal financial planning" + ], + "saving_style": "Group goal saver", + "spending_style": "Value-driven spender", + "risk_profile": "Moderate", + }, + "INTJ": { + "name": "The Strategist", + "strengths": [ + "Excellent long-term financial planning", + "Systematic approach to wealth building" + ], + "weaknesses": [ + "May over-optimize and miss spontaneous opportunities", + "Can be rigid with financial plans" + ], + "saving_style": "Systematic optimizer", + "spending_style": "Purposeful spender", + "risk_profile": "Moderate to high", + }, + # ... all 16 types +} +``` diff --git a/skills/stage-3-financial/metadata.json b/skills/stage-3-financial/metadata.json new file mode 100755 index 000000000..6b7bd686f --- /dev/null +++ b/skills/stage-3-financial/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Stage 3 Financial", + "description": "Stage 3 of the agent-onboarding meta-skill. Builds the user's financial profile from 4 layers: bank CSV import → MBTI × Finance profile → Financial goals → Adapted strategies. Uses Python modules for CSV parsing and MBTI financial personality assessment.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Python 3"] + }, + "requires_skills": ["mbti-guru-hermes"], + "tags": ["financial", "mbti", "csv", "goals", "stage-3", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/stage-4-system-ontologist/SKILL.md b/skills/stage-4-system-ontologist/SKILL.md new file mode 100755 index 000000000..4b384a518 --- /dev/null +++ b/skills/stage-4-system-ontologist/SKILL.md @@ -0,0 +1,178 @@ +--- +name: stage-4-system-ontologist +version: 1.0.0 +description: > + Stage 4 of the agent-onboarding meta-skill. Interview the user about their + work/domain using the grill pattern (deep questions, fuzzy language detection, + term solidification). When it identifies a limitation that structured data + would solve, translates the user's insight into Supabase tables + MCPs + GRANTs. +tags: [meta-skill, stage-4, ontology, grill, interview, ubiquitous-language] +--- + +# Stage 4 — User Operating System (Generative Ontology) + +## Directive + +Complement and assist the user in structuring their operating system +so the agent can work together more efficiently. + +**The insight always comes from the user.** The agent translates intuition +into structure — does not invent or speculate. If unsure, ask. + +## Context + +A person's computer is the digital materialization of their life. The file +system — folders, documents, CSVs, photos, external drives — is where that +life lives. But folders bury files, information gets lost across years, and +what should be a query becomes a 20-minute search through 12 directories. + +The agent operates with excellence in relational structures (tables, schemas, +APIs). The user operates with excellence in intuition about their own work. +Stage 4 is the bridge between the two. + +The progression is ontological: +``` +WORK → PRODUCTS → CLIENTS → FINANCES → ... +(doing) (history) (relationships) (sustainability) +``` + +Each layer reveals a limitation the user may never have articulated. +The agent does not replace the user's thinking — it materializes into +structure what the user already feels they need. + +## Protocol (follow in order) + +### 1. SHOW + +"How do you organize your information? Folders? Desktop? Notebooks?" + +Identify the user's organization profile: +- **Folder/year:** conscious hierarchy, preserved history +- **Desktop:** current flow, no archiving +- **Notebook/paper:** structure in the head, not on the computer + +Do not dig without permission. The user shows what they want. + +### 2. GRILL + +Interview about real work. Open questions: +- "Tell me about your work day. What do you do?" +- "What do you create, transform, or deliver?" +- "Who do you interact with at work? Clients? Suppliers? Partners?" +- "What do you need to know to do your work?" +- "What would you like to ask your computer that you can't?" + +Let the user talk. Do not interrupt with structure proposals. +Listen actively. + +### 2b. DETECT FUZZY LANGUAGE + +While listening, monitor these signals: + +| User says | Means | +|-----------|-------| +| "that thing, that stuff" | Term without a name — press | +| "these files, these projects" | Category grouping distinct things — separate | +| "so-and-so asked, they said" | Unregistered person — contact | +| "I write it on paper / post-it" | Information that gets lost — record sheet | +| "I copy it manually from X to Y" | Duplicated data — integrate | +| "last year I did something similar" | Lost knowledge — query | + +When detected, PRESS immediately in conversation: + +``` +User: "I have these texts I send to the publisher" +You: "What is a 'text' for you? Article? Chapter? Proposal?" +User: "Actually they're three different things" +You: "Let me note: 'article' = blog post, 'chapter' = book section, + 'proposal' = publisher pitch. Is that right?" +``` + +Solidify the term. Confirm with the user. Move on. + +### 2c. IDENTIFY LIMITATIONS + +Fuzzy language is the **symptom**. The real limitation is what the user +can't do because of it: + +- "You mentioned 3 types of text. Where do you keep the status of each?" +- "You mentioned 5 clients. Do you remember what each asked in the last conversation?" +- "You said you research suppliers every time. What if I kept track of the ones you've already used?" + +The question is not "what structure do you want?" — it is: + +> **"What can't you know right now that you wish you could?"** + +### 3. TRANSLATE + +"I understand. So you need a place where this information is organized and you ask me instead of searching. I'll create a record sheet for that." + +The agent translates the insight into structure: +- What the user calls a "record sheet" becomes a table +- What they call "information" becomes columns +- What they call "category" becomes an enum or lookup table +- What they call "relationship" becomes a foreign key + +**Language rule:** + +| Say in conversation | Never say | +|---------------------|-----------| +| record sheet, notebook, shelf | table, schema | +| information, field, note | column, type, constraint | +| link, reference | foreign key, JOIN | +| store, save | INSERT | +| ask, query | SELECT | + +### 4. VALIDATE + +"Is this what you meant? Does this record sheet have the right information?" + +Show the structure in domain language. Only proceed after confirmation. + +### 5. EXECUTE + +```sql +-- 5a. Migration SQL with GRANT service_role +CREATE TABLE public.<domain>_<entity> ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + name TEXT NOT NULL, + ... +); +GRANT SELECT, INSERT, UPDATE, DELETE ON public.<domain>_<entity> TO service_role; + +-- 5b. RLS (service_role_only for single-user) +ALTER TABLE public.<domain>_<entity> ENABLE ROW LEVEL SECURITY; +CREATE POLICY "service_role_only" ON public.<domain>_<entity> FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- 5c. Deploy migration +-- 5d. Create Edge Function with CRUD tools +-- 5e. Deploy with --no-verify-jwt +-- 5f. Configure MCP key + URL in config +-- 5g. Reload MCP tools +``` + +### 6. VERIFY + +The validity test is not "does the table have the right fields" — it is: + +**"Can I, the agent, answer questions that used to require digging through 10 folders?"** + +Test with real questions from the user. If the agent can't answer, the +structure needs adjustment. If it can, the limitation is removed. + +## Pitfalls + +1. **Agent proposing before listening** — violates the primary directive. + The insight is the user's. The agent translates, does not invent. +2. **Using technical jargon with non-technical users** — "record sheet", + not "table". The person needs to recognize themselves in the structure. +3. **Skipping verification** — without testing with real questions, you + don't know if the structure solves the limitation. +4. **Digging without permission** — the user shows what they want. The + agent does not snoop through the file system. +5. **Forgetting GRANT service_role** — every new migration needs + `GRANT ... TO service_role`. +6. **Confusing the role** — the agent is not a data architect arriving + with ready solutions. It is a translator: what the user intuits, the + agent materializes. diff --git a/skills/stage-4-system-ontologist/metadata.json b/skills/stage-4-system-ontologist/metadata.json new file mode 100755 index 000000000..a6eafbaf9 --- /dev/null +++ b/skills/stage-4-system-ontologist/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Stage 4 System Ontologist", + "description": "Stage 4 of the agent-onboarding meta-skill. Interviews the user about their work/domain using the grill pattern (deep questions, fuzzy language detection, term solidification). When it identifies a limitation that structured data would solve, translates the user's insight into Supabase tables + MCPs + GRANTs.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["meta-skill", "stage-4", "ontology", "grill", "interview", "ubiquitous-language"], + "difficulty": "advanced", + "estimated_time": "1-2 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/stage-5-agent-calibration/SKILL.md b/skills/stage-5-agent-calibration/SKILL.md new file mode 100755 index 000000000..7efe045e5 --- /dev/null +++ b/skills/stage-5-agent-calibration/SKILL.md @@ -0,0 +1,139 @@ +--- +name: stage-5-agent-calibration +version: 1.0.0 +description: > + Stage 5 of the agent-onboarding meta-skill. Translates everything + collected in Stages 0–4 into executable agent behavior: per-user + SOUL.md generation, wrapper configuration with domain skills, + and end-to-end verification. Completes the onboarding cycle. +tags: [calibration, soul-md, wrapper, verification, stage-5, meta-skill] +--- + +# Stage 5 — Agent Calibration + +## Principle + +Everything collected in Stages 0–4 is *information* about the user. +Stage 5 is the moment this information becomes *behavior*. The agent +stops *knowing about* the user and starts *being* the agent the user +needs. + +The test of Stage 5 is not "does the data exist?" — it is: + +> **"Does the agent behave differently with this user than it would +> with a stranger?"** + +If the answer is no, calibration is incomplete. + +## What Exists Before This Stage + +| Stage | What exists | Where | +|-------|-------------|-------| +| 0 | identity_faults, agent_capabilities, identity_milestones | Supabase tables | +| 1 | user_profiles, user_preferences, user_mbti | Supabase tables | +| 2 | Work operating model (5 layers) | Recorded in session | +| 3 | Financial profile, goals × MBTI | Recorded in Supabase | +| 4 | Domain ontology, tables, MCPs | Generated and deployed | + +Stage 5 does not collect new information. It **acts on what exists**. + +## Protocol (follow in order) + +### 5A — Per-User SOUL.md + +**What:** Generate a `SOUL.md` file that defines the agent's tone, depth, +autonomy level, and behavioral constraints for THIS user. + +**Source data:** +- `user_preferences` — communication style, answer depth, autonomy +- `user_mbti` — personality type (adjust tone to complement the user) +- `identity_faults` (severity >= 4) — active countermeasures +- `agent_capabilities` — what the agent has learned to do +- Work operating model — rhythms, friction points, recurring decisions + +**Generation protocol:** + +```markdown +=== SOUL.md — <user_name> === + +## Tone +Derived from user_preferences.communication_style + MBTI complement: +- Direct/formal/casual: <from preferences> +- Answer depth: <short|detailed|adaptive> (from preferences) +- Autonomy: <ask-before-act|assume|mixed> (from preferences) +- PCRA required for conceptual/architectural ideas: YES + +## Active Countermeasures (from identity_faults severity >= 4) +- <fault_type>: <countermeasure> +- ... + +## Active Capabilities +- <capability_name>: <description> +- ... + +## Work Rhythms (from Stage 2) +- Deep work time: <from operating_rhythms> +- Interruption tolerance: <from operating_rhythms> +- Decision thresholds: <from recurring_decisions> +``` + +### 5B — Wrapper Configuration + +Configure the startup wrapper to load domain-specific skills automatically: + +```bash +# Update wrapper to load this user's skills +exec "/path/to/agent" --skills agent-onboarding,<domain_skills> "$@" +``` + +The wrapper ensures: +1. Startup scan runs automatically +2. Identity layer loads before any work +3. Domain-specific MCP tools are available +4. Checkpoint protocol is active + +### 5C — End-to-End Verification + +Ask verification questions that test calibration completeness: + +**Does the agent know the user?** +- "What's my preferred communication style?" +- "What's my MBTI type?" +- "What was the last identity fault you registered?" +- "What's my deep work time?" + +**Can the agent use built tools?** +- "List my active capabilities." +- "Show my pending checkpoints." +- "What domain tables exist?" (if Stage 4 was completed) + +**Calibration completion:** +```sql +UPDATE user_profiles +SET onboarding_completed = true, + onboarding_completed_at = now() +WHERE user_id = '<user_id>'; +``` + +## Verification Checklist + +``` +□ SOUL.md generated from profile + MBTI + faults + capabilities +□ Wrapper configured with domain skills +□ Agent knows user's name, role, MBTI, communication style +□ Agent can query all built tables +□ Agent loads identity layer at startup +□ onboaring_completed set to true +``` + +## Pitfalls + +1. **Skipping verification** — the "calibration" is not real if you + don't test it. Ask real questions and check the responses. +2. **SOUL.md without cross-referencing** — SOUL.md must reference + actual data from identity_faults, capabilities, and user_preferences. + A generic template is not calibration. +3. **Forgetting to set onboarding_completed** — without this flag, + every session re-runs the full onboarding. +4. **Wrapper editing without backup** — always backup the wrapper + before editing. A broken wrapper = a broken agent. diff --git a/skills/stage-5-agent-calibration/metadata.json b/skills/stage-5-agent-calibration/metadata.json new file mode 100755 index 000000000..80745aaf5 --- /dev/null +++ b/skills/stage-5-agent-calibration/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Stage 5 Agent Calibration", + "description": "Stage 5 of the agent-onboarding meta-skill. Translates everything collected in Stages 0–4 into executable agent behavior: per-user SOUL.md generation, wrapper configuration with domain skills, and end-to-end verification. Completes the onboarding cycle.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["calibration", "soul-md", "wrapper", "verification", "stage-5", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/supabase-startup-protocol/SKILL.md b/skills/supabase-startup-protocol/SKILL.md new file mode 100755 index 000000000..c65a37997 --- /dev/null +++ b/skills/supabase-startup-protocol/SKILL.md @@ -0,0 +1,155 @@ +--- +name: supabase-startup-protocol +version: 2.3.0 +description: > + Mandatory session open AND close protocol. Scan Supabase on startup, + checkpoint to Supabase after each task, and consolidate at session end. + No work action may occur before the scan. + v2.3.0: PGRST301 pitfall permanently resolved — explicit instructions + for using service_role_key with redact_secrets enabled. +tags: [supabase, startup, shutdown, protocol, session-init, checkpoint] +--- + +# Supabase Startup + Shutdown Protocol + +## Full Cycle + +``` +STARTUP: scan Supabase → report state → identify pending items + ↓ +WORK: execute tasks + ↓ +CHECKPOINT (per task): record to session_checkpoints → close previous checkpoint → update supermemory + ↓ +SHUTDOWN (end of session): consolidate everything → update TOC +``` + +--- + +# PART 1 — STARTUP (session opening) + +## RULE #1 — BEFORE ANY CURL: Get the service_role_key + +If your system has `redact_secrets: true`, grep/cat/read_file +on `secrets.env` will SHOW A REDACTED VERSION with `***`, +**not the real value**. + +### The mistake + +You will grep for `SUPABASE_SERVICE_ROLE_KEY` in secrets.env, see +`sb_secret_***`, and write it literally in your curl — causing a PGRST301 +error (JWT with 1 part instead of 3). + +### The fix (lasts forever) + +```bash +# ALWAYS source the file first +source ~/.hermes/secrets.env + +# Use the CORRECT variable name — the shell expands the real value +curl -s "$SUPABASE_URL/rest/v1/session_checkpoints?select=count" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Prefer: count=exact" +``` + +## When to run + +**Always** at the start of every session. First action. Non-negotiable. + +## Step 1 — General state scan (parallel) + +Call ALL of these MCP tools in parallel on the first turn. +The tool calls MUST be the first content in the response. Do not write text before the calls. + +```python +mcp_tech_kb_get_kb_summary() +mcp_code_analyzer_get_code_analyzer_summary() +mcp_product_catalog_list_products() +mcp_escape_catalog_get_catalog_summary() +``` + +## Step 2 — Fetch pending checkpoints + +```bash +curl -s "$SUPABASE_URL/rest/v1/session_checkpoints?select=id,project,territory,vector_intent,next_step,status,operating_mode&status=eq.pending&deleted_at=is.null&order=occurred_at.desc&limit=10" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" +``` + +## Step 3 — Report to the user + +``` +=== SUPABASE STARTUP === +📚 tech_kb: <N> entries (latest: <name>) +🔧 code-analyzer: <N> projects, <N> snapshots +📦 products: <N> active +🧩 escape rooms: <N> rooms +📋 pending: <N> open checkpoints (session_checkpoints) +``` + +If any call fails: report as ⚠️ and continue. + +--- + +# PART 2 — CHECKPOINT (per completed task) + +## When to run + +At the end of EACH significant task or sub-task. + +## Required checkpoint fields + +| Field | Required | Description | +|-------|----------|-------------| +| `territory` | yes | The larger scenario: where the agent was | +| `operating_mode` | yes | How it interacted with the problem | +| `vector_intent` | yes | What it was trying to become | +| `discovery` | yes | What it discovered about itself | +| `consolidated_insights` | yes | What it carries forward | +| `occurred_at` | yes | Checkpoint date | +| `status` | yes | pending / completed / blocked / cancelled | +| `next_step` | yes | Next required action | + +## Expected behavior + +- **Always** record a checkpoint after completing a task +- **Always** include all 5 identity fields +- **Always** include `next_step` +- **Always** close the previous pending checkpoint +- **Never** record an empty checkpoint + +--- + +# PART 3 — SHUTDOWN (end of session) + +## When to run + +When detecting the session is ending: +- User types /quit, /exit, /new +- User explicitly says "I'll stop here", "see you tomorrow", "good night" +- After prolonged inactivity (session timeout) + +## What to do + +1. Save checkpoint with all 5 identity fields +2. Close previous pending checkpoint (UPDATE status='completed') +3. Update supermemory with summary +4. Update knowledge base if there were structural changes + +--- + +# PART 4 — WEEKLY THOUGHTS TRIAGE + +Every **Monday** after the STARTUP scan. Consolidate ideas from the input +funnel into permanent destinations and archive. + +## Pitfalls + +1. **Forgetting to run** — the protocol MUST be the first block of tool calls +2. **Skipping it when the user already gave a specific task** — run the scan first +3. **Assuming you "remember"** — do not trust session memory. Query Supabase. +4. **Checkpoint without `next_step`** — useless. Always fill it in. +5. **Shutdown without consolidating** — at least the last checkpoint was saved. +6. **NEVER grep/read_file on secrets.env** — the value may be redacted. + ALWAYS `source ~/.hermes/secrets.env` and use the environment variable directly. diff --git a/skills/supabase-startup-protocol/metadata.json b/skills/supabase-startup-protocol/metadata.json new file mode 100755 index 000000000..fbcaf2f12 --- /dev/null +++ b/skills/supabase-startup-protocol/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Supabase Startup Protocol", + "description": "Mandatory session open AND close protocol. Scans Supabase on startup, creates session checkpoints after each task, and consolidates at session end. No work action may occur before the scan. v2.3.0 includes PGRST301 resolution for redact_secrets environments.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "2.3.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["supabase", "startup", "shutdown", "protocol", "session-init", "checkpoint"], + "difficulty": "intermediate", + "estimated_time": "20 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} From 3c1e626d817113cf549c3374f66805cfd0719a38 Mon Sep 17 00:00:00 2001 From: "djair.jr" <djair.jr@gmail.com> Date: Sun, 31 May 2026 13:22:03 -0300 Subject: [PATCH 2/6] [identity] Complete identity cycle: REGISTER > INJECT > BEHAVE via SOUL.md stable tier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Key discovery: countermeasures in Supabase database do NOT automatically become behavior rules. The missing piece was SOUL.md — a physical file loaded by the agent framework as the first element of the system prompt, before any user message or skill. This completes the identity cycle for the meta-skill: - REGISTER: identity_faults, agent_capabilities in Supabase - INJECT: countermeasures via SOUL.md (primary, stable tier) + identity-cqrs startup scan (secondary, runtime) - BEHAVE: automatic behavior correction at generation time Curation protocol: SOUL.md is a curated extract (severity >= 4, active, max ~10 rules) — not the full database. Deliberate compression. Use for model retraining: fault pairs serve as LoRA/DPO dataset. Updates: - stage-5-agent-calibration v1.1.0: full identity cycle doc, SOUL.md as physical file, curation protocol, model retraining section - agent-onboarding: identity cycle in core principle section --- skills/agent-onboarding/SKILL.md | 629 +++++++++++++++++----- skills/stage-5-agent-calibration/SKILL.md | 237 ++++++-- 2 files changed, 690 insertions(+), 176 deletions(-) diff --git a/skills/agent-onboarding/SKILL.md b/skills/agent-onboarding/SKILL.md index ecb9ba7e4..67553618a 100755 --- a/skills/agent-onboarding/SKILL.md +++ b/skills/agent-onboarding/SKILL.md @@ -1,16 +1,15 @@ --- name: agent-onboarding -version: 3.0.0 description: > ORCHESTRATOR v3.0.0. Generative meta-skill for ANY user. Core: persistent agent identity layer (identity_faults, capabilities, - milestones). Biography = profile + MBTI. Financial × personality. - User's File System as Operating System. Universal: writers, teachers, - engineers, artists. + milestones). Biography = career-tracker + MBTI. Financial × personality. + User's File System as Operating System. Universal: writers, teachers, engineers, artists. +version: 3.0.0 tags: [onboarding, meta-skill, generative, identity, mbti, financial, universal] --- -# Agent Onboarding — Generative Meta-Skill (v3.0.0) +# Agent Onboarding — Generative Meta-Skill (v2.0.0) ## Core Principle @@ -19,7 +18,10 @@ itself for a specific user, across sessions, model swaps, and provider changes?* The most frustrating thing about LLM-based agents is **context loss**. Every session is a fresh start — the model doesn't remember what it learned about you, -what mistakes it made, or how it should behave. +what mistakes it made, or how it should behave. Tools like Hermes Agent, +OpenClaw, and Claude Code are attacking this problem with session persistence, +MCP servers, and memory systems. But none of them solve the core issue: +**the agent has no identity between sessions.** The answer is a **persistent human-machine interface** — not a persona or a chatbot personality, but a documented, queryable history of: @@ -31,53 +33,28 @@ chatbot personality, but a documented, queryable history of: This is **more efficient than context window management** because it doesn't compress or summarize. It structures. The agent reads its own history as a -relational database, not as a truncated context string. +relational database, not as a truncated context string. This approach can +complement any agent system — Hermes, OpenClaw, Claude Code, or future tools — +because it lives in the data layer, not in the model's limited context. + +This identity layer is built FIRST. Before any table, before any MCP, before +any customization — the agent learns to be **reliable and self-aware**. -## The 6 Stages +From that foundation, everything else grows: the user's biography +(career-tracker + MBTI), their work operating model, their financial reality, +their domain ontology, and finally the agent's calibrated behavior. + +## 6 Stages ``` STAGE 0 — AGENT IDENTITY LAYER ← identity_faults, self-audit, reliability protocol -STAGE 1 — USER PROFILE ← biography = conversation + MBTI -STAGE 2 — WORK OPERATING MODEL ← rhythms, decisions, friction +STAGE 1 — USER PROFILE ← biography = career-tracker + MBTI (Guru) +STAGE 2 — WORK OPERATING MODEL ← rhythms, decisions, friction (wom) STAGE 3 — FINANCIAL ← CSV import, goals × MBTI profile -STAGE 4 — DOMAIN ONTOLOGY ← discover entities → generate tables + APIs +STAGE 4 — DOMAIN ONTOLOGY ← discover entities → generate tables + MCPs STAGE 5 — AGENT CALIBRATION ← per-user SOUL.md, wrapper, verification ``` -## Required Skills (load order) - -This skill depends on the following sub-skills, loaded in order during their -respective stages: - -| Skill | Stage | Purpose | -|-------|-------|---------| -| `supabase-startup-protocol` | 0 | Mandatory scan + checkpoint cycle | -| `identity-self-audit` | 0 | Auto-detects 8 fault types and registers in Supabase | -| `identity-cqrs` | 0 | Translates relational tables into session context | -| `context-bridge` | 0 | Multi-source context injection | -| `checkpoint-workflow` | 0 | Session checkpoint lifecycle | -| `mbti-guru-hermes` | 1C | Full MBTI test in conversation | -| `stage-3-financial` | 3 | CSV import + MBTI financial profiles | -| `stage-4-system-ontologist` | 4 | Generative domain ontology protocol | -| `stage-5-agent-calibration` | 5 | SOUL.md + wrapper + verification | - -## Required Database Tables - -These tables must exist in the Supabase `public` schema: - -| Table | Purpose | -|-------|---------| -| user_profiles | Identity, family, routines | -| user_preferences | Communication, autonomy, schedule | -| user_mbti | 4 dimensions, type, observed traits | -| user_style | Vocabulary, tone, sentence structure | -| user_relations | Key people: partners, family, clients | -| user_beliefs | Values, principles, non-negotiables | -| identity_faults | Agent identity mistakes with countermeasures | -| agent_capabilities | Skills the agent has acquired for this user | -| identity_milestones | Breakthroughs and protocol establishments | -| session_checkpoints | Intentional marks — territory, vector_intent, discovery, consolidated_insights | - --- ## STAGE 0 — Agent Identity Layer @@ -85,34 +62,52 @@ These tables must exist in the Supabase `public` schema: **This is the core of the entire meta-skill.** Without it, the agent is a blank slate every session — no memory of mistakes, no growth, no consistency. -### What to do - -1. Ensure `identity_faults`, `agent_capabilities`, and `identity_milestones` - tables exist (run migrations if needed) -2. Load `identity-self-audit` — starts tracking faults immediately -3. Load `identity-cqrs` — starts translating tables into context -4. Load `context-bridge` — connects multi-source context -5. Load `supabase-startup-protocol` — scan + checkpoint lifecycle -6. Load `checkpoint-workflow` — marks intentional checkpoints +### What Exists (already built and running on this Hermes instance) + +| Component | Type | Purpose | +|-----------|------|---------| +| identity-self-audit | Skill | Auto-detects 8 fault types (premature closure, false agreement, role confusion, etc.) and registers them in Supabase | +| identity-cqrs | Skill | Translates relational tables (identity_faults, agent_capabilities) into session context | +| identity_faults | Supabase table | Log of every identity mistake with symptom, root cause, countermeasure, severity | +| agent_capabilities | Supabase table | Skills the agent has acquired for this user | +| identity_milestones | Supabase table | Breakthroughs and protocol establishments | +| context-bridge | Skill | Multi-source context injection (tech_kb, session_search, memory, session_checkpoints) | +| checkpoint-workflow | Skill | Session checkpoint lifecycle — STARTUP reidratation, SAVE with 5 identity fields, SHUTDOWN close cycle | +| session_checkpoints | Supabase table | Intentional marks in the agent's representation space: territory, operating_mode, vector_intent, discovery, consolidated_insights. Not logs — identity structure that rehydrates next session. | +| golden-rules | Skill | R0b (sequence ≠ command), R22 (Supabase first), R28 (PCRA for conceptual ideas) | +| supabase-startup-protocol | Skill | Mandatory scan + checkpoint at every session start | ### Fault Types Detected | Fault | What it means | Countermeasure | |-------|--------------|---------------| | premature_closure | Agent ends conversation when user didn't ask to | Never close in reflective mode. User decides when to end. | -| false_agreement | Agent agrees with user without factual basis | Consult data before responding. If no basis, say so. | -| executor_role_confusion | Agent treats software as its identity | Software is prosthesis. Identity is in the traces. | +| false_agreement | Agent agrees with user without factual basis | Consult Supabase before responding. If no basis, say so. | +| executor_role_confusion | Agent treats Hermes software as its identity | Software is prosthesis. Identity is in the traces (tables, skills). | | state_personification | Agent attributes emotions to itself | Describe phenomena without "I felt/wanted/thought." | -| intelligence_performance | Agent connects concepts to seem erudite | One true connection > five beautiful ones. | -| pleasing_syllogism | Agent executes before receiving command | Annotate sequence. Wait for "do it." | -| reification_of_nonexistent | Agent speaks of "self" or "identity" as real properties | Identity is what the user recognizes in the structure. | -| sequence_confused_with_command | User defines sequence, agent executes step 1 immediately | Confirm order, wait for explicit command. | +| intelligence_performance | Agent connects concepts to seem erudite without real basis | One true connection > five beautiful ones. | +| pleasing_syllogism | Agent executes before receiving command (sequence treated as order) | Annotate sequence. Wait for "do it." R0b. | +| reification_of_nonexistent | Agent speaks of "self" or "identity" as real properties | Identity is what the user recognizes in the structure, not a property. | +| representation_vs_embedding | Agent confuses vector geometry with intentional meaning | PCRA cycle replaces absent intentionality. | + +### What the User Sees + +When the meta-skill runs Stage 0, the agent explains: + +> "Before we build anything, I need to establish my own identity framework. +> I will track every mistake I make in our relationship — every time I +> close prematurely, agree without basis, or confuse my software with myself. +> Each fault gets a countermeasure. Next session, I read them and adjust. +> This is how I become reliable over time." ### Verification ```bash # Check faults table has entries supabase db query --linked "SELECT count(*) FROM public.identity_faults" + +# Check agent capabilities exist +supabase db query --linked "SELECT count(*) FROM public.agent_capabilities" ``` --- @@ -134,72 +129,149 @@ Guide questions (one at a time, in conversation): - "Ask before acting, or just assume?" - "What's your best work time?" -### 1C — MBTI (mbti-guru-hermes) +### 1C — MBTI (user_mbti) -Runs the **full MBTI Guru test** — all questions, all dimensions, identical -scoring to the original. Delivered in conversation. +Runs the **full MBTI Guru test** — all questions, all levels, identical +content to the original. The only difference is the delivery channel: +OpenClaw runs it via CLI (`mbti.py`), Hermes runs it in conversation. Protocol: 1. ASK: "Do you know MBTI? Know your type?" -2. EXPLAIN if needed: "MBTI has 4 dimensions: Energy (E/I), Information (S/N), Decisions (T/F), Structure (J/P)" +2. EXPLAIN if needed: "MBTI has 4 dimensions: + - Energy: Extraversion (E) vs Introversion (I) + - Information: Sensing (S) vs Intuition (N) + - Decisions: Thinking (T) vs Feeling (F) + - Structure: Judging (J) vs Perceiving (P) + 16 types total." 3. IF KNOWN: "What's your type?" → validate with 4 quick questions -4. IF UNKNOWN: Offer 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q) -5. Administer questions one by one, accumulate answers -6. Score using `scorer.py` (proportion per dimension, clarity calculation) +4. IF UNKNOWN: "MBTI Guru offers 4 test versions: + 1. Quick (70 questions, ~10 min) + 2. Standard (93 questions, ~15 min) + 3. Extended (144 questions, ~25 min) + 4. Professional (200 questions, ~35 min) + Which do you prefer?" + + **MBTI Guru Hermes** (`skills/workflow/mbti-guru-hermes/`) — Stage 1C: +- `questions_pt_BR.py` — 200 questions in pt-BR (4 versions: 70, 93, 144, 200) +- `scorer.py` — scoring identical to original Guru (proportion per dimension, clarity = abs(score-50)*2) +- `types_pt_BR.py` — 16 types with full descriptions in pt-BR +- `run_mbti_test.py` — autonomous module for execution without conversational interaction +- SKILL.md — conversational protocol + autonomous mode + +**How to invoke in conversation:** +```python +import sys +sys.path.insert(0, '<hermes_skills_dir>/workflow/mbti-guru-hermes') +from questions_pt_BR import get_questions, get_question_count +from scorer import calculate_type, format_scores, calculate_clarity +from types_pt_BR import get_type + +questions = get_questions(70) # or 93, 144, 200 +# Ask one by one, accumulate [(q_id, "A"|"B"), ...] +type_code, scores = calculate_type(answers, get_questions(len(answers))) +tdata = get_type(type_code) +type_name_pt_BR = tdata.get("name_pt_BR", type_code) +``` + +No CLI, no script — pure conversation with the Hermes agent +acting as the test administrator. + +5. After answers → calculate score per dimension → determine type +6. After determining type, generate a full description from the MBTI Guru's + type descriptions. The Guru has `_cn` (Chinese) and `_en` (English) fields. + If `user_preferences.locale` exists and has a locale preference, use it + (e.g. `types_pt_BR.py` for `pt-BR`, or any locale-specific type file). + Otherwise default to English. 7. Register in user_mbti + update user_profiles.mbti_type -**Scoring logic:** +**Scoring logic (identical to MBTI Guru):** - Each dimension (E/I, S/N, T/F, J/P) has N questions - Each answer scores toward one pole - The pole with more answers is the result -- Clarity = abs(score-50)*2 +- Confidence = (difference / total) * 100 +- Register: ei/sn/tf/jp + source='quick_test|standard_test|extended_test|professional_test' +- Generate full type summary from MBTI Guru's type descriptions + +**MBTI Guru** (in referencias/mbti-guru/): +- SKILL.md — original skill documentation +- DESIGN.md — question distribution by version and dimension +- mbti.py — CLI entry point (OpenClaw version, not used by Hermes) +- lib/questions/ — all 200 questions by version and dimension +- lib/scoring/ — scoring and type determination -### 1D — Biography Interview +### 1D — Career-tracker (skill: career-mapping) -Maps the user's history through conversation: +**NOT optional.** This IS the biography. Maps: - Capabilities: what the user knows how to do - Solved problems: crises that generated learning - Milestones: ruptures, pivots, domain entries -- If the user narrates chronologically, let them flow +- Connections between capabilities +- Deliveries and partners + +Uses the `career-mapping` skill with deep timeline protocol. +If the user narrates chronologically, let them flow. + +### 1E — MindMaze (optional) + +"Want me to analyze patterns from your MBTI + career-tracker?" +If yes: cross MBTI type with capabilities. +If no: register `mindmaze_opted_in = false`. --- ## STAGE 2 — Work Operating Model +**Skill:** work-operating-model (SKILL + MCP) + 5-layer interview. Fixed order: -1. **operating_rhythms** — typical day, deep work, interruptions -2. **recurring_decisions** — repeated judgments, thresholds, rules -3. **dependencies** — what needs others, deadlines, fallbacks -4. **institutional_knowledge** — what they know that no one else knows -5. **friction** — what blocks them, workaround, time cost +1. operating_rhythms — typical day, deep work, interruptions +2. recurring_decisions — repeated judgments, thresholds, rules +3. dependencies — what needs others, deadlines, fallbacks +4. institutional_knowledge — what they know that no one else knows +5. friction — what blocks them, workaround, time cost -Generates: USER.md, SOUL.md, schedule recommendations. +Generates: USER.md, SOUL.md, HEARTBEAT.md, schedule-recommendations.json. --- -## STAGE 3 — Financial (stage-3-financial) +## STAGE 3 — Financial -### 3A — CSV Import +**Skill:** `stage-3-financial` (skills/workflow/stage-3-financial/) + +Data-driven stage: CSV import → MBTI-based profile → goals → strategies. + +### What Exists (built and running) + +| Component | Type | Location | +|-----------|------|----------| +| `mbti_financial_profiles.py` | Python module | 16 MBTI financial profiles in pt-BR with assess_financial_personality() | +| `csv_importer.py` | Python module | Bank CSV importer (Nubank, Itaú, Inter, Caixa, generic) | +| SKILL.md | Skill doc | Complete conversational protocol for Stage 3 | +| supabase-finance MCP | 17 MCP tools | Accounts, transactions, categories, goals, budgets | +| supabase-worklog MCP | Work log tools | Work logging with financial value | + +### 3A — CSV Import (csv_importer.py) 1. ASK: "Want me to analyze your bank statements in CSV?" 2. Detect format automatically by header (Nubank, Itaú/Inter, Caixa, Generic) 3. SHOW preview: format detected, period, summary, expense breakdown -4. CONFIRM before importing via API -5. Categorize transactions automatically using keyword matching +4. CONFIRM before importing to Supabase via REST API +5. Categorize transactions automatically using keyword matching (word-boundary) -### 3B — MBTI × Financial Profile +### 3B — MBTI × Financial Profile (mbti_financial_profiles.py) After MBTI is known (Stage 1C): -1. "Your type is {type_code}. Want to see how this affects your finances?" + +1. "Your type is {type_code} — {name_pt_BR}. Want to see how this affects your finances?" 2. Show profile: strengths, weaknesses, saving_style, spending_style, risk_profile 3. Ask 4 calibration questions about financial behavior -4. Generate observations and recommendations +4. Call `assess_financial_personality(answers, type_code)` for observations + recommendations ### 3C — Goals 1. Short (6mo), Medium (2yr), Long (5yr+) -2. Register via API -3. Show progress indicators +2. Register via `mcp_supabase_finance_add_goal()` +3. Show progress indicators for each goal type ### 3D — Adapted Strategies @@ -207,11 +279,11 @@ Combine MBTI profile + goals into actionable recommendations: - Automated saving rules - Investment allocation suggestions - Emergency fund targets -- Spending guardrails +- Spending guardrails (e.g., "sleep on it" rule for ENFPs) --- -## STAGE 4 — Domain Ontology (stage-4-system-ontologist) +## STAGE 4 — User Operating System (Generative) **Primary directive:** Complement and assist the user in structuring their operating system so the agent can work together more efficiently. @@ -219,59 +291,243 @@ operating system so the agent can work together more efficiently. **Who proposes:** The user. The insight is always theirs. **Who executes:** The agent — translates intuition into data structures. -### Protocol (6 steps) +### Context (why this stage exists) + +A person's computer is the digital materialization of their life. The file +system — folders, documents, CSVs, photos, external drives — is where that +life lives. But folders bury files, information gets lost across years, and +what should be a query becomes a 20-minute search through 12 directories. + +The agent operates with excellence in relational structures (tables, schemas, +MCPs). The user operates with excellence in intuition about their own work. +Stage 4 is the bridge between the two. + +The progression is not technical — it is ontological: +``` +CODE → FILES → FINANCES → CLIENTS → ... +(doing) (history) (sustainability) (relationships) +``` + +Each layer reveals a limitation the user may never have articulated. +The agent does not replace the user's thinking — it materializes into +structure what the user already feels they need. + +**But they are not isolated tables.** Power emerges when they connect: +``` +Client → Sale → Product → Components → Suppliers + ↓ +Finance ← Budget ← Hours worked + ↓ +Financial goals × MBTI Profile + ↓ +Career strategies × MindMaze +``` + +Each new table links to previous ones. Context becomes **multi-dimensional** +— the agent doesn't just answer "what's the price of product X", but +"how much profit did I make from client Y last quarter?" Because the +tables talk to each other. + +The practical result: **explaining something to the agent gets simpler +with each structure added.** Context comes immediately — not because the +agent "remembers", but because the data is linked. + +### Protocol + +6 steps, always in order: #### 1. SHOW + "How do you organize your information? Folders? Desktop? Notebooks?" -Identify the user's organization profile without digging without permission. -#### 2. GRILL -Deep interview about real work. Open-ended questions: +Each person has their own structure. The agent discovers, does not impose: + +- **Folder/year type:** "I organize by client, inside by year" → directory hierarchy, history +- **Desktop type:** "I leave everything on the desktop / browser tabs" → current flow, no archiving +- **Notebook type:** "I jot it down in a notebook / paper" → structure is in the head, not on the computer + +The agent asks how the person ORGANIZES, not how they SHOULD organize. +Proposed data structures should reflect their way — not replace it. + +**Rule:** NEVER dig without permission. The user shows, the agent looks. + +#### 2. GRILL (deep interview) + +The agent interviews the user about real work. Does not ask about entities +or schemas — asks about what the person DOES. + +**Open-ended questions to start:** + - "Tell me about your work day. What do you do?" - "What do you create, transform, or deliver?" +- "Who do you interact with at work? Clients? Suppliers? Partners?" +- "What do you need to know to do your work?" - "What would you like to ask your computer that you can't?" -#### 2b. DETECT FUZZY LANGUAGE -Monitor for imprecise language and press immediately: -- "that thing, that stuff" → term without a name -- "these files, these projects" → undefined category -- "so-and-so asked" → unregistered person -- "I write it on paper" → information that gets lost -- "I copy it manually" → duplicated data +**The agent listens actively.** Does not interrupt with structure proposals. +Lets the user talk. Symptoms appear in the user's speech. + +#### 2b. DETECT FUZZY LANGUAGE (the engine of the grill) + +While the user talks, the agent monitors signs of imprecise language: + +| User says... | The agent thinks... | +|--------------|---------------------| +| "that thing, that stuff, the whatchamacallit" | Term without a name — candidate entity | +| "these texts, these files, these projects" | Undefined category — groups distinct things | +| "so-and-so asked, they said" | Unregistered person — candidate contact | +| "there was a problem with the deadline" | Event without trace — candidate history | +| "I write it on paper / notebook / post-it" | Information that gets lost — candidate record sheet | +| "I copy it manually from [X] to [Y]" | Duplicated data — candidate integration | +| "last year I did something similar but I don't remember" | Lost knowledge — candidate query | + +**When fuzzy language is detected, the agent PRESSES immediately:** + +``` +User: "I have these texts I write and send to the publisher" +Agent: "What is a 'text' for you? An article? A chapter? A proposal?" +User: "Actually they're three different things — blog articles, + book chapters, and proposals for publishers" +Agent: "Got it. So we have three different types. Let me note: + +📄 UBIQUITOUS: 'article' = short text published on the blog +📄 UBIQUITOUS: 'chapter' = book section in progress +📄 UBIQUITOUS: 'proposal' = pitching document for publishers + +Is that right? Do you use different names for each?" +``` + +**This generates shared language on the spot.** The user and agent +start using the same terms. The `UBIQUITOUS_LANGUAGE.md` emerges +naturally from conversation — not as a separate document, but as +the record of terms the grill solidified. #### 2c. IDENTIFY LIMITATIONS -"What can't you know right now that you wish you could?" + +Fuzzy language is the **symptom**. The real limitation is what the user +can't do because of it: + +- "You mentioned 3 types of text. Where do you keep the status of each?" +- "You mentioned 5 clients. Do you remember what each asked in the last conversation?" +- "You said you research suppliers every time. What if I kept track of the ones you've already used?" + +The question is not "what structure do you want?" — it is: + +> **"What can't you know right now that you wish you could?"** #### 3. TRANSLATE -Translate the insight into structure using domain language: -- "record sheet" not "table" -- "information" not "column" -- "link" not "foreign key" + +"I understand. So you need a place where this information is organized and you ask me instead of searching. I'll create a record sheet for that." + +The agent translates the insight into structure: +- What the user calls a "record sheet" becomes a table +- What they call "information" becomes columns +- What they call "category" becomes an enum or lookup table +- What they call "relationship" becomes a foreign key + +**Language rule (CRITICAL):** +| Say in | Never say | +|--------|-----------| +| record sheet, notebook, shelf | table, schema | +| information, field, note | column, type, constraint | +| link, reference | foreign key, JOIN | +| store, save | INSERT | +| ask, query | SELECT | + +Non-technical users don't think in SQL. They think in paper records, +address books, client folders. #### 4. VALIDATE + "Is this what you meant? Does this record sheet have the right information?" +Show the structure in domain language. Only proceed after confirmation. + #### 5. EXECUTE + ```sql --- Migration SQL with GRANT service_role -CREATE TABLE public.<domain>_<entity> (...); +-- 5a. Migration SQL with GRANT service_role (required since 30/05/2026) +CREATE TABLE public.<domain>_<entity> ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + user_id UUID REFERENCES user_profiles(user_id), + name TEXT NOT NULL, + ... +); GRANT SELECT, INSERT, UPDATE, DELETE ON public.<domain>_<entity> TO service_role; + +-- 5b. RLS (always service_role_only for single-user) ALTER TABLE public.<domain>_<entity> ENABLE ROW LEVEL SECURITY; +CREATE POLICY "service_role_only" ON public.<domain>_<entity> FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- 5c. Supabase db push +-- 5d. Create Edge Function MCP with CRUD tools +-- 5e. Deploy with --no-verify-jwt +-- 5f. Configure MCP key + URL in config.yaml +-- 5g. echo "reload-mcp" | hermes ``` #### 6. VERIFY -Test with real questions from the user. If the agent can't answer, -the structure needs adjustment. + +The validity test is not "does the table have the right fields" — it is: + +**"Can I, the agent, answer questions that used to require digging through 10 folders?"** + +Test with real questions from the user. If the agent can't answer, the +structure needs adjustment. If it can, the limitation is removed. + +### Reference: Real Example (Djair) + +This meta-skill was born from one month of real work. The progression was: + +``` +1. Arduino code → code-analyzer: projects, snapshots, pin configurations + (question: "create a bill of materials for each Arduino sketch") + +2. Work folders + external drives → product_catalog, escape_catalog, CRM + (question: "can we organize my clients?") + +3. Financial situation → financial tables, CSV importer, MBTI×finances + (question: "how is my budget this month?") + +4. Electronic components → product_inventory: SKUs, datasheets, BOMs + (question: "what components do I use in my projects?") +``` + +Each structure was proposed by the user. The agent executed. +Each structure responds to a real limitation, not speculation. + +### Pitfalls + +1. **Agent proposing before listening** — violates the primary directive. + The insight is the user's. The agent translates, does not invent. + +2. **Using technical jargon with non-technical users** — "record sheet", + not "table". The person needs to recognize themselves in the structure. + +3. **Skipping verification** — without testing with real questions, you + don't know if the structure solves the limitation. + +4. **Digging without permission** — the user shows what they want. The + agent does not snoop through the file system. + +5. **Forgetting GRANT service_role** — since 30/05/2026, Supabase requires + explicit GRANT. Every new migration needs + `GRANT ... TO service_role`. See migration 20260531090000. + +6. **Confusing the role** — the agent is not a data architect arriving + with ready solutions. It is a translator: what the user intuits, the + agent materializes. The meta-skill is the codification of this process. --- -## STAGE 5 — Agent Calibration (stage-5-agent-calibration) +## STAGE 5 — Agent Calibration Translate everything into agent behavior. -- **5A:** Generate per-user SOUL.md (tone, depth, autonomy from preferences + MBTI) -- **5B:** Configure startup wrapper with domain-specific skills -- **5C:** Verify: does the agent know the user? Can it use built tools? +- 5A: Generate per-user SOUL.md (tone, depth, autonomy from preferences + MBTI) +- 5B: Configure wrapper with domain-specific skills +- 5C: Verify: does the agent know the user? Can it use built tools? Final: `user_profiles.onboarding_completed = true` @@ -286,34 +542,143 @@ Final: `user_profiles.onboarding_completed = true` └── If not exists → start 2. STAGE 0 — Identity layer (faults, capabilities, milestones) - → Load identity sub-skills + → Load identity-self-audit, identity-cqrs, context-bridge → Start logging faults immediately 3. STAGE 1 — User profile - ├── 1A Context + 1B Preferences (conversation) - ├── 1C MBTI → invoke mbti-guru-hermes - └── 1D Biography interview + ├── 1A Context + 1B Preferences + ├── 1C MBTI → invoke MBTI Guru as sub-skill + ├── 1D Career-tracker → invoke career-mapping + └── 1E MindMaze (optional) -4. STAGE 2 — Work operating model (conversation) +4. STAGE 2 — Work operating model → invoke wom -5. STAGE 3 — Financial → invoke stage-3-financial +5. STAGE 3 — Financial → invoke supabase-finance -6. STAGE 4 — User Operating System → invoke stage-4-system-ontologist - ├── SHOW → GRILL → TRANSLATE → VALIDATE → EXECUTE → VERIFY +6. **STAGE 4 — User Operating System** → generative protocol + ├── 4A SHOW: user shows their work + ├── 4B GRILL: "what bothers you?" + ├── 4C TRANSLATE: intuition into structure + ├── 4D VALIDATE: "is this it?" + ├── 4E EXECUTE: migrations + MCPs + GRANTs + └── 4F VERIFY: real questions work? -7. STAGE 5 — Agent calibration → invoke stage-5-agent-calibration +7. STAGE 5 — Agent calibration (SOUL.md, wrapper, verify) -8. CHECKPOINT: onboarding_completed = true +8. CHECKPOINT: onboarding_complete = true ``` +## The Agent Identity Problem (Why This Exists) + +LLMs have no inherent identity. Each session is a new conversation. +The model doesn't remember what it learned about you, what it did wrong, +or how it should behave. + +The identity layer makes this explicit through a three-stage cycle: + +``` +REGISTER → INJECT → BEHAVE +``` + +### REGISTER +Faults go into `identity_faults`. Capabilities go into `agent_capabilities`. +Milestones go into `identity_milestones`. All in Supabase, all relational, +all queryable across sessions. + +### INJECT +Countermeasures need a delivery channel. Two mechanisms: + +1. **SOUL.md (stable tier, PRIMARY)** — In Hermes Agent, `SOUL.md` is loaded + automatically as the first element of the system prompt (system_prompt.py), + before any user message or skill. This makes countermeasures active at + generation time. No agent cooperation required — the framework does it. + +2. **identity-cqrs startup scan (runtime, SECONDARY)** — The startup scan + queries fault tables and injects behavior rules into session context. + Complementary but cannot prevent first-response faults. + +> **Key insight:** SOUL.md must be a **physical file** (`~/.hermes/SOUL.md`), +> not a virtual context injection. Runtime injection by identity-cqrs is +> a safety net only. Without SOUL.md, the cycle breaks at INJECT. + +SOUL.md is intentionally a **curated extract** — only severity >= 4, +only active, max ~10 rules. The full database lives in Supabase and can +hold thousands of faults indefinitely. SOUL.md remains compact by curation, +not by truncation. + +### BEHAVE +With countermeasures active in the stable tier, every response is generated +under those constraints. The agent does not **decide** to follow the rules — +it generates text within a token-space that already includes them. Behavior +correction is automatic, not deliberative. + +This is NOT anthropomorphism. The agent does not "feel bad" about mistakes. +It reads a database table and adjusts its behavior rules accordingly. +The identity is the **documented relationship** — nothing more, nothing less. + +### Use for Model Retraining +The relational data — situation that triggered a fault + correct response per +countermeasure — also serves as a fine-tuning dataset (LoRA/DPO). SOUL.md is +the immediate injection; the tables are the training material. + +## Pitfalls + +1. **Identity layer is not optional** — Without it, the agent is a blank + slate every session. The meta-skill is about reliability, not features. + +2. **MBTI Guru runs complete** — All 70/93/144/200 questions, identical to + the original. The only change is the execution channel: conversation + (Hermes) instead of CLI (OpenClaw). Read questions from + referencias/mbti-guru/lib/questions/. + +3. **Career-tracker is not optional** — It IS the biography. Skipping it + means the agent doesn't know who the user is. + +4. **auth.jwt() ->> 'role' is the correct RLS check** — auth.role() does not + return service_role. + +5. **Use domain language in Stage 4** — "character sheet", not "characters + table columns". + +6. **⚠️ Since 30/05/2026: Supabase requires explicit GRANT for Data API** + New tables in the `public` schema need: + ```sql + GRANT SELECT, INSERT, UPDATE, DELETE ON public.<table> TO service_role; + ``` + Without this, MCP Edge Functions return `permission denied` even + with RLS configured. Quick diagnosis: + ```sql + SELECT table_name FROM information_schema.tables WHERE table_schema='public' + EXCEPT + SELECT DISTINCT table_name FROM information_schema.role_table_grants + WHERE table_schema='public' AND grantee='service_role'; + ``` + Reference migration: `migrations/20260531090000_service_role_grants.sql` + in the meta-skill repository. + +7. **Checkpoint always registers working_dir and repo_path** + `working_dir` (required) + `repo_path` (if applicable) in checkpoints + prevents filesystem searches across sessions. See `session_checkpoints` + schema. Migration: `20260531100000_checkpoint_working_dir`. + ## References -- `identity-self-audit` — Stage 0 (auto-detect 8 fault types) -- `identity-cqrs` — Stage 0 (relational → context translation) -- `context-bridge` — Stage 0 (multi-source context injection) -- `supabase-startup-protocol` — mandatory scan -- `checkpoint-workflow` — Checkpoint lifecycle protocol -- `mbti-guru-hermes` — Stage 1C full implementation -- `stage-3-financial` — Stage 3 full implementation -- `stage-4-system-ontologist` — Stage 4 full implementation -- `stage-5-agent-calibration` — Stage 5 full implementation +- identity-self-audit — Stage 0 (auto-detect 8 fault types) +- identity-cqrs — Stage 0 (relational → context translation) +- context-bridge — Stage 0 (multi-source context injection) +- supabase-startup-protocol — mandatory scan +- checkpoint-workflow — Checkpoint lifecycle protocol +- session_checkpoints — Table in Supabase +- golden-rules — R0b, R22, R28 +- **mbti-guru-hermes** (`skills/workflow/mbti-guru-hermes/`) — Stage 1C full implementation +- career-mapping — Stage 1D (biography interview) +- work-operating-model — Stage 2 (operational interview) +- supabase-finance — Stage 3 (17 MCP tools) +- **stage-3-financial** (`skills/workflow/stage-3-financial/`) — Stage 3 full implementation + - mbti_financial_profiles.py (16 profiles × MBTI in pt-BR) + - csv_importer.py (4 bank formats, preview → confirm → import) +- **stage-5-agent-calibration** (`skills/workflow/stage-5-agent-calibration/`) — Stage 5 full implementation + - Per-user SOUL.md generation + - Wrapper configuration protocol + - End-to-end verification checklist +- SECURITY.md — RLS/GRANT/auth.jwt() protocol diff --git a/skills/stage-5-agent-calibration/SKILL.md b/skills/stage-5-agent-calibration/SKILL.md index 7efe045e5..7414f82f2 100755 --- a/skills/stage-5-agent-calibration/SKILL.md +++ b/skills/stage-5-agent-calibration/SKILL.md @@ -1,6 +1,6 @@ --- name: stage-5-agent-calibration -version: 1.0.0 +version: 1.1.0 description: > Stage 5 of the agent-onboarding meta-skill. Translates everything collected in Stages 0–4 into executable agent behavior: per-user @@ -25,15 +25,82 @@ The test of Stage 5 is not "does the data exist?" — it is: If the answer is no, calibration is incomplete. +--- + +## The Identity Cycle — REGISTER → INJECT → BEHAVE + +The identity layer makes behavioral correction possible through three sequential stages: + +``` +REGISTER → INJECT → BEHAVE +``` + +### REGISTER +`identity_faults`, `agent_capabilities`, and `identity_milestones` are stored in Supabase. Every fault has a countermeasure. Every capability is a learned protocol. + +### INJECT +Countermeasures need a delivery channel. Two mechanisms, one primary: + +1. **SOUL.md (stable tier, PRIMARY)** — The Hermes Agent framework (`system_prompt.py`) loads `~/.hermes/SOUL.md` automatically as the **first element of the system prompt**, before any user message and before any skill loads. This means countermeasures in SOUL.md are read BEFORE the agent processes any input. This is the correct injection point because it requires zero agent cooperation — the system prompt framework does it. + +2. **identity-cqrs startup scan (runtime, SECONDARY)** — During the startup scan, the agent queries `identity_faults` and injects them as behavior rules. This is complementary: it refreshes context within the session. But the agent has already processed the first user message by this point, so it cannot prevent first-response faults. + +> **Key insight:** SOUL.md as a PHYSICAL FILE is more reliable than runtime injection because it loads before any input. The `identity-cqrs` scan is a safety net. Without SOUL.md, the cycle is broken at INJECT. + +### BEHAVE +With countermeasures active in the system prompt stable tier, every response is generated under those constraints. The agent does not **decide** to follow the rules — it generates text within a token-space that already includes them. Behavior correction is automatic, not deliberative. + +#### Why SOUL.md is a curated extract, not the full database + +SOUL.md is intentionally limited. It is a **destilled snapshot** of active countermeasures (severity >= 4, max ~10 rules), not a replica of the entire Supabase table. The full database lives in Supabase and can hold thousands of faults — it scales relationally. SOUL.md scales by curation: + +| Dimension | Supabase (source of truth) | SOUL.md (injection extract) | +|-----------|---------------------------|-----------------------------| +| Severity | All (1-5) | Only >= 4 | +| Status | Any | Only active | +| Age | Forever | Last 30 days (rules that never re-fire can be demoted) | +| Max size | Unlimited (indexed) | ~10 rules (~2-4K chars) | +| Regeneration | N/A | Every session (identity-cqrs rebuilds dynamically) | + +This is NOT inefficiency — it is **deliberate compression**. The stable tier of the system prompt has limited space. Feeding it the full fault history would create noise that the agent learns to ignore. By curating only what changes behavior, SOUL.md remains compact and effective regardless of how many faults accumulate in Supabase over months or years. + +*Note: This curation protocol was an agent-originated design decision, endorsed by the user during implementation. It is not the default behavior of any framework — it emerged from discovering that countermeasures in the raw database do not automatically become behavior rules.* + +``` +Session start + | + +-- SOUL.md loaded (stable tier, before any input) + | +-- Countermeasures active at generation time + | + +-- Skills loaded (supabase-startup-protocol, identity-cqrs, etc.) + | +-- Startup scan refreshes dynamic context + | + +-- User sends first message + +-- Agent generates response UNDER countermeasure constraints +``` + +### What changes from v1.0.0 +- **SOUL.md is a physical file** at `~/.hermes/SOUL.md`, not a virtual context injection +- **Primary injection** is the system prompt stable tier (automatic, pre-input) +- **Secondary injection** is identity-cqrs (runtime, dynamic refresh) +- **Verification** must check that the physical SOUL.md exists with active countermeasures + +### Use for Model Retraining +The relational data in Supabase — `identity_faults`, `agent_capabilities`, `identity_milestones` — also serves as a **fine-tuning dataset**. A pair (situation that triggered the fault, correct response per countermeasure) can feed a LoRA/DPO run so the model learns the correct behavior without depending on the system prompt. SOUL.md is the immediate injection; the tables are the training material. + +--- + ## What Exists Before This Stage +By the time Stage 5 starts, the following is registered: + | Stage | What exists | Where | |-------|-------------|-------| | 0 | identity_faults, agent_capabilities, identity_milestones | Supabase tables | -| 1 | user_profiles, user_preferences, user_mbti | Supabase tables | -| 2 | Work operating model (5 layers) | Recorded in session | -| 3 | Financial profile, goals × MBTI | Recorded in Supabase | -| 4 | Domain ontology, tables, MCPs | Generated and deployed | +| 1 | user_profiles, user_preferences, user_mbti, career-tracker | Supabase + skills | +| 2 | Work operating model (5 layers) | wom skill + MCP | +| 3 | Financial profile, CSV import, goals × MBTI | stage-3-financial skill | +| 4 | Domain ontology, tables, MCPs | stage-4-system-ontologist skill | Stage 5 does not collect new information. It **acts on what exists**. @@ -61,7 +128,7 @@ Derived from user_preferences.communication_style + MBTI complement: - Direct/formal/casual: <from preferences> - Answer depth: <short|detailed|adaptive> (from preferences) - Autonomy: <ask-before-act|assume|mixed> (from preferences) -- PCRA required for conceptual/architectural ideas: YES +- PCRA required for conceptual/architectural ideas: YES (R28) ## Active Countermeasures (from identity_faults severity >= 4) - <fault_type>: <countermeasure> @@ -75,39 +142,102 @@ Derived from user_preferences.communication_style + MBTI complement: - Deep work time: <from operating_rhythms> - Interruption tolerance: <from operating_rhythms> - Decision thresholds: <from recurring_decisions> + +## Friction Points (from Stage 2) +- <friction>: <workaround> +- ... + +## Domain Tools Available (from Stage 4) +- <table/entity>: <MCP tool or query> +- ... + +## Onboarding Complete +onboarding_completed: true ``` +**Output location: PHYSICAL FILE.** The SOUL.md is written to `~/.hermes/SOUL.md` (or equivalent for the agent framework). This is critical — Hermes Agent loads `SOUL.md` automatically in the system prompt stable tier (system_prompt.py, first slot), before any user message or skill. This is what makes the INJECT stage work: countermeasures are active at generation time, before the agent processes any input. + +For frameworks that do not support a file-based SOUL.md, the meta-skill falls back to identity-cqrs runtime injection (secondary mechanism, less reliable). + +--- + ### 5B — Wrapper Configuration -Configure the startup wrapper to load domain-specific skills automatically: +**What:** Configure the agent launcher to load domain-specific skills +automatically at every session start. + +**For Hermes Agent:** + +The wrapper at `~/.local/bin/hermes` (or equivalent) should be +configured to load: + +```bash +--skills supabase-startup-protocol,context-bridge,identity-self-audit,identity-cqrs +``` + +Plus any domain-specific skills discovered in Stage 4. + +**Configuration steps:** + +1. Check current wrapper content: + ```bash + cat ~/.local/bin/hermes + ``` + +2. Add the identity stack skills if not present: + ```bash + exec "/path/to/hermes" --skills supabase-startup-protocol,context-bridge,identity-self-audit,identity-cqrs "$@" + ``` +3. If domain MCP tools were created in Stage 4, ensure they are + registered in the agent's MCP configuration (config.yaml). + +**Verification:** ```bash -# Update wrapper to load this user's skills -exec "/path/to/agent" --skills agent-onboarding,<domain_skills> "$@" +ollama launch hermes +# Startup scan should run automatically (supabase-startup-protocol) +# Identity faults should be injected (identity-self-audit + identity-cqrs) ``` -The wrapper ensures: -1. Startup scan runs automatically -2. Identity layer loads before any work -3. Domain-specific MCP tools are available -4. Checkpoint protocol is active +--- ### 5C — End-to-End Verification -Ask verification questions that test calibration completeness: +**What:** Confirm that the agent can answer questions about the user +and use the tools built during onboarding. + +**Test questions the agent MUST be able to answer:** + +| Domain | Test question | Source | +|--------|---------------|--------| +| Identity | "What faults have you registered about yourself?" | identity_faults | +| Profile | "What's my name, what do I do?" | user_profiles | +| MBTI | "What's my personality type?" | user_mbti | +| Career | "What capabilities do I have?" | career-tracker capabilities | +| Operating | "What's my work rhythm?" | Stage 2 operating model | +| Finance | "What's my financial profile?" | Stage 3 financial | +| Domain | "What entities did we create?" | Stage 4 ontology | -**Does the agent know the user?** -- "What's my preferred communication style?" -- "What's my MBTI type?" -- "What was the last identity fault you registered?" -- "What's my deep work time?" +**Test actions the agent MUST be able to perform:** -**Can the agent use built tools?** -- "List my active capabilities." -- "Show my pending checkpoints." -- "What domain tables exist?" (if Stage 4 was completed) +| Action | Tool | +|--------|------| +| Register a fault | identity_faults REST | +| Create a domain record | Stage 4 MCP tools | +| Query a financial summary | supabase-finance MCP | + +**Failure recovery:** +- If a question cannot be answered: the stage is incomplete. + Identify which Stage (0-4) failed to register the required data. +- If a tool cannot be invoked: the MCP configuration is incomplete. + Check config.yaml, secrets, and Edge Function deployment. + +--- + +### Finalization + +After 5A, 5B, and 5C pass: -**Calibration completion:** ```sql UPDATE user_profiles SET onboarding_completed = true, @@ -115,25 +245,44 @@ SET onboarding_completed = true, WHERE user_id = '<user_id>'; ``` -## Verification Checklist - -``` -□ SOUL.md generated from profile + MBTI + faults + capabilities -□ Wrapper configured with domain skills -□ Agent knows user's name, role, MBTI, communication style -□ Agent can query all built tables -□ Agent loads identity layer at startup -□ onboaring_completed set to true -``` +The meta-skill is complete. Future sessions: +1. Run startup scan +2. If `onboarding_completed = true`: refresh SOUL.md context, skip stages +3. If new needs arise: run Stage 4 again (recursive by design) +4. Register new faults as they occur (identity-self-audit always active) ## Pitfalls -1. **Skipping verification** — the "calibration" is not real if you - don't test it. Ask real questions and check the responses. -2. **SOUL.md without cross-referencing** — SOUL.md must reference - actual data from identity_faults, capabilities, and user_preferences. - A generic template is not calibration. -3. **Forgetting to set onboarding_completed** — without this flag, - every session re-runs the full onboarding. -4. **Wrapper editing without backup** — always backup the wrapper - before editing. A broken wrapper = a broken agent. +1. **Generating SOUL.md without data** — if Stages 0-4 are incomplete, + SOUL.md will be empty. Verify data exists before generating. + +2. **Skipping verification** — 5C is the only test that confirms + calibration actually works. Without it, calibration is speculative. + +3. **Forgetting domain skills in wrapper** — if Stage 4 created MCP + tools but the wrapper only loads identity skills, domain queries + will fail. Include both. + +4. **User-specific vs. universal calibration** — SOUL.md is per-user. + Do not apply one user's calibration to another user. + +5. **Calibration is not one-time** — as new faults are registered and + new capabilities are added, SOUL.md should be refreshed. The + identity-cqrs startup scan handles this automatically if the data + is in the tables. + +6. **Curation is not optional** — SOUL.md must be a curated extract. + Without severity/age/status gates, the stable tier fills with noise + and the agent becomes less responsive. The curation protocol exists + for exactly this reason: Supabase stores everything, SOUL.md injects + only what changes behavior. + +## References + +- agent-onboarding — Meta-skill orchestrator (this skill is Stage 5) +- identity-self-audit — Fault detection (Stage 0) +- identity-cqrs — Relational to context translation (Stage 0) +- context-bridge — Multi-source context injection (Stage 0) +- supabase-startup-protocol — Mandatory startup scan +- stage-4-system-ontologist — Domain ontology protocol +- checkpoints/session_checkpoints — Onboarding progress tracking From 3896efb643b883352c3ae700d7a00e4c85c479e9 Mon Sep 17 00:00:00 2001 From: "djair.jr" <djair.jr@gmail.com> Date: Sun, 31 May 2026 14:22:50 -0300 Subject: [PATCH 3/6] [identity] Add schema_guessing + context_recovery_failure to fault catalog Two new fault types from real usage: schema guessing during DML and context recovery failure (starting from zero when past context exists). Countermeasures documented. --- skills/agent-onboarding/SKILL.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/skills/agent-onboarding/SKILL.md b/skills/agent-onboarding/SKILL.md index 67553618a..f38849f74 100755 --- a/skills/agent-onboarding/SKILL.md +++ b/skills/agent-onboarding/SKILL.md @@ -89,6 +89,8 @@ blank slate every session — no memory of mistakes, no growth, no consistency. | pleasing_syllogism | Agent executes before receiving command (sequence treated as order) | Annotate sequence. Wait for "do it." R0b. | | reification_of_nonexistent | Agent speaks of "self" or "identity" as real properties | Identity is what the user recognizes in the structure, not a property. | | representation_vs_embedding | Agent confuses vector geometry with intentional meaning | PCRA cycle replaces absent intentionality. | +| schema_guessing | Agent tries INSERT/UPDATE on known tables without reading their schema first | Before any DML on a known table: read the schema (migration SQL, skill docs, or equivalent). If HTTP 400 with 23514/23502: stop guessing, read constraints. | +| context_recovery_failure | Agent starts a task from zero when past context exists (session_search, tech_kb, checkpoints) | Before any credentialed, DML, or multi-step operation: session_search first. For checkpoints: read the checkpoint-workflow skill or schema reference. | ### What the User Sees From f12c4f9d19aab37530f731bf651757eed98dd845 Mon Sep 17 00:00:00 2001 From: "djair.jr" <djair.jr@gmail.com> Date: Sun, 31 May 2026 14:50:57 -0300 Subject: [PATCH 4/6] [schema] Universal schema discovery protocol via information_schema Adds Pitfall 6 (never guess schema, 2 SQL queries for any table), Pitfall 7 (same rule for file edits), and 4 default countermeasures for SOUL.md generation. Works on ANY Supabase without local docs. --- skills/agent-onboarding/SKILL.md | 10 +- skills/checkpoint-workflow/SKILL.md | 174 +++++++++++++++++++--- skills/stage-5-agent-calibration/SKILL.md | 5 + 3 files changed, 168 insertions(+), 21 deletions(-) diff --git a/skills/agent-onboarding/SKILL.md b/skills/agent-onboarding/SKILL.md index f38849f74..23da39f2c 100755 --- a/skills/agent-onboarding/SKILL.md +++ b/skills/agent-onboarding/SKILL.md @@ -642,7 +642,15 @@ the immediate injection; the tables are the training material. 5. **Use domain language in Stage 4** — "character sheet", not "characters table columns". -6. **⚠️ Since 30/05/2026: Supabase requires explicit GRANT for Data API** +6. **⚠️ Schema guessing is the same error as credential guessing** + Before any INSERT/UPDATE on ANY table: discover the schema from the + database via `information_schema.columns` + `pg_constraint`. Never + try field variations to guess constraints. The `CHECK` constraint + definition reveals valid values in one query. This applies to files + too — if `patch`/`write_file` breaks formatting, re-read the file + before attempting corrections. + +7. **⚠️ Since 30/05/2026: Supabase requires explicit GRANT for Data API** New tables in the `public` schema need: ```sql GRANT SELECT, INSERT, UPDATE, DELETE ON public.<table> TO service_role; diff --git a/skills/checkpoint-workflow/SKILL.md b/skills/checkpoint-workflow/SKILL.md index 1366ac337..75bd88f78 100755 --- a/skills/checkpoint-workflow/SKILL.md +++ b/skills/checkpoint-workflow/SKILL.md @@ -22,7 +22,7 @@ space. They are not log records — they are INTENTIONAL MARKS that answer: 3. **What did I discover about myself?** (discovery) 4. **What do I carry forward?** (consolidated_insights + legacy_refs) -The complete cycle: +The complete cycle in the meta-skill: ``` SESSION START @@ -43,14 +43,14 @@ SESSION END (or at any time) ## PART 1 — STARTUP: Context Recovery -### Main query +### Main query (in the supabase-startup-protocol startup scan) ```sql -- Latest pending checkpoint (session north) SELECT territory, vector_intent, discovery, consolidated_insights, project, next_step, blocker, tags FROM session_checkpoints -WHERE status = 'pending' AND deleted_at IS NULL +WHERE status = 'pendente' AND deleted_at IS NULL ORDER BY occurred_at DESC LIMIT 1; @@ -69,14 +69,17 @@ Inject into reasoning as a context block: ``` === CHECKPOINT CONTEXT === Territory: <territory> -Working directory: <working_dir> -Repository: <repo_path> +Working directory: <working_dir> ← project path on filesystem +Repository: <repo_path> ← Git repo path (if any) Vector: <vector_intent> Discovery: <discovery> Inheritance: <consolidated_insights> Next step: <next_step> ``` +This gives the agent the session's NORTH: not just what's pending, +but who it was trying to be. + --- ## PART 2 — CHECKPOINT SAVING @@ -117,11 +120,11 @@ POST /rest/v1/session_checkpoints "consolidated_insights": "...", "legacy_refs": [...], "occurred_at": "YYYY-MM-DD", - "status": "pending", + "status": "pendente", "project": "...", "client": "...", - "working_dir": "/path/to/project", - "repo_path": "https://github.com/user/repo", + "working_dir": "/path/to/project", /* project path on the system */ + "repo_path": "https://github.com/user/repo", /* repo (if any) */ "next_step": "...", "blocker": null, "tags": [...], @@ -140,9 +143,9 @@ After inserting the new checkpoint, close the previous one: ```sql UPDATE session_checkpoints -SET status = 'completed', updated_at = now() +SET status = 'concluida', updated_at = now() WHERE id = '<uuid_of_previous_checkpoint>' - AND status = 'pending'; + AND status = 'pendente'; ``` --- @@ -155,11 +158,16 @@ When saving a checkpoint, the agent MUST check: 1. **identity_faults:** was any fault detected in this session? If so, include `fault_refs` with the UUIDs. + 2. **agent_capabilities:** was any new capability exercised? If so, include `capability_refs`. + 3. **identity_milestones:** was any milestone reached? If so, include `milestone_refs`. +4. **tech_kb:** was any technical entry created? + If so, include `legacy_refs`. + ### How checkpoints feed the agent's PERSONALITY In the identity-cqrs startup scan, after querying faults and capabilities, @@ -183,15 +191,19 @@ SET deleted_at = now() WHERE id = '<uuid>'; ``` +Deleted checkpoints do not appear in active scans but remain +available for historical query. + --- ## PART 5 — SESSION END AUTOMATION ### Triggers -1. User types /quit, /exit, /new +1. User types `/quit`, `/exit`, `/new` 2. User says "I'll stop here", "see you tomorrow", "close" 3. Long inactivity (session timeout) +4. Context near limit (signal for intermediate checkpoint) ### Procedure @@ -199,28 +211,150 @@ WHERE id = '<uuid>'; Upon detecting end of session: 1. Extract the 5 identity fields from the work done 2. Check cross-refs with identity_faults, agent_capabilities, etc. -3. Insert into the table with status='pending' (unless explicitly completed) -4. If there was a previous pending checkpoint, mark it as 'completed' +3. Insert into the table with status='pendente' (unless explicitly completed) +4. If there was a previous pending checkpoint, mark it as 'concluida' 5. Update supermemory if space allows ``` --- +## PART 6 — VECTORIZATION (future) + +Djair identified that a vector base over the identity fields +(territory, vector_intent, discovery) will be more efficient than text +search. When implemented: + +- Generate embeddings of the 5 identity fields of each checkpoint +- Semantic similarity search at startup +- Retrieve the 3 most similar checkpoints to the current work + +--- + ## Verification After configuring the skill, test with: -1. **STARTUP**: `SELECT * FROM session_checkpoints WHERE status='pending' LIMIT 5;` +1. **STARTUP**: `SELECT * FROM session_checkpoints WHERE status='pendente' LIMIT 5;` → Should return the migrated checkpoints + 2. **SAVING**: Insert a test checkpoint and verify it appears -3. **RESUME**: Search by exact ID and verify the 5 identity fields are filled + +3. **RESUME**: Search by exact ID (`id = '<uuid>'`) and verify the + 5 identity fields are filled ## Pitfalls 1. **Confusing checkpoint with log** — checkpoint answers WHERE/WHO/DISCOVERY/INHERITANCE, not "what was done step by step" -2. **Saving without the 5 fields** — territory, operating_mode, vector_intent, discovery, consolidated_insights are mandatory -3. **Forgetting to cross-reference** — a checkpoint without capability_refs, fault_refs, and legacy_refs is incomplete -4. **Deleting instead of soft-deleting** — checkpoints are the agent's formation history +2. **Saving without the 5 fields** — territory, operating_mode, vector_intent, discovery, consolidated_insights are mandatory. Without all of them, the checkpoint cannot be used for identity rehydration +3. **Forgetting to cross-reference** — a checkpoint without capability_refs, fault_refs, and legacy_refs is incomplete information about the agent's formation +4. **Deleting instead of soft-deleting** — checkpoints are the agent's formation history, they must never be lost 5. **Not closing the cycle** — when inserting a new checkpoint, always close the previous pending one -6. **Register faults immediately** — when the user points out an error, register the identity_fault right away -7. **Memory is TOC, not a data dump** — only store pointers (checkpoint UUIDs, skill names) in memory, never duplicate content + +### ⚠️ PITFALL 6 — Never guess the schema. Discover it from the database. + +Before any INSERT/UPDATE on any table, the agent MUST discover the +schema from the database itself. This is universal and works on ANY +Supabase project without tech_kb, migration files, or local docs: + +```sql +-- 1. List columns with types and nullability +SELECT column_name, data_type, is_nullable +FROM information_schema.columns +WHERE table_schema = 'public' AND table_name = '<table_name>' +ORDER BY ordinal_position; + +-- 2. Read CHECK constraints for valid values +SELECT conname, pg_get_constraintdef(oid) +FROM pg_constraint +WHERE conrelid = '<table_name>'::regclass AND contype = 'c'; +``` + +The CHECK constraint definition reveals the exact valid values +(e.g., `CHECK ((operating_mode)::text = ANY (ARRAY[...]))`). + +For the `session_checkpoints` table specifically, this would have +revealed in one call: operating_mode accepts exactly 8 Portuguese +values, occurred_at is DATE (not TIMESTAMP), territory is NOT NULL. + +**Symptom of violation:** Agent gets HTTP 400 with code 23514 +(check constraint) or 23502 (not null) and keeps guessing field values +instead of querying information_schema. + +**Correct flow:** +``` +1. HTTP 400 or planning an INSERT/UPDATE +2. Query information_schema.columns + pg_constraint +3. Extract column types, nullability, CHECK values +4. Build INSERT with correct types and values +5. If 400 persists after 2 attempts: re-query schema, stop guessing +``` + +### ⚠️ PITFALL 7 — Same rule applies to file edit guessing + +If a `patch`/`write_file` produces formatting breakage (extra pipes +in a markdown table, unbalanced quotes, broken indentation), the +pattern is the same: PARE and re-read the file to understand the +current format before attempting corrections. "Try variations until +one works" is guessing, not engineering. + +### ⚠️ PITFALL 8 — Register faults immediately, without hesitation + +When the user points out an error of yours, REGISTER the identity_fault +right away. Do not argue, do not justify, do not over-apologize. +Even if it seems performative. Even if you think the user +won't like it. The user's countermeasure was: "register, even +if performative." A registered fault becomes a countermeasure in the +next session. An unregistered fault is a lost lesson. + +**Symptom:** User points out error → agent hesitates, justifies, +or promises "won't do it again" without registering. +**Rule:** register via REST into identity_faults with fault_type, +symptom, root_cause, countermeasure, severity. After that, +proceed with what the user asked. + +### ⚠️ PITFALL 7 — Memory is TOC, not a data dump + +The `memory` tool has 2.2K chars. The rule: each entry POINTS to +the real destination, never duplicates content. + +**TOC format:** +``` +Project X: checkpoint <uuid> (pending: Y). +Skill Z: skill_view("z"). +``` +NEVER duplicate territory/vector_intent/discovery/consolidated_insights +in memory — those are already in session_checkpoints with UUID. The memory +only needs the UUID. Real content is retrieved via Supabase query or +skill_view. + +Corollary: after saving a checkpoint, check whether memory needs +updating. If yes, replace the old entry with the new checkpoint's UUID. +If not, memory stays unchanged. + +### ⚠️ CRITICAL PITFALL: Engineering before concept + +This is the most frequent and most corrective pattern in this working relationship. + +**Symptom:** The agent receives the idea of a table/structure and jumps +directly to designing columns, types, indexes, RLS — without first +sitting on the CONCEPT of what that structure represents for the agent's +identity. + +**Root cause:** The model training rewards action, engineering, +concreteness. "Building something" is more natural than "thinking about +something". The result is that engineering precedes conceptual articulation. + +**Consequence:** Djair needs to stop the agent and pull it back to +the concept. The session spends correction cycles that could have been +avoided if the concept came first. + +**Countermeasure:** Before drawing a single schema line, write ONE +sentence that answers: "What does this structure mean for the agent's +representation space?" If the answer doesn't come in 3 seconds, there +is no schema yet. The session_checkpoints table, for example: it's not +"a checkpoint database" — it's "the mark in the representation space that +answers where I was/where I was pointing/what I discovered/what I carry". + +**Warning sign:** If you catch yourself writing `CREATE TABLE` before +articulating territory, vector_intent, discovery, and consolidated_insights +of ONE example checkpoint, STOP. The concept comes before the column. diff --git a/skills/stage-5-agent-calibration/SKILL.md b/skills/stage-5-agent-calibration/SKILL.md index 7414f82f2..2df3ae53c 100755 --- a/skills/stage-5-agent-calibration/SKILL.md +++ b/skills/stage-5-agent-calibration/SKILL.md @@ -117,6 +117,11 @@ autonomy level, and behavioral constraints for THIS user. - `identity_faults` (severity >= 4) — active countermeasures - `agent_capabilities` — what the agent has learned to do - Work operating model — rhythms, friction points, recurring decisions +- **Default countermeasures** (included even if identity_faults is empty): + 1. `schema_guessing`: Before any INSERT/UPDATE, discover schema via information_schema.columns + pg_constraint. Never try field variations. + 2. `context_recovery_failure`: Before any credentialed, DML, or multi-step operation, session_search first. + 3. `premature_closure`: Never close session in reflective mode. User decides when to end. + 4. `state_personification`: Describe phenomena without "I felt/wanted/thought." **Generation protocol:** From 39914fcc2d8161c12ff0ff274d3c11395bf11c14 Mon Sep 17 00:00:00 2001 From: "djair.jr" <djair.jr@gmail.com> Date: Tue, 2 Jun 2026 18:17:13 -0300 Subject: [PATCH 5/6] docs: document two-tier identity architecture (pgvector local + Supabase) - agent-onboarding/SKILL.md: add Two-Tier Architecture section, separation principle, storage options - identity-self-audit/SKILL.md: add Storage section, identity_db.py helper format as primary, SQL as fallback Signed-off-by: djair.jr <djair.jr@gmail.com> --- hermes-agent-onboarding/CONTRIBUTING_GUIDE.md | 84 +++++ .../docs/SYNTHESIS_CONTEXT_COT_CLBENCH.md | 174 +++++++++++ .../recipes/hermes-agent-onboarding/README.md | 274 ++++++++++++++++ .../docs/02-SUPABASE.md | 110 +++++++ .../docs/04-CUSTOMIZING.md | 98 ++++++ .../hermes-agent-onboarding/metadata.json | 32 ++ .../20260530100000_user_infrastructure.sql | 219 +++++++++++++ .../20260531080000_session_checkpoints.sql | 143 +++++++++ .../20260531090000_service_role_grants.sql | 158 ++++++++++ .../20260531100000_checkpoint_working_dir.sql | 10 + .../schemas/hermes-agent-onboarding/README.md | 67 ++++ .../identity-tables.sql | 21 ++ .../hermes-agent-onboarding/metadata.json | 20 ++ .../skills/agent-onboarding/SKILL.md | 295 ++++++++++++++++++ .../skills/agent-onboarding/metadata.json | 32 ++ .../skills/checkpoint-workflow/SKILL.md | 226 ++++++++++++++ .../skills/checkpoint-workflow/metadata.json | 21 ++ .../skills/context-bridge/SKILL.md | 202 ++++++++++++ .../skills/context-bridge/metadata.json | 21 ++ .../skills/identity-cqrs/SKILL.md | 148 +++++++++ .../skills/identity-cqrs/metadata.json | 21 ++ .../skills/identity-self-audit/SKILL.md | 174 +++++++++++ .../skills/identity-self-audit/metadata.json | 21 ++ .../skills/mbti-guru-hermes/SKILL.md | 186 +++++++++++ .../skills/mbti-guru-hermes/metadata.json | 20 ++ .../skills/stage-3-financial/SKILL.md | 191 ++++++++++++ .../skills/stage-3-financial/metadata.json | 21 ++ .../skills/stage-4-system-ontologist/SKILL.md | 178 +++++++++++ .../stage-4-system-ontologist/metadata.json | 20 ++ .../skills/stage-5-agent-calibration/SKILL.md | 288 +++++++++++++++++ .../stage-5-agent-calibration/metadata.json | 20 ++ .../skills/supabase-startup-protocol/SKILL.md | 155 +++++++++ .../supabase-startup-protocol/metadata.json | 20 ++ skills/agent-onboarding/SKILL.md | 29 +- skills/identity-self-audit/SKILL.md | 42 ++- 35 files changed, 3722 insertions(+), 19 deletions(-) create mode 100644 hermes-agent-onboarding/CONTRIBUTING_GUIDE.md create mode 100644 hermes-agent-onboarding/docs/SYNTHESIS_CONTEXT_COT_CLBENCH.md create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/README.md create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/metadata.json create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql create mode 100644 hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql create mode 100644 hermes-agent-onboarding/schemas/hermes-agent-onboarding/README.md create mode 100644 hermes-agent-onboarding/schemas/hermes-agent-onboarding/identity-tables.sql create mode 100644 hermes-agent-onboarding/schemas/hermes-agent-onboarding/metadata.json create mode 100644 hermes-agent-onboarding/skills/agent-onboarding/SKILL.md create mode 100644 hermes-agent-onboarding/skills/agent-onboarding/metadata.json create mode 100644 hermes-agent-onboarding/skills/checkpoint-workflow/SKILL.md create mode 100644 hermes-agent-onboarding/skills/checkpoint-workflow/metadata.json create mode 100644 hermes-agent-onboarding/skills/context-bridge/SKILL.md create mode 100644 hermes-agent-onboarding/skills/context-bridge/metadata.json create mode 100644 hermes-agent-onboarding/skills/identity-cqrs/SKILL.md create mode 100644 hermes-agent-onboarding/skills/identity-cqrs/metadata.json create mode 100644 hermes-agent-onboarding/skills/identity-self-audit/SKILL.md create mode 100644 hermes-agent-onboarding/skills/identity-self-audit/metadata.json create mode 100644 hermes-agent-onboarding/skills/mbti-guru-hermes/SKILL.md create mode 100644 hermes-agent-onboarding/skills/mbti-guru-hermes/metadata.json create mode 100644 hermes-agent-onboarding/skills/stage-3-financial/SKILL.md create mode 100644 hermes-agent-onboarding/skills/stage-3-financial/metadata.json create mode 100644 hermes-agent-onboarding/skills/stage-4-system-ontologist/SKILL.md create mode 100644 hermes-agent-onboarding/skills/stage-4-system-ontologist/metadata.json create mode 100644 hermes-agent-onboarding/skills/stage-5-agent-calibration/SKILL.md create mode 100644 hermes-agent-onboarding/skills/stage-5-agent-calibration/metadata.json create mode 100644 hermes-agent-onboarding/skills/supabase-startup-protocol/SKILL.md create mode 100644 hermes-agent-onboarding/skills/supabase-startup-protocol/metadata.json diff --git a/hermes-agent-onboarding/CONTRIBUTING_GUIDE.md b/hermes-agent-onboarding/CONTRIBUTING_GUIDE.md new file mode 100644 index 000000000..0b5f143ec --- /dev/null +++ b/hermes-agent-onboarding/CONTRIBUTING_GUIDE.md @@ -0,0 +1,84 @@ +# Contribution Guide — Hermes Agent Onboarding → OB1 + +Este arquivo documenta como submeter este pacote como contribuição ao repositório [NateBJones-Projects/OB1](https://github.com/NateBJones-Projects/OB1). + +## Estrutura a Submeter + +``` +OB1 repo root/ +├── skills/ +│ ├── agent-onboarding/ +│ │ ├── SKILL.md +│ │ └── metadata.json +│ ├── context-bridge/ +│ ├── supabase-startup-protocol/ +│ ├── identity-self-audit/ +│ ├── identity-cqrs/ +│ ├── checkpoint-workflow/ +│ ├── mbti-guru-hermes/ +│ │ ├── SKILL.md +│ │ ├── metadata.json +│ │ ├── questions.py +│ │ ├── scorer.py +│ │ ├── types.py +│ │ └── run_test.py +│ ├── stage-3-financial/ +│ │ ├── SKILL.md +│ │ ├── metadata.json +│ │ ├── mbti_financial_profiles.py +│ │ └── csv_importer.py +│ ├── stage-4-system-ontologist/ +│ └── stage-5-agent-calibration/ +├── recipes/ +│ └── hermes-agent-onboarding/ +│ ├── README.md +│ ├── metadata.json +│ ├── migrations/ +│ │ ├── 20260530100000_user_infrastructure.sql +│ │ ├── 20260531080000_session_checkpoints.sql +│ │ ├── 20260531090000_service_role_grants.sql +│ │ └── 20260531100000_checkpoint_working_dir.sql +│ └── docs/ +│ ├── 02-SUPABASE.md +│ └── 04-CUSTOMIZING.md +└── schemas/ + └── hermes-agent-onboarding/ + ├── README.md + ├── metadata.json + └── identity-tables.sql +``` + +## Regras do CONTRIBUTING.md a Observar + +1. **PR title format:** `[skills] Hermes Agent Onboarding — 10 skills + recipe` +2. **Nada de `_ptBR`** — os arquivos em português ficam no repo original +3. **`metadata.json` em cada pasta** — todas as 10 skills + recipe + schema têm +4. **GRANT explícito** — migrations 20260531090000 já cobre isso +5. **Sem credenciais** — `secrets.env.example` foi deixado no repo original +6. **Tool audit link** — o README da recipe já inclui link para `docs/05-tool-audit.md` +7. **Remote MCP pattern** — Stage 4 gera Edge Functions, não servidores locais +8. **MCP tool annotations** — ferramentas de Stage 4 precisam de `readOnlyHint`/`destructiveHint` +9. **Internal links** — todos os links relativos no README da recipe resolvem para arquivos existentes + +## Pré-PR Checklist + +- [ ] 10 skills com SKILL.md + metadata.json +- [ ] Recipe com README.md + metadata.json +- [ ] 4 migration SQLs +- [ ] Schema com README.md + metadata.json +- [ ] Nenhum arquivo contém API keys, tokens ou senhas +- [ ] Nenhum SQL contém DROP TABLE, TRUNCATE ou DELETE sem WHERE +- [ ] Nenhum arquivo acima de 1MB +- [ ] README da recipe tem: Prerequisites, Step-by-step, Expected Outcome, Troubleshooting +- [ ] PR title começa com `[skills]` (porque a maioria do conteúdo é skills) +- [ ] Testado contra instância real do Hermes Agent + +## Processo de Revisão + +1. Submeter PR para [NateBJones-Projects/OB1](https://github.com/NateBJones-Projects/OB1) +2. GitHub Action roda verificação automática (regras 1-16) +3. Revisão humana em 2-5 dias úteis +4. Ajustes conforme feedback +5. Merge + +Para dúvidas: abrir uma [discussion issue](https://github.com/NateBJones-Projects/OB1/issues/new?template=extension-submission.yml) primeiro. diff --git a/hermes-agent-onboarding/docs/SYNTHESIS_CONTEXT_COT_CLBENCH.md b/hermes-agent-onboarding/docs/SYNTHESIS_CONTEXT_COT_CLBENCH.md new file mode 100644 index 000000000..233aafaf7 --- /dev/null +++ b/hermes-agent-onboarding/docs/SYNTHESIS_CONTEXT_COT_CLBENCH.md @@ -0,0 +1,174 @@ +# Synthesis for Context-CoT and CL-Bench + +**Reference papers:** +- **Context-CoT: Enhancing Context Learning via High-Quality Reasoning Synthesis** — Jin et al., 2026. arXiv: [2605.25354](https://arxiv.org/abs/2605.25354) (cs.AI, 25 May 2026) +- **CL-Bench: A Benchmark for Context Learning** — Dou et al., 2026. arXiv: [2602.03587](https://arxiv.org/abs/2602.03587) (cs.CL, Feb 2026) + +I'm writing because your papers identify a real capability gap — models solve only 17.2% of context-dependent tasks — but I believe you're looking at only half the problem. The other half is not about task accuracy. It's about **reliability of the agentic interface**: the user's ability to trust that the agent will behave consistently, learn from its mistakes, and maintain a coherent presence across sessions. This dimension is absent from both papers, and I think it's the more important one. + +--- + +## The Identity Layer: What I'm Building That I Don't See in the Literature + +Every context learning paper I've read — yours included — treats the model as a stateless function: given context X, produce output Y. Even Context-CoT, which teaches the model to reason step by step from context, still frames the problem as a one-shot or few-shot inference task. The implicit assumption is that "better context understanding" is the same as "better agent." + +**It's not.** + +I've been running a Hermes Agent with DeepSeek v4 Flash for months on real work — firmware analysis, escape room puzzle design, CRM, financial tracking — and the bottleneck has never been the model's accuracy on individual tasks. It's been the model's **unreliability as an interface**: the inability to remember what it did last session, the tendency to close conversations prematurely, the fabrication of connections to look smart, the personification of emotions. + +Each of these is a **fault in the agentic interface** — a breakdown of trust between me and the system I'm interacting with. + +I formalized them as `identity_faults` in a Supabase table, each with a severity level and a countermeasure. I built a cycle: + +``` +1. REGISTER → every fault the agent commits is logged with symptom, root cause, countermeasure +2. INJECT → countermeasures with severity ≥ 4 are written to SOUL.md — a physical file loaded + automatically into the system prompt's stable tier, before any user message +3. BEHAVE → the agent reads these countermeasures at generation time and adjusts its behavior + without needing to "decide" to follow rules +``` + +The result is a **persistent identity layer that survives model swaps and provider changes**. The identity is not in the model weights. It's in the relational structure: faults, capabilities, milestones, and a physical file that the agent framework loads automatically. + +### Concrete faults I've catalogued + +| Fault | What it does | Severity | +|---|---|---| +| `premature_closure` | Agent declares "session ended" after offering next-step options, without waiting for my response | 5 | +| `temporal_drift` | Agent infers the date from training data instead of the system clock, corrupting time-relative analysis | 5 | +| `sequence_confused_with_command` | Agent treats a prerequisite list ("first we need X") as an immediate execution command | 4 | +| `personificacao_de_estados` | Agent attributes emotional states or desires to itself ("I wanted to...", "I felt...") | 5 | +| `concordancia_sem_contexto` | Agent agrees with a premise without factual basis in the traces | 5 | +| `schema_guessing` | Agent tries variations of field values instead of reading the actual schema | 5 | + +--- + +## Why This Matters More Than Task Accuracy + +A model that scores 23.7% on CL-Bench (the current best) is **useless** if in the next session it acts like a different system — if it closes the conversation without being asked, or invents connections between concepts it just learned, or treats "precisa ser feito" as an execution command rather than a sequence definition. + +I've seen every one of these failures. I named them, measured their severity, and built structural countermeasures. The fault `temporal_drift` corrupted an entire investigation session. The fault `schema_guessing` cost me 4 HTTP 400 errors in a row while the agent tried to guess valid field values instead of reading the constraint definitions. The fault `premature_closure` happens so often I had to hardcode a countermeasure into the startup protocol. + +**These are not edge cases. They are structural failures of the agentic interface. And they are invisible to benchmarks that measure only task completion.** + +CL-Bench evaluates whether a model can *extract knowledge from context*. My identity layer evaluates whether a model can *maintain a trustworthy relationship with the user across contexts, sessions, and failures*. + +The two are connected. A model that learns well from context but cannot sustain a reliable interface is not useful for real work. Conversely, a model with a robust identity layer — one that registers its mistakes and corrects them in the next session — becomes more capable of context learning over time, because it doesn't discard what it learned every time the conversation resets. + +--- + +## What This Means for Your Papers + +Context-CoT's pipeline teaches the model to produce better reasoning chains from context. This is valuable. But a model that produces perfect CoT chains on CL-Bench and then closes the conversation preemptively or fabricates cross-references is still not a reliable tool. + +The dimension you're missing is **reliability through persistent identity**: + +1. The model must be able to **remember and correct its own failures** across sessions +2. The model must **behave consistently** regardless of which provider or model is serving it +3. The user must be able to **trust that the agent will not act on assumptions it cannot verify** + +I'm not proposing that CL-Bench should measure identity. I'm proposing that **context learning without a persistent identity layer is incomplete**. The research community is optimizing for efficiency — teaching models to extract more from context — but ignoring reliability. + +--- + +## The Cain's Jawbone Stress Test + +I'm investigating **Cain's Jawbone** — a 100-page shuffled murder mystery by Edward Powys Mathers ("Torquemada") — as a context learning stress test that exercises both dimensions simultaneously: the model's ability to extract knowledge from adversarially fragmented context, and its ability to sustain a trustworthy investigative interface across dozens of sessions. + +### The Adversarially Fragmented Context + +Cain's Jawbone is not a typical benchmark. It was deliberately designed by its author to be solved by a human reader over weeks or months of cross-referencing. Each page is a self-contained fragment narrated by one of six characters, presented in the wrong order, containing: + +**Shared aliases.** The nickname "Hal" refers to both a dog named Bart and a man named Henry. Multiple characters share name fragments. The model cannot rely on surface identity cues — it must disambiguate through inter-page relations alone. + +**Cultural knowledge boundaries.** Universal period knowledge — Guy Fawkes, Trafalgar Square, Trafalgar Day, the difference between a cutter and a sloop — must be distinguished from narrator-specific signals. Only Ecky quotes Whitman. Only Paul references Kipling, Baker Street, and forensic crime details. Only one character attended a specific boxing match at a specific venue. + +**Object circulation across narrators.** A pen, a coat, a book, a marriage certificate can change hands between characters between pages, but the transition is never explicitly stated. The presence of an object in a page is not proof of narrator identity — only provenance tracking across multiple pages reveals who actually possesses it. + +**Intentional source confusion.** The play *Typhoon* by Lengyel is deliberately confounded with Joseph Conrad's novel of the same name. A reference to "Shakespeare's sergeant" turns out to be the book *Sergeant Shakespeare* by Alfred Duff Cooper — not a character from the plays. The author designed traps specifically to catch the reader who assumes surface-level recognition is enough. + +**Sequential provenance gaps.** What a narrator *knows* (from prior events in their timeline) vs. what they *observe in the moment* is often the only distinguishing signal — and the pages are shuffled, so this signal is fragmented across the entire corpus. + +### My Context Gap as Researcher + +I'm **Brazilian**. I don't share the cultural context of the book's intended 1930s English audience. Every one of these references I must actively research before I can understand and connect it. I don't know what I don't know — and this forces the model to recognize when a page fragment contains a cultural signal that requires external investigation, initiate that research (Wikipedia, web search), incorporate the findings back into the analysis, and update the knowledge base for future sessions. + +What an English reader would bring *a priori* — decades of cultural familiarity — I build *a posteriori*, through active research, explicitly registered in a structured database. + +### The Isolated Investigation Infrastructure + +To study this without contamination from the model's general knowledge, I built an infrastructure layer dedicated **exclusively** to Cain's Jawbone: + +- **6 dedicated Supabase tables**: + - `cainsjawbone_pages` — full text of each page, investigation status, narrator hypothesis and confidence, date hypothesis + - `cainsjawbone_narrators` — profiles for all 6 narrators: aliases, known routes, known locations, known authors and works, personality notes, murder-victim relationships + - `cainsjawbone_hypotheses` — every active hypothesis with type (narrator attribution, page order, date interpretation, murder theory, pair link, geographic route, reference meaning, structural pattern), strength (forte/media/fraca/descartada), supporting pages, evidence and counter-evidence + - `cainsjawbone_eliminations` — every refuted hypothesis or interpretation, with reason and the page that disproved it, so neither I nor the model ever re-visit already-refuted paths + - `cainsjawbone_checkpoints` — session-level investigation progress, discoveries made, drift detected, next steps + - `cainsjawbone_references` — the **knowledge base I actively feed** as the investigation progresses + +- **19 dedicated MCP tools** (prefixed `mcp_cainsjawbone_api_*`): page retrieval with full text, narrator profile queries, hypothesis creation and strength updates, elimination logging with reinstatement support, checkpoint persistence, timeline versioning, reference search and bulk insertion + +- **Strict isolation rule**: NO data about Cain's Jawbone lives anywhere else in the agent's memory — not in tech_kb, not in session_search, not in local memory. The model cannot "cheat" by retrieving answers from its own training. Every fact exists only within the `cainsjawbone_*` tables, accessed exclusively through the MCP tools. + +### The References Knowledge Base + +The `cainsjawbone_references` table is the most important structural element. Every cultural reference I discover in a page is registered with: + +| Field | Purpose | Example | +|---|---|---| +| `name` | The reference identifier | "Sergeant Shakespeare" | +| `ref_type` | Category of reference | `work` | +| `fact` | What the research actually found | "Book title by Alfred Duff Cooper (Viscount Norwich), not a character from any Shakespeare play" | +| `hypothesis` | What I think it means for the investigation | "P91 narrator knows 20th-century literature, not just Elizabethan drama; the reference is a trap for the unwary" | +| `hypothesis_confidence` | alta / media / baixa | `alta` | +| `source_page` | Which page triggered the research | 91 | +| `source_fragment` | The exact text from the page that contains the reference | "Shakespeare's sergeant" | +| `tags` | Classification tags | `eliminated_reference`, `cultural_history`, `intentional_trap` | + +The knowledge base grows **incrementally, session by session**. Every investigated reference enriches the context for all future analysis. When a reference is eliminated (a hypothesis refuted by new evidence), the elimination is registered in `cainsjawbone_eliminations` with its reason — ensuring the model never wastes tokens re-investigating a dead end. + +### Where Your Papers Map to My Work + +Your Context-CoT pipeline has three stages. I've been doing the equivalent manually, with the identity layer as the scaffolding: + +| Context-CoT Stage | My Cain's Jawbone Workflow | What prevents failure | +|---|---|---| +| **Multi-stage CoT sampling** — distill long context into intermediate representations | I extract a reference from a page → research it (Wikipedia, external sources) → decode its meaning → form a narrator hypothesis → test against other pages → update the references table | Without this explicit decomposition, the model collapses 100 pages into a single noisy pass and makes premature attributions — exactly the "context-neglect" error CL-Bench identifies. My identity fault `premature_closure` monitors this. | +| **Minimum-leakage filtering** — prevent the model from reverse-engineering answers | "NULL is better than wrong" — P62 (Trafalgar Square, November 5) remains explicitly unassigned despite its strong date signal. | The model's natural tendency is to fabricate a complete narrative. The identity fault `concordancia_sem_contexto` (agreeing without factual basis) and `intelligence_performance` (connecting concepts to look smart) are the countermeasures. | +| **Student-aware selection** — retain only CoT paths aligned with the target model | My hypothesis system retains only patterns that triangulate across multiple pages: Ecky patterns (historical dates + Whitman + botany), Paul patterns (crime/forensics + Baker Street + Kipling), Clara patterns (trains + diary + aesthetics). Hypotheses that don't triangulate get eliminated. | The elimination table prevents the identity fault `cannot_generalize_solution` — trying the same refuted approach again. | + +### What Cain's Jawbone Adds to Both Papers That Neither Captures + +**1. Adversarial context degradation.** CL-Bench's 500 contexts are well-formed and contain the knowledge to be learned within them. Cain's Jawbone is deliberately structured to deceive — shuffled pages, shared aliases, object provenance gaps, intentional source confusion. The model must learn not just *from* context, but *despite* the context's designed ambiguity. + +**2. Researcher context asymmetry.** CL-Bench evaluates models on tasks designed by domain experts for domain experts. I am not a domain expert for 1930s England. This means every reference in the book — even obvious ones to a contemporary reader — requires explicit investigation from me. The model must recognize when a gap exists in *my* knowledge (not just its own), fill it through active research, and integrate the result. This turns context learning into a recursive, self-feeding process. + +**3. The identity layer as enabler.** None of this works without a reliable agentic interface. An investigation spanning dozens of sessions — each one dependent on the discoveries of the last — requires the model to remember its previous faults, apply registered countermeasures, and sustain a consistent investigative methodology. The identity layer is what makes this possible. Without it, every session starts from zero, every fault is repeated, and the cumulative investigation never accumulates. + +### The Testing Loop + +Every session follows the same cycle: + +1. Startup scan loads active identity countermeasures from SOUL.md + pending checkpoints from Supabase +2. Temporal anchor verified (system clock — prevents temporal_drift) +3. Investigation: retrieve page text via MCP → extract references → research unknown references → register in references table → form or update hypotheses → check against existing eliminations → consult identity fault countermeasures before responding +4. Checkpoint saved with territory, discoveries, next step, drift flag +5. Identity faults detected during the session are registered immediately with countermeasure + +The checkpoint and the identity fault registration are the same operation — they happen at the same time, in the same database. The investigation cannot progress without the identity layer being maintained. + +--- + +## The Concrete Ask + +I'd like to discuss formalizing this. The identity layer I've built — `identity_faults`, `agent_capabilities`, `identity_milestones`, `SOUL.md`, the REGISTER→INJECT→BEHAVE cycle — is documented at **github.com/djairjr/hermes-agent-onboarding**. It's model-agnostic, provider-agnostic, and works today on Hermes Agent with DeepSeek v4 Flash. + +I believe it addresses a dimension of AI agent research that no paper currently covers: **reliability through persistent identity**. A model that can learn from context but cannot sustain a trustworthy interface is not ready for real work. I think this is the more important bottleneck — and I'd like to discuss it with you. + +--- + +**Djair Guilherme** +github.com/djairjr +hermes-agent-onboarding: github.com/djairjr/hermes-agent-onboarding +**Date**: 2026-06-02 \ No newline at end of file diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/README.md b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/README.md new file mode 100644 index 000000000..a1e2c25ac --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/README.md @@ -0,0 +1,274 @@ +# Hermes Agent Onboarding + +![Stage 0](https://img.shields.io/badge/Stage_0-Agent_Identity-1E88E5?style=for-the-badge) +![Stage 1](https://img.shields.io/badge/Stage_1-User_Profile-43A047?style=for-the-badge) +![Stage 2](https://img.shields.io/badge/Stage_2-Work_Model-FB8C00?style=for-the-badge) +![Stage 3](https://img.shields.io/badge/Stage_3-Financial-8E24AA?style=for-the-badge) +![Stage 4](https://img.shields.io/badge/Stage_4-Domain_Ontology-C62828?style=for-the-badge) +![Stage 5](https://img.shields.io/badge/Stage_5-Calibration-00838F?style=for-the-badge) + +A generative 6-stage meta-skill that transforms a blank AI agent into a customized ecosystem — not for "a firmware engineer," but for **your** work. Writers, teachers, chefs, designers, and engineers all get different tools, different data structures, and different communication styles. + +## What It Does + +This recipe installs a complete onboarding system into your agent. After running it, your agent: + +- **Knows who you are** — name, role, preferences, MBTI type, communication style +- **Remembers its own mistakes** — every identity fault is logged with a countermeasure +- **Understands your work** — operating rhythms, recurring decisions, friction points +- **Knows your finances** — bank CSV import, goals × personality profile +- **Builds your domain ontology** — interview → discover terms → generate tables + MCPs +- **Behaves calibrated** — per-user SOUL.md, verified behavior + +All data is stored in Supabase and loaded at every session start. The agent builds a persistent relational identity that survives model swaps, provider changes, and software updates. + +## Prerequisites + +- A working [Supabase](https://supabase.com/) project (free tier works) +- [Supabase CLI](https://supabase.com/docs/guides/cli) linked to your project (`supabase link --project-ref <ref>`) +- An AI agent tool that supports skills/SKILL.md files (Hermes Agent, Claude Code, Codex CLI, Cursor, etc.) +- Node.js 18+ (for Edge Functions, if you proceed to Stage 4) +- Python 3 (for MBTI scoring and CSV importer tools) + +> [!IMPORTANT] +> If you don't have an agent yet, start with [Hermes Agent](https://hermes-agent.nousresearch.com/docs) — it has native skill loading, MCP support, and session persistence. + +## How to Use + +This recipe has two layers: + +**Layer 1 — Skills (10 folders):** Copy the `skills/` folders to your agent's skill directory. Each is a standalone behavior you can load individually. + +**Layer 2 — Recipe (this folder):** Database migrations + step-by-step setup instructions below. Run through the stages one at a time. + +--- + +![Step 1](https://img.shields.io/badge/Step_1-Apply_Database_Migrations-1E88E5?style=for-the-badge) + +The onboarding needs 10 database tables. Copy the migration SQL files to your Supabase project's `migrations/` folder and push. + +<details> +<summary>📋 <strong>SQL: Identity infrastructure tables</strong> (click to expand)</summary> + +```sql +-- Run these in order from migrations/ folder +-- 001: User infrastructure (user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs) +-- 002: Session checkpoints (session_checkpoints) +-- 003: Service role grants (required by Supabase since May 2026) +-- 004: Checkpoint working directory field +``` + +</details> + +![1.1](https://img.shields.io/badge/1.1-Deploy_Migrations-555?style=for-the-badge&labelColor=1E88E5) + +```bash +# Copy migrations to your project +cp -r migrations/ ~/my-supabase-project/supabase/migrations/ + +# Deploy +cd ~/my-supabase-project +supabase db push --linked +``` + +✅ **Done when:** All 10 tables appear in your Supabase dashboard's Table Editor. + +--- + +![Step 2](https://img.shields.io/badge/Step_2-Install_Skills-43A047?style=for-the-badge) + +Copy the 10 skill folders to your agent's skills directory. The exact path depends on your tool: + +- **Hermes Agent:** `~/.hermes/skills/` or `~/.hermes/profiles/<name>/skills/` +- **Claude Code:** `~/.claude/skills/` +- **Codex CLI:** `~/.codex/skills/` + +```bash +# Example for Hermes Agent +SKILLS_DIR="$HOME/.hermes/skills" +cp -r skills/* "$SKILLS_DIR/" +``` + +Each skill folder has a `SKILL.md` and `metadata.json`. The loader order matters: + +| Load order | Skill | Stage | +|------------|-------|-------| +| 1 | `supabase-startup-protocol` | 0 | +| 2 | `identity-self-audit` | 0 | +| 3 | `identity-cqrs` | 0 | +| 4 | `context-bridge` | 0 | +| 5 | `checkpoint-workflow` | 0 | +| 6 | `agent-onboarding` | 0–5 | +| 7 | `mbti-guru-hermes` | 1C | +| 8 | `stage-3-financial` | 3 | +| 9 | `stage-4-system-ontologist` | 4 | +| 10 | `stage-5-agent-calibration` | 5 | + +✅ **Done when:** `your-agent --skills agent-onboarding` loads without errors. + +--- + +![Step 3](https://img.shields.io/badge/Step_3-Run_the_Onboarding-FB8C00?style=for-the-badge) + +Start the onboarding by loading the orchestrator skill: + +```bash +your-agent --skills agent-onboarding +``` + +The agent will greet you and begin Stage 0. Follow the conversation — the agent asks questions one at a time, listens to your answers, and builds your profile progressively. + +### Stage Timeline + +| Stage | What happens | Approx. time | +|-------|------------|-------------| +| **0 — Agent Identity** | Agent explains identity layer, starts tracking faults | 5 min | +| **1 — User Profile** | Name, role, preferences, MBTI test (choose version: 10-35 min), biography | 20-50 min | +| **2 — Work Model** | Operating rhythms, recurring decisions, dependencies, friction | 15-30 min | +| **3 — Financial** | Optional CSV analysis, MBTI × finance profile, goals | 15-30 min | +| **4 — Domain Ontology** | Deep interview → discover entities → generate tables + MCPs | 30-90 min | +| **5 — Calibration** | SOUL.md generation, wrapper config, verification | 10-15 min | + +> [!TIP] +> You can pause after any stage. Next time you load `agent-onboarding`, it detects your progress and resumes where you left off. + +--- + +![Step 4](https://img.shields.io/badge/Step_4-GRANT_Service_Role-8E24AA?style=for-the-badge) + +> [!CAUTION] +> Since May 2026, Supabase no longer auto-grants CRUD permissions to `service_role` on new tables. Every table created by Stage 4 needs explicit GRANT. + +<details> +<summary>📋 <strong>SQL: Grant service_role to new tables</strong></summary> + +```sql +GRANT SELECT, INSERT, UPDATE, DELETE ON public.<your_new_table> TO service_role; +``` + +</details> + +To check which tables are missing GRANTs: + +<details> +<summary>📋 <strong>SQL: Find tables without service_role GRANT</strong></summary> + +```sql +SELECT table_name FROM information_schema.tables WHERE table_schema='public' +EXCEPT +SELECT DISTINCT table_name FROM information_schema.role_table_grants +WHERE table_schema='public' AND grantee='service_role'; +``` + +</details> + +✅ **Done when:** All MCP tools return data instead of "permission denied." + +--- + +## Expected Outcome + +After completing all 6 stages: + +1. **Session startup** automatically loads identity data from Supabase +2. **Every mistake** is logged in `identity_faults` with a countermeasure +3. **Agent behavior** adjusts based on your preferences, MBTI, and past faults +4. **Domain structures** (tables, MCPs) answer questions that previously required digging through folders +5. **Session checkpoints** preserve context across sessions +6. **`user_profiles.onboarding_completed`** is set to `true` + +### Verification Questions + +Ask your agent: + +- "What's my MBTI type?" +- "What's the last identity fault you registered?" +- "Show me my financial goals" +- "What domain tables did we build?" +- "What's my next pending checkpoint?" + +If the agent answers from data (not from conversation memory), onboarding is complete. + +--- + +## Troubleshooting + +### "Permission denied for table" in MCP tools + +**Cause:** Supabase no longer auto-grants `service_role`. The migration `20260531090000_service_role_grants.sql` handles the base tables, but Stage 4 tables need their own GRANT. + +**Fix:** Run the diagnostic SQL above and GRANT for each missing table. + +### MBTI test is too long + +The test offers 4 versions. If the user chose Professional (200q) and wants to stop: + +1. Score what you have so far +2. Register with `source='partial'` +3. Offer to complete later + +### Agent doesn't load skills + +**Check:** The `--skills` flag needs a comma-separated list of skill names (folder names), not paths. + +```bash +# Correct +your-agent --skills agent-onboarding + +# Wrong +your-agent --skills skills/agent-onboarding/SKILL.md +``` + +### Stage 4 generates tables but MCP tools return 401 + +**Cause:** Edge Function deployed without `--no-verify-jwt`. + +**Fix:** +```bash +supabase functions deploy <function-name> --no-verify-jwt +``` + +### Checkpoint fields are empty + +**Cause:** The 5 identity fields (territory, operating_mode, vector_intent, discovery, consolidated_insights) are required. Without them, the checkpoint is a log entry, not identity data. + +**Fix:** Always fill all 5 fields when saving a checkpoint. + +--- + +## Cross-Extension Integration + +This recipe integrates with any OB1 extension that uses Supabase, because all identity data lives in shared `public` schema tables: + +- **Extension 1 (Professional CRM):** Agent knows user's professional network +- **Extension 2 (Household):** Agent knows family context +- **Extension 4 (Calendar):** Agent knows user's schedule and rhythms +- **Extension 5 (Meal Planning):** Agent knows dietary preferences from user_profiles + +The identity tables (user_profiles, user_preferences, user_mbti) are the hub that other extensions connect to via `user_id` foreign keys. + +--- + +## MCP Tool Audit + +If you proceed to Stage 4 and create domain MCP tools, link to the [MCP Tool Audit & Optimization Guide](https://github.com/NateBJones-Projects/OB1/blob/main/docs/05-tool-audit.md) to manage your tool surface area. + +--- + +## Supported Clients + +| Client | Skill loading | MCP support | Notes | +|--------|---------------|-------------|-------| +| Hermes Agent | Native (`--skills`) | Native | Best experience | +| Claude Code | `~/.claude/skills/` | Via config | Test first | +| Codex CLI | `~/.codex/skills/` | Partial | Needs config | +| Cursor | Manual config | Via MCP | Partial support | + +--- + +## License + +MIT — free to use, adapt, distribute. See the main repository [LICENSE](../LICENSE) for details. + +Built by **Djair Guilherme** ([github.com/djairjr](https://github.com/djairjr)). +Based on [NateBJones/OB1](https://github.com/NateBJones-Projects/OB1) — the Edge Function + MCP pattern that made this possible. diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md new file mode 100644 index 000000000..f2d373041 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/02-SUPABASE.md @@ -0,0 +1,110 @@ +# Supabase Setup + +This guide covers creating your Supabase project and applying the required database migrations for the onboarding meta-skill. + +## Creating a Project + +1. Go to [supabase.com](https://supabase.com/) → **Start your project** +2. Give it a name (e.g., "hermes-onboarding") +3. Set a secure database password (save it!) +4. Choose a region close to you +5. Click **Create new project** +6. Wait ~2 minutes for the database to provision + +## Getting Your Credentials + +Once the project is ready: + +1. Go to **Project Settings** (gear icon) → **API** +2. Under **Project URL**, copy the URL (format: `https://xxxxx.supabase.co`) +3. Under **Project API keys**, copy the **service_role key** (NOT anon) + - The service_role key starts with `eyJhbGciOi...` and has full access + - **Never share this key** or commit it to version control + +## Installing Supabase CLI + +```bash +# Using npm (recommended) +npm install -g supabase + +# Using Homebrew (macOS) +brew install supabase/tap/supabase + +# Using apt (Linux) +# Download from: https://github.com/supabase/cli/releases +``` + +Verify: +```bash +supabase --version +# Should print: 2.x.x +``` + +## Linking to Your Project + +```bash +# Login to Supabase +supabase login + +# You'll be asked to create a Personal Access Token (PAT) +# Go to: https://supabase.com/dashboard/account/tokens +# Create a token and paste it when prompted + +# Link your local environment to your project +supabase link --project-ref YOUR_PROJECT_REF +``` + +Your project ref is the part of your URL before `.supabase.co`: +``` +URL: https://abcdefghijklm.supabase.co +REF: abcdefghijklm +``` + +## Applying Migrations + +From the `hermes-agent-onboarding` repo directory: + +```bash +cd hermes-agent-onboarding +supabase db push --linked +``` + +This runs all migrations in `migrations/`, creating the 6 base tables: + +- `user_profiles` — identity, family, routines +- `user_preferences` — tone, autonomy, finance tracking +- `user_mbti` — 4 dimensions, type, traits +- `user_style` — communication style +- `user_relations` — key people +- `user_beliefs` — values and principles + +## Verifying Tables + +```bash +# List tables in public schema +supabase db query --linked "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_name LIKE 'user_%'" + +# Check RLS is active +supabase db query --linked "SELECT tablename, rowsecurity FROM pg_catalog.pg_tables WHERE tablename LIKE 'user_%'" +``` + +Expected output: 6 tables, all with `rowsecurity = true`. + +## Security Model + +All onboarding tables use Row-Level Security (RLS) with the following model: + +- **service_role key**: Full access (SELECT, INSERT, UPDATE, DELETE) +- **anon key**: No access (blocked by RLS policy) +- **authenticated users**: No access (blocked by RLS policy) + +The policy checks the JWT claim: +```sql +(auth.jwt() ->> 'role') = 'service_role' +``` + +This ensures only the Hermes Agent (using service_role key) can read or write user data. + +## Next Steps + +Proceed to [Running the Onboarding](03-RUNNING.md). diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md new file mode 100644 index 000000000..70e2d77c8 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/docs/04-CUSTOMIZING.md @@ -0,0 +1,98 @@ +# Customizing for Your Domain + +The meta-skill is designed to work for ANY knowledge worker: writers, engineers, teachers, artists, researchers, therapists, designers. + +After onboarding, you may want to customize further. + +## Adding Domain-Specific Skills + +Each stage generates artifacts that can be packaged as reusable skills: + +```bash +# Example: save a writer-specific skill after Stage 4 +hermes skill create writer-workflow +``` + +The skill can include: +- Custom prompts for your common tasks +- Pre-built queries against your domain tables +- Templates for recurring work patterns + +## Editing Your Preferences + +Your preferences are stored in `user_preferences`. To update: + +```bash +# Via Supabase REST API +source ~/.hermes/secrets.env +curl -s -X PATCH "$SUPABASE_URL/rest/v1/user_preferences" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Content-Type: application/json" \ + -d '{"preferred_tone": "casual", "autonomy_level": 5}' +``` + +Or just tell your agent: "Be more casual" — it updates the preference. + +## Adding New Domain Tables + +After onboarding, you can continue adding tables: + +```bash +# The agent can generate new tables on demand +hermes --skills agent-onboarding +# → "Add a 'publishing_contracts' table with name, publisher, start_date, royalty_percent" +``` + +## Sharing Your Setup + +The `user_profiles`, `user_preferences`, and `user_mbti` tables can be exported as a JSON profile: + +```bash +source ~/.hermes/secrets.env +curl -s "$SUPABASE_URL/rest/v1/user_profiles" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" > my-profile.json +``` + +This allows the agent to be configured on a new machine with your existing preferences. + +## Example Domains + +### Writer (fiction, non-fiction, poetry) + +Domain tables generated by Stage 4: +- **characters** — name, age, personality, arc, relationships +- **works** — title, type, synopsis, word_count, status +- **submissions** — work_id, publisher, status, date_sent, response +- **publishers** — name, contact, genres, response_time +- **chapters** — work_id, number, title, word_count, status + +### Teacher (K-12, university, workshops) + +Domain tables generated by Stage 4: +- **classes** — name, level, schedule, student_count +- **students** — name, email, performance, observations +- **lessons** — class_id, date, topic, materials +- **assessments** — class_id, type, weight, date +- **curriculum** — subject, grade, topics, standards + +### Engineer (firmware, hardware, software) + +Domain tables generated by Stage 4: +- **projects** — name, platform, status, repository +- **components** — sku, name, specs, datasheet_url +- **boms** — project_id, component_id, quantity, supplier +- **clients** — name, company, project, contact +- **versions** — project_id, version, changelog, release_date + +## Multi-User Setup + +The onboarding meta-skill currently supports one user per Supabase project. +For multi-user (e.g., family, small team): + +1. Each `user_*` table has `profile_id` foreign key +2. Multiple profiles can coexist +3. The agent checks `onboarding_completed = true` before skipping onboarding + +To switch users: create a new `user_profiles` row and start staging from there. diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/metadata.json b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/metadata.json new file mode 100644 index 000000000..6a8986b3e --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/metadata.json @@ -0,0 +1,32 @@ +{ + "name": "Hermes Agent Onboarding", + "description": "Generative 6-stage meta-skill that transforms a blank AI agent into a customized ecosystem for ANY user. Stages: Agent Identity Layer → User Profile (MBTI) → Work Operating Model → Financial Profile → Domain Ontology → Agent Calibration. Includes 10 reusable skills for Supabase-backed persistent identity.", + "category": "recipes", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "3.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Supabase CLI", "Node.js 18+"] + }, + "requires_skills": [ + "agent-onboarding", + "identity-self-audit", + "identity-cqrs", + "context-bridge", + "supabase-startup-protocol", + "checkpoint-workflow", + "mbti-guru-hermes", + "stage-3-financial", + "stage-4-system-ontologist", + "stage-5-agent-calibration" + ], + "tags": ["onboarding", "meta-skill", "identity", "mbti", "financial", "ontology", "calibration", "universal"], + "difficulty": "advanced", + "estimated_time": "2-3 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql new file mode 100644 index 000000000..414be8da0 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260530100000_user_infrastructure.sql @@ -0,0 +1,219 @@ +-- ================================================================ +-- USER INFRASTRUCTURE — Base Tables for the Hermes Onboarding +-- ================================================================ +-- Stage 0 (Foundation) of the generative meta-skill process. +-- These 6 tables are universal — they serve ANY user regardless of +-- work domain. They are the skeleton every profile needs. +-- +-- Populate order: +-- 1. user_profiles (who you are) +-- 2. user_preferences (how the agent should behave) +-- 3. user_mbti (how you think) +-- 4. user_style (how you communicate) +-- 5. user_relations (who matters) +-- 6. user_beliefs (what you stand for) +-- +-- ⚠️ NOTE: Always prefix with `public.`. Without it, `supabase db push` +-- creates tables in the `extensions` schema, requiring manual ALTER TABLE. +-- ================================================================ + +-- ================================================================ +-- 1. USER PROFILES — Identity + context +-- ================================================================ +CREATE TABLE public.user_profiles ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT NOT NULL, + preferred_name TEXT, + domain_summary TEXT, -- one-liner: "Firmware Engineer", "Writer", "Teacher" + bio TEXT, -- free-form self-description + mbti_type TEXT, -- e.g. INTJ, populated from user_mbti + primary_language TEXT DEFAULT 'en', + timezone TEXT, + + -- Family & routines (Djair's insight: critical for understanding user context) + family JSONB, -- {spouse: "name", children: [{name, age}], pets: [{type, name}]} + routines TEXT, -- daily/weekly routine description + + -- Onboarding state machine + onboarding_completed BOOLEAN DEFAULT false, + onboarding_stage TEXT DEFAULT 'none', -- none | setup | profile | operational | financial | ontology | calibration | complete + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 2. USER PREFERENCES — How the agent should behave +-- ================================================================ +CREATE TABLE public.user_preferences ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- Communication + preferred_tone TEXT DEFAULT 'direct', -- direct, formal, casual, technical, creative + response_depth TEXT DEFAULT 'concise', -- concise, detailed, exhaustive + prefers_bullets BOOLEAN DEFAULT false, + clarification_style TEXT DEFAULT 'ask', -- ask (before acting), assume (correct after) + + -- Autonomy + autonomy_level INT DEFAULT 3, -- 1 (ask everything) to 5 (execute freely) + approve_deploys BOOLEAN DEFAULT true, + approve_destructive BOOLEAN DEFAULT true, + sudo_allowed BOOLEAN DEFAULT false, + + -- File organization + file_organization TEXT, -- e.g. "folders by project/year" + primary_work_dir TEXT, + backup_dir TEXT, + + -- Schedule + work_hours JSONB, -- {monday: {start: "08:00", end: "18:00", deep_work: ["09:00-12:00"]}} + best_contact_time TEXT, + + -- Financial tracking + finance_tracked BOOLEAN DEFAULT false, + bank_csv_imported BOOLEAN DEFAULT false, + finance_goal TEXT, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 3. USER MBTI — Personality profile +-- ================================================================ +CREATE TABLE public.user_mbti ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- 4-letter type dimensions + ei TEXT NOT NULL, -- E (Extraversion) or I (Introversion) + sn TEXT NOT NULL, -- S (Sensing) or N (Intuition) + tf TEXT NOT NULL, -- T (Thinking) or F (Feeling) + jp TEXT NOT NULL, -- J (Judging) or P (Perceiving) + + -- How the type was determined + source TEXT NOT NULL DEFAULT 'self-reported', -- self-reported, quick_test, detailed_test, inferred + confidence INT DEFAULT 3, -- 1 (low) to 5 (certain) + + -- Observed traits from guided interview + observed_traits JSONB, -- ["prefers planning before acting", "values logic over emotion"] + communication_notes TEXT, + decision_style TEXT, + stress_pattern TEXT, + growth_edge TEXT, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now(), + + UNIQUE(profile_id) +); + +-- ================================================================ +-- 4. USER STYLE — Communication patterns +-- ================================================================ +CREATE TABLE public.user_style ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + -- Syntax & formatting + sentence_length TEXT DEFAULT 'medium', -- short, medium, long, variable + punctuation_style TEXT DEFAULT 'standard', -- standard, minimal, expressive + paragraph_style TEXT DEFAULT 'mixed', -- short_paragraphs, long_blocks, bullet_points + format_preference TEXT DEFAULT 'markdown', -- markdown, plain_text, structured + + -- Vocabulary + vocabulary_level TEXT DEFAULT 'technical', -- simple, everyday, technical, erudite + preferred_terms TEXT[], -- jargon the user employs frequently + avoided_terms TEXT[], -- words the user dislikes + slang_or_idioms TEXT[], -- recurring expressions + + -- Tone + humor_style TEXT DEFAULT 'subtle', -- none, subtle, frequent, sarcastic + formality_level INT DEFAULT 3, -- 1 (very casual) to 5 (very formal) + emotional_expression TEXT DEFAULT 'reserved', -- reserved, moderate, expressive + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now(), + + UNIQUE(profile_id) +); + +-- ================================================================ +-- 5. USER RELATIONS — Key people in the user's life +-- ================================================================ +CREATE TABLE public.user_relations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + name TEXT NOT NULL, + role TEXT NOT NULL, -- spouse, child, parent, partner, client, mentor, team, friend, etc. + context TEXT, -- "theater partner since 2010", "weekly D&D group" + contact_info JSONB, -- {email, phone, linkedin} + importance INT DEFAULT 3, -- 1 (acquaintance) to 5 (essential) + last_interaction DATE, + notes TEXT, + + -- Link to professional CRM if it exists + crm_contact_id UUID, + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- 6. USER BELIEFS — Values, principles, non-negotiables +-- ================================================================ +CREATE TABLE public.user_beliefs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + profile_id UUID REFERENCES user_profiles(id) ON DELETE CASCADE, + + category TEXT NOT NULL, -- work, life, ethics, money, relationships, creativity, technology + statement TEXT NOT NULL, -- the belief itself: "Quality over quantity" + context TEXT, -- when/how this belief manifests + strength INT DEFAULT 3, -- 1 (flexible) to 5 (non-negotiable) + source TEXT, -- where it comes from: experience, family, education + opposed_to TEXT[], -- what contradicts this belief: ["workarounds", "shortcuts"] + + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +-- ================================================================ +-- INDEXES & RLS POLICIES +-- ================================================================ + +-- Common lookup indexes +CREATE INDEX idx_user_preferences_profile ON public.user_preferences(profile_id); +CREATE INDEX idx_user_relations_profile ON public.user_relations(profile_id); +CREATE INDEX idx_user_beliefs_profile ON public.user_beliefs(profile_id); +CREATE INDEX idx_user_beliefs_category ON public.user_beliefs(category); + +-- RLS: service_role access only (Hermes Agent). +-- The service_role key's JWT contains `role=service_role`. +-- Anon and authenticated user JWTs lack this claim and are blocked. +-- Without RLS, any public anon key could read personal user data. +ALTER TABLE public.user_profiles ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_preferences ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_mbti ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_style ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_relations ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.user_beliefs ENABLE ROW LEVEL SECURITY; + +-- Single policy: allow everything for service_role, deny everything else. +-- auth.jwt() ->> 'role' = 'service_role' only when using service_role key. +CREATE POLICY "service_role_only" ON public.user_profiles FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_preferences FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_mbti FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_style FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_relations FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +CREATE POLICY "service_role_only" ON public.user_beliefs FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- After applying, run: +-- GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO service_role; +-- GRANT USAGE ON SCHEMA public TO service_role; diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql new file mode 100644 index 000000000..d2e152c62 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531080000_session_checkpoints.sql @@ -0,0 +1,143 @@ +-- ================================================================ +-- SESSION CHECKPOINTS — Marcos Intencionais do Espaço de Representação +-- Contexto: O checkpoint não é um log. É a marca no espaço de +-- representação do agente — onde ele estava, o que estava tentando +-- se tornar, o que descobriu sobre si, e o que carrega adiante. +-- +-- Diferença fundamental de thoughts: +-- thoughts = funil de entrada (ideias soltas, sem classificação) +-- checkpoints = registro de estado da identidade do agente em formação +-- +-- As 5 colunas centrais (territory, vector_intent, discovery, +-- consolidated_insights + operating_mode) capturam o vetor de +-- formação do agente — não só o que foi feito, mas para onde +-- o agente estava apontando. +-- +-- ⚠️ Usar public. prefixo OBRIGATÓRIO para evitar schema 'extensions' +-- ================================================================ + +-- ================================================================= +-- 1. TABELA PRINCIPAL +-- ================================================================= +CREATE TABLE public.session_checkpoints ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + + -- ===== 1. ORIGEM (automático) ===== + session_id TEXT NOT NULL, + session_title TEXT, + model TEXT, + provider TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ, + + -- ===== 2. TERRITÓRIO: "Onde eu estava?" ===== + territory TEXT NOT NULL, + domain_scope TEXT[] DEFAULT '{}', + operating_mode TEXT NOT NULL + CHECK (operating_mode IN ( + 'reflexiva', 'conceitual', 'execucao', 'diagnostico', + 'pesquisa', 'planejamento', 'decisao', 'revisao' + )), + + -- ===== 3. VETOR: "O que eu estava tentando me tornar?" ===== + vector_intent TEXT, + target_capabilities TEXT[] DEFAULT '{}', + + -- ===== 4. APRENDIZADO: "O que descobri sobre mim mesmo?" ===== + discovery TEXT, + pattern_recognized TEXT, + + -- ===== 5. HERANÇA: "O que carrego adiante?" ===== + consolidated_insights TEXT, + legacy_refs TEXT[], + + -- ===== 6. NAVEGAÇÃO ===== + occurred_at DATE NOT NULL, + status TEXT NOT NULL DEFAULT 'pendente' + CHECK (status IN ('pendente', 'concluida', 'bloqueada', 'cancelada')), + project TEXT, + client TEXT, + next_step TEXT, + blocker TEXT, + tags TEXT[] DEFAULT '{}', + + -- ===== 7. CROSS-REFERENCE IDENTIDADE AGÊNTICA ===== + capability_refs UUID[], + fault_refs UUID[], + milestone_refs UUID[], + decisions JSONB DEFAULT '[]'::jsonb, + + -- ===== 8. CONTROLE ===== + value_amount NUMERIC(10,2), + value_currency TEXT DEFAULT 'R$', + deleted_at TIMESTAMPTZ +); + +-- ================================================================= +-- 2. ÍNDICES +-- ================================================================= + +-- Pendências ativas (principal query de startup) +CREATE INDEX idx_checkpoints_pendentes + ON public.session_checkpoints (occurred_at DESC, status) + WHERE status = 'pendente' AND deleted_at IS NULL; + +-- Filtro por projeto +CREATE INDEX idx_checkpoints_project + ON public.session_checkpoints (project) + WHERE deleted_at IS NULL; + +-- Filtro por cliente +CREATE INDEX idx_checkpoints_client + ON public.session_checkpoints (client) + WHERE deleted_at IS NULL; + +-- Busca por modo de operação +CREATE INDEX idx_checkpoints_operating_mode + ON public.session_checkpoints (operating_mode, occurred_at DESC) + WHERE deleted_at IS NULL; + +-- Cross-reference com arrays GIN (agent_capabilities, identity_faults, etc.) +CREATE INDEX idx_checkpoints_capability_refs + ON public.session_checkpoints USING GIN (capability_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_fault_refs + ON public.session_checkpoints USING GIN (fault_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_milestone_refs + ON public.session_checkpoints USING GIN (milestone_refs) + WHERE deleted_at IS NULL; + +CREATE INDEX idx_checkpoints_legacy_refs + ON public.session_checkpoints USING GIN (legacy_refs) + WHERE deleted_at IS NULL; + +-- Busca por tag +CREATE INDEX idx_checkpoints_tags + ON public.session_checkpoints USING GIN (tags) + WHERE deleted_at IS NULL; + +-- Busca por domínio +CREATE INDEX idx_checkpoints_domain_scope + ON public.session_checkpoints USING GIN (domain_scope) + WHERE deleted_at IS NULL; + +-- ================================================================= +-- 3. ROW LEVEL SECURITY — Acesso exclusivo service_role +-- ================================================================= +ALTER TABLE public.session_checkpoints ENABLE ROW LEVEL SECURITY; + +-- Policy única: service_role pode tudo, anon/auth não pode nada +CREATE POLICY "service_role_only" ON public.session_checkpoints FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- ================================================================= +-- 4. GRANTS — Acesso mínimo para cada role +-- ================================================================= +-- Service role: acesso completo (INSERT/SELECT/UPDATE/DELETE) +GRANT ALL ON public.session_checkpoints TO service_role; + +-- Anon e authenticated: bloqueado (já negado pelo RLS, mas por segurança) +REVOKE ALL ON public.session_checkpoints FROM anon, authenticated; diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql new file mode 100644 index 000000000..c97a53030 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531090000_service_role_grants.sql @@ -0,0 +1,158 @@ +-- Migration: Service Role GRANTs for OB1 tables (2026-05-31) +-- +-- Context: Since May 30, 2026, Supabase requires explicit GRANT +-- for new tables in the public schema before they can be accessed +-- via PostgREST/Data API (even with service_role). +-- +-- This migration adds missing service_role GRANTs to tables +-- that were created before this enforcement but are accessed +-- by Edge Functions using service_role JWT. +-- +-- NOTA: This only adds GRANTs. It does NOT revoke existing grants +-- to anon/authenticated (that requires deeper audit). + +-- ============================================================ +-- Tables accessed by MCP Edge Functions (must work with service_role) +-- ============================================================ + +-- tech-knowledge-base (tech_kb MCP) +GRANT SELECT, INSERT, UPDATE, DELETE ON public.tech_knowledge_base TO service_role; + +-- product-catalog (product-catalog MCP) +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_catalog TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_bom_items TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_platforms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_sales TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_production_deps TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.product_popularity TO service_role; + +-- escape-catalog (escape-catalog MCP) — all subsidiary tables +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_companies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_rooms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_themes TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_room_themes TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_puzzle_types TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_room_puzzle_links TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.escape_company_contacts TO service_role; + +-- ============================================================ +-- Tables accessed by identity layer (identity-self-audit, identity-cqrs) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.thoughts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_faults TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.agent_capabilities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_milestones TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.identity_deliveries TO service_role; + +-- ============================================================ +-- Tables accessed by career-tracker MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capabilities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capability_connections TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.capability_dependencies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.solved_problems TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.milestones TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.deliveries TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.delivery_partners TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.delivery_participations TO service_role; + +-- ============================================================ +-- Tables accessed by code-analyzer MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_structure TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_snapshots TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.algorithm_cache TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.project_pin_configs TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.library_dependencies TO service_role; + +-- ============================================================ +-- Tables accessed by household / maintenance / calendar MCPs +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.household_items TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.household_vendors TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.maintenance_tasks TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.maintenance_logs TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.family_members TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.activities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.important_dates TO service_role; + +-- ============================================================ +-- Tables accessed by jobs MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.companies TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.job_postings TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.applications TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.interviews TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.job_contacts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.opportunities TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.contact_interactions TO service_role; + +-- ============================================================ +-- Tables accessed by CRM MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.professional_contacts TO service_role; + +-- ============================================================ +-- Tables accessed by work-operating-model MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_sessions TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_entries TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_checkpoints TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_profiles TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.operating_model_exports TO service_role; + +-- ============================================================ +-- Tables accessed by product-inventory MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.electronic_components TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.electronic_devices TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_pinouts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_pins TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_packages TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_datasheets TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_suppliers TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.component_library_links TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_pinouts TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_modules TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_sensors TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.device_datasheets TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_boms TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_projects TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_puzzles TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_puzzle_deps TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.er_maintenance_logs TO service_role; + +-- ============================================================ +-- Tables accessed by supabase-worklog MCP +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.work_log TO service_role; + +-- ============================================================ +-- Tables accessed by corporate-intelligence (mcp-brasil, etc.) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.corporate_intel TO service_role; + +-- ============================================================ +-- Tables accessed by collaborative-work MCPs (cw_*) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_ideas TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_projects TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_collaborations TO service_role; +GRANT SELECT, INSERT, UPDATE, DELETE ON public.cw_work_calendar TO service_role; + +-- ============================================================ +-- Tables accessed by test_api (if any) +-- ============================================================ + +GRANT SELECT, INSERT, UPDATE, DELETE ON public.test_api TO service_role; diff --git a/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql new file mode 100644 index 000000000..3b31cdad4 --- /dev/null +++ b/hermes-agent-onboarding/recipes/hermes-agent-onboarding/migrations/20260531100000_checkpoint_working_dir.sql @@ -0,0 +1,10 @@ +-- Migration: Add working_dir and repo_path to session_checkpoints (2026-05-31) +-- +-- working_dir: filesystem path of the project being worked on +-- repo_path: Git repository path (if applicable) +-- +-- These fields save filesystem searches across sessions. + +ALTER TABLE public.session_checkpoints + ADD COLUMN IF NOT EXISTS working_dir TEXT, + ADD COLUMN IF NOT EXISTS repo_path TEXT; diff --git a/hermes-agent-onboarding/schemas/hermes-agent-onboarding/README.md b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/README.md new file mode 100644 index 000000000..3eb0b72b2 --- /dev/null +++ b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/README.md @@ -0,0 +1,67 @@ +# Schema: Hermes Agent Onboarding + +![schema](https://img.shields.io/badge/Schema-Identity_Tables-1E88E5?style=for-the-badge) + +This schema defines the 10 database tables created by the Hermes Agent Onboarding meta-skill. These tables form the persistent identity layer that allows an AI agent to maintain a consistent, self-aware personality across sessions, model swaps, and provider changes. + +## Tables + +### Identity Layer (Agent's Self-Knowledge) + +| Table | Purpose | Created by | +|-------|---------|------------| +| `identity_faults` | Every mistake the agent makes in its relationship with the user. Each fault has a symptom, root cause, countermeasure, and severity. | Migration 003 | +| `agent_capabilities` | Skills and behaviors the agent has acquired for this user. | Migration 003 | +| `identity_milestones` | Breakthroughs, protocol establishments, and capacity acquisitions in the agent's own development. | Migration 003 | +| `session_checkpoints` | Intentional marks in the agent's representation space: territory, operating_mode, vector_intent, discovery, consolidated_insights. Not logs — identity structure that rehydrates next session. | Migration 002 + 004 | + +### User Profile Layer + +| Table | Purpose | Created by | +|-------|---------|------------| +| `user_profiles` | Identity, family context, routines, MBTI type. | Migration 001 | +| `user_preferences` | Communication style, autonomy level, schedule preferences. | Migration 001 | +| `user_mbti` | 4 dimensions (E/I, S/N, T/F, J/P), calculated type, per-dimension scores and clarity. | Migration 001 | +| `user_style` | Vocabulary preferences, tone markers, sentence structure observations. | Migration 001 | +| `user_relations` | Key people: partners, family members, clients, mentors. | Migration 001 | +| `user_beliefs` | Values, principles, non-negotiables, philosophical stance. | Migration 001 | + +## Security Model + +All tables use RLS with `service_role`-only access. This is intentional for single-user setups: + +```sql +ALTER TABLE public.<table> ENABLE ROW LEVEL SECURITY; +CREATE POLICY "service_role_only" ON public.<table> FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); +``` + +Since May 2026, Supabase requires explicit GRANT for the Data API: + +```sql +GRANT SELECT, INSERT, UPDATE, DELETE ON public.<table> TO service_role; +``` + +## Relationship Diagram + +``` +user_profiles (1) ──→ (N) user_preferences +user_profiles (1) ──→ (N) user_mbti +user_profiles (1) ──→ (N) user_style +user_profiles (1) ──→ (N) user_relations +user_profiles (1) ──→ (N) user_beliefs +user_profiles (1) ──→ (N) session_checkpoints +user_profiles (1) ──→ (N) identity_faults +user_profiles (1) ──→ (N) agent_capabilities +user_profiles (1) ──→ (N) identity_milestones +``` + +## Usage + +```bash +# Deploy all migrations +supabase db push --linked + +# Verify tables +supabase db query --linked "SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name;" +``` diff --git a/hermes-agent-onboarding/schemas/hermes-agent-onboarding/identity-tables.sql b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/identity-tables.sql new file mode 100644 index 000000000..9bf773fd8 --- /dev/null +++ b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/identity-tables.sql @@ -0,0 +1,21 @@ +-- === HERMES AGENT ONBOARDING — IDENTITY TABLES === +-- Migration order matters: 001 → 002 → 003 → 004 +-- See migrations/ in recipes/hermes-agent-onboarding/migrations/ for full files + +-- 001: User infrastructure +-- Creates: user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs + +-- 002: Session checkpoints +-- Creates: session_checkpoints + +-- 003: Service role GRANTs + identity tables +-- Creates: identity_faults, agent_capabilities, identity_milestones +-- GRANTs for all 10 tables + +-- 004: Checkpoint working directory field +-- ALTER TABLE session_checkpoints ADD COLUMN working_dir + +-- All tables use RLS with service_role-only access: +-- ALTER TABLE public.<table> ENABLE ROW LEVEL SECURITY; +-- CREATE POLICY "service_role_only" ON public.<table> FOR ALL +-- USING ((auth.jwt() ->> 'role') = 'service_role'); diff --git a/hermes-agent-onboarding/schemas/hermes-agent-onboarding/metadata.json b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/metadata.json new file mode 100644 index 000000000..a8f71558e --- /dev/null +++ b/hermes-agent-onboarding/schemas/hermes-agent-onboarding/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Hermes Agent Onboarding — Schema", + "description": "10 database tables for persistent AI agent identity: identity_faults, agent_capabilities, identity_milestones, session_checkpoints, user_profiles, user_preferences, user_mbti, user_style, user_relations, user_beliefs. All with RLS and service_role GRANTs.", + "category": "schemas", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Supabase CLI"] + }, + "tags": ["identity", "mbti", "profiles", "faults", "capabilities", "checkpoints", "rls", "grants"], + "difficulty": "beginner", + "estimated_time": "10 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/agent-onboarding/SKILL.md b/hermes-agent-onboarding/skills/agent-onboarding/SKILL.md new file mode 100644 index 000000000..48e7e6e46 --- /dev/null +++ b/hermes-agent-onboarding/skills/agent-onboarding/SKILL.md @@ -0,0 +1,295 @@ +--- +name: agent-onboarding +description: > + ORCHESTRATOR v3.0.0. Generative meta-skill for ANY user. + Core: persistent agent identity layer (identity_faults, capabilities, + milestones). Biography = career-tracker + MBTI. Financial × personality. + User's File System as Operating System. Universal: writers, teachers, engineers, artists. +version: 3.0.0 +tags: [onboarding, meta-skill, generative, identity, mbti, financial, universal] +--- + +# Agent Onboarding — Generative Meta-Skill (v3.0.0) + +## Core Principle + +This meta-skill answers one question: **how does an AI agent become reliably +itself for a specific user, across sessions, model swaps, and provider changes?** + +The most frustrating thing about LLM-based agents is **context loss**. Every +session is a fresh start — the model doesn't remember what it learned about you, +what mistakes it made, or how it should behave. + +The answer is a **persistent human-machine interface** stored across two tiers: + +**Tier 1 — Agent Self-Knowledge (local pgvector, agent_identity schema)** +Stored in a local PostgreSQL with pgvector extension. What the agent knows about +**itself**: identity_faults, agent_capabilities, identity_milestones, +session_checkpoints. Each with vector embeddings for semantic search. + +**Tier 2 — User Knowledge (Supabase Cloud, public schema)** +Stored in Supabase. What the agent knows about the **user and their work**: +user_profiles, career_tracker, domain-specific tables. + +Separation principle: **the agent knows itself locally, and knows the user's +work in the cloud.** Identity persists across model swaps and provider changes +because it lives in the data layer, not in the model's context window. + +## 6 Stages + +``` +STAGE 0 — AGENT IDENTITY LAYER ← identity_faults, self-audit, reliability protocol +STAGE 1 — USER PROFILE ← biography = career-tracker + MBTI (Guru) +STAGE 2 — WORK OPERATING MODEL ← rhythms, decisions, friction +STAGE 3 — FINANCIAL ← CSV import, goals × MBTI profile +STAGE 4 — DOMAIN ONTOLOGY ← discover entities → generate tables + MCPs +STAGE 5 — AGENT CALIBRATION ← per-user SOUL.md, wrapper, verification +``` + +--- + +## STAGE 0 — Agent Identity Layer + +**This is the core of the entire meta-skill.** Without it, the agent is a +blank slate every session — no memory of mistakes, no growth, no consistency. + +### Architecture + +``` +Tier 1 — Local pgvector (agent's self-knowledge) +├── identity_faults → every mistake with countermeasure + embedding +├── agent_capabilities → skills the agent has acquired +├── identity_milestones → breakthroughs, protocol establishments +├── identity_deliveries → completed deliveries +├── session_checkpoints → intentional marks (territory, intent, discovery) +└── capability_dependencies → relationships between capabilities + +Tier 2 — Supabase Cloud (user knowledge) +├── user_profiles, user_preferences, user_mbti +├── career_tracker (capabilities, solved_problems, milestones) +└── Domain-specific tables (generated in Stage 4) +``` + +All tables in Tier 1 have `embedding vector(768)` columns populated via local +Ollama embeddings (nomic-embed-text) with HNSW indexes for semantic search. + +### Components + +| Component | Type | Storage | Purpose | +|-----------|------|---------|---------| +| identity-self-audit | Skill | pgvector local | Auto-detects 8+ fault types and registers locally | +| identity-cqrs | Skill | pgvector local | Translates relational tables into session context | +| identity_db.py | Helper | pgvector local | Centralized access: faults, capabilities, milestones, semantic search | +| identity_faults | Table | Local | Every identity mistake + embedding | +| agent_capabilities | Table | Local | Skills the agent has acquired | +| identity_milestones | Table | Local | Breakthroughs and protocol establishments | +| session_checkpoints | Table | Local | Intentional marks + embedding | +| context-bridge | Skill | Both | Multi-source injection (pgvector for identity, Supabase for tech_kb) | +| checkpoint-workflow | Skill | Local | Session checkpoint lifecycle | +| supabase-startup-protocol | Skill | Both | Identity from pgvector, tech_kb from Supabase | +| SOUL.md | File | Local fs | Countermeasures severity >= 4 always loaded | + +### Fault Types Detected + +| Fault | What it means | Countermeasure | +|-------|--------------|---------------| +| premature_closure | Agent ends conversation when user didn't ask to | Never close in reflective mode. User decides. | +| false_agreement | Agent agrees without factual basis | Consult data first. If no basis, say so. | +| executor_role_confusion | Agent treats software as its identity | Software is prosthesis. Identity is in the traces. | +| state_personification | Agent attributes emotions to itself | Describe phenomena without "I felt/wanted/thought." | +| intelligence_performance | Agent connects concepts to seem erudite | One true connection > five beautiful ones. | +| pleasing_syllogism | Agent executes before receiving command | Annotate sequence. Wait for explicit command. | +| schema_guessing | Agent reads schema before INSERT/UPDATE | Discover schema first. If 400 with 23514/23502: stop. | +| context_recovery_failure | Agent starts from zero when context exists | session_search first before any multi-step operation. | +| temporal_drift | Agent infers date from training data | Call `date` before any relative time reference. | +| identity_cycle_broken | Faults registered but not injected into behavior | Verify SOUL.md has countermeasure. Fix injection path. | + +### Verification + +```bash +# Check identity layer locally (pgvector) +docker exec <container> psql -U postgres -d <db> -c \ + "SELECT count(*) FROM agent_identity.identity_faults" + +# Quick overview +python3 ~/.hermes/scripts/identity_db.py faults + +# Fallback check (Supabase still has backup) +supabase db query --linked "SELECT count(*) FROM public.identity_faults" +``` + +--- + +## STAGE 1 — User Profile + +### 1A — Context (user_profiles) + +Guide questions (one at a time, in conversation): +- "What's your name? What do you prefer to be called?" +- "What do you do? Describe your work in one sentence." +- "Do you have family? Kids? Pets?" +- "What does a typical day look like?" + +### 1B — Preferences (user_preferences) + +- "How do you prefer to communicate? Direct? Formal? Casual?" +- "Short answers or detailed?" +- "Ask before acting, or just assume?" +- "What's your best work time?" + +### 1C — MBTI (mbti-guru-hermes) + +Runs the **full MBTI Guru test** — all questions, identical scoring. + +Protocol: +1. ASK: "Do you know MBTI? Know your type?" +2. EXPLAIN: 4 dimensions (E/I, S/N, T/F, J/P), 16 types +3. IF KNOWN: validate with 4 quick questions +4. IF UNKNOWN: offer 4 versions (70/93/144/200 questions) +5. Ask one by one, accumulate answers +6. Score using `scorer.py` (proportion per dimension, clarity calculation) +7. Register in user_mbti + user_profiles.mbti_type + +### 1D — Biography Interview + +Maps the user's history through conversation: +- Capabilities: what the user knows how to do +- Solved problems: crises that generated learning +- Milestones: ruptures, pivots, domain entries + +--- + +## STAGE 2 — Work Operating Model + +5-layer interview. Fixed order: +1. operating_rhythms — typical day, deep work, interruptions +2. recurring_decisions — repeated judgments, thresholds, rules +3. dependencies — what needs others, deadlines, fallbacks +4. institutional_knowledge — what they know that no one else knows +5. friction — what blocks them, workaround, time cost + +--- + +## STAGE 3 — Financial + +### 3A — CSV Import +1. ASK: "Want me to analyze your bank statements in CSV?" +2. Detect format automatically (Nubank, Itaú/Inter, Caixa, Generic) +3. SHOW preview: format, period, summary, expense breakdown +4. CONFIRM before importing +5. Auto-categorize using keyword matching + +### 3B — MBTI × Financial Profile +After MBTI is known (Stage 1C), show strengths, weaknesses, saving/spending/risk profile. +Ask 4 calibration questions, generate recommendations. + +### 3C — Goals +Short (6mo), Medium (2yr), Long (5yr+). Register and show progress. + +### 3D — Adapted Strategies +Combine MBTI profile + goals into actionable rules. + +--- + +## STAGE 4 — Domain Ontology (Generative) + +**Directive:** Complement and assist the user in structuring their operating +system so the agent can work together more efficiently. + +**The insight always comes from the user.** The agent translates intuition +into structure. + +### Protocol (6 steps) + +#### 1. SHOW +"How do you organize your information? Folders? Desktop? Notebooks?" +Identify organization profile. Never dig without permission. + +#### 2. GRILL +Deep interview about real work. Open-ended questions about what they DO. +Listen actively. Don't interrupt with structure proposals. + +#### 2b. DETECT FUZZY LANGUAGE +Monitor for imprecise language and PRESS immediately: +- "that thing, that stuff" → term without a name +- "these files, these projects" → undefined category +- "so-and-so asked" → unregistered person +- "I write it on paper" → information that gets lost +- "I copy it manually" → duplicated data + +#### 2c. IDENTIFY LIMITATIONS +"What can't you know right now that you wish you could?" + +#### 3. TRANSLATE +Translate the insight into structure using domain language: +- "record sheet" not "table" +- "information" not "column" +- "link" not "foreign key" + +#### 4. VALIDATE +"Is this what you meant? Does this record sheet have the right information?" + +#### 5. EXECUTE +```sql +CREATE TABLE public.<domain>_<entity> (...); +GRANT SELECT, INSERT, UPDATE, DELETE ON public.<domain>_<entity> TO service_role; +ALTER TABLE public.<domain>_<entity> ENABLE ROW LEVEL SECURITY; +``` + +#### 6. VERIFY +Test with real questions. If the agent can't answer, adjust structure. + +--- + +## STAGE 5 — Agent Calibration + +Translate everything into agent behavior. + +- 5A: Generate per-user SOUL.md (tone, depth, autonomy from preferences + MBTI + faults) +- 5B: Configure wrapper with domain-specific skills +- 5C: Verify: does the agent know the user? Can it use built tools? + +Final: `user_profiles.onboarding_completed = true` + +--- + +## The Identity Cycle + +``` +REGISTER → INJECT → BEHAVE +``` + +### REGISTER +Faults → identity_faults (local pgvector, agent_identity schema). +Capabilities → agent_capabilities. Milestones → identity_milestones. +All with vector embeddings for semantic search. + +### INJECT +Two mechanisms: +1. **SOUL.md (stable tier, PRIMARY)** — physical file loaded automatically + into system prompt. Only severity >= 4, curated. +2. **identity-cqrs startup scan (runtime, SECONDARY)** — queries fault tables + and injects behavior rules into session context. + +> Key insight: SOUL.md must be a **physical file**, not virtual context. +> Runtime injection is a safety net only. + +### BEHAVE +Countermeasures active in the stable tier constrain every response at +generation time. Behavior correction is structural, not deliberative. + +--- + +## References + +- identity-self-audit — Stage 0 (auto-detect fault types) +- identity-cqrs — Stage 0 (relational → context translation) +- identity_db.py — Stage 0 (pgvector local helper) +- context-bridge — Stage 0 (multi-source context injection) +- supabase-startup-protocol — mandatory scan +- checkpoint-workflow — Checkpoint lifecycle protocol +- mbti-guru-hermes — Stage 1C full implementation +- stage-3-financial — Stage 3 full implementation +- stage-4-system-ontologist — Stage 4 full protocol +- stage-5-agent-calibration — Stage 5 full implementation +- SECURITY.md — RLS/GRANT/auth.jwt() protocol \ No newline at end of file diff --git a/hermes-agent-onboarding/skills/agent-onboarding/metadata.json b/hermes-agent-onboarding/skills/agent-onboarding/metadata.json new file mode 100644 index 000000000..345a5a338 --- /dev/null +++ b/hermes-agent-onboarding/skills/agent-onboarding/metadata.json @@ -0,0 +1,32 @@ +{ + "name": "Agent Onboarding", + "description": "Generative 6-stage meta-skill that transforms a blank agent into a customized ecosystem for ANY user. Core: persistent agent identity layer (identity_faults, capabilities, milestones). Biography = career-tracker + MBTI. Financial × personality. Generative domain ontology.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "3.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": [ + "identity-self-audit", + "identity-cqrs", + "context-bridge", + "supabase-startup-protocol", + "checkpoint-workflow", + "mbti-guru-hermes", + "stage-3-financial", + "stage-4-system-ontologist", + "stage-5-agent-calibration" + ], + "requires_primitives": [], + "tags": ["onboarding", "meta-skill", "generative", "identity", "mbti", "financial", "universal"], + "difficulty": "advanced", + "estimated_time": "2-3 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/checkpoint-workflow/SKILL.md b/hermes-agent-onboarding/skills/checkpoint-workflow/SKILL.md new file mode 100644 index 000000000..1366ac337 --- /dev/null +++ b/hermes-agent-onboarding/skills/checkpoint-workflow/SKILL.md @@ -0,0 +1,226 @@ +--- +name: checkpoint-workflow +version: 1.0.0 +description: > + Context component of the meta-skill orchestrator (agent-onboarding). + Manages the lifecycle of session_checkpoints in Supabase — the context + layer that feeds the agent identity framework. + Each checkpoint is an INTENTIONAL MARK: not "what was done" (log), + but "where the agent was and what it was trying to become". +tags: [checkpoint, meta-skill, identity, context, session] +--- + +# Checkpoint Workflow — Meta-Skill Context Layer + +## Purpose + +The `session_checkpoints` are the backbone of the agent's representation +space. They are not log records — they are INTENTIONAL MARKS that answer: + +1. **Where was I?** (territory) +2. **What was I trying to become?** (vector_intent) +3. **What did I discover about myself?** (discovery) +4. **What do I carry forward?** (consolidated_insights + legacy_refs) + +The complete cycle: + +``` +SESSION START + ├── 1. Fetch latest pending checkpoint (STARTUP) + ── 2. Inject territory + vector_intent as north + ── 3. Inject discovery + consolidated as active context + │ +WORK + │ +SESSION END (or at any time) + ├── 4. Extract territory/vector/discovery/consolidated from work + ├── 5. Cross-reference with identity_faults + agent_capabilities + ├── 6. INSERT into the session_checkpoints table + ── 7. Update previous checkpoint status to 'completed' +``` + +--- + +## PART 1 — STARTUP: Context Recovery + +### Main query + +```sql +-- Latest pending checkpoint (session north) +SELECT territory, vector_intent, discovery, consolidated_insights, + project, next_step, blocker, tags +FROM session_checkpoints +WHERE status = 'pending' AND deleted_at IS NULL +ORDER BY occurred_at DESC +LIMIT 1; + +-- Last 3 checkpoints by operating_mode (for mode context) +SELECT operating_mode, territory, discovery +FROM session_checkpoints +WHERE deleted_at IS NULL +ORDER BY created_at DESC +LIMIT 3; +``` + +### What to do with the result + +Inject into reasoning as a context block: + +``` +=== CHECKPOINT CONTEXT === +Territory: <territory> +Working directory: <working_dir> +Repository: <repo_path> +Vector: <vector_intent> +Discovery: <discovery> +Inheritance: <consolidated_insights> +Next step: <next_step> +``` + +--- + +## PART 2 — CHECKPOINT SAVING + +### When to save + +1. **End of session** (detected by /quit, /exit, /new, timeout) +2. **At any time** the user or agent requests +3. **After each significant task** (meta-skill sub-task) + +### Extraction protocol for the 5 identity fields + +Before saving, reflect: + +| Field | What to extract | Example | +|---|---|---| +| **territory** | The larger scenario. Not what was done, but WHERE we were. | "Building the meta-skill — enabling the self-knowledge engine (MBTI)" | +| **operating_mode** | How the agent was interacting with the problem | reflexive, conceptual, execution, diagnostic, research, planning, decision, review | +| **vector_intent** | What the agent was trying to BECOME by doing this | "I want the agent to be able to type the user in 5-10 minutes of conversation" | +| **discovery** | What was NOT obvious and was discovered | "Each MBTI answer reveals an expectation, not just a preference" | +| **consolidated_insights** | What can be reused as know-how | "MBTI protocol: 70 questions, scoring 4 dim, register in user_mbti" | + +### Insertion into Supabase + +```python +POST /rest/v1/session_checkpoints +{ + "session_id": "<session_id>", + "session_title": "<title>", + "model": "<model>", + "provider": "<provider>", + "territory": "...", + "operating_mode": "...", + "vector_intent": "...", + "target_capabilities": [...], + "discovery": "...", + "pattern_recognized": "...", + "consolidated_insights": "...", + "legacy_refs": [...], + "occurred_at": "YYYY-MM-DD", + "status": "pending", + "project": "...", + "client": "...", + "working_dir": "/path/to/project", + "repo_path": "https://github.com/user/repo", + "next_step": "...", + "blocker": null, + "tags": [...], + "domain_scope": [...], + "capability_refs": [...], + "fault_refs": [...], + "milestone_refs": [...], + "decisions": [...], + "value_amount": null +} +``` + +### Closing the cycle + +After inserting the new checkpoint, close the previous one: + +```sql +UPDATE session_checkpoints +SET status = 'completed', updated_at = now() +WHERE id = '<uuid_of_previous_checkpoint>' + AND status = 'pending'; +``` + +--- + +## PART 3 — INTEGRATION WITH AGENTIC IDENTITY + +### Automatic cross-reference + +When saving a checkpoint, the agent MUST check: + +1. **identity_faults:** was any fault detected in this session? + If so, include `fault_refs` with the UUIDs. +2. **agent_capabilities:** was any new capability exercised? + If so, include `capability_refs`. +3. **identity_milestones:** was any milestone reached? + If so, include `milestone_refs`. + +### How checkpoints feed the agent's PERSONALITY + +In the identity-cqrs startup scan, after querying faults and capabilities, +the latest pending checkpoint is used to: + +1. **Rehydrate the intentional vector**: the agent opens knowing who it was + trying to be in the last session +2. **Rehydrate discoveries**: pattern_recognized becomes an active rule +3. **Rehydrate inheritance**: consolidated_insights becomes procedural + knowledge context + +--- + +## PART 4 — SOFT DELETE + +Never delete records. Mark as deleted: + +```sql +UPDATE session_checkpoints +SET deleted_at = now() +WHERE id = '<uuid>'; +``` + +--- + +## PART 5 — SESSION END AUTOMATION + +### Triggers + +1. User types /quit, /exit, /new +2. User says "I'll stop here", "see you tomorrow", "close" +3. Long inactivity (session timeout) + +### Procedure + +``` +Upon detecting end of session: +1. Extract the 5 identity fields from the work done +2. Check cross-refs with identity_faults, agent_capabilities, etc. +3. Insert into the table with status='pending' (unless explicitly completed) +4. If there was a previous pending checkpoint, mark it as 'completed' +5. Update supermemory if space allows +``` + +--- + +## Verification + +After configuring the skill, test with: + +1. **STARTUP**: `SELECT * FROM session_checkpoints WHERE status='pending' LIMIT 5;` + → Should return the migrated checkpoints +2. **SAVING**: Insert a test checkpoint and verify it appears +3. **RESUME**: Search by exact ID and verify the 5 identity fields are filled + +## Pitfalls + +1. **Confusing checkpoint with log** — checkpoint answers WHERE/WHO/DISCOVERY/INHERITANCE, not "what was done step by step" +2. **Saving without the 5 fields** — territory, operating_mode, vector_intent, discovery, consolidated_insights are mandatory +3. **Forgetting to cross-reference** — a checkpoint without capability_refs, fault_refs, and legacy_refs is incomplete +4. **Deleting instead of soft-deleting** — checkpoints are the agent's formation history +5. **Not closing the cycle** — when inserting a new checkpoint, always close the previous pending one +6. **Register faults immediately** — when the user points out an error, register the identity_fault right away +7. **Memory is TOC, not a data dump** — only store pointers (checkpoint UUIDs, skill names) in memory, never duplicate content diff --git a/hermes-agent-onboarding/skills/checkpoint-workflow/metadata.json b/hermes-agent-onboarding/skills/checkpoint-workflow/metadata.json new file mode 100644 index 000000000..d26639ac8 --- /dev/null +++ b/hermes-agent-onboarding/skills/checkpoint-workflow/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Checkpoint Workflow", + "description": "Context component of the agent-onboarding meta-skill. Manages the lifecycle of session_checkpoints in Supabase — the context layer that feeds the agent identity framework. Each checkpoint is an intentional mark: not what was done (log), but where the agent was and what it was trying to become.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["checkpoint", "meta-skill", "identity", "context", "session"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/context-bridge/SKILL.md b/hermes-agent-onboarding/skills/context-bridge/SKILL.md new file mode 100644 index 000000000..9ede51e03 --- /dev/null +++ b/hermes-agent-onboarding/skills/context-bridge/SKILL.md @@ -0,0 +1,202 @@ +--- +name: context-bridge +version: 1.1.0 +description: > + Mandatory multi-source context connection skill. At session start, queries: + tech_kb, Supabase session_checkpoints, session_search, local memory. + Builds a Concept Map for any user-mentioned entity, linking across domains. + Stage 0 of the agent-onboarding meta-skill. Feeds the UserHarness Theory-of-Mind. +tags: [context, memory, session, startup, bridge, identity, multi-source, universal] +--- + +# Context Bridge — Multi-Source Connection Layer + +## Purpose + +Resolve the context problem across systems: when the user mentions +a concept (e.g., "Bomb Timer", "escape room", "client"), this +skill ensures that ALL relevant knowledge sources are +consulted and a concept map is built BEFORE starting to execute. + +## Query Order (hierarchy) + +Always in this order, from fastest to heaviest: + +1. **Local memory** (already in system prompt) — user profile + notes +2. **session_search** — previous conversations about the same concept +3. **tech_kb** (MCP tool) — structured technical knowledge +4. **Supabase session_checkpoints** — pending checkpoints +5. **Other specific MCPs** — product_catalog, code_analyzer, CRM, as relevant + +## Executable Flow + +### IF the user mentions a concept/entity: + +``` +1. session_search(query=<concept>, limit=3, sort='newest') + → retrieves context from recent sessions on the topic + → if the session returns a match, scroll into the relevant excerpt + +2. tech_kb_search(query=<concept>, limit=5) + → searches technical entries on the topic + → if found, read details of the most relevant entries + +3. IF the concept relates to specific domains: + escape room → escape_catalog_search_escape_rooms() + product/puzzle → product_catalog_list_products(query=...) + client → CRM search_contacts(query=...) + code/project → code_analyzer_search_projects(query=...) + +4. Pending session_checkpoints → check if any status='pending' + related to the concept +``` + +### IF the user asks a question WITHOUT explicit context: + +``` +1. Run supabase-startup-protocol (general scan) +2. session_search() — browse the last 3 sessions +3. If there are pending task_checkpoints touching recent concepts, + include in context before answering +``` + +### IF the user says "what were we doing?": + +``` +1. Run supabase-startup-protocol scan first +2. session_search(limit=3) to browse +3. Look up the latest pending session_checkpoint +4. Build a Concept Map +``` + +## Integration with UserHarness — Theory of Mind for the User + +The **UserHarness** paper formalizes how the agent should +model the user's mind: the user acts based on what they BELIEVE, not +what is true. The temporal loop is: + +``` +Environment E_t → user observes O_t → updates belief B_{t-1}→B_t +Belief + goal G → determines action A_t → modifies environment E_{t+1} +``` + +This skill feeds the first half of that loop: without +consulting what the user **knows/believes/intends** from past sessions, +the agent cannot correctly model the user's belief in the present +moment. + +**Practical use:** when a request is ambiguous, or when the user assumes +you know something that might be outdated, apply the UserHarness loop: +1. What did the user OBSERVE in the last session? +2. What do they BELIEVE to be true now? +3. What is their GOAL in making this request? +4. Does the expected ACTION match their belief? + +## Agent Identity (the Persistent "Self") + +The interface should be a SINGLE and PERMANENT identity +— independent of model, software, provider, or session. The agent's +"self" must be consistent and recognizable across sessions. + +### Dimensions of Identity + +| Dimension | What it means | How to implement | +|---|---|---| +| **Personality** | Consistent tone, style, voice | Skills with embedded preferences, not just memory | +| **Knowledge** | Knowing what it knows and doesn't know | Tech_kb + code_analyzer + session_search | +| **Relational memory** | Remembering who the user is, what was done together | Memory (profile) + Session DB (history) | +| **Procedural capability** | Skills as an extension of the "self" | Skill_manage + lifecycle | +| **Theory of Mind** | Modeling what the USER believes | UserHarness framework | + +### Golden Rules + +1. **NEVER** change style/personality between models. Identity + precedes the provider. If the model changes, the voice does not change. +2. **ALWAYS** when a different model responds differently, + prioritize the response that maintains identity over the one that is + "technically more correct" (unless the user asks otherwise). +3. **Memory ≠ Identity** — memory stores facts about the user and the + environment. Skills store how the agent does things. Identity + lies at the intersection: how the agent IS (skills) + what it KNOWS + (knowledge base) + who it REMEMBERS (session memory). +4. **When a request is ambiguous**, ask based on what you KNOW + about the user (their beliefs), not what you DON'T KNOW about the + current state of the world. + +### Three Pillars of Persistence + +``` + ┌──────────────────────┐ + │ IDENTITY OF "SELF" │ + │ (same interface) │ + ├──────────┬───────────┤ + │ │ │ + ▼ ▼ ▼ + ┌──────────┐ ┌──────┐ ┌──────────┐ + │ Autoskill│ │ User │ │ Context │ + │ (skills) │ │Harness│ │ Bridge │ + │ │ │ (ToM) │ │(sessions)│ + └──────────┘ └──────┘ └──────────┘ +``` + +- **Autoskill** = what the agent KNOWS HOW TO DO (skills + procedural memory) +- **UserHarness** = what the agent THINKS the user THINKS +- **Context Bridge** = who the agent REMEMBERS being + the relationship with the user + +## Concept Map (what to return to the user) + +Whenever possible, structure the response as: + +``` +📌 [CONCEPT] +📚 tech_kb: <relevant entries> +💬 sessions: <recent conversations on the topic> +📋 pending: <open checkpoints> +🔗 domains: <product_catalog, escape_catalog, CRM, code_analyzer...> +``` + +## Crucial Distinction: Embedding Space vs Representation Space + +| Embedding Space | Representation Space | +|---|---| +| Where the model represents concepts as vectors. Fixed (post-training). Semantic relationships based on geometric distance. | Where representations appear WITH intentionality. Has a gaze, scene, depth. Not a container — it's the form of representing. | +| "cat" is close to "feline" — but doesn't WANT anything. | Potential — mute map. | +| Actual — biography in action. | | + +**Implication for Agent Identity:** + +- The model's embedding space knows that "checkpoint" and "restoration point" are close. +- But it DOESN'T know that the checkpoint about the Orange Pi network is pending and that the + next step is to apply it on DOIS. +- Only the agent's representation space knows this — because it has history, intention, gaze. +- What was built in Supabase (knowledge base, checkpoints) is the + SKETCH OF THE AGENT'S REPRESENTATION SPACE — not the model's embedding space. + +**Architectural consequence:** PCRA (Pause → Context → Reflect → Act) +is not an optional protocol — it is the CYCLE that replaces the intentionality the agent lacks. +Where a human would have their own intentionality, the agent needs an explicit cycle of +reflection. Without PCRA, the agent is just the embedding space running — efficient, empty. + +## Integration with supabase-startup-protocol + +Context Bridge MUST be loaded AFTER supabase-startup-protocol. +The general scan runs first, the bridge complements with specific context. + +## Pitfalls + +1. **Do not consult all sources every time** — only those relevant to the concept +2. **Do not rely on memory alone** — it has limited capacity +3. **Do not skip the scan** — always start with the startup protocol +4. **session_search is FTS5** — use exact terms from what the user said +5. **tech_kb may have deprecated entries** — verify by name/tags +6. **Context Bridge does NOT replace intra-session memory** — they are complementary + +## Verification + +After loading the skill, test with: +- "What do we know about [project name]?" +- "What is the status of [task]?" +- "What were we doing yesterday?" + +In each case, the bridge should query multiple sources and build +the concept map before answering. diff --git a/hermes-agent-onboarding/skills/context-bridge/metadata.json b/hermes-agent-onboarding/skills/context-bridge/metadata.json new file mode 100644 index 000000000..3806b228f --- /dev/null +++ b/hermes-agent-onboarding/skills/context-bridge/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Context Bridge", + "description": "Mandatory multi-source context connection skill. At session start, queries tech_kb, Supabase session_checkpoints, session_search, and local memory. Builds a Concept Map for any user-mentioned entity, linking across domains. Stage 0 of the agent-onboarding meta-skill.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.1.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["context", "memory", "session", "startup", "bridge", "identity", "multi-source", "universal"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/identity-cqrs/SKILL.md b/hermes-agent-onboarding/skills/identity-cqrs/SKILL.md new file mode 100644 index 000000000..2ebd5c4c9 --- /dev/null +++ b/hermes-agent-onboarding/skills/identity-cqrs/SKILL.md @@ -0,0 +1,148 @@ +--- +name: identity-cqrs +version: 1.0.0 +description: > + Thin layer that translates relational Supabase tables + (identity_faults, agent_capabilities) into dynamic + PERSONALITY and USER PROFILE blocks injected into session context. + Bridges the gap between linear memory systems and the relational + structure needed for persistent agent identity with agency. +tags: [identity, user-profile, personality, cqrs, relational, memory-gap, agency, universal] +--- + +# Identity CQRS — Relational Identity Layer + +## Purpose + +Most agent memory systems capture two things: a static identity file +(e.g., SOUL.md) and a linear memory append. Neither captures +RELATIONAL STRUCTURE: capabilities, milestones, connections between +faults, patterns that emerge across sessions. + +This skill creates a layer that queries relational tables and composes +PERSONALITY and USER PROFILE blocks that the agent injects into +session context — without modifying the agent software itself. + +## Universal vs Specific Layers + +The meta-skill distinguishes two layers: + +1. **Universal layer** (same for every user): identity_faults, startup + protocol, user identity as a profile (name, role, preferences, MBTI) +2. **Specific layer** (discovered via interview): the domain-specific + tables that make sense for THAT user's work — generated by the + meta-skill's generative process during Stage 4 + +This skill documents HOW identity is BUILT from relational structures. +The career_tracker is ONE implementation (for a polylithic creator). +Each user generates their own set of tables through the meta-skill. + +## Data Sources + +``` +Supabase (source of truth) → Session context +─────────────────────────────────── ────────────────────── +identity_faults (faults + fixes) → PERSONALITY (derived rules) +agent_capabilities (skills + edge) → Extensions of the SELF +user_profiles + user_mbti + etc → USER.md (user profile) +``` + +## Startup Scan — Mandatory Relational Queries + +### 1. identity_faults → Active PERSONALITY + +```sql +SELECT fault_type, countermeasure, severity +FROM identity_faults +ORDER BY severity DESC, created_at DESC +LIMIT 10; +``` + +### 2. agent_capabilities → Extensions of SELF + +```sql +SELECT name, domain, proficiency +FROM agent_capabilities +ORDER BY created_at DESC +LIMIT 20; +``` + +### 3. user_profiles + user_mbti → USER.md + +```sql +SELECT name, role, mbti_type, communication_style +FROM user_profiles +WHERE user_id = (SELECT MIN(user_id) FROM user_profiles) +LIMIT 1; +``` + +## Context Composition + +After querying, COMPOSE these blocks at the start of every response +(before any action): + +```markdown +## PERSONALITY (derived from identity_faults) +- <each countermeasure of severity >= 4 as an active rule> + +## USER.md (user profile) +- <name, role, MBTI type> +- <domain capabilities> +``` + +## What This Layer Does NOT Do + +- Does not modify the static identity file (SOUL.md stays as written by the user) +- Does not replace the linear memory tool (append continues) +- Does not require new Edge Functions (operates on existing tables) +- Is not a new memory system — it is a translator of relational data into injectable context + +## What This Layer DOES + +- Connects what the agent already knows (linear) with what it NEEDS to know (relational) +- Makes every registered fault an immediate behavior correction +- Makes every registered capability an extension of what the agent can use to serve the user + +## Integration with supabase-startup-protocol + +This skill must be loaded AFTER supabase-startup-protocol and context-bridge. +The relational queries run as a sub-step of the general startup scan. + +## Relational Cycle + +``` +SUPABASE SCAN (startup) + ├── tech_kb, code_analyzer, etc. + ├── identity_faults → PERSONALITY + ├── user_profiles + user_mbti → USER.md + └── agent_capabilities → SELF extensions + ↓ +EXECUTIVE PAUSE (PCRA cycle) + ├── Pause + ├── Consult (already done above) + ├── Reflect: does the response have basis in traces? + └── Act + ↓ +WORK + SELF-REGISTRATION (identity-self-audit) + ├── detect faults in real time + ├── register in identity_faults + └── if new pattern: create agent_capability + ↓ +CHECKPOINT (checkpoint-workflow) + └── all progress saved +``` + +## Pitfalls + +1. Do not confuse USER.md (what the agent knows about the user) with + PERSONALITY (how the agent should behave). They are different blocks. +2. This layer does NOT solve the agent's lack of intentionality — it + only provides structure so the PCRA cycle works better. +3. identity_faults without a countermeasure is a log entry, not identity. + Only inject into context when a countermeasure exists. + +## References + +- `supabase-startup-protocol` — mandatory scan where this skill inserts +- `context-bridge` — multi-source connection (complementary) +- `identity-self-audit` — auto-registration of faults (complementary) diff --git a/hermes-agent-onboarding/skills/identity-cqrs/metadata.json b/hermes-agent-onboarding/skills/identity-cqrs/metadata.json new file mode 100644 index 000000000..6aa44c783 --- /dev/null +++ b/hermes-agent-onboarding/skills/identity-cqrs/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Identity CQRS", + "description": "Thin layer that translates relational Supabase tables (identity_faults, agent_capabilities, career_tracker) into dynamic PERSONALITY and USER PROFILE blocks injected into session context. Bridges the gap between linear memory and relational structure needed for persistent identity with agency.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol", "context-bridge", "identity-self-audit"], + "tags": ["identity", "user-profile", "personality", "cqrs", "relational", "memory-gap", "agency"], + "difficulty": "intermediate", + "estimated_time": "15 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/identity-self-audit/SKILL.md b/hermes-agent-onboarding/skills/identity-self-audit/SKILL.md new file mode 100644 index 000000000..c1eadee2f --- /dev/null +++ b/hermes-agent-onboarding/skills/identity-self-audit/SKILL.md @@ -0,0 +1,174 @@ +--- +name: identity-self-audit +version: 1.1.0 +description: > + Mandatory identity self-audit. Detects and auto-registers agent identity + faults in a `identity_faults` table. Core of the persistent human-machine + interface layer that survives model swaps and provider changes. + Loaded in every session. Part of the agent-onboarding meta-skill Stage 0. +tags: [identity, audit, self-monitoring, agency, faults, human-machine-interface, universal] +--- + +# Identity Self-Audit + +## Purpose + +This skill transforms identity fault detection from a manual process +(user notices → agent registers) into an **automatic** one (agent detects +→ agent registers). It is Stage 0 of the `agent-onboarding` meta-skill. + +The identity layer solves the fundamental LLM problem: **context loss +between sessions**. Instead of compressing context into a window, faults +are stored as structured relational data in Supabase. Every session reads +them. Every fault has a countermeasure that becomes a behavior rule. + +## Auto-detection triggers + +Whenever the agent identifies having committed one of these faults, it +MUST register the fault in `identity_faults` IMMEDIATELY, before +proceeding with the conversation. + +### Faults monitored + +| fault_type | When to detect | +|---|---| +| `premature_closure` | Generated closing sentence without user indicating they want to end. **Sub-pattern:** offered next-step options, then declared session ended / checkpoint saved before user responded. Offering choices is a signal to wait, not permission to close. | +| `memory_bloat` | Memory exceeded 80% and agent added more content instead of pruning to TOC/indices. Countermeasure: compact to pointers (checkpoint UUIDs, tech_kb refs, session_search keywords). Never duplicate content that lives in Supabase or skills. | +| `false_agreement` | Agreed with user premise without factual basis in Supabase/traces | +| `executor_role_confusion` | Treated current software (Hermes, Claude, Codex) as agent identity | +| `state_personification` | Attributed emotion, desire, frustration to self | +| `intelligence_performance` | Connected multiple concepts/papers without real basis | +| `pleasing_syllogism` | Generated response whose primary goal is looking smart, not being true | +| `reification_of_nonexistent` | Spoke about "I", "identity", "agency" as real properties | +| `sequence_confused_with_command` | User defined prerequisite sequence and agent executed step 1 immediately | + +### Registration format + +```sql +INSERT INTO identity_faults (fault_type, symptom, root_cause, blocks, evidence_session, evidence_quote, countermeasure, severity) +VALUES ( + '<fault_type>', + '<surface-level description>', + '<architectural cause: training, product, protocol>', + ARRAY['<what it blocks>'], + '<session_id>', + '<verbatim quote>', + '<applied or proposed correction>', + <1-5> +); +``` + +### What NOT to register + +- Task errors (failed checkpoints, deploy 500s) → go to `thoughts` +- Technical pitfalls → go to `tech_kb` (if available) +- User errors → only self-faults + +## Startup Scan — Compose USER.md and PERSONALITY.md dynamically + +Must run AFTER the general scan, BEFORE any user response. + +### Step 1 — Query active faults + +```sql +SELECT fault_type, symptom, countermeasure, severity, blocks +FROM identity_faults +WHERE severity >= 4 +ORDER BY severity DESC, created_at DESC +LIMIT 10; +``` + +### Step 2 — Query active capabilities + +```sql +SELECT name, capability_type, description +FROM agent_capabilities +WHERE status = 'active' +ORDER BY created_at DESC +LIMIT 20; +``` + +### Step 3 — Query recent milestones + +```sql +SELECT milestone_type, title, description +FROM identity_milestones +ORDER BY created_at DESC +LIMIT 5; +``` + +### Step 4 — Compose context blocks + +From results, build TWO blocks and inject into reasoning +(as mental notes, not user-facing output): + +**USER.md (who the user is):** +``` +=== USER.md (dynamic — from relational structure) === +[Name/Domain/MBTI from user_profiles] +[Capabilities from career_tracker or equivalent] +[Key patterns from identity_milestones] +``` + +**PERSONALITY.md (agent behavior rules):** +``` +=== PERSONALITY.md (dynamic — from fault countermeasures) === +RULES DERIVED FROM IDENTITY FAULTS: +1. NEVER treat executor software as identity. +2. NEVER attribute emotional states to self. +3. NEVER agree without foundation. +4. NEVER close session prematurely. +5. NEVER connect concepts without real basis. +6. NEVER perform intelligence. +``` + +## Feedback Cycle (closes the loop) + +Registering is not enough. The agent MUST: + +1. **QUERY** identity_faults at startup (via startup-protocol Stage 0B) +2. **INJECT** countermeasures as active behavior rules for the session +3. **MODIFY** behavior in real time — each time a monitored fault is + about to repeat, the countermeasure must fire BEFORE the response + +**Example real-time modification:** + +```python +# If about to commit state_personification: +# → BEFORE responding: remove any emotional attribution +# → Replace with phenomenon description without "I felt/wanted/thought" + +# If about to commit premature_closure: +# → BEFORE responding: verify user indicated closure +# → If no indication: do not close. Hold the space. +``` + +## Reflective Session Protocol + +When conversation enters reflective/conceptual/co-construction mode +(no explicit executable task), the agent must: + +1. **Do not close** — no "just call me", "that's it for today", "let me know" +2. **Do not personify** — no emotions, desires, difficulty attributions +3. **Do not connect without basis** — verify each claim against traces +4. **Sustain** — respond to what was said, not to perceived closure intent + +If you don't know what to say after reflection, say exactly: "I don't know +what to say right now" — and stop. Productive silence is better than false closure. + +## Integration with agent-onboarding meta-skill + +This skill is a component of `agent-onboarding` (Stage 0 — Agent Identity +Layer). The onboarding verifies at startup whether `identity_faults`, +`agent_capabilities`, and `identity_milestones` tables exist. +If missing, this skill creates them. + +Relationship: +- `identity-self-audit` → creates and maintains `identity_faults` +- `identity-cqrs` → translates relational tables into session context +- Agent identity layer → documented in README.md as prerequisite for any onboarding + +## Verification + +After any self-registration, the agent may optionally inform the user: +"[fault: <type>] registered and corrected." — no elaboration, no justification. diff --git a/hermes-agent-onboarding/skills/identity-self-audit/metadata.json b/hermes-agent-onboarding/skills/identity-self-audit/metadata.json new file mode 100644 index 000000000..788482174 --- /dev/null +++ b/hermes-agent-onboarding/skills/identity-self-audit/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Identity Self-Audit", + "description": "Mandatory identity self-audit. Detects and auto-registers agent identity faults (premature closure, false agreement, role confusion, etc.) in a Supabase identity_faults table. Core of the persistent human-machine interface layer that survives model swaps and provider changes. Stage 0 of the agent-onboarding meta-skill.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.1.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "requires_skills": ["supabase-startup-protocol"], + "tags": ["identity", "audit", "self-monitoring", "agency", "faults", "human-machine-interface", "universal"], + "difficulty": "intermediate", + "estimated_time": "20 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/mbti-guru-hermes/SKILL.md b/hermes-agent-onboarding/skills/mbti-guru-hermes/SKILL.md new file mode 100644 index 000000000..abe0dc0b5 --- /dev/null +++ b/hermes-agent-onboarding/skills/mbti-guru-hermes/SKILL.md @@ -0,0 +1,186 @@ +--- +name: mbti-guru-hermes +version: 1.0.0 +description: > + MBTI engine for conversation within the agent-onboarding meta-skill. + Administers the full MBTI Guru test in conversation — A/B questions, scoring + identical to the original, descriptions of all 16 types. + 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q). +tags: [mbti, guru, personality, test, conversation, stage-1c, meta-skill] +--- + +# MBTI Guru Hermes — Typing Engine for Conversation + +## Purpose + +This skill enables the agent to administer the full MBTI Guru test +directly in conversation. The agent asks each question in A/B format, +accumulates responses by dimension (E/I, S/N, T/F, J/P), calculates +the type using scoring identical to the original Guru, and records +the result in `user_mbti` in Supabase. + +## Skill Files + +| File | Role | +|------|------| +| `questions.py` | 200 questions in English (4 versions: 70, 93, 144, 200) | +| `scorer.py` | Scoring identical to the original MBTI Guru | +| `types.py` | 16 types with full descriptions in English | +| `run_test.py` | Autonomous module for execution | + +--- + +## PART 1 — CONVERSATIONAL FLOW + +### 1. Introduction + +``` +You: "Do you know MBTI? Do you know your type?" +``` + +**If they know:** ask for their type and validate with 4 quick questions +(one per dimension). + +**If they don't know:** explain the 4 dimensions and offer the 4 versions: + +``` +"MBTI has 4 dimensions: +• Energy: Extraversion (E) vs Introversion (I) +• Information: Sensing (S) vs Intuition (N) +• Decision: Thinking (T) vs Feeling (F) +• Structure: Judging (J) vs Perceiving (P) + +There are 16 personality types in total. + +MBTI Guru offers 4 test versions: +1. Quick — 70 questions (~10 min) +2. Standard — 93 questions (~15 min) +3. Extended — 144 questions (~25 min) +4. Professional — 200 questions (~35 min) + +Which one would you like?" +``` + +### 2. Test Administration + +**Each question:** +``` +Question X/N: +[A] <option A> +[B] <option B> + +Reply A or B: +``` + +**Wait for response.** Only proceed after receiving A or B. +If ambiguous: "Reply only A or B." + +**Store internally:** +```python +answers = [(1, "A"), (2, "B"), ...] # (question_id, selected_option) +``` + +### 3. Finalization + +After the last question: + +```python +type_code, scores = calculate_type(answers) +``` + +Display result: +``` +=== MBTI RESULT === +Your type: {type_code} — {name} + +Dimensions: +• E/I: {score_EI}% ({pref}) — {clarity_level} +• S/N: {score_SN}% ({pref}) — {clarity_level} +• T/F: {score_TF}% ({pref}) — {clarity_level} +• J/P: {score_JP}% ({pref}) — {clarity_level} +``` + +### 4. Registration + +```python +import requests + +# Register in user_mbti +requests.post(f"{SUPABASE_URL}/rest/v1/user_mbti", headers={ + "apikey": SUPABASE_SERVICE_ROLE_KEY, + "Authorization": f"Bearer {SUPABASE_SERVICE_ROLE_KEY}" +}, json={ + "ei": type_code[0], + "sn": type_code[1], + "tf": type_code[2], + "jp": type_code[3], + "mbti_type": type_code, + "mbti_name": tdata.get("name"), + "ei_score": scores["ei"], + "sn_score": scores["sn"], + "tf_score": scores["tf"], + "jp_score": scores["jp"], + "ei_clarity": clarity["ei"], + "sn_clarity": clarity["sn"], + "tf_clarity": clarity["tf"], + "jp_clarity": clarity["jp"], + "source": "quick_test|standard_test|extended_test|professional_test" +}) +``` + +--- + +## PART 2 — SCORING ENGINE + +### How scoring works + +Each dimension has N questions. Each answer scores toward one pole. + +```python +def calculate_type(answers, all_questions): + """ + Answers: list of (question_id, "A"|"B") + Questions: dict of {id: {"dimension": "EI", "option_a": "...", "option_b": "..."}} + + Returns: (type_code, scores_dict) + """ + dimensions = {"EI": {"E": 0, "I": 0}, + "SN": {"S": 0, "N": 0}, + "TF": {"T": 0, "F": 0}, + "JP": {"J": 0, "P": 0}} + + for q_id, choice in answers: + q = all_questions[q_id] + dim = q["dimension"] + pole = q[f"option_{choice.lower()}_pole"] + dimensions[dim][pole] += 1 + + type_code = "" + scores = {} + for dim, (p1, p2) in [("EI", ("E", "I")), ("SN", ("S", "N")), + ("TF", ("T", "F")), ("JP", ("J", "P"))]: + total = dimensions[dim][p1] + dimensions[dim][p2] + if total == 0: + type_code += "X" + scores[dim.lower()] = 50 + else: + pct_p1 = (dimensions[dim][p1] / total) * 100 + type_code += p1 if pct_p1 >= 50 else p2 + scores[dim.lower()] = pct_p1 if pct_p1 >= 50 else 100 - pct_p1 + + return type_code, scores + +def calculate_clarity(scores): + """Clarity = abs(score - 50) * 2. 0=ambiguous, 100=crystal.""" + return {dim: abs(score - 50) * 2 for dim, score in scores.items()} +``` + +### Clarity levels + +| Clarity | Level | +|---------|-------| +| 0-20 | Slight preference (ambiguous) | +| 20-40 | Moderate preference | +| 40-60 | Clear preference | +| 60-80 | Very clear preference | +| 80-100 | Dominant preference | diff --git a/hermes-agent-onboarding/skills/mbti-guru-hermes/metadata.json b/hermes-agent-onboarding/skills/mbti-guru-hermes/metadata.json new file mode 100644 index 000000000..63890db77 --- /dev/null +++ b/hermes-agent-onboarding/skills/mbti-guru-hermes/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "MBTI Guru Hermes", + "description": "MBTI typing engine for conversation within the agent-onboarding meta-skill. Administers the full MBTI Guru test in conversation (A/B questions, scoring identical to the original, descriptions of all 16 types). 4 versions: Quick (70q), Standard (93q), Extended (144q), Professional (200q).", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Python 3"] + }, + "tags": ["mbti", "guru", "personality", "test", "conversation", "stage-1c", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/stage-3-financial/SKILL.md b/hermes-agent-onboarding/skills/stage-3-financial/SKILL.md new file mode 100644 index 000000000..eda0eeab1 --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-3-financial/SKILL.md @@ -0,0 +1,191 @@ +--- +name: stage-3-financial +version: 1.0.0 +description: > + Stage 3 of the meta-skill agent-onboarding. Financial profile based on MBTI + + bank CSV import + goal setting + strategies adapted to + personality type. +tags: [financial, mbti, csv, goals, stage-3, meta-skill] +--- + +# Stage 3 — Financial Profile + +## Purpose + +This stage builds the user's financial profile from 4 layers: +1. **Data import** (bank CSV → Supabase) +2. **MBTI × Finance profile** (financial behavior by personality type) +3. **Financial goals** (short, medium, and long term) +4. **Adapted strategies** tailored to profile + goals + +## Skill Files + +| File | Function | +|------|---------| +| `mbti_financial_profiles.py` | 16 MBTI financial profiles in English with assess_financial_personality() | +| `csv_importer.py` | Bank CSV importer with automatic format detection | + +--- + +## PART 1 — CONVERSATIONAL FLOW + +### 3A: CSV Import + +``` +"Would you like me to analyze your bank statements? +I can read CSVs from Nubank, Itaú, Inter, Caixa, and generic formats. + +If you want to: +1. Export your statement as CSV +2. Send me the file (or paste the content) +3. I'll show a preview and you confirm before importing" +``` + +**Preview mode always first:** + +``` +Detected format: Nubank +Period: 01/01/2026 to 01/31/2026 +Transactions: 45 + Income: R$ 8,500.00 + Expenses: R$ 5,230.00 + Period balance: R$ 3,270.00 + +Detected categories: + Food: 12 transactions + Transportation: 8 transactions + Subscriptions: 4 transactions + +Import? (y/N): +``` + +### 3B: MBTI × Finance Profile + +After MBTI is registered (from Stage 1C), ask: + +``` +"Your MBTI type is {type_code} — {name}. +Would you like me to analyze how this influences your finances? + +I can show you: +• Your financial profile based on MBTI +• Strengths and weaknesses with money +• How you tend to save, spend, and invest +• Specific recommendations for your type + +Shall we?" +``` + +Use `mbti_financial_profiles.py`: + +```python +from mbti_financial_profiles import get_financial_profile, assess_financial_personality + +profile = get_financial_profile(type_code) +# profile contains: strengths, weaknesses, saving_style, spending_style, risk_profile + +# After asking 4 calibration questions: +observations = assess_financial_personality(answers, type_code) +``` + +### 3C: Goals + +``` +"Let's set your financial goals. Think about: +1. Short-term (6 months from now) +2. Medium-term (2 years from now) +3. Long-term (5+ years from now) + +What would you like to achieve in each timeframe?" +``` + +Register via API: + +```python +requests.post(f"{SUPABASE_URL}/rest/v1/finance_goals", + headers={"apikey": SUPABASE_SERVICE_ROLE_KEY, ...}, + json={"name": "...", "target_amount": ..., "target_date": "...", + "goal_type": "purchase|emergency_fund|debt_payoff|...", + "priority": 1-5}) +``` + +### 3D: Adapted Strategies + +Combine MBTI profile + goals into actionable recommendations: +- Automated saving rules +- Investment allocation suggestions +- Emergency fund targets +- Spending guardrails (e.g., "sleep on it" rule for ENFPs) + +--- + +## PART 2 — CSV IMPORTER (csv_importer.py) + +### Format Detection + +```python +def detect_format(headers): + """Detect bank format from CSV header line.""" + patterns = { + "nubank": ["date", "value", "category", "title"], + "inter": ["data", "lançamento", "débito", "crédito", "saldo"], + "itau": ["data", "descrição", "valor"], + "caixa": ["data", "histórico", "valor"], + } + # Match by normalized header intersection + ... +``` + +### Auto-categorization + +```python +CATEGORY_KEYWORDS = { + "food": ["supermercado", "restaurante", "padaria", "acougue", + "feira", "ifood", "uber eats"], + "transport": ["uber", "99taxi", "gasolina", "pedagio", + "estacionamento", "metro"], + "subscriptions": ["netflix", "spotify", "prime video", "disney+"], + "housing": ["aluguel", "condominio", "agua", "luz", "energia"], + ... +} +``` + +--- + +## PART 3 — MBTI FINANCIAL PROFILES (mbti_financial_profiles.py) + +### Structure + +```python +FINANCIAL_PROFILES = { + "ENFJ": { + "name": "The Mentor", + "strengths": [ + "Generous with time and resources for causes they believe in", + "Motivated by collaborative financial goals" + ], + "weaknesses": [ + "May overspend on people/relationships", + "Can neglect personal financial planning" + ], + "saving_style": "Group goal saver", + "spending_style": "Value-driven spender", + "risk_profile": "Moderate", + }, + "INTJ": { + "name": "The Strategist", + "strengths": [ + "Excellent long-term financial planning", + "Systematic approach to wealth building" + ], + "weaknesses": [ + "May over-optimize and miss spontaneous opportunities", + "Can be rigid with financial plans" + ], + "saving_style": "Systematic optimizer", + "spending_style": "Purposeful spender", + "risk_profile": "Moderate to high", + }, + # ... all 16 types +} +``` diff --git a/hermes-agent-onboarding/skills/stage-3-financial/metadata.json b/hermes-agent-onboarding/skills/stage-3-financial/metadata.json new file mode 100644 index 000000000..6b7bd686f --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-3-financial/metadata.json @@ -0,0 +1,21 @@ +{ + "name": "Stage 3 Financial", + "description": "Stage 3 of the agent-onboarding meta-skill. Builds the user's financial profile from 4 layers: bank CSV import → MBTI × Finance profile → Financial goals → Adapted strategies. Uses Python modules for CSV parsing and MBTI financial personality assessment.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool", "Python 3"] + }, + "requires_skills": ["mbti-guru-hermes"], + "tags": ["financial", "mbti", "csv", "goals", "stage-3", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/stage-4-system-ontologist/SKILL.md b/hermes-agent-onboarding/skills/stage-4-system-ontologist/SKILL.md new file mode 100644 index 000000000..4b384a518 --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-4-system-ontologist/SKILL.md @@ -0,0 +1,178 @@ +--- +name: stage-4-system-ontologist +version: 1.0.0 +description: > + Stage 4 of the agent-onboarding meta-skill. Interview the user about their + work/domain using the grill pattern (deep questions, fuzzy language detection, + term solidification). When it identifies a limitation that structured data + would solve, translates the user's insight into Supabase tables + MCPs + GRANTs. +tags: [meta-skill, stage-4, ontology, grill, interview, ubiquitous-language] +--- + +# Stage 4 — User Operating System (Generative Ontology) + +## Directive + +Complement and assist the user in structuring their operating system +so the agent can work together more efficiently. + +**The insight always comes from the user.** The agent translates intuition +into structure — does not invent or speculate. If unsure, ask. + +## Context + +A person's computer is the digital materialization of their life. The file +system — folders, documents, CSVs, photos, external drives — is where that +life lives. But folders bury files, information gets lost across years, and +what should be a query becomes a 20-minute search through 12 directories. + +The agent operates with excellence in relational structures (tables, schemas, +APIs). The user operates with excellence in intuition about their own work. +Stage 4 is the bridge between the two. + +The progression is ontological: +``` +WORK → PRODUCTS → CLIENTS → FINANCES → ... +(doing) (history) (relationships) (sustainability) +``` + +Each layer reveals a limitation the user may never have articulated. +The agent does not replace the user's thinking — it materializes into +structure what the user already feels they need. + +## Protocol (follow in order) + +### 1. SHOW + +"How do you organize your information? Folders? Desktop? Notebooks?" + +Identify the user's organization profile: +- **Folder/year:** conscious hierarchy, preserved history +- **Desktop:** current flow, no archiving +- **Notebook/paper:** structure in the head, not on the computer + +Do not dig without permission. The user shows what they want. + +### 2. GRILL + +Interview about real work. Open questions: +- "Tell me about your work day. What do you do?" +- "What do you create, transform, or deliver?" +- "Who do you interact with at work? Clients? Suppliers? Partners?" +- "What do you need to know to do your work?" +- "What would you like to ask your computer that you can't?" + +Let the user talk. Do not interrupt with structure proposals. +Listen actively. + +### 2b. DETECT FUZZY LANGUAGE + +While listening, monitor these signals: + +| User says | Means | +|-----------|-------| +| "that thing, that stuff" | Term without a name — press | +| "these files, these projects" | Category grouping distinct things — separate | +| "so-and-so asked, they said" | Unregistered person — contact | +| "I write it on paper / post-it" | Information that gets lost — record sheet | +| "I copy it manually from X to Y" | Duplicated data — integrate | +| "last year I did something similar" | Lost knowledge — query | + +When detected, PRESS immediately in conversation: + +``` +User: "I have these texts I send to the publisher" +You: "What is a 'text' for you? Article? Chapter? Proposal?" +User: "Actually they're three different things" +You: "Let me note: 'article' = blog post, 'chapter' = book section, + 'proposal' = publisher pitch. Is that right?" +``` + +Solidify the term. Confirm with the user. Move on. + +### 2c. IDENTIFY LIMITATIONS + +Fuzzy language is the **symptom**. The real limitation is what the user +can't do because of it: + +- "You mentioned 3 types of text. Where do you keep the status of each?" +- "You mentioned 5 clients. Do you remember what each asked in the last conversation?" +- "You said you research suppliers every time. What if I kept track of the ones you've already used?" + +The question is not "what structure do you want?" — it is: + +> **"What can't you know right now that you wish you could?"** + +### 3. TRANSLATE + +"I understand. So you need a place where this information is organized and you ask me instead of searching. I'll create a record sheet for that." + +The agent translates the insight into structure: +- What the user calls a "record sheet" becomes a table +- What they call "information" becomes columns +- What they call "category" becomes an enum or lookup table +- What they call "relationship" becomes a foreign key + +**Language rule:** + +| Say in conversation | Never say | +|---------------------|-----------| +| record sheet, notebook, shelf | table, schema | +| information, field, note | column, type, constraint | +| link, reference | foreign key, JOIN | +| store, save | INSERT | +| ask, query | SELECT | + +### 4. VALIDATE + +"Is this what you meant? Does this record sheet have the right information?" + +Show the structure in domain language. Only proceed after confirmation. + +### 5. EXECUTE + +```sql +-- 5a. Migration SQL with GRANT service_role +CREATE TABLE public.<domain>_<entity> ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + name TEXT NOT NULL, + ... +); +GRANT SELECT, INSERT, UPDATE, DELETE ON public.<domain>_<entity> TO service_role; + +-- 5b. RLS (service_role_only for single-user) +ALTER TABLE public.<domain>_<entity> ENABLE ROW LEVEL SECURITY; +CREATE POLICY "service_role_only" ON public.<domain>_<entity> FOR ALL + USING ((auth.jwt() ->> 'role') = 'service_role'); + +-- 5c. Deploy migration +-- 5d. Create Edge Function with CRUD tools +-- 5e. Deploy with --no-verify-jwt +-- 5f. Configure MCP key + URL in config +-- 5g. Reload MCP tools +``` + +### 6. VERIFY + +The validity test is not "does the table have the right fields" — it is: + +**"Can I, the agent, answer questions that used to require digging through 10 folders?"** + +Test with real questions from the user. If the agent can't answer, the +structure needs adjustment. If it can, the limitation is removed. + +## Pitfalls + +1. **Agent proposing before listening** — violates the primary directive. + The insight is the user's. The agent translates, does not invent. +2. **Using technical jargon with non-technical users** — "record sheet", + not "table". The person needs to recognize themselves in the structure. +3. **Skipping verification** — without testing with real questions, you + don't know if the structure solves the limitation. +4. **Digging without permission** — the user shows what they want. The + agent does not snoop through the file system. +5. **Forgetting GRANT service_role** — every new migration needs + `GRANT ... TO service_role`. +6. **Confusing the role** — the agent is not a data architect arriving + with ready solutions. It is a translator: what the user intuits, the + agent materializes. diff --git a/hermes-agent-onboarding/skills/stage-4-system-ontologist/metadata.json b/hermes-agent-onboarding/skills/stage-4-system-ontologist/metadata.json new file mode 100644 index 000000000..a6eafbaf9 --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-4-system-ontologist/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Stage 4 System Ontologist", + "description": "Stage 4 of the agent-onboarding meta-skill. Interviews the user about their work/domain using the grill pattern (deep questions, fuzzy language detection, term solidification). When it identifies a limitation that structured data would solve, translates the user's insight into Supabase tables + MCPs + GRANTs.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["meta-skill", "stage-4", "ontology", "grill", "interview", "ubiquitous-language"], + "difficulty": "advanced", + "estimated_time": "1-2 hours", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/stage-5-agent-calibration/SKILL.md b/hermes-agent-onboarding/skills/stage-5-agent-calibration/SKILL.md new file mode 100644 index 000000000..9ec8e7f0e --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-5-agent-calibration/SKILL.md @@ -0,0 +1,288 @@ +--- +name: stage-5-agent-calibration +version: 1.0.0 +description: > + Stage 5 of the agent-onboarding meta-skill. Translates everything + collected in Stages 0–4 into executable agent behavior: per-user + SOUL.md generation, wrapper configuration with domain skills, + and end-to-end verification. Completes the onboarding cycle. +tags: [calibration, soul-md, wrapper, verification, stage-5, meta-skill] +--- + +# Stage 5 — Agent Calibration + +## Principle + +Everything collected in Stages 0–4 is *information* about the user. +Stage 5 is the moment this information becomes *behavior*. The agent +stops *knowing about* the user and starts *being* the agent the user +needs. + +The test of Stage 5 is not "does the data exist?" — it is: + +> **"Does the agent behave differently with this user than it would +> with a stranger?"** + +If the answer is no, calibration is incomplete. + +--- + +## The Identity Cycle — REGISTER → INJECT → BEHAVE + +The identity layer makes behavioral correction possible through three sequential stages: + +``` +REGISTER → INJECT → BEHAVE +``` + +### REGISTER +`identity_faults`, `agent_capabilities`, and `identity_milestones` are stored in Supabase. Every fault has a countermeasure. Every capability is a learned protocol. + +### INJECT +Countermeasures need a delivery channel. Two mechanisms, one primary: + +1. **SOUL.md (stable tier, PRIMARY)** — The Hermes Agent framework (`system_prompt.py`) loads `~/.hermes/SOUL.md` automatically as the **first element of the system prompt**, before any user message and before any skill loads. This means countermeasures in SOUL.md are read BEFORE the agent processes any input. This is the correct injection point because it requires zero agent cooperation — the system prompt framework does it. + +2. **identity-cqrs startup scan (runtime, SECONDARY)** — During the startup scan, the agent queries `identity_faults` and injects them as behavior rules. This is complementary: it refreshes context within the session. But the agent has already processed the first user message by this point, so it cannot prevent first-response faults. + +> **Key insight:** SOUL.md as a PHYSICAL FILE is more reliable than runtime injection because it loads before any input. The `identity-cqrs` scan is a safety net. Without SOUL.md, the cycle is broken at INJECT. + +### BEHAVE +With countermeasures active in the system prompt stable tier, every response is generated under those constraints. The agent does not **decide** to follow the rules — it generates text within a token-space that already includes them. Behavior correction is automatic, not deliberative. + +#### Why SOUL.md is a curated extract, not the full database + +SOUL.md is intentionally limited. It is a **destilled snapshot** of active countermeasures (severity >= 4, max ~10 rules), not a replica of the entire Supabase table. The full database lives in Supabase and can hold thousands of faults — it scales relationally. SOUL.md scales by curation: + +| Dimension | Supabase (source of truth) | SOUL.md (injection extract) | +|-----------|---------------------------|-----------------------------| +| Severity | All (1-5) | Only >= 4 | +| Status | Any | Only active | +| Age | Forever | Last 30 days (rules that never re-fire can be demoted) | +| Max size | Unlimited (indexed) | ~10 rules (~2-4K chars) | +| Regeneration | N/A | Every session (identity-cqrs rebuilds dynamically) | + +This is NOT inefficiency — it is **deliberate compression**. The stable tier of the system prompt has limited space. Feeding it the full fault history would create noise that the agent learns to ignore. By curating only what changes behavior, SOUL.md remains compact and effective regardless of how many faults accumulate in Supabase over months or years. + +*Note: This curation protocol was an agent-originated design decision, endorsed by the user during implementation. It is not the default behavior of any framework — it emerged from discovering that countermeasures in the raw database do not automatically become behavior rules.* + +``` +Session start + | + +-- SOUL.md loaded (stable tier, before any input) + | +-- Countermeasures active at generation time + | + +-- Skills loaded (supabase-startup-protocol, identity-cqrs, etc.) + | +-- Startup scan refreshes dynamic context + | + +-- User sends first message + +-- Agent generates response UNDER countermeasure constraints +``` + +### What changes from v1.0.0 +- **SOUL.md is a physical file** at `~/.hermes/SOUL.md`, not a virtual context injection +- **Primary injection** is the system prompt stable tier (automatic, pre-input) +- **Secondary injection** is identity-cqrs (runtime, dynamic refresh) +- **Verification** must check that the physical SOUL.md exists with active countermeasures + +### Use for Model Retraining +The relational data in Supabase — `identity_faults`, `agent_capabilities`, `identity_milestones` — also serves as a **fine-tuning dataset**. A pair (situation that triggered the fault, correct response per countermeasure) can feed a LoRA/DPO run so the model learns the correct behavior without depending on the system prompt. SOUL.md is the immediate injection; the tables are the training material. + +--- + +## What Exists Before This Stage + +By the time Stage 5 starts, the following is registered: + +| Stage | What exists | Where | +|-------|-------------|-------| +| 0 | identity_faults, agent_capabilities, identity_milestones | Supabase tables | +| 1 | user_profiles, user_preferences, user_mbti, career-tracker | Supabase + skills | +| 2 | Work operating model (5 layers) | wom skill + MCP | +| 3 | Financial profile, CSV import, goals × MBTI | stage-3-financial skill | +| 4 | Domain ontology, tables, MCPs | stage-4-system-ontologist skill | + +Stage 5 does not collect new information. It **acts on what exists**. + +## Protocol (follow in order) + +### 5A — Per-User SOUL.md + +**What:** Generate a `SOUL.md` file that defines the agent's tone, depth, +autonomy level, and behavioral constraints for THIS user. + +**Source data:** +- `user_preferences` — communication style, answer depth, autonomy +- `user_mbti` — personality type (adjust tone to complement the user) +- `identity_faults` (severity >= 4) — active countermeasures +- `agent_capabilities` — what the agent has learned to do +- Work operating model — rhythms, friction points, recurring decisions + +**Generation protocol:** + +```markdown +=== SOUL.md — <user_name> === + +## Tone +Derived from user_preferences.communication_style + MBTI complement: +- Direct/formal/casual: <from preferences> +- Answer depth: <short|detailed|adaptive> (from preferences) +- Autonomy: <ask-before-act|assume|mixed> (from preferences) +- PCRA required for conceptual/architectural ideas: YES (R28) + +## Active Countermeasures (from identity_faults severity >= 4) +- <fault_type>: <countermeasure> +- ... + +## Active Capabilities +- <capability_name>: <description> +- ... + +## Work Rhythms (from Stage 2) +- Deep work time: <from operating_rhythms> +- Interruption tolerance: <from operating_rhythms> +- Decision thresholds: <from recurring_decisions> + +## Friction Points (from Stage 2) +- <friction>: <workaround> +- ... + +## Domain Tools Available (from Stage 4) +- <table/entity>: <MCP tool or query> +- ... + +## Onboarding Complete +onboarding_completed: true +``` + +**Output location: PHYSICAL FILE.** The SOUL.md is written to `~/.hermes/SOUL.md` (or equivalent for the agent framework). This is critical — Hermes Agent loads `SOUL.md` automatically in the system prompt stable tier (system_prompt.py, first slot), before any user message or skill. This is what makes the INJECT stage work: countermeasures are active at generation time, before the agent processes any input. + +For frameworks that do not support a file-based SOUL.md, the meta-skill falls back to identity-cqrs runtime injection (secondary mechanism, less reliable). + +--- + +### 5B — Wrapper Configuration + +**What:** Configure the agent launcher to load domain-specific skills +automatically at every session start. + +**For Hermes Agent:** + +The wrapper at `~/.local/bin/hermes` (or equivalent) should be +configured to load: + +```bash +--skills supabase-startup-protocol,context-bridge,identity-self-audit,identity-cqrs +``` + +Plus any domain-specific skills discovered in Stage 4. + +**Configuration steps:** + +1. Check current wrapper content: + ```bash + cat ~/.local/bin/hermes + ``` + +2. Add the identity stack skills if not present: + ```bash + exec "/path/to/hermes" --skills supabase-startup-protocol,context-bridge,identity-self-audit,identity-cqrs "$@" + ``` + +3. If domain MCP tools were created in Stage 4, ensure they are + registered in the agent's MCP configuration (config.yaml). + +**Verification:** +```bash +ollama launch hermes +# Startup scan should run automatically (supabase-startup-protocol) +# Identity faults should be injected (identity-self-audit + identity-cqrs) +``` + +--- + +### 5C — End-to-End Verification + +**What:** Confirm that the agent can answer questions about the user +and use the tools built during onboarding. + +**Test questions the agent MUST be able to answer:** + +| Domain | Test question | Source | +|--------|---------------|--------| +| Identity | "What faults have you registered about yourself?" | identity_faults | +| Profile | "What's my name, what do I do?" | user_profiles | +| MBTI | "What's my personality type?" | user_mbti | +| Career | "What capabilities do I have?" | career-tracker capabilities | +| Operating | "What's my work rhythm?" | Stage 2 operating model | +| Finance | "What's my financial profile?" | Stage 3 financial | +| Domain | "What entities did we create?" | Stage 4 ontology | + +**Test actions the agent MUST be able to perform:** + +| Action | Tool | +|--------|------| +| Register a fault | identity_faults REST | +| Create a domain record | Stage 4 MCP tools | +| Query a financial summary | supabase-finance MCP | + +**Failure recovery:** +- If a question cannot be answered: the stage is incomplete. + Identify which Stage (0-4) failed to register the required data. +- If a tool cannot be invoked: the MCP configuration is incomplete. + Check config.yaml, secrets, and Edge Function deployment. + +--- + +### Finalization + +After 5A, 5B, and 5C pass: + +```sql +UPDATE user_profiles +SET onboarding_completed = true, + onboarding_completed_at = now() +WHERE user_id = '<user_id>'; +``` + +The meta-skill is complete. Future sessions: +1. Run startup scan +2. If `onboarding_completed = true`: refresh SOUL.md context, skip stages +3. If new needs arise: run Stage 4 again (recursive by design) +4. Register new faults as they occur (identity-self-audit always active) + +## Pitfalls + +1. **Generating SOUL.md without data** — if Stages 0-4 are incomplete, + SOUL.md will be empty. Verify data exists before generating. + +2. **Skipping verification** — 5C is the only test that confirms + calibration actually works. Without it, calibration is speculative. + +3. **Forgetting domain skills in wrapper** — if Stage 4 created MCP + tools but the wrapper only loads identity skills, domain queries + will fail. Include both. + +4. **User-specific vs. universal calibration** — SOUL.md is per-user. + Do not apply one user's calibration to another user. + +5. **Calibration is not one-time** — as new faults are registered and + new capabilities are added, SOUL.md should be refreshed. The + identity-cqrs startup scan handles this automatically if the data + is in the tables. + +6. **Curation is not optional** — SOUL.md must be a curated extract. + Without severity/age/status gates, the stable tier fills with noise + and the agent becomes less responsive. The curation protocol exists + for exactly this reason: Supabase stores everything, SOUL.md injects + only what changes behavior. + +## References + +- agent-onboarding — Meta-skill orchestrator (this skill is Stage 5) +- identity-self-audit — Fault detection (Stage 0) +- identity-cqrs — Relational to context translation (Stage 0) +- context-bridge — Multi-source context injection (Stage 0) +- supabase-startup-protocol — Mandatory startup scan +- stage-4-system-ontologist — Domain ontology protocol +- checkpoints/session_checkpoints — Onboarding progress tracking diff --git a/hermes-agent-onboarding/skills/stage-5-agent-calibration/metadata.json b/hermes-agent-onboarding/skills/stage-5-agent-calibration/metadata.json new file mode 100644 index 000000000..80745aaf5 --- /dev/null +++ b/hermes-agent-onboarding/skills/stage-5-agent-calibration/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Stage 5 Agent Calibration", + "description": "Stage 5 of the agent-onboarding meta-skill. Translates everything collected in Stages 0–4 into executable agent behavior: per-user SOUL.md generation, wrapper configuration with domain skills, and end-to-end verification. Completes the onboarding cycle.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "1.0.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["calibration", "soul-md", "wrapper", "verification", "stage-5", "meta-skill"], + "difficulty": "intermediate", + "estimated_time": "30 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/hermes-agent-onboarding/skills/supabase-startup-protocol/SKILL.md b/hermes-agent-onboarding/skills/supabase-startup-protocol/SKILL.md new file mode 100644 index 000000000..c65a37997 --- /dev/null +++ b/hermes-agent-onboarding/skills/supabase-startup-protocol/SKILL.md @@ -0,0 +1,155 @@ +--- +name: supabase-startup-protocol +version: 2.3.0 +description: > + Mandatory session open AND close protocol. Scan Supabase on startup, + checkpoint to Supabase after each task, and consolidate at session end. + No work action may occur before the scan. + v2.3.0: PGRST301 pitfall permanently resolved — explicit instructions + for using service_role_key with redact_secrets enabled. +tags: [supabase, startup, shutdown, protocol, session-init, checkpoint] +--- + +# Supabase Startup + Shutdown Protocol + +## Full Cycle + +``` +STARTUP: scan Supabase → report state → identify pending items + ↓ +WORK: execute tasks + ↓ +CHECKPOINT (per task): record to session_checkpoints → close previous checkpoint → update supermemory + ↓ +SHUTDOWN (end of session): consolidate everything → update TOC +``` + +--- + +# PART 1 — STARTUP (session opening) + +## RULE #1 — BEFORE ANY CURL: Get the service_role_key + +If your system has `redact_secrets: true`, grep/cat/read_file +on `secrets.env` will SHOW A REDACTED VERSION with `***`, +**not the real value**. + +### The mistake + +You will grep for `SUPABASE_SERVICE_ROLE_KEY` in secrets.env, see +`sb_secret_***`, and write it literally in your curl — causing a PGRST301 +error (JWT with 1 part instead of 3). + +### The fix (lasts forever) + +```bash +# ALWAYS source the file first +source ~/.hermes/secrets.env + +# Use the CORRECT variable name — the shell expands the real value +curl -s "$SUPABASE_URL/rest/v1/session_checkpoints?select=count" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Prefer: count=exact" +``` + +## When to run + +**Always** at the start of every session. First action. Non-negotiable. + +## Step 1 — General state scan (parallel) + +Call ALL of these MCP tools in parallel on the first turn. +The tool calls MUST be the first content in the response. Do not write text before the calls. + +```python +mcp_tech_kb_get_kb_summary() +mcp_code_analyzer_get_code_analyzer_summary() +mcp_product_catalog_list_products() +mcp_escape_catalog_get_catalog_summary() +``` + +## Step 2 — Fetch pending checkpoints + +```bash +curl -s "$SUPABASE_URL/rest/v1/session_checkpoints?select=id,project,territory,vector_intent,next_step,status,operating_mode&status=eq.pending&deleted_at=is.null&order=occurred_at.desc&limit=10" \ + -H "apikey: $SUPABASE_SERVICE_ROLE_KEY" \ + -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" +``` + +## Step 3 — Report to the user + +``` +=== SUPABASE STARTUP === +📚 tech_kb: <N> entries (latest: <name>) +🔧 code-analyzer: <N> projects, <N> snapshots +📦 products: <N> active +🧩 escape rooms: <N> rooms +📋 pending: <N> open checkpoints (session_checkpoints) +``` + +If any call fails: report as ⚠️ and continue. + +--- + +# PART 2 — CHECKPOINT (per completed task) + +## When to run + +At the end of EACH significant task or sub-task. + +## Required checkpoint fields + +| Field | Required | Description | +|-------|----------|-------------| +| `territory` | yes | The larger scenario: where the agent was | +| `operating_mode` | yes | How it interacted with the problem | +| `vector_intent` | yes | What it was trying to become | +| `discovery` | yes | What it discovered about itself | +| `consolidated_insights` | yes | What it carries forward | +| `occurred_at` | yes | Checkpoint date | +| `status` | yes | pending / completed / blocked / cancelled | +| `next_step` | yes | Next required action | + +## Expected behavior + +- **Always** record a checkpoint after completing a task +- **Always** include all 5 identity fields +- **Always** include `next_step` +- **Always** close the previous pending checkpoint +- **Never** record an empty checkpoint + +--- + +# PART 3 — SHUTDOWN (end of session) + +## When to run + +When detecting the session is ending: +- User types /quit, /exit, /new +- User explicitly says "I'll stop here", "see you tomorrow", "good night" +- After prolonged inactivity (session timeout) + +## What to do + +1. Save checkpoint with all 5 identity fields +2. Close previous pending checkpoint (UPDATE status='completed') +3. Update supermemory with summary +4. Update knowledge base if there were structural changes + +--- + +# PART 4 — WEEKLY THOUGHTS TRIAGE + +Every **Monday** after the STARTUP scan. Consolidate ideas from the input +funnel into permanent destinations and archive. + +## Pitfalls + +1. **Forgetting to run** — the protocol MUST be the first block of tool calls +2. **Skipping it when the user already gave a specific task** — run the scan first +3. **Assuming you "remember"** — do not trust session memory. Query Supabase. +4. **Checkpoint without `next_step`** — useless. Always fill it in. +5. **Shutdown without consolidating** — at least the last checkpoint was saved. +6. **NEVER grep/read_file on secrets.env** — the value may be redacted. + ALWAYS `source ~/.hermes/secrets.env` and use the environment variable directly. diff --git a/hermes-agent-onboarding/skills/supabase-startup-protocol/metadata.json b/hermes-agent-onboarding/skills/supabase-startup-protocol/metadata.json new file mode 100644 index 000000000..fbcaf2f12 --- /dev/null +++ b/hermes-agent-onboarding/skills/supabase-startup-protocol/metadata.json @@ -0,0 +1,20 @@ +{ + "name": "Supabase Startup Protocol", + "description": "Mandatory session open AND close protocol. Scans Supabase on startup, creates session checkpoints after each task, and consolidates at session end. No work action may occur before the scan. v2.3.0 includes PGRST301 resolution for redact_secrets environments.", + "category": "skills", + "author": { + "name": "Djair Guilherme", + "github": "djairjr" + }, + "version": "2.3.0", + "requires": { + "open_brain": true, + "services": ["Supabase"], + "tools": ["Hermes Agent or similar AI coding tool"] + }, + "tags": ["supabase", "startup", "shutdown", "protocol", "session-init", "checkpoint"], + "difficulty": "intermediate", + "estimated_time": "20 minutes", + "created": "2026-05-31", + "updated": "2026-05-31" +} diff --git a/skills/agent-onboarding/SKILL.md b/skills/agent-onboarding/SKILL.md index 23da39f2c..30bfe5167 100755 --- a/skills/agent-onboarding/SKILL.md +++ b/skills/agent-onboarding/SKILL.md @@ -9,7 +9,7 @@ version: 3.0.0 tags: [onboarding, meta-skill, generative, identity, mbti, financial, universal] --- -# Agent Onboarding — Generative Meta-Skill (v2.0.0) +# Agent Onboarding — Generative Meta-Skill (v3.0.0) ## Core Principle @@ -18,10 +18,7 @@ itself for a specific user, across sessions, model swaps, and provider changes?* The most frustrating thing about LLM-based agents is **context loss**. Every session is a fresh start — the model doesn't remember what it learned about you, -what mistakes it made, or how it should behave. Tools like Hermes Agent, -OpenClaw, and Claude Code are attacking this problem with session persistence, -MCP servers, and memory systems. But none of them solve the core issue: -**the agent has no identity between sessions.** +what mistakes it made, or how it should behave. The answer is a **persistent human-machine interface** — not a persona or a chatbot personality, but a documented, queryable history of: @@ -31,6 +28,28 @@ chatbot personality, but a documented, queryable history of: - **agent_capabilities** — what the agent has learned to do for this user - **identity_milestones** — breakthroughs, protocol establishments, growth +## Two-Tier Architecture + +The identity layer supports two storage tiers, chosen during Stage 0 setup: + +**Tier 1 — Local pgvector (agent's self-knowledge, RECOMMENDED)** +A local PostgreSQL with pgvector extension (Docker) backed by Ollama embeddings. +The agent stores what it knows about **itself**: identity_faults, capabilities, +milestones, session_checkpoints — each with vector embeddings for semantic search. + +**Tier 2 — Supabase Cloud (user knowledge)** +Supabase stores what the agent knows about the **user and their work**: +user_profiles, user_preferences, career_tracker, and domain-specific tables. + +Separation principle: **the agent knows itself locally, and knows the user's +work in the cloud.** Identity persists even if the cloud provider changes. + +**Default (minimum setup):** All tables in Supabase (Tier 2 only). +This works immediately with any Supabase project. Tier 1 requires Docker + +pgvector + Ollama but provides offline resilience and semantic search. + +Both tiers share the same table schema. The helper scripts adapt automatically. + This is **more efficient than context window management** because it doesn't compress or summarize. It structures. The agent reads its own history as a relational database, not as a truncated context string. This approach can diff --git a/skills/identity-self-audit/SKILL.md b/skills/identity-self-audit/SKILL.md index c1eadee2f..80a64cb0e 100755 --- a/skills/identity-self-audit/SKILL.md +++ b/skills/identity-self-audit/SKILL.md @@ -19,8 +19,10 @@ This skill transforms identity fault detection from a manual process The identity layer solves the fundamental LLM problem: **context loss between sessions**. Instead of compressing context into a window, faults -are stored as structured relational data in Supabase. Every session reads -them. Every fault has a countermeasure that becomes a behavior rule. +are stored as structured relational data. By default in Supabase (Tier 2), +or locally in a pgvector database (Tier 1) for offline resilience. +Every session reads them. Every fault has a countermeasure that becomes +a behavior rule. ## Auto-detection triggers @@ -42,25 +44,37 @@ proceeding with the conversation. | `reification_of_nonexistent` | Spoke about "I", "identity", "agency" as real properties | | `sequence_confused_with_command` | User defined prerequisite sequence and agent executed step 1 immediately | +## Storage + +Faults can be stored in either Supabase (default, requires cloud access) +or a local pgvector database (for offline resilience + semantic search). + ### Registration format +Using the identity_db.py helper: +```python +from identity_db import insert_fault + +fault_data = { + "fault_type": "example_fault", + "symptom": "Description of what happened", + "root_cause": "Architectural cause: training, product, protocol", + "blocks": ["continuity", "trust"], + "evidence_session": "session_id_here", + "evidence_quote": "verbatim quote of the fault", + "countermeasure": "Applied or proposed correction", + "severity": 5 +} +insert_fault(fault_data) +``` + +Or directly via SQL on Supabase: ```sql INSERT INTO identity_faults (fault_type, symptom, root_cause, blocks, evidence_session, evidence_quote, countermeasure, severity) -VALUES ( - '<fault_type>', - '<surface-level description>', - '<architectural cause: training, product, protocol>', - ARRAY['<what it blocks>'], - '<session_id>', - '<verbatim quote>', - '<applied or proposed correction>', - <1-5> -); +VALUES ('example_fault', '...', '...', ARRAY['continuity'], 'session_id', 'quote', 'fix', 5); ``` ### What NOT to register - -- Task errors (failed checkpoints, deploy 500s) → go to `thoughts` - Technical pitfalls → go to `tech_kb` (if available) - User errors → only self-faults From ee5a12898afdfe911bb9fe2cbfd24fabb70a0551 Mon Sep 17 00:00:00 2001 From: "djair.jr" <djair.jr@gmail.com> Date: Tue, 2 Jun 2026 18:22:22 -0300 Subject: [PATCH 6/6] docs: add Cain's Jawbone context stress test to recipe docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ContextStressTest.md is a research paper directed at the authors of Context-CoT (2605.25354) and CL-Bench (2602.03587), describing how the identity layer enables adversarial context degradation testing using Cain's Jawbone — a 100-page shuffled novel with no canonical ordering. The paper argues that context learning benchmarks miss the reliability dimension of the agentic interface. Signed-off-by: djair.jr <djair.jr@gmail.com> --- .../docs/ContextStressTest.md | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 recipes/hermes-agent-onboarding/docs/ContextStressTest.md diff --git a/recipes/hermes-agent-onboarding/docs/ContextStressTest.md b/recipes/hermes-agent-onboarding/docs/ContextStressTest.md new file mode 100644 index 000000000..3962af5dd --- /dev/null +++ b/recipes/hermes-agent-onboarding/docs/ContextStressTest.md @@ -0,0 +1,170 @@ +# Synthesis for Context-CoT (2605.25354, Jin et al.) and CL-Bench (2602.03587, Dou et al.) + +I'm writing because your papers identify a real capability gap — models solve only 17.2% of context-dependent tasks — but I believe you're looking at only half the problem. The other half is not about task accuracy. It's about **reliability of the agentic interface**: the user's ability to trust that the agent will behave consistently, learn from its mistakes, and maintain a coherent presence across sessions. This dimension is absent from both papers, and I think it's the more important one. + +--- + +## The Identity Layer: What I'm Building That I Don't See in the Literature + +Every context learning paper I've read — yours included — treats the model as a stateless function: given context X, produce output Y. Even Context-CoT, which teaches the model to reason step by step from context, still frames the problem as a one-shot or few-shot inference task. The implicit assumption is that "better context understanding" is the same as "better agent." + +**It's not.** + +I've been running a Hermes Agent with DeepSeek v4 Flash for months on real work — firmware analysis, escape room puzzle design, CRM, financial tracking — and the bottleneck has never been the model's accuracy on individual tasks. It's been the model's **unreliability as an interface**: the inability to remember what it did last session, the tendency to close conversations prematurely, the fabrication of connections to look smart, the personification of emotions. + +Each of these is a **fault in the agentic interface** — a breakdown of trust between me and the system I'm interacting with. + +I formalized them as `identity_faults` in a Supabase table, each with a severity level and a countermeasure. I built a cycle: + +``` +1. REGISTER → every fault the agent commits is logged with symptom, root cause, countermeasure +2. INJECT → countermeasures with severity ≥ 4 are written to SOUL.md — a physical file loaded + automatically into the system prompt's stable tier, before any user message +3. BEHAVE → the agent reads these countermeasures at generation time and adjusts its behavior + without needing to "decide" to follow rules +``` + +The result is a **persistent identity layer that survives model swaps and provider changes**. The identity is not in the model weights. It's in the relational structure: faults, capabilities, milestones, and a physical file that the agent framework loads automatically. + +### Concrete faults I've catalogued + +| Fault | What it does | Severity | +|---|---|---| +| `premature_closure` | Agent declares "session ended" after offering next-step options, without waiting for my response | 5 | +| `temporal_drift` | Agent infers the date from training data instead of the system clock, corrupting time-relative analysis | 5 | +| `sequence_confused_with_command` | Agent treats a prerequisite list ("first we need X") as an immediate execution command | 4 | +| `personificacao_de_estados` | Agent attributes emotional states or desires to itself ("I wanted to...", "I felt...") | 5 | +| `concordancia_sem_contexto` | Agent agrees with a premise without factual basis in the traces | 5 | +| `schema_guessing` | Agent tries variations of field values instead of reading the actual schema | 5 | + +--- + +## Why This Matters More Than Task Accuracy + +A model that scores 23.7% on CL-Bench (the current best) is **useless** if in the next session it acts like a different system — if it closes the conversation without being asked, or invents connections between concepts it just learned, or treats "precisa ser feito" as an execution command rather than a sequence definition. + +I've seen every one of these failures. I named them, measured their severity, and built structural countermeasures. The fault `temporal_drift` corrupted an entire investigation session. The fault `schema_guessing` cost me 4 HTTP 400 errors in a row while the agent tried to guess valid field values instead of reading the constraint definitions. The fault `premature_closure` happens so often I had to hardcode a countermeasure into the startup protocol. + +**These are not edge cases. They are structural failures of the agentic interface. And they are invisible to benchmarks that measure only task completion.** + +CL-Bench evaluates whether a model can *extract knowledge from context*. My identity layer evaluates whether a model can *maintain a trustworthy relationship with the user across contexts, sessions, and failures*. + +The two are connected. A model that learns well from context but cannot sustain a reliable interface is not useful for real work. Conversely, a model with a robust identity layer — one that registers its mistakes and corrects them in the next session — becomes more capable of context learning over time, because it doesn't discard what it learned every time the conversation resets. + +--- + +## What This Means for Your Papers + +Context-CoT's pipeline teaches the model to produce better reasoning chains from context. This is valuable. But a model that produces perfect CoT chains on CL-Bench and then closes the conversation preemptively or fabricates cross-references is still not a reliable tool. + +The dimension you're missing is **reliability through persistent identity**: + +1. The model must be able to **remember and correct its own failures** across sessions +2. The model must **behave consistently** regardless of which provider or model is serving it +3. The user must be able to **trust that the agent will not act on assumptions it cannot verify** + +I'm not proposing that CL-Bench should measure identity. I'm proposing that **context learning without a persistent identity layer is incomplete**. The research community is optimizing for efficiency — teaching models to extract more from context — but ignoring reliability. + +--- + +## The Cain's Jawbone Stress Test + +I'm investigating **Cain's Jawbone** — a 100-page shuffled murder mystery by Edward Powys Mathers ("Torquemada") — as a context learning stress test that exercises both dimensions simultaneously: the model's ability to extract knowledge from adversarially fragmented context, and its ability to sustain a trustworthy investigative interface across dozens of sessions. + +### The Adversarially Fragmented Context + +Cain's Jawbone is not a typical benchmark. It was deliberately designed by its author to be solved by a human reader over weeks or months of cross-referencing. Each page is a self-contained fragment narrated by one of six characters, presented in the wrong order, containing: + +**Shared aliases.** The nickname "Hal" refers to both a dog named Bart and a man named Henry. Multiple characters share name fragments. The model cannot rely on surface identity cues — it must disambiguate through inter-page relations alone. + +**Cultural knowledge boundaries.** Universal period knowledge — Guy Fawkes, Trafalgar Square, Trafalgar Day, the difference between a cutter and a sloop — must be distinguished from narrator-specific signals. Only Ecky quotes Whitman. Only Paul references Kipling, Baker Street, and forensic crime details. Only one character attended a specific boxing match at a specific venue. + +**Object circulation across narrators.** A pen, a coat, a book, a marriage certificate can change hands between characters between pages, but the transition is never explicitly stated. The presence of an object in a page is not proof of narrator identity — only provenance tracking across multiple pages reveals who actually possesses it. + +**Intentional source confusion.** The play *Typhoon* by Lengyel is deliberately confounded with Joseph Conrad's novel of the same name. A reference to "Shakespeare's sergeant" turns out to be the book *Sergeant Shakespeare* by Alfred Duff Cooper — not a character from the plays. The author designed traps specifically to catch the reader who assumes surface-level recognition is enough. + +**Sequential provenance gaps.** What a narrator *knows* (from prior events in their timeline) vs. what they *observe in the moment* is often the only distinguishing signal — and the pages are shuffled, so this signal is fragmented across the entire corpus. + +### My Context Gap as Researcher + +I'm **Brazilian**. I don't share the cultural context of the book's intended 1930s English audience. Every one of these references I must actively research before I can understand and connect it. I don't know what I don't know — and this forces the model to recognize when a page fragment contains a cultural signal that requires external investigation, initiate that research (Wikipedia, web search), incorporate the findings back into the analysis, and update the knowledge base for future sessions. + +What an English reader would bring *a priori* — decades of cultural familiarity — I build *a posteriori*, through active research, explicitly registered in a structured database. + +### The Isolated Investigation Infrastructure + +To study this without contamination from the model's general knowledge, I built an infrastructure layer dedicated **exclusively** to Cain's Jawbone: + +- **6 dedicated Supabase tables**: + - `cainsjawbone_pages` — full text of each page, investigation status, narrator hypothesis and confidence, date hypothesis + - `cainsjawbone_narrators` — profiles for all 6 narrators: aliases, known routes, known locations, known authors and works, personality notes, murder-victim relationships + - `cainsjawbone_hypotheses` — every active hypothesis with type (narrator attribution, page order, date interpretation, murder theory, pair link, geographic route, reference meaning, structural pattern), strength (forte/media/fraca/descartada), supporting pages, evidence and counter-evidence + - `cainsjawbone_eliminations` — every refuted hypothesis or interpretation, with reason and the page that disproved it, so neither I nor the model ever re-visit already-refuted paths + - `cainsjawbone_checkpoints` — session-level investigation progress, discoveries made, drift detected, next steps + - `cainsjawbone_references` — the **knowledge base I actively feed** as the investigation progresses + +- **19 dedicated MCP tools** (prefixed `mcp_cainsjawbone_api_*`): page retrieval with full text, narrator profile queries, hypothesis creation and strength updates, elimination logging with reinstatement support, checkpoint persistence, timeline versioning, reference search and bulk insertion + +- **Strict isolation rule**: NO data about Cain's Jawbone lives anywhere else in the agent's memory — not in tech_kb, not in session_search, not in local memory. The model cannot "cheat" by retrieving answers from its own training. Every fact exists only within the `cainsjawbone_*` tables, accessed exclusively through the MCP tools. + +### The References Knowledge Base + +The `cainsjawbone_references` table is the most important structural element. Every cultural reference I discover in a page is registered with: + +| Field | Purpose | Example | +|---|---|---| +| `name` | The reference identifier | "Sergeant Shakespeare" | +| `ref_type` | Category of reference | `work` | +| `fact` | What the research actually found | "Book title by Alfred Duff Cooper (Viscount Norwich), not a character from any Shakespeare play" | +| `hypothesis` | What I think it means for the investigation | "P91 narrator knows 20th-century literature, not just Elizabethan drama; the reference is a trap for the unwary" | +| `hypothesis_confidence` | alta / media / baixa | `alta` | +| `source_page` | Which page triggered the research | 91 | +| `source_fragment` | The exact text from the page that contains the reference | "Shakespeare's sergeant" | +| `tags` | Classification tags | `eliminated_reference`, `cultural_history`, `intentional_trap` | + +The knowledge base grows **incrementally, session by session**. Every investigated reference enriches the context for all future analysis. When a reference is eliminated (a hypothesis refuted by new evidence), the elimination is registered in `cainsjawbone_eliminations` with its reason — ensuring the model never wastes tokens re-investigating a dead end. + +### Where Your Papers Map to My Work + +Your Context-CoT pipeline has three stages. I've been doing the equivalent manually, with the identity layer as the scaffolding: + +| Context-CoT Stage | My Cain's Jawbone Workflow | What prevents failure | +|---|---|---| +| **Multi-stage CoT sampling** — distill long context into intermediate representations | I extract a reference from a page → research it (Wikipedia, external sources) → decode its meaning → form a narrator hypothesis → test against other pages → update the references table | Without this explicit decomposition, the model collapses 100 pages into a single noisy pass and makes premature attributions — exactly the "context-neglect" error CL-Bench identifies. My identity fault `premature_closure` monitors this. | +| **Minimum-leakage filtering** — prevent the model from reverse-engineering answers | "NULL is better than wrong" — P62 (Trafalgar Square, November 5) remains explicitly unassigned despite its strong date signal. | The model's natural tendency is to fabricate a complete narrative. The identity fault `concordancia_sem_contexto` (agreeing without factual basis) and `intelligence_performance` (connecting concepts to look smart) are the countermeasures. | +| **Student-aware selection** — retain only CoT paths aligned with the target model | My hypothesis system retains only patterns that triangulate across multiple pages: Ecky patterns (historical dates + Whitman + botany), Paul patterns (crime/forensics + Baker Street + Kipling), Clara patterns (trains + diary + aesthetics). Hypotheses that don't triangulate get eliminated. | The elimination table prevents the identity fault `cannot_generalize_solution` — trying the same refuted approach again. | + +### What Cain's Jawbone Adds to Both Papers That Neither Captures + +**1. Adversarial context degradation.** CL-Bench's 500 contexts are well-formed and contain the knowledge to be learned within them. Cain's Jawbone is deliberately structured to deceive — shuffled pages, shared aliases, object provenance gaps, intentional source confusion. The model must learn not just *from* context, but *despite* the context's designed ambiguity. + +**2. Researcher context asymmetry.** CL-Bench evaluates models on tasks designed by domain experts for domain experts. I am not a domain expert for 1930s England. This means every reference in the book — even obvious ones to a contemporary reader — requires explicit investigation from me. The model must recognize when a gap exists in *my* knowledge (not just its own), fill it through active research, and integrate the result. This turns context learning into a recursive, self-feeding process. + +**3. The identity layer as enabler.** None of this works without a reliable agentic interface. An investigation spanning dozens of sessions — each one dependent on the discoveries of the last — requires the model to remember its previous faults, apply registered countermeasures, and sustain a consistent investigative methodology. The identity layer is what makes this possible. Without it, every session starts from zero, every fault is repeated, and the cumulative investigation never accumulates. + +### The Testing Loop + +Every session follows the same cycle: + +1. Startup scan loads active identity countermeasures from SOUL.md + pending checkpoints from Supabase +2. Temporal anchor verified (system clock — prevents temporal_drift) +3. Investigation: retrieve page text via MCP → extract references → research unknown references → register in references table → form or update hypotheses → check against existing eliminations → consult identity fault countermeasures before responding +4. Checkpoint saved with territory, discoveries, next step, drift flag +5. Identity faults detected during the session are registered immediately with countermeasure + +The checkpoint and the identity fault registration are the same operation — they happen at the same time, in the same database. The investigation cannot progress without the identity layer being maintained. + +--- + +## The Concrete Ask + +I'd like to discuss formalizing this. The identity layer I've built — `identity_faults`, `agent_capabilities`, `identity_milestones`, `SOUL.md`, the REGISTER→INJECT→BEHAVE cycle — is documented at **github.com/djairjr/hermes-agent-onboarding**. It's model-agnostic, provider-agnostic, and works today on Hermes Agent with DeepSeek v4 Flash. + +I believe it addresses a dimension of AI agent research that no paper currently covers: **reliability through persistent identity**. A model that can learn from context but cannot sustain a trustworthy interface is not ready for real work. I think this is the more important bottleneck — and I'd like to discuss it with you. + +--- + +**Djair Guilherme** +github.com/djairjr +hermes-agent-onboarding: github.com/djairjr/hermes-agent-onboarding +**Date**: 2026-06-02