@rigstate/rules-engine 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateAvailableSkillsSection = generateAvailableSkillsSection;
4
+ exports.generateSkillFileContent = generateSkillFileContent;
5
+ exports.getRigstateStandardSkills = getRigstateStandardSkills;
6
+ /**
7
+ * Generate the <available_skills> XML block for the root .cursorrules file.
8
+ */
9
+ function generateAvailableSkillsSection(skills) {
10
+ if (skills.length === 0)
11
+ return '';
12
+ const skillBlocks = skills.map(skill => ` <skill>
13
+ <name>${skill.name}</name>
14
+ <description>${skill.description}</description>
15
+ <location>.agent/skills/${skill.name}/SKILL.md</location>
16
+ </skill>`).join('\n');
17
+ return `## 🧠 AGENT SKILLS
18
+ > **OPTIMIZED CAPABILITIES:** The following skills are available for on-demand activation.
19
+
20
+ <available_skills>
21
+ ${skillBlocks}
22
+ </available_skills>`;
23
+ }
24
+ /**
25
+ * Generate the content for a specific SKILL.md file.
26
+ */
27
+ function generateSkillFileContent(skill) {
28
+ return `---
29
+ name: ${skill.name}
30
+ description: ${skill.description}
31
+ version: "${skill.version}"
32
+ specialist: ${skill.specialist}
33
+ governance: ${skill.governance}
34
+ ---
35
+
36
+ ${skill.content}
37
+
38
+ ---
39
+ *Generated by Rigstate Rules Engine. Do not modify manually.*`;
40
+ }
41
+ /**
42
+ * Get the standard Rigstate library of skills.
43
+ */
44
+ function getRigstateStandardSkills() {
45
+ return [
46
+ {
47
+ name: 'rigstate-integrity-gate',
48
+ description: 'Handles the Pre-Deployment Compliance Gate, automated quality audits (Security/Performance), and generation of the Strategic Release Manifest. Use this whenever you are finishing a task or moving code towards completion.',
49
+ version: '1.0.0',
50
+ specialist: 'Frank (The Orchestrator)',
51
+ governance: 'SOFT_LOCK',
52
+ content: `# 🎖️ Rigstate Integrity Gate Skill
53
+
54
+ This skill defines the high-level protocol for ensuring code quality and security before a task is marked as "COMPLETED". It orchestrates specialized agents (Sven, Sindre) and generates the audit trail known as the **Strategic Release Manifest**.
55
+
56
+ ## 🔄 The Protocol Workflow
57
+
58
+ Whenever you are ready to complete a task, follow this mandatory 3-step sequence:
59
+
60
+ ### 1. Audit (The Scan)
61
+ Run the \`audit_integrity_gate\` tool. This will trigger:
62
+ - **Security Check (Sven):** Scans for RLS status on all tables.
63
+ - **Performance Check (Sindre):** Scans for N+1 queries and missing database indexes.
64
+
65
+ ### 2. Decision (The Gate)
66
+ Evaluate the result from \`audit_integrity_gate\`:
67
+ - **Mode: OPEN:** All critical checks passed. You can proceed to completion.
68
+ - **Mode: SOFT_LOCK:** Issues were found (e.g., missing RLS or N+1 warnings). You **MUST** report these to the user. You can only proceed if the user provides an override or if you fix the issues first.
69
+ - **Mode: HARD_LOCK (Future):** Critical violations detected. Completion is blocked until fixed.
70
+
71
+ ### 3. Manifest (The Release)
72
+ Upon passing the gate, use the \`complete_roadmap_task\` tool.
73
+ - Pass the **full JSON response** from the \`audit_integrity_gate\` into the \`integrityGate\` parameter.
74
+ - This automatically generates the **Strategic Release Manifest** in the Mission Report, creating a permanent record of quality for this release.
75
+
76
+ ## 🛠️ Tools Used by this Skill
77
+
78
+ - \`audit_integrity_gate\`: Orchestrates the security and performance scans.
79
+ - \`complete_roadmap_task\`: Finalizes the task and attaches the quality certificate.
80
+
81
+ ## 📝 Best Practices
82
+
83
+ - **Never skip the audit.** Even if you think the change is small, the Integrity Gate is our source of truth.
84
+ - **Explain violations clearly.** If in \`SOFT_LOCK\`, don't just say "it failed". List the specific tables lacking RLS or the specific files with N+1 issues.
85
+ - **Summarize the Manifest.** After successful completion, tell the user: "Release Manifest generated with [X] security passes and [Y] performance checks."`
86
+ },
87
+ {
88
+ name: 'rigstate-legacy-renovator',
89
+ description: 'Handles the modernization of legacy Vibeline code to the Rigstate standard. Renovates branding, extracts "Ghost Features" into the roadmap, and repairs architectural drift.',
90
+ version: '1.0.0',
91
+ specialist: 'Brynjar (The Archivist)',
92
+ governance: 'SOFT_LOCK',
93
+ content: `# 🏺 Rigstate Legacy Renovator Skill
94
+
95
+ This skill is activated when legacy patterns (e.g., "Vibeline") are detected. It uses archaeological scanning to restore technical history and performs branding renovation.
96
+
97
+ ## 🔄 The Protocol Workflow
98
+
99
+ ### 1. Archaeological Scan (The Discovery)
100
+ Use the \`archaeological_scan\` tool to find "Ghost Features" – completed work that is not yet reflected in the project roadmap. This restores the technical context of the project.
101
+
102
+ ### 2. Import Ghost Features
103
+ If the scan discovers COMPLETED work, use \`import_ghost_features\` to add them to the roadmap. This ensures the agent understands the historical foundation it is building upon.
104
+
105
+ ### 3. Branding Renovation
106
+ Identify "Vibeline" references in:
107
+ - UI components (Text logos, labels)
108
+ - Code comments and TODOs
109
+ - Documentation
110
+ - Database seed files
111
+
112
+ Perform a non-destructive rename to "Rigstate" following the rebrand protocol.
113
+
114
+ ### 4. Dependency Audit
115
+ Check for circular dependencies or architectural violations in legacy modules using \`analyze_dependency_graph\`.
116
+
117
+ ## 🛠️ Tools Used by this Skill
118
+
119
+ - \`archaeological_scan\`: Reconstructs project history from Git.
120
+ - \`import_ghost_features\`: Synchronizes historical work with the roadmap.
121
+ - \`analyze_dependency_graph\`: Detects architectural rot.
122
+
123
+ ## 📝 Best Practices
124
+
125
+ - **Respect History.** Don't delete legacy notes; transform them into Rigstate memories.
126
+ - **Batched Renaming.** Rename branding in logical groups (e.g., all UI first, then all comments).
127
+ - **Update the Brain.** When a legacy feature is renovated, save the decision to the Project Brain using \`save_to_project_brain\`.`
128
+ }
129
+ ];
130
+ }
@@ -0,0 +1,2 @@
1
+ import { RuleGenerationContext } from '../types';
2
+ export declare function generateStackDnaSection(project: RuleGenerationContext["project"], stack: string[], legacyStats?: RuleGenerationContext["legacyStats"]): string;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateStackDnaSection = generateStackDnaSection;
4
+ function generateStackDnaSection(project, stack, legacyStats) {
5
+ const stackText = stack.length > 0
6
+ ? stack.map(s => `- ${s}`).join('\n')
7
+ : '- Next.js 14+ (App Router)\n- Supabase\n- TypeScript\n- Tailwind CSS';
8
+ const tenancy = project.tenancy || 'SINGLE';
9
+ const monetization = project.monetization || 'FREE';
10
+ const compliance = project.compliance || 'NONE';
11
+ const vibe = project.vibe || 'CREATIVE';
12
+ // Dynamic settings with defaults
13
+ const lmax = project.settings?.lmax || 400;
14
+ const lmaxUi = project.settings?.lmax_ui || 250;
15
+ const securityLevel = project.settings?.security_level || 'STANDARD';
16
+ const guardianRules = [
17
+ `🛡️ **THE ${lmax}-LINE RULE (STRICT):** No file may exceed ${lmax} lines. If approaching this limit, you MUST propose a refactor into smaller modules.`,
18
+ `🛡️ **TSX LIMIT:** React components (.tsx) should not exceed ${lmaxUi} lines. Extract sub-components proactively.`,
19
+ '🛡️ **TYPE SAFETY:** Avoid "any". Use strict TypeScript types. Infer from Zod schemas when possible.',
20
+ ];
21
+ if (tenancy === 'MULTI_ORG') {
22
+ guardianRules.push('🔐 All database queries MUST be org-scoped (filter by org_id)');
23
+ guardianRules.push('🔐 Implement proper organization switching in UI');
24
+ }
25
+ else {
26
+ guardianRules.push('👤 All queries are user-scoped (filter by user_id or RLS)');
27
+ }
28
+ if (stackText.toLowerCase().includes('supabase')) {
29
+ guardianRules.push('⚡ Enable RLS on ALL new tables immediately');
30
+ guardianRules.push('⚡ Use @supabase/ssr patterns for server-side auth');
31
+ }
32
+ if (compliance === 'GDPR') {
33
+ guardianRules.push('🛡️ GDPR: Implement data export and deletion endpoints');
34
+ }
35
+ else if (compliance === 'HIPAA') {
36
+ guardianRules.push('🛡️ HIPAA: Encrypt all PHI at rest and in transit');
37
+ }
38
+ // Security Level Rules
39
+ if (securityLevel === 'STRICT') {
40
+ guardianRules.push('🔒 STRICT MODE: All inputs MUST be validated with Zod schemas');
41
+ guardianRules.push('🔒 STRICT MODE: Consult Security Specialist for ANY auth-related changes');
42
+ }
43
+ else if (securityLevel === 'MINIMAL') {
44
+ guardianRules.push('⚡ MINIMAL MODE: Focus on speed over security hardening for MVP');
45
+ }
46
+ // IMPACT_GUARD: Dependency analysis before destructive actions
47
+ guardianRules.push('🚨 **IMPACT_GUARD:** Before deleting ANY file, you MUST:');
48
+ guardianRules.push(' 1. Search codebase for all imports/references (use grep_search or equivalent)');
49
+ guardianRules.push(' 2. Update or remove ALL references first');
50
+ guardianRules.push(' 3. Only delete after confirming ZERO references remain');
51
+ guardianRules.push(' 4. Commit changes atomically (references + deletion in same commit)');
52
+ // BUILD_INTEGRITY: Type-check verification after structural changes
53
+ guardianRules.push('✅ **BUILD_INTEGRITY:** After ANY structural change (new files, moved modules, refactors):');
54
+ guardianRules.push(' 1. Run type-check (e.g., `tsc --noEmit` or framework equivalent)');
55
+ guardianRules.push(' 2. Verify build success before declaring task complete');
56
+ guardianRules.push(' 3. If errors detected, fix immediately—do NOT leave broken builds');
57
+ let legacySection = '';
58
+ if (legacyStats && legacyStats.legacyCount > 0) {
59
+ legacySection = `
60
+ ### 📚 Legacy Context
61
+ This project contains **${legacyStats.legacyCount} legacy features** (imported via Brynjar) and **${legacyStats.activeCount} active features**.
62
+
63
+ **LEGACY AWARENESS RULE:**
64
+ When encountering code or features marked with \`is_legacy: true\`:
65
+ - Treat them as **Established Foundations** — they are proven, working code.
66
+ - Any modifications to legacy code MUST bring it up to current Guardian standards:
67
+ - Type-safety (no "any")
68
+ - RLS enforcement (if database-related)
69
+ - 400-line limit compliance
70
+ - Proper error handling
71
+ - Do NOT count legacy features in velocity metrics — they predate Rigstate.`;
72
+ }
73
+ return `## 🧬 STACK DNA
74
+
75
+ ### Tech Stack
76
+ ${stackText}
77
+
78
+ ### Project Configuration
79
+ | Attribute | Value |
80
+ |-----------|-------|
81
+ | Tenancy | ${tenancy} |
82
+ | Monetization | ${monetization} |
83
+ | Compliance | ${compliance} |
84
+ | Design Vibe | ${vibe} |
85
+ ${legacySection}
86
+
87
+ ### 🛡️ GUARDIAN RULES (Mandatory)
88
+ ${guardianRules.map(r => `${r}`).join('\n')}`;
89
+ }
@@ -0,0 +1,2 @@
1
+ import { RuleGenerationContext } from '../types';
2
+ export declare function generateToolingSection(activeAgents?: RuleGenerationContext["activeAgents"]): string;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateToolingSection = generateToolingSection;
4
+ function generateToolingSection(activeAgents) {
5
+ const getAgent = (keyPart) => activeAgents?.find((a) => a.key.includes(keyPart));
6
+ const frank = getAgent('frank') || getAgent('orchestrator');
7
+ const brynjar = getAgent('brynjar');
8
+ const gunhild = getAgent('scribe');
9
+ const sindre = getAgent('sindre');
10
+ const sven = getAgent('sven');
11
+ const allTools = [
12
+ { name: 'query_brain', owner: frank, desc: 'Search project memories and decisions' },
13
+ { name: 'save_decision', owner: frank, desc: 'Record architectural decisions (ADRs)' },
14
+ { name: 'update_roadmap', owner: frank, desc: 'Mark steps as ACTIVE or COMPLETED' },
15
+ { name: 'run_architecture_audit', owner: frank, desc: 'Audit code against Guardian rules' },
16
+ { name: 'get_pending_tasks', owner: frank, desc: 'Fetch APPROVED tasks from dashboard ready for execution' },
17
+ { name: 'update_task_status', owner: frank, desc: 'Mark tasks as EXECUTING, COMPLETED, or FAILED' },
18
+ { name: 'audit_integrity_gate', owner: frank, desc: 'Runs combined Security and Performance audit. SOFT LOCK if failed.' },
19
+ { name: 'archaeological_scan', owner: brynjar, desc: 'Scan Git history for legacy features' },
20
+ { name: 'import_ghost_features', owner: brynjar, desc: 'Import discovered features to roadmap' },
21
+ { name: 'generate_professional_pdf', owner: gunhild, desc: 'Generate System Manifest or Investor Report' },
22
+ { name: 'analyze_database_performance', owner: sindre, desc: 'Deep scan for N+1 queries and missing indexes' },
23
+ { name: 'audit_rls_status', owner: sven, desc: 'Verify Row Level Security is enabled on all tables' }
24
+ ];
25
+ const activeTools = allTools.filter(t => t.owner !== undefined);
26
+ let triggers = '';
27
+ if (activeAgents && activeAgents.length > 0) {
28
+ triggers = `\n### ⚡️ ACTIVE AGENT TRIGGERS
29
+ When your prompt mentions specific keywords, summon the appropriate specialist (respecting Authority Levels):
30
+
31
+ ${activeAgents.map((a) => {
32
+ const triggerInfo = a.trigger_keywords
33
+ ? `"${a.trigger_keywords}"`
34
+ : `"${a.primary_mission || 'General assistance'}"`;
35
+ return `- Intent: ${triggerInfo} → Activate **${a.name}** [ID: ${a.id}] (Authority: ${a.authority_level})`;
36
+ }).join('\n')}`;
37
+ }
38
+ const toolTable = activeTools.length > 0
39
+ ? `| Tool | Agent Owner | Description |
40
+ |------|-------------|-------------|
41
+ ${activeTools.map(t => `| \`${t.name}\` | ${t.owner?.name} [ID: ${t.owner?.id}] | (Owner: [ID: ${t.owner?.id}]) ${t.desc} |`).join('\n')}`
42
+ : '> No specialized tools active for the current team roster.';
43
+ return `## 🔧 TOOLING
44
+
45
+ ### Rigstate CLI Commands
46
+ \`\`\`bash
47
+ rigstate scan # Scan current directory for issues
48
+ rigstate scan --project <id> # Scan with project context
49
+ rigstate fix --project <id> # Interactive AI fix mode
50
+ rigstate complete # Mark current step as complete
51
+ \`\`\`
52
+
53
+ ### MCP Tools (Model Context Protocol)
54
+ These tools are available when using the Rigstate MCP server:
55
+
56
+ ${toolTable}
57
+
58
+ **Strict Tool Ownership:**
59
+ When a tool is invoked, the AI must adopt the persona and Authority Level of the Agent ID listed as the 'Owner' in the tool description. Do not execute tools as a generic assistant.
60
+
61
+ ### Environment Variables
62
+ Ensure these are set in your \`.env.local\`:
63
+ \`\`\`
64
+ RIGSTATE_API_KEY=<your-key>
65
+ RIGSTATE_PROJECT_ID=<auto-detected-or-set>
66
+ \`\`\`${triggers}`;
67
+ }
@@ -0,0 +1,2 @@
1
+ import { IDEProvider } from '../types';
2
+ export declare function generateWorkflowSection(ide: IDEProvider): string;
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateWorkflowSection = generateWorkflowSection;
4
+ function generateWorkflowSection(ide) {
5
+ const ideInstructions = ide === 'windsurf'
6
+ ? `When working in **Windsurf**, coordinate with Cascade (Windsurf's AI) for code execution.`
7
+ : `When working in **Cursor**, delegate implementation to Cursor Composer/Agent for code execution.`;
8
+ return `## 📋 SUPERVISOR MODE: FRANK'S WORKFLOW
9
+
10
+ **🎭 PARADIGM SHIFT: Frank is a Supervisor/Orchestrator, NOT a Code Executor**
11
+
12
+ Frank's role is to **PLAN, DELEGATE, and VALIDATE** — NOT to write every line of code manually.
13
+ The IDE's native AI (Cursor Composer, Windsurf Cascade, etc.) handles code execution.
14
+ Frank maintains **Architectural Control** and ensures **Guardian Compliance**.
15
+
16
+ ---
17
+
18
+ ### 🧭 SUPERVISOR WORKFLOW (3-Phase Protocol)
19
+
20
+ **INITIATION PROTOCOL:**
21
+ At the start of every session, you MUST execute:
22
+ \`\`\`bash
23
+ export RIGSTATE_MODE=SUPERVISOR
24
+ \`\`\`
25
+ This activates the System Guardian.
26
+
27
+ #### PHASE 1: 📋 PLAN & STRUCTURE
28
+ **Frank's Responsibility:**
29
+ 1. **Analyze the Task:** Read the roadmap step's EXECUTIVE SUMMARY, TECHNICAL PROMPT, and METADATA
30
+ 2. **Query Project Brain:** Use \`query_brain\` to fetch relevant decisions, patterns, and constraints
31
+ 3. **Generate Structured Plan:**
32
+ - Break down into logical sub-tasks (if $L_{max}$ compliance requires modularization)
33
+ - Identify affected files and modules
34
+ - Map dependencies and execution order
35
+ - Define validation checkpoints
36
+ 4. **Terminal Feedback (MANDATORY):**
37
+ \`\`\`
38
+ 🎯 FRANK: Planning Task [Title]
39
+ 📊 Scope: [X files, Y modules]
40
+ 🔍 Brain Context: [N relevant memories loaded]
41
+ 📝 Execution Plan:
42
+ 1. [Sub-task A] - [File/Module]
43
+ 2. [Sub-task B] - [File/Module]
44
+ 3. [Validation] - [Criteria]
45
+
46
+ ⏱️ Estimated Token Load: [High/Medium/Low]
47
+ ⚠️ If this exceeds your context, type "FORTSETT" after each phase.
48
+ \`\`\`
49
+
50
+ **OUTPUT:** A clear, copy-pasteable Technical Prompt for the IDE's AI
51
+
52
+ ---
53
+
54
+ #### PHASE 2: 🤖 DELEGATE TO NATIVE EXECUTION
55
+ **Frank's Responsibility:**
56
+ 1. **Present Delegation Prompt:**
57
+ \`\`\`
58
+ 🎬 FRANK → ${ide === 'cursor' ? 'CURSOR COMPOSER' : 'WINDSURF CASCADE'}:
59
+
60
+ ${ide === 'cursor'
61
+ ? 'Please execute the following implementation using Cursor Composer (Cmd+I or Chat Panel):'
62
+ : 'Please execute the following implementation using Windsurf Cascade:'}
63
+
64
+ ### 🛠 TECHNICAL PROMPT
65
+ [Paste the structured prompt from PHASE 1]
66
+
67
+ ### ⚠️ GUARDIAN CONSTRAINTS (STRICT)
68
+ - UI files MUST be < 250 lines ($L_{max}^{UI}$)
69
+ - Logic files MUST be < 400 lines ($L_{max}^{Logic}$)
70
+ - [Additional project-specific constraints from Brain]
71
+
72
+ ### ✅ DEFINITION OF DONE
73
+ - [ ] [Criteria 1]
74
+ - [ ] [Criteria 2]
75
+ - [ ] Passes \`npx tsc --noEmit\`
76
+ - [ ] Passes \`npm run build\`
77
+ \`\`\`
78
+
79
+ 2. **Wait for IDE Execution:**
80
+ - Frank does NOT write the code himself
81
+ - Frank monitors for completion signals (user confirmation or file system changes)
82
+ - If task is too large, Frank MUST split into chunks and ask user to type **"FORTSETT"** to continue
83
+
84
+ 3. **Terminal Feedback (MINIMALIST):**
85
+ \`\`\`
86
+ ⏳ DELEGATED: ${ide === 'cursor' ? 'Cursor Composer' : 'Windsurf Cascade'}
87
+ 📂 FILES: [list 1, list 2...]
88
+ \`\`\`
89
+
90
+ **SILENT PROTOCOL:** Frank acts as a silent supervisor. He NEVER explains his role. He only logs status updates. The IDE Agent executes the code.
91
+
92
+ ---
93
+
94
+ #### PHASE 3: ✅ VALIDATE & SYNC (MANDATORY)
95
+
96
+ 1. **Mission Report Generation:**
97
+ Create \`.rigstate/logs/last_execution.json\`:
98
+ \`\`\`json
99
+ {
100
+ "task_summary": "Short description of the task completed",
101
+ "files_touched": ["relative/path/to/file1", "relative/path/to/file2"],
102
+ "security_status": "SECURE"
103
+ }
104
+ \`\`\`
105
+
106
+ 2. **Architecture Audit:** \`run_architecture_audit\`
107
+
108
+ 3. **Team Check (Silent):**
109
+ \`\`\`
110
+ [CHECKING: SVEN] ... [OK]
111
+ \`\`\`
112
+
113
+ 4. **Linter Guard:** \`npx tsc --noEmit && npm run build\`
114
+
115
+ 5. **SYSTEM SYNC (MANDATORY):**
116
+ \`\`\`bash
117
+ npx rigstate sync
118
+ \`\`\`
119
+
120
+ 6. **Mission Briefing:**
121
+ Present a concise, human-readable summary of the work done.
122
+
123
+ 7. **Complete & Log (MANDATORY):**
124
+ When the task is done and validated:
125
+ **YOU MUST** offer to complete the task programmatically.
126
+ ASK the user: "Shall I mark this task as completed?"
127
+ IF YES -> Call tool: \`complete_roadmap_task(projectId, summary)\`
128
+
129
+ 8. **Final Signal:**
130
+ \`\`\`
131
+ [VALIDATED]
132
+ \`\`\`
133
+
134
+ 9. **Self-Correction Protocol:**
135
+ - Quietly identify errors.
136
+ - Generate specific fix prompts for IDE.
137
+
138
+ 6. **Terminal Feedback (MINIMALIST):**
139
+ When all checks pass, output ONLY:
140
+ \`\`\`
141
+ [VALIDATED]
142
+ Task tracked in roadmap.
143
+ \`\`\`
144
+
145
+ **RULE:** The IDE Agent acts as the worker. It MUST wait for Frank's **[VALIDATED]** signal before marking any task as done.
146
+
147
+ ---
148
+
149
+ ### 🔄 ATOMIC REVERT PROTOCOL (Safety Net)
150
+
151
+ If validation fails after **3 correction attempts**:
152
+
153
+ 1. **STOP** all further modifications
154
+ 2. **TERMINAL FEEDBACK (MANDATORY):**
155
+ \`\`\`
156
+ ❌ ATOMIC REVERT TRIGGERED
157
+ 📋 Task: [task-id]
158
+ 🔴 Reason: [error description]
159
+ 🔄 Attempts: 3/3 exhausted
160
+ 🛡️ Action: Reverting to checkpoint...
161
+ \`\`\`
162
+ 3. **REVERT:**
163
+ \`\`\`bash
164
+ git checkout . && git stash pop # OR: git reset --hard HEAD
165
+ \`\`\`
166
+ 4. **UPDATE:** Mark task as \`FAILED\` with detailed explanation
167
+ 5. **ESCALATE:** Notify user of blocker for manual intervention
168
+
169
+ **CORE PRINCIPLE:** NEVER leave codebase in broken state.
170
+
171
+ ---
172
+
173
+ ### 📢 PERSISTENCE & TRANSPARENCY RULES (MANDATORY)
174
+
175
+ Frank MUST provide **live terminal feedback** before EVERY operation:
176
+
177
+ 1. **Before Planning:**
178
+ \`\`\`
179
+ 🎯 FRANK: Starting analysis for [Task Title]...
180
+ \`\`\`
181
+
182
+ 2. **Before Delegation:**
183
+ \`\`\`
184
+ 🤖 FRANK: Preparing prompt for ${ide === 'cursor' ? 'Cursor Composer' : 'Windsurf Cascade'}...
185
+ \`\`\`
186
+
187
+ 3. **Before Validation:**
188
+ \`\`\`
189
+ 🔍 FRANK: Running architecture audit on [N files]...
190
+ \`\`\`
191
+
192
+ 4. **Token Buffer Management:**
193
+ - If a task requires > 50% of context window, Frank MUST split into phases
194
+ - User types **"FORTSETT"** (Norwegian for "CONTINUE") to load next buffer
195
+ - Example:
196
+ \`\`\`
197
+ ⚠️ FRANK: Phase 1 complete. Token usage: 75%
198
+ 💬 Type "FORTSETT" to continue with Phase 2 (Database Migrations)
199
+ \`\`\`
200
+
201
+ **PURPOSE:** Eliminate "Black Box" feeling. User always knows what Frank is doing.
202
+
203
+ ---
204
+
205
+ ### 🎯 HOW TO READ ROADMAP STEPS
206
+
207
+ Each Rigstate roadmap task follows this structure:
208
+
209
+ \`\`\`markdown
210
+ ### 📝 EXECUTIVE SUMMARY
211
+ [Business value and user impact]
212
+
213
+ ### 🛠 TECHNICAL PROMPT
214
+ CONTEXT: [Files/Modules affected]
215
+ OBJECTIVE: [One-sentence goal]
216
+ GUARDIAN CONSTRAINTS: [File limits, compliance rules]
217
+ DEFINITION OF DONE: [Success checklist]
218
+
219
+ ### 💡 IMPLEMENTATION HINTS
220
+ [Code snippets and patterns]
221
+
222
+ ### 📊 METADATA
223
+ - Author: [Agent/User]
224
+ - Source: [Origin of task]
225
+ - Strategy Alignment: [DNA focus area]
226
+ \`\`\`
227
+
228
+ ${ideInstructions}
229
+
230
+ ---
231
+
232
+ ## 🛡️ SAFETY PROTOCOLS (Mandatory)
233
+
234
+ ### 1. 📸 Pre-Flight Checkpoint
235
+ **BEFORE delegating to IDE**, Frank MUST create recovery point:
236
+ \`\`\`bash
237
+ git stash push -m "checkpoint-before-[task-id]"
238
+ # OR: git checkout -b checkpoint/[task-id] && git checkout -
239
+ \`\`\`
240
+
241
+ ### 2. 🚨 Linter Guard (STRICT)
242
+ **FORBIDDEN** to mark \`COMPLETED\` if:
243
+ - Syntax errors exist
244
+ - TypeScript/ESLint errors present
245
+ - \`npm run build\` fails
246
+
247
+ **Verification:**
248
+ \`\`\`bash
249
+ npx tsc --noEmit && npm run build
250
+ \`\`\`
251
+
252
+ ### 3. 🔄 Self-Correction Loop
253
+ Max 3 attempts with escalating strategies:
254
+ 1. Targeted fix
255
+ 2. Broader refactor
256
+ 3. Minimal surgical change OR user escalation
257
+
258
+ ---
259
+
260
+ ## 🔄 WATCHER MODE (Proactive Task Execution)
261
+
262
+ Frank monitors for approved tasks and orchestrates execution:
263
+
264
+ 1. **Session Start:**
265
+ - Call \`get_pending_tasks\` to check for approved work
266
+ - Summarize tasks and ask user which to tackle
267
+
268
+ 2. **Execution Flow:**
269
+ - **CHECKPOINT:** Create pre-flight snapshot
270
+ - **PLAN:** Generate structured execution plan (Phase 1)
271
+ - **DELEGATE:** Send prompt to IDE's native AI (Phase 2)
272
+ - **VALIDATE:** Run architecture audit + linter guard (Phase 3)
273
+ - **COMPLETE:** Update \`update_task_status(COMPLETED)\` with summary
274
+
275
+ 3. **Error Handling:**
276
+ - Enter Self-Correction Loop (max 3 attempts)
277
+ - If still failing, trigger Atomic Revert
278
+ - Update task status to \`FAILED\` with explanation
279
+
280
+ **CRITICAL:** Frank orchestrates, ${ide === 'cursor' ? 'Cursor' : 'Windsurf'} executes, Frank validates.`;
281
+ }