Files
stitch/docs/PLAN.md
T
thekhalidsha 61409cb444 Initial import: Stitch 0.4.3 (versionCode 16)
The project's first commit, six days and 16 releases after it started. Everything
up to this point existed only as files on one machine, with no history and no undo.

Contents: single Gradle module, 62 Kotlin files (11,244 lines) and the Needle 2 JNI
bridge, 70 tools, 87 passing unit tests, and the five documents in docs/ plus
DEVELOPMENT_HISTORY.md and README.md.

Not tracked: build outputs (build/, .cxx/, .gradle/), the release APKs in dist/
(~800 MB, rebuildable), local.properties, and .claude/settings.local.json — all
machine-specific. The prebuilt libneedle.a files (38 MB) *are* tracked on purpose,
so a checkout builds without depending on Hugging Face still serving them.
2026-09-25 14:23:14 +05:30

40 KiB
Raw Blame History

Project "Stitch": On-Device Android Agent (Needle + BYO AI)

⚠️ HISTORICAL DOCUMENT — not the implementation contract. This is the original scope of work, written 19 Sep 2026 before any code existed. It is kept because it records the reasoning behind the design, but the app diverged from it deliberately (see DEVELOPMENT_HISTORY.md §4, "Plan vs. what was built"). Its "Phase 4" means Needle fine-tuning, and is unrelated to the stages in docs/UPGRADE_PLAN.md. For what Stitch does today, read README.md. For where it is going, read docs/UPGRADE_PLAN.md.

Working name: Stitch. Needle does the on-device work, and your AI fills the gaps between steps. Rename anytime. Status: DRAFT v0.1 · 2026-09-19 · Scope of work and implementation plan


1. Summary

Stitch is an Android app that turns natural language (typed or spoken) into real actions on the phone.

  • A small on-device tool-calling model (Cactus Needle) handles phone and device intents locally. Examples: turn on the flashlight, call Mom, set an alarm, read my notifications, reply on WhatsApp. It works offline, responds in milliseconds, and keeps data on the device.
  • A user-connected AI (BYOK / agent) handles anything Needle can't: writing content, reasoning, web search, and multi-step planning. Supported backends include OpenAI-compatible, Anthropic, Gemini, OpenRouter, local Ollama, Hermes Agent, and an OpenCode server.
  • The two talk through a strict JSON contract, the Action Plan Protocol (APP). The cloud AI never touches the phone directly. It returns a structured plan, and the on-device Executor validates it, asks for confirmation when needed, and runs it with native Android APIs.
  • A lightweight voice layer handles input: speech-to-text on the device, with optional text-to-speech replies.

Example: "Draft me a leave request and keep it in Gmail drafts."

  1. Needle maps the request to gmail.create_draft, but it can't write the subject or body, so it calls the meta-tool delegate_to_ai(task, target_tool="gmail.create_draft").
  2. The orchestrator sends the task, the target tool's schema, and the user profile (name, manager's email if known) to the connected AI.
  3. The AI returns an Action Plan: [ask_user("Which dates?")] → gmail.create_draft{to, subject, body}.
  4. The Executor asks the user for the dates, re-requests or fills the plan, then saves the draft through the Gmail API. If the Gmail API isn't connected, it falls back to opening Gmail compose with the fields prefilled and uses UI automation to save the draft.
  5. The user sees: "Saved 'Leave Request – 22–24 Sep' to Gmail Drafts" with a link to open it.

2. Research findings that shape this plan

Item Finding Impact
Needle 2 (Cactus Compute) 45M params, one ~14 MB binary, ~28 MB RAM per session, Apache-2.0. It runs on Android arm64/armv7. It uses grammar-constrained JSON output: {type: call|respond, function_calls[], reasoning, confidence}. It returns an empty call list when no tool fits instead of guessing. The empty result and the confidence score give us a clear, reliable signal for handing a request to the cloud AI.
Needle 3 (current) 8–29 MB. Adds structured extraction and embeddings. Needle 2 is still available (generation=2). Build against Needle 3 and keep Needle 2 as a fallback. Embeddings let us retrieve the right tools on the device.
Context window 256-token sliding window with pinned tool KV cache. We can't give Needle 80 tools at once. We need top-k tool retrieval, and long prompts go straight to the cloud.
Distribution libneedle.a (C), a CLI binary with an --serve HTTP mode, WASM. cactus-kotlin SDK (com.cactuscompute:cactus) uses JNI on Android and includes Whisper STT. Main path: a JNI wrapper around libneedle built with NDK/CMake. The Phase 0 spike checks whether cactus-kotlin already exposes Needle.
Fine-tuning pip install "cactus-needle[train]" → needle finetune data.jsonl → needle build --lora … --out tuned.cact Fine-tune on our exact tool catalog with synthetic data generated by a large model (Phase 4).
Hermes Agent (Nous) Open-source (MIT), self-hosted, exposes an OpenAI-compatible API server. Supported with no extra work through the OpenAI-compatible provider. A dedicated connector adds session and memory features later.

Sources: huggingface.co/Cactus-Compute/needle2 · github.com/cactus-compute/needle · github.com/cactus-compute/cactus-kotlin · hermes-agent.nousresearch.com


3. Scope of Work (SOW)

3.1 Objectives

  1. Run common phone actions on the device, offline, with p50 latency under 1 s (from text to action started).
  2. Let users connect any AI they choose (BYOK or a self-hosted agent) in under 2 minutes.
  3. Handle multi-step and generative tasks through the Action Plan Protocol, run safely on the device.
  4. Accept voice input with on-device STT and no extra cloud dependency.
  5. Safe by default: every sensitive action (send, call, delete, pay) needs explicit confirmation, and everything goes to an audit log.

3.2 In scope

# Workstream Deliverables
W1 Needle runtime NDK/JNI wrapper, model loading from assets, tool-set caching, embeddings-based tool retrieval, benchmark harness
W2 Orchestrator Router (local vs. cloud), Action Plan Protocol, plan validator, executor with variable binding, confirmation policy, retries
W3 AI providers OpenAI-compatible (OpenAI, OpenRouter, Groq, DeepSeek, Together, Ollama/LM Studio on LAN, Hermes), Anthropic Messages, Google Gemini, OpenCode server (Phase 4); streaming; structured output; web search passthrough
W4 Tool catalog ~50 tools across Device, Comms, Productivity, Info, UI-Automation, and Meta (see §6)
W5 Voice Push-to-talk STT (Android on-device recognizer + sherpa-onnx offline fallback), VAD, TTS replies
W6 App UX Onboarding, chat with action cards, permission center, provider setup, history and audit log, settings, Quick Settings tile, home widget, assistant-role entry point
W7 Security and privacy Keystore/Tink-encrypted secrets, risk-based confirmation, prompt-injection guards, data-egress preview, local-only mode
W8 Quality Unit, integration, and instrumented tests, a Needle accuracy eval set, CI, crash reporting (opt-in)
W9 Release Two build flavors (play and full), Play policy declarations, privacy policy, signed releases

3.3 Out of scope (v1)

  • iOS, wear OS, and desktop builds
  • Always-on wake word (planned for v1.x; see §11)
  • Payments and banking actions
  • Our own hosted backend or cloud (the app is serverless; users bring their own AI)
  • Automating third-party apps beyond the listed targets (Gmail, WhatsApp, Settings)

3.4 Assumptions

  • Minimum SDK 28 (Android 9) and target/compile SDK 36. (Needle runs on API 24+, but 28+ keeps permission handling simpler.)
  • A single user per device, with no accounts on our side.
  • The user supplies their own API keys and pays their provider directly.

3.5 Acceptance criteria (v1.0)

  • ≥ 95% correct tool plus arguments on our 300-prompt local eval set (after fine-tuning; baseline measured in Phase 0).
  • Local action latency p50 < 800 ms, p95 < 1.5 s on a mid-range device (e.g., Pixel 6a or Galaxy A54).
  • Cloud-delegated plans validate against the schema ≥ 98% of the time (with 1 automatic repair retry).
  • No HIGH-risk action runs without confirmation (enforced by tests).
  • App cold start < 1.5 s. Needle RAM < 60 MB. APK < 45 MB (without optional STT model).
  • The leave-request, WhatsApp-message, call, flashlight, and notification-summary scenarios pass end to end on 3 real devices.

4. Architecture

┌──────────────────────────────── Android App ─────────────────────────────────┐
│  UI (Compose)  ── Chat · Voice button · Action cards · Confirm sheets          │
│        │                                                                       │
│  Input: Text | Voice(STT) | QS Tile | Widget | Assistant role | Share-to       │
│        ▼                                                                       │
│  ┌──────────────────────── ORCHESTRATOR ─────────────────────────┐            │
│  │ 1. Pre-router (rules: length, "search", attachments)           │            │
│  │ 2. ToolRetriever (Needle embeddings → top-k tools + meta tools)│            │
│  │ 3. NeedleEngine.infer(prompt, tools, facts)                    │            │
│  │      ├─ call(local tool, conf ≥ τ)  → Executor                 │            │
│  │      ├─ call(delegate_to_ai / web_search) → CloudPlanner       │            │
│  │      └─ empty / low conf            → CloudPlanner             │            │
│  │ 4. CloudPlanner → AiProvider → ActionPlan JSON                 │            │
│  │ 5. PlanValidator (schema, tool exists, args, risk)             │            │
│  │ 6. Executor (steps, {{vars}}, ask_user, confirm, retry)        │            │
│  │ 7. Result → (optional) summarizer → UI/TTS                     │            │
│  └────────────────────────────────────────────────────────────────┘            │
│        ▼                                                                       │
│  TOOL REGISTRY ── Device │ Comms │ Productivity │ Info │ UI-Automation │ Meta  │
│        ▼                                                                       │
│  Android APIs: CameraManager, Telecom, SmsManager, ContactsContract,           │
│  CalendarContract, AlarmClock, NotificationListener, AccessibilityService,     │
│  MediaSession, Location, Gmail REST, Intents …                                 │
│                                                                                │
│  Data: Room (history, audit, memory) · DataStore (settings) · Tink (secrets)   │
└────────────────────────────────────────────────────────────────────────────────┘
            │ HTTPS (only the user's chosen AI; nothing else)
            ▼
   OpenAI-compat / Anthropic / Gemini / OpenRouter / Ollama / Hermes / OpenCode

4.1 Routing rules

Condition Route
Prompt > ~150 tokens, has an attachment, or contains explicit "search/look up/latest" Cloud directly
Needle returns a local tool with confidence ≥ 0.75 and all required args Execute locally
Needle returns delegate_to_ai or web_search Cloud, with the chosen target tool's schema attached
Needle returns empty, respond, or confidence < 0.75 Cloud (full catalog summary)
No AI connected (local-only mode) Needle only. Otherwise say "This needs an AI connection"

4.2 Why the cloud AI gets our tool catalog

The cloud AI plans with the same tool registry (exported as OpenAI/Anthropic/Gemini tool schemas) and returns an Action Plan, not free text. Needle stays the fast local path. The Executor remains the only component that touches the device.


5. Action Plan Protocol (APP) v1

The system prompt sent to the cloud AI enforces this contract. It uses native structured output where the provider supports it (OpenAI response_format: json_schema, Anthropic tool-forced output, Gemini responseSchema), with JSON-schema validation and one repair retry.

{
  "app_version": "1",
  "intent": "Create a leave-request email draft",
  "reply": "Saved your leave request to Gmail Drafts.",
  "steps": [
    { "id": "s1", "type": "ask_user", "question": "Which dates do you need off?",
      "save_as": "dates", "input": "text" },
    { "id": "s2", "type": "tool", "tool": "contacts.search",
      "args": { "query": "manager" }, "save_as": "mgr", "optional": true },
    { "id": "s3", "type": "tool", "tool": "gmail.create_draft",
      "args": { "to": "{{mgr.email}}", "subject": "Leave Request – {{dates}}",
                "body": "Dear {{mgr.name|Manager}},\n..." } },
    { "id": "s4", "type": "respond", "text": "Draft saved: {{s3.result.subject}}" }
  ]
}

Step types: tool, ask_user, confirm, respond, ai (a sub-query back to the AI with prior results, e.g., "summarize these notifications"), condition (if: "{{s1.result.count}} > 0").

Executor rules

  • Max 12 steps and max 2 nested ai calls per request.
  • {{var.path|default}} binding, resolved at step time.
  • Every tool step is validated against the registry schema before it runs.
  • Risk is taken from the tool definition, never from the AI. HIGH-risk steps always show a confirm sheet with the final resolved args.
  • Tool results sent back to the AI are truncated and redacted (for example, phone numbers masked unless needed).
  • Content from notifications, web pages, or screen text is wrapped as untrusted_content in prompts. A plan produced after reading untrusted content gets confirmation forced on every non-read step.

6. Tool Catalog (v1)

Risk levels: L = runs silently · M = runs with a snackbar and Undo · H = explicit confirmation required.

Group Tool Android mechanism Permission / special access Risk
Device device.flashlight(on) CameraManager.setTorchMode none L
device.volume(stream, level) AudioManager none L
device.ringer_mode(mode) / dnd(on) AudioManager, NotificationManager Notification-policy access M
device.brightness(level) Settings.System WRITE_SETTINGS (special) L
device.open_settings_panel(wifi|bt|internet|nfc) Settings.Panel (direct Wi-Fi/BT toggles are blocked on Android 10+) none L
device.battery_status() / device.info() BatteryManager none L
device.screenshot() AccessibilityService takeScreenshot (API 30+) Accessibility M
device.rotate_lock(on) Settings.System WRITE_SETTINGS L
Apps apps.open(name) / apps.list() PackageManager + launcher <queries> none L
Media media.control(play|pause|next|prev) MediaSessionManager Notification listener L
media.play_search(query, app) MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH none L
Clock alarm.set(time, label) / timer.set(sec) / alarm.list() AlarmClock intents SET_ALARM M
Calendar calendar.list(range) / calendar.create(event) CalendarContract READ/WRITE_CALENDAR L / M
Contacts contacts.search(query) / contacts.get(id) ContactsContract READ_CONTACTS L
Phone phone.call(number|contact) ACTION_CALL (full) / ACTION_DIAL (play) CALL_PHONE H
phone.recent_calls() CallLog READ_CALL_LOG (full flavor only) L
SMS sms.send(to, text) SmsManager (full) / ACTION_SENDTO (play) SEND_SMS (full flavor only) H
sms.read_recent(from?) Telephony.Sms READ_SMS (full only) L
WhatsApp whatsapp.open_chat(contact, text?) https://wa.me/<num>?text= or ACTION_SEND + setPackage(com.whatsapp) none M
whatsapp.send(contact, text) open chat + AccessibilityService taps Send Accessibility H
whatsapp.reply(notification_id, text) NotificationListener RemoteInput reply (reliable, no UI scraping) Notification listener H
Email gmail.create_draft(to, cc?, subject, body) Gmail REST API users.drafts.create (OAuth, scope gmail.compose) Google authorization M
gmail.send(...) Gmail API messages.send Google authorization H
gmail.search(query) / gmail.read(id) Gmail API (gmail.readonly) Google authorization L
email.compose(to, subject, body) ACTION_SENDTO mailto: (any mail app; fallback) none M
Notifications notifications.list(app?, since?) / notifications.summarize() NotificationListenerService + Room cache Notification listener L
notifications.dismiss(id) same same M
Location / Nav location.current() Fused Location Provider ACCESS_COARSE/FINE_LOCATION L
maps.navigate(dest, mode) google.navigation: / geo: intents none L
Camera camera.capture_photo() / camera.record_video() MediaStore intents none L
Files / Clipboard clipboard.set(text) / share.text(text, app?) ClipboardManager, ACTION_SEND none L
Notes / Reminders notes.create(text) / reminder.create(text, time) Local Room + AlarmManager exact alarm SCHEDULE_EXACT_ALARM / USE_EXACT_ALARM L
UI automation ui.read_screen() / ui.tap(text|id) / ui.type(text) / ui.back() / ui.scroll(dir) AccessibilityService node tree Accessibility (disclosure required) M–H
Info web_search(query) Via cloud provider's native search (Anthropic web_search, OpenAI web search, Gemini grounding) or a BYO Brave/Tavily key network L
web.fetch(url) OkHttp + Readability-style extraction network L
Meta delegate_to_ai(task, target_tool?) Sends to CloudPlanner none –
ask_user(question) / respond(text) UI none –
memory.remember(fact) / memory.recall(query) Room + Needle embeddings none L

Tool retrieval for Needle's 256-token window: every tool description is embedded once with Needle embeddings. For each query we take the top-6 tools plus 3 meta-tools (delegate_to_ai, web_search, ask_user) and cache the compiled tool KV per tool-set signature (LRU of 16). Phase 0 checks the real tool budget.


7. Technology Stack

Layer Choice Notes
Language Kotlin 2.x (K2), Java 17 toolchain
UI Jetpack Compose + Material 3 (Compose BOM), Navigation-Compose (type-safe routes) Adaptive layouts
Architecture MVVM + UDF, Clean-ish layers (ui → domain → data), multi-module Gradle
DI Hilt (+ KSP)
Async Coroutines + Flow
Serialization kotlinx.serialization (JSON) Tool schemas, APP plans
JSON Schema validation com.networknt:json-schema-validator or a small hand-rolled validator in :core:model Plan validation
Networking OkHttp 4/5 + okhttp-sse (streaming), kotlinx.serialization converters No Retrofit needed
Local DB Room (KSP) history, audit, notifications cache, memory, embeddings
Settings DataStore (Proto or Preferences)
Secrets Android Keystore + Google Tink (AEAD) wrapping a DataStore EncryptedSharedPreferences is deprecated
Background WorkManager (model downloads, notification indexing), foreground service type microphone while listening
On-device model Cactus Needle 3 (Needle 2 fallback) via NDK + CMake + JNI around libneedle. Alternative: com.cactuscompute:cactus SDK .cact model bundled in assets/ (~14–29 MB)
STT (primary) Android SpeechRecognizer. createOnDeviceSpeechRecognizer (API 31+) = offline, 0 MB Default
STT (offline fallback) sherpa-onnx (Apache-2.0) streaming Zipformer model (~20–70 MB, downloaded on demand) + Silero VAD Also covers devices without an on-device recognizer. Alternative: Cactus Whisper-tiny
TTS Android TextToSpeech Optional voice replies
Google auth Credential Manager (Sign in with Google) + Identity.getAuthorizationClient for Gmail scopes Gmail REST calls go through OkHttp
AI providers Hand-written thin clients: OpenAI Chat Completions/Responses-compatible, Anthropic Messages, Gemini generateContent Kept thin; no heavy SDKs
Agent connectors Hermes Agent (OpenAI-compatible API server), OpenCode (opencode serve HTTP API), MCP client (Streamable HTTP) in v1.x
Images Coil 3 Avatars and app icons
Logging Timber
Crash reporting Opt-in only: Sentry (self-hostable) or none Privacy first
Testing JUnit5, MockK, Turbine, kotlinx-coroutines-test, Robolectric, Compose UI test, Espresso/UIAutomator, MockWebServer
Quality ktlint/Spotless, Detekt, Android Lint, R8 full mode
Build Gradle KTS, version catalog (libs.versions.toml), convention plugins in build-logic/
CI GitHub Actions: lint → unit → build both flavors → (nightly) instrumented on emulator
Model tooling (dev only) Python 3.11, cactus-needle[train] for fine-tuning and evals tools/needle/

Exact library versions get pinned in gradle/libs.versions.toml at the latest stable release when the project starts.

7.1 Build flavors (needed because of Play Store policy)

Flavor Distribution Differences
play Google Play No SEND_SMS, READ_SMS, or READ_CALL_LOG (Play restricts these to default SMS/dialer apps). Sends go through intents where the user taps Send. Accessibility automation stays behind a prominent disclosure and the Play Accessibility declaration.
full GitHub Releases / F-Droid-style sideload All permissions. Direct SMS, direct calls, and full UI automation.

8. Security, Privacy & Safety

  1. Secrets: API keys and OAuth tokens are encrypted with Tink AEAD using a Keystore-backed key (StrongBox when available). They never appear in logs and are excluded from backups (dataExtractionRules).
  2. Egress control: the app contacts only (a) the configured AI endpoint, (b) Google APIs if Gmail is connected, and (c) the search API if configured. A "What will be sent" preview can be turned on in Settings.
  3. Local-only mode: Needle only, with the network turned off for AI.
  4. Confirmation policy: set per tool (L/M/H), with user overrides only toward more strict.
  5. Prompt-injection defenses: untrusted-content tagging, forced confirmation after reading untrusted input, and no chaining of ai steps that feed untrusted content into send-type tools without confirmation.
  6. Audit log: every executed step with its timestamp, tool, redacted args, and result. Exportable and clearable.
  7. Accessibility service: limited to an allow-list of packages (Gmail, WhatsApp, Settings) and active only during a running plan. canRetrieveWindowContent is used only while a plan is running.
  8. Permissions are requested just in time, with a rationale screen, from the Permission Center.

9. Project structure: every file to create

ai-support/
├── README.md                              # Overview, build, flavors, setup
├── LICENSE                                # Project license (TBD – Apache-2.0 suggested)
├── .gitignore
├── .editorconfig
├── settings.gradle.kts                    # Module includes, repositories
├── build.gradle.kts                       # Root: plugin aliases only
├── gradle.properties                      # JVM args, AndroidX, config cache
├── gradle/
│   ├── libs.versions.toml                 # Version catalog (all deps pinned)
│   └── wrapper/gradle-wrapper.properties
├── gradlew / gradlew.bat
├── build-logic/                           # Convention plugins
│   ├── settings.gradle.kts
│   └── convention/
│       ├── build.gradle.kts
│       └── src/main/kotlin/
│           ├── AndroidApplicationConventionPlugin.kt
│           ├── AndroidLibraryConventionPlugin.kt
│           ├── AndroidComposeConventionPlugin.kt
│           ├── AndroidHiltConventionPlugin.kt
│           ├── AndroidRoomConventionPlugin.kt
│           ├── KotlinSerializationConventionPlugin.kt
│           └── FlavorsConvention.kt       # play / full flavors
├── config/
│   ├── detekt/detekt.yml
│   └── lint/lint.xml
├── .github/workflows/
│   ├── ci.yml                             # lint, unit, assemble both flavors
│   └── nightly-instrumented.yml
├── docs/
│   ├── PLAN.md                            # ← this document
│   ├── ARCHITECTURE.md
│   ├── ACTION_PLAN_PROTOCOL.md            # APP v1 spec + JSON schema
│   ├── TOOL_CATALOG.md                    # Generated from registry
│   ├── PRIVACY_POLICY.md
│   ├── PLAY_POLICY_DECLARATIONS.md        # Accessibility / permissions justification
│   └── adr/0001-needle-jni.md, 0002-app-protocol.md, 0003-flavors.md
│
├── app/
│   ├── build.gradle.kts
│   ├── proguard-rules.pro
│   └── src/
│       ├── main/
│       │   ├── AndroidManifest.xml        # permissions, services, queries, QS tile, assistant
│       │   ├── kotlin/app/stitch/
│       │   │   ├── StitchApplication.kt   # @HiltAndroidApp, Timber, WorkManager config
│       │   │   ├── MainActivity.kt        # Compose host, intent handling (share/assist)
│       │   │   ├── navigation/StitchNavHost.kt
│       │   │   ├── navigation/Routes.kt
│       │   │   ├── entry/AssistActivity.kt          # ACTION_ASSIST / long-press entry
│       │   │   ├── entry/StitchTileService.kt       # Quick Settings tile → voice
│       │   │   ├── entry/StitchWidget.kt            # Glance home widget
│       │   │   ├── entry/ShareReceiverActivity.kt   # "Share to Stitch"
│       │   │   └── di/AppModule.kt
│       │   └── res/
│       │       ├── values/strings.xml, themes.xml, colors.xml
│       │       ├── xml/accessibility_service_config.xml
│       │       ├── xml/data_extraction_rules.xml, backup_rules.xml
│       │       ├── xml/stitch_widget_info.xml
│       │       └── mipmap-*/ic_launcher*
│       ├── play/AndroidManifest.xml       # removes SMS/CallLog perms (tools:node="remove")
│       ├── full/AndroidManifest.xml       # adds SEND_SMS, READ_SMS, READ_CALL_LOG
│       └── androidTest/…/EndToEndScenariosTest.kt
│
├── core/
│   ├── common/        src/main/kotlin/app/stitch/core/common/
│   │   ├── Result.kt, DispatcherProvider.kt, Clock.kt, Redactor.kt
│   ├── model/         src/main/kotlin/app/stitch/core/model/
│   │   ├── ToolSpec.kt              # name, description, params (JSON schema), risk, permissions
│   │   ├── ToolCall.kt, ToolResult.kt, RiskLevel.kt
│   │   ├── ActionPlan.kt            # APP v1 data classes (@Serializable)
│   │   ├── PlanStep.kt              # sealed: Tool, AskUser, Confirm, Respond, Ai, Condition
│   │   ├── ChatMessage.kt, Conversation.kt
│   │   └── ProviderConfig.kt
│   │   └── src/main/resources/schema/action_plan_v1.schema.json
│   ├── data/          src/main/kotlin/app/stitch/core/data/
│   │   ├── db/StitchDatabase.kt
│   │   ├── db/dao/{ConversationDao, MessageDao, AuditDao, NotificationDao, MemoryDao}.kt
│   │   ├── db/entity/{ConversationEntity, MessageEntity, AuditEntity, NotificationEntity, MemoryEntity}.kt
│   │   ├── settings/SettingsRepository.kt   # DataStore
│   │   ├── repo/{ConversationRepository, AuditRepository, MemoryRepository}.kt
│   │   └── di/DataModule.kt
│   ├── security/      src/main/kotlin/app/stitch/core/security/
│   │   ├── SecretStore.kt           # Tink AEAD + Keystore
│   │   ├── ConfirmationPolicy.kt
│   │   └── UntrustedContent.kt      # tagging + injection guards
│   └── ui/            src/main/kotlin/app/stitch/core/ui/
│       ├── theme/{Theme, Color, Type, Shape}.kt
│       └── components/{ActionCard, ConfirmSheet, MicButton, ProviderChip, PermissionRow}.kt
│
├── engine/
│   ├── needle/
│   │   ├── build.gradle.kts         # externalNativeBuild cmake, abiFilters arm64-v8a, armeabi-v7a, x86_64
│   │   ├── src/main/cpp/
│   │   │   ├── CMakeLists.txt
│   │   │   ├── needle_jni.cpp       # JNI: load, setTools, infer, embed, release
│   │   │   └── third_party/needle/  # libneedle.a per ABI + needle.h (vendored release)
│   │   ├── src/main/assets/models/needle.cact
│   │   └── src/main/kotlin/app/stitch/engine/needle/
│   │       ├── NeedleNative.kt      # external fun declarations
│   │       ├── NeedleEngine.kt      # suspend infer(), single-thread dispatcher, lifecycle
│   │       ├── NeedleResult.kt      # type, calls, reasoning, confidence, metrics
│   │       ├── ToolSetCache.kt      # LRU of compiled tool sets
│   │       ├── ToolRetriever.kt     # embeddings top-k
│   │       ├── SystemFacts.kt       # date, locale, battery, foreground app…
│   │       └── di/NeedleModule.kt
│   └── orchestrator/  src/main/kotlin/app/stitch/engine/orchestrator/
│       ├── Orchestrator.kt          # entry: handle(userInput): Flow<OrchestratorEvent>
│       ├── PreRouter.kt
│       ├── RouteDecision.kt
│       ├── CloudPlanner.kt          # builds prompt, calls provider, parses APP
│       ├── PlannerPrompts.kt        # system prompt, APP contract, few-shots
│       ├── PlanValidator.kt
│       ├── PlanRepairer.kt          # one retry with validator errors
│       ├── Executor.kt              # step loop, var binding, ask/confirm suspension
│       ├── VariableResolver.kt      # {{a.b|default}}
│       ├── OrchestratorEvent.kt     # Thinking, NeedsInput, NeedsConfirm, StepDone, Reply, Error
│       └── di/OrchestratorModule.kt
│
├── ai/
│   └── providers/     src/main/kotlin/app/stitch/ai/providers/
│       ├── AiProvider.kt            # interface: chat(), planStructured(), supportsSearch
│       ├── ProviderRegistry.kt
│       ├── ToolSchemaExporter.kt    # ToolSpec → OpenAI / Anthropic / Gemini formats
│       ├── openai/OpenAiCompatibleProvider.kt  # OpenAI, OpenRouter, Groq, Ollama, LM Studio, Hermes
│       ├── anthropic/AnthropicProvider.kt
│       ├── gemini/GeminiProvider.kt
│       ├── opencode/OpenCodeProvider.kt        # Phase 4
│       ├── hermes/HermesProvider.kt            # Phase 4 (extends OpenAI-compat + session)
│       ├── mcp/McpClient.kt                    # v1.x
│       ├── search/{SearchProvider, BraveSearch, TavilySearch}.kt
│       ├── http/{HttpClientFactory, SseParser}.kt
│       └── di/ProvidersModule.kt
│
├── tools/
│   ├── api/           src/main/kotlin/app/stitch/tools/api/
│   │   ├── DeviceTool.kt            # interface { spec; suspend execute(args, ctx) }
│   │   ├── ToolRegistry.kt          # Hilt multibinding Set<DeviceTool>
│   │   ├── ToolContext.kt           # permissions checker, activity launcher, confirmer
│   │   ├── PermissionGate.kt
│   │   └── ArgParser.kt
│   ├── device/        …/tools/device/{Flashlight, Volume, RingerDnd, Brightness, SettingsPanel, Battery, DeviceInfo, AppsOpen, AppsList, MediaControl, MediaPlaySearch}Tool.kt
│   ├── comms/         …/tools/comms/{PhoneCall, RecentCalls, SmsSend, SmsRead, ContactsSearch, ContactsGet, WhatsAppOpenChat, WhatsAppSend, WhatsAppReply, EmailCompose}Tool.kt
│   │                  …/tools/comms/gmail/{GmailAuth, GmailApi, GmailCreateDraftTool, GmailSendTool, GmailSearchTool, GmailReadTool}.kt
│   ├── productivity/  …/tools/productivity/{AlarmSet, TimerSet, AlarmList, CalendarList, CalendarCreate, NoteCreate, ReminderCreate, Clipboard, ShareText, CameraCapture, Navigate, LocationCurrent}Tool.kt
│   ├── notifications/ …/tools/notifications/
│   │   ├── StitchNotificationListener.kt   # NotificationListenerService
│   │   ├── NotificationIndexer.kt
│   │   └── {NotificationsList, NotificationsSummarize, NotificationsDismiss}Tool.kt
│   ├── automation/    …/tools/automation/
│   │   ├── StitchAccessibilityService.kt
│   │   ├── ScreenReader.kt          # node tree → compact text for AI
│   │   ├── UiActions.kt             # tap/type/scroll/back with waits
│   │   ├── recipes/GmailSaveDraftRecipe.kt
│   │   ├── recipes/WhatsAppSendRecipe.kt
│   │   └── {UiReadScreen, UiTap, UiType, UiBack, UiScroll, Screenshot}Tool.kt
│   ├── web/           …/tools/web/{WebSearchTool, WebFetchTool}.kt
│   └── meta/          …/tools/meta/{DelegateToAiTool, AskUserTool, RespondTool, MemoryRememberTool, MemoryRecallTool}.kt
│
├── voice/             src/main/kotlin/app/stitch/voice/
│   ├── SpeechInput.kt               # interface: Flow<SpeechEvent> (partial, final, level, error)
│   ├── AndroidSpeechInput.kt        # SpeechRecognizer / on-device
│   ├── SherpaSpeechInput.kt         # sherpa-onnx streaming + VAD
│   ├── SpeechModelDownloader.kt     # WorkManager, checksum
│   ├── VoiceSessionService.kt       # FGS type=microphone
│   ├── SpeechOutput.kt              # TextToSpeech wrapper
│   └── di/VoiceModule.kt
│
├── feature/
│   ├── chat/          …/feature/chat/{ChatScreen, ChatViewModel, MessageList, InputBar, ActionTimeline}.kt
│   ├── onboarding/    …/feature/onboarding/{OnboardingScreen, WelcomeStep, ConnectAiStep, PermissionsStep, VoiceStep}.kt
│   ├── providers/     …/feature/providers/{ProvidersScreen, ProviderEditScreen, ProviderTestUseCase, ProvidersViewModel}.kt
│   ├── permissions/   …/feature/permissions/{PermissionCenterScreen, PermissionCenterViewModel, SpecialAccessIntents}.kt
│   ├── history/       …/feature/history/{HistoryScreen, AuditLogScreen, HistoryViewModel}.kt
│   └── settings/      …/feature/settings/{SettingsScreen, SafetySettings, VoiceSettings, PrivacySettings, SettingsViewModel}.kt
│
└── tools-dev/         (not shipped – dev tooling)
    └── needle/
        ├── requirements.txt          # cactus-needle[train]
        ├── export_tools.py           # reads generated tools.json from the app build
        ├── gen_synthetic_data.py     # uses a big LLM to create prompt→call pairs
        ├── eval_set.jsonl            # 300 hand-checked prompts
        ├── run_eval.py               # accuracy / latency report
        └── finetune.sh               # needle finetune → needle build → .cact

About 190 source files across 20 Gradle modules. Modules keep the native/JNI code, tools, and providers separately testable and allow parallel work.


10. Implementation Phases & Timeline

Estimates assume 1 senior Android dev full-time; with two devs, roughly 40% less. Every phase ends with a demo build.

Phase Duration Content Exit criteria
0 – Feasibility spike 1 wk Build libneedle for arm64 via NDK, JNI infer/embed, bench on 2 devices; measure tool budget in the 256-token window; confirm Needle 2 vs 3; test SpeechRecognizer on-device availability; Gmail OAuth test app Go/No-Go: p50 < 500 ms inference, ≥ 80% baseline accuracy on 50 prompts
1 – Foundation & MVP 3 wks Gradle skeleton, build-logic, core modules, Room/DataStore/Tink; Needle engine + retriever; Orchestrator (local path); OpenAI-compatible + Anthropic + Gemini providers; APP v1 + validator + executor; 15 tools (device, apps, alarms, contacts, media, calendar); Chat UI + action cards; push-to-talk voice (Android STT) "Turn on the flashlight", "set an alarm for 7", "what's on my calendar" work offline; "what's the weather in Lagos" goes to the cloud
2 – Communication & email 3 wks Phone, SMS (flavor-split), WhatsApp open/reply via notification, notification listener + summarize, Gmail OAuth + drafts/send/search, email.compose fallback, confirm sheets, audit log, Permission Center Leave-request → Gmail draft end to end; "reply to Ali on WhatsApp: on my way" works from notification
3 – Automation & voice+ 3 wks AccessibilityService + recipes (Gmail save-draft fallback, WhatsApp send), ui.* tools, screen-context to AI, sherpa-onnx offline STT + VAD, TTS replies, QS tile, widget, assistant role, share-to-Stitch Full scenario list passes on 3 devices; voice works in airplane mode
4 – Agents & tuning 2 wks Hermes connector, OpenCode connector, web search (native + Brave/Tavily), memory tools; synthetic dataset + Needle fine-tune on our catalog; eval harness in CI ≥ 95% local eval accuracy; Hermes/OpenCode round-trip demo
5 – Hardening & release 2 wks Security review, injection red-team, perf/battery profiling, accessibility (TalkBack) for our own UI, Play declarations, privacy policy, store listing, signed play + full releases All acceptance criteria in §3.5 met

Total: about 14 weeks to v1.0. The MVP (Phase 1) is demoable at about week 4.


11. Roadmap after v1

  • Wake word ("Hey Stitch") via openWakeWord/ONNX in a low-power FGS
  • MCP client, so any MCP server's tools become cloud-side tools
  • Expose Stitch as an MCP server / API on the LAN, so desktop agents (OpenCode, Hermes, Claude Code) can drive the phone
  • Routines and triggers ("when I get home, turn on DND"), like Tasker
  • More app recipes (Telegram, Signal, Slack, Outlook)
  • Wear OS companion

12. Risks & Mitigations

Risk Likelihood Impact Mitigation
Needle's Android packaging/JNI is less documented than Python/C Med High Phase 0 spike; fallback: run the needle --serve arm64 binary as a local process on 127.0.0.1, or use the cactus-kotlin SDK
256-token window limits tool count High Med Embedding-based top-k retrieval, compact tool descriptions, fine-tuning
Play policy rejects Accessibility / SMS use High High play/full flavors, intent fallbacks, prominent disclosure, Notification RemoteInput for replies
gmail.compose is a restricted scope (needs Google verification + security assessment for public use) High Med Testing mode (≤100 users) during development; intent + accessibility fallback; budget for CASA before public launch
WhatsApp UI changes break the send recipe Med Med Prefer notification reply and wa.me prefill; resilient selectors (content-desc/resource-id), recipe versioning, graceful fallback to "tap Send yourself"
Prompt injection via notifications/web Med High Untrusted tagging, forced confirmations, egress limits (§8)
OEM background restrictions (Xiaomi, Samsung) kill listeners Med Med Battery-optimization exemption guide in onboarding, health check screen
User cost/latency of cloud AI Med Low Needle-first routing; show which path was used; model choice per provider

13. Open questions for the owner

  1. App name and package id: is app.stitch OK?
  2. Distribution: Play Store, sideload, or both? This decides how much of the full flavor we build first.
  3. Minimum Android: is 9 (API 28) OK, or do you need older devices?
  4. Gmail: is Gmail API with OAuth (best UX, needs Google Cloud project + verification later) acceptable for v1, or intent-only?
  5. Primary AI to test with first: OpenRouter, Anthropic, OpenAI, local Ollama, or Hermes?
  6. Languages for voice: English only for v1, or also Urdu/Hindi/Arabic? This affects the STT model choice.
  7. License: open source (Apache-2.0) or closed?