mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 06:59:39 +08:00
* feat(game-studio): add Game Studio tab, local game service and MCP game tools Game Studio page with template waterfall, My games sidebar, landscape/portrait choice and auto-open of Agent-created drafts; local game projects service with rooms, playtest, simulate and cover capture; openmotion_game_* MCP tools; openmotion-game handbook ported from the MIT higgsfield-ai/skills handbook; coop-3d and arcade-2d starter kits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): register game tools, dedupe handbook provenance, fix search and code reload Register the openmotion_game_* tools in MCP counts, onboarding scenarios and tracking dimensions; keep them out of WebMCP. Move the shared MIT provenance note to PROVENANCE.md. Studio search now matches localized titles, and the Code tab reloads its source. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): harden game service and fix invite copy and code fullscreen Case-insensitive reserved paths and request-id saves; sandbox CSP for game documents; WebSocket fragment count, time and buffer limits; AST-based determinism check; single-player start for playtest and cover capture; atomic batch writes with rollback. Studio: clipboard-write for embedded games and Code-tab fullscreen on the stage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): trim KayKit characters below 1 MiB for the storage policy Keep 12 common clips per character (meshes, skin and bones unchanged) so Knight.glb and Mage.glb stay ordinary Git files; update the character README and the 3D handbook. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(game-studio): hand drafts to the user's Agent; derive the WebSocket test nonce Drafts show "Waiting for your Agent" until the Agent sets building. The draft page offers Copy instruction and Open in Codex (prefill only) with the full instruction: game id, brief and steps. GET /api/games/:id/handoff returns it for any workspace draft, including drafts created elsewhere and remixes; creation now includes the portrait layout in the instruction. Tests derive the RFC 6455 sample nonce at runtime so release scanning stays strict. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): spin the detail status only while the Agent is building Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(game-studio): exercise all twelve game tools in the packaged MCP smoke test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): vendor acorn so packaged builds can run the game rules sandbox Packaged builds ship without node_modules, so openmotion_game_simulate failed with "Cannot find module 'acorn'". Ship acorn 8.19.0 (MIT, license in the file header) under shared/vendor and import it relatively. Verified in a node_modules-free copy of the phase1 file list: create plus reference simulation wins at tick 809. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): resolve browser and trailer dependencies from the host runtime root Packaged builds install npm dependencies under the data directory, so playtest, cover capture and trailer recording failed with "Cannot find module 'puppeteer-core'" and the trailer looked for HyperFrames in the plugin folder. Server and phase1 hosts now pass their runtime root; puppeteer, HyperFrames checks, the trailer's Phase1Service and render queue use it (source checkouts fall back to the plugin root). Verified in a node_modules-free phase1 file copy: playtest, cover, simulate, publish and a trailer through ready. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): isolate catalog entries, smoke-test solo logic and run the game suite in CI Review follow-ups: - The catalog skips and reports a game folder it cannot read (an orphan or malformed game.json) instead of failing GET /api/games; create and remix remove their folder when a step fails, so a partial create no longer leaves an orphan. - Validation runs the bounded logic.js smoke check for every game with rules. Single-player games follow validateAction as live play does, the loop stops when the game ends, and a kit game missing logic.js is reported. Room checks stay multiplayer-only. - tests/game-projects.test.ts runs in the Distribution browser lane (Chrome and native export cases skip themselves when unavailable) and leaves the unscheduled list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(game-studio): stabilize scrolling and animate build indicator * fix(game-studio): validate runtime before browser discovery Resolve the requested runtime dependencies before detecting Chrome so missing-runtime diagnostics remain deterministic on Linux. Preserve all tests and emit failed Game Studio assertions as GitHub check annotations. * fix(game-studio): stop waiting for network silence during capture Wait for the document load and visible canvas while retaining room, startup and runtime assertions. Add a real polling regression that reproduces the 20-second navigation timeout and verifies successful background responses during capture. --------- Co-authored-by: zhanghuihua <zhanghuihua@huihuideMacBook-Pro.local> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: zhanghuihua <zhanghuihua@Mac.lan> Co-authored-by: stevenguotj <stevenguotj@stevengotjdeMBP.lan>
289 lines
21 KiB
TypeScript
289 lines
21 KiB
TypeScript
import { existsSync } from 'node:fs';
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import { mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { tmpdir } from 'node:os';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { WorkspaceStore } from '../workspace.ts';
|
|
import { getWorkflow, markdownAnchors, readWorkflowResource, resolveGuideFile, workflowLinkAnchors, workflowReferences, workflowRegistry, workflowSections, phase1WorkflowNames } from '../shared/workflow.ts';
|
|
|
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
const workflows = phase1WorkflowNames;
|
|
const productionSections = Object.keys(workflowRegistry.production.sections);
|
|
const entries = Object.entries(workflowRegistry).filter(([name]) => workflows.includes(name)).flatMap(([workflow, definition]) =>
|
|
Object.entries(definition.sections).map(([section, documentId]) => ({ workflow, section, documentId, status: definition.status })));
|
|
|
|
function stdio(directory: string, messages: Record<string, unknown>[], entry = path.join(root, 'mcp.ts')) {
|
|
const child = spawnSync(process.execPath, ['--experimental-strip-types', entry], {
|
|
cwd: directory, input: messages.map(message => JSON.stringify({ jsonrpc: '2.0', ...message })).join('\n') + '\n',
|
|
encoding: 'utf8', env: { ...process.env, MOTION_DATA_DIR: directory }, timeout: 10_000, maxBuffer: 8 * 1024 * 1024,
|
|
});
|
|
assert.equal(child.status, 0, child.stderr);
|
|
const responses = child.stdout.trim().split('\n').map(line => JSON.parse(line));
|
|
assert.equal(responses.length, messages.length);
|
|
return new Map(responses.map(response => [response.id, response.error ? { isError: true, content: [{ text: response.error.message }] } : response.result.contents ? { structuredContent: JSON.parse(response.result.contents[0].text) } : response.result]));
|
|
}
|
|
|
|
function workflowCall(id: number, args?: any) {
|
|
const valid = args === undefined || args && !Array.isArray(args) && typeof args === 'object' && Object.keys(args).every(key => ['workflow', 'section'].includes(key)) && (args.workflow === undefined || typeof args.workflow === 'string') && (args.section === undefined || typeof args.section === 'string');
|
|
return { id, method: 'resources/read', params: { uri: valid ? `openmotion://workflow/${args?.workflow ?? 'production'}/${args?.section ?? 'start'}` : 'invalid' } };
|
|
}
|
|
|
|
test('MCP-only client discovers and reads the packaged workflow without starting a preview', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-workflow-mcp-'));
|
|
try {
|
|
const sections = [...productionSections.slice(0, 5), 'materials'];
|
|
const responses = stdio(directory, [
|
|
{ id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25' } },
|
|
{ id: 2, method: 'tools/list' }, workflowCall(3),
|
|
{ id: 20, method: 'resources/list' },
|
|
{ id: 21, method: 'resources/read', params: { uri: 'motion://workflow/production/materials' } },
|
|
...sections.map((section, index) => workflowCall(index + 4, { section })),
|
|
]);
|
|
assert.match(responses.get(1).instructions, /resources\/read/);
|
|
assert.ok(!responses.get(2).tools.some((tool: any) => tool.name === 'openmotion_get_workflow'));
|
|
assert.ok(responses.get(20).resources.some((resource: { uri: string }) => resource.uri === 'openmotion://workflow/production/materials'));
|
|
assert.equal(responses.get(3).structuredContent.documentId, 'skills/openmotion-production/SKILL.md');
|
|
assert.equal(responses.get(21).structuredContent.documentId, 'skills/openmotion-production/references/materials.md');
|
|
assert.equal(responses.get(21).structuredContent.contentHash, (await getWorkflow('materials')).contentHash);
|
|
for (const [index, section] of sections.entries()) {
|
|
const result = responses.get(index + 4).structuredContent;
|
|
assert.equal(result.workflow, 'production');
|
|
assert.equal(result.section, section);
|
|
assert.ok(result.content.length > 100);
|
|
assert.deepEqual(result.sections, productionSections);
|
|
assert.deepEqual({ ...await getWorkflow(section), workflows }, result);
|
|
}
|
|
const store = new WorkspaceStore(directory);
|
|
assert.match((await store.get()).revision, /^[a-f0-9]{64}$/);
|
|
assert.equal((await store.get()).project, null);
|
|
assert.deepEqual(await readdir(directory), []);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('every workflow document and linked reference is reachable over MCP with canonical identity, without changing an existing project', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-workflow-documents-'));
|
|
try {
|
|
const store = new WorkspaceStore(directory);
|
|
await mkdir(store.projectDirectory);
|
|
await writeFile(path.join(store.projectDirectory, 'index.html'), '<main data-composition-id="existing">Existing work</main>');
|
|
const before = await store.get();
|
|
const filesBefore = await readdir(directory, { recursive: true });
|
|
const responses = stdio(directory, entries.map(({ workflow, section }, index) => workflowCall(index + 1, { workflow, section })));
|
|
const returned = new Map<string, any>();
|
|
const byRoute = new Map<string, any>();
|
|
for (const [index, entry] of entries.entries()) {
|
|
const response = responses.get(index + 1);
|
|
assert.ok(!response.isError, JSON.stringify(response));
|
|
const result = response.structuredContent;
|
|
assert.equal(result.workflow, entry.workflow);
|
|
assert.equal(result.section, entry.section);
|
|
assert.equal(result.status, entry.status);
|
|
assert.equal(result.documentId, entry.documentId);
|
|
assert.equal(result.path, path.join(root, entry.documentId));
|
|
assert.equal(result.content, await readFile(path.join(root, entry.documentId), 'utf8'));
|
|
assert.equal(result.contentHash, createHash('sha256').update(result.content).digest('hex'));
|
|
assert.deepEqual(result.workflows, workflows);
|
|
assert.deepEqual(result.sections, Object.keys(workflowRegistry[entry.workflow as keyof typeof workflowRegistry].sections));
|
|
assert.equal(new Set(result.references.map((reference: { documentId: string }) => reference.documentId)).size, result.references.length);
|
|
if (!returned.has(result.documentId)) returned.set(result.documentId, result);
|
|
byRoute.set(`${result.workflow}/${result.section}`, result);
|
|
}
|
|
for (const document of returned.values()) {
|
|
for (const reference of document.references) {
|
|
const target = byRoute.get(`${reference.workflow}/${reference.section}`);
|
|
assert.ok(target, `${document.documentId} links to an unreachable document`);
|
|
assert.equal(target.documentId, reference.documentId);
|
|
}
|
|
}
|
|
assert.equal(returned.get('skills/openmotion-template-to-video/SKILL.md').status, 'ready');
|
|
assert.equal(returned.get('skills/openmotion-template-to-video/SKILL.md').workflow, 'template');
|
|
assert.equal(returned.get('skills/openmotion-recreate/SKILL.md').status, 'ready');
|
|
assert.equal(returned.get('skills/openmotion-video-to-template/SKILL.md').status, 'ready');
|
|
assert.equal(returned.get('skills/openmotion-video-to-template/SKILL.md').workflow, 'video-to-template');
|
|
for (const route of workflows) {
|
|
if (route === 'game') {
|
|
const refs = returned.get(workflowRegistry.game.sections.start).references;
|
|
assert.ok(refs.some((reference: { documentId: string }) => reference.documentId === 'skills/openmotion-game/references/game-flow.md'));
|
|
assert.ok(refs.some((reference: { documentId: string }) => reference.documentId === 'skills/openmotion-game/references/game-stylization.md'));
|
|
continue;
|
|
}
|
|
assert.ok(returned.get(workflowRegistry[route as keyof typeof workflowRegistry].sections.start).references.some((reference: { documentId: string }) =>
|
|
reference.documentId === 'skills/openmotion-production/references/edit.md'), `${route} must expose the shared edit workflow`);
|
|
assert.ok(returned.get(workflowRegistry[route as keyof typeof workflowRegistry].sections.start).references.some((reference: { documentId: string }) =>
|
|
reference.documentId === 'skills/openmotion-production/references/materials.md'), `${route} must expose the shared material policy`);
|
|
}
|
|
assert.deepEqual(await store.get(), before);
|
|
assert.deepEqual(await readdir(directory, { recursive: true }), filesBefore);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('MCP template delivery exposes a paused zero-second handoff with user playback precedence', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-workflow-opening-frame-'));
|
|
try {
|
|
const responses = stdio(directory, [
|
|
workflowCall(1, { workflow: 'template' }),
|
|
workflowCall(2, { workflow: 'production', section: 'native' }),
|
|
]);
|
|
const template = responses.get(1).structuredContent;
|
|
const native = responses.get(2).structuredContent;
|
|
assert.ok(template.references.some((reference: { documentId: string }) =>
|
|
reference.documentId === native.documentId), 'Template delivery must expose the shared handoff to MCP-only clients');
|
|
assert.match(template.content, /After the playback check[^.]*handoff's paused playback state/i, 'Template delivery must return to the shared paused handoff');
|
|
assert.doesNotMatch(template.content, /opening frame is blank|seek\(0\)/i, 'Template delivery must not restate the shared zero-second rule');
|
|
assert.match(native.content, /pause the preview first[^.]*seek to 0 seconds/i, 'Playback must pause before seeking to zero');
|
|
assert.match(native.content, /paused at 0 seconds[^.]*opening frame is blank[^.]*do not advance/i, 'A blank opening must not move the playhead forward');
|
|
assert.match(native.content, /Before recording display confirmation[\s\S]*?default handoff[^.]*at 0 seconds[^.]*stable[^.]*paused/i, 'Stable paused playback at zero must be checked before confirmation');
|
|
assert.match(native.content, /authored blank opening frame is valid[^.]*unloaded preview is not/i, 'An authored blank frame must remain distinct from a preview that failed to load');
|
|
assert.match(native.content, /explicit user request[^.]*playback[^.]*takes precedence/i, 'Explicit playback requests must retain precedence');
|
|
assert.match(native.content, /explicit playback request[^.]*verify[^.]*requested position or playing state/i, 'Requested playing states must be verified without forcing a pause');
|
|
assert.match(native.content, /observed time[^.]*playback state[^.]*visible content[^.]*display evidence/i, 'Display evidence must identify the observed handoff state');
|
|
assert.match(native.content, /cannot be verified[^.]*confirmation pending/i, 'Unavailable controls or content must not produce a successful display receipt');
|
|
assert.deepEqual(await readdir(directory), [], 'Reading delivery guidance must not create a project');
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('Markdown references resolve across workflows, deduplicate canonical paths, and reject missing internal instructions', () => {
|
|
const documentId = 'skills/openmotion-director/SKILL.md';
|
|
const refs = workflowReferences([
|
|
'[sound](references/sound-narrative.md#anchors)',
|
|
'[sound again](./references/sound-narrative.md?version=1)',
|
|
'[shared context](<../openmotion-production/references/context.md> "Common context")',
|
|
'[actions][script]', '[script]: references/action-script.md',
|
|
'[external](https://example.com/other.md)', '[protocol-relative](//example.com/other.md)', '[anchor](#local)',
|
|
'`[example](not-a-document.md)`', '```markdown', '[example](also-not-a-document.md)', '```',
|
|
].join('\n'), documentId);
|
|
assert.deepEqual(refs, [
|
|
{ workflow: 'director', section: 'sound', documentId: 'skills/openmotion-director/references/sound-narrative.md' },
|
|
{ workflow: 'production', section: 'context', documentId: 'skills/openmotion-production/references/context.md' },
|
|
{ workflow: 'director', section: 'actions', documentId: 'skills/openmotion-director/references/action-script.md' },
|
|
]);
|
|
for (const target of ['missing.md', '../../../outside.md', '/absolute.md', '..%2F..%2Foutside.md']) {
|
|
assert.throws(() => workflowReferences(`[missing](${target})`, documentId), /Unregistered workflow Markdown link/);
|
|
}
|
|
});
|
|
|
|
test('Markdown heading anchors follow rendered slugs and every packaged #fragment link resolves', async () => {
|
|
const headings = [
|
|
'# Check and deliver', '## 1. Export the inspected version', '## 旁白选角与语气', '### `measure` CLI: probe', '## Notes', '## Notes', '## Closed heading ##',
|
|
'## _Emphasis_ and <em>tags</em>', '## `a_b` snake_case', '## _private', '## __init__ hook', '# a', '# a-1', '# a',
|
|
'````markdown', '## Inside a longer fence', '```', '## Still inside', '````', '## After the fence',
|
|
'~~~', '## Unclosed fence hides the rest',
|
|
];
|
|
const anchors = markdownAnchors(headings.join('\n'));
|
|
assert.deepEqual([...markdownAnchors(headings.join('\r\n'))], [...anchors]);
|
|
assert.deepEqual([...anchors], ['check-and-deliver', '1-export-the-inspected-version', '旁白选角与语气', 'measure-cli-probe', 'notes', 'notes-1', 'closed-heading',
|
|
'emphasis-and-tags', 'a_b-snake_case', '_private', 'init-hook', 'a', 'a-1', 'a-2', 'after-the-fence']);
|
|
|
|
const documentId = 'skills/openmotion-director/SKILL.md';
|
|
const links = workflowLinkAnchors([
|
|
'[sound](references/sound-narrative.md#审听与比较)', '[encoded](references/sound-narrative.md#%E5%AE%A1%E5%90%AC%E4%B8%8E%E6%AF%94%E8%BE%83)',
|
|
'[self](#local)', '[whole](references/action-script.md)', '`[code](references/action-script.md#ignored)`', '[external](https://example.com/a.md#b)',
|
|
].join('\n'), documentId);
|
|
assert.deepEqual(links.map(({ documentId, anchor }) => ({ documentId, anchor })), [
|
|
{ documentId: 'skills/openmotion-director/references/sound-narrative.md', anchor: '审听与比较' },
|
|
{ documentId: 'skills/openmotion-director/references/sound-narrative.md', anchor: '审听与比较' },
|
|
{ documentId, anchor: 'local' },
|
|
]);
|
|
|
|
const missing: string[] = [];
|
|
for (const { workflow, section } of entries) {
|
|
const document = await getWorkflow(section, workflow);
|
|
for (const link of workflowLinkAnchors(document.content, document.documentId)) {
|
|
const target = link.documentId === document.documentId ? document : await getWorkflow(link.section, link.workflow);
|
|
if (!markdownAnchors(target.content).has(link.anchor)) missing.push(`${document.documentId}: ${link.href}`);
|
|
}
|
|
}
|
|
assert.deepEqual(missing, []);
|
|
});
|
|
test('MCP rejects unknown routes, invalid route-section pairs and arbitrary paths without creating workspace files', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-workflow-invalid-'));
|
|
try {
|
|
const invalid = [
|
|
{ workflow: 'unknown' }, { workflow: 'debug-media' }, { workflow: '__proto__' }, { workflow: '../director' }, { workflow: null }, { workflow: [] },
|
|
{ section: '../.env' }, { section: 'constructor' }, { section: null }, { section: 1 }, { section: {} },
|
|
{ workflow: 'director', section: 'intake' }, { workflow: 'template', section: 'production' }, { workflow: 'recreate', section: 'native' },
|
|
{ workflow: 'production', section: 'actions' }, { path: 'skills/openmotion-director/SKILL.md' }, [], 'director',
|
|
{ workflow: 'video-to-template', section: 'intake' }, { workflow: 'video--to-template' }, { workflow: 'video-to-template-' }, { workflow: 'template-to-video' }, { workflow: 'motion-template' },
|
|
];
|
|
const responses = stdio(directory, invalid.map((args, index) => workflowCall(index + 1, args)));
|
|
for (const [index, args] of invalid.entries()) assert.equal(responses.get(index + 1).isError, true, JSON.stringify(args));
|
|
assert.deepEqual(await readdir(directory), []);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('MCP starts through a symlinked installation path from another working directory', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-linked-mcp-'));
|
|
try {
|
|
const linked = path.join(directory, 'linked-plugin');
|
|
await symlink(root, linked, process.platform === 'win32' ? 'junction' : 'dir');
|
|
const responses = stdio(directory, workflows.map((workflow, index) => workflowCall(index + 1, { workflow })), path.join(linked, 'mcp.ts'));
|
|
for (const [index, workflow] of workflows.entries()) {
|
|
const result = responses.get(index + 1).structuredContent;
|
|
assert.ok(result, JSON.stringify(responses.get(index + 1)));
|
|
assert.equal(result.workflow, workflow);
|
|
assert.equal(result.section, 'start');
|
|
assert.equal(result.documentId, workflowRegistry[workflow as keyof typeof workflowRegistry].sections.start);
|
|
assert.equal(result.contentHash, (await getWorkflow('start', workflow)).contentHash);
|
|
}
|
|
assert.deepEqual(await readdir(directory), ['linked-plugin']);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
|
|
test('phase1 resource discovery exposes all five routes and their supporting documents, without starting a project', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-five-routes-'));
|
|
try {
|
|
const result = stdio(directory, [{ id: 1, method: 'resources/list' }]).get(1);
|
|
const uris = result.resources.map((resource: { uri: string }) => resource.uri);
|
|
const expected = entries.map(({ workflow, section }) => `openmotion://workflow/${workflow}/${section}`);
|
|
assert.deepEqual(uris, [...expected, 'openmotion://fonts/index', 'openmotion://engine/SKILL.md', 'ui://openmotion/inline-video/v2/player.html']);
|
|
assert.ok(uris.includes('openmotion://workflow/video-to-template/verification'));
|
|
assert.ok(!uris.some(uri => uri.includes('debug-media')));
|
|
const reads = stdio(directory, expected.map((uri, i) => ({ id: i, method: 'resources/read', params: { uri } })));
|
|
for (const [i, entry] of entries.entries()) assert.equal(reads.get(i).structuredContent.documentId, entry.documentId);
|
|
assert.deepEqual(await readdir(directory), []);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('engine resource reads reject every uri outside the pinned guide root', async () => {
|
|
const directory = await mkdtemp(path.join(tmpdir(), 'motion-engine-uri-'));
|
|
try {
|
|
// Grammar rejections are resolved without touching the installed runtime.
|
|
for (const uri of [42, 'http://example.com/SKILL.md', 'openmotion://engine/package.json',
|
|
'openmotion://engine/../SKILL.md', 'openmotion://engine/..%2fREADME.md', 'openmotion://engine/',
|
|
'openmotion://workflow/production', 'openmotion://engine/SKILL.md/extra']) {
|
|
await assert.rejects(() => readWorkflowResource(uri as unknown as string, directory),
|
|
/INVALID_RESOURCE_URI/, 'Must reject: ' + String(uri));
|
|
}
|
|
|
|
// The containment rule itself, exercised directly. Going through the URI grammar
|
|
// would prove only that the pattern rejects `..`, which is a different control.
|
|
const parent = await mkdtemp(path.join(tmpdir(), 'motion-guide-'));
|
|
try {
|
|
// Resolve the root first: on macOS the temporary directory is reached through a
|
|
// symlinked parent, so an unresolved root would never prefix-match a resolved target.
|
|
await mkdir(path.join(parent, 'guide'), { recursive: true });
|
|
const guide = await realpath(path.join(parent, 'guide'));
|
|
await mkdir(path.join(guide, 'nested'), { recursive: true });
|
|
await writeFile(path.join(guide, 'nested', 'inside.md'), 'inside');
|
|
await writeFile(path.join(parent, 'outside.md'), 'outside');
|
|
assert.ok(await resolveGuideFile(guide, 'nested/inside.md'), 'A file inside the root resolves');
|
|
await assert.rejects(() => resolveGuideFile(guide, '../outside.md'), /INVALID_RESOURCE_URI/,
|
|
'An existing file one level above the root must never be readable');
|
|
await assert.rejects(() => resolveGuideFile(guide, '../../outside.md'), /INVALID_RESOURCE_URI/);
|
|
await assert.rejects(() => resolveGuideFile(guide, 'absent.md'), /INVALID_RESOURCE_URI/,
|
|
'A missing target is a rejected file, not a raw filesystem error');
|
|
} finally { await rm(parent, { recursive: true, force: true }); }
|
|
|
|
// Error consistency through the resource reader needs the pinned guide, which only
|
|
// exists once the locked runtime is installed.
|
|
const installed = path.join(root, 'node_modules/hyperframes/dist/skills/hyperframes');
|
|
if (!existsSync(installed)) return;
|
|
await assert.rejects(() => readWorkflowResource('openmotion://engine/absent-guide.md', directory),
|
|
/INVALID_RESOURCE_URI/, 'A missing target is a rejected uri, not a raw filesystem error');
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
}); |