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: diagnose MCP connections and align Studio validation
罗高35506255582a
diff --git a/README.md b/README.mdindex 4a83f11a..8967a345 100644--- a/README.md+++ b/README.md@@ -552,6 +552,8 @@ Select a preview to watch the clip. Entries marked “View component” also linFor a packaged install, give your agent the [test installation guide](https://releases.open-design.ai/open-motion/dev/install.md). It pins the package version and walks through isolated setup. To run from source, follow the steps below.+If MCP tools are missing or fail to connect, use the installed [connection diagnosis and recovery guide](docs/npm-installation.md#missing-mcp-tools-or-a-failed-connection) to inspect the actual host configuration and verify the original workspace before continuing.+Use Git, npm and **Node.js 26.11.1**. Source-based preview and export also need Chrome/Chromium and FFmpeg/FFprobe. [Runtime setup](docs/usage.md)```shdiff --git a/docs/agent-adapters.md b/docs/agent-adapters.mdindex d53d77d2..dcf64018 100644--- a/docs/agent-adapters.md+++ b/docs/agent-adapters.md@@ -85,6 +85,8 @@ Codex 声明 `requires_local_executor`;两家原生插件均引用同一外置独立验证使用临时 `CODEX_HOME` / `CLAUDE_CONFIG_DIR`,安装后读取宿主实际解析的启动配置,检查工具和 `motion_get_project.dataDirectory`。卸载仅移除薄入口,保留外置运行时和用户数据。旧自带服务源码的 `check-installed-mcp.mjs` / `resolve-installed.mjs` 不用于新适配器缓存;本轮不改变旧安装器行为。+For an npm-managed installation, the installed `scripts/npm-installer.mjs diagnose --host HOST --home HOME` reuses the transport probe with that installation's launcher, host configuration and expected data directory; it does not inspect an assumed plugin cache. Missing/disabled registration, startup errors, invalid protocol output, version/tool mismatches and a different workspace are reported separately. Its independent probe cannot observe every active host session or reconnect a closed chat transport. Follow [connection diagnosis and recovery](npm-installation.md#missing-mcp-tools-or-a-failed-connection), then verify the original project through the real host MCP connection.+## DeepSeek Harness```shdiff --git a/docs/hyperframes.md b/docs/hyperframes.mdindex 5d9ef327..6dde3ca1 100644--- a/docs/hyperframes.md+++ b/docs/hyperframes.md@@ -30,6 +30,8 @@ Studio 前端从上游 0.9.7 的固定 commit 迁入 `studio/src/` 并在本仓导出链是版本校验 → 复制并校验内容快照 → 记录快照尺寸/fps/时长 → 后台独占领取 → 上游 lint/render → 实际 MP4 头检查 → completed。渲染日志和预期规格保留,结束后删除媒体快照,查询返回原请求版本。一期 `motion_export_request` 在 completed 前自动按任务规格检查实际 MP4、完整解码视频/音频并执行代表帧 seek;通过 `motion_get_project` 的 exportJobId 查询报告;视觉、声音内容与实际播放器检查仍独立执行。旧浏览器 WebM 上传端点、claim/fail 协议、Canvas renderer、MediaRecorder、离线打包和 IndexedDB 草稿已删除。+OpenMotion preview and export preflight run the pinned native `lintProject` with `host: "studio"` in an isolated child process, retaining timeout, cancellation, referenced-file checks and native finding locations/fix hints. Root composition structure errors are rejected before opening Studio or invoking the renderer; ordinary warnings remain non-blocking. The same check is available from `node scripts/lint-project.mjs RUNTIME_ROOT PROJECT_DIRECTORY` (exit 0 for no errors, 1 for validation errors). Direct upstream `hyperframes lint` retains its CLI warning policy; its success alone is not Studio acceptance. `info` and `timeline` keep their original CLI behavior.+测试包含真实 Studio API 的 If-Match 编辑、MCP 反向编辑、原生模板 lint/timeline、旧文件保留、路径/链接隔离、缓存与 manifest 的区别,以及无浏览器页面参与的带音轨渲染。集成测试验证 320×180、24fps、H.264、音频、时长、移动图形帧差和下载字节。没有本机渲染依赖时显式跳过集成测试。官方参考:[代码与包结构](https://github.com/heygen-com/hyperframes)、[Composition 格式](https://github.com/heygen-com/hyperframes/blob/main/skills/hyperframes/references/format.md)、[Studio CLI](https://github.com/heygen-com/hyperframes/blob/main/packages/cli/src/commands/preview.ts)。具体行为按锁定的 npm 版本验证,更新上游版本时应复测原生 API、Studio manifests、生命周期输出和渲染链路。diff --git a/docs/mcp-phase1-tools.md b/docs/mcp-phase1-tools.mdindex db9ad970..dc5b549e 100644--- a/docs/mcp-phase1-tools.md+++ b/docs/mcp-phase1-tools.md@@ -50,6 +50,8 @@ list 无参数,返回 indexPath、total、catalogVersion 和可选 warning,Default action=open accepts an explicit projectId or bound sessionId, optional embedded, presentation, expectedRevision and expectedVersionId. When supplied, both identities are checked before and after lint/open. The result includes previewHandoff, previewUrl, preflight, selectionSource and openedByHost=false; the host must present the existing project. No project is created implicitly.+Preview and export preflight use the same pinned native `host:"studio"` lint policy as the editor. Structural errors return `PROJECT_VALIDATION_FAILED` before preview opening, or a failed export before rendering, with native code/file/location/fix hints. Warnings do not fail the check. See the [shared lint command](hyperframes.md).+The handoff preserves the current chat by default (presentation=foreground): reuse its native Tab and queue while inactive. On return, resolve the latest project version without replaying the queued version. Codex actions include a calling-chat-only visibilitySync and bounded observation instructions; queued alone is not confirmation. Only an explicit presentation=now request allows switching back for this turn; background skips presentation. See the shared [continuing-edit workflow](../skills/motion-production/references/native.md#continuing-edits).action=record_display requires projectId, requestId and display={revision,versionId,previewUrl,visibility,contentVerified,evidence}; optional hostStatus and hostTabId retain the acknowledgment and actual native providerTabId independently. Only visible plus inspected latest content returns confirmed. Hidden/queued/unavailable or unverified content remains pending. Reject foreign project/session/origin URLs and stale revision/version identities, including same-hash restores and retries. Records are host_reported; motion_get_project.previewDisplay exposes isCurrentVersion and liveVisibilityVerified=false, never a live visibility claim.diff --git a/docs/npm-installation.md b/docs/npm-installation.mdindex d0ea9463..6a9ff14b 100644--- a/docs/npm-installation.md+++ b/docs/npm-installation.md@@ -117,6 +117,24 @@ Before upgrading, back up projects/configuration, run setup with the new exact t## Native tools and diagnostics+### Missing MCP tools or a failed connection++Run the installed CLI with the same application home and selected host:++```sh+node /absolute/application/scripts/npm-installer.mjs diagnose --host codex --home /absolute/installation-home+```++The installed Skill's `scope.json` or `openmotion-install.json` supplies `runtimeRoot` (the application directory), `installHome` and `host`; do not guess them from the video project. The packaged npm CLI also exposes `openmotion diagnose` through the same exact package used for setup. Select `codex`, `claude`, `deepseek` or `workbuddy`; preserve any custom `--codex` executable or Harness `--profile`. The saved Harness profile is used by default.++Diagnosis reads the selected host's owned configuration and starts an independent, bounded MCP probe using its command, arguments, registered environment overrides and working directory. It otherwise inherits the diagnostic process environment, which can differ from a GUI host. It verifies initialization, the installed tool list and a `motion_get_project` read of the expected data directory. It never registers/replaces configuration, creates a project, restarts another process or replays an export. A probe can start or reuse this installation's backend; it does not wait for native media/browser downloads. Credential-like environment values are redacted from reported startup output.++The JSON result includes `status`, `hostSessionVerified:false` and `nextAction`; failures also include the stage, code and message. A successful probe does not establish that the current host chat loaded those tools, and Claude/WorkBuddy/Harness configuration reads cannot observe every session-specific enablement or tool-selection setting. Inspect the host's status/output and correct the reported configuration, runtime or version problem. In an interactive Claude Code session use the server's Reconnect action in `/mcp`; in other hosts use their supported MCP refresh/reconnect control. Then call `motion_get_project` through the active host connection, check the directory and original project/version, and resume the task. An empty tool search alone is not a diagnosis.++For source/plugin installations without an npm `installHome`, use the host's actual registered launch command and logs. The source Codex bootstrap retains `scripts/check-installed-mcp.mjs`; do not point it at a guessed plugin cache or substitute a different workspace. A closed host transport must be reconnected by the host. Keep running exports and original request IDs while recovering.++### Native media and browser preparation+The runtime lock pins HTTPS URLs, versions, target OS/CPU and SHA256 for FFmpeg, ffprobe and Chrome for Testing. Downloads require no repository credentials, never attach repository tokens, and do not run brew/winget. Independent archives are prepared concurrently from the existing platform manifest: three separate components on macOS, browser and combined media on Windows. Explicit `prepare` settles every component before returning; any failure rejects the operation while completed components remain reusable. Component and archive cache locks coalesce requests across processes and app versions sharing the same platform/hash cache. Contenders wait; dead-owner locks can be recovered without deleting live locks. Atomic per-component state supports Studio reloads and failure retry. Completed components are reused, including after another component fails. Temporary extraction and completion markers retain retry/cache protection. Downloads interrupted mid-transfer restart that asset; HTTP range resume is not implemented. A failed download is not ready. Explicit native path overrides remain supported. See [runtime details](test-packages.md).A local `--manifest /absolute/release-npm.json` remains available for legacy delivery and controlled fixtures. HTTP, URL credentials, unsafe extraction paths and invalid hashes are rejected. Do not remove a leftover install lock until its owning process is confirmed stopped.diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex ecc36cfb..35f97440 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -161,6 +161,8 @@ README 参考 OpenDesign 的产品导览和 HTML Anything 的贡献、来源表一期公开 MCP 已按[11 Tool 契约](../mcp-phase1-tools.md) 实现本地适配与构建过滤,默认 phase1。发布清单同时控制发现/调用、HTTP 接入元数据及各分发包,原28项内部兼容实现和 Studio 服务保留。phase1.ts 负责明确项目、请求去重、批量素材/保存、具名任务与审阅;phase1-versions.ts 复用原生 history、补稳定 vN 和原生未留存媒体及保存恢复日志。恢复历史创建新版本并保留后续历史,区别于内容哈希和单文件保存。导出继续委托原渲染器并自动完整技术验证;取消区分受理和进程退出。5个随包 Skill 与 MCP resources 指引同步新契约。此为本地实现,未据此宣布部署/平台/宿主业务验收。+Preview/export preflight and the bundled OpenMotion lint command use the pinned native linter's Studio policy in an isolated, cancellable process. A structurally invalid project is rejected before editor opening or rendering; non-blocking warnings remain warnings. The npm CLI's `diagnose` command reads the installed host configuration and probes initialization, tool discovery and the expected workspace through an independent MCP process. It does not mutate configuration, create projects or prove active-chat connectivity. Host reconnection and a subsequent real host read remain separate completion conditions; see [connection diagnosis](../npm-installation.md#missing-mcp-tools-or-a-failed-connection).+| 能力 | 负责模块 | 当前边界 || --- | --- | --- || MVP editor and project navigation | `MotionApp.tsx`、`WorkspaceFrame.tsx`、`MotionHome.tsx`、`useWorkspace.ts`(位于 `studio/src/motion/`) | Root and project URLs open the editor directly. The sidebar lists projects; switching retains native save guards. Home/session UI modules remain unmounted. |diff --git a/hyperframes.ts b/hyperframes.tsindex 16bfa584..752a3b85 100644--- a/hyperframes.ts+++ b/hyperframes.ts@@ -109,7 +109,9 @@ export async function runHyperframes(runtimeRoot: string, directory: string, arg}export async function inspectProject(runtimeRoot: string, directory: string, view: string, signal?: AbortSignal) {if (!['info', 'lint', 'timeline'].includes(view)) throw new Error('view 必须为 info、lint 或 timeline');- const result = await runHyperframes(runtimeRoot, directory, [view, '.', '--json'], undefined, undefined, signal);+ const result = view === 'lint'+ ? await execute(process.execPath, [path.join(pluginRoot, 'scripts/lint-project.mjs'), runtimeRoot, directory], directory, undefined, undefined, signal)+ : await runHyperframes(runtimeRoot, directory, [view, '.', '--json'], undefined, undefined, signal);try { return { exitCode: result.code, result: JSON.parse(result.stdout) }; }catch { throw new Error('Hyperframes ' + view + ' 失败:' + (result.stderr || result.stdout).slice(-1500)); }}diff --git a/scripts/check-installed-mcp.mjs b/scripts/check-installed-mcp.mjsindex 11f8a7a3..1a6075b5 100644--- a/scripts/check-installed-mcp.mjs+++ b/scripts/check-installed-mcp.mjs@@ -3,29 +3,57 @@ import path from 'node:path';import { spawnSync } from 'node:child_process';import { fileURLToPath } from 'node:url';-export function checkTransport(config, expectedVersion) {- if (!config?.enabled || config.transport?.type !== 'stdio') throw new Error('OpenDesign MCP 未启用或不是 stdio 服务');+const failure = (code, message) => Object.assign(new Error(message), { code });+export function redact(message, environment) {+ for (const [key, value] of Object.entries(environment)) {+ if (/token|secret|password|authorization|api.?key/i.test(key) && typeof value === 'string' && value.length >= 4) message = message.replaceAll(value, '[redacted]');+ }+ return message.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')+ .replace(/([\w-]*(?:token|secret|password|authorization|api.?key)[\w-]*["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'[^']*'|[^\s,;}]+)/gi, '$1[redacted]').slice(-1500);+}++export function checkTransport(config, expectedVersion, { expectedTools, dataDirectory } = {}) {+ if (!config) throw failure('MCP_NOT_REGISTERED', 'OpenMotion MCP is not registered in this host. Run setup for the selected host.');+ if (config.enabled === false) throw failure('MCP_DISABLED', 'OpenMotion MCP is disabled. Enable it in the selected host before reconnecting.');+ if (config.transport?.type !== 'stdio') throw failure('MCP_CONFIG_INVALID', 'OpenMotion requires a local stdio MCP connection.');const transport = config.transport;- if (JSON.stringify([transport.command, transport.cwd, transport.args]).includes('${')) throw new Error('Codex 解析后的启动配置仍含未展开占位符,不能启动 MCP;请更新 OpenDesign 配置');- if (!path.isAbsolute(transport.cwd || '') || !fs.statSync(transport.cwd).isDirectory()) throw new Error('Codex 解析后的 MCP 工作目录不存在');- if (transport.command !== 'node' || JSON.stringify(transport.args) !== JSON.stringify(['--experimental-strip-types', 'mcp.ts'])) throw new Error('OpenDesign 的实际启动命令与当前插件不一致,已停止预检');+ if (transport.cwd != null && typeof transport.cwd !== 'string') throw failure('MCP_CONFIG_INVALID', 'MCP working directory must be a string.');+ if (transport.env != null && (typeof transport.env !== 'object' || Array.isArray(transport.env) || Object.values(transport.env).some(value => typeof value !== 'string'))) throw failure('MCP_CONFIG_INVALID', 'MCP environment overrides must contain string values.');+ if (JSON.stringify([transport.command, transport.cwd, transport.args]).includes('${')) throw failure('MCP_CONFIG_INVALID', 'The resolved MCP command contains an unexpanded placeholder. Fix the host configuration.');+ if (typeof transport.command !== 'string' || !transport.command || !Array.isArray(transport.args) || transport.args.some(arg => typeof arg !== 'string')) throw failure('MCP_CONFIG_INVALID', 'MCP requires an executable command and string arguments.');+ if (transport.cwd && (!path.isAbsolute(transport.cwd) || !fs.existsSync(transport.cwd) || !fs.statSync(transport.cwd).isDirectory())) throw failure('MCP_CONFIG_INVALID', 'The resolved MCP working directory does not exist or is not absolute.');const messages = [{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'motion-install-check', version: '1' } } },{ jsonrpc: '2.0', method: 'notifications/initialized' },{ jsonrpc: '2.0', id: 2, method: 'tools/list' },];+ if (dataDirectory) messages.push({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'motion_get_project', arguments: {} } });+ const environment = { ...process.env, ...(transport.env || {}) };const result = spawnSync(transport.command, transport.args, { cwd: transport.cwd,- env: { ...process.env, ...(transport.env || {}) }, encoding: 'utf8', timeout: 15_000,+ env: environment, encoding: 'utf8', timeout: 15_000, maxBuffer: 4 * 1024 * 1024,input: messages.map(message => JSON.stringify(message)).join('\n') + '\n' });- if (result.error || result.status !== 0) throw new Error('按 Codex 实际配置启动 MCP 失败:' + (result.error?.message || result.stderr.slice(-1000)));- const responses = result.stdout.trim().split('\n').map(line => JSON.parse(line));+ if (result.error || result.status !== 0) throw failure(result.error?.code === 'ETIMEDOUT' ? 'MCP_PROBE_TIMEOUT' : 'MCP_STARTUP_FAILED',+ 'MCP probe failed: ' + redact(result.error?.message || result.stderr || `exit ${result.status}`, environment));+ let responses;+ try {+ responses = result.stdout.trim().split('\n').filter(Boolean).map(line => JSON.parse(line));+ if (responses.some(response => !response || response.jsonrpc !== '2.0')) throw new Error('Invalid MCP response');+ }+ catch { throw failure('MCP_PROTOCOL_INVALID', 'MCP stdout contains invalid JSON. Keep diagnostic logs on stderr.'); }const initialization = responses.find(response => response.id === 1)?.result;const listed = responses.find(response => response.id === 2)?.result?.tools;- if (initialization?.serverInfo?.version !== expectedVersion) throw new Error('实际启动的 OpenDesign 版本与待安装版本不同');- const names = listed?.map(tool => tool.name) || [];- const expected = JSON.parse(fs.readFileSync(new URL('../shared/mcp-profiles.json', import.meta.url), 'utf8')).phase1.tools;- if (names.length !== expected.length || !expected.every(name => names.includes(name))) throw new Error('实际 MCP 未严格返回一期公开 motion_ Tool 清单,请更新 OpenMotion 插件');- return { version: expectedVersion, cwd: transport.cwd, tools: names };+ if (!initialization?.serverInfo) throw failure('MCP_INITIALIZATION_FAILED', 'The MCP process did not complete initialization. Inspect its startup output in the host.');+ if (initialization.serverInfo.version !== expectedVersion) throw failure('MCP_VERSION_MISMATCH', 'The MCP application version does not match this installation.');+ const names = Array.isArray(listed) ? listed.map(tool => tool?.name) : [];+ const expected = expectedTools || JSON.parse(fs.readFileSync(new URL('../shared/mcp-profiles.json', import.meta.url), 'utf8')).phase1.tools;+ if (names.length !== expected.length || !expected.every(name => names.includes(name))) throw failure('MCP_TOOLS_MISMATCH', 'The MCP tool list does not match this installation. Refresh the host tool discovery after correcting the installation.');+ if (dataDirectory) {+ const read = responses.find(response => response.id === 3);+ if (!read?.result || read.error || read.result.isError) throw failure('MCP_READ_FAILED', 'motion_get_project failed: ' + redact(JSON.stringify(read?.error || read?.result?.structuredContent || read?.result?.content || 'No result returned'), environment));+ const directory = read?.result?.structuredContent?.dataDirectory;+ if (typeof directory !== 'string' || path.resolve(directory) !== path.resolve(dataDirectory)) throw failure('MCP_WORKSPACE_MISMATCH', 'motion_get_project did not confirm the installation data directory. Do not switch workspaces or create a replacement project.');+ }+ return { version: expectedVersion, cwd: transport.cwd, tools: names, ...(dataDirectory ? { dataDirectory } : {}) };}if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {try {diff --git a/scripts/distribution.ts b/scripts/distribution.tsindex 911f98e4..81c1cfb7 100644--- a/scripts/distribution.ts+++ b/scripts/distribution.ts@@ -493,7 +493,8 @@ export async function distributionFiles(profile: string): Promise<string[]> {'server.ts', 'browser.ts', 'workspace.ts', 'mcp.ts', 'mcp-tools.ts', 'editor-runtime.ts','phase1.ts', 'phase1-versions.ts', 'preview.ts', 'hyperframes.ts', 'template-library.ts','template-catalog.ts', 'prism-templates.ts', 'editor-server.ts',- 'scripts/runtime-assets.mjs', 'scripts/npm-runtime.mjs', 'scripts/runtime-lock.json',+ 'scripts/runtime-assets.mjs', 'scripts/npm-runtime.mjs', 'scripts/runtime-lock.json', 'scripts/lint-project.mjs',+ 'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/check-installed-mcp.mjs','scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts','shared/workflow-entry.js', 'studio/LICENSE', 'studio/README.md', 'template-library/LICENSE', 'shared/editor-launch.pl','tracking/core.ts', 'tracking/node.ts', 'tracking/browser.ts', 'tracking/events.ts',diff --git a/scripts/lint-project.mjs b/scripts/lint-project.mjsnew file mode 100644index 00000000..9f2a2b57--- /dev/null+++ b/scripts/lint-project.mjs@@ -0,0 +1,14 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++const [runtimeRoot, directory] = process.argv.slice(2);+if (!runtimeRoot || !directory) throw new Error('Usage: node scripts/lint-project.mjs RUNTIME_ROOT PROJECT_DIRECTORY');+const coreRoot = path.resolve(runtimeRoot, 'node_modules/@hyperframes/core');+const core = JSON.parse(await readFile(path.join(coreRoot, 'package.json'), 'utf8'));+const { lintProject } = await import(pathToFileURL(path.join(coreRoot, core.exports['./lint'].import)).href);+const checked = await lintProject(path.resolve(directory), undefined, { host: 'studio' });+const result = { ok: checked.totalErrors === 0, errorCount: checked.totalErrors, warningCount: checked.totalWarnings,+ infoCount: checked.totalInfos, findings: checked.results.flatMap(entry => entry.result.findings), filesScanned: checked.results.length };+process.stdout.write(JSON.stringify(result) + '\n');+process.exitCode = result.ok ? 0 : 1;diff --git a/scripts/npm-hosts.mjs b/scripts/npm-hosts.mjsindex 04f2f6fc..a5775bd4 100644--- a/scripts/npm-hosts.mjs+++ b/scripts/npm-hosts.mjs@@ -27,7 +27,7 @@ export async function hostPlan(options, home, launcher, previous) {try { current = JSON.parse(await cli(['mcp', 'get', 'openmotion', '--json'])); }catch (error) { if (!/No MCP server named ['"]openmotion['"] found/.test(error.message)) throw error; }assert(!current || (saved && equalTransport(current.transport, transport)), 'Existing openmotion MCP configuration is not owned by this installation');- return { host, ...metadata, metadata, register: async () => { if (!current) await cli(['mcp', 'add', 'openmotion', '--', process.execPath, launcher]); } };+ return { host, ...metadata, metadata, connection: current, register: async () => { if (!current) await cli(['mcp', 'add', 'openmotion', '--', process.execPath, launcher]); } };}if (host === 'claude') {const claude = options.claude || 'claude';@@ -38,7 +38,7 @@ export async function hostPlan(options, home, launcher, previous) {const current = settings?.mcpServers?.openmotion;assert(!current || (saved?.configFile === configFile && equalTransport(current, transport)), 'Existing Claude openmotion MCP is not owned by this installation');metadata.configFile = configFile;- return { host, ...metadata, metadata, register: async () => {+ return { host, ...metadata, metadata, connection: current && { transport: current }, register: async () => {if (!current) await runFile(claude, ['mcp', 'add-json', '-s', 'user', 'openmotion', JSON.stringify(transport)]);} };}@@ -50,8 +50,9 @@ export async function hostPlan(options, home, launcher, previous) {const current = config?.mcpServers?.openmotion;assert(!current || (saved?.configFile === configFile && equalTransport(current, transport)), 'Existing WorkBuddy openmotion MCP is not owned by this installation');};- check(await readJSON(configFile)); metadata.configFile = configFile;- return { host, ...metadata, metadata, register: async () => {+ const configured = await readJSON(configFile);+ check(configured); metadata.configFile = configFile;+ return { host, ...metadata, metadata, connection: configured?.mcpServers?.openmotion && { transport: configured.mcpServers.openmotion }, register: async () => {await withLock(configFile + '.openmotion.lock', async () => {const config = await readJSON(configFile) || {}; check(config);await writeJSON(configFile, { ...config, mcpServers: { ...config.mcpServers, openmotion: transport } });@@ -76,7 +77,14 @@ export async function hostPlan(options, home, launcher, previous) {try { await access(desktop); dsh = desktop; } catch {}}metadata.configFile = configFile; metadata.profile = profile; metadata.bundleDirectory = bundleDirectory; metadata.skillsDirectory = path.join(bundleDirectory, 'skills'); metadata.layout = 'deepseek';- return { host, skillsDirectory: path.join(bundleDirectory, 'skills'), layout: 'deepseek', metadata, register: async () => {+ return { host, skillsDirectory: path.join(bundleDirectory, 'skills'), layout: 'deepseek', metadata,+ readConnection: async () => {+ if (!dependency) return null;+ const patch = await readJSON(path.join(bundleDirectory, 'cordis.patch.yml'));+ assert(patch === null || Array.isArray(patch), 'Invalid managed Harness MCP bundle. Run setup for the same host, home and profile to repair it.');+ const configured = patch?.flatMap(item => item.insert || []).find(item => item.id === 'mcp-openmotion')?.config;+ return configured && { transport: { ...configured, type: configured.transport } };+ }, register: async () => {await runFile(dsh, ['plugin', '--profile', profile, 'add', bundleDirectory, '--ignore-scripts'], { env: { ...process.env, DSH_HOME: dshHome } });}, writeBundle: async (stage, appRoot, version) => {await writeJSON(path.join(stage, 'package.json'), { name: bundleName, version, private: true, type: 'module', files: ['cordis.patch.yml'], dsh: { bundle: { patch: './cordis.patch.yml' } } });diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjsindex 02841d2a..fedf8966 100644--- a/scripts/npm-installer.mjs+++ b/scripts/npm-installer.mjs@@ -9,6 +9,7 @@ import { parseArgs } from 'node:util';import { canonical, extractArchive, nativeComponents, obtainAsset, readJSON, relativePath, runFile, withLock, writeAtomic, writeJSON } from './runtime-assets.mjs';import { ensureNativeRuntime, startNativePreparation } from './npm-runtime.mjs';import { hosts, hostPlan, skillTargets, obsoleteSkills, checkSkillOwner, copyHostSkills } from './npm-hosts.mjs';+import { checkTransport, redact } from './check-installed-mcp.mjs';// Keep ownership stable so earlier local installations remain upgradable.export const managedBy = '@openmotion/installer';@@ -18,6 +19,7 @@ const contains = (parent, child) => { const rel = path.relative(parent, child);const usage = `Usage:openmotion setup --host <${hosts.join('|')}> [options]openmotion prepare [--home DIR]+ openmotion diagnose --host <${hosts.join('|')}> [--home DIR] [host options]openmotion --versionSelect the current Agent host explicitly; installed CLIs do not identify the current host.@@ -35,6 +37,8 @@ Setup options:Setup starts native preparation in the background; editing does not wait for it.Use prepare to wait explicitly for every video component or retry failed preparation.Refresh the selected host's Tools/Skills; registration alone does not prove loading.+Diagnose checks the installed host configuration and probes its MCP command without changing configuration.+It does not reconnect the host; follow its recovery guidance and verify a read in the active Agent chat.Use separate host configuration, home, data and Skills paths for test candidates.-h, --help Show this help without installing or changing configuration--version Show this package's version`;@@ -149,6 +153,33 @@ export async function setup(options) {});}+export async function diagnose(options) {+ let stage = 'installation';+ const host = options.host || 'codex';+ const recovery = host === 'claude'+ ? 'After correcting the reported cause, open /mcp in the current Claude Code session and select Reconnect for openmotion.'+ : `After correcting the reported cause, refresh or reconnect openmotion in the current ${host} host${options.profile ? ' profile ' + options.profile : ''}.`;+ try {+ const environment = (await readJSON(bundledManifest))?.templateEnvironment;+ const home = await canonical(options.home || defaultHome(environment));+ const state = await readJSON(path.join(home, 'install.json'));+ assert(state?.managedBy === managedBy, 'Run setup for the selected host and installation home first.');+ assert(state.hosts?.[host] || host === 'codex' && state.skillsDirectory, 'This installation is not registered for the selected host.');+ stage = 'host_configuration';+ const saved = state.hosts?.[host];+ const plan = await hostPlan({ ...options, skillsDirectory: saved?.skillsDirectory, profile: options.profile || saved?.profile }, home, state.launcher, state);+ const connection = plan.readConnection ? await plan.readConnection() : plan.connection;+ stage = 'mcp_probe';+ const expectedTools = (await readJSON(path.join(state.appRoot, 'shared/mcp-profiles.json'))).phase1.tools;+ const checked = checkTransport(connection, state.version, { expectedTools, dataDirectory: state.dataDirectory });+ return { status: 'passed', host, ...checked, hostSessionVerified: false,+ nextAction: 'Call motion_get_project through the active host connection and verify the original project and version. This independent probe does not verify the active chat connection. If that chat still lacks Motion tools: ' + recovery };+ } catch (error) {+ return { status: 'failed', host, stage, code: error.code || 'MCP_DIAGNOSIS_FAILED', message: redact(error.message, process.env),+ hostSessionVerified: false, nextAction: recovery + ' Keep existing projects and exports; do not create replacement work or blindly replay a mutation.' };+ }+}+async function main() {const { positionals, values } = parseArgs({ allowPositionals: true, options: {manifest: { type: 'string' }, home: { type: 'string' }, 'data-dir': { type: 'string' }, 'skills-dir': { type: 'string' }, host: { type: 'string' }, codex: { type: 'string' }, claude: { type: 'string' }, dsh: { type: 'string' }, profile: { type: 'string' },@@ -166,6 +197,10 @@ async function main() {assert(state?.managedBy === managedBy, 'Run setup first');await ensureNativeRuntime(state.appRoot);console.log('Pinned FFmpeg, ffprobe and browser are ready.');- } else throw new Error('Supported commands: setup, prepare');+ } else if (command === 'diagnose') {+ const result = await diagnose({ home: values.home, host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile });+ console.log(JSON.stringify(result, null, 2));+ if (result.status !== 'passed') process.exitCode = 1;+ } else throw new Error('Supported commands: setup, prepare, diagnose');}if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) main().catch(error => { console.error(error.message + '\nRun openmotion --help for supported hosts and installation options.'); process.exitCode = 1; });diff --git a/scripts/package-npm.mjs b/scripts/package-npm.mjsindex 9609275d..d9970db7 100644--- a/scripts/package-npm.mjs+++ b/scripts/package-npm.mjs@@ -95,7 +95,7 @@ export async function packageNpm(output = path.join(root, 'dist/npm-local'), ver}await writeJSON(path.join(application, 'shared/template-config.json'), templateConfig);const skills = (await readdir(path.join(application, 'skills'))).sort();- for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));+ for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs', 'check-installed-mcp.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));await chmod(path.join(installer, 'scripts/npm-installer.mjs'), 0o755);const installerPkg = JSON.parse(await readFile(path.join(root, 'packages/npm/package.json'), 'utf8'));assert.equal(installerPkg.private, true, 'Keep the source package protected; publish only an explicitly versioned artifact');diff --git a/shared/integration.ts b/shared/integration.tsindex 5a1706b2..43686c4f 100644--- a/shared/integration.ts+++ b/shared/integration.ts@@ -107,6 +107,7 @@ ${integrationConfig(info, host).text}\`\`\`配置中的绝对路径、MOTION_DATA_DIR 和 PORT 来自正在运行的服务,不要换成其他副本。必要时新建会话加载工具。通过 initialize 和 tools/list 确认工具加载,再调用 motion_get_project,核对返回的 dataDirectory。网页可达或复制配置不代表 MCP 已连接。只验证接入时不要修改工程。+If tools are missing, inspect this host's server status and startup output before authoring. Follow the connection diagnosis and recovery section in the shared production guide. A separate command-line probe cannot reconnect or verify this chat; after the host reconnects, read the expected data directory and original project/version through its actual MCP connection.${host === 'deepseek' ? '\n将上方条目合并到 Harness 当前配置,保留其他插件。配置模型后重新加载会话,验证工具 mcp__motion__motion_get_project;以工具列表中的实际名称为准。MCP 启动不需要 DeepSeek 模型 API Key,模型凭据由 Harness 自身管理。官方配置:https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/mcp/mcp-client/README.md\n' : ''}## 工具diff --git a/skills/motion-production/references/context.md b/skills/motion-production/references/context.mdindex b52dbd25..4598b953 100644--- a/skills/motion-production/references/context.md+++ b/skills/motion-production/references/context.md@@ -15,6 +15,8 @@ Agent 结合当前目标、保持项与工程状态选择本轮入口;工程通过 npm 安装的平铺 Skill 可读取入口旁的 `openmotion-install.json`:`runtimeRoot` 指向应用和共享 `docs/`,不要从当前工程猜测服务路径。完整包或薄插件仍按其 `scope.json.runtimeRoot` / 已注册启动配置定位;五个入口的相对参考保持同一技能目录布局。+If Motion tools are unavailable, apply the [connection diagnosis and recovery rules](production.md#tool-transport-and-workspace-readiness) before creating or importing work. Use the installed host/home identity, retain the actual connection error and verify recovery through a real host MCP read; a separate CLI probe cannot confirm the current chat connection.+## 先补齐阅读缺口,再执行当前范围每轮先复用会话或已有 `STATE.md` 中的**已读文档**,再计算“本次必需 − 正文仍在上下文中的已读文档”。只读取差集。独立读取可以并行,但长文档应按外层工具的实际输出预算分批或分段,检查模型收到的结果是否截断,不能只看命令成功或完整 stdout。后续章节再次提到“读取”同一参考,表示应用其规范,不是重新加载全文。diff --git a/skills/motion-production/references/native.md b/skills/motion-production/references/native.mdindex a4272220..4bf08035 100644--- a/skills/motion-production/references/native.md+++ b/skills/motion-production/references/native.md@@ -18,6 +18,8 @@ The first output of original creation, reference-video recreation and editable-tThe Tool runs lint and selects an existing project in Studio; it does not create a project or open the host browser. Preserve the URL's embed/query/hash, verify that the intended project and current content loaded, and reuse its browser tab on continued work. If lint fails, fix the reported source problem before retrying. If preview or browser capability is unavailable, provide the project URL when available and state the concrete gap; report the page as opened only after observing it. Do not substitute the system `open` command, AppleScript or a separately launched visible browser for the host's browser. For an independent folder/ZIP, use a supported managed-project handoff if available; the public MCP has no general folder/ZIP adoption Tool. Preserve the actual source and report that limitation rather than opening an unrelated carrier.+Preview preflight, export preflight and the OpenMotion command `node <runtimeRoot>/scripts/lint-project.mjs <runtimeRoot> <projectDirectory>` use the native linter with `host: "studio"`. Structural errors therefore fail before the editor is opened or rendering begins; ordinary warnings remain non-blocking. A direct upstream `hyperframes lint` still uses its own CLI warning policy and is not proof that Studio will accept a project.+### Continuing editsEvery content-editing turn saves the result and requests its preview in the same host chat. Reuse the project and native tab. Default `presentation:"foreground"` preserves the user's current chat: show the right panel when this chat is active; otherwise queue it until the user returns. Before writing, confirm project ownership and the current source/version; show the target when this chat is active. Apply this shared rule across production, director, template and recreation edits.diff --git a/skills/motion-production/references/production.md b/skills/motion-production/references/production.mdindex 15a49ee4..7ae0c90d 100644--- a/skills/motion-production/references/production.md+++ b/skills/motion-production/references/production.md@@ -25,6 +25,15 @@ Before opening a project for an Agent workflow, call `motion_get_project` througExisting phase-one MCP connections automatically reuse a compatible backend after plugin updates, keeping the same workspace and running exports. Version/build differences alone do not require reconnecting: the backend must advertise the same phase-one API protocol and the requested Tool. For `EDITOR_RUNTIME_INCOMPATIBLE`, compare the expected/actual identity and update the incompatible components together when idle; internal legacy connections may also return `MCP_RUNTIME_RELOAD_REQUIRED`. A transport already closed by the host requires host reconnection. Do not stop a compatible backend or silently substitute shell/HTTP exports for failed MCP calls. Preserve existing projects and completed jobs, and query an applicable export before creating another.+When Motion tools are missing or a connection fails:++1. Read the selected host's server status and startup output. An empty tool search does not distinguish an unregistered server, a disabled connection, startup failure or discovery still in progress. Keep the actual error; do not infer the cause from a browser URL or a running backend.+2. For an npm installation, read `runtimeRoot`, `installHome` and `host` from the installed Skill's `openmotion-install.json` or `scope.json`. Run `node <runtimeRoot>/scripts/npm-installer.mjs diagnose --host <host> --home <installHome>` with argument-safe paths; preserve the selected profile and CLI overrides where needed. It checks that host's owned configuration, initializes an independent MCP process, checks the installed tool list and reads the expected data directory. It does not verify or reconnect the current chat. For a source/plugin installation without `installHome`, inspect the host's actual registered command and output; do not guess an npm home or run setup over an unrelated installation.+3. Correct the reported cause before retrying. Missing runtimes, invalid paths, disabled servers and incompatible versions need their specific fix. Use the host's supported refresh/reconnect action; in Claude Code's interactive session use the server's Reconnect action in `/mcp`. If the host exposes no recovery capability, give that concrete user action. Do not claim to reconnect by starting a separate shell process or repeatedly reinstalling. Allow one safe read retry after a transient failure or completed recovery; if it still fails, report the error and recovery action rather than looping.+4. Through the recovered host MCP connection, call `motion_get_project`, confirm its data directory and the original project's identity/current version, then resume this task. A passed independent probe is not host recovery. Query existing jobs and preserve request IDs before deciding whether a mutation needs retrying; never create replacement work to hide a connection failure.++If only an independent folder can be produced, state that the editable Studio handoff is unavailable. Continue that delivery only within the user's accepted scope; do not report the project as open or directly editable in Studio without observing it.+1. Reuse complete guidance already read. Installed Skills and MCP resources/read provide the same documents; production start only routes a task that lacks a specialist. Changes to existing content use [edit workflow](edit.md). Missing instructions/source reads return to the model before dependent writes.2. Reuse the target projectId or explicitly create a new one. Read its current revision and content version. No global most-recent project fallback. Five is a list page size, not a retention policy.3. Use returned asset paths and native HTML/CSS/JS. Import and file save are separate operations. Images/footage/music generation belongs to the host's available tools or Studio; no generation Tool is exposed by this phase-one MCP package. Missing media capabilities must be stated.diff --git a/tests/lint.test.ts b/tests/lint.test.tsnew file mode 100644index 00000000..66e65f07--- /dev/null+++ b/tests/lint.test.ts@@ -0,0 +1,52 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { lintProject } from '@hyperframes/core/lint';+import { fixture } from './fixtures.ts';+import { Phase1Service } from '../phase1.ts';+import { inspectProject, pluginRoot, runHyperframes } from '../hyperframes.ts';+import { renderNext } from '../server.ts';++test('Motion lint and preview reject the same structural errors as Studio before opening or rendering', () => fixture(async store => {+ let opened = 0;+ const service = new Phase1Service(store, pluginRoot, {+ origin: () => 'http://127.0.0.1:4173', nativeUrl: () => undefined, openProject: async () => { opened++; },+ mutation: async task => task(), cancel: async () => {},+ });+ const project = await service.call('motion_create_project', { requestId: 'create', projectType: 'natural_language', title: 'Lint compatibility', requirements: 'An editable film' });+ const directory = store.projectDirectoryFor(project.projectId);+ const original = await readFile(path.join(directory, 'index.html'), 'utf8');+ const nested = '<section id="scene" data-start="0" data-duration="10" data-track-index="1"><div id="content">Nested scene</div></section>';+ const invalid = original.replace('</div>', nested + '</div>');+ const saved = await service.call('motion_edit_project', { projectId: project.projectId, requestId: 'invalid', expectedRevision: project.revision,+ expectedVersionId: project.currentVersionId, files: [{ path: 'index.html', content: invalid }] });+ assert.equal((await runHyperframes(pluginRoot, directory, ['lint', '.', '--json'])).code, 0, 'the upstream CLI only warns about this structure');+ const checked = await inspectProject(pluginRoot, directory, 'lint');+ const studio = await lintProject(directory, undefined, { host: 'studio' });+ assert.equal(checked.exitCode, 1);+ assert.equal(checked.result.errorCount, studio.totalErrors);+ assert.deepEqual(checked.result.findings, studio.results.flatMap(entry => entry.result.findings));+ assert.ok(checked.result.findings.some(item => item.code === 'nested_structure_needs_subcomposition' && item.severity === 'error' && item.file && item.line && item.fixHint));+ await assert.rejects(service.call('motion_open_preview', { projectId: project.projectId }), /PROJECT_VALIDATION_FAILED.*nested_structure_needs_subcomposition/);+ assert.equal(opened, 0);+ assert.equal(await readFile(path.join(directory, 'index.html'), 'utf8'), invalid);+ const requested = await service.call('motion_export_request', { projectId: project.projectId, requestId: 'export-invalid', expectedRevision: saved.revision, versionId: saved.version.versionId, audio: 'silent' });+ await renderNext(store, pluginRoot);+ const failed = await store.job(requested.job.id);+ assert.equal(failed?.state, 'failed');+ assert.match(failed?.error || '', /nested_structure_needs_subcomposition/);+ const fixed = await service.call('motion_edit_project', { projectId: project.projectId, requestId: 'fixed', expectedRevision: saved.revision,+ expectedVersionId: saved.version.versionId, files: [+ { path: 'index.html', content: original.replace('</div>', '<div id="scene" data-composition-id="scene" data-composition-src="compositions/scene.html" data-start="0" data-duration="10" data-track-index="1"></div></div>').replace('</style>', '#main{transition:opacity 1s}</style>') },+ { path: 'compositions/scene.html', content: '<template><div id="root" data-composition-id="scene" data-width="1920" data-height="1080" data-start="0" data-duration="10" data-no-timeline>' + nested + '</div></template>' },+ ] });+ const valid = await service.call('motion_open_preview', fixed.previewHandoff.nextAction.arguments);+ assert.equal(valid.preflight.errorCount, 0);+ assert.ok(valid.preflight.findings.some(item => item.code === 'css_transition_used' && item.severity === 'warning'));+ assert.equal(opened, 1, 'ordinary warnings must not block the editor');+}, false));++test('Motion lint retains cancellation before starting its isolated worker', () => fixture(async store => {+ await assert.rejects(inspectProject(pluginRoot, store.projectDirectory, 'lint', AbortSignal.abort()), /COMMAND_CANCELLED/);+}));diff --git a/tests/mcp-config.test.ts b/tests/mcp-config.test.tsindex 294d0d88..b5121161 100644--- a/tests/mcp-config.test.ts+++ b/tests/mcp-config.test.ts@@ -1,6 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';-import { readFile } from 'node:fs/promises';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';import { checkTransport } from '../scripts/check-installed-mcp.mjs';@@ -17,5 +18,46 @@ test('packaged relative cwd launches exactly as the Codex host resolves it, with});test('installation check catches the exact installed placeholder bug before reporting success', () => {assert.throws(() => checkTransport({ enabled: true, transport: { type: 'stdio', command: 'node',- args: ['--experimental-strip-types', '${PLUGIN_ROOT}/mcp.ts'], cwd: path.join(root, '${PLUGIN_ROOT}') } }, VERSION), /未展开占位符/);+ args: ['--experimental-strip-types', '${PLUGIN_ROOT}/mcp.ts'], cwd: path.join(root, '${PLUGIN_ROOT}') } }, VERSION), /unexpanded placeholder/);+});++test('transport diagnostics distinguish configuration, startup, protocol and workspace failures without leaking credentials', async t => {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-mcp-diagnose-'));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const filename = path.join(directory, 'server.mjs');+ await writeFile(filename, `import {createInterface} from 'node:readline';+if(process.env.PROBE_FAILURE){console.error('startup rejected: '+process.env.API_TOKEN);process.exit(1)}+for await(const line of createInterface({input:process.stdin})){+ const q=JSON.parse(line);if(q.id===undefined)continue;+ const result=q.id===1?{serverInfo:{version:'1.2.3'}}:q.id===2?{tools:[{name:'motion_get_project'}]}:{structuredContent:{dataDirectory:process.env.PROBE_DIRECTORY}};+ console.log(JSON.stringify({jsonrpc:'2.0',id:q.id,result}));+}`);+ const config = { enabled: true, transport: { type: 'stdio', command: process.execPath, args: [filename], env: { PROBE_DIRECTORY: directory } } };+ const options = { expectedTools: ['motion_get_project'], dataDirectory: directory };+ assert.equal(checkTransport(config, '1.2.3', options).dataDirectory, directory);+ assert.deepEqual(checkTransport({ transport: { ...config.transport, cwd: null, env: null } }, '1.2.3', { expectedTools: options.expectedTools }).tools, ['motion_get_project']);+ assert.throws(() => checkTransport(null, '1.2.3', options), { code: 'MCP_NOT_REGISTERED' });+ assert.throws(() => checkTransport({ ...config, enabled: false }, '1.2.3', options), { code: 'MCP_DISABLED' });+ assert.throws(() => checkTransport({ ...config, transport: { ...config.transport, cwd: path.join(directory, 'missing') } }, '1.2.3', options), { code: 'MCP_CONFIG_INVALID' });+ assert.throws(() => checkTransport({ ...config, transport: { ...config.transport, command: path.join(directory, 'missing-node') } }, '1.2.3', options), { code: 'MCP_STARTUP_FAILED' });+ assert.throws(() => checkTransport(config, '9.9.9', options), { code: 'MCP_VERSION_MISMATCH' });+ assert.throws(() => checkTransport(config, '1.2.3', { ...options, expectedTools: ['missing_tool'] }), { code: 'MCP_TOOLS_MISMATCH' });+ assert.throws(() => checkTransport(config, '1.2.3', { ...options, dataDirectory: path.join(directory, 'other') }), { code: 'MCP_WORKSPACE_MISMATCH' });+ assert.throws(() => checkTransport({ ...config, transport: { ...config.transport, env: { PROBE_FAILURE: '1', API_TOKEN: 'fixture-secret-value' } } }, '1.2.3', options), error => {+ assert.equal(error.code, 'MCP_STARTUP_FAILED');+ assert.match(error.message, /startup rejected/);+ assert.doesNotMatch(error.message, /fixture-secret-value/);+ return true;+ });+ await writeFile(filename, 'console.log("non-protocol log");');+ assert.throws(() => checkTransport(config, '1.2.3', options), { code: 'MCP_PROTOCOL_INVALID' });+ await writeFile(filename, 'console.error(\'API_KEY="embedded-fixture-secret"\');process.exit(1);');+ assert.throws(() => checkTransport(config, '1.2.3', options), error => {+ assert.doesNotMatch(error.message, /embedded-fixture-secret/);+ return true;+ });+});++test('an unresponsive MCP probe times out without retrying or waiting indefinitely', { timeout: 20_000 }, () => {+ assert.throws(() => checkTransport({ transport: { type: 'stdio', command: process.execPath, args: ['-e', 'setInterval(()=>{},1000)'] } }, '1.2.3', { expectedTools: ['motion_get_project'] }), { code: 'MCP_PROBE_TIMEOUT' });});diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.tsindex 0dc61e61..1b3b5425 100644--- a/tests/npm-installer.test.ts+++ b/tests/npm-installer.test.ts@@ -5,10 +5,10 @@ import path from 'node:path';import { tmpdir } from 'node:os';import { pathToFileURL } from 'node:url';import { fileURLToPath } from 'node:url';-import { localManifest, setup } from '../scripts/npm-installer.mjs';+import { diagnose, localManifest, setup } from '../scripts/npm-installer.mjs';import { hosts } from '../scripts/npm-hosts.mjs';import { configureNativeEnvironment, ensureNativeRuntime, nativeConfiguration } from '../scripts/npm-runtime.mjs';-import { obtainAsset, relativePath, runFile, sha256, withLock, writeJSON } from '../scripts/runtime-assets.mjs';+import { canonical, obtainAsset, relativePath, runFile, sha256, withLock, writeJSON } from '../scripts/runtime-assets.mjs';const dummyRuntime = () => ({ targets: { fixture: { platform: process.platform, arch: process.arch,browser: { url: 'https://example.invalid/browser.zip', sha256: 'b'.repeat(64), executable: 'browser/chrome' },@@ -37,13 +37,14 @@ async function setupFixture(t: any) {for (const name of ['mcp.ts', 'scripts/npm-runtime.mjs', 'studio/build/index.html', 'README.md', 'AGENTS.md', 'CLAUDE.md']) await writeFile(path.join(application, name), 'fixture');await writeFile(path.join(application, 'skills/motion-production/SKILL.md'), '---\nname: motion-production\ndescription: fixture\n---\nFixture');await writeJSON(path.join(application, 'shared/template-config.json'), { environment: 'prod' });+ await cp(new URL('../shared/mcp-profiles.json', import.meta.url), path.join(application, 'shared/mcp-profiles.json'));await writeJSON(path.join(application, 'package.json'), { name: 'motion-fixture', version: '1.2.3', private: true });await writeJSON(path.join(application, 'package-lock.json'), { name: 'motion-fixture', version: '1.2.3', lockfileVersion: 3, packages: { '': { name: 'motion-fixture', version: '1.2.3' } } });const manifest = path.join(directory, 'release.json');await writeJSON(manifest, { schemaVersion: 1, version: '1.2.3', application: await archive(directory, application, 'application'), runtime: dummyRuntime() });const codex = path.join(directory, 'codex'), config = path.join(directory, 'codex.json');await writeJSON(config, { unrelated: { transport: { command: 'keep-this' } } });- await writeFile(codex, `#!${process.execPath}\nimport fs from 'node:fs';\nconst file=${JSON.stringify(config)};\nconst state=JSON.parse(fs.readFileSync(file,'utf8'));\nconst args=process.argv.slice(2);\nif(args[1]==='get'){if(!state.openmotion){console.error(\"No MCP server named 'openmotion' found.\");process.exit(1);}console.log(JSON.stringify(state.openmotion));}\nelse if(args[1]==='add'){if(state.fail){console.error('registration failed');process.exit(1);}state.openmotion={transport:{command:args[4],args:args.slice(5)}};fs.writeFileSync(file,JSON.stringify(state));}\n`, { mode: 0o755 });+ await writeFile(codex, `#!${process.execPath}\nimport fs from 'node:fs';\nconst file=${JSON.stringify(config)};\nconst state=JSON.parse(fs.readFileSync(file,'utf8'));\nconst args=process.argv.slice(2);\nif(args[1]==='get'){if(!state.openmotion){console.error(\"No MCP server named 'openmotion' found.\");process.exit(1);}console.log(JSON.stringify(state.openmotion));}\nelse if(args[1]==='add'){if(state.fail){console.error('registration failed');process.exit(1);}state.openmotion={transport:{type:'stdio',command:args[4],args:args.slice(5)}};fs.writeFileSync(file,JSON.stringify(state));}\n`, { mode: 0o755 });await chmod(codex, 0o755);return { directory, application, home, skillsDirectory, manifest, codex, config };}@@ -51,7 +52,7 @@ async function setupFixture(t: any) {test('bundled CLI installs without a sidecar manifest, isolates DEV defaults and rejects a mixed-environment home', async t => {const options = await setupFixture(t), bundle = path.join(options.directory, 'bundle');await mkdir(path.join(bundle, 'scripts'), { recursive: true }); await mkdir(path.join(bundle, 'payload'));- for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs']) {+ for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs', 'check-installed-mcp.mjs']) {await cp(new URL('../scripts/' + file, import.meta.url), path.join(bundle, 'scripts', file));}await writeJSON(path.join(bundle, 'package.json'), { version: '1.2.3', type: 'module' });@@ -179,7 +180,7 @@ test('separate ffmpeg and ffprobe archives validate independently and recover witest('CLI help and version cover every host without reading a manifest or changing an installation', async t => {const directory = await fixture(t), cli = fileURLToPath(new URL('../scripts/npm-installer.mjs', import.meta.url));const missing = path.join(directory, 'missing.json'), home = path.join(directory, 'app');- for (const command of [['--help'], ['setup', '-h'], ['prepare', '--help']]) {+ for (const command of [['--help'], ['setup', '-h'], ['prepare', '--help'], ['diagnose', '--help']]) {const help = await runFile(process.execPath, [cli, ...command, '--manifest', missing, '--home', home]);for (const host of hosts) assert(help.includes(host), host);for (const option of ['--profile', '--skills-dir', '--codex', '--claude', '--dsh']) assert(help.includes(option), option);@@ -196,6 +197,62 @@ test('npm bin symlink executes the CLI instead of silently exiting', { skip: proawait assert.rejects(runFile(process.execPath, [link, 'prepare', '--home', directory]), /Run setup first/);});+test('diagnose verifies each installed host without changing its configuration or projects', { skip: process.platform === 'win32' }, async t => {+ const options = await setupFixture(t), installed = await setup(options);+ const expected = JSON.parse(await readFile(new URL('../shared/mcp-profiles.json', import.meta.url), 'utf8')).phase1.tools;+ await writeFile(installed.launcher, `import {createInterface} from 'node:readline';+for await(const line of createInterface({input:process.stdin})){+ const q=JSON.parse(line);if(q.id===undefined)continue;+ const result=q.id===1?{serverInfo:{version:'1.2.3'}}:q.id===2?{tools:${JSON.stringify(expected)}.map(name=>({name}))}:{structuredContent:{dataDirectory:process.env.PROBE_DIRECTORY||${JSON.stringify(installed.dataDirectory)}}};+ console.log(JSON.stringify({jsonrpc:'2.0',id:q.id,result}));+}`);+ await mkdir(installed.dataDirectory, { recursive: true });+ const project = path.join(installed.dataDirectory, 'keep.txt'); await writeFile(project, 'existing project');+ const stateFile = path.join(options.home, 'install.json');+ const state = JSON.parse(await readFile(stateFile, 'utf8'));+ const transport = { type: 'stdio', command: process.execPath, args: [installed.launcher] };+ const previous = Object.fromEntries(['CLAUDE_CONFIG_DIR', 'WORKBUDDY_CONFIG_DIR', 'DSH_HOME'].map(key => [key, process.env[key]]));+ t.after(() => { for (const [key, value] of Object.entries(previous)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } });+ process.env.CLAUDE_CONFIG_DIR = path.join(options.directory, 'claude');+ process.env.WORKBUDDY_CONFIG_DIR = path.join(options.directory, 'buddy');+ process.env.DSH_HOME = path.join(options.directory, 'dsh');+ const claude = path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json');+ const buddy = path.join(process.env.WORKBUDDY_CONFIG_DIR, 'mcp.json');+ const profile = path.join(process.env.DSH_HOME, 'profiles/custom/package.json');+ const bundle = path.join(options.home, 'hosts/deepseek');+ for (const directory of [path.dirname(claude), path.dirname(buddy), path.dirname(profile), bundle]) await mkdir(directory, { recursive: true });+ await writeJSON(claude, { mcpServers: { openmotion: transport } });+ await writeJSON(buddy, { mcpServers: { openmotion: transport } });+ await writeJSON(profile, { dependencies: { 'dsh-plugin-openmotion-local': 'file:' + bundle } });+ const patch = path.join(bundle, 'cordis.patch.yml');+ await writeJSON(patch, [{ insert: [{ id: 'mcp-openmotion', config: { ...transport, transport: 'stdio' } }] }]);+ state.hosts.claude = { configFile: await canonical(claude), skillsDirectory: options.skillsDirectory };+ state.hosts.workbuddy = { configFile: await canonical(buddy), skillsDirectory: options.skillsDirectory };+ state.hosts.deepseek = { configFile: await canonical(profile), profile: 'custom', skillsDirectory: path.join(bundle, 'skills') };+ await writeJSON(stateFile, state);+ const files = [options.config, claude, buddy, profile, patch, stateFile, project, installed.launcher];+ const before = await Promise.all(files.map(file => readFile(file, 'utf8')));+ for (const host of hosts) {+ const result = await diagnose({ home: options.home, host, codex: options.codex });+ assert.equal(result.status, 'passed', JSON.stringify(result));+ assert.equal(result.hostSessionVerified, false, 'an independent process cannot confirm the active chat');+ assert.equal(result.dataDirectory, installed.dataDirectory);+ assert.deepEqual(result.tools, expected);+ assert.match(result.nextAction, /motion_get_project/);+ }+ assert.deepEqual(await Promise.all(files.map(file => readFile(file, 'utf8'))), before);+ const configured = JSON.parse(await readFile(options.config, 'utf8'));+ configured.openmotion.enabled = false; await writeJSON(options.config, configured);+ assert.equal((await diagnose({ home: options.home, host: 'codex', codex: options.codex })).code, 'MCP_DISABLED');+ delete configured.openmotion; await writeJSON(options.config, configured);+ const missing = await diagnose({ home: options.home, host: 'codex', codex: options.codex });+ assert.equal(missing.code, 'MCP_NOT_REGISTERED');+ assert.match(missing.nextAction, /do not create replacement/);+ const cli = fileURLToPath(new URL('../scripts/npm-installer.mjs', import.meta.url));+ await assert.rejects(runFile(process.execPath, [cli, 'diagnose', '--host', 'codex', '--codex', options.codex, '--home', options.home]), /MCP_NOT_REGISTERED/);+ assert.equal(await readFile(project, 'utf8'), 'existing project');+});+test('setup installs complete Skills and MCP without waiting for native downloads and preserves repeated-install data', { skip: process.platform === 'win32' }, async t => {clearNativeEnvironment(t);const options = await setupFixture(t);diff --git a/tests/npm-package.test.ts b/tests/npm-package.test.tsindex b094a822..f128c555 100644--- a/tests/npm-package.test.ts+++ b/tests/npm-package.test.ts@@ -98,6 +98,8 @@ test('test npm artifacts contain their application, locked manifest and no bundlassert(entries.includes('skills/motion-recreate/references/verify.md'));assert(entries.includes('studio/build/index.html'));assert(entries.includes('shared/editor-launch.pl'), 'macOS shared editor launcher must ship');+ for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);+ await readFile(path.join(installer, 'package/scripts/check-installed-mcp.mjs'));assert(entries.includes('shared/workflow-entry.js'), 'Workflow discovery must ship with the five Skills');assert(!entries.split('\n').some(file => file.split('/').some(part => part.startsWith('._'))), 'Do not distribute macOS file metadata');assert(entries.includes('template-library/NOTICE.md'));