The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(tracking): enforce release policy and preserve opt-out controls
罗高56134f3cb750
diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.mdindex dc5b549e..a295d5d4 100644--- a/docs/mcp-phase1-tools.md+++ b/docs/mcp-phase1-tools.md@@ -110,7 +110,7 @@ action=record_review 要求 projectId/requestId/jobId/review;只能对本项### Phase-one API compatibility-`shared/phase1-tools.ts` defines API protocol 1 and the available Tool names. Both editor and preview health advertise these capabilities. A phase-one stdio adapter can forward to another version/build only when the backend explicitly supports the same API protocol and requested Tool; the backend validates the complete input again before execution. Service, workspace, instance and authority protocol checks still apply. Internal legacy calls retain exact version/build checks.+`shared/phase1-tools.ts` defines API protocol 1 and the available Tool names. Both editor and preview health advertise these capabilities. A phase-one stdio adapter can forward to another version/build only when the backend explicitly supports the same API protocol and requested Tool and has the same stable/test tracking policy; the backend validates the complete input again before execution. Stable and test clients use separate data directories; cross-policy authority reuse is rejected without stopping the existing service. Service, workspace, instance and authority protocol checks still apply. Internal legacy calls retain exact version/build checks.Protocol 1 preserves existing request/response shapes and semantics. New Tools and optional fields are additive; incompatible required fields, removed fields or changed semantics must increment the protocol. A supported older connection keeps its project binding, stable request IDs and existing export queries through a compatible plugin or backend replacement without another MCP initialization. Running exports stay with the live authority; recovery does not terminate it or replay an uncertain mutation. An already-closed host transport and an incompatible protocol cannot be repaired by this negotiation.diff --git a/docs/npm-installation.md b/docs/npm-installation.mdindex dfa76131..eebf1721 100644--- a/docs/npm-installation.md+++ b/docs/npm-installation.md@@ -6,6 +6,8 @@ The npm tgz contains the installer, a prebuilt Motion application archive and itSource `package.json` is the development baseline; the published artifact can have a different version. For example, source `0.6.3` can produce `0.6.4-test.6` without a stable `0.6.4` release. Packaging changes output identities only. Manual [candidate builds](release-workflows.md#1-build) accept an empty version and automatically generate the next patch plus a short `test.N` workflow counter (with an attempt suffix on reruns); publication keeps the exact accepted version.+Test/prerelease/local packages never report usage data, even with a saved opt-in or an enable flag. Stable releases collect by default and support persistent opt-out and re-enable in Studio Privacy settings. See [tracking controls](../tracking/README.md#reporting-and-user-control).+## Requirements and package contentsUsers provide Node.js 22.18+ with npm and their Agent host. Builds use the Node version pinned in CI. npm installs locked production dependencies with `npm ci --omit=dev --ignore-scripts`. Setup starts FFmpeg, ffprobe and browser preparation in a detached background worker. MCP connection, source editing and ordinary preview do not wait; Studio displays readiness and retry. `prepare` remains an explicit wait/retry command. Node, native binaries, node_modules, user projects and credentials are not bundled in this npm format. It is not an offline package. Complete platform ZIPs remain a backup.diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex fb5a1449..43c0edf2 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -147,7 +147,7 @@ README 参考 OpenDesign 的产品导览和 HTML Anything 的贡献、来源表1. **两类入口共用领域能力。** Studio 与 MCP 使用同一 Gateway 合约和持久化数据。macOS 的 stdio 适配器按数据目录连接唯一后台,共用网关、任务与工程能力;每条连接绑定自己的工程。Windows / Linux 保留原生命周期。唯一后台依赖系统文件锁与私有身份验证,不以固定端口或 PID 文件作为唯一依据,见 [共享编辑器](../shared-editor.md)。- Public phase-one MCP calls negotiate a stable API protocol and supported Tool independently of the editor version/build. Compatible plugin updates preserve existing stdio connections, workspace/project bindings and active exports; they do not restart the authority or replay mutations. Private authority identity and protocol checks remain strict, and internal legacy calls retain exact version/build checks. This boundary does not refresh host discovery metadata or revive a transport the host already closed; see [API compatibility](../mcp-phase1-tools.md#phase-one-api-compatibility).+ Public phase-one MCP calls negotiate a stable API protocol and supported Tool independently of the editor version/build. Compatible plugin updates within the same stable/test collection policy preserve existing stdio connections, workspace/project bindings and active exports; they do not restart the authority or replay mutations. Private authority identity and protocol checks remain strict, and internal legacy calls retain exact version/build checks. This boundary does not refresh host discovery metadata or revive a transport the host already closed; see [API compatibility](../mcp-phase1-tools.md#phase-one-api-compatibility).2. **作品与执行配置分开。** 原生工程包含作品源文件与媒体;供应商凭据、模型默认路由和生成任务属于工作区。项目包可以交给别人继续编辑,使用者无需继承原作者的 Key。3. **素材成功不自动成为编辑成功。** 生成任务产生候选文件,采用结果才触发原生放置/替换。撤销作品修改不删除候选文件,也不撤销已经发生的供应商调用或费用。4. **上下文不能随等待漂移。** 提交时固定生成工程和参考输入,采用时验证编辑目标;切换工程、合成、删除或改换原素材引用后,旧回调不得覆盖新目标。@@ -244,7 +244,7 @@ flowchart LR当前交付标准:连接可验证、模板可定位、工程可继续编辑、预览与源文件一致、导出存在真实文件、检查结果有证据。相关实现由 `tests/`、`npm run test:studio` 的原生单元/DOM 与宿主回归、类型检查、设计检查和按需浏览器验证覆盖;没有执行的检查不能记为通过。-The runtime includes a default-on, explicit-event tracking package shared by MCP and Studio. A persistent user preference and environment overrides can disable collection for the whole installation. Studio submits allowlisted events to the local service; Node adds a random installation identity before asynchronous ingestion into the existing OpenDesign PostHog project. OM events carry product=openmotion; queries must distinguish products. An OM-only transformation preserves coarse country/region/timezone and removes raw IP and precise location after the existing GeoIP transformation, without changing other OpenDesign events or global project settings. The implementation covers tool results, selected domain operations and selected Studio interactions; it does not establish a product analytics baseline or implement every proposed event. See [tracking configuration, privacy and coverage](../../tracking/README.md).+The runtime includes an explicit-event tracking package shared by MCP and Studio. Stable releases collect by default; test/prerelease/local application versions are locked off regardless of the saved preference or launch overrides. The test-build Privacy switch explains the lock without overwriting the saved stable-release choice. Shared-backend discovery rejects test/stable cross-policy reuse rather than allowing a reporting authority to execute test actions. In stable releases, a persistent user preference can stop collection for the whole installation and resume new reports when enabled again; discarded events are not replayed. Environment force-off controls still take priority. Studio submits allowlisted events to the local service; Node adds a random installation identity before asynchronous ingestion into the existing OpenDesign PostHog project. OM events carry product=openmotion; queries must distinguish products. An OM-only transformation preserves coarse country/region/timezone and removes raw IP and precise location after the existing GeoIP transformation, without changing other OpenDesign events or global project settings. The implementation covers tool results, selected domain operations and selected Studio interactions; it does not establish a product analytics baseline or implement every proposed event. See [tracking configuration, privacy and coverage](../../tracking/README.md).The following product measures still require agreed observation windows and validated evidence:diff --git a/docs/shared-editor.md b/docs/shared-editor.mdindex 1a7f8ddb..c67a6255 100644--- a/docs/shared-editor.md+++ b/docs/shared-editor.md@@ -37,14 +37,14 @@ flowchart LR| 显式打开预览 | 按需启动或复用原生 Studio;返回已有完整/嵌入链接契约 || 全部 MCP 会话退出 | 后台继续服务网页与导出;不会因某个 Agent 退出取消其他人的工作 || 用户停止后台 | 私有停止接口拒绝正在执行的 MCP、视频导出或素材任务;空闲时关闭子服务并退出 |-| Compatible plugin/backend version or build change | Existing phase-one connections continue through the same workspace authority when it advertises the same MCP API protocol and requested Tool; keep running exports and request IDs intact. |-| Incompatible authority/API protocol, missing Tool or legacy version/build mismatch | Refuse before dispatch with expected/actual identity. Never automatically kill or launch a competing backend. |+| Compatible plugin/backend version or build change | Existing phase-one connections continue through the same workspace authority when it advertises the same MCP API protocol, requested Tool and stable/test tracking policy; keep running exports and request IDs intact. |+| Incompatible authority/API protocol, missing Tool, stable/test policy mismatch or legacy version/build mismatch | Refuse before dispatch with expected/actual identity. Never automatically kill or launch a competing backend. || A live MCP client's plugin directory was replaced or removed | Phase-one calls keep their stdio connection and reuse a compatible live backend. Internal legacy connections return `MCP_RUNTIME_RELOAD_REQUIRED`. A transport already closed by the host cannot be revived by the plugin. || 同目录已有旧版预览服务 | 拒绝另外启动共享后台;退出旧服务后重试 |macOS 使用系统 `/usr/bin/perl` 取得 `flock` 后直接 exec Node;Perl 不常驻。锁描述符同时由后台和 Studio 守卫持有。后台死亡后,守卫先清理旧 Studio,再释放锁,新后台才能启动。锁文件保留不等于锁仍被占用;不通过删除锁文件来恢复。-Phase-one compatibility is independent of the editor's implementation build. Authenticated private health and public preview health advertise `mcp.protocol` and `mcp.tools`; forwarding retains service, workspace, instance and authority-protocol validation. Compatible updates reuse the current authority without restarting it or replaying mutations. If an idle authority is separately replaced, the next call discovers or starts the same workspace's compatible replacement using the existing stdio connection. This does not hot-reload the UI, refresh host Tool metadata or automatically install updates. See the [API compatibility contract](mcp-phase1-tools.md#phase-one-api-compatibility).+Phase-one compatibility is independent of the editor's implementation build within the same stable/test tracking policy. Authenticated private health and public preview health advertise `mcp.protocol` and `mcp.tools`; forwarding retains service, workspace, instance and authority-protocol validation. Compatible updates reuse the current authority without restarting it or replaying mutations. If an idle authority is separately replaced, the next call discovers or starts the same workspace's compatible replacement using the existing stdio connection. This does not hot-reload the UI, refresh host Tool metadata or automatically install updates. See the [API compatibility contract](mcp-phase1-tools.md#phase-one-api-compatibility).显式停止(必须指定同一个数据目录):diff --git a/editor-runtime.ts b/editor-runtime.tsindex 0c18dd8c..2a20473e 100644--- a/editor-runtime.ts+++ b/editor-runtime.ts@@ -8,6 +8,7 @@ import { WorkspaceStore, Conflict } from './workspace.ts';import { isMain } from './shared/entry.ts';import { templateConfig } from './shared/template-config.ts';import { phase1McpCapabilities, supportsPhase1Tool } from './shared/phase1-tools.ts';+import { trackingReleaseEnabled } from './tracking/node.ts';export const sharedEditorEnabled = process.platform === 'darwin';const root = fileURLToPath(new URL('./', import.meta.url));@@ -54,7 +55,9 @@ export async function ensureEditor(directory: string, mcpTool?: string): Promisetry {const health = await editorRequest(registry, '/editor-api/health', undefined, 1200);if (health.service !== service || health.dataDirectory !== data || health.instanceId !== registry.instanceId) throw Object.assign(new Error('编辑器实例身份不匹配'), { terminal: true });- const compatible = mcpTool ? supportsPhase1Tool(health, mcpTool) : health.version === version && health.build === editorBuild;+ // Test clients must not execute through a stable authority that can report their actions.+ const sameReleasePolicy = trackingReleaseEnabled(health.version) === trackingReleaseEnabled(version);+ const compatible = sameReleasePolicy && (mcpTool ? supportsPhase1Tool(health, mcpTool) : health.version === version && health.build === editorBuild);if (health.protocol !== protocol || !compatible) throw Object.assign(new Error('Editor runtime incompatible. Reconnect the Motion MCP connection to the installed runtime and compare the expected and actual versions/builds. Stop an older editor only after confirming it is idle; do not bypass MCP or switch workspaces to continue.'),{ terminal: true, code: 'EDITOR_RUNTIME_INCOMPATIBLE', details: {diff --git a/preview.ts b/preview.tsindex 1003c222..d85adb43 100644--- a/preview.ts+++ b/preview.ts@@ -6,6 +6,7 @@ import { readFileSync } from 'node:fs';import { WorkspaceStore } from './workspace.ts';import { ensureEditor, editorRequest, readEditor, sharedEditorEnabled } from './editor-runtime.ts';import { supportsPhase1Tool } from './shared/phase1-tools.ts';+import { trackingReleaseEnabled } from './tracking/node.ts';const pluginRoot = fileURLToPath(new URL('./', import.meta.url));export const VERSION: string = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;@@ -118,6 +119,7 @@ export async function openPreview(store = new WorkspaceStore(), environment: Preconst candidates = [...new Set([...(previous ? [previous] : []), ...Array.from({ length: 10 }, (_, i) => firstPort + i)])];let available: number | null = null;const matches = (result: Probe) => result.kind === 'motion' && result.health.service === 'motion-preview' && result.health.protocol === 2 && result.health.ready+ && trackingReleaseEnabled(result.health.version) === trackingReleaseEnabled(VERSION)&& (options.mcpTool ? supportsPhase1Tool(result.health, options.mcpTool) : result.health.version === VERSION) && path.resolve(result.health.dataDirectory) === store.directory;async function ready(port: number, health: Health, reused: boolean, pid?: number) {if (options.editor && !health.studioUrl) {diff --git a/server.ts b/server.tsindex a517d5d7..2cec9c14 100644--- a/server.ts+++ b/server.ts@@ -25,7 +25,7 @@ import { Phase1Service } from './phase1.ts';import { phase1McpCapabilities } from './shared/phase1-tools.ts';import { recoverProjectTransactions } from './phase1-versions.ts';import { verifyExport } from './scripts/verify-export.ts';-import { createAppTracking, closeTracking, saveTrackingPreference, trackingPreference, trackingLocked, type OmTracking } from './shared/tracking.ts';+import { createAppTracking, closeTracking, saveTrackingPreference, trackingPreference, trackingLockReason, type OmTracking } from './shared/tracking.ts';import { studioEvents } from './tracking/events.ts';import { nativeRuntimeStatus, startNativePreparation, requireNativeRuntime } from './scripts/npm-runtime.mjs';import { nativeRouteCapability } from './shared/native-runtime.ts';@@ -266,12 +266,14 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =if (motionRequest && url.pathname === '/api/tracking/preferences' && ['GET', 'PUT'].includes(req.method!)) {const directory = (store.workspaceStore ?? store).directory;if (req.method === 'PUT') {- if (trackingLocked()) return json(res, 403, { error: 'TRACKING_DISABLED_BY_ENVIRONMENT' });+ const reason = trackingLockReason();+ if (reason) return json(res, 403, { error: reason === 'test_build' ? 'TRACKING_DISABLED_IN_TEST_BUILD' : 'TRACKING_DISABLED_BY_ENVIRONMENT' });const data = await input(req, 1024);if (!data || Object.keys(data).length !== 1 || typeof data.enabled !== 'boolean') return json(res, 400, { error: 'INVALID_TRACKING_PREFERENCE' });await saveTrackingPreference(directory, data.enabled);}- return json(res, 200, { enabled: context.tracking?.enabled() ?? false, preference: trackingPreference(directory), locked: trackingLocked() });+ const reason = trackingLockReason();+ return json(res, 200, { enabled: context.tracking?.enabled() ?? false, preference: trackingPreference(directory), locked: reason !== null, reason });}if (motionRequest && url.pathname === '/api/tracking' && req.method === 'GET') return json(res, 200, { enabled: context.tracking?.enabled() ?? false });if (motionRequest && url.pathname === '/api/tracking' && req.method === 'POST') {diff --git a/shared/tracking.ts b/shared/tracking.tsindex 9c173d90..0d23cee5 100644--- a/shared/tracking.ts+++ b/shared/tracking.ts@@ -3,14 +3,17 @@ import { readFileSync, watch } from 'node:fs';import { mkdir, rename, rm, writeFile } from 'node:fs/promises';import { createTracker, uuid } from '../tracking/core.ts';import type { Entry } from '../tracking/core.ts';-import { createNodeTracking, loadIdentity } from '../tracking/node.ts';+import { createNodeTracking, loadIdentity, trackingReleaseEnabled } from '../tracking/node.ts';import { omEvents } from '../tracking/events.ts';import { VERSION } from '../preview.ts';export type OmTracking = ReturnType<typeof createTracker<typeof omEvents>>;-export function trackingLocked() {- return ['0', 'false', 'off'].includes(process.env.OPENMOTION_TELEMETRY?.toLowerCase() ?? '') || process.env.DO_NOT_TRACK === '1';+export function trackingLockReason() {+ if (!trackingReleaseEnabled(VERSION)) return 'test_build' as const;+ return ['0', 'false', 'off'].includes(process.env.OPENMOTION_TELEMETRY?.toLowerCase() ?? '') || process.env.DO_NOT_TRACK === '1'+ ? 'environment' as const : null;}+export function trackingLocked() { return trackingLockReason() !== null; }export function trackingPreference(directory: string): boolean {try { return JSON.parse(readFileSync(path.join(directory, 'tracking/preferences.json'), 'utf8')).enabled === true; }catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT'; }@@ -25,7 +28,7 @@ export async function saveTrackingPreference(directory: string, enabled: boolean}export async function createAppTracking(directory: string, entrypoint: Entry): Promise<OmTracking> {- const disabled = () => createTracker({ registry: omEvents, entrypoint, enabled: false, send: async () => 'drop' });+ const disabled = () => createTracker({ registry: omEvents, entrypoint, enabled: false, isEnabled: () => false, send: async () => 'drop' });if (trackingLocked()) return disabled();try {const testing = Boolean(process.env.NODE_TEST_CONTEXT) || process.env.NODE_ENV === 'test';diff --git a/studio/src/i18n/de.json b/studio/src/i18n/de.jsonindex 0fb9e11c..632b93d5 100644--- a/studio/src/i18n/de.json+++ b/studio/src/i18n/de.json@@ -1758,6 +1758,7 @@"Share usage data": "Nutzungsdaten teilen","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Funktionsnutzung, Fehlerkategorien und ungefähre Region zur Verbesserung von OpenMotion senden. Prompts und Projektinhalte sind ausgeschlossen.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Diese Einstellung gilt für MCP und Studio dieser Installation und bleibt nach einem Neustart erhalten.",+ "Usage data collection is disabled in test builds.": "In Testversionen werden keine Nutzungsdaten erfasst.","Disabled by your environment settings.": "Durch Ihre Umgebungseinstellungen deaktiviert.","Could not load privacy settings.": "Datenschutzeinstellungen konnten nicht geladen werden.","Could not save privacy settings.": "Datenschutzeinstellungen konnten nicht gespeichert werden.",diff --git a/studio/src/i18n/es.json b/studio/src/i18n/es.jsonindex 534a90df..88ffba7f 100644--- a/studio/src/i18n/es.json+++ b/studio/src/i18n/es.json@@ -1758,6 +1758,7 @@"Share usage data": "Compartir datos de uso","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Enviar el uso de funciones, categorías de errores y región aproximada para mejorar OpenMotion. Se excluyen los prompts y el contenido de los proyectos.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Este ajuste se aplica a MCP y Studio de esta instalación y se conserva tras reiniciar.",+ "Usage data collection is disabled in test builds.": "La recopilación de datos de uso está desactivada en las versiones de prueba.","Disabled by your environment settings.": "Desactivado por la configuración del entorno.","Could not load privacy settings.": "No se pudo cargar la configuración de privacidad.","Could not save privacy settings.": "No se pudo guardar la configuración de privacidad.",diff --git a/studio/src/i18n/fr.json b/studio/src/i18n/fr.jsonindex cab8cb95..9de635c0 100644--- a/studio/src/i18n/fr.json+++ b/studio/src/i18n/fr.json@@ -1758,6 +1758,7 @@"Share usage data": "Partager les données d’utilisation","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Envoyer l’utilisation des fonctions, les catégories d’erreurs et la région approximative pour améliorer OpenMotion. Les prompts et le contenu des projets sont exclus.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Ce réglage s’applique à MCP et Studio pour cette installation et reste enregistré après un redémarrage.",+ "Usage data collection is disabled in test builds.": "La collecte des données d’utilisation est désactivée dans les versions de test.","Disabled by your environment settings.": "Désactivé par vos paramètres d’environnement.","Could not load privacy settings.": "Impossible de charger les paramètres de confidentialité.","Could not save privacy settings.": "Impossible d’enregistrer les paramètres de confidentialité.",diff --git a/studio/src/i18n/it.json b/studio/src/i18n/it.jsonindex 97e70383..1cee8ff0 100644--- a/studio/src/i18n/it.json+++ b/studio/src/i18n/it.json@@ -1758,6 +1758,7 @@"Share usage data": "Condividi dati di utilizzo","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Invia l’utilizzo delle funzioni, le categorie di errore e la regione approssimativa per migliorare OpenMotion. I prompt e i contenuti dei progetti sono esclusi.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Questa impostazione si applica a MCP e Studio di questa installazione e viene mantenuta dopo il riavvio.",+ "Usage data collection is disabled in test builds.": "La raccolta dei dati di utilizzo è disattivata nelle versioni di prova.","Disabled by your environment settings.": "Disattivato dalle impostazioni dell’ambiente.","Could not load privacy settings.": "Impossibile caricare le impostazioni privacy.","Could not save privacy settings.": "Impossibile salvare le impostazioni privacy.",diff --git a/studio/src/i18n/ja.json b/studio/src/i18n/ja.jsonindex 3f4dff90..11d3651f 100644--- a/studio/src/i18n/ja.json+++ b/studio/src/i18n/ja.json@@ -1722,6 +1722,7 @@"Share usage data": "利用データを共有","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion の改善のため、機能の利用状況、エラーの種類、おおよその地域を送信します。プロンプトやプロジェクト内容は送信しません。","This setting applies to MCP and Studio on this installation and is kept after restart.": "この設定は同じインストールの MCP と Studio に適用され、再起動後も保持されます。",+ "Usage data collection is disabled in test builds.": "テスト版では利用データの収集が無効になっています。","Disabled by your environment settings.": "環境設定により無効になっています。","Could not load privacy settings.": "プライバシー設定を読み込めませんでした。","Could not save privacy settings.": "プライバシー設定を保存できませんでした。",diff --git a/studio/src/i18n/ko.json b/studio/src/i18n/ko.jsonindex 31274649..c2bf1426 100644--- a/studio/src/i18n/ko.json+++ b/studio/src/i18n/ko.json@@ -1722,6 +1722,7 @@"Share usage data": "사용 데이터 공유","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion 개선을 위해 기능 사용 현황, 오류 유형, 대략적인 지역을 전송합니다. 프롬프트와 프로젝트 내용은 제외됩니다.","This setting applies to MCP and Studio on this installation and is kept after restart.": "이 설정은 이 설치의 MCP와 Studio에 적용되며 다시 시작해도 유지됩니다.",+ "Usage data collection is disabled in test builds.": "테스트 버전에서는 사용 데이터를 수집하지 않습니다.","Disabled by your environment settings.": "환경 설정으로 비활성화되었습니다.","Could not load privacy settings.": "개인정보 설정을 불러오지 못했습니다.","Could not save privacy settings.": "개인정보 설정을 저장하지 못했습니다.",diff --git a/studio/src/i18n/pt-BR.json b/studio/src/i18n/pt-BR.jsonindex ad5cb397..59b36f65 100644--- a/studio/src/i18n/pt-BR.json+++ b/studio/src/i18n/pt-BR.json@@ -1758,6 +1758,7 @@"Share usage data": "Compartilhar dados de uso","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Enviar uso de recursos, categorias de erros e região aproximada para melhorar o OpenMotion. Prompts e conteúdo dos projetos são excluídos.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Esta configuração se aplica ao MCP e ao Studio desta instalação e é mantida após reiniciar.",+ "Usage data collection is disabled in test builds.": "A coleta de dados de uso está desativada nas versões de teste.","Disabled by your environment settings.": "Desativado pelas configurações do ambiente.","Could not load privacy settings.": "Não foi possível carregar as configurações de privacidade.","Could not save privacy settings.": "Não foi possível salvar as configurações de privacidade.",diff --git a/studio/src/i18n/ru.json b/studio/src/i18n/ru.jsonindex dbb6bd03..0f836ff3 100644--- a/studio/src/i18n/ru.json+++ b/studio/src/i18n/ru.json@@ -1782,6 +1782,7 @@"Share usage data": "Делиться данными об использовании","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "Отправлять данные об использовании функций, категориях ошибок и примерном регионе для улучшения OpenMotion. Запросы и содержимое проектов не отправляются.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Настройка действует для MCP и Studio этой установки и сохраняется после перезапуска.",+ "Usage data collection is disabled in test builds.": "В тестовых версиях сбор данных об использовании отключён.","Disabled by your environment settings.": "Отключено настройками окружения.","Could not load privacy settings.": "Не удалось загрузить настройки конфиденциальности.","Could not save privacy settings.": "Не удалось сохранить настройки конфиденциальности.",diff --git a/studio/src/i18n/tr.json b/studio/src/i18n/tr.jsonindex 6a24961f..847d5e48 100644--- a/studio/src/i18n/tr.json+++ b/studio/src/i18n/tr.json@@ -1722,6 +1722,7 @@"Share usage data": "Kullanım verilerini paylaş","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "OpenMotion’ı geliştirmek için özellik kullanımı, hata kategorileri ve yaklaşık bölgeyi gönderin. İstemler ve proje içerikleri dahil edilmez.","This setting applies to MCP and Studio on this installation and is kept after restart.": "Bu ayar, bu kurulumdaki MCP ve Studio için geçerlidir ve yeniden başlatıldıktan sonra korunur.",+ "Usage data collection is disabled in test builds.": "Test sürümlerinde kullanım verileri toplanmaz.","Disabled by your environment settings.": "Ortam ayarlarınız tarafından devre dışı bırakıldı.","Could not load privacy settings.": "Gizlilik ayarları yüklenemedi.","Could not save privacy settings.": "Gizlilik ayarları kaydedilemedi.",diff --git a/studio/src/i18n/zh-CN.json b/studio/src/i18n/zh-CN.jsonindex df5c8fe1..8f38b898 100644--- a/studio/src/i18n/zh-CN.json+++ b/studio/src/i18n/zh-CN.json@@ -1722,6 +1722,7 @@"Share usage data": "分享使用数据","Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.": "发送功能使用情况、错误类别和大致地区,帮助改进 OpenMotion。不会发送提示词或工程内容。","This setting applies to MCP and Studio on this installation and is kept after restart.": "此设置同时适用于本次安装的 MCP 和 Studio,重启后仍然保留。",+ "Usage data collection is disabled in test builds.": "测试版本不采集使用数据。","Disabled by your environment settings.": "已由环境设置关闭。","Could not load privacy settings.": "无法加载隐私设置。","Could not save privacy settings.": "无法保存隐私设置。",diff --git a/studio/src/motion/PrivacySettings.test.tsx b/studio/src/motion/PrivacySettings.test.tsxindex 46985b5c..ea42c9ad 100644--- a/studio/src/motion/PrivacySettings.test.tsx+++ b/studio/src/motion/PrivacySettings.test.tsx@@ -27,6 +27,21 @@ it('shows the enabled default and persists a user opt-out while stopping browserexpect(toggle.checked).toBe(false);expect(requests[1].method).toBe('PUT'); expect(JSON.parse(String(requests[1].body))).toEqual({ enabled: false });expect(hooks.enabled).toHaveBeenCalledWith(false);+ for (let cycle = 0; cycle < 2; cycle++) {+ await act(async () => toggle.click()); expect(toggle.checked).toBe(true);+ expect(hooks.enabled).toHaveBeenLastCalledWith(true);+ await act(async () => toggle.click()); expect(toggle.checked).toBe(false);+ expect(hooks.enabled).toHaveBeenLastCalledWith(false);+ }+});++it('locks collection in test builds without overwriting the saved production preference', async () => {+ const fetcher = vi.fn(async () => Response.json({ enabled: false, preference: true, locked: true, reason: 'test_build' }));+ vi.stubGlobal('fetch', fetcher);+ const toggle = await open(); expect(toggle.checked).toBe(false); expect(toggle.disabled).toBe(true);+ await act(async () => toggle.click());+ expect(fetcher).toHaveBeenCalledTimes(1); expect(hooks.enabled).not.toHaveBeenCalled();+ expect(document.querySelector('[role=status]')?.textContent).toContain('disabled in test builds');});it('shows an environment lock and never offers to override it', async () => {diff --git a/studio/src/motion/PrivacySettings.tsx b/studio/src/motion/PrivacySettings.tsxindex 727b2ee3..bc878193 100644--- a/studio/src/motion/PrivacySettings.tsx+++ b/studio/src/motion/PrivacySettings.tsx@@ -3,7 +3,7 @@ import { useI18n } from '../i18n/I18n';import { motionApi } from './useWorkspace';import { setMotionTrackingEnabled } from './tracking';-type Status = { enabled: boolean; preference: boolean; locked: boolean };+type Status = { enabled: boolean; preference: boolean; locked: boolean; reason?: 'test_build' | 'environment' | null };export function PrivacySettings({ onClose }: { onClose: () => void }) {const { t } = useI18n(), dialog = useRef<HTMLDialogElement>(null);const [status, setStatus] = useState<Status | null>(null), [busy, setBusy] = useState(false), [error, setError] = useState('');@@ -28,7 +28,7 @@ export function PrivacySettings({ onClose }: { onClose: () => void }) {<section><label className="motion-media-toggle"><input type="checkbox" checked={status?.enabled ?? false} disabled={!status || busy || status.locked} onChange={event => void change(event.target.checked)} />{t('Share usage data')}</label><p>{t('Send feature usage, error categories and approximate region to improve OpenMotion. Prompts and project contents are excluded.')}</p><p className="motion-media-muted">{t('This setting applies to MCP and Studio on this installation and is kept after restart.')}</p>- {status?.locked && <p role="status">{t('Disabled by your environment settings.')}</p>}+ {status?.locked && <p role="status">{t(status.reason === 'test_build' ? 'Usage data collection is disabled in test builds.' : 'Disabled by your environment settings.')}</p>}{error && <p role="alert">{error}</p>}</section></dialog>;diff --git a/studio/src/motion/tracking.test.ts b/studio/src/motion/tracking.test.tsindex ad819b20..93af840e 100644--- a/studio/src/motion/tracking.test.ts+++ b/studio/src/motion/tracking.test.ts@@ -117,6 +117,27 @@ it('does not retry a server opt-out and allows a confirmed preference change toexpect(await tracking.trackMotion('ui_click', click)).toBe('disabled');});+it('resumes reporting new events after repeated opt-out and re-enable cycles', async () => {+ const bodies: any[] = [];+ vi.stubGlobal('fetch', vi.fn(async (_url, init?: RequestInit) => {+ if (init?.body) bodies.push(JSON.parse(String(init.body)));+ return Response.json({ enabled: true });+ }));+ const tracking = await import('./tracking');+ for (let cycle = 0; cycle < 3; cycle++) {+ tracking.setMotionTrackingEnabled(true);+ expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ expect(await tracking.flushMotionTracking()).toBe('accepted');+ expect(bodies).toHaveLength(cycle + 1);+ expect(await tracking.trackMotion('ui_click', click)).toBe('queued');+ tracking.setMotionTrackingEnabled(false);+ expect(await tracking.trackMotion('ui_click', click)).toBe('disabled');+ expect(await tracking.flushMotionTracking()).toBe('disabled');+ expect(tracking.getMotionTrackingStatus().pending).toBe(0);+ }+ expect(new Set(bodies.map(body => body.events[0].event_id)).size).toBe(3);+});+it('exposes safe queue and delivery statuses while rejecting private or non-Studio payloads', async () => {let failing = true;const fetcher = vi.fn(async (_url, init?: RequestInit) => init?.method === 'POST' && failingdiff --git a/tests/http.ts b/tests/http.tsindex 5c269582..4bb74cad 100644--- a/tests/http.ts+++ b/tests/http.ts@@ -12,14 +12,14 @@ class Capture extends Writable {_write(chunk: Buffer, _: string, done: () => void) { this.chunks.push(Buffer.from(chunk)); done(); }}// Runs the real HTTP request handler with streams, without binding a socket.-export function transport(store: WorkspaceStore, context?: Service): (url: string, init?: RequestInit) => Promise<Response> {+export function transport(store: WorkspaceStore, context?: Service, handle = handler): (url: string, init?: RequestInit) => Promise<Response> {return async (url, init = {}) => {const headers = Object.fromEntries(new Headers(init.headers));headers.host = 'localhost:4173'; headers.origin = 'http://localhost:4173';const input = typeof init.body === 'string' ? Buffer.from(init.body) : init.body instanceof Blob ? Buffer.from(await init.body.arrayBuffer()) : Buffer.alloc(0);const req = Object.assign(Readable.from([input]), { url, method: init.method || 'GET', headers });const res = new Capture(); const complete = finished(res);- await handler(req as unknown as IncomingMessage, res as unknown as ServerResponse, store, context);+ await handle(req as unknown as IncomingMessage, res as unknown as ServerResponse, store, context);await complete;return new Response(Buffer.concat(res.chunks), { status: res.statusCode, headers: res.headers });};diff --git a/tests/npm-package.test.ts b/tests/npm-package.test.tsindex d4dbfdd4..e55829a2 100644--- a/tests/npm-package.test.ts+++ b/tests/npm-package.test.ts@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises';import path from 'node:path';import { tmpdir } from 'node:os';import { checkReleaseLocks, packageNpm } from '../scripts/package-npm.mjs';@@ -10,6 +10,11 @@ import { phase1Skills } from '../shared/workflow.ts';import { mcpRegistry } from '../mcp.ts';const json = async (file: string) => JSON.parse(await readFile(file, 'utf8'));+async function verifyTrackingPolicy(application: string, mode: 'test' | 'stable') {+ await symlink(path.resolve('node_modules'), path.join(application, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');+ const result = JSON.parse(await runFile(process.execPath, ['--experimental-strip-types', path.resolve('tests/tracking-package.ts'), application, mode]));+ assert.equal(result.passed, true); assert.equal(result.external_requests, 0);+}test('shared Agent instructions keep the release controls synchronized', async () => {const section = async file => {@@ -67,6 +72,7 @@ test('test npm artifacts contain their application, locked manifest and no bundlassert(embeddedReadme.includes(`srcset="https://raw.githubusercontent.com/nexu-io/html-anything/${release.commit}/docs/readme/brand-hero.mobile.jpg"`));await assert.rejects(readdir(path.join(application, 'docs/readme/media')), { code: 'ENOENT' });assert.equal((await json(path.join(application, 'package.json'))).version, version);+ await verifyTrackingPolicy(application, 'test');assert.equal((await json(path.join(application, 'shared/template-config.json'))).environment, 'dev');assert.equal((await json(path.join(application, '.codex-plugin/plugin.json'))).version, version);assert.equal((await json(path.join(application, 'package-lock.json'))).packages[''].version, version);@@ -137,6 +143,8 @@ test('stable artifacts stage publication instead of replacing latest and retainawait extractArchive(built.installer, path.join(directory, 'npm'));const metadata = await json(path.join(directory, 'npm/package/package.json'));assert.equal((await json(built.manifest)).templateEnvironment, 'prod');+ const application = path.join(directory, 'app'); await extractArchive(built.application, application);+ await verifyTrackingPolicy(application, 'stable');assert.equal(metadata.version, '0.6.4'); assert.equal(metadata.private, false); assert.equal(metadata.publishConfig.tag, 'stage');assert.equal((await json('package.json')).private, true);assert.equal((await json('packages/npm/package.json')).private, true);diff --git a/tests/preview.test.ts b/tests/preview.test.tsindex 0d157b7e..2b757008 100644--- a/tests/preview.test.ts+++ b/tests/preview.test.ts@@ -81,7 +81,7 @@ test('phase1 port discovery leaves unrelated services and other workspaces intacassert.deepEqual(mock.stops, []);}, false));test('phase1 port discovery refuses an incompatible same-workspace authority without launching another', async t => {- for (const change of [{ protocol: 999 }, { version: VERSION, mcp: { protocol: 2, tools: ['motion_export_request'] } }, { mcp: { protocol: 1, tools: ['motion_get_project'] } }, { mcp: undefined }]) await t.test(JSON.stringify(change), () => fixture(async store => {+ for (const change of [{ protocol: 999 }, { version: '0.6.4-test.8', mcp: phase1McpCapabilities }, { version: VERSION, mcp: { protocol: 2, tools: ['motion_export_request'] } }, { mcp: { protocol: 1, tools: ['motion_get_project'] } }, { mcp: undefined }]) await t.test(JSON.stringify(change), () => fixture(async store => {const mock = runtime(store), port = Number(process.env.PORT || 4173);mock.occupied.set(port, { kind: 'motion', health: { service: 'motion-preview', protocol: 2, version: '0.6.4', dataDirectory: store.directory, ffmpeg: true, ready: true, ...change } });const before = await store.get();diff --git a/tests/tracking-package.ts b/tests/tracking-package.tsnew file mode 100644index 00000000..88020581--- /dev/null+++ b/tests/tracking-package.ts@@ -0,0 +1,92 @@+import assert from 'node:assert/strict';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { transport } from './http.ts';++// Run only in a child process against an extracted package; never contact a collector.+const [root, mode] = process.argv.slice(2);+assert(root && ['test', 'stable'].includes(mode));+for (const key of ['OPENMOTION_TELEMETRY', 'DO_NOT_TRACK', 'OPENMOTION_POSTHOG_HOST', 'OPENMOTION_POSTHOG_KEY']) delete process.env[key];+process.env.OPENMOTION_TRACKING_ENV = 'test'; process.env.OPENMOTION_TRACKING_TEST_RUN_ID = crypto.randomUUID();+const directory = await mkdtemp(path.join(tmpdir(), 'motion-tracking-package-'));+process.env.MOTION_DATA_DIR = directory;+const load = (file: string) => import(pathToFileURL(path.join(root, file)).href);+const { createAppTracking, saveTrackingPreference, trackingLocked, trackingLockReason } = await load('shared/tracking.ts');+const { handler } = await load('server.ts'), { WorkspaceStore } = await load('workspace.ts');+const { deviceContext } = await load('tracking/core.ts');+const packet = () => ({ event: 'ui_click', event_id: crypto.randomUUID(), occurred_at: new Date().toISOString(), entrypoint: 'studio',+ ...deviceContext(), properties: { page_name: 'home', area: 'workspace', element: 'new_creation' } });+const bodies: any[] = [];+globalThis.fetch = async (_url, init) => { bodies.push(JSON.parse(String(init?.body))); return Response.json({ status: 'Ok' }); };+const runtimes: any[] = [];+try {+ if (mode === 'test') await saveTrackingPreference(directory, true);+ for (const entry of ['mcp', 'worker']) runtimes.push(await createAppTracking(directory, entry));+ const request = transport(new WorkspaceStore(directory), { tracking: runtimes[1] }, handler);+ const set = (enabled: boolean) => request('/motion-api/tracking/preferences', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled }) });+ const send = () => request('/motion-api/tracking', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ events: [packet()] }) });+ if (mode === 'test') {+ process.env.OPENMOTION_TELEMETRY = '1';+ assert.equal(trackingLocked(), true); assert.equal(trackingLockReason(), 'test_build');+ const status = await (await request('/motion-api/tracking/preferences')).json();+ assert.deepEqual(status, { enabled: false, preference: true, locked: true, reason: 'test_build' });+ for (const runtime of runtimes) {+ runtime.setEnabled(true);+ assert.equal(runtime.ingest(packet()), 'disabled'); assert.equal(await runtime.flush(), 'disabled');+ }+ for (let cycle = 0; cycle < 2; cycle++) {+ assert.equal((await set(true)).status, 403);+ assert.deepEqual(await (await send()).json(), { accepted: 0, enabled: false });+ }+ assert.equal(bodies.length, 0);+ await assert.rejects(readFile(path.join(directory, 'tracking/identity.json')), /ENOENT/);+ assert.equal(JSON.parse(await readFile(path.join(directory, 'tracking/preferences.json'), 'utf8')).enabled, true);+ } else {+ assert.equal(trackingLocked(), false);+ const status = await (await request('/motion-api/tracking/preferences')).json();+ assert.deepEqual(status, { enabled: true, preference: true, locked: false, reason: null });+ assert.equal((await send()).status, 200); await runtimes[1].flush();+ for (let cycle = 0; cycle < 2; cycle++) {+ for (const runtime of runtimes) runtime.ingest(packet());+ assert.equal((await set(false)).status, 200);+ for (const runtime of runtimes) {+ assert.equal(runtime.enabled(), false);+ assert.equal(runtime.pending(), 0); assert.equal(runtime.ingest(packet()), 'disabled');+ assert.equal(await runtime.flush(), 'disabled');+ }+ const before = bodies.length;+ await send(); assert.equal(bodies.length, before);+ const restarted = await createAppTracking(directory, 'mcp'); runtimes.push(restarted);+ assert.equal(restarted.enabled(), false);+ assert.equal((await set(true)).status, 200);+ for (const runtime of runtimes) {+ assert.equal(runtime.ingest(packet()), 'queued'); assert.equal(await runtime.flush(), 'accepted');+ }+ assert.equal(bodies.length, before + runtimes.length);+ }+ assert.equal(new Set(bodies.flatMap(body => body.batch.map((event: any) => event.properties.installation_id))).size, 1);+ }+ if (process.getuid) {+ const { editorDirectory, ensureEditor } = await load('editor-runtime.ts');+ const { data, runtime } = await editorDirectory(directory);+ const registry = { service: 'opendesign-editor', protocol: 1, version: mode === 'test' ? '0.6.4' : '0.6.4-test.8',+ build: 'fixture', instanceId: crypto.randomUUID(), pid: process.pid, dataDirectory: data,+ endpoint: 'http://127.0.0.1:4173/', token: 'a'.repeat(64) };+ const registryFile = path.join(runtime, 'runtime.json');+ await writeFile(registryFile, JSON.stringify(registry));+ const before = await readFile(registryFile, 'utf8');+ globalThis.fetch = async url => {+ assert.equal(new URL(String(url)).pathname, '/editor-api/health');+ return Response.json({ ...registry, mcp: { protocol: 1, tools: ['motion_get_project'] } });+ };+ await assert.rejects(ensureEditor(directory, 'motion_get_project'), { code: 'EDITOR_RUNTIME_INCOMPATIBLE' });+ assert.equal(await readFile(registryFile, 'utf8'), before);+ }+ console.log(JSON.stringify({ version: JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')).version,+ policy: mode, captured_requests: bodies.length, external_requests: 0, passed: true }));+} finally {+ for (const runtime of runtimes) runtime.close();+ await rm(directory, { recursive: true, force: true });+}diff --git a/tests/tracking.test.ts b/tests/tracking.test.tsindex 06f6d273..752d3c08 100644--- a/tests/tracking.test.ts+++ b/tests/tracking.test.ts@@ -4,7 +4,7 @@ import { readFile, readdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { execFileSync } from 'node:child_process';import { createTracker, deviceContext } from '../tracking/core.ts';-import { createPosthogSender, loadIdentity } from '../tracking/node.ts';+import { createNodeTracking, createPosthogSender, loadIdentity } from '../tracking/node.ts';import { omEvents } from '../tracking/events.ts';import { closeTracking, createAppTracking, saveTrackingPreference, trackingError } from '../shared/tracking.ts';import { Phase1Service } from '../phase1.ts';@@ -73,7 +73,7 @@ test('concurrent identity creation has one winner, keeps its first source and fatest('PostHog adapter uses public ingest only, privacy fields and real receipt semantics', async () => {const identity = { installation_id: crypto.randomUUID(), utm_source: 'alice', created_at: new Date().toISOString() };- const options = { identity, appVersion: '0.0.0-test', env: 'test' as const, host: 'https://us.i.posthog.com', token: 'phc_test' };+ const options = { identity, appVersion: '0.0.0', env: 'test' as const, host: 'https://us.i.posthog.com', token: 'phc_test' };assert.throws(() => createPosthogSender({ ...options, token: 'phx_private' }), /PUBLIC_PROJECT/);assert.throws(() => createPosthogSender({ ...options, host: 'http://example.com' }), /INVALID_INGEST/);assert.throws(() => createPosthogSender({ ...options, host: 'https://user:[email protected]' }), /INVALID_INGEST/);@@ -101,6 +101,22 @@ test('PostHog adapter uses public ingest only, privacy fields and real receipt sassert.equal(Object.hasOwn(enriched[0].batch[0].properties, '$ip'), false);});+test('test and local versions cannot report even when enabled or given a test-run override', async () => {+ let sends = 0;+ const identity = { installation_id: crypto.randomUUID(), utm_source: null, created_at: new Date().toISOString() };+ for (const appVersion of ['0.6.4-test.8', '0.6.4-test.42.2', '0.6.4-local.1', '0.6.4-beta.1', 'invalid']) {+ const options = { registry: omEvents, identity, appVersion, entrypoint: 'mcp' as const, enabled: true,+ env: 'test' as const, testRunId: crypto.randomUUID(), host: 'https://us.i.posthog.com', token: 'phc_test' };+ const tracking = createNodeTracking(options);+ tracking.setEnabled(true);+ assert.equal(tracking.enabled(), false); assert.equal(tracking.ingest(packet()), 'disabled');+ assert.equal(await tracking.flush(), 'disabled'); tracking.close();+ const sender = createPosthogSender({ ...options, fetch: async () => { sends++; return Response.json({ status: 'Ok' }); } });+ assert.equal(await sender([packet()], new AbortController().signal), 'drop');+ }+ assert.equal(sends, 0);+});+test('browser ingress rejects forged identity, worker events and oversized batches', () => fixture(async store => {const events: PendingEvent[] = [], tracking = core(async batch => { events.push(...batch); return 'accepted'; });const request = transport(store, { tracking });@@ -174,7 +190,21 @@ test('default configuration reports without opt-in; saved opt-out covers runtimeassert.equal(mcp.pending(), 0); assert.equal(worker.pending(), 0); assert.equal(bodies.length, 1);const restarted = await createAppTracking(store.directory, 'mcp'); runtimes.push(restarted);assert.equal(restarted.enabled(), false); assert.equal(restarted.ingest(packet()), 'disabled');- await saveTrackingPreference(store.directory, true); assert.equal(restarted.enabled(), true);+ for (let cycle = 0; cycle < 2; cycle++) {+ assert.equal((await set(true)).status, 200);+ for (const runtime of runtimes) {+ assert.equal(runtime.enabled(), true); assert.equal(runtime.ingest(packet()), 'queued');+ assert.equal(await runtime.flush(), 'accepted');+ }+ assert.equal(bodies.length, 1 + (cycle + 1) * runtimes.length);+ assert.equal((await set(false)).status, 200);+ for (const runtime of runtimes) {+ assert.equal(runtime.ingest(packet()), 'disabled'); assert.equal(await runtime.flush(), 'disabled');+ }+ }+ assert.equal((await set(true)).status, 200);+ assert.equal(new Set(bodies.flatMap(body => body.batch.map((event: any) => event.properties.installation_id))).size, 1);+ assert.equal(restarted.enabled(), true);process.env.OPENMOTION_TELEMETRY = '0'; assert.equal(restarted.ingest(packet()), 'disabled');assert.equal((await set(true)).status, 403); delete process.env.OPENMOTION_TELEMETRY;await writeFile(path.join(store.directory, 'tracking/preferences.json'), 'corrupted');diff --git a/tracking/INTEGRATION.md b/tracking/INTEGRATION.mdindex b43fa600..d17a4754 100644--- a/tracking/INTEGRATION.md+++ b/tracking/INTEGRATION.md@@ -168,8 +168,15 @@ Do not add client IP lookups or collect IP in callers.Device timezone is separate from GeoIP timezone; VPN/proxy egress may differ.See [configuration, privacy and limits](README.md) and [coarse GeoIP](posthog-geoip.hog).-Tracking is on by default. Studio **Privacy settings → Share usage data** disables-collection for the installation, including MCP and Studio across restarts.+Tracking is on by default in stable releases. Studio **Privacy settings → Share+usage data** disables collection for the installation, including MCP and Studio+across restarts. Re-enabling resumes new reports without replaying discarded events.+Test/prerelease/local application versions are always disabled at runtime, even+with a saved opt-in, `OPENMOTION_TELEMETRY=1`, custom collector or test-run UUID.+Their Privacy switch is locked and explains the test-build policy; opening a test+build does not replace the saved stable-release preference.+Test and stable MCP clients must use separate data directories; shared-backend+discovery rejects cross-policy reuse without stopping or replacing the authority.`OPENMOTION_TELEMETRY=0` or `DO_NOT_TRACK=1` forces it off; browser Do Not Track alsosuppresses browser collection. An added event must respect those controls.@@ -229,6 +236,8 @@ Extend the existing tests nearest the changed boundary:missing call site cannot pass on schema tests alone.- `tests/source-install.test.ts`, `tests/package.test.ts` and`tests/npm-package.test.ts`: public boundary and distributed content when affected.+ The npm tests also execute extracted test and stable application archives with+ fake senders, checking the version lock and repeated disable/re-enable cycles.Check a valid event and required/unknown-field rejection, real success and failure,and the relevant no-op/retry/replay or rerender case. Prove there is one event per@@ -255,7 +264,9 @@ checks and applicable repository gates, not invented product events.## Read back a marked live run-Use an owned temporary data directory and fresh runtime processes. Apply the same+Use a stable-version application, an owned temporary data directory and fresh+runtime processes. A test/prerelease package never reports, even for this check;+do not change its version to bypass the policy. Apply the sametest environment to every participating MCP/local service process, including oneslaunched by a host. An already-running shared service will not inherit new variables.For a POSIX shell, prepare the environment before starting the normal test runnerdiff --git a/tracking/README.md b/tracking/README.mdindex 0967351d..419962a1 100644--- a/tracking/README.md+++ b/tracking/README.md@@ -9,7 +9,14 @@ For new events, start with the [integration guide and agent task template](INTEG## Reporting and user control-Reporting is **on by default** into the existing OpenDesign project (420348).+Reporting is **on by default in stable releases** into the existing OpenDesign project (420348).+Test and other prerelease/local application versions never report. This is enforced+from the packaged application version, independently of CI environment variables,+the saved preference, a custom collector or test-run overrides. The test-build+Privacy switch is locked off and does not overwrite a saved stable-release choice.+Stable and test clients cannot reuse each other's same-workspace backend authority;+use the separate installation/data directories already provided by DEV packages.+Compatible updates within the same release policy retain normal backend reuse.OM events carry `product=openmotion`; OM reports must filter by that property,and shared-project reports must distinguish OM from other products. The project'spublic, write-only token and ingestion host are distributed in@@ -22,6 +29,8 @@ to both MCP and Studio, including already-running processes and future restarts.Disabling clears pending queues and aborts in-flight delivery; accepted eventscannot be recalled. A filesystem watcher propagates preference changes, and eachenqueue/flush also checks the saved preference. Corrupt preference files fail closed.+On stable releases, re-enabling resumes collection of new events in MCP and Studio+without restarting. Events discarded while disabled are not buffered or replayed.`OPENMOTION_TELEMETRY=0` (also `false`/`off`) or `DO_NOT_TRACK=1` forces all collectionoff and locks the Studio switch. Restart services after changing launch environment@@ -42,6 +51,9 @@ Use `OPENMOTION_TRACKING_ENV=test` and a UUID inout of product dashboards. Normal environments are `production` and `development`.Node/Vitest tests suppress collection unless explicitly given a test run ID; CIalso forces collection off. No test should silently report into production funnels.+Marked live-ingestion checks require a stable-version application running with+`env=test`; a `-test.N` package cannot be opted into reporting. Deterministic checks+use fake senders and extracted stable/test packages without external requests.Studio retrieves only an enabled flag and submits semantic events to the same-origin`/motion-api/tracking` endpoint. The server validates the complete batch, rejectsdiff --git a/tracking/node.ts b/tracking/node.tsindex 1fdd233e..2d950fac 100644--- a/tracking/node.ts+++ b/tracking/node.ts@@ -6,6 +6,7 @@ import type { Entry, Registry, PendingEvent, Receipt } from './core.ts';export type Identity = { installation_id: string; utm_source: string | null; created_at: string };const sourcePattern = /^[A-Za-z0-9_.-]{1,64}$/;+export function trackingReleaseEnabled(version: string) { return /^\d+\.\d+\.\d+$/.test(version); }export async function loadIdentity(directory: string, source?: string): Promise<Identity> {if (source !== undefined && (typeof source !== 'string' || !sourcePattern.test(source))) throw new Error('INVALID_SOURCE');@@ -40,6 +41,7 @@ export function createPosthogSender(options: {if (!/^phc_[A-Za-z0-9_]+$/.test(options.token)) throw new Error('PUBLIC_PROJECT_TOKEN_REQUIRED');if (options.testRunId && (!uuid.test(options.testRunId) || options.env !== 'test')) throw new Error('INVALID_TEST_RUN');return async (events: readonly PendingEvent[], signal: AbortSignal): Promise<Receipt> => {+ if (!trackingReleaseEnabled(options.appVersion)) return 'drop';const batch = events.map(event => ({ event: event.event, uuid: event.event_id, timestamp: event.occurred_at,properties: { ...event.properties, event_schema_version: 1, schema_version: 1, product: 'openmotion',app_version: options.appVersion, env: options.env, channel: 'standalone',@@ -76,7 +78,8 @@ export function createNodeTracking<const R extends Registry>(options: {env: 'development' | 'test' | 'production'; testRunId?: string; entrypoint: Entry;enabled: boolean; timeoutMs?: number; flushIntervalMs?: number; maxQueue?: number; geoip?: boolean; isEnabled?: () => boolean;}) {- const enabled = options.enabled && !!options.token;+ const enabled = options.enabled && !!options.token && trackingReleaseEnabled(options.appVersion);const send = enabled ? createPosthogSender({ ...options, token: options.token! }) : async () => 'drop' as const;- return createTracker({ ...options, enabled, send });+ return createTracker({ ...options, enabled, send,+ isEnabled: () => trackingReleaseEnabled(options.appVersion) && (options.isEnabled?.() ?? true) });}