editorbrain 0.48.0 → 0.49.0
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/README.md +2 -2
- package/bin/editorbrain.mjs +714 -395
- package/package.json +1 -1
- package/skill/editorbrain/AGENTS.md +3 -1
- package/skill/editorbrain/SKILL.md +17 -5
- package/skill/editorbrain/references/cli-mcp.md +15 -0
- package/skill/editorbrain/references/production-and-review.md +5 -1
- package/skill/editorbrain/references/production-continuity.md +10 -1
- package/skill/editorbrain/references/starting-an-edit.md +7 -2
- package/skill/editorbrain/references/task-map.md +5 -0
- package/skill/editorbrain/references/workflow-evidence.md +107 -0
- package/skill/editorbrain/references/workspace-files.md +1 -1
package/bin/editorbrain.mjs
CHANGED
|
@@ -163,8 +163,8 @@ function validateStyleRules(value) {
|
|
|
163
163
|
const rules = Array.from(doc.rules, (input2) => {
|
|
164
164
|
if (!input2 || typeof input2 !== "object") invalid("expected rule.");
|
|
165
165
|
const type = input2.check;
|
|
166
|
-
const
|
|
167
|
-
const rule = object(input2, ["id", "check", "strength", "origin", ...
|
|
166
|
+
const fields3 = type === "frame.content" ? ["timeSeconds", "content", "text"] : type === "text.forbidden" ? ["phrases", "caseSensitive"] : type === "layout.safeZone" ? ["insets", "text"] : type === "audio.loudness" ? ["target"] : type === "manual" ? ["instruction"] : invalid("unsupported rule type.");
|
|
167
|
+
const rule = object(input2, ["id", "check", "strength", "origin", ...fields3]);
|
|
168
168
|
const ruleId = identifier(rule.id);
|
|
169
169
|
if (ids2.has(ruleId)) invalid("duplicate rule id.");
|
|
170
170
|
ids2.add(ruleId);
|
|
@@ -265,8 +265,8 @@ var forbiddenText = /(?:\b[a-z][a-z0-9+.-]*:\/\/|\b(?:data|file|mailto):|\b(?:au
|
|
|
265
265
|
function safeStyleResourcePath(path) {
|
|
266
266
|
if (typeof path !== "string" || !path || path.length > 400 || path !== path.trim() || /[\\\x00-\x1f\x7f%:?#]/.test(path) || path.startsWith("/") || path.startsWith("~")) throw new Error("Resource path must be a safe workspace-relative path");
|
|
267
267
|
const parts = path.split("/");
|
|
268
|
-
const
|
|
269
|
-
if (
|
|
268
|
+
const invalid14 = parts.filter((part) => !part || part === "." || part === ".." || part.length > 100 || /[. ]$/.test(part) || ["__proto__", "prototype", "constructor"].includes(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part));
|
|
269
|
+
if (invalid14.length) throw new Error(`Unsafe or nonportable resource path segment in ${JSON.stringify(path)}: ${invalid14.map((p) => JSON.stringify(p)).join(", ")}. Use relative segments of 1\u2013100 characters without traversal, reserved device names or trailing dots/spaces.`);
|
|
270
270
|
if (parts.some((part) => /^\.env(?:\.|$)/i.test(part) || /^(?:\.?credentials|secrets?|service[-_]account)(?:\.|$)/i.test(part) || [".git", ".ssh", ".aws", ".gnupg", ".sync.json", "id_rsa", "id_ed25519"].includes(part.toLowerCase()))) throw new Error("Credential and private configuration paths cannot be style resources");
|
|
271
271
|
return path;
|
|
272
272
|
}
|
|
@@ -274,7 +274,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
274
274
|
const path = `.editorbrain/styles/${expectedId}/resources.json`;
|
|
275
275
|
const issues = [];
|
|
276
276
|
const add = (message) => issues.push({ path, message });
|
|
277
|
-
const
|
|
277
|
+
const fields3 = (entry, allowed, label) => {
|
|
278
278
|
if (Object.keys(entry).some((key) => !allowed.includes(key))) add(`${label} has unsupported fields; do not include URLs, credentials or hidden resource sources`);
|
|
279
279
|
};
|
|
280
280
|
const text15 = (value2, label) => {
|
|
@@ -282,7 +282,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
282
282
|
else if (forbiddenText.test(value2) || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value2)) add(`${label} cannot contain URLs, credentials or control characters`);
|
|
283
283
|
};
|
|
284
284
|
if (!object2(value)) return { valid: false, issues: [{ path, message: "Style resources must be a JSON object" }] };
|
|
285
|
-
|
|
285
|
+
fields3(value, ["schemaVersion", "id", "resources"], "Style resources");
|
|
286
286
|
if (value.schemaVersion !== 1) add("schemaVersion must be 1");
|
|
287
287
|
if (!identifier2.test(expectedId) || value.id !== expectedId) add(`Style resource id must match path: ${expectedId}`);
|
|
288
288
|
if (!Array.isArray(value.resources) || value.resources.length > 200) add("Style resources requires a resources array");
|
|
@@ -294,7 +294,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
294
294
|
add(`${label} must be an object`);
|
|
295
295
|
continue;
|
|
296
296
|
}
|
|
297
|
-
|
|
297
|
+
fields3(resource, ["id", "kind", "purpose", "required", "source"], label);
|
|
298
298
|
if (typeof resource.id !== "string" || !identifier2.test(resource.id) || ["constructor", "prototype"].includes(resource.id)) add(`${label} requires a valid identifier`);
|
|
299
299
|
else if (ids2.has(resource.id)) add(`Duplicate resource id: ${resource.id}`);
|
|
300
300
|
else ids2.add(resource.id);
|
|
@@ -307,7 +307,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
307
307
|
continue;
|
|
308
308
|
}
|
|
309
309
|
if (source2.type === "local") {
|
|
310
|
-
|
|
310
|
+
fields3(source2, ["type", "path", "sha256"], `${label} local source`);
|
|
311
311
|
try {
|
|
312
312
|
safeStyleResourcePath(source2.path);
|
|
313
313
|
} catch (error62) {
|
|
@@ -315,7 +315,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
315
315
|
}
|
|
316
316
|
if (source2.sha256 !== void 0 && (typeof source2.sha256 !== "string" || !digest.test(source2.sha256))) add(`${label} sha256 must be a 64-character lowercase hexadecimal digest`);
|
|
317
317
|
} else if (source2.type === "asset") {
|
|
318
|
-
|
|
318
|
+
fields3(source2, ["type", "assetId", "fileName", "originalPath"], `${label} asset source`);
|
|
319
319
|
if (typeof source2.assetId !== "string" || !digest.test(source2.assetId)) add(`${label} assetId must be a 64-character lowercase hexadecimal digest`);
|
|
320
320
|
if (source2.originalPath !== void 0) {
|
|
321
321
|
try {
|
|
@@ -326,7 +326,7 @@ function validateStyleResources(value, expectedId) {
|
|
|
326
326
|
}
|
|
327
327
|
if (source2.fileName !== void 0 && (typeof source2.fileName !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,99}$/.test(source2.fileName))) add(`${label} fileName must be a portable basename, not a path.`);
|
|
328
328
|
} else if (source2.type === "requirement") {
|
|
329
|
-
|
|
329
|
+
fields3(source2, ["type", "description"], `${label} requirement source`);
|
|
330
330
|
text15(source2.description, `${label} requirement description`);
|
|
331
331
|
} else add(`${label} source must be local, asset or requirement`);
|
|
332
332
|
}
|
|
@@ -478,11 +478,11 @@ function styleReuseIssues(name, value, expectedId) {
|
|
|
478
478
|
if (!obj(value) || !(value.schemaVersion === 1 || name === "captions.json" && value.schemaVersion === 2) || value.id !== expectedId) return ["Expected schemaVersion: 1 (or 2 for captions) and id matching the style path."];
|
|
479
479
|
const errors = [];
|
|
480
480
|
const add = (s) => errors.push(s);
|
|
481
|
-
const
|
|
481
|
+
const fields3 = (v, allowed, label) => {
|
|
482
482
|
if (obj(v) && Object.keys(v).some((k) => !allowed.includes(k))) add(`${label} has unsupported fields; store only the documented contract, never credentials.`);
|
|
483
483
|
};
|
|
484
484
|
const top = { "techniques.json": ["techniques"], "media-style.json": ["status", "model", "referenceOrder", "promptTemplate", "variables", "reviewBeforeAnimation", "animation"], "captions.json": ["mode", "enabled", "font", "activeBox", "position", "forbiddenZones", "hideDuringCrossings", "tokenBindings"], "components.json": ["components"] };
|
|
485
|
-
|
|
485
|
+
fields3(value, ["schemaVersion", "id", ...top[name], ...name === "captions.json" && value.schemaVersion === 2 ? ["renderer", "usage", "referenceSize", "chunk", "pop", "marker"] : []], name);
|
|
486
486
|
if (name === "techniques.json") {
|
|
487
487
|
if (!Array.isArray(value.techniques) || value.techniques.length > 100) add("techniques must contain at most 100 entries.");
|
|
488
488
|
else {
|
|
@@ -491,14 +491,14 @@ function styleReuseIssues(name, value, expectedId) {
|
|
|
491
491
|
if (!obj(t) || !id(t.id) || seen.has(t.id) || !text3(t.purpose) || !texts2(t.when) || !obj(t.anchor) || t.anchor.kind !== "phrase" || !text3(t.anchor.text) || !ids(t.resourceIds) || !texts2(t.omitWhen) || !texts2(t.verify) || t.componentId !== void 0 && !id(t.componentId)) add('Each technique needs unique id, purpose, when: string[], anchor: {kind:"phrase",text}, resourceIds: string[], omitWhen: string[], verify: string[] and optional componentId.');
|
|
492
492
|
if (obj(t)) {
|
|
493
493
|
seen.add(t.id);
|
|
494
|
-
|
|
495
|
-
|
|
494
|
+
fields3(t, ["id", "purpose", "when", "anchor", "resourceIds", "componentId", "omitWhen", "verify"], "Technique");
|
|
495
|
+
fields3(t.anchor, ["kind", "text"], "Technique anchor");
|
|
496
496
|
}
|
|
497
497
|
}
|
|
498
498
|
}
|
|
499
499
|
}
|
|
500
500
|
if (name === "media-style.json") {
|
|
501
|
-
|
|
501
|
+
fields3(value.animation, ["model", "promptTemplate"], "Animation recipe");
|
|
502
502
|
if (!["draft", "ready"].includes(String(value.status)) || value.model !== void 0 && !text3(value.model) || !ids(value.referenceOrder) || !text3(value.promptTemplate) || !ids(value.variables) || !texts2(value.reviewBeforeAnimation)) add("Media recipe needs status draft|ready, optional model, ordered reference resource IDs, promptTemplate, variables and reviewBeforeAnimation arrays.");
|
|
503
503
|
if (value.status === "ready" && (!text3(value.model) || !Array.isArray(value.reviewBeforeAnimation) || !value.reviewBeforeAnimation.length)) add("A ready media recipe requires a model and explicit review checks.");
|
|
504
504
|
if (text3(value.promptTemplate) && Array.isArray(value.variables)) {
|
|
@@ -513,10 +513,10 @@ function styleReuseIssues(name, value, expectedId) {
|
|
|
513
513
|
const f = value.font, b = value.activeBox, p = value.position, z2 = value.forbiddenZones;
|
|
514
514
|
if (value.schemaVersion === 2) {
|
|
515
515
|
const r = value.referenceSize, c = value.chunk, a = value.pop, m = value.marker;
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
516
|
+
fields3(r, ["width", "height"], "Caption referenceSize");
|
|
517
|
+
fields3(c, ["maxWords", "punctuation", "noEndWith"], "Caption chunk");
|
|
518
|
+
fields3(a, ["durationSeconds", "scale"], "Caption pop");
|
|
519
|
+
fields3(m, ["scope", "roughness", "drawOnSeconds", "seed"], "Caption marker");
|
|
520
520
|
if (value.renderer !== "builtin-captions-v2" || !["box", "karaoke", "marker"].includes(String(value.mode))) add("Captions v2 needs renderer builtin-captions-v2 and mode box|karaoke|marker; arbitrary modules are not executed.");
|
|
521
521
|
if (value.usage !== void 0 && value.usage !== "preferred") add("Caption usage is preferred: adapt or omit for the actual video.");
|
|
522
522
|
if (!obj(r) || !Number.isInteger(r.width) || !Number.isInteger(r.height) || Number(r.width) < 16 || Number(r.height) < 16 || Number(r.width) > 8192 || Number(r.height) > 8192) add("Caption referenceSize needs width/height integers 16..8192; font size and padding are reference pixels.");
|
|
@@ -528,10 +528,10 @@ function styleReuseIssues(name, value, expectedId) {
|
|
|
528
528
|
if (value.mode !== "marker" && m !== void 0) add("marker settings require marker mode.");
|
|
529
529
|
}
|
|
530
530
|
if (value.schemaVersion === 1 && value.mode !== void 0 && !["phrase", "karaoke"].includes(String(value.mode))) add("Caption mode must be phrase or karaoke. Karaoke needs explicit word timings in the cues.");
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
if (Array.isArray(z2)) for (const zone of z2)
|
|
531
|
+
fields3(f, ["family", "weight", "size", "color", "resourceId"], "Caption font");
|
|
532
|
+
fields3(b, ["color", "padding"], "Caption activeBox");
|
|
533
|
+
fields3(p, ["x", "y"], "Caption position");
|
|
534
|
+
if (Array.isArray(z2)) for (const zone of z2) fields3(zone, ["x", "y", "width", "height"], "Caption zone");
|
|
535
535
|
if (obj(f) && f.resourceId !== void 0 && !id(f.resourceId)) add("font.resourceId must name a declared font resource.");
|
|
536
536
|
if (value.tokenBindings !== void 0 && (!obj(value.tokenBindings) || Object.entries(value.tokenBindings).some(([key, v]) => !["fontFamily", "color", "boxColor"].includes(key) || typeof v !== "string" || !/^[a-z][a-z0-9_.-]{0,79}$/.test(v) || ["constructor", "prototype", "__proto__"].includes(v)))) add("tokenBindings supports fontFamily, color and boxColor mapped to semantic token keys.");
|
|
537
537
|
if (typeof value.enabled !== "boolean" || !obj(f) || !text3(f.family) || /[\r\n,{}\\]/.test(String(f.family)) || !Number.isInteger(f.weight) || Number(f.weight) < 100 || Number(f.weight) > 900 || typeof f.size !== "number" || !Number.isFinite(f.size) || f.size < 8 || f.size > 300 || !color(f.color) || !obj(b) || !color(b.color) || typeof b.padding !== "number" || !Number.isFinite(b.padding) || b.padding < 0 || b.padding > 100 || !obj(p) || !unit(p.x) || !unit(p.y) || !Array.isArray(z2) || z2.length > 20 || z2.some((a) => !obj(a) || !unit(a.x) || !unit(a.y) || !unit(a.width) || !unit(a.height) || Number(a.x) + Number(a.width) > 1 || Number(a.y) + Number(a.height) > 1) || typeof value.hideDuringCrossings !== "boolean") add("captions needs enabled, font {family,weight:100..900,size:8..300,color:#RRGGBB}, activeBox {color,padding:0..100}, normalized position/zones and hideDuringCrossings boolean.");
|
|
@@ -553,11 +553,11 @@ function styleReuseIssues(name, value, expectedId) {
|
|
|
553
553
|
}
|
|
554
554
|
if (c.sourceFormat !== void 0 && !["html", "javascript-module"].includes(String(c.sourceFormat))) add("Component sourceFormat must be html or javascript-module; this declares inert source, not a runnable or deterministic scene.");
|
|
555
555
|
if (c.sourceFormat === "javascript-module" && typeof c.originPath === "string" && !/\.(m?js)$/i.test(c.originPath)) add("JavaScript module originPath must end in .js or .mjs.");
|
|
556
|
-
|
|
556
|
+
fields3(c, ["id", "sourceResourceId", "originPath", "sourceFormat", "status", "bindings"], "Component");
|
|
557
557
|
const names = /* @__PURE__ */ new Set();
|
|
558
558
|
for (const [index, b] of c.bindings.entries()) {
|
|
559
559
|
const label = `Component ${c.id}, binding ${index + 1}${obj(b) ? " (" + JSON.stringify(b.name) + ")" : ""}`;
|
|
560
|
-
|
|
560
|
+
fields3(b, ["name", "type", "literal", "occurrences", "role"], label);
|
|
561
561
|
if (!obj(b) || !bindingName(b.name) || names.has(b.name) || !["string", "number", "boolean"].includes(String(b.type)) || typeof b.literal !== b.type || typeof b.literal === "number" && !Number.isFinite(b.literal) || typeof b.literal === "string" && b.literal.length > 8e3 || !Number.isInteger(b.occurrences) || Number(b.occurrences) < 1 || Number(b.occurrences) > 1e3 || ["clip", "directory"].includes(String(b.role)) && b.type !== "string" || b.role !== void 0 && !["clip", "directory", "text", "timing", "layout"].includes(String(b.role))) add(`${label}: use a unique name starting with a letter or number (letters, numbers, _ or -, max 80; camelCase allowed), type string|number|boolean, literal of that type, occurrences:1..1000 and optional role clip|directory|text|timing|layout. Clip and directory bindings require type string.`);
|
|
562
562
|
if (obj(b)) names.add(b.name);
|
|
563
563
|
}
|
|
@@ -1045,9 +1045,9 @@ function validateToolPreferences(input2) {
|
|
|
1045
1045
|
if (value.schemaVersion !== 1) throw new Error("Tool preferences schemaVersion must be 1.");
|
|
1046
1046
|
for (const key of ["transcription", "images", "narration", "music"]) {
|
|
1047
1047
|
if (value[key] === void 0) continue;
|
|
1048
|
-
const
|
|
1049
|
-
const section2 = obj3(value[key],
|
|
1050
|
-
if (
|
|
1048
|
+
const fields3 = { transcription: ["provider", "language"], images: ["provider", "quality", "resolution", "aspectRatio"], narration: ["provider", "language"], music: ["provider", "durationSeconds", "character"] }[key];
|
|
1049
|
+
const section2 = obj3(value[key], fields3);
|
|
1050
|
+
if (fields3.some((field) => section2[field] === void 0)) throw new Error("Incomplete AI tool preferences.");
|
|
1051
1051
|
const providers = { transcription: transcriptionProviders, images: ["editorbrain", "higgsfield", "openai-images"], narration: ["editorbrain", "elevenlabs"], music: ["editorbrain", "suno", "elevenlabs"] }[key];
|
|
1052
1052
|
choice(section2.provider, providers);
|
|
1053
1053
|
if (key === "transcription" || key === "narration") choice(section2.language, toolLanguages);
|
|
@@ -1149,10 +1149,10 @@ function validateProjectCheckpoint(input2, projectId) {
|
|
|
1149
1149
|
if (!continuity.contextHashes || typeof continuity.contextHashes !== "object" || Array.isArray(continuity.contextHashes)) throw new Error("Checkpoint contextHashes must be an object.");
|
|
1150
1150
|
const hashes = Object.entries(continuity.contextHashes);
|
|
1151
1151
|
if (hashes.length > 256) throw new Error("Checkpoint contextHashes must contain at most 256 documents.");
|
|
1152
|
-
for (const [path,
|
|
1152
|
+
for (const [path, hash13] of hashes) {
|
|
1153
1153
|
const validPath = new RegExp(`^(?:videos/${projectId}/(?:project\\.json|brief\\.md|direction\\.md|script\\.md|media\\.json|audio\\.json|resources\\.json|preferences\\.json|style-decisions\\.json)|\\.editorbrain/(?:brands|styles)/[a-z0-9][a-z0-9_-]{0,79}/[a-z][a-z0-9-]*\\.(?:md|json)|\\.editorbrain/output-profiles/[a-z0-9][a-z0-9_-]{0,79}\\.json)$`);
|
|
1154
1154
|
const styleSnapshot = path.startsWith(`videos/${projectId}/style-snapshots/`) && styleSnapshotSourcePath(path) !== null;
|
|
1155
|
-
if (!validPath.test(path) && !styleSnapshot || typeof
|
|
1155
|
+
if (!validPath.test(path) && !styleSnapshot || typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13)) throw new Error("Checkpoint contextHashes requires editorial document paths and lowercase SHA-256 hashes.");
|
|
1156
1156
|
}
|
|
1157
1157
|
}
|
|
1158
1158
|
if (new TextEncoder().encode(JSON.stringify(value)).length > checkpointLimits.documentBytes) throw new Error("Checkpoint must be at most 128 KiB.");
|
|
@@ -1926,7 +1926,7 @@ function getMediaStyle(id4, version2) {
|
|
|
1926
1926
|
return MEDIA_STYLE_CATALOG.styles.find((style) => style.id === id4 && (version2 === void 0 || style.version === version2));
|
|
1927
1927
|
}
|
|
1928
1928
|
var record3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1929
|
-
var only = (value,
|
|
1929
|
+
var only = (value, fields3) => Object.keys(value).every((key) => fields3.includes(key));
|
|
1930
1930
|
function visualTasteIssues(value) {
|
|
1931
1931
|
if (!record3(value) || !only(value, ["density", "energy", "contrast"])) return ["visualTaste supports density, energy and contrast only."];
|
|
1932
1932
|
return Object.entries(visualTasteOptions).flatMap(([key, allowed]) => value[key] === void 0 || typeof value[key] === "string" && allowed.includes(value[key]) ? [] : [`Invalid visualTaste ${key}. Omit undecided choices.`]);
|
|
@@ -2055,8 +2055,8 @@ function editorialProfileIssues(value) {
|
|
|
2055
2055
|
if (!record4(value)) return ["El perfil editorial debe ser un objeto."];
|
|
2056
2056
|
const issues = [];
|
|
2057
2057
|
if (value.schemaVersion !== 1) issues.push("schemaVersion del perfil editorial debe ser 1.");
|
|
2058
|
-
const
|
|
2059
|
-
if (Object.keys(value).some((key) => !
|
|
2058
|
+
const fields3 = [...Object.keys(emptyProfile()), "mediaStyles", "visualTaste", "motionSelection", "motionProduction", "editorialDelivery", "mediaSources", "creativeDirection", "creativePreferencesReviewed", "questionMode", "creatorContext", "referenceLinks"];
|
|
2059
|
+
if (Object.keys(value).some((key) => !fields3.includes(key))) issues.push("El perfil editorial contiene campos desconocidos.");
|
|
2060
2060
|
for (const key of ["experience", "role", "goal", "pace", "captions", "sound", "freedom", "assets"]) {
|
|
2061
2061
|
const selected = value[key];
|
|
2062
2062
|
if ((key === "experience" || key === "role") && selected === void 0) continue;
|
|
@@ -2369,10 +2369,10 @@ function searchSfx(bank, options) {
|
|
|
2369
2369
|
const expanded = new Set(terms.flatMap((t) => groups.find((g) => g.includes(t)) ?? [t]));
|
|
2370
2370
|
const candidates = policy.enabled ? bank.entries.filter((e) => options.includeUnverified || e.license.kind !== "unverified").map((e) => {
|
|
2371
2371
|
const haystack = new Set(words([e.name, ...e.tags].join(" ")));
|
|
2372
|
-
const
|
|
2373
|
-
return { entry: e, matches, score:
|
|
2372
|
+
const matches2 = [...expanded].filter((t) => haystack.has(t));
|
|
2373
|
+
return { entry: e, matches: matches2, score: matches2.length * 4 + (policy.character !== "adaptive" && e.character === policy.character ? 2 : 0) };
|
|
2374
2374
|
}).filter((e) => !terms.length || e.matches.length > 0).sort((a, b) => b.score - a.score || a.entry.id.localeCompare(b.entry.id)) : [];
|
|
2375
|
-
return { bankId: bank.bankId, policy, total: candidates.length, items: candidates.slice(0, options.limit ?? 6).map(({ entry, matches }) => ({ ...entry, matchedTerms:
|
|
2375
|
+
return { bankId: bank.bankId, policy, total: candidates.length, items: candidates.slice(0, options.limit ?? 6).map(({ entry, matches: matches2 }) => ({ ...entry, matchedTerms: matches2 })), notice: "Lexical candidates with bilingual tags, not audio understanding. Rights are declared, not independently verified. Audition before use; metadata or a preview is not proof of an audible final mix." };
|
|
2376
2376
|
}
|
|
2377
2377
|
function checkSfxCues(audio, input2) {
|
|
2378
2378
|
const p = object6(input2, ["durationSeconds", "hookEndSeconds", "cues", "omissionReason"]);
|
|
@@ -2474,13 +2474,13 @@ function mergeProfile(base, patch) {
|
|
|
2474
2474
|
if (issues.length) throw new Error(issues.join("\n"));
|
|
2475
2475
|
result2[key] = [.../* @__PURE__ */ new Set([...base.creativePreferencesReviewed ?? [], ...value])];
|
|
2476
2476
|
} else if (key === "creatorContext") {
|
|
2477
|
-
const
|
|
2478
|
-
result2[key] = { ...object7(result2[key]) ? result2[key] : {}, ...
|
|
2477
|
+
const fields3 = record5(value, key, Object.keys(creatorContextOptions));
|
|
2478
|
+
result2[key] = { ...object7(result2[key]) ? result2[key] : {}, ...fields3 };
|
|
2479
2479
|
} else if (key === "editorialDelivery" || key === "visualTaste") {
|
|
2480
|
-
const
|
|
2480
|
+
const fields3 = record5(value, key, key === "editorialDelivery" ? Object.keys(editorialDeliveryOptions) : ["density", "energy", "contrast"]);
|
|
2481
2481
|
const previous = object7(result2[key]) ? result2[key] : {};
|
|
2482
2482
|
const next = { ...previous };
|
|
2483
|
-
for (const [field, selection] of Object.entries(
|
|
2483
|
+
for (const [field, selection] of Object.entries(fields3)) {
|
|
2484
2484
|
if (selection === null) delete next[field];
|
|
2485
2485
|
else if (selection !== void 0) next[field] = selection;
|
|
2486
2486
|
}
|
|
@@ -2547,9 +2547,9 @@ function readOnboardingIdentity(content) {
|
|
|
2547
2547
|
const name = [...previous.matchAll(/^# ([^\r\n]+)$/gm)];
|
|
2548
2548
|
if (name.length === 1 && name[0][1].length <= 100) result2.name = name[0][1];
|
|
2549
2549
|
for (const [key, heading, max] of [["description", "Qu\xE9 hacemos", 1500], ["audience", "Audiencia", 500], ["tone", "Voz", 500], ["links", "Enlaces compartidos por el usuario", 1500]]) {
|
|
2550
|
-
const
|
|
2551
|
-
if (
|
|
2552
|
-
let value =
|
|
2550
|
+
const matches2 = [...previous.matchAll(new RegExp(`^## ${heading}\\r?\\n([\\s\\S]*?)(?=^#{1,2} |$(?![\\s\\S]))`, "gm"))];
|
|
2551
|
+
if (matches2.length !== 1) continue;
|
|
2552
|
+
let value = matches2[0][1].trim();
|
|
2553
2553
|
if (key === "links") value = value.replace(/\nSon referencias no analizadas\. No asumir su contenido ni consultarlas automáticamente\.$/, "");
|
|
2554
2554
|
if (value && value !== "Por definir" && value.length <= max) result2[key] = value;
|
|
2555
2555
|
}
|
|
@@ -2867,7 +2867,7 @@ function numeric(value, name, min, max, integer3 = false) {
|
|
|
2867
2867
|
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max || integer3 && !Number.isInteger(value)) throw new Error(`${name} must be ${integer3 ? "an integer" : "a number"} from ${min} to ${max}.`);
|
|
2868
2868
|
}
|
|
2869
2869
|
function rasterDimensions(binary, mime2, name) {
|
|
2870
|
-
const
|
|
2870
|
+
const invalid14 = () => new Error(`${name} has malformed or missing raster dimensions.`);
|
|
2871
2871
|
const byte = (offset2) => binary.charCodeAt(offset2);
|
|
2872
2872
|
const u16 = (offset2) => byte(offset2) * 256 + byte(offset2 + 1);
|
|
2873
2873
|
const u32 = (offset2) => u16(offset2) * 65536 + u16(offset2 + 2);
|
|
@@ -2875,50 +2875,50 @@ function rasterDimensions(binary, mime2, name) {
|
|
|
2875
2875
|
const le24 = (offset2) => le16(offset2) + byte(offset2 + 2) * 65536;
|
|
2876
2876
|
const le32 = (offset2) => le24(offset2) + byte(offset2 + 3) * 16777216;
|
|
2877
2877
|
const check2 = (width, height) => {
|
|
2878
|
-
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw
|
|
2878
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw invalid14();
|
|
2879
2879
|
if (width > MOTION_INPUT_LIMITS.maxImageDimension || height > MOTION_INPUT_LIMITS.maxImageDimension || width * height > MOTION_INPUT_LIMITS.maxImagePixels) throw new Error(`${name} raster dimensions exceed ${MOTION_INPUT_LIMITS.maxImageDimension} pixels per side or ${MOTION_INPUT_LIMITS.maxImagePixels} total pixels.`);
|
|
2880
2880
|
};
|
|
2881
2881
|
if (mime2 === "image/png") {
|
|
2882
|
-
if (u32(8) !== 13) throw
|
|
2882
|
+
if (u32(8) !== 13) throw invalid14();
|
|
2883
2883
|
check2(u32(16), u32(20));
|
|
2884
2884
|
return;
|
|
2885
2885
|
}
|
|
2886
2886
|
if (mime2 === "image/jpeg") {
|
|
2887
2887
|
let offset2 = 2, dimensions;
|
|
2888
2888
|
while (offset2 < binary.length) {
|
|
2889
|
-
if (byte(offset2++) !== 255) throw
|
|
2889
|
+
if (byte(offset2++) !== 255) throw invalid14();
|
|
2890
2890
|
while (offset2 < binary.length && byte(offset2) === 255) offset2++;
|
|
2891
|
-
if (offset2 >= binary.length) throw
|
|
2891
|
+
if (offset2 >= binary.length) throw invalid14();
|
|
2892
2892
|
const marker = byte(offset2++);
|
|
2893
2893
|
if (marker === 217 || marker === 218) break;
|
|
2894
|
-
if (marker === 216 || marker === 0) throw
|
|
2894
|
+
if (marker === 216 || marker === 0) throw invalid14();
|
|
2895
2895
|
if (marker === 1 || marker >= 208 && marker <= 215) continue;
|
|
2896
|
-
if (offset2 + 2 > binary.length) throw
|
|
2896
|
+
if (offset2 + 2 > binary.length) throw invalid14();
|
|
2897
2897
|
const size = u16(offset2);
|
|
2898
|
-
if (size < 2 || offset2 + size > binary.length) throw
|
|
2898
|
+
if (size < 2 || offset2 + size > binary.length) throw invalid14();
|
|
2899
2899
|
if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker)) {
|
|
2900
|
-
if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw
|
|
2900
|
+
if (size < 11 || size !== 8 + byte(offset2 + 7) * 3) throw invalid14();
|
|
2901
2901
|
const width = u16(offset2 + 5), height = u16(offset2 + 3);
|
|
2902
2902
|
check2(width, height);
|
|
2903
|
-
if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw
|
|
2903
|
+
if (dimensions && (dimensions[0] !== width || dimensions[1] !== height)) throw invalid14();
|
|
2904
2904
|
dimensions = [width, height];
|
|
2905
2905
|
}
|
|
2906
2906
|
offset2 += size;
|
|
2907
2907
|
}
|
|
2908
|
-
if (!dimensions) throw
|
|
2908
|
+
if (!dimensions) throw invalid14();
|
|
2909
2909
|
return;
|
|
2910
2910
|
}
|
|
2911
|
-
if (le32(4) !== binary.length - 8) throw
|
|
2911
|
+
if (le32(4) !== binary.length - 8) throw invalid14();
|
|
2912
2912
|
const frameDimensions = (kind2, size, data) => {
|
|
2913
2913
|
if (kind2 === "VP8L") {
|
|
2914
|
-
if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw
|
|
2914
|
+
if (size < 5 || byte(data) !== 47 || byte(data + 4) >> 5 !== 0) throw invalid14();
|
|
2915
2915
|
const width = 1 + (byte(data + 1) | (byte(data + 2) & 63) << 8);
|
|
2916
2916
|
const height = 1 + (byte(data + 2) >> 6 | byte(data + 3) << 2 | (byte(data + 4) & 15) << 10);
|
|
2917
2917
|
check2(width, height);
|
|
2918
2918
|
return true;
|
|
2919
2919
|
}
|
|
2920
2920
|
if (kind2 === "VP8 ") {
|
|
2921
|
-
if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw
|
|
2921
|
+
if (size < 10 || byte(data) & 1 || binary.slice(data + 3, data + 6) !== "\x9D*") throw invalid14();
|
|
2922
2922
|
check2(le16(data + 6) & 16383, le16(data + 8) & 16383);
|
|
2923
2923
|
return true;
|
|
2924
2924
|
}
|
|
@@ -2927,26 +2927,26 @@ function rasterDimensions(binary, mime2, name) {
|
|
|
2927
2927
|
let offset = 12, found = false;
|
|
2928
2928
|
while (offset + 8 <= binary.length) {
|
|
2929
2929
|
const kind2 = binary.slice(offset, offset + 4), size = le32(offset + 4), data = offset + 8;
|
|
2930
|
-
if (size > binary.length - data) throw
|
|
2930
|
+
if (size > binary.length - data) throw invalid14();
|
|
2931
2931
|
if (kind2 === "VP8X") {
|
|
2932
|
-
if (size !== 10) throw
|
|
2932
|
+
if (size !== 10) throw invalid14();
|
|
2933
2933
|
check2(le24(data + 4) + 1, le24(data + 7) + 1);
|
|
2934
2934
|
found = true;
|
|
2935
2935
|
} else if (kind2 === "ANMF") {
|
|
2936
|
-
if (size < 16) throw
|
|
2936
|
+
if (size < 16) throw invalid14();
|
|
2937
2937
|
check2(le24(data + 6) + 1, le24(data + 9) + 1);
|
|
2938
2938
|
let nested = data + 16, frame = false;
|
|
2939
2939
|
while (nested + 8 <= data + size) {
|
|
2940
2940
|
const frameKind = binary.slice(nested, nested + 4), frameSize = le32(nested + 4), frameData = nested + 8;
|
|
2941
|
-
if (frameSize > data + size - frameData) throw
|
|
2941
|
+
if (frameSize > data + size - frameData) throw invalid14();
|
|
2942
2942
|
frame = frameDimensions(frameKind, frameSize, frameData) || frame;
|
|
2943
2943
|
nested = frameData + frameSize + frameSize % 2;
|
|
2944
2944
|
}
|
|
2945
|
-
if (!frame || nested !== data + size) throw
|
|
2945
|
+
if (!frame || nested !== data + size) throw invalid14();
|
|
2946
2946
|
} else found = frameDimensions(kind2, size, data) || found;
|
|
2947
2947
|
offset = data + size + size % 2;
|
|
2948
2948
|
}
|
|
2949
|
-
if (!found || offset !== binary.length) throw
|
|
2949
|
+
if (!found || offset !== binary.length) throw invalid14();
|
|
2950
2950
|
}
|
|
2951
2951
|
function dataUrl(value, name, kind2) {
|
|
2952
2952
|
const max = kind2 === "font" ? MOTION_INPUT_LIMITS.fontBytes : MOTION_INPUT_LIMITS.imageBytes;
|
|
@@ -7001,16 +7001,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
|
|
|
7001
7001
|
};
|
|
7002
7002
|
});
|
|
7003
7003
|
function handleExclusiveUnionResults(results, final, inst, ctx) {
|
|
7004
|
-
const
|
|
7004
|
+
const matches2 = [];
|
|
7005
7005
|
for (let i = 0; i < results.length; i++) {
|
|
7006
7006
|
if (results[i].issues.length === 0)
|
|
7007
|
-
|
|
7007
|
+
matches2.push(i);
|
|
7008
7008
|
}
|
|
7009
|
-
if (
|
|
7010
|
-
final.value = results[
|
|
7009
|
+
if (matches2.length === 1) {
|
|
7010
|
+
final.value = results[matches2[0]].value;
|
|
7011
7011
|
return final;
|
|
7012
7012
|
}
|
|
7013
|
-
if (
|
|
7013
|
+
if (matches2.length === 0) {
|
|
7014
7014
|
final.issues.push({
|
|
7015
7015
|
code: "invalid_union",
|
|
7016
7016
|
input: final.value,
|
|
@@ -7024,7 +7024,7 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
|
|
|
7024
7024
|
inst,
|
|
7025
7025
|
errors: [],
|
|
7026
7026
|
inclusive: false,
|
|
7027
|
-
matches
|
|
7027
|
+
matches: matches2
|
|
7028
7028
|
});
|
|
7029
7029
|
}
|
|
7030
7030
|
return final;
|
|
@@ -22223,20 +22223,20 @@ function checkArrayGuards(arraySchema, guards) {
|
|
|
22223
22223
|
if (guards.containsSchema) {
|
|
22224
22224
|
const minContains = guards.minContains ?? 1;
|
|
22225
22225
|
const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
|
|
22226
|
-
let
|
|
22226
|
+
let matches2 = 0;
|
|
22227
22227
|
for (const item of items) {
|
|
22228
|
-
if (guards.containsSchema.safeParse(item).success && ++
|
|
22228
|
+
if (guards.containsSchema.safeParse(item).success && ++matches2 >= ceiling)
|
|
22229
22229
|
break;
|
|
22230
22230
|
}
|
|
22231
|
-
if (
|
|
22231
|
+
if (matches2 < minContains) {
|
|
22232
22232
|
payload.issues.push({
|
|
22233
22233
|
code: "custom",
|
|
22234
|
-
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${
|
|
22234
|
+
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches2}`,
|
|
22235
22235
|
input: items,
|
|
22236
22236
|
continue: true
|
|
22237
22237
|
});
|
|
22238
22238
|
}
|
|
22239
|
-
if (guards.maxContains !== void 0 &&
|
|
22239
|
+
if (guards.maxContains !== void 0 && matches2 > guards.maxContains) {
|
|
22240
22240
|
payload.issues.push({
|
|
22241
22241
|
code: "custom",
|
|
22242
22242
|
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
|
|
@@ -201728,7 +201728,7 @@ var searchIndexes = { "1.1.0": buildSearchIndex(catalogs["1.1.0"]), "1.2.0": bui
|
|
|
201728
201728
|
var bilingualIndex = buildSearchIndex(catalogs["1.4.0"], true);
|
|
201729
201729
|
function termWeights(index) {
|
|
201730
201730
|
const frequencies = /* @__PURE__ */ new Map();
|
|
201731
|
-
for (const { fields:
|
|
201731
|
+
for (const { fields: fields3 } of index) for (const term of new Set(fields3.flatMap((field) => [...field.terms]))) {
|
|
201732
201732
|
frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
|
|
201733
201733
|
}
|
|
201734
201734
|
return new Map([...frequencies].map(([term, count2]) => [term, 1 + Math.log((index.length + 1) / (count2 + 1))]));
|
|
@@ -201742,23 +201742,23 @@ function rankedCandidates(search, version2, bilingual = false) {
|
|
|
201742
201742
|
if (exact) return [exact];
|
|
201743
201743
|
const queryTerms = bilingual ? discoveryTerms(search) : stems(search);
|
|
201744
201744
|
if (version2 === "1.4.0") queryTerms.delete("quien");
|
|
201745
|
-
return searchIndex.map(({ scene, fields:
|
|
201745
|
+
return searchIndex.map(({ scene, fields: fields3 }) => {
|
|
201746
201746
|
if (version2 === "1.4.0") {
|
|
201747
201747
|
let score = 0, coverage = 0;
|
|
201748
201748
|
for (const term of queryTerms) {
|
|
201749
|
-
const fieldWeight =
|
|
201749
|
+
const fieldWeight = fields3.reduce((sum, field) => sum + (field.terms.has(term) ? field.weight : 0), 0);
|
|
201750
201750
|
if (!fieldWeight) continue;
|
|
201751
201751
|
const rarity = (bilingual ? bilingualTermWeights : v14TermWeights).get(term);
|
|
201752
|
-
const mechanismBoost = bilingual && mechanismTerms.has(term) &&
|
|
201752
|
+
const mechanismBoost = bilingual && mechanismTerms.has(term) && fields3.slice(0, 2).some((field) => field.terms.has(term)) ? 3 : 1;
|
|
201753
201753
|
score += rarity * Math.sqrt(fieldWeight) * mechanismBoost;
|
|
201754
201754
|
coverage += rarity;
|
|
201755
201755
|
}
|
|
201756
201756
|
return { scene, score: score * Math.sqrt(coverage) };
|
|
201757
201757
|
}
|
|
201758
|
-
return { scene, score:
|
|
201759
|
-
let
|
|
201760
|
-
for (const term of queryTerms) if (field.terms.has(term))
|
|
201761
|
-
return total +
|
|
201758
|
+
return { scene, score: fields3.reduce((total, field) => {
|
|
201759
|
+
let matches2 = 0;
|
|
201760
|
+
for (const term of queryTerms) if (field.terms.has(term)) matches2++;
|
|
201761
|
+
return total + matches2 * field.weight;
|
|
201762
201762
|
}, 0) };
|
|
201763
201763
|
}).filter((result2) => result2.score > 0).sort((a, b) => b.score - a.score || (a.scene.id < b.scene.id ? -1 : a.scene.id > b.scene.id ? 1 : 0)).map((result2) => result2.scene);
|
|
201764
201764
|
}
|
|
@@ -201879,12 +201879,12 @@ var SOCIAL_SAFE_PROFILES = {
|
|
|
201879
201879
|
reels: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 },
|
|
201880
201880
|
shorts: { bottom: 0.25, right: 0.15, top: 0.08, left: 0.05 }
|
|
201881
201881
|
};
|
|
201882
|
-
function validateVisualReview(value,
|
|
201882
|
+
function validateVisualReview(value, hash13, duration3, width, height) {
|
|
201883
201883
|
const v = value;
|
|
201884
201884
|
const fail4 = () => {
|
|
201885
201885
|
throw new Error("Invalid visual profile: use the exact artifact hash, output-clock seconds and output-pixel boxes.");
|
|
201886
201886
|
};
|
|
201887
|
-
if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !==
|
|
201887
|
+
if (!v || typeof v !== "object" || Array.isArray(v) || v.schemaVersion !== 1 || v.artifactSha256 !== hash13 || !/^[a-f0-9]{64}$/.test(v.artifactSha256)) fail4();
|
|
201888
201888
|
if (Object.keys(v).some((k) => !["schemaVersion", "artifactSha256", "platform", "holds", "geometry"].includes(k))) fail4();
|
|
201889
201889
|
if (v.platform !== void 0 && !Object.hasOwn(SOCIAL_SAFE_PROFILES, v.platform)) fail4();
|
|
201890
201890
|
if (v.holds !== void 0 && (!Array.isArray(v.holds) || v.holds.length > 1e3)) fail4();
|
|
@@ -202574,6 +202574,96 @@ function findPublicTaskRoute(query) {
|
|
|
202574
202574
|
return PUBLIC_TASK_ROUTES.find((route) => route.id === key || route.aliases.some((alias) => taskKey(alias) === key));
|
|
202575
202575
|
}
|
|
202576
202576
|
|
|
202577
|
+
// packages/core/src/review-readiness.ts
|
|
202578
|
+
var reviewArtifactPhases = ["directions", "review", "delivery"];
|
|
202579
|
+
var identifier8 = /^[a-zA-Z0-9_-]{1,80}$/;
|
|
202580
|
+
var uuid5 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
202581
|
+
var hash5 = /^[a-f0-9]{64}$/;
|
|
202582
|
+
function fields2(value, required2, optional2, label) {
|
|
202583
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
202584
|
+
const result2 = value;
|
|
202585
|
+
if (required2.some((key) => !Object.hasOwn(result2, key)) || Object.keys(result2).some((key) => !required2.includes(key) && !optional2.includes(key))) {
|
|
202586
|
+
throw new Error(`${label} has missing or unsupported fields.`);
|
|
202587
|
+
}
|
|
202588
|
+
return result2;
|
|
202589
|
+
}
|
|
202590
|
+
function matches(value, pattern, label) {
|
|
202591
|
+
if (typeof value !== "string" || !pattern.test(value)) throw new Error(`Invalid review evidence ${label}.`);
|
|
202592
|
+
}
|
|
202593
|
+
function parseReviewEvidence(input2) {
|
|
202594
|
+
const value = fields2(input2, ["evidenceId", "projectId", "contextVersion", "phase", "source", "presented"], ["decision"], "Review evidence");
|
|
202595
|
+
matches(value.evidenceId, uuid5, "evidenceId: use a lowercase UUID");
|
|
202596
|
+
matches(value.projectId, identifier8, "projectId");
|
|
202597
|
+
matches(value.contextVersion, hash5, "contextVersion: use the shared editorial SHA-256");
|
|
202598
|
+
if (!reviewArtifactPhases.includes(value.phase)) throw new Error("Review evidence phase must be directions, review or delivery.");
|
|
202599
|
+
if (value.presented !== true) throw new Error("Review evidence requires an explicit presented: true attestation; creating or opening a file is not presentation.");
|
|
202600
|
+
const phase = value.phase;
|
|
202601
|
+
let source2;
|
|
202602
|
+
if (value.source && typeof value.source === "object" && "kind" in value.source && value.source.kind === "revision") {
|
|
202603
|
+
const item = fields2(value.source, ["kind", "revisionId"], [], "Review evidence revision source");
|
|
202604
|
+
matches(item.revisionId, uuid5, "source.revisionId");
|
|
202605
|
+
source2 = { kind: "revision", revisionId: item.revisionId };
|
|
202606
|
+
} else {
|
|
202607
|
+
const item = fields2(value.source, ["kind", "artifactId", "sha256", "relativePath"], [], "Review evidence local source");
|
|
202608
|
+
if (item.kind !== "local") throw new Error("Review evidence source.kind must be revision or local.");
|
|
202609
|
+
matches(item.artifactId, hash5, "source.artifactId");
|
|
202610
|
+
matches(item.sha256, hash5, "source.sha256");
|
|
202611
|
+
if (typeof item.relativePath !== "string") throw new Error("Review evidence source.relativePath must be a portable relative path.");
|
|
202612
|
+
try {
|
|
202613
|
+
assertCheckpointArtifactPath(item.relativePath);
|
|
202614
|
+
} catch {
|
|
202615
|
+
throw new Error("Review evidence source.relativePath must be a safe portable relative file path, without absolute paths, URLs, credentials or traversal.");
|
|
202616
|
+
}
|
|
202617
|
+
source2 = { kind: "local", artifactId: item.artifactId, sha256: item.sha256, relativePath: item.relativePath };
|
|
202618
|
+
}
|
|
202619
|
+
let decision;
|
|
202620
|
+
if (Object.hasOwn(value, "decision")) {
|
|
202621
|
+
if (source2.kind !== "local") throw new Error("Remote review approval must come from the existing revision; do not duplicate it in review evidence.");
|
|
202622
|
+
if (phase === "delivery") throw new Error("Delivery evidence does not record final acceptance; use the existing final acceptance flow.");
|
|
202623
|
+
const item = fields2(value.decision, phase === "directions" ? ["userConfirmed", "directionId"] : ["userConfirmed", "approved"], [], "Local review decision");
|
|
202624
|
+
if (item.userConfirmed !== true) throw new Error("A local review decision requires explicit userConfirmed: true.");
|
|
202625
|
+
if (phase === "directions") {
|
|
202626
|
+
matches(item.directionId, identifier8, "decision.directionId");
|
|
202627
|
+
decision = { userConfirmed: true, directionId: item.directionId };
|
|
202628
|
+
} else {
|
|
202629
|
+
if (item.approved !== true) throw new Error("A local sample decision requires approved: true for this exact artifact.");
|
|
202630
|
+
decision = { userConfirmed: true, approved: true };
|
|
202631
|
+
}
|
|
202632
|
+
}
|
|
202633
|
+
return { evidenceId: value.evidenceId, projectId: value.projectId, contextVersion: value.contextVersion, phase, source: source2, presented: true, ...decision ? { decision } : {} };
|
|
202634
|
+
}
|
|
202635
|
+
function parseProjectReviewReadiness(input2) {
|
|
202636
|
+
const value = fields2(input2, ["schemaVersion", "kind", "projectId", "contextVersion", "reviewMode", "production", "delivery"], [], "Project review readiness");
|
|
202637
|
+
if (value.schemaVersion !== 1 || value.kind !== "editorbrain.review-readiness") throw new Error("Unsupported project review readiness format.");
|
|
202638
|
+
matches(value.projectId, identifier8, "projectId");
|
|
202639
|
+
if (value.contextVersion !== null) matches(value.contextVersion, hash5, "contextVersion");
|
|
202640
|
+
if (value.reviewMode !== null && !["direct", "directions", "sample"].includes(value.reviewMode)) throw new Error("Invalid review readiness mode.");
|
|
202641
|
+
const parseGate = (input3) => {
|
|
202642
|
+
const item = fields2(input3, ["status", "phase", "reason", "evidence", "next"], [], "Review readiness gate");
|
|
202643
|
+
if (!["satisfied", "pending", "stale", "unknown", "not_required"].includes(item.status)) throw new Error("Invalid review readiness status.");
|
|
202644
|
+
if (item.phase !== null && !reviewArtifactPhases.includes(item.phase)) throw new Error("Invalid review readiness phase.");
|
|
202645
|
+
matches(item.reason, /^[a-z][a-z_]{0,119}$/, "readiness reason");
|
|
202646
|
+
if (item.next !== null && (typeof item.next !== "string" || !item.next.trim() || item.next.length > 2e3 || /[\p{Cc}\p{Cf}]/u.test(item.next))) throw new Error("Invalid review readiness next action.");
|
|
202647
|
+
let evidence = null;
|
|
202648
|
+
if (item.evidence !== null) {
|
|
202649
|
+
const ref = fields2(item.evidence, ["evidenceId", "phase", "source"], [], "Review readiness evidence reference");
|
|
202650
|
+
const parsed = parseReviewEvidence({ ...ref, projectId: value.projectId, contextVersion: value.contextVersion ?? "0".repeat(64), presented: true });
|
|
202651
|
+
if (parsed.phase !== item.phase) throw new Error("Review readiness evidence phase must match its gate.");
|
|
202652
|
+
evidence = { evidenceId: parsed.evidenceId, phase: parsed.phase, source: parsed.source };
|
|
202653
|
+
}
|
|
202654
|
+
return { status: item.status, phase: item.phase, reason: item.reason, evidence, next: item.next };
|
|
202655
|
+
};
|
|
202656
|
+
return {
|
|
202657
|
+
schemaVersion: 1,
|
|
202658
|
+
kind: "editorbrain.review-readiness",
|
|
202659
|
+
projectId: value.projectId,
|
|
202660
|
+
contextVersion: value.contextVersion,
|
|
202661
|
+
reviewMode: value.reviewMode,
|
|
202662
|
+
production: parseGate(value.production),
|
|
202663
|
+
delivery: parseGate(value.delivery)
|
|
202664
|
+
};
|
|
202665
|
+
}
|
|
202666
|
+
|
|
202577
202667
|
// packages/core/src/index.ts
|
|
202578
202668
|
var SCHEMA_VERSION = 1;
|
|
202579
202669
|
var MAX_DOCUMENT_BYTES = 128 * 1024;
|
|
@@ -202586,7 +202676,7 @@ var ValidationError = class extends Error {
|
|
|
202586
202676
|
}
|
|
202587
202677
|
issues;
|
|
202588
202678
|
};
|
|
202589
|
-
var
|
|
202679
|
+
var identifier9 = /^[a-z0-9][a-z0-9_-]{0,79}$/;
|
|
202590
202680
|
var tokenName = /^[a-z][a-z0-9_.-]{0,79}$/;
|
|
202591
202681
|
var tokenNameHelp = "Use 1\u201380 characters: start with a lowercase letter, then lowercase letters, digits, _, . or - (for example font_family). __proto__, constructor and prototype are reserved. Keys are flat semantic names, not CSS property names.";
|
|
202592
202682
|
var own5 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
@@ -202595,7 +202685,7 @@ var nonempty2 = (value) => typeof value === "string" && value.trim().length > 0;
|
|
|
202595
202685
|
var finite = (value) => typeof value === "number" && Number.isFinite(value);
|
|
202596
202686
|
var tokenValue = (value) => typeof value === "string" || typeof value === "boolean" || finite(value) || Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
202597
202687
|
function assertIdentifier(value) {
|
|
202598
|
-
if (!
|
|
202688
|
+
if (!identifier9.test(value)) throw new Error(`Invalid identifier: ${value}. Use lowercase letters, numbers, _ or - (max 80).`);
|
|
202599
202689
|
return value;
|
|
202600
202690
|
}
|
|
202601
202691
|
function safeDocumentPath(path) {
|
|
@@ -202703,7 +202793,7 @@ function validateDocument(path, content) {
|
|
|
202703
202793
|
}
|
|
202704
202794
|
if (isBrand || isStyle || isProject || isOutput) {
|
|
202705
202795
|
const expected = isOutput ? parts[2].slice(0, -5) : parts[isProject ? 1 : 2];
|
|
202706
|
-
if (!
|
|
202796
|
+
if (!identifier9.test(expected)) add("Invalid resource identifier in path");
|
|
202707
202797
|
if (doc.id !== void 0 && doc.id !== expected) add(`Document id must match path: ${expected}`);
|
|
202708
202798
|
}
|
|
202709
202799
|
if (parts[0] === ".editorbrain" && parts[1] === "sfx") {
|
|
@@ -202761,7 +202851,7 @@ function validateDocument(path, content) {
|
|
|
202761
202851
|
}
|
|
202762
202852
|
}
|
|
202763
202853
|
if (isProject) {
|
|
202764
|
-
for (const key of ["id", "brand", "style", "outputProfile"]) if (typeof doc[key] !== "string" || !
|
|
202854
|
+
for (const key of ["id", "brand", "style", "outputProfile"]) if (typeof doc[key] !== "string" || !identifier9.test(doc[key])) add(`${key} must be a valid identifier`);
|
|
202765
202855
|
if (!object10(doc.intent) || !nonempty2(doc.intent.topic) || !nonempty2(doc.intent.goal)) add("intent requires topic and goal");
|
|
202766
202856
|
for (const issue3 of creativeDirectionIssues(doc.creativeDirection)) add(issue3);
|
|
202767
202857
|
for (const issue3 of questionModeIssues(doc.questionMode)) add(issue3);
|
|
@@ -202780,7 +202870,7 @@ function validateDocument(path, content) {
|
|
|
202780
202870
|
}
|
|
202781
202871
|
}
|
|
202782
202872
|
if (isMedia) {
|
|
202783
|
-
if (!
|
|
202873
|
+
if (!identifier9.test(parts[1])) add("Invalid project identifier in media path");
|
|
202784
202874
|
if (!Array.isArray(doc.assets)) add("Production media requires an assets array");
|
|
202785
202875
|
else {
|
|
202786
202876
|
const ids2 = /* @__PURE__ */ new Set();
|
|
@@ -203318,7 +203408,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
|
|
|
203318
203408
|
const before = await input2.stat();
|
|
203319
203409
|
if (!before.isFile() || before.size <= 0 || before.size > maxBytes) throw new CliError("INVALID_REVIEW_FILE", "Review media is empty, not regular or exceeds its size limit.", `Use a separate review copy under ${maxBytes / 1024 / 1024} MiB. Keep the original.`);
|
|
203320
203410
|
output3 = await open3(target, "wx", 384);
|
|
203321
|
-
const buffer = Buffer.alloc(4 * 1024 * 1024),
|
|
203411
|
+
const buffer = Buffer.alloc(4 * 1024 * 1024), hash13 = createHash("sha256");
|
|
203322
203412
|
let length = 0;
|
|
203323
203413
|
for (; ; ) {
|
|
203324
203414
|
const { bytesRead } = await input2.read(buffer, 0, buffer.length, length);
|
|
@@ -203326,7 +203416,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
|
|
|
203326
203416
|
length += bytesRead;
|
|
203327
203417
|
if (length > before.size) throw new CliError("REVIEW_FILE_CHANGED", "Review media changed while copying.", "Finish rendering and create a new review.");
|
|
203328
203418
|
const chunk = buffer.subarray(0, bytesRead);
|
|
203329
|
-
|
|
203419
|
+
hash13.update(chunk);
|
|
203330
203420
|
let written = 0;
|
|
203331
203421
|
while (written < chunk.length) {
|
|
203332
203422
|
const result2 = await output3.write(chunk, written, chunk.length - written);
|
|
@@ -203338,7 +203428,7 @@ async function copyReviewFile(source2, target, maxBytes = LOCAL_REVIEW_MEDIA_BYT
|
|
|
203338
203428
|
if (length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new CliError("REVIEW_FILE_CHANGED", "Review media changed while copying.", "Finish rendering and create a new review.");
|
|
203339
203429
|
await verifyReviewPath(source2, before);
|
|
203340
203430
|
complete = true;
|
|
203341
|
-
return { bytes: length, sha256:
|
|
203431
|
+
return { bytes: length, sha256: hash13.digest("hex") };
|
|
203342
203432
|
} finally {
|
|
203343
203433
|
await input2.close();
|
|
203344
203434
|
await output3?.close();
|
|
@@ -203550,17 +203640,17 @@ async function videoEvidenceHash(path, expectedSize) {
|
|
|
203550
203640
|
try {
|
|
203551
203641
|
const before = await handle.stat();
|
|
203552
203642
|
if (!before.isFile() || before.size !== expectedSize) throw new Error("Video changed before hashing");
|
|
203553
|
-
const
|
|
203643
|
+
const hash13 = createHash2("sha256"), chunk = Buffer.alloc(1024 * 1024);
|
|
203554
203644
|
let offset = 0;
|
|
203555
203645
|
while (offset < before.size) {
|
|
203556
203646
|
const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, before.size - offset), offset);
|
|
203557
203647
|
if (!bytesRead) throw new Error("Video changed while hashing");
|
|
203558
|
-
|
|
203648
|
+
hash13.update(chunk.subarray(0, bytesRead));
|
|
203559
203649
|
offset += bytesRead;
|
|
203560
203650
|
}
|
|
203561
203651
|
const after = await handle.stat();
|
|
203562
203652
|
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw new Error("Video changed while hashing");
|
|
203563
|
-
return
|
|
203653
|
+
return hash13.digest("hex");
|
|
203564
203654
|
} finally {
|
|
203565
203655
|
await handle.close();
|
|
203566
203656
|
}
|
|
@@ -203718,9 +203808,9 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
|
|
|
203718
203808
|
warnings.push(`Final render evidence budget (2 GiB): omitted ${path} (${size} bytes).`);
|
|
203719
203809
|
continue;
|
|
203720
203810
|
}
|
|
203721
|
-
const
|
|
203811
|
+
const hash14 = await videoEvidenceHash(await checkedPath(root, path, false), size);
|
|
203722
203812
|
evidenceBytes += size;
|
|
203723
|
-
examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256:
|
|
203813
|
+
examples.push({ id: `video-${examples.length + 1}`, projectId, sourcePath: path, sha256: hash14, evidence: "final_render_local_hash_only", reviewStatus: "unreviewed" });
|
|
203724
203814
|
warnings.push(`Final render recorded by hash only; not uploaded: ${path} (${size} bytes).`);
|
|
203725
203815
|
continue;
|
|
203726
203816
|
}
|
|
@@ -203736,7 +203826,7 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
|
|
|
203736
203826
|
const bytes = await readReviewFile(await checkedPath(root, path, false), 90 * 1024 * 1024);
|
|
203737
203827
|
bytesRead += bytes.length;
|
|
203738
203828
|
assertPortableStyleCode(bytes, path);
|
|
203739
|
-
const
|
|
203829
|
+
const hash13 = digest3(bytes), existing = hashes.get(hash13);
|
|
203740
203830
|
if (existing) {
|
|
203741
203831
|
duplicatePaths.push({ path, resourceId: existing });
|
|
203742
203832
|
continue;
|
|
@@ -203746,8 +203836,8 @@ async function buildStyleFromProject(root, id4, projectId, name, scenePath) {
|
|
|
203746
203836
|
continue;
|
|
203747
203837
|
}
|
|
203748
203838
|
const rid = `resource-${resources.length + 1}`;
|
|
203749
|
-
hashes.set(
|
|
203750
|
-
resources.push({ id: rid, kind: kind(path), purpose: `${used.has(path) ? "Scene dependency" : "Candidate"} from ${posix2.basename(path)}; confirm use and adaptation.`, required: true, source: { type: "local", path, sha256:
|
|
203839
|
+
hashes.set(hash13, rid);
|
|
203840
|
+
resources.push({ id: rid, kind: kind(path), purpose: `${used.has(path) ? "Scene dependency" : "Candidate"} from ${posix2.basename(path)}; confirm use and adaptation.`, required: true, source: { type: "local", path, sha256: hash13 } });
|
|
203751
203841
|
} catch (error62) {
|
|
203752
203842
|
warnings.push(`Resource unavailable or unsupported: ${path}: ${error62.message}`);
|
|
203753
203843
|
if (resources.length < 200) resources.push({ id: `resource-${resources.length + 1}`, kind: kind(path), purpose: `Untransported source ${posix2.basename(path)}; inspect locally.`, required: true, source: { type: "requirement", description: "The source was not copied because it failed the portable-file checks. Redact private content or replace it with a safe declared dependency before reuse." } });
|
|
@@ -204046,14 +204136,14 @@ async function checkLocalResource(root, path, expected) {
|
|
|
204046
204136
|
const before = await handle.stat();
|
|
204047
204137
|
if (!before.isFile()) throw new Error("Resource is not a regular file.");
|
|
204048
204138
|
if (!expected) return {};
|
|
204049
|
-
const
|
|
204050
|
-
for await (const chunk of handle.createReadStream({ autoClose: false }))
|
|
204139
|
+
const hash13 = createHash3("sha256");
|
|
204140
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) hash13.update(chunk);
|
|
204051
204141
|
const after = await handle.stat();
|
|
204052
204142
|
const current2 = await lstat5(await checkedPath(root, path, false));
|
|
204053
204143
|
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current2.dev !== before.dev || current2.ino !== before.ino) {
|
|
204054
204144
|
throw new Error("Resource changed while its hash was being checked; check it again.");
|
|
204055
204145
|
}
|
|
204056
|
-
return { actualSha256:
|
|
204146
|
+
return { actualSha256: hash13.digest("hex") };
|
|
204057
204147
|
} finally {
|
|
204058
204148
|
await handle.close();
|
|
204059
204149
|
}
|
|
@@ -204142,6 +204232,13 @@ import { posix as posix3 } from "node:path";
|
|
|
204142
204232
|
// packages/cli/src/client.ts
|
|
204143
204233
|
import { setTimeout as delay } from "node:timers/promises";
|
|
204144
204234
|
var searchErrors = {
|
|
204235
|
+
review_required: { status: 409, code: "REVIEW_REQUIRED", hint: "Read workflow check --project ID and production present --project ID. Deliver the missing visual artifact, then record the real selection or approval for that exact context. Technical previews remain available. Preserve existing approvals and explicit direct mode; never change the mode to bypass review." },
|
|
204236
|
+
invalid_review_evidence: { status: 400, code: "INVALID_REVIEW_EVIDENCE", hint: "Read production present --help and the current evidence/version. Use explicit presented:true, an exact contextVersion and a source revision or verified local artifact. A generated/uploaded file is not proof of presentation; never invent user approval." },
|
|
204237
|
+
review_evidence_changed: { status: 409, code: "REVIEW_EVIDENCE_CHANGED", hint: "Read production present --project ID again. Reconcile changed project context, presentation receipts, feedback or approvals and use its current version. Do not silently reapprove or repeat a paid render." },
|
|
204238
|
+
review_evidence_conflict: { status: 409, code: "REVIEW_EVIDENCE_CONFLICT", hint: "This evidenceId already identifies different immutable evidence. Read production present --project ID and reconcile it. Retry the same bytes with the same ID; use a new ID only for an actually new presentation, never to bypass a conflict." },
|
|
204239
|
+
review_evidence_limit: { status: 409, code: "REVIEW_EVIDENCE_LIMIT", hint: "Read production present --project ID and reuse the receipt for the same artifact. Preserve history; do not create duplicate presentations or delete evidence to bypass the limit." },
|
|
204240
|
+
review_unavailable: { status: 409, code: "REVIEW_UNAVAILABLE", hint: "Read production reviews --project ID. Select the available, current, non-superseded revision that was actually presented; preserve comments and do not silently substitute or approve another version." },
|
|
204241
|
+
invalid_continuity_cursor: { status: 400, code: "INVALID_CONTINUITY_CURSOR", hint: "Read project continuity with the exact cursors returned for this project. An older API may not support optional review evidence; never change project or workspace to bypass this error." },
|
|
204145
204242
|
brand_limit_reached: { status: 409, code: "BRAND_LIMIT_REACHED", hint: "Consulta el l\xEDmite de marcas de este espacio en https://editorbrain.com/app/billing. Puedes seguir editando las existentes. Comprar cr\xE9ditos no aumenta este l\xEDmite." },
|
|
204146
204243
|
invalid_project_intake: { status: 400, code: "INVALID_PROJECT_INTAKE", hint: "Use projects create ID --brand ID --style ID --output-profile ID with existing IDs. The workspace comes from your authenticated account; do not send a workspace ID." },
|
|
204147
204244
|
project_dependency_missing: { status: 404, code: "PROJECT_DEPENDENCY_MISSING", hint: "Read dependencyKind and documentPath. Discover the existing brand with brands list and styles/output profiles with documents list --prefix .editorbrain/styles/ or .editorbrain/output-profiles/. Preserve saved choices; do not invent replacement preferences or select another brand silently." },
|
|
@@ -204218,7 +204315,7 @@ var searchErrors = {
|
|
|
204218
204315
|
studio_insufficient_credits: { status: 402, code: "STUDIO_INSUFFICIENT_CREDITS", hint: "Check studio catalog for available creative credits. Reconnecting does not replenish credits." },
|
|
204219
204316
|
studio_quote_expired: { status: 409, code: "STUDIO_QUOTE_EXPIRED", hint: "Request a new quote and review its price before authorizing." },
|
|
204220
204317
|
studio_budget_exceeded: { status: 409, code: "STUDIO_BUDGET_EXCEEDED", hint: "The quote exceeds the authorized budget. Do not increase it yourself." },
|
|
204221
|
-
stale_context: { status: 409, code: "STALE_CONTEXT", hint: "Read the current project preferences and request a new quote." },
|
|
204318
|
+
stale_context: { status: 409, code: "STALE_CONTEXT", hint: "Read the current project preferences and workflow. For presentation, reconcile the exact artifact and production present state; never copy an approval onto changed work. For generation/rendering, request a new quote." },
|
|
204222
204319
|
studio_preference_conflict: { status: 409, code: "STUDIO_PREFERENCE_CONFLICT", hint: "Reconcile project language, voice, music or media-source preferences before generating." },
|
|
204223
204320
|
studio_audio_format: { status: 422, code: "STUDIO_AUDIO_FORMAT", hint: "Prepare PCM 16-bit WAV from the original with studio prepare, then upload it." },
|
|
204224
204321
|
studio_invalid_input: { status: 400, code: "STUDIO_INVALID_INPUT", hint: "Check studio catalog and the request fields; never send provider credentials." },
|
|
@@ -204256,6 +204353,10 @@ function safeDiagnosticDetails(body) {
|
|
|
204256
204353
|
const e = body?.error;
|
|
204257
204354
|
if (!e || typeof e !== "object") return {};
|
|
204258
204355
|
const details = {};
|
|
204356
|
+
if (e.code === "review_required") {
|
|
204357
|
+
if (typeof e.projectId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(e.projectId)) details.projectId = e.projectId;
|
|
204358
|
+
if (["directions", "review", "delivery"].includes(String(e.phase))) details.phase = String(e.phase);
|
|
204359
|
+
}
|
|
204259
204360
|
if (e.code === "project_dependency_missing") {
|
|
204260
204361
|
if (["brand", "style", "outputProfile"].includes(String(e.dependencyKind))) details.dependencyKind = String(e.dependencyKind);
|
|
204261
204362
|
if (typeof e.documentPath === "string" && /^\.editorbrain\/(?:(?:brands|styles)\/[a-z0-9][a-z0-9_-]{0,79}\/(?:brand\.md|style\.json)|output-profiles\/[a-z0-9][a-z0-9_-]{0,79}\.json)$/.test(e.documentPath)) details.documentPath = e.documentPath;
|
|
@@ -204281,8 +204382,8 @@ function safeDiagnosticDetails(body) {
|
|
|
204281
204382
|
if (e.code === "studio_invalid_input") {
|
|
204282
204383
|
const allowed = /* @__PURE__ */ new Set(["tool", "projectId", "preferenceOverrideReason", "assetId", "language", "prompt", "referenceAssetIds", "quality", "resolution", "aspectRatio", "durationSeconds", "character", "text", "voice", "quoteId", "maxCredits", "userConfirmed", "batchLeaseToken", "request"]);
|
|
204283
204384
|
if (typeof e.invalidFields === "string" && e.invalidFields.length <= 512) {
|
|
204284
|
-
const
|
|
204285
|
-
if (
|
|
204385
|
+
const fields3 = e.invalidFields.split(",").filter((f) => allowed.has(f));
|
|
204386
|
+
if (fields3.length) details.invalidFields = [...new Set(fields3)].join(",");
|
|
204286
204387
|
}
|
|
204287
204388
|
if (Number.isSafeInteger(e.issueCount) && Number(e.issueCount) > 0 && Number(e.issueCount) <= 1e3) details.issueCount = Number(e.issueCount);
|
|
204288
204389
|
}
|
|
@@ -204301,7 +204402,7 @@ var ApiError = class extends CliError {
|
|
|
204301
204402
|
const recovery2 = diagnostic ? recoveryGuidance(diagnostic.serviceCode, status) : void 0;
|
|
204302
204403
|
const details = diagnostic ? safeDiagnosticDetails(body) : {};
|
|
204303
204404
|
const preferenceHint = diagnostic?.serviceCode === "studio_preference_conflict" && details.conflict === "narration" ? 'Read workflow and the returned projectPath/documentPath. Only after an explicit user request, save narrationOverride={value:"voiceover",reason:"user-requested reason"} in this project.json, then choose an authorized public voice with studio voices and studio voice VOICE_ID --project ID --expected-revision N. Preserve the brand. Quote again; a preference exception never authorizes spending.' : diagnostic?.serviceCode === "studio_preference_conflict" && details.conflict === "voice_selection" ? "Read workflow and studio voice --project ID. Reconcile the requested public alias with the authorized saved voice using studio voices; a deliberate change uses studio voice VOICE_ID --project ID --expected-revision N. Preserve original/no-narration restrictions and the brand. Quote again; a voice selection never authorizes spending." : void 0;
|
|
204304
|
-
const message = diagnostic?.serviceCode === "brand_limit_reached" ? `Este espacio alcanz\xF3 su l\xEDmite de marcas${typeof details.used === "number" && typeof details.limit === "number" ? ` (${details.used}/${details.limit})` : ""}.` : `API request failed (HTTP ${status}).`;
|
|
204405
|
+
const message = diagnostic?.serviceCode === "review_required" ? "The required visual presentation or approval is not recorded for this project context." : diagnostic?.serviceCode === "brand_limit_reached" ? `Este espacio alcanz\xF3 su l\xEDmite de marcas${typeof details.used === "number" && typeof details.limit === "number" ? ` (${details.used}/${details.limit})` : ""}.` : `API request failed (HTTP ${status}).`;
|
|
204305
204406
|
super(diagnostic?.code ?? code, message, recovery2 ? recoveryHint(recovery2) : preferenceHint ?? diagnostic?.hint ?? hint, !diagnostic && safeToRetry && (status === 429 || status >= 500), { status, ...recovery2 ? { recovery: recovery2 } : {}, ...diagnostic ? { serviceCode: diagnostic.serviceCode, ...details } : {}, ...retryAfterMs === void 0 ? {} : { retryAfterMs } });
|
|
204306
204407
|
this.status = status;
|
|
204307
204408
|
this.body = body;
|
|
@@ -204490,7 +204591,7 @@ var Client = class {
|
|
|
204490
204591
|
const retryAfterMs = retryDelay(response.headers.get("Retry-After"), this.runtime.now());
|
|
204491
204592
|
if (!response.ok) {
|
|
204492
204593
|
let errorBody;
|
|
204493
|
-
if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
|
|
204594
|
+
if ((/^\/v1\/(?:authored-motion|style-sources|sfx|team|studio|batches|render-cloud|resources)(?:\/|\?|$)/.test(path) || path.startsWith("/v1/documents/") || path === "/v1/search/brief" || path === "/v1/projects" || /^\/v1\/projects\/[^/]+\/(?:progress|intake|resolve|export|review-evidence(?:\/[a-f0-9-]{36})?|continuity(?:\?.*)?)$/.test(path)) && [400, 402, 403, 404, 409, 422, 429, 503].includes(response.status)) {
|
|
204494
204595
|
try {
|
|
204495
204596
|
const parsed = await boundedJson(response, 16 * 1024);
|
|
204496
204597
|
const knownDiagnostic = searchDiagnostic(response.status, parsed);
|
|
@@ -204543,12 +204644,12 @@ var Client = class {
|
|
|
204543
204644
|
}
|
|
204544
204645
|
}
|
|
204545
204646
|
async uploadPreview(path, content, mimeType) {
|
|
204546
|
-
const
|
|
204547
|
-
if (!
|
|
204647
|
+
const hash13 = path.match(/^\/v1\/assets\/([a-f0-9]{64})(?:\?|$)/)?.[1];
|
|
204648
|
+
if (!hash13 || new URL(path, this.url).searchParams.get("purpose") !== "preview") throw new Error("Use an exact preview asset endpoint.");
|
|
204548
204649
|
const sourceHash = new URL(path, this.url).searchParams.get("sourceSha256");
|
|
204549
|
-
if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash ===
|
|
204650
|
+
if (sourceHash !== null && (!/^[a-f0-9]{64}$/.test(sourceHash) || sourceHash === hash13)) throw new Error("Use a distinct original SHA-256, or omit it.");
|
|
204550
204651
|
let plan;
|
|
204551
|
-
const params = new URLSearchParams({ sha256:
|
|
204652
|
+
const params = new URLSearchParams({ sha256: hash13, bytes: String(content.byteLength) });
|
|
204552
204653
|
const projectId = new URL(path, "https://local.invalid").searchParams.get("projectId");
|
|
204553
204654
|
if (projectId) params.set("projectId", projectId);
|
|
204554
204655
|
try {
|
|
@@ -204560,7 +204661,7 @@ var Client = class {
|
|
|
204560
204661
|
if (typeof plan.allowed !== "boolean" || !Number.isSafeInteger(plan.additionalBytes)) throw new Error("Invalid preview preflight response.");
|
|
204561
204662
|
if (plan.existingAsset) {
|
|
204562
204663
|
const asset = plan.existingAsset;
|
|
204563
|
-
if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !==
|
|
204664
|
+
if (!plan.allowed || plan.additionalBytes !== 0 || asset.id !== hash13 || asset.sha256 !== hash13 || asset.bytes !== content.byteLength || asset.mimeType !== mimeType || typeof asset.name !== "string") throw new Error("Existing preview metadata does not match this file.");
|
|
204564
204665
|
return new Response(JSON.stringify({ ...asset, reused: true }), { headers: { "Content-Type": "application/json" } });
|
|
204565
204666
|
}
|
|
204566
204667
|
if (!plan.allowed) throw new CliError("PREVIEW_STORAGE_FULL", "There is not enough cloud storage for this review copy. Your local edit is intact.", "Continue on the computer, prepare a smaller legible preview, or review eligible files at https://editorbrain.com/app/files. Do not delete protected media or upgrade a plan automatically.");
|
|
@@ -204848,12 +204949,12 @@ async function pushStyle(client, directory, id4, options = {}) {
|
|
|
204848
204949
|
skippedResources.push({ id: resource.id, path, required: resource.required, reason: "Unsupported file type; retained as a local dependency, not uploaded." });
|
|
204849
204950
|
continue;
|
|
204850
204951
|
}
|
|
204851
|
-
const bytes = await readReviewFile(await checkedPath(root, path, false), MAX),
|
|
204852
|
-
if (resource.source.sha256 && resource.source.sha256 !==
|
|
204952
|
+
const bytes = await readReviewFile(await checkedPath(root, path, false), MAX), hash13 = digest4(bytes);
|
|
204953
|
+
if (resource.source.sha256 && resource.source.sha256 !== hash13) throw new Error(`Hash mismatch: ${path}`);
|
|
204853
204954
|
assertPortableStyleCode(bytes, path);
|
|
204854
204955
|
const ext = posix3.extname(path).toLowerCase(), name = "asset-" + posix3.basename(path, ext).replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 80) + ext;
|
|
204855
|
-
uploads.push({ resource, path, hash:
|
|
204856
|
-
resource.source = { type: "asset", assetId:
|
|
204956
|
+
uploads.push({ resource, path, hash: hash13, mime: mime2, name });
|
|
204957
|
+
resource.source = { type: "asset", assetId: hash13, fileName: name, originalPath: path };
|
|
204857
204958
|
}
|
|
204858
204959
|
if (options.withResources && files[resourcePath]) files[resourcePath] = stableJson(manifest);
|
|
204859
204960
|
const preview = await pushWorkspace(client, root, files, { dryRun: true });
|
|
@@ -204956,7 +205057,7 @@ var LOCAL_DOCUMENT_TREES = [".editorbrain", ".editorharness", "videos"];
|
|
|
204956
205057
|
var errno = (error62) => error62.code;
|
|
204957
205058
|
var object12 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
204958
205059
|
var keys2 = (value, expected) => Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
204959
|
-
var
|
|
205060
|
+
var identifier10 = (value) => typeof value === "string" && /^[a-z0-9][a-z0-9_-]{0,79}$/.test(value);
|
|
204960
205061
|
var localPath = (value) => typeof value === "string" && value.length <= 4096 && isAbsolute(value) && resolve2(value) === value && !/[\x00-\x1f\x7f]/.test(value);
|
|
204961
205062
|
var sameBinding = (left, right) => left === null ? right === null : right !== null && left.endpoint === right.endpoint && left.workspaceId === right.workspaceId;
|
|
204962
205063
|
var sameIdentity = (left, right) => left.projectId === right.projectId && left.brandId === right.brandId && sameBinding(left.binding, right.binding);
|
|
@@ -204981,7 +205082,7 @@ function role(value = "work") {
|
|
|
204981
205082
|
}
|
|
204982
205083
|
function parseBinding(value) {
|
|
204983
205084
|
if (value === null) return null;
|
|
204984
|
-
if (!object12(value) || !keys2(value, ["endpoint", "workspaceId"]) || typeof value.endpoint !== "string" || value.endpoint.length > 2048 || !
|
|
205085
|
+
if (!object12(value) || !keys2(value, ["endpoint", "workspaceId"]) || typeof value.endpoint !== "string" || value.endpoint.length > 2048 || !identifier10(value.workspaceId)) throw registryError();
|
|
204985
205086
|
try {
|
|
204986
205087
|
if (normalizeUrl(value.endpoint) !== value.endpoint) throw registryError();
|
|
204987
205088
|
} catch {
|
|
@@ -204995,7 +205096,7 @@ function parseRegistry(raw) {
|
|
|
204995
205096
|
if (!object12(value) || !keys2(value, ["schemaVersion", "projects"]) || value.schemaVersion !== 1 || !Array.isArray(value.projects) || value.projects.length > MAX_REGISTRY_PROJECTS) throw registryError();
|
|
204996
205097
|
const seen = /* @__PURE__ */ new Set();
|
|
204997
205098
|
const projects = value.projects.map((entry) => {
|
|
204998
|
-
if (!object12(entry) || !keys2(entry, ["root", "projectId", "brandId", "binding", "folders", "updatedAt", ...Object.hasOwn(entry, "activity") ? ["activity"] : []]) || !localPath(entry.root) || !
|
|
205099
|
+
if (!object12(entry) || !keys2(entry, ["root", "projectId", "brandId", "binding", "folders", "updatedAt", ...Object.hasOwn(entry, "activity") ? ["activity"] : []]) || !localPath(entry.root) || !identifier10(entry.projectId) || !identifier10(entry.brandId) || !object12(entry.folders) || !Object.keys(entry.folders).length || Object.keys(entry.folders).some((key2) => !ROLES.includes(key2)) || Object.values(entry.folders).some((path) => !localPath(path)) || !validTimestamp(entry.updatedAt)) throw registryError();
|
|
204999
205100
|
const key = JSON.stringify([entry.root, entry.projectId]);
|
|
205000
205101
|
if (seen.has(key)) throw registryError();
|
|
205001
205102
|
seen.add(key);
|
|
@@ -205085,7 +205186,7 @@ async function localBinding(root) {
|
|
|
205085
205186
|
try {
|
|
205086
205187
|
const bindings = candidates.map((raw) => {
|
|
205087
205188
|
const state = JSON.parse(raw);
|
|
205088
|
-
if (!object12(state) || state.schemaVersion !== 1 || !object12(state.documents) || typeof state.endpoint !== "string" || !
|
|
205189
|
+
if (!object12(state) || state.schemaVersion !== 1 || !object12(state.documents) || typeof state.endpoint !== "string" || !identifier10(state.workspaceId)) throw new Error();
|
|
205089
205190
|
return parseBinding({ endpoint: normalizeUrl(state.endpoint), workspaceId: state.workspaceId });
|
|
205090
205191
|
});
|
|
205091
205192
|
if (bindings.some((binding) => !sameBinding(binding, bindings[0]))) throw new Error();
|
|
@@ -205329,7 +205430,7 @@ async function recordProjectActivity(context, options) {
|
|
|
205329
205430
|
}
|
|
205330
205431
|
|
|
205331
205432
|
// packages/cli/src/style-operations.ts
|
|
205332
|
-
var
|
|
205433
|
+
var hash6 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
|
|
205333
205434
|
var readJson = async (root, path) => JSON.parse((await readReviewFile(await checkedPath(root, path, false), 1024 * 1024)).toString("utf8"));
|
|
205334
205435
|
var jsonLiteral = (value) => JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
|
|
205335
205436
|
async function localStyle(root, id4) {
|
|
@@ -205357,9 +205458,9 @@ function bindingSpans(code, bindings, format = "html") {
|
|
|
205357
205458
|
if (format === "javascript-module") {
|
|
205358
205459
|
const tokens = javascriptLiteralTokens(code);
|
|
205359
205460
|
for (const binding of bindings) {
|
|
205360
|
-
const literal2 = JSON.stringify(binding.literal),
|
|
205361
|
-
if (
|
|
205362
|
-
spans.push(...
|
|
205461
|
+
const literal2 = JSON.stringify(binding.literal), matches2 = tokens.filter((token) => code.slice(token.start, token.end) === literal2);
|
|
205462
|
+
if (matches2.length !== binding.occurrences) throw new Error(`Binding ${binding.name}: expected ${binding.occurrences} exact JSON literal occurrences; found ${matches2.length}. Use a dedicated configuration object in the module; comments and templates are not binding sites.`);
|
|
205463
|
+
spans.push(...matches2.map((token) => ({ ...token, binding })));
|
|
205363
205464
|
}
|
|
205364
205465
|
spans.sort((a, b) => a.start - b.start);
|
|
205365
205466
|
for (let i = 1; i < spans.length; i++) if (spans[i].start < spans[i - 1].end) throw new Error("Overlapping component bindings; use distinct configuration literals.");
|
|
@@ -205407,7 +205508,7 @@ async function extractComponent(directory, id4, componentId, scene, bindingsFile
|
|
|
205407
205508
|
bindingSpans(code, bindings, sourceFormat);
|
|
205408
205509
|
const manifest = JSON.parse(files[base + "resources.json"] ?? stableJson({ schemaVersion: 1, id: id4, resources: [] }));
|
|
205409
205510
|
if (manifest.resources.some((r) => r.id === resourceId)) throw new Error("Component resource ID already exists.");
|
|
205410
|
-
const digest7 =
|
|
205511
|
+
const digest7 = hash6(bytes), destination = `production-assets/styles/${id4}/${componentId}-${digest7}${posix4.extname(scene).toLowerCase()}`;
|
|
205411
205512
|
manifest.resources.push({ id: resourceId, kind: "script", purpose: `Exact source for component ${componentId}. Review dependencies and bindings before reuse.`, required: true, source: { type: "local", path: destination, sha256: digest7 } });
|
|
205412
205513
|
const style = JSON.parse(files[base + "style.json"]);
|
|
205413
205514
|
style.components = [...(style.components ?? []).filter((c) => c.id !== componentId), { id: componentId, status: bindings.length ? "implemented" : "concept" }];
|
|
@@ -205423,7 +205524,7 @@ async function extractComponent(directory, id4, componentId, scene, bindingsFile
|
|
|
205423
205524
|
if (error62.code !== "ENOENT") throw error62;
|
|
205424
205525
|
}
|
|
205425
205526
|
if (previousSource) {
|
|
205426
|
-
if (
|
|
205527
|
+
if (hash6(previousSource) !== digest7) throw new Error("Existing component snapshot was modified.");
|
|
205427
205528
|
} else await atomicWrite(root, destination, bytes, { document: false, overwrite: false });
|
|
205428
205529
|
for (const path of Object.keys(changes)) {
|
|
205429
205530
|
let current2;
|
|
@@ -205469,7 +205570,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
|
|
|
205469
205570
|
const expected = resource.source.type === "asset" ? resource.source.assetId : resource.source.sha256;
|
|
205470
205571
|
if (!expected) throw new Error("Component source must have a pinned hash.");
|
|
205471
205572
|
const bytes = await readReviewFile(await checkedPath(root, path, false), 2 * 1024 * 1024);
|
|
205472
|
-
if (
|
|
205573
|
+
if (hash6(bytes) !== expected) throw new Error("Component source SHA-256 mismatch.");
|
|
205473
205574
|
assertPortableStyleCode(bytes, path);
|
|
205474
205575
|
const code = bytes.toString(), values = await readJson(root, parameters);
|
|
205475
205576
|
if (!values || Array.isArray(values) || typeof values !== "object" || Object.keys(values).some((k) => !c.bindings.some((b) => b.name === k))) throw new Error(`Parameter object contains unknown bindings: ${values && typeof values === "object" ? Object.keys(values).filter((k) => !c.bindings.some((b) => b.name === k)).join(", ") : "expected an object"}. Expected: ${c.bindings.map((b) => b.name).join(", ")}.`);
|
|
@@ -205545,7 +205646,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
|
|
|
205545
205646
|
const expected2 = source2.source.type === "asset" ? source2.source.assetId : source2.source.type === "local" ? source2.source.sha256 : void 0;
|
|
205546
205647
|
const dependency = await readReviewFile(await checkedPath(root, mapped, false), 90 * 1024 * 1024);
|
|
205547
205648
|
if (!expected2 && sourceFormat === "javascript-module") throw new Error("Module dependency must have a pinned hash: " + original);
|
|
205548
|
-
if (expected2 &&
|
|
205649
|
+
if (expected2 && hash6(dependency) !== expected2) throw new Error("Dependency hash mismatch: " + original);
|
|
205549
205650
|
assertPortableStyleCode(dependency, mapped);
|
|
205550
205651
|
let rebased = posix4.relative(posix4.dirname(out), mapped).split("/").map(encodeURIComponent).join("/");
|
|
205551
205652
|
if (sourceFormat === "javascript-module" && !rebased.startsWith(".")) rebased = "./" + rebased;
|
|
@@ -205555,7 +205656,7 @@ async function prepareComponent(directory, id4, componentId, parameters, out) {
|
|
|
205555
205656
|
for (const replacement of replacements) prepared = prepared.split(replacement.from).join(replacement.to);
|
|
205556
205657
|
assertPortableStyleCode(Buffer.from(prepared), out);
|
|
205557
205658
|
await atomicWrite(root, out, prepared, { document: false, overwrite: false, mode: 384 });
|
|
205558
|
-
return { id: id4, componentId, out, sourceFormat, sourceSha256: expected, sha256:
|
|
205659
|
+
return { id: id4, componentId, out, sourceFormat, sourceSha256: expected, sha256: hash6(Buffer.from(prepared)), executed: false, rendered: false, warnings: [...new Set(warnings), "Review unbound pilot values and dependencies. This is a code adaptation, not a transfer quality or determinism certification."] };
|
|
205559
205660
|
}
|
|
205560
205661
|
async function testStyleTransfer(directory, id4, projectId) {
|
|
205561
205662
|
const root = await ensureRoot(directory);
|
|
@@ -205620,7 +205721,7 @@ async function loadCaptionContext(directory, projectId, styleId2, embedFont = tr
|
|
|
205620
205721
|
if (!resource || resource.kind !== "font" || resource.source.type === "requirement") throw new Error("Caption font resource is missing; declare and download the exact font.");
|
|
205621
205722
|
const path = resource.source.type === "local" ? resource.source.path : styleAssetPath(resolved.project.style, resource.source), expected = resource.source.type === "local" ? resource.source.sha256 : resource.source.assetId;
|
|
205622
205723
|
const bytes = await readReviewFile(await checkedPath(root, path, false), 8 * 1024 * 1024);
|
|
205623
|
-
if (!expected ||
|
|
205724
|
+
if (!expected || hash6(bytes) !== expected) throw new Error("Caption font needs a verified SHA-256.");
|
|
205624
205725
|
const ext = posix4.extname(path).slice(1);
|
|
205625
205726
|
if (!["woff", "woff2", "ttf", "otf"].includes(ext)) throw new Error("Unsupported caption font format.");
|
|
205626
205727
|
fontDataUrl = `data:font/${ext};base64,${bytes.toString("base64")}`;
|
|
@@ -206281,7 +206382,7 @@ async function localRenderPreflight(root, flags, dependencies) {
|
|
|
206281
206382
|
const destination = join5(temporary, filePath);
|
|
206282
206383
|
await mkdir5(dirname6(destination), { recursive: true });
|
|
206283
206384
|
const output3 = await open9(destination, "wx", 384);
|
|
206284
|
-
const
|
|
206385
|
+
const hash13 = createHash7("sha256"), buffer = Buffer.allocUnsafe(4 * 1024 * 1024);
|
|
206285
206386
|
let count2 = 0;
|
|
206286
206387
|
try {
|
|
206287
206388
|
for (; ; ) {
|
|
@@ -206290,13 +206391,13 @@ async function localRenderPreflight(root, flags, dependencies) {
|
|
|
206290
206391
|
count2 += bytesRead;
|
|
206291
206392
|
if (count2 > before.size) throw invalid3("An input changed during preflight.", pathDetail(filePath));
|
|
206292
206393
|
const bytes = buffer.subarray(0, bytesRead);
|
|
206293
|
-
|
|
206394
|
+
hash13.update(bytes);
|
|
206294
206395
|
await output3.writeFile(bytes);
|
|
206295
206396
|
}
|
|
206296
206397
|
} finally {
|
|
206297
206398
|
await output3.close();
|
|
206298
206399
|
}
|
|
206299
|
-
const sha2562 =
|
|
206400
|
+
const sha2562 = hash13.digest("hex"), after = await source2.stat();
|
|
206300
206401
|
if (count2 !== before.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw invalid3("An input changed during preflight.", pathDetail(filePath));
|
|
206301
206402
|
if (typeof manifest.files[index] !== "string" && (entry.bytes !== count2 || entry.sha256 !== sha2562)) throw invalid3("A local input differs from the prepared manifest.", { failure: { stage: "input_validation", reason: "input_checksum_mismatch", detail: entry.bytes !== count2 ? "size_mismatch" : "checksum_mismatch", ...pathDetail(filePath) } });
|
|
206302
206403
|
files.push({ ...entry, bytes: count2, sha256: sha2562 });
|
|
@@ -206324,6 +206425,143 @@ async function localRenderPreflight(root, flags, dependencies) {
|
|
|
206324
206425
|
|
|
206325
206426
|
// packages/cli/src/cloud-render.ts
|
|
206326
206427
|
import { readFile as readFile2, mkdir as mkdir6, open as open11, unlink as unlink7, lstat as lstat12 } from "node:fs/promises";
|
|
206428
|
+
|
|
206429
|
+
// packages/cli/src/project-sync.ts
|
|
206430
|
+
import { readdir as readdir5 } from "node:fs/promises";
|
|
206431
|
+
function projectPushScope(projectId) {
|
|
206432
|
+
assertIdentifier(projectId);
|
|
206433
|
+
return { kind: "project", projectId, prefix: `videos/${projectId}/`, sharedDependenciesIncluded: false };
|
|
206434
|
+
}
|
|
206435
|
+
async function readProjectDocuments(root, projectId) {
|
|
206436
|
+
const scope = projectPushScope(projectId);
|
|
206437
|
+
const files = /* @__PURE__ */ Object.create(null);
|
|
206438
|
+
async function walk(path) {
|
|
206439
|
+
const directory = await checkedPath(root, path, false);
|
|
206440
|
+
let entries;
|
|
206441
|
+
try {
|
|
206442
|
+
entries = await readdir5(directory, { withFileTypes: true });
|
|
206443
|
+
} catch (error62) {
|
|
206444
|
+
if (error62.code === "ENOENT") return;
|
|
206445
|
+
throw error62;
|
|
206446
|
+
}
|
|
206447
|
+
for (const entry of entries) {
|
|
206448
|
+
const child = `${path}/${entry.name}`;
|
|
206449
|
+
if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
|
|
206450
|
+
if (entry.name.startsWith(".")) continue;
|
|
206451
|
+
if (entry.isDirectory()) {
|
|
206452
|
+
if (["assets", "renders"].includes(entry.name)) continue;
|
|
206453
|
+
await walk(child);
|
|
206454
|
+
} else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) files[child] = await readText(root, child);
|
|
206455
|
+
}
|
|
206456
|
+
}
|
|
206457
|
+
await walk(scope.prefix.slice(0, -1));
|
|
206458
|
+
return files;
|
|
206459
|
+
}
|
|
206460
|
+
|
|
206461
|
+
// packages/cli/src/production-context.ts
|
|
206462
|
+
async function readProductionSnapshot(client, projectId) {
|
|
206463
|
+
const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
|
|
206464
|
+
const snapshot = result2.editorialSnapshot;
|
|
206465
|
+
if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash13) => typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
|
|
206466
|
+
if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash13) => typeof hash13 !== "string" || !/^[a-f0-9]{64}$/.test(hash13)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
|
|
206467
|
+
return snapshot;
|
|
206468
|
+
}
|
|
206469
|
+
async function prepareProductionContext(root, projectId, client) {
|
|
206470
|
+
const resolved = await resolveProject(await readProjectWorkspace(root, projectId), projectId);
|
|
206471
|
+
const sourceKey = stableJson(await effectiveEditorialSourceHashes(resolved));
|
|
206472
|
+
let contextVersion;
|
|
206473
|
+
const remote = async () => {
|
|
206474
|
+
const snapshot = await readProductionSnapshot(client, projectId);
|
|
206475
|
+
const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
|
|
206476
|
+
if (stableJson(portableHashes) !== (snapshot.effectiveSourceHashes ? sourceKey : stableJson(resolved.lock.sourceHashes))) throw new CliError("PRODUCTION_CONTEXT_CONFLICT", "Local and web project preferences or material differ.", "Use status and pull --project to inspect/reconcile changes. Do not overwrite either side automatically.");
|
|
206477
|
+
return snapshot.contextVersion;
|
|
206478
|
+
};
|
|
206479
|
+
if (client) contextVersion = await remote();
|
|
206480
|
+
else contextVersion = await sha256(sourceKey);
|
|
206481
|
+
const validateContext = async () => {
|
|
206482
|
+
const localUnchanged = async () => stableJson(await effectiveEditorialSourceHashes(await resolveProject(await readProjectWorkspace(root, projectId), projectId))) === sourceKey;
|
|
206483
|
+
if (!await localUnchanged()) return false;
|
|
206484
|
+
if (!client) return true;
|
|
206485
|
+
try {
|
|
206486
|
+
if (await remote() !== contextVersion) return false;
|
|
206487
|
+
} catch (error62) {
|
|
206488
|
+
if (error62 instanceof CliError && error62.code === "PRODUCTION_CONTEXT_CONFLICT") return false;
|
|
206489
|
+
throw error62;
|
|
206490
|
+
}
|
|
206491
|
+
return localUnchanged();
|
|
206492
|
+
};
|
|
206493
|
+
return { resolved, contextVersion, validateContext, contextScope: client ? "local_and_remote" : "local_only" };
|
|
206494
|
+
}
|
|
206495
|
+
|
|
206496
|
+
// packages/cli/src/workflow-local-sync.ts
|
|
206497
|
+
async function projectLocalSync(client, root, projectId, remoteHashes, completeRemoteContext = false) {
|
|
206498
|
+
assertIdentifier(projectId);
|
|
206499
|
+
const result2 = { status: "unknown", basis: "unavailable", projectId, pending: [], unknown: [], remoteChanged: [], contextPending: [], contextDirty: [], checkpoint: "unknown", actions: [], remoteVerified: false, uploaded: false };
|
|
206500
|
+
let files;
|
|
206501
|
+
let contextPaths;
|
|
206502
|
+
let requiredPaths;
|
|
206503
|
+
try {
|
|
206504
|
+
const projectFiles = await readProjectDocuments(root, projectId);
|
|
206505
|
+
if (!projectFiles[`videos/${projectId}/project.json`]) return result2;
|
|
206506
|
+
const contextFiles = await readProjectWorkspace(root, projectId);
|
|
206507
|
+
const project2 = JSON.parse(projectFiles[`videos/${projectId}/project.json`]);
|
|
206508
|
+
requiredPaths = new Set(projectSources(project2));
|
|
206509
|
+
contextPaths = /* @__PURE__ */ new Set([...Object.keys(contextFiles), ...projectSources(project2), ...optionalProjectSources(project2)]);
|
|
206510
|
+
files = { ...contextFiles, ...projectFiles };
|
|
206511
|
+
} catch (error62) {
|
|
206512
|
+
if (error62.code === "ENOENT") return result2;
|
|
206513
|
+
throw error62;
|
|
206514
|
+
}
|
|
206515
|
+
const me = await client.me();
|
|
206516
|
+
const state = await loadSyncState(root, client.url, me.workspaceId);
|
|
206517
|
+
const prefix = `videos/${projectId}/`, checkpoint = `${prefix}checkpoint.json`;
|
|
206518
|
+
const hashes = Object.fromEntries(await Promise.all(Object.entries(files).map(async ([path, content]) => [path, await sha256(content)])));
|
|
206519
|
+
for (const [path, current2] of Object.entries(hashes)) {
|
|
206520
|
+
const baseline = state.documents[path]?.sha256, remote = remoteHashes?.[path];
|
|
206521
|
+
if (remote === current2) continue;
|
|
206522
|
+
if (baseline && current2 !== baseline) result2.pending.push(path);
|
|
206523
|
+
else if (completeRemoteContext && contextPaths.has(path)) result2.remoteChanged.push(path);
|
|
206524
|
+
else if (remote && baseline && remote !== baseline) result2.remoteChanged.push(path);
|
|
206525
|
+
else if (!baseline) result2.unknown.push(path);
|
|
206526
|
+
}
|
|
206527
|
+
for (const path of Object.keys(state.documents)) if (path.startsWith(prefix) && !hashes[path] && !path.includes("/style-snapshots/")) result2.unknown.push(path);
|
|
206528
|
+
for (const path of contextPaths) if (!hashes[path] && (requiredPaths.has(path) || state.documents[path] || remoteHashes?.[path]) && !result2.unknown.includes(path)) result2.unknown.push(path);
|
|
206529
|
+
for (const values of [result2.pending, result2.unknown, result2.remoteChanged]) values.sort();
|
|
206530
|
+
result2.contextPending = [...new Set([...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => contextPaths.has(path)))].sort();
|
|
206531
|
+
result2.contextDirty = [...new Set([...result2.pending, ...result2.remoteChanged, ...result2.unknown.filter((path) => !!state.documents[path])].filter((path) => contextPaths.has(path)))].sort();
|
|
206532
|
+
result2.remoteVerified = !result2.unknown.length && !result2.remoteChanged.length && Object.keys(hashes).length > 0 && Object.entries(hashes).every(([path, hash13]) => remoteHashes?.[path] === hash13);
|
|
206533
|
+
result2.basis = remoteHashes ? "current_remote_and_baseline" : "last_sync_baseline";
|
|
206534
|
+
result2.status = result2.pending.length ? "pending" : result2.unknown.length || result2.remoteChanged.length || !result2.remoteVerified ? "unknown" : "in_sync";
|
|
206535
|
+
result2.checkpoint = !hashes[checkpoint] ? "missing" : result2.pending.includes(checkpoint) ? "pending" : remoteHashes?.[checkpoint] === hashes[checkpoint] ? "in_sync" : "unknown";
|
|
206536
|
+
const project = [...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => path.startsWith(prefix));
|
|
206537
|
+
const shared2 = [...result2.pending, ...result2.unknown, ...result2.remoteChanged].filter((path) => !path.startsWith(prefix));
|
|
206538
|
+
if (project.length) result2.actions.push({ kind: "project_sync", command: `editorbrain push --project ${projectId} --dry-run`, paths: [...new Set(project)].sort() });
|
|
206539
|
+
if (shared2.length) result2.actions.push({ kind: "shared_context", command: "editorbrain status", paths: [...new Set(shared2)].sort() });
|
|
206540
|
+
return result2;
|
|
206541
|
+
}
|
|
206542
|
+
async function currentProjectLocalSync(client, root, projectId) {
|
|
206543
|
+
const localSync = await projectLocalSync(client, root, projectId);
|
|
206544
|
+
if (localSync.basis === "unavailable") return { localSync, contextVersion: null };
|
|
206545
|
+
const snapshot = await readProductionSnapshot(client, projectId);
|
|
206546
|
+
return { localSync: await projectLocalSync(client, root, projectId, snapshot.sourceHashes, true), contextVersion: snapshot.contextVersion };
|
|
206547
|
+
}
|
|
206548
|
+
|
|
206549
|
+
// packages/cli/src/render-workflow-context.ts
|
|
206550
|
+
async function assertCloudRenderLocalContext(client, root, manifest, jobId) {
|
|
206551
|
+
if (manifest.purpose === "preview") return;
|
|
206552
|
+
const { localSync } = await currentProjectLocalSync(client, root, manifest.projectId);
|
|
206553
|
+
if (!localSync.contextDirty.length) return;
|
|
206554
|
+
try {
|
|
206555
|
+
const job = await client.request(`/v1/render-cloud/${jobId}`);
|
|
206556
|
+
if (job.id !== jobId || job.projectId !== manifest.projectId || typeof job.status !== "string") throw new CliError("INVALID_RENDER_RESPONSE", "The existing render did not match this project and request.", "Inspect the same job ID before continuing; do not create a replacement.");
|
|
206557
|
+
return;
|
|
206558
|
+
} catch (error62) {
|
|
206559
|
+
if (!(error62 instanceof ApiError) || error62.status !== 404) throw error62;
|
|
206560
|
+
}
|
|
206561
|
+
throw new CliError("RENDER_CONTEXT_UNSYNCED", "Local editorial documents differ from the context approved in the cloud.", "Inspect localSync and run the scoped push dry-run before reconciling documents and review evidence. Preview rendering remains available. Nothing was uploaded, rendered or charged.", false, { localSync });
|
|
206562
|
+
}
|
|
206563
|
+
|
|
206564
|
+
// packages/cli/src/cloud-render.ts
|
|
206327
206565
|
import { dirname as dirname8, basename, extname as extname2 } from "node:path";
|
|
206328
206566
|
import { createHash as createHash8, randomUUID as randomUUID3 } from "node:crypto";
|
|
206329
206567
|
|
|
@@ -206386,7 +206624,7 @@ async function inspectRenderFile(path, label, onChunk, chunkBytes = RENDER_CHUNK
|
|
|
206386
206624
|
try {
|
|
206387
206625
|
const before = await handle.stat();
|
|
206388
206626
|
if (!before.isFile() || before.size <= 0 || before.size > RENDER_LONG_MAX_BYTES) throw bad(`Invalid render file size or type: ${label}. Maximum ${RENDER_LONG_MAX_BYTES} bytes.`);
|
|
206389
|
-
const buffer = Buffer.allocUnsafe(chunkBytes),
|
|
206627
|
+
const buffer = Buffer.allocUnsafe(chunkBytes), hash13 = createHash8("sha256");
|
|
206390
206628
|
let bytes = 0, index = 0;
|
|
206391
206629
|
while (bytes < before.size) {
|
|
206392
206630
|
const expected = Math.min(buffer.length, before.size - bytes);
|
|
@@ -206397,13 +206635,13 @@ async function inspectRenderFile(path, label, onChunk, chunkBytes = RENDER_CHUNK
|
|
|
206397
206635
|
filled += part.bytesRead;
|
|
206398
206636
|
}
|
|
206399
206637
|
const chunk = buffer.subarray(0, filled);
|
|
206400
|
-
|
|
206638
|
+
hash13.update(chunk);
|
|
206401
206639
|
if (onChunk) await onChunk(chunk, index++);
|
|
206402
206640
|
bytes += filled;
|
|
206403
206641
|
}
|
|
206404
206642
|
const after = await handle.stat();
|
|
206405
206643
|
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw bad(`Input changed while reading: ${label}. Cancel any pending upload and prepare again.`);
|
|
206406
|
-
return { bytes, sha256:
|
|
206644
|
+
return { bytes, sha256: hash13.digest("hex") };
|
|
206407
206645
|
} finally {
|
|
206408
206646
|
await handle.close();
|
|
206409
206647
|
}
|
|
@@ -206516,7 +206754,7 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
|
|
|
206516
206754
|
}
|
|
206517
206755
|
const temp = dest + "." + randomUUID3() + ".part";
|
|
206518
206756
|
const handle = await open11(temp, "wx", 384);
|
|
206519
|
-
const
|
|
206757
|
+
const hash13 = createHash8("sha256");
|
|
206520
206758
|
let count2 = 0;
|
|
206521
206759
|
try {
|
|
206522
206760
|
for (let c = 0; c < o.chunks; c++) {
|
|
@@ -206524,10 +206762,10 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
|
|
|
206524
206762
|
const data = delivery ? await client.renderDeliveryChunk(`${endpoint2}/delivery/content`, start3, Math.min(o.bytes, start3 + RENDER_CHUNK_BYTES) - 1, o.bytes) : await client.renderChunk(`${endpoint2}/output/${c}`);
|
|
206525
206763
|
if (data.length !== Math.min(RENDER_CHUNK_BYTES, o.bytes - count2)) throw bad("Unexpected output chunk size.");
|
|
206526
206764
|
await handle.writeFile(data);
|
|
206527
|
-
|
|
206765
|
+
hash13.update(data);
|
|
206528
206766
|
count2 += data.length;
|
|
206529
206767
|
}
|
|
206530
|
-
if (
|
|
206768
|
+
if (hash13.digest("hex") !== o.sha256) throw bad("Output checksum mismatch.");
|
|
206531
206769
|
await publishDownloadedRender(handle, temp, dest);
|
|
206532
206770
|
} catch (e) {
|
|
206533
206771
|
await handle.close().catch(() => {
|
|
@@ -206626,6 +206864,7 @@ async function cloudRenderCommand(client, root, command, id4, flags) {
|
|
|
206626
206864
|
}
|
|
206627
206865
|
const maxCredits = flags["max-credits"] === void 0 ? void 0 : Number(flags["max-credits"]);
|
|
206628
206866
|
if (maxCredits !== void 0 && (!Number.isFinite(maxCredits) || maxCredits < 0)) throw bad("--max-credits must be a nonnegative number.");
|
|
206867
|
+
await assertCloudRenderLocalContext(client, root, manifest, input2.id);
|
|
206629
206868
|
for (const f of manifest.files) {
|
|
206630
206869
|
if (f.sourceAssetId) continue;
|
|
206631
206870
|
const info = await inspectRenderFile(await checkedPath(root, f.path, false), f.path);
|
|
@@ -206905,8 +207144,8 @@ async function probeLocalMedia(value) {
|
|
|
206905
207144
|
if (!before.isFile()) throw new MediaToolError("MEDIA_NOT_REGULAR", "The media input must be a regular local file.");
|
|
206906
207145
|
const entries = "format=duration,start_time:stream=index,codec_type,codec_name,width,height,avg_frame_rate,sample_rate,channels,duration,color_transfer,sample_aspect_ratio,pix_fmt:stream_disposition=attached_pic:stream_side_data=side_data_type,rotation,displaymatrix:stream_tags=rotate";
|
|
206907
207146
|
const { stdout } = await runMediaTool("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", ...localInputArgs(path)]);
|
|
206908
|
-
const
|
|
206909
|
-
for await (const chunk of handle.createReadStream({ autoClose: false }))
|
|
207147
|
+
const hash13 = createHash9("sha256");
|
|
207148
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) hash13.update(chunk);
|
|
206910
207149
|
const after = await handle.stat();
|
|
206911
207150
|
await assertNoMediaSymlinks(path);
|
|
206912
207151
|
const current2 = await lstat13(path);
|
|
@@ -206931,7 +207170,7 @@ async function probeLocalMedia(value) {
|
|
|
206931
207170
|
...type === "audio" ? { sampleRate: nonnegative2(stream.sample_rate), channels: positiveInteger(stream.channels) ?? null } : {}
|
|
206932
207171
|
};
|
|
206933
207172
|
});
|
|
206934
|
-
return { path, sha256:
|
|
207173
|
+
return { path, sha256: hash13.digest("hex"), bytes: after.size, durationSeconds: nonnegative2(raw.format?.duration), startTimeSeconds: finite2(raw.format?.start_time), streams };
|
|
206935
207174
|
} finally {
|
|
206936
207175
|
await handle.close();
|
|
206937
207176
|
}
|
|
@@ -206940,21 +207179,21 @@ async function probeLocalMedia(value) {
|
|
|
206940
207179
|
// packages/cli/src/production-continuity-check.ts
|
|
206941
207180
|
var obj2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
206942
207181
|
var number5 = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
|
|
206943
|
-
var
|
|
207182
|
+
var hash7 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
|
|
206944
207183
|
function validateContinuityInput(value) {
|
|
206945
207184
|
const issues = [];
|
|
206946
207185
|
if (!obj2(value)) throw new CliError("INVALID_REVIEW_INPUT", "Review input must be an object.", "Use the documented continuity schema.");
|
|
206947
207186
|
const add = (s) => issues.push(s);
|
|
206948
|
-
if (value.schemaVersion !== 1 || !
|
|
207187
|
+
if (value.schemaVersion !== 1 || !hash7(value.artifactSha256)) add("schemaVersion: 1 and artifactSha256 (64 lowercase hex) are required.");
|
|
206949
207188
|
if (Object.keys(value).some((k) => !["schemaVersion", "artifactSha256", "cuts", "transcript", "geometry"].includes(k))) add("Unexpected top-level review field.");
|
|
206950
207189
|
if (!value.cuts && !value.geometry) add("Provide cuts + transcript and/or geometry.");
|
|
206951
207190
|
if (value.cuts || value.transcript) {
|
|
206952
|
-
if (!obj2(value.cuts) || !
|
|
207191
|
+
if (!obj2(value.cuts) || !hash7(value.cuts.sourceSha256) || !Array.isArray(value.cuts.parts) || value.cuts.parts.length < 1 || value.cuts.parts.length > 200) add("cuts requires sourceSha256 and 1\u2013200 parts.");
|
|
206953
207192
|
else value.cuts.parts.forEach((p, i) => {
|
|
206954
207193
|
if (!obj2(p) || !["source", "final"].every((k) => Array.isArray(p[k]) && p[k].length === 2 && p[k].every(number5) && p[k][1] > p[k][0])) add(`cuts.parts[${i}]: expected source:[start,end], final:[start,end] in seconds.`);
|
|
206955
207194
|
else if (i && Math.abs(p.final[0] - value.cuts.parts[i - 1]?.final?.[1]) > 2e-3) add(`cuts.parts[${i}]: final intervals must be contiguous and ordered.`);
|
|
206956
207195
|
});
|
|
206957
|
-
if (!obj2(value.transcript) || !
|
|
207196
|
+
if (!obj2(value.transcript) || !hash7(value.transcript.sourceSha256) || value.transcript.sourceSha256 !== value.cuts?.sourceSha256 || !Array.isArray(value.transcript.words) || !value.transcript.words.length || value.transcript.words.length > 3e4) add("transcript requires matching sourceSha256 and 1\u201330000 source-timeline words.");
|
|
206958
207197
|
else value.transcript.words.forEach((w, i) => {
|
|
206959
207198
|
if (!obj2(w) || typeof w.text !== "string" || w.text.length > 500 || !number5(w.start) || !number5(w.end) || w.end <= w.start) add(`transcript.words[${i}]: expected text,start,end in source seconds.`);
|
|
206960
207199
|
});
|
|
@@ -207077,7 +207316,7 @@ async function loadContinuityInput(root, path) {
|
|
|
207077
207316
|
}
|
|
207078
207317
|
|
|
207079
207318
|
// packages/cli/src/project-variants.ts
|
|
207080
|
-
import { mkdir as mkdir7, readdir as
|
|
207319
|
+
import { mkdir as mkdir7, readdir as readdir6 } from "node:fs/promises";
|
|
207081
207320
|
import { createHash as createHash10 } from "node:crypto";
|
|
207082
207321
|
async function projectVariants(directory, project, operation, id4, changes) {
|
|
207083
207322
|
const root = await ensureRoot(directory);
|
|
@@ -207088,7 +207327,7 @@ async function projectVariants(directory, project, operation, id4, changes) {
|
|
|
207088
207327
|
if (operation === "list") {
|
|
207089
207328
|
let entries;
|
|
207090
207329
|
try {
|
|
207091
|
-
entries = await
|
|
207330
|
+
entries = await readdir6(await checkedPath(root, base, false), { withFileTypes: true });
|
|
207092
207331
|
} catch (e) {
|
|
207093
207332
|
if (e.code === "ENOENT") return { variants: [] };
|
|
207094
207333
|
throw e;
|
|
@@ -207162,7 +207401,7 @@ async function projectVariants(directory, project, operation, id4, changes) {
|
|
|
207162
207401
|
|
|
207163
207402
|
// packages/cli/src/project-disk.ts
|
|
207164
207403
|
import { constants as constants9 } from "node:fs";
|
|
207165
|
-
import { open as open13, readdir as
|
|
207404
|
+
import { open as open13, readdir as readdir7, lstat as lstat14, copyFile, rename as rename3, unlink as unlink8, chmod as chmod2, utimes } from "node:fs/promises";
|
|
207166
207405
|
import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";
|
|
207167
207406
|
import { dirname as dirname10, join as join6 } from "node:path";
|
|
207168
207407
|
async function fingerprintFile(path) {
|
|
@@ -207170,18 +207409,18 @@ async function fingerprintFile(path) {
|
|
|
207170
207409
|
try {
|
|
207171
207410
|
const before = await h.stat();
|
|
207172
207411
|
if (!before.isFile()) throw new Error("Expected a regular file.");
|
|
207173
|
-
const
|
|
207412
|
+
const hash13 = createHash11("sha256");
|
|
207174
207413
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
207175
207414
|
let offset = 0;
|
|
207176
207415
|
while (offset < before.size) {
|
|
207177
207416
|
const { bytesRead } = await h.read(buffer, 0, Math.min(buffer.length, before.size - offset), offset);
|
|
207178
207417
|
if (!bytesRead) throw new Error("File changed while hashing.");
|
|
207179
|
-
|
|
207418
|
+
hash13.update(buffer.subarray(0, bytesRead));
|
|
207180
207419
|
offset += bytesRead;
|
|
207181
207420
|
}
|
|
207182
207421
|
const after = await h.stat();
|
|
207183
207422
|
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error("File changed while hashing.");
|
|
207184
|
-
return { sha256:
|
|
207423
|
+
return { sha256: hash13.digest("hex"), bytes: before.size, ino: before.ino, dev: before.dev, mtimeMs: before.mtimeMs, atimeMs: before.atimeMs, mode: before.mode };
|
|
207185
207424
|
} finally {
|
|
207186
207425
|
await h.close();
|
|
207187
207426
|
}
|
|
@@ -207195,7 +207434,7 @@ async function projectDisk(root, project) {
|
|
|
207195
207434
|
if (depth > 16) throw new CliError("DISK_SCAN_LIMIT", "Project exceeds 16 directory levels.", "Inspect the project manually; nothing was removed.");
|
|
207196
207435
|
let entries;
|
|
207197
207436
|
try {
|
|
207198
|
-
entries = await
|
|
207437
|
+
entries = await readdir7(await checkedPath(root, dir, false), { withFileTypes: true });
|
|
207199
207438
|
} catch (e) {
|
|
207200
207439
|
if (e.code === "ENOENT") return;
|
|
207201
207440
|
throw e;
|
|
@@ -207314,7 +207553,7 @@ var introductions = {
|
|
|
207314
207553
|
checkpoint: "Usa --expected-checkpoint SHA256|none del \xFAltimo resume para proteger decisiones desde esa lectura. current toma el hash al iniciar este comando y detecta solo escrituras concurrentes durante esta invocaci\xF3n. --current-version, --primary-artifact, --dependency y --render-command conservan contexto t\xE9cnico portable; nunca ejecutan. Guarda el hito declarado y hashes en videos/ID/checkpoint.json. Las rutas son relativas a la carpeta registrada por rol o al workspace. Repite --done/--pending/--decision; sus listas reemplazan las anteriores. --primary-artifact y --dependency registran y verifican sus archivos sin repetir --artifact. --artifact reemplaza la lista base y a\xF1ade esas referencias expl\xEDcitas; omitirlo conserva los artefactos previos. Usa push expl\xEDcitamente para sincronizar el texto.",
|
|
207315
207554
|
projects: "find/list buscan por nombre/tema, --brand, --since y --before (UTC ISO), con paginaci\xF3n y actividad real; find --local consulta el registro privado; --dir lo limita a un workspace registrado, sin red ni escaneo. link/unlink administran carpetas privadas locales; where ID las consulta y resume ID recupera el hito. create crea el proyecto remoto y su baseline local sin sobrescribir cambios; pin-style fija sus documentos de estilo por hash; intake devuelve su material y enlace privado de subida. Conserva el mismo ID para retomarlo. No inicia edici\xF3n, render ni gasto; un enlace de subida requiere iniciar sesi\xF3n.",
|
|
207316
207555
|
styles: "Reglas preferred orientan decisiones por video; required expl\xEDcitas se verifican por separado. rules inspect muestra hashes, rules decisions guarda adaptaciones por proyecto. captions preview es local expl\xEDcito; export avisa p\xE9rdidas SRT/ASS. Estilos de edici\xF3n completos. list = biblioteca publicada; mine = estilos locales de este workspace. media styles son recetas visuales para generar im\xE1genes, no ediciones completas.",
|
|
207317
|
-
production: "submit prepara y registra una muestra privada autorizada con recibo recuperable; --parent sustituye la pendiente anterior sin aprobar ni borrar comentarios. reviews devuelve revisions por compatibilidad.
|
|
207556
|
+
production: "present sin --file consulta evidencia/version; con --file registra solo una presentaci\xF3n que realmente entregaste al usuario: expectedVersion, evidenceId UUID, contextVersion, phase directions|review|delivery, presented:true y source revision o local. Un HTML local requiere el sidecar y medios verificados; nunca inferir aprobaci\xF3n por generar/abrir/subir. decision local requiere userConfirmed y direcci\xF3n elegida o approved:true; nube reutiliza la revisi\xF3n existente. withdraw retira evidencia solo tras instrucci\xF3n del usuario y conserva el historial. submit prepara y registra una muestra privada autorizada con recibo recuperable; --parent sustituye la pendiente anterior sin aprobar ni borrar comentarios. reviews devuelve revisions por compatibilidad. Un chequeo t\xE9cnico no aprueba la calidad creativa. verify mide el archivo final; los chequeos de cortes/caras requieren evidencia alineada al mismo render.",
|
|
207318
207557
|
studio: "Herramientas de generaci\xF3n: catalog \u2192 quote \u2192 run \u2192 get. Una cotizaci\xF3n no gasta; run requiere presupuesto autorizado. Las capacidades dependen del proveedor y del plan.",
|
|
207319
207558
|
clean: "Primero inspecciona el disco. No elimina fuentes, masters ni recibos autom\xE1ticamente. --deduplicate usa copias independientes con bloques compartidos cuando el sistema lo admite.",
|
|
207320
207559
|
variants: "Variantes locales: reutilizan la edici\xF3n base y registran cambios de gancho/CTA sin duplicar medios ni modificar el proyecto original."
|
|
@@ -207337,14 +207576,14 @@ Usa --help despu\xE9s de un subcomando para ver su sintaxis.
|
|
|
207337
207576
|
}
|
|
207338
207577
|
|
|
207339
207578
|
// packages/cli/src/local-styles.ts
|
|
207340
|
-
import { readdir as
|
|
207579
|
+
import { readdir as readdir8 } from "node:fs/promises";
|
|
207341
207580
|
async function listLocalStyles(directory) {
|
|
207342
207581
|
const root = await ensureRoot(directory), styles = [], issues = [];
|
|
207343
207582
|
for (const prefix of [".editorbrain", ".editorharness"]) {
|
|
207344
207583
|
const base = `${prefix}/styles`;
|
|
207345
207584
|
let entries;
|
|
207346
207585
|
try {
|
|
207347
|
-
entries = await
|
|
207586
|
+
entries = await readdir8(await checkedPath(root, base, false), { withFileTypes: true });
|
|
207348
207587
|
} catch (e) {
|
|
207349
207588
|
if (e.code === "ENOENT") continue;
|
|
207350
207589
|
throw e;
|
|
@@ -207404,7 +207643,7 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
|
|
|
207404
207643
|
if (!reader) throw new CliError("INVALID_RESPONSE", "Source download body is missing.", "Retry the pinned source.");
|
|
207405
207644
|
const temporary = join7(dirname11(target), `.eb-motion-${randomUUID5()}.tmp`);
|
|
207406
207645
|
let handle;
|
|
207407
|
-
const
|
|
207646
|
+
const hash13 = createHash12("sha256");
|
|
207408
207647
|
let size = 0;
|
|
207409
207648
|
try {
|
|
207410
207649
|
await mkdir8(dirname11(target), { recursive: true });
|
|
@@ -207415,10 +207654,10 @@ async function downloadPinnedSource(client, pin, root, out, kind2, fetcher = fet
|
|
|
207415
207654
|
if (done) break;
|
|
207416
207655
|
size += value.length;
|
|
207417
207656
|
if (size > pin.bytes) throw new CliError("HASH_MISMATCH", "Source archive exceeds the pinned length.", "Discard the unverified download.");
|
|
207418
|
-
|
|
207657
|
+
hash13.update(value);
|
|
207419
207658
|
await handle.writeFile(value);
|
|
207420
207659
|
}
|
|
207421
|
-
if (size !== pin.bytes ||
|
|
207660
|
+
if (size !== pin.bytes || hash13.digest("hex") !== pin.sha256) throw new CliError("HASH_MISMATCH", "Source archive verification failed.", "Do not extract this download.");
|
|
207422
207661
|
await handle.sync();
|
|
207423
207662
|
await handle.close();
|
|
207424
207663
|
await checkedPath(root, out, false);
|
|
@@ -208709,7 +208948,7 @@ var mimeTypes = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "vide
|
|
|
208709
208948
|
var fail = (message) => {
|
|
208710
208949
|
throw new CliError("INVALID_RESOURCE", message, "Read editorbrain help and references/personal-resources.md. No upload or paid analysis is automatic.");
|
|
208711
208950
|
};
|
|
208712
|
-
function
|
|
208951
|
+
function uuid8(value) {
|
|
208713
208952
|
if (!value || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) fail("Provide a resource UUID.");
|
|
208714
208953
|
return value;
|
|
208715
208954
|
}
|
|
@@ -208754,7 +208993,7 @@ async function registerLocalResource(client, root, file2, options = {}) {
|
|
|
208754
208993
|
return { id: id4, revision: result2.revision, reused: !!existing, mediaUploaded: false, contentReviewed: false, localMap: path, next: "Use resources get to check for an existing index; inspect only missing evidence. Registering bytes does not transcribe, analyze or approve them." };
|
|
208755
208994
|
}
|
|
208756
208995
|
async function locateLocalResource(client, root, id4) {
|
|
208757
|
-
|
|
208996
|
+
uuid8(id4);
|
|
208758
208997
|
const [item, me] = await Promise.all([client.request("/v1/resources/" + id4), client.request("/v1/me")]);
|
|
208759
208998
|
const namespace = (await sha256(client.url + "\n" + me.workspaceId)).slice(0, 32), path = `.editorbrain-local/resources/${namespace}/${id4}.json`;
|
|
208760
208999
|
let mapping;
|
|
@@ -208786,7 +209025,7 @@ async function personalResourceCommand(client, root, command, arg, flags) {
|
|
|
208786
209025
|
}
|
|
208787
209026
|
return client.request("/v1/resources?" + params);
|
|
208788
209027
|
}
|
|
208789
|
-
const id4 =
|
|
209028
|
+
const id4 = uuid8(arg), path = "/v1/resources/" + id4;
|
|
208790
209029
|
if (command === "get") return client.request(path);
|
|
208791
209030
|
if (command === "locate") return locateLocalResource(client, root, id4);
|
|
208792
209031
|
if (command === "segments") {
|
|
@@ -208821,7 +209060,7 @@ async function personalResourceCommand(client, root, command, arg, flags) {
|
|
|
208821
209060
|
if (!item2.resource.media) fail("Tempo requires original media.");
|
|
208822
209061
|
if (item2.index && item2.index.method !== "tempo") fail("This resource has other evidence. Preserve it and merge transcript segments explicitly with resources index.");
|
|
208823
209062
|
await locateLocalResource(client, root, id4);
|
|
208824
|
-
const job = await client.request("/v1/studio/jobs/" +
|
|
209063
|
+
const job = await client.request("/v1/studio/jobs/" + uuid8(flag(flags, "job", true)));
|
|
208825
209064
|
if (!["scribe", "tempo"].includes(job.tool) || job.status !== "completed" || !job.assetId || !/^[a-f0-9]{64}$/.test(job.assetId)) fail("Choose an existing completed Tempo job; this command never runs or retries a paid job.");
|
|
208826
209065
|
const transcript = await client.request("/v1/assets/" + job.assetId), mapping = await readProductionJson(root, flag(flags, "mapping", true));
|
|
208827
209066
|
const index = indexFromTempo(transcript, item2.resource.media, mapping);
|
|
@@ -208844,11 +209083,25 @@ import { promisify as promisify2 } from "node:util";
|
|
|
208844
209083
|
// packages/cli/src/agent-guidance.ts
|
|
208845
209084
|
import { createHash as createHash14 } from "node:crypto";
|
|
208846
209085
|
import { constants as constants11 } from "node:fs";
|
|
208847
|
-
import { lstat as lstat16, open as open16, readdir as
|
|
209086
|
+
import { lstat as lstat16, open as open16, readdir as readdir9, rename as rename4 } from "node:fs/promises";
|
|
208848
209087
|
import { fileURLToPath } from "node:url";
|
|
208849
209088
|
|
|
208850
209089
|
// packages/cli/src/agent-guidance-history.ts
|
|
208851
209090
|
var VERIFIED_GUIDANCE_RELEASES = [
|
|
209091
|
+
{
|
|
209092
|
+
"version": "0.48.0",
|
|
209093
|
+
"archiveSha256": "c4f3c075b863c14e6bf01ab234d57c1de3eb97d4957850605ec63c89388e6af3",
|
|
209094
|
+
"files": {
|
|
209095
|
+
"editorbrain/SKILL.md": "a2d1afd5be9c046fd2e3cdb997333c31216f0c2acdbf7feee5e31f7a84ee1c2d",
|
|
209096
|
+
"editorbrain/AGENTS.md": "01e2b0b19df7be07a7dccef9b977aabb1f6975636338b67a7dd32c88be596b58",
|
|
209097
|
+
"editorbrain/references/starting-an-edit.md": "e27fc77256a31e31b8a1baeeaa233cdca013d462685f00f82cb762e5195ce7d4",
|
|
209098
|
+
"editorbrain/references/production-continuity.md": "622d37372ddadf132c917db483541478808f2059809269074bf9ed1507ab7d81",
|
|
209099
|
+
"editorbrain/references/production-and-review.md": "521c5f2f9ed7081b37e36241910789372dfaf66bf9af992b3086516331084bd1",
|
|
209100
|
+
"editorbrain/references/workspace-files.md": "2aa122599adafa1ab9f8b5969967a17742b52fe1daec77ad79160fc5ab6dc360",
|
|
209101
|
+
"editorbrain/references/cli-mcp.md": "88d829b847525fc7eeaf369db7c2acd2a4adf10f2c23e22f0dd7878d4cc2074f",
|
|
209102
|
+
"editorbrain/references/task-map.md": "279585f6098eb9c68ad30701b1117f2d763d3c4a885a6a1f5c1b2b2f92e32e1e"
|
|
209103
|
+
}
|
|
209104
|
+
},
|
|
208852
209105
|
{
|
|
208853
209106
|
"version": "0.47.1",
|
|
208854
209107
|
"archiveSha256": "7150de5343210269c33fabf105493150611df9d1a6fcee53f45eab1865b3120d",
|
|
@@ -209979,7 +210232,7 @@ async function loadSkill(directory) {
|
|
|
209979
210232
|
const files = /* @__PURE__ */ new Map();
|
|
209980
210233
|
async function walk(path = "") {
|
|
209981
210234
|
const location3 = path ? await checkedPath(root, path, false) : root;
|
|
209982
|
-
const entries = await
|
|
210235
|
+
const entries = await readdir9(location3, { withFileTypes: true });
|
|
209983
210236
|
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
209984
210237
|
const child = path ? `${path}/${entry.name}` : entry.name;
|
|
209985
210238
|
if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed in bundled skill: ${child}`);
|
|
@@ -210114,7 +210367,7 @@ async function installAgentGuidance(directory, agent = "both") {
|
|
|
210114
210367
|
|
|
210115
210368
|
// packages/cli/src/skill-installations.ts
|
|
210116
210369
|
import { createHash as createHash15, randomUUID as randomUUID7 } from "node:crypto";
|
|
210117
|
-
import { readFile as readFile4, readdir as
|
|
210370
|
+
import { readFile as readFile4, readdir as readdir10 } from "node:fs/promises";
|
|
210118
210371
|
import { homedir as homedir2 } from "node:os";
|
|
210119
210372
|
import { isAbsolute as isAbsolute2, join as join9 } from "node:path";
|
|
210120
210373
|
|
|
@@ -210244,13 +210497,13 @@ var probe = async (tool) => {
|
|
|
210244
210497
|
var remoteOptions = { timeoutMs: 3e3, maxAttempts: 1 };
|
|
210245
210498
|
var links = { credits: "https://editorbrain.com/app/billing", integrations: "https://editorbrain.com/app/integrations" };
|
|
210246
210499
|
function studioSummary(value) {
|
|
210247
|
-
const
|
|
210248
|
-
if (!value || typeof value !== "object") throw
|
|
210500
|
+
const invalid14 = () => new CliError("INVALID_RESPONSE", "Respuesta de herramientas IA incompleta.", "Consulta editorbrain studio catalog; no inicies una generaci\xF3n con estado desconocido.");
|
|
210501
|
+
if (!value || typeof value !== "object") throw invalid14();
|
|
210249
210502
|
const data = value;
|
|
210250
|
-
if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw
|
|
210503
|
+
if (typeof data.balance !== "number" || !Number.isFinite(data.balance) || data.balance < 0 || typeof data.checkoutAvailable !== "boolean" || !Array.isArray(data.tools) || data.tools.length > 20) throw invalid14();
|
|
210251
210504
|
const names = { scribe: "tempo", tempo: "tempo", prism: "prism", vox: "vox", music: "aura", aura: "aura" };
|
|
210252
210505
|
const tools = data.tools.map((item) => {
|
|
210253
|
-
if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw
|
|
210506
|
+
if (!item || typeof item !== "object" || typeof item.id !== "string" || !Object.hasOwn(names, item.id) || typeof item.available !== "boolean" || typeof item.canSpend !== "boolean") throw invalid14();
|
|
210254
210507
|
const reasons = [!item.available ? "unavailable" : null, !item.canSpend ? "permission_required" : null, data.balance === 0 ? "no_credits" : null].filter((reason) => reason !== null);
|
|
210255
210508
|
return {
|
|
210256
210509
|
id: names[item.id],
|
|
@@ -210260,7 +210513,7 @@ function studioSummary(value) {
|
|
|
210260
210513
|
reasons
|
|
210261
210514
|
};
|
|
210262
210515
|
});
|
|
210263
|
-
if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw
|
|
210516
|
+
if (tools.length !== 4 || new Set(tools.map((tool) => tool.id)).size !== 4) throw invalid14();
|
|
210264
210517
|
return {
|
|
210265
210518
|
balance: data.balance,
|
|
210266
210519
|
checkoutAvailable: data.checkoutAvailable,
|
|
@@ -210412,7 +210665,7 @@ async function listInstallations(registry2 = installationRegistry()) {
|
|
|
210412
210665
|
if (error62.code === "ENOENT") return [];
|
|
210413
210666
|
throw error62;
|
|
210414
210667
|
}
|
|
210415
|
-
const names = (await
|
|
210668
|
+
const names = (await readdir10(root)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
|
|
210416
210669
|
if (names.length > 1e3) throw new Error("Too many registered installations. Update a specific directory.");
|
|
210417
210670
|
const records = [];
|
|
210418
210671
|
for (const name of names) {
|
|
@@ -210868,38 +211121,6 @@ async function projectIntakeCommand(client, command, argument, flags) {
|
|
|
210868
211121
|
});
|
|
210869
211122
|
}
|
|
210870
211123
|
|
|
210871
|
-
// packages/cli/src/project-sync.ts
|
|
210872
|
-
import { readdir as readdir10 } from "node:fs/promises";
|
|
210873
|
-
function projectPushScope(projectId) {
|
|
210874
|
-
assertIdentifier(projectId);
|
|
210875
|
-
return { kind: "project", projectId, prefix: `videos/${projectId}/`, sharedDependenciesIncluded: false };
|
|
210876
|
-
}
|
|
210877
|
-
async function readProjectDocuments(root, projectId) {
|
|
210878
|
-
const scope = projectPushScope(projectId);
|
|
210879
|
-
const files = /* @__PURE__ */ Object.create(null);
|
|
210880
|
-
async function walk(path) {
|
|
210881
|
-
const directory = await checkedPath(root, path, false);
|
|
210882
|
-
let entries;
|
|
210883
|
-
try {
|
|
210884
|
-
entries = await readdir10(directory, { withFileTypes: true });
|
|
210885
|
-
} catch (error62) {
|
|
210886
|
-
if (error62.code === "ENOENT") return;
|
|
210887
|
-
throw error62;
|
|
210888
|
-
}
|
|
210889
|
-
for (const entry of entries) {
|
|
210890
|
-
const child = `${path}/${entry.name}`;
|
|
210891
|
-
if (entry.isSymbolicLink()) throw new Error(`Symlinks are not allowed: ${child}`);
|
|
210892
|
-
if (entry.name.startsWith(".")) continue;
|
|
210893
|
-
if (entry.isDirectory()) {
|
|
210894
|
-
if (["assets", "renders"].includes(entry.name)) continue;
|
|
210895
|
-
await walk(child);
|
|
210896
|
-
} else if (entry.isFile() && /\.(json|md)$/.test(entry.name)) files[child] = await readText(root, child);
|
|
210897
|
-
}
|
|
210898
|
-
}
|
|
210899
|
-
await walk(scope.prefix.slice(0, -1));
|
|
210900
|
-
return files;
|
|
210901
|
-
}
|
|
210902
|
-
|
|
210903
211124
|
// packages/cli/src/project-resume.ts
|
|
210904
211125
|
import { constants as constants14 } from "node:fs";
|
|
210905
211126
|
import { lstat as lstat20, open as open19, readdir as readdir11 } from "node:fs/promises";
|
|
@@ -210907,28 +211128,36 @@ import { createHash as createHash17 } from "node:crypto";
|
|
|
210907
211128
|
import { join as join12, resolve as resolve11 } from "node:path";
|
|
210908
211129
|
|
|
210909
211130
|
// packages/cli/src/project-continuity.ts
|
|
210910
|
-
var
|
|
211131
|
+
var hash8 = external_exports.string().regex(/^[a-f0-9]{64}$/);
|
|
210911
211132
|
var id3 = external_exports.string().min(1).max(80);
|
|
210912
211133
|
var text11 = external_exports.string().max(12e3);
|
|
210913
211134
|
var count = external_exports.number().int().nonnegative();
|
|
210914
|
-
var
|
|
211135
|
+
var uuid9 = external_exports.string().uuid();
|
|
211136
|
+
var readiness = external_exports.unknown().transform((value, ctx) => {
|
|
211137
|
+
try {
|
|
211138
|
+
return parseProjectReviewReadiness(value);
|
|
211139
|
+
} catch {
|
|
211140
|
+
ctx.addIssue({ code: "custom", message: "Invalid review readiness" });
|
|
211141
|
+
return external_exports.NEVER;
|
|
211142
|
+
}
|
|
211143
|
+
});
|
|
210915
211144
|
var section = (value) => external_exports.discriminatedUnion("status", [
|
|
210916
211145
|
external_exports.object({ status: external_exports.literal("available"), value }).strict(),
|
|
210917
211146
|
external_exports.object({ status: external_exports.literal("unavailable"), reason: external_exports.enum(["not_authorized", "not_available", "read_failed"]) }).strict()
|
|
210918
211147
|
]);
|
|
210919
|
-
var page = (item, limit) => external_exports.object({ items: external_exports.array(item).max(limit), limit: external_exports.literal(limit), complete: external_exports.boolean(), nextCursor:
|
|
211148
|
+
var page = (item, limit) => external_exports.object({ items: external_exports.array(item).max(limit), limit: external_exports.literal(limit), complete: external_exports.boolean(), nextCursor: uuid9.nullable(), contextVersion: hash8 }).strict();
|
|
210920
211149
|
var review = external_exports.object({
|
|
210921
|
-
revisionId:
|
|
211150
|
+
revisionId: uuid9,
|
|
210922
211151
|
projectId: id3,
|
|
210923
|
-
assetId:
|
|
210924
|
-
assetSha256:
|
|
210925
|
-
contextVersion:
|
|
211152
|
+
assetId: hash8,
|
|
211153
|
+
assetSha256: hash8,
|
|
211154
|
+
contextVersion: hash8,
|
|
210926
211155
|
status: external_exports.enum(["pending", "approved", "changes_requested"]),
|
|
210927
211156
|
approvedAt: text11.nullable(),
|
|
210928
211157
|
approvalKind: external_exports.enum(["human", "agent_recorded"]).nullable(),
|
|
210929
211158
|
staleReasons: external_exports.array(external_exports.object({ kind: external_exports.enum(["context_changed", "style_pin_changed", "shared_style_changed", "project_media_changed", "brand_changed", "project_document_changed", "resource_changed", "review_preferences_changed"]), path: external_exports.string().max(500).optional(), message: text11.optional() }).strict()).max(256).optional(),
|
|
210930
211159
|
superseded: external_exports.boolean().optional(),
|
|
210931
|
-
supersededByRevisionId:
|
|
211160
|
+
supersededByRevisionId: uuid9.nullable().optional(),
|
|
210932
211161
|
supersededAt: text11.nullable().optional(),
|
|
210933
211162
|
needsReview: external_exports.boolean().optional(),
|
|
210934
211163
|
createdAt: text11,
|
|
@@ -210938,15 +211167,15 @@ var review = external_exports.object({
|
|
|
210938
211167
|
pendingFeedbackCount: count
|
|
210939
211168
|
}).strict();
|
|
210940
211169
|
var feedback = external_exports.object({
|
|
210941
|
-
feedbackId:
|
|
211170
|
+
feedbackId: uuid9,
|
|
210942
211171
|
projectId: id3,
|
|
210943
|
-
revisionId:
|
|
211172
|
+
revisionId: uuid9,
|
|
210944
211173
|
text: text11,
|
|
210945
211174
|
target: external_exports.object({ startMs: count.optional(), endMs: count.optional(), segmentId: text11.optional() }).strict(),
|
|
210946
211175
|
reviewerKind: external_exports.enum(["human", "agent_recorded"]),
|
|
210947
211176
|
status: external_exports.literal("pending"),
|
|
210948
211177
|
createdAt: text11,
|
|
210949
|
-
resultRevisionId:
|
|
211178
|
+
resultRevisionId: uuid9.nullable(),
|
|
210950
211179
|
resultNote: text11.nullable(),
|
|
210951
211180
|
preservedElements: text11.nullable(),
|
|
210952
211181
|
resolvedAt: text11.nullable(),
|
|
@@ -210957,15 +211186,16 @@ var progress = external_exports.object({
|
|
|
210957
211186
|
projectId: id3,
|
|
210958
211187
|
stage: external_exports.enum(["to_edit", "editing", "review", "completed"]),
|
|
210959
211188
|
reason: text11,
|
|
210960
|
-
version:
|
|
211189
|
+
version: hash8,
|
|
210961
211190
|
updatedAt: text11.nullable(),
|
|
210962
211191
|
pendingFeedbackCount: count,
|
|
210963
|
-
latestReview: external_exports.object({ revisionId:
|
|
210964
|
-
finalRevisionId:
|
|
211192
|
+
latestReview: external_exports.object({ revisionId: uuid9, assetId: hash8, mimeType: text11, title: text11, available: external_exports.boolean(), stale: external_exports.boolean(), effectiveApproval: external_exports.boolean() }).strict().nullable(),
|
|
211193
|
+
finalRevisionId: uuid9.nullable(),
|
|
211194
|
+
readiness: readiness.optional()
|
|
210965
211195
|
}).strict();
|
|
210966
|
-
var studioJob = external_exports.object({ id:
|
|
211196
|
+
var studioJob = external_exports.object({ id: uuid9, projectId: id3, tool: text11, status: text11, contextVersion: hash8, assetIds: external_exports.array(hash8).max(100), error: text11.nullable(), credits: external_exports.number().nonnegative(), createdAt: text11, updatedAt: text11 }).strict();
|
|
210967
211197
|
var renderJob = external_exports.object({
|
|
210968
|
-
id:
|
|
211198
|
+
id: uuid9,
|
|
210969
211199
|
projectId: id3,
|
|
210970
211200
|
status: text11,
|
|
210971
211201
|
cleanupPending: external_exports.boolean(),
|
|
@@ -210973,28 +211203,28 @@ var renderJob = external_exports.object({
|
|
|
210973
211203
|
creditState: text11,
|
|
210974
211204
|
customerCreditsReserved: external_exports.number().nonnegative(),
|
|
210975
211205
|
customerCreditsCharged: external_exports.number().nonnegative(),
|
|
210976
|
-
output: external_exports.object({ sha256:
|
|
210977
|
-
delivery: external_exports.object({ state: text11, destination: text11, retention: text11, assetId:
|
|
211206
|
+
output: external_exports.object({ sha256: hash8, bytes: count }).strict().nullable(),
|
|
211207
|
+
delivery: external_exports.object({ state: text11, destination: text11, retention: text11, assetId: hash8.nullable(), sha256: hash8.nullable(), bytes: count.nullable(), expiresAt: count.nullable() }).strict().nullable()
|
|
210978
211208
|
}).strict();
|
|
210979
211209
|
var projectContinuitySchema = external_exports.object({
|
|
210980
211210
|
schemaVersion: external_exports.literal(1),
|
|
210981
211211
|
workspaceId: id3,
|
|
210982
211212
|
projectId: id3,
|
|
210983
211213
|
brandId: id3,
|
|
210984
|
-
project: external_exports.object({ revision: count, sha256:
|
|
210985
|
-
checkpoint: section(external_exports.object({ path: text11, revision: count, sha256:
|
|
210986
|
-
context: external_exports.object({ contextVersion:
|
|
211214
|
+
project: external_exports.object({ revision: count, sha256: hash8 }).strict(),
|
|
211215
|
+
checkpoint: section(external_exports.object({ path: text11, revision: count, sha256: hash8 }).strict().nullable()),
|
|
211216
|
+
context: external_exports.object({ contextVersion: hash8, reviewMode: external_exports.enum(["direct", "directions", "sample"]), sourceHashes: external_exports.record(external_exports.string().max(500), hash8) }).strict(),
|
|
210987
211217
|
progress: section(progress),
|
|
210988
211218
|
lastApprovedReview: section(review.nullable()),
|
|
210989
211219
|
reviews: section(page(review, 100)),
|
|
210990
211220
|
feedback: section(page(feedback, 100)),
|
|
210991
|
-
batch: section(external_exports.object({ batchId:
|
|
211221
|
+
batch: section(external_exports.object({ batchId: uuid9, name: text11, status: text11, styleMode: text11, queueState: text11, leaseExpiresAt: text11.nullable(), claimHeldByConnection: external_exports.boolean(), maxConcurrency: count, notice: text11 }).strict().nullable()),
|
|
210992
211222
|
jobs: external_exports.object({
|
|
210993
|
-
studio: section(external_exports.object({ scope: external_exports.literal("current_connection"), items: external_exports.array(studioJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor:
|
|
211223
|
+
studio: section(external_exports.object({ scope: external_exports.literal("current_connection"), items: external_exports.array(studioJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor: uuid9.nullable() }).strict()),
|
|
210994
211224
|
render: section(external_exports.object({ scope: external_exports.literal("current_user"), items: external_exports.array(renderJob).max(30), limit: external_exports.literal(30), complete: external_exports.boolean(), nextCursor: external_exports.null() }).strict())
|
|
210995
211225
|
}).strict(),
|
|
210996
211226
|
storage: section(external_exports.object({ configured: external_exports.boolean(), accountRevision: count, projectRevision: count, effectivePreferences: renderPreferencesSchema, quotaChecked: external_exports.literal(false), spendingAuthorized: external_exports.literal(false) }).strict()),
|
|
210997
|
-
assets: section(external_exports.object({ items: external_exports.array(external_exports.object({ id:
|
|
211227
|
+
assets: section(external_exports.object({ items: external_exports.array(external_exports.object({ id: hash8, sha256: hash8.nullable(), bytes: count.nullable(), mimeType: text11.nullable(), source: external_exports.enum(["project_media", "studio_output", "render_delivery"]), state: external_exports.enum(["catalogued", "unavailable"]) }).strict()).max(100), complete: external_exports.boolean(), limit: external_exports.literal(100), verification: external_exports.literal("catalog_only") }).strict()),
|
|
210998
211228
|
remoteReadOnly: external_exports.literal(true),
|
|
210999
211229
|
downloadedMedia: external_exports.literal(false),
|
|
211000
211230
|
spentCredits: external_exports.literal(0)
|
|
@@ -211003,12 +211233,19 @@ var invalid4 = () => new CliError("INVALID_CONTINUITY_RESPONSE", "Remote continu
|
|
|
211003
211233
|
async function readProjectContinuity(client, expected, options = {}) {
|
|
211004
211234
|
for (const value2 of [expected.projectId, expected.brandId]) assertIdentifier(value2);
|
|
211005
211235
|
if (!expected.workspaceId) throw invalid4();
|
|
211006
|
-
const parsedOptions = external_exports.object({ reviewsAfter:
|
|
211236
|
+
const parsedOptions = external_exports.object({ reviewsAfter: uuid9.optional(), feedbackAfter: uuid9.optional(), studioAfter: uuid9.optional(), includeReviewEvidence: external_exports.literal("1").optional() }).strict().safeParse(options);
|
|
211007
211237
|
if (!parsedOptions.success) throw invalid4();
|
|
211008
211238
|
const params = new URLSearchParams(Object.entries(parsedOptions.data).filter((entry) => entry[1] !== void 0));
|
|
211009
211239
|
let raw;
|
|
211010
211240
|
try {
|
|
211011
|
-
|
|
211241
|
+
const route = `/v1/projects/${encodeURIComponent(expected.projectId)}/continuity`;
|
|
211242
|
+
try {
|
|
211243
|
+
raw = await client.request(`${route}${params.size ? "?" + params.toString() : ""}`);
|
|
211244
|
+
} catch (error62) {
|
|
211245
|
+
if (!(error62 instanceof ApiError) || error62.status !== 400 || error62.body?.error?.code !== "invalid_continuity_cursor" || !params.has("includeReviewEvidence")) throw error62;
|
|
211246
|
+
params.delete("includeReviewEvidence");
|
|
211247
|
+
raw = await client.request(`${route}${params.size ? "?" + params.toString() : ""}`);
|
|
211248
|
+
}
|
|
211012
211249
|
} catch (error62) {
|
|
211013
211250
|
if (!(error62 instanceof ApiError) || error62.status !== 404) throw error62;
|
|
211014
211251
|
const [me, document2] = await Promise.all([client.me(), client.get(`videos/${expected.projectId}/project.json`)]);
|
|
@@ -211027,6 +211264,7 @@ async function readProjectContinuity(client, expected, options = {}) {
|
|
|
211027
211264
|
if (value.workspaceId !== expected.workspaceId || value.projectId !== expected.projectId || value.brandId !== expected.brandId || value.context.sourceHashes[`videos/${expected.projectId}/project.json`] !== value.project.sha256) throw invalid4();
|
|
211028
211265
|
if (value.checkpoint.status === "available" && value.checkpoint.value && value.checkpoint.value.path !== `videos/${expected.projectId}/checkpoint.json`) throw invalid4();
|
|
211029
211266
|
if (value.progress.status === "available" && value.progress.value.projectId !== expected.projectId) throw invalid4();
|
|
211267
|
+
if (value.progress.status === "available" && value.progress.value.readiness && (value.progress.value.readiness.projectId !== expected.projectId || value.progress.value.readiness.contextVersion !== value.context.contextVersion)) throw invalid4();
|
|
211030
211268
|
if (value.lastApprovedReview.status === "available" && value.lastApprovedReview.value && value.lastApprovedReview.value.projectId !== expected.projectId) throw invalid4();
|
|
211031
211269
|
for (const component of [value.reviews, value.feedback]) if (component.status === "available") {
|
|
211032
211270
|
if (component.value.contextVersion !== value.context.contextVersion || component.value.items.some((item) => item.projectId !== expected.projectId) || component.value.complete !== (component.value.nextCursor === null)) throw invalid4();
|
|
@@ -211173,15 +211411,15 @@ async function verifyLocalFile(options) {
|
|
|
211173
211411
|
entry = cached2;
|
|
211174
211412
|
verification = "cached_stat";
|
|
211175
211413
|
} else {
|
|
211176
|
-
const
|
|
211414
|
+
const hash13 = createHash16("sha256");
|
|
211177
211415
|
let bytes = 0n;
|
|
211178
211416
|
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
|
211179
211417
|
bytes += BigInt(chunk.length);
|
|
211180
211418
|
if (bytes > before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", "The artifact changed while hashing.", "Wait for its writer to finish before retrying.");
|
|
211181
|
-
|
|
211419
|
+
hash13.update(chunk);
|
|
211182
211420
|
}
|
|
211183
211421
|
if (bytes !== before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", "The artifact changed while hashing.", "Wait for its writer to finish before retrying.");
|
|
211184
|
-
entry = { scope, path: target, stat: stat2, sha256:
|
|
211422
|
+
entry = { scope, path: target, stat: stat2, sha256: hash13.digest("hex"), hashedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
211185
211423
|
verification = "fresh_sha256";
|
|
211186
211424
|
}
|
|
211187
211425
|
if (!sameProjectIdentity(identity, await getLocalProjectIdentity(identity.root, identity.projectId))) throw new CliError("PROJECT_LINK_STALE", "The project identity changed during verification.", "Verify the current workspace and project before retrying.");
|
|
@@ -211220,12 +211458,12 @@ async function checkpointFileHash(root, path) {
|
|
|
211220
211458
|
try {
|
|
211221
211459
|
const before = await handle.stat();
|
|
211222
211460
|
if (!before.isFile()) throw new CliError("CHECKPOINT_ARTIFACT_INVALID", `Artifact ${path} must be a regular file.`, "Link its directory and select a concrete scene, render or source file.");
|
|
211223
|
-
const
|
|
211461
|
+
const hash13 = createHash17("sha256");
|
|
211224
211462
|
let bytes = 0;
|
|
211225
211463
|
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
|
211226
211464
|
bytes += chunk.length;
|
|
211227
211465
|
if (bytes > before.size) throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", `Artifact ${path} changed while hashing.`, "Wait for the writer/render to finish before saving a checkpoint.");
|
|
211228
|
-
|
|
211466
|
+
hash13.update(chunk);
|
|
211229
211467
|
}
|
|
211230
211468
|
const after = await handle.stat();
|
|
211231
211469
|
await checkedPath(root, path, false);
|
|
@@ -211233,7 +211471,7 @@ async function checkpointFileHash(root, path) {
|
|
|
211233
211471
|
if (!current2.isFile() || bytes !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || before.ino !== current2.ino || before.dev !== current2.dev || current2.mtimeMs !== after.mtimeMs || current2.size !== after.size) {
|
|
211234
211472
|
throw new CliError("CHECKPOINT_ARTIFACT_CHANGED", `Artifact ${path} changed while hashing.`, "Wait for the writer/render to finish before saving a checkpoint.");
|
|
211235
211473
|
}
|
|
211236
|
-
return { sha256:
|
|
211474
|
+
return { sha256: hash13.digest("hex"), bytes };
|
|
211237
211475
|
} finally {
|
|
211238
211476
|
await handle.close();
|
|
211239
211477
|
}
|
|
@@ -211524,12 +211762,13 @@ async function resumeProject(client, projectId, directory, limits = artifactSear
|
|
|
211524
211762
|
const identity = await client.me();
|
|
211525
211763
|
const syncState = await loadSyncState(root, client.url, identity.workspaceId);
|
|
211526
211764
|
const project = JSON.parse(currentFiles[`videos/${projectId}/project.json`]);
|
|
211527
|
-
const remoteContinuity = await readProjectContinuity(client, { workspaceId: identity.workspaceId, projectId, brandId: project.brand });
|
|
211765
|
+
const remoteContinuity = await readProjectContinuity(client, { workspaceId: identity.workspaceId, projectId, brandId: project.brand }, { includeReviewEvidence: "1" });
|
|
211528
211766
|
const remote = remoteContinuity.status === "available" ? remoteContinuity.value : null;
|
|
211529
211767
|
if (remote && (remote.project.sha256 !== syncState.documents[`videos/${projectId}/project.json`]?.sha256 || remote.checkpoint.status === "available" && remote.checkpoint.value?.sha256 !== syncState.documents[path]?.sha256)) {
|
|
211530
211768
|
throw new CliError("CONTINUITY_CHANGED", "The remote project or checkpoint changed after pull.", "Resume again before continuing. Local changes were preserved; nothing was executed.");
|
|
211531
211769
|
}
|
|
211532
211770
|
const remoteContextDifferences = remote ? [.../* @__PURE__ */ new Set([...Object.keys(currentHashes), ...Object.keys(remote.context.sourceHashes)])].filter((path2) => currentHashes[path2] !== remote.context.sourceHashes[path2]) : [];
|
|
211771
|
+
const localSync = await projectLocalSync(client, root, projectId, remote ? { ...remote.context.sourceHashes, ...remote.checkpoint.status === "available" && remote.checkpoint.value ? { [path]: remote.checkpoint.value.sha256 } : {} } : void 0);
|
|
211533
211772
|
const cloudAssets = remote?.assets.status === "available" ? remote.assets.value.items : [];
|
|
211534
211773
|
const renderJobs = remote?.jobs.render.status === "available" ? remote.jobs.render.value.items : [];
|
|
211535
211774
|
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
@@ -211559,6 +211798,8 @@ async function resumeProject(client, projectId, directory, limits = artifactSear
|
|
|
211559
211798
|
remoteContinuity,
|
|
211560
211799
|
artifactAvailability,
|
|
211561
211800
|
remoteContextDifferences,
|
|
211801
|
+
localSync,
|
|
211802
|
+
reviewReadiness: remote?.progress.status === "available" ? remote.progress.value.readiness ?? null : null,
|
|
211562
211803
|
technicalStateNotice: "Cloud catalog metadata is not a downloaded/verified copy; saved render commands never run automatically.",
|
|
211563
211804
|
continuity: checkpoint?.continuity ?? null,
|
|
211564
211805
|
localActivity: links2?.activity ? { ...links2.activity, filesVerifiedByReceipt: false } : null,
|
|
@@ -211847,39 +212088,6 @@ async function generatePresenterMatte(options) {
|
|
|
211847
212088
|
// packages/cli/src/sfx.ts
|
|
211848
212089
|
import { readdir as readdir12, lstat as lstat21 } from "node:fs/promises";
|
|
211849
212090
|
import { join as join16, extname as extname5, basename as basename3 } from "node:path";
|
|
211850
|
-
|
|
211851
|
-
// packages/cli/src/production-context.ts
|
|
211852
|
-
async function prepareProductionContext(root, projectId, client) {
|
|
211853
|
-
const resolved = await resolveProject(await readProjectWorkspace(root, projectId), projectId);
|
|
211854
|
-
const sourceKey = stableJson(await effectiveEditorialSourceHashes(resolved));
|
|
211855
|
-
let contextVersion;
|
|
211856
|
-
const remote = async () => {
|
|
211857
|
-
const result2 = await client.request("/v1/workflow/check", { method: "POST", body: { projectId } });
|
|
211858
|
-
const snapshot = result2.editorialSnapshot;
|
|
211859
|
-
if (!snapshot || snapshot.projectId !== projectId || typeof snapshot.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.contextVersion) || !snapshot.sourceHashes || typeof snapshot.sourceHashes !== "object" || Array.isArray(snapshot.sourceHashes) || Object.values(snapshot.sourceHashes).some((hash11) => typeof hash11 !== "string" || !/^[a-f0-9]{64}$/.test(hash11))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service did not return a versioned editorial context.", "Update the service before connected verification, or explicitly use --offline to check local documents only.");
|
|
211860
|
-
if (snapshot.effectiveSourceHashes !== void 0 && (!snapshot.effectiveSourceHashes || typeof snapshot.effectiveSourceHashes !== "object" || Array.isArray(snapshot.effectiveSourceHashes) || Object.values(snapshot.effectiveSourceHashes).some((hash11) => typeof hash11 !== "string" || !/^[a-f0-9]{64}$/.test(hash11)))) throw new CliError("EDITORIAL_CONTEXT_UNAVAILABLE", "The service returned invalid effective context hashes.", "Retry after updating the service.");
|
|
211861
|
-
const portableHashes = Object.fromEntries(Object.entries(snapshot.effectiveSourceHashes ?? snapshot.sourceHashes).filter(([path]) => path !== "personal-resources:live"));
|
|
211862
|
-
if (stableJson(portableHashes) !== (snapshot.effectiveSourceHashes ? sourceKey : stableJson(resolved.lock.sourceHashes))) throw new CliError("PRODUCTION_CONTEXT_CONFLICT", "Local and web project preferences or material differ.", "Use status and pull --project to inspect/reconcile changes. Do not overwrite either side automatically.");
|
|
211863
|
-
return snapshot.contextVersion;
|
|
211864
|
-
};
|
|
211865
|
-
if (client) contextVersion = await remote();
|
|
211866
|
-
else contextVersion = await sha256(sourceKey);
|
|
211867
|
-
const validateContext = async () => {
|
|
211868
|
-
const localUnchanged = async () => stableJson(await effectiveEditorialSourceHashes(await resolveProject(await readProjectWorkspace(root, projectId), projectId))) === sourceKey;
|
|
211869
|
-
if (!await localUnchanged()) return false;
|
|
211870
|
-
if (!client) return true;
|
|
211871
|
-
try {
|
|
211872
|
-
if (await remote() !== contextVersion) return false;
|
|
211873
|
-
} catch (error62) {
|
|
211874
|
-
if (error62 instanceof CliError && error62.code === "PRODUCTION_CONTEXT_CONFLICT") return false;
|
|
211875
|
-
throw error62;
|
|
211876
|
-
}
|
|
211877
|
-
return localUnchanged();
|
|
211878
|
-
};
|
|
211879
|
-
return { resolved, contextVersion, validateContext, contextScope: client ? "local_and_remote" : "local_only" };
|
|
211880
|
-
}
|
|
211881
|
-
|
|
211882
|
-
// packages/cli/src/sfx.ts
|
|
211883
212091
|
var localPath2 = (id4) => {
|
|
211884
212092
|
sfxBankPath(id4);
|
|
211885
212093
|
return `.editorbrain-local/sfx/${id4}.json`;
|
|
@@ -212005,9 +212213,9 @@ async function prepareStudioAudio(root, file2, out, streamIndex) {
|
|
|
212005
212213
|
const verified = await probeLocalMedia(prepared);
|
|
212006
212214
|
if (verified.durationSeconds === null || verified.durationSeconds > 1800 || verified.bytes > 90 * 1024 * 1024) throw new CliError("AUDIO_DURATION_LIMIT", "The decoded audio exceeds the supported duration.", "Inspect source timestamps; no file was uploaded.");
|
|
212007
212215
|
if ((await probeLocalMedia(source2.path)).sha256 !== source2.sha256) throw new CliError("SOURCE_CHANGED", "The source changed during extraction.", "Retry only after the source is stable.");
|
|
212008
|
-
const bytes = await readFile8(prepared),
|
|
212216
|
+
const bytes = await readFile8(prepared), hash13 = createHash18("sha256").update(bytes).digest("hex");
|
|
212009
212217
|
await link5(prepared, target);
|
|
212010
|
-
return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256:
|
|
212218
|
+
return { kind: "editorbrain.scribe-input", name: "Tempo", path: target, sha256: hash13, bytes: bytes.length, durationMs: Math.round(verified.durationSeconds * 1e3), mimeType: "audio/wav", sourceSha256: source2.sha256, sourcePath: source2.path, audioStream: selected.index, sourceStartTimeSeconds: source2.startTimeSeconds, timestampBasis: "milliseconds_from_container_start", silenceRemoved: false, uploaded: false, next: "Upload this WAV using assets upload, then quote Tempo with its assetId. Keep this source mapping locally; returned word times refer to this prepared audio." };
|
|
212011
212219
|
} finally {
|
|
212012
212220
|
await rm6(temp, { recursive: true, force: true });
|
|
212013
212221
|
}
|
|
@@ -213216,7 +213424,7 @@ async function onboardingStatus(options) {
|
|
|
213216
213424
|
var object15 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
213217
213425
|
var integer2 = (value, min = 0) => Number.isSafeInteger(value) && Number(value) >= min;
|
|
213218
213426
|
var text12 = (value, max) => typeof value === "string" && !!value.trim() && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
|
|
213219
|
-
var
|
|
213427
|
+
var hash9 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
213220
213428
|
var date5 = (value) => text12(value, 64) && Number.isFinite(Date.parse(value));
|
|
213221
213429
|
function invalidInput(message) {
|
|
213222
213430
|
return new CliError("INVALID_ARGUMENT", message, "Use brain status --brand ID; read the current design.md revision before preparing. Acceptance requires the reviewed run and its source revision.");
|
|
@@ -213233,7 +213441,7 @@ function validateInput(input2, accept = false) {
|
|
|
213233
213441
|
if (!object15(input2) || Object.keys(input2).some((key) => !(accept ? ["brandId", "expectedDesignRevision", "runId", "reviewed"] : ["brandId", "expectedDesignRevision"]).includes(key))) throw invalidInput("Only the brand, document revision and explicit reviewed run are accepted.");
|
|
213234
213442
|
brandId(input2.brandId);
|
|
213235
213443
|
if (!integer2(input2.expectedDesignRevision, 1)) throw invalidInput("A positive source design revision is required.");
|
|
213236
|
-
if (accept && (!
|
|
213444
|
+
if (accept && (!hash9(input2.runId) || input2.reviewed !== true)) throw invalidInput("Accept only a specific proposal already reviewed and approved by the user; --run and --reviewed are required.");
|
|
213237
213445
|
}
|
|
213238
213446
|
function invalidResponse(write) {
|
|
213239
213447
|
return new CliError(
|
|
@@ -213245,31 +213453,31 @@ function invalidResponse(write) {
|
|
|
213245
213453
|
);
|
|
213246
213454
|
}
|
|
213247
213455
|
function brainState(value, brand, write = false) {
|
|
213248
|
-
const
|
|
213456
|
+
const invalid14 = () => {
|
|
213249
213457
|
throw invalidResponse(write);
|
|
213250
213458
|
};
|
|
213251
|
-
if (!object15(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text12(value.notice, 2e3) || value.contextVersion !== void 0 && !
|
|
213459
|
+
if (!object15(value) || value.brandId !== brand || typeof value.available !== "boolean" || typeof value.configured !== "boolean" || !text12(value.notice, 2e3) || value.contextVersion !== void 0 && !hash9(value.contextVersion) || value.contextChanged !== void 0 && typeof value.contextChanged !== "boolean") return invalid14();
|
|
213252
213460
|
let run2 = null;
|
|
213253
213461
|
if (value.run !== null) {
|
|
213254
213462
|
const row = value.run;
|
|
213255
|
-
if (!object15(row) || !
|
|
213256
|
-
if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return
|
|
213463
|
+
if (!object15(row) || !hash9(row.id) || !["queued", "running", "ready", "accepted", "failed"].includes(String(row.status)) || !integer2(row.sourceDesignRevision, 1) || !(row.acceptedDesignRevision === null || integer2(row.acceptedDesignRevision, 1)) || !(row.errorCode === null || typeof row.errorCode === "string" && /^[a-z][a-z0-9_]{0,119}$/.test(row.errorCode)) || !date5(row.createdAt) || !date5(row.updatedAt)) return invalid14();
|
|
213464
|
+
if (row.status === "accepted" ? row.acceptedDesignRevision !== row.sourceDesignRevision + 1 : row.acceptedDesignRevision !== null) return invalid14();
|
|
213257
213465
|
let proposal = null;
|
|
213258
213466
|
if (row.proposal !== null) {
|
|
213259
213467
|
const proposed = row.proposal;
|
|
213260
|
-
if (!object15(proposed) || !text12(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return
|
|
213468
|
+
if (!object15(proposed) || !text12(proposed.summary, 700) || !Array.isArray(proposed.recommendations) || proposed.recommendations.length < 1 || proposed.recommendations.length > 5) return invalid14();
|
|
213261
213469
|
const recommendations = [];
|
|
213262
213470
|
for (const item of proposed.recommendations) {
|
|
213263
|
-
if (!object15(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text12(item.text, 500) || !text12(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text12(field, 400))) return
|
|
213471
|
+
if (!object15(item) || !["images", "motion", "story", "audio"].includes(String(item.area)) || !text12(item.text, 500) || !text12(item.reason, 500) || !Array.isArray(item.sourceFields) || item.sourceFields.length < 1 || item.sourceFields.length > 5 || new Set(item.sourceFields).size !== item.sourceFields.length || item.sourceFields.some((field) => !text12(field, 400))) return invalid14();
|
|
213264
213472
|
recommendations.push({ area: item.area, text: item.text, reason: item.reason, sourceFields: [...item.sourceFields] });
|
|
213265
213473
|
}
|
|
213266
213474
|
proposal = { summary: proposed.summary, recommendations };
|
|
213267
213475
|
}
|
|
213268
|
-
if ((row.status === "ready" || row.status === "accepted") && !proposal) return
|
|
213476
|
+
if ((row.status === "ready" || row.status === "accepted") && !proposal) return invalid14();
|
|
213269
213477
|
let usage = null;
|
|
213270
213478
|
if (row.usage !== null) {
|
|
213271
213479
|
const measured = row.usage;
|
|
213272
|
-
if (!object15(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return
|
|
213480
|
+
if (!object15(measured) || !["inputTokens", "outputTokens", "totalTokens"].every((field) => measured[field] === null || integer2(measured[field])) || typeof measured.durationMs !== "number" || !Number.isFinite(measured.durationMs) || measured.durationMs < 0) return invalid14();
|
|
213273
213481
|
usage = { inputTokens: measured.inputTokens, outputTokens: measured.outputTokens, totalTokens: measured.totalTokens, durationMs: measured.durationMs };
|
|
213274
213482
|
}
|
|
213275
213483
|
run2 = { id: row.id, status: row.status, proposal, usage, errorCode: row.errorCode, sourceDesignRevision: row.sourceDesignRevision, acceptedDesignRevision: row.acceptedDesignRevision, createdAt: row.createdAt, updatedAt: row.updatedAt };
|
|
@@ -213491,7 +213699,7 @@ async function loginWithDevice(options, overrides = {}) {
|
|
|
213491
213699
|
import { chmod as chmod4, lstat as lstat26, mkdir as mkdir20, open as open23 } from "node:fs/promises";
|
|
213492
213700
|
import { constants as constants18 } from "node:fs";
|
|
213493
213701
|
import { homedir as homedir4 } from "node:os";
|
|
213494
|
-
import { basename as
|
|
213702
|
+
import { basename as basename9, dirname as dirname25, extname as extname11, join as join24, resolve as resolve19 } from "node:path";
|
|
213495
213703
|
|
|
213496
213704
|
// packages/cli/src/direction-context.ts
|
|
213497
213705
|
async function prepareDirectionContext(root, client, projectId) {
|
|
@@ -213557,8 +213765,8 @@ function parseAudioMeasurements(stderr, streamIndices, target) {
|
|
|
213557
213765
|
blocks.set(index, [...blocks.get(index) ?? [], block]);
|
|
213558
213766
|
}
|
|
213559
213767
|
return streamIndices.map((streamIndex) => {
|
|
213560
|
-
const
|
|
213561
|
-
const block =
|
|
213768
|
+
const matches2 = blocks.get(streamIndex);
|
|
213769
|
+
const block = matches2?.length === 1 ? matches2[0] : {};
|
|
213562
213770
|
const integrated = measurement(block.input_i), peak = measurement(block.input_tp), range2 = measurement(block.input_lra);
|
|
213563
213771
|
const known = integrated.state === "finite" && peak.state === "finite" && range2.state === "finite" && range2.value >= 0;
|
|
213564
213772
|
const targetStatus = !known ? "incomplete" : !target ? "not_evaluated" : Math.abs(integrated.value - target.targetIntegratedLufs) <= target.toleranceLu + 1e-9 && peak.value <= target.maxTruePeakDbtp + 1e-9 ? "pass" : "fail";
|
|
@@ -213693,8 +213901,8 @@ function safeUrl(value, hosts) {
|
|
|
213693
213901
|
function failure3(code, message) {
|
|
213694
213902
|
return new CliError(code, message, "Use public search terms and supported providers. Retry provider failures later; verify item rights on the source page.", false);
|
|
213695
213903
|
}
|
|
213696
|
-
function classifyMediaSourceLicense(
|
|
213697
|
-
const evidence = Object.entries(
|
|
213904
|
+
function classifyMediaSourceLicense(fields3) {
|
|
213905
|
+
const evidence = Object.entries(fields3).flatMap(([field, value]) => texts3(value).map((value2) => ({ field, value: value2 }))).slice(0, 16);
|
|
213698
213906
|
const recognized = /* @__PURE__ */ new Set();
|
|
213699
213907
|
let unsupported = false, url3 = null;
|
|
213700
213908
|
for (const entry of evidence) {
|
|
@@ -213809,11 +214017,11 @@ function requiredRecord(value) {
|
|
|
213809
214017
|
return value;
|
|
213810
214018
|
}
|
|
213811
214019
|
function result(provider, id4, title, sourceUrl, metadataUrl, retrieved) {
|
|
213812
|
-
const
|
|
213813
|
-
if (!
|
|
214020
|
+
const identifier12 = plain(id4, 512), name = plain(title), page2 = safeUrl(sourceUrl, HOSTS[provider]);
|
|
214021
|
+
if (!identifier12 || !name || !page2) return null;
|
|
213814
214022
|
return {
|
|
213815
214023
|
provider,
|
|
213816
|
-
id:
|
|
214024
|
+
id: identifier12,
|
|
213817
214025
|
title: name,
|
|
213818
214026
|
sourceUrl: page2,
|
|
213819
214027
|
metadataUrl,
|
|
@@ -213828,7 +214036,7 @@ function result(provider, id4, title, sourceUrl, metadataUrl, retrieved) {
|
|
|
213828
214036
|
previewVerified: false
|
|
213829
214037
|
};
|
|
213830
214038
|
}
|
|
213831
|
-
var
|
|
214039
|
+
var identifier11 = (value) => typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,199}$/.test(value) ? value : null;
|
|
213832
214040
|
async function searchProvider(provider, query, limit, client, report) {
|
|
213833
214041
|
const output3 = [];
|
|
213834
214042
|
const add = (item) => {
|
|
@@ -213862,7 +214070,7 @@ async function searchProvider(provider, query, limit, client, report) {
|
|
|
213862
214070
|
const url3 = endpoint("https://images-api.nasa.gov/search", { q: query, media_type: "image", page: "1", page_size: String(limit) });
|
|
213863
214071
|
const data = await client.get(url3);
|
|
213864
214072
|
for (const value of requiredList(record14(data.collection).items).slice(0, limit)) {
|
|
213865
|
-
const entry = record14(value), metadata = record14(array3(entry.data)[0]), id4 =
|
|
214073
|
+
const entry = record14(value), metadata = record14(array3(entry.data)[0]), id4 = identifier11(metadata.nasa_id);
|
|
213866
214074
|
const item = result(provider, id4, metadata.title, id4 ? `https://images.nasa.gov/details/${encodeURIComponent(id4)}` : null, url3.href, retrieved);
|
|
213867
214075
|
if (item) {
|
|
213868
214076
|
item.author = firstText(metadata.photographer, metadata.secondary_creator);
|
|
@@ -213909,7 +214117,7 @@ async function searchProvider(provider, query, limit, client, report) {
|
|
|
213909
214117
|
url3.searchParams.append("fl[]", "title");
|
|
213910
214118
|
const data = await client.get(url3);
|
|
213911
214119
|
for (const value of requiredList(record14(data.response).docs).slice(0, limit)) {
|
|
213912
|
-
const summary2 = record14(value), id4 =
|
|
214120
|
+
const summary2 = record14(value), id4 = identifier11(summary2.identifier);
|
|
213913
214121
|
if (!id4) {
|
|
213914
214122
|
add(null);
|
|
213915
214123
|
continue;
|
|
@@ -217023,9 +217231,94 @@ async function verifyProduction(options) {
|
|
|
217023
217231
|
return { report, summary: { ...summarizeProductionVerification(report), reportPath, reportSha256 }, reportPath, reportSha256 };
|
|
217024
217232
|
}
|
|
217025
217233
|
|
|
217234
|
+
// packages/cli/src/production-present.ts
|
|
217235
|
+
import { basename as basename5, extname as extname8 } from "node:path";
|
|
217236
|
+
var invalid9 = (message) => new CliError("INVALID_PRESENTATION_EVIDENCE", message, "Read production present --help. Record only an artifact actually shared with the user; generation, upload and opening a server are not presentation or approval.");
|
|
217237
|
+
var hash10 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
217238
|
+
async function presentProduction(client, root, projectId, value) {
|
|
217239
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid9("Evidence must be a JSON object.");
|
|
217240
|
+
const { expectedVersion, ...input2 } = value;
|
|
217241
|
+
if (!hash10(expectedVersion)) throw invalid9("expectedVersion must be the version returned by GET /v1/projects/ID/review-evidence.");
|
|
217242
|
+
if (input2.projectId !== void 0 && input2.projectId !== projectId) throw invalid9("The evidence belongs to a different project.");
|
|
217243
|
+
let evidence;
|
|
217244
|
+
try {
|
|
217245
|
+
evidence = parseReviewEvidence({ ...input2, projectId });
|
|
217246
|
+
} catch (error62) {
|
|
217247
|
+
throw invalid9(error62.message);
|
|
217248
|
+
}
|
|
217249
|
+
if (evidence.source.kind === "local") {
|
|
217250
|
+
const source2 = evidence.source;
|
|
217251
|
+
if (extname8(source2.relativePath).toLowerCase() !== ".html") throw invalid9("Local presentation requires a generated review HTML and its identity sidecar. Cloud media uses its existing review revision.");
|
|
217252
|
+
const verified = await checkpointFileHash(root, source2.relativePath);
|
|
217253
|
+
if (!verified.bytes || verified.sha256 !== source2.sha256) throw invalid9("The local artifact bytes do not match source.sha256. Preserve the old evidence and create a new version for changed media.");
|
|
217254
|
+
let sidecar;
|
|
217255
|
+
try {
|
|
217256
|
+
sidecar = JSON.parse((await readReviewFile(await checkedPath(root, `${source2.relativePath}.review.json`, false), 64 * 1024)).toString());
|
|
217257
|
+
} catch (error62) {
|
|
217258
|
+
if (error62.code !== "ENOENT") throw error62;
|
|
217259
|
+
}
|
|
217260
|
+
if (!sidecar) throw invalid9("This HTML lacks its review identity sidecar. Generate a new version with production review-artifact; preserve the existing file.");
|
|
217261
|
+
{
|
|
217262
|
+
if (sidecar.kind !== "editorbrain.local-review" || sidecar.artifactId !== source2.artifactId || sidecar.html?.sha256 !== source2.sha256 || sidecar.html?.file !== source2.relativePath) throw invalid9("The local review sidecar does not match this exact artifact.");
|
|
217263
|
+
const html = await readReviewFile(await checkedPath(root, source2.relativePath, false), 2 * 1024 * 1024);
|
|
217264
|
+
if (await sha256(html.toString()) !== source2.sha256) throw invalid9("The artifact changed during presentation verification.");
|
|
217265
|
+
const matches2 = [...html.toString().matchAll(/<script id="review-data" type="application\/json">([\s\S]*?)<\/script>/g)];
|
|
217266
|
+
if (matches2.length !== 1) throw invalid9("This is not an identifiable EditorBrain review artifact.");
|
|
217267
|
+
let data;
|
|
217268
|
+
try {
|
|
217269
|
+
data = JSON.parse(matches2[0][1]);
|
|
217270
|
+
} catch {
|
|
217271
|
+
throw invalid9("The artifact identity JSON is invalid.");
|
|
217272
|
+
}
|
|
217273
|
+
const { artifactId: embeddedId, ...clean } = data;
|
|
217274
|
+
if (embeddedId !== source2.artifactId || await sha256(JSON.stringify(clean)) !== source2.artifactId || data.projectId !== projectId || data.contextVersion !== evidence.contextVersion || data.stage !== evidence.phase) throw invalid9("The immutable artifact belongs to a different project, context or phase, or lacks that identity.");
|
|
217275
|
+
for (const key of ["projectId", "contextVersion", "stage"]) if (sidecar[key] !== void 0 && sidecar[key] !== data[key]) throw invalid9("The sidecar identity conflicts with the immutable artifact.");
|
|
217276
|
+
if (!Array.isArray(sidecar.media) || !sidecar.media.length || sidecar.media.length > 3) throw invalid9("The local review must include verified visual media; text-only proposals are not visual evidence.");
|
|
217277
|
+
if (evidence.phase === "directions") {
|
|
217278
|
+
if (!Array.isArray(data.directions) || !data.directions.length || data.directions.some((direction) => !hash10(direction?.preview?.sha256) || !sidecar.media.some((entry) => entry.sha256 === direction.preview.sha256 && entry.uri === direction.preview.uri))) throw invalid9("Every proposed direction needs its own verified visual preview.");
|
|
217279
|
+
if (evidence.decision && "directionId" in evidence.decision && !data.directions.some((direction) => direction.id === evidence.decision.directionId)) throw invalid9("The selected direction does not exist in this artifact.");
|
|
217280
|
+
} else if (!hash10(data.video?.sha256) || !sidecar.media.some((entry) => entry.sha256 === data.video.sha256 && entry.uri === data.video.uri && ["video/mp4", "video/webm"].includes(entry.mimeType))) {
|
|
217281
|
+
throw invalid9("A review or delivery requires its exact video medium.");
|
|
217282
|
+
}
|
|
217283
|
+
for (const entry of sidecar.media) {
|
|
217284
|
+
if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${source2.relativePath}.media-`) || !hash10(entry.sha256)) throw invalid9("The local review contains an invalid media reference.");
|
|
217285
|
+
const match = /^([a-f0-9-]{36})\/([a-f0-9]{64})\.(mp4|webm|png|jpg|jpeg|webp)$/.exec(entry.file.slice(`${source2.relativePath}.media-`.length));
|
|
217286
|
+
const mime2 = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
|
|
217287
|
+
if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]] || entry.uri !== `${encodeURIComponent(basename5(source2.relativePath) + ".media-" + match[1])}/${match[2]}.${match[3]}`) throw invalid9("The review URI does not name the verified local medium. Preserve the original HTML and media mapping.");
|
|
217288
|
+
const media3 = await checkpointFileHash(root, entry.file);
|
|
217289
|
+
if (media3.sha256 !== entry.sha256 || media3.bytes !== entry.bytes) throw invalid9("A local review medium changed or is missing. Present a new verified artifact.");
|
|
217290
|
+
}
|
|
217291
|
+
}
|
|
217292
|
+
}
|
|
217293
|
+
const { localSync, contextVersion } = await currentProjectLocalSync(client, root, projectId);
|
|
217294
|
+
if (localSync.contextPending.length) throw new CliError("PRESENTATION_CONTEXT_UNSYNCED", "This folder has project or shared-context edits whose synchronization is not confirmed.", "Inspect the localSync paths and scoped dry-run, reconcile deliberately, then prepare/present the artifact for the current context. No documents or media were uploaded.", false, { localSync });
|
|
217295
|
+
if (contextVersion !== null && contextVersion !== evidence.contextVersion) throw new CliError("PRESENTATION_CONTEXT_UNSYNCED", "The presentation belongs to a different editorial context than the current project.", "Read current evidence and reconcile the exact artifact context. Use production present --project ID --id EVIDENCE_ID to inspect an existing historical receipt without transferring its approval.", false, { localSync, contextVersion });
|
|
217296
|
+
const { projectId: _projectId, ...body } = evidence;
|
|
217297
|
+
const response = await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence`, { method: "POST", body: { ...body, expectedVersion } });
|
|
217298
|
+
const receipt = response.receipt?.evidence ?? (Array.isArray(response.evidence) ? response.evidence.find((fact) => fact?.evidence?.evidenceId === evidence.evidenceId)?.evidence : void 0);
|
|
217299
|
+
let exact = false;
|
|
217300
|
+
try {
|
|
217301
|
+
exact = JSON.stringify(parseReviewEvidence(receipt)) === JSON.stringify(evidence);
|
|
217302
|
+
} catch {
|
|
217303
|
+
}
|
|
217304
|
+
if (response.projectId !== projectId || !hash10(response.contextVersion) || !hash10(response.version) || !exact) throw new CliError("PRESENTATION_OUTCOME_UNKNOWN", "The presentation receipt could not be verified.", "Read production present --project ID --id EVIDENCE_ID before retrying. Never create another ID to conceal an uncertain write.", false, { evidenceId: evidence.evidenceId, outcome: "unknown" });
|
|
217305
|
+
return { ...response, localSync, rendered: false, uploaded: false, spentCredits: 0 };
|
|
217306
|
+
}
|
|
217307
|
+
async function readPresentationInput(root, file2) {
|
|
217308
|
+
return JSON.parse((await readReviewFile(await checkedPath(root, file2, false), 64 * 1024)).toString());
|
|
217309
|
+
}
|
|
217310
|
+
async function withdrawPresentation(client, projectId, evidenceId, expectedVersion, userConfirmed) {
|
|
217311
|
+
if (!/^[a-zA-Z0-9_-]{1,80}$/.test(projectId) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(evidenceId) || !hash10(expectedVersion)) throw invalid9("Use a project ID, evidence UUID and current expectedVersion from production present.");
|
|
217312
|
+
if (!userConfirmed) throw new CliError("USER_CONFIRMATION_REQUIRED", "Withdrawing review evidence requires the user\u2019s explicit instruction.", "Use --user-confirmed only after the user withdraws that exact local decision/presentation. Existing history and files are preserved.");
|
|
217313
|
+
const response = await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence/${evidenceId}`, { method: "DELETE", body: { expectedVersion } });
|
|
217314
|
+
const receipt = response.receipt ?? (Array.isArray(response.evidence) ? response.evidence.find((fact) => fact?.evidence?.evidenceId === evidenceId) : void 0);
|
|
217315
|
+
if (response.projectId !== projectId || !hash10(response.version) || receipt?.evidence?.evidenceId !== evidenceId || receipt.invalidated !== "revoked") throw new CliError("PRESENTATION_OUTCOME_UNKNOWN", "The withdrawal receipt could not be verified.", "Read production present --project ID --id EVIDENCE_ID before retrying. Preserve this evidenceId and existing files.", false, { evidenceId, outcome: "unknown" });
|
|
217316
|
+
return response;
|
|
217317
|
+
}
|
|
217318
|
+
|
|
217026
217319
|
// packages/cli/src/review-artifact.ts
|
|
217027
217320
|
import { lstat as lstat25, mkdir as mkdir18, link as link7, unlink as unlink14 } from "node:fs/promises";
|
|
217028
|
-
import { basename as
|
|
217321
|
+
import { basename as basename6, dirname as dirname24, extname as extname9, resolve as resolve18 } from "node:path";
|
|
217029
217322
|
import { createHash as createHash25, randomUUID as randomUUID10 } from "node:crypto";
|
|
217030
217323
|
|
|
217031
217324
|
// packages/cli/src/review-artifact-html.ts
|
|
@@ -217367,9 +217660,9 @@ ${JSON.stringify({ ...feedback2(), kind: "editorbrain.review-access-request", de
|
|
|
217367
217660
|
update();
|
|
217368
217661
|
}
|
|
217369
217662
|
function renderReviewArtifact(data, wordmark) {
|
|
217370
|
-
const script = `(${reviewApp.toString()})();`,
|
|
217663
|
+
const script = `(${reviewApp.toString()})();`, hash13 = createHash24("sha256").update(script).digest("base64");
|
|
217371
217664
|
const json2 = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
217372
|
-
return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${
|
|
217665
|
+
return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash13}'; style-src 'unsafe-inline'; img-src 'self' data:; media-src 'self' data: blob:; connect-src 'none'; font-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>EditorBrain \xB7 Tu edici\xF3n</title><style>
|
|
217373
217666
|
*{box-sizing:border-box} [hidden]{display:none!important} :root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:#f6f6f6;background:#090909}body{margin:0;background:radial-gradient(ellipse at 15% 0%,#252525 0,transparent 50%),#090909}main{max-width:1220px;margin:auto;padding:28px clamp(18px,4vw,50px) 44px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #ffffff20;padding-bottom:22px;gap:20px}header svg{width:146px;height:auto;display:block}header span{color:#aaa;font-size:12px}h1{font-size:clamp(28px,4vw,48px);font-weight:550;letter-spacing:-.045em;margin:14px 0}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 12px}.eyebrow{font-size:10px;letter-spacing:.18em;color:#aaa;margin:30px 0 0}.intro{color:#aaa;font-size:15px;line-height:1.6;margin-bottom:24px}button,a{touch-action:manipulation}button{border:1px solid #ffffff30;border-radius:12px;background:#ffffff08;color:#fff;padding:11px 15px;font:inherit;font-size:13px;cursor:pointer}button:hover{background:#ffffff16}button:disabled{opacity:.38;cursor:default}.primary{background:#f5f5f5;color:#111;font-weight:650;border-color:#fff}.primary:hover{background:#ddd}.secondary{background:transparent}button:focus-visible,textarea:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid #fff;outline-offset:4px}p{line-height:1.6}.workspace{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(280px,1fr);gap:30px;align-items:start}.preview{position:sticky;top:20px;min-width:0}.screen{border:1px solid #ffffff22;border-radius:20px;overflow:hidden;background:radial-gradient(ellipse,#242424,#050505);display:flex;justify-content:center;min-height:260px}.screen video{width:100%;max-height:590px;display:block}.controls{display:flex;justify-content:center;align-items:center;gap:16px;margin:12px 0;font-size:12px;color:#aaa;font-variant-numeric:tabular-nums}.controls button{padding:8px 12px}aside{background:linear-gradient(140deg,#ffffff07,#ffffff02);border:1px solid #ffffff19;border-radius:20px;padding:24px}aside>p{color:#aaa;font-size:13px}label{display:block;font-size:12px;color:#bbb}select{max-width:100%;padding:10px;background:#181818;color:#fff;border:1px solid #ffffff40;border-radius:8px}#learning-options article{padding:16px 0;border-top:1px solid #ffffff20}textarea{width:100%;background:#090909;border:1px solid #ffffff30;border-radius:12px;padding:14px;color:#fff;font:inherit;font-size:14px;line-height:1.5;min-height:108px;resize:vertical;margin:12px 0}textarea::placeholder{color:#818181}.target{display:flex;align-items:center;gap:10px;margin:16px 0 0;font-size:12px;color:#bbb;flex-wrap:wrap}.target button{padding:6px 10px}.save{width:100%;margin-bottom:16px}.muted{color:#aaa;font-size:12px}details{border-top:1px solid #ffffff20;padding-top:16px;margin-top:16px}summary{cursor:pointer;font-size:13px;line-height:1.6}#phrases{max-height:300px;overflow-y:auto;margin:12px 0}#phrases article{padding:12px;margin-bottom:8px;border-radius:10px;background:#ffffff04;border-left:2px solid transparent}#phrases .speaking{background:#ffffff12;border-left-color:#fff}#phrases article>button:first-child{border:0;background:none;text-align:left;padding:0;line-height:1.7;width:100%;margin-bottom:8px}#phrases article>button:last-child{font-size:11px;padding:6px 8px}#phrases .removed{opacity:.7}#show-cuts-label{margin:12px 0}#approve{width:100%;margin-top:18px}#pending{padding:12px 16px;border-left:2px solid #eee;background:#ffffff08;font-size:13px;margin-bottom:20px}#notes{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px}#notes article{border:1px solid #ffffff22;border-radius:12px;padding:15px;font-size:13px;overflow-wrap:anywhere}#notes p{margin-bottom:0}.note-head{display:flex;align-items:center;justify-content:space-between;gap:10px}.note-head button{font-size:11px;padding:5px 8px}#markers{display:flex;gap:8px;flex-wrap:wrap}#markers button{font-size:11px;padding:7px 10px}.handoff{margin-top:24px;padding:22px;border:1px solid #ffffff30;border-radius:18px;background:#ffffff05}.handoff-head{display:flex;align-items:center;justify-content:space-between;gap:20px}.handoff p{color:#aaa;font-size:13px;margin:6px 0}.handoff .actions{display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}#status{color:#fff;margin:14px 0;font-size:13px}#request{font-family:ui-monospace,monospace;font-size:12px;min-height:200px}footer{margin-top:22px;display:flex;justify-content:space-between;gap:16px;color:#888;font-size:11px}#direction-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,250px),1fr));gap:18px}.direction{padding:16px;border:1px solid #ffffff22;border-radius:18px;background:#ffffff05}.direction.chosen{border-color:#fff;box-shadow:0 0 0 1px #fff}.direction img,.direction video{width:100%;height:220px;object-fit:contain;border-radius:10px;background:#030303;margin-bottom:18px}.direction p{color:#bbb;font-size:14px}.direction button{width:100%}.direction details a{display:block;color:#fff;font-size:12px;margin:8px 0}.no-preview{height:160px;display:grid;place-items:center;background:#222;color:#aaa;margin-bottom:16px;border-radius:10px}#future{background:none;border:0;color:#aaa;padding:0;font-size:12px;text-align:left}#future-details{color:#aaa;font-size:13px}#future-details summary{color:#eee}.future-note{max-width:660px}#undo{margin-top:12px}input[type=checkbox]{accent-color:#fff}#intro{max-width:680px}
|
|
217374
217667
|
@media(max-width:760px){main{padding-top:20px}.workspace{grid-template-columns:1fr;gap:18px}.preview{position:static}.screen video{max-height:52svh}.screen{min-height:180px}aside{padding:20px}.handoff-head{display:block}.actions{margin-top:14px}.actions button{flex:1}.handoff{padding:18px}h1{font-size:32px}#direction-grid{grid-template-columns:1fr}header svg{width:125px}footer{flex-direction:column}#phrases{max-height:260px}}
|
|
217375
217668
|
@media(prefers-reduced-motion:no-preference){button,.direction{transition:background .15s,border-color .15s}}
|
|
@@ -217377,106 +217670,106 @@ function renderReviewArtifact(data, wordmark) {
|
|
|
217377
217670
|
}
|
|
217378
217671
|
|
|
217379
217672
|
// packages/cli/src/review-artifact.ts
|
|
217380
|
-
var
|
|
217673
|
+
var invalid10 = (message) => {
|
|
217381
217674
|
throw new CliError("INVALID_REVIEW_ARTIFACT", message, "See references/production-continuity.md. Use a new .editorbrain-local/.../review.html output for each version.");
|
|
217382
217675
|
};
|
|
217383
217676
|
var object19 = (v, keys4) => {
|
|
217384
|
-
if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys4.includes(k)))
|
|
217677
|
+
if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some((k) => !keys4.includes(k))) invalid10("Unexpected artifact fields.");
|
|
217385
217678
|
return v;
|
|
217386
217679
|
};
|
|
217387
217680
|
function text13(v, max) {
|
|
217388
|
-
if (typeof v !== "string" || !v.trim() || v.length > max)
|
|
217681
|
+
if (typeof v !== "string" || !v.trim() || v.length > max) invalid10("Missing or oversized artifact text.");
|
|
217389
217682
|
return v.trim();
|
|
217390
217683
|
}
|
|
217391
217684
|
function media2(v) {
|
|
217392
217685
|
const m = object19(v, ["file", "sha256", "purpose", "quality"]);
|
|
217393
217686
|
const file2 = text13(m.file, 4096);
|
|
217394
|
-
if (/^[a-z]+:\/\//i.test(file2))
|
|
217395
|
-
if (m.sha256 !== void 0 && (typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256)))
|
|
217396
|
-
if (m.purpose !== void 0 && !["preview", "final"].includes(m.purpose))
|
|
217397
|
-
if (m.quality !== void 0 && (m.purpose !== "preview" || ![480, 720].includes(m.quality)))
|
|
217687
|
+
if (/^[a-z]+:\/\//i.test(file2)) invalid10("Use a local media file, never a remote or signed URL.");
|
|
217688
|
+
if (m.sha256 !== void 0 && (typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256))) invalid10("Invalid media hash.");
|
|
217689
|
+
if (m.purpose !== void 0 && !["preview", "final"].includes(m.purpose)) invalid10("Media purpose must be preview or final.");
|
|
217690
|
+
if (m.quality !== void 0 && (m.purpose !== "preview" || ![480, 720].includes(m.quality))) invalid10("Preview quality must be 480 or 720 with purpose preview.");
|
|
217398
217691
|
return { file: file2, ...m.sha256 ? { sha256: m.sha256 } : {}, ...m.purpose ? { purpose: m.purpose } : {}, ...m.quality ? { quality: m.quality } : {} };
|
|
217399
217692
|
}
|
|
217400
217693
|
function parseReviewArtifact(value) {
|
|
217401
217694
|
const r = object19(value, ["schemaVersion", "projectId", "title", "version", "stage", "video", "transcript", "directions", "contextVersion", "learnings", "learningContext"]);
|
|
217402
|
-
if (r.schemaVersion !== 1 || !["directions", "review", "delivery"].includes(r.stage))
|
|
217695
|
+
if (r.schemaVersion !== 1 || !["directions", "review", "delivery"].includes(r.stage)) invalid10("Use schemaVersion 1 and stage directions, review or delivery.");
|
|
217403
217696
|
const projectId = text13(r.projectId, 80);
|
|
217404
217697
|
assertIdentifier(projectId);
|
|
217405
217698
|
const result2 = { schemaVersion: 1, projectId, title: text13(r.title, 120), version: text13(r.version, 80), stage: r.stage };
|
|
217406
217699
|
if (r.contextVersion !== void 0) {
|
|
217407
|
-
if (typeof r.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(r.contextVersion))
|
|
217700
|
+
if (typeof r.contextVersion !== "string" || !/^[a-f0-9]{64}$/.test(r.contextVersion)) invalid10("Use the exact editorial context hash.");
|
|
217408
217701
|
result2.contextVersion = r.contextVersion;
|
|
217409
217702
|
}
|
|
217410
217703
|
if (r.learnings !== void 0) {
|
|
217411
217704
|
try {
|
|
217412
217705
|
result2.learnings = parseReviewLearnings(r.learnings, projectId);
|
|
217413
217706
|
} catch (e) {
|
|
217414
|
-
|
|
217707
|
+
invalid10(e.message);
|
|
217415
217708
|
}
|
|
217416
217709
|
}
|
|
217417
217710
|
if (r.learningContext !== void 0) {
|
|
217418
217711
|
const c = object19(r.learningContext, ["brandId", "styleId", "formatId", "seriesId"]);
|
|
217419
217712
|
assertIdentifier(text13(c.brandId, 80));
|
|
217420
217713
|
assertIdentifier(text13(c.styleId, 80));
|
|
217421
|
-
if (memoryContextIssues({ ...c.formatId !== void 0 ? { formatId: c.formatId } : {}, ...c.seriesId !== void 0 ? { seriesId: c.seriesId } : {} }).length)
|
|
217714
|
+
if (memoryContextIssues({ ...c.formatId !== void 0 ? { formatId: c.formatId } : {}, ...c.seriesId !== void 0 ? { seriesId: c.seriesId } : {} }).length) invalid10("Invalid learning format or series.");
|
|
217422
217715
|
result2.learningContext = c;
|
|
217423
217716
|
}
|
|
217424
|
-
if (result2.learnings?.length && (!result2.learningContext || r.stage === "directions"))
|
|
217717
|
+
if (result2.learnings?.length && (!result2.learningContext || r.stage === "directions")) invalid10("Learning proposals need the selected context and a review/delivery.");
|
|
217425
217718
|
if (r.video !== void 0) result2.video = media2(r.video);
|
|
217426
|
-
if (result2.stage === "delivery" && result2.video?.purpose === "preview")
|
|
217719
|
+
if (result2.stage === "delivery" && result2.video?.purpose === "preview") invalid10("A preview cannot be the final delivery. Render the approved edit from originals at the final output profile first.");
|
|
217427
217720
|
if (r.transcript !== void 0) {
|
|
217428
217721
|
try {
|
|
217429
217722
|
result2.transcript = parseReviewTranscript(r.transcript);
|
|
217430
217723
|
} catch (e) {
|
|
217431
|
-
|
|
217724
|
+
invalid10(e.message);
|
|
217432
217725
|
}
|
|
217433
217726
|
}
|
|
217434
217727
|
if (r.directions !== void 0) {
|
|
217435
|
-
if (!Array.isArray(r.directions) || r.directions.length < 1 || r.directions.length > 3)
|
|
217728
|
+
if (!Array.isArray(r.directions) || r.directions.length < 1 || r.directions.length > 3) invalid10("Use one to three visual directions.");
|
|
217436
217729
|
const ids2 = /* @__PURE__ */ new Set();
|
|
217437
217730
|
result2.directions = r.directions.map((v) => {
|
|
217438
217731
|
const d = object19(v, ["id", "title", "description", "preview", "references"]), id4 = text13(d.id, 80);
|
|
217439
217732
|
assertIdentifier(id4);
|
|
217440
|
-
if (ids2.has(id4))
|
|
217733
|
+
if (ids2.has(id4)) invalid10("Direction IDs must be unique.");
|
|
217441
217734
|
ids2.add(id4);
|
|
217442
217735
|
let references;
|
|
217443
217736
|
if (d.references !== void 0) {
|
|
217444
|
-
if (!Array.isArray(d.references) || d.references.length > 5)
|
|
217737
|
+
if (!Array.isArray(d.references) || d.references.length > 5) invalid10("Use up to five inspected reference links per direction.");
|
|
217445
217738
|
references = d.references.map((v2) => {
|
|
217446
217739
|
const ref = object19(v2, ["label", "url"]), label = text13(ref.label, 140), url3 = text13(ref.url, 2e3);
|
|
217447
217740
|
let parsed;
|
|
217448
217741
|
try {
|
|
217449
217742
|
parsed = new URL(url3);
|
|
217450
217743
|
} catch {
|
|
217451
|
-
|
|
217744
|
+
invalid10("Use an HTTPS reference link.");
|
|
217452
217745
|
}
|
|
217453
|
-
if (parsed.protocol !== "https:" || parsed.username || parsed.password)
|
|
217746
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password) invalid10("Use an HTTPS reference link without credentials.");
|
|
217454
217747
|
return { label, url: url3 };
|
|
217455
217748
|
});
|
|
217456
217749
|
}
|
|
217457
217750
|
return { id: id4, title: text13(d.title, 100), description: text13(d.description, 500), ...d.preview ? { preview: media2(d.preview) } : {}, ...references ? { references } : {} };
|
|
217458
217751
|
});
|
|
217459
217752
|
}
|
|
217460
|
-
if (result2.stage === "directions" && (!result2.directions?.length || result2.video || result2.transcript))
|
|
217461
|
-
if (result2.stage !== "directions" && (!result2.video || result2.directions))
|
|
217753
|
+
if (result2.stage === "directions" && (!result2.directions?.length || result2.video || result2.transcript)) invalid10("Direction stage needs visual proposals, without an edited-video transcript.");
|
|
217754
|
+
if (result2.stage !== "directions" && (!result2.video || result2.directions)) invalid10("Review/delivery needs one video; keep direction choices in the earlier artifact.");
|
|
217462
217755
|
return result2;
|
|
217463
217756
|
}
|
|
217464
217757
|
async function prepareMedia(root, input2, kind2, mediaDir, entries) {
|
|
217465
|
-
const path = resolve18(root, input2.file), extension =
|
|
217758
|
+
const path = resolve18(root, input2.file), extension = extname9(path).toLowerCase();
|
|
217466
217759
|
const mime2 = { ".mp4": "video/mp4", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
|
|
217467
|
-
if (!mime2[extension] || kind2 === "video" && !mime2[extension].startsWith("video/"))
|
|
217760
|
+
if (!mime2[extension] || kind2 === "video" && !mime2[extension].startsWith("video/")) invalid10("Use MP4/WebM video or PNG/JPEG/WebP proposal previews.");
|
|
217468
217761
|
const meta3 = { ...input2.purpose ? { purpose: input2.purpose } : {}, ...input2.quality ? { quality: input2.quality } : {} };
|
|
217469
217762
|
if (!mediaDir) {
|
|
217470
217763
|
const bytes = await readReviewFile(path, REVIEW_MEDIA_BYTES), sha2562 = createHash25("sha256").update(bytes).digest("hex");
|
|
217471
|
-
if (input2.sha256 && input2.sha256 !== sha2562)
|
|
217764
|
+
if (input2.sha256 && input2.sha256 !== sha2562) invalid10("Preview hash does not match this version.");
|
|
217472
217765
|
return { uri: `data:${mime2[extension]};base64,${bytes.toString("base64")}`, sha256: sha2562, mimeType: mime2[extension], ...meta3 };
|
|
217473
217766
|
}
|
|
217474
217767
|
const temporary = await productionOutputPath(root, `${mediaDir}/copy-${randomUUID10()}`);
|
|
217475
217768
|
await mkdir18(dirname24(temporary), { recursive: true });
|
|
217476
217769
|
try {
|
|
217477
217770
|
const { sha256: sha2562, bytes } = await copyReviewFile(path, temporary);
|
|
217478
|
-
if (input2.sha256 && input2.sha256 !== sha2562)
|
|
217479
|
-
const name = `${sha2562}${extension}`, file2 = `${mediaDir}/${name}`, uri = `${encodeURIComponent(
|
|
217771
|
+
if (input2.sha256 && input2.sha256 !== sha2562) invalid10("Preview hash does not match this version.");
|
|
217772
|
+
const name = `${sha2562}${extension}`, file2 = `${mediaDir}/${name}`, uri = `${encodeURIComponent(basename6(mediaDir))}/${name}`;
|
|
217480
217773
|
if (!entries.some((entry) => entry.uri === uri)) {
|
|
217481
217774
|
await link7(temporary, await productionOutputPath(root, file2));
|
|
217482
217775
|
entries.push({ uri, file: file2, sha256: sha2562, bytes, mimeType: mime2[extension] });
|
|
@@ -217488,9 +217781,9 @@ async function prepareMedia(root, input2, kind2, mediaDir, entries) {
|
|
|
217488
217781
|
}
|
|
217489
217782
|
}
|
|
217490
217783
|
async function createReviewArtifact(root, value, out, mediaMode = "local") {
|
|
217491
|
-
if (!["local", "embedded"].includes(mediaMode))
|
|
217784
|
+
if (!["local", "embedded"].includes(mediaMode)) invalid10("Use --media-mode local or embedded.");
|
|
217492
217785
|
const input2 = parseReviewArtifact(value);
|
|
217493
|
-
if (!out.endsWith(".html"))
|
|
217786
|
+
if (!out.endsWith(".html")) invalid10("Output must be a new .html file.");
|
|
217494
217787
|
const target = await productionOutputPath(root, out);
|
|
217495
217788
|
for (const path of [target, `${target}.review.json`]) {
|
|
217496
217789
|
try {
|
|
@@ -217499,7 +217792,7 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
|
|
|
217499
217792
|
if (error62.code === "ENOENT") continue;
|
|
217500
217793
|
throw error62;
|
|
217501
217794
|
}
|
|
217502
|
-
|
|
217795
|
+
invalid10("Review output already exists. Use a new filename; previous decisions are preserved.");
|
|
217503
217796
|
}
|
|
217504
217797
|
const entries = [];
|
|
217505
217798
|
const mediaDir = mediaMode === "local" ? `${out}.media-${randomUUID10()}` : void 0;
|
|
@@ -217509,12 +217802,12 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
|
|
|
217509
217802
|
directions.push({ ...direction, ...preview ? { preview: await prepareMedia(root, preview, "preview", mediaDir, entries) } : {} });
|
|
217510
217803
|
}
|
|
217511
217804
|
const clean = { schemaVersion: 1, projectId: input2.projectId, title: input2.title, version: input2.version, stage: input2.stage, ...input2.contextVersion ? { contextVersion: input2.contextVersion } : {}, ...video ? { video } : {}, ...directions ? { directions } : {}, ...input2.transcript ? { transcript: input2.transcript } : {}, ...input2.learnings ? { learnings: input2.learnings } : {}, ...input2.learningContext ? { learningContext: input2.learningContext } : {} };
|
|
217512
|
-
if (JSON.stringify(clean).length > 40 * 1024 * 1024)
|
|
217805
|
+
if (JSON.stringify(clean).length > 40 * 1024 * 1024) invalid10("Embedded previews exceed 40 MiB. Use smaller review copies.");
|
|
217513
217806
|
const artifactId = createHash25("sha256").update(JSON.stringify(clean)).digest("hex");
|
|
217514
217807
|
const html = renderReviewArtifact({ ...clean, artifactId }, onboardingWordmark);
|
|
217515
217808
|
await mkdir18(dirname24(target), { recursive: true });
|
|
217516
217809
|
await atomicWrite(root, out, html, { document: false, overwrite: false, mode: 384 });
|
|
217517
|
-
if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, html: { file: out, sha256: createHash25("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
|
|
217810
|
+
if (mediaMode === "local") await atomicWrite(root, `${out}.review.json`, JSON.stringify({ schemaVersion: 1, kind: "editorbrain.local-review", artifactId, projectId: input2.projectId, stage: input2.stage, ...input2.contextVersion ? { contextVersion: input2.contextVersion } : {}, ...directions ? { directionIds: directions.map((direction) => direction.id), directionPreviews: Object.fromEntries(directions.filter((direction) => direction.preview).map((direction) => [direction.id, direction.preview.sha256])) } : {}, presented: false, html: { file: out, sha256: createHash25("sha256").update(html).digest("hex"), bytes: Buffer.byteLength(html) }, media: entries }), { document: false, overwrite: false, mode: 384 });
|
|
217518
217811
|
return { kind: "editorbrain.review-artifact", path: target, artifactId, projectId: input2.projectId, stage: input2.stage, videoSha256: video?.sha256 ?? null, mediaEmbedded: mediaMode === "embedded", htmlBytes: Buffer.byteLength(html), mediaBytes: entries.reduce((sum, item) => sum + item.bytes, 0), ...mediaMode === "local" ? { openCommand: { executable: "editorbrain", args: ["production", "review-open", "--file", out, "--dir", root] } } : {}, mediaUploaded: false, agentTriggered: false, reviewSurface: "computer", cloudStorageBytes: 0, next: mediaMode === "local" ? "Run openCommand as a persistent preview process. Open its verified URL in the Claude Code Desktop Browser pane or the host browser. Keep the process alive; verify video playback, seeking and comments before delivery. Do not attach this HTML alone or publish it as a native Claude artifact: its private media are separate. No upload. Clicks do not wake the agent." : "Standalone embedded export: inspect htmlBytes before attaching. Host size/playback limits vary; if rejected, regenerate with --media-mode local and use production review-open. Never paste the base64 file into model context. No upload or automatic agent wake-up." };
|
|
217519
217812
|
}
|
|
217520
217813
|
|
|
@@ -217522,18 +217815,18 @@ async function createReviewArtifact(root, value, out, mediaMode = "local") {
|
|
|
217522
217815
|
import { createServer as createServer3 } from "node:http";
|
|
217523
217816
|
import { Readable } from "node:stream";
|
|
217524
217817
|
import { createHash as createHash26, randomBytes as randomBytes2 } from "node:crypto";
|
|
217525
|
-
import { basename as
|
|
217526
|
-
var
|
|
217527
|
-
var
|
|
217818
|
+
import { basename as basename7 } from "node:path";
|
|
217819
|
+
var hash11 = (bytes) => createHash26("sha256").update(bytes).digest("hex");
|
|
217820
|
+
var invalid11 = () => new CliError("INVALID_LOCAL_REVIEW", "The local review or its media is missing, altered or unsupported.", "Regenerate with production review-artifact --media-mode local using a new output path. Keep the HTML, .review.json and media folder together.");
|
|
217528
217821
|
var validHash = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
|
|
217529
217822
|
async function startReviewArtifact(root, file2, port = 0) {
|
|
217530
217823
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError("INVALID_ARGUMENT", "Preview port must be 0 through 65535.", "Omit --port for an available loopback port.");
|
|
217531
|
-
if (!file2.endsWith(".html")) throw
|
|
217824
|
+
if (!file2.endsWith(".html")) throw invalid11();
|
|
217532
217825
|
const manifestPath = await productionOutputPath(root, `${file2}.review.json`);
|
|
217533
217826
|
const manifest = JSON.parse((await readReviewFile(manifestPath, 64 * 1024)).toString());
|
|
217534
|
-
if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file2 || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw
|
|
217827
|
+
if (manifest?.schemaVersion !== 1 || manifest.kind !== "editorbrain.local-review" || !validHash(manifest.artifactId) || manifest.html?.file !== file2 || !validHash(manifest.html.sha256) || !Array.isArray(manifest.media) || manifest.media.length > 3) throw invalid11();
|
|
217535
217828
|
const html = await readReviewFile(await productionOutputPath(root, file2), 2 * 1024 * 1024);
|
|
217536
|
-
if (
|
|
217829
|
+
if (hash11(html) !== manifest.html.sha256 || html.length !== manifest.html.bytes) throw invalid11();
|
|
217537
217830
|
const snapshots2 = [];
|
|
217538
217831
|
const cleanup = async () => {
|
|
217539
217832
|
await Promise.allSettled(snapshots2.splice(0).map((s) => s.close()));
|
|
@@ -217543,15 +217836,15 @@ async function startReviewArtifact(root, file2, port = 0) {
|
|
|
217543
217836
|
try {
|
|
217544
217837
|
const mime2 = { mp4: "video/mp4", webm: "video/webm", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
|
|
217545
217838
|
for (const entry of manifest.media) {
|
|
217546
|
-
if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${file2}.media-`) || !validHash(entry.sha256)) throw
|
|
217839
|
+
if (!entry || typeof entry.file !== "string" || !entry.file.startsWith(`${file2}.media-`) || !validHash(entry.sha256)) throw invalid11();
|
|
217547
217840
|
const suffix = entry.file.slice(`${file2}.media-`.length);
|
|
217548
217841
|
const match = /^([a-f0-9-]{36})\/([a-f0-9]{64})\.(mp4|webm|png|jpg|jpeg|webp)$/.exec(suffix);
|
|
217549
|
-
if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]]) throw
|
|
217550
|
-
const uri = `${encodeURIComponent(
|
|
217551
|
-
if (entry.uri !== uri || resources.has(uri)) throw
|
|
217842
|
+
if (!match || match[2] !== entry.sha256 || entry.mimeType !== mime2[match[3]]) throw invalid11();
|
|
217843
|
+
const uri = `${encodeURIComponent(basename7(file2) + ".media-" + match[1])}/${match[2]}.${match[3]}`;
|
|
217844
|
+
if (entry.uri !== uri || resources.has(uri)) throw invalid11();
|
|
217552
217845
|
const snapshot = await openReviewSnapshot(await productionOutputPath(root, entry.file));
|
|
217553
217846
|
snapshots2.push(snapshot);
|
|
217554
|
-
if (snapshot.bytes !== entry.bytes || snapshot.sha256 !== entry.sha256) throw
|
|
217847
|
+
if (snapshot.bytes !== entry.bytes || snapshot.sha256 !== entry.sha256) throw invalid11();
|
|
217555
217848
|
resources.set(uri, { snapshot, bytes: snapshot.bytes, mime: entry.mimeType });
|
|
217556
217849
|
}
|
|
217557
217850
|
const token = randomBytes2(24).toString("hex"), prefix = `/${token}/`;
|
|
@@ -217632,7 +217925,7 @@ async function startReviewArtifact(root, file2, port = 0) {
|
|
|
217632
217925
|
const address = server.address();
|
|
217633
217926
|
if (!address || typeof address === "string") {
|
|
217634
217927
|
server.close();
|
|
217635
|
-
throw
|
|
217928
|
+
throw invalid11();
|
|
217636
217929
|
}
|
|
217637
217930
|
origin = `http://127.0.0.1:${address.port}`;
|
|
217638
217931
|
const url3 = `${origin}${prefix}index.html`;
|
|
@@ -217648,7 +217941,7 @@ async function startReviewArtifact(root, file2, port = 0) {
|
|
|
217648
217941
|
};
|
|
217649
217942
|
try {
|
|
217650
217943
|
const probe2 = await fetch(url3, { signal: AbortSignal.timeout(5e3) });
|
|
217651
|
-
if (probe2.status !== 200 ||
|
|
217944
|
+
if (probe2.status !== 200 || hash11(Buffer.from(await probe2.arrayBuffer())) !== manifest.html.sha256) throw invalid11();
|
|
217652
217945
|
} catch (error62) {
|
|
217653
217946
|
await close();
|
|
217654
217947
|
throw error62;
|
|
@@ -217665,56 +217958,56 @@ async function serveReviewArtifact(root, file2, port = 0) {
|
|
|
217665
217958
|
} catch (error62) {
|
|
217666
217959
|
if (error62 instanceof CliError) throw error62;
|
|
217667
217960
|
if (error62.code === "EADDRINUSE") throw new CliError("REVIEW_PORT_UNAVAILABLE", "That preview port is already in use.", "Omit --port for a free port, or select another port in the host preview runner. Do not stop an unrelated server.");
|
|
217668
|
-
throw
|
|
217961
|
+
throw invalid11();
|
|
217669
217962
|
}
|
|
217670
217963
|
}
|
|
217671
217964
|
|
|
217672
217965
|
// packages/cli/src/production-review-client.ts
|
|
217673
217966
|
var productionReviewCommands = ["reviews", "transcript", "sample", "approve", "change", "feedback", "resolve-feedback", "revoke-sample"];
|
|
217674
|
-
var
|
|
217967
|
+
var invalid12 = (message) => {
|
|
217675
217968
|
throw new CliError("INVALID_ARGUMENT", message, "Read editorbrain help and references/production-continuity.md.");
|
|
217676
217969
|
};
|
|
217677
|
-
var
|
|
217678
|
-
if (typeof value !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value))
|
|
217970
|
+
var uuid10 = (value, name) => {
|
|
217971
|
+
if (typeof value !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)) invalid12(`${name} must be a revision or feedback UUID.`);
|
|
217679
217972
|
return value;
|
|
217680
217973
|
};
|
|
217681
|
-
var
|
|
217682
|
-
if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value))
|
|
217974
|
+
var hash12 = (value, name) => {
|
|
217975
|
+
if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) invalid12(`${name} must be an exact SHA-256 hash.`);
|
|
217683
217976
|
return value;
|
|
217684
217977
|
};
|
|
217685
217978
|
var text14 = (value, name, max, optional2 = false) => {
|
|
217686
217979
|
if (optional2 && (value === void 0 || value === null)) return "";
|
|
217687
|
-
if (typeof value !== "string" || value.length > max || !optional2 && !value.trim())
|
|
217980
|
+
if (typeof value !== "string" || value.length > max || !optional2 && !value.trim()) invalid12(`${name} must contain ${optional2 ? "0" : "1"}\u2013${max} characters.`);
|
|
217688
217981
|
return value.trim();
|
|
217689
217982
|
};
|
|
217690
217983
|
function reviewBody(value, command) {
|
|
217691
|
-
const
|
|
217692
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !
|
|
217984
|
+
const fields3 = command === "sample" ? ["assetId", "contextVersion", "title", "notes", "parentRevisionId", "revisionId", "transcript", "supersedeParent"] : ["resultRevisionId", "contextVersion", "resultNote", "preservedElements"];
|
|
217985
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !fields3.includes(key))) invalid12("Use only documented review fields; project and feedback IDs come from command flags, never the JSON body.");
|
|
217693
217986
|
const body = value;
|
|
217694
|
-
|
|
217987
|
+
hash12(body.contextVersion, "contextVersion");
|
|
217695
217988
|
if (command === "sample") {
|
|
217696
|
-
if (body.supersedeParent !== void 0 && (typeof body.supersedeParent !== "boolean" || body.supersedeParent && !body.parentRevisionId))
|
|
217989
|
+
if (body.supersedeParent !== void 0 && (typeof body.supersedeParent !== "boolean" || body.supersedeParent && !body.parentRevisionId)) invalid12("supersedeParent must be a boolean and requires parentRevisionId when true.");
|
|
217697
217990
|
if (body.transcript !== void 0) {
|
|
217698
217991
|
try {
|
|
217699
217992
|
body.transcript = parseReviewTranscript(body.transcript);
|
|
217700
217993
|
} catch (e) {
|
|
217701
|
-
|
|
217994
|
+
invalid12(e.message);
|
|
217702
217995
|
}
|
|
217703
217996
|
}
|
|
217704
|
-
|
|
217997
|
+
hash12(body.assetId, "assetId");
|
|
217705
217998
|
text14(body.title, "title", 120);
|
|
217706
217999
|
text14(body.notes, "notes", 2e3, true);
|
|
217707
|
-
for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0)
|
|
218000
|
+
for (const key of ["parentRevisionId", "revisionId"]) if (body[key] !== void 0) uuid10(body[key], key);
|
|
217708
218001
|
} else {
|
|
217709
|
-
|
|
218002
|
+
uuid10(body.resultRevisionId, "resultRevisionId");
|
|
217710
218003
|
text14(body.resultNote, "resultNote", 1500);
|
|
217711
218004
|
text14(body.preservedElements, "preservedElements", 2e3);
|
|
217712
218005
|
}
|
|
217713
|
-
if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192))
|
|
218006
|
+
if (Buffer.byteLength(JSON.stringify(body)) > (command === "sample" ? REVIEW_SAMPLE_MAX_BYTES : 8192)) invalid12(command === "sample" ? "Review metadata exceeds the 64 KiB service limit." : "Review metadata exceeds the 8 KiB service limit.");
|
|
217714
218007
|
return body;
|
|
217715
218008
|
}
|
|
217716
218009
|
async function productionReviewCommand(client, root, command, flags) {
|
|
217717
|
-
if (!productionReviewCommands.includes(command))
|
|
218010
|
+
if (!productionReviewCommands.includes(command)) invalid12("Unknown production review command.");
|
|
217718
218011
|
const required2 = (name) => {
|
|
217719
218012
|
const value = flags[name];
|
|
217720
218013
|
if (typeof value !== "string" || !value) throw new CliError("INVALID_ARGUMENT", `--${name} is required.`, "Read editorbrain help.");
|
|
@@ -217734,24 +218027,24 @@ async function productionReviewCommand(client, root, command, flags) {
|
|
|
217734
218027
|
const projectId = required2("project");
|
|
217735
218028
|
assertIdentifier(projectId);
|
|
217736
218029
|
const base = `/v1/projects/${encodeURIComponent(projectId)}`;
|
|
217737
|
-
const revision2 = () => encodeURIComponent(
|
|
217738
|
-
const contextVersion = () =>
|
|
217739
|
-
const after = flags.after === void 0 ? void 0 :
|
|
218030
|
+
const revision2 = () => encodeURIComponent(uuid10(required2("revision"), "--revision"));
|
|
218031
|
+
const contextVersion = () => hash12(required2("context-version"), "--context-version");
|
|
218032
|
+
const after = flags.after === void 0 ? void 0 : uuid10(required2("after"), "--after");
|
|
217740
218033
|
if (command === "transcript") return client.request(`${base}/production-reviews/${revision2()}/transcript`);
|
|
217741
218034
|
if (command === "reviews") return client.request(`${base}/production-reviews${after ? "?" + new URLSearchParams({ after }) : ""}`);
|
|
217742
218035
|
if (command === "feedback") {
|
|
217743
218036
|
const query = new URLSearchParams();
|
|
217744
218037
|
if (flags.status !== void 0) {
|
|
217745
218038
|
const status = required2("status");
|
|
217746
|
-
if (!["pending", "resolved"].includes(status))
|
|
218039
|
+
if (!["pending", "resolved"].includes(status)) invalid12("--status must be pending or resolved.");
|
|
217747
218040
|
query.set("status", status);
|
|
217748
218041
|
}
|
|
217749
|
-
if (flags.revision !== void 0) query.set("revisionId",
|
|
218042
|
+
if (flags.revision !== void 0) query.set("revisionId", uuid10(required2("revision"), "--revision"));
|
|
217750
218043
|
if (after) query.set("after", after);
|
|
217751
218044
|
return client.request(`${base}/production-feedback?${query}`);
|
|
217752
218045
|
}
|
|
217753
218046
|
if (command === "sample" || command === "resolve-feedback") {
|
|
217754
|
-
const feedbackId = command === "resolve-feedback" ?
|
|
218047
|
+
const feedbackId = command === "resolve-feedback" ? uuid10(required2("id"), "--id") : void 0;
|
|
217755
218048
|
const body = reviewBody(await readProductionJson(root, required2("file")), command);
|
|
217756
218049
|
return client.request(command === "sample" ? `${base}/production-reviews` : `${base}/production-feedback/${encodeURIComponent(feedbackId)}/resolve`, { method: "POST", body });
|
|
217757
218050
|
}
|
|
@@ -217762,10 +218055,10 @@ async function productionReviewCommand(client, root, command, flags) {
|
|
|
217762
218055
|
if (command === "revoke-sample") return client.request(`${base}/production-reviews/${revision2()}`, { method: "DELETE" });
|
|
217763
218056
|
if (command === "change") {
|
|
217764
218057
|
const segment = flags.segment === void 0 ? void 0 : required2("segment");
|
|
217765
|
-
if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment))
|
|
218058
|
+
if (segment !== void 0 && !/^[a-zA-Z0-9_-]{1,80}$/.test(segment)) invalid12("Use a valid transcript segment ID.");
|
|
217766
218059
|
const times = flags.at === void 0 ? [] : required2("at").split(",");
|
|
217767
218060
|
if (times.length > 2 || times.some((t) => !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(t) || !Number.isFinite(Number(t)) || Number(t) > 36e3) || times.length === 2 && Number(times[1]) < Number(times[0])) throw new CliError("INVALID_ARGUMENT", "--at accepts one second or a start,end range between 0 and 36000 seconds.", "Example: --at 12,15.5. Omit it for the whole sample.");
|
|
217768
|
-
return client.request(`${base}/production-reviews/${revision2()}/changes`, { method: "POST", body: { contextVersion: contextVersion(), text: text14(required2("text"), "--text", 1500), target: { ...segment ? { segmentId: segment } : {}, ...times.length ? { startMs: Math.round(Number(times[0]) * 1e3), ...times.length === 2 ? { endMs: Math.round(Number(times[1]) * 1e3) } : {} } : {} }, ...flags.id !== void 0 ? { feedbackId:
|
|
218061
|
+
return client.request(`${base}/production-reviews/${revision2()}/changes`, { method: "POST", body: { contextVersion: contextVersion(), text: text14(required2("text"), "--text", 1500), target: { ...segment ? { segmentId: segment } : {}, ...times.length ? { startMs: Math.round(Number(times[0]) * 1e3), ...times.length === 2 ? { endMs: Math.round(Number(times[1]) * 1e3) } : {} } : {} }, ...flags.id !== void 0 ? { feedbackId: uuid10(required2("id"), "--id") } : {} } });
|
|
217769
218062
|
}
|
|
217770
218063
|
throw new CliError("INVALID_ARGUMENT", "Unknown production review command.", "Read editorbrain help.");
|
|
217771
218064
|
}
|
|
@@ -217774,7 +218067,7 @@ async function productionReviewCommand(client, root, command, flags) {
|
|
|
217774
218067
|
import { constants as constants17 } from "node:fs";
|
|
217775
218068
|
import { open as open22, mkdir as mkdir19 } from "node:fs/promises";
|
|
217776
218069
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
217777
|
-
import { basename as
|
|
218070
|
+
import { basename as basename8, extname as extname10, join as join23 } from "node:path";
|
|
217778
218071
|
|
|
217779
218072
|
// packages/cli/src/production-parent.ts
|
|
217780
218073
|
var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
@@ -217816,7 +218109,7 @@ async function latestProductionParent(client, projectId) {
|
|
|
217816
218109
|
var HASH2 = /^[a-f0-9]{64}$/;
|
|
217817
218110
|
var UUID2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
217818
218111
|
var MAX_BYTES2 = 90 * 1024 * 1024;
|
|
217819
|
-
var
|
|
218112
|
+
var invalid13 = (message) => {
|
|
217820
218113
|
throw new CliError("INVALID_ARGUMENT", message, "Use production submit --project ID --file relative.mp4 --title TEXT [--parent UUID|latest] [--notes TEXT] [--quality 480|720].");
|
|
217821
218114
|
};
|
|
217822
218115
|
async function optionalText2(root, path, document2 = true) {
|
|
@@ -217841,14 +218134,14 @@ async function verifyRegistered(value, receipt) {
|
|
|
217841
218134
|
if (!JSON.parse(value.media.content).assets.some((asset) => asset.id === receipt.preview.sha256)) throw new CliError("SUBMISSION_RESPONSE_INVALID", "The returned media document does not reference this submitted preview.", "Keep the receipt and inspect the registered submission before reconciling media.");
|
|
217842
218135
|
}
|
|
217843
218136
|
async function submitProduction(client, root, flags, runtime2 = { probe: probeLocalMedia, prepare: prepareMediaPreview }) {
|
|
217844
|
-
for (const key of Object.keys(flags)) if (!["project", "file", "title", "parent", "notes", "quality", "dir", "url"].includes(key))
|
|
217845
|
-
const required2 = (key) => typeof flags[key] === "string" && flags[key].trim() ? flags[key] :
|
|
218137
|
+
for (const key of Object.keys(flags)) if (!["project", "file", "title", "parent", "notes", "quality", "dir", "url"].includes(key)) invalid13(`--${key} is not supported for production submit.`);
|
|
218138
|
+
const required2 = (key) => typeof flags[key] === "string" && flags[key].trim() ? flags[key] : invalid13(`--${key} is required.`);
|
|
217846
218139
|
const projectId = assertIdentifier(required2("project")), file2 = required2("file"), title = required2("title").trim();
|
|
217847
218140
|
const notes = flags.notes === void 0 ? void 0 : required2("notes").trim(), parentRevisionId = flags.parent === void 0 ? void 0 : required2("parent");
|
|
217848
|
-
if (title.length > 120 || notes !== void 0 && notes.length > 2e3 || parentRevisionId !== void 0 && parentRevisionId !== "latest" && !UUID2.test(parentRevisionId))
|
|
218141
|
+
if (title.length > 120 || notes !== void 0 && notes.length > 2e3 || parentRevisionId !== void 0 && parentRevisionId !== "latest" && !UUID2.test(parentRevisionId)) invalid13("Use a title up to 120 characters, notes up to 2000, and a parent UUID or latest.");
|
|
217849
218142
|
const selectedQuality = flags.quality === void 0 ? 720 : Number(required2("quality"));
|
|
217850
|
-
const quality = selectedQuality === 480 ? 480 : selectedQuality === 720 ? 720 :
|
|
217851
|
-
if (
|
|
218143
|
+
const quality = selectedQuality === 480 ? 480 : selectedQuality === 720 ? 720 : invalid13("--quality must be 480 or 720.");
|
|
218144
|
+
if (extname10(file2).toLowerCase() !== ".mp4") invalid13("--file must name a workspace-relative MP4.");
|
|
217852
218145
|
const sourcePath = await checkedPath(root, file2, false), source2 = await runtime2.probe(sourcePath);
|
|
217853
218146
|
const me = await client.me();
|
|
217854
218147
|
await loadSyncState(root, client.url, me.workspaceId);
|
|
@@ -217933,7 +218226,7 @@ async function submitProduction(client, root, flags, runtime2 = { probe: probeLo
|
|
|
217933
218226
|
if (await sha256(bytes) !== receipt.preview.sha256) throw new CliError("SUBMISSION_PREVIEW_CHANGED", "The preview changed during upload preparation.", "Restore its exact bytes before retrying.");
|
|
217934
218227
|
receipt.state = "uploading";
|
|
217935
218228
|
await save(receipt);
|
|
217936
|
-
const params = new URLSearchParams({ name:
|
|
218229
|
+
const params = new URLSearchParams({ name: basename8(file2, extname10(file2)) + "-review.mp4", projectId, purpose: "preview", ...receipt.sourceSha256 !== receipt.preview.sha256 ? { sourceSha256: receipt.sourceSha256 } : {} });
|
|
217937
218230
|
const uploaded = await client.uploadPreview(`/v1/assets/${receipt.preview.sha256}?${params}`, bytes, "video/mp4");
|
|
217938
218231
|
const asset = await uploaded.json();
|
|
217939
218232
|
if (asset.id !== receipt.preview.sha256 || asset.sha256 !== receipt.preview.sha256 || asset.bytes !== bytes.byteLength || asset.mimeType !== "video/mp4") throw new CliError("SUBMISSION_UPLOAD_UNCONFIRMED", "The preview upload response could not be verified.", "Retry the same submission; its hash preflight will inspect the existing bytes before any upload.");
|
|
@@ -218140,6 +218433,8 @@ editorbrain production matte-plan --file montage.mp4 [--dir folder]
|
|
|
218140
218433
|
editorbrain production check --file render [--profile local-profile.json] [--dir folder] [--out .editorbrain-local/report.json] [--details]
|
|
218141
218434
|
editorbrain production verify --project ID --file final.mp4 [--ocr] [--ocr-language eng] [--audio-profile audio.json] [--review-inputs continuity.json] [--platform tiktok|reels|shorts] [--profile geometry.json] [--duration seconds] [--at 0,5,12] [--dir folder] [--out .editorbrain-local/new-check] [--offline] [--details]
|
|
218142
218435
|
editorbrain production review-artifact --file review.json --out .editorbrain-local/review-v1.html [--media-mode local|embedded] [--dir folder]
|
|
218436
|
+
editorbrain production present --project ID [--file presentation.json | --id UUID] [--dir folder] [--url https://server]
|
|
218437
|
+
editorbrain production withdraw --project ID --id UUID --expected-version HASH --user-confirmed [--url https://server]
|
|
218143
218438
|
editorbrain production review-open --file .editorbrain-local/review-v1.html [--port 0] [--dir folder]
|
|
218144
218439
|
editorbrain production reviews --project ID [--after UUID]
|
|
218145
218440
|
editorbrain production transcript --project ID --revision UUID
|
|
@@ -218683,6 +218978,27 @@ async function main() {
|
|
|
218683
218978
|
}
|
|
218684
218979
|
return;
|
|
218685
218980
|
}
|
|
218981
|
+
if (command === "production" && subcommand === "withdraw") {
|
|
218982
|
+
if (argument || Object.keys(args.flags).some((key) => !["project", "id", "expected-version", "user-confirmed", "url"].includes(key))) throw new CliError("INVALID_ARGUMENT", "Unsupported production withdraw option.", "Read production withdraw --help.");
|
|
218983
|
+
output2(await withdrawPresentation(new Client(await config2(args)), str(args, "project") ?? "", str(args, "id") ?? "", str(args, "expected-version") ?? "", args.flags["user-confirmed"] === true));
|
|
218984
|
+
return;
|
|
218985
|
+
}
|
|
218986
|
+
if (command === "production" && subcommand === "present") {
|
|
218987
|
+
if (argument || Object.keys(args.flags).some((key) => !["project", "file", "id", "dir", "url"].includes(key))) throw new CliError("INVALID_ARGUMENT", "Unsupported production present option.", "Use --project ID; omit --file to read current evidence/version, or --id UUID for an exact historical receipt. Supply --file only after sharing the artifact with the user.");
|
|
218988
|
+
const projectId = str(args, "project");
|
|
218989
|
+
if (!projectId) throw new CliError("INVALID_ARGUMENT", "--project is required.", "Use production present --project ID.");
|
|
218990
|
+
assertIdentifier(projectId);
|
|
218991
|
+
const receiptId = str(args, "id"), file2 = str(args, "file");
|
|
218992
|
+
if (receiptId && (file2 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(receiptId))) throw new CliError("INVALID_ARGUMENT", "Use --id UUID for reading one receipt, or --file to record a presentation.", "Keep the same evidenceId when recovering an uncertain write.");
|
|
218993
|
+
const client = new Client(await config2(args));
|
|
218994
|
+
if (!file2) {
|
|
218995
|
+
output2(await client.request(`/v1/projects/${encodeURIComponent(projectId)}/review-evidence${receiptId ? "/" + receiptId : ""}`));
|
|
218996
|
+
return;
|
|
218997
|
+
}
|
|
218998
|
+
const root2 = await ensureRoot(str(args, "dir") ?? process.cwd());
|
|
218999
|
+
output2(await presentProduction(client, root2, projectId, await readPresentationInput(root2, file2)));
|
|
219000
|
+
return;
|
|
219001
|
+
}
|
|
218686
219002
|
if (command === "production" && subcommand === "review-artifact") {
|
|
218687
219003
|
if (argument || Object.keys(args.flags).some((k) => !["file", "out", "dir", "media-mode"].includes(k))) throw new CliError("INVALID_ARGUMENT", "Unsupported review-artifact option.", "Use --file, --out, optional --media-mode local|embedded and --dir.");
|
|
218688
219004
|
const root2 = resolve19(str(args, "dir") ?? process.cwd()), file2 = str(args, "file"), out = str(args, "out");
|
|
@@ -219221,17 +219537,17 @@ async function main() {
|
|
|
219221
219537
|
await handle.close();
|
|
219222
219538
|
}
|
|
219223
219539
|
const types2 = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg" };
|
|
219224
|
-
const mimeType = str(args, "mime") ?? types2[
|
|
219540
|
+
const mimeType = str(args, "mime") ?? types2[extname11(target).toLowerCase()];
|
|
219225
219541
|
if (!mimeType) throw new Error("Unsupported extension; specify --mime for a supported media format");
|
|
219226
|
-
const
|
|
219227
|
-
const params = new URLSearchParams({ name:
|
|
219542
|
+
const hash13 = await sha256(bytes);
|
|
219543
|
+
const params = new URLSearchParams({ name: basename9(target) });
|
|
219228
219544
|
if (str(args, "project")) params.set("projectId", str(args, "project"));
|
|
219229
219545
|
if (str(args, "purpose")) params.set("purpose", str(args, "purpose"));
|
|
219230
219546
|
if (str(args, "source-sha256")) params.set("sourceSha256", str(args, "source-sha256"));
|
|
219231
|
-
const path = `/v1/assets/${
|
|
219547
|
+
const path = `/v1/assets/${hash13}?${params}`;
|
|
219232
219548
|
const result2 = str(args, "purpose") === "preview" ? await client.uploadPreview(path, bytes, mimeType) : await client.media(path, { content: bytes, mimeType });
|
|
219233
219549
|
const body = await result2.json();
|
|
219234
|
-
if (body.sha256 !==
|
|
219550
|
+
if (body.sha256 !== hash13) throw new Error("Upload response hash mismatch");
|
|
219235
219551
|
output2(body);
|
|
219236
219552
|
return;
|
|
219237
219553
|
}
|
|
@@ -219239,11 +219555,11 @@ async function main() {
|
|
|
219239
219555
|
if (!/^[a-f0-9]{64}$/.test(argument)) throw new Error("Asset ID must be its SHA-256");
|
|
219240
219556
|
const destination = resolve19(str(args, "dir") ?? process.cwd(), str(args, "out"));
|
|
219241
219557
|
const root2 = await ensureRoot(dirname25(destination), true);
|
|
219242
|
-
await checkedPath(root2,
|
|
219558
|
+
await checkedPath(root2, basename9(destination), false);
|
|
219243
219559
|
const response = await client.media(`/v1/assets/${argument}`);
|
|
219244
219560
|
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
219245
219561
|
if (await sha256(bytes) !== argument) throw new Error("Downloaded asset failed SHA-256 verification");
|
|
219246
|
-
await atomicWrite(root2,
|
|
219562
|
+
await atomicWrite(root2, basename9(destination), bytes, { document: false, overwrite: false });
|
|
219247
219563
|
output2({ path: destination, sha256: argument, bytes: bytes.length });
|
|
219248
219564
|
return;
|
|
219249
219565
|
}
|
|
@@ -219305,7 +219621,10 @@ async function main() {
|
|
|
219305
219621
|
previousContextVersion: str(args, "previous-context-version"),
|
|
219306
219622
|
...str(args, "questions") ? { questionNeeds: await readProductionJson(await ensureRoot(str(args, "dir") ?? process.cwd()), str(args, "questions")) } : {}
|
|
219307
219623
|
} });
|
|
219308
|
-
|
|
219624
|
+
const projectId = str(args, "project");
|
|
219625
|
+
const localSync = projectId ? await projectLocalSync(client, await ensureRoot(str(args, "dir") ?? process.cwd()), projectId, result2.editorialSnapshot?.sourceHashes) : void 0;
|
|
219626
|
+
const projected = args.flags.summary && result2.kind !== "editorbrain.workflow-summary" ? summarizeWorkflow(result2) : result2;
|
|
219627
|
+
output2({ ...projected, ...localSync ? { localSync } : {} });
|
|
219309
219628
|
return;
|
|
219310
219629
|
}
|
|
219311
219630
|
if (command === "search" && subcommand === "brief") {
|
|
@@ -219353,10 +219672,10 @@ async function main() {
|
|
|
219353
219672
|
if (assetId && !/^[a-f0-9]{64}$/.test(assetId)) throw new Error("--asset requires an owned production asset SHA-256.");
|
|
219354
219673
|
if (videoPath) {
|
|
219355
219674
|
const bytes = await readInput(videoPath, 12 * 1024 * 1024);
|
|
219356
|
-
const mimeType = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" }[
|
|
219675
|
+
const mimeType = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" }[extname11(videoPath).toLowerCase()];
|
|
219357
219676
|
if (!mimeType) throw new Error("Use MP4, MOV or WebM.");
|
|
219358
219677
|
assetId = await sha256(bytes);
|
|
219359
|
-
const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(
|
|
219678
|
+
const uploaded = await client.media(`/v1/assets/${assetId}?name=${encodeURIComponent(basename9(videoPath))}`, { content: bytes, mimeType });
|
|
219360
219679
|
if ((await uploaded.json()).sha256 !== assetId) throw new Error("Upload hash mismatch.");
|
|
219361
219680
|
}
|
|
219362
219681
|
if (!script && !assetId && !str(args, "project")) throw new Error("Provide --script, --video, --asset or --project with a saved script.");
|
|
@@ -219389,20 +219708,20 @@ async function main() {
|
|
|
219389
219708
|
}
|
|
219390
219709
|
if (subcommand === "get" && argument) {
|
|
219391
219710
|
const document2 = str(args, "document");
|
|
219392
|
-
const
|
|
219393
|
-
if (
|
|
219394
|
-
const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...
|
|
219395
|
-
if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 ||
|
|
219711
|
+
const hash13 = str(args, "sha256");
|
|
219712
|
+
if (hash13 && !document2) throw new Error("--sha256 requires --document for library get.");
|
|
219713
|
+
const result2 = await client.request(`/v1/library/${encodeURIComponent(argument)}${document2 ? `/documents?${new URLSearchParams({ path: document2, ...hash13 ? { sha256: hash13 } : {} })}` : ""}`);
|
|
219714
|
+
if (document2 && (typeof result2.content !== "string" || await sha256(result2.content) !== result2.sha256 || hash13 && result2.sha256 !== hash13)) throw new CliError("HASH_MISMATCH", "Reference document verification failed.", "Do not use this evidence; retry the pinned version.");
|
|
219396
219715
|
output2(result2);
|
|
219397
219716
|
return;
|
|
219398
219717
|
}
|
|
219399
219718
|
if (subcommand === "media" && argument && str(args, "out")) {
|
|
219400
|
-
const
|
|
219401
|
-
if (!
|
|
219719
|
+
const hash13 = str(args, "sha256");
|
|
219720
|
+
if (!hash13 || !/^[a-f0-9]{64}$/.test(hash13)) throw new Error("--sha256 must be a media SHA-256 from library get.");
|
|
219402
219721
|
const destination = resolve19(str(args, "dir") ?? process.cwd(), str(args, "out"));
|
|
219403
219722
|
const root2 = await ensureRoot(dirname25(destination), true);
|
|
219404
|
-
await checkedPath(root2,
|
|
219405
|
-
const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${
|
|
219723
|
+
await checkedPath(root2, basename9(destination), false);
|
|
219724
|
+
const response = await client.media(`/v1/library/${encodeURIComponent(argument)}/media/${hash13}`);
|
|
219406
219725
|
const reader = response.body?.getReader();
|
|
219407
219726
|
if (!reader) throw new Error("Media body missing.");
|
|
219408
219727
|
const chunks = [];
|
|
@@ -219418,9 +219737,9 @@ async function main() {
|
|
|
219418
219737
|
chunks.push(value);
|
|
219419
219738
|
}
|
|
219420
219739
|
const bytes = Buffer.concat(chunks);
|
|
219421
|
-
if (await sha256(bytes) !==
|
|
219422
|
-
await atomicWrite(root2,
|
|
219423
|
-
output2({ videoId: argument, path: destination, sha256:
|
|
219740
|
+
if (await sha256(bytes) !== hash13) throw new CliError("HASH_MISMATCH", "Reference media verification failed.", "Do not use this file as evidence.");
|
|
219741
|
+
await atomicWrite(root2, basename9(destination), bytes, { document: false, overwrite: false });
|
|
219742
|
+
output2({ videoId: argument, path: destination, sha256: hash13, bytes: size, mimeType: response.headers.get("Content-Type"), reviewed: false });
|
|
219424
219743
|
return;
|
|
219425
219744
|
}
|
|
219426
219745
|
throw new Error("Use library search, library get, or library media <video-id> --sha256 hash --out file.");
|