@tora-editor/tora 0.2.0 → 0.3.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.
Files changed (107) hide show
  1. package/README.md +5 -6
  2. package/bin/tora.mjs +255 -29
  3. package/crates/packer/trusted/native-3d-meta.json +3 -3
  4. package/crates/packer/trusted/native-3d.js +180 -180
  5. package/crates/packer/trusted/native-meta.json +3 -3
  6. package/crates/packer/trusted/native.js +5 -5
  7. package/crates/packer/trusted/release-manifest.json +17 -17
  8. package/crates/packer/trusted/review-runtime-meta.json +3 -3
  9. package/crates/packer/trusted/review-runtime.js +182 -182
  10. package/docs/MIGRATION_0_3.md +39 -0
  11. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  12. package/docs/TORA_AGENT_SETUP.md +24 -106
  13. package/docs/TORA_CREATION_API.md +63 -365
  14. package/docs/reference/CORE_AUTHORING.md +8 -2
  15. package/docs/reference/PLAYABLE_STARTERS.md +1 -1
  16. package/docs/reference/packs/3d.md +2 -0
  17. package/package.json +6 -6
  18. package/packages/creative-project/project-v21.schema.json +108 -1
  19. package/scripts/lean/editor/entry.js +11 -6
  20. package/scripts/lean/editor/project-launcher.js +116 -0
  21. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  22. package/scripts/lean/editor/review-editor.css +246 -68
  23. package/scripts/lean/editor/review-editor.js +1731 -1099
  24. package/scripts/lean/editor-state.mjs +6 -0
  25. package/scripts/lean/editor.mjs +6 -3
  26. package/scripts/lean/matrix.mjs +5 -0
  27. package/scripts/lean/native/agent-tools.mjs +35 -58
  28. package/scripts/lean/native/api.mjs +148 -134
  29. package/scripts/lean/native/audio-assets.mjs +30 -0
  30. package/scripts/lean/native/browser-pool.mjs +34 -0
  31. package/scripts/lean/native/build-cache.mjs +36 -5
  32. package/scripts/lean/native/contracts.mjs +8 -6
  33. package/scripts/lean/native/creative-qa.mjs +66 -12
  34. package/scripts/lean/native/demos.mjs +11 -20
  35. package/scripts/lean/native/document.mjs +14 -2
  36. package/scripts/lean/native/local-bundle.mjs +4 -2
  37. package/scripts/lean/native/mcp-server.mjs +16 -35
  38. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  39. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  40. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  41. package/scripts/lean/native/project-bundle.mjs +3 -2
  42. package/scripts/lean/native/project-index.mjs +0 -2
  43. package/scripts/lean/native/qa-adapters.mjs +10 -0
  44. package/scripts/lean/native/quick-edit.mjs +328 -0
  45. package/scripts/lean/native/review.mjs +203 -572
  46. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  47. package/scripts/lean/native/schema.mjs +1 -1
  48. package/scripts/lean/native/scope.mjs +45 -0
  49. package/scripts/lean/native/service.mjs +242 -70
  50. package/scripts/lean/native/starters.mjs +135 -8
  51. package/scripts/lean/native/variant-adapters.mjs +8 -0
  52. package/scripts/lean/native/variants-core.mjs +186 -0
  53. package/scripts/lean/native/variants.mjs +63 -0
  54. package/scripts/lean/native/win-cues.mjs +1 -1
  55. package/skills/tora-playables/SKILL.md +1 -1
  56. package/scripts/lean/editor/review-intake.js +0 -837
  57. package/scripts/lean/model-client.mjs +0 -119
  58. package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
  59. package/scripts/lean/native/author-fps.mjs +0 -545
  60. package/scripts/lean/native/author-games.mjs +0 -160
  61. package/scripts/lean/native/author-harvest.mjs +0 -74
  62. package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
  63. package/scripts/lean/native/author-salvage.mjs +0 -71
  64. package/scripts/lean/native/chat-compose.mjs +0 -287
  65. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
  66. package/scripts/lean/native/check-salvage.mjs +0 -200
  67. package/scripts/lean/native/compatibility.mjs +0 -34
  68. package/scripts/lean/native/concept.mjs +0 -633
  69. package/scripts/lean/native/draw-stroke.mjs +0 -26
  70. package/scripts/lean/native/erase-mask.mjs +0 -18
  71. package/scripts/lean/native/glb-loader.mjs +0 -468
  72. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  73. package/scripts/lean/native/instance-steering.mjs +0 -24
  74. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  75. package/scripts/lean/native/intake-creator-tools.mjs +0 -218
  76. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  77. package/scripts/lean/native/match-board.mjs +0 -138
  78. package/scripts/lean/native/modules/index.mjs +0 -54
  79. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  80. package/scripts/lean/native/path-network.mjs +0 -132
  81. package/scripts/lean/native/physics-2d.mjs +0 -154
  82. package/scripts/lean/native/physics-3d.mjs +0 -259
  83. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  84. package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
  85. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  86. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  87. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  88. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  89. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  90. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  91. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  92. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  93. package/scripts/lean/native/presentation.mjs +0 -335
  94. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  95. package/scripts/lean/native/review-connection.mjs +0 -303
  96. package/scripts/lean/native/review-fields.mjs +0 -24
  97. package/scripts/lean/native/review-intake.mjs +0 -385
  98. package/scripts/lean/native/review-intents.mjs +0 -217
  99. package/scripts/lean/native/review-provider.mjs +0 -580
  100. package/scripts/lean/native/review-receipts.mjs +0 -76
  101. package/scripts/lean/native/review-resolver.mjs +0 -429
  102. package/scripts/lean/native/review-targets.mjs +0 -35
  103. package/scripts/lean/native/runtime.mjs +0 -1809
  104. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  105. package/scripts/lean/native/stage-3d.mjs +0 -1121
  106. package/scripts/lean/native/verify.mjs +0 -4
  107. package/scripts/lean/scene-document.mjs +0 -48
@@ -0,0 +1,10 @@
1
+ import schema from '../../../packages/creative-project/project-v21.schema.json' with {type:'json'};
2
+
3
+ const kinds=variants=>variants.map(variant=>variant.properties.kind.const??variant.properties.kind.enum?.[0]).filter(Boolean);
4
+ const fields=variants=>Object.fromEntries(variants.map(variant=>{
5
+ const kind=variant.properties.kind.const??variant.properties.kind.enum?.[0];
6
+ return [kind,Object.keys(variant.properties).filter(key=>key!=='kind')];
7
+ }));
8
+
9
+ export const schemaEvents=Object.freeze(kinds(schema.properties.events.items.oneOf));
10
+ export const schemaActions=Object.freeze(fields(schema.properties.eventBindings.items.properties.actions.items.oneOf));
@@ -54,4 +54,4 @@ const action={oneOf:[
54
54
  obj({kind:{const:'playModelAnimation'},componentId:id,clipName:{type:'string',maxLength:96},loop:{enum:['repeat','once','pingpong']},speed:{type:'number',minimum:0,maximum:4},fadeSeconds:{type:'number',minimum:0,maximum:2},restart:{type:'boolean'}},['loop','speed','fadeSeconds','restart']),
55
55
  ...['animate','stopAnimation','emit','playAudio'].map(kind=>obj({kind:{const:kind},behaviorId:id})),
56
56
  ]};
57
- export const nativeSchema={$schema:'https://json-schema.org/draft/2020-12/schema',$id:'urn:tora:creative-project:2.1.0',title:'Creative Project 2.1 native scene',...obj({schemaVersion:{const:'2.1.0'},projectId:id,revisionId:{type:'string',minLength:1,maxLength:128},generationOrigin:{const:'human-authored'},creativeBrief:obj({goal:{type:'string',minLength:1,maxLength:2048},language:{const:'en'}}),base:obj({kind:{const:'native-scene'},runtimeId:{const:'tora-native'},runtimeVersion:{const:'1.0.0'},width:{type:'number',minimum:240,maximum:2048},height:{type:'number',minimum:240,maximum:2048},startScene:id,storeUrl:{type:'string',pattern:'^$|^https://(play\\.google\\.com/store/apps/details\\?id=[a-zA-Z0-9._-]+|apps\\.apple\\.com/[a-zA-Z0-9/._?=&-]+)$'}}),scenes:{...array(obj({id,label:{type:'string',maxLength:80},role:{enum:['interactive','end-card']}}),16),minItems:1},components:array({oneOf:Object.values(contracts).map(c=>obj({id,label:{type:'string',maxLength:80},contract:{const:c.id},sceneId:id,parentId:id,order:num,transform:matrix,parameters:specs(c.properties),assetSlots:c.id==='native.mesh3d.v1'?array(obj({slotId:{enum:mesh3dSlots},assetId:id}),4):array(obj({slotId:{const:'source'},assetId:id}),1),prototype:{type:'boolean'}},['parentId']))},limits.components),variables:array({oneOf:['number','boolean','string'].map(type=>obj({id,label:{type:'string',maxLength:80},type:{const:type},initial:type==='number'?num:type==='boolean'?{type}:str}))},limits.variables),gameplay:array({oneOf:Object.entries(behaviors).map(([kind,params])=>obj({id,componentId:id,kind:{const:kind},parameters:specs(params)}))},limits.gameplay),events:array(event,384),eventBindings:array(obj({id,eventId:id,condition:ref('Condition'),actions:{...array(action,32),minItems:1}},['condition']),limits.eventBindings),assets:array(obj({id,hash:{type:'string',pattern:'^sha256:[a-f0-9]{64}$'},mime:{enum:['image/png','image/jpeg','audio/wav','audio/mpeg','model/tora-mesh','model/gltf-binary']},bytes:{type:'integer',minimum:1,maximum:1048576},rights:{type:'string',minLength:1,maxLength:2048},provenance:{type:'string',minLength:1,maxLength:2048}},['provenance']),256),tombstones:{...array(id,4096),uniqueItems:true}}),$defs:{Condition:condition}};
57
+ export const nativeSchema={$schema:'https://json-schema.org/draft/2020-12/schema',$id:'urn:tora:creative-project:2.1.0',title:'Creative Project 2.1 native scene',...obj({schemaVersion:{const:'2.1.0'},projectId:id,revisionId:{type:'string',minLength:1,maxLength:128},generationOrigin:{const:'human-authored'},creativeBrief:obj({goal:{type:'string',minLength:1,maxLength:2048},language:{type:'string',maxLength:16,pattern:'^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?$'}}),base:obj({kind:{const:'native-scene'},runtimeId:{const:'tora-native'},runtimeVersion:{const:'1.0.0'},width:{type:'number',minimum:240,maximum:2048},height:{type:'number',minimum:240,maximum:2048},startScene:id,storeUrl:{type:'string',pattern:'^$|^https://(play\\.google\\.com/store/apps/details\\?id=[a-zA-Z0-9._-]+|apps\\.apple\\.com/[a-zA-Z0-9/._?=&-]+)$'}}),scenes:{...array(obj({id,label:{type:'string',maxLength:80},role:{enum:['interactive','end-card']}}),16),minItems:1},components:array({oneOf:Object.values(contracts).map(c=>obj({id,label:{type:'string',maxLength:80},contract:{const:c.id},sceneId:id,parentId:id,order:num,transform:matrix,parameters:specs(c.properties),assetSlots:c.id==='native.mesh3d.v1'?array(obj({slotId:{enum:mesh3dSlots},assetId:id}),4):array(obj({slotId:{const:'source'},assetId:id}),1),prototype:{type:'boolean'}},['parentId']))},limits.components),variables:array({oneOf:['number','boolean','string'].map(type=>obj({id,label:{type:'string',maxLength:80},type:{const:type},initial:type==='number'?num:type==='boolean'?{type}:str}))},limits.variables),gameplay:array({oneOf:Object.entries(behaviors).map(([kind,params])=>obj({id,componentId:id,kind:{const:kind},parameters:specs(params)}))},limits.gameplay),events:array(event,384),eventBindings:array(obj({id,eventId:id,condition:ref('Condition'),actions:{...array(action,32),minItems:1}},['condition']),limits.eventBindings),assets:array(obj({id,hash:{type:'string',pattern:'^sha256:[a-f0-9]{64}$'},mime:{enum:['image/png','image/jpeg','audio/wav','audio/mpeg','model/tora-mesh','model/gltf-binary']},bytes:{type:'integer',minimum:1,maximum:1048576},rights:{type:'string',minLength:1,maxLength:2048},provenance:{type:'string',minLength:1,maxLength:2048}},['provenance']),256),tombstones:{...array(id,4096),uniqueItems:true}}),$defs:{Condition:condition}};
@@ -0,0 +1,45 @@
1
+ import {isDeepStrictEqual} from 'node:util';
2
+ import {check,references} from './document.mjs';
3
+
4
+ export const nativeCollections=['scenes','components','variables','gameplay','events','eventBindings','assets'];
5
+ const mutableCollections=['components','variables','gameplay','events','eventBindings'];
6
+
7
+ export function nativeRecordRefs(record){
8
+ const refs=[...references(record)];
9
+ if(record?.parentId)refs.push(record.parentId);
10
+ if(record?.contract==='native.text.v1'&&typeof record.parameters?.text==='string'){
11
+ for(const match of record.parameters.text.matchAll(/\{\{([a-z0-9_.-]+)\}\}/g))refs.push(match[1]);
12
+ }
13
+ return refs;
14
+ }
15
+
16
+ export function changedNativeRecords(before,after){
17
+ const ids=new Set(nativeCollections.flatMap(collection=>[...before[collection],...after[collection]].map(record=>record.id)));
18
+ const changed=[...ids].filter(id=>{
19
+ const find=project=>nativeCollections.flatMap(collection=>project[collection]).find(record=>record.id===id);
20
+ return !isDeepStrictEqual(find(before),find(after));
21
+ });
22
+ if(!isDeepStrictEqual(before.base,after.base))changed.push('$project.base');
23
+ return changed;
24
+ }
25
+
26
+ export function outsideNativeScope(before,after,changed,scope,allowCreates=false,createScope=scope){
27
+ const authorized=new Set(scope);
28
+ if(!allowCreates)return changed.filter(id=>!authorized.has(id));
29
+ const createAuthorized=new Set(createScope);
30
+ const existingAll=new Set(nativeCollections.flatMap(collection=>before[collection].map(record=>record.id)));
31
+ const existingMutable=new Set(mutableCollections.flatMap(collection=>before[collection].map(record=>record.id)));
32
+ const previewById=new Map(nativeCollections.flatMap(collection=>after[collection].map(record=>[record.id,record])));
33
+ return changed.filter(id=>{
34
+ if(authorized.has(id))return false;
35
+ if(id==='$project.base'||existingAll.has(id))return true;
36
+ const record=previewById.get(id);
37
+ if(!record)return true;
38
+ return nativeRecordRefs(record).some(ref=>existingMutable.has(ref)&&!createAuthorized.has(ref));
39
+ });
40
+ }
41
+
42
+ export function assertNativeScope(before,after,changed,scope,allowCreates=false,createScope=scope){
43
+ const outside=outsideNativeScope(before,after,changed,scope,allowCreates,createScope);
44
+ check(outside.length===0,'E_REVIEW_OUTSIDE_SCOPE',{outsideScope:outside});
45
+ }
@@ -1,8 +1,8 @@
1
1
  import {execFile} from 'node:child_process';
2
2
  import {promisify} from 'node:util';
3
3
  import {Buffer} from 'node:buffer';
4
- import {writeFile,mkdir,mkdtemp,readFile,copyFile,rm} from 'node:fs/promises';
5
- import {resolve,dirname} from 'node:path';
4
+ import {writeFile,mkdir,mkdtemp,readFile,copyFile,rm,rename,stat} from 'node:fs/promises';
5
+ import {resolve,dirname,relative,isAbsolute,sep} from 'node:path';
6
6
  import {randomUUID} from 'node:crypto';
7
7
  import {canonical,projectContent} from '../../../packages/creative-project/src/canonical.mjs';
8
8
  import {check,exact,applyOperations,validateDocument,references} from './document.mjs';
@@ -13,12 +13,27 @@ import {resolvePreparedProvenance} from './asset-prep.mjs';
13
13
  import {capabilities} from './contracts.mjs';
14
14
  import {CREATIVE_QA_CHECKER_VERSION,CREATIVE_QA_FORMAT,getPlaywrightBrowserVersion,runStaticPreflight} from './creative-qa.mjs';
15
15
  import {isAudioMime} from './media-validate.mjs';
16
- import {assertNetworkTarget} from './network-targets.mjs';
16
+ import {acceptsTargetBytes,assertNetworkTarget} from './network-targets.mjs';
17
17
  import {NativeBuildCache,VerificationReceiptCache,buildCacheKey} from './build-cache.mjs';
18
18
  import {mapWithConcurrency} from './concurrency.mjs';
19
19
  import {assertSingleVisualStyleFamily} from './cc0-staging.mjs';
20
20
  import {requireNativeTool} from './native-bin.mjs';
21
+ import {closeSharedBrowser,defaultQaConcurrency,getSharedBrowser} from './browser-pool.mjs';
22
+ import {exportBudget} from './export-budget.mjs';
23
+ import {playableHTML} from './html.mjs';
24
+ import {createPresetOverlay,extractLocalizableStrings,materializeVariant,readVariants,updateVariants,validateVariantStore,variantStoreHash,visibleStringVariables} from './variants.mjs';
25
+ import {qaAdapterForProject} from './qa-adapters.mjs';
26
+ import {variantAdapterForProject} from './variant-adapters.mjs';
27
+ import {withProjectFileLock} from '../editor-state.mjs';
21
28
  const runTool=promisify(execFile);
29
+ const checkerHashCache=new Map();
30
+ async function nativeBinaryHash(commandPath){
31
+ const info=await stat(commandPath),cached=checkerHashCache.get(commandPath);
32
+ if(cached&&cached.mtimeMs===info.mtimeMs&&cached.size===info.size)return cached.digest;
33
+ const digest=hash(await readFile(commandPath));
34
+ checkerHashCache.set(commandPath,{mtimeMs:info.mtimeMs,size:info.size,digest});
35
+ return digest;
36
+ }
22
37
  const MODEL_FIT_LADDER=Object.freeze([
23
38
  {maxTextureSide:256,targetBytes:180000},
24
39
  {maxTextureSide:192,targetBytes:110000},
@@ -27,6 +42,7 @@ const MODEL_FIT_LADDER=Object.freeze([
27
42
  ]);
28
43
  const IMAGE_FIT_SIDES=Object.freeze([512,384,256,160]);
29
44
  const PREAPPLY_AUDIO_BLOCKERS=new Set(['audio-role-mismatch','audio-valence-mismatch','audio-win-loss-duplicate','audio-contour-mismatch','audio-clipping']);
45
+ let sharedBatchJobs=0;
30
46
  export const contentHash=p=>hash('tora-v2-hash/1\ndocument-content\n'+canonical(projectContent(p)));
31
47
  export function requireCreativeQa(report){
32
48
  if(report?.ok)return report;
@@ -47,33 +63,101 @@ function qaReportSatisfiesOptions(report,{motionFilmstrip=true,recordVideo=false
47
63
  }
48
64
  return true;
49
65
  }
66
+ function evidenceFiles(report){return [...(report.screenshots??[]),...(report.contactSheets??[]),...(report.motionFilmstrips??[]),...(report.video?[report.video]:[])];}
67
+ function evidencePath(root,path){
68
+ if(typeof path!=='string'||isAbsolute(path))throw Error('E_QA_EVIDENCE_PATH');
69
+ const srcRoot=resolve(root),resolved=resolve(srcRoot,path),rel=relative(srcRoot,resolved);
70
+ if(!rel||rel==='..'||rel.startsWith('..'+sep))throw Error('E_QA_EVIDENCE_PATH');
71
+ return resolved;
72
+ }
50
73
  async function verifyAndCopyQaArtifacts(cachedOutputDir,targetOutputDir,report,options={}){
51
74
  if(!qaReportSatisfiesOptions(report,options))return false;
52
- const files=[
53
- ...(report.screenshots??[]),
54
- ...(report.contactSheets??[]),
55
- ...(report.motionFilmstrips??[]),
56
- ...(report.video?[report.video]:[]),
57
- ];
58
- for(const entry of files){
59
- if(!entry?.path||!entry?.sha256)return false;
60
- try{
61
- const bytes=await readFile(resolve(cachedOutputDir,entry.path));
75
+ const files=evidenceFiles(report);
76
+ try{
77
+ for(const entry of files){
78
+ if(!entry?.path||!entry?.sha256)return false;
79
+ const bytes=await readFile(evidencePath(cachedOutputDir,entry.path));
62
80
  if(hash(bytes)!==entry.sha256)return false;
63
- }catch{return false;}
64
- }
81
+ }
82
+ await readFile(evidencePath(cachedOutputDir,'report.json'));
83
+ }catch{return false;}
65
84
  const srcRoot=resolve(cachedOutputDir),dstRoot=resolve(targetOutputDir);
66
85
  if(srcRoot!==dstRoot){
67
86
  await mkdir(dstRoot,{recursive:true});
68
87
  for(const entry of files){
69
- const dst=resolve(dstRoot,entry.path);
88
+ const dst=evidencePath(dstRoot,entry.path);
70
89
  await mkdir(dirname(dst),{recursive:true});
71
- await copyFile(resolve(srcRoot,entry.path),dst);
90
+ await copyFile(evidencePath(srcRoot,entry.path),dst);
72
91
  }
73
- await copyFile(resolve(srcRoot,'report.json'),resolve(dstRoot,'report.json')).catch(()=>{});
92
+ await copyFile(evidencePath(srcRoot,'report.json'),evidencePath(dstRoot,'report.json'));
74
93
  }
75
94
  return true;
76
95
  }
96
+ async function copyFailedQaArtifacts(source,target,report){
97
+ await mkdir(target,{recursive:true});
98
+ for(const entry of evidenceFiles(report)){
99
+ if(!entry?.path)continue;
100
+ try{const bytes=await readFile(evidencePath(source,entry.path));if(entry.sha256&&hash(bytes)!==entry.sha256)throw Error('E_QA_EVIDENCE_HASH');const destination=evidencePath(target,entry.path);await mkdir(dirname(destination),{recursive:true});await writeFile(destination,bytes);}
101
+ catch(error){if(error.code!=='ENOENT')throw error;}
102
+ }
103
+ await copyFile(evidencePath(source,'report.json'),evidencePath(target,'report.json'));return target;
104
+ }
105
+ async function writeAtomic(path,bytes){
106
+ await mkdir(dirname(path),{recursive:true});const temporary=resolve(dirname(path),'.'+randomUUID()+'.tmp');
107
+ try{await writeFile(temporary,bytes,{flag:'wx'});await rename(temporary,path);}finally{await rm(temporary,{force:true});}
108
+ }
109
+ function deliveryFilename(id,artifact,target){
110
+ if(artifact.archiveFilename)return artifact.archiveFilename;
111
+ return target==='standalone-browser-draft'?`${id}-draft.html`:'index.html';
112
+ }
113
+ function artifactCheckFailure(report,cause){
114
+ const error=Error('E_ARTIFACT_CHECK',{cause});error.code='E_ARTIFACT_CHECK';error.artifactCheck=report;return error;
115
+ }
116
+ function expectedCopyFor(project,variant){
117
+ if(!variant?.language)return undefined;
118
+ const checks={opening:new Set(),'after-first-input':new Set(),'end-card':new Set(),timeout:new Set()},components=new Map(project.components.map(component=>[component.id,component])),sceneStates=new Map(project.scenes.map(scene=>[scene.id,scene.role==='end-card'?(/fail|loss|timeout/i.test(scene.id)?'timeout':'end-card'):'opening']));
119
+ const effectivelyVisible=component=>{for(let current=component;current;current=components.get(current.parentId))if(current.parameters.visible===false)return false;return true;};
120
+ const rendered=component=>component?.parameters.text?.replace(/\{\{([a-z0-9_.-]+)\}\}/g,(_,key)=>String(project.variables.find(variable=>variable.id===key)?.initial??''));
121
+ const descendants=id=>{const ids=new Set([id]);for(let changed=true;changed;){changed=false;for(const component of project.components)if(component.parentId&&ids.has(component.parentId)&&!ids.has(component.id)){ids.add(component.id);changed=true;}}return ids;};
122
+ const phaseOutcome=value=>{if(!value||typeof value!=='object')return false;if(/(?:^|\.)phase$/.test(value.variableId??'')&&['cta','payoff'].includes(value.value))return true;return Object.values(value).some(phaseOutcome);};
123
+ const descriptor=qaAdapterForProject(project),canCheckEndCard=project.scenes.some(scene=>scene.role==='end-card')||Boolean(descriptor?.qa?.playToEndCard),canCheckTimeout=[...sceneStates.values()].includes('timeout')||Boolean(descriptor?.qa?.deadlineBehaviorId&&descriptor?.qa?.phaseVariable);
124
+ const stateFor=(binding,component)=>{
125
+ const event=project.events.find(item=>item.id===binding.eventId),sceneState=sceneStates.get(component?.sceneId)??'opening',transition=binding.actions.find(action=>action.kind==='changeScene');
126
+ if(transition){const state=sceneStates.get(transition.sceneId)??sceneState;return state==='end-card'&&!canCheckEndCard||state==='timeout'&&!canCheckTimeout?null:state;}
127
+ if(event?.kind==='timer'&&(/deadline|timeout/i.test(event.behaviorId??'')||binding.actions.some(action=>action.kind==='set'&&/(?:^|\.)phase$/.test(action.variableId??'')&&action.value==='cta')))return canCheckTimeout?'timeout':null;
128
+ if(event?.kind==='variableChange'&&(phaseOutcome(binding.condition)||binding.actions.some(action=>action.kind==='set'&&/(?:^|\.)phase$/.test(action.variableId??'')&&['cta','payoff'].includes(action.value))))return canCheckEndCard?'end-card':null;
129
+ if(['variableChange','timer'].includes(event?.kind))return null;
130
+ return sceneState;
131
+ };
132
+ const revealed=new Map(),hidden=new Map(),overrides=new Map();
133
+ for(const binding of project.eventBindings){
134
+ for(const action of binding.actions)if(action.kind==='setComponent'){
135
+ const component=components.get(action.componentId),state=stateFor(binding,component);
136
+ if(action.key==='visible'){
137
+ const states=action.value===true?revealed:hidden;for(const id of descendants(action.componentId)){if(!states.has(id))states.set(id,new Set());states.get(id).add(state);}
138
+ }
139
+ if(action.key==='text'){if(!overrides.has(action.componentId))overrides.set(action.componentId,new Set());overrides.get(action.componentId).add(state);}
140
+ }
141
+ }
142
+ for(const id of Object.keys(variant.texts??{})){
143
+ const component=components.get(id);if(!component)continue;const text=rendered(component);if(!text?.trim())continue;
144
+ const states=revealed.get(id);if(states)for(const state of states)if(state&&!overrides.get(id)?.has(state)&&!hidden.get(id)?.has(state))checks[state].add(text);
145
+ else {const state=sceneStates.get(component.sceneId)??'opening';if(effectivelyVisible(component)&&!hidden.get(id)?.has(state))checks[state].add(text);}
146
+ }
147
+ const visibleVariables=new Set(project.components.filter(component=>component.contract==='native.text.v1').flatMap(component=>[...component.parameters.text.matchAll(/\{\{([a-z0-9_.-]+)\}\}/g)].map(match=>match[1])));
148
+ for(const binding of project.eventBindings)for(const action of binding.actions){
149
+ if(typeof action.value!=='string'||!action.value.trim()||action.value.includes('{{'))continue;
150
+ const isText=action.kind==='setComponent'&&action.key==='text',isVisibleVariable=action.kind==='set'&&visibleVariables.has(action.variableId);if(!isText&&!isVisibleVariable)continue;
151
+ const event=project.events.find(item=>item.id===binding.eventId),component=components.get(action.componentId),state=stateFor(binding,component);
152
+ if(isVisibleVariable&&['click','timer'].includes(event?.kind)){
153
+ const linked=project.components.filter(component=>component.contract==='native.text.v1'&&component.parameters.text.includes('{{'+action.variableId+'}}'));
154
+ if(state&&linked.some(component=>revealed.get(component.id)?.has(state)||effectivelyVisible(component)&&!hidden.get(component.id)?.has(state)))checks[state].add(action.value);continue;
155
+ }
156
+ if(isText&&state&&!hidden.get(action.componentId)?.has(state)&&(effectivelyVisible(component)||revealed.get(action.componentId)?.has(state)))checks[state].add(action.value);
157
+ }
158
+ const result=Object.fromEntries(Object.entries(checks).filter(([,values])=>values.size).map(([state,values])=>[state,[...values]]));
159
+ return Object.keys(result).length?result:undefined;
160
+ }
77
161
  export class NativeService{
78
162
  constructor(store,history,{qaRunner=defaultQaRunner,browserProvider,useVerifyCache}={}){this.store=store;this.history=history;this.qaRunner=qaRunner;this.browserProvider=browserProvider;this.useVerifyCache=useVerifyCache;this.buildCache=new NativeBuildCache();this.verifyCache=new VerificationReceiptCache(store.root);}
79
163
  async create(input){check(input?.id!=='compose'&&/^[a-z][a-z0-9-]{1,47}$/.test(input?.id)&&exact(input,['id','name','kind','androidUrl']),'E_NATIVE_ARGUMENT');await this.store.createNative(input);return this.read(input.id);}
@@ -196,8 +280,10 @@ export class NativeService{
196
280
  }finally{await rm(stage,{recursive:true,force:true});}
197
281
  return compileNative(makeProject(),{assets:workingAssets,target,sourceContentHash:origContentHash,optimizationReport:makeReport()});
198
282
  }
199
- async build(id,project,target='standalone-browser-draft',{fitTargetBudget=false}={}){
200
- const assets=await lowerAssets(resolve(this.store.root,id),project.assets),runtimeHash=hash(projectUses3d(project)?await runtime3dBundle():await runtimeBundle()),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(a=>a.hash)});
283
+ async build(id,project,target='standalone-browser-draft',{fitTargetBudget=false,preLoweredAssets}={}){
284
+ const assets=preLoweredAssets??await lowerAssets(resolve(this.store.root,id),project.assets);
285
+ check(Array.isArray(assets)&&assets.length===project.assets.length&&assets.every((asset,index)=>asset.id===project.assets[index].id&&asset.hash===project.assets[index].hash&&asset.bytes===project.assets[index].bytes&&asset.mime===project.assets[index].mime&&typeof asset.data==='string'),'E_NATIVE_ASSET');
286
+ const runtimeHash=hash(projectUses3d(project)?await runtime3dBundle():await runtimeBundle()),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(a=>a.hash)});
201
287
  return this.buildCache.getOrBuild(key,()=>fitTargetBudget?this.fitToTarget(id,project,assets,target):compileNative(project,{assets,target}));
202
288
  }
203
289
  async render(id,revisionId){check(typeof revisionId==='string','E_NATIVE_ARGUMENT');const {project}=await this.read(id,revisionId),assets=await lowerAssets(resolve(this.store.root,id),project.assets),artifact=await compileNative(project,{assets});return {assets,artifact:artifact.manifest};}
@@ -249,62 +335,148 @@ export class NativeService{
249
335
  const committed=await this.transact(id,{...envelope,previewDigest:preview.previewDigest},{registeredAssets:registered});
250
336
  return {...committed,assets:registered.map(({optimization,...record})=>({...record,...(optimization?{optimization}:{})}))};
251
337
  }
252
- async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false,artifact:prebuiltArtifact,fitTargetBudget=false,reuseVideoReceipt=false}={}){
253
- assertNetworkTarget(target);
254
- const current=await this.read(id,revisionId),effectiveRevisionId=current.revisionId;
255
- const qaDirSuffix=(fitTargetBudget?'-fit':'')+(recordVideo?'-video':motionFilmstrip?'':'-nomotion');
256
- const resolvedOut=resolve(outputDir??resolve(this.store.root,id,'qa',effectiveRevisionId,target+qaDirSuffix));
257
- const artifact=prebuiltArtifact??await this.build(id,current.project,target,{fitTargetBudget});
258
- const artifactHash=artifact.manifest.artifactHash;
259
- const isDefaultRunner=this.qaRunner===defaultQaRunner;
260
- const cacheEnabled=this.useVerifyCache??isDefaultRunner;
261
- let receiptKey;
338
+ async runQa(id,{revisionId,target='standalone-browser-draft',outputDir,motionFilmstrip=true,recordVideo=false,artifact:prebuiltArtifact,fitTargetBudget=false,reuseVideoReceipt=false,variantId,project:projectOverride,variant,expectedCopyChecks,preLoweredAssets,confirmReviewed,browserProvider}={}){
339
+ assertNetworkTarget(target);const current=await this.read(id,revisionId);let selected;
340
+ if(!projectOverride&&variantId)selected=await this.selectVariant(id,current,variantId);
341
+ const project=projectOverride??selected?.project??current.project;
342
+ variant??=selected?.variant;expectedCopyChecks??=expectedCopyFor(project,variant);
343
+ const artifact=prebuiltArtifact??await this.build(id,project,target,{fitTargetBudget,preLoweredAssets}),artifactHash=artifact.manifest.artifactHash,packagedCheck=confirmReviewed!==undefined?await this.verifyPackagedArtifact(id,artifact,target,{confirmReviewed}):undefined;
344
+ const isDefaultRunner=this.qaRunner===defaultQaRunner,cacheEnabled=this.useVerifyCache??isDefaultRunner;
345
+ const qaRoot=resolve(this.store.root,id,'qa'),byArtifactRoot=resolve(qaRoot,'by-artifact');await mkdir(byArtifactRoot,{recursive:true});
346
+ let browserVersion,receiptKey,scenarioHash;
347
+ const scenario=qaScenarioTag({motionFilmstrip,recordVideo})+(fitTargetBudget?';fit=1':'')+(expectedCopyChecks?';copy='+hash(canonical(expectedCopyChecks)):'');
348
+ if(cacheEnabled)browserVersion=await getPlaywrightBrowserVersion();
349
+ const checkerVersion=`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion??'not-loaded'}`;
350
+ scenarioHash=hash(canonical({artifactHash,target,checkerVersion,scenario}));
351
+ const immutableDir=resolve(byArtifactRoot,`${artifactHash.slice(7,23)}-${scenarioHash.slice(7,19)}`),resolvedOut=resolve(outputDir??immutableDir);
352
+ const keyFor=video=>this.verifyCache.receiptKey({artifactHash,checkerVersion:`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion}`,kind:'creative-qa',host:target,scenario:qaScenarioTag({motionFilmstrip,recordVideo:video})+(fitTargetBudget?';fit=1':'')+(expectedCopyChecks?';copy='+hash(canonical(expectedCopyChecks)):''),qaTier:'full'});
262
353
  if(cacheEnabled){
263
- const browserVersion=await getPlaywrightBrowserVersion();
264
- const keyFor=video=>this.verifyCache.receiptKey({
265
- artifactHash,checkerVersion:`${CREATIVE_QA_CHECKER_VERSION}:${browserVersion}`,kind:'creative-qa',host:target,
266
- scenario:qaScenarioTag({motionFilmstrip,recordVideo:video})+(fitTargetBudget?';fit=1':''),
267
- });
268
354
  receiptKey=keyFor(recordVideo);
269
- const candidateKeys=[receiptKey,...(reuseVideoReceipt&&!recordVideo?[keyFor(true)]:[])];
270
- for(const key of candidateKeys){
355
+ for(const key of [receiptKey,...(reuseVideoReceipt&&!recordVideo?[keyFor(true)]:[])]){
271
356
  const cached=await this.verifyCache.read(key);
272
- if(cached?.report?.ok!==true||cached.report.format!==CREATIVE_QA_FORMAT||typeof cached.outputDir!=='string')continue;
273
- if(await verifyAndCopyQaArtifacts(cached.outputDir,resolvedOut,cached.report,{motionFilmstrip,recordVideo,isDefaultRunner})){
274
- return {...cached.report,artifactHash,outputDir:resolvedOut,cacheHit:true};
275
- }
357
+ if(cached?.report?.ok!==true||cached.report.format!==CREATIVE_QA_FORMAT||typeof cached.outputDir!=='string'||!resolve(cached.outputDir).startsWith(byArtifactRoot+sep))continue;
358
+ if(await verifyAndCopyQaArtifacts(cached.outputDir,resolvedOut,cached.report,{motionFilmstrip,recordVideo,isDefaultRunner}))return {...cached.report,artifactHash,outputDir:resolvedOut,immutableOutputDir:cached.outputDir,cacheHit:true,...(packagedCheck?{artifactCheck:packagedCheck}:{})};
276
359
  }
277
360
  }
278
- const browser=isDefaultRunner&&this.browserProvider?await this.browserProvider():undefined;
279
- const report=await this.qaRunner({html:artifact.html,outputDir:resolvedOut,network:target,motionFilmstrip,recordVideo,...(browser?{browser}:{})});
280
- const stampedReport={...report,artifactHash};
281
- if(cacheEnabled&&report?.ok===true&&receiptKey&&qaReportSatisfiesOptions(report,{motionFilmstrip,recordVideo,isDefaultRunner})){
282
- await this.verifyCache.write(receiptKey,{report:stampedReport,outputDir:resolvedOut});
283
- }
284
- return {...stampedReport,outputDir:resolvedOut,cacheHit:false};
361
+ const stage=await mkdtemp(resolve(qaRoot,'.stage-'));
362
+ try{
363
+ let report,lastError;
364
+ for(let attempt=0;attempt<2;attempt++){
365
+ const browser=isDefaultRunner&&(this.browserProvider??browserProvider)?await (this.browserProvider??browserProvider)():undefined;
366
+ try{report=await this.qaRunner({html:artifact.html,project,outputDir:stage,network:target,motionFilmstrip,recordVideo,...(expectedCopyChecks?{expectedCopyChecks}:{}),...(browser?{browser}:{})});lastError=undefined;break;}
367
+ catch(error){lastError=error;if(!isDefaultRunner||attempt||!/disconnect|closed|crash/i.test(error?.message??''))throw error;}
368
+ }
369
+ if(lastError)throw lastError;
370
+ let stampedReport={...report,artifactHash};await writeFile(resolve(stage,'report.json'),JSON.stringify(report));
371
+ if(report?.ok!==true||!qaReportSatisfiesOptions(report,{motionFilmstrip,recordVideo,isDefaultRunner})){const failureDir=await copyFailedQaArtifacts(stage,outputDir?resolvedOut:resolve(qaRoot,'failures',randomUUID()),report);return {...stampedReport,outputDir:failureDir,cacheHit:false,...(packagedCheck?{artifactCheck:packagedCheck}:{})};}
372
+ if(!await verifyAndCopyQaArtifacts(stage,stage,report,{motionFilmstrip,recordVideo,isDefaultRunner}))throw Error('E_QA_EVIDENCE_HASH');
373
+ await withProjectFileLock(resolve(byArtifactRoot,'.publish.lock'),async()=>{
374
+ try{await rename(stage,immutableDir);}
375
+ catch(error){
376
+ if(!['EEXIST','ENOTEMPTY','EPERM'].includes(error.code))throw error;
377
+ let existing;try{existing=JSON.parse(await readFile(resolve(immutableDir,'report.json'),'utf8'));}catch{existing=null;}
378
+ if(existing?.ok===true&&await verifyAndCopyQaArtifacts(immutableDir,immutableDir,existing,{motionFilmstrip,recordVideo,isDefaultRunner})){report=existing;stampedReport={...report,artifactHash};}
379
+ else{
380
+ const corrupt=resolve(byArtifactRoot,'.corrupt-'+randomUUID());await rename(immutableDir,corrupt);
381
+ try{await rename(stage,immutableDir);await rm(corrupt,{recursive:true,force:true});}catch(publishError){await rename(corrupt,immutableDir).catch(()=>{});throw publishError;}
382
+ }
383
+ }
384
+ if(cacheEnabled&&receiptKey){await this.verifyCache.write(receiptKey,{report:stampedReport,outputDir:immutableDir});await this.verifyCache.pruneOrphanedArtifactDirs(byArtifactRoot);}
385
+ });
386
+ if(!await verifyAndCopyQaArtifacts(immutableDir,resolvedOut,stampedReport,{motionFilmstrip,recordVideo,isDefaultRunner}))throw Error('E_QA_EVIDENCE_HASH');
387
+ return {...stampedReport,outputDir:resolvedOut,immutableOutputDir:immutableDir,cacheHit:false,...(packagedCheck?{artifactCheck:packagedCheck}:{})};
388
+ }finally{await rm(stage,{recursive:true,force:true});}
285
389
  }
286
- async export(id,{revisionId,target,fitTargetBudget=false}){check(typeof revisionId==='string','E_NATIVE_ARGUMENT');assertNetworkTarget(target);const {project,accepted}=await this.read(id,revisionId),artifact=await this.build(id,project,target,{fitTargetBudget}),outputDir=resolve(this.store.root,id,'qa',revisionId,target+(fitTargetBudget?'-fit':'')),creativeQa=requireCreativeQa(await this.runQa(id,{revisionId,target,outputDir,artifact,fitTargetBudget,reuseVideoReceipt:true}));check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');return {...artifact,creativeQa,manifest:{...artifact.manifest,accepted,creativeQa:{format:CREATIVE_QA_FORMAT,ok:true,blockers:0,warnings:creativeQa.warnings.length,artifactHash:creativeQa.artifactHash},checks:[...artifact.manifest.checks,'creative-qa']}};}
287
- async exportBatch(id,{revisionId,targets,outputDir,fitTargetBudget=false}){
288
- check(Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');
289
- check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');
290
- for(const target of targets)assertNetworkTarget(target);
291
- const current=await this.read(id,revisionId),resolvedDir=resolve(outputDir);
292
- const built=await mapWithConcurrency(targets,4,async target=>({target,artifact:await this.build(id,current.project,target,{fitTargetBudget})}));
293
- const verified=[];
294
- for(const {target,artifact}of built){
295
- const qaDir=resolve(this.store.root,id,'qa',current.revisionId,target+(fitTargetBudget?'-fit':''));
296
- const creativeQa=requireCreativeQa(await this.runQa(id,{revisionId:current.revisionId,target,outputDir:qaDir,artifact,fitTargetBudget,reuseVideoReceipt:true}));
297
- check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');
298
- verified.push({target,artifact,creativeQa});
299
- }
300
- await mkdir(resolvedDir,{recursive:true});
301
- const exports=[];
302
- for(const {target,artifact,creativeQa}of verified){
303
- const filename=target==='mintegral-appgrowth-zip'?`${id}.zip`:artifact.archiveBytes?`${id}-${target}.zip`:`${id}-${target}.html`;
304
- const output=resolve(resolvedDir,filename);
305
- await writeFile(output,artifact.archiveBytes??artifact.html);
306
- exports.push({target,output,artifactHash:artifact.manifest.artifactHash,bytes:artifact.manifest.bytes,packaging:artifact.manifest.packaging,cacheHit:Boolean(creativeQa.cacheHit)});
390
+ async verifyPackagedArtifact(id,artifact,target,{confirmReviewed}={}){
391
+ const networkTarget=assertNetworkTarget(target);if(networkTarget.hostKind==='browser')return {technicalStatus:'PASS',ruleVerificationStatus:'not-applicable',ruleReviewStatus:'not-applicable',status:'DRAFT',cacheHit:false};
392
+ check(confirmReviewed===undefined||typeof confirmReviewed==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(confirmReviewed),'E_NATIVE_ARGUMENT');
393
+ const payload=Buffer.from(artifact.archiveBytes??artifact.html),artifactHash=artifact.manifest.artifactHash,filename=deliveryFilename(id,artifact,target);
394
+ check(hash(payload)===artifactHash,'E_ARTIFACT_CHECK');
395
+ const tool=requireNativeTool('cli'),checkerVersion=await nativeBinaryHash(tool.command),reviewedOn=new Date().toISOString().slice(0,10),key=this.verifyCache.receiptKey({artifactHash,checkerVersion,artifactCheckVersion:'playable-artifact-check-1',kind:'packaged-artifact',host:target,scenario:canonical({confirmReviewed:confirmReviewed??'',reviewedOn}),qaTier:'full'});
396
+ const valid=cached=>cached?.artifactHash===artifactHash&&cached.filename===filename&&cached.report?.technicalStatus==='PASS'&&cached.report.fileBytes===payload.length&&(!confirmReviewed||cached.report.status==='STATIC_PASS');
397
+ const cached=await this.verifyCache.read(key);if(valid(cached))return {...cached,cacheHit:true};
398
+ const qaRoot=resolve(this.store.root,id,'qa');await mkdir(qaRoot,{recursive:true});const stage=await mkdtemp(resolve(qaRoot,'.artifact-'));
399
+ try{
400
+ const stagedPath=resolve(stage,filename);await writeFile(stagedPath,payload,{flag:'wx'});
401
+ const args=[...tool.prefixArgs,'artifact','check',stagedPath,'--network',target,...(confirmReviewed?['--confirm-reviewed',confirmReviewed]:[]),'--json'];
402
+ let stdout,exitCode=0;try{stdout=(await runTool(tool.command,args,{timeout:120000,maxBuffer:4*1024*1024})).stdout;}catch(error){stdout=error.stdout;exitCode=typeof error.code==='number'?error.code:-1;if(!stdout)throw artifactCheckFailure(null,error);}
403
+ let report;try{report=JSON.parse(stdout);}catch(error){throw artifactCheckFailure(null,error);}
404
+ if(exitCode===5||report.technicalStatus!=='PASS'||![0,6].includes(exitCode)||confirmReviewed&&(exitCode!==0||report.status!=='STATIC_PASS'))throw artifactCheckFailure(report);
405
+ check(report.fileBytes===payload.length,'E_ARTIFACT_CHECK');
406
+ const result={artifactHash,filename,checkerVersion,report,ruleReviewStatus:report.status,ruleVerificationStatus:networkTarget.ruleVerificationStatus};
407
+ await this.verifyCache.write(key,result);return {...result,cacheHit:false};
408
+ }finally{await rm(stage,{recursive:true,force:true});}
409
+ }
410
+ async selectVariant(id,current,variantId){
411
+ if(variantId===undefined||variantId==='base')return {project:globalThis.structuredClone(current.project),variant:undefined,store:await readVariants(resolve(this.store.root,id),current.project)};
412
+ const store=await readVariants(resolve(this.store.root,id),current.project),variant=store.variants.find(item=>item.id===variantId);check(variant,'E_NATIVE_NOT_FOUND');
413
+ const report=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false});
414
+ const issues=[...report.orphans,...report.incomplete].filter(item=>item.variantId===variantId);check(!issues.length,'E_NATIVE_VARIANT',{issues});
415
+ return {project:materializeVariant(current.project,variant),variant,store};
416
+ }
417
+ async listVariants(id){
418
+ const current=await this.read(id),store=await readVariants(resolve(this.store.root,id),current.project),validation=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false}),localizable=extractLocalizableStrings(current.project),visible=visibleStringVariables(current.project);
419
+ localizable.variables=Object.fromEntries(current.project.variables.filter(variable=>variable.type==='string'&&visible.has(variable.id)).map(variable=>[variable.id,variable.initial]));
420
+ return {...store,hash:variantStoreHash(store),diagnostics:[...validation.diagnostics,...validation.orphans,...validation.incomplete],localizable,baseRevisionId:current.revisionId,baseContentHash:current.contentHash};
421
+ }
422
+ async upsertVariant(id,variant,{expectedVariantRevision}={}){
423
+ const current=await this.read(id),store=await updateVariants(resolve(this.store.root,id),current.project,expectedVariantRevision,current=>{const index=current.variants.findIndex(item=>item.id===variant?.id);if(index<0)current.variants.push(variant);else current.variants[index]=variant;return current;});
424
+ return {...store,hash:variantStoreHash(store),variant:store.variants.find(item=>item.id===variant.id)};
425
+ }
426
+ async deleteVariant(id,variantId,{expectedVariantRevision}={}){
427
+ const current=await this.read(id);check(typeof variantId==='string'&&variantId!=='base','E_NATIVE_ARGUMENT');
428
+ const store=await updateVariants(resolve(this.store.root,id),current.project,expectedVariantRevision,current=>{check(current.variants.some(item=>item.id===variantId),'E_NATIVE_NOT_FOUND');current.variants=current.variants.filter(item=>item.id!==variantId);return current;});return {...store,hash:variantStoreHash(store)};
429
+ }
430
+ async diffVariant(id,variantId,{revisionId}={}){const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId);return {projectId:id,variantId:variantId??'base',variant:selected.variant,project:selected.project,baseRevisionId:current.revisionId,baseContentHash:current.contentHash,variantStoreHash:variantStoreHash(selected.store)};}
431
+ async createPresetVariant(id,input){
432
+ const {action,expectedVariantRevision,...presetInput}=input;void action;
433
+ const current=await this.read(id),descriptor=variantAdapterForProject(current.project),useModulePreset=presetInput.preset!=='locale'&&descriptor?.variantPreset,generated=useModulePreset?descriptor.variantPreset(presetInput.preset):{},base=createPresetOverlay(current.project,presetInput),overlay={...generated};delete overlay.id;delete overlay.label;delete overlay.preset;
434
+ const variant=useModulePreset?{id:base.id,label:base.label,preset:base.preset,...overlay}:{...base,...overlay};
435
+ return this.upsertVariant(id,variant,{expectedVariantRevision});
436
+ }
437
+ async estimateBudget(id,{target='standalone-browser-draft',variantId,revisionId,fitTargetBudget=false}={}){
438
+ const networkTarget=assertNetworkTarget(target),current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),project=selected.project,assets=await lowerAssets(resolve(this.store.root,id),project.assets),runtime=projectUses3d(project)?await runtime3dBundle():await runtimeBundle(),runtimeHash=hash(runtime),key=buildCacheKey({project,target,runtimeHash,fitPolicyKey:fitTargetBudget?'fit-v1':'standard',deliveredAssetHashes:assets.map(asset=>asset.hash)}),cached=this.buildCache.peek(key);
439
+ const measured=cached?.manifest?.budget,html=measured?null:playableHTML({...project,assets},runtime,target==='standalone-browser-draft'?{}:{network:target}),budget=measured??exportBudget(project,assets,runtime,networkTarget,Buffer.byteLength(html),Buffer.byteLength(html)),status=!acceptsTargetBytes(networkTarget,budget.totalBytes)?'over':networkTarget.maxBytes!==null&&budget.totalBytes>=networkTarget.maxBytes*.95?'tight':'ok';
440
+ return {...budget,target,variantId:variantId??'base',fitTargetBudget,measurement:measured?'measured':'estimated',...(measured||networkTarget.packaging!=='zip'?{}:{estimateBasis:'uncompressed-html'}),status,unusedAssetCount:budget.perAsset.filter(asset=>asset.unused).length,topAssets:[...budget.perAsset].sort((a,b)=>b.rawBytes-a.rawBytes||a.id.localeCompare(b.id)).slice(0,3)};
441
+ }
442
+ async verifyExportEntry(id,current,project,target,{fitTargetBudget=false,confirmReviewed,preLoweredAssets,variant,expectedCopyChecks,browserProvider}={}){
443
+ const artifact=await this.build(id,project,target,{fitTargetBudget,preLoweredAssets}),[artifactCheck,creativeQaResult]=await Promise.all([this.verifyPackagedArtifact(id,artifact,target,{confirmReviewed}),this.runQa(id,{revisionId:current.revisionId,target,artifact,fitTargetBudget,reuseVideoReceipt:true,project,variant,preLoweredAssets,expectedCopyChecks,browserProvider})]),creativeQa=requireCreativeQa(creativeQaResult);
444
+ check(creativeQa.artifactHash===artifact.manifest.artifactHash,'E_CREATIVE_QA_HASH_MISMATCH');
445
+ const checks=[...artifact.manifest.checks,'creative-qa',...(target==='standalone-browser-draft'?[]:['rust-artifact-check'])];
446
+ return {target,artifact,creativeQa,artifactCheck,manifest:{...artifact.manifest,...(variant?{variantId:variant.id}:{}),accepted:current.accepted,creativeQa:{format:CREATIVE_QA_FORMAT,ok:true,blockers:0,warnings:creativeQa.warnings.length,artifactHash:creativeQa.artifactHash,evidencePath:creativeQa.immutableOutputDir},artifactCheck:{technicalStatus:artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:artifactCheck.ruleReviewStatus,ruleVerificationStatus:artifactCheck.ruleVerificationStatus,artifactHash:artifact.manifest.artifactHash},checks}};
447
+ }
448
+ async export(id,{revisionId,target,fitTargetBudget=false,variantId,confirmReviewed}){
449
+ check(typeof revisionId==='string','E_NATIVE_ARGUMENT');assertNetworkTarget(target);const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),verified=await this.verifyExportEntry(id,current,selected.project,target,{fitTargetBudget,confirmReviewed,variant:selected.variant});return {...verified.artifact,creativeQa:verified.creativeQa,artifactCheck:verified.artifactCheck,manifest:verified.manifest};
450
+ }
451
+ async exportBatch(id,{revisionId,targets,outputDir,fitTargetBudget=false,confirmReviewed,variantId}){
452
+ check(Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');for(const target of targets)assertNetworkTarget(target);
453
+ const current=await this.read(id,revisionId),selected=await this.selectVariant(id,current,variantId),preLoweredAssets=await lowerAssets(resolve(this.store.root,id),current.project.assets),resolvedDir=resolve(outputDir),browserProvider=this.browserProvider??getSharedBrowser;
454
+ if(!this.browserProvider)sharedBatchJobs++;
455
+ try{
456
+ const verified=await mapWithConcurrency(targets,defaultQaConcurrency(),target=>this.verifyExportEntry(id,current,selected.project,target,{fitTargetBudget,confirmReviewed,preLoweredAssets,variant:selected.variant,browserProvider}));
457
+ const exports=[];for(const row of verified){const filename=deliveryFilename(id,row.artifact,row.target),output=resolve(resolvedDir,row.target,filename);await writeAtomic(output,row.artifact.archiveBytes??row.artifact.html);exports.push({target:row.target,output,artifactHash:row.artifact.manifest.artifactHash,bytes:row.artifact.manifest.bytes,packaging:row.artifact.manifest.packaging,cacheHit:Boolean(row.creativeQa.cacheHit),artifactCheck:{technicalStatus:row.artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:row.artifactCheck.ruleReviewStatus},evidencePath:row.creativeQa.immutableOutputDir});}
458
+ return {status:'EXPORTED',projectId:id,variantId:variantId??'base',expected:{revisionId:current.revisionId,contentHash:current.contentHash},outputDir:resolvedDir,exports};
459
+ }finally{if(!this.browserProvider&&--sharedBatchJobs===0)await closeSharedBrowser();}
460
+ }
461
+ async exportVariantMatrix(id,{revisionId,variants,targets,outputDir,fitTargetBudget=false,confirmReviewed,onProgress,expectedCopyChecks}={}){
462
+ check(Array.isArray(variants)&&variants.length>=1&&variants.length<=128&&new Set(variants).size===variants.length&&Array.isArray(targets)&&targets.length>=1&&targets.length<=8&&new Set(targets).size===targets.length,'E_NATIVE_ARGUMENT');check(typeof outputDir==='string'&&outputDir.length>0,'E_AGENT_OUTPUT');for(const target of targets)assertNetworkTarget(target);
463
+ const current=await this.read(id,revisionId),store=await readVariants(resolve(this.store.root,id),current.project),validation=validateVariantStore(store,current.project,{failOnOrphans:false,failOnIncomplete:false});check(validation.valid,'E_NATIVE_VARIANT',validation);
464
+ const resolvedIds=[];
465
+ for(const requested of variants){
466
+ if(requested==='all')for(const item of store.variants){if(!resolvedIds.includes(item.id))resolvedIds.push(item.id);}
467
+ else if(!resolvedIds.includes(requested))resolvedIds.push(requested);
307
468
  }
308
- return {status:'EXPORTED',projectId:id,expected:{revisionId:current.revisionId,contentHash:current.contentHash},outputDir:resolvedDir,exports};
469
+ check(resolvedIds.length>=1&&resolvedIds.length<=128,'E_NATIVE_ARGUMENT');
470
+ const pinned={baseRevisionId:current.revisionId,baseContentHash:current.contentHash,variantStoreRevision:store.revision,variantStoreHash:variantStoreHash(store)},materializedVariants=resolvedIds.map(variantId=>{
471
+ if(variantId==='base')return {variantId:'base',variant:undefined,project:globalThis.structuredClone(current.project)};
472
+ const variant=store.variants.find(item=>item.id===variantId);check(variant,'E_NATIVE_NOT_FOUND');
473
+ return {variantId,variant,project:materializeVariant(current.project,variant)};
474
+ }),preLoweredAssets=await lowerAssets(resolve(this.store.root,id),current.project.assets),jobs=materializedVariants.flatMap(({variantId,variant,project})=>targets.map(target=>({variantId,variant,project,target}))),resolvedDir=resolve(outputDir),browserProvider=this.browserProvider??getSharedBrowser;
475
+ if(!this.browserProvider)sharedBatchJobs++;
476
+ try{
477
+ const entries=await mapWithConcurrency(jobs,defaultQaConcurrency(),async job=>{onProgress?.({status:'started',variantId:job.variantId,target:job.target});try{const verified=await this.verifyExportEntry(id,current,job.project,job.target,{fitTargetBudget,confirmReviewed,preLoweredAssets,variant:job.variant,expectedCopyChecks:expectedCopyChecks?.[job.variantId],browserProvider});onProgress?.({status:'passed',variantId:job.variantId,target:job.target});return {...job,status:'PASS',...verified};}catch(error){onProgress?.({status:'failed',variantId:job.variantId,target:job.target,error:error.message});return {...job,status:'FAIL',error:error.message,creativeQa:error.creativeQa,artifactCheck:error.artifactCheck};}});
478
+ const passing=entries.filter(entry=>entry.status==='PASS'),exports=[];for(const entry of passing){const folder=resolve(resolvedDir,entry.variantId,entry.target),filename=deliveryFilename(id,entry.artifact,entry.target),output=resolve(folder,filename);await writeAtomic(output,entry.artifact.archiveBytes??entry.artifact.html);exports.push({variantId:entry.variantId,target:entry.target,output,artifactHash:entry.artifact.manifest.artifactHash,bytes:entry.artifact.manifest.bytes,evidencePath:entry.creativeQa.immutableOutputDir,artifactCheck:{technicalStatus:entry.artifactCheck.report?.technicalStatus??'PASS',ruleReviewStatus:entry.artifactCheck.ruleReviewStatus}});}
479
+ const failures=entries.filter(entry=>entry.status==='FAIL').map(entry=>({variantId:entry.variantId,target:entry.target,error:entry.error,blockers:entry.creativeQa?.blockers??entry.artifactCheck?.findings??[]})),summary={format:'tora-variant-matrix-1',status:failures.length?'FAILED':'EXPORTED',projectId:id,...pinned,outputDir:resolvedDir,exports,failures,entries:entries.map(entry=>({variantId:entry.variantId,target:entry.target,status:entry.status,artifactHash:entry.artifact?.manifest.artifactHash,error:entry.error}))};await writeAtomic(resolve(resolvedDir,'matrix-summary.json'),JSON.stringify(summary));return summary;
480
+ }finally{if(!this.browserProvider&&--sharedBatchJobs===0)await closeSharedBrowser();}
309
481
  }
310
482
  }