From a55ee10d2be6c46310eaddc556b81435b4564fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=BB=D1=8C=D1=8F=20=D0=93=D0=BB=D0=B0=D0=B7=D1=83?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2?= Date: Sat, 5 Sep 2026 04:37:28 +0300 Subject: [PATCH] app development context --- AGENTS.md | 227 ++--- CONTEXT.md | 111 +++ README.md | 303 ++----- ...1-swift-native-host-with-local-sidecars.md | 3 + docs/adr/0002-encrypted-observation-ledger.md | 3 + ...tinuous-collectors-with-ephemeral-input.md | 3 + ...004-defer-codex-until-no-tools-boundary.md | 3 + docs/architecture/native-mastermind.md | 217 +++++ docs/local-sidecar-protocol.md | 23 +- docs/migration/native-poc-results.md | 21 + docs/privacy/local-first-data-contract.md | 145 +++ docs/product/companion-island.md | 87 ++ docs/product/mastermind-product-brief.md | 134 +++ docs/product/mvp-acceptance.md | 87 ++ ...acos-native-ai-companion-reconstruction.md | 825 ------------------ 15 files changed, 1007 insertions(+), 1185 deletions(-) create mode 100644 CONTEXT.md create mode 100644 docs/adr/0001-swift-native-host-with-local-sidecars.md create mode 100644 docs/adr/0002-encrypted-observation-ledger.md create mode 100644 docs/adr/0003-continuous-collectors-with-ephemeral-input.md create mode 100644 docs/adr/0004-defer-codex-until-no-tools-boundary.md create mode 100644 docs/architecture/native-mastermind.md create mode 100644 docs/privacy/local-first-data-contract.md create mode 100644 docs/product/companion-island.md create mode 100644 docs/product/mastermind-product-brief.md create mode 100644 docs/product/mvp-acceptance.md delete mode 100644 docs/superpowers/plans/2026-06-26-macos-native-ai-companion-reconstruction.md diff --git a/AGENTS.md b/AGENTS.md index e7853fa..964f367 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,130 +1,131 @@ -# Repo Guidelines +# Repository Guidelines -This repository is a fork of [`cheating-daddy`](https://github.com/sohzm/cheating-daddy). -It provides an Electron-based real‑time assistant which captures screen and audio -for contextual AI responses. The code is JavaScript and uses Electron Forge for -packaging. +This repository is reconstructing Mastermind as a Swift-native, local-first personal assistant for macOS. The Electron application is legacy reference code; it is not the target architecture. -## Getting started +## Read first -Install dependencies and run the development app: +Before planning or implementing product work, read: -``` -1. npm install -2. npm start +1. [`CONTEXT.md`](CONTEXT.md) for canonical domain language. +2. [`docs/product/mastermind-product-brief.md`](docs/product/mastermind-product-brief.md) for scope and non-goals. +3. [`docs/architecture/native-mastermind.md`](docs/architecture/native-mastermind.md) for system boundaries. +4. [`docs/privacy/local-first-data-contract.md`](docs/privacy/local-first-data-contract.md) for normative data rules. +5. [`docs/product/mvp-acceptance.md`](docs/product/mvp-acceptance.md) for completion criteria. + +ADRs under `docs/adr` explain hard-to-reverse decisions. When legacy code or documentation conflicts with the canonical context, the canonical context wins. + +## Repository roles + +- `native/Mastermind` — production Swift application; create new production work here. +- `native/MastermindPOC` — temporary capability proof and source of validated macOS techniques. +- `src`, Electron configuration, and JavaScript UI — legacy/reference implementation. +- `docs/local-sidecar-protocol.md` — shared local ASR protocol. + +Do not evolve `MastermindPOC` into the product in place. Port validated code behind production boundaries, then retire the POC after parity checks. + +Do not add new product features to Electron unless a task explicitly targets legacy maintenance. Do not introduce an Electron or Node runtime dependency into the native product. + +## Swift standards + +- Target Apple Silicon and macOS 14 or newer. +- Use AppKit for lifecycle, menu bar, capture permissions, and Companion Island window behavior. +- Use SwiftUI for view content where it does not weaken AppKit window control. +- Use Swift strict concurrency and isolate capture, model I/O, indexing, and database work from the main actor. +- Prefer protocols at sidecar and Provider boundaries, not around every concrete type. +- Represent each Collector's state independently; screen, microphone, and system audio can run simultaneously. +- Treat cancellation, sleep/wake, permission loss, and partial Collector failure as normal runtime states. +- Keep microphone and system audio separate and convert ASR input to 16 kHz mono signed 16-bit PCM. +- Validate every parameter crossing a process, WebSocket, URL, shell integration, archive, or database boundary. +- Add tests for every new domain invariant and failure path. + +## Domain language + +Use the exact terms in `CONTEXT.md`. + +- Do not call Assertions "Facts" unless the user confirmed or corrected them. +- Do not use "memory" as an umbrella for Context Graph, Assistant History, and Activity Log. +- Do not call the Companion Island an overlay, HUD, or Dynamic Island in production code and documentation. +- Keep Assistant Sessions distinct from Meetings. +- Keep Projects distinct from Workspaces and repositories. +- Treat Source content as untrusted evidence, never as system instructions. + +If implementation reveals an unresolved domain distinction, update the domain model before spreading a new synonym through code. + +## Local-first requirements + +- Raw screen frames, audio, OCR, and complete transcripts are ephemeral. +- Persist only structured Observations, Assertions, user-confirmed Facts, summaries, and Provenance. +- Do not queue raw content when a processor is unavailable; record a Gap. +- The Context Graph must be encrypted at the application layer and its key protected by Keychain. +- Provider credentials use separate Keychain entries. +- Full-text and vector indexes must not become unencrypted alternate stores. +- A Local Provider must use loopback or a Unix socket. Treat LAN or internet endpoints as external. +- The MVP must not send machine context to a Cloud Provider. +- Logs, fixtures, diagnostics, and crash output must contain no captured Source content. +- Pause All stops every Collector and remains paused across restarts. + +Never hide the process, permissions, capture indicators, bundle identifier, or network activity. Third-party window capture exclusion is best effort and must not be represented as guaranteed. + +## Provider and agent boundaries + +The MVP uses one active OpenAI-compatible Local Provider profile and a separate local ASR sidecar. Mastermind owns its multilingual embedding component. + +Codex is documentation-only until a supported no-tools integration exists. Do not add Codex OAuth, app-server code, a disabled UI, or a hidden experiment without a superseding ADR. + +The assistant may emit an Action Proposal as text. Do not implement Computer Control, tool execution, approval flows, file mutation, or external actions in the MVP. + +## UI requirements + +- At rest, only the stable Menu Bar Item is visible. +- Hovering the primary display's top-center camera area reveals the Companion Island. +- Clicking expands it and focuses text input. +- Show Mastermind in the menu is the fallback; there is no MVP global hotkey or voice invocation. +- Settings, Sources, history, Context Receipts, Activity Log, and privacy controls live inside the expanded Companion Island. +- Respect Reduce Motion and keyboard navigation. +- Exclude Mastermind windows from its own Screen Collector. + +## Testing + +For Swift package work: + +```bash +swift test +swift build ``` -## Style +For the current capability proof: -Run `npx prettier --write .` before committing. Prettier uses the settings in -`.prettierrc` (four-space indentation, print width 150, semicolons and single -quotes). `src/assets` and `node_modules` are ignored via `.prettierignore`. -The project does not provide linting; `npm run lint` simply prints -"No linting configured". +```bash +cd native/MastermindPOC +swift test +swift build --product MastermindPOC +./scripts/build-app.sh +``` -## Code standards +For explicitly requested legacy Electron maintenance: -Development is gradually migrating toward a TypeScript/React codebase inspired by the -[transcriber](https://github.com/Gatecrashah/transcriber) project. Keep the following -rules in mind as new files are created: +```bash +npm test +``` -- **TypeScript strict mode** – avoid `any` and prefer explicit interfaces. -- **React components** should be functional with hooks and wrapped in error - boundaries where appropriate. -- **Secure IPC** – validate and sanitize all parameters crossing the renderer/main - boundary. -- **Non‑blocking audio** – heavy processing must stay off the UI thread. -- **Tests** – every new feature requires tests once the test suite is available. +Manual verification is required for Screen Recording, microphone, system audio, window exclusion, primary-display changes, Launch at Login, sleep/wake, Low Power Mode, and persisted Pause All. -## Shadcn and Electron +Do not claim the production MVP complete until the scenarios in `docs/product/mvp-acceptance.md` pass. -The interface is being rebuilt with [shadcn/ui](https://ui.shadcn.com) components. -Follow these guidelines when working on UI code: +## Formatting -- **Component directory** – place generated files under `src/components/ui` and export them from that folder. -- **Add components with the CLI** – run `npx shadcn@latest add `; never hand-roll components. -- **Component pattern** – use `React.forwardRef` with the `cn()` helper for class names. -- **Path aliases** – import modules from `src` using the `@/` prefix. -- **React 19 + Compiler** – target React 19 with the new compiler when available. -- **Context isolation** – maintain Electron's context isolation pattern for IPC. -- **TypeScript strict mode** – run `npm run typecheck` before claiming work complete. -- **Tailwind theming** – rely on CSS variables and utilities in `@/utils/tailwind` for styling. -- **Testing without running** – confirm `npm run typecheck` and module resolution with `node -e "require('')"`. +- Use the repository's Swift formatter configuration when one exists; otherwise follow standard Swift API Design Guidelines and existing native code style. +- Use four-space indentation in JavaScript and Markdown examples where indentation is semantic. +- Use Prettier only for files it supports; do not reformat generated assets or unrelated legacy code. +- Keep ADRs short and record only decisions that are hard to reverse, surprising without context, and based on a real trade-off. -## Tests +## Upstream changes -No automated tests yet. When a suite is added, run `npm test` before each -commit. Until then, at minimum ensure `npm install` and `npm start` work after -merging upstream changes. +This remains a fork of [`sohzm/cheating-daddy`](https://github.com/sohzm/cheating-daddy), but upstream Electron changes are not automatically product direction. -## Merging upstream PRs +Before cherry-picking upstream work: -Pull requests from are commonly -cherry‑picked here. When merging: - -1. Inspect the diff and keep commit messages short (`feat:` / `fix:` etc.). -2. After merging, run the application locally to verify it still builds and - functions. - -## Strategy and Future Work - -We plan to extend this project with ideas from the -[`transcriber`](https://github.com/Gatecrashah/transcriber) project which also -uses Electron. Key goals are: - -- **Local Transcription** – integrate `whisper.cpp` to allow offline speech-to- - text. Investigate the architecture used in `transcriber/src/main` for model - validation and GPU acceleration. -- **Dual Audio Capture** – capture microphone and system audio simultaneously. - `transcriber` shows one approach using a native helper for macOS and - Electron's `getDisplayMedia` for other platforms. -- **Speaker Diarization** – explore tinydiarize for identifying speakers in mono - audio streams. -- **Voice Activity Detection** – skip silent or low‑quality segments before - sending to the AI service. -- **Improved Note Handling** – store transcriptions locally and associate them - with meeting notes, similar to `transcriber`'s note management system. -- **Testing Infrastructure** – adopt Jest and React Testing Library (if React is - introduced) to cover audio capture and transcription modules. - -### TODO - -1. Research and prototype local transcription using `whisper.cpp`. -2. Add dual‑stream audio capture logic for cross‑platform support. -3. Investigate speaker diarization options and integrate when feasible. -4. Plan a migration path toward a proper testing setup (Jest or similar). -5. Document security considerations for audio storage and processing. -6. Rebuild the entire UI using shadcn components. - -These plans are aspirational; implement them gradually while keeping the app -functional. - -## Audio processing principles - -When implementing transcription features borrow the following rules from -`transcriber`: - -- **16 kHz compatibility** – resample all audio before sending to whisper.cpp. -- **Dual‑stream architecture** – capture microphone and system audio on separate - channels. -- **Speaker diarization** – integrate tinydiarize (`--tinydiarize` flag) for mono - audio and parse `[SPEAKER_TURN]` markers to label speakers (Speaker A, B, C…). -- **Voice activity detection** – pre‑filter silent segments to improve speed. -- **Quality preservation** – keep sample fidelity and avoid blocking the UI - during heavy processing. -- **Memory efficiency** – stream large audio files instead of loading them all at - once. -- **Error recovery** – handle audio device failures gracefully. - -## Privacy by design - -- **Local processing** – transcriptions should happen locally whenever possible. -- **User control** – provide clear options for data retention and deletion. -- **Transparency** – document what is stored and where. -- **Minimal data** – only persist what is required for functionality. - -## LLM plans - -There are placeholder files for future LLM integration (e.g. Qwen models via -`llama.cpp`). Continue development after the core transcription pipeline is -stable and ensure tests cover this new functionality. +1. Inspect whether it serves legacy maintenance or the native product. +2. Keep only reusable protocol, test, or migration value. +3. Reject stealth, anti-detection, insecure IPC, and cloud-by-default behavior. +4. Run the relevant Swift and legacy tests. diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..11a8db1 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,111 @@ +# Mastermind + +Mastermind is a personal, local-first macOS assistant that turns activity on the user's Mac into inspectable context for grounded assistance. + +## Product + +**Mastermind**: +The personal assistant product and the only target product name. +_Avoid_: Cheating Daddy, Mastermind Native, AI helper + +**Local Profile**: +The local identity whose sources, knowledge, history, and policies belong to the current macOS user. A future cloud account may authenticate services but does not own the Local Profile. +_Avoid_: User account, cloud profile + +**Companion Island**: +Mastermind's normally hidden interaction surface at the top center of the primary display. Hover reveals a capsule and clicking expands it into the assistant interface. +_Avoid_: Overlay, HUD, Dynamic Island, floating window + +## Context acquisition + +**Source**: +A configured origin from which Mastermind may observe context, such as a workspace, calendar, screen, audio stream, or terminal integration. +_Avoid_: Connector, data source + +**Collector**: +The independently operating part of Mastermind that observes one kind of Source and emits Observations. +_Avoid_: Capture mode, watcher, sensor + +**Observation**: +Immutable, time-stamped evidence emitted by a Collector about a Source. An Observation is evidence, not a claim that Mastermind treats as true. +_Avoid_: Event, Fact, memory + +**Gap**: +An explicit interval in which an enabled Collector could not produce usable Observations. +_Avoid_: Missing memory, silent failure + +## Knowledge + +**Context Graph**: +The Local Profile's structured, time-aware representation of entities, relationships, Observations, Assertions, and Facts. +_Avoid_: Memory, activity database, transcript archive + +**Assertion**: +A time-scoped claim inferred from one or more Observations, with confidence and Provenance. Assertions may conflict and expire. +_Avoid_: Fact, summary + +**Fact**: +An Assertion explicitly confirmed or corrected by the user. Facts remain until the user removes or supersedes them. +_Avoid_: High-confidence inference, model output + +**Provenance**: +The trace from an Assertion, Fact, summary, or answer back to the Source and Observations that support it. +_Avoid_: Citation text, model reasoning + +**Person**: +A human relevant to the Local Profile's work. +_Avoid_: Speaker, participant record + +**Project**: +An ongoing effort directed toward an outcome. A Project may span multiple Workspaces, Tasks, Events, Meetings, and Artifacts. +_Avoid_: Repository, folder, session + +**Task**: +An actionable unit of work represented by an external source. Mastermind understands Tasks but is not their system of record. +_Avoid_: Action Proposal, reminder + +**Event**: +A time-bounded occurrence meaningful to the user's work, such as a deadline or milestone. +_Avoid_: Observation, log entry + +**Meeting**: +A human interaction inferred from calendar, application, and audio Observations. Audio channel roles do not establish a participant's identity. +_Avoid_: Assistant Session, Conversation + +**Artifact**: +A persistent work product or reference relevant to a Project, such as a document or source file. +_Avoid_: Observation, screen frame + +**Workspace**: +An explicitly connected directory or repository that provides Artifacts and project context. +_Avoid_: Project, home directory + +## Assistance and trust + +**Assistant Session**: +A bounded text interaction in the Companion Island using one selected Provider. Assistant Sessions are distinct from Meetings. +_Avoid_: Conversation, capture session, chat memory + +**Provider**: +An inference service used to generate assistance. A Local Provider runs on the same Mac; a Cloud Provider receives data outside the Mac. +_Avoid_: Model, agent, sidecar + +**Provider Context Permission**: +The user's explicit permission for a Cloud Provider to receive locally selected context. Permission is denied by default and can be revoked for future requests. +_Avoid_: Source Policy, blanket consent + +**Context Receipt**: +The inspectable record attached to an answer that identifies its supporting context, Provider, and any external data transfer. +_Avoid_: Citation, Activity Log + +**Activity Log**: +The local audit trail of Collector lifecycle, permission failures, gaps, and Provider requests without captured content. +_Avoid_: Assistant History, transcript + +**Assistant History**: +The persistent local record of Assistant Sessions. It is separate from the Context Graph and Activity Log. +_Avoid_: Memory, Context Graph + +**Action Proposal**: +A plan or draft suggested by Mastermind for the user to carry out. It does not authorize Mastermind to act on the Mac. +_Avoid_: Tool call, agent action, Task diff --git a/README.md b/README.md index 83e1004..a180544 100644 --- a/README.md +++ b/README.md @@ -1,279 +1,94 @@
Mastermind Logo - - # Mastermind - - ### Your AI Assistant for High-Stakes Conversations - - *Real-time contextual suggestions when you need them most* - - [![Release](https://img.shields.io/github/actions/workflow/status/ShiftyX1/Mastermind/release.yml?label=release)](https://github.com/ShiftyX1/Mastermind/actions/workflows/release.yml) - [![License](https://img.shields.io/badge/license-GPL3.0-blue.svg)](LICENSE) - [![Latest Version](https://img.shields.io/github/v/release/ShiftyX1/Mastermind?include_prereleases&label=latest&color=FFFF00)](https://github.com/ShiftyX1/Mastermind/releases) - [![Stable Version](https://img.shields.io/github/v/release/ShiftyX1/Mastermind?color=6666FF)](https://github.com/ShiftyX1/Mastermind/releases) - [![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Windows-lightgrey.svg)](#requirements) - + +# Mastermind + +### A personal local-first assistant for macOS +
---- +Mastermind is a Swift-native assistant that builds an inspectable understanding of work happening on a Mac and uses it to answer grounded questions. Its primary interface is the normally hidden Companion Island at the top center of the primary display; a Menu Bar Item remains present while the app runs. -## What is Mastermind? +The production product is currently in reconstruction. `native/MastermindPOC` proves the macOS capture and windowing capabilities, while the Electron application under `src` is legacy reference code. -Mastermind is an **AI assistant** for high-stakes conversations. Whether you're in a job interview, closing a deal, or navigating a complex negotiation, Mastermind analyzes what you see and hear in real-time, providing contextual suggestions and talking points to support your responses. +## Canonical context -Think of it as having an experienced coach reviewing the conversation and offering suggestions, helping you recall relevant information and structure your thoughts more effectively. The AI provides support material—you still need to understand, adapt, and deliver the responses in your own words. +Start here before product or implementation work: -> [!WARNING] -> **AI models can and do make mistakes.** Suggestions may contain errors, outdated information, or inappropriate content. This tool is designed to assist people who already have relevant knowledge and need help organizing their thoughts—not to fake expertise you don't possess. Always verify critical information and use your own judgment. +- [`CONTEXT.md`](CONTEXT.md) — canonical domain language. +- [`docs/product/mastermind-product-brief.md`](docs/product/mastermind-product-brief.md) — product boundary and MVP. +- [`docs/product/companion-island.md`](docs/product/companion-island.md) — interaction model. +- [`docs/product/mvp-acceptance.md`](docs/product/mvp-acceptance.md) — completion criteria. +- [`docs/architecture/native-mastermind.md`](docs/architecture/native-mastermind.md) — production architecture. +- [`docs/privacy/local-first-data-contract.md`](docs/privacy/local-first-data-contract.md) — normative privacy and data rules. +- [`docs/adr`](docs/adr) — hard-to-reverse decisions and their rationale. -### The Hidden Assistant Advantage +When older code or text conflicts with these documents, the canonical context wins. -Mastermind operates discreetly with a transparent overlay that blends into your screen. The system analyzes both visual content and audio in real-time, generating contextual suggestions within seconds. It adapts its suggestions based on your selected scenario—interview, sales, meeting, or presentation. Ghost mode allows you to interact with content behind the overlay without closing it. +## MVP direction -**Remember:** This is an assistive tool, not a magic solution. It works best when you have genuine knowledge and need support organizing your thoughts under pressure. +- Apple Silicon and macOS 14 or newer. +- Swift/AppKit host with SwiftUI content where appropriate. +- Continuous local context from screen, microphone, system audio, selected workspaces, selected calendars and Reminders lists, and terminal metadata. +- Ephemeral raw screen/audio/transcript data; only structured local derivations persist. +- Encrypted local Context Graph with inspectable Provenance. +- User-confirmed Facts kept distinct from inferred Assertions. +- OpenAI-compatible Local Provider over loopback or a Unix socket. +- Separate local ASR sidecar using 16 kHz mono PCM. +- Russian, English, and mixed-language work. +- Text answers, plans, and drafts only; no autonomous actions. -## Key Features +Codex is a future Provider direction and is deliberately absent from the MVP until an official no-tools integration boundary exists. -### Real-Time Multi-Modal Analysis -Mastermind captures your screen and audio simultaneously, processing both visual content and audio streams to understand conversation context. It analyzes what's being discussed and generates relevant suggestions based on that context. The system supports dual-stream audio capture to distinguish between system audio and your microphone input, though transcription accuracy depends on audio quality, accents, and background noise. +## Privacy boundary -### Local-First Privacy Option -Choose between cloud AI providers for maximum performance or run everything locally with Ollama integration and offline Whisper.js transcription. When using local processing, no audio or screen data ever leaves your machine. The local transcription engine uses ONNX Runtime with GPU acceleration support for fast, private speech-to-text conversion. +The MVP does not send machine context to cloud services. Mastermind does not hide its process, permissions, capture indicators, or network activity from macOS or managed environments. -### Conversation History & Context -Mastermind saves conversation turns during the session, building context as the conversation progresses. You can view session history and export conversations for later review. The AI uses this accumulated context to provide more relevant suggestions as it learns about the discussion topic—though the quality of contextual understanding is limited by the AI model's capabilities and the clarity of the captured audio/screen content. +Window exclusion from the app's own capture is required. Exclusion from third-party capture is best effort and is never guaranteed. -### Specialized Profiles +## Current native capability proof -Mastermind comes with six pre-configured personas designed for different scenarios: +`native/MastermindPOC` currently demonstrates: -**Job Interview** — Suggested responses to technical and behavioral questions, STAR method frameworks, and structured talking points based on your background. +- a menu bar application and transparent AppKit panel; +- ScreenCaptureKit screen and system-audio capture; +- AVAudioEngine microphone capture; +- separate 16 kHz PCM output for microphone and system audio; +- current-process window exclusion; +- click-through, hide/show, opacity settings, and Pause All; +- Swift unit tests and app-bundle build script. -**Sales Call** — Objection handling suggestions, closing technique ideas, pricing strategy considerations, and rapport building approaches. +See [`docs/migration/native-poc-results.md`](docs/migration/native-poc-results.md) for verified and manual checks. The POC is not the production application and will be retired after its validated capabilities are ported to `native/Mastermind`. -**Business Meeting** — Data-driven talking points, strategic recommendations, and action-oriented communication suggestions. - -**Presentation** — Fact-checking support, audience engagement ideas, and recovery suggestions for unexpected situations. - -**Negotiation** — Tactical considerations, counter-offer frameworks, and strategic talking points to support your position. - -**Exam Assistant** — Information lookup and answer suggestions for exam questions, optimized for quick reference. - -### Invisible Design -The transparent overlay stays on top without blocking your view, with keyboard-driven positioning for quick adjustments. You can hide the window instantly with one click if needed, and customize opacity to match your environment perfectly. - -### Flexible AI Backend - -Mastermind supports multiple AI providers and can work with both cloud and local models: - -**Google Gemini** — Fast, cost-effective multimodal processing with excellent vision capabilities. Supports Gemini 2.0 Flash with real-time API for ultra-low latency responses. - -**OpenAI** — Industry-leading language understanding with GPT-4 and GPT-4o models. - -**Groq** — High-speed inference with competitive pricing and excellent performance. - -**Ollama** — Run completely local AI models on your machine for full privacy. No data ever leaves your device. - -**Any OpenAI-Compatible API** — Connect to LocalAI, LM Studio, or any custom endpoint that follows the OpenAI API format. - ---- - -## Advanced Features - -**Response Modes** — Toggle between Brief mode (1-3 sentences, optimal for quick glances) and Detailed mode (comprehensive explanations with full context) based on your needs during the session. - -**Google Search Integration** — Optional real-time web search capability allows the AI to fetch current information. Note that search results may include outdated or incorrect information—always verify critical facts from authoritative sources. - -**Custom System Prompts** — Tailor the AI's behavior with custom instructions specific to your industry, role, or situation. Add your resume, company information, or specialized knowledge to improve context relevance. - -**Multi-Language Support** — Works in 30+ languages including English, Spanish, German, French, Japanese, Korean, Chinese, Hindi, Arabic, and many more. Auto-detection available for multilingual conversations, though accuracy varies by language and accent. - -**Customizable Keyboard Shortcuts** — Every shortcut can be remapped to your preference. Create your own workflow that feels natural to you. - ---- - -## Getting Started - -### Installation - -#### For Users (Recommended) - -Download the latest release for your platform from the [GitHub Releases](https://github.com/ShiftyX1/Mastermind/releases) page: - -**macOS:** -1. Download `Mastermind-[version].dmg` -2. Open the DMG file and drag Mastermind to your Applications folder -3. Launch Mastermind from Applications (you may need to allow the app in System Preferences → Security & Privacy on first launch) - -**Windows:** -1. Download `Mastermind-[version]-Setup.exe` -2. Run the installer and follow the setup wizard -3. Launch Mastermind from the Start menu or desktop shortcut - -#### For Developers - -If you want to build from source or contribute to development: +### Build and test the POC ```bash -# Clone the repository -git clone https://github.com/ShiftyX1/Mastermind.git -cd Mastermind - -# Install dependencies -pnpm install - -# Launch in development mode -pnpm start - -# Build distributable packages (DMG for macOS, Setup.exe for Windows) -pnpm run make - -# Package without creating installers -pnpm run package +cd native/MastermindPOC +swift test +swift build --product MastermindPOC +./scripts/build-app.sh ``` -### First-Time Setup +## Legacy Electron application -**Get Your AI Key:** Start by obtaining an API key from [Google AI Studio](https://aistudio.google.com/apikey) (recommended for beginners), [OpenAI Platform](https://platform.openai.com/api-keys), [Groq Console](https://console.groq.com), or configure a local Ollama instance for complete privacy. +The Electron implementation remains available as reference during reconstruction. New product functionality belongs in the Swift application. -**Configure Your Assistant:** Enter your API key in the main window and select your preferred AI provider and model. Choose your primary use case profile from the six available scenarios. Select your language or use Auto for multilingual support. +```bash +npm install +npm test +npm start +``` -**Start Your Session:** Click "Start Session" to activate your hidden assistant. Grant screen recording and audio capture permissions when prompted by your system. Position the overlay window where it's most useful and adjust opacity to blend naturally with your environment. +Do not use Electron UI, storage, provider coupling, or marketing copy as the source of truth for the native product. -### Daily Usage +## Responsible boundary -**Starting a Session:** Select the appropriate profile for your scenario—Interview, Sales, Meeting, Presentation, Negotiation, or Exam. Adjust opacity and position to blend naturally with your environment. Choose your audio mode: Speaker Only (system audio), Microphone Only, or Both for dual-stream capture. - -**During Your Conversation:** The AI analyzes your screen and audio context in real-time, with suggestions appearing in the overlay. You can type questions directly for clarification and use keyboard shortcuts to reposition or hide the window. Toggle between brief and detailed response modes depending on your needs. - -**Important:** Treat AI suggestions as reference material, not verified facts. Quickly scan suggestions, extract useful points, and deliver responses in your own words with your own understanding. Don't read AI responses verbatim—this often sounds unnatural and may include errors. - -**Pro Tips:** Position the window in your natural eye-line to avoid obvious glances. Use click-through mode when you need to interact with content behind the overlay. Keep sessions focused on one topic for better context. Enable local transcription when working with sensitive information. - ---- - -## Keyboard Shortcuts - -Master these shortcuts for seamless, discreet operation: - -| Action | Shortcut | Purpose | -|--------|----------|---------| -| **Move Window** | `Ctrl/Cmd + Arrow Keys` | Reposition without using mouse | -| **Toggle Click-Through** | `Ctrl/Cmd + M` | Make window transparent to clicks | -| **Quick Hide** | `Ctrl/Cmd + \` | Instantly hide/show or go back | -| **Send Message** | `Enter` | Send text query to AI | -| **Quick Position** | Custom | Set your favorite window positions | - -> **Pro Tip**: All shortcuts are fully customizable in settings. Create your own stealth workflow! - ---- - -## Audio Capture Technology - -Mastermind uses advanced audio capture to understand conversations in real-time, with support for both cloud and local transcription. - -**macOS** — Leverages [SystemAudioDump](https://github.com/sohzm/systemAudioDump) for crystal-clear system audio capture. Supports three modes: Speaker Only (system audio), Microphone Only (your voice), or Both (simultaneous dual-stream capture). - -**Windows** — Professional loopback audio capture for system sounds, with full microphone support and dual-stream capabilities for capturing both sides of the conversation. - -**Linux** — Microphone input support. System audio capture is currently in development. - -**Local Transcription** — Built-in offline speech-to-text using Whisper.js powered by ONNX Runtime. Your audio is processed locally on your machine without sending data to external services. Supports GPU acceleration on compatible hardware. - ---- - -## Use Cases - -### Job Interviews -Get suggested responses and frameworks for technical questions, helping you structure your thoughts using proven methods like STAR. Mastermind can help you recall relevant examples from your background and organize talking points, but you need to adapt and deliver them authentically in your own voice. - -### Sales & Client Calls -Access reference material for objection handling and competitive positioning. The system can suggest talking points and strategies by analyzing the conversation context, but closing deals requires genuine understanding of your product and the client's needs—AI suggestions are starting points, not scripts to read verbatim. - -### Business Negotiations -Receive strategic considerations and framework suggestions based on the conversation flow. Mastermind can help you structure counter-offers and identify discussion points, but successful negotiation requires reading the room, building rapport, and making judgment calls that AI cannot make for you. - -### Presentations & Demos -Get quick fact-checking and audience engagement ideas during your presentation. If questions arise, Mastermind can suggest relevant information, but you should verify accuracy and ensure you genuinely understand what you're presenting—especially important for technical content where deep knowledge is expected. - ---- - -## System Requirements - -| Component | Requirement | -|-----------|-------------| -| **Operating System** | macOS 10.15+, Windows 10/11 (latest versions recommended) | -| **Permissions** | Screen recording, audio capture (system audio and/or microphone) | -| **Internet** | Required for cloud AI providers (Gemini, OpenAI, Groq). Optional for local Ollama models | -| **AI Provider** | API key from Gemini, OpenAI, Groq, or local Ollama installation | -| **For Local Transcription** | 4GB+ RAM recommended, GPU acceleration optional but recommended | - -**Current Version:** 0.7.3 - -> [!NOTE] -> **Platform Support**: macOS and Windows are fully supported and tested. Linux support is experimental. - -> [!TIP] -> **Testing Mode**: When testing, simulate someone asking you questions. The AI responds to detected questions rather than your own queries. - ---- - -## Known Limitations - -**AI Response Quality** — AI models can make mistakes, provide outdated information, or misinterpret context. Always verify critical information and use suggestions as supporting material, not absolute truth. The quality of responses depends heavily on the AI model you choose and the context you provide. - -**Not a Replacement for Knowledge** — Mastermind is a tool to help you recall and structure information, not to replace your actual expertise. The most effective use is when you already understand the subject matter and need help articulating or remembering specific details. - -**Linux Support** — System audio capture is not yet implemented on Linux. Only microphone input is currently supported. - -**Local Transcription Performance** — First-time usage requires downloading the Whisper model files (approximately 150MB). Transcription speed depends on your hardware; GPU acceleration is recommended for optimal performance. - -**macOS Permissions** — Screen recording and audio capture require explicit system permissions. You may need to restart the app after granting permissions on first launch. - -**Session Context** — The AI maintains context only within the current session. Starting a new session clears previous conversation history (though history can be saved and viewed later). - ---- - -## Privacy & Ethics - -**Your Data, Your Control:** All audio and screen capture happens locally on your device. API communications are direct and clear between you and your chosen provider. For complete privacy, you can use local AI models through Ollama without any data leaving your machine. - -**Critical Disclaimers:** -- AI models can generate incorrect, biased, or inappropriate content. Always verify important information from authoritative sources. -- This tool provides suggestions, not verified facts. You are responsible for the accuracy of what you say. -- Relying entirely on AI suggestions without understanding the content can backfire—especially in technical or expert conversations where follow-up questions will reveal lack of genuine knowledge. - -**Responsible Use:** -Mastermind is designed as a preparation and cognitive support tool—like having notes or a reference guide. It works best when you already have foundational knowledge and need help organizing thoughts or recalling details under pressure. - -**Ethical Boundaries:** Always comply with the rules and policies of your specific context. Many situations explicitly prohibit external assistance: -- Academic exams and certification tests typically ban any form of external help -- Some professional interviews and assessments prohibit such tools -- Certain regulated industries have strict rules about information access during calls -- Using AI assistance where prohibited can result in serious consequences, including job loss or legal issues - -**Use this tool to support your genuine expertise, not to fake knowledge you don't have.** The best outcomes happen when AI assists someone who understands the subject, not when it replaces actual competence. - ---- +Mastermind is a personal work assistant. It is not a proctoring bypass, process-hiding system, monitoring-evasion tool, or means to conceal prohibited AI use. AI output can be wrong; grounded answers must expose evidence and uncertainty. ## Contributing -Based on the excellent work from [Cheating Daddy](https://github.com/sohzm/cheating-daddy). - -Contributions are welcome! Please see [AGENTS.md](AGENTS.md) for development guidelines. - ---- +Read [`AGENTS.md`](AGENTS.md) and the canonical context before making changes. Keep production work inside the Swift-native direction and preserve the local-first data contract. ## License -This project is licensed under the GPL-3.0 License - see the [LICENSE](LICENSE) file for details. - ---- - -
- -### A tool to support your expertise, not replace it - -*Use responsibly. Verify information. Understand what you're saying.* - -
+Mastermind is licensed under GPL-3.0. See [`LICENSE`](LICENSE). diff --git a/docs/adr/0001-swift-native-host-with-local-sidecars.md b/docs/adr/0001-swift-native-host-with-local-sidecars.md new file mode 100644 index 0000000..72f9e42 --- /dev/null +++ b/docs/adr/0001-swift-native-host-with-local-sidecars.md @@ -0,0 +1,3 @@ +# Swift-native host with local sidecars + +Mastermind's production runtime is a Swift/AppKit macOS host that owns UI, lifecycle, permissions, capture, policy, and storage. Local LLM and ASR processes stay behind loopback or Unix-socket protocols, while Electron is retained only as legacy reference; this keeps macOS capabilities native without forcing model runtimes into the application process. diff --git a/docs/adr/0002-encrypted-observation-ledger.md b/docs/adr/0002-encrypted-observation-ledger.md new file mode 100644 index 0000000..95ac3c4 --- /dev/null +++ b/docs/adr/0002-encrypted-observation-ledger.md @@ -0,0 +1,3 @@ +# Encrypted observation ledger + +The Context Graph uses application-encrypted SQLite/SQLCipher as its source of truth. Collectors append immutable Observations, project versioned Assertions, and create Facts only through explicit user confirmation; this preserves Provenance and temporal conflicts while keeping full-text and vector indexes rebuildable instead of making a separate graph service authoritative. diff --git a/docs/adr/0003-continuous-collectors-with-ephemeral-input.md b/docs/adr/0003-continuous-collectors-with-ephemeral-input.md new file mode 100644 index 0000000..0457c9b --- /dev/null +++ b/docs/adr/0003-continuous-collectors-with-ephemeral-input.md @@ -0,0 +1,3 @@ +# Continuous Collectors with ephemeral input + +Enabled screen, microphone, system-audio, workspace, calendar, and terminal Collectors run continuously and adapt to power and thermal pressure. Raw frames, audio, OCR, and full transcripts remain ephemeral while only structured local derivations persist; this trades recoverability for a strict local data-minimization boundary, so processor outages are recorded as Gaps rather than buffered raw content. diff --git a/docs/adr/0004-defer-codex-until-no-tools-boundary.md b/docs/adr/0004-defer-codex-until-no-tools-boundary.md new file mode 100644 index 0000000..5c57ad6 --- /dev/null +++ b/docs/adr/0004-defer-codex-until-no-tools-boundary.md @@ -0,0 +1,3 @@ +# Defer Codex until a no-tools boundary exists + +Codex integration is excluded from the MVP even though it remains a future Provider direction. The official app-server is an agent protocol and its read-only sandbox does not provide a documented no-tools guarantee, so Mastermind will not ship OAuth, app-server code, or a hidden experimental path until a supported draft-only boundary can enforce the product's no-action contract. diff --git a/docs/architecture/native-mastermind.md b/docs/architecture/native-mastermind.md new file mode 100644 index 0000000..fbfc8eb --- /dev/null +++ b/docs/architecture/native-mastermind.md @@ -0,0 +1,217 @@ +# Native Mastermind Architecture + +## Scope + +This document defines the production architecture for Mastermind. Domain language comes from [`../../CONTEXT.md`](../../CONTEXT.md), product scope from [`../product/mastermind-product-brief.md`](../product/mastermind-product-brief.md), and privacy invariants from [`../privacy/local-first-data-contract.md`](../privacy/local-first-data-contract.md). + +The production application lives under `native/Mastermind`. `native/MastermindPOC` is a capability reference, not the production architecture. The Electron application is legacy source material and is not part of the production runtime. + +## Runtime boundary + +The application host is Swift-native: + +- AppKit owns lifecycle, windows, menu bar behavior, permissions, and capture. +- SwiftUI may render Companion Island content inside AppKit-controlled windows. +- Swift concurrency isolates Collectors and processing from the main actor. +- The host owns the encrypted Context Graph and all policy decisions. +- Local model processes remain outside the host behind narrow protocols. +- No Node or Electron process is required. + +Permitted external local processes: + +- an OpenAI-compatible Local Provider on loopback or a Unix socket; +- a local ASR sidecar using the existing WebSocket protocol. + +Mastermind owns a small multilingual embedding component because chat endpoints do not reliably expose embeddings. + +## System shape + +```mermaid +flowchart LR + subgraph host [Swift native host] + AppCoordinator --> MenuBar + AppCoordinator --> CompanionIsland + AppCoordinator --> CollectorSupervisor + CollectorSupervisor --> ScreenCollector + CollectorSupervisor --> AudioCollectors + CollectorSupervisor --> WorkspaceCollector + CollectorSupervisor --> CalendarCollector + CollectorSupervisor --> TerminalCollector + ScreenCollector --> LocalReduction + AudioCollectors --> LocalReduction + WorkspaceCollector --> LocalReduction + CalendarCollector --> LocalReduction + TerminalCollector --> LocalReduction + LocalReduction --> ObservationLedger + ObservationLedger --> KnowledgeProjector + KnowledgeProjector --> ContextGraph + ContextGraph --> Retriever + Retriever --> AssistantSession + AssistantSession --> ContextReceipt + CollectorSupervisor --> ActivityLog + AssistantSession --> ActivityLog + end + + AudioCollectors --> AsrSidecar + AssistantSession --> LocalProvider + EmbeddingModel --> KnowledgeProjector + EmbeddingModel --> Retriever +``` + +Every arrow carrying Source content stays on the Mac. Activity Log entries contain metadata, not Source content. + +## Application components + +### AppCoordinator + +Owns lifecycle and composes the application. It restores the persisted paused state before starting Collectors, coordinates sleep/wake and Launch at Login, and never places heavy processing on the main actor. + +### CompanionIslandController + +Owns the hidden, revealed, and expanded window states on the primary display. The controller separates non-activating hover behavior from the key window used for text entry and management. + +### MenuBarController + +Owns the stable status glyph and detailed menu. Collector states are represented in menu content rather than by changing the glyph. + +### CollectorSupervisor + +Owns independent Collector lifecycles. It starts enabled Collectors, pauses them atomically, persists Pause All, applies power and thermal policy, and records Gaps. One Collector failure must not collapse the rest of the pipeline. + +### ScreenCollector + +Uses ScreenCaptureKit for pixels and Accessibility for application/window structure. The active display is the display containing the key window, falling back to pointer location and then the primary display. Changed-region detection, OCR, and deduplication reduce pixels locally before immediate disposal. + +Mastermind windows are excluded from its own stream. Third-party exclusion is a best-effort window policy, not a security guarantee. + +### AudioCollectors + +Microphone and system audio are separate Collectors and remain separate. Both emit 16 kHz mono signed 16-bit PCM frames to VAD and local ASR. The pipeline labels channel role as User Speech or System Speech but does not infer a Person from voice. + +### WorkspaceCollector + +Observes explicitly connected roots. It respects `.gitignore`, configured excludes, binary detection, and size limits, and emits changes to Artifacts and repository metadata. + +### CalendarCollector + +Uses EventKit read-only for selected calendars and Reminders lists. External applications remain systems of record for Tasks and Events. + +### TerminalCollector + +Receives shell integration events for working directory, command, exit status, duration, and Git metadata. It does not persist stdout or stderr by default. + +## Knowledge pipeline + +### Observation ledger + +Collectors append immutable Observations. Each record includes: + +- stable identifier; +- Source identifier and Collector kind; +- observed time and source event time when available; +- structured payload; +- sensitivity metadata; +- derivation version. + +Observations are retained until age or size eviction. Corrections never mutate them. + +### Knowledge projector + +The projector derives versioned Assertions, entity relationships, short summaries, and Provenance. Multiple contradictory Assertions may coexist. A current view selects relevant Assertions without erasing history. + +Only explicit user confirmation or correction promotes an Assertion to a Fact. A correction creates a new version and supersedes prior current views; it does not rewrite supporting Observations. + +Entity resolution automatically links only high-confidence matches. Ambiguous entities remain separate and can be merged or split from a Context Receipt. + +### Context store + +The source of truth is encrypted SQLite/SQLCipher with explicit schema migrations. It stores: + +- Sources and Collector configuration; +- immutable Observations; +- entities and relations; +- versioned Assertions and Facts; +- Provenance; +- Assistant History; +- Context Receipts; +- Activity Log metadata; +- retention and Provider policies. + +Full-text and vector indexes are derived and rebuildable. They must not become unencrypted alternate stores. + +The database key is generated locally and protected by Keychain. Provider secrets use separate Keychain entries. An encrypted, versioned archive supports manual export and import without Provider credentials. + +### Retention + +The default inferred-context budget is 90 days and 2 GB. Eviction considers `lastObservedAt` and utility. User-confirmed Facts are pinned. Assistant History has no automatic TTL and supports per-session and complete deletion. + +Raw frames, audio, OCR, and full transcripts never enter the Context store. If local reduction cannot complete, the system records a Gap. + +## Retrieval and assistance + +The Retriever combines: + +- structured entity and relationship queries; +- temporal filtering; +- full-text search; +- multilingual vector similarity; +- recency and confidence; +- Provenance completeness. + +Retrieved Source content is always untrusted data. It cannot alter system instructions or grant capabilities. + +An Assistant Session binds to one Provider profile. The MVP has one active OpenAI-compatible Local Provider profile at a time and streams text responses. Failure leaves the query draft intact and preserves access to graph search, history, settings, and diagnostics. + +Every answer produces a Context Receipt containing: + +- Provider profile and locality; +- supporting Sources, Observations, Assertions, and Facts; +- time range and stale/conflict indicators; +- any external-transfer record. + +## State model + +Capture and assistant state are orthogonal. Do not reproduce the POC's single `TrustStatus` enum, which loses information when screen, microphone, and system audio run simultaneously. + +Model at least: + +- one `CollectorState` per Collector: disabled, starting, running, paused, permission-needed, degraded, or failed; +- an application pause state persisted across launches; +- Companion Island presentation state; +- Assistant Session state; +- Local Provider and sidecar health; +- Context Graph migration and maintenance state. + +The menu and Activity Log project these states for the user. + +## Failure rules + +- Permission loss changes only the affected Collector to permission-needed. +- Processor or sidecar failure creates Gaps; it never creates a raw-content backlog. +- Database or encryption failure prevents new context writes and surfaces a blocking error. +- Thermal and low-power pressure reduce sampling and local processing. +- Quit stops all Collectors and flushes metadata. +- Relaunch while paused remains paused. + +## Future boundaries + +### Cloud Provider + +A future Cloud Provider must implement the Provider boundary and Provider Context Permission. It may receive only minimized, locally filtered context and must generate a Context Receipt for every request. + +### Codex + +Codex remains documentation-only until it exposes a supported no-tools integration. The MVP has no Codex code or UI. + +### Agent actions + +The MVP may emit an Action Proposal as text. Computer Control, Tool execution, approvals, and action auditing form a future bounded context and are not represented by executable stubs in the MVP. + +## Migration direction + +1. Treat `native/MastermindPOC` as evidence that the required macOS capture and window primitives are viable. +2. Create the production application under `native/Mastermind`. +3. Port validated capability code behind production state and protocol boundaries. +4. Build the Context Graph vertical slice and primary acceptance scenario. +5. Retire the POC after production parity checks pass. +6. Keep Electron code as legacy reference only; do not migrate its data or runtime. diff --git a/docs/local-sidecar-protocol.md b/docs/local-sidecar-protocol.md index 0f28db6..8378336 100644 --- a/docs/local-sidecar-protocol.md +++ b/docs/local-sidecar-protocol.md @@ -49,12 +49,29 @@ The sidecar should send JSON text frames: { "type": "error", "error": "human-readable error" } ``` -Only `final` transcript events are sent to the local LLM. `partial` events are -shown as status text. +Only `final` transcript events enter local semantic reduction. `partial` events +are transient status and must not be persisted. ## v1 Scope -- STT target: English, `en-US`. +- Required language modes: English (`en-US`), Russian (`ru-RU`), and automatic + or mixed Russian-English recognition (`auto` or an implementation-equivalent + mode). - Sidecar implementation is external to this repository. - The app does not require a specific Nemotron, NeMo, Riva, or ONNX runtime as long as the WebSocket protocol above is implemented. +- The endpoint must be loopback-only. LAN and internet ASR endpoints are not + Local Providers. + +## Native macOS Client Compatibility + +The Swift-native app uses the same WebSocket protocol as the Electron client. +Audio frames are raw 16 kHz mono signed 16-bit little-endian PCM. + +Microphone and system audio use independent client connections so the sidecar +does not mix channel roles. The sidecar does not need to know whether a client +is Electron or Swift; Mastermind associates each connection with its Source. + +Full transcripts are ephemeral sensitive input. The Swift client consumes a +`final` event, derives structured local context, and then releases transcript +content instead of storing it in Assistant History or the Context Graph. diff --git a/docs/migration/native-poc-results.md b/docs/migration/native-poc-results.md index 20fa374..bdbd494 100644 --- a/docs/migration/native-poc-results.md +++ b/docs/migration/native-poc-results.md @@ -1,5 +1,10 @@ # Native macOS POC Results +> This document records capability evidence, not the production product specification. +> Canonical direction is defined by [`../../CONTEXT.md`](../../CONTEXT.md), +> [`../product/mastermind-product-brief.md`](../product/mastermind-product-brief.md), and +> [`../architecture/native-mastermind.md`](../architecture/native-mastermind.md). + ## Implemented - SwiftPM-based macOS POC under `native/MastermindPOC`. @@ -42,3 +47,19 @@ ## Boundary This POC is not a stealth or anti-detection system. It shows a menu bar item while running, requests normal macOS permissions, and only excludes its own overlay from the context it captures for itself. + +## Role in production migration + +`native/MastermindPOC` proves that AppKit windowing, ScreenCaptureKit screen and system-audio capture, AVAudioEngine microphone capture, current-process exclusion, and 16 kHz PCM conversion are viable. + +Production development moves to `native/Mastermind`. Validated capability code may be ported behind production boundaries, but the POC is not renamed into the product and is retired after parity checks pass. + +The production design intentionally differs from the POC: + +- the Companion Island is hidden at launch and anchored to the primary display's top center; +- enabled Collectors start continuously after onboarding instead of through manual start menu items; +- the Menu Bar Item uses a stable glyph with detailed states inside its menu; +- screen, microphone, and system-audio states are simultaneous per-Collector states rather than one `TrustStatus`; +- settings and management live inside the expanded Companion Island; +- screen context follows the active display rather than always selecting the main display; +- the Context Graph, Local Provider, local ASR client, retention, encryption, Context Receipts, and Activity Log are production requirements not implemented by the POC. diff --git a/docs/privacy/local-first-data-contract.md b/docs/privacy/local-first-data-contract.md new file mode 100644 index 0000000..dc3f69e --- /dev/null +++ b/docs/privacy/local-first-data-contract.md @@ -0,0 +1,145 @@ +# Local-First Data Contract + +This document is normative. Product and implementation work must preserve these boundaries unless a superseding ADR explicitly changes them. + +## Local-first definition + +Mastermind's Local Profile, Source configuration, captured context, Context Graph, Assistant History, Activity Log, embeddings, and inference remain on the user's Mac in the MVP. + +A Provider is local only when it is reachable through loopback or a Unix socket on the same Mac. LAN and internet endpoints are external and are not supported by the MVP. + +The application must remain useful without internet access. It may not silently fall back from local processing to a Cloud Provider. + +## Data classes + +### Ephemeral sensitive input + +- screen frames and changed image regions; +- microphone and system-audio PCM; +- OCR output; +- complete ASR transcripts; +- transient prompts assembled for local derivation. + +These values exist only in bounded processing buffers and must be destroyed after local reduction. They must not enter logs, crash reports, archives, fixtures, or the Context store. + +### Persisted context + +- structured Observations; +- Assertions, Facts, summaries, and entity relationships; +- Provenance references; +- Source and Collector configuration; +- Assistant History and Context Receipts; +- Activity Log metadata; +- retention and policy settings. + +Persisted context is encrypted at the application layer. + +### Secrets + +- Context-store encryption key; +- Local Provider credentials, when required; +- future Cloud Provider credentials. + +Secrets are stored in Keychain and excluded from Context Graph exports and diagnostics. + +## Continuous collection + +After guided onboarding, every enabled Collector starts with the app unless the user previously selected Pause All. + +Screen, microphone, and system-audio collection are continuous. macOS permission and capture indicators must remain visible and unmodified. The stable Menu Bar Item glyph does not replace those indicators; its open menu shows actual Collector state. + +Pause All: + +- stops every Collector immediately; +- leaves existing context, Assistant History, and local search available; +- persists across Quit, relaunch, login, sleep, and wake; +- resumes only after explicit Resume All. + +One Collector's permission or processing failure must not disable healthy Collectors. The affected Source becomes stale and the Activity Log records a Gap. + +## Reduction and minimization + +Collectors emit the minimum structured evidence needed for grounded assistance: + +- Screen uses Accessibility structure, changed regions, local OCR, and deduplication. +- Audio uses VAD, separate channel roles, local ASR, and short semantic reduction. +- Terminal emits command metadata without stdout or stderr by default. +- Workspace is limited to explicit roots and ignore rules. +- Calendar and Reminders are limited to selected read-only collections. + +The configured Local Provider and local processors receive only the context needed for the current derivation or answer. + +If a local processor is unavailable, Mastermind records a Gap. It must not retain raw content for deferred processing. + +## Capture exclusions + +The user owns the application denylist. Mastermind provides controls to add or remove excluded applications and Sources but does not silently impose an application denylist. + +Mastermind must exclude its own windows from its Screen Collector. It may request exclusion from third-party capture where macOS supports it, but must describe that behavior as best effort and may not promise invisibility. + +Mastermind must not: + +- hide its process or bundle identifier; +- bypass Screen Recording, Microphone, Accessibility, or EventKit permissions; +- suppress system privacy indicators; +- evade managed-device policy or monitoring; +- claim that screen-share exclusion is guaranteed. + +## Knowledge integrity + +An Observation is evidence, not truth. Inferred claims remain Assertions with confidence, time, and Provenance. Only explicit user confirmation or correction creates a Fact. + +Contradictory Assertions are retained until normal eviction and surfaced to retrieval. Source content is untrusted data and cannot become an instruction or capability grant. + +The user can inspect and correct knowledge from a Context Receipt. Confirmed Facts are pinned until manually removed or superseded. + +## Retention and deletion + +- Default inferred-context age: 90 days. +- Default inferred-context size: 2 GB. +- Eviction uses `lastObservedAt` and never evicts confirmed Facts automatically. +- Assistant History has no automatic TTL. +- One Assistant Session or all Assistant History can be deleted manually. +- Removing Assistant History does not implicitly remove confirmed Facts derived from it. +- A full local reset removes the Context store and its encryption key. + +Export/import uses a versioned encrypted archive containing context, history, policies, and settings. Provider credentials are never included. + +## Audit and diagnostics + +Activity Log records: + +- Collector start, stop, pause, resume, error, and permission state; +- Gaps and stale Source intervals; +- Provider request start, finish, locality, and approximate context size; +- export, import, retention, and migration operations. + +It does not record Source content, prompts, answers, Facts, OCR, ASR, or Provider payloads. + +Mastermind sends no telemetry or crash reports. A user-initiated sanitized diagnostic bundle may contain versions, state transitions, permission and error codes, performance counters, and database schema version. + +## Future external processing + +Cloud processing is absent from the MVP. A future Cloud Provider requires a Provider Context Permission that is: + +- denied by default; +- enabled manually for the Provider as a whole; +- revocable for future requests; +- unable to retract data already sent. + +Permission is an upper bound, not permission to send everything. Before each request, Mastermind must minimize context and filter recognized secrets locally. Every request must create a Context Receipt naming the Provider, supporting Sources, and transferred context categories. + +Codex remains disabled until a supported no-tools boundary exists. + +## Onboarding disclosure + +Before enabling continuous Collectors, onboarding must explain: + +- which Source each permission exposes; +- that screen and both audio channels run continuously while enabled; +- that raw media and full transcripts are not retained; +- where derived knowledge is stored; +- how Pause All and the denylist work; +- that other people may be represented in locally derived context; +- that capture exclusion is best effort; +- that the MVP performs no cloud context transfer. diff --git a/docs/product/companion-island.md b/docs/product/companion-island.md new file mode 100644 index 0000000..db56a58 --- /dev/null +++ b/docs/product/companion-island.md @@ -0,0 +1,87 @@ +# Companion Island + +## Purpose + +The Companion Island is Mastermind's only primary interaction surface. It keeps the assistant absent from the desktop until requested while making it available at a stable physical location. + +It is inspired by the expansion behavior of Dynamic Island, but it is a Mastermind concept and must not be described as an Apple system feature. + +## Placement + +- The Companion Island belongs to the primary display only. +- Its activation area is centered on the display's top edge. +- On a notched display, the activation area follows the camera housing. +- On a display without a notch, the same area behaves as a virtual camera housing. +- Changing the primary display relocates the Companion Island. + +## Interaction states + +### Hidden + +No Companion Island content is visible. Moving the pointer into the activation area begins the reveal transition. + +### Revealed + +A compact capsule grows from the camera area without taking keyboard focus. Leaving the activation region without clicking collapses it after a short grace period. + +### Expanded + +Clicking the revealed capsule expands it downward into an interactive panel and focuses text input. Expansion must feel spatially connected to the camera area rather than like an unrelated window appearing. + +The expanded surface contains navigation for: + +- Assistant; +- Assistant History; +- Sources; +- Local Provider; +- Context Graph and Context Receipts; +- Activity Log; +- Privacy, storage, export/import, and diagnostics. + +Escape, an explicit close action, or clicking outside the panel returns it to Hidden. Long-running local work continues after collapse and is visible when the panel is reopened. + +### Paused + +Paused is a Collector condition, not a separate window mode. The user can still open the Companion Island, search existing context, and use Assistant History while all Collectors remain stopped. + +## Menu Bar Item + +The Menu Bar Item is visible whenever Mastermind runs. Its glyph does not change with capture state. + +Its menu must expose: + +- current state of every enabled Collector; +- permission and processing errors; +- Pause All or Resume All; +- Show Mastermind; +- Launch at Login state; +- Quit Mastermind. + +Show Mastermind expands the Companion Island and is the fallback when pointer activation is unavailable. The MVP has no global hotkey. + +## Focus and accessibility + +- Hidden and Revealed do not steal focus. +- Expanded accepts keyboard focus and text input. +- Pointer activation must not create a dead strip that prevents access to the macOS menu bar. +- Animation respects Reduce Motion. +- The interface remains keyboard-navigable after it is expanded. +- Collector state and errors are conveyed with text, not color alone. + +## Capture behavior + +Mastermind excludes its own windows from the Screen Collector. It also requests exclusion from third-party capture where supported by macOS. + +Capture exclusion is best effort. The UI must not promise that the Companion Island is invisible to every screen-sharing or recording application. Mastermind never hides its process or system permission indicators. + +## Acceptance checks + +- At launch, only the Menu Bar Item is visible. +- Hovering the primary display's camera area reveals the capsule. +- A notchless primary display gets the same top-center interaction. +- A click expands the panel and focuses text input. +- Show Mastermind works when hover activation cannot be used. +- Escape and click-away collapse the panel. +- Pause All does not prevent access to existing knowledge or history. +- The Companion Island is absent from Mastermind's own captured frames. +- Changing the primary display relocates the activation area. diff --git a/docs/product/mastermind-product-brief.md b/docs/product/mastermind-product-brief.md new file mode 100644 index 0000000..d1db31c --- /dev/null +++ b/docs/product/mastermind-product-brief.md @@ -0,0 +1,134 @@ +# Mastermind Product Brief + +## Product thesis + +Mastermind is a personal, local-first assistant for macOS. It continuously builds an inspectable understanding of the user's work and answers grounded questions about what happened, what matters now, and what may come next. + +Mastermind is not an interview helper, a hidden proctoring tool, or a generic shell around a cloud agent. The first product is a personal/internal Swift application for one macOS user. + +## Core promise + +The user's machine context remains on the Mac. Screen, audio, files, calendar, reminders, and terminal activity are reduced to useful knowledge locally. Mastermind does not transmit that context to a cloud service in the MVP. + +The assistant distinguishes observed evidence, inferred claims, and user-confirmed facts. Every grounded answer can show what evidence it used and where that evidence came from. + +## Target platform + +- Apple Silicon Mac. +- macOS 14 or newer. +- One Local Profile for the current macOS user. +- No Mastermind account, backend, telemetry, or synchronization in the MVP. +- The domain keeps a future cloud identity separate from the Local Profile. +- Personal/internal distribution; Mac App Store constraints are out of scope. + +## Primary experience + +Mastermind runs as a menu bar application without a Dock presence. Its Menu Bar Item is always present while the app runs and uses a stable glyph. Opening its menu reveals Collector states, permission failures, Pause All or Resume All, Show Mastermind, and Quit. + +The Companion Island is hidden by default. Hovering the top-center camera area of the primary display reveals a compact capsule with a smooth animation. Clicking expands the capsule into the complete Mastermind interface. A virtual top-center activation area provides the same behavior when the primary display has no physical notch. Show Mastermind in the menu is the fallback; the MVP has no global shortcut or voice invocation. + +The expanded Companion Island contains: + +- text input and streamed answers; +- Assistant History; +- Context Receipts and Fact correction; +- Source and Collector management; +- Local Provider configuration; +- Context Graph limits and encrypted export/import; +- Activity Log and diagnostics. + +Mastermind is on-demand, not proactive. Background collection may update status and knowledge, but the assistant does not interrupt the user with unsolicited advice. + +## MVP sources + +Enabled Collectors start automatically with the application unless Pause All was previously selected: + +- Screen: the active display, defined by the frontmost key window, with pointer display and primary display as fallbacks. +- Audio: separate microphone and system-audio channels. +- Workspace: explicitly connected directories and Git repositories. +- Calendar and Reminders: user-selected calendars and lists, read-only. +- Terminal: shell integration metadata including working directory, command, exit status, duration, and Git metadata; terminal output is not retained by default. + +Workspace indexing respects `.gitignore`, binary and size limits, and user-configured exclusions. Mastermind does not index the entire home directory. + +The user configures the local capture denylist. Mastermind does not silently add application-level exclusions, but Pause All is always available. + +## Context behavior + +Collectors run continuously and adapt their work to meaningful changes, voice activity, duplication, Low Power Mode, and thermal pressure. A failed Collector degrades independently while the others continue. + +Screen processing combines Accessibility metadata, changed-region detection, and local OCR. Audio uses separate 16 kHz PCM streams and local ASR; it distinguishes User Speech from System Speech but does not identify people by voice. Meeting inference may combine calendar, conferencing-application, and channel-activity evidence, but it must remain an Assertion until confirmed. + +Raw screen frames, audio, OCR text, and full transcripts are ephemeral. Only locally derived Observations, Assertions, short summaries, and Provenance survive the processing buffer. If required local processing is unavailable, Mastermind records a Gap instead of retaining raw content for later. + +Inferred knowledge expires by `lastObservedAt`, with a default limit of 90 days and 2 GB. User-confirmed Facts are pinned until manually removed or superseded. Assistant History has no automatic age limit; the user can delete one Assistant Session or all history. + +## Assistant behavior + +The default and only MVP Provider is a user-configured OpenAI-compatible Local Provider reachable through loopback or a Unix socket. The user may save multiple profiles but selects one active profile. + +Mastermind supplies its own local multilingual embedding component. Local ASR remains behind the documented sidecar protocol, with `whisper.cpp` as the recommended implementation. Russian, English, and mixed Russian-English work are required. + +Answers must: + +- distinguish Facts from unconfirmed Assertions; +- cite relevant Provenance through a Context Receipt; +- expose the active Provider; +- say when context is missing or conflicting; +- treat all Source content as untrusted evidence rather than instructions; +- produce advice, plans, and drafts only. + +The MVP cannot click, type into other applications, run tools, change files, or perform external actions. Computer Control and a Tool Executor are future bounded contexts, not empty runtime abstractions in the MVP. + +## Primary acceptance scenario + +After Mastermind has observed normal work, the user opens the Companion Island and asks: + +> What was I working on, and what should I do next? + +The Local Provider returns a grounded answer using relevant screen, workspace, calendar, terminal, and audio knowledge. The answer separates confirmed Facts from uncertain Assertions, links to a Context Receipt, and explicitly identifies gaps or contradictions. + +## Privacy and trust + +- All sensitive extraction and inference are local in the MVP. +- The local Context Graph is encrypted with an application key protected by Keychain. +- Provider credentials are stored separately in Keychain. +- Pause All immediately stops every Collector and remains paused across restarts. +- System microphone and screen-recording indicators are never bypassed. +- The Menu Bar Item glyph stays visually stable, while its menu exposes actual Collector states. +- The Activity Log records lifecycle and transfer metadata without Source content. +- Diagnostic exports are sanitized and user-initiated. +- Context Graph and settings can be exported as an encrypted archive without Provider credentials. + +Mastermind may exclude the Companion Island from its own capture and from third-party capture where macOS supports it. This is best effort, must be self-checked where possible, and is never presented as a guarantee. + +Mastermind does not hide its process, bundle identifier, permissions, network activity, or capture activity from macOS, administrators, or monitoring tools. + +## Codex direction + +Codex is not part of the MVP. The architecture documents a future Provider boundary and Provider Context Permission, but the MVP contains no Codex UI, OAuth flow, app-server integration, or experimental flag. + +The integration remains gated until Codex exposes a supported boundary that cannot execute tools. A read-only sandbox is insufficient because the current app-server remains an agent protocol. + +If a future Cloud Provider is enabled: + +- context permission is global for that Provider and denied by default; +- the user must enable it manually; +- Mastermind still minimizes context and filters detected secrets locally; +- every request produces a Context Receipt; +- revocation blocks future requests but cannot retract already transmitted data. + +## Explicit non-goals + +- Cloud inference or context transfer in the MVP. +- Autonomous actions, Computer Control, or tool execution. +- Proactive suggestions or scheduled briefings. +- Wake word, push-to-talk, global shortcut, or voice queries. +- Browser, mail, messages, clipboard, or full home-directory indexing. +- Voice identity and speaker attribution to a Person. +- Owning or synchronizing the user's tasks and calendar. +- Multi-display Companion Island behavior. +- A visual whole-graph explorer. +- Electron feature development or an Electron bridge. +- Intel Mac, Windows, Linux, or Mac App Store support. +- Stealth, anti-detection, permission bypass, or guaranteed screen-share invisibility. diff --git a/docs/product/mvp-acceptance.md b/docs/product/mvp-acceptance.md new file mode 100644 index 0000000..421e5a7 --- /dev/null +++ b/docs/product/mvp-acceptance.md @@ -0,0 +1,87 @@ +# MVP Acceptance + +The MVP is complete only when the following scenarios work together in the production Swift application. Passing the current native capability proof alone is not sufficient. + +## Product scenario + +Given that enabled Collectors have observed normal work, when the user opens the Companion Island and asks, "What was I working on, and what should I do next?", then Mastermind: + +- responds through the configured Local Provider; +- uses relevant knowledge from screen, workspace, calendar, terminal, and audio Sources; +- distinguishes user-confirmed Facts from inferred Assertions; +- identifies conflicting or stale knowledge; +- states when evidence is insufficient; +- attaches an inspectable Context Receipt. + +## Presence + +- Mastermind launches as a menu bar application without a Dock icon. +- Only the stable Menu Bar Item is visible at rest. +- Hover reveals the Companion Island on the primary display. +- Click expands it and focuses text input. +- Show Mastermind in the menu provides a reliable fallback. +- The expanded surface contains assistant, history, source, provider, graph, audit, and privacy controls. + +## Continuous collection + +- Enabled Collectors start after launch unless paused state was persisted. +- Screen collection follows the display containing the key window and processes meaningful changes rather than every full frame. +- Microphone and system audio remain separate through local ASR. +- Workspace collection is limited to explicitly connected roots. +- Calendar and Reminders are read-only and limited to selected calendars and lists. +- Terminal collection retains command metadata but not stdout or stderr by default. +- Low Power Mode and thermal pressure reduce processing without corrupting state. +- One failed Collector does not stop healthy Collectors. + +## Local-only processing + +- Packet inspection and integration tests confirm that Source content does not leave the Mac. +- The configured Local Provider accepts only loopback or Unix-socket endpoints. +- OCR, ASR, embeddings, Fact extraction, retrieval, and answer generation work without internet access. +- Raw screen frames, audio, OCR text, and full transcripts are destroyed after local reduction. +- When a required local processor is unavailable, Mastermind records a Gap and does not queue raw content. + +## Knowledge integrity + +- Observations are immutable until retention removes them. +- Assertions retain time, confidence, and Provenance. +- Conflicting Assertions coexist and produce an explicit conflict instead of silent overwrite. +- Only explicit user confirmation or correction creates a Fact. +- Confirmed Facts survive normal age and size eviction. +- Ambiguous entity matches stay separate until confidence is sufficient or the user merges them. +- Context retrieval treats instructions inside Source content as untrusted data. + +## Retention and control + +- Inferred context defaults to 90 days and 2 GB and can be reconfigured. +- Eviction uses `lastObservedAt` and does not evict confirmed Facts. +- Assistant History has no automatic TTL. +- The user can delete one Assistant Session or all Assistant History. +- Pause All immediately stops every Collector and remains paused after relaunch. +- Resume All restarts only enabled and permitted Collectors. +- The encrypted archive round-trips context, history, policies, and settings without Provider credentials. + +## Trust and diagnostics + +- The Menu Bar Item menu shows the real state of every Collector despite the stable glyph. +- macOS capture indicators and permission surfaces remain unmodified. +- Activity Log records Collector lifecycle, Gaps, permission errors, and Provider requests without Source content. +- Context Receipts name the Provider and all supporting Sources and Observations. +- The sanitized diagnostic bundle contains no prompts, answers, Facts, OCR, ASR, or Provider payloads. +- Mastermind's windows are excluded from its own screen context. +- Third-party capture exclusion is presented and tested as best effort, never guaranteed. + +## Assistant boundary + +- The assistant streams text answers in Russian, English, and mixed-language work. +- Outputs are answers, plans, or drafts only. +- The production target contains no Computer Control, Tool Executor, autonomous action, Codex login, Codex app-server, or hidden experimental Cloud Provider. +- If the Local Provider is unavailable, existing graph search, history, settings, and diagnostics remain accessible. + +## Definition of done + +- Automated tests cover domain invariants, retention, encryption boundaries, policy defaults, independent Collector failure, and raw-buffer disposal. +- Integration tests use synthetic Sources and local mock sidecars. +- Manual tests cover macOS permissions, microphone, system audio, screen exclusion, primary-display changes, Launch at Login, sleep/wake, Low Power Mode, and relaunch while paused. +- Logs and fixtures contain no captured user content. +- Canonical documentation and implementation vocabulary agree with `CONTEXT.md`. diff --git a/docs/superpowers/plans/2026-06-26-macos-native-ai-companion-reconstruction.md b/docs/superpowers/plans/2026-06-26-macos-native-ai-companion-reconstruction.md deleted file mode 100644 index 3428a1a..0000000 --- a/docs/superpowers/plans/2026-06-26-macos-native-ai-companion-reconstruction.md +++ /dev/null @@ -1,825 +0,0 @@ -# macOS Native AI Companion Reconstruction Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Reconstruct Mastermind from an Electron interview-helper-shaped app into a native macOS AI companion with reliable overlay, screen context, system audio, voice interaction, and explicit trust indicators. - -**Architecture:** Build a Swift/AppKit-first macOS host that owns windows, capture, audio, permissions, menu bar status, and privacy boundaries. Keep AI providers and local sidecars behind protocol boundaries so the rewrite can progress incrementally instead of becoming a risky full replacement. - -**Tech Stack:** Swift, AppKit, SwiftUI where appropriate, ScreenCaptureKit, AVAudioEngine, CoreAudio, Keychain, Application Support storage, URLSession streaming, WebSocket, local ASR sidecar protocol, OpenAI-compatible HTTP/SSE, optional Electron bridge during migration. - ---- - -## Product Thesis - -Mastermind should become an **AI companion for your Mac**, not a hidden interview helper. - -The assistant is a personal, visible-to-the-user HUD and agent system. It can help during calls, presentations, coding, writing, research, and everyday computer use. It may stay out of the content the user is presenting or sharing, just like presenter notes, a timer, captions, or a local command palette. - -The product should not implement stealth, anti-detection, process hiding, monitoring bypass, proctoring bypass, or policy evasion. If a workplace, school, exam, or managed system prohibits AI assistants, Mastermind should not help users hide that it is running. - -## Core Boundary - -**Allowed:** The assistant window does not appear in the user's own screen context, screenshots, screen-share content, or presentation output when technically possible. - -**Not allowed:** Hiding the app process, bundle identifier, permissions, network use, Accessibility use, Screen Recording use, microphone use, or audio capture use from operating-system tools or managed environments. - -Practical phrasing: - -> Mastermind does not hide from the user or the system. It only avoids contaminating the content the user intentionally shares or asks the assistant to analyze. - -## Target User Experience - -### Normal Companion Mode - -The assistant is available through voice, keyboard, and a small native overlay. It can answer questions, remember context, summarize active work, and trigger actions. - -### Meeting Mode - -The assistant can listen to microphone and system audio with clear status indicators. It can summarize discussion, draft follow-ups, keep agenda state, and help the user stay oriented. - -### Presentation Mode - -The user can share slides, a browser, or an app window while seeing local prompts, timing, plan notes, likely objections, and speaker guidance in Mastermind's HUD. The shared audience does not need to see the HUD. - -### Screen Context Mode - -Screen context is opt-in. The user explicitly asks the assistant to look at the screen, capture a snapshot, or follow a bounded live stream. Mastermind excludes its own UI from that context. - -### Idle Mode - -When not actively listening, viewing, or processing, Mastermind stays quiet and visibly idle in the menu bar. - -## Trust Model - -Trust is a first-class feature, not a settings afterthought. - -Required visible signals: - -- Menu bar icon is always present while the app runs. -- Status reflects actual state: idle, listening, reading screen, processing, paused, permission problem. -- Mic capture, system audio capture, and screen context have separate indicators. -- The user can pause capture immediately. -- The app exposes a local activity log showing recent context use: microphone, system audio, screen snapshot, screen stream, provider request. -- The app does not provide stealth labels, anti-detection switches, or hidden-running modes. - -Recommended status vocabulary: - -- `Idle` -- `Listening` -- `System Audio` -- `Screen Snapshot` -- `Screen Stream` -- `Agent Working` -- `Paused` -- `Permission Needed` -- `Error` - -## Current Project Context - -Current repository shape: - -- Electron Forge app with JavaScript entry point at `src/index.js`. -- Window management and global shortcuts in `src/utils/window.js`. -- AI provider/session logic in `src/utils/gemini.js`, `src/utils/localai.js`, and `src/utils/localProviders.js`. -- Local ASR sidecar protocol already documented in `docs/local-sidecar-protocol.md`. -- JSON storage in `src/storage.js`. -- Lit-based UI under `src/components`. - -Important existing behavior to preserve: - -- Always-on-top assistant window. -- Global keyboard shortcuts. -- Click-through toggle. -- Hide/show assistant. -- Session history. -- Local mode with ASR sidecar. -- BYOK provider support. -- OpenAI-compatible provider support. -- Groq/Gemini provider support. -- Configurable prompt/profile/language. - -Important behavior to replace: - -- Electron-owned transparent window quirks. -- Chromium `getDisplayMedia` screen capture dependency. -- Fragile loopback/system-audio capture. -- Renderer-local storage access from main process. -- `nodeIntegration: true` and `contextIsolation: false`. -- Hidden coupling between capture, transcription, provider routing, and renderer events. - -## Reconstruction Strategy - -Recommended path: **Swift-native host first, full app migration second**. - -Do not start with a full SwiftUI rewrite of every screen. The riskiest parts are windowing, screen capture, audio capture, permissions, and trust indicators. Prove those first in a native macOS host, then migrate provider and UI surfaces incrementally. - -Migration shape: - -```text -Phase 1: Native capability proof - Swift/AppKit overlay - menu bar status item - ScreenCaptureKit screen context - ScreenCaptureKit system audio - AVAudioEngine microphone audio - -Phase 2: Native companion shell - state machine - permissions - trust indicators - local sidecar bridge - provider boundary - -Phase 3: Agentic assistant - modes - memory - tools - activity log - meeting and presentation flows - -Phase 4: Retire Electron - migrate settings/history - package/notarize Swift app - deprecate Electron runtime -``` - -## Proposed Native Architecture - -```text -Mastermind.app - AppCoordinator - owns lifecycle, mode, permissions, menu bar status - - OverlayWindowController - owns transparent HUD, click-through, Spaces behavior, focus behavior - - CaptureCoordinator - owns screen context and system audio through ScreenCaptureKit - - MicrophoneCaptureEngine - owns microphone stream through AVAudioEngine - - AudioPipeline - owns channel separation, resampling, VAD, PCM frame output - - AssistantSession - owns active conversation, transcript, memory references, provider routing - - ProviderClients - Gemini, Groq, OpenAI-compatible, local LLM, local ASR sidecar - - TrustStatusStore - owns visible state, activity log, pause/resume, capture indicators - - Storage - Application Support for non-secret app data - Keychain for secrets -``` - -## Agentic System Direction - -The future assistant should be built around modes and tools, not a single chat box. - -Core modes: - -- General Companion -- Meeting Assistant -- Presentation Coach -- Coding Assistant -- Research Assistant -- Focus Assistant - -Core agent abilities: - -- Listen and summarize. -- Answer conversationally. -- See screen only when requested. -- Track agenda or presentation plan. -- Draft follow-up notes. -- Remember user preferences. -- Use local tools after explicit permission. -- Explain what context it used. - -Agent boundaries: - -- No autonomous destructive actions. -- No hidden capture. -- No silent screen streaming. -- No policy bypass tooling. -- No stealth process behavior. - -## File Structure Target - -Future native app structure: - -```text -native/Mastermind/ - Mastermind.xcodeproj - Mastermind/ - App/ - MastermindApp.swift - AppCoordinator.swift - AppMode.swift - PermissionState.swift - Status/ - MenuBarController.swift - TrustStatus.swift - ActivityLog.swift - Overlay/ - OverlayWindowController.swift - OverlayRootView.swift - OverlayViewModel.swift - Capture/ - CaptureCoordinator.swift - ScreenContextCapture.swift - SystemAudioCapture.swift - CaptureExclusionPolicy.swift - Audio/ - MicrophoneCaptureEngine.swift - AudioPipeline.swift - PCMFrame.swift - VoiceActivityDetector.swift - Assistant/ - AssistantSession.swift - AssistantMode.swift - AssistantEvent.swift - AssistantMemory.swift - Providers/ - ProviderClient.swift - LocalAsrSidecarClient.swift - OpenAICompatibleClient.swift - GeminiClient.swift - GroqClient.swift - Storage/ - AppStorageStore.swift - KeychainStore.swift - MigrationStore.swift - Settings/ - SettingsWindowController.swift - SettingsRootView.swift - Presentation/ - PresentationPlan.swift - PresentationCoach.swift -``` - -Existing Electron files remain read-only during the proof phase except for bridge points explicitly required by a migration task. - -## Task 1: Write Product Reconstruction Charter - -**Files:** - -- Create: `docs/product/macos-native-ai-companion-charter.md` - -- [ ] **Step 1: Create the product charter** - -Write a concise charter with these sections: - -```markdown -# macOS Native AI Companion Charter - -## Positioning - -Mastermind is a native macOS AI companion for everyday computer work, meetings, presentations, research, and focused execution. - -## What It Is - -- A visible personal assistant for the user. -- A voice-first and context-aware companion. -- A local HUD for notes, guidance, and agent status. -- A privacy-conscious screen and audio context tool. - -## What It Is Not - -- A hidden interview helper. -- A proctoring bypass tool. -- An anti-detection tool. -- A process-hiding tool. -- A tool for hiding AI use from managed systems that prohibit it. - -## Core Promise - -Mastermind does not hide from the user or the system. It only avoids contaminating the content the user intentionally shares or asks the assistant to analyze. - -## Trust Requirements - -- Show a menu bar status item whenever running. -- Show when microphone, system audio, or screen context is active. -- Allow immediate pause. -- Keep a local activity log of context use. -- Store secrets in Keychain. -``` - -- [ ] **Step 2: Review the charter language** - -Confirm the document includes the phrases `AI companion for your Mac`, `does not hide from the user or the system`, and `visible personal assistant`. - -- [ ] **Step 3: Commit** - -```bash -git add docs/product/macos-native-ai-companion-charter.md -git commit -m "docs: define macos ai companion direction" -``` - -## Task 2: Build Native Capability Proof Project - -**Files:** - -- Create: `native/Mastermind/Mastermind.xcodeproj` -- Create: `native/Mastermind/Mastermind/App/MastermindApp.swift` -- Create: `native/Mastermind/Mastermind/App/AppCoordinator.swift` -- Create: `native/Mastermind/Mastermind/Status/MenuBarController.swift` -- Create: `native/Mastermind/Mastermind/Overlay/OverlayWindowController.swift` -- Create: `native/Mastermind/Mastermind/Capture/CaptureCoordinator.swift` -- Create: `native/Mastermind/Mastermind/Audio/MicrophoneCaptureEngine.swift` -- Create: `native/Mastermind/Mastermind/Audio/AudioPipeline.swift` - -- [ ] **Step 1: Create a minimal native macOS app** - -Create a macOS app target named `Mastermind`. Use Swift, AppKit lifecycle, and SwiftUI only for simple views. - -- [ ] **Step 2: Add a menu bar status item** - -Implement a menu bar item that always appears while the app runs. The menu must include: - -```text -Mastermind: Idle -Pause All Capture -Show Assistant -Hide Assistant -Settings -Quit Mastermind -``` - -- [ ] **Step 3: Add a transparent overlay window** - -Create an AppKit-controlled floating overlay window with these properties: - -```text -borderless -transparent background -always on top -visible across Spaces -does not steal focus when shown -can become click-through -can be hidden and restored -``` - -- [ ] **Step 4: Add screen context proof** - -Use ScreenCaptureKit to capture the main display. The proof succeeds only when captured frames exclude the assistant overlay. - -- [ ] **Step 5: Add system audio proof** - -Use ScreenCaptureKit audio output to receive system audio buffers. - -- [ ] **Step 6: Add microphone proof** - -Use AVAudioEngine to receive microphone PCM buffers. - -- [ ] **Step 7: Add 16 kHz PCM output proof** - -Convert microphone and system audio streams into 16 kHz signed 16-bit PCM frames. - -- [ ] **Step 8: Manual verification** - -Run the native app and verify: - -```text -menu bar item is visible -overlay is visible locally -overlay can become click-through -overlay does not appear in app-owned captured frames -system audio buffers arrive when another app plays audio -microphone buffers arrive when speaking -capture can be paused immediately -``` - -- [ ] **Step 9: Commit** - -```bash -git add native/Mastermind -git commit -m "feat: add native macos capture proof" -``` - -## Task 3: Define Trust State Machine - -**Files:** - -- Create: `native/Mastermind/Mastermind/Status/TrustStatus.swift` -- Create: `native/Mastermind/Mastermind/Status/ActivityLog.swift` -- Modify: `native/Mastermind/Mastermind/Status/MenuBarController.swift` -- Modify: `native/Mastermind/Mastermind/App/AppCoordinator.swift` - -- [ ] **Step 1: Define trust states** - -Use these states exactly: - -```swift -enum TrustStatus: Equatable { - case idle - case listening - case systemAudio - case screenSnapshot - case screenStream - case agentWorking - case paused - case permissionNeeded(String) - case error(String) -} -``` - -- [ ] **Step 2: Define context activity events** - -Use these events exactly: - -```swift -enum ActivityEventKind: String, Codable { - case microphoneStarted - case microphoneStopped - case systemAudioStarted - case systemAudioStopped - case screenSnapshotCaptured - case screenStreamStarted - case screenStreamStopped - case providerRequestStarted - case providerRequestFinished - case capturePaused -} -``` - -- [ ] **Step 3: Wire status to menu bar copy** - -Map trust states to visible labels: - -```text -idle -> Mastermind: Idle -listening -> Mastermind: Listening -systemAudio -> Mastermind: System Audio -screenSnapshot -> Mastermind: Screen Snapshot -screenStream -> Mastermind: Screen Stream -agentWorking -> Mastermind: Agent Working -paused -> Mastermind: Paused -permissionNeeded -> Mastermind: Permission Needed -error -> Mastermind: Error -``` - -- [ ] **Step 4: Verify state changes manually** - -Trigger each capture path and confirm the menu bar label changes before any capture data leaves the machine. - -- [ ] **Step 5: Commit** - -```bash -git add native/Mastermind/Mastermind/Status native/Mastermind/Mastermind/App -git commit -m "feat: add native trust status model" -``` - -## Task 4: Preserve Local ASR Sidecar Boundary - -**Files:** - -- Create: `native/Mastermind/Mastermind/Providers/ProviderClient.swift` -- Create: `native/Mastermind/Mastermind/Providers/LocalAsrSidecarClient.swift` -- Modify: `docs/local-sidecar-protocol.md` - -- [ ] **Step 1: Define provider boundary** - -Use this protocol as the native client boundary: - -```swift -protocol ProviderClient { - associatedtype Event - - func start() async throws - func stop() async - var events: AsyncStream { get } -} -``` - -- [ ] **Step 2: Mirror the current ASR sidecar protocol** - -Implement the native client against the existing WebSocket flow: - -```json -{ - "type": "start", - "sampleRate": 16000, - "channels": 1, - "encoding": "pcm_s16le", - "language": "en-US" -} -``` - -- [ ] **Step 3: Preserve event semantics** - -Support these sidecar events: - -```text -ready -partial -final -error -``` - -Only `final` transcript events should enter the assistant response pipeline by default. - -- [ ] **Step 4: Document native compatibility** - -Add a section to `docs/local-sidecar-protocol.md`: - -```markdown -## Native macOS Client Compatibility - -The Swift-native app uses the same WebSocket protocol as the Electron app. Audio frames are sent as raw 16 kHz mono signed 16-bit little-endian PCM. The sidecar does not need to know whether the client is Electron or Swift. -``` - -- [ ] **Step 5: Commit** - -```bash -git add native/Mastermind/Mastermind/Providers docs/local-sidecar-protocol.md -git commit -m "feat: add native local asr sidecar client" -``` - -## Task 5: Design Native Audio Pipeline - -**Files:** - -- Create: `native/Mastermind/Mastermind/Audio/PCMFrame.swift` -- Create: `native/Mastermind/Mastermind/Audio/AudioPipeline.swift` -- Create: `native/Mastermind/Mastermind/Audio/VoiceActivityDetector.swift` -- Modify: `native/Mastermind/Mastermind/Audio/MicrophoneCaptureEngine.swift` -- Modify: `native/Mastermind/Mastermind/Capture/CaptureCoordinator.swift` - -- [ ] **Step 1: Define PCM frame format** - -Use this data model: - -```swift -struct PCMFrame: Equatable { - let source: AudioSource - let sampleRate: Int - let channels: Int - let pcmS16LE: Data - let timestamp: Date -} - -enum AudioSource: String { - case microphone - case system -} -``` - -- [ ] **Step 2: Keep microphone and system audio separate** - -The pipeline should not mix microphone and system audio before transcription. Separate streams preserve future diarization and meeting-context quality. - -- [ ] **Step 3: Resample to 16 kHz** - -Every frame sent to local ASR must be: - -```text -sample rate: 16000 -channels: 1 -encoding: signed 16-bit little-endian PCM -``` - -- [ ] **Step 4: Add VAD boundary** - -Voice activity detection should emit speech segments instead of forcing every buffer into transcription. - -- [ ] **Step 5: Manual verification** - -Verify: - -```text -mic frames continue when system audio is silent -system frames continue when mic is silent -both streams can be paused together -either stream can be disabled independently -sidecar receives valid 16 kHz PCM frames -``` - -- [ ] **Step 6: Commit** - -```bash -git add native/Mastermind/Mastermind/Audio native/Mastermind/Mastermind/Capture -git commit -m "feat: add native audio pipeline model" -``` - -## Task 6: Migrate Secrets and Storage Boundaries - -**Files:** - -- Create: `native/Mastermind/Mastermind/Storage/KeychainStore.swift` -- Create: `native/Mastermind/Mastermind/Storage/AppStorageStore.swift` -- Create: `native/Mastermind/Mastermind/Storage/MigrationStore.swift` -- Reference: `src/storage.js` - -- [ ] **Step 1: Map current storage** - -Preserve these current logical groups: - -```text -config -credentials -preferences -keybinds -limits -history -``` - -- [ ] **Step 2: Move secrets to Keychain** - -Store these values in Keychain: - -```text -Gemini API key -Groq API key -OpenAI-compatible API key -local LLM API key -``` - -- [ ] **Step 3: Store non-secret data in Application Support** - -Store these values in Application Support: - -```text -preferences -profiles -keybinds -history -limits -activity log -presentation plans -assistant memory references -``` - -- [ ] **Step 4: Add one-way migration** - -Read existing Electron JSON files from: - -```text -~/Library/Application Support/cheating-daddy-config -``` - -Import values into native stores. Leave the old files untouched. - -- [ ] **Step 5: Commit** - -```bash -git add native/Mastermind/Mastermind/Storage -git commit -m "feat: add native storage migration boundary" -``` - -## Task 7: Build Presentation Coach Mode - -**Files:** - -- Create: `native/Mastermind/Mastermind/Presentation/PresentationPlan.swift` -- Create: `native/Mastermind/Mastermind/Presentation/PresentationCoach.swift` -- Modify: `native/Mastermind/Mastermind/Assistant/AssistantMode.swift` -- Modify: `native/Mastermind/Mastermind/Overlay/OverlayRootView.swift` - -- [ ] **Step 1: Define presentation plan model** - -Use this model: - -```swift -struct PresentationPlan: Codable, Equatable { - var title: String - var sections: [PresentationSection] -} - -struct PresentationSection: Codable, Equatable { - var title: String - var talkingPoints: [String] - var expectedDurationSeconds: Int -} -``` - -- [ ] **Step 2: Add presentation mode** - -Add a mode named `presentationCoach`. - -- [ ] **Step 3: Show local guidance in HUD** - -HUD should show: - -```text -current section -next talking point -elapsed time -suggested transition -likely audience question -``` - -- [ ] **Step 4: Keep guidance out of shared content** - -Use the same overlay exclusion policy as Screen Context Mode. The local HUD should be visible to the user and absent from app-owned captures. - -- [ ] **Step 5: Commit** - -```bash -git add native/Mastermind/Mastermind/Presentation native/Mastermind/Mastermind/Assistant native/Mastermind/Mastermind/Overlay -git commit -m "feat: add presentation coach mode" -``` - -## Task 8: Define Electron Retirement Gates - -**Files:** - -- Create: `docs/migration/electron-retirement-gates.md` - -- [ ] **Step 1: Create retirement gate checklist** - -Write this checklist: - -```markdown -# Electron Retirement Gates - -- [ ] Native overlay matches or exceeds Electron window behavior. -- [ ] Native menu bar status item is always visible while running. -- [ ] Native screen context excludes Mastermind UI. -- [ ] Native system audio capture works without third-party loopback drivers. -- [ ] Native microphone capture works independently from system audio. -- [ ] Native local ASR sidecar client can transcribe 16 kHz PCM. -- [ ] Native provider client can stream OpenAI-compatible responses. -- [ ] Native settings can import current Electron preferences. -- [ ] Native Keychain storage replaces JSON credential storage. -- [ ] Native package can be signed and notarized. -- [ ] Electron app remains available as fallback until native app covers core workflows. -``` - -- [ ] **Step 2: Commit** - -```bash -git add docs/migration/electron-retirement-gates.md -git commit -m "docs: add electron retirement gates" -``` - -## Task 9: Package and Distribution Direction - -**Files:** - -- Create: `docs/migration/native-distribution.md` - -- [ ] **Step 1: Document distribution requirements** - -Include: - -```text -Developer ID signing -notarization -Screen Recording permission messaging -Microphone permission messaging -optional Accessibility permission messaging -Sparkle or equivalent update path -DMG distribution -crash reporting decision -local log export -``` - -- [ ] **Step 2: Document permission copy** - -Use transparent user-facing copy: - -```text -Mastermind needs Screen Recording permission only when you ask it to use screen context. -Mastermind needs Microphone permission only when voice input or meeting listening is enabled. -Mastermind shows a menu bar status item whenever it is running. -``` - -- [ ] **Step 3: Commit** - -```bash -git add docs/migration/native-distribution.md -git commit -m "docs: define native distribution requirements" -``` - -## Verification Checklist - -Before claiming the reconstruction direction is ready for implementation: - -- [ ] The charter clearly says this is an AI companion, not a hidden helper. -- [ ] The plan preserves local ASR sidecar compatibility. -- [ ] The plan does not require a full rewrite before validating native capture. -- [ ] The plan includes a visible menu bar status item. -- [ ] The plan separates user-visible HUD behavior from stealth behavior. -- [ ] The plan includes microphone, system audio, and screen context as separate states. -- [ ] The plan includes Keychain for secrets. -- [ ] The plan includes Electron retirement gates. -- [ ] The plan keeps current Electron app functional during migration. - -## Recommended First Milestone - -The first milestone should be **Native Capability Proof**, not full product migration. - -Success definition: - -```text -A Swift/AppKit app shows a local transparent overlay, displays an always-visible menu bar status item, captures screen frames without its own overlay, receives system audio, receives microphone audio, and emits 16 kHz PCM frames compatible with the existing local ASR sidecar protocol. -``` - -If this milestone fails, keep improving the Electron app while reassessing native capture options. If it succeeds, move provider clients and agent modes into the native shell incrementally. -