ozmoz 0.1.58 → 0.1.59

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 (2) hide show
  1. package/dist/cli.cjs +47 -46
  2. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,33 +1,33 @@
1
1
  #!/usr/bin/env node
2
- var i=require("fs"),a=require("path"),Y=require("https"),re=require("http"),A=require("os"),{exec:ie,spawnSync:I}=require("child_process"),ae=[a.join(__dirname,"..","scripts","setup-lib.cjs"),a.join(__dirname,"..","..","scripts","setup-lib.cjs"),a.join(__dirname,"scripts","setup-lib.cjs")],ce=ae.find(i.existsSync)||a.join(__dirname,"..","scripts","setup-lib.cjs"),{runFullSetup:K,handleAuthAndEnv:q,touchTsConfig:le,attemptViteAutoImportPatch:de,injectUniversalRuntime:ue,writeBrowserConfig:me,patchAllowScripts:pe}=require(ce),fe=!!(process.stdout&&process.stdout.isTTY&&typeof process.stdout.hasColors=="function"&&process.stdout.hasColors(16777216)),he=fe?"\x1B[38;2;15;156;140m":"\x1B[36m",ge="\x1B[31m",H="\x1B[0m",X="https://api.ozmoz.io/cli/";function u(e){console.log(e.replace(/OZmoz|\[|\]|→/g,t=>`${he}${t}${H}`))}function y(e){console.error(`${ge}${e}${H}`)}var _="ozmoz",J=/<!--\s*(?:ozmoz|fleetbo|OZmoz):start[^>]*-->[\s\S]*?<!--\s*(?:ozmoz|fleetbo|OZmoz):end\s*-->/i,ye="<!-- OZmoz:end -->",Q="# OZMOZ DATA OS \u2014 DIRECTIVES SYST\xC8ME",Z={claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",devin:"Devin",codex:"Codex CLI",gemini:"Gemini CLI",antigravity:"Antigravity CLI",copilot:"GitHub Copilot"},j={created:"created",updated:"updated",unchanged:"already up to date",appended:"OZmoz block appended (your own content was kept)",migrated:"old file replaced (backup: <file>.ozmoz-legacy.bak)",invalid:"skipped: the file is not valid JSON, fix or delete it first"};function Oe(){try{return JSON.parse(i.readFileSync(a.join(__dirname,"..","package.json"),"utf8")).version||"dev"}catch{return"dev"}}var ze=Buffer.from("QUl6YVN5QUM1Uk94STNibklPMUR5TmZsTWhGUnJ0blItNDVwNFJF","base64").toString("utf8");function ve(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8"));return typeof t.exp=="number"&&t.exp*1e3<Date.now()+6e4}catch{return!1}}function ee(e,t){i.writeFileSync(e,t,{mode:384});try{i.chmodSync(e,384)}catch{}}async function Se(e,t){let s=await fetch(`https://securetoken.googleapis.com/v1/token?key=${ze}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=refresh_token&refresh_token=${encodeURIComponent(t)}`});if(!s.ok)return null;let n=await s.json();return n.id_token?(ee(e,JSON.stringify({devToken:n.id_token,refreshToken:n.refresh_token||t,updatedAt:new Date().toISOString()},null,2)),n.id_token):null}async function U(){if(process.env.FLEETBO_DEV_TOKEN)return process.env.FLEETBO_DEV_TOKEN;try{let e=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(e)){let t=JSON.parse(i.readFileSync(e,"utf8"));if(t.devToken&&!ve(t.devToken))return t.devToken;if(t.refreshToken)try{let s=await Se(e,t.refreshToken);if(s)return s}catch{}}}catch{}return null}async function te(){let e=a.join(A.homedir(),".fleetbo","guidelines.json"),t=await U();t||y('[OZmoz] Not logged in: run "npx ozmoz login" first to load the full instructions. Using local cache if available.');try{u("[OZmoz] Fetching instructions from Cloud...");let s=await fetch(X+"getagentdirectives",{method:"POST",headers:Object.assign({"Content-Type":"application/json"},t?{Authorization:`Bearer ${t}`}:{}),body:JSON.stringify({data:{}})});if(!s.ok)y("[OZmoz] Cloud error HTTP "+s.status);else{let n=await s.json(),r=n.result?.data||n.result||n.data;if(r&&r.protocol&&r.directives)return u("[OZmoz] Instructions loaded successfully."),i.existsSync(a.dirname(e))||i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,JSON.stringify(r,null,2),"utf8"),r;y("[OZmoz] Empty Cloud response.")}}catch(s){y("[OZmoz] Network error: "+s.message)}if(i.existsSync(e)){u("[OZmoz] Using local cache (~/.fleetbo/guidelines.json)");try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{}}return{protocol:"",directives:"",version:"1.0.0"}}function V(e,t){return"<!-- ozmoz:start v"+e+` -->
2
+ var i=require("fs"),a=require("path"),Y=require("https"),re=require("http"),A=require("os"),{exec:ie,spawnSync:x}=require("child_process"),ae=[a.join(__dirname,"..","scripts","setup-lib.cjs"),a.join(__dirname,"..","..","scripts","setup-lib.cjs"),a.join(__dirname,"scripts","setup-lib.cjs")],ce=ae.find(i.existsSync)||a.join(__dirname,"..","scripts","setup-lib.cjs"),{runFullSetup:K,handleAuthAndEnv:q,touchTsConfig:le,attemptViteAutoImportPatch:de,injectUniversalRuntime:ue,writeBrowserConfig:me,patchAllowScripts:pe}=require(ce),fe=!!(process.stdout&&process.stdout.isTTY&&typeof process.stdout.hasColors=="function"&&process.stdout.hasColors(16777216)),he=fe?"\x1B[38;2;15;156;140m":"\x1B[36m",ge="\x1B[31m",H="\x1B[0m",X="https://api.ozmoz.io/cli/";function u(e){console.log(e.replace(/OZmoz|\[|\]|→/g,t=>`${he}${t}${H}`))}function g(e){console.error(`${ge}${e}${H}`)}var _="ozmoz",V=/<!--\s*(?:ozmoz|fleetbo|OZmoz):start[^>]*-->[\s\S]*?<!--\s*(?:ozmoz|fleetbo|OZmoz):end\s*-->/i,ye="<!-- OZmoz:end -->",Q="# OZMOZ DATA OS \u2014 DIRECTIVES SYST\xC8ME",Z={claude:"Claude Code",cursor:"Cursor",windsurf:"Windsurf",devin:"Devin",codex:"Codex CLI",gemini:"Gemini CLI",antigravity:"Antigravity CLI",copilot:"GitHub Copilot"},j={created:"created",updated:"updated",unchanged:"already up to date",appended:"OZmoz block appended (your own content was kept)",migrated:"old file replaced (backup: <file>.ozmoz-legacy.bak)",invalid:"skipped: the file is not valid JSON, fix or delete it first"};function Oe(){try{return JSON.parse(i.readFileSync(a.join(__dirname,"..","package.json"),"utf8")).version||"dev"}catch{return"dev"}}var ze=Buffer.from("QUl6YVN5QUM1Uk94STNibklPMUR5TmZsTWhGUnJ0blItNDVwNFJF","base64").toString("utf8");function ve(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8"));return typeof t.exp=="number"&&t.exp*1e3<Date.now()+6e4}catch{return!1}}function ee(e,t){i.writeFileSync(e,t,{mode:384});try{i.chmodSync(e,384)}catch{}}async function Se(e,t){let s=await fetch(`https://securetoken.googleapis.com/v1/token?key=${ze}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=refresh_token&refresh_token=${encodeURIComponent(t)}`});if(!s.ok)return null;let o=await s.json();return o.id_token?(ee(e,JSON.stringify({devToken:o.id_token,refreshToken:o.refresh_token||t,updatedAt:new Date().toISOString()},null,2)),o.id_token):null}async function U(){if(process.env.FLEETBO_DEV_TOKEN)return process.env.FLEETBO_DEV_TOKEN;try{let e=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(e)){let t=JSON.parse(i.readFileSync(e,"utf8"));if(t.devToken&&!ve(t.devToken))return t.devToken;if(t.refreshToken)try{let s=await Se(e,t.refreshToken);if(s)return s}catch{}}}catch{}return null}async function te(){let e=a.join(A.homedir(),".fleetbo","guidelines.json"),t=await U();t||g('[OZmoz] Not logged in: run "npx ozmoz login" first to load the full instructions. Using local cache if available.');try{u("[OZmoz] Fetching instructions from Cloud...");let s=await fetch(X+"getagentdirectives",{method:"POST",headers:Object.assign({"Content-Type":"application/json"},t?{Authorization:`Bearer ${t}`}:{}),body:JSON.stringify({data:{}})});if(!s.ok)g("[OZmoz] Cloud error HTTP "+s.status);else{let o=await s.json(),r=o.result?.data||o.result||o.data;if(r&&r.protocol&&r.directives)return u("[OZmoz] Instructions loaded successfully."),i.existsSync(a.dirname(e))||i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,JSON.stringify(r,null,2),"utf8"),r;g("[OZmoz] Empty Cloud response.")}}catch(s){g("[OZmoz] Network error: "+s.message)}if(i.existsSync(e)){u("[OZmoz] Using local cache (~/.fleetbo/guidelines.json)");try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{}}return{protocol:"",directives:"",version:"1.0.0"}}function J(e,t){return"<!-- ozmoz:start v"+e+` -->
3
3
  `+t.trim()+`
4
4
  `+ye+`
5
- `}function we(e,t,s){let n=i.existsSync(e)?i.readFileSync(e,"utf8"):null,r,o;return n===null?(r="created",o=t):J.test(n)?(o=n.replace(J,()=>t.trimEnd()),r=o===n?"unchanged":"updated"):n.includes(Q)?(r="migrated",o=t):(r="appended",o=n.replace(/\s*$/,`
5
+ `}function Ee(e,t,s){let o=i.existsSync(e)?i.readFileSync(e,"utf8"):null,r,n;return o===null?(r="created",n=t):V.test(o)?(n=o.replace(V,()=>t.trimEnd()),r=n===o?"unchanged":"updated"):o.includes(Q)?(r="migrated",n=t):(r="appended",n=o.replace(/\s*$/,`
6
6
 
7
- `)+t),!s&&r!=="unchanged"&&(r==="migrated"&&i.writeFileSync(e+".ozmoz-legacy.bak",n,"utf8"),i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,o,"utf8")),r}function oe(){return[a.join(__dirname,"ozmoz-mcp.js"),a.join(__dirname,"..","bin","ozmoz-mcp.js"),a.join(__dirname,"bin","ozmoz-mcp.js"),a.join(__dirname,"..","src","bin","ozmoz-mcp.js")].find(t=>i.existsSync(t))||a.resolve(__dirname,"ozmoz-mcp.js")}function M(e,t,s){let n=Object.assign({command:process.execPath,args:[__filename,"mcp","--run"]},s||{}),r={};if(i.existsSync(e))try{let d=JSON.parse(i.readFileSync(e,"utf8"));if(!d||typeof d!="object"||Array.isArray(d))return"invalid";r=d}catch{return"invalid"}let o=r.mcpServers&&r.mcpServers[_];return o&&JSON.stringify(o)===JSON.stringify(n)?"unchanged":(r.mcpServers=r.mcpServers||{},r.mcpServers[_]=n,t||(i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,JSON.stringify(r,null,2)+`
8
- `,"utf8")),o?"updated":"created")}function R(e){let t=process.platform==="win32"?"where":"which";return I(t,[e],{stdio:"ignore"}).status===0}function G(e,t,s){let n=I(e,t,{encoding:"utf8",timeout:s||3e4,shell:process.platform==="win32"});return{ok:n.status===0,out:(n.stdout||"")+(n.stderr||"")}}function Ee(e,t,s){let n=e==="claude"?["--scope",s||"user"]:[],r=oe(),o=["mcp","add"].concat(n,[_,"--",process.execPath,r]),d=["mcp","remove",_].concat(n),c=e+" "+o.join(" ");if(!R(e))return{status:"manual",detail:c};if(t)return{status:"planned",detail:c};let h=G(e,["mcp","list"],6e4),f=h.ok?h.out.split(`
9
- `):[],p=f.find(w=>/^[\s|│┃]*ozmoz(?![\w@-])/.test(w)),m=f.some(w=>/^\s*(?:fleetbo|ozmoz):\s/.test(w));if(p&&p.includes("ozmoz@latest"))return{status:"unchanged",legacy:m};if(p&&!G(e,d).ok)return{status:"manual",detail:e+" "+d.join(" ")+" && "+c,legacy:m};let g=G(e,o);return g.ok?{status:p?"updated":"created",legacy:m}:{status:"failed",detail:c,message:g.out.trim().split(`
10
- `).slice(-2).join(" "),legacy:m}}function Te(e){let t={user:!1,local:!1,others:[]};try{let s=JSON.parse(i.readFileSync(a.join(A.homedir(),".claude.json"),"utf8")),n=c=>!!c&&typeof c=="object"&&/fleetbo|ozmoz/.test(String(c.command||"")+" "+JSON.stringify(c.args||[])),r=(c,h)=>{!c||typeof c!="object"||Object.keys(c).forEach(f=>{f===_?t[h]=!0:n(c[f])&&t.others.push({name:f,where:h})})};r(s.mcpServers,"user");let o=e;try{o=i.realpathSync(e)}catch{}let d=s.projects||{};Array.from(new Set([e,o])).forEach(c=>r((d[c]||{}).mcpServers,"local"))}catch{}return t}function be(e){let t=Te(e);t.user&&u(" \u26A0\uFE0F A global (user-scope) '"+_+"' entry from a previous version also exists: the tools appear in every project. To keep them in OZmoz projects only: claude mcp remove "+_+" --scope user"),t.local&&u(" \u26A0\uFE0F A local-scope '"+_+"' entry exists for this folder and takes precedence over .mcp.json. Remove it: claude mcp remove "+_+" --scope local"),t.others.forEach(s=>{u(" \u26A0\uFE0F An old MCP entry named '"+s.name+"' ("+s.where+" scope) points to OZmoz. Remove it: claude mcp remove "+s.name+" --scope "+s.where)})}function Ae(e){let t=A.homedir(),s=n=>i.existsSync(n);return{claude:R("claude")||s(a.join(t,".claude")),cursor:s(a.join(e,".cursor"))||s(a.join(t,".cursor"))||R("cursor"),windsurf:s(a.join(t,".codeium","windsurf"))||s(a.join(e,".windsurf")),devin:s(a.join(e,".devin")),codex:R("codex")||s(a.join(t,".codex")),gemini:R("gemini")||s(a.join(t,".gemini")),antigravity:R("agy")||s(a.join(t,".antigravity"))||s(a.join(e,".antigravity")),copilot:R("copilot")||s(a.join(t,".copilot"))}}var Ce={claude:{bin:"claude",launch:e=>[e]},gemini:{bin:"gemini",launch:e=>["-i",e]},codex:{bin:"codex",launch:e=>[e]},antigravity:{bin:"agy",launch:e=>["-i",e]}};function Ie(e){return String(e||"").replace(/[^\p{L}\p{N} '.,:\-_]/gu," ").replace(/\s+/g," ").trim().slice(0,4e3)}function ke(e,t,s){let n=Ie(t),r=n?`The user already provided their project description and technical choices: "${n}".
7
+ `)+t),!s&&r!=="unchanged"&&(r==="migrated"&&i.writeFileSync(e+".ozmoz-legacy.bak",o,"utf8"),i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,n,"utf8")),r}function oe(){return[a.join(__dirname,"ozmoz-mcp.js"),a.join(__dirname,"..","bin","ozmoz-mcp.js"),a.join(__dirname,"bin","ozmoz-mcp.js"),a.join(__dirname,"..","src","bin","ozmoz-mcp.js")].find(t=>i.existsSync(t))||a.resolve(__dirname,"ozmoz-mcp.js")}function M(e,t,s){let o=Object.assign({command:process.execPath,args:[__filename,"mcp","--run"]},s||{}),r={};if(i.existsSync(e))try{let d=JSON.parse(i.readFileSync(e,"utf8"));if(!d||typeof d!="object"||Array.isArray(d))return"invalid";r=d}catch{return"invalid"}let n=r.mcpServers&&r.mcpServers[_];return n&&JSON.stringify(n)===JSON.stringify(o)?"unchanged":(r.mcpServers=r.mcpServers||{},r.mcpServers[_]=o,t||(i.mkdirSync(a.dirname(e),{recursive:!0}),i.writeFileSync(e,JSON.stringify(r,null,2)+`
8
+ `,"utf8")),n?"updated":"created")}function R(e){let t=process.platform==="win32"?"where":"which";return x(t,[e],{stdio:"ignore"}).status===0}function G(e,t,s){let o=x(e,t,{encoding:"utf8",timeout:s||3e4,shell:process.platform==="win32"});return{ok:o.status===0,out:(o.stdout||"")+(o.stderr||"")}}function we(e,t,s){let o=e==="claude"?["--scope",s||"user"]:[],r=oe(),n=["mcp","add"].concat(o,[_,"--",process.execPath,r]),d=["mcp","remove",_].concat(o),c=e+" "+n.join(" ");if(!R(e))return{status:"manual",detail:c};if(t)return{status:"planned",detail:c};let h=G(e,["mcp","list"],6e4),f=h.ok?h.out.split(`
9
+ `):[],p=f.find(E=>/^[\s|│┃]*ozmoz(?![\w@-])/.test(E)),m=f.some(E=>/^\s*(?:fleetbo|ozmoz):\s/.test(E));if(p&&p.includes("ozmoz@latest"))return{status:"unchanged",legacy:m};if(p&&!G(e,d).ok)return{status:"manual",detail:e+" "+d.join(" ")+" && "+c,legacy:m};let y=G(e,n);return y.ok?{status:p?"updated":"created",legacy:m}:{status:"failed",detail:c,message:y.out.trim().split(`
10
+ `).slice(-2).join(" "),legacy:m}}function Te(e){let t={user:!1,local:!1,others:[]};try{let s=JSON.parse(i.readFileSync(a.join(A.homedir(),".claude.json"),"utf8")),o=c=>!!c&&typeof c=="object"&&/fleetbo|ozmoz/.test(String(c.command||"")+" "+JSON.stringify(c.args||[])),r=(c,h)=>{!c||typeof c!="object"||Object.keys(c).forEach(f=>{f===_?t[h]=!0:o(c[f])&&t.others.push({name:f,where:h})})};r(s.mcpServers,"user");let n=e;try{n=i.realpathSync(e)}catch{}let d=s.projects||{};Array.from(new Set([e,n])).forEach(c=>r((d[c]||{}).mcpServers,"local"))}catch{}return t}function be(e){let t=Te(e);t.user&&u(" \u26A0\uFE0F A global (user-scope) '"+_+"' entry from a previous version also exists: the tools appear in every project. To keep them in OZmoz projects only: claude mcp remove "+_+" --scope user"),t.local&&u(" \u26A0\uFE0F A local-scope '"+_+"' entry exists for this folder and takes precedence over .mcp.json. Remove it: claude mcp remove "+_+" --scope local"),t.others.forEach(s=>{u(" \u26A0\uFE0F An old MCP entry named '"+s.name+"' ("+s.where+" scope) points to OZmoz. Remove it: claude mcp remove "+s.name+" --scope "+s.where)})}function Ae(e){let t=A.homedir(),s=o=>i.existsSync(o);return{claude:R("claude")||s(a.join(t,".claude")),cursor:s(a.join(e,".cursor"))||s(a.join(t,".cursor"))||R("cursor"),windsurf:s(a.join(t,".codeium","windsurf"))||s(a.join(e,".windsurf")),devin:s(a.join(e,".devin")),codex:R("codex")||s(a.join(t,".codex")),gemini:R("gemini")||s(a.join(t,".gemini")),antigravity:R("agy")||s(a.join(t,".antigravity"))||s(a.join(e,".antigravity")),copilot:R("copilot")||s(a.join(t,".copilot"))}}var Ce={claude:{bin:"claude",launch:e=>[e]},gemini:{bin:"gemini",launch:e=>["-i",e]},codex:{bin:"codex",launch:e=>[e]},antigravity:{bin:"agy",launch:e=>["-i",e]}};function Ie(e){return String(e||"").replace(/[^\p{L}\p{N} '.,:\-_]/gu," ").replace(/\s+/g," ").trim().slice(0,4e3)}function xe(e,t,s){let o=Ie(t),r=o?`The user already provided their project description and technical choices: "${o}".
11
11
  - Check if the framework (e.g. React, Vue) is already specified.
12
12
  - If it is, DO NOT ask a generic "what tech do you want" question. Acknowledge their choice naturally (e.g. "J'ai bien not\xE9 que vous souhaitez utiliser React...") and only ask for the missing precision (TypeScript vs JavaScript) in a single friendly confirmation, or proceed directly if obvious.
13
- - Once the user answers, do NOT run exploratory bash commands. IMMEDIATELY call the MCP tool 'oz_create_project' with the application name.`:"Ask me the starter questions from your OZmoz instructions before installing anything: the technology first, then a one-sentence project description, one question at a time.",o=null,d=!0;try{let m=a.join(s,".env");if(i.existsSync(m)){let g=i.readFileSync(m,"utf8"),w=g.match(/^\s*OZ_DB_KEY\s*=\s*(.+?)\s*$/m);w&&(o=w[1].trim());let E=g.match(/^\s*OZ_PROTOTYPE\s*=\s*(.+?)\s*$/m);E&&(d=E[1].trim().toLowerCase()==="true")}}catch{}let c=i.existsSync(a.join(s,"svro.schema.json")),h=i.existsSync(a.join(s,"index.html"))||i.existsSync(a.join(s,"package.json")),f=d?"OZ_PROTOTYPE=true (mode essai / local sandbox)":"OZ_PROTOTYPE=false (mode r\xE9el / live database)",p=o||c?"This folder ALREADY contains an OZmoz project (OZ_DB_KEY="+o+", "+f+"). Do NOT call oz_create_project, and do NOT ask the starter questions. State this in one plain sentence to the user \u2014 then ask what I want to work on now.":h?'This folder does NOT have an OZmoz project yet, but a frontend project ALREADY exists here \u2014 do NOT run "npm create vite" or scaffold a new frontend. Skip the technology question and ask me only for a one-sentence project description, then call oz_create_project directly.':"This folder does NOT contain an OZmoz project yet (no .env, no svro.schema.json). "+r;return"Use OZmoz as the backend of my app. You are in the project folder ("+s+`). Your OZmoz instructions are already loaded: they are in AGENTS.md / GEMINI.md at the project root and in the OZmoz MCP server (prompt "oz_contract_rules", tool "oz_get_contract"). Never try to read files inside an mcp/ folder or in the agent's own configuration folders, and do not run bash commands or web searches to look for them. If you do not have them in context, call the MCP tool "oz_get_contract" once before answering. `+p}function xe(){let e=process.env;if(e.CLAUDECODE==="1"||e.GEMINI_CLI||e.CODEX_CLI||e.AI_AGENT||e.CURSOR_AGENT||e.ANTIGRAVITY_CLI)return!0;if(process.platform==="win32")return!1;try{let t=I("ps",["-A","-o","pid=,ppid=,args="],{encoding:"utf8"});if(t.status!==0)return!1;let s=new Map;t.stdout.split(`
14
- `).forEach(r=>{let o=r.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);o&&s.set(Number(o[1]),{ppid:Number(o[2]),args:o[3]})});let n=process.ppid;for(let r=0;n>1&&r<20&&s.has(n);r++){let{ppid:o,args:d}=s.get(n);if(d.split(/\s+/).slice(0,2).some(h=>/(^|\/)(gemini|claude|codex|antigravity|agy)$/.test(h))||/@google\/gemini-cli|@anthropic-ai\/claude-code|@openai\/codex/.test(d))return!0;n=o}}catch{}return!1}function _e(e){let t=process.platform==="win32"?"where":"which";return I(t,[e],{stdio:"ignore"}).status===0}function Ne(e,t){a.resolve(e)===A.homedir()&&(y("Run this command inside a project folder, not in your home folder."),process.exit(1));let s=t.slice(1).filter(p=>!p.startsWith("--")),n=(s[0]||"").toLowerCase(),r=s.slice(1).join(" "),o=Ce[n];o||(y('Usage: npx ozmoz start <claude|gemini|codex> ["your app idea"]'),y('Cursor, Windsurf, Devin and GitHub Copilot have no terminal agent to launch: run "npx ozmoz mcp --agent=<cursor|windsurf|devin|copilot>" instead.'),process.exit(1));let d=!1;try{d=!!JSON.parse(i.readFileSync(a.join(A.homedir(),".fleetbo","credentials.json"),"utf8")).devToken}catch{}d||(u("[OZmoz] First use on this machine: sign in (your browser opens, approve once)."),I(process.execPath,[__filename,"login"],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(y('Sign-in did not complete. Run "npx ozmoz start '+n+'" again.'),process.exit(1))),I(process.execPath,[__filename,"mcp","--agent="+n],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(y("Could not configure "+o.bin+'. Run "npx ozmoz mcp --agent='+n+'" to see why.'),process.exit(1)),xe()&&(u(`
13
+ - Once the user answers, do NOT run exploratory bash commands. IMMEDIATELY call the MCP tool 'oz_create_project' with the application name.`:"Ask me the starter questions from your OZmoz instructions before installing anything: the technology first, then a one-sentence project description, one question at a time.",n=null,d=!0;try{let m=a.join(s,".env");if(i.existsSync(m)){let y=i.readFileSync(m,"utf8"),E=y.match(/^\s*OZ_DB_KEY\s*=\s*(.+?)\s*$/m);E&&(n=E[1].trim());let w=y.match(/^\s*OZ_PROTOTYPE\s*=\s*(.+?)\s*$/m);w&&(d=w[1].trim().toLowerCase()==="true")}}catch{}let c=i.existsSync(a.join(s,"svro.schema.json")),h=i.existsSync(a.join(s,"index.html"))||i.existsSync(a.join(s,"package.json")),f=d?"OZ_PROTOTYPE=true (mode essai / local sandbox)":"OZ_PROTOTYPE=false (mode r\xE9el / live database)",p=n||c?"This folder ALREADY contains an OZmoz project (OZ_DB_KEY="+n+", "+f+"). Do NOT call oz_create_project, and do NOT ask the starter questions. State this in one plain sentence to the user \u2014 then ask what I want to work on now.":h?'This folder does NOT have an OZmoz project yet, but a frontend project ALREADY exists here \u2014 do NOT run "npm create vite" or scaffold a new frontend. Skip the technology question and ask me only for a one-sentence project description, then call oz_create_project directly.':"This folder does NOT contain an OZmoz project yet (no .env, no svro.schema.json). "+r;return"Use OZmoz as the backend of my app. You are in the project folder ("+s+`). Your OZmoz instructions are already loaded: they are in AGENTS.md / GEMINI.md at the project root and in the OZmoz MCP server (prompt "oz_contract_rules", tool "oz_get_contract"). Never try to read files inside an mcp/ folder or in the agent's own configuration folders, and do not run bash commands or web searches to look for them. If you do not have them in context, call the MCP tool "oz_get_contract" once before answering. `+p}function ke(){let e=process.env;if(e.CLAUDECODE==="1"||e.GEMINI_CLI||e.CODEX_CLI||e.AI_AGENT||e.CURSOR_AGENT||e.ANTIGRAVITY_CLI)return!0;if(process.platform==="win32")return!1;try{let t=x("ps",["-A","-o","pid=,ppid=,args="],{encoding:"utf8"});if(t.status!==0)return!1;let s=new Map;t.stdout.split(`
14
+ `).forEach(r=>{let n=r.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);n&&s.set(Number(n[1]),{ppid:Number(n[2]),args:n[3]})});let o=process.ppid;for(let r=0;o>1&&r<20&&s.has(o);r++){let{ppid:n,args:d}=s.get(o);if(d.split(/\s+/).slice(0,2).some(h=>/(^|\/)(gemini|claude|codex|antigravity|agy)$/.test(h))||/@google\/gemini-cli|@anthropic-ai\/claude-code|@openai\/codex/.test(d))return!0;o=n}}catch{}return!1}function _e(e){let t=process.platform==="win32"?"where":"which";return x(t,[e],{stdio:"ignore"}).status===0}function Ne(e,t){a.resolve(e)===A.homedir()&&(g("Run this command inside a project folder, not in your home folder."),process.exit(1));let s=t.slice(1).filter(p=>!p.startsWith("--")),o=(s[0]||"").toLowerCase(),r=s.slice(1).join(" "),n=Ce[o];n||(g('Usage: npx ozmoz start <claude|gemini|codex> ["your app idea"]'),g('Cursor, Windsurf, Devin and GitHub Copilot have no terminal agent to launch: run "npx ozmoz mcp --agent=<cursor|windsurf|devin|copilot>" instead.'),process.exit(1));let d=!1;try{d=!!JSON.parse(i.readFileSync(a.join(A.homedir(),".fleetbo","credentials.json"),"utf8")).devToken}catch{}d||(u("[OZmoz] First use on this machine: sign in (your browser opens, approve once)."),x(process.execPath,[__filename,"login"],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(g('Sign-in did not complete. Run "npx ozmoz start '+o+'" again.'),process.exit(1))),x(process.execPath,[__filename,"mcp","--agent="+o],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(g("Could not configure "+n.bin+'. Run "npx ozmoz mcp --agent='+o+'" to see why.'),process.exit(1)),ke()&&(u(`
15
15
  [OZmoz] OZmoz is set up in this folder (instruction file + MCP server).
16
- `),process.exit(0)),_e(o.bin)||(y('"'+o.bin+'" is not installed or not in your PATH. Install it, then run: npx ozmoz start '+n),process.exit(1));let h=ke(o.rules,r,e);u(`
17
- [OZmoz] Launching `+o.bin+` in this folder...
18
- `);let f=I(o.bin,o.launch(process.platform==="win32"?'"'+h+'"':h),{stdio:"inherit",cwd:e,shell:process.platform==="win32"});process.exit(f.status===null?1:f.status)}async function ne(e,t){a.resolve(e)===A.homedir()&&(y("Run this command inside a project folder, not in your home folder."),process.exit(1));let s=t.includes("--dry-run"),n=t.find(l=>l.startsWith("--agent=")),r=n&&n.slice(8).trim()?n.slice(8).split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):null,o=null;if(r){o=r.includes("all")?Object.keys(Z):r;let l=o.filter(O=>!Z[O]);l.length&&(y("Unknown agent(s): "+l.join(", ")+". Valid values: "+Object.keys(Z).join(", ")+", all."),process.exit(1))}let d=t.find(l=>l.startsWith("--scope=")),c=d?d.slice(8).trim().toLowerCase():"project";["project","user","local"].includes(c)||(y("Unknown scope: "+c+". Valid values for Claude Code: project (default), user, local."),process.exit(1));let h=Ae(e),f=o||Object.keys(Z).filter(l=>h[l]),p=Oe();!s&&!await U()&&(process.stdout.isTTY?(u("[OZmoz] First use on this machine: sign in (your browser opens, approve once)."),I(process.execPath,[__filename,"login"],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(y("Sign-in did not complete. Run this command again."),process.exit(1))):(y('[OZmoz] Not signed in. Run "npx -y ozmoz@latest login", wait for "Developer token received and stored successfully!", then run this command again.'),process.exit(1))),u(`
19
- [OZmoz] Configuring your AI agents`+(s?" (dry run: nothing is written)":"")+"...");let m=await te(),g=m.version||p,w=`# OZMOZ DATA OS \u2014 DIRECTIVES AGENT
16
+ `),process.exit(0)),_e(n.bin)||(g('"'+n.bin+'" is not installed or not in your PATH. Install it, then run: npx ozmoz start '+o),process.exit(1));let h=xe(n.rules,r,e);u(`
17
+ [OZmoz] Launching `+n.bin+` in this folder...
18
+ `);let f=x(n.bin,n.launch(process.platform==="win32"?'"'+h+'"':h),{stdio:"inherit",cwd:e,shell:process.platform==="win32"});process.exit(f.status===null?1:f.status)}async function ne(e,t){a.resolve(e)===A.homedir()&&(g("Run this command inside a project folder, not in your home folder."),process.exit(1));let s=t.includes("--dry-run"),o=t.find(l=>l.startsWith("--agent=")),r=o&&o.slice(8).trim()?o.slice(8).split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):null,n=null;if(r){n=r.includes("all")?Object.keys(Z):r;let l=n.filter(O=>!Z[O]);l.length&&(g("Unknown agent(s): "+l.join(", ")+". Valid values: "+Object.keys(Z).join(", ")+", all."),process.exit(1))}let d=t.find(l=>l.startsWith("--scope=")),c=d?d.slice(8).trim().toLowerCase():"project";["project","user","local"].includes(c)||(g("Unknown scope: "+c+". Valid values for Claude Code: project (default), user, local."),process.exit(1));let h=Ae(e),f=n||Object.keys(Z).filter(l=>h[l]),p=Oe();!s&&!await U()&&(process.stdout.isTTY?(u("[OZmoz] First use on this machine: sign in (your browser opens, approve once)."),x(process.execPath,[__filename,"login"],{stdio:"inherit",cwd:e,env:Object.assign({},process.env,{FLEETBO_START:"1"})}).status!==0&&(g("Sign-in did not complete. Run this command again."),process.exit(1))):(g('[OZmoz] Not signed in. Run "npx -y ozmoz@latest login", wait for "Developer token received and stored successfully!", then run this command again.'),process.exit(1))),u(`
19
+ [OZmoz] Configuring your AI agents`+(s?" (dry run: nothing is written)":"")+"...");let m=await te(),y=m.version||p,E=`# OZMOZ DATA OS \u2014 DIRECTIVES AGENT
20
20
 
21
21
  `+(m.directives||m.guidelines||"")+`
22
22
 
23
23
  ## PROTOCOLE DONN\xC9ES : QUI FAIT QUOI (AGENT FRONTEND \u2194 ALEX AI)
24
24
 
25
- `+(m.protocol||""),E=V(g,w),b=[["AGENTS.md",E],["GEMINI.md",E],["CLAUDE.md",V(g,`# OZMOZ DATA OS \u2014 DIRECTIVES AGENT
26
- @AGENTS.md`)]],v=a.join(e,".cursorrules");if(i.existsSync(v)){let l=i.readFileSync(v,"utf8");(J.test(l)||l.includes(Q))&&b.push([".cursorrules",E])}for(let l of b)u("\u2192 "+l[0]+": "+j[we(a.join(e,l[0]),l[1],s)]);for(let l of f){let O=Z[l];if(l==="cursor")u("\u2192 "+O+" MCP (.cursor/mcp.json): "+j[M(a.join(e,".cursor","mcp.json"),s)]);else if(l==="windsurf")u("\u2192 "+O+" MCP (~/.codeium/windsurf/mcp_config.json): "+j[M(a.join(A.homedir(),".codeium","windsurf","mcp_config.json"),s)]);else if(l==="copilot")u("\u2192 "+O+" MCP (~/.copilot/mcp-config.json): "+j[M(a.join(A.homedir(),".copilot","mcp-config.json"),s,{type:"local",tools:["*"]})]);else if(l==="claude"&&c==="project"){let S=M(a.join(e,".mcp.json"),s);u("\u2192 "+O+" MCP (.mcp.json, project scope): "+j[S]),(S==="created"||S==="updated")&&u(" Claude Code asks you to approve a project server the first time you launch it. Commit .mcp.json to share it with your team (it contains no token)."),be(e)}else if(l==="gemini"){let S=[a.join(A.homedir(),".gemini","settings.json"),a.join(e,".gemini","settings.json"),a.join(e,".mcp.json")],T="unchanged";S.forEach(F=>{let P=M(F,s);(P==="created"||P==="updated")&&(T=P)}),u("\u2192 "+O+" MCP (settings.json & .mcp.json): "+j[T])}else if(l==="claude"||l==="codex"||l==="antigravity"){let S=l==="antigravity"?"agy":l,T=Ee(S,s,c);T.status==="manual"?u("\u2192 "+O+": '"+S+"' not found or not scriptable. Run manually: "+T.detail):T.status==="planned"?u("\u2192 "+O+" MCP: would run: "+T.detail):T.status==="failed"?y("\u2192 "+O+" MCP: registration failed ("+T.message+"). Run manually: "+T.detail):u("\u2192 "+O+" MCP"+(l==="claude"?" ("+c+" scope)":"")+": "+j[T.status]),T.legacy&&u(" \u26A0\uFE0F An old MCP entry named 'fleetbo' exists. Remove it: "+S+" mcp remove fleetbo")}else l==="devin"&&u("\u2192 "+O+": reads AGENTS.md. Devin runs in its own environment: add the OZmoz MCP server from Devin's settings (not automated).")}!o&&f.length===0&&u("\u2192 No agent detected: instruction files were written; re-run with --agent=<name> to register the MCP server.");let k=!!($(e).FLEETBO_DEV_TOKEN||process.env.FLEETBO_DEV_TOKEN),z=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(z))try{k=k||!!JSON.parse(i.readFileSync(z,"utf8")).devToken}catch{}k||y('\u26A0\uFE0F No developer token found. Run "npx ozmoz login" once.'),process.env.FLEETBO_START||u(`
25
+ `+(m.protocol||""),w=J(y,E),b=[["AGENTS.md",w],["GEMINI.md",w],["CLAUDE.md",J(y,`# OZMOZ DATA OS \u2014 DIRECTIVES AGENT
26
+ @AGENTS.md`)]],v=a.join(e,".cursorrules");if(i.existsSync(v)){let l=i.readFileSync(v,"utf8");(V.test(l)||l.includes(Q))&&b.push([".cursorrules",w])}for(let l of b)u("\u2192 "+l[0]+": "+j[Ee(a.join(e,l[0]),l[1],s)]);for(let l of f){let O=Z[l];if(l==="cursor")u("\u2192 "+O+" MCP (.cursor/mcp.json): "+j[M(a.join(e,".cursor","mcp.json"),s)]);else if(l==="windsurf")u("\u2192 "+O+" MCP (~/.codeium/windsurf/mcp_config.json): "+j[M(a.join(A.homedir(),".codeium","windsurf","mcp_config.json"),s)]);else if(l==="copilot")u("\u2192 "+O+" MCP (~/.copilot/mcp-config.json): "+j[M(a.join(A.homedir(),".copilot","mcp-config.json"),s,{type:"local",tools:["*"]})]);else if(l==="claude"&&c==="project"){let S=M(a.join(e,".mcp.json"),s);u("\u2192 "+O+" MCP (.mcp.json, project scope): "+j[S]),(S==="created"||S==="updated")&&u(" Claude Code asks you to approve a project server the first time you launch it. Commit .mcp.json to share it with your team (it contains no token)."),be(e)}else if(l==="gemini"){let S=[a.join(A.homedir(),".gemini","settings.json"),a.join(e,".gemini","settings.json"),a.join(e,".mcp.json")],T="unchanged";S.forEach(F=>{let P=M(F,s);(P==="created"||P==="updated")&&(T=P)}),u("\u2192 "+O+" MCP (settings.json & .mcp.json): "+j[T])}else if(l==="claude"||l==="codex"||l==="antigravity"){let S=l==="antigravity"?"agy":l,T=we(S,s,c);T.status==="manual"?u("\u2192 "+O+": '"+S+"' not found or not scriptable. Run manually: "+T.detail):T.status==="planned"?u("\u2192 "+O+" MCP: would run: "+T.detail):T.status==="failed"?g("\u2192 "+O+" MCP: registration failed ("+T.message+"). Run manually: "+T.detail):u("\u2192 "+O+" MCP"+(l==="claude"?" ("+c+" scope)":"")+": "+j[T.status]),T.legacy&&u(" \u26A0\uFE0F An old MCP entry named 'fleetbo' exists. Remove it: "+S+" mcp remove fleetbo")}else l==="devin"&&u("\u2192 "+O+": reads AGENTS.md. Devin runs in its own environment: add the OZmoz MCP server from Devin's settings (not automated).")}!n&&f.length===0&&u("\u2192 No agent detected: instruction files were written; re-run with --agent=<name> to register the MCP server.");let k=!!($(e).FLEETBO_DEV_TOKEN||process.env.FLEETBO_DEV_TOKEN),z=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(z))try{k=k||!!JSON.parse(i.readFileSync(z,"utf8")).devToken}catch{}k||g('\u26A0\uFE0F No developer token found. Run "npx ozmoz login" once.'),process.env.FLEETBO_START||u(`
27
27
  [OZmoz] Done.
28
- `)}function Pe(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?'start ""':"xdg-open";ie(`${t} "${e}"`)}function De(e){return new Promise((t,s)=>{let n=re.createServer((r,o)=>{if(o.setHeader("Access-Control-Allow-Origin","*"),o.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),o.setHeader("Access-Control-Allow-Private-Network","true"),r.method==="OPTIONS"){o.writeHead(204),o.end();return}let d=new URL(r.url,"http://127.0.0.1");if(d.pathname==="/callback"){let c=d.searchParams.get("token"),h=d.searchParams.get("refresh");if(!c){o.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),o.end("<h3>Error: Missing token.</h3>");return}let f=a.join(A.homedir(),".fleetbo");i.existsSync(f)||i.mkdirSync(f,{recursive:!0,mode:448}),ee(a.join(f,"credentials.json"),JSON.stringify({devToken:c,refreshToken:h||null,updatedAt:new Date().toISOString()},null,2));let p=a.join(e,".env");if(i.existsSync(p)){let m=i.readFileSync(p,"utf8");m.includes("FLEETBO_DEV_TOKEN=")?m=m.replace(/FLEETBO_DEV_TOKEN=.*/g,`FLEETBO_DEV_TOKEN=${c}`):m+=`
28
+ `)}function Pe(e){let t=a.join(A.homedir(),".fleetbo","credentials.json"),s=!1;try{i.existsSync(t)&&(i.unlinkSync(t),s=!0)}catch(o){g("Could not remove the saved sign-in: "+o.message),process.exit(1)}try{let o=a.join(e,".env");if(i.existsSync(o)){let r=i.readFileSync(o,"utf8"),n=r.replace(/^[ \t]*FLEETBO_DEV_TOKEN=.*(\r?\n|$)/gm,"");n!==r&&i.writeFileSync(o,n,"utf8")}}catch{}u(s?"[OZmoz] Signed out: the saved sign-in was removed from this computer.":"[OZmoz] You were not signed in on this computer."),process.env.FLEETBO_DEV_TOKEN&&u("Note: FLEETBO_DEV_TOKEN is set in your shell: unset it to finish signing out.")}function De(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?'start ""':"xdg-open";ie(`${t} "${e}"`)}function je(e){return new Promise((t,s)=>{let o=re.createServer((r,n)=>{if(n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.setHeader("Access-Control-Allow-Private-Network","true"),r.method==="OPTIONS"){n.writeHead(204),n.end();return}let d=new URL(r.url,"http://127.0.0.1");if(d.pathname==="/callback"){let c=d.searchParams.get("token"),h=d.searchParams.get("refresh");if(!c){n.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),n.end("<h3>Error: Missing token.</h3>");return}let f=a.join(A.homedir(),".fleetbo");i.existsSync(f)||i.mkdirSync(f,{recursive:!0,mode:448}),ee(a.join(f,"credentials.json"),JSON.stringify({devToken:c,refreshToken:h||null,updatedAt:new Date().toISOString()},null,2));let p=a.join(e,".env");if(i.existsSync(p)){let m=i.readFileSync(p,"utf8");m.includes("FLEETBO_DEV_TOKEN=")?m=m.replace(/FLEETBO_DEV_TOKEN=.*/g,`FLEETBO_DEV_TOKEN=${c}`):m+=`
29
29
  FLEETBO_DEV_TOKEN=${c}
30
- `,i.writeFileSync(p,m,"utf8")}o.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),o.end(`
30
+ `,i.writeFileSync(p,m,"utf8")}n.writeHead(200,{"Content-Type":"text/html; charset=utf-8",Connection:"close"}),n.end(`
31
31
  <!DOCTYPE html>
32
32
  <html>
33
33
  <head>
@@ -48,25 +48,25 @@ FLEETBO_DEV_TOKEN=${c}
48
48
  `),u(`
49
49
  [OZmoz] Developer token received and stored successfully!`),!process.env.FLEETBO_START&&!["AGENTS.md","CLAUDE.md","GEMINI.md"].some(m=>i.existsSync(a.join(e,m)))&&(u(`
50
50
  Next step to connect your AI agents:`),u(` npx ozmoz mcp (Configure Claude Code, Cursor, Windsurf, Devin, Codex CLI, Gemini CLI, Antigravity CLI, GitHub Copilot)
51
- `)),typeof n.closeAllConnections=="function"&&n.closeAllConnections(),n.close(()=>t()),setTimeout(()=>t(),300)}});n.listen(0,"127.0.0.1",()=>{let o=`https://ozmoz.io/cli-auth?port=${n.address().port}`;u(`
52
- [OZmoz] Waiting for authentication...`),u(`If your browser does not open automatically, visit: ${o}`),Pe(o);let d=Number(process.env.FLEETBO_LOGIN_TIMEOUT_MS)||12e4;setTimeout(()=>{try{typeof n.closeAllConnections=="function"&&n.closeAllConnections()}catch{}n.close(),s(new Error(`Login timed out after ${Math.round(d/1e3)}s: browser approval not received. Run "npx ozmoz login" once more and approve in the browser.`))},d).unref()}),n.on("error",r=>s(r))})}async function je(e,t,s){let n=await U();return new Promise((r,o)=>{let d=JSON.stringify({enterpriseID:e,schema:t,workflow:s}),c={hostname:"api.ozmoz.io",path:"/sync-schema",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(d),...n?{Authorization:`Bearer ${n}`}:{}}},h=Y.request(c,f=>{let p="";f.on("data",m=>{p+=m}),f.on("end",()=>{f.statusCode>=200&&f.statusCode<300?r(JSON.parse(p)):f.statusCode===401?o(new Error('Please sign in first: run "npx ozmoz login".')):f.statusCode===403?o(new Error("Access denied: your account does not have access to this project.")):o(new Error(`OZmoz sync failed with HTTP ${f.statusCode}`))})});h.on("error",f=>o(f)),h.write(d),h.end()})}function $(e){let t=a.join(e,".env");if(!i.existsSync(t))return{};let s=i.readFileSync(t,"utf8"),n={};return s.split(`
53
- `).forEach(r=>{let[o,...d]=r.split("=");o&&d.length>0&&(n[o.trim()]=d.join("=").trim())}),n}async function W(e,t){let s=await U();return new Promise((n,r)=>{let o=JSON.stringify({projectId:e,moduleName:t}),d={hostname:"api.ozmoz.io",path:"/cli/getmodulecache",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(o),...s?{Authorization:`Bearer ${s}`}:{}}},c=Y.request(d,h=>{let f="";h.on("data",p=>{f+=p}),h.on("end",()=>{if(h.statusCode>=200&&h.statusCode<300)try{let p=JSON.parse(f);if(p.success&&p.found&&p.module){let m=p.module.code||p.module.mockCode;n(typeof m=="string"?JSON.parse(m):m)}else n(null)}catch{r(new Error(`Invalid JSON response for ${t}.`))}else h.statusCode===401||h.statusCode===403?r(new Error('Access denied. Run "npx ozmoz login" with an account that has access to this project.')):r(new Error(`Server error ${h.statusCode} while fetching ${t}`))})});c.on("error",h=>r(h)),c.write(o),c.end()})}var C=process.argv.slice(2),x=C[0],Re=["id","_id","userId","author","dateCreated","createdAt","_schema_version"],se=e=>Re.includes(e)||/^_/.test(e)||/^(created|updated|modified|deleted)(At|By)$/i.test(e);function B(e){return!e||typeof e!="object"?null:e.fields&&typeof e.fields=="object"?e.fields:e.schema&&typeof e.schema=="object"?e.schema:null}function Fe(e){let t=[];if(!e||typeof e!="object"||!e.collections)return{schema:e,changed:!1,notes:t};let s=JSON.parse(JSON.stringify(e));return Object.entries(s.collections).forEach(([n,r])=>{let o=B(r);o&&Object.keys(o).forEach(d=>{se(d)&&o[d]&&typeof o[d]=="object"&&o[d].required===!0&&(o[d].required=!1,t.push(n+"."+d))})}),{schema:s,changed:t.length>0,notes:t}}function Le(e){let t=String(typeof e=="string"?e:e&&e.type||"").toLowerCase(),s=e&&(e.enum||e.values||e.options);return Array.isArray(s)&&s.length?JSON.stringify(s[0]):t==="number"||t==="integer"||t==="float"?"0":t==="boolean"||t==="toggle"?"false":t==="date"||t==="datetime"||t==="timestamp"?"new Date().toISOString()":t==="reference"?"'<id du document li\xE9>'":t==="media"?"null /* image/fichier : oz.addWithMedia */":t==="array"?"[]":"'\u2026'"}function Ze(e){let s=Object.entries(e&&e.collections||{}),n=`## \u{1F4E5} CE QUE LE CODE DOIT ENVOYER (MOD\xC8LES D'\xC9CRITURE)
51
+ `)),typeof o.closeAllConnections=="function"&&o.closeAllConnections(),o.close(()=>t()),setTimeout(()=>t(),300)}});o.listen(0,"127.0.0.1",()=>{let n=`https://ozmoz.io/cli-auth?port=${o.address().port}`;u(`
52
+ [OZmoz] Waiting for authentication...`),u(`If your browser does not open automatically, visit: ${n}`),De(n);let d=Number(process.env.FLEETBO_LOGIN_TIMEOUT_MS)||12e4;setTimeout(()=>{try{typeof o.closeAllConnections=="function"&&o.closeAllConnections()}catch{}o.close(),s(new Error(`Login timed out after ${Math.round(d/1e3)}s: browser approval not received. Run "npx ozmoz login" once more and approve in the browser.`))},d).unref()}),o.on("error",r=>s(r))})}async function Re(e,t,s){let o=await U();return new Promise((r,n)=>{let d=JSON.stringify({enterpriseID:e,schema:t,workflow:s}),c={hostname:"api.ozmoz.io",path:"/sync-schema",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(d),...o?{Authorization:`Bearer ${o}`}:{}}},h=Y.request(c,f=>{let p="";f.on("data",m=>{p+=m}),f.on("end",()=>{f.statusCode>=200&&f.statusCode<300?r(JSON.parse(p)):f.statusCode===401?n(new Error('Please sign in first: run "npx ozmoz login".')):f.statusCode===403?n(new Error("Access denied: your account does not have access to this project.")):n(new Error(`OZmoz sync failed with HTTP ${f.statusCode}`))})});h.on("error",f=>n(f)),h.write(d),h.end()})}function $(e){let t=a.join(e,".env");if(!i.existsSync(t))return{};let s=i.readFileSync(t,"utf8"),o={};return s.split(`
53
+ `).forEach(r=>{let[n,...d]=r.split("=");n&&d.length>0&&(o[n.trim()]=d.join("=").trim())}),o}async function W(e,t){let s=await U();return new Promise((o,r)=>{let n=JSON.stringify({projectId:e,moduleName:t}),d={hostname:"api.ozmoz.io",path:"/cli/getmodulecache",method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n),...s?{Authorization:`Bearer ${s}`}:{}}},c=Y.request(d,h=>{let f="";h.on("data",p=>{f+=p}),h.on("end",()=>{if(h.statusCode>=200&&h.statusCode<300)try{let p=JSON.parse(f);if(p.success&&p.found&&p.module){let m=p.module.code||p.module.mockCode;o(typeof m=="string"?JSON.parse(m):m)}else o(null)}catch{r(new Error(`Invalid JSON response for ${t}.`))}else h.statusCode===401||h.statusCode===403?r(new Error('Access denied. Run "npx ozmoz login" with an account that has access to this project.')):r(new Error(`Server error ${h.statusCode} while fetching ${t}`))})});c.on("error",h=>r(h)),c.write(n),c.end()})}var C=process.argv.slice(2),I=C[0],Fe=["id","_id","userId","author","dateCreated","createdAt","_schema_version"],se=e=>Fe.includes(e)||/^_/.test(e)||/^(created|updated|modified|deleted)(At|By)$/i.test(e);function B(e){return!e||typeof e!="object"?null:e.fields&&typeof e.fields=="object"?e.fields:e.schema&&typeof e.schema=="object"?e.schema:null}function Le(e){let t=[];if(!e||typeof e!="object"||!e.collections)return{schema:e,changed:!1,notes:t};let s=JSON.parse(JSON.stringify(e));return Object.entries(s.collections).forEach(([o,r])=>{let n=B(r);n&&Object.keys(n).forEach(d=>{se(d)&&n[d]&&typeof n[d]=="object"&&n[d].required===!0&&(n[d].required=!1,t.push(o+"."+d))})}),{schema:s,changed:t.length>0,notes:t}}function Ze(e){let t=String(typeof e=="string"?e:e&&e.type||"").toLowerCase(),s=e&&(e.enum||e.values||e.options);return Array.isArray(s)&&s.length?JSON.stringify(s[0]):t==="number"||t==="integer"||t==="float"?"0":t==="boolean"||t==="toggle"?"false":t==="date"||t==="datetime"||t==="timestamp"?"new Date().toISOString()":t==="reference"?"'<id du document li\xE9>'":t==="media"?"null /* image/fichier : oz.addWithMedia */":t==="array"?"[]":"'\u2026'"}function Me(e){let s=Object.entries(e&&e.collections||{}),o=`## \u{1F4E5} CE QUE LE CODE DOIT ENVOYER (MOD\xC8LES D'\xC9CRITURE)
54
54
 
55
- `;n+=`### \u{1F194} Identifiants
56
- `,n+="* OZmoz attribue lui-m\xEAme `_id` (cha\xEEne) \xE0 chaque document. Utilise `doc._id` partout ; \xE0 la lecture, `doc.id` existe comme alias de `_id` (m\xEAme valeur), en prototype comme en production, mais la r\xE9f\xE9rence est `_id`.\n",n+="* N'envoie **jamais** `id` ni `_id` dans `oz.add` : `oz.add` renvoie `{ success, documentId }` (`documentId` = `_id`).\n",n+="* Pour lire, modifier ou supprimer un document : `oz.getDoc(table, doc._id)`, `oz.update(table, doc._id, {\u2026})`, `oz.delete(table, doc._id)`. Pour relier deux collections, stocke le `_id` du document li\xE9 dans un champ (ex. `playlistId`).\n",n+="* `userId`, `createdAt` et les autres champs de tra\xE7abilit\xE9 sont renseign\xE9s par le moteur : ne les envoie pas.\n\n";let r=s.filter(([,o])=>B(o)&&Object.keys(B(o)).length>0);return r.length===0?n+`_Aucune collection scell\xE9e pour l'instant : les mod\xE8les appara\xEEtront apr\xE8s la mod\xE9lisation d'Alex._
57
- `:(r.forEach(([o,d])=>{let c=B(d),h=Object.entries(c).filter(([m])=>!se(m));n+="### `"+o+`\`
55
+ `;o+=`### \u{1F194} Identifiants
56
+ `,o+="* OZmoz attribue lui-m\xEAme `_id` (cha\xEEne) \xE0 chaque document. Utilise `doc._id` partout ; \xE0 la lecture, `doc.id` existe comme alias de `_id` (m\xEAme valeur), en prototype comme en production, mais la r\xE9f\xE9rence est `_id`.\n",o+="* N'envoie **jamais** `id` ni `_id` dans `oz.add` : `oz.add` renvoie `{ success, documentId }` (`documentId` = `_id`).\n",o+="* Pour lire, modifier ou supprimer un document : `oz.getDoc(table, doc._id)`, `oz.update(table, doc._id, {\u2026})`, `oz.delete(table, doc._id)`. Pour relier deux collections, stocke le `_id` du document li\xE9 dans un champ (ex. `playlistId`).\n",o+="* `userId`, `createdAt` et les autres champs de tra\xE7abilit\xE9 sont renseign\xE9s par le moteur : ne les envoie pas.\n\n";let r=s.filter(([,n])=>B(n)&&Object.keys(B(n)).length>0);return r.length===0?o+`_Aucune collection scell\xE9e pour l'instant : les mod\xE8les appara\xEEtront apr\xE8s la mod\xE9lisation d'Alex._
57
+ `:(r.forEach(([n,d])=>{let c=B(d),h=Object.entries(c).filter(([m])=>!se(m));o+="### `"+n+`\`
58
58
 
59
59
  | Champ | Type | Obligatoire | Valeurs / remarques |
60
60
  |---|---|---|---|
61
- `,h.forEach(([m,g])=>{let w=typeof g=="string"?g:g&&g.type||"any",E=g&&(g.enum||g.values||g.options),b=Array.isArray(E)&&E.length?"parmi : "+E.map(v=>"`"+v+"`").join(", "):"";n+="| `"+m+"` | "+w+" | "+(g&&g.required===!0?"\u2705 oui":"non")+" | "+b+` |
62
- `});let f=h.filter(([,m])=>m&&m.required===!0),p=h.filter(([,m])=>!(m&&m.required===!0));n+="\nInsertion valide :\n```js\nawait oz.add('"+o+`', {
63
- `,f.forEach(([m,g])=>{n+=" "+m+": "+Le(g)+`,
64
- `}),p.length&&(n+=" // optionnels : "+p.map(([m])=>m).join(", ")+`
65
- `),n+=`}, {
66
- `,n+=" desc: 'Cr\xE9ation d\\'un \xE9l\xE9ment dans "+o+`',
67
- `,n+=` role: 'AUTHENTICATED' // ou 'ANONYMOUS', 'ADMIN'
68
- `,n+=` // guard: 'condition sur les donn\xE9es' (optionnel)
69
- `,n+="});\n```\n\n"}),n)}function Me(e,t,s=""){return`# THE OZMOZ DATA CONTRACT (SVRO DATA CONTRACT)
61
+ `,h.forEach(([m,y])=>{let E=typeof y=="string"?y:y&&y.type||"any",w=y&&(y.enum||y.values||y.options),b=Array.isArray(w)&&w.length?"parmi : "+w.map(v=>"`"+v+"`").join(", "):"";o+="| `"+m+"` | "+E+" | "+(y&&y.required===!0?"\u2705 oui":"non")+" | "+b+` |
62
+ `});let f=h.filter(([,m])=>m&&m.required===!0),p=h.filter(([,m])=>!(m&&m.required===!0));o+="\nInsertion valide :\n```js\nawait oz.add('"+n+`', {
63
+ `,f.forEach(([m,y])=>{o+=" "+m+": "+Ze(y)+`,
64
+ `}),p.length&&(o+=" // optionnels : "+p.map(([m])=>m).join(", ")+`
65
+ `),o+=`}, {
66
+ `,o+=" desc: 'Cr\xE9ation d\\'un \xE9l\xE9ment dans "+n+`',
67
+ `,o+=` role: 'AUTHENTICATED' // ou 'ANONYMOUS', 'ADMIN'
68
+ `,o+=` // guard: 'condition sur les donn\xE9es' (optionnel)
69
+ `,o+="});\n```\n\n"}),o)}function Ue(e,t,s=""){return`# THE OZMOZ DATA CONTRACT (SVRO DATA CONTRACT)
70
70
 
71
71
  ### \u{1F6A8} MANDATORY CODE RULES (READ BEFORE WRITING ANY VIEW)
72
72
  1. **Identifiers:** the database generates \`_id\` (string) for each document. Use \`doc._id\` for \`key={doc._id}\`, for \`oz.getDoc/update/delete\`, and to link two collections (store the linked document's \`_id\` in a field, e.g., \`playlistId\`). \`doc.id\` exists on read as an alias (same value), but the canonical reference is \`_id\`.
@@ -612,7 +612,7 @@ ${e?.context||t?.context||"No written specifications provided."}
612
612
 
613
613
  ---
614
614
 
615
- ${Ze(e)}
615
+ ${Me(e)}
616
616
 
617
617
  ---
618
618
 
@@ -627,27 +627,27 @@ ${JSON.stringify({...e||{},context:void 0},null,2)}
627
627
  \`\`\`json
628
628
  ${JSON.stringify(t||{},null,2)}
629
629
  \`\`\`
630
- `}function Ue(e){return String(e).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]/g,"_").replace(/^_+|_+$/g,"").slice(0,30)||"app"}async function Be(e,t){let s=$(e),n=i.existsSync(a.join(e,"svro.schema.json"));(s.OZ_DB_KEY||n)&&(y("Cannot create project: an OZmoz project already exists in this folder."),u('\u2192 Use "npx ozmoz sync" or evolve the existing contract instead.'),process.exit(1));let r=(t||"").trim();r||(y('Project name is required. Usage: npx ozmoz create "<name>"'),process.exit(1));let o=a.join(e,".ozmoz.lock");if(i.existsSync(o)){let c=!1;try{let h=Number(i.readFileSync(o,"utf8"));Date.now()-h>6e4&&(c=!0)}catch{c=!0}c||(y("A project creation is already running in this folder."),process.exit(1)),i.unlinkSync(o)}i.writeFileSync(o,String(Date.now()));let d=()=>{if(i.existsSync(o))try{i.unlinkSync(o)}catch{}};try{let c=process.env.FLEETBO_DEV_TOKEN;if(!c){let E=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(E))try{c=JSON.parse(i.readFileSync(E,"utf8")).devToken}catch{}}c||(d(),y('Missing developer token. Please run "npx ozmoz login" first.'),process.exit(1)),u(`[OZmoz] Creating project "${r}" on Cloud...`);let h=Ue(r),f=[h,`${h.slice(0,24)}_${Math.random().toString(36).slice(2,6)}`,`${h.slice(0,24)}_${Math.random().toString(36).slice(2,6)}`],p=null,m=null;for(let E of f)try{let b=await fetch(X+"createprojectlight",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({data:{name:r,keyApp:E}})}),v=await b.json();if(b.ok&&!v.error){p={keyApp:E,data:v.result?.data||v.data||{}};break}else m=v.error?.message||`HTTP ${b.status}`}catch(b){m=b.message}p||(d(),y(`Failed to create project on Cloud: ${m||"Unknown error"}`),process.exit(1));let g=p.data.bootstrapToken;await q(e,[`--keyApp=${p.keyApp}`,`--token=${g}`]);let w=a.join(e,"package.json");K(e,w),await ne(e,[]),u(`
630
+ `}function Be(e){return String(e).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]/g,"_").replace(/^_+|_+$/g,"").slice(0,30)||"app"}async function $e(e,t){let s=$(e),o=i.existsSync(a.join(e,"svro.schema.json"));(s.OZ_DB_KEY||o)&&(g("Cannot create project: an OZmoz project already exists in this folder."),u('\u2192 Use "npx ozmoz sync" or evolve the existing contract instead.'),process.exit(1));let r=(t||"").trim();r||(g('Project name is required. Usage: npx ozmoz create "<name>"'),process.exit(1));let n=a.join(e,".ozmoz.lock");if(i.existsSync(n)){let c=!1;try{let h=Number(i.readFileSync(n,"utf8"));Date.now()-h>6e4&&(c=!0)}catch{c=!0}c||(g("A project creation is already running in this folder."),process.exit(1)),i.unlinkSync(n)}i.writeFileSync(n,String(Date.now()));let d=()=>{if(i.existsSync(n))try{i.unlinkSync(n)}catch{}};try{let c=process.env.FLEETBO_DEV_TOKEN;if(!c){let w=a.join(A.homedir(),".fleetbo","credentials.json");if(i.existsSync(w))try{c=JSON.parse(i.readFileSync(w,"utf8")).devToken}catch{}}c||(d(),g('Missing developer token. Please run "npx ozmoz login" first.'),process.exit(1)),u(`[OZmoz] Creating project "${r}" on Cloud...`);let h=Be(r),f=[h,`${h.slice(0,24)}_${Math.random().toString(36).slice(2,6)}`,`${h.slice(0,24)}_${Math.random().toString(36).slice(2,6)}`],p=null,m=null;for(let w of f)try{let b=await fetch(X+"createprojectlight",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({data:{name:r,keyApp:w}})}),v=await b.json();if(b.ok&&!v.error){p={keyApp:w,data:v.result?.data||v.data||{}};break}else m=v.error?.message||`HTTP ${b.status}`}catch(b){m=b.message}p||(d(),g(`Failed to create project on Cloud: ${m||"Unknown error"}`),process.exit(1));let y=p.data.bootstrapToken;await q(e,[`--keyApp=${p.keyApp}`,`--token=${y}`]);let E=a.join(e,"package.json");K(e,E),await ne(e,[]),u(`
631
631
  [OZmoz] Project "${r}" (${p.keyApp}) created and configured successfully.`),u(`AI AGENTS: do NOT stop here and do NOT ask the user to restart. Continue NOW in the same turn: scaffold the frontend if missing, run "npx ozmoz sync", read ozmoz_contract.md, write ALL views in trial mode (OZ_PROTOTYPE=true), then start the dev server and ask the user to validate.
632
- `)}finally{if(i.existsSync(o))try{i.unlinkSync(o)}catch{}}}async function $e(e){let t=await U(),n=$(e).OZ_KEY_APP;(!n||!t)&&(y("Cannot update: project uninitialized or dev token missing."),process.exit(1));let r=i.existsSync(a.join(e,"src"))?a.join(e,"src"):e,o=new Set([".jsx",".tsx",".vue",".svelte",".js",".ts",".html"]),d=[],c=0;function h(z){let l=[];try{l=i.readdirSync(z,{withFileTypes:!0})}catch{return}for(let O of l){if(/^(node_modules|\.git|dist|build|\.next|\.svelte-kit)$/.test(O.name))continue;let S=a.join(z,O.name);if(O.isDirectory())h(S);else if(o.has(a.extname(O.name))&&!O.name.endsWith(".d.ts"))try{let T=i.statSync(S);if(T.size>3e5)continue;let F=i.readFileSync(S,"utf8");/oz\.|<oz-/i.test(F)&&(c+=T.size,d.push({name:a.relative(e,S).split(a.sep).join("/"),content:F}))}catch{}}}let f=C.find(z=>z.startsWith("--files=")),p=f?f.slice(8).split(",").map(z=>z.trim()).filter(Boolean):null;if(p&&p.length>0)for(let z of p){let l=a.resolve(e,z);if(i.existsSync(l)){let O=i.readFileSync(l,"utf8");c+=i.statSync(l).size,d.push({name:a.relative(e,l).split(a.sep).join("/"),content:O})}}else h(r);d.length===0&&(y("Cannot update: no components using oz.* found."),process.exit(1)),c>8*1024*1024&&(y("Payload too large: total UI source files exceed 8 MB limit."),process.exit(1));let m=C.find(z=>z.startsWith("--rules=")),g=m?m.slice(8).trim():"",w=C.find(z=>z.startsWith("--reasoning=")),E=w?w.slice(12).trim().toLowerCase():void 0;E!=="standard"&&E!=="high"&&(y("Missing or invalid --reasoning=<standard|high>."),y("If you are an AI agent: ask the user which analysis depth they want (numbered [1]/[2] choice, recommended option first) before running this command, then pass --reasoning=standard or --reasoning=high accordingly. Never pick it yourself."),process.exit(1)),u(`[OZmoz] Sending ${d.length} component(s) to Cloud Engine for modeling...`);try{let z,l,O;for(let S=1;S<=3&&(z=await fetch("https://updateprojectlight-jqycakhlxa-uc.a.run.app",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({data:{keyApp:n,name:n,newViewFiles:d,oz_rules:g,reasoning:E}})}),l=await z.json().catch(()=>({})),O=l.result?.data||l.data||l,!(z.status<500||S===3));S++)u("\u2192 The modeling service is busy (attempt "+S+"/3). Retrying in 20s..."),await new Promise(T=>setTimeout(T,2e4));if(!z.ok||l.error||O.success===!1){let S=l.error?.message||O.warnings?.join(", ")||l.message||"Server error";y(`Update failed: ${S}`),process.exit(1)}u("\u2192 Cloud modeling response: "+JSON.stringify(l).slice(0,800))}catch(z){y(`Network error: ${z.message}`),process.exit(1)}u("\u2192 Structure modeled. Sealing into OZmoz SVRO Kernel...");let b=I(process.execPath,[__filename,"sync"],{stdio:"inherit",cwd:e}),v=Date.now();for(let z=1;z<=5&&b.status===0;z++){let l=!1;try{let O=JSON.parse(i.readFileSync(a.join(e,"svro.schema.json"),"utf8")),S=JSON.parse(i.readFileSync(a.join(e,"svro.workflow.json"),"utf8"));l=Object.keys(O.collections||{}).length>0&&(S.sequences||[]).length>0}catch{}if(l)break;u("\u2192 Contract still empty, waiting for the cloud (attempt "+z+"/5, "+Math.round((Date.now()-v)/1e3)+"s elapsed)..."),await new Promise(O=>setTimeout(O,6e3)),b=I(process.execPath,[__filename,"sync"],{stdio:"inherit",cwd:e})}let N=!1,k=!1;try{let z=JSON.parse(i.readFileSync(a.join(e,"svro.schema.json"),"utf8"));N=Object.keys(z.collections||{}).length>0,k=(JSON.parse(i.readFileSync(a.join(e,"svro.workflow.json"),"utf8")).sequences||[]).length>0}catch{}b.status===0&&N&&k?u(`
632
+ `)}finally{if(i.existsSync(n))try{i.unlinkSync(n)}catch{}}}async function Ge(e){let t=await U(),o=$(e).OZ_KEY_APP;(!o||!t)&&(g("Cannot update: project uninitialized or dev token missing."),process.exit(1));let r=i.existsSync(a.join(e,"src"))?a.join(e,"src"):e,n=new Set([".jsx",".tsx",".vue",".svelte",".js",".ts",".html"]),d=[],c=0;function h(z){let l=[];try{l=i.readdirSync(z,{withFileTypes:!0})}catch{return}for(let O of l){if(/^(node_modules|\.git|dist|build|\.next|\.svelte-kit)$/.test(O.name))continue;let S=a.join(z,O.name);if(O.isDirectory())h(S);else if(n.has(a.extname(O.name))&&!O.name.endsWith(".d.ts"))try{let T=i.statSync(S);if(T.size>3e5)continue;let F=i.readFileSync(S,"utf8");/oz\.|<oz-/i.test(F)&&(c+=T.size,d.push({name:a.relative(e,S).split(a.sep).join("/"),content:F}))}catch{}}}let f=C.find(z=>z.startsWith("--files=")),p=f?f.slice(8).split(",").map(z=>z.trim()).filter(Boolean):null;if(p&&p.length>0)for(let z of p){let l=a.resolve(e,z);if(i.existsSync(l)){let O=i.readFileSync(l,"utf8");c+=i.statSync(l).size,d.push({name:a.relative(e,l).split(a.sep).join("/"),content:O})}}else h(r);d.length===0&&(g("Cannot update: no components using oz.* found."),process.exit(1)),c>8*1024*1024&&(g("Payload too large: total UI source files exceed 8 MB limit."),process.exit(1));let m=C.find(z=>z.startsWith("--rules=")),y=m?m.slice(8).trim():"",E=C.find(z=>z.startsWith("--reasoning=")),w=E?E.slice(12).trim().toLowerCase():void 0;w!=="standard"&&w!=="high"&&(g("Missing or invalid --reasoning=<standard|high>."),g("If you are an AI agent: ask the user which analysis depth they want (numbered [1]/[2] choice, recommended option first) before running this command, then pass --reasoning=standard or --reasoning=high accordingly. Never pick it yourself."),process.exit(1)),u(`[OZmoz] Sending ${d.length} component(s) to Cloud Engine for modeling...`);try{let z,l,O;for(let S=1;S<=3&&(z=await fetch("https://updateprojectlight-jqycakhlxa-uc.a.run.app",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({data:{keyApp:o,name:o,newViewFiles:d,oz_rules:y,reasoning:w}})}),l=await z.json().catch(()=>({})),O=l.result?.data||l.data||l,!(z.status<500||S===3));S++)u("\u2192 The modeling service is busy (attempt "+S+"/3). Retrying in 20s..."),await new Promise(T=>setTimeout(T,2e4));if(!z.ok||l.error||O.success===!1){let S=l.error?.message||O.warnings?.join(", ")||l.message||"Server error";g(`Update failed: ${S}`),process.exit(1)}u("\u2192 Cloud modeling response: "+JSON.stringify(l).slice(0,800))}catch(z){g(`Network error: ${z.message}`),process.exit(1)}u("\u2192 Structure modeled. Sealing into OZmoz SVRO Kernel...");let b=x(process.execPath,[__filename,"sync"],{stdio:"inherit",cwd:e}),v=Date.now();for(let z=1;z<=5&&b.status===0;z++){let l=!1;try{let O=JSON.parse(i.readFileSync(a.join(e,"svro.schema.json"),"utf8")),S=JSON.parse(i.readFileSync(a.join(e,"svro.workflow.json"),"utf8"));l=Object.keys(O.collections||{}).length>0&&(S.sequences||[]).length>0}catch{}if(l)break;u("\u2192 Contract still empty, waiting for the cloud (attempt "+z+"/5, "+Math.round((Date.now()-v)/1e3)+"s elapsed)..."),await new Promise(O=>setTimeout(O,6e3)),b=x(process.execPath,[__filename,"sync"],{stdio:"inherit",cwd:e})}let N=!1,k=!1;try{let z=JSON.parse(i.readFileSync(a.join(e,"svro.schema.json"),"utf8"));N=Object.keys(z.collections||{}).length>0,k=(JSON.parse(i.readFileSync(a.join(e,"svro.workflow.json"),"utf8")).sequences||[]).length>0}catch{}b.status===0&&N&&k?u(`
633
633
  [OZmoz] Contract locked into SVRO Kernel.
634
- `):b.status===0&&N&&!k?(y(`
634
+ `):b.status===0&&N&&!k?(g(`
635
635
  [OZmoz] Contract incomplete: the workflow is empty. Rerun the update before writing any code.
636
- `),process.exit(1)):b.status===0&&!N?(y(`
636
+ `),process.exit(1)):b.status===0&&!N?(g(`
637
637
  [OZmoz] Sync completed with 0 collections. Rerun with --reasoning=high.
638
- `),process.exit(1)):(y(`
638
+ `),process.exit(1)):(g(`
639
639
  [OZmoz] Sync failed. Run "npx ozmoz sync".
640
- `),process.exit(1))}async function Ge(){let e=process.cwd(),t=a.join(e,"package.json");if(x==="init"||x==="doctor")u(`
640
+ `),process.exit(1))}async function Ve(){let e=process.cwd(),t=a.join(e,"package.json");if(I==="init"||I==="doctor")u(`
641
641
  [OZmoz] Initializing and configuring OZmoz...`),await q(e,C),K(e,t),u(`
642
642
  [OZmoz] Configuration completed successfully!
643
643
  `),u(`
644
644
  Next step:`),u(` npx ozmoz sync (Sync cloud schema & generate IDE types)
645
- `);else if(x==="sync"){let s=C.includes("--dry-run"),n=C.includes("--check-only");u(`[OZmoz] Syncing schema...${s?" (dry-run)":""}${n?" (check-only, no network)":""}`),s||me(e);let r=a.join(e,"svro.schema.json"),o=a.join(e,"svro.workflow.json"),d=a.join(e,"ozmoz_contract.md"),c=a.join(e,"src","ozmoz.d.ts"),f=$(e).OZ_ENTERPRISE_ID,p=null,m=null;if(n)u("\u2192 Mode check-only : Local contract used, no cloud fetch..");else if(f)try{u(" \u2192 Fetching latest contracts from OZmoz..."),p=await W(f,"svro.schema.json"),p&&(i.writeFileSync(r,JSON.stringify(p,null,2)+`
646
- `),u(" \u2192 Local svro.schema.json updated.")),m=await W(f,"svro.workflow.json"),m&&(i.writeFileSync(o,JSON.stringify(m,null,2)+`
647
- `),u(" \u2192 Local svro.workflow.json updated."))}catch(v){y(`\u26A0\uFE0F Cloud fetch bypassed: ${v.message}. Using local file fallback.`)}else y("\u26A0\uFE0F OZ_ENTERPRISE_ID missing in .env. Skipping cloud fetch.");let g=p;if(!g&&i.existsSync(r))try{g=JSON.parse(i.readFileSync(r,"utf8"))}catch{}g||(g={context:"Application en cours de mod\xE9lisation initiale.",collections:{}},i.writeFileSync(r,JSON.stringify(g,null,2)+`
648
- `,"utf8"),u("\u2192 Initial blank svro.schema.json created."));let w=m;if(!w&&i.existsSync(o))try{w=JSON.parse(i.readFileSync(o,"utf8"))}catch{}w||(w={actors:{},sequences:[]},i.writeFileSync(o,JSON.stringify(w,null,2)+`
649
- `,"utf8"),u("\u2192 Initial blank svro.workflow.json created."));{let v=Fe(g);v.changed&&(g=v.schema,i.writeFileSync(r,JSON.stringify(g,null,2)+`
650
- `,"utf8"),u("\u2192 Managed by system, no longer required from your code: "+v.notes.join(", ")+"."))}let{protocol:E}=await te(),b=Me(g,w,E);i.writeFileSync(d,b,"utf8"),u(" \u2192 Contract markdown successfully generated at project root.");try{let v=Object.keys(g.collections||{});if(f&&!n&&Object.keys(g.collections||{}).length>0)try{await je(f,g,w),u(" \u2192 Schema successfully sealed into OZmoz Kernel.")}catch(l){y(`\u26A0\uFE0F Kernel Shield sync warning: ${l.message}`)}let N=g.collections||{},k=Object.entries(N).map(([l,O])=>{let S=O.fields||O.schema||{},T=Object.entries(S).map(([F,P])=>{let L="any",D=String(typeof P=="string"?P:P.type||"").toLowerCase();return D==="string"||D==="text"||D==="media"?L="string":D==="number"?L="number":D==="boolean"||D==="toggle"?L="boolean":D==="array"&&(L="any[]"),` ${F}?:${L};`}).join(`
645
+ `);else if(I==="sync"){let s=C.includes("--dry-run"),o=C.includes("--check-only");u(`[OZmoz] Syncing schema...${s?" (dry-run)":""}${o?" (check-only, no network)":""}`),s||me(e);let r=a.join(e,"svro.schema.json"),n=a.join(e,"svro.workflow.json"),d=a.join(e,"ozmoz_contract.md"),c=a.join(e,"src","ozmoz.d.ts"),f=$(e).OZ_ENTERPRISE_ID,p=null,m=null;if(o)u("\u2192 Mode check-only : Local contract used, no cloud fetch..");else if(f)try{u(" \u2192 Fetching latest contracts from OZmoz..."),p=await W(f,"svro.schema.json"),p&&(i.writeFileSync(r,JSON.stringify(p,null,2)+`
646
+ `),u(" \u2192 Local svro.schema.json updated.")),m=await W(f,"svro.workflow.json"),m&&(i.writeFileSync(n,JSON.stringify(m,null,2)+`
647
+ `),u(" \u2192 Local svro.workflow.json updated."))}catch(v){g(`\u26A0\uFE0F Cloud fetch bypassed: ${v.message}. Using local file fallback.`)}else g("\u26A0\uFE0F OZ_ENTERPRISE_ID missing in .env. Skipping cloud fetch.");let y=p;if(!y&&i.existsSync(r))try{y=JSON.parse(i.readFileSync(r,"utf8"))}catch{}y||(y={context:"Application en cours de mod\xE9lisation initiale.",collections:{}},i.writeFileSync(r,JSON.stringify(y,null,2)+`
648
+ `,"utf8"),u("\u2192 Initial blank svro.schema.json created."));let E=m;if(!E&&i.existsSync(n))try{E=JSON.parse(i.readFileSync(n,"utf8"))}catch{}E||(E={actors:{},sequences:[]},i.writeFileSync(n,JSON.stringify(E,null,2)+`
649
+ `,"utf8"),u("\u2192 Initial blank svro.workflow.json created."));{let v=Le(y);v.changed&&(y=v.schema,i.writeFileSync(r,JSON.stringify(y,null,2)+`
650
+ `,"utf8"),u("\u2192 Managed by system, no longer required from your code: "+v.notes.join(", ")+"."))}let{protocol:w}=await te(),b=Ue(y,E,w);i.writeFileSync(d,b,"utf8"),u(" \u2192 Contract markdown successfully generated at project root.");try{let v=Object.keys(y.collections||{});if(f&&!o&&Object.keys(y.collections||{}).length>0)try{await Re(f,y,E),u(" \u2192 Schema successfully sealed into OZmoz Kernel.")}catch(l){g(`\u26A0\uFE0F Kernel Shield sync warning: ${l.message}`)}let N=y.collections||{},k=Object.entries(N).map(([l,O])=>{let S=O.fields||O.schema||{},T=Object.entries(S).map(([F,P])=>{let L="any",D=String(typeof P=="string"?P:P.type||"").toLowerCase();return D==="string"||D==="text"||D==="media"?L="string":D==="number"?L="number":D==="boolean"||D==="toggle"?L="boolean":D==="array"&&(L="any[]"),` ${F}?:${L};`}).join(`
651
651
  `);return` ${l}: {
652
652
  ${T}
653
653
  };`}).join(`
@@ -799,10 +799,11 @@ declare module 'svelte/elements' {
799
799
  'oz-reference': OzProp;
800
800
  }
801
801
  }
802
- `;i.writeFileSync(c,l)}le(e),de(e,t),ue(e),pe(e),u(`[OZmoz] Schema synced successfully (${v.length} collection(s)).`),s&&u(" \u2192 [Dry-run] Schema is valid.")}catch(v){y(`Error during synchronization: ${v.message}`),process.exit(1)}}else if(x==="create"){let s=C.slice(1).filter(n=>!n.startsWith("--")).join(" ");await Be(e,s),process.exit(0)}else if(x==="update")await $e(e),process.exit(0);else if(x==="mcp"){let s=C.includes("--run"),n=!1;if(!s&&!process.stdin.isTTY&&(s=await new Promise(r=>{let o=process.stdin,d=null,c=p=>{clearTimeout(d),o.removeListener("data",h),o.removeListener("end",f),o.removeListener("error",f),r(p)},h=p=>{o.pause(),o.unshift(p),n=!0,c(!0)},f=()=>c(!1);d=setTimeout(()=>{o.pause(),c(!1)},1500),o.on("data",h),o.once("end",f),o.once("error",f)})),s){try{await import(`file://${oe()}`),n&&process.stdin.resume()}catch(r){y(`Failed to start MCP server: ${r.message}`),process.exit(1)}return}await ne(e,C),process.exit(0)}else x==="login"?(await De(e),process.exit(0)):x==="start"?Ne(e,C):["--help","-h","help"].includes(x)?(u(`OZmoz CLI
802
+ `;i.writeFileSync(c,l)}le(e),de(e,t),ue(e),pe(e),u(`[OZmoz] Schema synced successfully (${v.length} collection(s)).`),s&&u(" \u2192 [Dry-run] Schema is valid.")}catch(v){g(`Error during synchronization: ${v.message}`),process.exit(1)}}else if(I==="create"){let s=C.slice(1).filter(o=>!o.startsWith("--")).join(" ");await $e(e,s),process.exit(0)}else if(I==="update")await Ge(e),process.exit(0);else if(I==="mcp"){let s=C.includes("--run"),o=!1;if(!s&&!process.stdin.isTTY&&(s=await new Promise(r=>{let n=process.stdin,d=null,c=p=>{clearTimeout(d),n.removeListener("data",h),n.removeListener("end",f),n.removeListener("error",f),r(p)},h=p=>{n.pause(),n.unshift(p),o=!0,c(!0)},f=()=>c(!1);d=setTimeout(()=>{n.pause(),c(!1)},1500),n.on("data",h),n.once("end",f),n.once("error",f)})),s){try{await import(`file://${oe()}`),o&&process.stdin.resume()}catch(r){g(`Failed to start MCP server: ${r.message}`),process.exit(1)}return}await ne(e,C),process.exit(0)}else I==="login"?(await je(e),process.exit(0)):I==="logout"?(Pe(e),process.exit(0)):I==="start"?Ne(e,C):["--help","-h","help"].includes(I)?(u(`OZmoz CLI
803
803
 
804
804
  Commands:
805
805
  login Authenticate this machine (opens the browser: approve once, the command exits by itself)
806
+ logout Forget the local authentication token (no cloud call)
806
807
  mcp Connect your AI agent and write its instruction files (AGENTS.md, CLAUDE.md, GEMINI.md).
807
808
  --agent=claude,cursor,windsurf,devin,codex,gemini,antigravity,copilot|all
808
809
  --scope=project|user|local
@@ -815,4 +816,4 @@ Commands:
815
816
 
816
817
  AI agents: to create a project, call the MCP tool "oz_create_project".
817
818
  To evolve schema/workflow from UI files, call the MCP tool "oz_update_project", then run "sync".
818
- `),process.exit(0)):(y('Unknown command. Run "npx ozmoz --help".'),process.exit(1))}Ge().catch(e=>{y(`OZmoz CLI Error: ${e.message}`),process.exit(1)});
819
+ `),process.exit(0)):(g('Unknown command. Run "npx ozmoz --help".'),process.exit(1))}Ve().catch(e=>{g(`OZmoz CLI Error: ${e.message}`),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ozmoz",
3
- "version": "0.1.58",
3
+ "version": "0.1.59",
4
4
  "mcpName": "io.ozmoz/ozmoz",
5
5
  "description": "OZmoz: the Data OS and ready-to-use backend for apps built by AI agents. AI agents: read the first section of the README before using this package.",
6
6
  "license": "UNLICENSED",