@lalalic/markcut 3.2.48 → 3.2.50
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/docs/developer-reference.md +4 -0
- package/package.json +1 -1
- package/src/mcp/bridge.mjs +4 -2
- package/src/mcp/mobile-review-cli.mjs +12 -7
- package/src/mcp/review-delivery.mjs +6 -5
- package/src/mcp/server.mjs +2 -2
- package/src/render/cli.mjs +1 -0
- package/src/vision/cli.mjs +81 -19
- package/tests/mcp-preview-bridge.test.ts +2 -2
- package/tests/mcp-preview-delivery.test.ts +7 -6
- package/tests/mobile-preview-cli.test.ts +5 -3
- package/tests/vision-duration-metadata.test.ts +29 -0
- package/tests/vision-normalize-only.test.ts +55 -0
|
@@ -316,3 +316,7 @@ When extracting HTTPS BGM from a preview tree, traverse the tree **before** retu
|
|
|
316
316
|
## Route map framing
|
|
317
317
|
|
|
318
318
|
For `map view:route`, omit `zoom` to auto-fit geotagged stops to the Remotion composition dimensions, including 9:16 vertical output; auto-fit reserves 14% padding. The route schema and both descriptive compiler paths must leave omitted zoom undefined, or their old `zoom:10` defaults silently override the runtime fit. Explicit `zoom` and camera tweens still override fit. Verify the real browser map's zoom/center and rendered tiles, not just a successful Markdown compile or Google API HTTP response. A calculated Directions line is not proof of a recorded GPS track.
|
|
319
|
+
|
|
320
|
+
## Git-backed interactive Review identity (2026-11)
|
|
321
|
+
|
|
322
|
+
Event-mode Markcut Preview requires a full 40-character Git Commit SHA from a **validated** Neo Project Stage, supplied with `--commit-sha SHA` (CLI) or `review.commitSha` (MCP). The Neo Project Runner commits *before* preview delivery, then adds an immutable `review/rN` tag. The Neo Master REST request and Relay `task.interactive_decision` use `commitSha` as the only review revision identity (with `interactive.revision=commitSha`). `mediaHash` is retained separately for compiled preview media retrieval, **not** for decision binding; standalone `delivery:text` continues to use Markcut's internal compile cache identity. Never accept an Event review without an explicit SHA or silently revert to content-hash identity.
|
package/package.json
CHANGED
package/src/mcp/bridge.mjs
CHANGED
|
@@ -153,10 +153,10 @@ function eventEnvelope(template,review){
|
|
|
153
153
|
const fixed=template.data.interactive;
|
|
154
154
|
if(!match || !fixed || fixed.jobId!==match[1] || fixed.taskId!==match[2] ||
|
|
155
155
|
fixed.executionId!==match[3] || !fixed.invocationId ||
|
|
156
|
-
['decision','feedback','comments','revision','revisionId','contentHash','previewId','requestId','idempotencyKey']
|
|
156
|
+
['decision','feedback','comments','revision','revisionId','contentHash','commitSha','previewId','requestId','idempotencyKey']
|
|
157
157
|
.some(key=>Object.prototype.hasOwnProperty.call(fixed,key)))throw new Error('Invalid bound interactive decision');
|
|
158
158
|
return {type:template.type,source:template.source,data:{...template.data,interactive:{
|
|
159
|
-
...fixed,revision:
|
|
159
|
+
...fixed,revision:activeReview.commitSha,commitSha:activeReview.commitSha,
|
|
160
160
|
previewId:review.previewId,requestId:review.requestId,decision:review.decision,
|
|
161
161
|
feedback:review.feedback||review.comments.map(c=>c.text).join('\\n'),
|
|
162
162
|
comments:review.comments,idempotencyKey:review.idempotencyKey
|
|
@@ -164,6 +164,8 @@ function eventEnvelope(template,review){
|
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
async function sendReviewEvent(result){
|
|
167
|
+
if(!/^[a-f0-9]{40}$/.test(activeReview.commitSha||''))throw new Error('Review requires Git Commit SHA');
|
|
168
|
+
result.commitSha=activeReview.commitSha;
|
|
167
169
|
const event=eventEnvelope(activeReview.eventTemplate,result);
|
|
168
170
|
// MCP Apps tools/call is host-mediated; an unavailable or unauthorized Events
|
|
169
171
|
// provider MUST fail, never be substituted with ui/message.
|
|
@@ -10,17 +10,20 @@ const delay = ms => new Promise(done => setTimeout(done,ms));
|
|
|
10
10
|
|
|
11
11
|
export function parseEventPreviewOptions(argv) {
|
|
12
12
|
if (argv[0] !== 'preview' || !argv[1] || argv[1].startsWith('--')) throw new Error('Usage: markcut preview <file.md> --delivery event --event-template <file.json>');
|
|
13
|
-
const allowed=new Set(['--delivery','--event-template','--timeout-ms']);
|
|
13
|
+
const allowed=new Set(['--delivery','--event-template','--timeout-ms','--commit-sha']);
|
|
14
14
|
const options={file:resolve(argv[1])};
|
|
15
15
|
for(let i=2;i<argv.length;i+=2){
|
|
16
16
|
const flag=argv[i],value=argv[i+1];
|
|
17
17
|
if(!allowed.has(flag) || !value || value.startsWith('--'))throw new Error('Missing or unsupported preview event flag: '+flag);
|
|
18
|
-
const key={'--delivery':'delivery','--event-template':'eventTemplatePath','--timeout-ms':'timeoutMs'}[flag];
|
|
18
|
+
const key={'--delivery':'delivery','--event-template':'eventTemplatePath','--timeout-ms':'timeoutMs','--commit-sha':'commitSha'}[flag];
|
|
19
19
|
if(Object.hasOwn(options,key))throw new Error('Duplicate flag: '+flag);
|
|
20
20
|
options[key]=value;
|
|
21
21
|
}
|
|
22
22
|
if(!['text','event'].includes(options.delivery) || (options.delivery==='event')!==Boolean(options.eventTemplatePath))
|
|
23
23
|
throw new Error('Event delivery requires --event-template; Text delivery must omit it');
|
|
24
|
+
if(options.delivery==='event' && !/^[a-f0-9]{40}$/.test(options.commitSha||''))
|
|
25
|
+
throw new Error('Event review requires --commit-sha with full 40-character Git SHA');
|
|
26
|
+
if(options.delivery==='text' && options.commitSha)throw new Error('Text previews do not bind a Git Commit SHA');
|
|
24
27
|
const limit=options.timeoutMs===undefined ? 300000 : Number(options.timeoutMs);
|
|
25
28
|
if(!Number.isSafeInteger(limit) || limit<1000 || limit>1800000)throw new Error('--timeout-ms must be 1000..1800000');
|
|
26
29
|
options.timeoutMs=limit;
|
|
@@ -52,14 +55,16 @@ export function buildReviewRequest(options,config,state,operationId){
|
|
|
52
55
|
if(!data||typeof data.contentHash!=='string'||typeof data.revisionId!=='string'||
|
|
53
56
|
!data.contentHash.match(/^[a-f0-9]{64}$/)||!data.revisionId)
|
|
54
57
|
throw Error('Compiled Preview has no immutable revision identity');
|
|
55
|
-
const request={id:operationId,
|
|
56
|
-
previewId:data.id,title:basename(options.file,'.md'),delivery:config.delivery};
|
|
58
|
+
const request={id:operationId,previewId:data.id,title:basename(options.file,'.md'),delivery:config.delivery};
|
|
57
59
|
if(config.delivery==='event'){
|
|
60
|
+
if(!/^[a-f0-9]{40}$/.test(options.commitSha||''))throw Error('Git Commit SHA required for Event Review');
|
|
61
|
+
request.commitSha=options.commitSha;
|
|
62
|
+
request.mediaHash=data.contentHash; // Transport-only lookup for the compiled player, never the review identity.
|
|
58
63
|
const fixed=config.eventTemplate.data.interactive;
|
|
59
64
|
request.eventTemplate=config.eventTemplate;
|
|
60
65
|
request.jobId=fixed.jobId;
|
|
61
66
|
request.groupId=`job/${fixed.jobId}/task/${fixed.taskId}`;
|
|
62
|
-
}else request.groupId=options.file;
|
|
67
|
+
}else {request.contentHash=data.contentHash;request.revisionId=data.revisionId;request.groupId=options.file;}
|
|
63
68
|
return request;
|
|
64
69
|
}
|
|
65
70
|
export async function submitNeoReview(request,{fetchImpl=fetch,url=neoReviewEndpoint()}={}){
|
|
@@ -79,7 +84,7 @@ export async function submitNeoReview(request,{fetchImpl=fetch,url=neoReviewEndp
|
|
|
79
84
|
|
|
80
85
|
export async function runMobilePreview(argv){
|
|
81
86
|
const opts=parseEventPreviewOptions(argv);
|
|
82
|
-
const config=opts.delivery==='event' ? normalizeReviewConfig({delivery:'event',
|
|
87
|
+
const config=opts.delivery==='event' ? normalizeReviewConfig({delivery:'event',commitSha:opts.commitSha,
|
|
83
88
|
eventTemplate:JSON.parse(readFileSync(resolve(opts.eventTemplatePath),'utf8'))}) : {delivery:'text'};
|
|
84
89
|
const [{startCompileOperation},{EXPORT_ROOT}]=await Promise.all([
|
|
85
90
|
import('./compile-operation.mjs'),import('./remote-assets.mjs'),
|
|
@@ -98,7 +103,7 @@ export async function runMobilePreview(argv){
|
|
|
98
103
|
const request=buildReviewRequest(opts,config,state,operation.operationId);
|
|
99
104
|
const receipt=await submitNeoReview(request);
|
|
100
105
|
return {status:'review_requested',operationId:operation.operationId,requestId:request.id,
|
|
101
|
-
contentHash:state.result.contentHash,revisionId:state.result.revisionId,
|
|
106
|
+
...(opts.delivery==='event' ? {commitSha:opts.commitSha} : {contentHash:state.result.contentHash,revisionId:state.result.revisionId}),
|
|
102
107
|
...(config.delivery==='event' ? {jobId:config.eventTemplate.data.interactive.jobId} : {}),
|
|
103
108
|
delivery:config.delivery,notification:receipt.accepted?'apns_submitted':'inbox_stored'};
|
|
104
109
|
}
|
|
@@ -3,7 +3,7 @@ const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
|
3
3
|
const SOURCE = /^job\/[A-Za-z0-9_-]+\/task\/[A-Za-z0-9_-]+\/execution\/[A-Za-z0-9_-]+$/;
|
|
4
4
|
const RECORD = value => value && typeof value === "object" && !Array.isArray(value);
|
|
5
5
|
const INTERACTIVE_TYPE = "task.interactive_decision";
|
|
6
|
-
const REVIEW_FIELDS = ["decision","feedback","comments","revision","revisionId","contentHash","previewId","requestId","idempotencyKey"];
|
|
6
|
+
const REVIEW_FIELDS = ["decision","feedback","comments","revision","revisionId","contentHash","commitSha","previewId","requestId","idempotencyKey"];
|
|
7
7
|
function copyData(value) {
|
|
8
8
|
if (!RECORD(value)) throw new Error("eventTemplate.data must be an object");
|
|
9
9
|
// No executable values or reserved overrides can be shipped in a template.
|
|
@@ -40,25 +40,26 @@ export function normalizeReviewConfig(value) {
|
|
|
40
40
|
!ID.test(interactive.invocationId||"") ||
|
|
41
41
|
REVIEW_FIELDS.some(field=>Object.hasOwn(interactive,field)))
|
|
42
42
|
throw new Error("Invalid task.interactive_decision event template");
|
|
43
|
-
|
|
43
|
+
if (!/^[a-f0-9]{40}$/.test(value.commitSha||"")) throw new Error("Event review requires full Git Commit SHA");
|
|
44
|
+
return {delivery:"event",commitSha:value.commitSha,eventTemplate:{
|
|
44
45
|
type:template.type,source:template.source,data,
|
|
45
46
|
}};
|
|
46
47
|
}
|
|
47
48
|
export function eventForReview(config,review) {
|
|
48
49
|
const {eventTemplate:template}=normalizeReviewConfig(config);
|
|
49
50
|
if (!template) throw new Error("Event mode required");
|
|
50
|
-
if (!RECORD(review) || !ID.test(review.requestId || "") ||
|
|
51
|
-
|| !/^[a-f0-9]{64}$/.test(review.contentHash || "")
|
|
51
|
+
if (!RECORD(review) || !ID.test(review.requestId || "") || !/^[a-f0-9]{40}$/.test(review.commitSha || "")
|
|
52
52
|
|| !["approved","changes_requested"].includes(review.decision)
|
|
53
53
|
|| !ID.test(review.idempotencyKey || "") || !Array.isArray(review.comments))
|
|
54
54
|
throw new Error("Invalid review result");
|
|
55
|
+
if (review.commitSha !== config.commitSha)throw new Error("Review Commit SHA differs from immutable preview request");
|
|
55
56
|
const details=template.data.interactive;
|
|
56
57
|
const feedback=typeof review.feedback==="string" ? review.feedback :
|
|
57
58
|
review.comments.map(comment=>comment.text).filter(value=>typeof value==="string").join("\n");
|
|
58
59
|
return {type:INTERACTIVE_TYPE,source:template.source,data:{
|
|
59
60
|
...template.data,
|
|
60
61
|
interactive:{...details,
|
|
61
|
-
revision:review.
|
|
62
|
+
revision:review.commitSha,commitSha:review.commitSha,
|
|
62
63
|
previewId:review.previewId,requestId:review.requestId,
|
|
63
64
|
decision:review.decision,feedback,comments:structuredClone(review.comments),
|
|
64
65
|
idempotencyKey:review.idempotencyKey},
|
package/src/mcp/server.mjs
CHANGED
|
@@ -47,10 +47,10 @@ registerAppTool(
|
|
|
47
47
|
server,
|
|
48
48
|
TOOL_NAME,
|
|
49
49
|
{
|
|
50
|
-
description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. Review delivery defaults to ui/message, or submits an authorized caller-bound event when explicitly configured.
|
|
50
|
+
description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. Review delivery defaults to ui/message, or submits an authorized caller-bound event when explicitly configured. Event-mode decisions bind the verified 40-character Git Commit SHA, not the compiled-media cache hash.",
|
|
51
51
|
inputSchema: z.object({
|
|
52
52
|
path: z.string().describe("Absolute .md path or NeoY HTTPS mounted file URL"),
|
|
53
|
-
review: z.object({delivery:z.enum(["text","event"]).optional(),eventTemplate:z.object({type:z.string(),source:z.string(),data:z.record(z.string(),z.unknown())}).optional()}).optional(),
|
|
53
|
+
review: z.object({delivery:z.enum(["text","event"]).optional(),commitSha:z.string().regex(/^[a-f0-9]{40}$/).optional(),eventTemplate:z.object({type:z.string(),source:z.string(),data:z.record(z.string(),z.unknown())}).optional()}).optional(),
|
|
54
54
|
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."),
|
|
55
55
|
}),
|
|
56
56
|
_meta: {
|
package/src/render/cli.mjs
CHANGED
|
@@ -85,6 +85,7 @@ Commands:
|
|
|
85
85
|
--verbose Show full per-frame progress (default: compact)
|
|
86
86
|
|
|
87
87
|
vision <folder> Full pipeline: extract → normalize → percept → segments
|
|
88
|
+
--normalize-only Produce lightweight Vision Understanding files without AI
|
|
88
89
|
--label Add interactive labeling step before AI pipeline
|
|
89
90
|
--instruct "text" Background context about people/places (injected into prompts)
|
|
90
91
|
|
package/src/vision/cli.mjs
CHANGED
|
@@ -207,8 +207,10 @@ function extractMetadata(filePath) {
|
|
|
207
207
|
}
|
|
208
208
|
} catch { /* fall through */ }
|
|
209
209
|
|
|
210
|
-
//
|
|
211
|
-
|
|
210
|
+
// Always probe videos for their precise duration. ExifTool's formatted
|
|
211
|
+
// Duration can be "0:01:16" or "1 min 16 sec", which parseFloat misreads
|
|
212
|
+
// as 0 or 1 even when it has already reported valid width/height.
|
|
213
|
+
if (!width || !height || VIDEO_EXTS.has(extname(filePath).toLowerCase())) {
|
|
212
214
|
try {
|
|
213
215
|
const probe = JSON.parse(run(
|
|
214
216
|
`ffprobe -v quiet -print_format json -show_format -show_streams ${shQuote(filePath)}`,
|
|
@@ -218,7 +220,8 @@ function extractMetadata(filePath) {
|
|
|
218
220
|
const videoStream = streams.find((s) => s.codec_type === "video") || {};
|
|
219
221
|
width = width || videoStream.width || 0;
|
|
220
222
|
height = height || videoStream.height || 0;
|
|
221
|
-
|
|
223
|
+
const probedDuration = Number(format.duration);
|
|
224
|
+
if (Number.isFinite(probedDuration) && probedDuration > 0) duration = probedDuration;
|
|
222
225
|
created = created || format.tags?.creation_time || videoStream.tags?.creation_time || null;
|
|
223
226
|
if (!location && format.tags) {
|
|
224
227
|
const iso = format.tags["com.apple.quicktime.location.ISO6709"] || "";
|
|
@@ -282,7 +285,7 @@ function normalizeImage(srcPath, normDir, maxDim = MAX_IMAGE_DIMENSION) {
|
|
|
282
285
|
const outPath = join(normDir, outName);
|
|
283
286
|
if (existsSync(outPath)) return outPath;
|
|
284
287
|
const filter = `scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease`;
|
|
285
|
-
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -vf ${shQuote(filter)} -q:v 3 -update 1 ${shQuote(outPath)}`;
|
|
288
|
+
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -map_metadata -1 -vf ${shQuote(filter)} -q:v 3 -update 1 ${shQuote(outPath)}`;
|
|
286
289
|
try { run(cmd); return outPath; }
|
|
287
290
|
catch (e) { emitWarn(`Failed to normalize image ${basename(srcPath)}: ${e.message}`); return srcPath; }
|
|
288
291
|
}
|
|
@@ -299,7 +302,7 @@ function normalizeVideo(srcPath, normDir, duration, maxDim = MAX_VIDEO_DIMENSION
|
|
|
299
302
|
const outPath = join(normDir, outName);
|
|
300
303
|
if (existsSync(outPath)) return { path: outPath, trimmedDuration: totalDur, timeHint };
|
|
301
304
|
const filter = `scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1`;
|
|
302
|
-
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -t ${totalDur} -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -c:a aac -b:a 64k ${shQuote(outPath)}`;
|
|
305
|
+
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -t ${totalDur} -map_metadata -1 -map_chapters -1 -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -c:a aac -b:a 64k ${shQuote(outPath)}`;
|
|
303
306
|
try { run(cmd, { timeout: 600_000 }); return { path: outPath, trimmedDuration: totalDur, timeHint }; }
|
|
304
307
|
catch (e) { emitWarn(`Failed to normalize video ${basename(srcPath)}: ${e.message}`); return { path: srcPath, trimmedDuration: totalDur, timeHint }; }
|
|
305
308
|
}
|
|
@@ -313,7 +316,7 @@ function normalizeVideo(srcPath, normDir, duration, maxDim = MAX_VIDEO_DIMENSION
|
|
|
313
316
|
const step = Math.max(1, Math.floor(frameCount / maxSamples));
|
|
314
317
|
const actualSamples = Math.min(maxSamples, Math.ceil(frameCount / step));
|
|
315
318
|
const filter = `select='not(mod(n,${step}))',setpts=N/TB,scale='min(${maxDim},iw)':'min(${maxDim},ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1`;
|
|
316
|
-
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -an -t ${actualSamples} -r 1 ${shQuote(outPath)}`;
|
|
319
|
+
const cmd = `ffmpeg -y -i ${shQuote(srcPath)} -map_metadata -1 -map_chapters -1 -vf ${shQuote(filter)} -c:v libx264 -preset fast -crf 28 -an -t ${actualSamples} -r 1 ${shQuote(outPath)}`;
|
|
317
320
|
try {
|
|
318
321
|
emitInfo(` Sampling ${actualSamples} frames across ${totalDur.toFixed(1)}s video`);
|
|
319
322
|
run(cmd, { timeout: 600_000 });
|
|
@@ -809,6 +812,27 @@ function buildMergedCues(userHint, cues, sceneChangesMs, totalDurationMs) {
|
|
|
809
812
|
return merged;
|
|
810
813
|
}
|
|
811
814
|
|
|
815
|
+
/** Make a source-time-faithful, metadata-stripped clip for one VTT segment.
|
|
816
|
+
* Never seek a long video's uniformly sampled understanding copy with original
|
|
817
|
+
* timestamps, and never let an empty ffmpeg output masquerade as evidence.
|
|
818
|
+
*/
|
|
819
|
+
function extractOriginalSegment(original, output, startSec, durationSec) {
|
|
820
|
+
if (!Number.isFinite(startSec) || startSec < 0 || !Number.isFinite(durationSec) || durationSec <= 0) {
|
|
821
|
+
throw new Error("Invalid source segment range");
|
|
822
|
+
}
|
|
823
|
+
const clipFilter = "scale='min(360,iw)':'min(360,ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1";
|
|
824
|
+
if (!existsSync(output) || getVideoDuration(output) <= 0) {
|
|
825
|
+
try { rmSync(output, { force: true }); } catch {}
|
|
826
|
+
run(`ffmpeg -y -i ${shQuote(original)} -ss ${startSec} -t ${durationSec} -map_metadata -1 -map_chapters -1 -vf ${shQuote(clipFilter)} -c:v libx264 -preset fast -crf 28 -an -fflags +genpts ${shQuote(output)}`, { timeout: 120_000 });
|
|
827
|
+
}
|
|
828
|
+
const actualDuration = getVideoDuration(output);
|
|
829
|
+
if (!Number.isFinite(actualDuration) || actualDuration <= 0) {
|
|
830
|
+
try { rmSync(output, { force: true }); } catch {}
|
|
831
|
+
throw new Error(`Cannot decode source segment at ${startSec}s for ${durationSec}s`);
|
|
832
|
+
}
|
|
833
|
+
return output;
|
|
834
|
+
}
|
|
835
|
+
|
|
812
836
|
function analyzeVideo(videoPath, normInfo, normDir, prompts, context = "", userHint = "", sampleInterval = DEFAULT_VTT_SAMPLE_INTERVAL, userHints = null, skipSTT = false) {
|
|
813
837
|
let ctxParts = [];
|
|
814
838
|
if (context) ctxParts.push(`Context: ${context}`);
|
|
@@ -937,23 +961,18 @@ function analyzeVideo(videoPath, normInfo, normDir, prompts, context = "", userH
|
|
|
937
961
|
|
|
938
962
|
const clipName = `${basename(normInfo.path, extname(normInfo.path))}_seg_${key}.mp4`;
|
|
939
963
|
const clipOut = join(segDir, clipName);
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
try {
|
|
946
|
-
// Use -ss after -i (output seek) for accurate duration metadata
|
|
947
|
-
run(`ffmpeg -y -i ${shQuote(srcForClip)} -ss ${startSec} -t ${durSec} -vf ${shQuote(clipFilter)} -c:v libx264 -preset fast -crf 28 -an -fflags +genpts ${shQuote(clipOut)}`, { timeout: 120_000 });
|
|
948
|
-
if (existsSync(clipOut)) clipPath = clipOut;
|
|
949
|
-
} catch { /* fallback */ }
|
|
950
|
-
} else { clipPath = clipOut; }
|
|
964
|
+
// Segment keys are ORIGINAL source timestamps. Long recordings have a
|
|
965
|
+
// uniformly sampled understanding copy whose seconds do not map 1:1 to
|
|
966
|
+
// the original timeline; seeking it can produce empty late segments.
|
|
967
|
+
// Extract from the original, then scale/strip its metadata for VTT.
|
|
968
|
+
const clipPath = extractOriginalSegment(videoPath, clipOut, startSec, durSec);
|
|
951
969
|
|
|
952
970
|
// Use runVTT for video clips (extracts frames, then runs ITT)
|
|
953
971
|
const segRawVis = runVTT(clipPath, visSegPrompt, DEFAULT_VTT_CLI, DEFAULT_ITT_CLI, sampleInterval);
|
|
954
972
|
const segVisText = extractRawText(segRawVis);
|
|
955
973
|
seg.vision = stripThinkBlocks(looseJSONParse(segRawVis)?.desc || segVisText.slice(0, 300) || segRawVis.slice(0, 300));
|
|
956
|
-
|
|
974
|
+
if (!seg.vision?.trim()) throw new Error(`Segment ${key} returned no verified visual response`);
|
|
975
|
+
try { rmSync(clipPath, { force: true }); } catch {}
|
|
957
976
|
}
|
|
958
977
|
try { rmSync(segDir, { recursive: true, force: true }); } catch {}
|
|
959
978
|
perception.segments = segments;
|
|
@@ -1105,7 +1124,14 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
|
|
|
1105
1124
|
|
|
1106
1125
|
emitInfo(`\n🎬 Video: ${base}${userHint ? ` (hint: "${userHint}")` : ""}`);
|
|
1107
1126
|
const vidPath = join(folder, fileName);
|
|
1108
|
-
|
|
1127
|
+
// Existing metadata.json may contain an incomplete or incorrectly parsed
|
|
1128
|
+
// ExifTool Duration from a previous extraction. Reconcile against the
|
|
1129
|
+
// original container before using it for segmentation and handoff.
|
|
1130
|
+
const originalDuration = getVideoDuration(vidPath);
|
|
1131
|
+
if (!Number.isFinite(originalDuration) || originalDuration <= 0)
|
|
1132
|
+
throw new Error(`Video has no usable original duration: ${fileName}`);
|
|
1133
|
+
meta.duration = originalDuration;
|
|
1134
|
+
const normInfo = normalizeVideo(vidPath, normDir, originalDuration);
|
|
1109
1135
|
let perception = {};
|
|
1110
1136
|
let cacheKey = "";
|
|
1111
1137
|
const ctxV = context ? `Context: ${context}\n\n` : "";
|
|
@@ -1152,9 +1178,11 @@ markcut vision — Analyze images and videos in a folder for video generation
|
|
|
1152
1178
|
Usage:
|
|
1153
1179
|
markcut vision <folder> Full pipeline: extract → normalize → percept → segments
|
|
1154
1180
|
markcut vision <folder> --label Same as default, plus interactive labeling step before AI
|
|
1181
|
+
markcut vision <folder> --normalize-only Produce token-efficient Vision Understanding inputs without AI
|
|
1155
1182
|
|
|
1156
1183
|
Options:
|
|
1157
1184
|
--label Open interactive labeling preview before running AI pipeline
|
|
1185
|
+
--normalize-only 360px video / 384px image inputs, full input-time mapping; long videos sampled; no AI
|
|
1158
1186
|
--instruct "text" Background context about people/places (injected into prompts)
|
|
1159
1187
|
--prompts-file <path> Path to prompts markdown file (default: vision_prompts.md)
|
|
1160
1188
|
--vtt-sample-interval <n> Sample one video frame every N seconds (default: 5)
|
|
@@ -1180,6 +1208,7 @@ export async function main(args) {
|
|
|
1180
1208
|
let skipSTT = false;
|
|
1181
1209
|
let dryRun = false;
|
|
1182
1210
|
let doLabel = false;
|
|
1211
|
+
let normalizeOnly = false;
|
|
1183
1212
|
let candidateMode = false;
|
|
1184
1213
|
let output = "";
|
|
1185
1214
|
let modelCommand = "";
|
|
@@ -1199,6 +1228,7 @@ export async function main(args) {
|
|
|
1199
1228
|
const flag = args[i++];
|
|
1200
1229
|
if (flag === "--help") { printUsage(); return; }
|
|
1201
1230
|
else if (flag === "--label") { doLabel = true; }
|
|
1231
|
+
else if (flag === "--normalize-only") { normalizeOnly = true; }
|
|
1202
1232
|
else if (["--itt", "--vtt", "--agent", "--stt", "--tts", "--tti", "--ttv", "--edit-cli"].includes(flag) && args[i]) { i++; }
|
|
1203
1233
|
else if (flag === "--candidate") { candidateMode = true; }
|
|
1204
1234
|
else if (flag === "--output" && args[i]) { output = resolve(args[i++]); }
|
|
@@ -1248,6 +1278,36 @@ export async function main(args) {
|
|
|
1248
1278
|
return;
|
|
1249
1279
|
}
|
|
1250
1280
|
|
|
1281
|
+
if (normalizeOnly) {
|
|
1282
|
+
if (doLabel || candidateMode || dryRun || pickSet.size > 0) {
|
|
1283
|
+
throw new Error('--normalize-only cannot be combined with label, candidate, pick or dry-run');
|
|
1284
|
+
}
|
|
1285
|
+
// Reuse exactly the normalization used by the VTT/ITT pipeline. No AI
|
|
1286
|
+
// inference or full-resolution media is sent to an understanding model.
|
|
1287
|
+
const media = scanMedia(folder);
|
|
1288
|
+
if (media.images.length + media.videos.length === 0) throw new Error('No Vision Understanding source media');
|
|
1289
|
+
const normDir = join(folder, '.normalized');
|
|
1290
|
+
mkdirSync(normDir, { recursive: true });
|
|
1291
|
+
const files = [];
|
|
1292
|
+
for (const original of media.images) {
|
|
1293
|
+
const normalized = normalizeImage(original, normDir);
|
|
1294
|
+
if (normalized === original || !existsSync(normalized)) throw new Error(`Failed to normalize Vision image: ${original}`);
|
|
1295
|
+
files.push({ source: basename(original), path: normalized, kind: 'image', sampled: false,
|
|
1296
|
+
maxDimension: MAX_IMAGE_DIMENSION });
|
|
1297
|
+
}
|
|
1298
|
+
for (const original of media.videos) {
|
|
1299
|
+
const duration = getVideoDuration(original);
|
|
1300
|
+
if (!Number.isFinite(duration) || duration <= 0) throw new Error(`Video has no usable duration: ${original}`);
|
|
1301
|
+
const info = normalizeVideo(original, normDir, duration);
|
|
1302
|
+
if (info.path === original || !existsSync(info.path)) throw new Error(`Failed to normalize Vision video: ${original}`);
|
|
1303
|
+
files.push({ source: basename(original), path: info.path, kind: 'video',
|
|
1304
|
+
sampled: duration > MAX_VIDEO_DURATION, sourceDurationSeconds: duration,
|
|
1305
|
+
maxDimension: MAX_VIDEO_DIMENSION });
|
|
1306
|
+
}
|
|
1307
|
+
console.log(JSON.stringify({ status: 'PASS', usage: 'vision-understanding-only',
|
|
1308
|
+
profile: 'markcut-vision-normalized-v1', files }));
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1251
1311
|
if (doLabel) {
|
|
1252
1312
|
// Full pipeline with interactive labeling
|
|
1253
1313
|
await runFullPipeline(folder, prompts, context, pickSet, vttSampleInterval, skipSTT, dryRun);
|
|
@@ -1276,6 +1336,8 @@ export async function main(args) {
|
|
|
1276
1336
|
// ═════════════════════════════════════════════════════════════════════════
|
|
1277
1337
|
|
|
1278
1338
|
export {
|
|
1339
|
+
extractOriginalSegment,
|
|
1340
|
+
extractMetadata,
|
|
1279
1341
|
scanMedia,
|
|
1280
1342
|
buildPreviewTree,
|
|
1281
1343
|
mergeLabelsIntoMetadata,
|
|
@@ -377,7 +377,7 @@ describe('Review event delivery',()=>{
|
|
|
377
377
|
const template={type:'task.interactive_decision',
|
|
378
378
|
source:'job/551/task/producer/execution/e1',data:{interactive:{jobId:'551',taskId:'producer',executionId:'e1',invocationId:'review-551'},purpose:'video'}};
|
|
379
379
|
const media={id:'video1',requestId:'d9b2006a-0618-45aa-a3d8-31363fa629ca',revisionId:'rv1',
|
|
380
|
-
contentHash:'a'.repeat(64),path:'/tmp/video.md',compiled:{children:[]},review:{delivery:'event',eventTemplate:template}};
|
|
380
|
+
contentHash:'a'.repeat(64),path:'/tmp/video.md',compiled:{children:[]},review:{delivery:'event',commitSha:'c'.repeat(40),eventTemplate:template}};
|
|
381
381
|
it('does not publish until explicit Submit, preserves fixed envelope and scoped comments',async()=>{
|
|
382
382
|
const h=harness(undefined,undefined, m=> m.method==='tools/call'?{published:true,event:{event_id:'ack'}}:undefined);
|
|
383
383
|
h.result(media);h.selectSpot(0);h.scene({sceneId:'intro',timeSeconds:2.25,sceneStart:0});
|
|
@@ -389,7 +389,7 @@ describe('Review event delivery',()=>{
|
|
|
389
389
|
expect(calls[0]).toMatchObject({params:{name:'events',arguments:{command:'publish',
|
|
390
390
|
args:{type:template.type,source:template.source,data:{purpose:'video',
|
|
391
391
|
interactive:{jobId:'551',taskId:'producer',executionId:'e1',invocationId:'review-551',
|
|
392
|
-
requestId:media.requestId,
|
|
392
|
+
requestId:media.requestId,revision:'c'.repeat(40),commitSha:'c'.repeat(40),
|
|
393
393
|
decision:'changes_requested',feedback:'Trim opening',comments:[{sceneId:'intro',timeSeconds:2.25,text:'Trim opening'}]}}}}}});
|
|
394
394
|
expect(h.messages.filter(m=>m.method==='ui/message')).toHaveLength(0);
|
|
395
395
|
expect(h.nodes.status.textContent).toContain('submitted');
|
|
@@ -3,7 +3,8 @@ import {normalizeReviewConfig,eventForReview} from '../src/mcp/review-delivery.m
|
|
|
3
3
|
|
|
4
4
|
const template={type:'task.interactive_decision',source:'job/j1/task/t1/execution/e1',
|
|
5
5
|
data:{interactive:{jobId:'j1',taskId:'t1',executionId:'e1',invocationId:'review-r1'},meta:{source:'ok'}}};
|
|
6
|
-
const
|
|
6
|
+
const sha='c'.repeat(40);
|
|
7
|
+
const review={requestId:'r1',previewId:'p1',commitSha:sha,
|
|
7
8
|
decision:'changes_requested',comments:[{sceneId:'intro',timeSeconds:3.2,text:'Shorter intro'}],idempotencyKey:'key1'};
|
|
8
9
|
|
|
9
10
|
describe('Provider-bound preview delivery',()=>{
|
|
@@ -22,22 +23,22 @@ describe('Provider-bound preview delivery',()=>{
|
|
|
22
23
|
expect(()=>normalizeReviewConfig({delivery:'event',eventTemplate:{...template,
|
|
23
24
|
data:{interactive:{...template.data.interactive,taskId:'forged'}}}})).toThrow();
|
|
24
25
|
expect(()=>normalizeReviewConfig({delivery:'event',eventTemplate:{...template,
|
|
25
|
-
data:{interactive:{...template.data.interactive,revision:
|
|
26
|
+
data:{interactive:{...template.data.interactive,revision:sha}}}})).toThrow();
|
|
26
27
|
});
|
|
27
28
|
it('freezes caller-owned identity and fills only data.interactive fields on human submit',()=>{
|
|
28
|
-
const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
|
|
29
|
+
const config=normalizeReviewConfig({delivery:'event',commitSha:sha,eventTemplate:template});
|
|
29
30
|
template.data.meta.source='changed after validation';
|
|
30
31
|
const event=eventForReview(config,review);
|
|
31
32
|
expect(event).toMatchObject({type:'task.interactive_decision',source:template.source,
|
|
32
33
|
data:{meta:{source:'ok'},interactive:{jobId:'j1',taskId:'t1',executionId:'e1',
|
|
33
|
-
invocationId:'review-r1',revision:
|
|
34
|
+
invocationId:'review-r1',revision:sha,commitSha:sha,
|
|
34
35
|
decision:'changes_requested',feedback:'Shorter intro',comments:review.comments,
|
|
35
36
|
idempotencyKey:'key1'}}});
|
|
36
37
|
expect(template.data.interactive).not.toHaveProperty('decision');
|
|
37
38
|
});
|
|
38
39
|
it('refuses malformed review identity or unauthorized decision',()=>{
|
|
39
|
-
const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
|
|
40
|
-
expect(()=>eventForReview(config,{...review,
|
|
40
|
+
const config=normalizeReviewConfig({delivery:'event',commitSha:sha,eventTemplate:template});
|
|
41
|
+
expect(()=>eventForReview(config,{...review,commitSha:'bogus'})).toThrow();
|
|
41
42
|
expect(()=>eventForReview(config,{...review,decision:'task.completed'})).toThrow();
|
|
42
43
|
});
|
|
43
44
|
});
|
|
@@ -3,7 +3,7 @@ import {parseEventPreviewOptions,neoReviewEndpoint,buildReviewRequest,submitNeoR
|
|
|
3
3
|
|
|
4
4
|
describe('Standalone Markcut CLI preview (notification belongs to Neo)',()=>{
|
|
5
5
|
it('accepts externally supplied event templates without a phone or APNs URL',()=>{
|
|
6
|
-
expect(parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','template.json']).delivery).toBe('event');
|
|
6
|
+
expect(parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','template.json','--commit-sha','a'.repeat(40)]).delivery).toBe('event');
|
|
7
7
|
expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event'])).toThrow();
|
|
8
8
|
expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','a','--phone-url','http://phone'])).toThrow();
|
|
9
9
|
expect(parseEventPreviewOptions(['preview','video.md','--delivery','text']).delivery).toBe('text');
|
|
@@ -15,6 +15,7 @@ describe('Neo-owned REST notification from standalone CLI',()=>{
|
|
|
15
15
|
const id='82ba2e6c-6432-4ecd-83ee-cb78ba87c668';
|
|
16
16
|
const hash='f'.repeat(64);
|
|
17
17
|
const options={file:'/tmp/preview.md'};
|
|
18
|
+
const eventOptions={...options,commitSha:'a'.repeat(40)};
|
|
18
19
|
const state={result:{id:'preview-123',contentHash:hash,revisionId:'revision-123'}};
|
|
19
20
|
it('builds a durable, immutable text request for phone view-only sync',()=>{
|
|
20
21
|
const request=buildReviewRequest(options,{delivery:'text'},state,id);
|
|
@@ -24,8 +25,9 @@ describe('Neo-owned REST notification from standalone CLI',()=>{
|
|
|
24
25
|
it('uses exact caller-bound template for Relay event review',()=>{
|
|
25
26
|
const template={type:'task.interactive_decision',source:'job/12/task/prod/execution/ex1',
|
|
26
27
|
data:{interactive:{jobId:'12',taskId:'prod',executionId:'ex1',invocationId:'i1'}}};
|
|
27
|
-
const request=buildReviewRequest(
|
|
28
|
-
expect(request).toMatchObject({id,eventTemplate:template,jobId:'12',groupId:'job/12/task/prod'});
|
|
28
|
+
const request=buildReviewRequest(eventOptions,{delivery:'event',eventTemplate:template},state,id);
|
|
29
|
+
expect(request).toMatchObject({id,commitSha:eventOptions.commitSha,mediaHash:hash,eventTemplate:template,jobId:'12',groupId:'job/12/task/prod'});
|
|
30
|
+
expect(request).not.toHaveProperty('revisionId');expect(request).not.toHaveProperty('contentHash');
|
|
29
31
|
});
|
|
30
32
|
it('POSTs to local Neo Core REST and requires persisted matching ACK',async()=>{
|
|
31
33
|
const request=buildReviewRequest(options,{delivery:'text'},state,id);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { extractMetadata, extractOriginalSegment } from "../src/vision/cli.mjs";
|
|
7
|
+
|
|
8
|
+
describe("Vision metadata long-video duration", () => {
|
|
9
|
+
it("uses ffprobe time instead of misreading formatted ExifTool Duration", () => {
|
|
10
|
+
const dir=mkdtempSync(join(tmpdir(),"markcut-duration-"));
|
|
11
|
+
try {
|
|
12
|
+
const video=join(dir,"long.mov");
|
|
13
|
+
execFileSync("ffmpeg",["-loglevel","error","-y","-f","lavfi","-i","color=c=blue:s=160x90:r=2:d=76.16",
|
|
14
|
+
"-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p",video],{timeout:30000});
|
|
15
|
+
const metadata=extractMetadata(video);
|
|
16
|
+
expect(metadata.width).toBe(160);
|
|
17
|
+
expect(metadata.height).toBe(90);
|
|
18
|
+
expect(metadata.duration).toBeGreaterThan(76);
|
|
19
|
+
expect(metadata.duration).toBeLessThan(77);
|
|
20
|
+
const segment=join(dir,"segment.mp4");
|
|
21
|
+
extractOriginalSegment(video,segment,63,13);
|
|
22
|
+
const seconds=Number(execFileSync("ffprobe",["-v","error","-show_entries","format=duration",
|
|
23
|
+
"-of","default=noprint_wrappers=1:nokey=1",segment],{encoding:"utf8"}).trim());
|
|
24
|
+
expect(seconds).toBeGreaterThan(12);
|
|
25
|
+
expect(seconds).toBeLessThanOrEqual(13.5);
|
|
26
|
+
expect(() => extractOriginalSegment(video,join(dir,"missing.mp4"),80,5)).toThrow(/Cannot decode source segment/);
|
|
27
|
+
} finally {rmSync(dir,{recursive:true,force:true});}
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {afterEach,describe,expect,it} from 'vitest';
|
|
2
|
+
import {execFileSync} from 'node:child_process';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {existsSync,mkdtempSync,readFileSync,rmSync} from 'node:fs';
|
|
5
|
+
import {tmpdir} from 'node:os';
|
|
6
|
+
import {join} from 'node:path';
|
|
7
|
+
import {main} from '../src/vision/cli.mjs';
|
|
8
|
+
|
|
9
|
+
const roots:string[]=[];
|
|
10
|
+
const probe=(file:string)=>JSON.parse(execFileSync('ffprobe',[
|
|
11
|
+
'-v','error','-show_entries','stream=codec_name,codec_type,width,height:format=duration:format_tags',
|
|
12
|
+
'-of','json',file],{encoding:'utf8'}));
|
|
13
|
+
const hash=(f:string)=>createHash('sha256').update(readFileSync(f)).digest('hex');
|
|
14
|
+
afterEach(()=>{for(const p of roots.splice(0))rmSync(p,{recursive:true,force:true});});
|
|
15
|
+
|
|
16
|
+
describe('Markcut Vision native normalization-only mode',()=>{
|
|
17
|
+
it('normalizes images and video for understanding without touching originals or running AI',async()=>{
|
|
18
|
+
const dir=mkdtempSync(join(tmpdir(),'markcut-vision-tiny-'));roots.push(dir);
|
|
19
|
+
const inputVideo=join(dir,'source.mov'),inputImage=join(dir,'photo.png');
|
|
20
|
+
execFileSync('ffmpeg',['-hide_banner','-loglevel','error','-y',
|
|
21
|
+
'-f','lavfi','-i','testsrc2=size=1600x900:duration=2:rate=10',
|
|
22
|
+
'-f','lavfi','-i','sine=frequency=440:duration=2',
|
|
23
|
+
'-metadata','location=+45.5000-075.7500/',
|
|
24
|
+
'-c:v','libx264','-preset','ultrafast','-crf','18','-c:a','aac','-shortest',inputVideo]);
|
|
25
|
+
execFileSync('ffmpeg',['-hide_banner','-loglevel','error','-y',
|
|
26
|
+
'-f','lavfi','-i','color=c=blue:s=1600x900:d=1','-frames:v','1',inputImage]);
|
|
27
|
+
const before=[hash(inputVideo),hash(inputImage)];
|
|
28
|
+
let text='';const old=console.log;
|
|
29
|
+
console.log=(value:unknown)=>{text+=String(value)+'\n';};
|
|
30
|
+
try{await main(['node','cli.mjs','vision',dir,'--normalize-only']);}
|
|
31
|
+
finally{console.log=old;}
|
|
32
|
+
const result=JSON.parse(text.trim().split('\n').at(-1)!);
|
|
33
|
+
expect(result).toMatchObject({status:'PASS',profile:'markcut-vision-normalized-v1',usage:'vision-understanding-only'});
|
|
34
|
+
expect(result.files).toHaveLength(2);
|
|
35
|
+
const videos=result.files.filter((x:{kind:string})=>x.kind==='video');
|
|
36
|
+
const images=result.files.filter((x:{kind:string})=>x.kind==='image');
|
|
37
|
+
expect(videos).toHaveLength(1);expect(images).toHaveLength(1);
|
|
38
|
+
expect(videos[0].sampled).toBe(false);
|
|
39
|
+
expect(videos[0].sourceDurationSeconds).toBeGreaterThanOrEqual(1.9);
|
|
40
|
+
for(const item of result.files){
|
|
41
|
+
expect(existsSync(item.path)).toBe(true);
|
|
42
|
+
expect(item.path).toContain('/.normalized/');
|
|
43
|
+
const metadata=probe(item.path),stream=metadata.streams.find((x:{codec_type:string})=>x.codec_type==='video');
|
|
44
|
+
expect(Math.max(stream.width,stream.height)).toBeLessThanOrEqual(item.maxDimension);
|
|
45
|
+
expect(JSON.stringify(metadata.format?.tags||{}).toLowerCase()).not.toContain('location');
|
|
46
|
+
if(item.kind==='video'){
|
|
47
|
+
expect(stream.codec_name).toBe('h264');
|
|
48
|
+
expect(metadata.streams.some((x:{codec_type:string})=>x.codec_type==='audio')).toBe(true);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
expect([hash(inputVideo),hash(inputImage)]).toEqual(before);
|
|
52
|
+
// Native cache is re-usable with the same source filenames.
|
|
53
|
+
const t=JSON.parse(text.trim()); expect(t.files.length).toBe(2);
|
|
54
|
+
});
|
|
55
|
+
});
|