@tora-editor/tora 0.1.0 → 0.2.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 (73) hide show
  1. package/README.md +108 -58
  2. package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
  3. package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
  4. package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
  5. package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
  6. package/assets/kenney-food-starter/License.txt +28 -0
  7. package/assets/kenney-food-starter/burger.glb +0 -0
  8. package/assets/kenney-food-starter/frying-pan.glb +0 -0
  9. package/assets/kenney-food-starter/plan.json +61 -0
  10. package/assets/kenney-food-starter/plate.glb +0 -0
  11. package/assets/kenney-food-starter/pot.glb +0 -0
  12. package/assets/kenney-harvest/audio/victory.wav +0 -0
  13. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
  14. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
  15. package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
  16. package/bin/tora.mjs +77 -9
  17. package/crates/packer/trusted/native-3d-meta.json +3 -2
  18. package/crates/packer/trusted/native-3d.js +181 -181
  19. package/crates/packer/trusted/native-meta.json +2 -2
  20. package/crates/packer/trusted/native.js +5 -5
  21. package/crates/packer/trusted/release-manifest.json +17 -17
  22. package/crates/packer/trusted/review-runtime-meta.json +3 -2
  23. package/crates/packer/trusted/review-runtime.js +182 -182
  24. package/docs/TORA_AGENT_SETUP.md +24 -13
  25. package/docs/TORA_CREATION_API.md +29 -12
  26. package/docs/reference/CORE_AUTHORING.md +2 -1
  27. package/docs/reference/PLAYABLE_STARTERS.md +20 -0
  28. package/docs/reference/packs/3d.md +9 -3
  29. package/network-rules/mintegral-appgrowth-single-html.json +10 -10
  30. package/package.json +6 -6
  31. package/packages/creative-project/project-v21.schema.json +264 -8
  32. package/scripts/lean/editor/review-editor.css +10 -0
  33. package/scripts/lean/editor/review-editor.js +117 -1
  34. package/scripts/lean/native/agent-tools.mjs +7 -7
  35. package/scripts/lean/native/api.mjs +16 -5
  36. package/scripts/lean/native/asset-catalog.mjs +7 -6
  37. package/scripts/lean/native/asset-lineage.mjs +54 -0
  38. package/scripts/lean/native/asset-prep.mjs +173 -40
  39. package/scripts/lean/native/assets.mjs +107 -11
  40. package/scripts/lean/native/author-expansion-proofs.mjs +2 -99
  41. package/scripts/lean/native/author-fps.mjs +545 -0
  42. package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
  43. package/scripts/lean/native/build-cache.mjs +2 -2
  44. package/scripts/lean/native/cc0-inputs.mjs +24 -0
  45. package/scripts/lean/native/cc0-staging.mjs +28 -8
  46. package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
  47. package/scripts/lean/native/check-salvage.mjs +8 -5
  48. package/scripts/lean/native/compiler.mjs +9 -3
  49. package/scripts/lean/native/contracts.mjs +11 -8
  50. package/scripts/lean/native/creative-qa.mjs +305 -122
  51. package/scripts/lean/native/demos.mjs +47 -3
  52. package/scripts/lean/native/document.mjs +36 -10
  53. package/scripts/lean/native/export-budget.mjs +75 -0
  54. package/scripts/lean/native/glb-loader.mjs +468 -0
  55. package/scripts/lean/native/intake-creator-tools.mjs +83 -30
  56. package/scripts/lean/native/local-bundle.mjs +5 -3
  57. package/scripts/lean/native/mcp-server.mjs +33 -46
  58. package/scripts/lean/native/media-validate.mjs +124 -0
  59. package/scripts/lean/native/native-bin.mjs +3 -3
  60. package/scripts/lean/native/outcome-playthrough.mjs +97 -0
  61. package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
  62. package/scripts/lean/native/project-bundle.mjs +3 -3
  63. package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
  64. package/scripts/lean/native/review-agent-tools.mjs +2 -2
  65. package/scripts/lean/native/review.mjs +3 -0
  66. package/scripts/lean/native/runtime.mjs +242 -56
  67. package/scripts/lean/native/schema.mjs +7 -5
  68. package/scripts/lean/native/service.mjs +159 -32
  69. package/scripts/lean/native/stage-3d.mjs +343 -40
  70. package/scripts/lean/native/starters.mjs +436 -0
  71. package/scripts/lean/native/verify.mjs +1 -1
  72. package/scripts/lean/native/win-cues.mjs +96 -0
  73. package/skills/tora-playables/SKILL.md +1 -1
@@ -0,0 +1,436 @@
1
+ import {resolve} from 'node:path';
2
+ import {lstat,mkdir,writeFile} from 'node:fs/promises';
3
+ import {registerSourceBytes} from './assets.mjs';
4
+ import {inspectMedia} from './asset-catalog.mjs';
5
+ import {assertSingleVisualStyleFamily, compactAssetProvenance, resolveCc0SourceItem} from './cc0-staging.mjs';
6
+ import {hash} from './compiler.mjs';
7
+ import {applyOperations, check, emptyProject} from './document.mjs';
8
+ import {exportProjectFile} from './local-bundle.mjs';
9
+
10
+ const gameplay = 'scene.play';
11
+ const win = 'scene.win';
12
+ const timeout = 'scene.timeout';
13
+ const steps = 'starter.steps';
14
+ const dropFrame = 'starter.drop-frame';
15
+ const layers = ['patty', 'cheese', 'salad', 'tomato', 'bun-top'];
16
+ const cars = ['blue', 'red', 'yellow', 'green'];
17
+ const carSources = Object.fromEntries(cars.map(color => [
18
+ color, `assets/kenney-racing/source/racing-pack/extracted/PNG/Cars/car_${color}_1.png`,
19
+ ]));
20
+
21
+ const definitions = {
22
+ 'stack-and-serve': {
23
+ name: 'Stack & Serve',
24
+ mechanic: 'Stack five 3D ingredients to finish an order.',
25
+ palette: {background: '#382322', surface: '#fff2d7', ink: '#321b1a', accent: '#ffc15e'},
26
+ winTitle: 'Order up!',
27
+ timeoutTitle: 'So close',
28
+ art: Object.fromEntries(['burger', 'plate', 'frying-pan', 'pot'].map(model => [model, `Models/GLB format/${model}.glb`])),
29
+ artPack: 'kenney-food-kit',
30
+ audio: {music: 'arcade-pop/ambient.wav', step: 'arcade-pop/reward.wav', win: 'arcade-pop/win.wav', loss: 'arcade-pop/loss.wav'},
31
+ },
32
+ 'tap-targets': {
33
+ name: 'Pit Stop Dash',
34
+ mechanic: 'Tap each car as it arrives at a pit box to finish the round.',
35
+ palette: {background: '#132635', surface: '#dbeaf2', ink: '#10232c', accent: '#ffc750'},
36
+ winTitle: 'Grid ready!',
37
+ timeoutTitle: 'Race awaits',
38
+ art: carSources,
39
+ artPack: 'kenney-racing-pack',
40
+ audio: {music: 'arcade-pop/ambient.wav', step: 'arcade-pop/reward.wav', win: 'audio/victory.wav', loss: 'arcade-pop/loss.wav'},
41
+ },
42
+ };
43
+
44
+ const starterNames = Object.keys(definitions);
45
+ const strings = keys => ({
46
+ type: 'object',
47
+ additionalProperties: false,
48
+ properties: Object.fromEntries(keys.map(key => [key, {type: 'string'}])),
49
+ });
50
+ export const starterInputProperties = {
51
+ ...strings(['id','name','androidUrl','ctaLabel','winTitle','timeoutTitle']).properties,
52
+ starter: {type: 'string', enum: starterNames},
53
+ deliver: {type:'boolean',description:'Save a browser draft, editable bundle, and packaged-playback QA to a new folder in this workspace.'},
54
+ durationSeconds: {type: 'integer', minimum: 10, maximum: 60},
55
+ winHoldSeconds: {type: 'number', minimum: 0.25, maximum: 3},
56
+ palette: strings(['background','surface','ink','accent']),
57
+ art: strings([...Object.keys(definitions['stack-and-serve'].art), ...cars]),
58
+ audio: strings(['music','step','win','loss']),
59
+ };
60
+
61
+ export function listStarters(){
62
+ return {
63
+ starters: Object.entries(definitions).map(([id, definition]) => ({
64
+ id, name: definition.name, mechanic: definition.mechanic,
65
+ visualPack: definition.artPack, artRoles: Object.keys(definition.art),
66
+ })),
67
+ defaults: {durationSeconds: 25, winHoldSeconds: 0.9, ctaLabel: 'Play now'},
68
+ outputs: 'Use deliver:true for a browser draft, editable bundle, and packaged-playback evidence in a new folder.',
69
+ };
70
+ }
71
+
72
+ function contrast(a,b){
73
+ const luminance = color=>{
74
+ const channels = color.slice(1).match(/../g).map(hex=>parseInt(hex,16)/255);
75
+ const [red,green,blue] = channels.map(value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4);
76
+ return .2126*red+.7152*green+.0722*blue;
77
+ };
78
+ const colors = [luminance(a),luminance(b)];
79
+ return (Math.max(...colors)+.05)/(Math.min(...colors)+.05);
80
+ }
81
+
82
+ function settings(input){
83
+ check(Object.hasOwn(definitions, input.starter), 'E_STARTER_KIND');
84
+ const definition = definitions[input.starter];
85
+ const {durationSeconds=25, winHoldSeconds=0.9, ctaLabel='Play now',
86
+ winTitle=definition.winTitle, timeoutTitle=definition.timeoutTitle} = input;
87
+ for(const label of [ctaLabel, winTitle, timeoutTitle]){
88
+ check(typeof label === 'string' && label.trim().length && label.length <= 24 && label.trim().split(/\s+/).length <= 3,
89
+ 'E_STARTER_COPY');
90
+ }
91
+ check(Number.isInteger(durationSeconds) && durationSeconds >= 10 && durationSeconds <= 60, 'E_STARTER_TIMING');
92
+ check(Number.isFinite(winHoldSeconds) && winHoldSeconds >= 0.25 && winHoldSeconds <= 3, 'E_STARTER_TIMING');
93
+ const palette = {...definition.palette, ...input.palette};
94
+ check(Object.values(palette).every(color => /^#[0-9a-f]{6}$/i.test(color)), 'E_STARTER_PALETTE');
95
+ for(const [foreground,background] of [['surface','background'],['ink','accent']]){
96
+ check(contrast(palette[foreground],palette[background])>=4.5,'E_STARTER_CONTRAST',
97
+ {foreground,background,minimumRatio:4.5});
98
+ }
99
+ check(Object.keys(input.art??{}).every(role => Object.hasOwn(definition.art, role)), 'E_STARTER_ART_ROLE');
100
+ return {definition, palette, durationSeconds, winHoldSeconds, ctaLabel, winTitle, timeoutTitle};
101
+ }
102
+
103
+ function builder(){
104
+ const operations = [];
105
+ const append = operation => operations.push(operation);
106
+ const component = (id, sceneId, kind, x, y, width, height, parameters={}, options={}) =>
107
+ append({kind:'createComponent',component:{
108
+ id, sceneId, contract:`native.${kind}.v1`, transform:[1,0,0,1,x,y],
109
+ parameters:{width,height,...parameters}, ...options,
110
+ }});
111
+ const behavior = (id, componentId, kind, parameters) =>
112
+ append({kind:'putBehavior',behavior:{id,componentId,kind,parameters}});
113
+ const bind = (id, event, actions, condition) =>
114
+ append({kind:'putBinding',binding:{id,event,actions,...(condition?{condition}:{})}});
115
+ const landscape = (componentId,x,y,scaleX=1,scaleY=scaleX) =>
116
+ behavior(componentId+'.layout',componentId,'responsive-layout',{x,y,scaleX,scaleY});
117
+ const placed = (id,scene,x,y,w,h,alternate,order=0) => {
118
+ const groupId = id+'.placement';
119
+ component(groupId,scene,'group',x,y,w,h,{}, {order});
120
+ landscape(groupId,...alternate);
121
+ return groupId;
122
+ };
123
+ const label = (id,scene,x,y,w,h,text,fontSize,color,parentId) =>
124
+ component(id,scene,'text',x,y,w,h,{text,fontSize,color,fontWeight:'900',align:'center',wrap:false,autoFit:true,minFontSize:14},
125
+ parentId?{parentId}:{});
126
+ const art = (id,scene,x,y,w,h,assetId,parentId) =>
127
+ component(id,scene,'image',x,y,w,h,{fit:'contain'},{parentId,assetSlots:[{slotId:'source',assetId}]});
128
+ const variable = id => append({kind:'putVariable',variable:{id,label:id,type:'number',initial:0}});
129
+ return {operations,append,component,behavior,bind,landscape,placed,label,art,variable};
130
+ }
131
+
132
+ const set = (componentId,key,value) => ({kind:'setComponent',componentId,key,value});
133
+ const play = name => ({kind:'playAudio',behaviorId:`starter.audio.${name}`});
134
+ const eq = (variableId,value) => ({variableId,op:'eq',value});
135
+ const timer = behaviorId => ({kind:'timer',behaviorId});
136
+
137
+ function button(make,id,scene,x,y,w,h,copy,palette,{landscapeX,landscapeY,cta=false}){
138
+ const parentId = make.placed(id,scene,x,y,w,h,[landscapeX,landscapeY],30);
139
+ make.component(id,scene,'button',0,0,w,h,{
140
+ radius:18, fill:palette.accent, hoverFill:palette.accent, pressedFill:palette.surface,
141
+ stroke:palette.ink, strokeWidth:2, presentation:cta?'shiny-cta':'flat',
142
+ }, {parentId});
143
+ make.label(id+'.label',scene,0,0,w,h,copy,26,palette.ink,id);
144
+ make.behavior(id+'.press',id,'press-feedback',{scaleDown:.94,springBackSeconds:.17,liftShadow:true});
145
+ }
146
+
147
+ function backdrop(make,scene,palette){
148
+ const id = scene+'.backdrop';
149
+ const parentId = make.placed(id,scene,0,0,390,700,[0,0,700/390,390/700]);
150
+ make.component(id,scene,'rectangle',0,0,390,700,{fill:palette.background},{parentId});
151
+ }
152
+
153
+ function progress(make,count,palette){
154
+ make.component('starter.progress',gameplay,'group',125,62,140,20,{}, {order:15});
155
+ make.landscape('starter.progress',475,106);
156
+ for(let i=0;i<count;i++){
157
+ make.component(`starter.pip.${i}`,gameplay,'rectangle',i*28,2,23,10,{
158
+ fill:palette.surface+'32',radius:5,
159
+ },{parentId:'starter.progress'});
160
+ }
161
+ }
162
+
163
+ function audioRig(make){
164
+ for(const [name,scene,bus,volume,role] of [
165
+ ['music',gameplay,'music',.12,'ambient'],
166
+ ['step',gameplay,'sfx',.22,'reward'],
167
+ ['win',win,'stinger',.40,'win'],
168
+ ['loss',timeout,'stinger',.27,'loss'],
169
+ ]){
170
+ const id = `starter.sound.${name}`;
171
+ make.component(id,scene,'group',0,0,0,0,{visible:false},
172
+ {assetSlots:[{slotId:'source',assetId:`starter.asset.${name}`}]});
173
+ make.behavior(`starter.audio.${name}`,id,'audio',{
174
+ bus,volume,role,loop:name==='music',frequency:440,seconds:.4,cooldownMs:55,allowSynthFallback:false,
175
+ });
176
+ }
177
+ }
178
+
179
+ function completeStep(index,count,palette,winHoldSeconds){
180
+ return [
181
+ ...(index===0?[play('music')]:[]),
182
+ play('step'),
183
+ set(`starter.pip.${index}`,'fill',palette.accent),
184
+ {kind:'add',variableId:steps,value:1},
185
+ ...(index===count-1?[{kind:'changeScene',sceneId:win,delaySeconds:winHoldSeconds}]:[]),
186
+ ];
187
+ }
188
+
189
+ function outcome(make,scene,copy,ctaLabel,palette,addShowcase){
190
+ make.append({kind:'createScene',scene:{id:scene,label:scene===win?'Win':'Timeout',role:'end-card'}});
191
+ backdrop(make,scene,palette);
192
+ addShowcase();
193
+ const title = scene+'.title';
194
+ make.component(title,scene,'group',40,88,310,90,{}, {order:20});
195
+ make.landscape(title,374,105);
196
+ make.label(title+'.text',scene,0,0,310,90,copy,39,palette.surface,title);
197
+ const cta = scene+'.cta';
198
+ button(make,cta,scene,58,537,274,70,ctaLabel,palette,{landscapeX:392,landscapeY:208,cta:true});
199
+ make.behavior(cta+'.pulse',cta,'animation',{
200
+ property:'scale',from:1,to:1.035,seconds:1.8,loop:true,easing:'ease-in-out',
201
+ });
202
+ const enterActions = [{kind:'animate',behaviorId:cta+'.pulse'},play(scene===win?'win':'loss')];
203
+ if(scene===win){
204
+ const effect = scene+'.confetti';
205
+ make.behavior(effect,scene+'.backdrop','emitter',{
206
+ coverage:'screen',shape:'confetti',color:palette.accent,color2:palette.surface,color3:'#fc7657',
207
+ count:46,speed:110,lifetime:1.9,gravity:34,spread:280,
208
+ });
209
+ enterActions.push({kind:'emit',behaviorId:effect});
210
+ }
211
+ make.bind(scene+'.enter',{kind:'sceneEnter',sceneId:scene},enterActions);
212
+ make.bind(scene+'.store',{kind:'click',componentId:cta},[{kind:'store'}]);
213
+ }
214
+
215
+ function kitchen(make,scene,palette,{completed=false,plan}={}){
216
+ const stage = scene+'.kitchen';
217
+ const parentId = make.placed(stage,scene,0,128,390,402,[34,13,.9],1);
218
+ make.component(stage,scene,'stage3d',0,0,390,402,{
219
+ skyColor:palette.background, hemiSkyColor:'#fff0d6', hemiGroundColor:'#624032',
220
+ hemiIntensity:1.25,sunColor:'#fff1d2',sunIntensity:3.0,sunX:-4,sunY:8,sunZ:5,
221
+ shadowsEnabled:true,shadowMapSize:'1024',toneMapping:'aces',renderMaxDim:600,
222
+ cameraX:0,cameraY:1.85,cameraZ:3.25,cameraFov:32,
223
+ landscapeCameraX:0,landscapeCameraY:1.6,landscapeCameraZ:3.05,landscapeCameraFov:34,
224
+ lookAtY:.31,introLift:0,
225
+ },{parentId});
226
+ const mesh = (id, asset, parameters) =>
227
+ make.component(id,scene,'mesh3d',0,0,0,0,{
228
+ primitive:'model',materialMode:'lambert',castShadow:true,receiveShadow:true,...parameters,
229
+ },{parentId:stage,assetSlots:[{slotId:'source',assetId:`starter.asset.${asset}`}]});
230
+ mesh(stage+'.plate','plate',{x:0,y:0,z:0,sx:1.65,sy:1.25,sz:1.65});
231
+ if(scene===gameplay){
232
+ mesh(stage+'.pan','frying-pan',{x:-.72,y:.03,z:-.72,ry:.4,sx:.52,sy:.52,sz:.52});
233
+ mesh(stage+'.pot','pot',{x:.73,y:.04,z:-.92,ry:-.25,sx:.5,sy:.5,sz:.5});
234
+ }
235
+ if(completed){
236
+ mesh(stage+'.burger','burger',{y:.115,sx:1.35,sy:1.35,sz:1.35});
237
+ make.behavior(stage+'.hero-bob',stage+'.burger','oscillate-3d',{axis:'y',amplitude:.025,angularSpeed:1.35,phase:0});
238
+ }else{
239
+ const burgerSize = 1.2;
240
+ mesh(stage+'.base','burger',{subNode:'bun-bottom',y:.1,sx:burgerSize,sy:burgerSize,sz:burgerSize});
241
+ plan?.(mesh);
242
+ }
243
+ }
244
+
245
+ function stackAndServe(make,{palette,winHoldSeconds,ctaLabel,winTitle,timeoutTitle}){
246
+ const control = 'starter.drop';
247
+ button(make,control,gameplay,65,556,260,68,'Drop ingredient',palette,{landscapeX:414,landscapeY:185});
248
+ const fallTimer = 'starter.drop-step';
249
+ make.variable(dropFrame);
250
+ make.behavior(fallTimer,control,'timer',{seconds:.055,repeat:true});
251
+ const part = index => `starter.layer.${index}`;
252
+ const hoverY = .7;
253
+ kitchen(make,gameplay,palette,{plan:mesh=>{
254
+ layers.forEach((subNode,index)=>{
255
+ mesh(part(index),'burger',{subNode,y:hoverY,visible:index===0,sx:1.2,sy:1.2,sz:1.2});
256
+ });
257
+ }});
258
+ layers.forEach((_,index)=>{
259
+ const id = part(index), landedY = .1+index*.035;
260
+ const burst = id+'.burst';
261
+ make.behavior(burst,id,'emitter',{
262
+ origin:'contact-3d',coverage:'local',shape:'circle',color:palette.accent,color2:palette.surface,color3:'#ff7045',
263
+ count:13,speed:115,lifetime:.42,gravity:240,spread:230,
264
+ });
265
+ make.bind(id+'.drop',{kind:'click',componentId:control},[
266
+ set(id,'y',hoverY*0.87),{kind:'set',variableId:dropFrame,value:1},
267
+ ],{all:[eq(steps,index),eq(dropFrame,0)]});
268
+ make.bind(id+'.land',timer(fallTimer),[
269
+ set(id,'y',landedY),{kind:'emit',behaviorId:burst},
270
+ {kind:'set',variableId:dropFrame,value:0},
271
+ ...(index<layers.length-1?[set(part(index+1),'visible',true)]:[]),
272
+ ...completeStep(index,layers.length,palette,winHoldSeconds),
273
+ ],{all:[eq(steps,index),eq(dropFrame,3)]});
274
+ for(const [frame, fraction] of [[2,.24],[1,.51]]){
275
+ make.bind(id+'.advance-'+frame,timer(fallTimer),[
276
+ set(id,'y',landedY+(hoverY-landedY)*fraction),
277
+ {kind:'set',variableId:dropFrame,value:frame+1},
278
+ ],{all:[eq(steps,index),eq(dropFrame,frame)]});
279
+ }
280
+ });
281
+ outcome(make,win,winTitle,ctaLabel,palette,()=>kitchen(make,win,palette,{completed:true}));
282
+ outcome(make,timeout,timeoutTitle,ctaLabel,palette,()=>kitchen(make,timeout,palette,{
283
+ plan:mesh=>layers.forEach((subNode,index)=>{
284
+ const id = `scene.timeout.layer.${index}`;
285
+ mesh(id,'burger',{subNode,y:.1+index*.035,visible:false,sx:1.2,sy:1.2,sz:1.2});
286
+ make.bind(id+'.reveal',{kind:'sceneEnter',sceneId:timeout},[set(id,'visible',true)],
287
+ {all:[{variableId:steps,op:'gt',value:index}]});
288
+ }),
289
+ }));
290
+ return layers.length;
291
+ }
292
+
293
+ function pitScene(make,scene,palette){
294
+ const panel = scene+'.pit';
295
+ const parentId = make.placed(panel,scene,23,141,344,370,[26,27,.9],1);
296
+ for(const [index,color] of cars.entries()){
297
+ make.component(panel+'.'+color,scene,'rectangle',index%2?188:20,index<2?11:181,136,165,{
298
+ fill:palette.ink,stroke:palette.surface+'45',strokeWidth:2,radius:20,
299
+ },{parentId,order:-1});
300
+ }
301
+ return parentId;
302
+ }
303
+
304
+ function tapTargets(make,{palette,winHoldSeconds,ctaLabel,winTitle,timeoutTitle}){
305
+ const panel = pitScene(make,gameplay,palette);
306
+ const w = 108, h = 139;
307
+ const targets = cars.map((color,index)=>{
308
+ const id = 'starter.car.'+color;
309
+ const x = index%2?202:34, y = index<2?24:194;
310
+ make.component(id,gameplay,'button',x,y,w,h,{
311
+ radius:18,fill:palette.accent,hoverFill:palette.accent,pressedFill:palette.surface,visible:index===0,
312
+ },{order:10,parentId:panel});
313
+ make.art(id+'.art',gameplay,23,10,62,119,`starter.asset.${color}`,id);
314
+ make.behavior(id+'.press',id,'press-feedback',{scaleDown:.88,springBackSeconds:.15,liftShadow:true});
315
+ make.behavior(id+'.spark',id,'emitter',{
316
+ count:12,origin:'center',coverage:'local',shape:'circle',color:palette.accent,
317
+ speed:125,lifetime:.45,gravity:180,spread:170,
318
+ });
319
+ return id;
320
+ });
321
+ targets.forEach((id,index)=>{
322
+ make.bind(id+'.collect',{kind:'click',componentId:id},[
323
+ set(id,'visible',false),{kind:'emit',behaviorId:id+'.spark'},
324
+ ...(targets[index+1]?[set(targets[index+1],'visible',true)]:[]),
325
+ ...completeStep(index,targets.length,palette,winHoldSeconds),
326
+ ],{all:[eq(steps,index)]});
327
+ });
328
+ const instruction = 'starter.hint';
329
+ make.component(instruction,gameplay,'group',65,542,260,65,{}, {order:22});
330
+ make.landscape(instruction,410,183);
331
+ make.label(instruction+'.text',gameplay,0,0,260,65,'Tap the cars',28,palette.surface,instruction);
332
+ make.bind(instruction+'.hide',{kind:'variableChange',variableId:steps},[set(instruction,'visible',false)]);
333
+ for(const [scene,copy] of [[win,winTitle],[timeout,timeoutTitle]]){
334
+ outcome(make,scene,copy,ctaLabel,palette,()=>{
335
+ const panelId = pitScene(make,scene,palette);
336
+ cars.forEach((color,index)=>{
337
+ make.art(`${scene}.hero.${color}`,scene,index%2?190:54,index<2?27:176,95,144,`starter.asset.${color}`,panelId);
338
+ });
339
+ const lead = scene+'.hero.blue';
340
+ make.behavior(lead+'.lift',lead,'animation',{property:'y',from:55,to:27,seconds:.5,loop:false,easing:'ease-out'});
341
+ make.bind(lead+'.enter',{kind:'sceneEnter',sceneId:scene},[{kind:'animate',behaviorId:lead+'.lift'}]);
342
+ });
343
+ }
344
+ return targets.length;
345
+ }
346
+
347
+ function composition(input, settings){
348
+ const make = builder();
349
+ const {palette,durationSeconds} = settings;
350
+ backdrop(make,gameplay,palette);
351
+ make.variable(steps);
352
+ audioRig(make);
353
+ const count = (input.starter==='stack-and-serve'?stackAndServe:tapTargets)(make,settings);
354
+ progress(make,count,palette);
355
+ const deadline = 'starter.deadline';
356
+ make.behavior(deadline,gameplay+'.backdrop','timer',{seconds:durationSeconds,repeat:false});
357
+ make.bind(deadline+'.transition',timer(deadline),[
358
+ {kind:'changeScene',sceneId:timeout},
359
+ ],{all:[{variableId:steps,op:'lt',value:count}]});
360
+ return make.operations;
361
+ }
362
+
363
+ async function starterSources(input, definition, catalog, remoteFetcher){
364
+ await catalog.load();
365
+ const roles = [...Object.entries(definition.art),...Object.entries(definition.audio)];
366
+ const assets = await Promise.all(roles.map(async ([role,path])=>{
367
+ const isArt = Object.hasOwn(definition.art,role);
368
+ const requested = (isArt?input.art:input.audio)?.[role];
369
+ const entry = [...catalog.entries.values()].find(row=>row.sourceFile===path&&(!isArt||row.sourceId===definition.artPack));
370
+ const sourceId = requested ?? entry?.id;
371
+ check(sourceId,'E_STARTER_ASSET_UNAVAILABLE',{role,path});
372
+ const source = await resolveCc0SourceItem(sourceId,{catalog,remoteFetcher});
373
+ const expectedType = isArt?(input.starter==='stack-and-serve'?'model/gltf-binary':'image/'):'audio/';
374
+ check(source.mime.startsWith(expectedType),'E_STARTER_ASSET_TYPE',{role,expectedType});
375
+ if(role==='burger'){
376
+ const {subNodes=[]} = inspectMedia(source.bytes,source.mime);
377
+ check(['bun-bottom',...layers].every(layer=>subNodes.includes(layer)),'E_STARTER_BURGER_NODES',{role});
378
+ }
379
+ return {...source,id:`starter.asset.${role}`,provenance:compactAssetProvenance(source.provenance)};
380
+ }));
381
+ assertSingleVisualStyleFamily([],assets);
382
+ return assets;
383
+ }
384
+
385
+ export async function composeStarter(input,{service,catalog,remoteFetcher,workspaceRoot}){
386
+ const options = settings(input);
387
+ const createInput = {id:input.id,name:input.name??options.definition.name,androidUrl:input.androidUrl};
388
+ const blank = emptyProject(createInput);
389
+ const outputDir=input.deliver?resolve(workspaceRoot,input.id+'-draft'):undefined;
390
+ if(outputDir){
391
+ const existing=await lstat(outputDir).catch(error=>{if(error.code!=='ENOENT')throw error;});
392
+ check(!existing,'E_STARTER_OUTPUT_EXISTS',{outputDir});
393
+ }
394
+ const sources = await starterSources(input,options.definition,catalog,remoteFetcher);
395
+ const operations = composition(input,options);
396
+ const register = asset => ({kind:'registerAsset',asset});
397
+ // Resolve and validate the whole recipe before claiming a new project ID.
398
+ applyOperations(blank,[
399
+ ...sources.map(({id,mime,rights,provenance,bytes})=>register({id,mime,rights,provenance,bytes:bytes.length,hash:hash(bytes)})),
400
+ ...operations,
401
+ ]);
402
+ const created = await service.create(createInput);
403
+ const projectRoot = resolve(service.store.root,input.id);
404
+ const assets = await Promise.all(sources.map(({id,mime,rights,bytes,provenance,master})=>
405
+ registerSourceBytes(projectRoot,{id,mime,rights,...(!master?{optimize:'none'}:{})},bytes,{provenance,master})));
406
+ const envelope = {
407
+ format:'tora-transaction-1',
408
+ expected:{revisionId:created.revisionId,contentHash:created.contentHash},
409
+ operations:[...assets.map(({optimization,...asset})=>{void optimization;return register(asset);}),...operations],
410
+ };
411
+ const preview = await service.preview(input.id,envelope);
412
+ const {revisionId, contentHash, editorUrl} = await service.transact(input.id,{
413
+ ...envelope,previewDigest:preview.previewDigest,
414
+ },{registeredAssets:assets});
415
+ const result={status:'DRAFT',starter:input.starter,projectId:input.id,expected:{revisionId,contentHash},editorUrl};
416
+ if(!outputDir)return {...result,next:'Run tora_qa with recordVideo:true and inspect the packaged playthrough and audio.'};
417
+ const {project}=await service.read(input.id,revisionId);
418
+ const [artifact,bundle]=await Promise.all([service.build(input.id,project),exportProjectFile(service,input.id,revisionId)]);
419
+ await mkdir(outputDir);
420
+ const outputs={html:resolve(outputDir,input.id+'.html'),project:resolve(outputDir,input.id+'.tora.json')};
421
+ await Promise.all([writeFile(outputs.html,artifact.html,{flag:'wx'}),writeFile(outputs.project,bundle,{flag:'wx'})]);
422
+ const evidenceDir=resolve(outputDir,'qa');
423
+ let report;
424
+ try{report=await service.runQa(input.id,{revisionId,outputDir:evidenceDir,artifact,recordVideo:true});}
425
+ catch(error){
426
+ return {...result,outputs,qa:{status:'UNAVAILABLE',code:error.code??'E_STARTER_QA',outputDir:evidenceDir}};
427
+ }
428
+ const {ok,blockers,warnings,summary,video}=report;
429
+ const contactSheet=report.contactSheets?.find(sheet=>sheet.state==='all');
430
+ return {...result,outputs,qa:{
431
+ ok,blockers,warnings,checkedStates:summary.checkedStates,storeCta:report.checks.browser?.storeCta,
432
+ report:resolve(evidenceDir,'report.json'),
433
+ ...(contactSheet?{contactSheet:resolve(evidenceDir,contactSheet.path)}:{}),
434
+ ...(video?{video:resolve(evidenceDir,video.path),videoReachedEndCard:video.reachedEndCard}:{}),
435
+ }};
436
+ }
@@ -1,4 +1,4 @@
1
1
  import process from 'node:process';
2
2
  import {spawnSync} from 'node:child_process';
3
- const checks=[['cargo',['build','--locked','-p','asset-pipeline','--example','inspect_native']],['cargo',['build','--locked','-p','asset-pipeline','--example','optimize_native']],['cargo',['build','--locked','-p','playable-cli']],['cargo',['test','-p','asset-pipeline']],['cargo',['test','-p','playable-cli']],['node',['scripts/m2/generate-project-v21.mjs','--check']],['node',['node_modules/typescript/bin/tsc','--project','packages/creative-project/tsconfig.json','--noEmit']],['cargo',['test','-p','creative-project-schema','--lib']],...['asset-policy','build-cache','module-registry','review-intake','review','review-connection','chat-editor-byok','demos-and-hosted-editor','review-resolver','review-agent','review-agent-resolver','review-agent-tools','review-deterministic','project-index','project-bundle','local-bundle','document','runtime','drag-drop-gestures','instance-targeting','canvas-physics2d-primitives','fps-joystick-3d','physics-primitives','path-economy-primitives','stability','concept','concept-browser','harvest-concept-browser','star-salvage','star-salvage-browser','mcp','compact-discovery','batch-assets-and-edit','qa-cache-and-sheets','distribution-cli','mcp-cc0-and-prep','motion-filmstrip-qa','asset-optimization','network-packages','native-unity','native-applovin','native-vendor-networks','remote-cc0-fetcher','intake-creator-agent','browser'].map(name=>['node',['tests/native/'+name+'.test.mjs']])];
3
+ const checks=[['cargo',['build','--locked','-p','asset-pipeline','--example','inspect_native']],['cargo',['build','--locked','-p','asset-pipeline','--example','optimize_native']],['cargo',['build','--locked','-p','playable-cli']],['cargo',['test','-p','asset-pipeline']],['cargo',['test','-p','playable-cli']],['node',['scripts/m2/generate-project-v21.mjs','--check']],['node',['node_modules/typescript/bin/tsc','--project','packages/creative-project/tsconfig.json','--noEmit']],['cargo',['test','-p','creative-project-schema','--lib']],...['asset-policy','build-cache','module-registry','review-intake','review','review-connection','chat-editor-byok','demos-and-hosted-editor','review-resolver','review-agent','review-agent-resolver','review-agent-tools','review-deterministic','project-index','project-bundle','local-bundle','document','runtime','drag-drop-gestures','instance-targeting','canvas-physics2d-primitives','fps-joystick-3d','model3d-conformance','model3d-pipeline','model3d-runtime','model3d-phase2','physics-primitives','path-economy-primitives','stability','concept','concept-browser','harvest-concept-browser','star-salvage','star-salvage-browser','mcp','compact-discovery','batch-assets-and-edit','qa-cache-and-sheets','distribution-cli','mcp-cc0-and-prep','motion-filmstrip-qa','outcome-qa-browser','asset-optimization','network-packages','native-unity','native-applovin','native-vendor-networks','remote-cc0-fetcher','remote-cc0-3d','intake-creator-agent','browser'].map(name=>['node',['tests/native/'+name+'.test.mjs']])];
4
4
  for(const [command,args]of checks){const r=spawnSync(command,args,{stdio:'inherit'});if(r.status!==0)process.exit(r.status??1);}
@@ -0,0 +1,96 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {Buffer} from 'node:buffer';
3
+ import {readFile} from 'node:fs/promises';
4
+ import {resolve} from 'node:path';
5
+ import {PACKAGE_ROOT} from '../runtime-paths.mjs';
6
+ import {lowerAssets} from './assets.mjs';
7
+ import {loadCatalog} from './catalog-cache.mjs';
8
+ import {check,exact} from './document.mjs';
9
+ import {isAudioMime} from './media-validate.mjs';
10
+ import {stageAudio} from './review-agent-tools.mjs';
11
+
12
+ export const winCueCatalog = Object.freeze({
13
+ 'arcade-rise': Object.freeze({catalogId:'kenney-music-jingles/audio/victory.wav',label:'Arcade rise'}),
14
+ 'arcade-fanfare': Object.freeze({catalogId:'kenney-music-jingles/arcade-pop/win.wav',label:'Arcade fanfare'}),
15
+ });
16
+
17
+ async function catalogCue(key){
18
+ check(Object.hasOwn(winCueCatalog,key),'E_NATIVE_ARGUMENT');
19
+ const catalogId=winCueCatalog[key].catalogId;
20
+ const cue=(await loadCatalog()).audioFiles.find(item=>item.catalogId===catalogId);
21
+ check(cue?.source.license==='CC0-1.0','E_NATIVE_NOT_FOUND');
22
+ return cue;
23
+ }
24
+
25
+ export async function winCuePreview(key){
26
+ const {file}=await catalogCue(key);
27
+ const bytes=await readFile(resolve(PACKAGE_ROOT,file.file));
28
+ check('sha256:'+createHash('sha256').update(bytes).digest('hex')===file.sha256,'E_NATIVE_HASH');
29
+ return {bytes,mime:file.mime};
30
+ }
31
+
32
+ function projectTracks(project){
33
+ const used=new Set(project.eventBindings.flatMap(binding=>binding.actions
34
+ .filter(action=>action.kind==='playAudio').map(action=>action.behaviorId)));
35
+ const routes=project.gameplay.filter(behavior=>behavior.kind==='audio');
36
+ const winRoutes=routes.filter(({id,parameters})=>used.has(id)&&!parameters.loop&&['win','victory'].includes(parameters.role));
37
+ if(winRoutes.length!==1)return;
38
+ const win=winRoutes[0];
39
+ if(routes.some(route=>route.id!==win.id&&route.componentId===win.componentId))return;
40
+ const assetFor=route=>{
41
+ const component=project.components.find(item=>item.id===route.componentId);
42
+ const assetId=component?.assetSlots.find(slot=>slot.slotId==='source')?.assetId;
43
+ return project.assets.find(asset=>asset.id===assetId&&isAudioMime(asset.mime));
44
+ };
45
+ const current=assetFor(win);
46
+ if(!current)return;
47
+ const music=routes.find(({id,parameters})=>used.has(id)&&parameters.bus==='music'&&parameters.loop);
48
+ const backing=music&&assetFor(music);
49
+ return {win,current,...(backing?{music,backing}:{})};
50
+ }
51
+
52
+ function matchesCue(asset,file){
53
+ if(asset.hash===file.sha256)return true;
54
+ if(!asset.provenance?.startsWith('{'))return false;
55
+ try{return JSON.parse(asset.provenance).sourceHash===file.sha256;}catch{return false;}
56
+ }
57
+
58
+ export async function projectWinCueChoices(project){
59
+ const tracks=projectTracks(project);
60
+ if(!tracks)return;
61
+ const choices=await Promise.all(Object.entries(winCueCatalog).map(async ([key,choice])=>{
62
+ const {file}=await catalogCue(key);
63
+ return {key,label:choice.label,current:matchesCue(tracks.current,file)};
64
+ }));
65
+ return {choices,volume:tracks.win.parameters.volume,duckMusic:tracks.win.parameters.bus==='stinger',
66
+ ...(tracks.music?{musicVolume:tracks.music.parameters.volume}:{})};
67
+ }
68
+
69
+ export async function projectWinCueTrack(service,id,track){
70
+ check(track==='music'||track==='current','E_NATIVE_ARGUMENT');
71
+ const {project}=await service.read(id),tracks=projectTracks(project);
72
+ const ref=track==='music'?tracks?.backing:tracks?.current;
73
+ check(ref,'E_NATIVE_NOT_FOUND');
74
+ const [asset]=await lowerAssets(resolve(service.store.root,id),[ref]);
75
+ return {bytes:Buffer.from(asset.data,'base64'),mime:asset.mime};
76
+ }
77
+
78
+ export async function replaceProjectWinCue(service,id,body){
79
+ check(exact(body,['expected','key'])&&exact(body.expected,['revisionId','contentHash'])&&typeof body.key==='string','E_NATIVE_ARGUMENT');
80
+ const {project,revisionId,contentHash}=await service.read(id);
81
+ check(body.expected.revisionId===revisionId&&body.expected.contentHash===contentHash,'E_NATIVE_STALE');
82
+ const tracks=projectTracks(project);
83
+ check(tracks,'E_NATIVE_NOT_FOUND');
84
+ const cue=await catalogCue(body.key);
85
+ if(matchesCue(tracks.current,cue.file))return {revisionId,contentHash};
86
+ const existing=project.assets.find(asset=>asset.hash===cue.file.sha256&&isAudioMime(asset.mime));
87
+ let assetId=existing?.id??'catalog.win.'+body.key;
88
+ let sequence=1;
89
+ while(!existing&&(project.assets.some(asset=>asset.id===assetId)||project.tombstones.includes(assetId)))assetId='catalog.win.'+body.key+'.'+sequence++;
90
+ const imports=existing?[]:await stageAudio(service,id,[{catalogId:cue.catalogId,assetId}],{optimize:'none'});
91
+ const operations=[...imports,{kind:'replaceAsset',id:tracks.win.componentId,assetId}];
92
+ const envelope={format:'tora-transaction-1',expected:body.expected,operations};
93
+ const preview=await service.preview(id,envelope);
94
+ const committed=await service.transact(id,{...envelope,previewDigest:preview.previewDigest});
95
+ return {revisionId:committed.revisionId,contentHash:committed.contentHash};
96
+ }
@@ -25,7 +25,7 @@ Prove one representative scene at the intended phone size before expanding the a
25
25
 
26
26
  ## Author and inspect safely
27
27
 
28
- Create a new project or inspect the requested existing project. Use `tora_inspect({ id, tree: true })` for a compact scene outline before targeted `ids` reads (`full: true` only when you truly need the complete JSON document); preserve unrelated objects and scenes. Use `tora_list_assets` and `tora_fetch_cc0_pack` to discover/cache verified CC0 packs and `tora_stage_cc0_assets` to stage them with server-enforced provenance and single-visual-style-family validation. When sprite sheets or padded sprites need faithful mechanical preparation (`crop`, `trim`, `resize`/`maxSide`, or `sliceGrid`), run `tora_prep_assets` and upload the emitted `.tora/prepared-assets/...` paths via `tora_upload_assets` (which verifies the hash-bound prep manifest and preserves provenance and `styleFamily`). For raw studio assets, use `tora_upload_assets` with workspace `filePath` items (up to 32 files in one atomic revision, avoiding the 12 MiB MCP frame limit), or `tora_upload_asset` for a single file. Raw PNG/JPEG/WAV/MP3 uploads up to 8 MiB are optimized automatically while original masters are retained; use `optimize:"lossless"|"none"`, `preserveResolution`, workspace `filePath`, or an original `sourceHash` when needed. Connect delivered assets to image components through the supported operations.
28
+ Create a new project or inspect the requested existing project. Use `tora_inspect({ id, tree: true })` for a compact scene outline before targeted `ids` reads (`full: true` only when you truly need the complete JSON document); preserve unrelated objects and scenes. Use `tora_list_assets` and `tora_fetch_cc0_pack` to discover/cache verified CC0 2D, 3D, and audio packs and `tora_stage_cc0_assets` to stage them with server-enforced provenance, retained 3D masters, and single-visual-style-family validation. Remote 3D sources are restricted to Kenney, Quaternius, and CC0-filtered OpenGameArt; external-only Quaternius downloads require manual workspace import. When sprite sheets or padded sprites need faithful mechanical preparation (`crop`, `trim`, `resize`/`maxSide`, or `sliceGrid`), or GLB/glTF/OBJ models need dependency-aware `prep-3d`, run `tora_prep_assets` and upload the emitted `.tora/prepared-assets/...` paths via `tora_upload_assets` (which verifies the hash-bound prep manifest and preserves provenance, dependency lineage, and `styleFamily`). For raw studio assets, use `tora_upload_assets` with workspace `filePath` items (up to 32 files in one atomic revision, avoiding the 12 MiB MCP frame limit), or `tora_upload_asset` for a single file. Raw PNG/JPEG/WAV/MP3 uploads up to 8 MB and GLB/glTF/OBJ uploads up to 32 MiB are optimized automatically while original masters are retained; use `optimize:"lossless"|"none"`, `preserveResolution`, workspace `filePath`, or an original `sourceHash` when needed. Connect delivered images and models through supported asset slots; inspect mesh `subNodes`/`animations`, use `animate-3d` for bounded clips, and opt in to `fitTargetBudget` on export/QA when a network cap requires deterministic re-optimization from retained masters.
29
29
 
30
30
  Submit edits through `tora_edit`, with the inspected `expected` revision and intended changed record IDs in `scope`. Use `scopeCreates: true` to auto-allow brand-new records without duplicating every new ID in `scope` — any pre-existing component, behavior, event, binding, or variable referenced by a new record (or `$project.base`) still requires explicit inclusion in `scope`. A `PREVIEW` response is not a committed change: inspect the effects and either adjust scope and commit the cached preview directly via `commitPreviewDigest` (without re-emitting `operations[]`) when those effects belong to the requested task, or revise your operations. On a stale revision, inspect again before rebuilding the edit. Never blindly replay edits or bypass validation. For HTTP authoring, use the documented preview/commit sequence and revision checks.
31
31