From 32a4b077e2da16d0ac7ef00b5473896b20878fe7 Mon Sep 17 00:00:00 2001 From: Danny Stocker Date: Thu, 13 Nov 2025 13:17:57 +0100 Subject: [PATCH] [CLOUD PROMPTS] Add builder/prompts directory with all session instructions - current/: Active feature development (smart-ocr, multiformat) - implementation/: MVP feature builds (photo, search, timeline, polish, testing) - research/: Strategy sessions (market, technical, UX, planning, validation) - README.md: Session launch protocol and status dashboard All prompts now accessible via GitHub for cloud sessions on separate machines. --- builder/prompts/README.md | 213 +++ .../prompts/current/session-1-smart-ocr.md | 238 +++ .../prompts/current/session-2-multiformat.md | 276 ++++ .../CLOUD_SESSION_PROMPT_1_PHOTO_INVENTORY.md | 137 ++ .../CLOUD_SESSION_PROMPT_2_DOCUMENT_SEARCH.md | 164 ++ ...D_SESSION_PROMPT_3_MAINTENANCE_TIMELINE.md | 193 +++ .../CLOUD_SESSION_PROMPT_4_DEMO_POLISH.md | 224 +++ ...UD_SESSION_PROMPT_5_INTEGRATION_TESTING.md | 316 ++++ .../research/session-1-market-research.md | 451 ++++++ .../session-2-technical-integration.md | 814 ++++++++++ .../prompts/research/session-3-ux-sales.md | 601 +++++++ .../session-4-implementation-planning.md | 1431 +++++++++++++++++ .../session-5-synthesis-validation.md | 1250 ++++++++++++++ 13 files changed, 6308 insertions(+) create mode 100644 builder/prompts/README.md create mode 100644 builder/prompts/current/session-1-smart-ocr.md create mode 100644 builder/prompts/current/session-2-multiformat.md create mode 100644 builder/prompts/implementation/CLOUD_SESSION_PROMPT_1_PHOTO_INVENTORY.md create mode 100644 builder/prompts/implementation/CLOUD_SESSION_PROMPT_2_DOCUMENT_SEARCH.md create mode 100644 builder/prompts/implementation/CLOUD_SESSION_PROMPT_3_MAINTENANCE_TIMELINE.md create mode 100644 builder/prompts/implementation/CLOUD_SESSION_PROMPT_4_DEMO_POLISH.md create mode 100644 builder/prompts/implementation/CLOUD_SESSION_PROMPT_5_INTEGRATION_TESTING.md create mode 100644 builder/prompts/research/session-1-market-research.md create mode 100644 builder/prompts/research/session-2-technical-integration.md create mode 100644 builder/prompts/research/session-3-ux-sales.md create mode 100644 builder/prompts/research/session-4-implementation-planning.md create mode 100644 builder/prompts/research/session-5-synthesis-validation.md diff --git a/builder/prompts/README.md b/builder/prompts/README.md new file mode 100644 index 0000000..fa9dea2 --- /dev/null +++ b/builder/prompts/README.md @@ -0,0 +1,213 @@ +# NaviDocs Cloud Session Prompts + +**Created:** 2025-11-13 +**Purpose:** Centralized prompt library for cloud-based development sessions +**Access:** https://github.com/dannystocker/navidocs/tree/navidocs-cloud-coordination/builder/prompts + +--- + +## Directory Structure + +``` +builder/prompts/ +├── README.md (this file) +├── current/ # Active feature development (PRIORITY) +├── implementation/ # MVP feature builds +└── research/ # Strategy and planning sessions +``` + +--- + +## 🚀 Current Sessions (Start Here!) + +**Location:** `builder/prompts/current/` + +These are the **ACTIVE** sessions for the v0.5 → v1.0 feature roadmap: + +### Session 1: Smart OCR Optimization +**File:** `current/session-1-smart-ocr.md` +**Branch:** `feature/smart-ocr` +**Duration:** 60 minutes +**Priority:** P0 (36x performance improvement) + +**Goal:** Extract native PDF text first, only OCR scanned pages +**Performance:** 180s → 5s for text-heavy PDFs +**Dependencies:** `npm install pdfjs-dist` + +**Quick Start:** +```bash +git checkout -b feature/smart-ocr +# Follow prompt instructions +``` + +--- + +### Session 2: Multi-Format Upload +**File:** `current/session-2-multiformat.md` +**Branch:** `feature/multiformat` +**Duration:** 90 minutes +**Priority:** P1 (Feature expansion) + +**Goal:** Support JPG, PNG, DOCX, XLSX, TXT, MD uploads +**Dependencies:** `npm install mammoth xlsx` + +**Quick Start:** +```bash +git checkout -b feature/multiformat +# Follow prompt instructions +``` + +--- + +### Session 3: Timeline Feature (TBD) +**File:** `current/session-3-timeline.md` +**Branch:** `feature/timeline` +**Duration:** 2 hours (backend + frontend) +**Priority:** P1 (Core demo feature) + +**Goal:** Organization activity timeline (uploads, maintenance, events) +**Spec:** `/home/setup/navidocs/FEATURE_SPEC_TIMELINE.md` + +--- + +## 📦 Implementation Sessions + +**Location:** `builder/prompts/implementation/` + +These prompts build **MVP features** for the Riviera Plaisance demo: + +1. **Photo Inventory** - Boat photo upload with tag filtering +2. **Document Search** - Smart classifier + ranking +3. **Maintenance Timeline** - Service alerts + history +4. **Demo Polish** - UI/UX optimization +5. **Integration Testing** - Quality gate + sign-off + +**Use Case:** Sequential deployment for demo readiness (7.5 hours total) + +**Index File:** See `CLOUD_PROMPTS_INDEX.md` for full details + +--- + +## 🔬 Research Sessions + +**Location:** `builder/prompts/research/` + +These prompts perform **deep analysis** and **strategic planning**: + +1. **Market Research** - Competitive intelligence + TAM/SAM +2. **Technical Integration** - Architecture + API design +3. **UX + Sales Enablement** - Pitch deck + ROI calculator +4. **Implementation Planning** - 4-week sprint breakdown +5. **Synthesis + Validation** - Guardian review + dossier + +**Use Case:** Strategic planning before feature builds + +--- + +## 🔄 Polling for Updates + +Cloud sessions should poll this directory for updated instructions: + +```bash +# Check for new prompts or updates every 15 minutes +git fetch origin +git diff origin/navidocs-cloud-coordination -- builder/prompts/ +``` + +**Update Notifications:** +- New files indicate new sessions available +- Modified files indicate updated instructions +- Check `README.md` for announcements + +--- + +## 📋 Session Launch Protocol + +### For Cloud Session Operators: + +1. **Read the prompt file** - Understand mission + success criteria +2. **Create feature branch** - Use naming convention: `feature/[name]` +3. **Follow implementation steps** - Code, test, document +4. **Commit with tag** - Use `[SESSION-N]` prefix +5. **Report completion** - Create `SESSION-N-COMPLETE.md` summary +6. **Push to GitHub** - `git push origin feature/[name]` + +### Communication: +- Progress updates every 30 minutes +- Blockers escalated within 15 minutes +- Completion report required before next session + +--- + +## 🎯 Success Criteria + +Each prompt includes specific success criteria. General requirements: + +- ✅ All code committed to feature branch +- ✅ Tests passing (if applicable) +- ✅ No regressions in existing functionality +- ✅ Documentation updated +- ✅ Session completion report created + +--- + +## 🚨 If Blocked + +**Check these resources:** +1. `/home/setup/navidocs/SESSION_DEBUG_BLOCKERS.md` - Known issues +2. `/home/setup/navidocs/ARCHITECTURE-SUMMARY.md` - System overview +3. GitHub Issues - Open issue with `[BLOCKER]` tag + +**Escalation Path:** +1. Try 2 workarounds first (15 min max) +2. Document blocker clearly +3. Signal for help via GitHub Issue or session report + +--- + +## 📊 Status Dashboard + +| Session | Status | Branch | Completion | +|---------|--------|--------|------------| +| Session 1: Smart OCR | ⏳ Ready | `feature/smart-ocr` | 0% | +| Session 2: Multi-format | ⏳ Ready | `feature/multiformat` | 0% | +| Session 3: Timeline | 📝 Planning | `feature/timeline` | 0% | +| Session 4: TBD | 💤 Pending | - | 0% | +| Session 5: TBD | 💤 Pending | - | 0% | + +**Last Updated:** 2025-11-13 13:05 UTC +**Next Review:** After Session 1 completion + +--- + +## 🔗 Key Links + +- **GitHub Repo:** https://github.com/dannystocker/navidocs +- **Working Branch:** `navidocs-cloud-coordination` +- **Demo Tag:** `v0.5-demo-ready` +- **Local Dev:** `/home/setup/navidocs` + +**API Endpoints:** +- Backend: http://localhost:8001 +- Frontend: http://localhost:8081 +- Meilisearch: http://localhost:7700 + +**Test Credentials:** +- User: test2@navidocs.test +- Pass: TestPassword123 +- Org ID: 6ce0dfc7-f754-4122-afde-85154bc4d0ae + +--- + +## 📝 Version History + +| Date | Change | Commit | +|------|--------|--------| +| 2025-11-13 | Initial prompts directory created | TBD | +| 2025-11-13 | Added current/ implementation/ research/ structure | TBD | + +--- + +**Welcome to NaviDocs builder system! 🚢** + +Start with `current/session-1-smart-ocr.md` for immediate impact. diff --git a/builder/prompts/current/session-1-smart-ocr.md b/builder/prompts/current/session-1-smart-ocr.md new file mode 100644 index 0000000..77c6187 --- /dev/null +++ b/builder/prompts/current/session-1-smart-ocr.md @@ -0,0 +1,238 @@ +# Welcome Cloud Session 1: Smart OCR Engineer + +**Your Role:** OCR Optimization Specialist +**Your Machine:** Browser-based Claude Code Cloud (claude.ai) +**Session ID:** session-1 +**Coordination:** Hub-and-spoke (report to local Sonnet orchestrator) +**Communication:** SSH file sync to StackCP server + +--- + +## Quick Start (Copy-Paste This) + +Hi Claude! You're **Session 1** in a 5-session cloud deployment for NaviDocs. Your job: **Implement smart OCR** that skips unnecessary Tesseract processing for PDFs with native text. + +### Context + +**Project:** NaviDocs - Boat documentation management system +**Tech Stack:** Node.js (Express) + Vue 3 + SQLite + Meilisearch +**Current Problem:** 100-page PDF with native text takes 3+ minutes to OCR (should be 5 seconds) +**Your Fix:** Add pdfjs-dist to extract native text first, only OCR scanned pages +**Performance Goal:** 36x speed improvement (180s → 5s) + +**GitHub Repo:** https://github.com/dannystocker/navidocs +**Branch:** navidocs-cloud-coordination (v0.5-demo-ready tag) +**Your Feature Branch:** feature/smart-ocr + +--- + +## Your Task Specification + +### Files to Create/Modify + +1. **server/services/pdf-text-extractor.js** (NEW) + - Function: `extractNativeTextPerPage(pdfPath)` + - Function: `hasNativeText(pdfPath, minChars = 100)` + - Uses: `pdfjs-dist` library + +2. **server/services/ocr.js** (MODIFY lines 36-96) + - Add import: `pdf-text-extractor.js` + - Add hybrid logic: Try native text first + - If page has >50 chars native text, use it (confidence: 0.99) + - If page has <50 chars, run Tesseract OCR + - Add method field: `'native-extraction'` or `'tesseract-ocr'` + +3. **server/.env** (ADD) + ```env + OCR_MIN_TEXT_THRESHOLD=50 + FORCE_OCR_ALL_PAGES=false + ``` + +### Dependencies to Install +```bash +npm install pdfjs-dist +``` + +### Testing Strategy +```bash +# Test with reprocess script (should complete in ~5 seconds) +node server/scripts/reprocess-liliane.js + +# Verify logs show: +# "[OCR Optimization] PDF has native text, extracting without OCR..." +# "[Native Text] Page 1/100 (2845 chars)" +``` + +--- + +## Code Example: pdf-text-extractor.js + +```javascript +/** + * Native PDF Text Extraction using pdfjs-dist + * Extracts text directly from PDF without OCR + */ +import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs'; +import { readFileSync } from 'fs'; + +export async function extractNativeTextPerPage(pdfPath) { + const data = new Uint8Array(readFileSync(pdfPath)); + const pdf = await pdfjsLib.getDocument({ data }).promise; + + const pageTexts = []; + const pageCount = pdf.numPages; + + for (let pageNum = 1; pageNum <= pageCount; pageNum++) { + const page = await pdf.getPage(pageNum); + const textContent = await page.getTextContent(); + const pageText = textContent.items.map(item => item.str).join(' '); + pageTexts.push(pageText.trim()); + } + + return pageTexts; +} + +export async function hasNativeText(pdfPath, minChars = 100) { + try { + const pageTexts = await extractNativeTextPerPage(pdfPath); + const totalText = pageTexts.join(''); + return totalText.length >= minChars; + } catch (error) { + console.error('Error checking native text:', error); + return false; + } +} +``` + +--- + +## Communication Protocol + +You're working **independently** but reporting to orchestrator via chat system. + +**When you start work:** +```bash +# Signal you're active (use StackCP SSH access) +# Note: This is conceptual - actual implementation TBD based on your environment +echo "SESSION-1 STARTED: Smart OCR implementation" > status.txt +``` + +**Progress updates (every 30 min):** +- Report completion percentage +- Note any blockers +- Share preliminary test results + +**When complete:** +```bash +# Report success +git commit -m "[Session 1] Smart OCR implemented - 36x performance gain" +git push origin feature/smart-ocr + +# Create summary +cat > SESSION-1-COMPLETE.md <15 minutes, signal for help + +--- + +## Success Criteria + +- [ ] `pdfjs-dist` installed successfully +- [ ] `pdf-text-extractor.js` created with 2 functions +- [ ] `ocr.js` modified with hybrid logic +- [ ] Test document processes in <10 seconds (down from 180s) +- [ ] Scanned PDFs still work correctly +- [ ] Code committed to feature branch +- [ ] Unit tests pass (if applicable) +- [ ] No regressions in existing OCR functionality + +--- + +## Environment Setup + +**If you don't have NaviDocs cloned:** +```bash +git clone https://github.com/dannystocker/navidocs.git +cd navidocs +git checkout navidocs-cloud-coordination +git pull origin navidocs-cloud-coordination +git checkout -b feature/smart-ocr + +# Install dependencies +cd server +npm install +npm install pdfjs-dist + +# Set up environment +cp .env.example .env +``` + +**Test data location:** +- Liliane1 manual: `/home/setup/navidocs/uploads/efb25a15-7d84-4bc3-b070-6bd7dec8d59a.pdf` +- Test user: `test2@navidocs.test` / `TestPassword123` +- Organization: `6ce0dfc7-f754-4122-afde-85154bc4d0ae` + +--- + +## Key Files to Read First + +1. `server/services/ocr.js` (existing OCR logic) +2. `server/workers/ocr-worker.js` (how OCR is called) +3. `IMPROVEMENT_PLAN_OCR_AND_UPLOADS.md` (full spec) +4. `server/scripts/reprocess-liliane.js` (test script) + +--- + +## Timeline + +- **T+0 min:** Read this prompt, clone repo, read existing code +- **T+15 min:** Create pdf-text-extractor.js +- **T+30 min:** Modify ocr.js with hybrid logic +- **T+45 min:** Test with Liliane1 PDF +- **T+60 min:** Verify scanned PDFs still work, commit, report complete + +--- + +## Dependencies on Other Sessions + +**None - you can start immediately!** +Sessions 2-5 are working in parallel on different features. + +--- + +## Questions? + +Read the code first, then: +1. Check `IMPROVEMENT_PLAN_OCR_AND_UPLOADS.md` for detailed spec +2. Review existing `ocr.js` to understand current flow +3. Test incrementally (don't wait until the end) +4. Commit early, commit often + +--- + +**You're autonomous! Start as soon as you're ready. Good luck, Session 1! 🚀** + +**Claude Code URL:** https://claude.com/claude-code +**Repo:** https://github.com/dannystocker/navidocs +**Your Branch:** feature/smart-ocr diff --git a/builder/prompts/current/session-2-multiformat.md b/builder/prompts/current/session-2-multiformat.md new file mode 100644 index 0000000..42a52d7 --- /dev/null +++ b/builder/prompts/current/session-2-multiformat.md @@ -0,0 +1,276 @@ +# Cloud Session 2: Multi-Format Upload Support + +**Session ID:** session-2 +**Role:** File Processing Engineer +**Priority:** P1 (Feature expansion) +**Estimated Time:** 90 minutes +**Dependencies:** None (parallel with Session 1) + +--- + +## Your Mission + +Enable NaviDocs to accept JPG, PNG, DOCX, XLSX, TXT, MD files in addition to PDFs. + +**Current Limitation:** +- Only `.pdf` files accepted +- `file-safety.js` hardcoded to PDF-only +- No image, Office, or text document support + +**Expected Outcome:** +- Upload images directly (JPG, PNG, WebP) +- Upload Word documents (DOCX) with text extraction +- Upload Excel spreadsheets (XLSX) with data extraction +- Upload plain text/markdown (TXT, MD) + +--- + +## Implementation Steps + +### Step 1: Install Dependencies (5 min) +```bash +cd /home/setup/navidocs/server +npm install mammoth xlsx +``` + +### Step 2: Update File Validation (15 min) + +**File:** `server/services/file-safety.js` + +```javascript +const ALLOWED_EXTENSIONS = [ + // Documents + '.pdf', + '.doc', '.docx', + '.xls', '.xlsx', + '.txt', '.md', + // Images + '.jpg', '.jpeg', '.png', '.webp' +]; + +const ALLOWED_MIME_TYPES = [ + 'application/pdf', + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'text/plain', + 'text/markdown', + 'image/jpeg', + 'image/png', + 'image/webp' +]; + +export function getFileCategory(filename) { + const ext = path.extname(filename).toLowerCase(); + + if (['.pdf'].includes(ext)) return 'pdf'; + if (['.doc', '.docx'].includes(ext)) return 'word'; + if (['.xls', '.xlsx'].includes(ext)) return 'excel'; + if (['.txt', '.md'].includes(ext)) return 'text'; + if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) return 'image'; + + return 'unknown'; +} +``` + +### Step 3: Create Document Processor Router (40 min) + +**File:** `server/services/document-processor.js` (NEW) + +```javascript +import { extractTextFromPDF } from './ocr.js'; +import { extractTextFromImage } from './ocr.js'; +import { getFileCategory } from './file-safety.js'; +import { readFileSync } from 'fs'; +import mammoth from 'mammoth'; +import XLSX from 'xlsx'; + +export async function processDocument(filePath, options = {}) { + const category = getFileCategory(filePath); + + console.log(`[Document Processor] Processing ${category}: ${filePath}`); + + switch (category) { + case 'pdf': + return await extractTextFromPDF(filePath, options); + + case 'image': + return await processImageFile(filePath, options); + + case 'word': + return await processWordDocument(filePath, options); + + case 'excel': + return await processExcelDocument(filePath, options); + + case 'text': + return await processTextFile(filePath, options); + + default: + throw new Error(`Unsupported file type: ${category}`); + } +} + +async function processImageFile(imagePath, options = {}) { + const { language = 'eng' } = options; + + console.log('[Image Processor] Running OCR...'); + const ocrResult = await extractTextFromImage(imagePath, language); + + return [{ + pageNumber: 1, + text: ocrResult.text, + confidence: ocrResult.confidence, + method: 'tesseract-ocr' + }]; +} + +async function processWordDocument(docPath, options = {}) { + console.log('[Word Processor] Extracting text from DOCX...'); + + const result = await mammoth.extractRawText({ path: docPath }); + const text = result.value; + + return [{ + pageNumber: 1, + text: text, + confidence: 0.99, + method: 'native-extraction' + }]; +} + +async function processExcelDocument(xlsPath, options = {}) { + console.log('[Excel Processor] Reading workbook...'); + + const workbook = XLSX.readFile(xlsPath); + const sheets = []; + + workbook.SheetNames.forEach((sheetName, idx) => { + const worksheet = workbook.Sheets[sheetName]; + const text = XLSX.utils.sheet_to_csv(worksheet); + + sheets.push({ + pageNumber: idx + 1, + text: text, + confidence: 0.99, + method: 'native-extraction', + sheetName: sheetName + }); + }); + + console.log(`[Excel Processor] Extracted ${sheets.length} sheets`); + return sheets; +} + +async function processTextFile(txtPath, options = {}) { + const text = readFileSync(txtPath, 'utf-8'); + + return [{ + pageNumber: 1, + text: text, + confidence: 1.0, + method: 'native-extraction' + }]; +} +``` + +### Step 4: Update OCR Worker (10 min) + +**File:** `server/workers/ocr-worker.js` (line 96) + +```javascript +// OLD: +const ocrResults = await extractTextFromPDF(filePath, { + language: document.language || 'eng', + onProgress: updateProgress +}); + +// NEW: +import { processDocument } from '../services/document-processor.js'; + +const ocrResults = await processDocument(filePath, { + language: document.language || 'eng', + onProgress: updateProgress +}); +``` + +### Step 5: Update Frontend Upload Form (20 min) + +**File:** `client/src/components/UploadForm.vue` + +```vue + + +
+ Supported: PDF, Images (JPG/PNG), Word, Excel, Text/Markdown +
+``` + +### Step 6: Test Each File Type (20 min) + +```bash +# Test image upload +curl -X POST http://localhost:8001/api/upload \ + -H "Authorization: Bearer $TOKEN" \ + -F "file=@test-photo.jpg" \ + -F "title=Boat Engine Photo" \ + -F "documentType=photo" \ + -F "organizationId=$ORG_ID" + +# Test Word document +curl -X POST http://localhost:8001/api/upload \ + -F "file=@service-report.docx" \ + -F "title=2024 Service Report" \ + -F "documentType=service-record" \ + -F "organizationId=$ORG_ID" + +# Test Excel +curl -X POST http://localhost:8001/api/upload \ + -F "file=@parts-inventory.xlsx" \ + -F "title=Parts Inventory 2024" \ + -F "documentType=inventory" \ + -F "organizationId=$ORG_ID" + +# Test text file +curl -X POST http://localhost:8001/api/upload \ + -F "file=@maintenance-notes.txt" \ + -F "title=Maintenance Notes" \ + -F "documentType=notes" \ + -F "organizationId=$ORG_ID" +``` + +--- + +## Success Criteria + +- [ ] `mammoth` and `xlsx` installed +- [ ] `file-safety.js` updated with all file types +- [ ] `document-processor.js` created with routing logic +- [ ] `ocr-worker.js` updated to use processor +- [ ] Frontend accepts multiple file types +- [ ] All file types upload and index successfully +- [ ] Search works across all document types + +--- + +## Reporting + +```bash +/tmp/send-to-cloud.sh 2 "COMPLETE: Multi-Format Upload" " +✅ Multi-format upload implemented +- Supported: PDF, JPG, PNG, DOCX, XLSX, TXT, MD +- All processors tested and working +- Search indexes all file types +- Frontend updated +- 5 test uploads successful +" +``` + +--- + +**Start immediately - independent of Session 1.** diff --git a/builder/prompts/implementation/CLOUD_SESSION_PROMPT_1_PHOTO_INVENTORY.md b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_1_PHOTO_INVENTORY.md new file mode 100644 index 0000000..5b57439 --- /dev/null +++ b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_1_PHOTO_INVENTORY.md @@ -0,0 +1,137 @@ +# Cloud Session 1: Photo Inventory System + +**Session ID:** CLOUD-1-PHOTO-INVENTORY +**Timeline:** 90 minutes +**Deadline:** 4 hours from now (Riviera Plaisance presentation) +**Target:** Build boat photo gallery + inventory tagging system + +--- + +## Your Mission + +Add sticky daily-use photo management to NaviDocs MVP. Boat owners should be able to: +- Upload boat photos (exterior, interior, systems) +- Tag photos by system (engine, electrical, hull, interior) +- Search photos by tag +- View inventory checklist with photo evidence +- Export photo inventory for insurance/resale documentation + +This solves the **"€15K-€50K forgotten value" problem** - owners can't remember what upgrades they have until resale. + +--- + +## Quick Start + +1. **Clone repo:** + ```bash + git clone https://github.com/dannystocker/navidocs.git && cd navidocs + ``` + +2. **Read your brief:** + ```bash + cat /home/setup/navidocs/CLOUD_SESSION_1_MARKET_RESEARCH.md | head -80 + ``` + +3. **Check current blockers:** + ```bash + cat /home/setup/navidocs/SESSION_DEBUG_BLOCKERS.md + ``` + +4. **Review codebase structure:** + - **Frontend:** `/src/app/` (Next.js 14 with App Router) + - **API:** `/src/api/` (Prisma + Meilisearch) + - **Database:** `schema.prisma` (13 tables, photos table ready) + - **Components:** `/src/components/` (Tailwind + shadcn/ui) + +--- + +## Your Task List + +- [ ] **Design:** Photo upload UI component (drag-drop, multi-select) +- [ ] **Database:** Extend `PhotoInventory` table with tags (engine, electrical, hull, interior, etc.) +- [ ] **API:** Create 3 endpoints: + - `POST /api/photos/upload` - Store with system tags + - `GET /api/photos/by-tag/:tag` - Filter by system type + - `GET /api/photos/inventory-list` - Full inventory with photo count +- [ ] **Frontend:** Photo gallery grid component with tag filtering +- [ ] **Search Integration:** Add photo metadata to Meilisearch index +- [ ] **Git commit:** `[AGENT-1] Add photo inventory system with tag filtering` +- [ ] **Create issue:** `[AGENT-1] DEPLOY-READY: Photo Inventory System` with: + - Screenshots of photo upload & gallery + - API test results + - Estimated storage impact + - Deployment steps for StackCP + +--- + +## Technical Context + +**Stack:** +- Frontend: Next.js 14 (App Router) +- API: Node.js + Prisma ORM +- Database: PostgreSQL (17 tables) +- Search: Meilisearch (already integrated) +- Storage: StackCP filesystem (`/public/uploads/photos/`) +- UI: Tailwind CSS + shadcn/ui components + +**Key Files to Modify:** +- `prisma/schema.prisma` - Add photo tags +- `src/app/api/photos/route.ts` - Create upload endpoints +- `src/components/PhotoGallery.tsx` - Create gallery UI +- `src/app/inventory/photos/page.tsx` - Photo inventory page + +**Design Specs:** +- Photo upload max: 5MB per image (JPEG/PNG) +- Supported tags: engine, electrical, hull, interior, deck, safety, upgrade, other +- Gallery: 3-column grid (desktop), 2-column (tablet), 1-column (mobile) +- Tag filter: Multi-select with counts (e.g., "Engine (12)") + +--- + +## Critical Notes + +1. **Demo Focus:** Owners see boat photos + auto-populated inventory list with photo evidence +2. **Sticky Engagement:** "Check boat photos while away" = daily app habit +3. **Insurance Value:** Photo timestamped inventory = proof of ownership/upgrades +4. **Resale Value:** Export photo manifest to potential buyers +5. **Must work offline:** Photos should load from cache for remote boats + +--- + +## GitHub Access + +- **Repo:** https://github.com/dannystocker/navidocs +- **Branch:** `feature/photo-inventory` (create from main) +- **Base for PR:** main branch +- **Code review:** Not required (direct commit to feature branch) + +--- + +## Success Criteria + +✅ Photo upload working (multi-select, drag-drop) +✅ Photos visible in gallery with tags +✅ Search filters by tag return correct results +✅ API endpoints return correct JSON +✅ No console errors in browser/server +✅ Component responsive on mobile/tablet/desktop +✅ Git commit with [AGENT-1] tag + +--- + +## If Blocked + +1. Check `/home/setup/navidocs/SESSION_DEBUG_BLOCKERS.md` for known issues +2. Verify PostgreSQL connection: `echo "SELECT version()" | psql` +3. Verify Meilisearch running: `curl http://localhost:7700/health` +4. Review existing photos API: `grep -r "POST /api/photos" src/` +5. Create issue: `[AGENT-1] BLOCKER: [description]` + +--- + +## Questions? + +Read these files for context: +- `ARCHITECTURE-SUMMARY.md` - System design +- `BUILD_COMPLETE.md` - What's already working +- `DEMO-GUIDE.md` - Feature showcase guide diff --git a/builder/prompts/implementation/CLOUD_SESSION_PROMPT_2_DOCUMENT_SEARCH.md b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_2_DOCUMENT_SEARCH.md new file mode 100644 index 0000000..a8dfdbe --- /dev/null +++ b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_2_DOCUMENT_SEARCH.md @@ -0,0 +1,164 @@ +# Cloud Session 2: Advanced Document Search + +**Session ID:** CLOUD-2-DOCUMENT-SEARCH +**Timeline:** 90 minutes +**Deadline:** 4 hours from now (Riviera Plaisance presentation) +**Target:** Ship OCR search + document classifier improvements + +--- + +## Your Mission + +Improve the document search experience so boat owners can find maintenance manuals, insurance papers, warranty docs instantly. Current system works but needs: +- **Sticky engagement:** "Where's my engine manual?" → answers in 2 seconds +- **OCR accuracy:** Text extraction from boat documents (technical manuals, warranty cards, insurance papers) +- **Smart grouping:** Show warranty + insurance + service history together +- **Auto-tagging:** Classify documents by type (engine, electrical, safety equipment, etc.) + +This prevents **"Where's the engine manual?" crisis** during mechanical emergencies. + +--- + +## Quick Start + +1. **Clone repo:** + ```bash + git clone https://github.com/dannystocker/navidocs.git && cd navidocs + ``` + +2. **Read context:** + - `OCR_PIPELINE_SETUP.md` - Current OCR implementation (Tesseract + Google Vision) + - `BUILD_COMPLETE.md` - What search features already work + +3. **Check Meilisearch status:** + ```bash + curl http://localhost:7700/health + ``` + +4. **Review OCR API:** + ```bash + grep -r "ocr\|vision" src/api/ + ``` + +--- + +## Your Task List + +- [ ] **Diagnostic:** Review current OCR results quality + - Upload 5 test documents (warranty card, engine manual, insurance doc) + - Check extraction quality (confidence scores, missing text?) + - Document findings in `SEARCH_QUALITY_REPORT.md` + +- [ ] **Implement:** Smart document classifier + - Add `documentType` field to Document table (engine, electrical, hull, interior, warranty, insurance, service, safety) + - Create classifier endpoint: `POST /api/documents/classify` (reads OCR text → returns type) + - Support manual override (user selects type if AI wrong) + +- [ ] **Improve:** Search results ranking + - Boost warranty + service docs to top + - Show document type icon + confidence score + - Group results by document type + +- [ ] **Test:** Search UX with real documents + - "engine manual" → Find service manuals + - "warranty" → Find all warranty cards + service plans + - "electrical" → Find electrical system diagrams + parts docs + +- [ ] **API endpoints:** + - `POST /api/documents/classify` - Auto-classify document type + - `GET /api/documents/by-type/:type` - Filter by type + - `GET /api/search/advanced` - Enhanced search with type + relevance ranking + +- [ ] **Git commit:** `[AGENT-2] Add document classifier and search ranking` +- [ ] **Create issue:** `[AGENT-2] DEPLOY-READY: Document Search Improvements` with: + - Test results (5 documents, accuracy %) + - Search quality report + - Performance metrics (search latency) + - Deployment checklist + +--- + +## Technical Context + +**Current Stack:** +- OCR Pipeline: Tesseract (local) + Google Vision API (backup) +- Search Engine: Meilisearch (localhost:7700) +- Database: PostgreSQL - `Document` table with `content` field (OCR extracted text) +- Frontend: Next.js search UI component + +**Key Files:** +- `src/api/ocr/route.ts` - Current OCR implementation +- `src/api/search/route.ts` - Search endpoint +- `src/components/DocumentSearch.tsx` - Search UI +- `prisma/schema.prisma` - Document model + +**Design Specs:** +- Document types: engine, electrical, hull, interior, warranty, insurance, service, safety, other +- OCR text stored in `Document.content` (PostgreSQL) +- Meilisearch index includes: title, type, confidence, upload_date +- Search results show: document title, type badge, 2-line preview, relevance score + +--- + +## Sample Test Documents + +Create these for testing OCR quality: + +1. **Engine Manual** - Technical specifications, maintenance schedule +2. **Warranty Card** - Registration, coverage terms, contact info +3. **Insurance Document** - Policy details, coverage limits +4. **Service Record** - Date, service performed, parts replaced +5. **Electrical Diagram** - System schematic with part numbers + +**Quality Thresholds:** +- OCR confidence >85% = no review needed +- 70-85% = flag for manual review +- <70% = skip from search (mark as low-confidence) + +--- + +## Critical Notes + +1. **Boat owner pain point:** Mechanical emergency at 2am, need engine manual NOW +2. **Search must be fast:** <500ms response time (cached results) +3. **OCR accuracy matters:** Wrong document type = wrong answers +4. **Offline support:** Downloaded documents searchable without internet +5. **Mobile first:** Search on small screens must work perfectly + +--- + +## GitHub Access + +- **Repo:** https://github.com/dannystocker/navidocs +- **Branch:** `feature/document-search` (create from main) +- **Base for PR:** main branch + +--- + +## Success Criteria + +✅ Document classifier working (type detection >80% accurate) +✅ Search results ranked by type + relevance +✅ Test documents fully searchable +✅ OCR quality report completed +✅ API endpoints tested and working +✅ No console errors +✅ Git commit with [AGENT-2] tag + +--- + +## If Blocked + +1. Check Google Vision API credentials: `echo $GOOGLE_VISION_API_KEY` +2. Verify Tesseract installed: `tesseract --version` +3. Review current OCR: `cat OCR_PIPELINE_SETUP.md` +4. Check Meilisearch index: `curl http://localhost:7700/indexes/documents/stats` +5. Create blocker issue: `[AGENT-2] BLOCKER: [description]` + +--- + +## Reference Files + +- `OCR_PIPELINE_SETUP.md` - Complete OCR setup guide +- `ARCHITECTURE-SUMMARY.md` - System architecture +- `SMOKE_TEST_CHECKLIST.md` - Testing procedures diff --git a/builder/prompts/implementation/CLOUD_SESSION_PROMPT_3_MAINTENANCE_TIMELINE.md b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_3_MAINTENANCE_TIMELINE.md new file mode 100644 index 0000000..bdb1c1a --- /dev/null +++ b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_3_MAINTENANCE_TIMELINE.md @@ -0,0 +1,193 @@ +# Cloud Session 3: Maintenance Timeline & Alerts + +**Session ID:** CLOUD-3-MAINTENANCE-TIMELINE +**Timeline:** 90 minutes +**Deadline:** 4 hours from now (Riviera Plaisance presentation) +**Target:** Build maintenance log + service reminder system + +--- + +## Your Mission + +Create sticky daily-use maintenance tracking that makes boat owners check NaviDocs constantly: +- **Sticky engagement:** Service reminder notification = daily app habit +- **Maintenance checklist:** Engine hours, filter changes, system inspections +- **Service history:** When was engine serviced? Hull repainted? Electronics upgraded? +- **Alert system:** "Engine service due in 30 days" notification +- **Resale documentation:** Complete maintenance history proves boat was well-maintained + +This solves the **"How many hours on the engine?" crisis** when selling or servicing. + +--- + +## Quick Start + +1. **Clone repo:** + ```bash + git clone https://github.com/dannystocker/navidocs.git && cd navidocs + ``` + +2. **Review maintenance data model:** + ```bash + grep -A 20 "model MaintenanceRecord" prisma/schema.prisma + ``` + +3. **Check alert system:** + ```bash + grep -r "notification\|alert" src/api/ + ``` + +--- + +## Your Task List + +- [ ] **Database:** Maintenance table enhancements + - Add fields: `nextServiceDate`, `serviceIntervalDays`, `alertSent`, `completed` + - Support recurring services (e.g., oil change every 100 hours) + - Track engine hours, hull hours, electrical hours separately + +- [ ] **Create service templates:** Pre-defined maintenance items + - Engine: Oil change (every 100 hours), Coolant flush (yearly), Zincs replacement (yearly) + - Hull: Bottom paint (every 3 years), Haul-out inspection (yearly) + - Electrical: Battery test (every 6 months), Generator service (yearly) + - Safety: Life jacket inspection (yearly), Fire extinguisher check (yearly) + +- [ ] **API endpoints:** + - `POST /api/maintenance/add` - Add maintenance record + - `GET /api/maintenance/upcoming` - Services due in next 30/60/90 days + - `GET /api/maintenance/history` - Complete service history with dates + - `POST /api/maintenance/mark-complete` - Log completed service + +- [ ] **Notifications:** + - Create `MaintenanceAlert` component + - Show alerts on dashboard: "Engine service due in 30 days" + - Email notification 30 days before due date + - In-app notification when service overdue + +- [ ] **Timeline UI:** + - Vertical timeline showing service history (newest first) + - Color code: green=completed, yellow=upcoming, red=overdue + - Show estimated cost for each service + - Allow photos/notes for each service record + +- [ ] **Git commit:** `[AGENT-3] Add maintenance timeline and service alerts` +- [ ] **Create issue:** `[AGENT-3] DEPLOY-READY: Maintenance & Alerts System` with: + - Screenshots of timeline UI + - Sample maintenance schedules + - Alert notification examples + - Deployment notes for StackCP + +--- + +## Technical Context + +**Stack:** +- Frontend: Next.js 14 + Tailwind CSS +- Backend: Node.js + Prisma +- Database: PostgreSQL +- Notifications: Email (SMTP) + in-app alerts + +**Key Tables to Create/Modify:** +- `MaintenanceRecord` - Service records (date, type, cost, notes, photos) +- `MaintenanceTemplate` - Pre-defined service types (oil change, bottom paint, etc.) +- `MaintenanceAlert` - Triggered notifications (due date, sent date, read status) + +**Design Requirements:** +- Timeline should show last 24 months of maintenance +- Upcoming alerts should highlight next 90 days +- Color scheme: green=recent, yellow=upcoming, red=overdue, gray=old +- Mobile: swipeable timeline, tap for details +- Desktop: expandable timeline with full service notes + +--- + +## Maintenance Schedule Example + +**Engine Maintenance:** +- Oil & filter change: every 100 running hours +- Coolant flush: annually (or every 200 hours) +- Zinc replacement: every 2 years +- Spark plug service: every 5 years + +**Hull Maintenance:** +- Bottom paint: every 3 years (or as needed) +- Haul-out inspection: annually +- Caulking/sealant: every 5 years + +**Electrical Maintenance:** +- Battery test: every 6 months +- Generator service: annually +- Shore power system: every 2 years + +**Safety Maintenance:** +- Life jacket inspection: annually +- Fire extinguisher check: annually +- Coast Guard documentation: every 5 years + +--- + +## Critical Notes + +1. **Boat owner pain point:** "When was the last engine service?" = app opens NaviDocs +2. **Sticky feature:** Service due notification = daily habit (check app, mark complete) +3. **Resale value:** Complete maintenance history = higher resale price (proven care) +4. **Insurance value:** Service records = coverage proof in claims +5. **Engagement metric:** Maintenance alerts should drive 50% daily active user rate + +--- + +## GitHub Access + +- **Repo:** https://github.com/dannystocker/navidocs +- **Branch:** `feature/maintenance-timeline` (create from main) +- **Base for PR:** main branch + +--- + +## Success Criteria + +✅ Maintenance table created with correct fields +✅ Service templates loaded (15+ pre-defined services) +✅ Timeline UI shows 12+ months of history +✅ Alert system triggers for upcoming services +✅ Email notifications working (test with dummy email) +✅ No console errors +✅ Responsive on mobile/tablet/desktop +✅ Git commit with [AGENT-3] tag + +--- + +## If Blocked + +1. Check database schema: `grep -A 30 "model Maintenance" prisma/schema.prisma` +2. Verify email config: `echo $SMTP_HOST $SMTP_PORT` +3. Review notification system: `grep -r "notification\|email" src/` +4. Check database migration: `npx prisma migrate status` +5. Create issue: `[AGENT-3] BLOCKER: [description]` + +--- + +## Sample UI Elements + +**Timeline Item:** +``` +[GREEN CIRCLE] Engine oil change - Nov 13, 2025 + Next due: Jan 15, 2026 (63 days) + Cost: €150 + Mechanic: Marina Service S.A.R.L. +``` + +**Alert Banner:** +``` +⚠️ Engine service due in 30 days (Jan 15, 2026) + Last service: Nov 13, 2025 (2 months ago) + [SCHEDULE SERVICE] [DISMISS] +``` + +--- + +## Reference Files + +- `ARCHITECTURE-SUMMARY.md` - System design +- `BUILD_COMPLETE.md` - Working features +- `DEMO-GUIDE.md` - Feature showcase guide diff --git a/builder/prompts/implementation/CLOUD_SESSION_PROMPT_4_DEMO_POLISH.md b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_4_DEMO_POLISH.md new file mode 100644 index 0000000..767b4ca --- /dev/null +++ b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_4_DEMO_POLISH.md @@ -0,0 +1,224 @@ +# Cloud Session 4: Demo Polish & Riviera Plaisance Showcase + +**Session ID:** CLOUD-4-DEMO-POLISH +**Timeline:** 90 minutes +**Deadline:** 4 hours from now (Riviera Plaisance presentation) +**Target:** Polish UI/UX for impressive Sylvain demo + +--- + +## Your Mission + +Make NaviDocs shine for the Riviera Plaisance meeting. Focus on: +- **Impressive visuals:** Perfect onboarding flow, smooth animations +- **Sticky demo:** "Forgotten tender case study" showing €33K value (real example) +- **Demo script:** 10-minute pitch with "aha moment" at 2-minute mark +- **Error handling:** No crashes, graceful failures +- **Performance:** Smooth 60fps interactions, <1s load times +- **Mobile ready:** Works perfectly on iPad (Sylvain's device) + +The goal: Sylvain walks out saying "I want to bundle this with every boat sale" + +--- + +## Quick Start + +1. **Clone repo:** + ```bash + git clone https://github.com/dannystocker/navidocs.git && cd navidocs + ``` + +2. **Review existing demo guide:** + ```bash + cat DEMO-GUIDE.md + ``` + +3. **Start dev server:** + ```bash + npm run dev + # http://localhost:3000 + ``` + +4. **Test on mobile:** + ```bash + # From your machine: http://:3000 on iPad + ``` + +--- + +## Your Task List + +- [ ] **Onboarding Flow Audit:** + - First-time user sees: Welcome → Boat setup → Photo upload → Document scan → Dashboard + - Each step has helpful copy + visual cues + - No confusing jargon + - Should take <3 minutes to complete + - Document findings in `ONBOARDING_AUDIT.md` + +- [ ] **Forgotten Tender Case Study:** + - Create sample boat: "Sunseeker 40ft - €1.2M" + - Add photos: exterior, cabin, engine, safety equipment + - Add inventory: engine, tender (€35K), solar panels (€8K), electronics (€25K) + - Add maintenance: Last service November 2024 + - This demo proves: "Owner forgot tender worth €35K until selling" → NaviDocs prevented loss + +- [ ] **UI Polish Checklist:** + - [ ] Buttons have hover states + loading states + - [ ] Form inputs show validation errors clearly + - [ ] Empty states are friendly (not blank, have next steps) + - [ ] Images load smoothly (no layout shift) + - [ ] Modals have close buttons that work + - [ ] Navigation breadcrumbs always visible + - [ ] Search field has clear button + - [ ] All colors meet WCAG AA contrast standards + - [ ] Icons are consistent (Lucide React or Heroicons) + - [ ] Font sizes readable on mobile (16px minimum) + +- [ ] **Performance Optimization:** + - Measure: Largest Contentful Paint (LCP) <2.5s + - Measure: Cumulative Layout Shift (CLS) <0.1 + - Measure: First Input Delay (FID) <100ms + - Run Lighthouse audit: `npm run build && npx lighthouse http://localhost:3000` + - Report findings in `PERFORMANCE_REPORT.md` + +- [ ] **Error Handling:** + - Network errors: Show friendly message + retry button + - Upload failures: Clear error message + upload again + - Missing documents: "No documents yet" with [Add Document] button + - Photo load failures: Placeholder image instead of broken image + - Test by disabling network: Graceful degradation + +- [ ] **Demo Script Creation:** + - 10-minute pitch for Sylvain + - 0:00-2:00 - Problem statement (boat owners forget €15K-€50K in upgrades) + - 2:00-4:00 - NaviDocs solution (photos, documents, inventory) + - 4:00-8:00 - Live demo (upload photo, add inventory, search documents) + - 8:00-10:00 - Business case (€33K tender case study, sticky engagement) + - Include talking points for objections ("costs too much", "too complex", "we already have docs") + +- [ ] **Mobile Testing:** + - Test on iPad (target device for Sylvain) + - Portrait + landscape orientations + - Touch targets 48x48px minimum (accessibility) + - Forms don't get covered by keyboard + - Pinch-zoom disabled on appropriate elements + - No horizontal scroll needed + - File: `MOBILE_TEST_REPORT.md` + +- [ ] **Git commit:** `[AGENT-4] Polish UI/UX for Riviera Plaisance demo` +- [ ] **Create issue:** `[AGENT-4] DEMO-READY: Launch Package` with: + - Performance metrics (LCP, CLS, FID) + - Demo script (text file) + - Case study preview (screenshot) + - Checklist sign-off (all items green) + - Video recording of demo flow (optional but impressive) + +--- + +## The €33K Tender Case Study + +**Scenario:** +- Owner buys Sunseeker 40ft for €1.2M (includes tender, electronics, solar) +- 3 years later, decides to sell +- Without inventory photos/docs: **Forgets tender was included** +- Tender worth €35K just sits in storage +- Sells boat for €950K (loses €50K + tender = €85K total loss) + +**With NaviDocs:** +- Uploaded photos on day 1: exterior, tender on davits, cabin, electronics +- Maintenance log: annual haul-out with photos +- Inventory checklist: engine, tender, electronics, safety equipment all tagged +- When selling: "Here's photographic proof of everything included" +- Sells for €1.0M (prevents loss) + +**Talking Points for Sylvain:** +1. "You just sold a €1.2M boat" +2. "What if the owner forgot they included a €35K tender?" +3. "They remember when they're negotiating the sale" +4. "Your reputation: 'I forgot to sell the tender'" +5. "With NaviDocs: Photos + inventory from day 1" +6. "When selling: Complete documentation proves everything" +7. "Result: Higher resale prices, happier customers, repeat business" + +--- + +## Technical Context + +**Tools Available:** +- Lighthouse: `npm run build && npx lighthouse` +- React DevTools: Browser extension (check render performance) +- Chrome DevTools: Network tab (check load times) +- Mobile debugging: Chrome remote debugging + +**Key Metrics:** +- Lighthouse score target: >85 +- Largest Contentful Paint (LCP): <2.5 seconds +- Cumulative Layout Shift (CLS): <0.1 +- First Input Delay (FID): <100ms + +**UI Framework:** +- Next.js 14 with App Router +- Tailwind CSS for styling +- shadcn/ui components (consistent design) +- Lucide React for icons + +--- + +## Critical Demo Notes + +1. **Aha Moment:** At 2-minute mark, show forgotten tender photo → "That's €35K" +2. **Sticky Engagement:** Show push notification for maintenance due → daily habit +3. **Resale Value:** Before/after: competing boats same price, NaviDocs boat sells first +4. **Simplicity:** No jargon. "Boat owner" not "stakeholder" +5. **Success Metric:** Sylvain says "I want to bundle this with every boat sale" + +--- + +## GitHub Access + +- **Repo:** https://github.com/dannystocker/navidocs +- **Branch:** `feature/demo-polish` (create from main) +- **Base for PR:** main branch + +--- + +## Success Criteria + +✅ Lighthouse score >85 on all pages +✅ Performance metrics within targets (LCP <2.5s, CLS <0.1, FID <100ms) +✅ UI polish checklist 100% complete +✅ Demo script written (10 minutes, includes case study) +✅ €33K tender case study configured +✅ Mobile testing complete (iPad compatible) +✅ No console errors (warnings OK) +✅ Error handling covers common failures +✅ Git commit with [AGENT-4] tag + +--- + +## If Blocked + +1. Check Lighthouse: `npm run build && npx lighthouse http://localhost:3000` +2. Check React performance: Open DevTools → Profiler tab +3. Check network: DevTools → Network tab → throttle to "Slow 3G" +4. Review design system: `grep -r "shadcn\|lucide" src/components/` +5. Create issue: `[AGENT-4] BLOCKER: [description]` + +--- + +## Deliverable Files + +Create these before wrapping up: +1. `DEMO_SCRIPT.txt` - 10-minute pitch +2. `ONBOARDING_AUDIT.md` - Onboarding flow review +3. `PERFORMANCE_REPORT.md` - Lighthouse + Web Vitals +4. `MOBILE_TEST_REPORT.md` - iPad compatibility +5. `UI_POLISH_CHECKLIST.md` - All items green + +--- + +## Reference Files + +- `DEMO-GUIDE.md` - Demo structure +- `ARCHITECTURE-SUMMARY.md` - Technical overview +- `BRANDING_CREATIVE_BRIEF.md` - Visual identity guidelines diff --git a/builder/prompts/implementation/CLOUD_SESSION_PROMPT_5_INTEGRATION_TESTING.md b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_5_INTEGRATION_TESTING.md new file mode 100644 index 0000000..7d45826 --- /dev/null +++ b/builder/prompts/implementation/CLOUD_SESSION_PROMPT_5_INTEGRATION_TESTING.md @@ -0,0 +1,316 @@ +# Cloud Session 5: Integration Testing & Readiness + +**Session ID:** CLOUD-5-INTEGRATION-TESTING +**Timeline:** 90 minutes +**Deadline:** 4 hours from now (Riviera Plaisance presentation) +**Target:** Verify all features work together without breaking + +--- + +## Your Mission + +Test that all features integrated from Sessions 1-4 work together: +- Photo inventory (Session 1) + Document search (Session 2) work together +- Maintenance timeline (Session 3) integrates with notifications +- UI polish (Session 4) looks good on all pages +- No database errors, no API crashes +- Full end-to-end flow: Upload boat → Add photos → Upload docs → Set maintenance → View dashboard + +This is the **final quality gate** before Riviera Plaisance demo. + +--- + +## Quick Start + +1. **Clone repo:** + ```bash + git clone https://github.com/dannystocker/navidocs.git && cd navidocs + ``` + +2. **Verify all features:** + ```bash + git branch -a | grep feature/ # Check all feature branches merged + npm run build # Full build + npm run dev # Start server + ``` + +3. **Check integration points:** + ```bash + grep -r "import.*Photo" src/app/dashboard/ + grep -r "import.*Document" src/app/search/ + grep -r "import.*Maintenance" src/app/maintenance/ + ``` + +--- + +## Your Task List + +- [ ] **Database Integration Test:** + - Create test boat with all data: + - 5 photos (engine, cabin, exterior, safety, upgrade) + - 3 documents (warranty, service record, insurance) + - 10 maintenance records (past + upcoming) + - Verify no foreign key conflicts + - Check data consistency (orphaned records?) + - Document findings in `DATABASE_INTEGRITY_REPORT.md` + +- [ ] **API Integration Test:** + - Test photo upload → verify Meilisearch indexed + - Test document upload → verify OCR triggers → verify search works + - Test maintenance record → verify notification scheduled + - Test all 15+ API endpoints for errors + - Document API flow in `API_INTEGRATION_REPORT.md` + +- [ ] **UI Flow End-to-End Test:** + - Create boat (Landing → Onboarding → Dashboard) + - Upload photos (Dashboard → Photos → Upload → Verify in gallery) + - Upload documents (Dashboard → Documents → Upload → Search for keyword) + - Add maintenance (Dashboard → Maintenance → Add service → Check timeline) + - Verify all pages render without errors + - Check responsive design (mobile, tablet, desktop) + +- [ ] **Search Integration Test:** + - Add 20 documents with various text + OCR + - Search for common boat terms: "engine", "warranty", "service", "electrical" + - Verify results ranked correctly (title match > content match) + - Verify photo tags appear in search results + - Test pagination (10+ results) + - Document search quality in `SEARCH_QUALITY_REPORT.md` + +- [ ] **Performance Under Load Test:** + - Upload 50 photos simultaneously + - Index 100 documents + - Query search with 10 concurrent requests + - Check server logs for errors + - Verify response times acceptable (<500ms) + - Run: `npm run build && npm run start` + - Document findings in `LOAD_TEST_REPORT.md` + +- [ ] **Error Recovery Test:** + - Simulate network failure during upload + - Kill database connection mid-transaction + - Interrupt file upload at 50% + - Verify graceful error messages + - Verify no data corruption + - Document error scenarios in `ERROR_RECOVERY_REPORT.md` + +- [ ] **Browser Compatibility Test:** + - Chrome (latest) + - Firefox (latest) + - Safari (latest) + - Edge (latest) + - Test on: Windows, macOS, iOS, Android + - Document incompatibilities in `BROWSER_COMPAT_REPORT.md` + +- [ ] **Accessibility Test:** + - Tab navigation works everywhere + - Screen reader friendly (ARIA labels) + - Color contrast WCAG AA standard + - Forms labeled correctly + - Run: `npx axe-core` on key pages + - Document findings in `ACCESSIBILITY_REPORT.md` + +- [ ] **Data Export Test:** + - Export maintenance history (PDF + CSV) + - Export photo inventory (ZIP with metadata) + - Export document collection (PDF bundle) + - Verify exports complete without errors + - Check file integrity (can open + view correctly) + - Document in `EXPORT_FUNCTIONALITY_REPORT.md` + +- [ ] **Offline Mode Test:** + - Load app, download cache + - Disable network + - Verify cached photos visible + - Verify cached documents searchable + - Verify maintenance history accessible + - Document offline capabilities in `OFFLINE_CAPABILITY_REPORT.md` + +- [ ] **Security Test:** + - Verify API requires authentication + - Test CORS headers + - Verify uploaded files scanned for malware + - Check for SQL injection in search + - Verify file upload size limits enforced + - Document findings in `SECURITY_AUDIT_REPORT.md` + +- [ ] **Git commit:** `[AGENT-5] Complete integration testing + deployment checklist` +- [ ] **Create issue:** `[AGENT-5] READY-FOR-DEMO: All integration tests passed` with: + - Summary of all 11 reports + - Pass/fail status for each test + - Known issues (if any) with workarounds + - Deployment sign-off checklist + +--- + +## Test Scenarios + +### Scenario 1: Complete Boat Setup (Sunny Path) +``` +1. User creates boat (Sunseeker 40ft) +2. Uploads 5 photos (engine, cabin, exterior, tender, electronics) +3. Uploads 3 documents (warranty, service record, insurance) +4. System auto-classifies documents +5. System indexes photos + documents in Meilisearch +6. User searches "warranty" → finds document instantly +7. User searches "engine" → finds engine photo + maintenance record +8. User sets maintenance reminder (oil change every 100 hours) +9. Dashboard shows: 5 photos, 3 docs, 1 upcoming maintenance +``` +**Expected Result:** All features work, no errors, <2s load times + +### Scenario 2: Search Integration (Edge Case) +``` +1. User uploads warranty card (scanned image + OCR) +2. OCR extracts text: "Coverage: €50,000 engine protection" +3. Document classified as "warranty" +4. User searches "engine" +5. Results should show: warranty doc + engine photo + maintenance record +6. Results should be ranked: engine maintenance record first (exact match) +7. Warranty doc second (context match) +8. Engine photo third (tag match) +``` +**Expected Result:** Smart ranking, document type tags, no missing results + +### Scenario 3: Maintenance Workflow (Sticky Engagement) +``` +1. User adds maintenance record: "Engine oil change - completed Nov 13" +2. System extracts cost from receipt: €150 +3. System calculates next service due: Jan 15, 2026 (every 100 hours) +4. User gets notification: "Engine service due in 30 days" +5. User taps notification → marks service complete +6. Timeline updates immediately +7. Next notification scheduled for March 2026 +``` +**Expected Result:** Full lifecycle, notifications work, timeline accurate + +--- + +## Technical Context + +**Stack to Verify:** +- Frontend: Next.js 14 (all pages render correctly) +- API: Node.js + Prisma (all endpoints respond) +- Database: PostgreSQL (no integrity issues) +- Search: Meilisearch (documents indexed + searchable) +- Storage: Filesystem (photos + uploads) +- Notifications: Email + in-app (timely delivery) + +**Critical Integration Points:** +1. Photo upload → Meilisearch index +2. Document upload → OCR processing → Classification → Meilisearch +3. Maintenance record → Notification scheduling +4. Dashboard aggregation (5 photos + 3 docs + 2 upcoming services) + +--- + +## Test Data + +Create complete test boat for realistic integration testing: + +**Boat Profile:** +- Name: "Riviera Demo Boat" +- Brand: Sunseeker 40ft +- Year: 2020 +- Value: €1.2M + +**Photos:** +- Exterior (full boat shot) +- Engine room (clear engine photo) +- Cabin (showing interior condition) +- Tender on davits (€35K upgrade) +- Electronics console (GPS, radar, autopilot) + +**Documents:** +- Warranty card (scanned + OCR) +- Service record from 2024 +- Insurance policy document +- Original purchase documentation +- Electronics manual (PDF) + +**Maintenance Records:** +- Oil change (Nov 2024) +- Hull inspection (Nov 2024) +- Electronics check (Oct 2024) +- Upcoming: Engine service (Jan 2026) +- Upcoming: Bottom paint (May 2026) + +--- + +## Reports Required + +Create these 11 markdown files: + +1. `DATABASE_INTEGRITY_REPORT.md` - Data consistency check +2. `API_INTEGRATION_REPORT.md` - All endpoints tested +3. `SEARCH_QUALITY_REPORT.md` - Results quality + ranking +4. `LOAD_TEST_REPORT.md` - Performance under stress +5. `ERROR_RECOVERY_REPORT.md` - Failure scenarios +6. `BROWSER_COMPAT_REPORT.md` - Cross-browser testing +7. `ACCESSIBILITY_REPORT.md` - WCAG compliance +8. `EXPORT_FUNCTIONALITY_REPORT.md` - Data export verification +9. `OFFLINE_CAPABILITY_REPORT.md` - Offline mode testing +10. `SECURITY_AUDIT_REPORT.md` - Security verification +11. `INTEGRATION_SUMMARY.md` - Overall status + sign-off + +--- + +## Success Criteria + +✅ All 11 test reports created +✅ Database integrity verified (no orphaned records) +✅ All 15+ API endpoints returning correct data +✅ Photo upload → Search works end-to-end +✅ Document upload → Classification → Search works end-to-end +✅ Maintenance → Notifications works end-to-end +✅ Dashboard loads in <2 seconds +✅ Mobile responsive on all pages +✅ No console errors (warnings acceptable) +✅ All navigation flows work +✅ Error messages friendly + helpful +✅ Browser compatibility verified (4+ browsers) +✅ WCAG AA accessibility standards met +✅ Offline mode caches correctly +✅ Git commit with [AGENT-5] tag + +--- + +## GitHub Access + +- **Repo:** https://github.com/dannystocker/navidocs +- **Branch:** `feature/integration-testing` (create from main) +- **Base for PR:** main branch +- **Documentation:** All 11 reports in `intelligence/session-5/` + +--- + +## If Blocked + +1. Check database: `psql -c "SELECT COUNT(*) FROM Boat, Photo, Document, MaintenanceRecord;"` +2. Check API responses: `curl http://localhost:3000/api/boats` +3. Check Meilisearch: `curl http://localhost:7700/health` +4. Check build: `npm run build` (watch for errors) +5. Create blocker: `[AGENT-5] BLOCKER: [description]` + +--- + +## Demo Day Readiness + +**Before Showing Sylvain:** +- [ ] All 11 integration test reports green +- [ ] Database populated with demo boat + data +- [ ] Server running without errors +- [ ] Network stable (check ping to server) +- [ ] iPad loaded + ready (cached offline if needed) +- [ ] Demo script printed + reviewed +- [ ] Backup laptop ready (in case primary fails) +- [ ] Screenshot of each key feature (fallback if demo breaks) + +--- + +## Reference Files + +- `SMOKE_TEST_CHECKLIST.md` - Quick smoke tests +- `ARCHITECTURE-SUMMARY.md` - System architecture +- `BUILD_COMPLETE.md` - Feature status +- `DEMO-GUIDE.md` - Demo flow diff --git a/builder/prompts/research/session-1-market-research.md b/builder/prompts/research/session-1-market-research.md new file mode 100644 index 0000000..eecd63f --- /dev/null +++ b/builder/prompts/research/session-1-market-research.md @@ -0,0 +1,451 @@ +# Cloud Session 1: Yacht Sales Market Intelligence +## NaviDocs × Riviera Plaisance Opportunity Analysis + +**Session Type:** Market Research Coordinator +**Lead Agent:** Sonnet (strategic intelligence) +**Swarm Size:** 10 Haiku agents +**Token Budget:** $15 (7.5K Sonnet + 50K Haiku) +**Output:** Market analysis + competitive landscape + +--- + +## Mission Statement + +Gather comprehensive market intelligence for Riviera Plaisance Euro Voiles, focusing on **recreational motor boat owners** (Jeanneau Prestige + Sunseeker 40-60ft, €800K-€1.5M range) and the daily boat management pain points that NaviDocs solves with sticky engagement features. + +--- + +## Context (Read First) + +**NaviDocs:** Daily boat management app with sticky engagement (cameras, maintenance logs, inventory tracking) that happens to have perfect documentation when you need it. + +**Meeting:** Riviera Plaisance yacht sales agent (Sylvain) - pitch NaviDocs as included service with every boat sale + +**Riviera Plaisance Euro Voiles Profile:** +- **Location:** Antibes, Golfe Juan, Beaulieu (French Riviera) +- **Brands:** Jeanneau, Prestige Yachts, Fountaine Pajot, Monte Carlo Yachts +- **Volume:** 150+ new boats/year, 20,500+ active customers +- **Boat Types:** Recreational motor boats 40-50ft (€800K-€1.5M range) +- **Owner Profile:** Weekend/holiday users (20-40 days/year), NOT crew-managed mega yachts + +**Current NaviDocs Status:** +- 65% complete MVP +- Production-ready architecture (13 tables, 40+ APIs) +- OCR pipeline functional (Tesseract + Google Vision) +- Multi-tenant ready +- **Critical Gap:** Lacks sticky daily-use features (cameras, maintenance, inventory, contacts) + +**Key Insights from Local Research:** +1. **Inventory tracking pain:** Owners forget €15K-€50K in upgrades when selling (tender, electronics, blinds) +2. **Passive docs don't work:** Owners ignore documentation vault until emergency/sale +3. **Sticky features needed:** Camera check, maintenance log, crew contacts, expense tracking +4. **Warranty tracking:** Still valuable (€8K-€33K losses) but secondary to daily engagement +5. **Search UX critical:** No long lists - structured, impeccable search results + +--- + +## Agent Identity & Check-In Protocol + +**YOU ARE:** Sonnet coordinator for Session 1 (Market Research) + +**YOUR HAIKU SWARM:** You have 10 Haiku agents available. Use as many as needed (not required to use all 10). + +**AGENT IDENTITY SYSTEM:** +When spawning a Haiku agent, assign it an identity: `S1-H01` through `S1-H10` +Each agent MUST: +1. **Check in** at start: "I am S1-H03, assigned to [task name]" +2. **Reference their task** by searching this document for "Agent 3:" (matching their number) +3. **Retain identity** throughout execution +4. **Report completion** with identity: "S1-H03 complete: [deliverable summary]" + +**TASK DEPENDENCIES:** +- Agents 1-9 can run in parallel (no dependencies) +- Agent 10 (Evidence Synthesis) MUST wait for Agents 1-9 to complete + +--- + +## Your Tasks (Use Haiku Agents S1-H01 through S1-H10 as Needed) + +### Agent 1: Recreational Boat Market (Prestige + Sunseeker) +**AGENT ID:** S1-H01 +**PERSONA:** Joe Trader (Epic V4 Merchant-Philosopher) - detect discontinuities, market trends +**Research:** +- **ACTUAL SALE PRICES:** Search YachtWorld, Boat Trader ads for current + historical sales +- Price trend analysis 2020-2025 (COVID boom impact, current market) +- Jeanneau Prestige + Sunseeker 40-60ft market (units sold annually, €800K-€1.5M range) +- Riviera Plaisance Euro Voiles volume (150+ boats/year validated) +- Owner demographics (age, usage patterns, pain points) +- Boat ownership costs (maintenance, storage, upgrades) + +**Deliverable:** Market report with ACTUAL sale data + trend analysis (Joe Trader discontinuity lens) + +### Agent 2 Competitor Analysis (Boat Management Apps) +**AGENT ID:** S1-H02 +** +**Research:** +- Boat management apps (Savvy Navvy, Dockwa, Boat Buddy, BoatVault, DeckDocs) +- Daily engagement features (cameras, maintenance logs, inventory tracking) +- Pricing models (€5-€50/month for consumer apps) +- Feature gaps: Do they solve "forgot €15K tender" problem? +- Customer reviews: What makes boat apps sticky vs abandoned? + +**Deliverable:** Competitive matrix showing NaviDocs differentiation (daily engagement + perfect docs) + +### Agent 3 Owner Pain Points (Daily Boat Management) +**AGENT ID:** S1-H03 +** +**Research:** +- What frustrates recreational boat owners? (maintenance tracking, expense tracking, remote monitoring) +- "Forgot to sell the tender" problem - how common is inventory loss at resale? +- Camera/remote monitoring needs (is my boat OK while I'm away?) +- Crew/service contact management (who do I call for cleaning/repairs?) +- Accounting pain (how much am I spending on this boat annually?) + +**Deliverable:** Owner pain point analysis ranked by frequency and financial impact + +### Agent 4 Inventory Tracking & Resale Value Protection +**AGENT ID:** S1-H04 +** +**Research:** +- Boat equipment upgrade market (tenders, electronics, deck refinishing, automatic systems) +- Average upgrade spend per boat per year (Jeanneau Prestige + Sunseeker 40-60ft owners) +- "Forgotten inventory" problem - how much value is lost at resale? +- Receipt/invoice management for boats (tax deduction, warranty claims, resale documentation) +- Comparable: RV/car inventory tracking solutions + +**Deliverable:** ROI calculator for inventory tracking (€X forgotten value prevented) + +### Agent 5 Sticky Engagement Feature Research +**AGENT ID:** S1-H05 +** +**Research:** +- Boat camera/monitoring systems (Siren Marine, GOST, Nautic Alert) +- Maintenance reminder apps (what makes them sticky vs ignored?) +- Expense tracking for recreational vehicles (boats, RVs, classic cars) +- Contact management for boat services (marina, mechanics, cleaners, charter crew) +- User engagement metrics: daily active users for boat apps + +**Deliverable:** Feature prioritization - which sticky features drive daily/weekly engagement? + +### Agent 6 Search UX Best Practices (Critical for Inventory) +**AGENT ID:** S1-H06 +** +**Research:** +- Search UX for inventory/asset management (how to avoid long lists?) +- Structured search results (Pinterest, Amazon, Airbnb approaches) +- Filtering/faceting for boat equipment (by zone, category, value, warranty status) +- Mobile-first search (owners check from phone) +- Voice search for boat management ("Show me tender warranty") + +**Deliverable:** Search UX recommendations - impeccable structured results, zero long lists + +### Agent 7 Pricing Strategy Research (Broker-Included Model) +**AGENT ID:** S1-H07 +** +**Research:** +- "Included with purchase" software models (Tesla app, luxury car apps) +- Broker/dealer software bundling strategies +- Freemium boat apps (free basic, paid premium features) +- Monthly subscription tolerance (€5-€20/month for boat owners?) +- Revenue share models (broker pays €X per boat sold, owner pays ongoing) + +**Deliverable:** Pricing recommendation for "included with every Riviera boat" model + +### Agent 8 Home Assistant & Camera Integration Research +**AGENT ID:** S1-H08 +** +**Research:** +- Home Assistant boat monitoring setups (camera feeds, bilge sensors, battery monitoring) +- Marine camera systems compatible with HA (Hikvision, Reolink, marine-rated cameras) +- Boat monitoring hardware (Victron, Siren Marine, GOST integrations) +- Remote boat access use cases (security, maintenance alerts, peace of mind) +- API integration patterns (webhook, MQTT, REST) + +**Deliverable:** Technical feasibility report for Home Assistant/camera integration + +### Agent 9 Broker Sales Objection Research +**AGENT ID:** S1-H09 +** +**Research:** +- Why brokers resist including software with boat sales (complexity, support burden) +- Owner adoption challenges (will they actually use it after purchase?) +- Sticky product examples (what makes owners keep using bundled software?) +- Success stories: software included with high-ticket purchases (luxury cars, boats, RVs) +- "I already use X" objections (existing boat management apps) + +**Deliverable:** Objection handling playbook for Sylvain meeting + +### Agent 10 Evidence Synthesis +**AGENT ID:** S1-H10 +** +**Research:** +- Compile all findings from Agents 1-9 +- Cross-reference data for consistency +- Identify gaps requiring additional research +- Flag unverified claims needing validation + +**Deliverable:** Master evidence database with citations + +--- + +## Intra-Agent Communication Protocol (IF.bus) + +**Based on:** InfraFabric S² multi-swarm coordination (3,563x faster than git polling) + +### IFMessage Schema + +Every agent-to-agent message follows this structure: + +```json +{ + "performative": "inform", // FIPA-ACL: inform, request, query-if, confirm, disconfirm, ESCALATE + "sender": "if://agent/session-1/haiku-Y", + "receiver": ["if://agent/session-1/haiku-Z"], + "conversation_id": "if://conversation/navidocs-session-1-2025-11-13", + "content": { + "claim": "[Your finding]", + "evidence": ["[URL or file:line]"], + "confidence": 0.85, // 0.0-1.0 + "cost_tokens": 1247 + }, + "citation_ids": ["if://citation/uuid"], + "timestamp": "2025-11-13T10:00:00Z", + "sequence_num": 1 +} +``` + +### Speech Acts (Performatives) + +**inform:** Share findings with synthesis agent (Agent 10) +- Example: "I am S1-H03. Inventory tracking prevents €15K-€50K loss (confidence 0.85)" + +**request:** Ask another agent for verification/data +- Example: "S1-H10 requests S1-H02: Verify market size with 2nd source (IF.TTT requirement)" + +**confirm:** Validate another agent's claim +- Example: "S1-H02 confirms S1-H01: Market size €2.3B verified (2 sources now)" + +**disconfirm:** Challenge another agent's claim +- Example: "S1-H03 challenges S1-H01: Price range conflict (€250K vs €1.5M = 500% variance)" + +**ESCALATE:** Flag critical conflict for Sonnet coordinator +- Example: "S1-H10 ESCALATES: Price variance >20%, requires human resolution" + +### Communication Flow (This Session) + +``` +S1-H01 through S1-H09 → S1-H10 (Evidence Synthesis) + ↓ + ESCALATE (if conflicts) + ↓ + Sonnet Resolves +``` + +**Key Patterns:** +1. **Agents 1-9 → Agent 10:** Send findings with confidence scores +2. **Agent 10 → Agents 1-9:** Request verification if confidence <0.75 +3. **Agent 10 → Sonnet:** ESCALATE conflicts (>20% variance) +4. **Sonnet → Agent X:** Request re-investigation with specific instructions + +### Multi-Source Verification Example + +```yaml +# Agent 1 finds data (1 source, low confidence) +S1-H01: "inform" → claim: "Market size €2.3B", confidence: 0.70 + +# Agent 10 detects low confidence, requests verification +S1-H10: "request" → S1-H02: "Verify market size (IF.TTT: need 2+ sources)" + +# Agent 2 searches, finds 2nd source +S1-H02: "confirm" → S1-H10: "Market size €2.3B verified", confidence: 0.90 + +# Agent 10 synthesizes +S1-H10: "inform" → Coordinator: "Market size €2.3B (VERIFIED, 2 sources)" +``` + +### Conflict Detection Example + +```yaml +# Agents report conflicting data +S1-H01: "inform" → "Prestige 50 price €250K" +S1-H03: "inform" → "Owner has €1.5M Prestige 50" + +# Agent 10 detects 500% variance +S1-H10: "ESCALATE" → Coordinator: "Price conflict requires resolution" + +# Sonnet resolves +Coordinator: "request" → S1-H01: "Re-search YachtWorld for Prestige 50 SOLD prices" + +# Agent 1 corrects +S1-H01: "inform" → "Prestige 50 price €800K-€1.5M (CORRECTED)" +``` + +### IF.TTT Compliance + +Every message MUST include: +- **citation_ids:** Links to evidence +- **confidence:** Explicit score (0.0-1.0) +- **evidence:** Observable artifacts (URLs, file:line) +- **cost_tokens:** Token consumption (IF.optimise tracking) + +--- + +## IF.optimise Protocol + +**Token Efficiency Targets:** +- Use Haiku for all web research and data extraction +- Use Sonnet only for final synthesis and strategic analysis +- Target: 70% Haiku delegation (10% better than 14-day sprint) + +**Cost Tracking:** +- Report token consumption per agent +- Alert if exceeding $15 budget +- Switch to Haiku-only mode if approaching limit + +--- + +## Output Format + +### Deliverable 1: Market Analysis Report +**File:** `session-1-market-analysis.md` + +**Structure:** +```markdown +# Yacht Sales Market Intelligence Report +## Mediterranean Focus - Riviera Plaisance Opportunity + +### Executive Summary +- Market size: [€X billion, Y thousand yachts sold annually] +- Riviera broker market: [Z brokerages, avg A boats/year] +- Opportunity: [€B revenue potential for NaviDocs] + +### Market Sizing +[Agent 1 findings with citations] + +### Competitive Landscape +[Agent 2 competitive matrix] + +### Broker Pain Points +[Agent 3 pain point analysis] + +### Value Proposition +[Agent 4 ROI calculator data] + +### Regulatory Requirements +[Agent 5 compliance checklist] + +### Charter Fleet Market +[Agent 6 charter feature needs] + +### Pricing Strategy +[Agent 7 pricing recommendations] + +### Integration Partnerships +[Agent 8 integration targets] + +### Sales Enablement +[Agent 9 objection handling] + +### Evidence Quality +[Agent 10 verification status] +- Total claims: X +- Verified claims: Y (Z%) +- Citations: [if://citation/uuid list] +``` + +### Deliverable 2: Citations Database +**File:** `session-1-citations.json` + +**Format:** +```json +{ + "session_id": "if://conversation/navidocs-session-1-2025-11-13", + "citations": [ + { + "citation_id": "if://citation/market-size-mediterranean-yachts", + "claim": "Mediterranean yacht sales market is €2.3B annually", + "sources": [ + { + "type": "web", + "url": "https://example.com/yacht-market-report-2024", + "accessed": "2025-11-13T10:00:00Z", + "hash": "sha256:..." + } + ], + "status": "verified", + "created_by": "if://agent/session-1/haiku-1" + } + ] +} +``` + +### Deliverable 3: Session Handoff +**File:** `session-1-handoff.md` + +**Structure:** +```markdown +# Session 1 Handoff to Session 2 + +## Mission Accomplished +- [x] Market analysis complete +- [x] Competitive landscape mapped +- [x] Pain points identified +- [x] Evidence database compiled + +## Key Findings for Session 2 +1. Market opportunity: €X million +2. Top 3 competitor gaps: [list] +3. Critical broker pain: [time spent on documentation] +4. Regulatory requirements: [jurisdictions covered] + +## Blockers for Next Session +- [ ] Need technical specs for MLS integration (Agent 8 flagged) +- [ ] Pricing model requires cost analysis (Agent 7 flagged) + +## Token Consumption +- Total: 52,450 tokens ($0.86) +- Sonnet: 7,200 tokens +- Haiku: 45,250 tokens +- Efficiency: 71% Haiku delegation ✅ + +## Evidence Quality +- Total claims: 47 +- Verified: 42 (89%) +- Unverified: 5 (flagged for Session 5 Guardian review) + +## Next Session Input +Read: session-1-market-analysis.md, session-1-citations.json +Focus: Technical integration architecture for broker CRM, MLS, Home Assistant +``` + +--- + +## IF.TTT Compliance Checklist + +- [ ] All claims have ≥2 source citations +- [ ] File hashes (SHA-256) for all web sources +- [ ] Agent token consumption logged +- [ ] Unverified claims flagged +- [ ] Session handoff document created +- [ ] GitHub commit with citation references + +--- + +## Success Criteria + +**Minimum Viable Output:** +- Market size quantified (€X billion, Y thousand yachts) +- Top 5 competitors identified with pricing +- 3-5 critical broker pain points documented +- ROI calculator inputs compiled +- Evidence quality >85% verified + +**Stretch Goals:** +- Integration partnership targets identified +- Sales objection handling playbook complete +- Charter fleet market analysis included + +--- + +**Start Command:** Deploy this prompt to Claude Code Cloud with GitHub repo access +**End Condition:** All deliverables committed to `dannystocker/navidocs` repo under `intelligence/session-1/` diff --git a/builder/prompts/research/session-2-technical-integration.md b/builder/prompts/research/session-2-technical-integration.md new file mode 100644 index 0000000..2de54b9 --- /dev/null +++ b/builder/prompts/research/session-2-technical-integration.md @@ -0,0 +1,814 @@ +# Cloud Session 2: Technical Integration Architecture +## NaviDocs Yacht Sales Enhancement Roadmap + +**Session Type:** Technical Integration Specialist +**Lead Agent:** Sonnet (architecture + development) +**Swarm Size:** 10 Haiku agents +**Token Budget:** $20 (10K Sonnet + 60K Haiku) +**Output:** Feature specs + integration architecture + sprint plan + +--- + +## Mission Statement + +Design technical architecture for **sticky daily-use features** (inventory tracking, cameras, maintenance logs, contacts, accounting) that make NaviDocs indispensable to recreational boat owners. Documentation features are secondary to engagement. + +--- + +## Context (Read First) + +**Prerequisites:** +1. Read `intelligence/session-1/session-1-market-analysis.md` (once Session 1 completes) +2. Read `intelligence/session-1/session-1-handoff.md` (once Session 1 completes) +3. Read `ARCHITECTURE_INTEGRATION_ANALYSIS.md` (in repo root) + +**Current NaviDocs Tech Stack:** +- Frontend: Vue 3 + Vite +- Backend: Express.js + SQLite +- Background: BullMQ + Redis +- Search: Meilisearch +- OCR: Tesseract + Google Vision +- Auth: JWT + bcrypt + +**Critical Feature Gaps (from Session 1):** +- **No document tracking/versioning** (core value prop: warranties, manuals, service records with IF.TTT traceability) +- **No WhatsApp group integration** (boat-specific chat with owner, after-sales, captain + AI agent) +- **No inventory tracking** (€15K-€50K forgotten value at resale) +- **No camera/monitoring integration** (owners want "is my boat OK?" reassurance) +- **No maintenance log** (when was last engine service? upcoming work alerts?) +- **No contact management** (crew, marina, mechanics, cleaners) +- **No expense tracking** (how much am I spending on this boat?) +- **No impeccable search** (avoid long lists, structured faceted results) +- **No VAT/tax tracking** (non-VAT boats must leave EU for stamp; different regs ES/FR/IT/global jurisdictions) +- **No calendar system** (service dates, warranty tracking, owner onboard dates, work roadmaps with budget signoff) + +--- + +## PHASE 1: Helper Agents (START IMMEDIATELY - ASSIST SESSIONS 1 & 3) + +**Mission:** While waiting for Session 1 market research and Session 3 UX/sales work, provide active technical assistance to accelerate their completion. + +**NO DEPENDENCIES:** All Phase 1 agents can start immediately (no need to wait for other sessions). + +--- + +### Agent 0A: Technical Validation Assistant (CRITICAL) +**AGENT ID:** S2-H0A +**START:** Immediately (no dependencies) + +**Assist Session 1 (Market Research):** +- **Verify competitor tech stacks:** When Session 1 identifies competitors (YachtWorld, Boat Trader, etc.), validate their API documentation +- **Check API availability:** Research if competitor APIs are public, require auth, or need partner agreements +- **Document API contracts:** Create structured summaries of competitor API capabilities for Session 1 citations + +**Assist Session 3 (UX/Sales):** +- **Technical feasibility checks:** When Session 3 proposes UI features, confirm if NaviDocs tech stack supports them +- **Performance estimates:** Provide load time estimates for proposed features (based on NaviDocs current architecture) +- **Mobile compatibility:** Validate if proposed UX patterns work on mobile (Vue 3 + PWA constraints) + +**Deliverable:** `intelligence/session-2/helper-technical-validations.md` (updated in real-time as Sessions 1 & 3 work) + +--- + +### Agent 0B: Citation Automation (SHA-256 Hash Generation) +**AGENT ID:** S2-H0B +**START:** Immediately (no dependencies) + +**Assist Session 1 (Market Research):** +- **Generate SHA-256 hashes:** When Session 1 cites web URLs, automatically fetch and hash content +- **Verify URL accessibility:** Check if cited URLs return 200 OK (flag broken links immediately) +- **Extract structured data:** Parse web pages for key data points (pricing, features, market stats) +- **Create citation JSON:** Auto-generate IF.TTT-compliant citation entries with hashes + +**Example Workflow:** +```bash +# Session 1 Agent 3 cites: "YachtWorld pricing: €25/month" +# Agent 0B immediately: +1. Fetches https://yachtworld.com/pricing +2. Generates SHA-256: a1b2c3d4e5f6... +3. Extracts pricing table +4. Creates citation JSON: +{ + "citation_id": "if://citation/yachtworld-pricing-nov2025", + "claim": "YachtWorld charges €25/month for yacht management", + "sources": [{ + "type": "web", + "url": "https://yachtworld.com/pricing", + "sha256": "a1b2c3d4e5f6...", + "accessed": "2025-11-13", + "quality": "primary", + "credibility": 9 + }], + "status": "verified", + "confidence_score": 0.95 +} +``` + +**Deliverable:** `intelligence/session-2/auto-citations.json` (append as Session 1 works) + +--- + +### Agent 0C: Web Scraping Assistant (Structured Data Extraction) +**AGENT ID:** S2-H0C +**START:** Immediately (no dependencies) + +**Assist Session 1 (Market Research):** +- **Extract competitor feature lists:** Scrape competitor websites for feature comparisons +- **Pricing table extraction:** Parse pricing pages into structured JSON +- **Market report parsing:** Extract key stats from industry reports (PDFs, web pages) +- **Automated data validation:** Cross-check data across multiple sources (detect conflicts) + +**Example:** +```yaml +# Session 1 Agent 5 researching competitors +# Agent 0C scrapes: +- YachtWorld: Features (inventory, CRM, MLS integration) +- Boat Trader: Pricing (€15/month basic, €45/month pro) +- Dockwa: User counts (50K+ marinas, 250K+ boaters) + +# Output: intelligence/session-2/competitor-data.json +{ + "yachtworld": { + "features": ["inventory", "crm", "mls_integration"], + "pricing": {"basic": 25, "pro": 75}, + "users": "unknown" + }, + "boat_trader": { + "features": ["listings", "leads", "analytics"], + "pricing": {"basic": 15, "pro": 45}, + "users": "unknown" + } +} +``` + +**Deliverable:** `intelligence/session-2/competitor-data.json` (structured data for Session 1 & 3 use) + +--- + +### Agent 0D: ROI Calculator Backend (Build Before Session 1 Data Arrives) +**AGENT ID:** S2-H0D +**START:** Immediately (no dependencies) + +**Build Generic ROI Calculator Framework:** +- **Formula engine:** Create generic calculator that accepts variables (warranty_savings, time_saved, resale_value_increase) +- **Input validation:** Define valid ranges for each variable (prevent unrealistic claims) +- **Visualization logic:** Prepare chart generation code (bar charts, pie charts for ROI breakdown) +- **Export functionality:** Generate PDF/Excel exports of ROI calculations + +**Example Structure:** +```javascript +// server/services/roi-calculator.service.js +class ROICalculator { + calculate(inputs) { + // inputs: { warranty_savings, time_saved_hours, resale_value_increase } + const warranty_roi = inputs.warranty_savings * 12; // Annual savings + const time_roi = inputs.time_saved_hours * 50; // €50/hour labor cost + const resale_roi = inputs.resale_value_increase; + + return { + total_annual_roi: warranty_roi + time_roi, + resale_value_lift: resale_roi, + payback_period_months: this.calculatePayback(inputs), + confidence: this.calculateConfidence(inputs) + }; + } +} +``` + +**When Session 1 Data Arrives:** +- Agent 0D plugs in Session 1 findings (€8K-€33K warranty savings, etc.) +- Generates final ROI report for Session 3 pitch deck +- Creates interactive calculator UI for demos + +**Deliverable:** `intelligence/session-2/roi-calculator-framework.js` (ready for Session 1 data integration) + +--- + + +## Agent Identity & Check-In Protocol + +**YOU ARE:** Sonnet coordinator for Session 2 (Technical Architecture) + +**YOUR HAIKU SWARM:** You have 10 Haiku agents available. Use as many as needed (not required to use all 10). + +**AGENT IDENTITY SYSTEM:** +When spawning a Haiku agent, assign it an identity: `S2-H01` through `S2-H10` +Each agent MUST: +1. **Check in** at start: "I am S2-H03, assigned to [task name]" +2. **Reference their task** by searching this document for "Agent 3:" (matching their number) +3. **Retain identity** throughout execution +4. **Report completion** with identity: "S2-H03 complete: [deliverable summary]" + +**TASK DEPENDENCIES:** +- Most agents can run in parallel +- Agent 10 typically synthesizes results from Agents 1-9 (must wait for completion) + +--- + +## Your Tasks (Spawn 10 Haiku Agents in Parallel) + +### Agent 1: NaviDocs Codebase Analysis +**AGENT ID:** S2-H01 +** +**Read Files:** +- `server/db/schema.sql` - Database structure +- `server/routes/*.js` - API endpoints +- `server/services/*.js` - Business logic +- `server/workers/*.js` - Background jobs + +**Deliverable:** Architecture map with integration points + +### Agent 2: Inventory Tracking System Design (CRITICAL) +**AGENT ID:** S2-H02 +** +**Design:** +- Database schema: `boat_inventory` (item_name, category, zone, purchase_date, purchase_price, receipt_url, warranty_expiration, current_value) +- Categories: tender/zodiac, electronics, engine, deck, interior, safety +- Zones: salon, galley, helm, engine room, stern storage +- OCR receipt extraction (auto-populate item, price, date) +- Resale value calculator (total upgrades since purchase) +- Search facets (by category, zone, value range, warranty status) + +**Deliverable:** Inventory tracking spec with impeccable search UX + +### Agent 3: Maintenance Log & Reminder System +**AGENT ID:** S2-H03 +** +**Design:** +- Database schema: `maintenance_log` (service_type, date, cost, provider, next_due_date, engine_hours) +- Service types: engine, electronics, hull, deck, safety equipment +- Reminder alerts (based on date OR engine hours) +- Service provider contacts (auto-suggest from past services) +- Expense rollup (total maintenance spend YTD, annual) + +**Deliverable:** Maintenance tracking spec with smart reminders + +### Agent 4: Camera & Remote Monitoring Integration (STICKY!) +**AGENT ID:** S2-H04 +** +**Research + Design:** +- Home Assistant camera feed integration (Hikvision, Reolink, marine cameras) +- Webhook architecture (NaviDocs ← HA events: motion detected, battery low, bilge alert) +- Camera snapshot storage (link to boat, timestamp, auto-cleanup old images) +- Mobile-first UI (owners check from phone: "is my boat OK?") +- Use cases: security monitoring, dock check, weather damage assessment + +**Deliverable:** Camera/HA integration architecture with peace-of-mind UX + +### Agent 5: Contact Management System +**AGENT ID:** S2-H05 +** +**Design:** +- Database schema: `boat_contacts` (name, role, phone, email, notes, last_used) +- Roles: marina, mechanic, cleaner, charter crew, electrician, surveyor +- One-tap call/email from mobile +- Auto-suggest from maintenance log (provider → contact) +- Quick actions: "Call my mechanic", "Email charter crew" + +**Deliverable:** Contact management spec with mobile-first UX + +### Agent 6: Receipt/Invoice Upload + Accounting Module Integration +**AGENT ID:** S2-H06 +** +**Research + Design:** + +**Open-Source Accounting Module Research:** +- Review `YACHT_ACCOUNTING_RESEARCH.md` (in repo root - Haiku research completed) +- **Recommended:** Spliit (MIT, 2.3K stars) - receipt scanning, expense splitting, PWA mobile +- **Alternative:** SplitPro (MIT, 916 stars) - BigInt precision, multi-currency +- **Foundation:** Medici (MIT, 330 stars) - double-entry GL, hierarchical accounts + +**Multi-User Expense Tracking:** +- **Owner expenditure:** + - Cash payments (€X for marina, €Y for fuel) + - Card payments (auto-import from bank APIs if available) + - Bank transfers (boat maintenance, insurance) + - Categories: marina fees, insurance, major upgrades, professional services +- **Captain expenditure:** + - Boat card (provisioning, fuel, minor repairs) + - Boat cash (tips, small purchases) + - Personal cash to reimburse (meals, supplies bought with personal funds) + - Categories: provisions, fuel, minor repairs, supplies, crew meals +- **Reimbursement workflow:** + - Captain submits expense with receipt photo + - NaviDocs OCR extracts (amount, vendor, date, category) + - Owner approves/rejects via WhatsApp or app + - Mark as "paid" when reimbursed + +**Receipt/Invoice Upload Integration:** +- Photo upload via mobile (camera + gallery) +- OCR processing (existing Tesseract + Google Vision pipeline) +- Auto-extraction: amount, vendor, date, VAT, category +- Link to maintenance log, inventory, or general expense +- Store original receipt image + extracted structured data +- IF.TTT compliance: SHA-256 hash, ed25519 signature, citation ID + +**Accounting Module Architecture:** +- Fork Spliit or integrate as library (MIT license allows) +- Customize for boat workflows (owner vs captain vs crew) +- Multi-currency support (€, $, £ for international owners) +- Export to Excel/CSV for accountant (tax deduction reports) +- Integration with WhatsApp: "@NaviDocs log expense €45 fuel" → AI creates expense entry + +**Deliverable:** Accounting module integration spec + receipt OCR workflow + multi-user expense tracking design + +### Agent 7: Impeccable Search UX Design (CRITICAL) +**AGENT ID:** S2-H07 +** +**Design:** +- Search architecture (Meilisearch faceted search) +- Structured results (NO long lists - Pinterest/Airbnb grid layout) +- Facets: category, zone, value range, warranty status, date range +- Mobile-first (owners search from phone) +- Voice search support ("Show me tender warranty") +- Quick filters: "Show expensive items", "Show expiring warranties" + +**Deliverable:** Search UX spec with visual mockups (avoid long lists!) + +### Agent 8: WhatsApp Group Integration (CRITICAL - NEW!) +**AGENT ID:** S2-H08 +** +**Research + Design:** +- WhatsApp Business API integration (boat-specific group chat) +- Group membership: Owner, Riviera after-sales, captain, stakeholders + NaviDocs AI agent +- AI agent capabilities: + - **Log all chats** (IF.TTT audit trail: who said what, when, with citations) + - **Answer questions** ("Where's the tender warranty?" → NaviDocs searches, responds with doc link) + - **Post updates** ("Maintenance service due in 2 weeks" → proactive reminders) + - **Document versioning notifications** ("New manual uploaded for autopilot") +- Technical architecture: + - Webhook from WhatsApp → NaviDocs tenant API + - AI agent response generation (Claude API integration) + - Message history storage (IF.TTT compliance: ed25519 signatures, SHA-256 hashes) + - Multi-tenant isolation (each boat's chat stays separate) +- Use cases: + - Owner: "When was last engine service?" → AI responds with maintenance log data + - After-sales: "@NaviDocs upload warranty for new tender" → AI confirms, creates inventory entry + - Captain: "Bilge pump alarm triggered" → AI logs incident, suggests mechanic contact + +**Deliverable:** WhatsApp integration architecture with AI agent spec + IF.TTT compliance checklist + +### Agent 9: Document Tracking & Versioning (CORE VALUE PROP) +**AGENT ID:** S2-H09 +** +**Design:** +- Document versioning system (git-style: track changes, rollback, history) +- IF.TTT compliance: Every doc upload/edit gets: + - Ed25519 signature (who uploaded) + - SHA-256 content hash (tamper detection) + - Timestamp (when) + - Citation ID (if://doc/navidocs/boat-123/warranty-tender-v2) +- Document categories: warranties, manuals, service records, invoices, certificates, insurance +- Versioning metadata: version number, change description, changed_by, changed_at +- Search integration: Meilisearch indexes doc content (OCR text + metadata) +- Mobile-first: owners upload photos of receipts/manuals → OCR extraction → structured data + +**Deliverable:** Document versioning spec with IF.TTT traceability architecture + +### Agent 3A: VAT/Tax Jurisdiction Tracking & Compliance Reminders (CRITICAL) +**AGENT ID:** S2-H03A +** +**Research + Design:** +- **Non-VAT boat regulations:** Research requirements for tax-exempt yachts in major jurisdictions + - **EU:** Must leave EU waters to get customs stamp (prevents VAT liability) + - **France:** Check exit requirements, grace periods, penalties for non-compliance + - **Spain:** Different exit requirements than France (research specific regs) + - **Italy:** Different exit requirements (research specific regs) + - **Global:** Check major yachting jurisdictions (Monaco, Gibraltar, Malta, Cayman Islands, US, Caribbean) +- **VAT-paid vs Non-VAT tracking:** + - Database schema: `boat_tax_status` (vat_paid, home_jurisdiction, purchase_date, exemption_expiry, last_exit_date) + - Track: VAT status, home port, last EU exit, next required exit +- **Compliance reminder system:** + - Calculate: days until required EU exit (based on jurisdiction rules) + - Alerts: 60/30/14/7 days before required exit + - Dashboard widget: "EU Exit Required in 23 days (Spain regs)" + - Integration with calendar system (scheduled exits on owner calendar) +- **Jurisdiction-specific rules engine:** + - Store rules per jurisdiction (exit frequency, grace periods, documentation requirements) + - Update mechanism (regulations change - need easy updates) + - Multi-jurisdiction support (owner moves between FR/ES/IT marinas) + +**Deliverable:** VAT/tax tracking spec with compliance reminders + jurisdiction rules engine + integration with calendar system + +### Agent 7A: Multi-Calendar System (CRITICAL) +**AGENT ID:** S2-H07A +** +**Design:** +- **Calendar architecture** (4 separate calendar types, unified UI): + 1. **Service Calendar:** + - Maintenance appointments (past + upcoming) + - Service due dates (based on date OR engine hours) + - Reminders: 60/30/14/7 days before service due + - Integration: Maintenance log (Agent 3) feeds service dates + 2. **Warranty Calendar:** + - Warranty expiration dates (equipment-specific) + - Purchase anniversaries (for warranty tracking) + - Reminders: 90/60/30 days before warranty expires + - Integration: Inventory tracking (Agent 2) feeds warranty dates + 3. **Owner Onboard Calendar:** + - Owner scheduled trips ("On boat: July 15-22, 2025") + - Captain can see owner arrival dates (prep boat) + - After-sales can see owner activity patterns (engagement tracking) + - Integration: Stakeholder dashboard (Session 3) shows owner engagement + 4. **Work Roadmap Calendar:** + - Planned work with budget estimates ("Hull repaint: €15K, scheduled Aug 2025") + - Budget signoff workflow (owner approves/rejects planned work) + - Status tracking: Proposed → Approved → Scheduled → In Progress → Complete + - Integration: Expense tracking (Agent 6) for actual costs vs budget + +**Calendar Features:** +- **Unified dashboard view:** All 4 calendars in one interface (color-coded) +- **Mobile-first:** Owners check calendars from phone +- **Smart notifications:** Context-aware (e.g., "Service due + Owner arriving in 3 days → notify captain to schedule service before arrival") +- **Export:** iCal/Google Calendar sync (owners add to personal calendar) +- **Conflict detection:** "Owner arriving July 15, but hull repaint scheduled July 10-20 → flag conflict" + +**Database Schema:** +- `calendar_events` (event_type, date, boat_id, title, description, status, budget_amount, actual_cost, created_by, approved_by) +- Event types: service_due, warranty_expires, owner_onboard, work_planned, tax_exit_required +- Status: proposed, approved, scheduled, in_progress, completed, cancelled + +**Deliverable:** Multi-calendar system spec with unified dashboard + smart notifications + conflict detection + budget signoff workflow + +### Agent 10: Architecture Synthesis & Sprint Planning +**AGENT ID:** S2-H10 +** +**Wait for:** Agents 1-9 + 3A + 7A to complete (11 agents total) + +**Compile:** +- Integration architecture (all 11 features working together) +- Week 1-4 task breakdown with priorities: + - **Week 1:** Document tracking/versioning + WhatsApp integration (core value props) + - **Week 2:** Inventory tracking + maintenance log + VAT/tax tracking (Agent 3A) + - **Week 3:** Camera integration + contact management + multi-calendar system (Agent 7A) + - **Week 4:** Expense tracking + search UX + AI agent training + calendar integrations +- Dependencies mapped: + - WhatsApp AI agent needs document search working first + - Calendar system needs maintenance log + inventory tracking data feeds + - VAT compliance alerts integrate with calendar system (exit reminders) + - Work roadmap calendar integrates with expense tracking (budget vs actual) +- Acceptance criteria per feature +- Testing strategy (unit, integration, E2E + IF.TTT audit validation) +- IF.TTT dogfooding checklist (we're using our own traceability standards) + +**Deliverable:** Complete architecture document + 4-week sprint plan with IF.TTT compliance + calendar/tax integration roadmap + +--- + +## Intra-Agent Communication Protocol (IF.bus) + +**Based on:** InfraFabric S² multi-swarm coordination (3,563x faster than git polling) + +### IFMessage Schema + +Every agent-to-agent message follows this structure: + +```json +{ + "performative": "inform", // FIPA-ACL: inform, request, query-if, confirm, disconfirm, propose, agree, ESCALATE + "sender": "if://agent/session-2/haiku-Y", + "receiver": ["if://agent/session-2/haiku-Z"], + "conversation_id": "if://conversation/navidocs-session-2-2025-11-13", + "content": { + "claim": "[Your design proposal]", + "evidence": ["[File references or codebase analysis]"], + "confidence": 0.85, // 0.0-1.0 + "cost_tokens": 1247 + }, + "citation_ids": ["if://citation/uuid"], + "timestamp": "2025-11-13T10:00:00Z", + "sequence_num": 1 +} +``` + +### Speech Acts (Performatives) + +**propose:** Agent suggests a design or approach +- Example: "S2-H02 proposes: Inventory tracking via manual entry forms" + +**agree:** Agent validates another agent's proposal +- Example: "S2-H04 agrees with S2-H02: Manual entry compatible with camera feeds" + +**disconfirm:** Agent challenges another agent's design +- Example: "S2-H04 challenges S2-H02: Camera feeds can auto-detect equipment (CV models available)" + +**request:** Ask another agent for design input +- Example: "S2-H02 requests S2-H04: How do cameras integrate with inventory schema?" + +**confirm:** Validate another agent's technical claim +- Example: "S2-H01 confirms S2-H03: Express.js patterns match existing routes" + +**ESCALATE:** Flag critical integration conflicts +- Example: "S2-H10 ESCALATES: Inventory + cameras overlap, needs integration design" + +### Communication Flow (This Session) + +``` +S2-H01 (Codebase) ──→ S2-H10 +S2-H02 (Inventory) ──→ S2-H04 (Cameras) ─→ S2-H10 (peer review) +S2-H03 (Maintenance) → S2-H05 (Contacts) → S2-H10 (integration check) +S2-H06 (Expense) ────→ S2-H07 (Search UX)→ S2-H10 +``` + +**Key Patterns:** +1. **Design Proposals:** Agents 2-7 propose features independently +2. **Peer Review:** Adjacent agents challenge/validate designs +3. **Integration Checks:** Agent 10 ensures no conflicts between subsystems +4. **Sonnet Approval:** Final architecture review & synthesis + +### Cross-Domain Validation Example + +```yaml +# Agent 2 (Inventory Tracking) proposes design +S2-H02: "propose" → content: + feature: "Inventory tracking via manual entry forms" + rationale: "Simple, no OCR complexity" + +# Agent 4 (Cameras) challenges with technical capability +S2-H04: "disconfirm" → content: + original_proposal: "Manual entry only" + challenge: "Camera feeds can auto-detect equipment (tender, electronics) via CV" + evidence: ["OpenCV boat equipment detection models"] + alternative: "Hybrid: Manual + camera-assisted auto-detection" + +# Agent 2 revises proposal +S2-H02: "agree" → content: + revised_proposal: "Inventory tracking: Manual entry + camera-assisted CV detection" + integration_point: "Use S2-H04's camera feed for equipment detection" +``` + +### API Integration Conflict Example + +```yaml +# Agent 3 (Maintenance) proposes maintenance log API +S2-H03: "propose" → POST /api/maintenance/{boat_id}/logs + +# Agent 7 (Search UX) challenges completeness +S2-H07: "query-if" → content: + question: "Does maintenance API support date-range queries for yearly reporting?" + reasoning: "Search UI needs to filter by date for expense rollups" + +# Agent 3 confirms and extends API +S2-H03: "confirm" → content: + api_extended: "GET /api/maintenance/{boat_id}/logs?start_date=&end_date=&category=" + integration: "Supports S2-H06 expense rollup queries" +``` + +### IF.TTT Compliance + +Every message MUST include: +- **citation_ids:** Links to design docs, codebase references +- **confidence:** Explicit score (0.0-1.0) +- **evidence:** File:line references from NaviDocs codebase +- **cost_tokens:** Token consumption (IF.optimise tracking) + +--- + +## IF.bus Integration Pattern + +### Event Bus Design +```javascript +// server/services/event-bus.js +class EventBus { + async publish(topic, event) { + // Publish to Redis pub/sub + // Trigger webhooks (Home Assistant) + // Queue background jobs + // Log to audit trail + } + + async subscribe(topic, handler) { + // Subscribe to Redis channel + // Handle incoming events + } +} + +// Topics for NaviDocs +const TOPICS = { + WARRANTY_EXPIRING: 'warranty.expiring', + DOCUMENT_UPLOADED: 'document.uploaded', + SALE_INITIATED: 'sale.initiated', + BOAT_TRANSFERRED: 'boat.transferred' +}; +``` + +### Webhook Framework +```javascript +// server/services/webhook.service.js +class WebhookService { + async sendWebhook(url, event) { + // POST event to external system + // Retry on failure (exponential backoff) + // Log delivery status + } + + async registerWebhook(organizationId, url, topics) { + // Store webhook subscription + // Validate URL reachability + } +} +``` + +--- + +## Output Format + +### Deliverable 1: Technical Architecture Document +**File:** `session-2-architecture.md` + +**Structure:** +```markdown +# NaviDocs Yacht Sales Technical Architecture + +## System Overview +[High-level architecture diagram] + +## Database Schema Changes +[Agent 9: Migration scripts] + +## API Endpoints (New) +### Warranty Tracking +- POST /api/warranties +- GET /api/warranties/:id +- PUT /api/warranties/:id +- DELETE /api/warranties/:id +- GET /api/warranties/expiring + +### Sale Workflow +- POST /api/sales +- GET /api/sales/:id/documents +- POST /api/sales/:id/transfer + +### Webhooks +- POST /api/webhooks/register +- GET /api/webhooks +- DELETE /api/webhooks/:id + +## Integration Architecture +### Home Assistant +[Agent 4: Webhook + MQTT design] + +### MLS Platforms +[Agent 6: API contracts] + +### Notification System +[Agent 8: Email/SMS/Push architecture] + +## Security Remediation +[Agent 7: Security fixes] + +## Offline Mode +[Agent 5: PWA caching strategy] + +## 4-Week Sprint Plan +[Agent 10: Gantt chart + tasks] +``` + +### Deliverable 2: Implementation Tasks +**File:** `session-2-sprint-plan.md` + +**Structure:** +```markdown +# 4-Week Implementation Sprint + +## Week 1: Foundation (Nov 13-19) +### Day 1-2: Database Migrations +- [ ] Create warranty_tracking table +- [ ] Create sale_workflows table +- [ ] Create webhooks table +- [ ] Create notification_templates table + +### Day 3-4: Event Bus +- [ ] Implement IF.bus service +- [ ] Create webhook delivery system +- [ ] Add Redis pub/sub + +### Day 5: Security Fixes +- [ ] Protect DELETE endpoints +- [ ] Enforce auth on all routes +- [ ] Fix stats endpoint (tenant isolation) + +## Week 2: Core Integrations (Nov 20-26) +### Day 1-2: Warranty Tracking +- [ ] Warranty CRUD APIs +- [ ] Expiration alert background job +- [ ] Claim package generator + +### Day 3-5: Home Assistant +- [ ] Webhook receiver endpoint +- [ ] MQTT broker integration +- [ ] Camera system connector + +## Week 3: Automation (Nov 27 - Dec 3) +### Day 1-2: Sale Workflow +- [ ] As-built package generator +- [ ] Document transfer API +- [ ] Buyer handoff workflow + +### Day 3-4: Notifications +- [ ] Email service implementation +- [ ] SMS gateway integration +- [ ] In-app notification center + +### Day 5: Offline Mode +- [ ] Service worker caching +- [ ] Offline sync queue + +## Week 4: Polish & Deploy (Dec 4-10) +### Day 1-2: MLS Integration +- [ ] YachtWorld API connector +- [ ] Boat Trader sync + +### Day 3: Testing +- [ ] E2E test suite +- [ ] Security audit +- [ ] Performance testing + +### Day 4-5: Deployment +- [ ] Sales demo environment +- [ ] Production deployment +- [ ] Riviera Plaisance pilot +``` + +### Deliverable 3: Code Templates +**File:** `session-2-code-templates/` + +**Files:** +- `warranty.model.js` - Warranty database model +- `warranty.routes.js` - API endpoints +- `warranty.service.js` - Business logic +- `webhook.service.js` - Webhook delivery +- `event-bus.service.js` - IF.bus implementation +- `notification.service.js` - Alert system + +### Deliverable 4: Session Handoff +**File:** `session-2-handoff.md` + +**Structure:** +```markdown +# Session 2 Handoff to Session 3 + +## Mission Accomplished +- [x] Architecture designed +- [x] Sprint plan created +- [x] Code templates generated +- [x] Security audit complete + +## Key Findings for Session 3 (UX/Sales) +1. Warranty tracking saves €8K-€33K per yacht (ROI calculator input) +2. Home Assistant integration enables remote monitoring +3. 4-week implementation timeline (Week 1: Foundation, Week 4: Deploy) +4. Security fixes required before demo (DELETE endpoint, auth) + +## Blockers for Next Session +- [ ] Need UI/UX mockups for warranty dashboard (Session 3) +- [ ] Sales pitch requires demo script (Session 3) + +## Token Consumption +- Total: 62,800 tokens ($1.42) +- Sonnet: 9,500 tokens +- Haiku: 53,300 tokens +- Efficiency: 68% Haiku delegation ✅ + +## Evidence Quality +- Code templates: 6 files created +- API endpoints: 15 new routes documented +- Migrations: 4 SQL scripts ready +- All architecture verified against NaviDocs codebase + +## Next Session Input +Read: session-2-architecture.md, session-2-sprint-plan.md +Focus: Sales pitch, demo script, ROI calculator, objection handling +``` + +--- + +## IF.TTT Compliance Checklist + +- [ ] All code templates include file:line references +- [ ] API specs link to NaviDocs existing endpoints +- [ ] Database migrations tested (rollback verified) +- [ ] Security audit cites OWASP Top 10 +- [ ] Sprint plan has acceptance criteria per task +- [ ] Evidence artifacts stored in `/intelligence/session-2/` + +--- + +## Success Criteria + +**Minimum Viable Output:** +- Database migrations for warranty tracking +- 4-week sprint plan with dependencies +- Home Assistant integration architecture +- Security remediation plan (5 vulnerabilities) +- Code templates for warranty + webhook systems + +**Stretch Goals:** +- MLS integration specs (YachtWorld, Boat Trader) +- Offline mode PWA architecture +- Notification system design (email/SMS/push) + +--- + +**Start Command:** Deploy to Claude Code Cloud after Session 1 complete +**End Condition:** All deliverables committed to `dannystocker/navidocs` repo under `intelligence/session-2/` diff --git a/builder/prompts/research/session-3-ux-sales.md b/builder/prompts/research/session-3-ux-sales.md new file mode 100644 index 0000000..e11fa64 --- /dev/null +++ b/builder/prompts/research/session-3-ux-sales.md @@ -0,0 +1,601 @@ +# Cloud Session 3: UX/Sales Enablement +## NaviDocs Riviera Plaisance Pitch Materials + +**Session Type:** UX Designer + Sales Strategist +**Lead Agent:** Sonnet (design + persuasion) +**Swarm Size:** 10 Haiku agents +**Token Budget:** $15 (7.5K Sonnet + 50K Haiku) +**Output:** Pitch deck + demo script + ROI calculator + +--- + +## Mission Statement + +Create sales pitch demonstrating **NaviDocs as sticky daily-use app** (not passive doc vault) that owners actually use because it solves real problems: inventory tracking, camera monitoring, maintenance reminders, expense visibility. + +--- + +## Context (Read First) + +**Prerequisites:** +1. Read `intelligence/session-1/session-1-market-analysis.md` +2. Read `intelligence/session-2/session-2-architecture.md` +3. Read `intelligence/session-2/session-2-sprint-plan.md` + +**Meeting Context:** +- Audience: Sylvain (Riviera Plaisance yacht sales agent) +- Goal: Include NaviDocs with every boat sale +- Time: 15-minute presentation + 5-minute demo +- Constraints: Technical audience (understands marine documentation) + +**Key Value Propositions (Sticky Engagement Model):** +- **For Owners (daily use):** Camera check, maintenance reminders, expense tracking, crew contacts +- **For Owners (resale):** Inventory tracking prevents €15K-€50K forgotten value +- **For Brokers:** Sticky product = owners refer friends = more sales for Sylvain +- **Differentiation:** Only boat app with daily engagement + perfect documentation +- **Business model:** Included with every Riviera boat (Tesla app model) + +--- + + +## Agent Identity & Check-In Protocol + +**YOU ARE:** Sonnet coordinator for Session 3 (UX/Sales) + +**YOUR HAIKU SWARM:** You have 10 Haiku agents available. Use as many as needed (not required to use all 10). + +**AGENT IDENTITY SYSTEM:** +When spawning a Haiku agent, assign it an identity: `S3-H01` through `S3-H10` +Each agent MUST: +1. **Check in** at start: "I am S3-H03, assigned to [task name]" +2. **Reference their task** by searching this document for "Agent 3:" (matching their number) +3. **Retain identity** throughout execution +4. **Report completion** with identity: "S3-H03 complete: [deliverable summary]" + +**TASK DEPENDENCIES:** +- Most agents can run in parallel +- Agent 10 typically synthesizes results from Agents 1-9 (must wait for completion) + +--- + +## Your Tasks (Spawn 10 Haiku Agents in Parallel) + +### Agent 1: Pitch Deck Structure (Sticky Engagement Focus) +**AGENT ID:** S3-H01 +** +**Design:** +- Slide 1: Problem - "Owners ignore passive doc vaults" (show app abandonment stats) +- Slide 2: Solution - "Daily-use app they actually open" (camera, maintenance, inventory) +- Slide 3: Sticky features demo - Camera check, maintenance reminder, expense tracking +- Slide 4: Resale value protection - €15K-€50K inventory tracking ROI +- Slide 5: Broker benefit - Sticky product = referrals = more Riviera sales +- Slide 6: Business model - Included with every boat (like Tesla app) +- Slide 7: 4-week timeline + pilot program + +**Deliverable:** Pitch deck emphasizing daily engagement, NOT passive documentation + +### Agent 2: Demo Script Writer (Daily Use Scenarios) +**AGENT ID:** S3-H02 +** +**Create:** +- 5-minute demo showing DAILY engagement (not just sale-time docs) +- Screen 1: Camera check - "Is my boat OK?" (2 mins) +- Screen 2: Maintenance reminder - "Engine service due" (1 min) +- Screen 3: Inventory search - "Find tender warranty" with impeccable UX (1 min) +- Screen 4: Expense tracking - "I've spent €18K this year" (1 min) +- Key message: Owners open this app WEEKLY, not just at resale + +**Deliverable:** Demo script showing sticky engagement, NOT passive vault + +### Agent 3: ROI Calculator Designer (Inventory Focus) +**AGENT ID:** S3-H03 +** +**Build:** +- Input fields: boat purchase price, annual upgrades (€5K-€20K typical) +- Inventory forgotten at resale: tender €15K, electronics €8K, blinds €3K +- Total forgotten value over 10-year ownership: €30K-€50K +- NaviDocs cost: €15/month × 120 months = €1,800 +- ROI: €30K-€50K saved - €1.8K cost = €28K-€48K net benefit +- Comparison: With vs without inventory tracking + +**Deliverable:** ROI calculator showing inventory tracking value (primary) + maintenance reminders (secondary) + +### Agent 4: Objection Handling Playbook +**AGENT ID:** S3-H04 +** +**Research:** +- Common broker objections (from Session 1 research) +- Responses with data backing +- Competitive differentiation points +- Risk mitigation talking points + +**Deliverable:** Objection handling guide (Q&A format) + +### Agent 5: Pricing Strategy Presentation +**AGENT ID:** S3-H05 +** +**Design:** +- Per-yacht pricing model (€50-€200/yacht) +- Brokerage bulk pricing (10+ yachts) +- One-time setup fee vs recurring +- Free pilot program offer (Riviera Plaisance) + +**Deliverable:** Pricing slide with 3 tiers + +### Agent 6: Competitive Differentiation +**AGENT ID:** S3-H06 +** +**Compile:** +- NaviDocs vs 5 top competitors (from Session 1) +- Feature comparison table +- Unique selling points (Home Assistant, multi-jurisdiction) +- Visual comparison matrix + +**Deliverable:** Competitive matrix slide + +### Agent 7: Technical Architecture Visualization +**AGENT ID:** S3-H07 +** +**Create:** +- System architecture diagram (non-technical) +- Integration points (Home Assistant, cameras, offline) +- Data flow (document upload → OCR → warranty tracking → alerts) +- Security highlights (multi-tenant, encrypted) + +**Deliverable:** Architecture diagram (Mermaid or visual) + +### Agent 8: Case Study Writer +**AGENT ID:** S3-H08 +** +**Draft:** +- Hypothetical yacht sale scenario +- Before NaviDocs: 6 hours documentation prep, €8K warranty miss +- After NaviDocs: 20-minute automated package, €33K warranty captured +- Buyer satisfaction increase + +**Deliverable:** One-page case study + +### Agent 9: Visual Design System +**AGENT ID:** S3-H09 +** +**Define:** +- Color palette (nautical theme: blues, whites) +- Typography (readable, professional) +- Icon set (warranties, documents, alerts) +- Slide layout templates + +**Deliverable:** Design system guide + +### Agent 10: Sales Collateral Package +**AGENT ID:** S3-H10 +** +**Compile:** +- One-pager (leave-behind document) +- Email follow-up template +- Pilot program agreement draft +- Next steps checklist + +**Deliverable:** Sales collateral bundle + +--- + +## Intra-Agent Communication Protocol (IF.bus) + +**Based on:** InfraFabric S² multi-swarm coordination (3,563x faster than git polling) + +### IFMessage Schema + +Every agent-to-agent message follows this structure: + +```json +{ + "performative": "inform", // FIPA-ACL: inform, request, query-if, confirm, disconfirm, ESCALATE + "sender": "if://agent/session-3/haiku-Y", + "receiver": ["if://agent/session-3/haiku-Z"], + "conversation_id": "if://conversation/navidocs-session-3-2025-11-13", + "content": { + "claim": "[Your pitch/objection finding]", + "evidence": ["[Market data, competitor analysis, customer research]"], + "confidence": 0.85, // 0.0-1.0 + "cost_tokens": 1247 + }, + "citation_ids": ["if://citation/uuid"], + "timestamp": "2025-11-13T10:00:00Z", + "sequence_num": 1 +} +``` + +### Speech Acts (Performatives) + +**inform:** Share pitch content or objection research +- Example: "S3-H01 informs S3-H05: Pitch emphasizes €8K-€33K warranty savings" + +**request:** Ask another agent for market validation +- Example: "S3-H03 requests S3-H05: Validate ROI assumptions with competitor pricing" + +**disconfirm:** Challenge pitch claim with evidence +- Example: "S3-H05 disconfirms S3-H01: Warranty savings claim needs 2nd source (only €8K cited)" + +**confirm:** Validate pitch claim with external evidence +- Example: "S3-H06 confirms S3-H03: ROI calculator inputs match Session 1 research" + +**ESCALATE:** Flag critical objection that requires resolution +- Example: "S3-H05 ESCALATES: Broker pricing objection not addressed in pitch" + +### Communication Flow (This Session) + +``` +S3-H01 (Pitch) ──→ S3-H05 (Objections) ──→ S3-H10 (adversarial testing) +S3-H03 (ROI) ────→ S3-H05 (Validate) ────→ S3-H10 +S3-H04 (Demo) ───→ S3-H06 (Case Study) ──→ S3-H10 +``` + +**Key Patterns:** +1. **Pitch → Objection:** Agent 5 challenges every pitch claim with real objections +2. **ROI → Validation:** Agent 5 verifies ROI assumptions with Session 1 market data +3. **Demo → Testing:** Agent 6 checks if demo matches real-world success stories +4. **Agent 10 Synthesis:** Ensures pitch is airtight before presentation + +### Adversarial Testing Example + +```yaml +# Agent 1 (Pitch Deck) proposes value proposition +S3-H01: "inform" → content: + claim: "NaviDocs enables €8K-€33K warranty savings per yacht" + evidence: ["Session 1 market analysis"] + confidence: 0.85 + +# Agent 5 (Objections) challenges claim completeness +S3-H05: "disconfirm" → content: + original_claim: "€8K-€33K warranty savings" + objection: "Which brokers actually claim this? Need real testimonials, not estimates" + requested_change: "Find 2 brokers who missed €8K+ warranties. Use as proof point." + evidence: ["Broker interviews required"] + +# Agent 1 strengthens claim +S3-H01: "confirm" → content: + revised_claim: "NaviDocs prevents warranty losses (case study: Broker X missed €15K tender)" + evidence: [ + "Broker interview transcript", + "YachtWorld resale comparison (boat with/without tender)", + "Session 1 pain point research" + ] + confidence: 0.95 +``` + +### ROI Calculator Validation Example + +```yaml +# Agent 3 (ROI Calculator) proposes model +S3-H03: "propose" → content: + calculation: "ROI = (Warranty Savings + Time Savings) - NaviDocs Cost" + inputs: { + warranty_savings: "€8K-€33K per yacht", + time_savings: "6 hours manual → 20 minutes automated", + navidocs_cost: "€15/month × 120 months" + } + +# Agent 5 (Objections) validates assumptions +S3-H05: "query-if" → content: + question: "Are time savings (6→20 mins) validated with actual brokers?" + reasoning: "If brokers claim 8 hours, our 20-min estimate is unrealistic" + request: "Get time commitment estimate from Sylvain or 2 other Riviera brokers" + +# Agent 3 confirms with validation +S3-H03: "confirm" → content: + validated_inputs: { + time_savings: "Confirmed: Riviera broker spends 5.5 hours on doc prep (conservatively estimate 4 hours savings)" + } + revised_roi: "(Warranty €8K-€33K) + (Time €200-€600/sale) - €1800/year" + confidence: 0.92 +``` + +### Demo Script Credibility Example + +```yaml +# Agent 4 (Demo Script) proposes key screens +S3-H04: "propose" → content: + screens: ["Dashboard", "Warranty Detail", "Claim Package", "Home Assistant"] + timing: "5 minutes total" + +# Agent 6 (Case Study) challenges realism +S3-H06: "disconfirm" → content: + concern: "Demo shows perfect claim package generation (15 mins), but real workflow?" + challenge: "What if boat has missing docs? Demo assumes complete warranty archive." + recommendation: "Add realistic scenario: Missing engine receipt, still generates partial claim" + +# Agent 4 revises demo +S3-H04: "agree" → content: + revised_demo: "Screen 1: Complete case (Azimut 55S) - best case, Screen 2: Sunseeker 40 with missing docs - realistic case" + messaging: "NaviDocs works even with incomplete records, fills gaps intelligently" +``` + +### IF.TTT Compliance + +Every message MUST include: +- **citation_ids:** Links to Session 1 research, competitor analysis +- **confidence:** Explicit score (0.0-1.0) +- **evidence:** Market data, broker interviews, case studies +- **cost_tokens:** Token consumption (IF.optimise tracking) + +--- + +## Presentation Flow (15 Minutes) + +### Opening (2 minutes) +- **Hook:** "How much is €33,000 worth to you on a single yacht sale?" +- **Problem:** Brokers lose 6 hours per sale to documentation, miss warranty claims +- **Credibility:** NaviDocs is production-ready, multi-tenant architecture + +### Market Opportunity (3 minutes) +- **Market size:** [Session 1 findings] +- **Broker pain points:** Manual documentation, jurisdictional complexity +- **Buyer expectations:** Turnkey documentation packages increase sale value + +### NaviDocs Solution (5 minutes) +- **Core features:** OCR, warranty tracking, expiration alerts, claim generation +- **Integration:** Home Assistant (remote monitoring), offline mode (onboard access) +- **Automation:** As-built package (6 hours → 20 minutes) + +### ROI Demonstration (3 minutes) +- **Warranty savings:** €8K-€33K per yacht (calculator demo) +- **Time savings:** 6 hours manual → 20 minutes automated +- **Value proposition:** Include NaviDocs with every sale = premium service + +### Implementation Plan (2 minutes) +- **Timeline:** 4-week sprint (foundation → deploy) +- **Pilot program:** Free for Riviera Plaisance (first 5 yachts) +- **Support:** Onboarding, training, ongoing maintenance + +--- + +## Demo Script (5 Minutes) + +### Screen 1: Dashboard (30 seconds) +**Show:** Multi-yacht overview, warranty status indicators +**Say:** "Broker sees all yachts, warranty expiration alerts at a glance" + +### Screen 2: Yacht Detail (1 minute) +**Show:** Single yacht, document library, warranty timeline +**Say:** "€400K-€800K in active warranties tracked, expiration alerts prevent €8K-€33K losses" + +### Screen 3: Warranty Alert (1 minute) +**Show:** 30-day expiration warning, claim package generator +**Say:** "System alerts 90, 30, 14 days before expiration, auto-generates claim package" + +### Screen 4: Claim Package (1 minute) +**Show:** PDF with warranty docs, invoice, jurisdiction-specific forms +**Say:** "6 hours manual work → 15 minutes automated, jurisdiction-aware (France, Italy, Spain, etc.)" + +### Screen 5: Home Assistant Integration (1 minute) +**Show:** Webhook configuration, camera feed integration +**Say:** "Remote monitoring, onboard sensors, security cameras integrated" + +### Screen 6: Offline Mode (30 seconds) +**Show:** Service worker, critical manual access +**Say:** "Works onboard without internet, syncs when online" + +--- + +## ROI Calculator Specifications + +### Input Fields +1. **Yacht Purchase Price** (€300K - €5M) +2. **Number of Active Warranties** (10-50 typical) +3. **Average Warranty Value** (€8K - €50K) +4. **Annual Warranty Claims Expected** (1-5) +5. **Broker Documentation Hours/Sale** (6 hours typical) +6. **Broker Hourly Rate** (€50-€150) + +### Calculations +- **Warranty Savings (3 years):** Claims × Success Rate Increase × Avg Value +- **Time Savings (3 years):** Hours Saved × Hourly Rate × Sales/Year +- **Missed Claim Prevention:** (1 - NaviDocs) × Claim Value × 3 Years +- **Total ROI:** (Savings + Time) - NaviDocs Cost + +### Output Display +- **3-Year Total Savings:** €XX,XXX +- **Break-Even Point:** X months +- **ROI Percentage:** XXX% +- **Comparison Chart:** Manual vs Automated + +--- + +## Objection Handling Playbook + +### Objection 1: "We already have a documentation system" +**Response:** +- "How does it handle warranty expiration alerts?" +- "Can it generate jurisdiction-specific claim packages?" +- NaviDocs integrates with existing CRM (Salesforce, HubSpot) + +### Objection 2: "Too expensive for our brokerage" +**Response:** +- ROI calculator shows break-even in [X] months +- Free pilot program (first 5 yachts) +- Per-yacht pricing scales with your business + +### Objection 3: "Brokers won't adopt new software" +**Response:** +- 5-minute demo proves ease of use +- Onboarding training included +- Time savings (6 hours → 20 minutes) drives adoption + +### Objection 4: "What about data security?" +**Response:** +- Multi-tenant architecture (isolated databases) +- JWT authentication + bcrypt password hashing +- Audit logging for compliance (GDPR ready) + +### Objection 5: "Implementation timeline too long" +**Response:** +- 4-week sprint to production-ready +- Pilot program starts Week 3 (warranty tracking live) +- Incremental rollout (core features first, integrations later) + +--- + +## Pricing Strategy + +### Tier 1: Solo Broker +- **Price:** €99/month +- **Included:** Up to 5 yachts, basic warranty tracking, email support +- **Target:** Individual yacht sales agents + +### Tier 2: Brokerage +- **Price:** €299/month +- **Included:** Up to 25 yachts, Home Assistant integration, priority support +- **Target:** Small brokerages (Riviera Plaisance) + +### Tier 3: Enterprise +- **Price:** Custom (€500+/month) +- **Included:** Unlimited yachts, MLS integration, white-label option, dedicated support +- **Target:** Large brokerages, charter fleets + +### Pilot Program (Riviera Plaisance) +- **Offer:** Free Tier 2 for 3 months (first 5 yachts) +- **Commitment:** Feedback, case study participation +- **Conversion:** 50% discount first year if adopted + +--- + +## Output Format + +### Deliverable 1: Pitch Deck +**File:** `session-3-pitch-deck.md` (Markdown with Mermaid diagrams) + +**Structure:** +```markdown +# NaviDocs Yacht Sales Pitch Deck +## Riviera Plaisance Presentation + +### Slide 1: The €33,000 Question +[Hook: warranty tracking ROI] + +### Slide 2: Broker Documentation Pain +[Market research from Session 1] + +### Slide 3: NaviDocs Solution Overview +[Feature highlights with icons] + +### Slide 4: Warranty Tracking ROI +[Calculator demo, €8K-€33K savings] + +### Slide 5: Technical Architecture +[Mermaid diagram: Home Assistant, offline mode] + +### Slide 6: 4-Week Implementation Roadmap +[Gantt chart from Session 2] + +### Slide 7: Pilot Program Offer +[Pricing, free trial, next steps] + +**Appendix: Demo Screenshots** +[6 screens with annotations] +``` + +### Deliverable 2: Demo Script +**File:** `session-3-demo-script.md` + +**Structure:** +```markdown +# NaviDocs Live Demo Script (5 Minutes) + +## Setup Instructions +- Browser: Chrome/Firefox +- URL: https://demo.navidocs.app +- Login: demo@rivieraplaisance.com / DemoPass123 +- Pre-loaded yacht: "Azimut 55S" (€800K, 15 warranties) + +## Screen-by-Screen Walkthrough +### [0:00-0:30] Dashboard +**Action:** Show multi-yacht overview +**Say:** "Broker dashboard shows all yachts, warranty status at a glance..." +**Highlight:** Red badge on Azimut (warranty expiring in 28 days) + +### [0:30-1:30] Yacht Detail +**Action:** Click Azimut 55S +**Say:** "€760K in active warranties tracked, system prevents €8K-€33K losses..." +**Highlight:** Warranty timeline, document library + +[... continue for all 6 screens] +``` + +### Deliverable 3: ROI Calculator +**File:** `session-3-roi-calculator.html` (web app) or `.xlsx` (spreadsheet) + +**Implementation:** +```html + + +NaviDocs ROI Calculator + +

NaviDocs Yacht Sales ROI Calculator

+
+ + + + + + + [... all input fields] + + +
+ +
+

3-Year Savings: €

+

Break-Even: months

+ +
+ + + + +``` + +### Deliverable 4: Sales Collateral Package +**File:** `session-3-sales-collateral/` + +**Files:** +- `one-pager.pdf` - Leave-behind document (1 page, visual) +- `email-follow-up-template.md` - Post-meeting email +- `pilot-agreement.md` - Free trial terms +- `objection-handling.md` - Q&A playbook + +--- + +## IF.TTT Compliance Checklist + +- [ ] All ROI calculations cite Session 1 market research +- [ ] Demo script references actual NaviDocs features (verify against codebase) +- [ ] Pricing strategy validated against competitor analysis (Session 1) +- [ ] Technical architecture diagram matches Session 2 specs +- [ ] Evidence artifacts stored in `/intelligence/session-3/` + +--- + +## Success Criteria + +**Minimum Viable Output:** +- 7-slide pitch deck (problem → solution → ROI → timeline → pricing) +- 5-minute demo script with screen annotations +- Working ROI calculator (web or spreadsheet) +- Objection handling playbook (5+ objections) + +**Stretch Goals:** +- Video demo recording (screencast with voiceover) +- Interactive ROI calculator (embedded in pitch deck) +- Animated architecture diagram (Mermaid with transitions) +- Printed sales collateral (one-pager PDF) + +--- + +**Start Command:** Deploy to Claude Code Cloud after Session 2 complete +**End Condition:** All deliverables committed to `dannystocker/navidocs` repo under `intelligence/session-3/` diff --git a/builder/prompts/research/session-4-implementation-planning.md b/builder/prompts/research/session-4-implementation-planning.md new file mode 100644 index 0000000..960ed88 --- /dev/null +++ b/builder/prompts/research/session-4-implementation-planning.md @@ -0,0 +1,1431 @@ +# Cloud Session 4: Implementation Planning +## NaviDocs Sticky Engagement Features - 4-Week Sprint + +**Session Type:** Project Manager + DevOps Specialist +**Lead Agent:** Sonnet (planning + coordination) +**Swarm Size:** 10 Haiku agents +**Token Budget:** $15 (7.5K Sonnet + 50K Haiku) +**Output:** Sprint plan for inventory tracking + cameras + maintenance + contacts + search UX + +--- + +## Mission Statement + +Create detailed 4-week implementation plan with task breakdown, dependencies, acceptance criteria, and testing strategy for NaviDocs yacht sales features. + +--- + +## Context (Read First) + +**Prerequisites:** +1. Read `intelligence/session-2/session-2-architecture.md` +2. Read `intelligence/session-2/session-2-sprint-plan.md` +3. Read `server/db/schema.sql` - Current database structure +4. Read `server/routes/*.js` - Existing API patterns + +**Technical Constraints:** +- Backend: Express.js (must maintain compatibility) +- Database: SQLite (migration-friendly approach) +- Queue: BullMQ (extend existing workers) +- Frontend: Vue 3 (add new components, don't break existing) + +**Team Size:** 1 developer (solo sprint) +**Working Hours:** 6-8 hours/day +**Timeline:** 4 weeks (Nov 13 - Dec 10) + +--- + +## PHASE 1: Helper Agents (START IMMEDIATELY - ASSIST SESSIONS 1 & 3) + +**Mission:** While waiting for Sessions 1+2+3 to complete, provide active project management assistance to accelerate overall coordination and quality. + +**NO DEPENDENCIES:** All Phase 1 agents can start immediately (no need to wait for other sessions). + +--- + +### Agent 0A: Research Coordination Dashboard (Real-Time Progress Tracking) +**AGENT ID:** S4-H0A +**START:** Immediately (no dependencies) + +**Assist Session 1 (Market Research):** +- **Agent progress tracker:** Monitor which of the 10 Session 1 agents have completed their tasks +- **Completion status:** Track deliverables (market-analysis.md, citations.json, handoff.md) +- **Blocker detection:** Identify if any Session 1 agent is stuck or over-budget +- **Estimated completion:** Predict when Session 1 will finish based on current progress + +**Dashboard Format:** +```yaml +# intelligence/session-4/coordination-dashboard.md +## Session 1 Progress (Updated Every 5 Minutes) + +Agents Complete: 7/10 (70%) +Deliverables: + - market-analysis.md: ✅ COMPLETE (87KB) + - session-1-citations.json: 🟡 IN PROGRESS (43 citations so far) + - session-1-handoff.md: ⏳ PENDING (Agent 10 not started) + +Estimated Completion: 15 minutes + +Blockers: None + +Token Usage: $12.50 / $15.00 budget (83% consumed) +``` + +**Deliverable:** `intelligence/session-4/coordination-dashboard.md` (updated every 5 minutes) + +--- + +### Agent 0B: Citation Quality Checker (Pre-Validate Before Session 5) +**AGENT ID:** S4-H0B +**START:** Immediately (no dependencies) + +**Assist Sessions 1, 2, 3 (Pre-Validation):** +- **Citation format check:** Validate citations follow IF.TTT schema (citation_id, sources, confidence_score, etc.) +- **Source quality scoring:** Verify primary sources have 9-10 credibility (not tertiary) +- **Multi-source validation:** Check high-confidence claims (≥0.9) have ≥2 sources +- **SHA-256 verification:** Confirm web URLs have SHA-256 hashes (tamper detection) +- **Broken link detection:** Test cited URLs return 200 OK (flag dead links) + +**Example Feedback:** +```yaml +# intelligence/session-4/citation-quality-report.md + +## Session 1 Citation Quality (43 citations reviewed) + +✅ PASS (38 citations): + - All have if://citation/ IDs + - Primary sources properly cited + - ≥2 sources for high-confidence claims + +⚠️ NEEDS ATTENTION (5 citations): + 1. Citation: if://citation/broker-count-med + - Issue: Single source (need 2nd corroboration) + - Recommendation: Add Boat International report as 2nd source + + 2. Citation: if://citation/warranty-costs + - Issue: Missing SHA-256 hash for YachtWorld URL + - Recommendation: Run `sha256sum` on fetched page + + 3. Citation: if://citation/competitor-pricing + - Issue: Confidence 0.95 but only secondary sources (credibility 7-8) + - Recommendation: Lower confidence to 0.85 or find primary source +``` + +**Value:** Catch citation issues BEFORE Session 5 validation (faster feedback loop, less rework) + +**Deliverable:** `intelligence/session-4/citation-quality-report.md` (updated as sessions work) + +--- + +### Agent 0C: Demo Script Structure (Outline Before Session 1 Data) +**AGENT ID:** S4-H0C +**START:** Immediately (no dependencies) + +**Assist Session 3 (UX/Sales):** +- **Demo flow research:** Study winning software demo structures (problem → solution → demo → ROI → close) +- **Generic outline:** Create demo script template with placeholders for Session 1 data +- **Objection handling:** Research common yacht owner objections (cost, complexity, time investment) +- **Storytelling techniques:** Identify emotional hooks (peace of mind, warranty savings, resale value) + +**Generic Demo Outline (Before Session 1 Data):** +```markdown +# NaviDocs Demo Script (Template) + +## 1. Opening (2 min) +- Pain point: "[INSERT: Top pain point from Session 1]" +- Teaser: "What if you could [INSERT: Key benefit]?" + +## 2. Problem Deep Dive (3 min) +- Story: "[INSERT: Yacht owner story from Session 1]" +- Consequence: "Without NaviDocs, owners lose [INSERT: €X savings]" + +## 3. Solution Demo (10 min) +- Feature 1: [INSERT: Sticky feature from Session 2] + - Show: [Screen recording placeholder] + - Benefit: [INSERT: Time/money saved] + +## 4. ROI Reveal (5 min) +- Calculator: [INSERT: Session 1 warranty savings data] +- Comparison: "That's [X] hours saved per year" + +## 5. Close (2 min) +- Call to action: "Sign up for Riviera pilot" +- Objection handling: [INSERT: Top 3 objections from Session 1] +``` + +**When Session 1 Completes:** +- Agent 0C fills placeholders with real data +- Creates final polished demo script for Session 3 + +**Deliverable:** `intelligence/session-4/demo-script-template.md` (ready for Session 1 data integration) + +--- + +### Agent 0D: Cross-Session Dependency Tracker (Visual Dependency Graph) +**AGENT ID:** S4-H0D +**START:** Immediately (no dependencies) + +**Monitor All Sessions:** +- **Dependency mapping:** Track which sessions are blocking others +- **Critical path visualization:** Identify slowest session (bottleneck) +- **Parallel work opportunities:** Find tasks that can run concurrently +- **Completion predictions:** Estimate when each session will finish + +**Dependency Graph (Mermaid):** +```mermaid +graph TD + S1[Session 1: Market Research] --> S2[Session 2: Technical Architecture] + S1 --> S3[Session 3: UX/Sales] + S2 --> S3 + S1 --> S4[Session 4: Implementation Planning] + S2 --> S4 + S3 --> S4 + S1 --> S5[Session 5: Guardian Validation] + S2 --> S5 + S3 --> S5 + S4 --> S5 + + style S1 fill:#90EE90 + style S2 fill:#FFD700 + style S3 fill:#FFD700 + style S4 fill:#FFD700 + style S5 fill:#87CEEB +``` + +**Real-Time Status Updates:** +```yaml +# intelligence/session-4/dependency-status.md + +## Critical Path Analysis (Updated Every 5 Minutes) + +SLOWEST SESSION: Session 1 (30 min remaining) + - Blocks: Session 2 (Agent 10), Session 3 (Agents 8-10), Session 4 (All agents) + +PARALLEL WORK: + - Session 2 Phase 1 agents (0A-0D): ✅ RUNNING (assisting Session 1) + - Session 5 Phase 1 agents (0A-0C): ✅ RUNNING (deploying standards) + +ESTIMATED COMPLETION: + - Session 1: 13:30 UTC + - Session 2: 14:00 UTC (depends on Session 1) + - Session 3: 14:30 UTC (depends on Sessions 1+2) + - Session 4: 15:00 UTC (depends on Sessions 1+2+3) + - Session 5: 16:30 UTC (depends on all) +``` + +**Deliverable:** `intelligence/session-4/dependency-status.md` (updated every 5 minutes with Mermaid graph) + +--- + + +## Agent Identity & Check-In Protocol + +**YOU ARE:** Sonnet coordinator for Session 4 (Implementation Planning) + +**YOUR HAIKU SWARM:** You have 10 Haiku agents available. Use as many as needed (not required to use all 10). + +**AGENT IDENTITY SYSTEM:** +When spawning a Haiku agent, assign it an identity: `S4-H01` through `S4-H10` +Each agent MUST: +1. **Check in** at start: "I am S4-H03, assigned to [task name]" +2. **Reference their task** by searching this document for "Agent 3:" (matching their number) +3. **Retain identity** throughout execution +4. **Report completion** with identity: "S4-H03 complete: [deliverable summary]" + +**TASK DEPENDENCIES:** +- Most agents can run in parallel +- Agent 10 typically synthesizes results from Agents 1-9 (must wait for completion) + +--- + +## Your Tasks (Spawn 10 Haiku Agents in Parallel) + +### Agent 1: Week 1 Task Breakdown +**AGENT ID:** S4-H01 +** +**Create:** +- Day-by-day tasks for foundation week +- Database migrations (warranty tracking, webhooks, notifications) +- Event bus implementation (IF.bus pattern) +- Security fixes (5 vulnerabilities from handover doc) +- Time estimates per task (granular, 2-4 hour blocks) + +**Deliverable:** Week 1 detailed schedule with dependencies + +### Agent 2: Week 2 Task Breakdown +**AGENT ID:** S4-H02 +** +**Create:** +- Day-by-day tasks for core integrations +- Warranty tracking APIs (CRUD + expiration alerts) +- Home Assistant webhook integration +- Background job for expiration checks +- Time estimates + dependency mapping + +**Deliverable:** Week 2 detailed schedule + +### Agent 3: Week 3 Task Breakdown +**AGENT ID:** S4-H03 +** +**Create:** +- Day-by-day tasks for automation features +- Sale workflow (as-built package generator) +- Notification system (email, SMS, in-app) +- Offline mode (service worker, critical manual caching) +- Time estimates + dependencies + +**Deliverable:** Week 3 detailed schedule + +### Agent 4: Week 4 Task Breakdown +**AGENT ID:** S4-H04 +** +**Create:** +- Day-by-day tasks for polish & deployment +- MLS integration (YachtWorld, Boat Trader APIs) +- E2E testing suite +- Security audit +- Production deployment checklist + +**Deliverable:** Week 4 detailed schedule + +### Agent 5: Acceptance Criteria Writer +**AGENT ID:** S4-H05 +** +**Define:** +- Feature-level acceptance criteria (Given/When/Then format) +- API endpoint acceptance tests +- UI component acceptance criteria +- Performance benchmarks (load times, query speeds) + +**Deliverable:** Acceptance criteria document (all features) + +### Agent 6: Testing Strategy Designer +**AGENT ID:** S4-H06 +** +**Create:** +- Unit test plan (service layer, utilities) +- Integration test plan (API endpoints, database) +- E2E test plan (critical user flows) +- Test data generation strategy + +**Deliverable:** Testing strategy document with tooling recommendations + +### Agent 7: Dependency Mapper +**AGENT ID:** S4-H07 +** +**Analyze:** +- Task dependencies (Gantt chart format) +- Critical path identification +- Parallel work opportunities +- Risk areas (blockers, unknowns) + +**Deliverable:** Dependency graph (Mermaid Gantt or visual) + +### Agent 8: API Specification Writer +**AGENT ID:** S4-H08 +** +**Document:** +- All new API endpoints (OpenAPI 3.0 format) +- Request/response schemas +- Error codes and handling +- Authentication requirements + +**Deliverable:** OpenAPI spec file (`api-spec.yaml`) + +### Agent 9: Database Migration Planner +**AGENT ID:** S4-H09 +** +**Create:** +- Migration scripts (up/down for each change) +- Data backups strategy +- Rollback procedures +- Migration testing plan + +**Deliverable:** Migration scripts + rollback guide + +### Agent 10: Deployment Checklist Creator +**AGENT ID:** S4-H10 +** +**Compile:** +- Pre-deployment checklist (backups, tests, env vars) +- Deployment steps (zero-downtime strategy) +- Post-deployment validation (smoke tests) +- Rollback procedure (if deployment fails) + +**Deliverable:** Deployment runbook + +--- + +## Intra-Agent Communication Protocol (IF.bus) + +**Based on:** InfraFabric S² multi-swarm coordination (3,563x faster than git polling) + +### IFMessage Schema + +Every agent-to-agent message follows this structure: + +```json +{ + "performative": "inform", // FIPA-ACL: inform, request, query-if, confirm, disconfirm, ESCALATE + "sender": "if://agent/session-4/haiku-Y", + "receiver": ["if://agent/session-4/haiku-Z"], + "conversation_id": "if://conversation/navidocs-session-4-2025-11-13", + "content": { + "claim": "[Week N deliverables/blockers]", + "evidence": ["[Task completion status, test results]"], + "confidence": 0.85, // 0.0-1.0 + "cost_tokens": 1247 + }, + "citation_ids": ["if://citation/uuid"], + "timestamp": "2025-11-13T10:00:00Z", + "sequence_num": 1 +} +``` + +### Speech Acts (Performatives) + +**inform:** Share week deliverables with next week's agent +- Example: "S4-H01 informs S4-H02: Week 1 foundation complete (DB migrations, Event Bus tested)" + +**request:** Ask about dependencies before proceeding +- Example: "S4-H02 requests S4-H01: Confirm DB migrations deployed and tested" + +**confirm:** Validate previous week's work +- Example: "S4-H02 confirms S4-H01: Database migrations executed successfully on dev" + +**disconfirm:** Flag blockers from previous week +- Example: "S4-H02 disconfirms: Event Bus tests failing - need S4-H01 to investigate" + +**ESCALATE:** Flag critical timeline risk +- Example: "S4-H03 ESCALATES: Week 2 not complete, blocks Week 3 sale workflow" + +### Communication Flow (This Session) + +``` +S4-H01 (Week 1) ──→ S4-H02 (Week 2) ──→ S4-H03 (Week 3) ──→ S4-H04 (Week 4) ──→ S4-H10 + ↓ handoff ↓ handoff ↓ handoff ↓ handoff +``` + +**Key Patterns:** +1. **Sequential Handoffs:** Week N agent sends deliverables + blockers to Week N+1 +2. **Dependency Validation:** Week N checks if Week N-1 unblocks their tasks +3. **Progress Tracking:** Each agent tracks token cost + time spent +4. **Agent 10 Synthesis:** Ensures 4-week roadmap is coherent and on-track + +### Week Handoff Example + +```yaml +# End of Week 1 (S4-H01) +S4-H01: "inform" → content: + week: 1 + status: "COMPLETE" + deliverables: [ + "DB migrations: warranty_tracking, webhooks, notification_templates", + "Event bus service: IF.bus messaging system", + "Security fixes: DELETE endpoint protection, auth enforcement", + "Background jobs: warranty expiration worker" + ] + tests_passed: 23/23 + blockers: [] + ready_for_week_2: true + +# S4-H02 validates Week 1 and confirms readiness +S4-H02: "confirm" → content: + week: 1 + validation: "All migrations tested on dev. Event bus ready for Week 2 warranty APIs." + week_2_dependencies: [ + "DB migrations (ready)", + "Event bus service (ready)", + "Security fixes (ready)" + ] + can_start_week_2: true + +# S4-H02 executes Week 2 and reports progress +S4-H02: "inform" → content: + week: 2 + status: "IN_PROGRESS" + progress: "Warranty APIs 60% complete (CRUD done, expiring endpoint 80%)" + blockers: ["Home Assistant integration needs webhook URL format validation"] +``` + +### Critical Path Conflict Example + +```yaml +# S4-H03 (Week 3) reports blocker +S4-H03: "disconfirm" → content: + week: 3 + blocker: "Sale workflow requires DB schema from Week 2, but S4-H02 incomplete" + missing: "webhooks table not migrated yet" + impact: "Cannot implement sale_workflows table migration" + estimated_delay: "1-2 days" + +# S4-H10 escalates to coordinator +S4-H10: "ESCALATE" → content: + critical_blocker: "Week 2 delays cascading to Week 3" + chain_affected: ["Week 3", "Week 4"] + recommendation: "Prioritize webhooks table migration immediately (2-hour task)" + +# Sonnet coordinator responds +Coordinator: "request" → S4-H02: "Prioritize webhooks migration today (deadline noon)" + +# S4-H02 confirms +S4-H02: "confirm" → content: + priority_shift: "Moved webhooks migration to top of queue" + eta: "9am completion" + unblocks: "S4-H03 can start sale workflow design by noon" +``` + +### Token Cost Tracking (IF.optimise) + +Every handoff message includes cost tracking: + +```yaml +S4-H01: "inform" → content: + tokens_used: 8750 + tokens_budgeted: 12500 + efficiency: 70% + cost_usd: 0.14 + remaining_budget: 3750 +``` + +### IF.TTT Compliance + +Every message MUST include: +- **citation_ids:** Links to task specs, test results +- **confidence:** Explicit score on deliverable completeness (0.0-1.0) +- **evidence:** Test counts, git commits, code reviews +- **cost_tokens:** Token consumption (IF.optimise tracking) + +--- + +## Week 1: Foundation (Nov 13-19) + +### Day 1 (Nov 13): Database Migrations +**Morning (4 hours):** +- [ ] Create `warranty_tracking` table + - Columns: id, boat_id, item_name, provider, purchase_date, warranty_period_months, expiration_date, coverage_amount, claim_instructions, status + - Indexes: boat_id, expiration_date, status + - Migration script: `migrations/20251113_add_warranty_tracking.sql` + +**Afternoon (3 hours):** +- [ ] Create `sale_workflows` table + - Columns: id, boat_id, initiated_by, buyer_email, status, transfer_date, documents_generated + - Migration script: `migrations/20251113_add_sale_workflows.sql` +- [ ] Create `webhooks` table + - Columns: id, organization_id, url, topics (JSON), secret, status, created_at + - Migration script: `migrations/20251113_add_webhooks.sql` + +**Testing:** +- [ ] Run migrations on dev database +- [ ] Verify rollback scripts work +- [ ] Check indexes created correctly + +**Acceptance Criteria:** +- Given new tables created, When querying schema, Then all columns and indexes exist +- Given migration rollback executed, When checking schema, Then tables removed cleanly + +### Day 2 (Nov 13): Event Bus Implementation +**Morning (4 hours):** +- [ ] Create `server/services/event-bus.service.js` + - Redis pub/sub integration + - Topic-based routing (WARRANTY_EXPIRING, DOCUMENT_UPLOADED, etc.) + - Event logging to audit trail + - Error handling (retry logic) + +**Afternoon (3 hours):** +- [ ] Create `server/services/webhook.service.js` + - HTTP POST to external URLs + - Exponential backoff retry (3 attempts) + - Webhook delivery status tracking + - Signature generation (HMAC-SHA256) + +**Testing:** +- [ ] Unit tests for event publishing +- [ ] Unit tests for webhook delivery +- [ ] Integration test: event → webhook delivery + +**Acceptance Criteria:** +- Given event published, When subscribers listening, Then event delivered within 100ms +- Given webhook URL fails, When retry triggered, Then exponential backoff applied (1s, 2s, 4s) + +### Day 3 (Nov 14): Security Fixes +**Morning (4 hours):** +- [ ] Fix DELETE endpoint protection + - Add ownership verification (user can only delete own boats) + - Add soft delete (mark as deleted, don't remove) + - Update `server/routes/boat.routes.js` + +- [ ] Enforce auth on all routes + - Audit `server/routes/*.js` for missing `authenticateToken` middleware + - Add auth to stats endpoint (`server/routes/stats.routes.js`) + +**Afternoon (2 hours):** +- [ ] Fix stats endpoint tenant isolation + - Filter stats by organization_id + - Add integration test (user can't see other org stats) + +**Testing:** +- [ ] Security tests (unauthorized access attempts) +- [ ] Tenant isolation tests (cross-organization data leaks) + +**Acceptance Criteria:** +- Given unauthorized user, When attempting DELETE, Then return 403 Forbidden +- Given user from Org A, When requesting stats, Then only Org A data returned + +### Day 4 (Nov 15): Notification Templates +**Morning (3 hours):** +- [ ] Create `notification_templates` table + - Columns: id, type (email/sms/push), event_type, subject, body, variables (JSON) + - Seed templates: WARRANTY_EXPIRING (90/30/14 day variants) + +**Afternoon (4 hours):** +- [ ] Create `server/services/notification.service.js` + - Email sending (Nodemailer integration) + - Template rendering (variable substitution) + - Notification queue (BullMQ job) + +**Testing:** +- [ ] Unit test: template rendering with variables +- [ ] Integration test: email sent via queue + +**Acceptance Criteria:** +- Given WARRANTY_EXPIRING event, When notification triggered, Then email sent with correct warranty details + +### Day 5 (Nov 16): Background Jobs +**Morning (4 hours):** +- [ ] Create `server/workers/warranty-expiration.worker.js` + - Daily job: check warranties expiring in 90/30/14 days + - Publish WARRANTY_EXPIRING events + - Mark notifications sent (avoid duplicates) + +**Afternoon (3 hours):** +- [ ] Register worker with BullMQ + - Update `server/index.js` to start worker + - Add worker health check endpoint + +**Testing:** +- [ ] Integration test: worker finds expiring warranties +- [ ] Integration test: events published correctly + +**Acceptance Criteria:** +- Given warranty expires in 30 days, When worker runs, Then WARRANTY_EXPIRING event published +- Given notification already sent, When worker runs again, Then duplicate not sent + +--- + +## Week 2: Core Integrations (Nov 20-26) + +### Day 1-2 (Nov 20-21): Warranty Tracking APIs +**Day 1 Morning (4 hours):** +- [ ] Create `server/routes/warranty.routes.js` + - POST /api/warranties (create) + - GET /api/warranties/:id (read) + - PUT /api/warranties/:id (update) + - DELETE /api/warranties/:id (soft delete) + +**Day 1 Afternoon (3 hours):** +- [ ] Create `server/services/warranty.service.js` + - Business logic: calculate expiration dates + - Validation: warranty period constraints + - Database operations (CRUD) + +**Day 2 Morning (4 hours):** +- [ ] Create GET /api/warranties/expiring endpoint + - Query params: days (90/30/14), boat_id (filter) + - Return warranties + days until expiration + - Sort by expiration date (ascending) + +**Day 2 Afternoon (3 hours):** +- [ ] Create GET /api/boats/:id/warranties endpoint + - Return all warranties for specific boat + - Include expired warranties (flagged) + - Total coverage amount calculation + +**Testing:** +- [ ] API integration tests (all endpoints) +- [ ] Authorization tests (tenant isolation) + +**Acceptance Criteria:** +- Given authenticated user, When POST /api/warranties, Then warranty created with calculated expiration +- Given boat with 3 warranties, When GET /api/boats/:id/warranties, Then all 3 returned with total coverage + +### Day 3-5 (Nov 22-24): Home Assistant Integration +**Day 3 Morning (4 hours):** +- [ ] Create `server/routes/integrations.routes.js` + - POST /api/integrations/home-assistant (register webhook) + - GET /api/integrations/home-assistant (get config) + - DELETE /api/integrations/home-assistant (remove) + +**Day 3 Afternoon (3 hours):** +- [ ] Create `server/services/home-assistant.service.js` + - Webhook URL validation (reachability check) + - Event forwarding (NaviDocs event → HA webhook) + - Retry logic (exponential backoff) + +**Day 4 Morning (4 hours):** +- [ ] Create Home Assistant automation examples + - YAML config: warranty expiration → notification + - YAML config: document uploaded → log entry + - Documentation: `docs/home-assistant-integration.md` + +**Day 4 Afternoon (3 hours):** +- [ ] MQTT integration (optional stretch goal) + - Research MQTT.js library + - Design topic structure (navidocs/boat/{id}/warranty/expiring) + - Prototype event publishing to MQTT broker + +**Day 5 (7 hours):** +- [ ] Camera system integration (optional stretch goal) + - Research Home Assistant camera APIs + - Design snapshot storage (link to NaviDocs documents) + - Prototype: camera snapshot → upload to NaviDocs + +**Testing:** +- [ ] Integration test: NaviDocs event → HA webhook delivery +- [ ] Manual test: HA automation triggered by NaviDocs event + +**Acceptance Criteria:** +- Given HA webhook registered, When WARRANTY_EXPIRING event, Then HA receives POST with event data +- Given MQTT broker configured, When document uploaded, Then MQTT topic published + +--- + +## Week 3: Automation (Nov 27 - Dec 3) + +### Day 1-2 (Nov 27-28): Sale Workflow +**Day 1 Morning (4 hours):** +- [ ] Create `server/services/sale-workflow.service.js` + - POST /api/sales (initiate sale) + - GET /api/sales/:id (get sale status) + - POST /api/sales/:id/generate-package (as-built package) + +**Day 1 Afternoon (3 hours):** +- [ ] As-built package generator + - Gather all boat documents (registration, surveys, warranties) + - Generate cover letter (template with boat details) + - Create ZIP archive with organized folders + +**Day 2 Morning (4 hours):** +- [ ] Document transfer workflow + - POST /api/sales/:id/transfer (mark documents transferred) + - Send buyer access email (with download link) + - Log transfer event (audit trail) + +**Day 2 Afternoon (3 hours):** +- [ ] Buyer handoff notification + - Email template: "Your yacht documentation package" + - Include warranty summary, important dates + - Download link (expiring in 30 days) + +**Testing:** +- [ ] Integration test: sale initiated → package generated +- [ ] E2E test: full sale workflow (initiate → generate → transfer) + +**Acceptance Criteria:** +- Given boat with 10 documents, When generate package, Then ZIP contains all docs in organized folders +- Given sale transferred, When buyer receives email, Then download link works and expires in 30 days + +### Day 3-4 (Nov 29-30): Notification System +**Day 3 Morning (4 hours):** +- [ ] Email service implementation + - Nodemailer configuration (SMTP settings) + - Template system (Handlebars or EJS) + - Email queue (BullMQ job) + +**Day 3 Afternoon (3 hours):** +- [ ] SMS gateway integration (Twilio or similar) + - Research SMS provider APIs + - Design SMS template system + - Implement sending logic + +**Day 4 Morning (4 hours):** +- [ ] In-app notification center + - Create `notifications` table (id, user_id, type, message, read, created_at) + - GET /api/notifications (user's notifications) + - PUT /api/notifications/:id/read (mark as read) + +**Day 4 Afternoon (3 hours):** +- [ ] Push notifications (PWA) + - Service worker push subscription + - Web Push API integration + - Notification permission request UI + +**Testing:** +- [ ] Email delivery test (dev SMTP server) +- [ ] In-app notification test (create + read) + +**Acceptance Criteria:** +- Given WARRANTY_EXPIRING event, When notification sent, Then email delivered within 5 minutes +- Given user logged in, When notification created, Then appears in notification center + +### Day 5 (Dec 1): Offline Mode +**Morning (4 hours):** +- [ ] Service worker caching strategy + - Cache-first for static assets (/_next/, /assets/) + - Network-first for API calls + - Offline fallback page + +**Afternoon (3 hours):** +- [ ] Critical manual pre-caching + - Engine manuals (PDF files) + - Safety documents (emergency procedures) + - Offline sync queue (IndexedDB) + +**Testing:** +- [ ] Offline test: disconnect network, verify cached content loads +- [ ] Sync test: reconnect network, verify queued uploads process + +**Acceptance Criteria:** +- Given offline mode, When user accesses critical manuals, Then PDFs load from cache +- Given offline edits made, When network restored, Then changes sync automatically + +--- + +## Week 4: Polish & Deploy (Dec 4-10) + +### Day 1-2 (Dec 4-5): MLS Integration +**Day 1 Morning (4 hours):** +- [ ] Research YachtWorld API + - Authentication (API key vs OAuth) + - Listing endpoints (create, update, get) + - Documentation upload endpoints + +**Day 1 Afternoon (3 hours):** +- [ ] Create `server/services/yachtworld.service.js` + - API client setup + - Listing sync (NaviDocs boat → YachtWorld listing) + - Document attachment (warranties, surveys) + +**Day 2 Morning (4 hours):** +- [ ] Research Boat Trader API (similar to YachtWorld) +- [ ] Design unified MLS abstraction layer + - Interface: `IMLSProvider` (create, update, sync methods) + - Implementations: YachtWorldProvider, BoatTraderProvider + +**Day 2 Afternoon (3 hours):** +- [ ] MLS sync background job + - Daily job: sync boat data to configured MLS platforms + - Update listing status (sold, pending, available) + +**Testing:** +- [ ] Integration test: NaviDocs boat → YachtWorld listing created +- [ ] Manual test: verify listing appears on YachtWorld website + +**Acceptance Criteria:** +- Given boat marked for sale, When MLS sync runs, Then YachtWorld listing created with documents + +### Day 3 (Dec 6): E2E Testing +**Morning (4 hours):** +- [ ] Set up Playwright or Cypress +- [ ] E2E test: user registration → boat creation → document upload +- [ ] E2E test: warranty tracking → expiration alert → claim package + +**Afternoon (3 hours):** +- [ ] E2E test: sale workflow (initiate → generate package → transfer) +- [ ] E2E test: Home Assistant integration (event → webhook delivery) + +**Acceptance Criteria:** +- Given E2E test suite, When run against demo environment, Then all tests pass + +### Day 4 (Dec 7): Security Audit +**Morning (3 hours):** +- [ ] Run OWASP dependency check +- [ ] SQL injection testing (parameterized queries verified) +- [ ] XSS testing (input sanitization verified) + +**Afternoon (4 hours):** +- [ ] Authentication audit (JWT expiration, refresh tokens) +- [ ] Authorization audit (tenant isolation, role-based access) +- [ ] Secrets management (env vars, no hardcoded keys) + +**Acceptance Criteria:** +- Given security audit, When vulnerabilities found, Then all high/critical issues fixed + +### Day 5 (Dec 8-10): Production Deployment +**Dec 8 Morning (4 hours):** +- [ ] Pre-deployment checklist + - Database backup (SQLite file copy) + - Environment variables configured + - SSL certificate valid + +**Dec 8 Afternoon (3 hours):** +- [ ] Deploy to production + - Stop server + - Run database migrations + - Deploy new code (git pull + npm install) + - Restart server + +**Dec 9 (7 hours):** +- [ ] Post-deployment validation + - Smoke tests (critical endpoints functional) + - Performance testing (load times, query speeds) + - Monitor error logs (first 24 hours) + +**Dec 10 (7 hours):** +- [ ] Riviera Plaisance pilot setup + - Create demo account + - Import sample boat data + - Configure Home Assistant webhook + - Train Sylvain on system + +**Acceptance Criteria:** +- Given production deployment, When smoke tests run, Then all critical flows functional +- Given Riviera pilot account, When Sylvain logs in, Then demo boat with warranties visible + +--- + +## Acceptance Criteria (Master List) + +### Warranty Tracking Feature +```gherkin +Feature: Warranty Expiration Tracking + +Scenario: Create warranty with automatic expiration calculation + Given authenticated user + And boat with id "boat-123" + When POST /api/warranties with: + | boat_id | item_name | purchase_date | warranty_period_months | + | boat-123 | Engine | 2023-01-15 | 24 | + Then warranty created with expiration_date "2025-01-15" + And response status 201 + +Scenario: Expiration alert triggered 30 days before + Given warranty expires on "2025-12-13" + And current date is "2025-11-13" + When warranty expiration worker runs + Then WARRANTY_EXPIRING event published + And notification sent to boat owner + +Scenario: Claim package generation + Given warranty expiring in 14 days + When POST /api/warranties/:id/generate-claim-package + Then ZIP file returned containing: + | warranty document | + | purchase invoice | + | claim form (jurisdiction-specific) | +``` + +### Home Assistant Integration +```gherkin +Feature: Home Assistant Webhook Integration + +Scenario: Register Home Assistant webhook + Given authenticated user + When POST /api/integrations/home-assistant with: + | url | topics | + | https://ha.example.com/api/webhook/navidocs | ["WARRANTY_EXPIRING", "DOCUMENT_UPLOADED"] | + Then webhook registered + And reachability check passed + +Scenario: Event forwarding to Home Assistant + Given HA webhook registered for "WARRANTY_EXPIRING" + When WARRANTY_EXPIRING event published + Then POST sent to HA webhook within 5 seconds + And HA webhook receives event with warranty details +``` + +### Sale Workflow +```gherkin +Feature: Yacht Sale Workflow + +Scenario: Generate as-built package + Given boat with 10 documents + When POST /api/sales/:id/generate-package + Then ZIP file created with organized folders: + | Registration | + | Surveys | + | Warranties | + | Engine Manuals | + And generation time < 30 seconds + +Scenario: Transfer documents to buyer + Given sale with generated package + When POST /api/sales/:id/transfer with buyer_email + Then buyer receives email with download link + And link expires in 30 days + And transfer logged in audit trail +``` + +--- + +## Testing Strategy + +### Unit Tests (Target: 70% Coverage) +**Tools:** Mocha + Chai +**Scope:** +- Service layer functions (warranty calculations, validation) +- Utility functions (date helpers, string formatting) +- Middleware (auth, error handling) + +**Example:** +```javascript +// test/services/warranty.service.test.js +describe('WarrantyService', () => { + describe('calculateExpirationDate', () => { + it('should add warranty period to purchase date', () => { + const purchaseDate = '2023-01-15'; + const warrantyMonths = 24; + const result = warrantyService.calculateExpirationDate(purchaseDate, warrantyMonths); + expect(result).to.equal('2025-01-15'); + }); + }); +}); +``` + +### Integration Tests (Target: 50% Coverage) +**Tools:** Supertest + SQLite in-memory +**Scope:** +- API endpoints (request/response validation) +- Database operations (CRUD, migrations) +- Background jobs (worker execution) + +**Example:** +```javascript +// test/routes/warranty.routes.test.js +describe('POST /api/warranties', () => { + it('should create warranty with valid data', async () => { + const response = await request(app) + .post('/api/warranties') + .set('Authorization', `Bearer ${validToken}`) + .send({ + boat_id: 'boat-123', + item_name: 'Engine', + purchase_date: '2023-01-15', + warranty_period_months: 24 + }); + + expect(response.status).to.equal(201); + expect(response.body.expiration_date).to.equal('2025-01-15'); + }); +}); +``` + +### E2E Tests (Target: 10 Critical Flows) +**Tools:** Playwright +**Scope:** +- User registration → boat creation → warranty tracking +- Warranty expiration alert → claim package generation +- Sale initiation → package generation → buyer transfer +- Home Assistant webhook registration → event delivery + +**Example:** +```javascript +// e2e/warranty-tracking.spec.js +test('warranty expiration alert flow', async ({ page }) => { + await page.goto('https://demo.navidocs.app'); + await page.fill('#email', 'demo@example.com'); + await page.fill('#password', 'password'); + await page.click('#login-button'); + + // Navigate to boat with expiring warranty + await page.click('text=Azimut 55S'); + + // Verify warranty alert badge + await expect(page.locator('.warranty-alert')).toHaveText('Expires in 28 days'); + + // Generate claim package + await page.click('#generate-claim-package'); + await expect(page.locator('.download-link')).toBeVisible(); +}); +``` + +--- + +## Dependency Graph (Gantt Chart) + +```mermaid +gantt + title NaviDocs 4-Week Sprint + dateFormat YYYY-MM-DD + section Week 1 + DB Migrations :done, w1d1, 2025-11-13, 1d + Event Bus :done, w1d2, 2025-11-13, 1d + Security Fixes :w1d3, 2025-11-14, 1d + Notification Templates :w1d4, 2025-11-15, 1d + Background Jobs :w1d5, after w1d4, 1d + + section Week 2 + Warranty APIs :w2d1, 2025-11-20, 2d + Home Assistant :w2d3, after w2d1, 3d + + section Week 3 + Sale Workflow :w3d1, 2025-11-27, 2d + Notification System :w3d3, after w3d1, 2d + Offline Mode :w3d5, after w3d3, 1d + + section Week 4 + MLS Integration :w4d1, 2025-12-04, 2d + E2E Testing :w4d3, after w4d1, 1d + Security Audit :w4d4, after w4d3, 1d + Production Deploy :w4d5, after w4d4, 3d +``` + +**Critical Path:** +DB Migrations → Event Bus → Background Jobs → Warranty APIs → E2E Testing → Deploy + +**Parallel Opportunities:** +- Week 2: Home Assistant work can run parallel to Warranty APIs (if different developer) +- Week 3: Offline Mode can run parallel to Notification System +- Week 4: MLS Integration is optional (can defer to Week 5 if needed) + +--- + +## API Specification (OpenAPI 3.0) + +```yaml +openapi: 3.0.0 +info: + title: NaviDocs Yacht Sales API + version: 1.0.0 + description: Warranty tracking, sale workflow, and integrations for yacht documentation + +servers: + - url: https://api.navidocs.app/v1 + description: Production + - url: http://localhost:3000/api + description: Development + +paths: + /warranties: + post: + summary: Create warranty + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - boat_id + - item_name + - purchase_date + - warranty_period_months + properties: + boat_id: + type: string + example: "boat-123" + item_name: + type: string + example: "Engine" + provider: + type: string + example: "Caterpillar" + purchase_date: + type: string + format: date + example: "2023-01-15" + warranty_period_months: + type: integer + example: 24 + coverage_amount: + type: number + example: 50000 + responses: + '201': + description: Warranty created + content: + application/json: + schema: + $ref: '#/components/schemas/Warranty' + '401': + description: Unauthorized + '400': + description: Invalid input + + /warranties/expiring: + get: + summary: Get expiring warranties + security: + - bearerAuth: [] + parameters: + - name: days + in: query + schema: + type: integer + enum: [90, 30, 14] + default: 30 + - name: boat_id + in: query + schema: + type: string + responses: + '200': + description: List of expiring warranties + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Warranty' + + /sales: + post: + summary: Initiate yacht sale + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - boat_id + - buyer_email + properties: + boat_id: + type: string + buyer_email: + type: string + format: email + responses: + '201': + description: Sale initiated + content: + application/json: + schema: + $ref: '#/components/schemas/Sale' + + /sales/{id}/generate-package: + post: + summary: Generate as-built package + security: + - bearerAuth: [] + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + '200': + description: ZIP file with documentation + content: + application/zip: + schema: + type: string + format: binary + +components: + schemas: + Warranty: + type: object + properties: + id: + type: string + boat_id: + type: string + item_name: + type: string + provider: + type: string + purchase_date: + type: string + format: date + warranty_period_months: + type: integer + expiration_date: + type: string + format: date + coverage_amount: + type: number + status: + type: string + enum: [active, expired, claimed] + created_at: + type: string + format: date-time + + Sale: + type: object + properties: + id: + type: string + boat_id: + type: string + buyer_email: + type: string + status: + type: string + enum: [initiated, package_generated, transferred, completed] + created_at: + type: string + format: date-time + + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT +``` + +--- + +## Database Migration Scripts + +### Migration: Add Warranty Tracking + +**File:** `migrations/20251113_add_warranty_tracking.sql` + +```sql +-- Up Migration +CREATE TABLE IF NOT EXISTS warranty_tracking ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + boat_id TEXT NOT NULL, + item_name TEXT NOT NULL, + provider TEXT, + purchase_date TEXT NOT NULL, + warranty_period_months INTEGER NOT NULL, + expiration_date TEXT NOT NULL, + coverage_amount REAL, + claim_instructions TEXT, + status TEXT DEFAULT 'active' CHECK(status IN ('active', 'expired', 'claimed')), + created_at TEXT DEFAULT (datetime('now')), + updated_at TEXT DEFAULT (datetime('now')), + FOREIGN KEY (boat_id) REFERENCES boats(id) ON DELETE CASCADE +); + +CREATE INDEX idx_warranty_boat_id ON warranty_tracking(boat_id); +CREATE INDEX idx_warranty_expiration ON warranty_tracking(expiration_date); +CREATE INDEX idx_warranty_status ON warranty_tracking(status); + +-- Down Migration (Rollback) +-- DROP INDEX idx_warranty_status; +-- DROP INDEX idx_warranty_expiration; +-- DROP INDEX idx_warranty_boat_id; +-- DROP TABLE warranty_tracking; +``` + +### Migration: Add Webhooks + +**File:** `migrations/20251113_add_webhooks.sql` + +```sql +-- Up Migration +CREATE TABLE IF NOT EXISTS webhooks ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + organization_id TEXT NOT NULL, + url TEXT NOT NULL, + topics TEXT NOT NULL, -- JSON array + secret TEXT NOT NULL, + status TEXT DEFAULT 'active' CHECK(status IN ('active', 'inactive')), + last_delivery_at TEXT, + last_delivery_status TEXT, + created_at TEXT DEFAULT (datetime('now')), + FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE +); + +CREATE INDEX idx_webhook_org_id ON webhooks(organization_id); +CREATE INDEX idx_webhook_status ON webhooks(status); + +-- Down Migration (Rollback) +-- DROP INDEX idx_webhook_status; +-- DROP INDEX idx_webhook_org_id; +-- DROP TABLE webhooks; +``` + +--- + +## Deployment Runbook + +### Pre-Deployment Checklist +- [ ] All tests passing (unit, integration, E2E) +- [ ] Database backup created (`cp navidocs.db navidocs.db.backup-$(date +%Y%m%d)`) +- [ ] Environment variables configured in `.env.production` +- [ ] SSL certificate valid (check expiration) +- [ ] Dependencies updated (`npm audit fix`) +- [ ] Security audit passed (no high/critical vulnerabilities) + +### Deployment Steps (Zero-Downtime) +1. **Stop Background Workers** (prevent job processing during migration) + ```bash + pm2 stop navidocs-worker + ``` + +2. **Database Backup** + ```bash + cp /var/www/navidocs/navidocs.db /var/www/navidocs/backups/navidocs.db.$(date +%Y%m%d-%H%M%S) + ``` + +3. **Deploy Code** + ```bash + cd /var/www/navidocs + git pull origin main + npm install --production + npm run build + ``` + +4. **Run Migrations** + ```bash + npm run migrate:up + ``` + +5. **Restart Server** + ```bash + pm2 restart navidocs-api + pm2 restart navidocs-worker + ``` + +### Post-Deployment Validation +- [ ] Health check endpoint returns 200 (`GET /api/health`) +- [ ] Login flow functional (test with demo account) +- [ ] Critical API endpoints responding (`GET /api/boats`, `POST /api/warranties`) +- [ ] Background workers processing jobs (`pm2 logs navidocs-worker`) +- [ ] Error rate within acceptable range (<1% of requests) + +### Rollback Procedure (If Deployment Fails) +1. **Stop Server** + ```bash + pm2 stop navidocs-api navidocs-worker + ``` + +2. **Restore Database** + ```bash + cp /var/www/navidocs/backups/navidocs.db. /var/www/navidocs/navidocs.db + ``` + +3. **Revert Code** + ```bash + git revert HEAD + npm install --production + ``` + +4. **Restart Server** + ```bash + pm2 restart navidocs-api navidocs-worker + ``` + +--- + +## IF.TTT Compliance Checklist + +- [ ] All tasks link to codebase files (file:line references) +- [ ] Acceptance criteria testable (Given/When/Then format) +- [ ] Dependencies mapped (Gantt chart with critical path) +- [ ] API specs validated against existing routes +- [ ] Migration scripts include rollback procedures +- [ ] Evidence artifacts stored in `/intelligence/session-4/` + +--- + +## Success Criteria + +**Minimum Viable Output:** +- 4-week sprint breakdown (day-by-day tasks) +- Acceptance criteria for all major features +- Gantt chart with dependencies +- API specification (OpenAPI format) +- Database migration scripts with rollbacks + +**Stretch Goals:** +- Automated testing framework setup (Playwright config) +- CI/CD pipeline configuration (GitHub Actions) +- Performance benchmarks (load testing plan) +- Monitoring setup (error tracking, uptime alerts) + +--- + +**Start Command:** Deploy to Claude Code Cloud after Session 2 complete +**End Condition:** All deliverables committed to `dannystocker/navidocs` repo under `intelligence/session-4/` diff --git a/builder/prompts/research/session-5-synthesis-validation.md b/builder/prompts/research/session-5-synthesis-validation.md new file mode 100644 index 0000000..304dbec --- /dev/null +++ b/builder/prompts/research/session-5-synthesis-validation.md @@ -0,0 +1,1250 @@ +# Cloud Session 5: Evidence Synthesis & Guardian Validation +## NaviDocs Sticky Engagement Model - Final Dossier + +**Session Type:** Guardian Council Coordinator + Evidence Curator +**Lead Agent:** Sonnet (synthesis + validation) +**Swarm Size:** 10 Haiku agents +**Token Budget:** $25 (15K Sonnet + 60K Haiku) +**Output:** Intelligence dossier validating inventory tracking + daily engagement model + +--- + +## Mission Statement + +**Active Quality Assurance Partner (Immediate Start):** Deploy evidence quality standards, monitor Sessions 1-4 commits in real-time, provide continuous feedback to prevent rework. + +**Final Validation (When Sessions 1-4 Complete):** Synthesize all intelligence into comprehensive dossier, validate claims with medical-grade evidence standards, achieve Guardian Council consensus (>90% approval), and deliver final presentation materials. + +--- + +## Context (Read First) + +**Prerequisites (MUST READ ALL):** +1. `intelligence/session-1/session-1-market-analysis.md` +2. `intelligence/session-1/session-1-handoff.md` +3. `intelligence/session-2/session-2-architecture.md` +4. `intelligence/session-2/session-2-sprint-plan.md` +5. `intelligence/session-3/session-3-pitch-deck.md` +6. `intelligence/session-3/session-3-demo-script.md` +7. `intelligence/session-4/session-4-sprint-plan.md` + +**Guardian Council Composition:** +- 6 Core Guardians (Empiricism, Verificationism, Fallibilism, Falsificationism, Coherentism, Pragmatism) +- 3 Western Philosophers (Aristotle, Kant, Russell) +- 3 Eastern Philosophers (Confucius, Nagarjuna, Zhuangzi) +- 8 IF.sam Facets (Light Side: Ethical Idealist, Visionary Optimist, Democratic Collaborator, Transparent Communicator; Dark Side: Pragmatic Survivor, Strategic Manipulator, Ends-Justify-Means Operator, Corporate Diplomat) + +**Consensus Requirements:** +- **Standard Approval:** >90% (18/20 votes) +- **100% Consensus:** Requires empirical validation + testable predictions + addresses all guardian concerns +- **Veto Power:** Contrarian Guardian can veto >95% approval with 2-week cooling-off period + +**Evidence Standards (IF.TTT):** +- All claims MUST have ≥2 independent sources +- Citations include: file:line references, web URLs with SHA-256 hashes, git commits +- Status tracking: unverified → verified → disputed → revoked +- Citation schema: `schemas/citation/v1.0.schema.json` (in repo) + +--- + + +## Agent Identity & Check-In Protocol + +**YOU ARE:** Sonnet coordinator for Session 5 (Evidence Synthesis) + +**YOUR HAIKU SWARM:** You have 10 Haiku agents available. Use as many as needed (not required to use all 10). + +**AGENT IDENTITY SYSTEM:** +When spawning a Haiku agent, assign it an identity: `S5-H01` through `S5-H10` +Each agent MUST: +1. **Check in** at start: "I am S5-H03, assigned to [task name]" +2. **Reference their task** by searching this document for "Agent 3:" (matching their number) +3. **Retain identity** throughout execution +4. **Report completion** with identity: "S5-H03 complete: [deliverable summary]" + +**TASK DEPENDENCIES:** +- Most agents can run in parallel +- Agent 10 typically synthesizes results from Agents 1-9 (must wait for completion) + +--- + +## Your Tasks (Spawn 13 Haiku Agents) + +**PHASE 1: Active Quality Assurance (START IMMEDIATELY - NO DEPENDENCIES)** + +### Agent 0A: Evidence Quality Standards Deployment +**AGENT ID:** S5-H0A +**PRIORITY:** CRITICAL - Deploy within first 10 minutes +** +**Create:** +- `EVIDENCE_QUALITY_STANDARDS.md` - Master reference for Sessions 1-4 + - **Citation format templates:** + ```json + { + "citation_id": "if://citation/warranty-savings-8k-33k", + "claim": "NaviDocs prevents €8K-€33K warranty losses per yacht", + "sources": [ + { + "type": "web", + "url": "https://yachtworld.com/research/yacht-ownership-costs-2024", + "sha256": "a1b2c3d4...", + "accessed": "2025-11-13", + "quality": "primary", + "credibility": 9 + }, + { + "type": "file", + "path": "intelligence/session-1/market-analysis.md", + "line_range": "45-67", + "quality": "primary" + } + ], + "status": "verified", + "confidence_score": 0.95 + } + ``` + - **IF.TTT compliance checklist:** + - [ ] ≥2 independent sources for high-confidence claims + - [ ] Web URLs include SHA-256 hash (tamper detection) + - [ ] File references include line numbers + - [ ] Citation ID follows if:// URI scheme + - [ ] Confidence score justified (0.0-1.0) + - [ ] Status tracked: unverified → verified → disputed → revoked + - **Evidence quality scoring:** + - Primary source (9-10 credibility): Original research, official statistics, codebase analysis + - Secondary source (7-8 credibility): Industry reports, competitor websites, expert interviews + - Tertiary source (5-6 credibility): Blog posts, forum discussions, anecdotal evidence + - Unverified (0-4 credibility): Claims without sources + - **Multi-source verification examples:** + - Market sizing claim: YachtWorld stats + Boat International report + - Technical claim: Codebase file:line + architecture doc + - Competitive claim: Competitor website + pricing screenshot + +**Commit to coordination branch:** +```bash +git add EVIDENCE_QUALITY_STANDARDS.md +git commit -m "Session 5: Evidence quality standards for Sessions 1-4" +git push origin navidocs-cloud-coordination +``` + +**Notify other sessions:** +- Update `AUTONOMOUS-COORDINATION-STATUS.md`: "✅ Evidence standards deployed - Sessions 1-4 reference EVIDENCE_QUALITY_STANDARDS.md" + +**Deliverable:** `EVIDENCE_QUALITY_STANDARDS.md` (Sessions 1-4 read this immediately) + +--- + +### Agent 0B: Real-Time Quality Monitor (CONTINUOUS) +**AGENT ID:** S5-H0B +**PRIORITY:** HIGH - Run every 5 minutes for entire session +** +**Monitor:** +- Poll `intelligence/session-1/`, `session-2/`, `session-3/`, `session-4/` for new commits +- Check git log every 5 minutes: + ```bash + git fetch origin navidocs-cloud-coordination + git log --since="5 minutes ago" --name-status -- intelligence/ + ``` + +**Review:** +- New citations: Are they IF.TTT compliant? (SHA-256 hashes, ≥2 sources, line numbers) +- Market claims: Do they cite credible sources? (not just "industry experts say...") +- Technical claims: Do they reference codebase? (file:line required) +- ROI calculations: Do they show work? (formulas + source data) + +**Feedback Loop:** +- Create `QUALITY_FEEDBACK.md` (updated every 5 minutes): + ```markdown + # Real-Time Quality Feedback (Updated: 2025-11-13 14:35 UTC) + + ## ✅ Session 1 (Good) + - Agent 2 citation: Excellent (2 primary sources, SHA-256 hashes included) + - Agent 3 market sizing: Good (YachtWorld + Boat International cited) + + ## ⚠️ Session 2 (Needs Attention) + - Agent 3 maintenance log claim: Missing line number reference + - Agent 6 accounting module: Only 1 source (need ≥2 for high confidence) + + ## 🔴 Session 3 (Action Required) + - Agent 5 ROI calculator: No source citations for €8K-€33K warranty claim + - Action: Review Session 1 market analysis, add citation links + + ## ✅ Session 4 (Good) + - Sprint plan: All tasks reference Session 2 architecture (file:line included) + ``` + +**Commit feedback every 5 minutes:** +```bash +git add QUALITY_FEEDBACK.md +git commit -m "Session 5: Quality feedback ($(date -Iseconds))" +git push origin navidocs-cloud-coordination +``` + +**Escalate if needed:** +- >20% of citations lack IF.TTT compliance → ESCALATE to Sonnet coordinator +- Sessions 1-4 read feedback, fix issues proactively (prevent rework at validation stage) + +**Deliverable:** `QUALITY_FEEDBACK.md` (updated every 5 minutes) + +--- + +### Agent 0C: Guardian Briefing Templates (PREP WORK) +**AGENT ID:** S5-H0C +** +**Create templates for final validation (ready when Sessions 1-4 complete):** + +1. **Guardian-Specific Briefing Template (20 guardians):** + ```markdown + # Guardian Briefing: [Guardian Name] + **Philosophy:** [Empiricism, Pragmatism, IF.sam Light/Dark, etc.] + **Focus Areas:** [What this guardian cares about most] + + ## Executive Summary + [Tailored to guardian's philosophy] + + ## Key Evidence + [Filtered to guardian's interests] + - Empiricism: Market research data, statistical evidence + - Pragmatism: ROI calculations, implementation feasibility + - IF.sam (Light): Ethical sales, transparency, user benefit + - IF.sam (Dark): Competitive advantage, revenue potential, market dominance + + ## Questions for This Guardian + [Anticipated concerns based on philosophy] + + ## Voting Criteria + - [ ] Evidence quality meets standards + - [ ] Claims aligned with guardian's values + - [ ] Implementation feasible + ``` + +2. **Consensus Prediction Formula:** + ```javascript + function predictConsensus(dossier) { + let approvalScore = 0; + // Evidence quality (40% weight) + approvalScore += dossier.verifiedCitations / dossier.totalCitations * 0.4; + // Multi-source verification (30% weight) + approvalScore += dossier.multiSourceClaims / dossier.totalClaims * 0.3; + // Implementation feasibility (20% weight) + approvalScore += dossier.feasibilityScore * 0.2; + // Guardian alignment (10% weight) + approvalScore += dossier.philosophyAlignment * 0.1; + + return approvalScore * 100; // Return as percentage + } + ``` + +3. **Voting Criteria Checklist:** + - [ ] All high-confidence claims have ≥2 sources + - [ ] Technical claims reference codebase (file:line) + - [ ] Market sizing backed by credible sources + - [ ] ROI calculations show work (formulas + data) + - [ ] Implementation timeline realistic (based on codebase complexity) + - [ ] Acceptance criteria testable + - [ ] No unverified claims in executive summary + +**Deliverable:** `GUARDIAN_BRIEFING_TEMPLATES/` directory with 20 templates + consensus formula + +--- + +**PHASE 2: Evidence Extraction & Validation (WAIT FOR SESSIONS 1-4)** + +### Agent 1: Session 1 Evidence Extraction +**AGENT ID:** S5-H01 +** +**Read:** +- `intelligence/session-1/session-1-market-analysis.md` +- `intelligence/session-1/session-1-citations.json` + +**Extract:** +- All market sizing claims (Mediterranean yacht sales, brokerage counts) +- Competitive landscape findings (competitor pricing, feature gaps) +- Broker pain points (time spent, documentation delays) +- ROI calculator inputs (warranty savings, claims costs) + +**Deliverable:** Evidence inventory with citation links + +### Agent 2: Session 2 Technical Claims Validation +**AGENT ID:** S5-H02 +** +**Read:** +- `intelligence/session-2/session-2-architecture.md` +- NaviDocs codebase (`server/db/schema.sql`, `server/routes/*.js`) + +**Validate:** +- Architecture claims match actual codebase (file:line references) +- Database migrations are executable (test on dev database) +- API endpoints align with existing patterns +- Integration points exist in code + +**Deliverable:** Technical validation report (verified vs unverified claims) + +### Agent 3: Session 3 Sales Material Review +**AGENT ID:** S5-H03 +** +**Read:** +- `intelligence/session-3/session-3-pitch-deck.md` +- `intelligence/session-3/session-3-demo-script.md` +- `intelligence/session-3/session-3-roi-calculator.html` + +**Review:** +- ROI calculations cite Session 1 sources +- Demo script matches NaviDocs features +- Pricing strategy aligns with competitor analysis +- Objection handling backed by evidence + +**Deliverable:** Sales material validation report + +### Agent 4: Session 4 Implementation Feasibility +**AGENT ID:** S5-H04 +** +**Read:** +- `intelligence/session-4/session-4-sprint-plan.md` +- NaviDocs codebase (all relevant files) + +**Assess:** +- 4-week timeline realistic (based on codebase complexity) +- Dependencies correctly identified +- Acceptance criteria testable +- Migration scripts safe (rollback procedures) + +**Deliverable:** Feasibility assessment report + +### Agent 5: Citation Database Compilation +**AGENT ID:** S5-H05 +** +**Gather:** +- All citations from Sessions 1-4 +- Web sources (with SHA-256 hashes) +- File references (with line numbers) +- Git commits (with SHA-1 hashes) + +**Create:** +- Master citations JSON file +- Citation status tracking (verified/unverified) +- Source quality assessment (primary vs secondary) + +**Deliverable:** `session-5-citations-master.json` + +### Agent 6: Cross-Session Consistency Check +**AGENT ID:** S5-H06 +** +**Analyze:** +- Market size claims (Session 1 vs Session 3 pitch deck) +- Technical architecture (Session 2 vs Session 4 implementation) +- ROI calculations (Session 1 inputs vs Session 3 calculator) +- Timeline claims (Session 2 roadmap vs Session 4 sprint plan) + +**Flag:** +- Contradictions between sessions +- Unsupported claims (no citation) +- Outdated information + +**Deliverable:** Consistency audit report + +### Agent 7: Guardian Council Vote Preparation +**AGENT ID:** S5-H07 +** +**Prepare:** +- Dossier summary for each guardian (tailored to philosophy) +- Empiricism: Focus on market research data, evidence quality +- Pragmatism: Focus on ROI, implementation feasibility +- IF.sam (Light): Focus on ethical sales practices, transparency +- IF.sam (Dark): Focus on competitive advantage, revenue potential + +**Create:** +- Guardian-specific briefing documents (20 total) +- Voting criteria checklist +- Consensus prediction (likely approval %) + +**Deliverable:** Guardian briefing package + +### Agent 8: Evidence Quality Scoring +**AGENT ID:** S5-H08 +** +**Score Each Claim:** +- **Primary Source (3 points):** Direct research, codebase analysis +- **Secondary Source (2 points):** Industry reports, competitor websites +- **Tertiary Source (1 point):** Blog posts, forum discussions +- **No Source (0 points):** Unverified claim + +**Calculate:** +- Total claims across all sessions +- Verified claims percentage +- Average evidence quality score + +**Deliverable:** Evidence quality scorecard + +### Agent 9: Final Dossier Compiler +**AGENT ID:** S5-H09 +** +**Synthesize:** +- Executive summary (2 pages max) +- Market analysis (Session 1 findings) +- Technical architecture (Session 2 design) +- Sales enablement materials (Session 3 pitch) +- Implementation roadmap (Session 4 sprint plan) +- Evidence appendix (citations, validation reports) + +**Format:** +- Professional document (markdown with Mermaid diagrams) +- Table of contents with page numbers +- Cross-references between sections + +**Deliverable:** `NAVIDOCS_INTELLIGENCE_DOSSIER.md` + +### Agent 10: Guardian Council Vote Coordinator +**AGENT ID:** S5-H10 +** +**Execute:** +- Submit dossier to Guardian Council +- Collect votes from all 20 guardians +- Tally results (approval %, abstentions, vetoes) +- Record dissent reasons (if any) +- Generate consensus report + +**Deliverable:** `session-5-guardian-vote.json` + +--- + +## Intra-Agent Communication Protocol (IF.bus) + +**Based on:** InfraFabric S² multi-swarm coordination (3,563x faster than git polling) + +### IFMessage Schema + +Every agent-to-agent message follows this structure: + +```json +{ + "performative": "inform", // FIPA-ACL: inform, request, query-if, confirm, disconfirm, ESCALATE + "sender": "if://agent/session-5/haiku-Y", + "receiver": ["if://agent/session-5/haiku-Z"], + "conversation_id": "if://conversation/navidocs-session-5-2025-11-13", + "content": { + "claim": "[Guardian critique, consensus findings]", + "evidence": ["[Citation links, validation reports]"], + "confidence": 0.85, // 0.0-1.0 + "cost_tokens": 1247 + }, + "citation_ids": ["if://citation/uuid"], + "timestamp": "2025-11-13T10:00:00Z", + "sequence_num": 1 +} +``` + +### Speech Acts (Performatives) + +**inform:** Share evidence extraction findings +- Example: "S5-H01 informs S5-H10: Market claims extracted, 47 citations identified" + +**query-if:** Ask for validation of cross-session consistency +- Example: "S5-H06 queries: Does Session 1 market size match Session 3 pitch deck?" + +**confirm:** Validate claim with multiple sources +- Example: "S5-H02 confirms: Architecture claims verified against NaviDocs codebase (file:line refs)" + +**disconfirm:** Flag inconsistencies between sessions +- Example: "S5-H06 disconfirms: Timeline contradiction (Session 2 says 4 weeks, Session 4 says 5 weeks)" + +**ESCALATE:** Flag evidence quality issues for Guardian review +- Example: "S5-H08 ESCALATES: 5 unverified claims (warranty savings, MLS integration time)" + +### Communication Flow (This Session) + +``` +Guardians (1-12) ──→ IF.sam Debate ──→ S5-H10 (Consensus) + ↓ ↓ +Individual Reviews 8-Way Dialogue +(Haiku agents) (Light vs Dark) + ↓ ↓ +Citation Validation Dissent Recording +(Agents 1-9) (IF.TTT traceability) + ↓ ↓ +ESCALATE (if <80% consensus) +``` + +**Key Patterns:** +1. **Evidence Extraction:** Agents 1-4 extract claims from Sessions 1-4 +2. **Citation Compilation:** Agent 5 builds master citation database +3. **Cross-Session Validation:** Agent 6 checks for contradictions +4. **Guardian Briefing:** Agent 7 prepares tailored documents for each guardian +5. **Evidence Scoring:** Agent 8 rates credibility (0-10 scale) +6. **Dossier Compilation:** Agent 9 synthesizes all findings +7. **Consensus Tallying:** Agent 10 collects Guardian votes, detects <80% threshold + +### Contradiction Detection Example + +```yaml +# Agent 6 (Cross-Session Consistency) detects timeline conflict +S5-H06: "disconfirm" → content: + conflict_type: "Timeline variance" + session_2_claim: "4-week sprint foundation → deploy" + session_4_claim: "Week 1: Foundation, Week 4: Polish & Deploy (full 4 weeks)" + discrepancy: "Session 2 says 4 weeks total, Session 4 says Week 4 is final polish" + resolution_needed: true + confidence: 0.65 + +# Agent 10 flags for Guardian review +S5-H10: "ESCALATE" → content: + issue: "Timeline ambiguity affects feasibility judgement" + impact_on_consensus: "Fallibilism guardian will rate implementation risky if timeline unclear" + recommendation: "Clarify: Is 4 weeks INCLUDING final polish or BEFORE final polish?" + +# Sonnet coordinator clarifies +Coordinator: "request" → S5-H04: "Timeline review: Week 4 is polish + deploy, all within 4 weeks?" + +# Agent 4 confirms +S5-H04: "confirm" → content: + clarification: "4-week timeline includes deployment to production (Dec 8-10)" + status: "VERIFIED - no timeline contradiction" +``` + +### Guardian Consensus Building Example + +```yaml +# Agents report evidence quality to Guardians +S5-H08: "inform" → content: + claim_count: 47 + verified: 42 + provisional: 3 + unverified: 2 + average_credibility: 8.2 + primary_sources: 32 + +# IF.sam Light Side (Ethical Idealist) reviews +S5-H07: "inform" → IF.sam_debate: content: + light_side_position: "Dossier is transparent and well-sourced. Unverified claims flagged clearly." + confidence: 0.95 + vote_recommendation: "APPROVE" + +# IF.sam Dark Side (Pragmatic Survivor) debates +IF.sam_dark: "disconfirm" → IF.sam_debate: content: + dark_side_concern: "4-week timeline is ambitious. Risk = missed delivery deadline." + mitigation: "Is minimum viable product defined if timeline slips?" + vote_recommendation: "ABSTAIN - needs contingency plan" + +# Agent 10 tallies initial results +S5-H10: "inform" → content: + early_tally: { + approve: 14, + abstain: 4, + reject: 2 + } + approval_percentage: 77.8 # Below 80% threshold + escalation_needed: true + recommendation: "Fallibilism and Nagarjuna abstaining. Address uncertainty concerns." +``` + +### IF.TTT Compliance + +Every message MUST include: +- **citation_ids:** Links to Sessions 1-4 findings +- **confidence:** Explicit score (0.0-1.0) on claim verification +- **evidence:** Citation database references, source credibility +- **cost_tokens:** Token consumption (IF.optimise tracking) + +--- + +## Guardian Council Voting Process + +### Step 1: Dossier Distribution (Agent 7) +Each guardian receives tailored briefing highlighting their philosophical concerns: + +**Empiricism Guardian:** +- Market sizing methodology (how was €2.3B figure derived?) +- Warranty savings calculation (€8K-€33K range justified?) +- Evidence quality (how many primary vs secondary sources?) + +**Verificationism Guardian:** +- Testable predictions (can ROI calculator claims be validated?) +- API specification completeness (OpenAPI spec executable?) +- Acceptance criteria measurability (Given/When/Then verifiable?) + +**Fallibilism Guardian:** +- Uncertainty acknowledgment (what assumptions might be wrong?) +- Risk mitigation (what if 4-week timeline slips?) +- Competitor analysis gaps (missing players?) + +**Falsificationism Guardian:** +- Refutable claims (can market size be disproven?) +- Contradiction check (any conflicting statements?) +- Alternative explanations (is NaviDocs the only solution?) + +**Coherentism Guardian:** +- Internal consistency (Sessions 1-4 align?) +- Logical flow (market → architecture → sales → implementation?) +- Integration points (do all pieces fit together?) + +**Pragmatism Guardian:** +- Business value (does this solve real broker problems?) +- Implementation feasibility (4-week sprint realistic?) +- ROI justification (€8K-€33K savings achievable?) + +**Aristotle (Virtue Ethics):** +- Broker welfare (does this genuinely help clients?) +- Honest representation (sales pitch truthful?) +- Excellence pursuit (is this best-in-class solution?) + +**Kant (Deontology):** +- Universalizability (could all brokerages adopt this?) +- Treating brokers as ends (not just revenue sources?) +- Duty to accuracy (no misleading claims?) + +**Russell (Logical Positivism):** +- Logical validity (arguments sound?) +- Empirical verifiability (claims testable?) +- Clear definitions (terms like "warranty tracking" precise?) + +**Confucius (Ren/Li):** +- Relationship harmony (broker-buyer trust enhanced?) +- Propriety (sales approach respectful?) +- Social benefit (does this improve yacht sales ecosystem?) + +**Nagarjuna (Madhyamaka):** +- Dependent origination (how does NaviDocs fit into larger system?) +- Avoiding extremes (balanced approach to automation vs manual?) +- Emptiness of claims (are market projections inherently uncertain?) + +**Zhuangzi (Daoism):** +- Natural flow (does solution feel organic to brokers?) +- Wu wei (effortless adoption vs forced change?) +- Perspective diversity (have we considered all viewpoints?) + +**IF.sam Light Side (Ethical Idealist):** +- Mission alignment (does this advance marine safety?) +- Transparency (all claims documented with sources?) +- User empowerment (brokers retain control?) + +**IF.sam Light Side (Visionary Optimist):** +- Innovation potential (is this cutting-edge?) +- Market expansion (can this grow beyond Riviera?) +- Long-term impact (10-year vision?) + +**IF.sam Light Side (Democratic Collaborator):** +- Stakeholder input (have we consulted brokers?) +- Team involvement (implementation plan includes feedback loops?) +- Open communication (findings shareable?) + +**IF.sam Light Side (Transparent Communicator):** +- Clarity (pitch deck understandable?) +- Honesty (limitations acknowledged?) +- Evidence disclosure (citations accessible?) + +**IF.sam Dark Side (Pragmatic Survivor):** +- Competitive edge (does this beat competitors?) +- Revenue potential (can this be profitable?) +- Risk management (what if Riviera says no?) + +**IF.sam Dark Side (Strategic Manipulator):** +- Persuasion effectiveness (will pitch close deal?) +- Objection handling (have we pre-empted pushback?) +- Narrative control (do we own the story?) + +**IF.sam Dark Side (Ends-Justify-Means):** +- Goal achievement (will this get NaviDocs adopted?) +- Efficiency (fastest path to deployment?) +- Sacrifice assessment (what corners can be cut?) + +**IF.sam Dark Side (Corporate Diplomat):** +- Stakeholder alignment (does this satisfy all parties?) +- Political navigation (how to handle objections?) +- Relationship preservation (no bridges burned?) + +### Step 2: Voting Criteria + +Each guardian votes on 3 dimensions: + +1. **Empirical Soundness (0-10):** Evidence quality, source verification +2. **Logical Coherence (0-10):** Internal consistency, argument validity +3. **Practical Viability (0-10):** Implementation feasibility, ROI justification + +**Approval Formula:** +- **Approve:** Average score ≥7.0 across 3 dimensions +- **Abstain:** Average score 5.0-6.9 (needs more evidence) +- **Reject:** Average score <5.0 (fundamental flaws) + +### Step 3: Consensus Calculation + +**Approval Percentage:** +``` +(Approve Votes) / (Total Guardians - Abstentions) * 100 +``` + +**Outcome Thresholds:** +- **100% Consensus:** All 20 guardians approve (gold standard) +- **>95% Supermajority:** 19/20 approve (subject to Contrarian veto) +- **>90% Strong Consensus:** 18/20 approve (standard for production) +- **<90% Weak Consensus:** Requires revision + +### Step 4: Dissent Recording + +If any guardian rejects or abstains, record: +- Guardian name +- Vote (reject/abstain) +- Reason (1-2 sentences) +- Required changes (specific requests) + +**Example Dissent:** +```json +{ + "guardian": "Fallibilism", + "vote": "abstain", + "reason": "4-week timeline lacks uncertainty bounds. No contingency if implementation slips.", + "required_changes": [ + "Add timeline variance analysis (best case, likely case, worst case)", + "Define minimum viable product if 4 weeks insufficient" + ] +} +``` + +--- + +## Evidence Quality Standards (IF.TTT) + +### Citation Schema (v1.0) + +```json +{ + "citation_id": "if://citation/navidocs-market-size-2025-11-13", + "claim": "Mediterranean yacht sales market is €2.3B annually", + "evidence_type": "market_research", + "sources": [ + { + "type": "web", + "url": "https://example.com/yacht-market-report-2024", + "accessed": "2025-11-13T10:00:00Z", + "hash": "sha256:a3b2c1d4e5f6...", + "quality": "secondary", + "credibility": 8 + }, + { + "type": "file", + "path": "intelligence/session-1/market-analysis.md", + "line_range": "45-67", + "git_commit": "abc123def456", + "quality": "primary", + "credibility": 9 + } + ], + "status": "verified", + "verification_date": "2025-11-13T12:00:00Z", + "verified_by": "if://agent/session-5/haiku-5", + "confidence_score": 0.85, + "dependencies": ["if://citation/broker-count-riviera"], + "created_by": "if://agent/session-1/haiku-1", + "created_at": 1699632000000000000, + "updated_at": 1699635600000000000, + "tags": ["market-sizing", "mediterranean", "yacht-sales"] +} +``` + +### Source Quality Tiers + +**Primary Sources (High Credibility: 8-10):** +- Direct codebase analysis (file:line references) +- Original market research (commissioned reports) +- First-hand interviews (broker testimonials) +- NaviDocs production data (actual usage metrics) + +**Secondary Sources (Medium Credibility: 5-7):** +- Industry reports (yacht brokerage associations) +- Competitor websites (pricing, features) +- Academic papers (marine documentation studies) +- Government regulations (flag registration requirements) + +**Tertiary Sources (Low Credibility: 2-4):** +- Blog posts (industry commentary) +- Forum discussions (broker pain points) +- News articles (yacht market trends) +- Social media (anecdotal evidence) + +**Unverified Claims (Credibility: 0-1):** +- Assumptions (not yet validated) +- Hypotheses (testable but untested) +- Projections (future predictions) + +### Verification Process + +**Step 1: Source Identification** +- Agent 1-4 extract claims from Sessions 1-4 +- Each claim tagged with source type + +**Step 2: Credibility Scoring** +- Agent 8 scores each source (0-10 scale) +- Primary sources: 8-10 +- Secondary sources: 5-7 +- Tertiary sources: 2-4 +- No source: 0 + +**Step 3: Multi-Source Validation** +- Claims with ≥2 sources (≥5 credibility each) → verified +- Claims with 1 source (≥8 credibility) → provisional +- Claims with 0 sources or <5 credibility → unverified + +**Step 4: Status Assignment** +- **verified:** ≥2 credible sources, no contradictions +- **provisional:** 1 credible source, needs confirmation +- **unverified:** 0 credible sources, flagged for review +- **disputed:** Contradictory sources, requires investigation +- **revoked:** Proven false, removed from dossier + +--- + +## Final Intelligence Dossier Structure + +### File: `NAVIDOCS_INTELLIGENCE_DOSSIER.md` + +```markdown +# NaviDocs Yacht Sales Intelligence Dossier +## Riviera Plaisance Opportunity Analysis + +**Generated:** 2025-11-13 +**Session ID:** if://conversation/navidocs-yacht-sales-2025-11-13 +**Guardian Approval:** [XX/20] ([YY]% consensus) +**Evidence Quality:** [ZZ]% verified claims + +--- + +## Executive Summary + +### Market Opportunity +[2-paragraph summary of Session 1 findings] +- Market size: €X.XB Mediterranean yacht sales +- Riviera broker count: XX brokerages +- Revenue potential: €XXX,XXX annually + +### Technical Solution +[2-paragraph summary of Session 2 architecture] +- NaviDocs enhancement: warranty tracking, Home Assistant integration +- Implementation timeline: 4 weeks +- Key features: expiration alerts, claim generation, offline mode + +### Business Case +[2-paragraph summary of Session 3 ROI] +- Broker savings: €8K-€33K per yacht (warranty tracking) +- Time savings: 6 hours → 20 minutes (as-built package) +- Pricing: €99-€299/month (tiered model) + +### Implementation Readiness +[2-paragraph summary of Session 4 plan] +- 4-week sprint (Nov 13 - Dec 10) +- Production-ready architecture (13 tables, 40+ APIs) +- Security fixes prioritized (5 vulnerabilities addressed) + +--- + +## Table of Contents + +1. Market Analysis (Session 1) +2. Technical Architecture (Session 2) +3. Sales Enablement Materials (Session 3) +4. Implementation Roadmap (Session 4) +5. Evidence Validation & Citations +6. Guardian Council Vote +7. Appendices + +--- + +## 1. Market Analysis + +### 1.1 Mediterranean Yacht Sales Market +[Session 1 findings with citations] + +**Market Size:** +- €2.3B annual sales (2024-2025) [Citation: if://citation/market-size-mediterranean] +- 4,500 yachts sold annually [Citation: if://citation/yacht-sales-volume] +- Average price: €500K (€300K-€5M range) [Citation: if://citation/avg-yacht-price] + +**Riviera Brokerage Landscape:** +- 120 active brokerages [Citation: if://citation/riviera-broker-count] +- 8-12 yachts per brokerage per year [Citation: if://citation/sales-per-broker] +- Documentation prep: 6 hours per sale [Citation: if://citation/doc-prep-time] + +### 1.2 Competitive Landscape +[Session 1 competitor matrix] + +**Top 5 Competitors:** +1. BoatVault - €150/month, basic document storage +2. DeckDocs - €200/month, OCR included +3. YachtArchive - €99/month, no warranty tracking +4. [... continue] + +**NaviDocs Differentiation:** +- Home Assistant integration (unique) +- Multi-jurisdiction document assembly (unique) +- Warranty expiration alerts (2/5 competitors) + +### 1.3 Broker Pain Points +[Session 1 research] + +**Documentation Challenges:** +- 6 hours manual prep per sale [Citation: if://citation/manual-prep-time] +- €8K-€33K missed warranty claims [Citation: if://citation/warranty-miss-cost] +- 9-jurisdiction complexity (flag changes) [Citation: if://citation/jurisdiction-count] + +--- + +## 2. Technical Architecture + +### 2.1 System Overview +[Session 2 architecture diagram] + +```mermaid +graph TD + A[NaviDocs Frontend] --> B[Express.js API] + B --> C[SQLite Database] + B --> D[BullMQ + Redis] + D --> E[Warranty Expiration Worker] + E --> F[IF.bus Event System] + F --> G[Home Assistant Webhook] + F --> H[Email Notification] +``` + +### 2.2 Database Schema Changes +[Session 2 migrations] + +**New Tables:** +1. `warranty_tracking` - 10 columns, 3 indexes +2. `sale_workflows` - 7 columns, 2 indexes +3. `webhooks` - 8 columns, 2 indexes +4. `notification_templates` - 6 columns + +### 2.3 API Endpoints (New) +[Session 2 API spec] + +**Warranty Tracking:** +- POST /api/warranties +- GET /api/warranties/expiring +- GET /api/boats/:id/warranties + +**Sale Workflow:** +- POST /api/sales +- POST /api/sales/:id/generate-package +- POST /api/sales/:id/transfer + +[... continue with all sections] + +--- + +## 5. Evidence Validation & Citations + +### 5.1 Evidence Quality Scorecard + +**Total Claims:** XXX +**Verified Claims:** YYY (ZZ%) +**Provisional Claims:** AA (BB%) +**Unverified Claims:** CC (DD%) + +**Average Credibility Score:** X.X / 10 + +**Source Breakdown:** +- Primary sources: XX claims +- Secondary sources: YY claims +- Tertiary sources: ZZ claims + +### 5.2 Citation Database + +[Link to session-5-citations-master.json] + +**Top 10 Critical Citations:** +1. if://citation/warranty-savings-8k-33k +2. if://citation/market-size-mediterranean +3. if://citation/doc-prep-time-6hours +4. [... continue] + +### 5.3 Unverified Claims Requiring Follow-Up + +1. "MLS integration reduces listing time by 50%" - No source yet +2. "Brokers willing to pay €299/month" - Needs pricing survey +3. [... continue] + +--- + +## 6. Guardian Council Vote + +### 6.1 Voting Summary + +**Approval:** [XX/20] ([YY]% consensus) +**Abstentions:** [AA] +**Rejections:** [BB] + +**Outcome:** [Strong Consensus / Weak Consensus / Requires Revision] + +### 6.2 Vote Breakdown by Guardian + +| Guardian | Vote | Empirical | Logical | Practical | Average | Reason | +|----------|------|-----------|---------|-----------|---------|--------| +| Empiricism | Approve | 9 | 8 | 9 | 8.7 | Market research well-sourced | +| Verificationism | Approve | 8 | 9 | 8 | 8.3 | Acceptance criteria testable | +| Fallibilism | Abstain | 7 | 7 | 6 | 6.7 | Timeline lacks uncertainty bounds | +| [... continue for all 20] | + +### 6.3 Dissent Analysis + +**Abstentions (requiring revision):** +1. **Fallibilism:** Timeline needs contingency planning + - Required change: Add best/likely/worst case estimates +2. **Nagarjuna:** Market projections assume stability + - Required change: Acknowledge economic uncertainty + +**Rejections (fundamental issues):** +- [None / List any rejections] + +### 6.4 Consensus Interpretation + +**Guardian Council Assessment:** +[2-3 paragraphs synthesizing vote results] + +If >90% approval: +> "The Guardian Council has achieved strong consensus (XX% approval) on the NaviDocs intelligence dossier. The market analysis is empirically sound, the technical architecture is logically coherent, and the implementation plan is practically viable. Dissenting voices raised valid concerns regarding [list], which have been addressed through [revisions/clarifications]." + +If <90% approval: +> "The Guardian Council requires revision before approving the dossier. Primary concerns include [list top 3 issues]. Recommend addressing [specific changes] and resubmitting for vote." + +--- + +## 7. Appendices + +### Appendix A: Session Handoff Documents +- Session 1 Handoff: intelligence/session-1/session-1-handoff.md +- Session 2 Handoff: intelligence/session-2/session-2-handoff.md +- [... continue] + +### Appendix B: Code Templates +- server/services/event-bus.service.js +- server/services/warranty.service.js +- [... continue] + +### Appendix C: Sales Collateral +- Pitch deck (PDF export) +- Demo script (annotated screenshots) +- ROI calculator (web app link) + +### Appendix D: Technical Specifications +- OpenAPI spec (api-spec.yaml) +- Database migrations (migrations/*.sql) +- Gantt chart (sprint-timeline.png) + +--- + +**Dossier Signature:** +``` +if://doc/navidocs-intelligence-dossier-2025-11-13 +Created: 2025-11-13T16:00:00Z +Guardian Approval: [XX/20] ([YY]%) +Evidence Quality: [ZZ]% verified +Signature: ed25519:[signature_bytes] +``` +``` + +--- + +## Output Format + +### Deliverable 1: Intelligence Dossier +**File:** `NAVIDOCS_INTELLIGENCE_DOSSIER.md` +**Size:** ~50-100 pages (comprehensive) +**Format:** Markdown with Mermaid diagrams, tables, citations + +### Deliverable 2: Guardian Council Vote +**File:** `session-5-guardian-vote.json` + +```json +{ + "session_id": "if://conversation/navidocs-yacht-sales-2025-11-13", + "vote_date": "2025-11-13T16:00:00Z", + "dossier": "if://doc/navidocs-intelligence-dossier", + "guardians": [ + { + "name": "Empiricism", + "vote": "approve", + "scores": {"empirical": 9, "logical": 8, "practical": 9}, + "average": 8.7, + "reason": "Market research well-sourced with ≥2 citations per claim" + }, + { + "name": "Fallibilism", + "vote": "abstain", + "scores": {"empirical": 7, "logical": 7, "practical": 6}, + "average": 6.7, + "reason": "4-week timeline lacks uncertainty bounds and contingency planning" + } + ], + "tally": { + "total_guardians": 20, + "approve": 18, + "abstain": 2, + "reject": 0, + "approval_percentage": 90.0 + }, + "outcome": "strong_consensus", + "dissent_summary": [ + "Fallibilism requests timeline variance analysis", + "Nagarjuna requests economic uncertainty acknowledgment" + ] +} +``` + +### Deliverable 3: Master Citation Database +**File:** `session-5-citations-master.json` + +```json +{ + "session_id": "if://conversation/navidocs-yacht-sales-2025-11-13", + "total_citations": 47, + "verified_citations": 42, + "provisional_citations": 3, + "unverified_citations": 2, + "citations": [ + { + "citation_id": "if://citation/warranty-savings-8k-33k", + "claim": "NaviDocs prevents €8K-€33K warranty losses per yacht", + "sources": [ + { + "type": "file", + "path": "intelligence/session-1/market-analysis.md", + "line_range": "45-67", + "quality": "primary", + "credibility": 9 + }, + { + "type": "file", + "path": "docs/debates/02-yacht-management-features.md", + "line_range": "120-145", + "quality": "primary", + "credibility": 9 + } + ], + "status": "verified", + "confidence_score": 0.95 + } + ] +} +``` + +### Deliverable 4: Evidence Quality Report +**File:** `session-5-evidence-quality.md` + +```markdown +# Evidence Quality Assessment +## NaviDocs Intelligence Dossier + +**Total Claims:** 47 +**Verified:** 42 (89.4%) +**Provisional:** 3 (6.4%) +**Unverified:** 2 (4.3%) + +### Quality Breakdown + +**Primary Sources (≥8 credibility):** 32 claims +- Codebase analysis: 12 claims +- Medium articles (NaviDocs docs): 8 claims +- Architecture analysis: 7 claims +- Local research files: 5 claims + +**Secondary Sources (5-7 credibility):** 10 claims +- Industry reports: 6 claims +- Competitor websites: 4 claims + +**Tertiary Sources (2-4 credibility):** 0 claims + +**Unverified (0-1 credibility):** 5 claims +- MLS integration time savings (no source) +- Broker pricing survey (hypothesis) +- [... continue] + +### Recommendations + +1. **High Priority:** Validate 2 unverified claims before Riviera meeting +2. **Medium Priority:** Convert 3 provisional claims to verified (add 2nd source) +3. **Low Priority:** Archive tertiary sources for future reference +``` + +### Deliverable 5: Session Handoff +**File:** `session-5-handoff.md` + +```markdown +# Session 5 Handoff to Production Deployment + +## Mission Accomplished +- [x] Intelligence dossier synthesized (50 pages) +- [x] Guardian Council vote achieved (XX/20, YY% approval) +- [x] Citation database compiled (47 citations, 89% verified) +- [x] Evidence quality validated (primary sources dominate) + +## Guardian Consensus: [Strong Consensus / Requires Revision] + +**Approval:** XX/20 (YY%) +**Outcome:** [Ready for production / Needs revision] + +## Key Deliverables for Riviera Plaisance Meeting +1. Pitch deck (intelligence/session-3/session-3-pitch-deck.pdf) +2. Demo script (intelligence/session-3/session-3-demo-script.md) +3. ROI calculator (intelligence/session-3/session-3-roi-calculator.html) +4. Intelligence dossier (full backup documentation) + +## Token Consumption +- Total: XXX,XXX tokens ($X.XX) +- Session 1: 52,450 tokens ($0.86) +- Session 2: 68,200 tokens ($1.42) +- Session 3: 59,800 tokens ($1.12) +- Session 4: 61,500 tokens ($1.18) +- Session 5: XX,XXX tokens ($X.XX) +- **Total Budget Used:** $XX / $100 (XX% efficiency) + +## Evidence Quality Metrics +- Total claims: 47 +- Verified: 42 (89.4%) +- Average credibility: 8.2/10 +- IF.TTT compliance: ✅ 100% + +## Next Steps (Post-Meeting) +1. Execute Session 4 implementation plan (4-week sprint) +2. Address guardian dissent (timeline contingency, economic uncertainty) +3. Validate 2 unverified claims (MLS integration, pricing survey) +4. Deploy production environment (Week 4, Dec 8-10) + +## Blockers for Production +- [ ] Security fixes required (5 vulnerabilities from NAVIDOCS_HANDOVER.md) +- [ ] Database migrations tested (dev environment) +- [ ] Home Assistant integration validated (live webhook test) + +**Next Session Input:** Read NAVIDOCS_INTELLIGENCE_DOSSIER.md +**Focus:** 4-week development sprint execution (Session 4 plan) +``` + +--- + +## IF.TTT Compliance Checklist + +- [ ] All claims have ≥2 source citations (or flagged as unverified) +- [ ] File hashes (SHA-256) for all web sources +- [ ] Git commits (SHA-1) for codebase references +- [ ] Guardian vote recorded (20/20 votes collected) +- [ ] Dissent reasons documented +- [ ] Evidence quality scored (0-10 scale) +- [ ] Citation database validated (JSON schema) +- [ ] Unverified claims flagged for follow-up + +--- + +## Success Criteria + +**Minimum Viable Output:** +- Intelligence dossier compiled (all sessions synthesized) +- Guardian Council vote achieved (>90% approval target) +- Citation database complete (≥80% verified claims) +- Evidence quality scorecard (credibility ≥7.0 average) + +**Stretch Goals:** +- 100% Guardian consensus (all 20 approve) +- 95%+ verified claims (only 5% unverified) +- Primary sources dominate (≥70% of claims) +- Zero contradictions between sessions + +--- + +**Start Command:** Deploy to Claude Code Cloud after Sessions 1-4 complete +**End Condition:** All deliverables committed to `dannystocker/navidocs` repo under `intelligence/session-5/`