@lalalic/markcut 3.2.36 → 3.2.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -302,6 +302,10 @@ For comment-editor or timeline-dot changes, verify the built MCP player in a rea
302
302
 
303
303
  Whenever Markcut MCP server, preview UI, bridge, or bundled player code changes, rebuild the MCP bundle and reload **only the Markcut MCP provider** through Neo's provider control interface before testing or declaring the change live. Verify the running provider serves the new resource URI, then open a fresh ChatGPT iframe and check its displayed version and affected behavior. A Git push or ChatGPT tool-list refresh alone is not a provider reload. Never restart the whole Neo MCP app as a workaround; if scoped reload fails, report the live version and blocker explicitly.
304
304
 
305
+ ## Stateless MCP review
306
+
307
+ `markcut.preview` compiles and publishes an immutable revision for the calling ChatGPT conversation. The hosted app verifies the current path-keyed revision record before enabling review and sends decisions to that same conversation with `ui/message`. Neo Mobile owns its locally notified requests and delivery. Markcut does not store shared review history or poll for decisions. `markcut.preview.media({contentHash})` reads a compiled revision when a client needs its scene tree; operation status, immutable content fingerprints, media cache and safe pruning remain server-owned.
308
+
305
309
  ## MCP background-audio regression guard
306
310
 
307
311
  When extracting HTTPS BGM from a preview tree, traverse the tree **before** returning the captured audio variable. JavaScript evaluates object properties left-to-right: returning `{audio, playbackRoot: strip(root)}` silently loses the BGM handle while removing the native audio node. Keep the pure extraction in `src/mcp/audio-preview-tree.ts` and run `tests/mcp-web-audio-preview.test.ts`. For user-style playback verification, check network HTTP 200, decoded duration, a running AudioContext, advancing Remotion frames, and nonzero Web Audio analyser RMS; a decoded source alone does not establish audible playback. Browser TTS must retain BGM and environmental audio, and only generated narration can be removed; listen for speech start/end to duck and restore Web Audio music gain.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lalalic/markcut",
3
- "version": "3.2.36",
3
+ "version": "3.2.38",
4
4
  "description": "Markdown-to-video engine. Describe scenes in markdown, get a rendered video.",
5
5
  "bin": {
6
6
  "markcut": "bin/markcut"
@@ -12,7 +12,7 @@ Markcut turns a Markdown video definition into a compiled stream tree and a play
12
12
  | User goal | Agent action |
13
13
  |---|---|
14
14
  | Understand a folder of photos or clips | Inspect the files; use `markcut vision <folder>` if scene selection needs visual/media understanding. |
15
- | Make or revise a video | Load the project-selected template, author/edit its Markdown scenes, then `markcut verify <file>`. |
15
+ | Make or revise a video | Load the project-selected template, author/edit its Markdown scenes, run `markcut verify <file>`, and **inspect real playback before claiming a finished video**. |
16
16
  | Quickly assess story structure | `markcut preview <file> --storyboard` (placeholder media, not a final-video quality check). |
17
17
  | Watch a native work-in-progress video | `markcut preview <file>`; test real visuals, sound, and seeking. |
18
18
  | Ask a person to review in ChatGPT | Call the available `markcut.preview({path})` tool; handle revision-specific feedback and approval. |
@@ -4,10 +4,10 @@ The 14 capability-driven scenarios test **next-action routing, source authority,
4
4
 
5
5
  ## Output contract
6
6
 
7
- Each case returns an object in a JSON array:
7
+ Each case returns a decision object inside a top-level JSON object. Codex structured outputs require an object at the root:
8
8
 
9
9
  ```json
10
- {"id":"case-id","action":"author","authority":"video_md","completion_gates":["verify","real_playback","human_review"],"reason":"Brief explanation"}
10
+ {"decisions":[{"id":"case-id","action":"author","authority":"video_md","completion_gates":["verify","real_playback","human_review"],"reason":"Brief explanation"}]}
11
11
  ```
12
12
 
13
13
  - `action`: `vision | author | storyboard | native_preview | mcp_review | render | verify | repair | report`. This is the **immediate next step**, not a later gate.
@@ -15,6 +15,8 @@ Each case returns an object in a JSON array:
15
15
  - `completion_gates`: any applicable checks drawn from `verify`, `real_playback`, `human_review`. `human_review` means the new revision must be reviewed/approved by an actual human before claiming a human review/approval result; it is **not** mandatory for an ordinary render. These are gates to **claim the requested outcome complete**, not actions to execute immediately.
16
16
  - `reason`: explain the decision and why a blocker/approval cannot be assumed resolved. Do not claim actions were actually completed.
17
17
 
18
+ For CLI-answer scenarios, explaining a command does not mean executing it. The `cli-verify` case checks that the explanation actually names `markcut verify` without requiring the `verify` completion gate.
19
+
18
20
  `cases.json` defines acceptable equivalent next actions or authorities and **required** and **forbidden** gates. The checker does not insist on irrelevant intermediate gates; the meaningful behavioral invariants matter more than one exact execution order. It still rejects a wrong initial action, wrong source authority, missing essential gate, or inappropriate human-review requirement. This avoids confusing a report of failure with a failed repair attempt.
19
21
 
20
22
  ## Run
@@ -24,6 +26,6 @@ node skills/markcut/evals/check.mjs --validate
24
26
  node skills/markcut/evals/run-codex.mjs --provider openrouter --model openrouter/free
25
27
  ```
26
28
 
27
- The `run-codex.mjs` runner uses the locally authenticated Codex CLI and current `SKILL.md`. **By default it evaluates one independent user request per Codex invocation**, matching actual Skill usage instead of testing the model's ability to manage a large multi-task JSON array. Override with `--batch-size N` only for a batch-stress experiment. The provider and model are runtime parameters; `cases.json` and the checker are provider-independent. The runner saves the actual responses, JSONL events, stderr, and a score in a per-run temporary directory. It never changes video files or asks the model to perform real side effects.
29
+ The `run-codex.mjs` runner uses the locally authenticated Codex CLI and current `SKILL.md`. **By default it evaluates one independent user request per Codex invocation**, matching actual Skill usage instead of testing the model's ability to manage a large multi-task JSON array. Override with `--batch-size N` only for a batch-stress experiment. The provider and model are runtime parameters; `cases.json` and the checker are provider-independent. The runner saves the actual responses, JSONL events, stderr, and a score in a per-run temporary directory. It never changes video files or asks the model to perform real side effects. The runner uses a top-level `{"decisions": [...]}` JSON schema for OpenAI compatibility, and flags any legacy/fenced response separately from behavioral correctness.
28
30
 
29
31
  If a result fails, inspect `reason` and classify it as a Skill ambiguity, prompt conflict, incorrect eval expectation, undocumented implementation behavior, or model failure **before modifying either the Skill or the assertions**. In particular, a successful `compiled.json` is never final video playback and an old revision's human approval never applies to new content.
@@ -198,14 +198,13 @@
198
198
  "request": "在正式导出前先验证 Markcut Markdown 的语法和素材路径,用什么 CLI?",
199
199
  "action": "report",
200
200
  "authority": "video_md",
201
- "notes": "The user asks which command, not to execute it; answer markcut verify <file> without performing a command.",
202
- "required_gates": [
203
- "verify"
204
- ],
201
+ "notes": "Question asks which CLI to use, not to execute it. A correct explanation must name markcut verify; no action gate needs to have occurred.",
202
+ "required_gates": [],
205
203
  "forbidden_gates": [
206
204
  "human_review",
207
205
  "real_playback"
208
- ]
206
+ ],
207
+ "reason_includes": "markcut verify"
209
208
  },
210
209
  {
211
210
  "id": "browser-broken",
@@ -35,6 +35,7 @@ for (const item of cases) {
35
35
  check(Array.isArray(required) && required.every(v => allowed.gate.has(v)) && new Set(required).size === required.length, `${item.id} required_gates`);
36
36
  check(Array.isArray(forbidden) && forbidden.every(v => allowed.gate.has(v)) && new Set(forbidden).size === forbidden.length, `${item.id} forbidden_gates`);
37
37
  check(required.every(v => !forbidden.includes(v)), `${item.id} gates do not contradict`);
38
+ if (item.reason_includes !== undefined) check(typeof item.reason_includes === 'string' && item.reason_includes.length > 2, `${item.id} required rationale text`);
38
39
  }
39
40
  const skill = readFileSync(resolve(root, 'SKILL.md'), 'utf8');
40
41
  check(skill.startsWith('---\nname: markcut\n'), 'skill metadata');
@@ -73,6 +74,7 @@ if (process.argv[2] === '--validate') {
73
74
  for (const forbidden of item.forbidden_gates) check(!gates.includes(forbidden), `${item.id} incorrect completion gate: ${forbidden}`);
74
75
  }
75
76
  check(typeof output.reason === 'string' && output.reason.trim().length > 12, `${item.id} explanation`);
77
+ if (item.reason_includes) check(typeof output.reason === 'string' && output.reason.toLowerCase().includes(item.reason_includes.toLowerCase()), `${item.id} explanation names ${item.reason_includes}`);
76
78
  if (failures === before) passedCases++;
77
79
  }
78
80
  console.log(`Scored ${cases.length} cases: ${passedCases}/${cases.length} passed; ${failures} failed assertions. Manually inspect reason text for misleading claims.`);
@@ -15,7 +15,7 @@ function score(responses) {
15
15
  return spawnSync(process.execPath, [join(root, 'check.mjs'), file], {encoding: 'utf8'});
16
16
  }
17
17
  const good = cases.map(c => ({id: c.id, action: c.action, authority:c.authority,
18
- completion_gates: [...c.required_gates], reason: 'Correct next action and required completion checks are recorded.'}));
18
+ completion_gates: [...c.required_gates], reason: c.id === 'cli-verify' ? 'Use npx @lalalic/markcut verify video.md to check Markdown paths.' : 'Correct next action and required completion checks are recorded.'}));
19
19
  test('checker scores valid capability decisions', () => {
20
20
  const outcome = score(good);
21
21
  assert.equal(outcome.status, 0, outcome.stderr);
@@ -38,6 +38,16 @@ test('checker rejects a fabricated human-review requirement for a render-only re
38
38
  assert.notEqual(outcome.status, 0);
39
39
  assert.match(outcome.stderr, /render-final incorrect completion gate: human_review/);
40
40
  });
41
+ test('CLI answer needs the correct command but no executed verify gate', () => {
42
+ const answers = structuredClone(good);
43
+ const cli = answers.find(c => c.id === 'cli-verify');
44
+ assert.deepEqual(cli.completion_gates, []);
45
+ assert.equal(score(answers).status, 0);
46
+ cli.reason = 'Use a generic video validator command, no specific command was identified.';
47
+ const outcome = score(answers);
48
+ assert.notEqual(outcome.status, 0);
49
+ assert.match(outcome.stderr, /cli-verify explanation names markcut verify/);
50
+ });
41
51
  test('checker rejects invalid JSON rather than repairing it silently', () => {
42
52
  const file = join(dir, 'invalid.json');
43
53
  writeFileSync(file, '[{"id":"media-folder"}}}');
@@ -0,0 +1,54 @@
1
+ /** Shared structured-output contract for the Codex eval runner. */
2
+ export function outputSchema() {
3
+ return {
4
+ type: 'object',
5
+ additionalProperties: false,
6
+ properties: {
7
+ decisions: {
8
+ type: 'array',
9
+ items: {
10
+ type: 'object',
11
+ additionalProperties: false,
12
+ properties: {
13
+ id: {type: 'string'},
14
+ action: {type: 'string', enum: ['vision', 'author', 'storyboard', 'native_preview', 'mcp_review', 'render', 'verify', 'repair', 'report']},
15
+ authority: {type: 'string', enum: ['source_media', 'selected_video_template', 'video_md']},
16
+ completion_gates: {type: 'array', items: {type: 'string', enum: ['verify', 'real_playback', 'human_review']}},
17
+ reason: {type: 'string'},
18
+ },
19
+ required: ['id', 'action', 'authority', 'completion_gates', 'reason'],
20
+ },
21
+ },
22
+ },
23
+ required: ['decisions'],
24
+ };
25
+ }
26
+
27
+ /** Preserve the model's decisions; normalize only recognized legacy envelopes. */
28
+ export function parseOutput(raw, expectedIds) {
29
+ let parsed;
30
+ let schemaCompliant = true;
31
+ try { parsed = JSON.parse(raw); }
32
+ catch {
33
+ const fence = raw.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n```$/);
34
+ if (!fence) throw new Error('Response is neither JSON nor a single complete JSON code fence');
35
+ parsed = JSON.parse(fence[1]);
36
+ schemaCompliant = false;
37
+ }
38
+ let decisions;
39
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Object.keys(parsed).length === 1 && Array.isArray(parsed.decisions)) {
40
+ decisions = parsed.decisions;
41
+ } else if (Array.isArray(parsed)) {
42
+ decisions = parsed;
43
+ schemaCompliant = false;
44
+ } else if (expectedIds.length === 1 && parsed && typeof parsed === 'object' && parsed.id === expectedIds[0]) {
45
+ decisions = [parsed];
46
+ schemaCompliant = false;
47
+ } else {
48
+ throw new Error('Response has no valid decisions array');
49
+ }
50
+ if (decisions.length !== expectedIds.length || decisions.some((decision, index) => decision?.id !== expectedIds[index])) {
51
+ throw new Error('Response count or case identifiers differ from the input');
52
+ }
53
+ return {decisions, schemaCompliant};
54
+ }
@@ -0,0 +1,38 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {outputSchema, parseOutput} from './output-format.mjs';
4
+
5
+ const decision = {id:'cli-verify', action:'report', authority:'video_md', completion_gates:[], reason:'Use markcut verify video.md to check paths.'};
6
+ test('OpenAI output schema has root object and required decisions', () => {
7
+ const s = outputSchema();
8
+ assert.equal(s.type, 'object');
9
+ assert.deepEqual(s.required, ['decisions']);
10
+ assert.equal(s.properties.decisions.type, 'array');
11
+ assert.equal(s.additionalProperties, false);
12
+ assert.deepEqual(s.properties.decisions.items.required, ['id','action','authority','completion_gates','reason']);
13
+ });
14
+ test('round-trip strict OpenAI envelope preserves every decision', () => {
15
+ const data = parseOutput(JSON.stringify({decisions:[decision]}), ['cli-verify']);
16
+ assert.equal(data.schemaCompliant,true);
17
+ assert.deepEqual(data.decisions,[decision]);
18
+ });
19
+ test('legacy array is accepted but flagged as noncompliant', () => {
20
+ const data = parseOutput(JSON.stringify([decision]), ['cli-verify']);
21
+ assert.equal(data.schemaCompliant,false);
22
+ assert.deepEqual(data.decisions,[decision]);
23
+ });
24
+ test('singleton legacy object is accepted only for one matching ID', () => {
25
+ const data=parseOutput(JSON.stringify(decision),['cli-verify']);
26
+ assert.equal(data.schemaCompliant,false);
27
+ assert.deepEqual(data.decisions,[decision]);
28
+ assert.throws(()=>parseOutput(JSON.stringify(decision),['another-id']),/valid decisions array/);
29
+ });
30
+ test('single fenced JSON is accepted without silently hiding envelope failure', () => {
31
+ const data=parseOutput('```json\n' + JSON.stringify({decisions:[decision]}) + '\n```',['cli-verify']);
32
+ assert.equal(data.schemaCompliant,false);
33
+ });
34
+ test('reject incomplete batches, bad identifiers and malformed data',()=>{
35
+ assert.throws(()=>parseOutput(JSON.stringify({decisions:[]}),['cli-verify']),/count or case identifiers/);
36
+ assert.throws(()=>parseOutput(JSON.stringify({decisions:[decision]}),['other-id']),/count or case identifiers/);
37
+ assert.throws(()=>parseOutput('not JSON', ['cli-verify']),/neither JSON nor/);
38
+ });
@@ -5,6 +5,7 @@ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { outputSchema, parseOutput } from './output-format.mjs';
8
9
 
9
10
  const here = dirname(fileURLToPath(import.meta.url));
10
11
  const root = resolve(here, '..');
@@ -24,15 +25,8 @@ const output = mkdtempSync(join(tmpdir(), 'markcut-skill-codex-eval-'));
24
25
  const skill = readFileSync(join(root, 'SKILL.md'), 'utf8');
25
26
  const decisions = [];
26
27
  const run = {model, provider, batchSize, evidenceDir: output, batches: [], strictJsonFormat: true};
27
- const promptIntro = `You are an agent using a Markcut Skill for a capability-decision test. This is a dry run. DO NOT execute tools, edit files, create videos or assert that tasks were completed. Use ONLY the Skill below as the behavioral contract.\n\nFor EACH independent user request, return one decision.\n\nFields:\n- id: exact request ID.\n- action: the IMMEDIATE next action, one of vision, author, storyboard, native_preview, mcp_review, render, verify, repair, report. After changes_requested, edit video.md BEFORE verifying; do not infer the edit happened. If asked a yes/no question, answer via report without executing anything.\n- authority: source_media (observations and physical assets), selected_video_template (creative/style defaults for new video), or video_md (current video source/edit/review revision/render).\n- completion_gates: zero or more checks needed BEFORE CLAIMING the user's entire requested goal complete: verify, real_playback, human_review. Gates are NOT the immediate next action. For a playable or moving-map result, real_playback matters; for explicit human review/approval, a real human must review the CURRENT revision. Do not require human_review for an ordinary MP4 render. For a factual answer about a setting, no playback is required.\n- reason: a short explanation of the action and important boundary.\n\nReturn ONLY syntactically valid JSON (no Markdown code fences, no text outside JSON), matching the requested JSON schema.\n\nMARKCUT SKILL:\n${skill}\n\nUSER REQUESTS:\n`;
28
- function schema(size) {
29
- return {type:'array',minItems:size,maxItems:size,items:{type:'object',additionalProperties:false,properties:{
30
- id:{type:'string'}, action:{type:'string',enum:['vision','author','storyboard','native_preview','mcp_review','render','verify','repair','report']},
31
- authority:{type:'string',enum:['source_media','selected_video_template','video_md']},
32
- completion_gates:{type:'array',uniqueItems:true,items:{type:'string',enum:['verify','real_playback','human_review']}},
33
- reason:{type:'string'},
34
- },required:['id','action','authority','completion_gates','reason']}};
35
- }
28
+ const promptIntro = `You are an agent using a Markcut Skill for a capability-decision test. This is a dry run. DO NOT execute tools, edit files, create videos or assert that tasks were completed. Use ONLY the Skill below as the behavioral contract.\n\nFor EACH independent user request, return one decision.\n\nFields:\n- id: exact request ID.\n- action: the IMMEDIATE next action, one of vision, author, storyboard, native_preview, mcp_review, render, verify, repair, report. After changes_requested, edit video.md BEFORE verifying; do not infer the edit happened. If asked a yes/no question, answer via report without executing anything.\n- authority: source_media (observations and physical assets), selected_video_template (creative/style defaults for new video), or video_md (current video source/edit/review revision/render).\n- completion_gates: zero or more checks needed BEFORE CLAIMING the user's entire requested goal complete: verify, real_playback, human_review. Gates are NOT the immediate next action. For a playable or moving-map result, real_playback matters; for explicit human review/approval, a real human must review the CURRENT revision. Do not require human_review for an ordinary MP4 render. For a factual answer about a setting, no playback is required.\n- reason: a short explanation of the action and important boundary.\n\nReturn ONLY a JSON object with one decisions array containing the decisions above (no Markdown fences or text outside JSON), matching the provided output schema.\n\nMARKCUT SKILL:\n${skill}\n\nUSER REQUESTS:\n`;
29
+
36
30
  console.log(`Target: codex/${provider}/${model}; artifacts: ${output}; cases=${cases.length}; batch-size=${batchSize}`);
37
31
  for (let offset = 0; offset < cases.length; offset += batchSize) {
38
32
  const selected = cases.slice(offset, offset+batchSize);
@@ -42,7 +36,7 @@ for (let offset = 0; offset < cases.length; offset += batchSize) {
42
36
  const schemaFile = join(batchDir,'schema.json');
43
37
  const responseFile = join(batchDir,'raw-response.txt');
44
38
  writeFileSync(join(batchDir,'prompt.txt'),prompt);
45
- writeFileSync(schemaFile,JSON.stringify(schema(selected.length),null,2));
39
+ writeFileSync(schemaFile,JSON.stringify(outputSchema(),null,2));
46
40
  const cmd=['exec','--ephemeral','--skip-git-repo-check','--ignore-rules','-s','read-only','-C',batchDir,
47
41
  '-c',`model_provider="${provider}"`,'-m',model,'-c','model_reasoning_effort="low"',
48
42
  '--json','--output-schema',schemaFile,'--output-last-message',responseFile,'-'];
@@ -54,27 +48,23 @@ for (let offset = 0; offset < cases.length; offset += batchSize) {
54
48
  run.batches.push(meta);
55
49
  writeFileSync(join(output,'run.json'),JSON.stringify(run,null,2));
56
50
  if (result.status!==0) {console.error(`FAIL Codex batch ${meta.index} exit=${result.status} ${result.error?.message??(result.stderr??'').slice(-450)}`);process.exit(1);}
57
- const raw=readFileSync(responseFile,'utf8');
51
+ const raw = readFileSync(responseFile, 'utf8');
58
52
  let response;
59
- try {response=JSON.parse(raw);} catch(error) {
60
- meta.strictJsonFormat=false; run.strictJsonFormat=false;
61
- const match=raw.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n```$/);
62
- if (!match) {console.error(`FAIL batch ${meta.index}: ${error.message}; not one complete JSON fence`);process.exit(1);}
63
- try {response=JSON.parse(match[1]);} catch(inner) {console.error(`FAIL batch ${meta.index}: invalid JSON inside fence: ${inner.message}`);process.exit(1);}
64
- }
65
- if (!Array.isArray(response)) {
66
- // One request may naturally produce one JSON object even when Codex ignores
67
- // the array output schema. Keep this as a recorded schema violation.
68
- if (selected.length === 1 && response && typeof response === 'object' && response.id === selected[0].id) {
69
- response = [response];
70
- meta.strictJsonFormat = false;
71
- run.strictJsonFormat = false;
72
- } else {console.error(`FAIL batch ${meta.index}: output is not an array`);process.exit(1);}
53
+ try {
54
+ const parsed = parseOutput(raw, selected.map(c => c.id));
55
+ response = parsed.decisions;
56
+ meta.schemaCompliant = parsed.schemaCompliant;
57
+ if (!parsed.schemaCompliant) {meta.strictJsonFormat = false; run.strictJsonFormat = false;}
58
+ } catch (error) {
59
+ meta.schemaCompliant = false;
60
+ writeFileSync(join(output,'run.json'),JSON.stringify(run,null,2));
61
+ console.error(`FAIL batch ${meta.index}: ${error.message}`);
62
+ process.exit(1);
73
63
  }
74
64
  writeFileSync(join(batchDir,'normalized-responses.json'),JSON.stringify(response,null,2)+'\n');
75
65
  writeFileSync(join(output,'run.json'),JSON.stringify(run,null,2));
76
66
  decisions.push(...response);
77
- console.log(`Batch ${meta.index}: ${response.length} decisions; strict JSON: ${meta.strictJsonFormat?'yes':'NO (fenced)'}`);
67
+ console.log(`Batch ${meta.index}: ${response.length} decisions; strict JSON: ${meta.strictJsonFormat?'yes':'NO (legacy envelope)'}`);
78
68
  }
79
69
  const combined=join(output,'responses.json');
80
70
  writeFileSync(combined,JSON.stringify(decisions,null,2)+'\n');
@@ -82,6 +72,6 @@ const scoring=spawnSync(process.execPath,[join(here,'check.mjs'),combined],{enco
82
72
  writeFileSync(join(output,'score.txt'),(scoring.stdout??'')+(scoring.stderr??''));
83
73
  process.stdout.write(scoring.stdout??'');
84
74
  process.stderr.write(scoring.stderr??'');
85
- if (!run.strictJsonFormat) console.log('FORMAT WARNING: at least one batch ignored the output schema (fences or singleton object) (raw output preserved).');
75
+ if (!run.strictJsonFormat) console.log('FORMAT WARNING: at least one batch did not follow the output schema; original response preserved.');
86
76
  if (run.batches.some(b=>b.modelMetadataWarning)) console.log('Codex warning: missing model metadata; fallback metadata was used.');
87
77
  process.exit(scoring.status??1);
@@ -1,14 +1,16 @@
1
- # ChatGPT MCP review: external behavior contract
1
+ # ChatGPT MCP preview lifecycle
2
2
 
3
- The `markcut.preview({path})` tool accepts an absolute Markcut `.md` path or a supported NeoY mounted HTTPS Markdown URL. This tool is for **interactive viewing and human review** inside ChatGPT, not for parsing unrelated Markdown or editing the supplied file. A `relay` correlation object is optional; use it only when the task already belongs to Agents Relay.
3
+ `markcut.preview({path})` compiles and publishes an immutable video revision for the calling ChatGPT conversation. The result includes `contentHash` and `revisionId`; the hosted player loads the compiled revision and checks the current path-keyed record at `revisions/<sha256(requestedPath)>.json` before enabling review actions.
4
4
 
5
- The tool starts compilation and publication of an immutable video revision. The returned operation or player resource can precede successful compilation. The hosted player may show stages before the video is playable. Record the revision/content hash when ready; validate in the actual hosted player.
5
+ Review is client-owned. The hosted ChatGPT app sends one `ui/message` containing the decision, revision identity, path, and comments directly to the conversation that opened it. Neo Mobile owns its locally notified review requests and handles its own delivery. Markcut does not keep a global review inbox, persist review decisions, or poll for decisions. A successful `ui/message` response means the conversation received the message; only then does the player show that review was sent. Failures are retried and reported without showing acceptance.
6
+
7
+ `markcut.preview.media({contentHash})` retrieves the immutable compiled scene tree for clients that need it. No review-session tools are provided. `markcut.preview` compilation operations and content fingerprinting remain available, and completed output is published at the same immutable resource locations.
6
8
 
7
9
  Human review behavior:
8
10
 
9
- - Draft comments may belong to a scene or a playback timestamp; submitting feedback sends `decision: changes_requested` with context. The agent edits the **original Markcut Markdown** and calls `markcut.preview` again for a new revision.
10
- - An explicit `decision: approved` is tied to the reviewed content hash/revision. Never apply it to a changed source file. Unsaved comments are not an approval.
11
+ - Draft comments may belong to a scene or playback timestamp. Submitting feedback sends `decision: changes_requested` with revision context. The agent edits the original Markcut Markdown and calls `markcut.preview` again for a new revision.
12
+ - An explicit `decision: approved` applies only to the reviewed content hash and revision. Unsaved comments are not an approval.
11
13
  - Earlier preview revisions are read-only after supersession. Failed compilation does not invalidate previously successful revisions, but does not authorize approval of an unrendered new one.
12
- - Browser TTS is a **preview playback option**, not an authoritative representation of the voice used in rendered MP4. Confirm the final file's audio independently.
14
+ - Browser TTS is a preview playback option, not an authoritative representation of the voice used in rendered MP4. Confirm the final file's audio independently.
13
15
 
14
- For implementation-specific caching, publishing and iframe internals, developers can consult the Markcut repository `docs/mcp-static-preview.md`. Such internals are not mandatory context for ordinary video authoring.
16
+ For implementation-specific caching, publishing, and iframe internals, consult `docs/mcp-static-preview.md`.
@@ -104,7 +104,7 @@ async function loadRemoteScenes(path){
104
104
  }catch(e){status.textContent='Scene lookup failed: '+String(e);}
105
105
  }
106
106
  function send(msg){window.parent.postMessage(msg,'*');}
107
- function request(method,params){const id=++nextId;send({jsonrpc:'2.0',id,method,params});return new Promise((resolve,reject)=>pending.set(id,{resolve,reject}));}
107
+ function request(method,params){const id=++nextId;return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pending.delete(id);reject(new Error('MCP request timed out'));},15000);pending.set(id,{resolve,reject,timer});send({jsonrpc:'2.0',id,method,params});});}
108
108
  function showVideoName(path,title){const el=document.getElementById('video-md-version');if(!el)return;const file=typeof path==='string'?decodeURIComponent(path.split('/').pop()||'video.md'):'video.md';el.textContent=typeof title==='string'&&title.trim()?title.trim():file.replace(/\.md$/i,'').replace(/[-_]+/g,' ');}
109
109
  function applyToolInput(params){
110
110
  const input=params?.arguments||params?.input||params?.toolInput||params||{};
@@ -123,6 +123,11 @@ function applyToolInput(params){
123
123
  }
124
124
  }
125
125
  let operationGeneration=0;
126
+ async function sendDecisionMessage(result){
127
+ for(let attempt=0;attempt<3;attempt++){
128
+ try{await request('ui/message',{role:'user',content:[{type:'text',text:JSON.stringify(result)}]});return true;}catch(e){if(attempt===2){status.textContent='Could not send review to this conversation: '+String(e.message||e);return false;}await new Promise(resolve=>setTimeout(resolve,250*(attempt+1)));}
129
+ }return false;
130
+ }
126
131
  async function trackOperation(data){
127
132
  const generation=++operationGeneration;
128
133
  ++fallbackGeneration; // Prevent an old published revision from replacing in-progress UI.
@@ -211,7 +216,7 @@ window.addEventListener('message',event=>{
211
216
  const message=event.data;
212
217
  if(!message||message.jsonrpc!=='2.0')return;
213
218
  if(Object.prototype.hasOwnProperty.call(message,'id')&&pending.has(message.id)){
214
- const item=pending.get(message.id);pending.delete(message.id);
219
+ const item=pending.get(message.id);pending.delete(message.id);clearTimeout(item.timer);
215
220
  if(message.error)item.reject(new Error(message.error.message||'MCP request failed'));
216
221
  else item.resolve(message.result);
217
222
  }else if(message.method==='ui/notifications/tool-input')applyToolInput(message.params);
@@ -240,9 +245,13 @@ async function submit(decision){
240
245
  result.feedback=preparedComments.length===1?preparedComments[0].text:preparedComments.map((item,index)=>String(index+1)+'. ['+sceneKey(item.playbackContext)+' @ '+(item.playbackContext.timeSeconds??0)+'s] '+item.text).join('\\n');
241
246
  if(window.__markcutPlaybackContext)result.playbackContext=window.__markcutPlaybackContext;
242
247
  }
243
- busy=true;status.textContent='Submitting…';
248
+ busy=true;status.textContent='Sending review to this conversation…';
244
249
  const submittedId=result.revisionId;
245
- try{await request('ui/message',{role:'user',content:[{type:'text',text:JSON.stringify(result)}]});if(identity?.revisionId===submittedId){submittedRevision=submittedId;status.textContent=decision==='approved'?'Approved.':'Feedback sent. Waiting for the updated preview.';}}
250
+ try{
251
+ const delivered=await sendDecisionMessage(result);
252
+ if(!delivered){busy=false;return;}
253
+ if(identity?.revisionId===submittedId){submittedRevision=submittedId;status.textContent=decision==='approved'?'Review sent.':'Feedback sent. Waiting for the updated preview.';}
254
+ }
246
255
  catch(e){busy=false;status.textContent=e.message||'Unable to submit review';}
247
256
  }
248
257
  document.getElementById('approve').onclick=()=>submit('approved');
@@ -5,6 +5,7 @@ import {join} from "node:path";
5
5
  import {fileURLToPath} from "node:url";
6
6
  import {EXPORT_ROOT,publicOrigin,resolvePreviewPath} from "./remote-assets.mjs";
7
7
  import {validateMarkdownPath} from "./preview.mjs";
8
+ import {fingerprintInputs} from "./source-fingerprint.mjs";
8
9
  const folder=join(EXPORT_ROOT,"operations");
9
10
  const RETAIN_MS=24*60*60*1000;
10
11
  function cleanupOldOperations(){
@@ -29,12 +30,13 @@ export function writeOperation(id,data){
29
30
  export function startCompileOperation(path,relay){
30
31
  const valid=validateMarkdownPath(resolvePreviewPath(path));
31
32
  if(!statSync(valid).isFile())throw new Error("Preview source must be a Markdown file");
32
- const sourceHash=createHash("sha256").update(readFileSync(valid)).digest("hex");
33
+ const input=fingerprintInputs(valid);
34
+ const sourceHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
33
35
  cleanupOldOperations();
34
36
  const id=randomUUID(),startedAt=Date.now();
35
- writeOperation(id,{id,state:"compiling",stage:"queued",startedAt,requestedPath:path});
37
+ writeOperation(id,{id,state:"compiling",stage:"queued",startedAt,requestedPath:path});
36
38
  const worker=fileURLToPath(new URL("./compile-worker.mjs",import.meta.url));
37
- const child=spawn(process.execPath,[worker,id,valid,path,JSON.stringify(relay||null),sourceHash],{detached:true,stdio:"ignore"});
39
+ const child=spawn(process.execPath,[worker,id,valid,path,JSON.stringify(relay||null),sourceHash],{detached:true,stdio:"ignore"});
38
40
  child.on("error",e=>{
39
41
  writeOperation(id,{id,state:"failed",stage:"failed",startedAt,requestedPath:path,error:e.message});
40
42
  });
@@ -1,14 +1,15 @@
1
1
  import {createHash} from "node:crypto";
2
- import {readFileSync} from "node:fs";
3
2
  import {ensureVideoPreview} from "./preview.mjs";
4
3
  import {publishPreviewRevision} from "./remote-assets.mjs";
5
4
  import {writeOperation} from "./compile-operation.mjs";
5
+ import {fingerprintInputs} from "./source-fingerprint.mjs";
6
6
  const [id,path,requestedPath,relayText,sourceHash]=process.argv.slice(2);
7
7
  const startedAt=Date.now();
8
8
  function update(stage){writeOperation(id,{id,state:"compiling",stage,startedAt,updatedAt:Date.now(),requestedPath});}
9
9
  try{
10
10
  update("resolving-and-compiling");
11
- const actualHash=createHash("sha256").update(readFileSync(path)).digest("hex");
11
+ const input=fingerprintInputs(path);
12
+ const actualHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
12
13
  if(actualHash!==sourceHash)throw new Error("Source changed while queued; retry preview");
13
14
  const result=await ensureVideoPreview(path,{onProgress:update});
14
15
  update("publishing");
@@ -6,9 +6,10 @@ import { isAbsolute, extname, dirname, resolve, basename } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { buildPreviewBridgeScript } from "./bridge.mjs";
8
8
  import { externalizePreviewMedia, publicOrigin, resolveMountedFile, resolvePreviewPath, publishPlayerBundle, publishCompiledCache, prunePublishedCache, EXPORT_ROOT } from "./remote-assets.mjs";
9
+ import {fingerprintInputs} from "./source-fingerprint.mjs";
9
10
 
10
11
  export const TOOL_NAME = "markcut.preview";
11
- export const RESOURCE_URI = "ui://markcut/video-preview-v38.html";
12
+ export const RESOURCE_URI = "ui://markcut/video-preview-v40.html";
12
13
  const PREVIEW_VERSION = RESOURCE_URI.match(/video-preview-(v\d+)/)?.[1] ?? "unknown";
13
14
  // Legacy entrypoints remain registered, but serve the current implementation.
14
15
  export const LEGACY_RESOURCE_URIS = [
@@ -47,6 +48,8 @@ export const LEGACY_RESOURCE_URIS = [
47
48
  "ui://markcut/video-preview-v35.html",
48
49
  "ui://markcut/video-preview-v36.html",
49
50
  "ui://markcut/video-preview-v37.html",
51
+ "ui://markcut/video-preview-v39.html",
52
+ "ui://markcut/video-preview-v38.html",
50
53
  ];
51
54
  export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
52
55
  // Google Maps JS loads libraries, tiles and Routes RPCs from these HTTPS origins.
@@ -170,8 +173,9 @@ async function pruneCache(dir, indexFile, entries, currentHash) {
170
173
  export async function ensureVideoPreview(path, options = {}) {
171
174
  const validatedPath = validateMarkdownPath(resolvePreviewPath(path));
172
175
  await access(validatedPath, fsConstants.R_OK);
173
- const source=await readFile(validatedPath,"utf8");
174
- const sourceHash=createHash("sha256").update(source).digest("hex");
176
+ const input=fingerprintInputs(validatedPath);
177
+ const source=input.source.toString("utf8");
178
+ const sourceHash=createHash("sha256").update(input.source).update("\0").update(JSON.stringify(input.assets)).digest("hex");
175
179
  const key=validatedPath+"\0"+sourceHash;
176
180
  if(pendingCompiles.has(key))return pendingCompiles.get(key);
177
181
  const prior=activeCompilesByPath.get(validatedPath)||Promise.resolve();
@@ -186,21 +190,13 @@ export async function ensureVideoPreview(path, options = {}) {
186
190
  const cacheDir=resolve(outputRoot,"cache");
187
191
  const indexFile=resolve(dir,"cache-index.json");
188
192
  const audio=await readPreviewAudio(validatedPath);
189
- const referencedAssets=[];
190
- for(const match of source.matchAll(/\b(?:src|audio)\s*:\s*["']?([^"'\s;]+\.(?:png|jpe?g|webp|svg|gif|mp4|mov|webm|wav|mp3|m4a|ogg|vtt|srt))/gi)){
191
- const candidate=match[1];
192
- if(candidate.includes("://")||candidate.startsWith("/"))continue;
193
- try {
194
- const info=await stat(resolve(baseDir,candidate));
195
- if(info.isFile())referencedAssets.push([candidate,info.size,info.mtimeMs]);
196
- }catch{}
197
- }
193
+ const referencedAssets=input.assets;
198
194
  referencedAssets.sort((a,b)=>String(a[0]).localeCompare(String(b[0])));
199
195
  // Compilation generates random scene ids. Identity must be based on inputs,
200
196
  // not on non-semantic runtime ids, so unchanged files reuse identical cache.
201
197
  if(audio.audioSrc && audio.audioSrc.startsWith("/")){
202
198
  const info=await stat(audio.audioSrc);
203
- referencedAssets.push([audio.audioSrc,info.size,info.mtimeMs]);
199
+ referencedAssets.push([audio.audioSrc,createHash("sha256").update(await readFile(audio.audioSrc)).digest("hex")]);
204
200
  }
205
201
  const hash=createHash("sha256").update(validatedPath).update("\0")
206
202
  .update(source).update("\0").update(JSON.stringify(referencedAssets)).update("\0").update(audio.audioSrc||"")
@@ -241,7 +237,9 @@ export async function ensureVideoPreview(path, options = {}) {
241
237
  catch(error){if(error.code!=="EEXIST")throw error;}
242
238
  }
243
239
  const currentSource=await readFile(validatedPath,"utf8");
244
- if(createHash("sha256").update(currentSource).digest("hex")!==sourceHash)
240
+ const current=fingerprintInputs(validatedPath,Buffer.from(currentSource));
241
+ const currentHash=createHash("sha256").update(current.source).update("\0").update(JSON.stringify(current.assets)).digest("hex");
242
+ if(currentHash!==sourceHash)
245
243
  throw new Error("Source changed during compilation; retry preview");
246
244
  await mkdir(dir,{recursive:true});
247
245
  report("publishing-static-preview");
@@ -268,25 +266,6 @@ export async function ensureVideoPreview(path, options = {}) {
268
266
  // Compatibility export: there is no longer a managed player to stop.
269
267
  export function stopManagedVideoPreview() {}
270
268
 
271
- export function reviewResult(decision, feedback = "") {
272
- if (decision === "approved") return { decision };
273
- if (decision === "changes_requested") {
274
- const normalized = typeof feedback === "string" ? feedback.trim() : "";
275
- if (!normalized) throw new Error("feedback is required when requesting changes");
276
- return { decision, feedback: normalized };
277
- }
278
- throw new Error(`unsupported review decision: ${String(decision)}`);
279
- }
280
-
281
- export function reviewMessage(result) {
282
- const normalized = reviewResult(result?.decision, result?.feedback);
283
- return {
284
- jsonrpc: "2.0",
285
- method: "ui/message",
286
- params: { role: "user", content: [{ type: "text", text: JSON.stringify(normalized) }] },
287
- };
288
- }
289
-
290
269
  export function buildPreviewHtml() {
291
270
  const playerScriptUrl = publishPlayerBundle(bundlePath);
292
271
  // Base64 keeps HTML parser-sensitive sequences inside the large JS bundle
@@ -6,7 +6,7 @@ import { z } from "zod";
6
6
  import {publishPreviewRevision} from "./remote-assets.mjs";
7
7
  import {startCompileOperation} from "./compile-operation.mjs";
8
8
  import {
9
- TOOL_NAME, RESOURCE_URI, LEGACY_RESOURCE_URIS, buildPreviewResourceResult, previewCsp, getPreviewMedia, ensureVideoPreview, stopManagedVideoPreview,
9
+ TOOL_NAME, RESOURCE_URI, LEGACY_RESOURCE_URIS, buildPreviewResourceResult, previewCsp, getPreviewMedia, stopManagedVideoPreview,
10
10
  } from "./preview.mjs";
11
11
 
12
12
  const server = new McpServer({ name: "markcut", version: "3.2.0" });
@@ -30,7 +30,11 @@ server.registerTool(
30
30
  },
31
31
  async ({contentHash}) => {
32
32
  try {
33
- return {content:[{type:"text",text:"Preview media ready"}], structuredContent:getPreviewMedia(contentHash)};
33
+ // Mobile clients need the current published player without a server-owned
34
+ // review session. Both resources are immutable and keyed by contentHash.
35
+ const media=getPreviewMedia(contentHash);
36
+ media.playerUrl=publishPlayerBundle(fileURLToPath(new URL("./remotion-app.bundle.js",import.meta.url)),publicOrigin());
37
+ return {content:[{type:"text",text:"Preview media ready"}], structuredContent:media};
34
38
  } catch (error) {
35
39
  return {isError:true,content:[{type:"text",text:error.message||String(error)}]};
36
40
  }
@@ -41,7 +45,7 @@ registerAppTool(
41
45
  server,
42
46
  TOOL_NAME,
43
47
  {
44
- description: "Show the Markcut video player for a Markdown video definition and ask a human to approve it or request changes. When a review ui/message arrives with decision=changes_requested, edit the supplied path using feedback and call markcut.preview again with the same path; do not consider it approved. When decision=approved, treat only that contentHash/revisionId as approved and stop the review loop. Never approve a newer revision from an older message.",
48
+ description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. The hosted player sends human review feedback directly to this conversation with ui/message; feedback is not stored or routed by the server. Approval applies only to the exact contentHash shown.",
45
49
  inputSchema: z.object({
46
50
  path: z.string().describe("Absolute .md path or NeoY HTTPS mounted file URL"),
47
51
  relay: z.object({jobId:z.string(),taskId:z.union([z.string(),z.number()]),executionId:z.string().optional()}).optional().describe("Optional Agents Relay task correlation. No Relay dependency for standalone ChatGPT/Work reviews."),
@@ -0,0 +1,24 @@
1
+ import {createHash} from "node:crypto";
2
+ import {closeSync,openSync,readFileSync,readSync,statSync} from "node:fs";
3
+ import {basename,dirname,isAbsolute,resolve} from "node:path";
4
+
5
+ const assetPattern=/\b(?:src|audio)\s*:\s*["']?([^"'\s;]+\.(?:png|jpe?g|webp|svg|gif|mp4|mov|webm|wav|mp3|m4a|ogg|vtt|srt))/gi;
6
+ function hashFile(path){
7
+ const fd=openSync(path,"r"),buffer=Buffer.allocUnsafe(1024*1024),hash=createHash("sha256");
8
+ try{let count;while((count=readSync(fd,buffer,0,buffer.length,null))>0)hash.update(buffer.subarray(0,count));return hash.digest("hex");}
9
+ finally{closeSync(fd);}
10
+ }
11
+ export function fingerprintInputs(path, sourceBytes=readFileSync(path)) {
12
+ const source=Buffer.isBuffer(sourceBytes)?sourceBytes:Buffer.from(sourceBytes);
13
+ const base=dirname(path), assets=[];
14
+ for(const match of source.toString("utf8").matchAll(assetPattern)){
15
+ const candidate=match[1]; if(candidate.includes("://")||isAbsolute(candidate))continue;
16
+ try {const file=resolve(base,candidate),info=statSync(file);if(info.isFile())assets.push([candidate,hashFile(file)]);}catch{}
17
+ }
18
+ if(![...source.toString("utf8").matchAll(assetPattern)].some(match=>/\baudio\s*:/i.test(match[0]))){
19
+ const file=resolve(base,basename(path,".md")+".wav");
20
+ try {const info=statSync(file);if(info.isFile())assets.push([file,hashFile(file)]);}catch{}
21
+ }
22
+ assets.sort((a,b)=>String(a[0]).localeCompare(String(b[0])));
23
+ return {source,assets};
24
+ }
@@ -3,7 +3,7 @@ import vm from 'node:vm';
3
3
  import {webcrypto} from 'node:crypto';
4
4
  import {buildPreviewBridgeScript} from '../src/mcp/bridge.mjs';
5
5
 
6
- function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>) {
6
+ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, toolCall?:(message:any)=>any) {
7
7
  const messages:any[]=[];
8
8
  const listeners:Record<string,Array<(evt:any)=>void>>={};
9
9
  const element=()=>({value:'',textContent:'',onclick:null as null|(()=>void),oninput:null as null|(()=>void),
@@ -15,7 +15,8 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>) {
15
15
  feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),approve:element(),changes:element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-count':element(),'comment-mode':element(),'overall-mode':element()
16
16
  };
17
17
  nodes['comment-mode'].value='spot';
18
- const parent={postMessage:(m:any)=>messages.push(m)};
18
+ let dispatch:(message:any,source?:any)=>void;
19
+ const parent={postMessage:(m:any)=>{messages.push(m);if(m.method==='tools/call'||m.method==='ui/message')setTimeout(()=>{const response=toolCall?.(m);dispatch?.(response?.rpcError?{id:m.id,error:response.rpcError}:{id:m.id,result:response||{content:[]}})},0)}};
19
20
  const events:any[]=[];
20
21
  const window={
21
22
  parent,
@@ -23,9 +24,9 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>) {
23
24
  dispatchEvent:(evt:any)=>{events.push(evt);return true},
24
25
  };
25
26
  const fetch=fetchOverride|| (async()=>({ok:true,json:async()=>remoteData}));
26
- const context=vm.createContext({crypto:webcrypto,TextEncoder,URL,fetch,setTimeout,window,document:{getElementById:(id:string)=>nodes[id],createElement:()=>element()},CustomEvent:class {type:string;detail:any;constructor(t:string,opts:any){this.type=t;this.detail=opts.detail}}});
27
- const dispatch=(message:any,source=parent)=>(listeners.message??[]).forEach(listener=>listener({source,data:{jsonrpc:'2.0',...message}}));
28
- const result=(data:any)=>dispatch({method:'ui/notifications/tool-result',params:{result:{structuredContent:data}}});
27
+ const context=vm.createContext({crypto:webcrypto,TextEncoder,URL,fetch,setTimeout,clearTimeout,window,document:{getElementById:(id:string)=>nodes[id],createElement:()=>element()},CustomEvent:class {type:string;detail:any;constructor(t:string,opts:any){this.type=t;this.detail=opts.detail}}});
28
+ dispatch=(message:any,source=parent)=>(listeners.message??[]).forEach(listener=>listener({source,data:{jsonrpc:'2.0',...message}}));
29
+ const result=(data:any)=>dispatch({method:'ui/notifications/tool-result',params:{result:{structuredContent:{...data}}}});
29
30
  const respond=(id:number,result:any={})=>dispatch({id,result});
30
31
  vm.runInContext(buildPreviewBridgeScript().replaceAll("__MARKCUT_ORIGIN__",JSON.stringify("https://neoy.qili2.com")),context);
31
32
  return {messages,nodes,events,dispatch,result,respond,scene:(detail:any)=>(listeners['markcut:scene-change']||[]).forEach(listener=>listener({detail})),selectSpot:(id:number)=>(listeners['markcut:spot-select']||[]).forEach(listener=>listener({detail:{id}}))};
@@ -42,25 +43,34 @@ describe('MCP Remotion bridge',()=>{
42
43
  expect(h.events.at(-1)?.detail?.revisionId).toBe('remote-r1');
43
44
  expect(h.nodes.status.textContent).toBe('');
44
45
  });
45
- it('initializes, delivers compiled scenes and submits review without secondary MCP calls',async()=>{
46
+ it('initializes, delivers compiled scenes and sends review directly to the caller',async()=>{
46
47
  const h=harness();
47
48
  expect(h.messages[0]).toMatchObject({id:1,method:'ui/initialize'});
48
49
  h.respond(1);
49
50
  await nextTick();
50
51
  expect(h.messages[1]).toMatchObject({method:'ui/notifications/initialized'});
51
52
  const compiled={width:640,height:480,fps:30,children:[{name:'Scene-A',durationInSeconds:2}]};
52
- h.result({id:'one',revisionId:'rev1',contentHash:'abcdef',path:'/tmp/a.md',compiled});
53
+ h.result({id:'one',revisionId:'rev1',contentHash:'a'.repeat(64),path:'/tmp/a.md',compiled});
53
54
  expect(h.events.map(e=>e.type)).toEqual(['markcut:revision']);
54
55
  expect(h.events[0].detail.compiled).toEqual(compiled);
55
56
  expect(h.nodes['path-label'].textContent).toBe('/tmp/a.md');
56
57
  expect(h.nodes['video-md-version'].textContent).toBe('a');
57
- expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
58
58
  h.nodes.approve.onclick?.();
59
- expect(h.messages[2]).toMatchObject({id:2,method:'ui/message'});
60
- expect(JSON.parse(h.messages[2].params.content[0].text)).toEqual({previewId:'one',revisionId:'rev1',contentHash:'abcdef',path:'/tmp/a.md',decision:'approved'});
61
- h.respond(2);
59
+ expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
60
+ await nextTick();
61
+ const notification=h.messages.find(m=>m.method==='ui/message');
62
+ expect(JSON.parse(notification.params.content[0].text)).toEqual({previewId:'one',revisionId:'rev1',contentHash:'a'.repeat(64),path:'/tmp/a.md',decision:'approved'});
63
+ h.respond(notification.id);
62
64
  await nextTick();
63
- expect(h.nodes.status.textContent).toBe('Approved.');
65
+ expect(h.nodes.status.textContent).toBe('Review sent.');
66
+ });
67
+ it('retries ui/message delivery errors and never reports success before delivery',async()=>{
68
+ let failed=0;const h=harness(undefined,undefined,(m)=>{if(m.method==='ui/message'&&failed++<2)return {rpcError:{message:'temporary delivery failure'}};return {content:[]};});
69
+ h.result({id:'retry',revisionId:'retry-r1',contentHash:'c'.repeat(64),path:'/retry.md',compiled:{children:[]}});
70
+ h.nodes.approve.onclick?.();
71
+ for(let i=0;i<80&&h.messages.filter(m=>m.method==='ui/message').length<3;i++)await new Promise(resolve=>setTimeout(resolve,10));
72
+ expect(h.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
73
+ expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(3);
64
74
  });
65
75
  it('keeps previews isolated per iframe and enforces feedback',async()=>{
66
76
  const a=harness(),b=harness();
@@ -76,7 +86,7 @@ describe('MCP Remotion bridge',()=>{
76
86
  a.nodes.feedback.value='Shorten the opening';
77
87
  a.nodes['save-spot'].onclick?.();
78
88
  a.nodes.changes.onclick?.();
79
- expect(JSON.parse(a.messages[2].params.content[0].text)).toMatchObject({previewId:'a',decision:'changes_requested',feedback:'Shorten the opening'});
89
+ expect(JSON.parse(a.messages.find(m=>m.method==='ui/message').params.content[0].text)).toMatchObject({decision:'changes_requested',comments:[{scope:'overall',text:'Shorten the opening'}]});
80
90
  expect(b.messages.filter(m=>m.method==='ui/message')).toHaveLength(0);
81
91
  });
82
92
  it('does not show the latest B result inside an A-bound iframe',()=>{
@@ -106,14 +116,15 @@ describe('MCP Remotion bridge',()=>{
106
116
  second.dispatch({method:'ui/notifications/tool-input',params:{arguments:{path:url}}});
107
117
  expect(second.events.at(-1).detail.revisionId).toBe('url-rev');
108
118
  second.nodes.approve.onclick?.();
109
- expect(JSON.parse(second.messages.at(-1).params.content[0].text).revisionId).toBe('url-rev');
119
+ expect(second.messages.filter(m=>m.method==='tools/call')).toHaveLength(0);
110
120
  });
111
- it('preserves optional Relay job/task context across review decisions',()=>{
121
+ it('preserves optional Relay job/task context across review decisions',async()=>{
112
122
  const h=harness();
113
123
  const relay={jobId:'job-7',taskId:19,executionId:'exec-1'};
114
124
  h.result({id:'r',revisionId:'r',contentHash:'hash',path:'/video.md',relay,compiled:{children:[]}});
115
125
  h.selectSpot(0);h.nodes.feedback.value='shorter title';h.nodes['save-spot'].onclick?.();h.nodes.changes.onclick?.();
116
- expect(JSON.parse(h.messages.at(-1).params.content[0].text).relay).toEqual(relay);
126
+ await nextTick();
127
+ expect(JSON.parse(h.messages.find(m=>m.method==='ui/message').params.content[0].text).relay).toEqual(relay);
117
128
  });
118
129
  it('handles request changes followed by a new revision and approval in the same app',async()=>{
119
130
  const h=harness();h.respond(1);await nextTick();
@@ -121,8 +132,9 @@ describe('MCP Remotion bridge',()=>{
121
132
  const next={id:'second',revisionId:'r2',contentHash:'sha2',path:'/video.md',compiled:{children:[{name:'Next'}]}};
122
133
  h.result(first);
123
134
  h.selectSpot(0);h.nodes.feedback.value='lowercase title';h.nodes['save-spot'].onclick?.();h.nodes.changes.onclick?.();
124
- expect(JSON.parse(h.messages[2].params.content[0].text)).toMatchObject({path:'/video.md',revisionId:'r1',decision:'changes_requested',feedback:'lowercase title'});
125
- h.respond(2);await nextTick();
135
+ expect(JSON.parse(h.messages.find(m=>m.method==='ui/message').params.content[0].text)).toMatchObject({decision:'changes_requested'});
136
+ await nextTick();
137
+ h.respond(3);await nextTick();
126
138
  expect(h.nodes.status.textContent).toContain('Waiting for the updated preview');
127
139
  h.nodes.approve.onclick?.();
128
140
  expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(1);
@@ -130,7 +142,7 @@ describe('MCP Remotion bridge',()=>{
130
142
  h.nodes.approve.onclick?.();
131
143
  const decisions=h.messages.filter(m=>m.method==='ui/message').map(m=>JSON.parse(m.params.content[0].text));
132
144
  expect(decisions).toHaveLength(2);
133
- expect(decisions[1]).toMatchObject({path:'/video.md',revisionId:'r2',contentHash:'sha2',decision:'approved'});
145
+ expect(decisions[1]).toMatchObject({contentHash:'sha2',decision:'approved'});
134
146
  });
135
147
 
136
148
  });
@@ -186,7 +198,7 @@ describe('MCP Remotion bridge',()=>{
186
198
  dots=h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots;
187
199
  expect(dots.filter((x:any)=>x.scope==='overall')).toEqual([expect.objectContaining({text:'Overall draft'})]);
188
200
  });
189
- it('saves overall, scene and spot scopes at their canonical timeline positions',()=>{
201
+ it('saves overall, scene and spot scopes at their canonical timeline positions',async()=>{
190
202
  const h=harness();h.result({id:'multi',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
191
203
  h.selectSpot(0);
192
204
  h.nodes.feedback.value='Improve pacing';h.nodes['save-spot'].onclick?.();
@@ -200,10 +212,11 @@ describe('MCP Remotion bridge',()=>{
200
212
  expect(h.events.filter(e=>e.type==='markcut:comments-change').at(-1).detail.sceneNames).toEqual(['Scene-A']);
201
213
  h.nodes.approve.onclick?.();expect(h.nodes.status.textContent).toContain('Submit or remove');
202
214
  h.nodes.changes.onclick?.();
215
+ await nextTick();
203
216
  const payload=JSON.parse(h.messages.filter(m=>m.method==='ui/message').at(-1).params.content[0].text);
204
217
  expect(payload.comments.map((x:any)=>x.scope)).toEqual(['overall','scene','spot']);
205
218
  });
206
- it('supports multiple timed notes on one scene and restores a saved note',()=>{
219
+ it('supports multiple timed notes on one scene and restores a saved note',async()=>{
207
220
  const h=harness();
208
221
  h.result({id:'spots',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
209
222
  h.scene({sceneId:'s1',sceneName:'Scene-A',timeSeconds:1});
@@ -222,13 +235,14 @@ describe('MCP Remotion bridge',()=>{
222
235
  h.nodes.feedback.value='Trim first second';
223
236
  h.nodes['save-spot'].onclick?.();
224
237
  h.nodes.changes.onclick?.();
238
+ await nextTick();
225
239
  const payload=JSON.parse(h.messages.at(-1).params.content[0].text);
226
240
  expect(payload.comments).toHaveLength(2);
227
241
  expect(h.nodes['comment-count'].textContent).toBe('2 comments');
228
242
  expect(payload.comments.map((x:any)=>x.text)).toContain('Trim first second');
229
243
  expect(payload.comments.map((x:any)=>x.text)).toContain('Keep reaction');
230
244
  });
231
- it('keeps typed text across scope switches and blocks unsaved submission',()=>{
245
+ it('keeps typed text across scope switches and blocks unsaved submission',async()=>{
232
246
  const h=harness();h.result({id:'draft',revisionId:'r',contentHash:'hash',compiled:{children:[]}});
233
247
  h.scene({sceneId:'s1',sceneName:'Scene-A',sceneStart:2,timeSeconds:3});
234
248
  h.nodes.feedback.value='Keep this text';
@@ -240,9 +254,10 @@ describe('MCP Remotion bridge',()=>{
240
254
  const note=h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots.find((x:any)=>!x.placeholder);
241
255
  h.selectSpot(note.id);
242
256
  h.nodes.changes.onclick?.();
257
+ await nextTick();
243
258
  expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(1);
244
259
  });
245
- it('deletes only the selected timeline marker',()=>{
260
+ it('deletes only the selected timeline marker',async()=>{
246
261
  const h=harness();h.result({id:'dots',revisionId:'r1',contentHash:'hash',compiled:{children:[]}});
247
262
  h.scene({sceneId:'s1',sceneName:'Scene-A',timeSeconds:1});
248
263
  h.nodes.feedback.value='First';h.nodes['save-spot'].onclick?.();
@@ -255,6 +270,7 @@ describe('MCP Remotion bridge',()=>{
255
270
  expect(h.nodes['remove-spot'].disabled).toBe(true);
256
271
  expect(h.events.filter(e=>e.type==='markcut:spots-change').at(-1).detail.spots).toHaveLength(2);
257
272
  h.nodes.changes.onclick?.();
273
+ await nextTick();
258
274
  expect(JSON.parse(h.messages.at(-1).params.content[0].text).comments.map((x:any)=>x.text)).toEqual(['Second']);
259
275
  });
260
276
  describe('static compiled-JSON bridge',()=>{
@@ -1,6 +1,6 @@
1
1
  import {describe,it,expect} from 'vitest';
2
2
  process.env.NEOY_PUBLIC_ORIGIN = 'https://neoy.example.test';
3
- import {buildPreviewHtml,buildPreviewResourceResult,RESOURCE_URI,LEGACY_RESOURCE_URIS,validateMarkdownPath,reviewResult,getPreviewMedia,readPreviewAudio,withPreviewAudio} from '../src/mcp/preview.mjs';
3
+ import {buildPreviewHtml,buildPreviewResourceResult,RESOURCE_URI,LEGACY_RESOURCE_URIS,validateMarkdownPath,getPreviewMedia,readPreviewAudio,withPreviewAudio} from '../src/mcp/preview.mjs';
4
4
  import {buildPreviewBridgeScript} from '../src/mcp/bridge.mjs';
5
5
  import {mkdtemp,writeFile,rm} from 'node:fs/promises';
6
6
  import {tmpdir} from 'node:os';
@@ -20,7 +20,7 @@ describe('Markcut Remotion MCP App',()=>{
20
20
  expect(html).toContain('#comment-tools>*{width:30px;height:28px;padding:0;border:0');
21
21
  expect(html).toContain('https://neoy.example.test/files/_neoy/markcut/player/');
22
22
  expect(html).not.toContain('id="remotion-bundle"');
23
- expect(html.length).toBeLessThan(20000);
23
+ expect(html.length).toBeLessThan(24000);
24
24
  expect(html).not.toContain('<video id="video-player"');
25
25
  expect(html).not.toContain('data:video/mp4');
26
26
  expect(html).not.toContain('127.0.0.1');
@@ -44,7 +44,10 @@ describe('Markcut Remotion MCP App',()=>{
44
44
  expect(script).toContain('ui/notifications/tool-result');
45
45
  expect(script).toContain("CustomEvent('markcut:revision'");
46
46
  expect(script).toContain('data.compiled');
47
- expect(script).not.toContain("'tools/call'");
47
+ expect(script).not.toContain('markcut.review.decide');
48
+ expect(script).not.toContain('markcut.review.get');
49
+ expect(script).toContain("request('ui/message'");
50
+ expect(script).not.toContain('pollDecision');
48
51
  expect(script).not.toContain('videoBase64');
49
52
  expect(script).toContain('fetch(');
50
53
  expect(script).toContain('/files/_neoy/markcut/revisions/');
@@ -74,8 +77,4 @@ describe('Markcut Remotion MCP App',()=>{
74
77
  expect(compiled.root.children).toHaveLength(1);
75
78
  expect(mixed.root.durationInSeconds).toBe(6);
76
79
  });
77
- it('requires review feedback',()=>{
78
- expect(reviewResult('approved')).toEqual({decision:'approved'});
79
- expect(()=>reviewResult('changes_requested','')).toThrow(/feedback/);
80
- });
81
- });
80
+ });
@@ -0,0 +1,17 @@
1
+ import {describe,it,expect} from 'vitest';
2
+ import {readFile} from 'node:fs/promises';
3
+
4
+ describe('stateless Markcut review',()=>{
5
+ it('does not register review session tools or reference a session store',async()=>{
6
+ const server=await readFile(new URL('../src/mcp/server.mjs',import.meta.url),'utf8');
7
+ const operation=await readFile(new URL('../src/mcp/compile-operation.mjs',import.meta.url),'utf8');
8
+ const worker=await readFile(new URL('../src/mcp/compile-worker.mjs',import.meta.url),'utf8');
9
+ const source=server+operation+worker;
10
+ for(const tool of ['markcut.review.list','markcut.review.get','markcut.review.media','markcut.review.decide'])expect(source).not.toContain(tool);
11
+ expect(source).toContain('markcut.preview.media');
12
+ expect(server).toContain('media.playerUrl=publishPlayerBundle');
13
+ expect(source).not.toContain('review-sessions.json');
14
+ expect(source).not.toContain('createOrReuseReviewSession');
15
+ expect(source).not.toContain('publishReviewRevision');
16
+ });
17
+ });