# Domain — Product Repos (MCP + A2A Opportunities)

This document captures **concrete, code-grounded** MCP/A2A touchpoints per product.
Each section lists what exists today (real files/APIs) and where MCP tools or A2A agents add leverage.

---

## Cross-product baseline (all 6 products)

Every product already wires these platform-service capabilities:

| Capability         | Client module                                | Status                                      |
| ------------------ | -------------------------------------------- | ------------------------------------------- |
| Telemetry events   | `@bytelyst/telemetry-client`                 | ✅ Live in all 6                            |
| Feature flags      | `/api/flags/poll`                            | ✅ Live in web/RN/iOS/Android               |
| Kill switch        | `@bytelyst/kill-switch-client`               | ✅ Live in NomGap, LysnrAI, JarvisJr        |
| Auth / JWT         | `@bytelyst/auth-client` or platform wrappers | ✅ All products                             |
| Remote diagnostics | `@bytelyst/diagnostics-client`               | ✅ Wired in all 6 products (web + iOS + RN) |
| Extraction service | `@bytelyst/extraction`                       | ✅ MindLyst + LysnrAI (partial)             |

**Diagnostics client is fully wired** across all 6 products. Type safety fixes and `void .start()` applied in a follow-up review pass (see fix commits per product below).

### Cross-product checklist

- [x] ChronoMind — wire `@bytelyst/diagnostics-client` (`web/src/app/providers.tsx`) — [cb79c9b](https://github.com/saravanakumardb1/learning_ai_clock/commit/cb79c9b)
- [x] JarvisJr — wire `@bytelyst/diagnostics-client` (`web/src/app/layout.tsx`) — [5bc1fcc](https://github.com/saravanakumardb1/learning_ai_jarvis_jr/commit/5bc1fcc)
- [x] MindLyst — wire `@bytelyst/diagnostics-client` (`mindlyst-native/web/src/app/providers.tsx`) — [a90bff2](https://github.com/saravanakumardb1/learning_multimodal_memory_agents/commit/a90bff2)
- [x] NomGap — wire `@bytelyst/diagnostics-client` (`src/app/_layout.tsx`) — [6371266](https://github.com/saravanakumardb1/learning_ai_fastgap/commit/6371266)
- [x] LysnrAI — wire `@bytelyst/diagnostics-client` (`user-dashboard-web/src/app/providers.tsx`) — [dacccda](https://github.com/saravanakumardb1/learning_voice_ai_agent/commit/dacccda)
- [x] PeakPulse iOS — wire `ByteLystDiagnostics` (`DiagnosticsService.swift`) — [7d4b86f](https://github.com/saravanakumardb1/learning_ai_peakpulse/commit/7d4b86f)

---

## ChronoMind (`learning_ai_clock`)

### What exists today

**`web/src/lib/`** (scanned):

- `telemetry.ts` — `@bytelyst/telemetry-client`, productId `chronomind`, tracks timer events
- `feature-flags.ts` — polls `/api/flags/poll`, 5-min interval, flags: `routines_enabled`, `focus_mode_enabled`, `calendar_import_enabled`, `cloud_sync_enabled`
- `platform-sync.ts` — offline queue + conflict detection for timers + routines (batch sync DTOs with `syncVersion`)
- `nl-parser.ts` (13 KB) — full natural-language → timer parsing engine (local, no LLM)
- `adaptive-snooze.ts` — learns snooze patterns per-user
- `billing-client.ts`, `auth-api.ts`, `use-sync.ts`

**Backend modules** (`backend/src/modules/`):
`timers/`, `routines/`, `shared-timers/`, `households/`, `webhooks/`

### MCP tools

```
chronomind.timers.list(userId)
chronomind.timers.create(input)
chronomind.timers.delete(id)
chronomind.routines.list(userId)
chronomind.routines.validate(routineId)      ← verify no step duration overflow
chronomind.sharedTimers.share(timerId, targets)
chronomind.households.listMembers(householdId)
chronomind.syncStatus(userId)               ← returns offline queue depth + last sync
```

### A2A agents

- **NLParserEvalAgent**: submits sample phrases to `nl-parser.ts` (or its extraction task equivalent), validates parsed timer fields, flags regressions after engine changes.
- **SyncConflictDiagnosticsAgent**: monitors `telemetry` for `sync_conflict` events → auto-starts a diagnostics session targeting the affected user; collects logs and generates a conflict report.
- **RoutineQualityAgent**: runs routine templates against the scheduler engine; flags routines that exceed household sleep time, overlap with calendar events, or have zero completion rates.
- **CalendarImportAgent**: automates `.ics` ingest + validation + conflict detection on import.

### Highest-ROI first

- [x] Wire `@bytelyst/diagnostics-client` (`web/src/app/providers.tsx` + `web/src/lib/diagnostics.ts`) — [cb79c9b](https://github.com/saravanakumardb1/learning_ai_clock/commit/cb79c9b)
- [x] `nl-timer-parse` extraction task (`id: 'timer-parse'`) — _already seeded in extraction-service `seed.ts`_
- [x] `chronomind.syncStatus` endpoint in `backend/src/modules/timers/routes.ts` — [4a3ac76](https://github.com/saravanakumardb1/learning_ai_clock/commit/4a3ac76)
- [x] Fix `getAuthToken` type-safety + `void .start()` + `unsyncedCount` logic — [909daf8](https://github.com/saravanakumardb1/learning_ai_clock/commit/909daf8)

---

## NomGap (`learning_ai_fastgap`)

### What exists today

**`src/api/`** (scanned):

- `fasting-api.ts` — sessions CRUD, `getUserStats()`, `getWeeklyStats()`
- `push-api.ts` — 7 typed trigger functions: `fireStreakRisk`, `fireFastMilestone`, `fireStageTransition`, `fireSocialInvite`, `fireWeeklyDigest`, `fireAchievementUnlocked`, `fireRefeedingReminder`
- `social-api.ts`, `meal-api.ts`, `blob-api.ts`, `billing-api.ts`

**`src/lib/`** (scanned):

- `telemetry.ts` — `@bytelyst/telemetry-client`, MMKV-backed storage for `installId`, mobile/RN transport
- `kill-switch.ts` — `@bytelyst/kill-switch-client`, fail-open
- `feature-flags.ts` — delegated to `@bytelyst/feature-flag-client`

**Backend modules**: `fasting-sessions/`, `fasting-protocols/`, `body-stages/`, `meal-log/`, `push-triggers/`, `social-fasting/`

### MCP tools

```
nomgap.fasting.createSession(userId, protocolId)
nomgap.fasting.getSession(id)
nomgap.fasting.getUserStats(userId)            ← streak, longestFast, completionRate
nomgap.fasting.getWeeklyStats(userId)
nomgap.push.fire(type, userId, variables?)     ← wraps all 7 trigger types
nomgap.protocols.list()
nomgap.protocols.get(id)
nomgap.bodyStages.list()                       ← stage thresholds + descriptions
nomgap.social.listGroupFasts(userId)
```

### A2A agents

- **EngagementAgent**: monitors `streak_risk` signals from telemetry → calls `nomgap.push.fire('streak_risk', userId)` proactively; escalates to `weekly_digest` if streak drops to zero.
- **SafetyMonitorAgent**: watches for fasts approaching 48 h threshold → fires `refeeding_reminder` at 24 h, 48 h (safety-critical). Can be A2A-chained from the `ExtendedFastDetectionAgent`.
- **SocialFastCoordinatorAgent**: when a user creates a group fast, A2A: notify all members (`fireSocialInvite`), schedule milestone push at each stage transition, send `weekly_digest` summary.
- **ProtocolTuningAgent**: uses telemetry completion-rate data + extraction to identify which protocol parameters correlate with abandonment; proposes protocol adjustments.

### Highest-ROI first

- [x] Wire `@bytelyst/diagnostics-client` (`src/app/_layout.tsx` + `src/lib/diagnostics.ts`) — [6371266](https://github.com/saravanakumardb1/learning_ai_fastgap/commit/6371266)
- [x] `nomgap.push.fire` convenience functions — _all 7 trigger types already existed in `src/api/push-api.ts`_
- [x] Fix `getAuthToken` type-safety + `void .start()` + `mmkvStorage` cast — [7a87a6c](https://github.com/saravanakumardb1/learning_ai_fastgap/commit/7a87a6c)
- [x] SafetyMonitorAgent spec — `docs/MCP+A2A/agents/SafetyMonitorAgent.md`

---

## PeakPulse (`learning_ai_peakpulse`)

### What exists today

**Backend modules** (scanned):

- `peak-sessions/` — `PeakSessionDoc`: activityType (`hiking`|`skiing`), GPS `TrackPointDoc[]` (lat/lon/alt/speed/accuracy), `HapticEventDoc[]`, `WeatherSnapshotDoc` (temp, wind, UV), `SkiMetricsDoc` (runCount, verticalDescent, liftTime), `locationName`, `barometerUsed`, `unitPreference`
- `peak-routes/` — route documents

**iOS Platform/** (scanned):

- `PlatformSyncManager.swift` — `BLSyncEngine` wrapper; uploads sessions, downloads, handles 401 token refresh
- `TelemetryService.swift` — `BLTelemetryClient` wrapper; tracks session events + milestones + errors
- `AuthService.swift`, `FeatureFlagService.swift`, `KillSwitchService.swift`, `KeychainHelper.swift`

### MCP tools

```
peakpulse.sessions.list(userId, activityType?)
peakpulse.sessions.get(sessionId)
peakpulse.sessions.export(sessionId, format)    ← GPX or JSON
peakpulse.routes.list(userId)
peakpulse.routes.get(routeId)
peakpulse.syncStatus(userId)                    ← upload queue depth + last sync
peakpulse.weather.getSnapshot(sessionId)        ← WeatherSnapshotDoc for a session
```

### A2A agents

- **RouteSafetyAssessmentAgent**: given a completed session's GPS track + `WeatherSnapshotDoc`, calls extraction service for risk assessment (elevation gain + UV + wind), produces a safety brief.
- **SyncDiagnosticsAgent**: when `sync_upload_failed` telemetry event is detected → starts a diagnostics session targeting that device; collects network traces during next sync attempt.
- **GoalCoachingAgent**: queries `GoalsEngine` data + session history; proposes next goal based on performance trends.
- **SkiRunAnalystAgent**: given `SkiMetricsDoc` (runCount, verticalDescent, liftTime, skiTime), identifies run quality trends across sessions; flags anomalies (e.g., sudden speed drop on a known run).

### Highest-ROI first

- [x] Wire `ByteLystDiagnostics` into iOS `PeakPulseApp.swift` (`DiagnosticsService.swift`) — [7d4b86f](https://github.com/saravanakumardb1/learning_ai_peakpulse/commit/7d4b86f)
- [x] `peakpulse.sessions.export` endpoint (`GET /peak/sessions/:id/export`) — [bfeb465](https://github.com/saravanakumardb1/learning_ai_peakpulse/commit/bfeb465)
- [x] Fix `pollIntervalSeconds` → `pollIntervalMs` in `DiagnosticsService.swift` — [690e007](https://github.com/saravanakumardb1/learning_ai_peakpulse/commit/690e007)
- [x] SyncDiagnosticsAgent spec — `docs/MCP+A2A/agents/SyncDiagnosticsAgent.md`

---

## JarvisJr (`learning_ai_jarvis_jr`)

### What exists today (this product IS a multi-agent platform)

**`web/src/lib/`** (scanned):

- `agent-client.ts` — `listAgents`, `getAgent`, `createAgent`, `updateAgent`, `deleteAgent`, `duplicateAgent`
- `session-client.ts` — `SessionRecord` includes `transcript`, `summary`, `coachingNotes[]`, `exercises[]`, `skillMetrics: Record<string, number>`, `getSessionStats()`
- `marketplace-client.ts` — full lifecycle: `browseCatalog`, `getListingDetail`, `installListing`, `uninstallListing`, `listInstalled`, `addReview`, `createListing`, `listMyListings`, `submitForReview`

**Backend modules** (scanned):

- `jarvis-agents/` — `AgentConfig` (systemPrompt, voiceId, coachingFramework, accentColor, difficultyLevel, privacyLevel, checkInSchedule)
- `jarvis-sessions/` — session with transcript + coaching artefacts
- `jarvis-memory/` — `JarvisMemoryDoc` with `type` (skill_note/preference/goal/context/exercise), `importance: 0–1`, `expiresAt`
- `jarvis-teams/` — enterprise team management
- `marketplace/` — `ListingDoc` (status: draft→pending→published→suspended, `isVerified`, cert statuses: pending/approved/rejected)

**iOS Shared/Engine/** (5 files):
SessionEngine, PromptBuilder, ArtifactExtractor, MemoryManager, (+ 1 more)

**iOS Shared/Voice/** (3 files):
VoiceSessionManager, AudioSessionHelper, VAD

### MCP tools

```
jarvis.agents.list(userId)
jarvis.agents.create(config)
jarvis.agents.duplicate(agentId)
jarvis.sessions.list(userId, agentId?)
jarvis.sessions.getStats(userId)                ← totalSessions, streak, perAgent
jarvis.memory.list(agentId, type?, minImportance?)
jarvis.memory.create(agentId, sessionId, type, content, importance)
jarvis.memory.prune(agentId, maxItems, minImportance)   ← memory hygiene
jarvis.marketplace.listPending()                ← admin: listings awaiting review
jarvis.marketplace.certify(listingId)
jarvis.marketplace.suspend(listingId, reason)
jarvis.marketplace.feature(listingId, featured)
jarvis.teams.listMembers(teamId)
```

### A2A agents

This product's own coaching "crew" maps naturally to A2A:

- **MarketplaceCertificationPipeline** (A2A workflow):
  1. `SubmissionIngestionAgent` — ingests listing draft, validates required fields (systemPrompt, coachingFramework, category, tags).
  2. `ContentSafetyAgent` — checks systemPrompt + description for policy violations via extraction.
  3. `QualityEvalAgent` — runs a sample session against the agent config, evaluates coherence.
  4. `CertificationDecisionAgent` — aggregates results, sets `isVerified`, notifies author.
- **MemoryCurationAgent**: periodically queries agent memories with `minImportance < 0.3`, decays or expires stale entries, promotes high-importance items.
- **ProgressAnalystAgent**: given `skillMetrics` across N sessions, identifies plateaus, recommends difficulty level changes or supplementary agents.
- **TeamProvisioningAgent**: when a new `jarvis-teams` member joins, A2A: recommends starter agents, seeds initial memories, schedules first check-in.

### Highest-ROI first

- [x] Wire `@bytelyst/diagnostics-client` (`web/src/app/layout.tsx` + `web/src/lib/diagnostics.ts`) — [5bc1fcc](https://github.com/saravanakumardb1/learning_ai_jarvis_jr/commit/5bc1fcc)
- [x] `jarvis.memory.prune` endpoint (`POST /jarvis/agents/:agentId/memory/prune`) — _already existed in codebase_
- [x] MarketplaceCertificationPipeline A2A spec — [docs/MCP+A2A/agents/MarketplaceCertificationPipeline.md](agents/MarketplaceCertificationPipeline.md)
- [x] Fix `getStoredToken` type-safety + `void .start()` + remove dead `void pathname` useEffect — [b31c04b](https://github.com/saravanakumardb1/learning_ai_jarvis_jr/commit/b31c04b)

---

## MindLyst (`learning_multimodal_memory_agents`)

### What exists today

**`web/src/lib/`** (scanned):

- `extraction-client.ts` — **three live task IDs**: `triage`, `memory-insight`, `reflection-enrichment` — backed by extraction-service
- `telemetry.ts` — `@bytelyst/telemetry-client`, web/beacon, productId `mindlyst`
- `feature-flags.ts`, `billing-client.ts`, `cosmos.ts` (direct Cosmos in web)

**Backend modules** (scanned):

- `memory/` — `MemoryItemDoc` with `TriageResult` (contentType, urgencyScore 0–1, emotionScore −1–+1, confidenceScore 0–1, suggestedBrainId, entities[], suggestedActions[]), sourceType (voice/image/link/email/text), captureSurface (app/widget/share_sheet/siri/email/web/notification_reply), blob media refs (audio + image)
- `brains/` — role-based "Brain" CRUD
- `reflections/` — reflection journal entries
- `daily-briefs/` — `DailyBriefDoc`: greeting, priorityItems[], brainSummaries (brainId → summary text), streakMessage, motivationalQuote
- `streaks/` — engagement streak tracking

### MCP tools

```
mindlyst.memory.list(userId, brainId?, filter?)    ← filter: forgotten | completed_today
mindlyst.memory.get(itemId)
mindlyst.memory.getTriageResult(itemId)            ← TriageResult with all scores
mindlyst.memory.retriage(itemId)                   ← re-run extraction on stale triage
mindlyst.brains.list(userId)
mindlyst.briefs.generate(userId, date)             ← trigger daily-brief generation
mindlyst.briefs.get(userId, date)
mindlyst.streaks.get(userId)
mindlyst.extractions.run(taskId, text)             ← direct extraction (all 3 task IDs)
```

### A2A agents

- **DailyBriefGenerationPipeline** (A2A workflow):
  1. `MemoryCollectorAgent` — queries recent memory items per brain, ranked by urgencyScore.
  2. `SummaryAgent` — calls `extraction.extract(text, 'memory-insight')` per brain.
  3. `BriefComposerAgent` — assembles DailyBriefDoc (greeting + priorityItems + brainSummaries).
  4. `DeliveryAgent` — stores brief + triggers push notification.
- **TriageQualityAgent**: queries memory items with `confidenceScore < 0.5`, re-runs extraction, proposes updated brain routing.
- **BrainOverflowAgent**: detects brains with >N items, no completions in T days → suggests archiving or reassignment.
- **ReflectionSynthesisAgent**: given recent reflections, runs `reflection-enrichment` extraction, surfaces themes and proposes weekly summary.

### Highest-ROI first

- [x] Wire `@bytelyst/diagnostics-client` (`mindlyst-native/web/src/app/providers.tsx` + `src/lib/diagnostics.ts`) — [a90bff2](https://github.com/saravanakumardb1/learning_multimodal_memory_agents/commit/a90bff2)
- [x] `mindlyst.memory.retriage` endpoint (`POST /memory-items/:id/retriage`) — [ae5c755](https://github.com/saravanakumardb1/learning_multimodal_memory_agents/commit/ae5c755)
- [x] DailyBriefGenerationPipeline A2A spec — [docs/MCP+A2A/agents/DailyBriefGenerationPipeline.md](agents/DailyBriefGenerationPipeline.md)
- [x] Fix retriage to parse `ExtractionItem[]` array correctly + `getStoredToken` type-safety — [31682dc](https://github.com/saravanakumardb1/learning_multimodal_memory_agents/commit/31682dc)

---

## LysnrAI (`learning_voice_ai_agent`)

### What exists today

**Backend modules** (scanned):

- `transcripts/` — `TranscriptDoc`: rawText, cleanedText, wordCount, duration, tokensUsed, context, source, `extractions[]`, `extractionMetadata`, `extractedAt` ← extraction pipeline is **partially wired** (fields exist, not always populated)
- `sessions/` — dictation session lifecycle
- `organizations/` — team/org management
- `api-tokens/` — API token CRUD
- `themes/` — UI theme management
- `export/` — data export module
- `webhooks/` — webhook subscriptions

**`src/audio/`** (scanned):

- `stt_router.py` — connectivity-aware STT router: Azure Speech SDK (online) / local Whisper (offline) automatic fallback
- `azure_stt.py` — Azure Speech SDK integration

**`src/llm/`** (scanned):

- `llm_factory.py` — cloud-agnostic factory: `create_llm_client()` returns `openai.OpenAI` or `openai.AzureOpenAI` depending on `LLM_PROVIDER` env var / endpoint URL auto-detection

**`src/cloud/`**: `blob_client.py`, `telemetry.py`, `crash_reporter.py`, `api_sync.py`, `cosmos_client.py`

### MCP tools

```
lysnrai.transcripts.list(userId, limit?, after?)
lysnrai.transcripts.get(id)
lysnrai.transcripts.runExtraction(id)              ← populate extractions[] field
lysnrai.transcripts.exportBatch(userId, format)    ← JSON / TXT via export module
lysnrai.sessions.stats(userId)
lysnrai.orgs.list()
lysnrai.orgs.get(orgId)
lysnrai.apiTokens.list(userId)
lysnrai.apiTokens.rotate(tokenId)
lysnrai.stt.getBackendStatus()                     ← online (Azure) vs offline (Whisper)
```

### A2A agents

- **KeyboardDiagnosticsAgent**: monitors `error` telemetry events from iOS keyboard extension → auto-creates a targeted diagnostics session for that `anonymousInstallId`; collects logs until the error reproduces; drafts a bug report.
- **TranscriptExtractionPipelineAgent**: queries transcripts where `extractedAt IS NULL` → calls extraction service for each → updates `extractions[]` + `extractionMetadata` in batch. (Fills the existing schema fields that today often remain empty.)
- **STTFallbackMonitorAgent**: watches telemetry for `stt_provider=whisper` events (offline fallback) vs expected Azure events; if offline rate exceeds threshold → triggers a diagnostics session to capture network state.
- **OrgProvisioningAgent**: when a new org is created (webhook event) → A2A: create default API token, apply default theme, seed initial users.

### Highest-ROI first

- [x] Wire `@bytelyst/diagnostics-client` (`user-dashboard-web/src/app/providers.tsx` + `src/lib/diagnostics.ts`) — [dacccda](https://github.com/saravanakumardb1/learning_voice_ai_agent/commit/dacccda)
- [x] Transcript extraction endpoint (`POST /transcripts/:id/extract`) — [3164a61](https://github.com/saravanakumardb1/learning_voice_ai_agent/commit/3164a61)
- [x] `lysnrai.stt.getBackendStatus` endpoint (`GET /transcripts/stt-status`) — [f79ab73](https://github.com/saravanakumardb1/learning_voice_ai_agent/commit/f79ab73)
- [x] Fix `payload.entities` → `payload.extractions` bug (was silently empty) + lint fixes — [3452025](https://github.com/saravanakumardb1/learning_voice_ai_agent/commit/3452025)

---

## Recommended first A2A workflows to ship (re-prioritised)

| Priority | Product    | Workflow                                          | Why first                                                 |
| -------- | ---------- | ------------------------------------------------- | --------------------------------------------------------- |
| 1        | All        | SupportTriageAgent + DiagnosticsOrchestratorAgent | Zero per-product code; needs only diagnostics-client init |
| 2        | MindLyst   | DailyBriefGenerationPipeline                      | Core product feature; extraction already live             |
| 3        | LysnrAI    | TranscriptExtractionPipelineAgent                 | Schema ready; fills real user-facing gap                  |
| 4        | JarvisJr   | MarketplaceCertificationPipeline                  | Blocks marketplace launch; no manual process exists       |
| 5        | NomGap     | SafetyMonitorAgent                                | Safety-critical; push trigger API ready                   |
| 6        | ChronoMind | SyncConflictDiagnosticsAgent                      | Sync conflicts are top ChronoMind support ticket          |
| 7        | PeakPulse  | RouteSafetyAssessmentAgent                        | Extraction + GPS data; new UX capability                  |

## Product-specific MCP namespace summary

| Product    | Backend port | Key namespaces                                                                                 |
| ---------- | ------------ | ---------------------------------------------------------------------------------------------- |
| ChronoMind | 4011         | `chronomind.timers`, `chronomind.routines`, `chronomind.sharedTimers`, `chronomind.households` |
| NomGap     | 4013         | `nomgap.fasting`, `nomgap.push`, `nomgap.protocols`, `nomgap.social`                           |
| PeakPulse  | 4010         | `peakpulse.sessions`, `peakpulse.routes`, `peakpulse.weather`                                  |
| JarvisJr   | 4012         | `jarvis.agents`, `jarvis.sessions`, `jarvis.memory`, `jarvis.marketplace`, `jarvis.teams`      |
| MindLyst   | 4014         | `mindlyst.memory`, `mindlyst.brains`, `mindlyst.briefs`, `mindlyst.extractions`                |
| LysnrAI    | 4015         | `lysnrai.transcripts`, `lysnrai.sessions`, `lysnrai.orgs`, `lysnrai.apiTokens`, `lysnrai.stt`  |
