# Roadmap and Acceptance Criteria

The plugin system is a platform change, not a feature. It lands in vertical slices so
that each slice is testable without a working plugin marketplace.

## 1. Current state

- Android client: Telegram for Android 13.4.3, package `app.nextgram.dev`, Java 17,
  `minSdk 23`.
- Implementation status:
  - Implemented: `nextgram-plugin-sdk` core contracts, `nextgram-plugin-sdk-android`
    screen/slot contracts, `.ngp` manifest and signature verification, atomic installer
    and registry, DEX loading, built-in plugin loading, safe mode, plugin manager and
    install consent UI, declarative settings, message actions, chat toolbar actions, a
    sample Java plugin and JVM verifier/installer tests. Plugin Manager and Community
    are compiled-in plugins loaded through the same context and contribution APIs;
    Plugin Manager is core and locked, Community can be disabled and re-enabled live.
  - Implemented in the latest slice: code-plugin appearance (`AppearanceTheme`,
    `AppearanceHost.applyTheme`, semantic tokens, raw upstream keys, plugin-scoped custom
    colors, reset, persistence and safe mode), the five screen keys and contexts, the
    host-owned overlay on `BaseFragment` and `MainTabsActivity`, screen/slot registries,
    `CHAT_LIST_HEADER` and `SETTINGS_HEADER` slots, `AndroidHost.openScreen`, the
    "Allow screen replacement plugins" kill switch and the kernel **Reset appearance**
    action. Theme packages and the theme kind are removed.
  - Implemented earlier: plugin updates with permission diff and changelog, signed
    revocations with critical disable and warning overrides, signed GitHub repository
    client and UI (strict index parser, ECDSA P-256 verification, ETag cache,
    search/categories/details, verified download and install through the existing
    consent screen), read API v1 (`accounts()`, `chats()` and `messages()` with
    permission checks and secret-chat filtering), message events (`RECEIVED`, `SENT`,
    `EDITED`, `DELETED`, send failed), account, chat and theme events,
    `STOP`/`onStop` pairing, first-frame boot counter, outgoing text interceptor,
    `ACTION_SEND` package install and `clipboard.write` enforcement.
  - Release hardening delivered: the release build passes with R8, SDK and built-in
    classes are kept, Gson registry/revocation state survives shrinking, archive and
    parser fuzz tests cover `.ngp`, catalog and revocation input, script packages pass
    the same verifier and consent flow, developer mode is compiled out of release builds,
    plugin log lines are capped, and performance smoke tests cover the pure-Java hot
    paths. See [security.md](/security/) for the final verifier and revocation rules.
  - Implemented in the maximum-capability slice: TypeScript SDK and CLI, QuickJS
    runtime and bridge, hybrid native modules, declarative UI and Canvas, the expanded
    screen/slot catalogue, resource overrides, message send/edit/delete/forward/react,
    member and chat-admin APIs, automation, HTTP/media/notifications, the internal
    facade, consent and manager switches, schema and documentation.
  - Not implemented yet: the test SDK module, custom repositories, per-screen theme
    isolation, media/calls inside a replaced chat, WorkManager-backed automation while
    the process is dead, and the broad instrumentation suite. A focused on-device
    package test exists.
  - Verified on this tree: `:TMessagesProj_App:assembleDebug`,
    `:TMessagesProj:testDebugUnitTest --tests 'dev.nextgram.plugin.*'`,
    `:nextgram-plugin-sdk-android:assembleDebug` and
    `:TMessagesProj_App:assembleRelease` pass. The JVM suite covers the plugin host,
    appearance mapping, screen/slot registries, repository parsers, archive attacks,
    deterministic fuzzing and performance smoke checks. The instrumentation test
    verifies signed code, appearance and screen packages on Android. On a physical
    device running Android 16, a locally served signed catalog was verified end to end:
    repository install, update with permission diff, warning and critical revocations,
    appearance apply/reset/persistence, and chat-list replacement with a slot.

## 2. Recommended execution order

The platform is built in vertical slices. The order below keeps every slice testable
and avoids adding API surface that the host cannot enforce.

1. **Freeze the implemented SDK surface.** Keep the status table in
   [sdk.md](/sdk/) accurate; stop documenting accounts/chats/messages as available
   until they are enforced and tested.
2. **Complete the event seams.** Delivered for lifecycle, account, chat, theme,
   received/sent/edited/deleted and send failed. The outgoing text interceptor is also
   wired.
3. **Add the read API.** Accounts, chats and message snapshots are delivered with
   permission checks and secret-chat filtering. Contacts, media and notification APIs
   are pending.
4. **Appearance and screens.** Code-plugin appearance and the five-screen overlay
   framework are delivered: `AppearanceTheme`, `AppearanceRuntime`,
   `nextgram-plugin-sdk-android`, screen/slot registries, the `BaseFragment` and
   `MainTabsActivity` seams, contexts, slots, `openScreen` and the kill switch.
   Follow-ups: per-screen theme isolation, chat media/calls, more screens and slots.
5. **Script runtime.** Delivered: QuickJS behind the script adapter, TypeScript SDK
   and CLI, sandbox limits, templates and examples. On-device runtime checks remain a
   release gate.
6. **GitHub repository and updates.** Repository scaffold, signed index, publishing
   workflow, Repository screen, install, update checks, permission diff and revocation
   are delivered. Custom repositories and share-to-chat remain. Follow
   [distribution.md](/distribution/).
7. **Platform tooling.** `nextgram-plugin-sdk-android` is delivered;
   `nextgram-plugin-sdk-test`, a Gradle plugin and the TypeScript CLI remain.
8. **Hardening.** Instrumentation tests, fuzzing, security review, performance budgets
   and the release gates in section 6.
9. **Desktop.** Reuse the container and manifest with a desktop payload and loader.

## 3. Milestones

### Phase 0 — Foundations

Status: partially delivered. The core SDK, Android screen SDK, manifest schema,
verifier fixtures and sample plugin exist. The test SDK, Gradle plugin and TypeScript
CLI do not.

Deliverables:

- Plugin SDK modules:
  - `nextgram-plugin-sdk` — platform-neutral core contracts (`java-library`);
  - `nextgram-plugin-sdk-android` — Android screen, slot and host contracts;
  - `nextgram-plugin-sdk-test` — fake host and fixtures.
- `plugin.schema.json` and a manifest validator.
- `.ngp` reader/writer test fixtures: valid code and script packages; invalid signature,
  traversal, duplicate entry, zip bomb, wrong API and wrong platform.
- `nextgram-plugin-tools` Gradle plugin skeleton and a TypeScript CLI skeleton.
- A sample code plugin repository layout and CI job that builds it against the SDK.

Acceptance:

- SDK modules build without depending on `TMessagesProj` or `org.telegram.*`.
- A sample plugin compiles against the SDK and produces a DEX + `.ngp`.
- The manifest schema validates all examples and rejects malformed manifests.
- Verifier unit tests pass on JVM.

### Phase 1 — Kernel and installer

Status: delivered except real-device verification of safe mode, `ACTION_SEND` and
Android 14 read-only DEX loading.

Deliverables:

- `dev.nextgram.plugin.host` kernel inside `TMessagesProj`.
- Installed-plugin registry and atomic package store.
- Signature verification, manifest validation and key pinning.
- `DexClassLoader` loading with read-only extraction.
- Safe mode and crash attribution.
- Plugin manager UI: installed list, details, enable/disable, uninstall, restart prompt.
- Installer UI: source, signature fingerprint, permissions, update consent.
- Install from file picker in the plugin manager for content with an unknown MIME type.
- `.ngp` detection in `AndroidUtilities.openDocument` and `openForView`.
- `ACTION_VIEW` and `ACTION_SEND` intent filters.
- System plugin registration for the plugin manager itself.

Acceptance:

- A signed sample `.ngp` sent in a chat installs from the chat document.
- The same package installs from a file manager and the share sheet.
- Invalid signatures, key mismatch, downgrade, unknown permission, unsafe path, native
  library, oversized package and unsupported API are rejected with specific errors.
- Install is atomic; a failed update leaves the previous version working.
- Enable/disable/uninstall works; code changes require a restart.
- A plugin that crashes during `onLoad` does not prevent the app from starting.
- Two consecutive boot crashes trigger safe mode with all external plugins disabled.
- Android 14+ loads the extracted DEX after it is marked read-only.
- The no-plugin path is unchanged.

### Phase 2 — API v1 and first extension points

Status: partially delivered. Declarative settings, message actions, toolbar actions,
lifecycle, account, chat, theme and message events, the outgoing text interceptor, the
accounts/chats/messages read API and the appearance/screen framework exist. Contacts,
media, notifications, Telegram actions and the remaining built-in migrations are
pending.

Deliverables:

- Lifecycle, context, permissions, storage, scheduler, logger.
- Snapshot mappers for accounts, dialogs, messages and users.
- Declarative settings (`SettingsSpec`) rendered through `UniversalFragment`/`UItem`.
- Message actions and chat toolbar actions in existing "More" menus.
- Events: app lifecycle, account, chat opened/closed, message received/sent/edited/
  deleted, theme changed.
- Outgoing message interceptor.
- Appearance API for code plugins and screen replacement/slots.
- Built-in plugins:
  - `app.nextgram.builtin.settings` — NextGram settings entry;
  - `app.nextgram.builtin.pluginmanager` — plugin manager (core, locked).
- Sample plugin exercising settings, message action, toolbar action, permission denial
  and storage.

Acceptance:

- The sample plugin adds a settings screen, a message action and a chat toolbar action.
- Settings are stored per plugin and survive restart.
- Permission revocation makes API calls fail with a clear error; the app does not crash.
- A code plugin applies an appearance theme and resets it without a restart.
- A code plugin replaces the chat list and adds a header slot; disabling it restores
  stock.
- Events arrive with correct account and snapshot data; secret chats never appear.
- Outgoing interceptor can modify and cancel a message; secret chats are excluded.
- Built-in plugins appear in the manager and can be disabled where allowed.
- No plugin registered: menus and settings are identical to upstream.
- UI is theme-aware, RTL-safe, and accessible.

### Phase 2.5 — Appearance and screen framework

Status: delivered. Theme packages are removed; appearance is a code-plugin capability.

Deliverables:

- `AppearanceTheme`, `AppearanceHost.applyTheme/resetTheme/hasTheme/themeColor/
  customColor`, compatibility wrappers and `AppearanceRuntime`.
- Semantic palette, raw upstream color keys, plugin-scoped custom colors, validation,
  persistence, previous-theme restore and safe-mode reset.
- `nextgram-plugin-sdk-android` with `AndroidHost`, `Screens`, `ScreenKey`, `SlotKey`,
  `PluginScreen`, `PluginScreenFactory`, the five contexts, `Navigation`,
  `MainTab` and `ScreenInsets`.
- Host-owned overlay at `BaseFragment`, `MAIN_NAVIGATION` at `MainTabsActivity`, the
  protected resolver, `ui.screens`/`ui.custom_screens` permissions, header slots,
  `openScreen` and the kill switch.
- Appearance section with the active provider and the kernel **Reset appearance**
  action. No theme catalog or preview.

Acceptance:

- A code plugin applies semantic, raw and custom colors and resets them.
- The five screen keys render plugin views; disabling the plugin restores stock.
- Secret chats, login, passcode, payments, installer and safe mode never receive plugin
  views or contexts.
- Status bar, navigation bar, cutouts, IME, RTL and font scale remain usable.
- The kill switch removes all overlays without uninstalling plugins.
- Zero-provider startup and frame time do not regress.

### Phase 3 — Script runtime

Status: delivered. QuickJS, the bridge, the TypeScript SDK and the CLI ship in this
tree; on-device runtime checks remain a release gate.

Deliverables:

- QuickJS integration behind a `ScriptRuntime` interface.
- `@nextgram/plugin` TypeScript SDK and `@nextgram/cli`.
- Script lifecycle, declarative settings, message actions, toolbar actions, events,
  storage, HTTP bridge, logging.
- Sandbox limits: 32 MB heap, 2 s background callback, 50 ms UI callback, bounded queue.
- Install-time script compilation check.
- A TypeScript sample plugin.

Acceptance:

- A TypeScript plugin can add settings and a translate message action.
- The script has no Android, Java, filesystem or socket access.
- A script infinite loop is interrupted and the plugin is disabled without an ANR.
- A script that exceeds memory is terminated.
- The TypeScript types match the v1 bridge; the CLI produces a signed `.ngp`.

Phase 3 is delivered. The manifest and package format already carried `kind: "script"`,
so the runtime landed without a format break.

### Phase 4 — GitHub repository and distribution

Status: app client, UI, install, updates, revocations and publishing tooling delivered.
The catalog repository is public and the official public key is pinned in the app; the
CI signing secret and the first published index are pending. Custom repositories are
deferred to the next release; share-to-chat is pending.

Deliverables:

- `nextgram-plugins` repository: per-plugin `entry.json`, schema, validation
  workflow, signed `catalog/index.json`, revocation list, contribution guide.
- Default repository `gitwelk/nextgram-plugins`; artifacts in GitHub Releases, index
  and metadata in the repository.
- Repository screen opened from the plugin manager: search, categories, featured,
  updates, plugin details with source, key fingerprint, permissions, changelog and
  screenshots.
- Index signature verification, pinned commit metadata, SHA-256 and package signature
  checks before the normal consent screen.
- Manual update check and opt-in daily check; permission diff on update.
- Revocation list handling.
- Share plugin from the plugin manager into a Telegram chat.
- Community repository support with trust-on-first-use and a visible key fingerprint.
- Optional presentation metadata: icon, cover and accent for plugin cards.

Acceptance:

- A repository install and an update pass the same verifier as a chat install.
- A repository entry cannot make a package signed by another key trusted.
- A new permission on update requires consent; declining keeps the old version.
- Revoked critical plugins are disabled at the next start with a clear notice.
- Update checks are off by default and send no account identifier.
- A bad or missing index signature fails closed; no package is offered.
- An artifact URL is immutable (release asset or commit-pinned raw path).
- Removing a release from the catalog does not break an already installed plugin.
- A pull request with an invalid entry, duplicate ID, bad icon or stale `versionCode`
  fails CI.
- Sharing a plugin sends a document with the correct MIME and file name.

See [distribution.md](/distribution/) for the repository layout and update flow.

### Phase 5 — Services and deeper UI

Status: not started.

Deliverables:

- Translation service and provider selection.
- Notification interceptor.
- Chat list actions/decorators, profile actions, drawer items, composer actions.
- Experimental message decorators (badge/footer/accent).
- Extract more existing features into built-in plugins.
- Plugin-to-plugin dependencies for load order only; typed cross-plugin services remain
  out of scope until a shared-class strategy exists.

Acceptance:

- A plugin can replace the translation provider and the user can switch back.
- A failing service provider falls back to the default without breaking the app.
- Chat list and profile contributions appear only where relevant and do not affect
  scroll performance.
- Built-in feature flags can disable migrated features without a rebuild.

### Phase 6 — Platform and hardening

Status: not started.

Deliverables:

- Desktop SDK and loader using the same container and manifest.
- Key rotation with an old-key-signed statement.
- Whole-file signature scheme in addition to JAR signing.
- Research spike: separate-process non-UI plugins with a Binder API.
- Security audit, fuzzing, reproducible builds and catalog attestations.
- Public plugin documentation and template repositories.

Acceptance:

- The same `.ngp` can carry an Android and a desktop payload; each client picks its
  own.
- A desktop plugin cannot break the Android verifier.
- Key rotation preserves plugin identity and data.
- The security audit has no open critical findings.

## 4. Work packages by area

### 3.1 SDK

```
nextgram-plugin-sdk/
  src/main/java/dev/nextgram/plugin/v1/
    NextGramPlugin.java
    PluginContext.java
    PluginInfo.java
    HostInfo.java
    PluginStorage.java
    PluginPreferences.java
    PluginScheduler.java
    PluginLogger.java
    PluginPermissions.java
    Permissions.java
    Contributions.java
    Registration.java
    Events.java
    Interceptors.java
    Services.java
    ServiceKey.java
    PlatformHost.java
    ...
    events/
    services/
    ui/
      SettingsSpec.java
      SettingsRow.java
      SettingsEntry.java
      SettingsScreen.java
      MessageAction.java
      ChatToolbarAction.java
      LocalizedText.java
      IconRef.java
      DialogSpec.java
```

```
nextgram-plugin-sdk-android/
  src/main/java/dev/nextgram/plugin/v1/android/
    AndroidHost.java
    Screens.java
    ScreenKey.java
    SlotKey.java
    PluginScreen.java
    PluginScreenFactory.java
    ScreenContext.java
    ChatListScreenContext.java
    ChatScreenContext.java
    SettingsScreenContext.java
    ProfileScreenContext.java
    MainNavigationScreenContext.java
    MainTab.java
    Navigation.java
    ScreenInsets.java
    SlotContribution.java
    SlotContext.java
    SlotSpec.java
```

The SDK modules must not depend on `TMessagesProj`.

### 3.2 Kernel

```
TMessagesProj/src/main/java/dev/nextgram/plugin/host/
  PluginRuntime.java
  PluginRegistry.java
  InstalledPlugin.java
  PluginManifest.java
  NgpVerifier.java
  PluginInstaller.java
  PluginClassLoader.java
  PluginGuard.java
  PluginPermissions.java
  PluginStorage.java
  PluginScheduler.java
  PluginLogger.java
  ContributionRegistry.java
  EventBus.java
  PluginInterceptorChain.java
  ServiceRegistry.java
  PluginThemeEvents.java
  AppearanceHostImpl.java
  AndroidHostImpl.java
  PluginScreensImpl.java
  PluginScreenRegistry.java
  PluginScreenRuntime.java
  PluginScreenPolicy.java
  PluginScreenContextImpl.java
  PluginScreenOverlay.java
  PluginScreenHostFragment.java
  PluginSlotRegistry.java
  PluginSlotHost.java

TMessagesProj/src/main/java/dev/nextgram/plugin/appearance/
  AppearanceRuntime.java
  AppearanceSpec.java
  AppearanceMapper.java
  AppearanceState.java

TMessagesProj/src/main/java/dev/nextgram/plugin/ui/
  PluginScreenSeams.java
```

### 3.3 Seams

```
TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java
TMessagesProj/src/main/java/org/telegram/ui/MainTabsActivity.java
TMessagesProj/src/main/java/org/telegram/ui/ActionBar/Theme.java
TMessagesProj/src/main/java/dev/nextgram/plugin/ui/
  PluginScreenSeams.java
TMessagesProj/src/main/java/dev/nextgram/plugin/host/
  PluginScreenOverlay.java
  PluginScreenHostFragment.java
  PluginSlotHost.java
```

Upstream files changed in Phase 1–2:

- `ApplicationLoader.java` — boot, lifecycle, crash handler.
- `LaunchActivity.java` — attach/detach UI host, install intents.
- `SettingsActivity.java` — NextGram settings entry.
- `ChatActivity.java` — message menu, toolbar overflow.
- `AndroidUtilities.java` — `.ngp` document detection.
- `SendMessagesHelper.java` — outgoing interceptor.
- `MessagesController.java` / `NotificationCenter.java` — event bridge.
- `Theme.java` — appearance/theme provider.
- `BaseFragment.java` — screen overlay attach, lifecycle, back and fast path.
- `MainTabsActivity.java` — main navigation tab-bar overlay.
- `TMessagesProj/src/main/AndroidManifest.xml` — installer intent filters.

### 3.4 Built-in plugins

```
TMessagesProj/src/main/java/dev/nextgram/builtin/
  community/CommunityPlugin.java
  pluginmanager/PluginManagerPlugin.java
  settings/NextGramSettingsPlugin.java
  ...
```

Built-in plugins use `dev.nextgram.plugin.host.internal` for privileged access and the
public SDK for contributions. They are registered once in `BuiltInPlugins.java`.

### 3.5 Tooling

```
nextgram-plugin-tools/            Gradle plugin: package, DEX, sign, verify
nextgram-plugin-cli/              TypeScript CLI: esbuild, package, sign
nextgram-plugin-template/         Kotlin/Java template repository
nextgram-script-template/         TypeScript template repository
```

The Gradle plugin must:

- collect the plugin's compiled classes and dependencies;
- run D8 with `--min-api 23` and produce one `classes.dex`;
- copy assets and the manifest;
- sign with the author's keystore;
- verify the result with the same verifier logic;
- fail if the SDK classes are bundled.

The TypeScript CLI must:

- bundle `script/main.js` with esbuild;
- reject Node built-ins and unsupported imports;
- generate or validate `plugin.json`;
- sign the package;
- optionally emit catalog metadata.

## 5. Test plan

### Unit tests (JVM)

- Manifest schema and semantic validation.
- Semver ranges and dependency resolution.
- ZIP path safety, duplicate entries, size limits, compression ratios.
- JAR signature verification and key pinning.
- Key mismatch and downgrade.
- Permission checks and default grants.
- Registry atomic writes and rollback.
- Settings spec mapping.
- Snapshot mappers with fake data.
- Event ordering and interceptor chain.
- Safe-mode state machine.
- `AppearanceTheme` builder limits, semantic/raw/custom validation, raw-key precedence,
  contrast warnings and appearance state transitions.
- `PluginScreenRegistry` stacks, duplicate rejection, protected resolver, permission
  gates, slot ordering and unload cleanup.

### Instrumentation tests

- Install from `content://`, `file://` and a chat document.
- DEX loading on API 23 and API 34+.
- Read-only extraction.
- Plugin manager enable/disable/uninstall.
- Settings screen rendering with `UniversalFragment`.
- Message menu and toolbar contributions.
- Appearance apply/reset, previous-theme restore and safe mode.
- Screen replacement, slot insertion, back, rotation and the kill switch.
- Protected surfaces: login, passcode, payment, installer and secret chat.
- Crash during `onLoad` and safe mode.
- Permission revocation.
- Secret chat filtering.
- Configuration change on a plugin screen.
- Multi-account events.

### Security tests

- Fuzz manifest JSON and ZIP parser.
- Malformed DEX headers.
- Signature stripping and duplicate entries.
- Zip bomb and nested archive.
- Script infinite loop, memory bomb and bridge type confusion.
- Screen provider registration without `ui.screens`, factory exceptions and unload
  during view creation.
- Appearance apply failure, invalid semantic/raw/custom keys and protected raw keys.
- Key mismatch update.
- Catalog signature forgery.
- Permission bypass attempts through the host API.
- QuickJS escape regression suite.

### Performance tests

- Startup with 0, 10, 25 and 50 plugins.
- Memory per idle plugin.
- Message menu build with no actions and with 20 actions.
- Chat list scroll with decorators off and on.
- Zero-provider screen seam allocations.
- Appearance apply time and screen creation time.
- Script callback latency.
- Install time for a 20 MB package.

## 6. Release gates for the first public plugin release

Verified on this tree:

- [x] Package format v1 is frozen for code and script payloads; both install through the
      same verifier and consent flow. Theme packages are removed and return
      `E_UNSUPPORTED_KIND`.
- [x] SDK API v1 is frozen in `dev.nextgram.plugin.v1`; the release build keeps the
      package names intact. The pre-release hard break is documented.
- [x] Archive attacks, parser limits, duplicate keys, deep nesting and malformed
      signatures are rejected by tests.
- [x] Script packages install and run on the QuickJS runtime behind the host bridge;
      the install screen shows the TypeScript sandbox badge.
- [x] Critical revocations disable a plugin at startup and when a signed feed is
      applied; warning overrides stay bounded by the revoked version range.
- [x] A failed update leaves the previous version installed and enabled.
- [x] Safe-mode state, first-frame boot reset, revocation matching, permission diff,
      snapshot mapping, appearance state and screen registry state are covered by
      pure-Java tests.
- [x] A debug build, the Android SDK module and a release build with R8 pass; the release
      APK is produced.
- [x] The SDK, built-ins and Gson state classes are kept from shrinking and
      obfuscation.
- [x] Plugin log lines are capped and host code does not log message contents or phone
      numbers.
- [x] Plugin documentation matches the shipped feature set.

Emulator verification (Android 16, API 36):

- [x] Safe mode after a real crash loop: repeated launch crashes enabled safe mode and
      appearance apply and screen providers stayed inactive.
- [x] Signed release APK installs and launches.
- [x] A signed code appearance package and a signed screen package install and open the
      install preview.
- [x] A theme package is rejected with `E_UNSUPPORTED_KIND` and no preview.
- [x] On-device instrumentation verifies signed code, appearance and screen packages
      (`PluginPackageDeviceTest`).

Verified on a physical device running Android 16 with an active account:

- [x] Repository browse, search, verified badge and download from a local signed catalog.
- [x] Appearance apply, reset and persistence across restart.
- [x] Chat-list replacement, header slot and stock restore on disable.
- [x] Update permission diff, consent and install of the new version.
- [x] Warning revocation with override and critical revocation with disable.

Still requires a specific device or account:

- [ ] Install from a chat document and a file manager on a production build.
- [ ] Android 14+ read-only DEX loading on a physical device.
- [ ] Startup and scroll performance budgets on low-end hardware.
- [ ] External security review of the verifier and signature code.
- [ ] First published catalog index and the CI signing secret.

## 7. Risks and mitigations

| Risk | Impact | Mitigation |
| --- | --- | --- |
| DEX plugins are trusted code | High | Clear UX, signatures, catalog review, script tier when shipped, future process isolation |
| Upstream merges break seams | Medium | Small seams, adapter tests, merge checklist |
| Android 14 dynamic code restrictions | Medium | Read-only extraction, API 34 tests, no native libs |
| DEX method limit | Medium | R8, single-dex limit, dependency guidance |
| Kotlin stdlib duplication | Low | Java API, per-plugin class loader |
| QuickJS binding maintenance | Medium | Abstract behind `ScriptRuntime`, pin and patch engine |
| Parser vulnerabilities | High | Limits, fuzzing, security review, fast updates |
| Repository governance | Medium | Signed index, review checklist, revocation, community indexes |
| GitHub outage or rate limits | Medium | Signed index cache, manual refresh, file/chat fallback |
| Malicious pull request or CI compromise | High | Required reviews, least-privilege CI, no signing key in PR jobs, signed index |
| Repository binary bloat | Low | Artifacts in GitHub Releases, not in the source tree |
| Account bans from automation | High | No raw MTProto, rate limits, confirmations, policy |
| Plugin UI clutter | Medium | Actions in "More", host-owned layout, review |
| Screen spoofing of unprotected UI | High | `ui.screens` high risk and off by default, protected resolver, kill switch, consent warning |
| Stock screen runs under the overlay | Medium | Opaque overlay, zero-provider fast path, measure 0/10 plugins, future child detaching |
| Global appearance tints protected surfaces | Medium | Documented residual; no data access; reset and safe mode; per-screen isolation is a follow-up |
| GPL licensing ambiguity | Medium | Decide SDK linking exception before public SDK release |
| User confusion about permissions | Medium | Plain-language explanations and the trusted-code warning |
| Plugin abandonment | Low | Compatibility policy, source links, uninstall |

## 8. Open decisions

Decided:

- DEX code plugins are trusted code and are allowed by default with an explicit
  warning. Script plugins are the safer tier and run sandboxed in QuickJS.
- Theme packages are removed. Appearance is a code-plugin capability through
  `ui.appearance`; there is no separate theme tier.
- Screen replacement is a code-plugin capability through `ui.screens`, limited to five
  host screens with protected surfaces excluded.
- The TypeScript runtime ships in this tree, on top of the core
  code/installer/appearance work.
- The SDK is published under GPL-3.0 with a plugin-linking exception, subject to legal
  review of the wording.
- Distribution uses a GitHub repository with a signed index; GitHub is transport, not
  the trust anchor.
- The default repository is `gitwelk/nextgram-plugins`.
- Plugin artifacts live in GitHub Releases; source, metadata and icons live in the
  repository.
- Updates are never silent and are off by default.

Still open:

1. The exact legal wording of the plugin-linking exception.
2. Repository governance and who can mark plugins verified.
3. The custom repository trust model. Custom repositories are deferred to the next
   release and use trust-on-first-use or an explicit key import when added.
4. Whether plugin-to-plugin typed services are worth the shared-class complexity.
5. Per-screen theme isolation for login, passcode and payment surfaces.
6. Whether chat media, calls and payments should ever be exposed to a replaced `CHAT`
   screen. The current default is no.
7. Minimum Android version for the script runtime; QuickJS ABI coverage must be checked
   against the app's supported ABIs.

## 9. Suggested pull request sequence

1. **Docs and schema** — this document set, JSON Schema, examples. Delivered.
2. **SDK skeleton** — core and Android modules, no runtime. Both modules delivered;
   test module pending.
3. **Verifier** — ZIP, manifest, signature, key pinning, tests and fixtures. Delivered.
4. **Registry and installer** — staging, atomic install, package store, errors. Delivered.
5. **Class loader and lifecycle** — DEX load, `onLoad`, guard, safe mode. Delivered for
   code plugins; lifecycle, account, chat, theme and message seams are done.
6. **Installer UI and plugin manager** — consent, list, details, restart. Delivered.
7. **Chat/file integration** — document seam, intent filters, share. Document and
   `ACTION_VIEW` and `ACTION_SEND` delivered; share-from-manager pending.
8. **First contributions** — settings, message action, toolbar action. Delivered.
9. **Appearance and screens** — `AppearanceTheme`, `AppearanceRuntime`, five screen
   keys, overlay, protected resolver, slots, `openScreen`, kill switch. Delivered;
   theme packages removed.
10. **Built-in migration** — NextGram settings and plugin manager entry. Plugin Manager
    and Community delivered; separate settings built-in is pending.
11. **Tooling** — Gradle plugin, sample plugins, CI. Sample and shell script delivered;
    Gradle plugin and TypeScript CLI pending.
12. **Script runtime** — QuickJS, TypeScript SDK/CLI, sample. Pending.
13. **Repository and updates** — `nextgram-plugins`, signed index, Repository screen,
    update checks, revocation. Delivered; the signing secret and first published index
    are pending, and custom repositories are deferred. See
    [distribution.md](/distribution/).
14. **Hardening** — fuzzing, performance, security review, release gates. Pending.

Each PR must keep the no-plugin path working and must not add plugin logic to upstream
files beyond a seam call.
