@lalalic/markcut 3.2.44 → 3.2.45

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.
package/bin/markcut CHANGED
@@ -6,6 +6,17 @@ import { fileURLToPath } from "node:url";
6
6
  const __filename = fileURLToPath(import.meta.url);
7
7
  const __dirname = dirname(__filename);
8
8
  const root = resolve(__dirname, "..");
9
+ if (process.argv[2] === "preview" && process.argv.includes("--delivery")) {
10
+ const index=process.argv.indexOf("--delivery");
11
+ if (process.argv[index+1] !== "event") {
12
+ console.error("CLI review delivery supports only --delivery event; omit --delivery for the native preview.");
13
+ process.exit(1);
14
+ }
15
+ const entry=resolve(root,"src","mcp","mobile-review-cli.mjs");
16
+ const result=spawnSync(process.execPath,[entry,...process.argv.slice(2)],{stdio:"inherit"});
17
+ if(result.error)console.error(result.error.message);
18
+ process.exit(result.status??1);
19
+ }
9
20
  if (process.argv[2] === "queue") {
10
21
  const result = spawnSync(process.execPath, [resolve(root, "src", "queue-worker.mjs"), ...process.argv.slice(3)], { stdio: "inherit" });
11
22
  if (result.error) console.error(result.error.message);
@@ -50,8 +50,11 @@ See [docs/markdown-strict-descriptive.md](docs/markdown-strict-descriptive.md) f
50
50
  ```bash
51
51
  markcut render <file.json|.md> [--output path]
52
52
  markcut preview <file.json|.md> [--edit] [--label] [--port 3001]
53
+ markcut preview <file.md> --delivery event --event-template /absolute/event.json [--phone-url http://17.local:9223/mcp]
53
54
  ```
54
55
 
56
+ For Codex/terminal event delivery, `preview --delivery event` uses the hosted MCP compiler and an **asynchronous** Neo Mobile human review, rather than the local interactive browser. The `--event-template` file must follow Relay's canonical `task.interactive_decision` Contract. See `skills/markcut/references/mobile-event-preview-cli.md`. Only `text` (native preview) and `event` (phone-review route) are supported.
57
+
55
58
  ## Project structure
56
59
 
57
60
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lalalic/markcut",
3
- "version": "3.2.44",
3
+ "version": "3.2.45",
4
4
  "description": "Markdown-to-video engine. Describe scenes in markdown, get a rendered video.",
5
5
  "bin": {
6
6
  "markcut": "bin/markcut"
@@ -21,7 +21,7 @@
21
21
  "render:all": "node src/render/cli.mjs render",
22
22
  "render:demo": "node src/render/cli.mjs render src/demo-components.json",
23
23
  "templates": "node src/render/cli.mjs templates",
24
- "preview": "node src/render/cli.mjs preview",
24
+ "preview": "node bin/markcut preview",
25
25
  "mcp": "node src/mcp/server.mjs",
26
26
  "build:mcp": "scripts/build-mcp-preview.sh",
27
27
  "verify": "node src/render/cli.mjs verify",
@@ -16,6 +16,7 @@ Markcut turns a Markdown video definition into a compiled stream tree and a play
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. |
19
+ | Ask for human review from Codex/terminal via iPhone | Use `markcut preview <video.md> --delivery event --event-template <relay-event.json>` on Neo Master. The CLI queues the video in Neo Mobile Review Inbox; the phone sends the review Event when the person submits. |
19
20
  | Deliver a finished MP4 | `markcut render <file> --output <path>`; inspect the resulting video and sound. |
20
21
  | Visualize a route or trip | Use a Markdown `map` stream; load [route/map reference](docs/map-dynamic-camera.md). |
21
22
 
@@ -56,7 +57,8 @@ Asset paths are relative to the Markdown document. A `prompt` without `src` asks
56
57
  1. **Structure gate:** `npx @lalalic/markcut verify video.md`, then `npx @lalalic/markcut preview video.md --storyboard` when rapid scene review is useful. Storyboard placeholders do not verify generated media or final audio.
57
58
  2. **Playback gate:** `npx @lalalic/markcut preview video.md`. Play and seek representative scenes; check black tails, media loading, narration, BGM, subtitles, route movement, and timing. For browser failures, load [Preview Troubleshooting](references/preview-troubleshooting.md) on demand.
58
59
  3. **Human review gate:** Use Neo's `markcut.preview({path: "/absolute/path/video.md"})` when the user wants the hosted ChatGPT video player. This is **not** the CLI preview. The tool compiles/publishes a revision for playback; it does not rewrite the source. Comments with `decision: changes_requested` require editing that Markdown and calling `markcut.preview` again. `decision: approved` applies **only** to the identified revision/content hash; never apply an old approval to changed content. Follow [Review Contract](review.md) for actual video assessment.
59
- 4. **Delivery gate:** `npx @lalalic/markcut render video.md --output out/video.mp4`. Confirm the MP4 exists and examine playback, including the final audio and subtitles. A valid Markdown file, compile success, or hosted-player resource alone is not proof of a finished video.
60
+ 4. **Codex / terminal human-review gate:** `npx @lalalic/markcut preview /absolute/video.md --delivery event --event-template /absolute/relay-event.json` on Neo Master. The Event Template must match Relay's canonical `task.interactive_decision` Contract (`type`, `source`, `data.interactive.{jobId,taskId,executionId,invocationId}` only, without review-result fields). The CLI reuses the MCP compiler, publishes immutable preview assets, discovers the nearby `neox` phone by Bonjour (`--phone-url http://<phone>.local:9223/mcp` or `NEOX_MCP_URL` if discovery is unavailable), then submits `review.request` to that phone. Exit receipt `review_requested` confirms only that **the iPhone inbox accepted the request**; human decisions arrive asynchronously on Events Bus. If the app is suspended/offline, CLI fails visibly; **there is no background delivery queue or automatic text fallback**. Do not claim approval or Relay worker continuation from the receipt. For retries with an uncertain phone acknowledgment, pass a stable `--request-id UUID`. See [Codex/mobile review CLI](references/mobile-event-preview-cli.md).
61
+ 5. **Delivery gate:** `npx @lalalic/markcut render video.md --output out/video.mp4`. Confirm the MP4 exists and examine playback, including the final audio and subtitles. A valid Markdown file, compile success, or hosted-player resource alone is not proof of a finished video.
60
62
 
61
63
  If the user asks only for a script or structure, stop at the requested stage. Do not trigger expensive generation or claim final video delivery without a requested rendered artifact. A project-specific agent owns its own editorial or approval decisions; Markcut supplies authoring, playback and revision capabilities.
62
64
 
@@ -0,0 +1,33 @@
1
+ # Codex / terminal → Neo Mobile Event Preview
2
+
3
+ On **Neo Master**, with a current managed Relay Task execution context, create a JSON Event Template according to `agents-relay/skills/agents-relay/contracts/event-contract.md`. **Do not invent Job/Task/Execution identity.** Use the exact execution identity supplied by Relay, and a stable, unique `invocationId` for each new video review request. Do not prefill `decision`, `feedback`, `comments`, `revision`, `contentHash`, `revisionId`, `previewId`, `requestId`, or `idempotencyKey`.
4
+
5
+ Example illustrative template file (`/tmp/review-event.json`; replace placeholders with actual Relay Task values):
6
+
7
+ ```json
8
+ {
9
+ "type": "task.interactive_decision",
10
+ "source": "job/<jobId>/task/<taskId>/execution/<executionId>",
11
+ "data": {
12
+ "interactive": {
13
+ "jobId": "<jobId>",
14
+ "taskId": "<taskId>",
15
+ "executionId": "<executionId>",
16
+ "invocationId": "<unique-review-request-id>"
17
+ }
18
+ }
19
+ }
20
+ ```
21
+
22
+ Run:
23
+
24
+ ```sh
25
+ markcut verify /absolute/video.md
26
+ markcut preview /absolute/video.md --delivery event --event-template /tmp/review-event.json
27
+ ```
28
+
29
+ The CLI auto-discovers the `neox` `_mcp._tcp` service on the local network. Override if necessary with `--phone-url http://<trusted-phone>.local:9223/mcp` or `NEOX_MCP_URL`. Options: `--title`, `--group-id`, `--group-title`, `--request-id <UUID>`, `--timeout-ms`.
30
+
31
+ It starts the same detached Markcut MCP compile worker, waits for an immutable revision, and calls the phone's `review.request`. On phone acceptance it prints JSON, including `status: "review_requested"`, `requestId`, `contentHash`, and `revisionId`. It **does not wait for a human decision**. The phone must have the Neo app running and reachable; offline delivery is not supported by this CLI. A rejected/missing ACK exits nonzero. If reattempting after an uncertain ACK, supply the **same** request UUID to avoid duplicate phone requests. Phone users can inspect the compiled scenes and submit `approved` or `changes_requested`, which publishes `task.interactive_decision` through the existing authenticated Events MCP. The Event's `data.interactive` includes the exact reviewed hash, scene/timestamp comments, and idempotency key.
32
+
33
+ Relay's Event receiver and Graph decide whether to resume/revise the original Task. **A successful phone enqueue is not a human approval or a resumed Codex thread.** Do not mark the Task complete until a real human decision was correlated to the correct immutable revision and the downstream workflow actually completed. For a local browser-only preview, omit `--delivery event` and use normal `markcut preview`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Library:** Markcut (`markcut.preview` and Neo Mobile review clients)
4
4
  **Created:** 2026-11-05
5
- **Status:** Proposed — specification only; not implemented
5
+ **Status:** Implemented — Text/Event MCP and Neo Mobile, plus headless Codex CLI Event submission
6
6
  **Decision:** Use exactly two delivery modes, `text` and `event`. No callback registry, callback dispatcher, or Markcut-owned Relay workflow.
7
7
 
8
8
  ## Goal and boundaries
@@ -36,6 +36,14 @@ Let the same Markcut Preview player collect human review decisions, scene/timest
36
36
  3. Given intermittent connectivity, when a queued review is retried after reconnect or relaunch, then the original request ID, video identity and idempotency key are preserved.
37
37
  4. Given a new published video revision, when the user views history, then approval of an older revision remains scoped to that older `contentHash` and `revisionId`.
38
38
 
39
+ ### US-4: Trigger Event-mode Preview from Codex CLI (P1)
40
+
41
+ 1. Given a current Relay execution and a caller-authored JSON Event Template, when Codex runs `markcut preview <video.md> --delivery event --event-template <file.json>`, the CLI must validate the template, compile/publish the same immutable Markcut Preview assets as the MCP provider, then enqueue a native `review.request` on Neo Mobile.
42
+ 2. The CLI discovers Neo Mobile's current `_mcp._tcp` Bonjour service (or uses the explicit `--phone-url` / `NEOX_MCP_URL`), then requires a verifiable `{accepted:true,id:requestId}` phone receipt. It returns `review_requested` with the immutable revision hash. No ChatGPT iframe or callback registry is involved.
43
+ 3. The CLI exits after mobile receipt, rather than waiting for human action. User submission on iPhone publishes the canonical `task.interactive_decision` using the frozen template. **Event Bus transport acceptance is not Relay Graph completion or Codex continuation.**
44
+ 4. If the phone is asleep, unavailable, or its app is not listening, report delivery failure explicitly. The current CLI is foreground-phone-only; offline durable delivery/APNs are a separate feature. Do not fall back to a chat message.
45
+ 5. On retry after an uncertain ACK, reuse the same mobile `--request-id` (UUID) so the phone can deduplicate the request. Never repurpose an old revision's approval to a changed source.
46
+
39
47
  ## Public contract (proposed)
40
48
 
41
49
  ### Preview request
@@ -121,7 +129,8 @@ Relay's canonical Event Contract is at `agents-relay/skills/agents-relay/contrac
121
129
  - **FR-009**: Validate template source/type permissions server-side or at the authenticated event gateway; never trust a browser-provided Relay execution identity. Review events must not be accepted as `task.completed`, `task.failed`, or Final Reviewer approval events.
122
130
  - **FR-010**: Preserve review and approval scope per exact immutable revision. A new video revision requires fresh human approval; an Agent review cannot substitute for it.
123
131
  - **FR-011**: Make submission failures visible and retryable, with no success banner until an actual accepted receipt. Do not change delivery modes automatically on failure.
124
- - **FR-012**: Preserve compatibility for existing Neo Mobile requests carrying legacy `ownerCallbackTool` / `ownerThreadID` while migrating new requests to the explicit two-mode contract; do not introduce a third public mode.
132
+ - **FR-012**: Text is the existing Agent conversation path; Event is exclusively the canonical Relay `task.interactive_decision`. Old Markcut-specific event types are rejected. Existing Neo Mobile legacy storage fields do not define an additional public delivery mode.
133
+ - **FR-013**: Provide a headless `markcut preview --delivery event` CLI for Codex and terminal agents, using the same publisher/compiler, and enqueue the request through the phone's `review.request` MCP. Validate the caller-owned template and require an actual phone receipt.
125
134
 
126
135
  ## Ownership and downstream behavior
127
136
 
@@ -144,7 +153,7 @@ Relay's canonical Event Contract is at `agents-relay/skills/agents-relay/contrac
144
153
  2. **Mobile**: both modes pass device-level submission and offline retry tests. An Event-mode review reaches a test consumer with unchanged template-owned fields and correct scene/timestamp comments.
145
154
  3. **Safety**: stale hashes, forged source/types, missing event capability and cancelled consumer contexts cannot be misreported as accepted or approved.
146
155
  4. **Idempotency**: duplicate submits and repeated transport delivery produce at most one consumer-side business decision per key.
147
- 5. **Backward compatibility**: existing text-only ChatGPT preview and existing Neo Mobile feedback requests continue to work; no callback dispatcher is required.
156
+ 5. **Compatibility**: existing text-only ChatGPT preview continues to work; no callback dispatcher or deprecated Markcut event type is required.
148
157
  6. **End-to-end evidence**: actual hosted Preview and iPhone submissions are tested separately. Published/queued receipts alone do not prove downstream Relay execution, a fixed video, or final delivery.
149
158
 
150
159
  ## Non-goals
@@ -154,9 +163,10 @@ Relay's canonical Event Contract is at `agents-relay/skills/agents-relay/contrac
154
163
  - Making Markcut decide how Relay revises, reruns, approves, or merges Tasks.
155
164
  - Treating human Preview approval as Relay Final Reviewer approval.
156
165
 
157
- ## Implementation notes to validate before coding
166
+ ## Implementation and observed evidence (2026-11-05)
158
167
 
159
- - Today's Markcut Provider accepts `path` and optional `relay` metadata; it does **not yet** accept the proposed `review` option.
160
- - Today the hosted player delivers through `ui/message`; today Neo Mobile uses an `ownerCallbackTool` / Agent-turn fallback. Both need migration to the two-mode configuration.
161
- - The Neo Events Bus has a `publish` MCP tool, with a separate `events` command façade. Verify that the hosted MCP App is permitted to invoke the authorized event tool through its actual Host before implementing a direct UI publish route. If not supported, treat that as an integration constraint to resolve without creating a generic callback framework by default.
162
- - Current Events Bus assigns transport `event_id` internally; place caller-side idempotency in `data.review.idempotencyKey` and enforce deduplication at the consumer.
168
+ - Markcut's MCP tool supports both `text` and canonical Relay `event` delivery. The hosted Review UI and the Neo Mobile Event requester use the immutable `data.interactive` field names.
169
+ - Codex/terminal users can now call `markcut preview <video.md> --delivery event --event-template <file.json>`; this route starts the same hosted-preview compiler and sends the accepted revision to Neo Mobile using its `review.request` MCP, without invoking a ChatGPT iframe.
170
+ - The first Codex CLI → physical iPhone 17 → Events Bus test (isolated Job `999999993`) returned `review_requested` and accepted the Event Template. The iPhone Review Inbox displayed the request and the phone submitted `changes_requested` with precise revision metadata, producing one persisted `task.interactive_decision`. This proves the transport and mobile UI paths, **not** real Relay Graph job continuation.
171
+ - The CLI requires the Neo app's MCP listener to be reachable; at present this means the app needs to be active. An offline phone queue or APNs-mediated durable review request delivery remains a separate feature.
172
+ - Events Bus assigns the transport `event_id`; the mobile review result carries a stable `data.interactive.idempotencyKey`, and Relay consumes the canonical Task event. Code-level Graph/worker continuation verification remains owned by Relay.
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ /** Codex/terminal human-review bridge. The phone publishes the caller-owned Event after Submit. */
3
+ import {spawn} from 'node:child_process';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {readFileSync} from 'node:fs';
6
+ import {basename,join,resolve} from 'node:path';
7
+ import {pathToFileURL} from 'node:url';
8
+ import {normalizeReviewConfig} from './review-delivery.mjs';
9
+
10
+ const delay = ms => new Promise(done => setTimeout(done,ms));
11
+ const UUID = /^[a-f0-9-]{36}$/i;
12
+
13
+ export function parseEventPreviewOptions(argv) {
14
+ if (argv[0] !== 'preview' || !argv[1] || argv[1].startsWith('--')) throw new Error('Usage: markcut preview <file.md> --delivery event --event-template <file.json> [--phone-url <url>]');
15
+ const allowed=new Set(['--delivery','--event-template','--phone-url','--title','--group-id','--group-title','--request-id','--timeout-ms']);
16
+ const options={file:resolve(argv[1])};
17
+ for(let i=2;i<argv.length;i+=2){
18
+ const flag=argv[i],value=argv[i+1];
19
+ if(!allowed.has(flag) || !value || value.startsWith('--'))throw new Error('Missing or unsupported preview event flag: '+flag);
20
+ const key={'--delivery':'delivery','--event-template':'eventTemplatePath','--phone-url':'phoneUrl','--title':'title','--group-id':'groupId','--group-title':'groupTitle','--request-id':'requestId','--timeout-ms':'timeoutMs'}[flag];
21
+ if(Object.hasOwn(options,key))throw new Error('Duplicate flag: '+flag);
22
+ options[key]=value;
23
+ }
24
+ if(options.delivery!=='event' || !options.eventTemplatePath)throw new Error('Event delivery and --event-template file are required');
25
+ if(options.requestId && !UUID.test(options.requestId))throw new Error('--request-id must be a UUID');
26
+ const limit=options.timeoutMs===undefined ? 300000 : Number(options.timeoutMs);
27
+ if(!Number.isSafeInteger(limit) || limit<1000 || limit>1800000)throw new Error('--timeout-ms must be 1000..1800000');
28
+ options.timeoutMs=limit;
29
+ return options;
30
+ }
31
+
32
+ export function phoneUrlFromDnsSdText(text){
33
+ const m=text.match(/can be reached at ([a-z0-9._-]+):([0-9]{1,5})\b/i);
34
+ if(!m)return null;
35
+ const host=m[1].replace(/\.+$/,'');
36
+ if(!host.endsWith('.local') || Number(m[2])<1 || Number(m[2])>65535)return null;
37
+ return `http://${host}:${m[2]}/mcp`;
38
+ }
39
+
40
+ export async function discoverPhoneUrl(timeoutMs=4000){
41
+ return await new Promise((resolveDiscovery,rejectDiscovery)=>{
42
+ const proc=spawn('dns-sd',['-L','neox','_mcp._tcp','local'],{stdio:['ignore','pipe','pipe']});
43
+ let output='',settled=false;
44
+ const done=(error,value)=>{
45
+ if(settled)return;settled=true;clearTimeout(timeout);proc.kill('SIGTERM');
46
+ if(error)rejectDiscovery(error);else resolveDiscovery(value);
47
+ };
48
+ const timeout=setTimeout(()=>done(new Error('Neo Mobile not discoverable; launch Neo on iPhone or provide --phone-url')),timeoutMs);
49
+ proc.stdout.on('data',c=>{output+=String(c);if(output.length>8192)output=output.slice(-8192);const url=phoneUrlFromDnsSdText(output);if(url)done(null,url);});
50
+ proc.stderr.on('data',c=>{output+=String(c);});
51
+ proc.on('error',e=>done(e));
52
+ proc.on('exit',()=>done(new Error('Neo Mobile Bonjour discovery stopped before resolution')));
53
+ });
54
+ }
55
+
56
+ export function validatePhoneUrl(input){
57
+ const u=new URL(input);
58
+ if(u.username || u.password || u.search || u.hash || u.pathname!=='/mcp')throw new Error('Phone MCP URL must have only /mcp path');
59
+ const h=u.hostname.toLowerCase();
60
+ const local=h==='localhost'||h.endsWith('.local')||h==='127.0.0.1'||h.startsWith('10.')||h.startsWith('192.168.')||
61
+ /^172\.(1[6-9]|2[0-9]|3[01])\./.test(h);
62
+ if((u.protocol!=='http:' || !local) && u.protocol!=='https:')throw new Error('Phone MCP URL must be local HTTP or HTTPS');
63
+ return u.toString();
64
+ }
65
+
66
+ export function buildMobileReviewRequest(operation,template,options={}){
67
+ const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
68
+ const result=operation.result;
69
+ if(operation.state!=='ready' || !result || !/^[a-f0-9]{64}$/.test(result.contentHash||'') ||
70
+ !result.revisionId || !result.id)throw new Error('Compiled preview is not ready');
71
+ const details=config.eventTemplate.data.interactive;
72
+ const id=options.requestId??operation.id;
73
+ if(!UUID.test(id))throw new Error('Invalid review request identity');
74
+ const title=options.title?.trim() || basename(options.file??result.requestedPath??'Preview','.md');
75
+ return {
76
+ id,contentHash:result.contentHash,revisionId:result.revisionId,previewId:result.id,
77
+ title,groupId:options.groupId ?? `job/${details.jobId}/task/${details.taskId}`,
78
+ groupTitle:options.groupTitle ?? title,jobId:details.jobId,
79
+ delivery:'event',eventTemplate:config.eventTemplate,
80
+ };
81
+ }
82
+
83
+ export async function sendMobileReviewRequest(phoneUrl,request,{fetchImpl=fetch}={}){
84
+ const url=validatePhoneUrl(phoneUrl);
85
+ const payload={jsonrpc:'2.0',id:1,method:'tools/call',params:{name:'review.request',arguments:request}};
86
+ let lastError;
87
+ for(let attempt=0;attempt<2;attempt++){
88
+ try{
89
+ const response=await fetchImpl(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:AbortSignal.timeout(9000)});
90
+ if(!response.ok)throw new Error(`Phone MCP returned HTTP ${response.status}`);
91
+ const body=await response.json();
92
+ if(body.error || body.result?.isError)throw new Error('Phone MCP rejected review.request');
93
+ const text=body.result?.content?.find(item=>item.type==='text')?.text;
94
+ let receipt;
95
+ try{receipt=JSON.parse(text);}catch{throw new Error('Phone MCP returned no structured review receipt');}
96
+ if(receipt.accepted!==true || receipt.id!==request.id)throw new Error('Phone rejected the review request: '+String(text).slice(0,130));
97
+ return receipt;
98
+ }catch(e){lastError=e;if(attempt===0)await delay(400);}
99
+ }
100
+ throw lastError;
101
+ }
102
+
103
+ export async function runMobilePreview(argv){
104
+ const opts=parseEventPreviewOptions(argv);
105
+ const template=JSON.parse(readFileSync(resolve(opts.eventTemplatePath),'utf8'));
106
+ const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
107
+ // Check phone reachability before starting potentially expensive compilation.
108
+ const phoneUrl=validatePhoneUrl(opts.phoneUrl || process.env.NEOX_MCP_URL || await discoverPhoneUrl());
109
+ const [{startCompileOperation},{EXPORT_ROOT}]=await Promise.all([
110
+ import('./compile-operation.mjs'),import('./remote-assets.mjs'),
111
+ ]);
112
+ const operation=startCompileOperation(opts.file,undefined,config);
113
+ const stateFile=join(EXPORT_ROOT,'operations',operation.operationId+'.json');
114
+ let state;
115
+ const until=Date.now()+opts.timeoutMs;
116
+ while(Date.now()<until){
117
+ try{state=JSON.parse(readFileSync(stateFile,'utf8'));}catch{}
118
+ if(state?.state==='ready')break;
119
+ if(state?.state==='failed')throw new Error('Preview compile failed: '+state.error);
120
+ await delay(300);
121
+ }
122
+ if(state?.state!=='ready')throw new Error('Preview compile timed out; operation '+operation.operationId);
123
+ const request=buildMobileReviewRequest(state,config.eventTemplate,{...opts,file:opts.file});
124
+ const receipt=await sendMobileReviewRequest(phoneUrl,request);
125
+ return {accepted:receipt.accepted,duplicate:receipt.duplicate===true,
126
+ status:'review_requested',operationId:operation.operationId,requestId:request.id,
127
+ contentHash:request.contentHash,revisionId:request.revisionId,jobId:request.jobId,
128
+ delivery:'event',phone:'Neo Mobile'};
129
+ }
130
+
131
+ if(process.argv[1] && import.meta.url===pathToFileURL(resolve(process.argv[1])).href){
132
+ runMobilePreview(process.argv.slice(2)).then(result=>console.log(JSON.stringify(result))).catch(error=>{
133
+ console.error('Markcut mobile event preview failed: '+(error?.message||error));
134
+ process.exitCode=1;
135
+ });
136
+ }
@@ -64,6 +64,13 @@ Commands:
64
64
  verify <file> Parse + validate descriptive file
65
65
 
66
66
  preview <file.json|.md> Open player with live preview
67
+ --delivery event Headless human review via Neo Mobile (requires .md)
68
+ --event-template <file.json> Relay task.interactive_decision envelope from current Task
69
+ --phone-url <url> Neo Mobile HTTP MCP (optional; Bonjour autodiscovery)
70
+ --title <text> Optional title displayed in Review Inbox
71
+ --group-id <id> Stable video group; later revisions supersede earlier ones
72
+ --request-id <uuid> Stable mobile request UUID for retry after uncertain ACK
73
+ --timeout-ms <n> Compilation timeout (default 300000)
67
74
  --label Open label input overlay
68
75
  --storyboard Fast structure preview: replaces TTI/TTV prompt
69
76
  nodes with <StoryboardSlot> placeholders and
@@ -0,0 +1,62 @@
1
+ import {describe,it,expect,vi} from 'vitest';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {
4
+ parseEventPreviewOptions,phoneUrlFromDnsSdText,validatePhoneUrl,
5
+ buildMobileReviewRequest,sendMobileReviewRequest,
6
+ } from '../src/mcp/mobile-review-cli.mjs';
7
+ const hash='a'.repeat(64);
8
+ const eventTemplate={type:'task.interactive_decision',source:'job/j1/task/producer/execution/e1',data:{
9
+ interactive:{jobId:'j1',taskId:'producer',executionId:'e1',invocationId:'review-req-1'},
10
+ }};
11
+ const id=randomUUID();
12
+ const operation={id,state:'ready',result:{id:hash,contentHash:hash,revisionId:hash,requestedPath:'/tmp/preview.md'}};
13
+
14
+ describe('Codex CLI event preview to Neo Mobile',()=>{
15
+ it('requires an explicit event template and rejects incomplete or unexpected flags',()=>{
16
+ expect(parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','template.json']).delivery).toBe('event');
17
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event'])).toThrow(/event-template/);
18
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','callback','--event-template','template.json'])).toThrow();
19
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','t.json','--other','x'])).toThrow();
20
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','t.json','--request-id','bad'])).toThrow();
21
+ });
22
+ it('finds Neo Mobile from Bonjour but only permits trusted local HTTP or HTTPS MCP addresses',()=>{
23
+ const dns='18:45:31 neox._mcp._tcp.local. can be reached at 17.local.:9223 (interface 11)';
24
+ expect(phoneUrlFromDnsSdText(dns)).toBe('http://17.local:9223/mcp');
25
+ expect(phoneUrlFromDnsSdText('unrelated service')).toBeNull();
26
+ expect(validatePhoneUrl('http://10.0.0.241:9223/mcp')).toBe('http://10.0.0.241:9223/mcp');
27
+ expect(()=>validatePhoneUrl('http://example.org:9223/mcp')).toThrow();
28
+ expect(()=>validatePhoneUrl('http://17.local:9223/mcp?target=evil')).toThrow();
29
+ });
30
+ it('constructs the immutable revision request with the caller-owned template',()=>{
31
+ const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id,file:'/tmp/preview.md'});
32
+ expect(request).toMatchObject({id,contentHash:hash,revisionId:hash,previewId:hash,
33
+ delivery:'event',groupId:'job/j1/task/producer',jobId:'j1',title:'preview',
34
+ eventTemplate:{type:'task.interactive_decision',source:eventTemplate.source,data:{interactive:{invocationId:'review-req-1'}}}});
35
+ expect(request.eventTemplate.data.interactive).not.toHaveProperty('decision');
36
+ expect(()=>buildMobileReviewRequest(operation,{...eventTemplate,type:'markcut.review.submitted'},{})).toThrow();
37
+ expect(()=>buildMobileReviewRequest({...operation,result:{...operation.result,contentHash:'old'}},eventTemplate,{})).toThrow();
38
+ });
39
+ it('sends review.request to the phone and requires its accepted matching receipt',async()=>{
40
+ const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id});
41
+ const fakeFetch=vi.fn(async (_url,opts)=>{
42
+ const sent=JSON.parse(opts.body);
43
+ expect(sent).toMatchObject({method:'tools/call',params:{name:'review.request',arguments:request}});
44
+ return {ok:true,json:async()=>({result:{content:[{type:'text',text:JSON.stringify({accepted:true,duplicate:false,id})}]}})};
45
+ });
46
+ expect(await sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:fakeFetch})).toEqual({accepted:true,duplicate:false,id});
47
+ expect(fakeFetch).toHaveBeenCalledTimes(1);
48
+ });
49
+ it('reuses the same request identity on uncertain transport retries and refuses false success',async()=>{
50
+ const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id});
51
+ const stable=[];
52
+ const fakeFetch=vi.fn(async(_url,opts)=>{
53
+ stable.push(JSON.parse(opts.body).params.arguments.id);
54
+ if(stable.length===1)throw new Error('lost ACK');
55
+ return {ok:true,json:async()=>({result:{content:[{type:'text',text:JSON.stringify({accepted:true,duplicate:true,id})}]}})};
56
+ });
57
+ expect((await sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:fakeFetch})).duplicate).toBe(true);
58
+ expect(stable).toEqual([id,id]);
59
+ const reject=vi.fn(async()=>({ok:true,json:async()=>({result:{content:[{type:'text',text:'Error: invalid review request'}]}})}));
60
+ await expect(sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:reject})).rejects.toThrow(/no structured review receipt/);
61
+ });
62
+ });