@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,30 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import {resolve} from 'node:path';
3
+ import {fileURLToPath,URL} from 'node:url';
4
+ import {check,exact,identifier} from './document.mjs';
5
+ import {registerSource} from './assets.mjs';
6
+ import {validateAssetPolicy} from './asset-policy.mjs';
7
+ import {loadCatalog} from './catalog-cache.mjs';
8
+
9
+ const root=fileURLToPath(new URL('../../../',import.meta.url));
10
+ export async function catalogAudio(){return (await loadCatalog()).audioFiles;}
11
+
12
+ export async function stageAudio(service,id,imports,{optimize}={}){
13
+ check(Array.isArray(imports)&&imports.length<=8,'E_REVIEW_IMPORT');
14
+ if(!imports.length)return [];
15
+ const catalog=await catalogAudio(),operations=[];
16
+ for(const item of imports){
17
+ check(exact(item,['catalogId','assetId'])&&identifier(item.assetId),'E_REVIEW_IMPORT');
18
+ const choice=catalog.find(cue=>cue.catalogId===item.catalogId);
19
+ check(choice,'E_REVIEW_IMPORT');
20
+ const {source,file}=choice;
21
+ const provenance={origin:'third-party-free',sourceId:source.id,sourceFile:file.path,sourceHash:file.sha256,author:source.author,license:source.license,sourceUrl:source.sourceUrl,styleFamily:source.styleFamily};
22
+ const data=(await readFile(resolve(root,file.file))).toString('base64');
23
+ const receipt=validateAssetPolicy({mime:file.mime,data,provenance},{role:'audio'});
24
+ const rights=[source.author+', '+source.license+'. '+source.sourceUrl,receipt.attribution].filter(Boolean).join('\n');
25
+ const asset=await registerSource(resolve(service.store.root,id),{id:item.assetId,mime:file.mime,data,rights,...(optimize?{optimize}:{})});
26
+ const record={...asset};delete record.optimization;
27
+ operations.push({kind:'registerAsset',asset:{...record,provenance:JSON.stringify(receipt)}});
28
+ }
29
+ return operations;
30
+ }
@@ -1,9 +1,22 @@
1
1
  /** Lazy, crash-recovering Playwright Chromium manager for local authoring/QA. */
2
+ import {cpus} from 'node:os';
3
+ import process from 'node:process';
2
4
  import {setTimeout,clearTimeout} from 'node:timers';
3
5
 
4
6
  const IDLE_MS=5*60*1000;
5
7
  let browser=null,launching=null,idleTimer=null;
6
8
 
9
+ export function defaultQaConcurrency(){
10
+ const override=process.env.TORA_QA_CONCURRENCY;
11
+ if(override!==undefined){
12
+ if(!/^[1-9][0-9]*$/.test(override))throw Error('E_QA_CONCURRENCY');
13
+ const value=Number(override);
14
+ if(!Number.isSafeInteger(value))throw Error('E_QA_CONCURRENCY');
15
+ return value;
16
+ }
17
+ return Math.min(4,Math.max(1,cpus().length-1));
18
+ }
19
+
7
20
  function scheduleIdleClose(){
8
21
  if(idleTimer)clearTimeout(idleTimer);
9
22
  idleTimer=setTimeout(()=>{void closeSharedBrowser();},IDLE_MS);
@@ -43,3 +56,24 @@ export async function closeSharedBrowser(){
43
56
  await current.close?.().catch(()=>{});
44
57
  }
45
58
  }
59
+
60
+ function isDisconnectFailure(instance,error){
61
+ if(instance?.isConnected?.()===false)return true;
62
+ return /(?:browser|context|target|connection).*(?:disconnect|closed)|(?:disconnect|closed).*(?:browser|context|target|connection)/i.test(error?.message??'');
63
+ }
64
+
65
+ export async function withBrowserContext(run,{launcher,contextOptions}={}){
66
+ let recovered=false;
67
+ while(true){
68
+ const instance=await getSharedBrowser(launcher);let context;
69
+ try{
70
+ context=await instance.newContext(contextOptions);
71
+ return await run(context,instance);
72
+ }catch(error){
73
+ if(recovered||!isDisconnectFailure(instance,error))throw error;
74
+ recovered=true;
75
+ }finally{
76
+ if(context)await context.close?.().catch(()=>{});
77
+ }
78
+ }
79
+ }
@@ -1,6 +1,6 @@
1
1
  import {createHash,randomUUID} from 'node:crypto';
2
2
  import {mkdir,readdir,rename,rm,stat,writeFile} from 'node:fs/promises';
3
- import {resolve} from 'node:path';
3
+ import {isAbsolute,relative,resolve} from 'node:path';
4
4
  import {canonical,projectContent} from '../../../packages/creative-project/src/canonical.mjs';
5
5
  import {safeFile} from './assets.mjs';
6
6
  import {assertStorePath} from './store-path.mjs';
@@ -11,10 +11,14 @@ export function buildCacheKey({project,target,runtimeHash,fitPolicyKey='standard
11
11
  return digest(canonical({format:'tora-build-cache-2',revisionId:project.revisionId,contentHash:digest('tora-v2-hash/1\ndocument-content\n'+canonical(projectContent(project))),target,runtimeHash,fitPolicyKey,deliveredAssetHashes}));
12
12
  }
13
13
  export class NativeBuildCache{
14
- constructor({maxEntries=16}={}){
14
+ constructor({maxEntries=64}={}){
15
15
  if(!Number.isSafeInteger(maxEntries)||maxEntries<1)throw Error('E_NATIVE_CACHE_ARGUMENT');
16
16
  this.maxEntries=maxEntries;this.entries=new Map();this.inFlight=new Map();this.counters={hits:0,misses:0,inFlightDedupes:0};
17
17
  }
18
+ peek(key){
19
+ if(!this.entries.has(key))return null;
20
+ return {...this.entries.get(key),cacheHit:true};
21
+ }
18
22
  async getOrBuild(key,buildFn){
19
23
  if(this.entries.has(key)){
20
24
  const value=this.entries.get(key);this.entries.delete(key);this.entries.set(key,value);this.counters.hits++;
@@ -35,12 +39,12 @@ export class NativeBuildCache{
35
39
  stats(){return {...this.counters};}
36
40
  }
37
41
  export class VerificationReceiptCache{
38
- constructor(storeRoot,{maxFiles=64}={}){
42
+ constructor(storeRoot,{maxFiles=512}={}){
39
43
  if(!Number.isSafeInteger(maxFiles)||maxFiles<1)throw Error('E_NATIVE_CACHE_ARGUMENT');
40
44
  this.root=resolve(storeRoot,'.cache','verify');this.maxFiles=maxFiles;
41
45
  }
42
- receiptKey({artifactHash,checkerVersion,kind,viewport,host,scenario}){
43
- return digest(canonical({format:VERIFICATION_CACHE_VERSION,artifactHash,checkerVersion,kind,viewport:viewport??'',host:host??'',scenario:scenario??''}));
46
+ receiptKey({artifactHash,checkerVersion,kind,viewport,host,scenario,qaTier='full',artifactCheckVersion}){
47
+ return digest(canonical({format:VERIFICATION_CACHE_VERSION,artifactHash,checkerVersion,kind,viewport:viewport??'',host:host??'',scenario:scenario??'',qaTier,artifactCheckVersion:artifactCheckVersion??''}));
44
48
  }
45
49
  path(key){
46
50
  if(typeof key!=='string'||!/^sha256:[a-f0-9]{64}$/.test(key))throw Error('E_NATIVE_CACHE_KEY');
@@ -69,4 +73,31 @@ export class VerificationReceiptCache{
69
73
  }
70
74
  return payload;
71
75
  }
76
+ async pruneOrphanedArtifactDirs(qaByArtifactRoot){
77
+ await assertStorePath(this.root);
78
+ let names;
79
+ try{names=(await readdir(this.root)).filter(name=>/^[a-f0-9]{64}\.json$/.test(name)).sort();}
80
+ catch(error){if(error.code!=='ENOENT')throw error;names=[];}
81
+ if(names.length>this.maxFiles)return [];
82
+ const referenced=[];
83
+ for(const name of names){
84
+ try{
85
+ const envelope=JSON.parse((await safeFile(resolve(this.root,name))).toString());
86
+ if(envelope?.format!==VERIFICATION_CACHE_VERSION||envelope.key!=='sha256:'+name.slice(0,-5)||typeof envelope.payload?.outputDir!=='string')continue;
87
+ referenced.push(resolve(envelope.payload.outputDir));
88
+ }catch{/* ignore invalid receipts */}
89
+ }
90
+ const root=resolve(qaByArtifactRoot);await assertStorePath(root);
91
+ let entries;
92
+ try{entries=await readdir(root,{withFileTypes:true});}
93
+ catch(error){if(error.code==='ENOENT')return [];throw error;}
94
+ const contains=(parent,child)=>{const rel=relative(parent,child);return rel===''||!rel.startsWith('..')&&!isAbsolute(rel);};
95
+ const removed=[];
96
+ for(const entry of entries.filter(entry=>entry.isDirectory()).sort((a,b)=>a.name.localeCompare(b.name)).slice(0,this.maxFiles)){
97
+ const path=resolve(root,entry.name);
98
+ if(referenced.some(output=>contains(path,output)||contains(output,path)))continue;
99
+ await rm(path,{recursive:true,force:true});removed.push(path);
100
+ }
101
+ return removed;
102
+ }
72
103
  }
@@ -1,4 +1,5 @@
1
1
  import {networkTargets,targets} from './network-targets.mjs';
2
+ import {schemaEvents,schemaActions} from './schema-vocabulary.mjs';
2
3
  /** Pinned declarative vocabulary. No runtime code or property paths supplied by authors. */
3
4
  export const limits={objects:512,components:512,scenes:16,bindings:512,variables:128,operations:256,transactionBytes:1048576,documentBytes:4194304,depth:64,nodes:100000,instances:128,particles:256,eventsPerFrame:256,actionsPerFrame:1024,runtimeNodes:4096,colliders:256,collisionPairsPerFrame:4096,gameplay:512,eventBindings:512,physicsBodies:64,physicsSubsteps:16,sceneChangeDelaySeconds:10,pathNodes:64,pathEdges:128,pathAgents:64};
4
5
  const number=(value,min=-10000,max=10000)=>({type:'number',default:value,min,max});
@@ -9,7 +10,7 @@ const enumeration=(value,options)=>({type:'enum',default:value,options});
9
10
  const arrayOf=(type,minItems,maxItems)=>({type,default:[],minItems,maxItems});
10
11
  const common={width:number(80,0,4096),height:number(80,0,4096),visible:boolean(true),opacity:number(1,0,1)};
11
12
  const paint={fill:color('#ffc857'),stroke:color('#193b46'),strokeWidth:number(0,0,64),pixelFrame:{...boolean(false),optional:true}};
12
- const typography={text:text('Text'),fontSize:number(24,6,240),fontFamily:enumeration('sans-serif',['sans-serif','serif','monospace','pixel']),fontWeight:enumeration('700',['400','600','700','900']),align:enumeration('center',['left','center','right']),color:color('#ffffff'),wrap:{...boolean(true),optional:true},autoFit:{...boolean(true),optional:true},minFontSize:{...number(12,8,120),optional:true},padding:{...number(4,0,64),optional:true},lineHeight:{...number(1.2,.9,2.5),optional:true},pixelPanel:{...boolean(false),optional:true},panelFill:{...color('#3c2933'),optional:true},panelStroke:{...color('#ffe6ab'),optional:true}};
13
+ const typography={text:text('Text'),fontSize:number(24,6,240),fontFamily:enumeration('sans-serif',['sans-serif','serif','monospace','pixel']),fontWeight:enumeration('700',['400','600','700','900']),align:enumeration('center',['left','center','right']),direction:{...enumeration('auto',['auto','ltr','rtl']),optional:true},color:color('#ffffff'),wrap:{...boolean(true),optional:true},autoFit:{...boolean(true),optional:true},minFontSize:{...number(12,8,120),optional:true},padding:{...number(4,0,64),optional:true},lineHeight:{...number(1.2,.9,2.5),optional:true},pixelPanel:{...boolean(false),optional:true},panelFill:{...color('#3c2933'),optional:true},panelStroke:{...color('#ffe6ab'),optional:true}};
13
14
  const spriteProperties={fit:enumeration('contain',['contain','cover','stretch']),frameCount:{...number(2,1,16),integer:true},frameColumns:{...number(2,1,16),integer:true},frameRate:number(3,0,24)};
14
15
  export const mesh3dSlots=['source','texture','normalMap','emissiveMap'];
15
16
  const optionalProperties=properties=>Object.fromEntries(Object.entries(properties).map(([key,descriptor])=>[key,{...descriptor,optional:true}]));
@@ -34,11 +35,12 @@ oscillate:{axis:enumeration('x',['x','y']),amplitude:number(64,0,1024),periodSec
34
35
  'aim-launch-3d':{stageId:text('',96),dragMode:enumeration('anywhere',['on-body','anywhere']),dragScale:number(2.8,.2,20),minPullPx:number(10,4,100),maxSpeed:number(9,.5,50),minSpeed:number(.35,.05,10),hitRadiusPx:number(85,20,400),showTrajectory:boolean(true),trajectoryDots:{...number(15,3,24),integer:true},powerVariableId:{...text('',96),optional:true}},
35
36
  'capture-zone-3d':{radius:number(.23,.05,3),maxCaptureSpeed:number(3.1,.2,20),heightTolerance:number(.16,.02,2),holdSeconds:number(1.55,0,5)},
36
37
  'fps-controller-3d':{x:number(0,-500,500),y:number(1.6,-500,500),z:number(6,-500,500),yaw:number(0,-6.2832,6.2832),pitch:number(0,-1.4,1.4),minYaw:{...number(-6.2832,-6.2832,6.2832),optional:true},maxYaw:{...number(6.2832,-6.2832,6.2832),optional:true},minPitch:{...number(-.75,-1.4,0),optional:true},maxPitch:{...number(.75,0,1.4),optional:true},moveSpeed:number(5.5,0,50),lookSensitivity:number(.006,.0005,.05),playerRadius:{...number(.45,.1,2),optional:true},boundsX:{...number(12,.5,100),optional:true},boundsZ:{...number(12,.5,100),optional:true},joystickBehaviorId:{...text('',96),optional:true},aimJoystickBehaviorId:{...text('',96),optional:true},aimMode:{...enumeration('delta',['delta','rate']),optional:true},aimTurnSpeed:{...number(1.8,.1,10),optional:true},invertAimY:{...boolean(false),optional:true},moveXVariableId:{...text('',96),optional:true},moveYVariableId:{...text('',96),optional:true},lookMode:{...enumeration('drag',['drag','none']),optional:true},bobAmplitude:{...number(.04,0,.25),optional:true}},
37
- 'steer-3d':{mode:enumeration('chase-camera',['chase-camera','strafe-camera','patrol']),speed:number(2.2,.1,50),stopDistance:{...number(2.5,0,50),optional:true},faceCamera:{...boolean(true),optional:true},boundsX:{...number(12,.5,100),optional:true},boundsZ:{...number(12,.5,100),optional:true}}};
38
+ 'steer-3d':{mode:enumeration('chase-camera',['chase-camera','strafe-camera','patrol']),speed:number(2.2,.1,50),stopDistance:{...number(2.5,0,50),optional:true},faceCamera:{...boolean(true),optional:true},boundsX:{...number(12,.5,100),optional:true},boundsZ:{...number(12,.5,100),optional:true}},
39
+ 'ui-anchor-3d':{targetId:text('',96),anchor:{...enumeration('center',['center','top','bottom']),optional:true},offsetX:{...number(0,-1024,1024),optional:true},offsetY:{...number(0,-1024,1024),optional:true},fitToProjectedBounds:{...boolean(false),optional:true},paddingPx:{...number(10,0,128),optional:true},minSizePx:{...number(48,16,512),optional:true},maxSizePx:{...number(260,32,1024),optional:true},squareBounds:{...boolean(false),optional:true},showHighlight:{...boolean(false),optional:true},highlightStyle:{...enumeration('pulse-ring',['ring','pulse-ring','box']),optional:true},highlightColor:{...color('#fff0bd'),optional:true},syncVisibility:{...boolean(true),optional:true},offscreen:{...enumeration('hide',['hide','clamp','none']),optional:true}}};
38
40
  for(const contract of Object.values(contracts)){contract.validationVersion=1;contract.migrationVersion=1;contract.dependencies=['sceneId','parentId','assetSlots[].assetId'];for(const [key,descriptor]of Object.entries(contract.properties)){descriptor.label=key.replace(/[A-Z]/g,letter=>' '+letter.toLowerCase()).replace(/^./,letter=>letter.toUpperCase());descriptor.group=['width','height'].includes(key)?'Dimensions':['text','fontSize','fontFamily','fontWeight','align','color'].includes(key)?'Typography':'Appearance';if(descriptor.type==='number')descriptor.units=({opacity:'normalized',frameCount:'frames',frameColumns:'columns',frameRate:'frames / second'})[key]??'pixels';}}
39
- for(const params of Object.values(behaviors))for(const [key,descriptor]of Object.entries(params)){descriptor.label=key.replace(/^./,letter=>letter.toUpperCase());if(descriptor.type==='number')descriptor.units=({seconds:'seconds',volume:'normalized',count:'count',frequency:'Hz',vx:'pixels / second',vy:'pixels / second',gravity:'pixels / second²',speed:'pixels / second',direction:'degrees'})[key]??'scalar';}
40
- export const events=['click','sceneEnter','sceneExit','timer','contactBegin','contactEnd','boundaryExit','variableChange','validMatch','invalidMatch','matchClear','pointerUp','dragStart','dragDrop','dragReject','swipe','holdStart','holdRelease','joystickStart','joystickEnd','launch','bodyBounce','bodyRest','bodyJump','zoneCapture','pathArrive','pathBlocked','instanceDepleted','strokeStart','strokeEnd','sliceHit','maskProgress','maskComplete','jointBreak','raycastHit3d','raycastMiss3d','modelAnimationEnd'];
41
- export const actions={setComponent:['componentId','key','value','valueVariableId'],setAsset:['componentId','assetId','slotId'],resetMatch:['componentId'],hintMatch:['componentId'],copyMatchAsset:['componentId','boardId'],set:['variableId','value'],add:['variableId','value'],spawn:['prototypeId','x','y'],despawn:['target'],moveToComponent:['componentId','targetComponentId','seconds','target'],returnToOrigin:['componentId','seconds'],random:['variableId','min','max','integer'],modifyInstanceState:['target','componentId','field','op','value','variableId'],launchToward:['componentId','targetMode','targetComponentId','team','angleVariableId','speed','speedVariableId','orientToVelocity'],changeScene:['sceneId','delaySeconds'],animate:['behaviorId'],stopAnimation:['behaviorId'],emit:['behaviorId'],playAudio:['behaviorId'],cameraShake:['intensity','seconds'],screenFlash:['color','opacity','seconds'],floatingText:['text','componentId','color','fontSize','risePx','seconds'],setVelocity:['componentId','vx','vy','vxVariableId','vyVariableId'],applyImpulse:['componentId','ix','iy','vxVariableId','vyVariableId'],setPosition:['componentId','x','y','xVariableId','yVariableId'],stopBody:['componentId'],setPathEdge:['behaviorId','edgeId','enabled','cost'],setPathTarget:['componentId','targetNode'],setPathGate:['behaviorId','mode','holdSeconds'],spawnOnPath:['prototypeId','networkBehaviorId','startNode','targetNode'],spawnAt:['prototypeId','targetComponentId','offsetX','offsetY','at','jitterX','jitterY','count','countVariableId'],compute:['variableId','op','value','operandVariableId','round','min','max'],clearStrokes:['componentId'],resetMask:['componentId'],raycast3d:['stageId','mode','maxDistance','targetTeam'],spawnAt3d:['prototypeId','fromComponentId','fromTeam','x','y','z','offsetX','offsetY','offsetZ','jitterX','jitterZ','count'],playModelAnimation:['componentId','clipName','loop','speed','fadeSeconds','restart'],restart:[],store:[]};
41
+ for(const params of Object.values(behaviors))for(const [key,descriptor]of Object.entries(params)){descriptor.label=key.replace(/^./,letter=>letter.toUpperCase());if(descriptor.type==='number')descriptor.units=({seconds:'seconds',volume:'normalized',count:'count',frequency:'Hz',vx:'pixels / second',vy:'pixels / second',gravity:'pixels / second²',speed:'pixels / second',direction:'degrees',offsetX:'pixels',offsetY:'pixels',paddingPx:'pixels',minSizePx:'pixels',maxSizePx:'pixels'})[key]??'scalar';}
42
+ export const events=schemaEvents;
43
+ export const actions=schemaActions;
42
44
  export const operations=['createScene','renameScene','deleteScene','createComponent','renameComponent','duplicateComponent','deleteComponent','setParameter','setTransform','setPrototype','registerAsset','replaceAsset','reorderComponent','reparentComponent','group','ungroup','putVariable','deleteVariable','putBehavior','deleteBehavior','putEvent','deleteEvent','putBinding','deleteBinding','setStartScene','setStore'];
43
45
  export function validateValue(d,v){
44
46
  if(d.type==='number')return Number.isFinite(v)&&v>=d.min&&v<=d.max&&(!d.integer||Number.isInteger(v));
@@ -57,7 +59,7 @@ const packDefinitions={
57
59
  'canvas-physics':{description:'Continuous canvas input and stable 2D physics',behaviors:['erase-mask','draw-stroke','physics-body','physics-joint','aim-launch','capture-zone','oscillate'],events:['launch','bodyBounce','bodyRest','bodyJump','zoneCapture','strokeStart','strokeEnd','sliceHit','maskProgress','maskComplete','jointBreak'],actions:['setVelocity','applyImpulse','setPosition','stopBody','clearStrokes','resetMask']},
58
60
  'match-board':{description:'Deterministic Match-3 boards and tiles',behaviors:['match-board','match-tile'],events:['validMatch','invalidMatch','matchClear'],actions:['resetMatch','hintMatch','copyMatchAsset']},
59
61
  'path-network':{description:'Dijkstra path networks, agents and gates',behaviors:['path-network','path-agent','path-gate'],events:['pathArrive','pathBlocked'],actions:['setPathEdge','setPathTarget','setPathGate','spawnOnPath']},
60
- '3d':{description:'3D stages, meshes, animations, FPS controller, hitscan raycasting, steering and physics',contracts:['native.stage3d.v1','native.mesh3d.v1'],behaviors:['physics-3d','animate-3d','oscillate-3d','aim-launch-3d','capture-zone-3d','fps-controller-3d','steer-3d'],events:['launch','bodyBounce','bodyRest','bodyJump','zoneCapture','raycastHit3d','raycastMiss3d','modelAnimationEnd'],actions:['raycast3d','spawnAt3d','playModelAnimation']},
62
+ '3d':{description:'3D stages, meshes, animations, 3D-to-UI anchoring, FPS controller, hitscan raycasting, steering and physics',contracts:['native.stage3d.v1','native.mesh3d.v1'],behaviors:['physics-3d','animate-3d','oscillate-3d','aim-launch-3d','capture-zone-3d','fps-controller-3d','steer-3d','ui-anchor-3d'],events:['launch','bodyBounce','bodyRest','bodyJump','zoneCapture','raycastHit3d','raycastMiss3d','modelAnimationEnd'],actions:['raycast3d','spawnAt3d','playModelAnimation']},
61
63
  };
62
64
  export const capabilityPacks=Object.freeze(Object.fromEntries(Object.entries(packDefinitions).map(([id,pack])=>[id,Object.freeze({id,...pack})])));
63
65
  export const availablePacks=Object.values(capabilityPacks).map(pack=>({...pack,guide:pack.id==='core'?'docs/reference/CORE_AUTHORING.md':`docs/reference/packs/${pack.id}.md`}));
@@ -7,7 +7,7 @@ import {Buffer} from 'node:buffer';
7
7
  import {setTimeout} from 'node:timers';
8
8
  import process from 'node:process';
9
9
  import {loadCatalog} from './catalog-cache.mjs';
10
- import {moduleForProject} from './modules/index.mjs';
10
+ import {qaAdapterForProject} from './qa-adapters.mjs';
11
11
  import {builtInPlaythrough} from './outcome-playthrough.mjs';
12
12
  import {isAudioMime,validateGlbHeader} from './media-validate.mjs';
13
13
  import {glbBudgetInfo} from './export-budget.mjs';
@@ -26,7 +26,7 @@ export const DEFAULT_VIEWPORTS=Object.freeze([
26
26
 
27
27
  const stateOrder=['opening','after-first-input','end-card','timeout'];
28
28
  const pixelGlyphs=new Set([...'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?.:,+-/\' ']);
29
- const layoutBlockers=new Set(['stage-overflow','parent-clip-crop','text-overflow','text-illegible','touch-target-small','interactive-overlap','sdk-safe-area-collision','panel-off-center','panel-edge-cramped','backdrop-incomplete','panel-content-overlap','duplicate-visible-copy','header-off-center']);
29
+ const layoutBlockers=new Set(['stage-overflow','parent-clip-crop','text-overflow','text-clipped','rtl-alignment','text-illegible','touch-target-small','interactive-overlap','sdk-safe-area-collision','panel-off-center','panel-edge-cramped','backdrop-incomplete','panel-content-overlap','duplicate-visible-copy','header-off-center','anchor-3d-target-offscreen','anchor-3d-misaligned','anchor-3d-occluded']);
30
30
  const roleWords={
31
31
  win:['win','won','winner','success','successful','victory','victorious','complete','completed','completion','goal','payoff'],
32
32
  loss:['loss','lose','lost','failure','failed','fail','gameover','timeout','deadline'],
@@ -613,7 +613,7 @@ async function openPlaywrightSession({html,htmlPath,project,primaryComponentId,n
613
613
  const playEnding=async(targetPage,session)=>{
614
614
  const current=await readProject(targetPage);
615
615
  if(!current)return {available:false,required:false};
616
- const {win,timeout}=endingScenes(current),{descriptor}=moduleForProject(current);
616
+ const {win,timeout}=endingScenes(current),descriptor=qaAdapterForProject(current);
617
617
  if(descriptor?.qa?.playToEndCard)return {...await descriptor.qa.playToEndCard(targetPage,current),required:true};
618
618
  if(!win.length)return {available:false,required:false};
619
619
  const play=builtInPlaythrough(current);
@@ -706,15 +706,35 @@ async function openPlaywrightSession({html,htmlPath,project,primaryComponentId,n
706
706
  const bindings=new Map(current.eventBindings.map(binding=>[binding.eventId,binding]));
707
707
  const multiply=(a,b)=>[a[0]*b[0]+a[2]*b[1],a[1]*b[0]+a[3]*b[1],a[0]*b[2]+a[2]*b[3],a[1]*b[2]+a[3]*b[3],a[0]*b[4]+a[2]*b[5]+a[4],a[1]*b[4]+a[3]*b[5]+a[5]];
708
708
  const clickEvents=current.events.filter(event=>event.kind==='click'&&byId.has(event.componentId));
709
- const liveState=activeScene?globalThis.toraRuntime?.state?.():null;
710
- const scene=liveState?.scene??current.base.startScene;
709
+ const liveState=globalThis.toraRuntime?.state?.()??null;
710
+ const liveAudit=globalThis.toraRuntime?.auditSceneLayout?.()??null;
711
+ const anchor3dByComp=new Map((current.gameplay??[]).filter(behavior=>behavior.kind==='ui-anchor-3d').map(behavior=>[behavior.componentId,behavior.parameters]));
712
+ const liveAnchorByComp=new Map((liveAudit?.anchors3d??[]).map(row=>[row.id,row]));
713
+ const liveInteractiveById=new Map((liveAudit?.interactive??[]).map(row=>[row.id,row]));
714
+ const scene=(activeScene?liveState?.scene:undefined)??current.base.startScene;
711
715
  const parameters=component=>({...component.parameters,...liveState?.components?.[component.id]?.parameters});
716
+ const nodeChainVisible=startNode=>{
717
+ for(let node=startNode;node;node=byId.get(node.parentId)){
718
+ const params=parameters(node);
719
+ if(params.visible===false||params.opacity===0)return false;
720
+ }
721
+ return true;
722
+ };
712
723
  const eligible=event=>{
713
724
  const component=byId.get(event.componentId);
714
725
  if(component.sceneId!==scene||component.prototype||parameters(component).enabled===false)return false;
715
726
  for(let node=component;node;node=byId.get(node.parentId)){
716
727
  const params=parameters(node);
717
728
  if(params.visible===false||params.opacity===0)return false;
729
+ const anchorCfg=anchor3dByComp.get(node.id);
730
+ if(anchorCfg){
731
+ if(anchorCfg.syncVisibility!==false){
732
+ const targetNode=byId.get(anchorCfg.targetId);
733
+ if(!targetNode||!nodeChainVisible(targetNode))return false;
734
+ }
735
+ const liveAnchor=liveAnchorByComp.get(node.id);
736
+ if(liveAnchor&&!liveAnchor.visible)return false;
737
+ }
718
738
  }
719
739
  return true;
720
740
  };
@@ -762,7 +782,14 @@ async function openPlaywrightSession({html,htmlPath,project,primaryComponentId,n
762
782
  const matrix=world(component),{width,height}=parameters(component);
763
783
  const screen=pt=>({x:rect.left+offsetX+pt.x*scale,y:rect.top+offsetY+pt.y*scale});
764
784
  const liveMatches=candidates[0]?.fromInstance?liveInstances.filter(instance=>instance.prototypeId===component.id):[];
765
- const center=liveMatches.length?{x:liveMatches[0].x+width/2,y:liveMatches[0].y+height/2}:{x:matrix[0]*width/2+matrix[2]*height/2+matrix[4],y:matrix[1]*width/2+matrix[3]*height/2+matrix[5]};
785
+ const liveRow=!liveMatches.length?liveInteractiveById.get(component.id):undefined;
786
+ const liveAnchorBounds=!liveMatches.length?liveAnchorByComp.get(component.id)?.overlayBounds:undefined;
787
+ const liveBounds=liveRow?.bounds??liveAnchorBounds;
788
+ const center=liveMatches.length
789
+ ?{x:liveMatches[0].x+width/2,y:liveMatches[0].y+height/2}
790
+ :liveBounds
791
+ ?{x:(liveBounds.left+liveBounds.right)/2,y:(liveBounds.top+liveBounds.bottom)/2}
792
+ :{x:matrix[0]*width/2+matrix[2]*height/2+matrix[4],y:matrix[1]*width/2+matrix[3]*height/2+matrix[5]};
766
793
  const start=screen(center),kind=candidates[0]?.kind;
767
794
  if(kind==='drag'){
768
795
  if(liveMatches.length>1&&current.gameplay.some(behavior=>behavior.kind==='drop-zone'&&behavior.componentId===component.id)){
@@ -804,7 +831,7 @@ async function openPlaywrightSession({html,htmlPath,project,primaryComponentId,n
804
831
  async enterTimeout(){
805
832
  const current=await readProject(page);
806
833
  if(!current)return {available:false,required:false};
807
- const {descriptor}=moduleForProject(current),{timeout}=endingScenes(current);
834
+ const descriptor=qaAdapterForProject(current),{timeout}=endingScenes(current);
808
835
  const phaseVariable=descriptor?.qa?.phaseVariable??null;
809
836
  const lossBindings=current.eventBindings.filter(binding=>binding.actions.some(
810
837
  action=>action.kind==='changeScene'&&timeout.includes(action.sceneId),
@@ -1126,6 +1153,8 @@ function layoutRemediation(kind){
1126
1153
  'stage-overflow':'Move or resize the component so its transformed bounds remain inside the stage.',
1127
1154
  'parent-clip-crop':'Resize the child or clipping parent so no visible content is cut off.',
1128
1155
  'text-overflow':'Enable wrapping or auto-fit and enlarge the text container without reducing legibility.',
1156
+ 'text-clipped':'Increase the text container height or reduce copy so no rendered lines are clipped.',
1157
+ 'rtl-alignment':'Use right or center alignment for right-to-left copy and verify the rendered direction.',
1129
1158
  'text-illegible':'Increase the effective text size and contrast to a readable phone presentation.',
1130
1159
  'touch-target-small':'Provide at least a 44 by 44 CSS-pixel interactive hit area.',
1131
1160
  'interactive-overlap':'Separate interactive hit areas or change stacking so each target is unambiguous.',
@@ -1138,9 +1167,18 @@ function layoutRemediation(kind){
1138
1167
  'text-clutter-heavy':'Cut narration and tutorial prose; playable ads are an experience, not a tutorial. Keep screens to concise visual cues and short punchy labels.',
1139
1168
  'particle-style-clash':'Match particle shape to the playable art direction (use circle/square for vector art; reserve pixel-confetti for pixel art).',
1140
1169
  'header-off-center':'Align centered banner or instruction text horizontally with the panel directly below it in both portrait and landscape.',
1170
+ 'anchor-3d-target-offscreen':'Adjust the 3D camera, landscapeCamera settings, or 3D mesh position so every anchored 3D target remains clearly inside all portrait and landscape viewports.',
1171
+ 'anchor-3d-misaligned':'Keep each anchored 2D UI overlay aligned with its projected 3D target bounds (reduce offsetX/offsetY or enable fitToProjectedBounds).',
1172
+ 'anchor-3d-occluded':'Reposition the 3D camera, target mesh, or blocking foreground 3D mesh so the anchored target is unobstructed across portrait and landscape viewports.',
1141
1173
  })[kind]??'Repair the reported layout defect and rerun the viewport audit.';
1142
1174
  }
1143
- function addLayoutReport(audit,viewport,state,blockers,warnings){
1175
+ function addLayoutReport(audit,viewport,state,blockers,warnings,expectedCopy){
1176
+ if(expectedCopy){
1177
+ const expected=Array.isArray(expectedCopy)?expectedCopy:expectedCopy.include??[];
1178
+ for(const text of expected)if(typeof text!=='string'||!text.trim()||!audit?.texts?.some(row=>row.text.trim()===text.trim()))blockers.push(issue('blocker','localized-copy-missing',null,'Ensure every required localized string is visibly rendered in its intended state.',{viewport,detail:`Required copy was not rendered during ${state}: ${text}`,metrics:{state,expected:text}}));
1179
+ for(const text of Array.isArray(expectedCopy)?[]:expectedCopy.exclude??[])if(audit?.texts?.some(row=>row.text.trim()===String(text).trim()))blockers.push(issue('blocker','localized-copy-leaked',null,'Remove stale source-language copy from the localized state.',{viewport,detail:`Excluded copy was rendered during ${state}: ${text}`,metrics:{state,excluded:text}}));
1180
+ }
1181
+ if(expectedCopy&&(!audit||!Array.isArray(audit.texts)))return;
1144
1182
  if(!audit){
1145
1183
  warnings.push(issue('warning','layout-audit-unavailable',null,'Expose toraRuntime.auditSceneLayout() so clipping, text, hit-area, overlap, and safe-zone checks can run.',{viewport,detail:`No layout audit API was available for ${state}.`}));
1146
1184
  return;
@@ -1202,7 +1240,21 @@ export async function runBrowserQa(options={}){
1202
1240
  if(!outputDir)throw Error('A deterministic output directory is required');
1203
1241
  if(!htmlPath&&typeof options.html!=='string'&&typeof options.htmlString!=='string')throw Error('Supply an HTML artifact path or HTML string');
1204
1242
  const html=typeof options.html==='string'?options.html:typeof options.htmlString==='string'?options.htmlString:await readFile(htmlPath,'utf8');
1205
- const project=options.project??projectFromHtml(html),blockers=[],warnings=[],interactions=[],states=[],screenshots=[],storeChecks={};
1243
+ const project=options.project??projectFromHtml(html),blockers=[],warnings=[],interactions=[],states=[],screenshots=[],storeChecks={},anchors3dChecks=[];
1244
+ const compactRect=rect=>rect?{left:Math.round(rect.left*10)/10,top:Math.round(rect.top*10)/10,right:Math.round(rect.right*10)/10,bottom:Math.round(rect.bottom*10)/10}:null;
1245
+ const recordAnchors3d=(result,viewport,state)=>{
1246
+ if(!Array.isArray(result?.anchors3d)||!result.anchors3d.length)return;
1247
+ anchors3dChecks.push({
1248
+ viewport:normalizeViewport(viewport),state,
1249
+ anchors:result.anchors3d.map(row=>({
1250
+ id:row.id,targetId:row.targetId,visible:Boolean(row.visible),
1251
+ behindCamera:Boolean(row.behindCamera),offscreen:Boolean(row.offscreen),
1252
+ clippedFraction:row.clippedFraction,occluded:Boolean(row.occluded),
1253
+ ...(row.occluderId?{occluderId:row.occluderId}:{}),
1254
+ targetBounds:compactRect(row.targetBounds),overlayBounds:compactRect(row.overlayBounds),
1255
+ })),
1256
+ });
1257
+ };
1206
1258
  let contactSheets=[],motionFilmstrips=[],video=null;
1207
1259
  const screenshotDir=resolve(outputDir,'screenshots');await mkdir(screenshotDir,{recursive:true});
1208
1260
  const staleCleanup=[
@@ -1236,7 +1288,8 @@ export async function runBrowserQa(options={}){
1236
1288
  }catch(error){
1237
1289
  blockers.push(issue('blocker','layout-audit-failed',null,'Repair the runtime layout audit so every key state can be inspected.',{viewport,detail:`${state}: ${error.message}`,metrics:{state}}));return;
1238
1290
  }
1239
- addLayoutReport(result,viewport,state,blockers,warnings);
1291
+ addLayoutReport(result,viewport,state,blockers,warnings,options.expectedCopyChecks?.[state]);
1292
+ recordAnchors3d(result,viewport,state);
1240
1293
  };
1241
1294
  const checkStore=async(targetSession,state)=>{
1242
1295
  const result=await targetSession.verifyStore();
@@ -1341,7 +1394,7 @@ export async function runBrowserQa(options={}){
1341
1394
  const components=project?.components??[],byId=new Map(components.map(c=>[c.id,c]));
1342
1395
  const active=new Set(components.filter(c=>{if(c.sceneId!==sceneId)return false;for(let cur=c;cur;cur=byId.get(cur.parentId))if(cur.prototype)return false;return true;}).map(c=>c.id));
1343
1396
  const res=await targetSession.auditLayout({ids:[...active],interactiveIds:[...new Set([...(project?.events??[]).filter(e=>e.kind==='click'&&active.has(e.componentId)).map(e=>e.componentId),...(project?.gameplay??[]).filter(behavior=>['aim-launch','drag','swipe-input','hold-charge','virtual-joystick','draw-stroke','erase-mask'].includes(behavior.kind)&&active.has(behavior.componentId)).map(behavior=>behavior.componentId)])],network,minTouchPx:MIN_TOUCH_PX});
1344
- addLayoutReport(res,viewport,'timeout',blockers,warnings);
1397
+ addLayoutReport(res,viewport,'timeout',blockers,warnings,options.expectedCopyChecks?.timeout);
1345
1398
  }
1346
1399
  await targetSession.setViewport(DEFAULT_VIEWPORTS[1]);
1347
1400
  await checkStore(targetSession,'timeout');
@@ -1380,7 +1433,8 @@ export async function runBrowserQa(options={}){
1380
1433
  }
1381
1434
  }
1382
1435
  }finally{await session.close?.();}
1383
- const report=formatCreativeQaReport({scope:'browser',blockers,warnings,interactions,states,screenshots,contactSheets,motionFilmstrips,video,checks:{viewports:DEFAULT_VIEWPORTS,browserContexts:wantVideo?2:1,primaryInteraction:'project-click-events',storeCta:storeChecks,interactionLimitMs:INTERACTION_LIMIT_MS,minTouchPx:MIN_TOUCH_PX,stateHook:stateHook?typeof stateHook:'not-supplied'}});
1436
+ for(const state of Object.keys(options.expectedCopyChecks??{}))if(!states.some(row=>row.state===state&&row.status==='checked'))blockers.push(issue('blocker','localized-copy-state-unavailable',null,'Make every state containing localized copy reachable and auditable.',{detail:`Required localized state was not checked: ${state}`,metrics:{state}}));
1437
+ const report=formatCreativeQaReport({scope:'browser',blockers,warnings,interactions,states,screenshots,contactSheets,motionFilmstrips,video,checks:{viewports:DEFAULT_VIEWPORTS,browserContexts:wantVideo?2:1,primaryInteraction:'project-click-events',storeCta:storeChecks,interactionLimitMs:INTERACTION_LIMIT_MS,minTouchPx:MIN_TOUCH_PX,stateHook:stateHook?typeof stateHook:'not-supplied',expectedCopyStates:Object.keys(options.expectedCopyChecks??{}),...(anchors3dChecks.length?{anchors3d:anchors3dChecks}:{})}});
1384
1438
  await writeCreativeQaReport(report,outputDir);return report;
1385
1439
  }
1386
1440
  export const runBrowserAudit=runBrowserQa;
@@ -5,10 +5,7 @@ import {ProjectStore} from '../project-store.mjs';
5
5
  import {EditorState} from '../editor-state.mjs';
6
6
  import {NativeService} from './service.mjs';
7
7
  import {NativeReview} from './review.mjs';
8
- import {NativeAgentTools} from './agent-tools.mjs';
9
- import {createHarvestConcept} from './author-harvest.mjs';
10
- import {authorProjectThroughService} from './author-primitive-proofs.mjs';
11
- import {authorSkyBlasterThroughService} from './author-fps.mjs';
8
+ import {importProjectFile} from './local-bundle.mjs';
12
9
  import {closeSharedBrowser} from './browser-pool.mjs';
13
10
  import {networkTargetIds} from './network-targets.mjs';
14
11
  import {PACKAGE_ROOT} from '../runtime-paths.mjs';
@@ -90,9 +87,14 @@ async function removeProjectDir(service,projectId){
90
87
  }
91
88
  }
92
89
 
90
+ async function demoFixtureAvailable(rawId){
91
+ try{return (await stat(resolve(PACKAGE_ROOT,'source/showcase',resolveDemoId(rawId)+'.tora.json'))).isFile();}
92
+ catch{return false;}
93
+ }
94
+
93
95
  export async function demoAssetsAvailable(rawId){
94
- const plans=DEMO_ASSET_PLANS[resolveDemoId(rawId)];
95
- if(!plans)return false;
96
+ const id=resolveDemoId(rawId),plans=DEMO_ASSET_PLANS[id];
97
+ if(!plans||!await demoFixtureAvailable(id))return false;
96
98
  try{
97
99
  const paths=await Promise.all(plans.map(async relative=>{
98
100
  const planPath=resolve(PACKAGE_ROOT,relative);
@@ -120,18 +122,10 @@ export async function materializeDemo(service,rawId,{overwrite=false}={}){
120
122
  };
121
123
  }
122
124
  if(!await demoAssetsAvailable(id))throw Error('E_DEMO_ASSETS_UNAVAILABLE');
123
- // Clean any empty draft or overwritten directory before authoring cleanly through NativeService
125
+ // Import the preserved editable native fixture instead of running an authoring script.
124
126
  await removeProjectDir(service,id);
125
- if(id==='tiny-harvest'){
126
- const agent=new NativeAgentTools(service);
127
- await agent.run({command:'compose',id,concept:await createHarvestConcept()});
128
- }else if(id==='traffic-tycoon'){
129
- await authorProjectThroughService(service,'traffic',id);
130
- }else if(id==='mini-golf'){
131
- await authorProjectThroughService(service,'golf',id);
132
- }else if(id==='sky-blaster'){
133
- await authorSkyBlasterThroughService(service,id);
134
- }
127
+ const fixture=await readFile(resolve(PACKAGE_ROOT,'source/showcase',id+'.tora.json'),'utf8');
128
+ await importProjectFile(service,fixture,{copy:false});
135
129
  return {
136
130
  id,projectId:id,name:meta.name,genre:meta.genre,tagline:meta.tagline,
137
131
  created:true,editorUrl:`/?project=${encodeURIComponent(id)}`,
@@ -178,9 +172,6 @@ export async function buildDemoSeed(rawId,rootDir=resolve(import.meta.dirname,'.
178
172
  const cleanMetadata={
179
173
  ...metadata,
180
174
  requests:[],
181
- passesUsed:0,
182
- feedbackModel:undefined,
183
- paidFeedbackModel:undefined,
184
175
  };
185
176
  return {
186
177
  id:meta.id,
@@ -1,6 +1,6 @@
1
1
  import {nativeStructural as structural} from '../../../packages/creative-project/src/native-structural.mjs';
2
2
  import {mesh3dSlots,contracts,behaviors,events,actions,limits,defaults,validateValue} from './contracts.mjs';
3
- import {identityMatrix,multiplyMatrix,inverseMatrix,validateMatrix} from '../scene-document.mjs';
3
+ import {identityMatrix,multiplyMatrix,inverseMatrix,validateMatrix} from '../matrix.mjs';
4
4
  export const check=(v,code='E_NATIVE_DOCUMENT',detail)=>{if(!v){const error=Error(code);if(detail)error.detail=detail;throw error;}};
5
5
  export const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).every(k=>keys.includes(k));
6
6
  export const identifier=v=>typeof v==='string'&&/^[a-z][a-z0-9_.-]{0,95}$/.test(v)&&!['constructor','prototype','__proto__'].includes(v);
@@ -25,7 +25,7 @@ export function references(value){const refs=[];function visit(v){if(!v||typeof
25
25
  export function validateDocument(p){
26
26
  check(exact(p,['schemaVersion','projectId','revisionId','generationOrigin','creativeBrief','base','scenes','components','assets','variables','gameplay','events','eventBindings','tombstones']));
27
27
  check(p.schemaVersion==='2.1.0'&&identifier(p.projectId)&&typeof p.revisionId==='string'&&p.revisionId.length<=128);
28
- check(p.generationOrigin==='human-authored'&&exact(p.creativeBrief,['goal','language'])&&typeof p.creativeBrief.goal==='string'&&p.creativeBrief.goal.length<=2048&&p.creativeBrief.language==='en');
28
+ check(p.generationOrigin==='human-authored'&&exact(p.creativeBrief,['goal','language'])&&typeof p.creativeBrief.goal==='string'&&p.creativeBrief.goal.length<=2048&&typeof p.creativeBrief.language==='string'&&p.creativeBrief.language.length<=16&&/^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?$/.test(p.creativeBrief.language));
29
29
  let nodes=0;function bounded(v,d){check(++nodes<=limits.nodes&&d<=limits.depth,'E_NATIVE_LIMIT');if(v&&typeof v==='object')for(const x of Object.values(v))bounded(x,d+1);else {check(v!==null&&(typeof v!=='number'||Number.isFinite(v)));if(typeof v==='string')for(const c of v){const code=c.codePointAt(0);check(code<0xd800||code>0xdfff,'E_NATIVE_UNICODE');}}}bounded(p,0);check(new globalThis.TextEncoder().encode(JSON.stringify(p)).length<=limits.documentBytes,'E_NATIVE_LIMIT');
30
30
  check(exact(p.base,['kind','runtimeId','runtimeVersion','width','height','startScene','storeUrl'])&&p.base.kind==='native-scene'&&p.base.runtimeId==='tora-native'&&p.base.runtimeVersion==='1.0.0','E_NATIVE_RUNTIME');
31
31
  check([p.base.width,p.base.height].every(n=>Number.isFinite(n)&&n>=240&&n<=2048));check(typeof p.base.storeUrl==='string'&&(p.base.storeUrl===''||/^https:\/\/(play\.google\.com\/store\/apps\/details\?id=[a-zA-Z0-9._-]+|apps\.apple\.com\/[a-zA-Z0-9/._?=&-]+)$/.test(p.base.storeUrl)),'E_NATIVE_STORE');
@@ -121,6 +121,18 @@ export function validateDocument(p){
121
121
  while(ancestor){check(!ancestor.prototype,'E_NATIVE_LAYOUT');ancestor=g.byId.get(ancestor.parentId);}
122
122
  check(p.gameplay.filter(other=>other.componentId===c.id&&other.kind==='responsive-layout').length===1,'E_NATIVE_LAYOUT');
123
123
  }
124
+ if(b.kind==='ui-anchor-3d'){
125
+ const owner=g.byId.get(b.componentId),target=g.byId.get(b.parameters.targetId);
126
+ check(!['native.stage3d.v1','native.mesh3d.v1'].includes(owner.contract)&&!owner.prototype,'E_NATIVE_LAYOUT',{...bctx,reason:'ui_anchor_3d_requires_2d_component'});
127
+ let ancestor=owner.parentId?g.byId.get(owner.parentId):undefined;
128
+ while(ancestor){check(!ancestor.prototype,'E_NATIVE_LAYOUT',{...bctx,reason:'ui_anchor_3d_cannot_be_under_prototype'});ancestor=g.byId.get(ancestor.parentId);}
129
+ check(p.gameplay.filter(other=>other.componentId===owner.id&&other.kind==='ui-anchor-3d').length===1,'E_NATIVE_LAYOUT',{...bctx,reason:'duplicate_ui_anchor_3d'});
130
+ check(!p.gameplay.some(other=>other.componentId===owner.id&&['responsive-layout','drag','motion'].includes(other.kind)),'E_NATIVE_LAYOUT',{...bctx,reason:'conflicting_layout_or_motion_behavior'});
131
+ check(identifier(b.parameters.targetId)&&target?.contract==='native.mesh3d.v1'&&target.sceneId===owner.sceneId,'E_NATIVE_REFERENCE',{...bctx,targetId:b.parameters.targetId,reason:'ui_anchor_3d_requires_scene_mesh3d_target'});
132
+ let targetAnc=target;
133
+ while(targetAnc){check(!targetAnc.prototype,'E_NATIVE_REFERENCE',{...bctx,targetId:b.parameters.targetId,reason:'ui_anchor_3d_target_cannot_be_prototype'});targetAnc=targetAnc.parentId?g.byId.get(targetAnc.parentId):undefined;}
134
+ check((b.parameters.minSizePx??48)<=(b.parameters.maxSizePx??260),'E_NATIVE_PROPERTY',{...bctx,key:'minSizePx',reason:'min_size_exceeds_max_size'});
135
+ }
124
136
  }
125
137
  function condition(c,depth=0){
126
138
  check(depth<8,'E_NATIVE_LIMIT');if(c.all||c.any){check(exact(c,[c.all?'all':'any']));const a=c.all??c.any;check(Array.isArray(a)&&a.length>0&&a.length<=8);a.forEach(x=>condition(x,depth+1));return;}
@@ -10,15 +10,17 @@ import {lowerAssets,storeVerifiedDeliveryAsset} from './assets.mjs';
10
10
  import {saveRevisionLineage} from './asset-lineage.mjs';
11
11
  import {resolveNativeTool} from './native-bin.mjs';
12
12
  import {IS_SOURCE_CHECKOUT,PACKAGE_ROOT} from '../runtime-paths.mjs';
13
+ import {readVariants,variantsPath} from './variants.mjs';
14
+ import {withProjectFileLock} from '../editor-state.mjs';
13
15
  const run=promisify(execFile);
14
- export async function exportProjectFile(service,id,revisionId){const current=await service.read(id,revisionId),assets=await lowerAssets(resolve(service.store.root,id),current.project.assets);return projectBundle(current.project,Object.fromEntries(assets.map(a=>[a.hash,a.data])));}
16
+ export async function exportProjectFile(service,id,revisionId){const current=await service.read(id,revisionId),projectRoot=resolve(service.store.root,id),assets=await lowerAssets(projectRoot,current.project.assets),variants=await withProjectFileLock(variantsPath(projectRoot)+'.lock',()=>readVariants(projectRoot,current.project));return projectBundle(current.project,Object.fromEntries(assets.map(a=>[a.hash,a.data])),variants);}
15
17
  export async function importProjectFile(service,text,{copy=false}={}){
16
18
  await assertStorePath(service.store.root);await mkdir(service.store.root,{recursive:true});const stage=await mkdtemp(resolve(service.store.root,'.import-'));let reserved;
17
19
  try{
18
20
  const decodeImage=async(bytes,mime)=>{let tool=resolveNativeTool('inspect');if(!tool&&IS_SOURCE_CHECKOUT){await run('cargo',['build','--locked','-p','playable-cli'],{cwd:PACKAGE_ROOT});tool=resolveNativeTool('inspect');}if(!tool)throw Error('E_NATIVE_BIN_UNAVAILABLE');await writeFile(resolve(stage,'image'),bytes);const result=JSON.parse((await run(tool.command,[...tool.prefixArgs,stage,'image'],{timeout:10000})).stdout)[0];if(result.source_mime!==mime)throw Error('E_NATIVE_ASSET_MIME');};
19
21
  const bundle=await readProjectBundle(text,{decodeImage});if(copy)bundle.project.projectId=bundle.project.projectId.slice(0,32)+'-import-'+randomUUID().slice(0,8);const id=bundle.project.projectId,target=resolve(service.store.root,id);
20
22
  const journal=resolve(service.history.directory,createHash('sha256').update(service.store.root+'\0'+id).digest('hex')+'.json');try{await access(journal);throw Error('E_PROJECT_EXISTS');}catch(e){if(e.code!=='ENOENT')throw e;}
21
- const folder=resolve(stage,id);await mkdir(folder);await mkdir(resolve(folder,'revisions'));await writeFile(resolve(folder,'workspace.json'),JSON.stringify({format:'tora-local-workspace-1',id,kind:'native-scene',status:'DRAFT',activeRevision:'initial'}));for(const asset of bundle.project.assets)await storeVerifiedDeliveryAsset(folder,{...asset,bytes:Buffer.from(bundle.assets[asset.hash],'base64'),expectedHash:asset.hash});await saveRevisionLineage(folder,bundle.project,null);await writeFile(resolve(folder,'project.json'),JSON.stringify(bundle.project));
23
+ const folder=resolve(stage,id);await mkdir(folder);await mkdir(resolve(folder,'revisions'));await writeFile(resolve(folder,'workspace.json'),JSON.stringify({format:'tora-local-workspace-1',id,kind:'native-scene',status:'DRAFT',activeRevision:'initial'}));for(const asset of bundle.project.assets)await storeVerifiedDeliveryAsset(folder,{...asset,bytes:Buffer.from(bundle.assets[asset.hash],'base64'),expectedHash:asset.hash});await saveRevisionLineage(folder,bundle.project,null);await writeFile(resolve(folder,'project.json'),JSON.stringify(bundle.project));if(bundle.variants)await writeFile(resolve(folder,'variants.json'),JSON.stringify(bundle.variants),{flag:'wx'});
22
24
  // Reserving the ID prevents concurrent creators from being overwritten.
23
25
  try{await mkdir(target);reserved=target;}catch(e){if(e.code==='EEXIST')throw Error('E_PROJECT_EXISTS',{cause:e});throw e;}await rename(folder,target);reserved=undefined;return {status:'IMPORTED',projectId:id,accepted:false};
24
26
  }finally{if(reserved)await rmdir(reserved);await rm(stage,{recursive:true,force:true});}