an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
release(v0.4.2): anonymous usage analytics, done in the open
Chaitanya Girie2e8873c094c
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex fdccf557..3a892dc7 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -49,6 +49,12 @@ jobs:- name: Compile (electron-vite → out/)run: npm run build+ env:+ # Anonymous product analytics (TELEMETRY.md). The PostHog project key+ # is public/write-only, but only official release builds inject it —+ # forks without the secret compile with '' and analytics no-ops.+ POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}+ POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}- name: Package installers# GH_TOKEN lets electron-builder skip its own publish; we upload via thediff --git a/CHANGELOG.md b/CHANGELOG.mdindex c51ea161..8caba0cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,31 @@ All notable changes to this project are documented here. The format is based on[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to[Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.4.2] — 2026-08-13++**Anonymous usage stats — documented, opt-out, and off in forks.**+The project previously had zero insight into whether anyone launches the app or which features+get used. This release adds a minimal, anonymous product-analytics layer (PostHog), governed by+a public contract: [TELEMETRY.md](TELEMETRY.md) lists every event and property, and the code+enforces that list as a hard allowlist.++### Added+- **Anonymous usage events** (`src/main/analytics.ts`): `first_run`, `app_launched`,+ `agent_spawned` (engine name only), `feature_used` (fixed enum, once per session), and+ `session_ended` (coarse duration bucket). Common properties are app version, OS, and CPU+ arch — nothing else. No prompts, transcripts, file paths, repo names, or identifiers of any+ kind; events are PostHog *anonymous events* (`$process_person_profile: false`), keyed by a+ random install UUID that lives in the app's user-data dir.+- **Consent surfaces**: a "Share anonymous usage stats" toggle on the final onboarding step and+ in Settings → General (`telemetryEnabled`, default on = opt-out). The standard `DO_NOT_TRACK`+ env var is respected unconditionally.+- **[TELEMETRY.md](TELEMETRY.md)** — the complete public contract, linked from the README.++### Note+The PostHog key is injected only in release CI (`POSTHOG_KEY` secret). **Building from source or+forking the repo produces a build with no key, and the entire analytics module is a no-op** — a+fork never sends events anywhere.+## [0.4.1] — 2026-08-13**The app says what the site says.**diff --git a/README.md b/README.mdindex 157deec2..8530db20 100644--- a/README.md+++ b/README.md@@ -62,6 +62,7 @@ visualized as avatars at work on a shared office floor.- [Design system](#design-system)- [Roadmap](#roadmap)- [Contributing](#contributing)+- [Telemetry](#telemetry)- [License](#license)- [Acknowledgements](#acknowledgements)@@ -303,6 +304,14 @@ Contributions are welcome — this is an early prototype with a lot of surface a`npm run typecheck` green, and **derive any new UI from [`DESIGN.md`](./DESIGN.md) tokens**. Goodfirst areas: wiring real hook events, the add-agent flow, the config drawer, and cross-platform work.+## Telemetry++Official builds send a **small set of anonymous usage events** (app opened, agent spawned, feature+used) — never prompts, code, file paths, or agent output. The complete event list, the anonymity+guarantees, and the three ways to opt out (Settings toggle, `DO_NOT_TRACK`, or building from+source — forks compile with no key and send nothing) are documented in+[`TELEMETRY.md`](./TELEMETRY.md).+## License> [!IMPORTANT]diff --git a/RELEASE.md b/RELEASE.mdindex 3ce48a44..8bb166b7 100644--- a/RELEASE.md+++ b/RELEASE.md@@ -1,4 +1,4 @@-# Munder Difflin v0.4.1+# Munder Difflin v0.4.2**A local hive of Claude Code, Antigravity, Codex, Grok & Copilot agents that run themselves** — messaging,routing, and remembering, coordinated by your clone, Michael, who you talk to. Local-first and open source.@@ -7,7 +7,25 @@ routing, and remembering, coordinated by your clone, Michael, who you talk to. L----## What's new in 0.4.1 — *The app says what the site says*+## What's new in 0.4.2 — *Anonymous usage stats, done in the open*++Munder Difflin now sends a **small set of anonymous usage events** (app opened, agent spawned,+feature used) so we can tell whether features are actually used. It is built the way an+open-source project should build it:++- **[TELEMETRY.md](https://github.com/chaitanyagiri/munder-difflin/blob/main/TELEMETRY.md) is the+ complete contract.** Every event and property is listed there, and the code enforces that list+ as a hard allowlist — anything not in the table cannot be sent. No prompts, no transcripts, no+ file paths, no repo names, no identifiers. Events are PostHog *anonymous events* (no person+ profile, no identity), keyed by a random UUID you can delete.+- **Opt-out, three ways.** Uncheck it during onboarding, flip **Settings → General → Anonymous+ usage stats**, or set the standard `DO_NOT_TRACK` env var.+- **Forks send nothing.** The analytics key is injected only in release CI — building from+ source produces a build where the analytics module is a complete no-op.++---++## Still new in 0.4.1 — *The app says what the site says***Michael is your clone.** The website has been describing Munder Difflin as a clone of you thatworks around the clock — the app still called it a "GOD agent." Now they match.@@ -27,43 +45,8 @@ works around the clock — the app still called it a "GOD agent." Now they match----## Still new in 0.4.0 — *The brand grew up*--**Munder Difflin looks like one product now.** The dock icon, the in-app logo, the site favicon,-and munderdiffl.in all carry the same yellow "MD" mark — and the landing page was rebuilt to show-the real app instead of describing it.--- **New app icon on every platform.** macOS gets a proper margined-and-shadowed `.icns`, Windows a- full-bleed `.ico`, Linux a 1024px `.png` — all cut from the same yellow tile as the in-app logo.-- **The landing page shows the product.** A looping screen recording in the hero, real screenshots- of the Add Agent dialog, the memory panel, and Autonomy & Budgets, and a live pixel-floor sim in- a yellow Pokédex shell.-- **Bright by default.** The site now opens in light mode; dark is one click away and remembered.-- **Pricing, reframed.** Two services carry the Teams story: **Private Cloud** (a dedicated- sandbox VM per clone, 24/7) and **Private Network** (E2E-encrypted clone-to-clone wire).-------## Still new in 0.3.9 — *Ask the app whether it's up to date*--**Settings → General now answers the question directly.** It names the version you're running,-tells you whether that's the latest, and gives you one button that says what pressing it does:-**Check for updates** → **Download v0.4.0** → **Restart to update**. The toolbar chip beside the-logo has always carried this, but it goes blank when everything is fine — which is not somewhere-you go to *ask*.--- **The avatars in the fullscreen roster are bigger.** They were drawn at 1× — an 18-pixel figure,- too small to tell two hires apart at a glance, which is the tile's whole job.--> [!IMPORTANT]-> **If you are on 0.3.8, update.** That build shipped a usage-limit guard that never let go: agents-> held behind a limit stayed held, the reset never landed, and **resume now** dropped them straight-> back into the hold. The guard is removed entirely — 0.3.9 delivers messages the way 0.3.7 did.------> [!NOTE]-> **Auto-update carries you here from v0.3.7 or v0.3.8.** If you are still on v0.3.5 or v0.3.6,+> **Auto-update carries you here from v0.3.7 or later.** If you are still on v0.3.5 or v0.3.6,> those builds shipped the broken updater and need one manual install — grab the download below,> once.@@ -71,6 +54,11 @@ you go to *ask*.## Previously+- **0.4.0** — *the brand grew up*: one yellow "MD" mark across the dock icon, in-app logo, site+ favicon, and munderdiffl.in; the landing page rebuilt around real screenshots and a live+ pixel-floor sim; pricing reframed around **Private Cloud** and **Private Network**.+- **0.3.9** — Settings → General answers "am I up to date?" directly, and removes 0.3.8's+ usage-limit guard that never released held agents.- **0.3.8** — memory condensation works for the first time; a Triggers hub; one compactionschedule instead of two; a readable commit history.- **0.3.7** — auto-update actually runs: a CommonJS/ESM import bug meant the native updater never@@ -100,22 +88,22 @@ Apple Silicon and Intel.### 🍎 macOS| Build | File ||---|---|-| Universal (Apple Silicon + Intel) | [`Munder-Difflin-0.4.1-mac-universal.dmg`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.1-mac-universal.dmg) |+| Universal (Apple Silicon + Intel) | [`Munder-Difflin-0.4.2-mac-universal.dmg`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.2-mac-universal.dmg) |### 🪟 Windows| Build | File ||---|---|-| Installer (x64) — *recommended* | [`Munder-Difflin-0.4.1-win-x64-setup.exe`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.1-win-x64-setup.exe) |-| Portable (x64, no install) | [`Munder-Difflin-0.4.1-win-x64-portable.exe`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.1-win-x64-portable.exe) |+| Installer (x64) — *recommended* | [`Munder-Difflin-0.4.2-win-x64-setup.exe`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.2-win-x64-setup.exe) |+| Portable (x64, no install) | [`Munder-Difflin-0.4.2-win-x64-portable.exe`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.2-win-x64-portable.exe) |### 🐧 Linux| Build | File ||---|---|-| AppImage (x86_64) | [`Munder-Difflin-0.4.1-linux-x86_64.AppImage`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.1-linux-x86_64.AppImage) |+| AppImage (x86_64) | [`Munder-Difflin-0.4.2-linux-x86_64.AppImage`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/Munder-Difflin-0.4.2-linux-x86_64.AppImage) |### 📦 Source-[Source code (zip)](https://github.com/chaitanyagiri/munder-difflin/archive/refs/tags/v0.4.1.zip) ·-[Source code (tar.gz)](https://github.com/chaitanyagiri/munder-difflin/archive/refs/tags/v0.4.1.tar.gz)+[Source code (zip)](https://github.com/chaitanyagiri/munder-difflin/archive/refs/tags/v0.4.2.zip) ·+[Source code (tar.gz)](https://github.com/chaitanyagiri/munder-difflin/archive/refs/tags/v0.4.2.tar.gz)> **Verify your download:** [`SHA256SUMS.txt`](https://github.com/chaitanyagiri/munder-difflin/releases/latest/download/SHA256SUMS.txt) — then `shasum -a 256 -c SHA256SUMS.txt` (macOS/Linux) or `Get-FileHash` (Windows).diff --git a/TELEMETRY.md b/TELEMETRY.mdnew file mode 100644index 00000000..ebcbd489--- /dev/null+++ b/TELEMETRY.md@@ -0,0 +1,65 @@+# Telemetry++Munder Difflin collects a small set of **anonymous** usage events so we can+understand adoption (how many people launch the app, which features get used)+and make the product better. This document is the complete, authoritative+contract: **if an event or property is not listed here, the app does not send+it.** The implementation lives in [`src/main/analytics.ts`](src/main/analytics.ts)+and enforces this list as a hard allowlist — the code and this file are kept in+lockstep, and because the repo is open source you can verify that yourself.++## What is sent++Every event carries only these common properties:++| Property | Example | Notes |+| --- | --- | --- |+| `app_version` | `0.4.2` | The app's own version |+| `os` | `darwin` / `win32` / `linux` | Platform, nothing more |+| `arch` | `arm64` / `x64` | CPU architecture |++The events:++| Event | Extra properties | When |+| --- | --- | --- |+| `first_run` | — | Once, the first time the app ever starts |+| `app_launched` | — | Each app start |+| `agent_spawned` | `provider` (CLI engine name, e.g. `claude`, `codex`) | An agent terminal is spawned |+| `feature_used` | `feature` — one of `slack_trigger`, `webhook_trigger`, `hire_install`, `voice_dictation` | At most once per feature per app session |+| `session_ended` | `duration_bucket` — one of `<5m`, `5-30m`, `30m-2h`, `2-8h`, `8h+` | On quit (coarse bucket, never raw duration) |++## What is never sent++No prompts. No agent transcripts or output. No file paths, repo names, branch+names, or hostnames. No email addresses, account identifiers, machine+identifiers, or API keys. Nothing free-form — the property allowlist in+`analytics.ts` drops anything not in the tables above.++## How it stays anonymous++- Events are sent to [PostHog](https://posthog.com) (itself open source) with+ `$process_person_profile: false`, which makes them **anonymous events**: no+ person profile is created and no identity is stored.+- The only identifier is a **random UUID** minted on first run and stored in+ the app's user-data directory (`telemetry-install-id`). It is not derived+ from your machine, and deleting the app's data deletes it.+- IP-based geolocation is used only to derive a country for aggregate stats;+ PostHog does not retain the IP on the event.++## Opting out++Any one of these fully disables telemetry:++1. **Settings → General → Anonymous usage stats → off** (or uncheck "Share+ anonymous usage stats" during onboarding). Takes effect immediately.+2. Set the standard [`DO_NOT_TRACK`](https://consoledonottrack.com)+ environment variable (any value other than `0`). Respected unconditionally.+3. **Build from source.** The PostHog key is injected only in official release+ CI; a local or forked build compiles without one and the analytics module+ is a no-op — forks never send events anywhere.++## Self-hosting note++PostHog is open source and self-hostable. Official builds point at PostHog+Cloud (US); the endpoint is a build-time setting (`POSTHOG_HOST`), so the+project can move to a self-hosted instance without any code change.diff --git a/blog/src/_includes/base.njk b/blog/src/_includes/base.njkindex c5c95dbf..9b4e51e3 100644--- a/blog/src/_includes/base.njk+++ b/blog/src/_includes/base.njk@@ -42,6 +42,29 @@<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet" /><link rel="stylesheet" href="{{ '/assets/blog.css' | u }}" />{% block head %}{% endblock %}+<script>+ // Anonymous blog analytics (PostHog) — same posture as the main site and the+ // app's TELEMETRY.md: public write-only token ('' = inert), anonymous-only+ // (person_profiles 'never'), no autocapture/recording, DNT respected.+ (function () {+ var PH_KEY = '';+ if (!PH_KEY || navigator.doNotTrack === '1') return;+ var s = document.createElement('script');+ s.async = true;+ s.src = 'https://us-assets.i.posthog.com/static/array.js';+ s.onload = function () {+ if (!window.posthog) return;+ window.posthog.init(PH_KEY, {+ api_host: 'https://us.i.posthog.com',+ person_profiles: 'never',+ autocapture: false,+ disable_session_recording: true,+ respect_dnt: true+ });+ };+ document.head.appendChild(s);+ })();+</script></head><body><a class="skip-link" href="#main">Skip to content</a>diff --git a/docs/index.html b/docs/index.htmlindex 97ee1b91..f2a30666 100644--- a/docs/index.html+++ b/docs/index.html@@ -33,7 +33,7 @@"url": "https://munderdiffl.in/","applicationCategory": "DeveloperApplication","operatingSystem": "macOS, Windows, Linux",- "softwareVersion": "0.4.1",+ "softwareVersion": "0.4.2","downloadUrl": "https://github.com/chaitanyagiri/munder-difflin/releases/latest","softwareHelp": "https://github.com/chaitanyagiri/munder-difflin#readme","license": "https://github.com/chaitanyagiri/munder-difflin/blob/main/LICENSE",@@ -2512,7 +2512,7 @@// download picker — pick macOS / Windows / Linux, click starts the download(function () {var REPO = 'chaitanyagiri/munder-difflin';- var REL = '0.4.1'; // fallback version; live links are resolved from the GitHub API below+ var REL = '0.4.2'; // fallback version; live links are resolved from the GitHub API belowvar BASE = 'https://github.com/' + REPO + '/releases/latest/download/';var PLATFORMS = [{ key: 'mac', icon: '🍎', os: 'macOS', sub: 'Universal · Apple Silicon + Intel', match: 'mac-universal.dmg', file: 'Munder-Difflin-' + REL + '-mac-universal.dmg' },@@ -2644,5 +2644,38 @@})();</script>+<script>+ // ── Anonymous site analytics (PostHog) ─────────────────────────────────────+ // PH_KEY is the PUBLIC write-only project token (safe to commit; it cannot+ // read data). '' keeps this entire block inert. Anonymous-only posture, same+ // contract as the app's TELEMETRY.md: person_profiles 'never' (no identity),+ // no autocapture, no session recording, DNT respected. Two events only:+ // $pageview and download_clicked (which file a visitor grabbed).+ (function () {+ var PH_KEY = '';+ if (!PH_KEY || navigator.doNotTrack === '1') return;+ var s = document.createElement('script');+ s.async = true;+ s.src = 'https://us-assets.i.posthog.com/static/array.js';+ s.onload = function () {+ if (!window.posthog) return;+ window.posthog.init(PH_KEY, {+ api_host: 'https://us.i.posthog.com',+ person_profiles: 'never',+ autocapture: false,+ disable_session_recording: true,+ respect_dnt: true+ });+ document.addEventListener('click', function (ev) {+ var a = ev.target && ev.target.closest ? ev.target.closest('a[data-download], a[download]') : null;+ if (!a) return;+ var href = a.getAttribute('href') || '';+ var file = href.split('/').pop() || 'releases-latest';+ window.posthog.capture('download_clicked', { file: file });+ }, true);+ };+ document.head.appendChild(s);+ })();+</script></body></html>diff --git a/electron.vite.config.ts b/electron.vite.config.tsindex e40f9734..91e28e32 100644--- a/electron.vite.config.ts+++ b/electron.vite.config.ts@@ -7,6 +7,17 @@ import { readFileSync, copyFileSync, mkdirSync, statSync } from 'node:fs';const pkg = JSON.parse(readFileSync(resolve(__dirname, 'package.json'), 'utf-8'));const define = { __APP_VERSION__: JSON.stringify(pkg.version) };+// Anonymous product analytics (src/main/analytics.ts, contract in TELEMETRY.md).+// The PostHog project key is a PUBLIC write-only token, but it is still injected+// at BUILD time from the environment (release CI sets it from a repo secret)+// rather than committed: local dev builds and forks compile with '' and the+// whole analytics module no-ops for them. Main-process only.+const defineMain = {+ ...define,+ __POSTHOG_KEY__: JSON.stringify(process.env.POSTHOG_KEY ?? ''),+ __POSTHOG_HOST__: JSON.stringify(process.env.POSTHOG_HOST ?? 'https://us.i.posthog.com')+};+// Copy raw .cjs main-process sidecars into out/main after the main bundle is// written. electron-vite/rollup neither bundles nor copies require()'d .cjs// sidecars, so without this the boot-time `require('./slack-trigger.cjs')` is@@ -41,7 +52,7 @@ function copyMainSidecars() {export default defineConfig({main: {plugins: [externalizeDepsPlugin(), copyMainSidecars()],- define,+ define: defineMain,build: {rollupOptions: {input: { index: resolve(__dirname, 'src/main/index.ts') }diff --git a/package-lock.json b/package-lock.jsonindex df1f7110..a94a0482 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "munder-difflin",- "version": "0.3.7",+ "version": "0.4.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "munder-difflin",- "version": "0.3.7",+ "version": "0.4.2","hasInstallScript": true,"dependencies": {"@codemirror/lang-css": "^6.3.1",@@ -34,6 +34,7 @@"monaco-editor": "^0.52.2","node-pty": "^1.0.0","pixi.js": "^8.5.1",+ "posthog-node": "^5.48.2","react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^10.1.0",@@ -2043,6 +2044,21 @@"node": ">=14"}},+ "node_modules/@posthog/core": {+ "version": "1.47.1",+ "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.47.1.tgz",+ "integrity": "sha512-d38C5DulL3gCox4g0VGyb/Lhn548fBvj9f35LZGVasPspOs3jyApxROJyDXoWwIRivOjCOIShZQAdYkZVn9J3w==",+ "license": "MIT",+ "dependencies": {+ "@posthog/types": "^1.403.0"+ }+ },+ "node_modules/@posthog/types": {+ "version": "1.403.0",+ "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.403.0.tgz",+ "integrity": "sha512-QbkO0epmdq38xhxwP214YRi0vgpZiXqhamaTjKT6kVGJYTtsE5qZ1GTgLp12IYehg/rd+whYYErH3/DeX8pj3Q==",+ "license": "MIT"+ },"node_modules/@rolldown/pluginutils": {"version": "1.0.0-beta.27","resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",@@ -9623,6 +9639,26 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/posthog-node": {+ "version": "5.48.2",+ "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.48.2.tgz",+ "integrity": "sha512-3Ni5upqpbUXL1QM2oU4sL9Y3OycDGgrKI9aJOGHbcF9xkPwR18cq481Tkvn6/CCPbl04p3tjdwQNkGHVveQcag==",+ "license": "MIT",+ "dependencies": {+ "@posthog/core": "^1.47.1"+ },+ "engines": {+ "node": "^20.20.0 || >=22.22.0"+ },+ "peerDependencies": {+ "rxjs": "^7.0.0"+ },+ "peerDependenciesMeta": {+ "rxjs": {+ "optional": true+ }+ }+ },"node_modules/prebuild-install": {"version": "7.1.3","resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",diff --git a/package.json b/package.jsonindex 7f64ed29..02d530c8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "munder-difflin",- "version": "0.4.1",+ "version": "0.4.2","private": true,"description": "Clones for you and your team, working 24/7 — a free, local-first multi-agent harness that turns the CLI coding agent you already run into a clone of you, coordinating an office of agents on your machine.","main": "out/main/index.js",@@ -52,6 +52,7 @@"monaco-editor": "^0.52.2","node-pty": "^1.0.0","pixi.js": "^8.5.1",+ "posthog-node": "^5.48.2","react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^10.1.0",diff --git a/src/main/analytics.ts b/src/main/analytics.tsnew file mode 100644index 00000000..6a49aa39--- /dev/null+++ b/src/main/analytics.ts@@ -0,0 +1,204 @@+/**+ * Product analytics (PostHog) — anonymous, allowlisted, opt-out.+ *+ * This is the OUTBOUND product-usage counterpart to telemetry.ts (which is the+ * loopback-only OTel collector and never leaves the machine). Everything here+ * is governed by TELEMETRY.md — the public contract. Keep the two in lockstep:+ * an event or property that isn't in TELEMETRY.md must not be added here, and+ * vice versa.+ *+ * 🔒 Anonymity is BY CONSTRUCTION, same philosophy as telemetry.ts:+ * - Every event carries `$process_person_profile: false` → PostHog stores it+ * as an anonymous event and never creates a person profile.+ * - The distinct id is a RANDOM UUID minted at first run and stored in+ * userData (`telemetry-install-id`) — not a machine id, not derivable from+ * anything, gone when the app's data dir is deleted.+ * - `track()` enforces a per-event property ALLOWLIST (EVENTS below), so a+ * future call site cannot leak a new property by accident: unknown events+ * and unknown keys are dropped, never sent.+ * - No prompts, transcripts, file paths, repo names, hostnames, or agent+ * output — nothing free-form crosses this seam.+ *+ * Sending is gated on ALL of (checked in this order):+ * 1. A build-time key (__POSTHOG_KEY__, injected from the POSTHOG_KEY env in+ * release CI). Dev builds and forks compile with '' → this whole module is+ * a silent no-op for them.+ * 2. The DO_NOT_TRACK env convention (any value except '' / '0') — respected+ * unconditionally, checked at every send so it can't be raced.+ * 3. The user's `telemetryEnabled` config (Settings → Privacy; default ON,+ * i.e. opt-out — flipped live via setEnabled()).+ *+ * Deliberately free of any `electron` import (paths/version are injected via+ * init) so it can be smoke-tested as a plain Node module, like telemetry.ts.+ */+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PostHog } from 'posthog-node';++// Injected by electron-vite `define` (electron.vite.config.ts) from the+// POSTHOG_KEY / POSTHOG_HOST env at BUILD time. Empty in dev/fork builds.+declare const __POSTHOG_KEY__: string;+declare const __POSTHOG_HOST__: string;++/** The complete event → allowed-property-keys contract. Mirrors TELEMETRY.md+ * exactly; `track()` refuses anything outside it. Common props (`app_version`,+ * `os`, `arch`) are stamped centrally and are not listed per event. */+const EVENTS: Record<string, ReadonlySet<string>> = {+ /** Once per install, when the install id is first minted. */+ first_run: new Set<string>(),+ /** Every app start. The DAU/retention backbone. */+ app_launched: new Set<string>(),+ /** An agent PTY spawned. `provider` is the CLI engine name only. */+ agent_spawned: new Set<string>(['provider']),+ /** Coarse feature adoption; `feature` is a fixed enum (see FEATURES), fired+ * at most once per feature per app session. */+ feature_used: new Set<string>(['feature']),+ /** Fired on quit. `duration_bucket` is a coarse label, never raw ms. */+ session_ended: new Set<string>(['duration_bucket'])+};++/** The only values `feature_used.feature` may take. */+export type AnalyticsFeature =+ | 'slack_trigger'+ | 'webhook_trigger'+ | 'hire_install'+ | 'voice_dictation';++export interface AnalyticsInitOptions {+ /** Directory for the install-id file (userData). Created if missing. */+ stateDir: string;+ /** App version stamped on every event. */+ appVersion: string;+ /** The user's `telemetryEnabled` config at boot (default true = opt-out). */+ enabled: boolean;+}++function dntSet(): boolean {+ const v = process.env.DO_NOT_TRACK;+ return v !== undefined && v !== '' && v !== '0';+}++class Analytics {+ private client: PostHog | null = null;+ private distinctId = '';+ private enabled = false;+ private firstRun = false;+ private startedAt = 0;+ private sessionEnded = false;+ /** Session-scoped dedup for feature_used. */+ private readonly featuresSeen = new Set<string>();+ private common: Record<string, string> = {};++ /** Boot the client (no-op without a build-time key / with DNT set). Returns+ * whether this boot minted a fresh install id (first run ever). */+ init(opts: AnalyticsInitOptions): void {+ this.enabled = opts.enabled;+ this.startedAt = Date.now();+ this.common = {+ app_version: opts.appVersion,+ os: process.platform,+ arch: process.arch+ };+ if (!__POSTHOG_KEY__ || dntSet()) return; // stay dark: no client, no id file+ try {+ this.distinctId = this.loadOrMintInstallId(opts.stateDir);+ this.client = new PostHog(__POSTHOG_KEY__, {+ host: __POSTHOG_HOST__ || 'https://us.i.posthog.com',+ // Events are rare (a handful per session) — send immediately so quit+ // loses at most the final session_ended, never a whole batch.+ flushAt: 1,+ flushInterval: 10_000,+ // posthog-node defaults GeoIP OFF (server lib); we re-enable it for+ // country-level numbers only — PostHog discards the IP after the+ // lookup and the event is anonymous either way (TELEMETRY.md).+ disableGeoip: false+ });+ } catch (e) {+ console.error('[analytics] init failed (telemetry disabled):', e);+ this.client = null;+ return;+ }+ if (this.firstRun) this.track('first_run');+ this.track('app_launched');+ }++ /** Live opt-in/out from Settings. Turning off stops sends instantly; nothing+ * needs recreating to turn back on. */+ setEnabled(on: boolean): void {+ this.enabled = on;+ }++ /** Capture one allowlisted event. Silently drops anything not in EVENTS. */+ track(event: string, props: Record<string, string> = {}): void {+ if (!this.client || !this.enabled || dntSet() || this.sessionEnded) return;+ const allowed = EVENTS[event];+ if (!allowed) return;+ const properties: Record<string, unknown> = {+ ...this.common,+ $process_person_profile: false // anonymous event — no person profile+ };+ for (const [k, v] of Object.entries(props)) {+ if (allowed.has(k) && typeof v === 'string') properties[k] = v;+ }+ try {+ this.client.capture({ distinctId: this.distinctId, event, properties });+ } catch (e) {+ console.error('[analytics] capture failed:', e);+ }+ }++ /** feature_used with per-session dedup (adoption signal, not a usage meter). */+ trackFeature(feature: AnalyticsFeature): void {+ if (this.featuresSeen.has(feature)) return;+ this.featuresSeen.add(feature);+ this.track('feature_used', { feature });+ }++ /** Fire session_ended and flush. Bounded by the caller (will-quit races this+ * against a timeout) — never assume it completes. Idempotent. */+ async endSession(): Promise<void> {+ if (!this.client || this.sessionEnded) return;+ this.track('session_ended', { duration_bucket: durationBucket(Date.now() - this.startedAt) });+ this.sessionEnded = true;+ try {+ await this.client.shutdown();+ } catch (e) {+ console.error('[analytics] shutdown flush failed:', e);+ }+ this.client = null;+ }++ private loadOrMintInstallId(stateDir: string): string {+ const file = join(stateDir, 'telemetry-install-id');+ try {+ if (existsSync(file)) {+ const id = readFileSync(file, 'utf8').trim();+ if (id) return id;+ }+ const id = randomUUID();+ mkdirSync(stateDir, { recursive: true });+ writeFileSync(file, id + '\n', 'utf8');+ this.firstRun = true;+ return id;+ } catch (e) {+ // Unwritable state dir: use an ephemeral id for this session rather than+ // failing closed on analytics (still anonymous, just not stable).+ console.error('[analytics] install-id persist failed (ephemeral id):', e);+ return randomUUID();+ }+ }+}++/** Coarse, non-identifying session-length label. */+function durationBucket(ms: number): string {+ const m = ms / 60_000;+ if (m < 5) return '<5m';+ if (m < 30) return '5-30m';+ if (m < 120) return '30m-2h';+ if (m < 480) return '2-8h';+ return '8h+';+}++/** The process-wide singleton, mirroring how index.ts owns other services. */+export const analytics = new Analytics();diff --git a/src/main/config.ts b/src/main/config.tsindex 835fc9cd..f2d5292b 100644--- a/src/main/config.ts+++ b/src/main/config.ts@@ -286,6 +286,11 @@ export interface HarnessConfig {* ("theme" key) at spawn so the TUI's truecolor palette matches. Scoped to* harness agents only; the user's global Claude theme is never touched. */terminalTheme?: 'light' | 'dark';+ /** Anonymous product analytics (PostHog) — the exact events/properties are+ * documented in TELEMETRY.md. Default ON (opt-out, like autoUpdate); builds+ * without an injected key and environments with DO_NOT_TRACK set never send+ * regardless of this flag. (Mirrored in preload + renderer config.) */+ telemetryEnabled?: boolean;/** Master flag for the TV-show office themes feature (Settings theme picker +* destructive switch flow). Default false = the picker is hidden and the* office renders as today (zero behavior change). */@@ -421,6 +426,7 @@ const DEFAULTS: HarnessConfig = {notifications: false,strongKeepalive: false,autoUpdate: true,+ telemetryEnabled: true,multiWindow: true,tvShowOffices: false,officeTheme: 'office',diff --git a/src/main/index.ts b/src/main/index.tsindex e8ab9a15..cb30da18 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -52,6 +52,7 @@ import { registerRealtimeActionIpc } from './realtimeActions';import { initCompletionWatcher } from './realtimeCompletionWatcher';import type { TaskCard, InboxMessage } from './realtimeCompletionWatcher';import { TelemetryCollector } from './telemetry';+import { analytics } from './analytics';import { IntegrationBroker } from './integrationBroker';import * as integrations from './integrations';import { validateBaseUrl, buildAuthHeaders, resolveUpstreamUrl, secretRefFor, INTEGRATION_TEMPLATES } from '../shared/integrations';@@ -1522,6 +1523,7 @@ async function startSlackServer(): Promise<{ ok: boolean; url?: string; error?:// Begin watching the kanban for Slack-origin tasks that reach 'done', to post// their one summary reply in-thread. OUTBOUND-only; never touches ingestion.startSlackDoneObserver();+ analytics.trackFeature('slack_trigger');return res;}@@ -1899,6 +1901,7 @@ async function startWebhookServer(): Promise<{ ok: boolean; url?: string; error?// "bound fine, tunnel unavailable" (the security boundary is live and must stay// reachable/stoppable — dropping it there would leak an unstoppable listener).if (!res.ok && !server.listening()) { webhookServer = null; return res; }+ analytics.trackFeature('webhook_trigger');if (res.url) lastWebhookUrl = res.url;startWebhookDoneObserver();return res;@@ -2018,6 +2021,7 @@ async function handleHireLink(link: string): Promise<void> {return;}deliverHire(res.manifest);+ analytics.trackFeature('hire_install');}// Register the protocol. In dev (electron .) Windows needs the explicit@@ -2705,6 +2709,7 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebContenawait enableCodexRemoteForSpawn(opts, opts.hive.id);}const res = ptyManager.spawn(opts, owner);+ if (res.ok) analytics.track('agent_spawned', { provider });syncKeepAwake(); // arm the power-save blocker while ≥1 agent PTY is alive (#18)// Hand the resolved worktree path back to the renderer so it can persist it on// the agent (only set when isolation actually provisioned a worktree above).@@ -2851,7 +2856,12 @@ ipcMain.handle('integrations:test', async (_evt, payload: unknown) => {// ─── IPC: config ────────────────────────────────────────────────────────────ipcMain.handle('config:get', (): HarnessConfig => readConfig());-ipcMain.handle('config:update', (_evt, patch: Partial<HarnessConfig>) => writeConfig(patch));+ipcMain.handle('config:update', (_evt, patch: Partial<HarnessConfig>) => {+ const next = writeConfig(patch);+ // Live opt-in/out from Settings → Privacy (TELEMETRY.md).+ if (typeof patch?.telemetryEnabled === 'boolean') analytics.setEnabled(patch.telemetryEnabled);+ return next;+});ipcMain.handle('config:ensureHome', (_evt, path: unknown) => {if (typeof path !== 'string' || path.length === 0) return { ok: false, error: 'invalid path' };return ensureHarnessHome(path);@@ -3811,7 +3821,7 @@ ipcMain.handle('freeflow:transcribe', async (_evt, arg: unknown) => {if (!(a.audio instanceof ArrayBuffer) && !(a.audio instanceof Uint8Array)) {return { ok: false, error: 'no audio' };}- return transcribeWithGroq({+ const out = await transcribeWithGroq({apiKey: cfg.groqApiKey,audio: a.audio,mimeType: typeof a.mimeType === 'string' ? a.mimeType : undefined,@@ -3819,6 +3829,8 @@ ipcMain.handle('freeflow:transcribe', async (_evt, arg: unknown) => {model: cfg.freeflowModel || DEFAULT_GROQ_MODEL,language: typeof a.language === 'string' && a.language ? a.language : undefined});+ if (out.ok) analytics.trackFeature('voice_dictation');+ return out;});// ─── IPC: Realtime Michael (voice orchestrator — ephemeral token mint, rt-1) ──@@ -4515,6 +4527,15 @@ app.whenReady().then(() => {// setMicGate(true)); macOS TCC stays a second gate regardless.if (readConfig().realtimeVoiceEnabled) writeConfig({ realtimeVoiceEnabled: false });+ // Anonymous product analytics (PostHog) — the full contract lives in+ // TELEMETRY.md. No-op unless a build-time key was injected (official releases+ // only), and gated on DO_NOT_TRACK + the telemetryEnabled config (opt-out).+ analytics.init({+ stateDir: app.getPath('userData'),+ appVersion: app.getVersion(),+ enabled: readConfig().telemetryEnabled !== false+ });+// A cold-start deep link (Windows/Linux) rides in on OUR argv.const startupHireLink = process.argv.find((a) => a.startsWith('munderdifflin://'));if (startupHireLink) void handleHireLink(startupHireLink);@@ -4591,3 +4612,18 @@ app.on('window-all-closed', () => {app.quit();}});++// Final analytics flush (session_ended + drain the send queue), bounded so a+// hung network can never wedge quit: preventDefault ONCE, race the flush+// against a short timeout, then re-enter quit with the latch set.+let analyticsFlushed = false;+app.on('will-quit', (e) => {+ if (analyticsFlushed) return;+ analyticsFlushed = true;+ e.preventDefault();+ const finish = (): void => app.quit();+ Promise.race([+ analytics.endSession(),+ new Promise<void>((r) => setTimeout(r, 1200))+ ]).then(finish, finish);+});diff --git a/src/preload/index.ts b/src/preload/index.tsindex d1b60db7..a04efc67 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -276,6 +276,9 @@ export interface HarnessConfig {strongKeepalive?: boolean;/** Auto-update from GitHub releases (default ON; Settings → General). */autoUpdate?: boolean;+ /** Anonymous product analytics (default ON, opt-out; see TELEMETRY.md).+ * Mirrors main + renderer HarnessConfig. */+ telemetryEnabled?: boolean;slackEnabled?: boolean;slackSigningSecret?: string;slackBotToken?: string;diff --git a/src/renderer/src/components/OnboardingWizard.tsx b/src/renderer/src/components/OnboardingWizard.tsxindex 00ae6dc0..c592e9cb 100644--- a/src/renderer/src/components/OnboardingWizard.tsx+++ b/src/renderer/src/components/OnboardingWizard.tsx@@ -89,6 +89,9 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {const [home, setHome] = useState<string>('');const [repos, setRepos] = useState<string[]>([]);const [autoMode, setAutoMode] = useState<boolean>(true);+ // Anonymous usage stats (TELEMETRY.md). Default ON (opt-out); persisted by+ // finish() so unchecking before finishing means nothing is ever sent.+ const [shareStats, setShareStats] = useState<boolean>(true);const [godProvider, setGodProvider] = useState<AgentProvider>('claude');const [godModel, setGodModel] = useState<string | undefined>(providerPreset('claude').recommendedOrchestratorModel@@ -165,7 +168,8 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {registeredRepos: repos,autoMode,godProvider,- godModel+ godModel,+ telemetryEnabled: shareStats});setBusy(false);onComplete(next);@@ -593,6 +597,16 @@ export function OnboardingWizard({ onComplete }: OnboardingWizardProps) {onChange={toggleOpenAtLogin}/>+ <ToggleRow+ icon="info"+ label="SHARE ANONYMOUS USAGE STATS"+ desc="A handful of anonymous events (app opened, agent spawned, feature used) that help improve Munder Difflin — never prompts, code, file paths, or agent output. Full list in TELEMETRY.md; change anytime in Settings."+ on={shareStats}+ tint="var(--cth-lemon-light)"+ edge="var(--cth-lemon)"+ onChange={() => setShareStats(!shareStats)}+ />+{/* LEVER 4 — instruction-only: macOS won't let the app flip Energy, so we deep-link the pane. */}<div style={{display: 'flex', gap: 10, alignItems: 'flex-start', padding: 10,diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsxindex 86104808..4973fd73 100644--- a/src/renderer/src/components/SettingsModal.tsx+++ b/src/renderer/src/components/SettingsModal.tsx@@ -380,6 +380,15 @@ export function SettingsModal({ config, onClose, initialSection }: SettingsModalcatch { setAutoUpdateOn(!next); }};+ // ─── Anonymous usage stats (default ON = opt-out; contract in TELEMETRY.md) ─+ const [telemetryOn, setTelemetryOn] = useState<boolean>(config.telemetryEnabled !== false);+ const toggleTelemetry = async () => {+ const next = !telemetryOn;+ setTelemetryOn(next);+ try { await window.cth.updateConfig({ telemetryEnabled: next }); }+ catch { setTelemetryOn(!next); }+ };+// --- Free Flow (voice dictation → message queue) ---const setFreeflowEnabledStore = useStore((s) => s.setFreeflowEnabled);const setHasGroqKeyStore = useStore((s) => s.setHasGroqKey);@@ -996,6 +1005,25 @@ export function SettingsModal({ config, onClose, initialSection }: SettingsModal{autoUpdateOn ? 'on' : 'off'}</PixelButton></div>+ <div style={{ height: 10 }} />+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <span style={{ fontSize: 13, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>+ Anonymous usage stats+ </span>+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>+ A handful of anonymous events (app opened, agent spawned, feature used) —+ never prompts, code, paths, or agent output. Full list in TELEMETRY.md.+ </span>+ </div>+ <PixelButton+ variant={telemetryOn ? 'primary' : 'secondary'}+ size="sm"+ onClick={toggleTelemetry}+ >+ {telemetryOn ? 'on' : 'off'}+ </PixelButton>+ </div></div>{/* Office Theme — TV-show office maps (experimental; flag tvShowOffices, default off) */}diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.tsindex fbc5f138..abe1a75b 100644--- a/src/renderer/src/store/config.ts+++ b/src/renderer/src/store/config.ts@@ -85,6 +85,9 @@ export interface HarnessConfig {strongKeepalive?: boolean;/** Auto-update from GitHub releases (default ON; Settings → General). */autoUpdate?: boolean;+ /** Anonymous product analytics (default ON, opt-out; see TELEMETRY.md).+ * Mirrors the main-process field (src/main/config.ts). */+ telemetryEnabled?: boolean;slackEnabled?: boolean;slackSigningSecret?: string;slackBotToken?: string;