@peripheries/engine 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peripheries/engine",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Build, check, knowledge and deploy for peripheries component repos",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{existsSync}from"node:fs";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";const HERE=dirname(fileURLToPath(import.meta.url));const bundled=resolve(HERE,"../template/cli.mjs");await(existsSync(bundled)?import(bundled):import(resolve(HERE,"../template/cli/index.ts")));
package/src/lib/run.mjs CHANGED
@@ -1 +1 @@
1
- import{spawnSync}from"node:child_process";import{existsSync}from"node:fs";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";import{REPO_ROOT}from"./root.mjs";const COMMANDS_DIR=resolve(dirname(fileURLToPath(import.meta.url)),"..","commands");const TSX=import.meta.resolve("tsx/esm");const COMMANDS={build:"build.mjs",deploy:"deploy.mjs",check:"check.mjs",harness:"harness.mjs","test-visual":"test-visual.mjs",upload:"upload-bundle.mjs",register:"register-components.mjs",cutover:"cutover.mjs",knowledge:"emit-knowledge.mjs",contracts:"emit-contracts.mjs","bundle-size":"bundle-size.mjs","check-bundle-leak":"check-bundle-leak.mjs","validate-externals":"validate-externals.mjs","check-wired":"check-wired-bindings.mjs","check-routes":"check-template-routes.mjs","check-design-refs":"check-design-refs.mjs","check-skills":"check-skills.mjs","check-work-orders":"check-work-orders.mjs","check-cutover-ownership":"check-cutover-ownership.mjs","check-fixtures":"check-fixtures.mjs","check-props-schema":"check-props-schema.mjs"};function commandFile(name){if(!COMMANDS[name])return null;const file=resolve(COMMANDS_DIR,COMMANDS[name]);const ts=file.replace(/\.mjs$/,".mts");return existsSync(file)?file:existsSync(ts)?ts:null}function runCommand(name,args=[],env={}){const file=commandFile(name);if(!file)throw new Error(`[engine] unknown command "${name}"`);const r=spawnSync(process.execPath,["--import",TSX,file,...args],{cwd:REPO_ROOT,stdio:"inherit",env:{...process.env,ENGINE_ROOT:REPO_ROOT,...env}});return r.status??1}export{COMMANDS,commandFile,runCommand};
1
+ import{spawnSync}from"node:child_process";import{existsSync}from"node:fs";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";import{REPO_ROOT}from"./root.mjs";const COMMANDS_DIR=resolve(dirname(fileURLToPath(import.meta.url)),"..","commands");const TSX=import.meta.resolve("tsx/esm");const COMMANDS={build:"build.mjs",deploy:"deploy.mjs",check:"check.mjs",harness:"harness.mjs","test-visual":"test-visual.mjs",template:"template.mjs",upload:"upload-bundle.mjs",register:"register-components.mjs",cutover:"cutover.mjs",knowledge:"emit-knowledge.mjs",contracts:"emit-contracts.mjs","bundle-size":"bundle-size.mjs","check-bundle-leak":"check-bundle-leak.mjs","validate-externals":"validate-externals.mjs","check-wired":"check-wired-bindings.mjs","check-routes":"check-template-routes.mjs","check-design-refs":"check-design-refs.mjs","check-skills":"check-skills.mjs","check-work-orders":"check-work-orders.mjs","check-cutover-ownership":"check-cutover-ownership.mjs","check-fixtures":"check-fixtures.mjs","check-props-schema":"check-props-schema.mjs"};function commandFile(name){if(!COMMANDS[name])return null;const file=resolve(COMMANDS_DIR,COMMANDS[name]);const ts=file.replace(/\.mjs$/,".mts");return existsSync(file)?file:existsSync(ts)?ts:null}function runCommand(name,args=[],env={}){const file=commandFile(name);if(!file)throw new Error(`[engine] unknown command "${name}"`);const r=spawnSync(process.execPath,["--import",TSX,file,...args],{cwd:REPO_ROOT,stdio:"inherit",env:{...process.env,ENGINE_ROOT:REPO_ROOT,...env}});return r.status??1}export{COMMANDS,commandFile,runCommand};
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ import{execSync}from"node:child_process";function parseArgs(argv){const flags=new Set;const values=new Map;const positional=[];for(let i=0;i<argv.length;i++){const token=argv[i];if(!token.startsWith("--")){positional.push(token);continue}const eq=token.indexOf("=");if(eq!==-1){values.set(token.slice(2,eq),token.slice(eq+1));continue}const key=token.slice(2);const next=argv[i+1];if(next!==void 0&&!next.startsWith("--")){values.set(key,next);i++}else{flags.add(key)}}return{command:positional[0]??"",targetEnv:resolveTargetEnv(flags,values),layer:values.get("layer")??null,name:values.get("name")??null,check:values.get("check")??null,version:values.get("version")??null,dryRun:flags.has("dry-run"),offline:flags.has("offline"),json:flags.has("json"),overwrite:flags.has("overwrite"),confirmProd:values.get("confirm-prod")??null,force:flags.has("force"),flags,values}}function resolveTargetEnv(flags,values){const fromValue=values.get("env")??null;const aliases=[];if(flags.has("develop"))aliases.push("develop");if(flags.has("prod"))aliases.push("prod");if(aliases.length>1){throw new Error("Pass at most one of --develop / --prod.")}if(fromValue!==null){if(fromValue!=="local"&&fromValue!=="develop"&&fromValue!=="prod"){throw new Error(`--env must be local | develop | prod (got "${fromValue}").`)}if(aliases.length===1&&aliases[0]!==fromValue){throw new Error(`--env ${fromValue} conflicts with --${aliases[0]}. Pass one.`)}return fromValue}return aliases[0]??"local"}function assertWriteAllowed(args,options){if(args.flags.has("replace-existing")){if(args.targetEnv==="prod"){throw new Error("--replace-existing is never allowed against prod.")}if(args.layer!=="dev-workbooks"&&args.layer!=="dev-client-data"||!args.name){throw new Error("--replace-existing requires --layer dev-workbooks|dev-client-data and --name <fixture> \u2014 it deletes a member's seeded rows, so it is never run across every client at once.")}}if(!options.requiresWrite||args.dryRun||args.offline)return;if(args.targetEnv==="local")return;if(!args.overwrite){throw new Error(`Writing to ${args.targetEnv} requires --overwrite. Run with --dry-run first and read the report.`)}if(args.targetEnv==="prod"){if(args.confirmProd!==options.orgSlug){throw new Error(`Writing to prod requires --confirm-prod ${options.orgSlug}. This is a deliberate speed bump: prod org config is live client-facing data.`)}if(!args.force&&isGitTreeDirty(options.repoRoot)){throw new Error("Refusing to write to prod from a dirty git tree \u2014 the files being uploaded would not match any commit, so the write could not be reproduced or reviewed. Commit first, or pass --force if you know exactly why.")}}}function isGitTreeDirty(repoRoot){try{const out=execSync("git status --porcelain",{cwd:repoRoot,encoding:"utf8",stdio:["ignore","pipe","ignore"]});return out.trim().length>0}catch{return false}}import{existsSync as existsSync11,readFileSync as readFileSync9}from"node:fs";import{join as join10}from"node:path";import{createClient}from"@supabase/supabase-js";import{existsSync,readFileSync}from"node:fs";import{resolve}from"node:path";var ENV_FILE={local:".env.local",develop:".env.develop",prod:".env.prod"};function loadEnv(target,repoRoot){const primary=resolve(repoRoot,ENV_FILE[target]);const fallback=target==="local"?resolve(repoRoot,".env"):null;const fileToLoad=existsSync(primary)?primary:fallback&&existsSync(fallback)?fallback:null;if(!fileToLoad)return null;for(const rawLine of readFileSync(fileToLoad,"utf8").split("\n")){const line=rawLine.trim();if(!line||line.startsWith("#"))continue;const match=line.match(/^([^=]+)=(.*)$/);if(!match)continue;const key=match[1].trim();let value=match[2].trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'")){value=value.slice(1,-1)}if(process.env[key]===void 0)process.env[key]=value}return fileToLoad}function getSupabaseConfig(){const url=process.env.SUPABASE_URL;const key=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!url){throw new Error("SUPABASE_URL not set. Add it to the env file for this target, or pass --offline to work without a database.")}if(!key){throw new Error("SUPABASE_SECRET_KEY (or SUPABASE_SERVICE_KEY / SUPABASE_SERVICE_ROLE_KEY) not set. Template writes need the secret key \u2014 the publishable key cannot pass RLS on org config tables.")}return{url,key}}function createSupabaseClient(target,repoRoot){loadEnv(target,repoRoot);const{url,key}=getSupabaseConfig();return createClient(url,key,{auth:{persistSession:false,autoRefreshToken:false}})}import{existsSync as existsSync3}from"node:fs";import{join as join3}from"node:path";import{pathToFileURL}from"node:url";import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"node:fs";import{join,resolve as resolve2}from"node:path";function typeName(value){if(value===null)return"null";if(Array.isArray(value))return"array";return typeof value}function checkField(key,spec,raw,errors){const present=raw!==void 0&&raw!==null;if(!present){if(spec.required){errors.push(`"${key}" is required`);return void 0}return"default"in spec?spec.default:void 0}switch(spec.type){case"string":if(typeof raw!=="string"){errors.push(`"${key}" must be a string (got ${typeName(raw)})`);return void 0}if(spec.minLength!==void 0&&raw.length<spec.minLength){errors.push(`"${key}" must be at least ${spec.minLength} character(s)`);return void 0}return raw;case"boolean":if(typeof raw!=="boolean"){errors.push(`"${key}" must be a boolean (got ${typeName(raw)})`);return void 0}return raw;case"number":if(typeof raw!=="number"||Number.isNaN(raw)){errors.push(`"${key}" must be a number (got ${typeName(raw)})`);return void 0}return raw;case"enum":if(typeof raw!=="string"||!spec.values.includes(raw)){errors.push(`"${key}" must be one of: ${spec.values.join(", ")} (got ${JSON.stringify(raw)})`);return void 0}return raw;case"object":if(typeName(raw)!=="object"){errors.push(`"${key}" must be an object (got ${typeName(raw)})`);return void 0}return raw;case"array":if(!Array.isArray(raw)){errors.push(`"${key}" must be an array (got ${typeName(raw)})`);return void 0}return raw;case"any":return raw}}function validateShape(raw,spec){const errors=[];if(typeName(raw)!=="object"){return{ok:false,value:null,errors:[`expected a JSON object, got ${typeName(raw)}`]}}const input=raw;const out={};for(const[key,fieldSpec]of Object.entries(spec.fields)){const value=checkField(key,fieldSpec,input[key],errors);if(value!==void 0)out[key]=value}const known=new Set([...Object.keys(spec.fields),...spec.ignored??[]]);for(const key of Object.keys(input)){if(spec.allowUnknown){if(!known.has(key))out[key]=input[key]}else if(!known.has(key)){errors.push(`unknown key "${key}" \u2014 not written to the database. Add it to the layer schema, or move this file out of the layer.`)}}return errors.length>0?{ok:false,value:null,errors}:{ok:true,value:out,errors:[]}}var REPO_ROOT=resolve2(process.env.ENGINE_ROOT??process.cwd());var TEMPLATE_ROOT=resolve2(REPO_ROOT,"template");var CONFIG_DIR=join(TEMPLATE_ROOT,"config");var DATA_DIR=join(TEMPLATE_ROOT,"data");var SEED_DIR=join(TEMPLATE_ROOT,"seed");var MAPPINGS_DIR=join(TEMPLATE_ROOT,"mappings");var cachedOrgConfig=null;function loadOrgConfig(){if(cachedOrgConfig)return cachedOrgConfig;const path=join(CONFIG_DIR,"org.json");if(!existsSync2(path)){throw new Error(`template/config/org.json not found at ${path}`)}const parsed=JSON.parse(readFileSync2(path,"utf8"));const result=validateShape(parsed,{fields:{slug:{type:"string",required:true,minLength:1},name:{type:"string",required:true,minLength:1},advisor:{type:"boolean",required:true},advisor_org_slug:{type:"string"},bundle_name:{type:"string",default:"main"},asset_bucket:{type:"string"},description:{type:"string"}},ignored:["_comment"]});if(!result.ok||!result.value){throw new Error(`template/config/org.json is invalid:
3
+ - ${result.errors.join("\n - ")}`)}if(!result.value.advisor&&!result.value.advisor_org_slug){console.warn("[template] config/org.json: client org has no advisor_org_slug \u2014 the org layer will not link an advisor org.")}cachedOrgConfig=result.value;return result.value}var cachedTemplatesConfig=null;function loadTemplatesConfig(){if(cachedTemplatesConfig)return cachedTemplatesConfig;const path=join(CONFIG_DIR,"templates.json");if(!existsSync2(path)){cachedTemplatesConfig={org_template:null,project_templates:[]};return cachedTemplatesConfig}const parsed=JSON.parse(readFileSync2(path,"utf8"));const outer=validateShape(parsed,{fields:{org_template:{type:"any"},project_templates:{type:"array",default:[]}},ignored:["_comment"]});if(!outer.ok||!outer.value){throw new Error(`template/config/templates.json is invalid:
4
+ - ${outer.errors.join("\n - ")}`)}let orgTemplate=null;if(outer.value.org_template){const result=validateShape(outer.value.org_template,{fields:{slug:{type:"string",required:true,minLength:1},bundle_name:{type:"string",default:"main"},layout_bundles:{type:"object"}},ignored:["_comment"]});if(!result.ok||!result.value){throw new Error(`templates.json org_template is invalid: ${result.errors.join("; ")}`)}orgTemplate=result.value}const projectTemplates=[];(outer.value.project_templates??[]).forEach((raw,index)=>{const result=validateShape(raw,{fields:{slug:{type:"string",required:true,minLength:1},bundle_name:{type:"string",default:"main"},skip_pages:{type:"boolean",default:false}},ignored:["_comment"]});if(!result.ok||!result.value){throw new Error(`templates.json project_templates[${index}] is invalid: ${result.errors.join("; ")}`)}projectTemplates.push(result.value)});cachedTemplatesConfig={org_template:orgTemplate,project_templates:projectTemplates};return cachedTemplatesConfig}function orgTemplatePath(slug){return join(REPO_ROOT,"src","org_templates",slug,"template.json")}function projectTemplateDir(slug){return join(REPO_ROOT,"src","project_templates",slug)}function projectTemplatePages(slug){const pagesDir=join(projectTemplateDir(slug),"pages");if(!existsSync2(pagesDir))return[];return readdirSync(pagesDir,{withFileTypes:true}).filter(e=>e.isDirectory()).map(e=>({page:e.name,path:join(pagesDir,e.name,"page.json")})).filter(p=>existsSync2(p.path)).sort((a,b)=>a.page.localeCompare(b.page))}function layerDir(sourceDir){return sourceDir?join(TEMPLATE_ROOT,sourceDir):null}function listJsonFiles(dir){if(!dir||!existsSync2(dir))return[];return readdirSync(dir).filter(f=>f.endsWith(".json")).sort()}function readJsonFile(path){try{return JSON.parse(readFileSync2(path,"utf8"))}catch(error){throw new Error(`${path}: not valid JSON \u2014 ${error instanceof Error?error.message:String(error)}`)}}import{join as join2}from"node:path";var LIST_KEY="bundle_refs";var SINGLE_KEY="bundle_ref";function describe(value){if(value===null)return"null";if(Array.isArray(value))return"an array";return typeof value}function refError(ref,path,orgSlug){if(typeof ref==="string"){if(ref===orgSlug)return null;return`${path}: bare-string bundle ref "${ref}" is an ORG SLUG, and it is not this org's ("${orgSlug}") \u2014 did you mean { "bundle": "${ref}" }? A bare string resolves to that org's main bundle, so a lineage name here silently falls through to main and the page renders with the wrong components. For a deliberate cross-org ref, name the lineage explicitly: { "bundle": "<lineage>", "org_slug": "${ref}" }.`}if(typeof ref!=="object"||ref===null||Array.isArray(ref)){return`${path}: a bundle ref must be a string or an object, got ${describe(ref)}`}const obj=ref;if("bundle"in obj){if(typeof obj.bundle!=="string"||obj.bundle.length===0){return`${path}: { "bundle": \u2026 } must name a lineage as a non-empty string, got ${describe(obj.bundle)}`}if("org_slug"in obj&&typeof obj.org_slug!=="string"){return`${path}: "org_slug" must be a string when present, got ${describe(obj.org_slug)}`}return null}if("bundle_id"in obj){if(typeof obj.bundle_id!=="string"||obj.bundle_id.length===0){return`${path}: { "bundle_id": \u2026 } must be a non-empty string`}return null}return`${path}: object bundle ref has neither "bundle" nor "bundle_id" (keys: ${Object.keys(obj).join(", ")||"none"}) \u2014 the union is string | { bundle_id } | { bundle, org_slug? }`}function bundleRefErrors(def,orgSlug){const errors=[];let visited=0;const walk=(node,path)=>{if(Array.isArray(node)){node.forEach((item,i)=>walk(item,`${path}[${i}]`));return}if(typeof node!=="object"||node===null)return;for(const[key,value]of Object.entries(node)){const here=path?`${path}.${key}`:key;if(key===LIST_KEY){if(!Array.isArray(value)){errors.push(`${here}: "${LIST_KEY}" must be an array, got ${describe(value)}`);continue}value.forEach((ref,i)=>{visited+=1;const error=refError(ref,`${here}[${i}]`,orgSlug);if(error)errors.push(error)});continue}if(key===SINGLE_KEY){if(value===void 0||value===null)continue;visited+=1;const error=refError(value,here,orgSlug);if(error)errors.push(error);continue}walk(value,here)}};walk(def,"");return{errors,visited}}function describeKey(naturalKey){return Object.entries(naturalKey).map(([k,v])=>`${k}=${v===null?"NULL":JSON.stringify(v)}`).join(", ")}async function upsertByNaturalKey(supabase,table,naturalKey,record,options={}){let query=supabase.from(table).select("id");for(const[key,value]of Object.entries(naturalKey)){query=value===null?query.is(key,null):query.eq(key,value)}const{data:existing,error:selectError}=await query.limit(2);if(selectError){throw new Error(`lookup failed on ${table} (${describeKey(naturalKey)}): ${selectError.message}`)}const rows=existing??[];if(rows.length>1){throw new Error(`${table} has at least ${rows.length} rows matching ${describeKey(naturalKey)} \u2014 ambiguous, refusing to write. Ids: ${rows.map(r=>r.id).join(", ")}. ${table==="client_data_type"?"This table has no unique constraint on its natural key, so duplicates are possible. ":""}Resolve the duplicate in the database first (see \`template/cli doctor\`).`)}const current=rows[0];if(current){if(options.dryRun)return{id:current.id,action:"updated"};const{data:data2,error:error2}=await supabase.from(table).update(record).eq("id",current.id).select("id").single();if(error2)throw new Error(`update failed on ${table} id=${current.id}: ${error2.message}`);return{id:data2.id,action:"updated"}}if(options.dryRun)return{id:"(new)",action:"created"};const{data,error}=await supabase.from(table).insert([record]).select("id").single();if(error){throw new Error(`insert failed on ${table} (${describeKey(naturalKey)}): ${error.message}`)}return{id:data.id,action:"created"}}var LayerManager=class{constructor(def,options,mappings){this.def=def;this.options=options;this.mappings=mappings}def;options;mappings;mappingEntities(){const primary=this.def.mappingEntity?[this.def.mappingEntity]:[];return[...primary,...this.def.mappingEntities??[]]}dir(){return layerDir(this.def.sourceDir)}duplicateDbKeys=new Set;bundleRefsVisited=0;files(){const files=listJsonFiles(this.dir());const filter=this.options.nameFilter;if(!filter)return files;return files.filter(f=>f===`${filter}.json`||f.replace(/\.json$/,"")===filter)}fileKeys(){const keys=[];for(const file of this.files()){try{keys.push(this.naturalKeyOf(this.loadFile(file)))}catch{}}return keys}loadFile(fileName){const dir=this.dir();if(!dir)throw new Error(`layer ${this.def.name} has no source directory`);const raw=readJsonFile(join2(dir,fileName));const result=validateShape(raw,this.shape);if(!result.ok||!result.value){throw new Error(result.errors.join("; "))}return result.value}extraIssues(_def){return{errors:[],warnings:[]}}validateAll(){this.bundleRefsVisited=0;const errors=[];const warnings=[];const files=this.files();const seen=new Map;for(const file of files){try{const def=this.loadFile(file);const refs=bundleRefErrors(def,this.options.orgSlug);this.bundleRefsVisited+=refs.visited;for(const message of refs.errors)errors.push({file,message});const extra=this.extraIssues(def);for(const message of extra.errors)errors.push({file,message});for(const message of extra.warnings)warnings.push({file,message});const key=this.naturalKeyOf(def);const previous=seen.get(key);if(previous){errors.push({file,message:`natural key "${key}" already declared by ${previous} \u2014 two files would fight over one row`})}else{seen.set(key,file)}}catch(error){errors.push({file,message:error instanceof Error?error.message:String(error)})}}if(files.length===0&&this.def.sourceDir&&!this.options.nameFilter){errors.push({file:this.dir()??"(layer)",message:`this layer declares sourceDir "${this.def.sourceDir}" and found NO files there. Every check in this layer runs per file, so zero files is a green run that verified nothing \u2014 a moved or unchecked-out directory, not a clean one.`})}return{layer:this.def.name,filesChecked:files.length,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];for(const file of this.files()){try{const def=this.loadFile(file);const key=this.naturalKeyOf(def);const outcome=await upsertByNaturalKey(this.options.supabase,this.def.table,this.naturalKeyFilter(def),this.toRow(def),{dryRun:this.options.dryRun});if(this.def.mappingEntity&&!this.options.dryRun){this.mappings.set(this.def.mappingEntity,key,outcome.id)}entities.push({entity:key,action:outcome.action,id:outcome.id})}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}async status(){const files=this.files();const base={layer:this.def.name,kind:this.def.kind,implemented:this.def.implemented,files:files.length,dbRows:null,mappedIds:this.mappingEntities().reduce((sum,e)=>sum+this.mappings.count(e),0),missingInDb:[],missingInFiles:[],unmappedInDb:[]};if(!this.def.implemented)return base;const fileKeys=new Set(this.fileKeys());try{const dbKeys=await this.fetchDbKeys();base.dbRows=dbKeys.size;base.missingInDb=[...fileKeys].filter(k=>!dbKeys.has(k)).sort();base.missingInFiles=[...dbKeys.keys()].filter(k=>!fileKeys.has(k)).sort();if(this.def.mappingEntity){const mapped=new Set(this.mappings.keys(this.def.mappingEntity));base.unmappedInDb=[...dbKeys.keys()].filter(k=>fileKeys.has(k)&&!mapped.has(k)).sort()}}catch(error){base.error=error instanceof Error?error.message:String(error)}return base}async healthChecks(){return[]}async orphans(){return[]}async pull(){const started=Date.now();const entities=[];const errors=[];if(!this.def.implemented||!this.def.mappingEntity){return{layer:this.def.name,created:0,updated:0,skipped:0,entities,errors,duration_ms:Date.now()-started}}try{const dbKeys=await this.fetchDbKeys();for(const key of this.fileKeys()){const id=dbKeys.get(key);if(!id){entities.push({entity:key,action:"skipped",id:null,reason:"not in database"});continue}if(this.duplicateDbKeys.has(key)){entities.push({entity:key,action:"skipped",id:null,reason:"ambiguous \u2014 more than one row shares this natural key; resolve the duplicate before mapping it (see `doctor`)"});continue}const before=this.mappings.getId(this.def.mappingEntity,key);this.mappings.set(this.def.mappingEntity,key,id);entities.push({entity:key,action:before===id?"skipped":"updated",id})}}catch(error){errors.push({entity:this.def.name,error:error instanceof Error?error.message:String(error)})}return{layer:this.def.name,created:0,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}};var CONTRACT=["src/types/host-contract.generated.ts","src/types/host-contract.generated.js"].map(f=>join3(REPO_ROOT,f)).find(f=>existsSync3(f));var AGENT_TOOL_NAMES=CONTRACT?(await import(pathToFileURL(CONTRACT).href)).AGENT_TOOL_NAMES??[]:[];var AgentTemplateManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"},is_template:{type:"boolean",default:true},prompt:{type:"any",required:true},tools:{type:"any",required:true},model:{type:"any"},output_schema:{type:"any"},skills:{type:"any"},metadata:{type:"object"}}}}extraIssues(def){const errors=[];const warnings=[];const tools=def.tools;if(tools!==void 0){const shape=tools;if(typeof tools!=="object"||tools===null||Array.isArray(tools)){errors.push(`"tools" must be an object carrying a toolNames array \u2014 the host keeps platform-agent's ADVISOR tools for any other shape, silently`)}else if(!Array.isArray(shape?.toolNames)){errors.push(`"tools.toolNames" must be an array \u2014 without it the host keeps platform-agent's ADVISOR tools (createEvent, updateEvent, submitProcessJob), silently, and this row's own tools are never applied`)}else if(shape.toolNames.some(t=>typeof t!=="string"||t.trim()==="")){errors.push(`"tools.toolNames" must contain non-empty strings \u2014 the host matches them by exact name against its tool registry, so a blank entry silently selects nothing`)}else if(AGENT_TOOL_NAMES.length>0){const known=new Set(AGENT_TOOL_NAMES);const names=shape.toolNames;const unknown=names.filter(t=>!known.has(t));if(unknown.length>0&&unknown.length<names.length){errors.push(`"tools.toolNames" names ${unknown.length} tool(s) of ${names.length} that the host does not have: ${unknown.join(", ")}. The runtime matches by exact name and drops the rest silently, so this agent would run with fewer tools than it declares. Valid names are in AGENT_TOOL_NAMES (host contract 2.15.0+)`)}else if(unknown.length===names.length){warnings.push(`none of this agent's ${names.length} tool name(s) are in the host's chat-agent registry, which reads as a BEA or other non-host runtime rather than a typo \u2014 every name would have to be wrong for a typo to look like this. Not checkable here: only the host chat runtime publishes its tool names (AGENT_TOOL_NAMES, contract 2.15.0+)`)}}}const prompt=def.prompt;if(prompt!==void 0){const shape=prompt;if(typeof prompt!=="object"||prompt===null||Array.isArray(prompt)){errors.push(`"prompt" must be an object with a "system" string \u2014 the host keeps platform-agent's ADVISOR system prompt for any other shape`)}else if(typeof shape?.system!=="string"||shape.system.trim()===""){errors.push(`"prompt.system" must be a non-empty string \u2014 without it the host keeps platform-agent's ADVISOR system prompt ("assistant for financial advisors")`)}}return{errors,warnings}}naturalKeyOf(def){return def.name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:def.name,is_template:true}}toRow(def){const row={org_id:this.options.orgId,name:def.name,is_template:true,archived:false,updated_at:new Date().toISOString()};if(def.description!==void 0)row.description=def.description;if(def.prompt!==void 0)row.prompt=def.prompt;if(def.tools!==void 0)row.tools=def.tools;if(def.model!==void 0)row.model=def.model;if(def.output_schema!==void 0)row.output_schema=def.output_schema;if(def.skills!==void 0)row.skills=def.skills;if(def.metadata!==void 0)row.metadata=def.metadata;return row}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("agent").select("id, name").eq("org_id",this.options.orgId).eq("is_template",true).eq("archived",false);if(error)throw new Error(`agent lookup failed: ${error.message}`);const out=new Map;for(const row of data??[]){if(row.name)out.set(row.name,row.id)}return out}};var DataTypeManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"},data_format:{type:"enum",values:["text","json","file"],default:"text"},schema:{type:"any"}},ignored:["org_id","org_name"]}}naturalKeyOf(def){return def.name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:def.name}}toRow(def){const row={org_id:this.options.orgId,name:def.name,data_format:def.data_format,updated_at:new Date().toISOString()};if(def.description!==void 0)row.description=def.description;if(def.schema!==void 0)row.schema=def.schema;return row}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("client_data_type").select("id, name").eq("org_id",this.options.orgId);if(error)throw new Error(`client_data_type lookup failed: ${error.message}`);const out=new Map;for(const row of data??[]){out.set(row.name,row.id)}return out}};import{existsSync as existsSync4,readdirSync as readdirSync2}from"node:fs";import{join as join4}from"node:path";var ORG_OVERRIDE_DIR=join4(DATA_DIR,"event-types");var EventTypeManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"},icon:{type:"string"},color:{type:"string"},category:{type:"string"},display_order:{type:"number"},metadata:{type:"object"}}}}naturalKeyOf(def){return def.name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:def.name}}toRow(def){const row={org_id:this.options.orgId,name:def.name,updated_at:new Date().toISOString()};if(def.description!==void 0)row.description=def.description;if(def.icon!==void 0)row.icon=def.icon;if(def.color!==void 0)row.color=def.color;if(def.metadata!==void 0)row.metadata=def.metadata;return row}orgFiles(){if(!existsSync4(ORG_OVERRIDE_DIR))return[];return readdirSync2(ORG_OVERRIDE_DIR).filter(f=>f.endsWith(".json")).sort()}resolvePath(fileName){const orgPath=join4(ORG_OVERRIDE_DIR,fileName);return existsSync4(orgPath)?orgPath:join4(this.dir()??"",fileName)}files(){const merged=new Set([...super.files(),...this.orgFiles()]);const all=[...merged].sort();const filter=this.options.nameFilter;if(!filter)return all;return all.filter(f=>f===`${filter}.json`||f.replace(/\.json$/,"")===filter)}loadFile(fileName){const raw=readJsonFile(this.resolvePath(fileName));const result=validateShape(raw,this.shape);if(!result.ok||!result.value)throw new Error(result.errors.join("; "));return result.value}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("event_type").select("id, name").eq("org_id",this.options.orgId);if(error)throw new Error(`event_type: ${error.message}`);const keys=new Map;for(const row of data??[]){keys.set(row.name,row.id)}return keys}};var FeedProducerManager=class extends LayerManager{get shape(){return{fields:{key:{type:"string",required:true,minLength:1},name:{type:"string",required:true,minLength:1},description:{type:"string"},kind:{type:"enum",values:["process","system","manual","user"],default:"process"},is_default:{type:"boolean",default:false},config:{type:"object",default:{}},status:{type:"enum",values:["active","paused","retired"],default:"active"},metadata:{type:"object"},source_table:{type:"string"},source_id:{type:"string"}}}}naturalKeyOf(def){return def.key}naturalKeyFilter(def){return{org_id:this.options.orgId,key:def.key}}toRow(def){const row={org_id:this.options.orgId,key:def.key,name:def.name,kind:def.kind,is_default:def.is_default,config:def.config,status:def.status,updated_at:new Date().toISOString()};if(def.description!==void 0)row.description=def.description;if(def.metadata!==void 0)row.metadata=def.metadata;if(def.source_table!==void 0)row.source_table=def.source_table;if(def.source_id!==void 0)row.source_id=def.source_id;return row}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("feed_producer").select("id, key").eq("org_id",this.options.orgId);if(error){throw new Error(`feed_producer lookup failed: ${error.message}. This layer needs the 20260804000000_feed_system migration.`)}const out=new Map;for(const row of data??[]){out.set(row.key,row.id)}return out}};import{existsSync as existsSync5}from"node:fs";import{join as join5}from"node:path";function decodeJsonbValue(value){let current=value;for(let depth=0;depth<4&&typeof current==="string";depth++){const trimmed=current.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("[")&&!trimmed.startsWith('"'))break;try{const parsed=JSON.parse(trimmed);if(parsed===current)break;current=parsed}catch{break}}return current!==null&&typeof current==="object"?current:value}var RETIRED_SECTION_CONFIG_KEYS={nextButtonText:'authored 10x across 8 files and consumed by nothing \u2014 DocumentSectionRenderer and UploadSectionRenderer render no forward control; advancement is FormNavigationButtons at form scope. Removed 2026-08-27. The requirement it encoded is recorded as a rule ("the forward control names its destination"), not as literals, in the host plan 02 \xA711 \u2014 reviving the key re-creates the literals and loses the rule.'};function retiredSectionConfigKeyErrors(def){const out=[];let visited=0;const pages=Array.isArray(def.pages)?def.pages:[];pages.forEach((page,pi)=>{const sections=Array.isArray(page?.sections)?page.sections:[];sections.forEach((section,si)=>{for(const[configKey,config]of Object.entries(section??{})){if(!configKey.endsWith("Config")||!config||typeof config!=="object")continue;visited+=1;for(const key of Object.keys(config)){const reason=RETIRED_SECTION_CONFIG_KEYS[key];if(reason){out.push(`retired key "${key}" at pages[${pi}].sections[${si}].${configKey} \u2014 ${reason}`)}}}})});return{errors:out,visited}}var SECTION_CONFIG_KEY={artifact:"artifactSectionConfig",document:"documentConfig",upload:"uploadConfig",review:"reviewConfig","advisor-review":"advisorReviewConfig",status:"statusConfig",cell:"cellConfig"};var FormTemplateManager=class extends LayerManager{get shape(){return{fields:{template_name:{type:"string",required:true,minLength:1},name:{type:"string"},description:{type:"string"},template_type:{type:"enum",values:["form","workbook"],default:"form"},is_published:{type:"boolean",default:false},is_archived:{type:"boolean",default:false},metadata:{type:"object"},shell:{type:"object"},pages:{type:"array",required:true}},ignored:["template_id","org_id","version","profile_block_id","profile_block_name"]}}validateAll(){const result=super.validateAll();let visited=0;for(const file of this.files()){try{visited+=retiredSectionConfigKeyErrors(super.loadFile(file)).visited}catch{}}if(visited===0){result.errors.push({file:"(layer)",message:"the retired-key walker visited zero section config objects across every form template \u2014 its traversal assumptions no longer match the file shape, so the retired-key check is passing vacuously. Fix the walker before trusting a green run."})}return result}loadFile(fileName){const def=super.loadFile(fileName);const{errors}=retiredSectionConfigKeyErrors(def);if(errors.length)throw new Error(errors.join("; "));return def}naturalKeyOf(def){return def.name??def.template_name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:this.naturalKeyOf(def)}}toRow(){throw new Error("FormTemplateManager writes via syncAll()")}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("client_form_template").select("id, name").eq("org_id",this.options.orgId);if(error)throw new Error(`client_form_template lookup failed: ${error.message}`);const out=new Map;for(const row of data??[]){out.set(row.name,row.id)}return out}sharedFieldsPath(){return join5(DATA_DIR,"shared-fields.json")}async syncSharedFields(entities,errors){const path=this.sharedFieldsPath();const map=new Map;if(!existsSync5(path))return map;try{const parsed=readJsonFile(path);const result=validateShape(parsed,{fields:{template_name:{type:"string",required:true,minLength:1},description:{type:"string"},shared_fields:{type:"array",required:true}},ignored:["template_id","org_id"]});if(!result.ok||!result.value){throw new Error(result.errors.join("; "))}const config=result.value;const outcome=await upsertByNaturalKey(this.options.supabase,"client_form_template",{org_id:this.options.orgId,name:config.template_name},{org_id:this.options.orgId,name:config.template_name,description:config.description??null,layout:{},updated_at:new Date().toISOString()},{dryRun:this.options.dryRun});const templateId=outcome.id;if(!this.options.dryRun){this.mappings.set("form_template",config.template_name,templateId)}let fieldCount=0;for(const field of config.shared_fields){const fieldOutcome=await this.upsertField(templateId,{fieldId:field.canonical_slug,label:field.label,fieldType:field.field_type,description:field.description??null,required:field.required??false,options:field.options??null,validation:decodeJsonbValue(field.validation)??null,placeholder:field.placeholder??null,pageId:null,sectionId:null,orderIndex:0},void 0);map.set(field.canonical_slug,fieldOutcome.id);if(!this.options.dryRun){this.mappings.set("shared_field",field.canonical_slug,fieldOutcome.id)}fieldCount++}entities.push({entity:`${config.template_name} (${fieldCount} shared field(s))`,action:outcome.action,id:templateId})}catch(error){errors.push({entity:"shared-fields.json",error:error instanceof Error?error.message:String(error)})}return map}async upsertPage(templateId,page){return upsertByNaturalKey(this.options.supabase,"client_form_page",{template_id:templateId,page_id:page.pageId},{template_id:templateId,page_id:page.pageId,title:page.title,description:page.description??null,order_index:page.orderIndex??0,conditional_logic:decodeJsonbValue(page.conditionalLogic)??null,org_id:this.options.orgId,updated_at:new Date().toISOString()},{dryRun:this.options.dryRun})}async upsertSection(templateId,pageId,section){const sectionType=section.sectionType??"standard";const configKey=SECTION_CONFIG_KEY[sectionType];const content=configKey?section[configKey]??null:section.content??null;return upsertByNaturalKey(this.options.supabase,"client_form_section",{template_id:templateId,page_id:pageId,section_id:section.sectionId},{template_id:templateId,page_id:pageId,section_id:section.sectionId,title:section.title,description:section.description??null,order_index:section.orderIndex??0,conditional_logic:decodeJsonbValue(section.conditionalLogic)??null,section_type:sectionType,org_id:this.options.orgId,content,content_before:section.contentBefore??null,content_after:section.contentAfter??null,updated_at:new Date().toISOString()},{dryRun:this.options.dryRun})}async upsertField(templateId,field,sharedFields){if(field.shared===true&&sharedFields){const sharedId=sharedFields.get(field.fieldId);if(sharedId)return{id:sharedId,action:"reused"}}const outcome=await upsertByNaturalKey(this.options.supabase,"client_input_field",{template_id:templateId,name:field.fieldId},{template_id:templateId,name:field.fieldId,label:field.label,description:field.description??null,field_type:field.fieldType,options:typeof field.options==="string"?JSON.parse(field.options):field.options??null,validation:decodeJsonbValue(field.validation)??null,required:field.required??false,default_value:field.defaultValue??null,placeholder:field.placeholder??null,help_text:field.helpText??null,conditional_logic:decodeJsonbValue(field.conditionalLogic)??null,page_id:field.pageId??null,section_id:field.sectionId??null,order_index:field.orderIndex??0,org_id:this.options.orgId,content_before:field.contentBefore??null,content_after:field.contentAfter??null,updated_at:new Date().toISOString()},{dryRun:this.options.dryRun});return outcome}async syncTemplate(file,sharedFields,entities){const def=this.loadFile(file);const templateName=this.naturalKeyOf(def);const dryRun=this.options.dryRun;const templateOutcome=await upsertByNaturalKey(this.options.supabase,"client_form_template",{org_id:this.options.orgId,name:templateName},{org_id:this.options.orgId,name:templateName,description:def.description??null,layout:{placeholder:true},status:def.is_published?"published":"draft",is_active:!def.is_archived,template_type:def.template_type,workbook_config:def.workbook_config??null,updated_at:new Date().toISOString()},{dryRun});const templateId=templateOutcome.id;const sharedFieldPlacements=[];const layoutPages=[];let sectionCount=0;let fieldCount=0;let reusedCount=0;for(const page of def.pages){const pageOutcome=await this.upsertPage(templateId,page);layoutPages.push({id:pageOutcome.id,pageId:page.pageId,title:page.title,description:page.description??null,orderIndex:page.orderIndex??0});if(!dryRun){this.mappings.set("form_page",`${templateName}:${page.pageId}`,pageOutcome.id)}for(const section of page.sections??[]){const sectionOutcome=await this.upsertSection(templateId,page.pageId,section);sectionCount++;if(!dryRun){this.mappings.set("form_section",`${templateName}:${page.pageId}:${section.sectionId}`,sectionOutcome.id)}for(const field of section.fields??[]){const fieldOutcome=await this.upsertField(templateId,field,sharedFields);fieldCount++;if(fieldOutcome.action==="reused"){reusedCount++;sharedFieldPlacements.push({fieldId:field.fieldId,pageId:field.pageId??page.pageId,sectionId:field.sectionId??section.sectionId,orderIndex:field.orderIndex??0})}if(!dryRun){this.mappings.set("form_field",`${templateName}:${field.fieldId}`,fieldOutcome.id)}}}}if(!dryRun){const{error}=await this.options.supabase.from("client_form_template").update({layout:{pages:layoutPages,sharedFieldPlacements,metadata:def.metadata??null,...def.shell===void 0?{}:{shell:def.shell}},updated_at:new Date().toISOString()}).eq("id",templateId);if(error)throw new Error(`failed to finalize layout for ${templateName}: ${error.message}`);this.mappings.set("form_template",templateName,templateId)}const shared=reusedCount>0?`, ${reusedCount} shared`:"";entities.push({entity:`${templateName} (${def.pages.length}p/${sectionCount}s/${fieldCount}f${shared})`,action:templateOutcome.action,id:templateId})}async healthChecks(){const declared=new Map;for(const file of this.files()){let def;try{def=this.loadFile(file)}catch{continue}const name=this.naturalKeyOf(def);const fields=new Set;const pages=new Set;const sections=new Set;for(const page of def.pages){pages.add(page.pageId);for(const section of page.sections??[]){sections.add(`${page.pageId}:${section.sectionId}`);for(const field of section.fields??[])fields.add(field.fieldId)}}declared.set(name,{fields,pages,sections})}const dbTemplates=await this.fetchDbKeys();const orphanFields=[];const orphanPages=[];const orphanSections=[];for(const[templateName,sets]of declared){const templateId=dbTemplates.get(templateName);if(!templateId)continue;const{data:fields}=await this.options.supabase.from("client_input_field").select("name").eq("template_id",templateId);for(const row of fields??[]){if(!sets.fields.has(row.name))orphanFields.push(`${templateName}/${row.name}`)}const{data:pages}=await this.options.supabase.from("client_form_page").select("page_id").eq("template_id",templateId);for(const row of pages??[]){if(!sets.pages.has(row.page_id))orphanPages.push(`${templateName}/${row.page_id}`)}const{data:sections}=await this.options.supabase.from("client_form_section").select("page_id, section_id").eq("template_id",templateId);for(const row of sections??[]){if(!sets.sections.has(`${row.page_id}:${row.section_id}`)){orphanSections.push(`${templateName}/${row.section_id}`)}}}const total=orphanFields.length+orphanPages.length+orphanSections.length;return[total===0?{name:"form-orphans",severity:"ok",message:`no orphaned form rows across ${declared.size} managed template(s)`}:{name:"form-orphans",severity:"warn",message:`${orphanFields.length} field(s), ${orphanSections.length} section(s) and ${orphanPages.length} page(s) belong to a managed template but are declared by no file \u2014 a form renderer WILL still show them, which is not a theoretical risk: a deleted probe section stayed member-visible for a day because this check counted only two of the three levels. Re-declare them in the source file, or remove them with \`npm run template -- prune --confirm-prune\`, which has always covered all three.`,detail:[...orphanFields,...orphanSections,...orphanPages]}]}async orphans(){const out=[];const dbTemplates=await this.fetchDbKeys();for(const file of this.files()){let def;try{def=this.loadFile(file)}catch{continue}const templateName=this.naturalKeyOf(def);const templateId=dbTemplates.get(templateName);if(!templateId)continue;const pages=new Set;const sections=new Set;const fields=new Set;for(const page of def.pages){pages.add(page.pageId);for(const section of page.sections??[]){sections.add(`${page.pageId}:${section.sectionId}`);for(const field of section.fields??[])fields.add(field.fieldId)}}const{data:dbFields}=await this.options.supabase.from("client_input_field").select("id, name").eq("template_id",templateId);for(const row of dbFields??[]){if(!fields.has(row.name)){out.push({table:"client_input_field",id:row.id,label:`${templateName}/${row.name}`})}}const{data:dbSections}=await this.options.supabase.from("client_form_section").select("id, page_id, section_id").eq("template_id",templateId);for(const row of dbSections??[]){if(!sections.has(`${row.page_id??""}:${row.section_id}`)){out.push({table:"client_form_section",id:row.id,label:`${templateName}/${row.page_id??"(no page)"}/${row.section_id}`})}}const{data:dbPages}=await this.options.supabase.from("client_form_page").select("id, page_id").eq("template_id",templateId);for(const row of dbPages??[]){if(!pages.has(row.page_id)){out.push({table:"client_form_page",id:row.id,label:`${templateName}/${row.page_id}`})}}}return out}async syncAll(){const started=Date.now();const entities=[];const errors=[];const sharedFields=await this.syncSharedFields(entities,errors);for(const file of this.files()){try{await this.syncTemplate(file,sharedFields,entities)}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}};async function findOrgBySlug(supabase,orgSlug){const{data,error}=await supabase.from("organization").select("id, name, advisor, metadata").eq("metadata->>org_slug",orgSlug).limit(2);if(error){throw new Error(`organization lookup failed for org_slug="${orgSlug}": ${error.message}`)}const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} organization rows have metadata->>org_slug="${orgSlug}" \u2014 ambiguous. Ids: ${rows.map(r=>r.id).join(", ")}. Fix the database before seeding.`)}const row=rows[0];if(!row)return null;const metadata=row.metadata??{};return{id:row.id,name:row.name,advisor:row.advisor===true,advisorOrgId:metadata["advisor_org_id"]??null,advisorOrgSlug:metadata["advisor_org_slug"]??null}}var DevUserManager=class extends LayerManager{get shape(){return{fields:{type:{type:"enum",values:["advisor","client"],required:true},email:{type:"string",required:true,minLength:3},name:{type:"string",required:true,minLength:1},first_name:{type:"string",required:true,minLength:1},last_name:{type:"string",required:true,minLength:1},user_metadata:{type:"object"},org_memberships:{type:"array",required:true},advisor_orgs:{type:"array"},client_record:{type:"object"}}}}naturalKeyOf(def){return def.email}naturalKeyFilter(def){return{email:def.email}}toRow(){throw new Error("DevUserManager writes via syncAll()")}devPassword(){return process.env.DEV_USER_PASSWORD??"Password123!"}async findAuthUser(email){const perPage=200;for(let page=1;page<=50;page++){const{data,error}=await this.options.supabase.auth.admin.listUsers({page,perPage});if(error)throw new Error(`auth.admin.listUsers failed: ${error.message}`);const users=data?.users??[];const match=users.find(u=>u.email?.toLowerCase()===email.toLowerCase());if(match)return match.id;if(users.length<perPage)return null}return null}async ensureAuthUser(def){const existing=await this.findAuthUser(def.email);if(existing)return{id:existing,created:false};const{data,error}=await this.options.supabase.auth.admin.createUser({email:def.email,password:this.devPassword(),email_confirm:true,user_metadata:{name:def.name,role:def.type,...def.user_metadata??{}}});if(error)throw new Error(`auth.admin.createUser failed for ${def.email}: ${error.message}`);const id=data?.user?.id;if(!id)throw new Error(`no user id returned for ${def.email}`);return{id,created:true}}async orgIdFor(slug){if(slug===this.options.orgSlug)return this.options.orgId;const org=await findOrgBySlug(this.options.supabase,slug);return org?.id??null}async ensureOrgMember(userId,orgId,def){const{data,error}=await this.options.supabase.from("org_member").select("id").eq("user_id",userId).eq("org_id",orgId).limit(2);if(error)throw new Error(`org_member lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} org_member rows for this user+org \u2014 role resolution will throw. Run doctor.`)}if(rows.length===1){const{error:updateError}=await this.options.supabase.from("org_member").update({first_name:def.first_name,last_name:def.last_name,nick_name:def.first_name}).eq("id",rows[0].id);if(updateError)throw new Error(`org_member update failed: ${updateError.message}`);return}const{error:insertError}=await this.options.supabase.from("org_member").insert({user_id:userId,org_id:orgId,first_name:def.first_name,last_name:def.last_name,nick_name:def.first_name});if(insertError)throw new Error(`org_member insert failed: ${insertError.message}`)}async ensureAdvisor(userId,def){const primarySlug=def.org_memberships[0];if(!primarySlug)throw new Error(`advisor ${def.name} has no org_memberships`);const primaryOrgId=await this.orgIdFor(primarySlug);if(!primaryOrgId)throw new Error(`cannot resolve primary org "${primarySlug}"`);const{data,error}=await this.options.supabase.from("advisor").select("id").eq("user_id",userId).eq("org_id",primaryOrgId).limit(2);if(error)throw new Error(`advisor lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} advisor rows for this user+org \u2014 role resolution will throw. Run doctor.`)}let advisorId;if(rows.length===1){advisorId=rows[0].id;await this.options.supabase.from("advisor").update({name:def.name,email:def.email}).eq("id",advisorId)}else{const{data:inserted,error:insertError}=await this.options.supabase.from("advisor").insert({user_id:userId,org_id:primaryOrgId,name:def.name,email:def.email}).select("id").single();if(insertError)throw new Error(`advisor insert failed: ${insertError.message}`);advisorId=inserted.id}for(const slug of def.advisor_orgs??[]){const linkedOrgId=await this.orgIdFor(slug);if(!linkedOrgId){console.warn(`[template] \u26A0 advisor_orgs: "${slug}" not found in ${this.options.targetEnv} \u2014 skipping the link. Seed that org, then re-run.`);continue}const{data:link}=await this.options.supabase.from("advisor_org").select("id").eq("advisor_id",advisorId).eq("org_id",linkedOrgId).maybeSingle();if(!link){const{error:linkError}=await this.options.supabase.from("advisor_org").insert({advisor_id:advisorId,org_id:linkedOrgId});if(linkError)throw new Error(`advisor_org insert failed: ${linkError.message}`)}}return advisorId}async ensureClient(userId,def){const record=def.client_record;if(!record)throw new Error(`client ${def.name} has no client_record`);const orgSlug=def.org_memberships[0]??this.options.orgSlug;const orgId=await this.orgIdFor(orgSlug);if(!orgId)throw new Error(`cannot resolve client org "${orgSlug}"`);const data={...record.metadata??{}};if(record.slug)data.slug=record.slug;const{data:found,error}=await this.options.supabase.from("client").select("id, data, user_id").eq("org_id",orgId).eq("name",record.name);if(error)throw new Error(`client lookup failed: ${error.message}`);let rows=found??[];if(rows.length>1){const mine=rows.filter(r=>r.user_id===userId);if(mine.length===1){console.warn(`[template] \u26A0 ${rows.length} client rows named "${record.name}" in this org; using the one already linked to ${def.email} (${mine[0].id}). Run doctor \u2014 the others are strays.`);rows=mine}else{throw new Error(`${rows.length} client rows named "${record.name}" in this org and ${mine.length} linked to ${def.email} \u2014 ambiguous, refusing to guess. Run doctor for the ids.`)}}if(rows[0]){const merged={...rows[0].data??{},...data};const{error:updateError}=await this.options.supabase.from("client").update({user_id:userId,data:merged,description:record.description??null}).eq("id",rows[0].id);if(updateError)throw new Error(`client update failed: ${updateError.message}`);return rows[0].id}const{data:inserted,error:insertError}=await this.options.supabase.from("client").insert({org_id:orgId,name:record.name,description:record.description??null,user_id:userId,data}).select("id").single();if(insertError)throw new Error(`client insert failed: ${insertError.message}`);return inserted.id}async fetchDbKeys(){const out=new Map;for(const file of this.files()){let def;try{def=this.loadFile(file)}catch{continue}const id=await this.findAuthUser(def.email);if(id)out.set(def.email,id)}return out}async healthChecks(){const{data,error}=await this.options.supabase.from("client").select("id, name, user_id").eq("org_id",this.options.orgId);if(error){return[{name:"dev-user-clients",severity:"warn",message:`lookup failed: ${error.message}`}]}const rows=data??[];const byName=new Map;for(const row of rows){byName.set(row.name,[...byName.get(row.name)??[],{id:row.id,user_id:row.user_id}])}const managed=new Set;for(const file of this.files()){try{const def=this.loadFile(file);if(def.client_record?.name)managed.add(def.client_record.name)}catch{}}const blocking=[];let unmanagedDuplicates=0;for(const[name,group]of byName){if(group.length<2)continue;if(!managed.has(name)){unmanagedDuplicates++;continue}const linked=group.filter(r=>r.user_id);if(linked.length===1)continue;blocking.push(`${name}: ${group.length} rows, ${linked.length} linked \u2014 ${group.map(r=>r.id).join(", ")}`)}const checks=[blocking.length===0?{name:"dev-user-clients",severity:"ok",message:`${managed.size} managed client(s), all resolvable`}:{name:"dev-user-clients",severity:"fail",message:`${blocking.length} managed client name(s) ambiguous \u2014 dev-users sync will refuse them`,detail:blocking}];if(unmanagedDuplicates>0){checks.push({name:"client-name-duplicates",severity:"warn",message:`${unmanagedDuplicates} client name(s) outside this layer appear more than once (bulk-imported member records; client has no unique constraint on (org_id, name)). Informational \u2014 a duplicate import or two members sharing a name.`})}return checks}async syncAll(){const started=Date.now();const entities=[];const errors=[];if(this.options.targetEnv==="prod"){return{layer:this.def.name,created:0,updated:0,skipped:1,entities:[{entity:"dev-users",action:"skipped",id:null,reason:"dev fixtures never run against prod"}],errors,duration_ms:Date.now()-started}}const files=this.files();const ordered=[...files.filter(f=>f.startsWith("advisor-")),...files.filter(f=>!f.startsWith("advisor-"))];for(const file of ordered){try{const def=this.loadFile(file);if(this.options.dryRun){const existing=await this.findAuthUser(def.email);entities.push({entity:`${def.type}:${def.email}`,action:existing?"updated":"created",id:existing??"(new)"});continue}const user=await this.ensureAuthUser(def);for(const slug of def.org_memberships){const orgId=await this.orgIdFor(slug);if(!orgId){console.warn(`[template] \u26A0 org_memberships: "${slug}" not found in ${this.options.targetEnv} \u2014 skipping membership.`);continue}await this.ensureOrgMember(user.id,orgId,def)}if(def.type==="advisor"){const advisorId=await this.ensureAdvisor(user.id,def);this.mappings.set("advisor",def.email,advisorId)}else{const clientId=await this.ensureClient(user.id,def);this.mappings.set("client",def.email,clientId);const slug=def.client_record?.slug;if(slug)this.mappings.set("client",slug,clientId)}entities.push({entity:`${def.type}:${def.email}`,action:user.created?"created":"updated",id:user.id})}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}};var DevClientDataManager=class extends LayerManager{get shape(){return{fields:{client:{type:"string",required:true,minLength:1},entries:{type:"array",required:true}},ignored:["_comment"]}}naturalKeyOf(def){return def.client}naturalKeyFilter(def){return{org_id:this.options.orgId,client:def.client}}toRow(){throw new Error("DevClientDataManager writes via syncAll()")}async fetchDbKeys(){const out=new Map;for(const file of this.files()){let def;try{def=this.loadFile(file)}catch{continue}const clientId=await this.resolveClientId(def.client);if(clientId)out.set(def.client,clientId)}return out}async resolveClientId(reference){const bySlug=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("data->>slug",reference).limit(2);if(bySlug.error)throw new Error(`client lookup failed: ${bySlug.error.message}`);const slugRows=bySlug.data??[];if(slugRows.length>1){throw new Error(`${slugRows.length} clients have data->>slug="${reference}" \u2014 ambiguous.`)}if(slugRows[0])return slugRows[0].id;const byName=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("name",reference).limit(2);if(byName.error)throw new Error(`client lookup failed: ${byName.error.message}`);const nameRows=byName.data??[];if(nameRows.length>1){throw new Error(`${nameRows.length} clients named "${reference}" \u2014 ambiguous.`)}return nameRows[0]?.id??null}async resolveDataTypeId(name){const{data,error}=await this.options.supabase.from("client_data_type").select("id, data_format").eq("org_id",this.options.orgId).eq("name",name).limit(2);if(error)throw new Error(`client_data_type lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} client_data_type rows named "${name}" in this org \u2014 ambiguous. That table has no unique constraint on (org_id, name); run doctor for the ids.`)}const row=rows[0];return row?{id:row.id,format:row.data_format}:null}async syncAll(){const started=Date.now();const entities=[];const errors=[];let created=0;let updated=0;let skipped=0;if(this.options.targetEnv==="prod"){return{layer:this.def.name,created:0,updated:0,skipped:1,entities:[{entity:"dev-client-data",action:"skipped",id:null,reason:"dev fixtures never run against prod"}],errors,duration_ms:Date.now()-started}}for(const file of this.files()){try{const def=this.loadFile(file);const clientId=await this.resolveClientId(def.client);if(!clientId){entities.push({entity:def.client,action:"skipped",id:null,reason:`no client matches "${def.client}" \u2014 seed dev-users first:
5
+ npm run template -- sync --layer dev-users --env ${this.options.targetEnv}`});skipped++;continue}const purged=new Set;if(this.options.replaceExisting){const typeIds=new Set;for(const entry of def.entries){const t=await this.resolveDataTypeId(entry.data_type);if(t)typeIds.add(t.id)}if(typeIds.size>0){const{data:stale,error:staleError}=await this.options.supabase.from("client_data").select("id, name").eq("client_id",clientId).in("data_type_id",[...typeIds]);if(staleError)throw new Error(`client_data lookup failed: ${staleError.message}`);for(const row of stale??[]){if(!this.options.dryRun){const{error:deleteError}=await this.options.supabase.from("client_data").delete().eq("id",row.id);if(deleteError)throw new Error(`client_data delete failed: ${deleteError.message}`)}purged.add(row.id);updated++;entities.push({entity:row.name,action:"updated",id:row.id,reason:this.options.dryRun?"dry run \u2014 would DELETE (replace-existing)":"deleted (replace-existing)"})}}}for(const entry of def.entries){const dataType=await this.resolveDataTypeId(entry.data_type);if(!dataType){entities.push({entity:`${entry.data_type} / ${entry.name}`,action:"skipped",id:null,reason:`no client_data_type named "${entry.data_type}". That row belongs to the data-types LAYER, not this one, and this layer deliberately does not create it:
6
+ npm run template -- sync --layer data-types --env ${this.options.targetEnv}`});skipped++;continue}const hasJson=entry.json_content!==void 0;const hasText=entry.content!==void 0;if(hasJson===hasText){throw new Error(`${entry.data_type} / ${entry.name}: supply exactly one of json_content or content (got ${hasJson?"both":"neither"}).`)}if(dataType.format==="json"&&!hasJson){throw new Error(`${entry.data_type} / ${entry.name}: data type declares data_format "json" but the fixture supplies \`content\`. A JSON reader looks at json_content and would find null.`)}if(dataType.format&&dataType.format!=="json"&&!hasText){throw new Error(`${entry.data_type} / ${entry.name}: data type declares data_format "${dataType.format}" but the fixture supplies \`json_content\`.`)}const{data:existingRows,error:existingError}=await this.options.supabase.from("client_data").select("id").eq("client_id",clientId).eq("data_type_id",dataType.id).eq("name",entry.name).limit(1);if(existingError)throw new Error(`client_data lookup failed: ${existingError.message}`);const found=(existingRows??[])[0];const existing=found&&!purged.has(found.id)?found:void 0;if(existing){entities.push({entity:`${entry.data_type} / ${entry.name}`,action:"skipped",id:existing.id,reason:"artefact already exists \u2014 client_data is append-only history, never rewritten"});skipped++;continue}if(this.options.dryRun){entities.push({entity:`${entry.data_type} / ${entry.name}`,action:"created",id:null,reason:"dry run"});created++;continue}const{data:inserted,error:insertError}=await this.options.supabase.from("client_data").insert({client_id:clientId,data_type_id:dataType.id,org_id:this.options.orgId,name:entry.name,description:entry.description??null,json_content:entry.json_content??null,content:entry.content??null}).select("id").single();if(insertError)throw new Error(`client_data insert failed: ${insertError.message}`);created++;entities.push({entity:`${entry.data_type} / ${entry.name}`,action:"created",id:inserted.id})}}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created,updated,skipped,entities,errors,duration_ms:Date.now()-started}}};var DevWorkbookManager=class _DevWorkbookManager extends LayerManager{get shape(){return{fields:{client:{type:"string",required:true,minLength:1},project:{type:"string"},workbooks:{type:"array",required:true}},ignored:["_comment"]}}naturalKeyOf(def){return def.client}naturalKeyFilter(def){return{org_id:this.options.orgId,client:def.client}}toRow(){throw new Error("DevWorkbookManager writes via syncAll()")}async fetchDbKeys(){const out=new Map;for(const file of this.files()){let def;try{def=this.loadFile(file)}catch{continue}const clientId=await this.resolveClientId(def.client);if(clientId)out.set(def.client,clientId)}return out}async resolveClientId(reference){const bySlug=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("data->>slug",reference).limit(2);if(bySlug.error)throw new Error(`client lookup failed: ${bySlug.error.message}`);const slugRows=bySlug.data??[];if(slugRows.length>1){throw new Error(`${slugRows.length} clients have data->>slug="${reference}" \u2014 ambiguous.`)}if(slugRows[0])return slugRows[0].id;const byName=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("name",reference).limit(2);if(byName.error)throw new Error(`client lookup failed: ${byName.error.message}`);const nameRows=byName.data??[];if(nameRows.length>1){throw new Error(`${nameRows.length} clients named "${reference}" \u2014 ambiguous.`)}return nameRows[0]?.id??null}async resolveProjectId(name){const{data,error}=await this.options.supabase.from("project").select("id").eq("org_id",this.options.orgId).eq("name",name).limit(2);if(error)throw new Error(`project lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1)throw new Error(`${rows.length} projects named "${name}" \u2014 ambiguous.`);return rows[0]?.id??null}async resolveTemplateId(name){const{data,error}=await this.options.supabase.from("client_form_template").select("id").eq("org_id",this.options.orgId).eq("name",name).limit(2);if(error)throw new Error(`client_form_template lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} client_form_template rows named "${name}" \u2014 ambiguous.`)}return rows[0]?.id??null}async resolveField(templateId,fieldName){const own=await this.options.supabase.from("client_input_field").select("id, field_type").eq("template_id",templateId).eq("name",fieldName).limit(1);if(own.error)throw new Error(`client_input_field lookup failed: ${own.error.message}`);const ownRow=(own.data??[])[0];if(ownRow)return{id:ownRow.id,fieldType:ownRow.field_type,sharedFrom:null};const shared=await this.options.supabase.from("client_input_field").select("id, field_type, client_form_template!inner(name, org_id)").eq("name",fieldName).eq("client_form_template.org_id",this.options.orgId).limit(5);if(shared.error)throw new Error(`client_input_field lookup failed: ${shared.error.message}`);const rows=shared.data??[];const nameOf=row2=>Array.isArray(row2.client_form_template)?row2.client_form_template[0]?.name??"?":row2.client_form_template.name;if(rows.length>1){throw new Error(`field "${fieldName}" is not declared by this workbook and is declared by ${rows.length} other templates (${rows.map(nameOf).join(", ")}) \u2014 ambiguous, refusing to guess which block the answer belongs to.`)}const row=rows[0];if(!row)return null;return{id:row.id,fieldType:row.field_type,sharedFrom:nameOf(row)}}async syncAll(){const started=Date.now();const entities=[];const errors=[];let created=0;let updated=0;let skipped=0;if(this.options.targetEnv==="prod"){return{layer:this.def.name,created:0,updated:0,skipped:1,entities:[{entity:"dev-workbooks",action:"skipped",id:null,reason:"dev fixtures never run against prod"}],errors,duration_ms:Date.now()-started}}for(const file of this.files()){try{const def=this.loadFile(file);const clientId=await this.resolveClientId(def.client);if(!clientId){entities.push({entity:def.client,action:"skipped",id:null,reason:`no client matches "${def.client}" \u2014 seed dev-users first:
7
+ npm run template -- sync --layer dev-users --env ${this.options.targetEnv}`});skipped++;continue}const projectId=def.project?await this.resolveProjectId(def.project):null;if(def.project&&!projectId){console.warn(`[template] \u26A0 project "${def.project}" not found \u2014 workbooks will be seeded without project_id. Seed the projects layer if a project link is wanted.`)}for(const workbook of def.workbooks){const templateId=await this.resolveTemplateId(workbook.template_name);if(!templateId){entities.push({entity:workbook.template_name,action:"skipped",id:null,reason:`no client_form_template named "${workbook.template_name}". That row belongs to the form-templates LAYER, not this one \u2014 and the name is an exact cross-repo key (blocks.ts workbookTemplateNames), so check for a typo before re-seeding:
8
+ npm run template -- sync --layer form-templates --env ${this.options.targetEnv}`});skipped++;continue}const{data:existingRows,error:existingError}=await this.options.supabase.from("client_form").select("id").eq("client_id",clientId).eq("template_id",templateId).limit(1);if(existingError){throw new Error(`client_form lookup failed: ${existingError.message}`)}const existing=(existingRows??[])[0];let replaced=null;if(existing&&this.options.replaceExisting){const{count,error:countError}=await this.options.supabase.from("client_input").select("id",{count:"exact",head:true}).eq("form_id",existing.id);if(countError)throw new Error(`client_input count failed: ${countError.message}`);if(this.options.dryRun){entities.push({entity:workbook.template_name,action:"updated",id:existing.id,reason:`dry run \u2014 would DELETE this workbook and its ${count??0} answer(s), then re-seed it`});updated++;continue}const{error:inputsError}=await this.options.supabase.from("client_input").delete().eq("form_id",existing.id);if(inputsError)throw new Error(`client_input delete failed: ${inputsError.message}`);const{error:formError}=await this.options.supabase.from("client_form").delete().eq("id",existing.id);if(formError)throw new Error(`client_form delete failed: ${formError.message}`);replaced={answers:count??0}}else if(existing){entities.push({entity:workbook.template_name,action:"skipped",id:existing.id,reason:"workbook already exists \u2014 member progress is never overwritten"});skipped++;continue}if(this.options.dryRun){entities.push({entity:workbook.template_name,action:"created",id:null,reason:"dry run"});created++;continue}const completed=workbook.completed===true;const now=new Date().toISOString();const{data:inserted,error:insertError}=await this.options.supabase.from("client_form").insert({client_id:clientId,template_id:templateId,org_id:this.options.orgId,project_id:projectId,status:workbook.status??(completed?"completed":"in_progress"),progress:workbook.progress??{},started_at:now,completed_at:completed?now:null}).select("id").single();if(insertError)throw new Error(`client_form insert failed: ${insertError.message}`);const formId=inserted.id;if(replaced)updated++;else created++;const answerCount=await this.seedAnswers(formId,templateId,workbook);entities.push({entity:`${workbook.template_name} (${completed?"completed":workbook.status??"in_progress"}, ${answerCount} answer(s))`,action:replaced?"updated":"created",id:formId,...replaced?{reason:`replaced an existing workbook and its ${replaced.answers} answer(s)`}:{}})}}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created,updated,skipped,entities,errors,duration_ms:Date.now()-started}}static envelope(fieldType,raw){if(fieldType==="number"){const n=typeof raw==="number"?raw:Number(raw);if(Number.isNaN(n)){throw new Error(`field_type "number" but value "${raw}" is not a number`)}return{data:n,type:fieldType}}return{data:String(raw),type:fieldType}}async seedAnswers(formId,templateId,workbook){let count=0;for(const answer of workbook.answers??[]){const field=await this.resolveField(templateId,answer.field_name);if(!field){console.warn(`[template] \u26A0 ${workbook.template_name}: no client_input_field named "${answer.field_name}" \u2014 answer skipped. Field names come from the form-templates layer; check the workbook definition.`);continue}if(field.sharedFrom){console.log(`[template] ${workbook.template_name}: "${answer.field_name}" resolved from shared template "${field.sharedFrom}"`)}if(!answer.revision){const{data:priorRows,error:priorError}=await this.options.supabase.from("client_input").select("id").eq("form_id",formId).eq("field_id",field.id).limit(1);if(priorError)throw new Error(`client_input lookup failed: ${priorError.message}`);if((priorRows??[]).length)continue}let value;try{value=_DevWorkbookManager.envelope(field.fieldType,answer.value)}catch(error2){throw new Error(`${workbook.template_name}.${answer.field_name}: ${error2 instanceof Error?error2.message:String(error2)}`)}const{error}=await this.options.supabase.from("client_input").insert({form_id:formId,field_id:field.id,org_id:this.options.orgId,value});if(error)throw new Error(`client_input insert failed: ${error.message}`);count++}return count}};var CUTOVER_OWNED_COLUMNS=["remote_version","previous_version","remote_url","remote_storage_bucket"];var LAYOUT_SYNC_OWNED=["name","description"];var OrgManager=class extends LayerManager{get shape(){return{fields:{slug:{type:"string",required:true,minLength:1},name:{type:"string",required:true,minLength:1},advisor:{type:"boolean"},advisor_org_slug:{type:"string"},bundle_name:{type:"string"},asset_bucket:{type:"string"},description:{type:"string"}},ignored:["_comment"]}}naturalKeyOf(def){return def.slug}naturalKeyFilter(def){return{metadata_org_slug:def.slug}}toRow(){throw new Error("OrgManager writes via syncAll()")}files(){return["org.json"]}async fetchDbKeys(){const config=loadOrgConfig();const org=await findOrgBySlug(this.options.supabase,config.slug);return org?new Map([[config.slug,org.id]]):new Map}async syncAll(){const started=Date.now();const entities=[];const errors=[];const config=loadOrgConfig();const dryRun=this.options.dryRun;try{const existingOrg=await findOrgBySlug(this.options.supabase,config.slug);let advisorOrgId=null;if(!config.advisor&&config.advisor_org_slug){const advisorOrg=await findOrgBySlug(this.options.supabase,config.advisor_org_slug);if(advisorOrg){advisorOrgId=advisorOrg.id;this.mappings.set("org",config.advisor_org_slug,advisorOrg.id)}else{entities.push({entity:`advisor:${config.advisor_org_slug}`,action:"skipped",id:null,reason:`advisor org "${config.advisor_org_slug}" not found in ${this.options.targetEnv} \u2014 seed the advisor org repo first, then re-run. Advisor-scoped lookups stay unresolved until then.`})}}const orgMetadata={...existingOrg?{}:{seeded:true,created_at:new Date().toISOString()},org_slug:config.slug,organization_type:config.advisor?"advisor":"client",...config.advisor_org_slug?{advisor_org_slug:config.advisor_org_slug}:{},...advisorOrgId?{advisor_org_id:advisorOrgId}:{}};let orgId;if(existingOrg){orgId=existingOrg.id;if(!dryRun){const{data:current}=await this.options.supabase.from("organization").select("metadata").eq("id",orgId).single();const merged={...current?.metadata??{},...orgMetadata};const{error}=await this.options.supabase.from("organization").update({advisor:config.advisor,metadata:merged}).eq("id",orgId);if(error)throw new Error(`organization update failed: ${error.message}`)}entities.push({entity:`organization:${config.slug}`,action:"updated",id:orgId})}else if(dryRun){orgId="(new)";entities.push({entity:`organization:${config.slug}`,action:"created",id:orgId})}else{const{data,error}=await this.options.supabase.from("organization").insert([{name:config.name,advisor:config.advisor,created_by:"00000000-0000-0000-0000-000000000000",metadata:orgMetadata}]).select("id").single();if(error)throw new Error(`organization insert failed: ${error.message}`);orgId=data.id;entities.push({entity:`organization:${config.slug}`,action:"created",id:orgId})}if(!dryRun&&orgId!=="(new)")this.mappings.set("org",config.slug,orgId);const{data:templateRows,error:templateError}=await this.options.supabase.from("org_template").select("id, metadata").eq("org_id",orgId==="(new)"?"00000000-0000-0000-0000-000000000000":orgId).eq("is_archived",false).limit(2);if(templateError)throw new Error(`org_template lookup failed: ${templateError.message}`);const templates=templateRows??[];if(templates.length>1){throw new Error(`${templates.length} non-archived org_template rows for org ${orgId} \u2014 ambiguous. Fix the DB first.`)}const existingTemplate=templates[0];if(existingTemplate){const patch={advisor_org_id:advisorOrgId,is_published:true,is_archived:false,metadata:{...existingTemplate.metadata??{},org_slug:config.slug,organization_type:config.advisor?"advisor":"client",...config.advisor_org_slug?{advisor_org_slug:config.advisor_org_slug}:{}},updated_at:new Date().toISOString()};const leaked=[...CUTOVER_OWNED_COLUMNS,...LAYOUT_SYNC_OWNED,"remote_name","remote_enabled"].filter(c=>c in patch);if(leaked.length){throw new Error(`BUG: org layer patch contains non-owned column(s): ${leaked.join(", ")}`)}if(!dryRun){const{error}=await this.options.supabase.from("org_template").update(patch).eq("id",existingTemplate.id);if(error)throw new Error(`org_template update failed: ${error.message}`)}entities.push({entity:"org_template",action:"updated",id:existingTemplate.id});if(!dryRun)this.mappings.set("org_template",config.slug,existingTemplate.id)}else if(dryRun){entities.push({entity:"org_template",action:"created",id:"(new)"})}else{const{data,error}=await this.options.supabase.from("org_template").insert([{org_id:orgId,advisor_org_id:advisorOrgId,name:config.name,description:config.description??null,is_published:true,is_archived:false,remote_name:config.slug,remote_enabled:true,metadata:{org_slug:config.slug,organization_type:config.advisor?"advisor":"client",...config.advisor_org_slug?{advisor_org_slug:config.advisor_org_slug}:{},created_by:"template-cli"}}]).select("id").single();if(error)throw new Error(`org_template insert failed: ${error.message}`);const templateId=data.id;entities.push({entity:"org_template",action:"created",id:templateId});this.mappings.set("org_template",config.slug,templateId)}}catch(error){errors.push({entity:"org",error:error instanceof Error?error.message:String(error)})}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}};import{existsSync as existsSync6,readFileSync as readFileSync3}from"node:fs";import{relative}from"node:path";var COLUMNS="id, org_id, org_slug, bundle_name, version, status, is_live, uploaded_at";async function resolveBundle(supabase,orgId,orgSlug,options={}){const bundleName=options.bundleName??"main";const version=options.version??null;if(version){const{data,error}=await supabase.from("component_bundle").select(COLUMNS).eq("org_id",orgId).eq("bundle_name",bundleName).eq("version",version).limit(2);if(error)throw new Error(`component_bundle lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} bundles match org=${orgSlug} bundle=${bundleName} version=${version} \u2014 ambiguous.`)}const row2=rows[0];if(!row2){throw new Error(`no component_bundle for org=${orgSlug} bundle=${bundleName} version=${version}.`)}return{...row2,resolved_by:"pin"}}const{data:liveRows,error:liveError}=await supabase.from("component_bundle").select(COLUMNS).eq("org_id",orgId).eq("bundle_name",bundleName).eq("is_live",true).limit(2);if(liveError)throw new Error(`component_bundle lookup failed: ${liveError.message}`);const live=liveRows??[];if(live.length>1){throw new Error(`${live.length} bundles in lineage "${bundleName}" (org=${orgSlug}) have is_live=true \u2014 exactly one row may be live. Re-run cutover from whichever repo owns this org's deploy pipeline (this one if it has scripts/cutover.mjs):
9
+ npm run deploy:cutover -- --org ${orgSlug} --version <v> --<env>`)}if(live[0]){return{...live[0],resolved_by:"is_live"}}const{data:latestRows,error:latestError}=await supabase.from("component_bundle").select(COLUMNS).eq("org_id",orgId).eq("bundle_name",bundleName).order("uploaded_at",{ascending:false}).limit(1);if(latestError)throw new Error(`component_bundle lookup failed: ${latestError.message}`);const latest=(latestRows??[])[0];if(!latest){throw new Error(`no component_bundle found for org=${orgSlug} bundle=${bundleName}. Run \`npm run deploy:upload\` first.`)}const row=latest;console.warn(`[template] \u26A0 no is_live bundle in lineage "${bundleName}" (org=${orgSlug}) \u2014 falling back to the most recently uploaded bundle (${row.version}). The host serves ONLY the is_live row, so this metadata may describe components the host is not running. Pin with --version, or promote one first from THIS repo:
10
+ npm run deploy:cutover -- --org ${orgSlug} --version ${row.version} --<env>`);return{...latest,resolved_by:"latest-uploaded"}}async function lineageExists(supabase,orgId,bundleName){const{data,error}=await supabase.from("component_bundle_lineage").select("bundle_name").eq("org_id",orgId).eq("bundle_name",bundleName).limit(1);if(error)throw new Error(`component_bundle_lineage lookup failed: ${error.message}`);return(data??[]).length>0}async function resolveBundleIfAny(supabase,orgId,orgSlug,options={}){try{return await resolveBundle(supabase,orgId,orgSlug,options)}catch(error){const message=error instanceof Error?error.message:String(error);if(!options.version&&message.startsWith("no component_bundle found for org="))return null;throw error}}var HOST_NATIVE_COMPONENTS=new Set(["ProjectPageByType","ProjectPageById","ProjectPageRenderer","IndividualPageViewer","CellRenderer","CellsRenderer"]);var REGISTRY_COLUMNS="component_name, description, props_schema, delivery_mode, exposed_export, is_active";async function fetchRegistry(supabase,bundleId,componentNames){if(!bundleId||componentNames.length===0)return new Map;const{data,error}=await supabase.from("component_registry").select(REGISTRY_COLUMNS).eq("bundle_id",bundleId).in("component_name",componentNames);if(error)throw new Error(`component_registry lookup failed: ${error.message}`);const rows=data??[];return new Map(rows.map(row=>[row.component_name,row]))}function missingBundleComponents(componentNames,registry){return componentNames.filter(n=>!registry.has(n)&&!HOST_NATIVE_COMPONENTS.has(n))}var SHELL_BLOCK_KEYS=["tab_bar","app_bar","chat_rail","more_menu"];function collectFromLayout(layout,out){if(!layout||typeof layout!=="object")return;const l=layout;if(l.base_route?.component)out.add(l.base_route.component);for(const route of l.whitelisted_routes??[]){if(route?.component)out.add(route.component);if(route?.right_sidebar?.component)out.add(route.right_sidebar.component)}for(const nav of l.sidebar?.navigation??[]){if(nav?.component)out.add(nav.component)}if(l.right_sidebar?.component)out.add(l.right_sidebar.component);for(const key of SHELL_BLOCK_KEYS){const block=l[key];if(block?.component)out.add(block.component)}}function collectComponentNames(payload){const out=new Set;collectFromLayout(payload.layout,out);for(const tier of["public","portal","platform","agency","aux"]){collectFromLayout(payload[`${tier}_layout`],out)}return[...out]}function collectCellComponents(cells){return[...new Set(cells.map(c=>c?.component).filter(c=>Boolean(c)))]}function extractRegistryMeta(row){const props=row.props_schema??{};return{description:row.description??null,declared_data:props.data??null,declared_actions:props.actions??null,declared_props:props.properties??null,contract_version:props.contract_version??null,delivery_mode:row.delivery_mode??null,exposed_export:row.exposed_export??null}}function metaFor(component,registry){if(!component)return null;const row=registry.get(component);return row?extractRegistryMeta(row):null}function inlineRouteRegistryMeta(routes,registry){if(!Array.isArray(routes))return routes;return routes.map(route=>{if(!route?.component)return route;const next={...route,registry_meta:metaFor(route.component,registry)};const sidebar=route.right_sidebar;if(sidebar?.component){next.right_sidebar={...sidebar,registry_meta:metaFor(sidebar.component,registry)}}return next})}function inlineNavRegistryMeta(navItems,registry){if(!Array.isArray(navItems))return navItems;return navItems.map(item=>item?.component?{...item,registry_meta:metaFor(item.component,registry)}:item)}function annotateLayout(layout,registry){if(!layout||typeof layout!=="object")return layout;const l=layout;return{...l,...l.sidebar?{sidebar:{...l.sidebar,navigation:inlineNavRegistryMeta(l.sidebar.navigation,registry)}}:{},...l.whitelisted_routes?{whitelisted_routes:inlineRouteRegistryMeta(l.whitelisted_routes,registry)}:{}}}function buildTemplateMeta(input){const{sourcePath,bundle,componentNames,registry,generator}=input;return{source:sourcePath,generated_at:new Date().toISOString(),generator,bundle_id:bundle.id,bundle_version:bundle.version,bundle_org_slug:bundle.org_slug,bundle_status:bundle.status,bundle_resolved_by:bundle.resolved_by,component_count:componentNames.length,missing_components:missingBundleComponents(componentNames,registry),host_native_components:componentNames.filter(n=>HOST_NATIVE_COMPONENTS.has(n))}}function stripHarnessOnly(value){if(Array.isArray(value))return value.map(v=>stripHarnessOnly(v));if(value&&typeof value==="object"){const out={};for(const[key,v]of Object.entries(value)){if(key.startsWith("_harness_")||key.startsWith("_mock"))continue;out[key]=stripHarnessOnly(v)}return out}return value}var GENERATOR="template/cli sync --layer org-template-layout";var LAYOUT_COLUMNS=["public_layout","portal_layout","platform_layout","agency_layout","aux_layout"];var CUTOVER_OWNED_COLUMNS2=["remote_name","remote_version","previous_version","remote_url","remote_storage_bucket","remote_enabled"];var OrgTemplateLayoutManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"}},allowUnknown:true}}naturalKeyOf(def){return def.name}naturalKeyFilter(){return{metadata_org_slug:loadOrgConfig().slug}}toRow(){throw new Error("OrgTemplateLayoutManager writes via syncAll()")}source(){const config=loadTemplatesConfig().org_template;if(!config)return null;return{slug:config.slug,bundleName:config.bundle_name??"main",layoutBundles:config.layout_bundles??{},path:orgTemplatePath(config.slug)}}bundleFor(column){const source=this.source();return source?.layoutBundles[column]??source?.bundleName??"main"}files(){const source=this.source();return source&&existsSync6(source.path)?[`src/org_templates/${source.slug}/template.json`]:[]}read(path){const parsed=JSON.parse(readFileSync3(path,"utf8"));const file=parsed;if(!file||typeof file.name!=="string"){throw new Error(`${path}: template.json must have at least { "name": "..." }`)}return file}fileKeys(){const source=this.source();if(!source||!existsSync6(source.path))return[];try{return[this.read(source.path).name]}catch{return[]}}async fetchDbKeys(){const source=this.source();if(!source||!existsSync6(source.path))return new Map;const{data,error}=await this.options.supabase.from("org_template").select("id, name").eq("org_id",this.options.orgId).eq("is_archived",false).limit(2);if(error)throw new Error(`org_template lookup failed: ${error.message}`);const rows=data??[];return new Map(rows.map(r=>[r.name,r.id]))}validateAll(){const errors=[];const warnings=[];const source=this.source();if(!source){return{layer:this.def.name,filesChecked:0,errors,warnings}}const label=`src/org_templates/${source.slug}/template.json`;if(!existsSync6(source.path)){errors.push({file:label,message:`declared in config/templates.json but not found on disk`});return{layer:this.def.name,filesChecked:0,errors,warnings}}let file;try{file=this.read(source.path)}catch(error){errors.push({file:label,message:error instanceof Error?error.message:String(error)});return{layer:this.def.name,filesChecked:1,errors,warnings}}const declared=LAYOUT_COLUMNS.filter(c=>file[c]!==void 0);if(declared.length===0){warnings.push({file:label,message:"declares no *_layout column \u2014 nothing to sync"})}const droppable=Object.keys(file).filter(k=>!["name","description","is_published","is_archived","metadata"].includes(k)&&!LAYOUT_COLUMNS.includes(k));for(const key of droppable){warnings.push({file:label,message:`"${key}" has no org_template column and is not written (harness-only or dead config)`})}if(collectComponentNames(file).length===0){warnings.push({file:label,message:"no component references found in any layout"})}return{layer:this.def.name,filesChecked:1,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];const source=this.source();const done=()=>({layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started});if(!source){entities.push({entity:"org-template-layout",action:"skipped",id:null,reason:"no org_template declared in config/templates.json"});return done()}try{const file=this.read(source.path);const cleaned=stripHarnessOnly(file);const presentColumns=LAYOUT_COLUMNS.filter(c=>cleaned[c]!==void 0);const neededLineages=[...new Set([source.bundleName,...presentColumns.map(c=>this.bundleFor(c))])].sort();const bundles=new Map;for(const lineage of neededLineages){const resolved=await resolveBundleIfAny(this.options.supabase,this.options.orgId,this.options.orgSlug,{version:lineage===source.bundleName?this.options.versionPin??null:null,bundleName:lineage});if(!resolved){entities.push({entity:`org_template:${cleaned.name}`,action:"skipped",id:null,reason:`no component_bundle in lineage "${lineage}" yet \u2014 layouts inline registry metadata from the bundle the host serves. Deploy (upload \u2192 register \u2192 host cutover), then re-run this layer.`});return done()}bundles.set(lineage,resolved)}const bundle=bundles.get(source.bundleName);const componentNames=collectComponentNames(cleaned);const registries=new Map;for(const lineage of neededLineages){const names=new Set;for(const column of presentColumns){if(this.bundleFor(column)!==lineage)continue;for(const n of collectComponentNames({[column]:cleaned[column]}))names.add(n)}const target=bundles.get(lineage);registries.set(lineage,await fetchRegistry(this.options.supabase,target.id,[...names]));const missing=missingBundleComponents([...names],registries.get(lineage));if(missing.length){console.warn(`[template] \u26A0 ${missing.length} component(s) not in ${lineage} bundle ${target.version}: ${missing.join(", ")}. Routes referencing them land with registry_meta=null.`)}}const registry=new Map;for(const r of registries.values())for(const[k,v]of r)registry.set(k,v);const{data:rows,error:fetchError}=await this.options.supabase.from("org_template").select("id, name, metadata").eq("org_id",this.options.orgId).eq("is_archived",false).limit(2);if(fetchError)throw new Error(`org_template lookup failed: ${fetchError.message}`);const existing=rows??[];if(existing.length>1){throw new Error(`${existing.length} non-archived org_template rows for this org \u2014 ambiguous. Fix the DB first.`)}const row=existing[0];if(!row){throw new Error(`no org_template row for "${this.options.orgSlug}". Run \`sync --layer org\` first \u2014 that layer owns row creation, this one owns the layout columns.`)}const patch={name:cleaned.name,updated_at:new Date().toISOString()};if(cleaned.description!==void 0)patch.description=cleaned.description;if(cleaned.is_published!==void 0)patch.is_published=cleaned.is_published;if(cleaned.is_archived!==void 0)patch.is_archived=cleaned.is_archived;for(const column of presentColumns){patch[column]=annotateLayout(cleaned[column],registries.get(this.bundleFor(column)))}patch.metadata={...row.metadata??{},...cleaned.metadata??{},org_slug:row.metadata?.org_slug??cleaned.metadata?.org_slug??this.options.orgSlug,bundle_refs:cleaned.metadata?.bundle_refs??[bundle.org_slug],template_meta:{...buildTemplateMeta({sourcePath:relative(REPO_ROOT,source.path),bundle,componentNames,registry,generator:GENERATOR}),layout_bundles:Object.fromEntries(presentColumns.map(column=>{const lineage=this.bundleFor(column);return[column,{bundle_name:lineage,version:bundles.get(lineage).version}]}))}};const leaked=CUTOVER_OWNED_COLUMNS2.filter(c=>c in patch);if(leaked.length){throw new Error(`BUG: cutover-owned column(s) in patch: ${leaked.join(", ")}`)}const untouched=LAYOUT_COLUMNS.filter(c=>!(c in patch));if(untouched.length){console.log(` layout columns preserved (absent from template.json): ${untouched.join(", ")}`)}if(!this.options.dryRun){const{error}=await this.options.supabase.from("org_template").update(patch).eq("id",row.id);if(error)throw new Error(`org_template update failed: ${error.message}`);this.mappings.set("org_template",this.options.orgSlug,row.id)}entities.push({entity:`org_template:${cleaned.name} (bundle ${bundle.version} via ${bundle.resolved_by})`,action:"updated",id:row.id})}catch(error){errors.push({entity:`src/org_templates/${source.slug}/template.json`,error:error instanceof Error?error.message:String(error)})}return done()}async healthChecks(){const source=this.source();if(!source||!existsSync6(source.path))return[];const{data,error}=await this.options.supabase.from("org_template").select("metadata").eq("org_id",this.options.orgId).eq("is_archived",false).limit(1);if(error){return[{name:"layout-bundle",severity:"warn",message:`lookup failed: ${error.message}`}]}const meta=(data??[])[0]?.metadata;const templateMeta=meta?.template_meta;if(!templateMeta){return[{name:"layout-bundle",severity:"warn",message:"org_template has no metadata.template_meta \u2014 layouts have never been synced from src/"}]}let live;try{live=await resolveBundle(this.options.supabase,this.options.orgId,this.options.orgSlug,{bundleName:source.bundleName})}catch(error2){return[{name:"layout-bundle",severity:"warn",message:error2 instanceof Error?error2.message:String(error2)}]}const recorded=templateMeta.bundle_version;if(recorded&&live.resolved_by==="is_live"&&recorded!==live.version){return[{name:"layout-bundle",severity:"warn",message:`layouts were annotated from bundle ${recorded}, but the host serves ${live.version}. Re-run \`sync --layer org-template-layout\` so registry_meta describes what is running.`}]}return[{name:"layout-bundle",severity:"ok",message:`layouts annotated from ${recorded??"(unknown)"}; host serves ${live.version} (${live.resolved_by})`}]}};import{existsSync as existsSync7,readFileSync as readFileSync4}from"node:fs";import{join as join6}from"node:path";var CONFIG_FILE=join6(CONFIG_DIR,"public.json");var DOMAIN_SHAPE={fields:{domain_pattern:{type:"string",required:true,minLength:1},is_wildcard:{type:"boolean",default:false},priority:{type:"number",default:100},is_active:{type:"boolean",default:true}},ignored:["_comment"]};var OrgTemplatePublicManager=class extends LayerManager{get shape(){return DOMAIN_SHAPE}naturalKeyOf(def){return def.domain_pattern}naturalKeyFilter(){throw new Error("OrgTemplatePublicManager writes via syncAll()")}toRow(){throw new Error("OrgTemplatePublicManager writes via syncAll()")}config(){if(!existsSync7(CONFIG_FILE))return null;const parsed=JSON.parse(readFileSync4(CONFIG_FILE,"utf8"));const outer=validateShape(parsed,{fields:{advisor_org_slug:{type:"string",required:true,minLength:1},domains:{type:"array",required:true},branding:{type:"object"},metadata:{type:"object"}},ignored:["_comment"]});if(!outer.ok||!outer.value){throw new Error(`template/config/public.json is invalid:
11
+ - ${outer.errors.join("\n - ")}`)}const domains=[];outer.value.domains.forEach((raw,index)=>{const result=validateShape(raw,DOMAIN_SHAPE);if(!result.ok||!result.value){throw new Error(`public.json domains[${index}] is invalid: ${result.errors.join("; ")}`)}domains.push(result.value)});const full=parsed;return{advisor_org_slug:outer.value.advisor_org_slug,domains,branding:full.branding,metadata:full.metadata}}publicLayout(){const configured=loadTemplatesConfig().org_template;if(!configured)return null;const path=orgTemplatePath(configured.slug);if(!existsSync7(path))return null;const parsed=JSON.parse(readFileSync4(path,"utf8"));return parsed.public_layout??null}files(){const config=this.config();if(!config)return[];const filter=this.options.nameFilter;const domains=config.domains.map(d=>d.domain_pattern);return filter?domains.filter(d=>d===filter):domains}fileKeys(){return this.files()}async advisorOrgId(slug){if(slug===loadOrgConfig().slug)return this.options.orgId;const org=await findOrgBySlug(this.options.supabase,slug);if(!org){throw new Error(`public.json advisor_org_slug "${slug}" resolves to no organization. Seed that org first.`)}return org.id}validateAll(){const errors=[];const warnings=[];let config;try{config=this.config()}catch(error){errors.push({file:"config/public.json",message:error instanceof Error?error.message:String(error)});return{layer:this.def.name,filesChecked:1,errors,warnings}}if(!config)return{layer:this.def.name,filesChecked:0,errors,warnings};const seen=new Set;for(const domain of config.domains){if(seen.has(domain.domain_pattern)){errors.push({file:"config/public.json",message:`domain_pattern "${domain.domain_pattern}" is declared twice`})}seen.add(domain.domain_pattern);if(domain.domain_pattern.includes("*")&&domain.is_wildcard!==true){warnings.push({file:"config/public.json",message:`"${domain.domain_pattern}" contains * but is_wildcard is false \u2014 it will only ever match literally`})}}if(!this.publicLayout()){warnings.push({file:"config/public.json",message:"the configured org template declares no public_layout \u2014 every domain row would be written with a null layout, and the anonymous path renders nothing"})}return{layer:this.def.name,filesChecked:1,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];const done=()=>({layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started});let config;try{config=this.config()}catch(error){errors.push({entity:"config/public.json",error:error instanceof Error?error.message:String(error)});return done()}if(!config){entities.push({entity:"org-template-public",action:"skipped",id:null,reason:"no template/config/public.json \u2014 this org publishes no public site"});return done()}const layout=this.publicLayout();const selected=new Set(this.files());let advisorOrgId;try{advisorOrgId=await this.advisorOrgId(config.advisor_org_slug)}catch(error){errors.push({entity:"advisor_org_slug",error:error instanceof Error?error.message:String(error)});return done()}for(const domain of config.domains){if(!selected.has(domain.domain_pattern))continue;try{const outcome=await upsertByNaturalKey(this.options.supabase,"org_template_public",{advisor_org_id:advisorOrgId,domain_pattern:domain.domain_pattern},{advisor_org_id:advisorOrgId,domain_pattern:domain.domain_pattern,is_wildcard:domain.is_wildcard??false,priority:domain.priority??100,is_active:domain.is_active??true,public_layout:layout,branding:config.branding??null,metadata:config.metadata??null,updated_at:new Date().toISOString()},{dryRun:this.options.dryRun});entities.push({entity:domain.domain_pattern,action:outcome.action,id:outcome.id})}catch(error){errors.push({entity:domain.domain_pattern,error:error instanceof Error?error.message:String(error)})}}return done()}async fetchDbKeys(){const config=this.config();if(!config)return new Map;const advisorOrgId=await this.advisorOrgId(config.advisor_org_slug);const{data,error}=await this.options.supabase.from("org_template_public").select("id, domain_pattern").eq("advisor_org_id",advisorOrgId);if(error)throw new Error(`org_template_public: ${error.message}`);const keys=new Map;for(const row of data??[]){keys.set(row.domain_pattern,row.id)}return keys}async healthChecks(){const config=this.config();if(!config)return[];const live=config.domains.filter(d=>d.is_active!==false);const exact=live.filter(d=>d.is_wildcard!==true);if(live.length===0){return[{name:"public-domains",severity:"fail",message:"every domain in public.json is is_active:false \u2014 the public site resolves nowhere"}]}if(exact.length===0){return[{name:"public-domains",severity:"warn",message:`${live.length} active domain(s), all wildcards \u2014 preview URLs resolve but the production hostname does not`}]}return[{name:"public-domains",severity:"ok",message:`${exact.length} exact + ${live.length-exact.length} wildcard domain(s) active`}]}};import{readFileSync as readFileSync5}from"node:fs";import{relative as relative2}from"node:path";var GENERATOR2="template/cli sync --layer page-templates";var PageTemplateManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},status:{type:"string",default:"active"},page_type:{type:"string"},content:{type:"object",required:true},layout:{type:"object"},metadata:{type:"object"}},allowUnknown:true}}naturalKeyOf(def){return def.page_type??def.name}naturalKeyFilter(def){return def.page_type?{org_id:this.options.orgId,page_type:def.page_type,is_template:true}:{org_id:this.options.orgId,name:def.name,is_template:true}}toRow(){throw new Error("PageTemplateManager writes via syncAll()")}sources(){const filter=this.options.nameFilter;const out=[];for(const template of loadTemplatesConfig().project_templates){if(template.skip_pages)continue;for(const page of projectTemplatePages(template.slug)){const label=`${template.slug}/${page.page}`;if(filter&&filter!==page.page&&filter!==label&&filter!==template.slug)continue;out.push({label,projectSlug:template.slug,bundleName:template.bundle_name??"main",path:page.path})}}return out}files(){return this.sources().map(s=>`src/project_templates/${s.projectSlug}/pages/${s.label.split("/")[1]}/page.json`)}read(path){const parsed=JSON.parse(readFileSync5(path,"utf8"));const file=parsed;if(!file?.name||!Array.isArray(file.content?.cells)){throw new Error(`${path}: page.json needs { name, content: { cells: [...] } }`)}return file}fileKeys(){const keys=[];for(const source of this.sources()){try{const file=this.read(source.path);keys.push(file.page_type??file.name)}catch{}}return keys}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("project_page").select("id, name, page_type").eq("org_id",this.options.orgId).eq("is_template",true);if(error)throw new Error(`project_page lookup failed: ${error.message}`);const out=new Map;this.duplicateDbKeys.clear();for(const row of data??[]){const key=row.page_type??row.name;if(out.has(key))this.duplicateDbKeys.add(key);out.set(key,row.id)}return out}validateAll(){const errors=[];const warnings=[];const byPageType=new Map;let checked=0;for(const source of this.sources()){const label=`${source.label}/page.json`;let file;try{file=this.read(source.path)}catch(error){errors.push({file:label,message:error instanceof Error?error.message:String(error)});continue}checked++;if(!file.page_type){warnings.push({file:label,message:"no page_type \u2014 the row can only be addressed by name, and project_template routes address pages by params.pageType"})}else{const previous=byPageType.get(file.page_type);if(previous){errors.push({file:label,message:`page_type "${file.page_type}" is also declared by ${previous}`})}else{byPageType.set(file.page_type,label)}}const cells=file.content.cells??[];if(cells.length===0){warnings.push({file:label,message:"no cells \u2014 the page renders empty"})}if(!file.layout){warnings.push({file:label,message:"no layout \u2014 one is derived from cell order on write"})}}return{layer:this.def.name,filesChecked:checked,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];const bundles=new Map;const bundleFor=async source=>{if(bundles.has(source.bundleName))return bundles.get(source.bundleName)??null;const resolved=await resolveBundleIfAny(this.options.supabase,this.options.orgId,this.options.orgSlug,{version:this.options.versionPin??null,bundleName:source.bundleName});bundles.set(source.bundleName,resolved);return resolved};for(const source of this.sources()){try{const file=stripHarnessOnly(this.read(source.path));const cells=file.content.cells??[];const bundle=await bundleFor(source);if(!bundle){entities.push({entity:source.label,action:"skipped",id:null,reason:`no component_bundle in lineage "${source.bundleName}" yet \u2014 cells inline registry metadata from it. Deploy the bundle, then re-run.`});continue}const componentNames=collectCellComponents(cells);const registry=await fetchRegistry(this.options.supabase,bundle.id,componentNames);const missing=missingBundleComponents(componentNames,registry);if(missing.length){console.warn(`[template] \u26A0 ${source.label}: ${missing.length} cell component(s) not in bundle ${bundle.version}: ${missing.join(", ")}`)}const naturalKey=this.naturalKeyFilter(file);let existingMetadata={};let lookup=this.options.supabase.from("project_page").select("id, metadata").eq("org_id",this.options.orgId).eq("is_template",true);lookup=file.page_type?lookup.eq("page_type",file.page_type):lookup.eq("name",file.name);const{data:existingRows,error:readError}=await lookup.limit(2);if(readError)throw new Error(`project_page lookup failed: ${readError.message}`);const existing=existingRows??[];if(existing[0])existingMetadata=existing[0].metadata??{};const row={org_id:this.options.orgId,project_id:null,is_template:true,name:file.name,status:file.status??"active",page_type:file.page_type??null,content:file.content,layout:file.layout??{type:"grid",structure:cells.map(c=>({cellId:c.id}))},metadata:{...existingMetadata,...file.metadata??{},bundle_refs:[bundle.org_slug],template_meta:{source:relative2(REPO_ROOT,source.path),generated_at:new Date().toISOString(),generator:GENERATOR2,bundle_id:bundle.id,bundle_version:bundle.version,bundle_org_slug:bundle.org_slug,bundle_status:bundle.status,bundle_resolved_by:bundle.resolved_by,project_template:source.projectSlug,cell_count:cells.length,missing_components:missing}},updated_at:new Date().toISOString()};const outcome=await upsertByNaturalKey(this.options.supabase,"project_page",naturalKey,row,{dryRun:this.options.dryRun});if(!this.options.dryRun){this.mappings.set("project_page",file.page_type??file.name,outcome.id)}entities.push({entity:`${source.label} \u2192 ${file.page_type??file.name} (${cells.length} cells)`,action:outcome.action,id:outcome.id})}catch(error){errors.push({entity:source.label,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}async healthChecks(){const{data,error}=await this.options.supabase.from("project_page").select("id, name, page_type, created_at").eq("org_id",this.options.orgId).eq("is_template",true);if(error){return[{name:"page-template-dupes",severity:"warn",message:`lookup failed: ${error.message}`}]}const rows=data??[];const groups=new Map;for(const row of rows){const key=row.page_type??`name:${row.name}`;groups.set(key,[...groups.get(key)??[],row])}const duplicated=[...groups.entries()].filter(([,group])=>group.length>1);if(duplicated.length===0){return[{name:"page-template-dupes",severity:"ok",message:`${groups.size} page template(s), one row each`}]}return[{name:"page-template-dupes",severity:"fail",message:`${duplicated.length} page type(s) have more than one template row \u2014 sync refuses to write them, and a page-builder agent cannot tell which is current. Created by scripts/upload-page-template.mjs, which upserts on a freshly generated id`,detail:duplicated.map(([key,group])=>`${key}: ${group.length} rows \u2014 ${group.map(r=>`${r.id.slice(0,8)} (${r.created_at.slice(0,10)})`).join(", ")}`)}]}};import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{join as join7,relative as relative3}from"node:path";var GENERATOR3="template/cli sync --layer project-templates";var ProjectTemplateManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"},project_type:{type:"string"},layout:{type:"object"},metadata:{type:"object"}},allowUnknown:true}}naturalKeyOf(def){return def.name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:def.name}}toRow(){throw new Error("ProjectTemplateManager writes via syncAll()")}sources(){const filter=this.options.nameFilter;return loadTemplatesConfig().project_templates.filter(t=>!filter||t.slug===filter).map(t=>({slug:t.slug,bundleName:t.bundle_name??"main",path:join7(projectTemplateDir(t.slug),"template.json")}))}files(){return this.sources().filter(s=>existsSync8(s.path)).map(s=>`src/project_templates/${s.slug}/template.json`)}read(path){const parsed=JSON.parse(readFileSync6(path,"utf8"));const file=parsed;if(!file||typeof file.name!=="string"){throw new Error(`${path}: template.json must have at least { "name": "..." }`)}return file}fileKeys(){const keys=[];for(const source of this.sources()){if(!existsSync8(source.path))continue;try{keys.push(this.read(source.path).name)}catch{}}return keys}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("project_template").select("id, name").eq("org_id",this.options.orgId);if(error)throw new Error(`project_template lookup failed: ${error.message}`);const out=new Map;for(const row of data??[]){out.set(row.name,row.id)}return out}validateAll(){const errors=[];const warnings=[];let checked=0;for(const source of this.sources()){const label=`src/project_templates/${source.slug}/template.json`;if(!existsSync8(source.path)){errors.push({file:label,message:"declared in config/templates.json but not on disk"});continue}checked++;let file;try{file=this.read(source.path)}catch(error){errors.push({file:label,message:error instanceof Error?error.message:String(error)});continue}if(!file.project_type){warnings.push({file:label,message:"no project_type \u2014 page-type routing needs one (host doc 07/08)"})}if(!file.layout){warnings.push({file:label,message:"no layout \u2014 the project renders no routes"})}if(collectComponentNames(file).length===0){warnings.push({file:label,message:"layout references no components"})}}return{layer:this.def.name,filesChecked:checked,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];for(const source of this.sources()){const label=`src/project_templates/${source.slug}/template.json`;try{if(!existsSync8(source.path)){throw new Error("declared in config/templates.json but not on disk")}const cleaned=stripHarnessOnly(this.read(source.path));const bundle=await resolveBundleIfAny(this.options.supabase,this.options.orgId,this.options.orgSlug,{version:this.options.versionPin??null,bundleName:source.bundleName});if(!bundle){entities.push({entity:cleaned.name,action:"skipped",id:null,reason:`no component_bundle in lineage "${source.bundleName}" yet \u2014 routes inline registry metadata from it, and project_template.bundle_name has an FK to component_bundle_lineage, which host cutover creates. Deploy the bundle, then re-run.`});continue}const componentNames=collectComponentNames(cleaned);const registry=await fetchRegistry(this.options.supabase,bundle.id,componentNames);const missing=missingBundleComponents(componentNames,registry);if(missing.length){console.warn(`[template] \u26A0 ${source.slug}: ${missing.length} component(s) not in bundle ${bundle.version}: ${missing.join(", ")}`)}const{data:existingRows,error:readError}=await this.options.supabase.from("project_template").select("id, metadata, bundle_name").eq("org_id",this.options.orgId).eq("name",cleaned.name).limit(2);if(readError)throw new Error(`project_template lookup failed: ${readError.message}`);const existing=existingRows??[];if(existing.length>1){throw new Error(`${existing.length} project_template rows named "${cleaned.name}" for this org \u2014 ambiguous, refusing to write. Ids: ${existing.map(r=>r.id).join(", ")}.`)}const layout=cleaned.layout?{...cleaned.layout,whitelisted_routes:inlineRouteRegistryMeta(cleaned.layout.whitelisted_routes,registry)}:null;const row={org_id:this.options.orgId,name:cleaned.name,description:cleaned.description??null,project_type:cleaned.project_type??null,bundle_name:await lineageExists(this.options.supabase,this.options.orgId,source.bundleName)?source.bundleName:existing[0]?.bundle_name??null,layout,metadata:{...existing[0]?.metadata??{},...cleaned.metadata??{},bundle_refs:cleaned.metadata?.bundle_refs??[bundle.org_slug],template_meta:buildTemplateMeta({sourcePath:relative3(REPO_ROOT,source.path),bundle,componentNames,registry,generator:GENERATOR3})},updated_at:new Date().toISOString()};const outcome=await upsertByNaturalKey(this.options.supabase,"project_template",{org_id:this.options.orgId,name:cleaned.name},row,{dryRun:this.options.dryRun});if(!this.options.dryRun){this.mappings.set("project_template",cleaned.name,outcome.id)}entities.push({entity:`${cleaned.name} (${source.bundleName}/${bundle.version} via ${bundle.resolved_by})`,action:outcome.action,id:outcome.id})}catch(error){errors.push({entity:label,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}async healthChecks(){const checks=[];for(const source of this.sources()){if(!existsSync8(source.path))continue;let file;try{file=this.read(source.path)}catch{continue}const routes=file.layout?.whitelisted_routes??[];const referenced=[...new Set(routes.map(r=>r.params?.pageType).filter(t=>Boolean(t)))];if(referenced.length===0)continue;const{data,error}=await this.options.supabase.from("project_page").select("page_type").eq("org_id",this.options.orgId).eq("is_template",true).in("page_type",referenced);if(error){checks.push({name:"route-page-types",severity:"warn",message:`page-type lookup failed: ${error.message}`});continue}const present=new Set((data??[]).map(r=>r.page_type));const absent=referenced.filter(t=>!present.has(t));checks.push(absent.length===0?{name:"route-page-types",severity:"ok",message:`${source.slug}: all ${referenced.length} routed page type(s) have a template`}:{name:"route-page-types",severity:"fail",message:`${source.slug}: ${absent.length} routed page type(s) have NO template row \u2014 those routes render nothing for a client`,detail:absent})}return checks}};var ProjectManager=class extends LayerManager{get shape(){return{fields:{name:{type:"string",required:true,minLength:1},description:{type:"string"},status:{type:"string",default:"active"},project_template_name:{type:"string",required:true,minLength:1},clients:{type:"array",default:[]},metadata:{type:"object"}},ignored:["_comment"]}}naturalKeyOf(def){return def.name}naturalKeyFilter(def){return{org_id:this.options.orgId,name:def.name}}toRow(){throw new Error("ProjectManager writes via syncAll()")}async anyBundleDeployed(){const{data,error}=await this.options.supabase.from("component_bundle").select("id").eq("org_id",this.options.orgId).limit(1);if(error)throw new Error(`component_bundle lookup failed: ${error.message}`);return(data??[]).length>0}async resolveTemplateId(name){const{data,error}=await this.options.supabase.from("project_template").select("id").eq("org_id",this.options.orgId).eq("name",name).limit(2);if(error)throw new Error(`project_template lookup failed: ${error.message}`);const rows=data??[];if(rows.length>1){throw new Error(`${rows.length} project_template rows named "${name}" \u2014 ambiguous.`)}if(!rows[0]){if(!await this.anyBundleDeployed())return null;throw new Error(`no project_template named "${name}" for this org, and this org HAS deployed bundles \u2014 so this is a missing or misnamed template, not an undeployed environment. That row is owned by the project-templates LAYER, not this one:
12
+ npm run template -- sync --layer project-templates --env ${this.options.targetEnv}`)}return rows[0].id}async resolveClientId(reference){const bySlug=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("data->>slug",reference).limit(2);if(bySlug.error)throw new Error(`client lookup failed: ${bySlug.error.message}`);const slugRows=bySlug.data??[];if(slugRows.length>1){throw new Error(`${slugRows.length} clients have data->>slug="${reference}" \u2014 ambiguous.`)}if(slugRows[0])return slugRows[0].id;const byName=await this.options.supabase.from("client").select("id").eq("org_id",this.options.orgId).eq("name",reference).limit(2);if(byName.error)throw new Error(`client lookup failed: ${byName.error.message}`);const nameRows=byName.data??[];if(nameRows.length>1){throw new Error(`${nameRows.length} clients named "${reference}" \u2014 ambiguous.`)}return nameRows[0]?.id??null}async fetchDbKeys(){const{data,error}=await this.options.supabase.from("project").select("id, name").eq("org_id",this.options.orgId);if(error)throw new Error(`project lookup failed: ${error.message}`);const out=new Map;for(const row of data??[]){if(row.name)out.set(row.name,row.id)}return out}async syncAll(){const started=Date.now();const entities=[];const errors=[];if(this.options.targetEnv==="prod"){return{layer:this.def.name,created:0,updated:0,skipped:1,entities:[{entity:"projects",action:"skipped",id:null,reason:"dev fixtures never run against prod"}],errors,duration_ms:Date.now()-started}}for(const file of this.files()){try{const def=this.loadFile(file);const templateId=await this.resolveTemplateId(def.project_template_name);if(templateId===null){entities.push({entity:def.name,action:"skipped",id:null,reason:`project_template "${def.project_template_name}" does not exist yet \u2014 this org has no deployed bundle, so the project-templates layer skipped too. Deploy (upload \u2192 register \u2192 host cutover), re-run project-templates, then re-run this layer.`});continue}const outcome=await upsertByNaturalKey(this.options.supabase,"project",{org_id:this.options.orgId,name:def.name},{org_id:this.options.orgId,name:def.name,description:def.description??null,status:def.status,project_template_id:templateId,metadata:def.metadata??{}},{dryRun:this.options.dryRun});let linked=0;const unresolved=[];for(const reference of def.clients){const clientId=await this.resolveClientId(reference);if(!clientId){unresolved.push(reference);continue}if(this.options.dryRun){linked++;continue}const{data:existing}=await this.options.supabase.from("client_project").select("id").eq("client_id",clientId).eq("project_id",outcome.id).maybeSingle();if(!existing){const{error}=await this.options.supabase.from("client_project").insert({client_id:clientId,project_id:outcome.id,org_id:this.options.orgId});if(error)throw new Error(`client_project insert failed: ${error.message}`)}linked++}if(unresolved.length){console.warn(`[template] \u26A0 project "${def.name}": could not resolve client(s) ${unresolved.join(", ")} \u2014 seed dev-users first. The project exists but those clients cannot open it.`)}if(!this.options.dryRun)this.mappings.set("project",def.name,outcome.id);entities.push({entity:`${def.name} (${linked}/${def.clients.length} client link(s))`,action:outcome.action,id:outcome.id})}catch(error){errors.push({entity:file,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}};import{existsSync as existsSync9,readFileSync as readFileSync7,statSync}from"node:fs";import{extname,join as join8,resolve as resolve3}from"node:path";var MIME_TYPES={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".mp4":"video/mp4",".webm":"video/webm",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".csv":"text/csv"};var ASSET_SHAPE={fields:{bucket:{type:"string",required:true,minLength:1},entity_type:{type:"any"},root:{type:"enum",values:["layer","repo"],default:"layer"},local_path:{type:"string",required:true,minLength:1},storage_path:{type:"string",required:true,minLength:1},advisor_slug:{type:"string"},description:{type:"string"}}};var StorageAssetManager=class extends LayerManager{get shape(){return{fields:{org_slug:{type:"string",required:true,minLength:1},assets:{type:"array",required:true}},ignored:["_comment"]}}naturalKeyOf(def){return def.org_slug}naturalKeyFilter(){return{}}toRow(){throw new Error("StorageAssetManager uploads files; it writes no table row")}files(){return existsSync9(join8(DATA_DIR,"storage","manifest.json"))?["manifest.json"]:[]}manifest(){return this.loadFile("manifest.json")}assets(){const errors=[];const out=[];const manifest=this.manifest();manifest.assets.forEach((raw,index)=>{const result=validateShape(raw,ASSET_SHAPE);if(!result.ok||!result.value){errors.push(`assets[${index}]: ${result.errors.join("; ")}`);return}out.push(result.value)});return{assets:out,errors}}localFile(asset){return asset.root==="repo"?resolve3(REPO_ROOT,asset.local_path):resolve3(DATA_DIR,"storage",asset.local_path)}resolvePath(asset){if(asset.entity_type==="advisor"){if(!asset.advisor_slug){throw new Error(`advisor_slug required for entity_type=advisor (${asset.storage_path})`)}const advisorId=this.mappings.getId("advisor",asset.advisor_slug);if(!advisorId){throw new Error(`cannot resolve advisor_id for slug "${asset.advisor_slug}" \u2014 seed dev-users first`)}return`${this.options.orgId}/advisors/${advisorId}/${asset.storage_path}`}if(asset.entity_type==="org"||asset.entity_type==="advisor_org"){return`${this.options.orgId}/${asset.storage_path}`}return asset.storage_path}mimeType(filePath){return MIME_TYPES[extname(filePath).toLowerCase()]??"application/octet-stream"}validateAll(){const errors=[];const warnings=[];if(this.files().length===0){return{layer:this.def.name,filesChecked:0,errors,warnings}}let assets=[];try{const parsed=this.assets();assets=parsed.assets;for(const message of parsed.errors)errors.push({file:"manifest.json",message})}catch(error){errors.push({file:"manifest.json",message:error instanceof Error?error.message:String(error)});return{layer:this.def.name,filesChecked:1,errors,warnings}}const destinations=new Map;for(const asset of assets){const local=this.localFile(asset);if(!existsSync9(local)){errors.push({file:"manifest.json",message:`file not found: ${asset.local_path}`});continue}if(statSync(local).size===0){warnings.push({file:"manifest.json",message:`empty file: ${asset.local_path}`})}const destination=`${asset.bucket}:${asset.storage_path}`;const previous=destinations.get(destination);if(previous){errors.push({file:"manifest.json",message:`${destination} is written by both "${previous}" and "${asset.local_path}"`})}else{destinations.set(destination,asset.local_path)}}return{layer:this.def.name,filesChecked:1,errors,warnings}}async syncAll(){const started=Date.now();const entities=[];const errors=[];if(this.files().length===0){return{layer:this.def.name,created:0,updated:0,skipped:0,entities,errors,duration_ms:Date.now()-started}}let assets;try{const parsed=this.assets();assets=parsed.assets;for(const message of parsed.errors)errors.push({entity:"manifest.json",error:message})}catch(error){return{layer:this.def.name,created:0,updated:0,skipped:0,entities,errors:[{entity:"manifest.json",error:error instanceof Error?error.message:String(error)}],duration_ms:Date.now()-started}}const existing=await this.listBucketObjects(assets);for(const asset of assets){const key=`${asset.bucket}:${asset.storage_path}`;try{const local=this.localFile(asset);if(!existsSync9(local)){errors.push({entity:key,error:`file not found: ${asset.local_path}`});continue}const storagePath=this.resolvePath(asset);const alreadyThere=existing.has(`${asset.bucket}:${storagePath}`);if(this.options.dryRun){entities.push({entity:key,action:alreadyThere?"updated":"created",id:storagePath});continue}const{error}=await this.options.supabase.storage.from(asset.bucket).upload(storagePath,readFileSync7(local),{contentType:this.mimeType(local),upsert:true,cacheControl:"3600"});if(error){errors.push({entity:key,error:error.message});continue}this.mappings.set("storage_asset",key,storagePath);entities.push({entity:key,action:alreadyThere?"updated":"created",id:storagePath})}catch(error){errors.push({entity:key,error:error instanceof Error?error.message:String(error)})}}return{layer:this.def.name,created:entities.filter(e=>e.action==="created").length,updated:entities.filter(e=>e.action==="updated").length,skipped:entities.filter(e=>e.action==="skipped").length,entities,errors,duration_ms:Date.now()-started}}async listBucketObjects(assets){const folders=new Set;for(const asset of assets){let resolved;try{resolved=this.resolvePath(asset)}catch{continue}const slash=resolved.lastIndexOf("/");folders.add(`${asset.bucket}:${slash===-1?"":resolved.slice(0,slash)}`)}const found=new Set;for(const folder of folders){const separator=folder.indexOf(":");const bucket=folder.slice(0,separator);const prefix=folder.slice(separator+1);const{data,error}=await this.options.supabase.storage.from(bucket).list(prefix,{limit:1e3});if(error)continue;for(const entry of data??[]){if(entry.name)found.add(`${bucket}:${prefix?`${prefix}/${entry.name}`:entry.name}`)}}return found}async fetchDbKeys(){if(this.files().length===0)return new Map;const{assets}=this.assets();const existing=await this.listBucketObjects(assets);const out=new Map;for(const entry of existing)out.set(entry,entry);return out}async status(){const base={layer:this.def.name,kind:this.def.kind,implemented:this.def.implemented,files:0,dbRows:null,mappedIds:this.mappingEntities().reduce((sum,e)=>sum+this.mappings.count(e),0),missingInDb:[],missingInFiles:[],unmappedInDb:[]};if(this.files().length===0)return base;try{const{assets}=this.assets();base.files=assets.length;const declared=new Map;for(const asset of assets)declared.set(`${asset.bucket}:${this.resolvePath(asset)}`,asset.storage_path);const present=await this.listBucketObjects(assets);base.dbRows=[...declared.keys()].filter(d=>present.has(d)).length;base.missingInDb=[...declared.entries()].filter(([full])=>!present.has(full)).map(([,short])=>short).sort();base.missingInFiles=[...present].filter(p=>!declared.has(p)).sort()}catch(error){base.error=error instanceof Error?error.message:String(error)}return base}async healthChecks(){if(this.files().length===0)return[];const{assets}=this.assets();const declared=new Set;for(const asset of assets){try{declared.add(`${asset.bucket}:${this.resolvePath(asset)}`)}catch{}}const present=await this.listBucketObjects(assets);const missing=[...declared].filter(d=>!present.has(d)).sort();const extra=[...present].filter(p=>!declared.has(p)).sort();const checks=[missing.length===0?{name:"storage-declared",severity:"ok",message:`all ${declared.size} declared asset(s) present in the bucket`}:{name:"storage-declared",severity:"warn",message:`${missing.length} declared asset(s) not in the bucket \u2014 run sync`,detail:missing}];if(extra.length>0){checks.push({name:"storage-unmanaged",severity:"warn",message:`${extra.length} object(s) in the manifest's folders are declared by no asset. Uploaded out of band, or left from an uploader that used different filenames. This layer never deletes.`,detail:extra})}return checks}};var LAYER_ORDER=["org","org-template-layout","org-template-public","event-types","data-types","feed-producers","agent-templates","form-templates","project-templates","page-templates","storage","dev-users","projects","dev-workbooks","dev-client-data"];var LAYERS={org:{name:"org",kind:"data",table:"organization + org_template",naturalKey:"metadata->>org_slug; org_template (org_id, is_archived=false)",mappingEntity:"org",sourceDir:"config",envs:["local","develop","prod"],implemented:true,notes:"Owns identity columns only: org_id, advisor_org_id, is_published/is_archived, metadata.org_slug. name/description are written on INSERT only \u2014 the layout sync owns them after that."},"org-template-layout":{name:"org-template-layout",kind:"data",table:"org_template.*_layout",naturalKey:"metadata->>org_slug (read-modify-write)",mappingEntity:"org_template",sourceDir:null,envs:["local","develop","prod"],implemented:true,notes:"Source stays in src/org_templates/<slug>/template.json (D-T3); config/templates.json names which slug and which bundle lineage. Owns the *_layout columns PRESENT in the file \u2014 an absent one is left untouched. Never creates the row; `sync --layer org` does."},"org-template-public":{name:"org-template-public",kind:"data",table:"org_template_public",naturalKey:"(advisor_org_id, domain_pattern)",mappingEntity:"org_template_public",sourceDir:null,envs:["local","develop","prod"],implemented:true,notes:"Advisor orgs only \u2014 the anonymous hostname\u2192layout lookup. Reads config/public.json for domains/branding and takes public_layout from src/org_templates/<slug>/template.json, so the layout is single-sourced rather than duplicated as the host did."},"event-types":{name:"event-types",kind:"data",table:"event_type",naturalKey:"(org_id, name) \u2014 NOT unique-constrained in the DB",mappingEntity:"event_type",sourceDir:"data/shared/event-types",envs:["local","develop","prod"],implemented:true,notes:"SHARED data (its hashes ship with the engine): org-scoped rows, identical in every org. data/event-types/ holds org-specific additions and is not hashed. category/display_order are in the files but are not columns \u2014 deliberately not written."},"data-types":{name:"data-types",kind:"data",table:"client_data_type",naturalKey:"(org_id, name) \u2014 NOT unique-constrained in the DB",mappingEntity:"client_data_type",sourceDir:"data/data-types",envs:["local","develop","prod"],implemented:true},"feed-producers":{name:"feed-producers",kind:"data",table:"feed_producer",naturalKey:"(org_id, key) \u2014 UNIQUE",mappingEntity:"feed_producer",sourceDir:"data/feed-producers",envs:["local","develop","prod"],implemented:true},"agent-templates":{name:"agent-templates",kind:"data",table:"agent",naturalKey:"(org_id, name, is_template=true)",mappingEntity:"agent",sourceDir:"data/agent-templates",envs:["local","develop","prod"],implemented:true,notes:"Org-scoped rows only \u2014 core (org_id IS NULL) agents stay in BEA (D-T9)."},"form-templates":{name:"form-templates",kind:"data",table:"client_form_template",naturalKey:"(org_id, name) + nested page/section/field keys",mappingEntity:"form_template",sourceDir:"data/form-templates",envs:["local","develop","prod"],implemented:true,notes:"Writes 5 mapping entities (form_template/page/section/field + shared_field). data/shared-fields.json is synced first so `shared: true` fields reuse the canonical uuid."},"project-templates":{name:"project-templates",kind:"data",table:"project_template",naturalKey:"(org_id, name) (read-modify-write)",mappingEntity:"project_template",sourceDir:null,envs:["local","develop","prod"],implemented:true,notes:"Source stays in src/project_templates/<slug>/template.json (D-T3). Writes bundle_name, which the .mjs uploader never did, and resolves registry metadata against the is_live bundle."},"page-templates":{name:"page-templates",kind:"data",table:"project_page",naturalKey:"(org_id, page_type, is_template=true) \u2014 name only when page_type is null",mappingEntity:"project_page",sourceDir:null,envs:["local","develop","prod"],implemented:true,notes:"Every pages/*/page.json under each configured project template, in one run. Replaces scripts/upload-page-template.mjs, which upserted on a freshly generated id and so created a duplicate template row on every re-run."},storage:{name:"storage",kind:"data",table:"storage.objects",naturalKey:"bucket + resolved path (org_id prefix from slug, never hardcoded)",mappingEntity:"storage_asset",sourceDir:"data/storage",envs:["local","develop","prod"],implemented:true,notes:'ONE manifest replaces three disagreeing uploaders. Branding SVGs are single-homed in assets/branding/ via root:"repo" \u2014 never copied into template/data/.'},"dev-users":{name:"dev-users",kind:"seed",table:"auth.users + org_member + advisor/client",naturalKey:"email; (user_id, org_id); (advisor_id, org_id)",mappingEntity:"client",mappingEntities:["advisor"],sourceDir:"seed/dev-users",envs:["local","develop"],implemented:true,notes:"Advisors live in the OTA repo, client users here (D-T4). org_member and advisor have NO unique constraint on (user_id, org_id) \u2014 duplicates break role resolution, so doctor checks."},projects:{name:"projects",kind:"seed",table:"project + client_project",naturalKey:"(org_id, name)",mappingEntity:"project",sourceDir:"seed/projects",envs:["local","develop"],implemented:true,notes:"NEW content for block-plans, not a port \u2014 the legacy fixtures resolved template rows no file recreates (D-T10). The project_template row is owned by the project-templates layer."},"dev-workbooks":{name:"dev-workbooks",kind:"seed",table:"client_form + client_input",naturalKey:"(client_id, template_id); client_input (form_id, field_id)",mappingEntity:null,sourceDir:"seed/dev-workbooks",envs:["local","develop"],implemented:true,notes:"CHECK-THEN-INSERT ONLY \u2014 these rows carry member progress, so an existing workbook is never overwritten (the converger objection in HOST-025/026). Definitions belong to form-templates; this layer only records that a member started one. client_input is APPEND-ONLY with no unique constraint on (form_id, field_id), so existence is checked here, not by the database."},"dev-client-data":{name:"dev-client-data",kind:"seed",table:"client_data",naturalKey:"(client_id, data_type_id, name)",mappingEntity:null,sourceDir:"seed/dev-client-data",envs:["local","develop"],implemented:true,notes:`CHECK-THEN-INSERT ONLY \u2014 client_data is append-only artefact history (the host inserts a new "Client Profile" row per save rather than updating), so a converger here would either revert a member's current profile or delete the history it versions. client_data_type rows belong to the data-types layer and are resolved by exact name, never created.`}};var FACTORIES={org:(options,mappings)=>new OrgManager(LAYERS.org,options,mappings),"org-template-layout":(options,mappings)=>new OrgTemplateLayoutManager(LAYERS["org-template-layout"],options,mappings),"project-templates":(options,mappings)=>new ProjectTemplateManager(LAYERS["project-templates"],options,mappings),"page-templates":(options,mappings)=>new PageTemplateManager(LAYERS["page-templates"],options,mappings),"org-template-public":(options,mappings)=>new OrgTemplatePublicManager(LAYERS["org-template-public"],options,mappings),"event-types":(options,mappings)=>new EventTypeManager(LAYERS["event-types"],options,mappings),"data-types":(options,mappings)=>new DataTypeManager(LAYERS["data-types"],options,mappings),"feed-producers":(options,mappings)=>new FeedProducerManager(LAYERS["feed-producers"],options,mappings),"agent-templates":(options,mappings)=>new AgentTemplateManager(LAYERS["agent-templates"],options,mappings),"form-templates":(options,mappings)=>new FormTemplateManager(LAYERS["form-templates"],options,mappings),storage:(options,mappings)=>new StorageAssetManager(LAYERS.storage,options,mappings),"dev-users":(options,mappings)=>new DevUserManager(LAYERS["dev-users"],options,mappings),projects:(options,mappings)=>new ProjectManager(LAYERS.projects,options,mappings),"dev-workbooks":(options,mappings)=>new DevWorkbookManager(LAYERS["dev-workbooks"],options,mappings),"dev-client-data":(options,mappings)=>new DevClientDataManager(LAYERS["dev-client-data"],options,mappings)};function isLayerName(value){return value in LAYERS}function assertLayerName(value){if(!isLayerName(value)){throw new Error(`unknown layer "${value}". Known layers: ${LAYER_ORDER.join(", ")}. Run \`npm run template -- list\` to see which are ported.`)}return value}function createManager(layer,options,mappings){const factory=FACTORIES[layer];return factory?factory(options,mappings):null}function resolveLayers(owned,options){const ordered=LAYER_ORDER.filter(l=>owned.includes(l));const selected=options.layer?ordered.filter(l=>l===options.layer):ordered;return selected.filter(l=>LAYERS[l].envs.includes(options.targetEnv))}import{existsSync as existsSync10,mkdirSync,readFileSync as readFileSync8,renameSync,writeFileSync}from"node:fs";import{join as join9}from"node:path";var MAPPING_ENTITIES=["org","org_template","org_template_public","client_data_type","event_type","feed_producer","agent","form_template","form_page","form_section","form_field","shared_field","project_template","project_page","project","client","client_form","advisor","storage_asset","process","system","skill"];var ENTITY_SET=new Set(MAPPING_ENTITIES);function isMappingEntity(value){return ENTITY_SET.has(value)}function assertMappingEntity(value){if(!isMappingEntity(value)){throw new Error(`"${value}" is not a canonical mapping entity. Add it to MAPPING_ENTITIES in template/lib/entities.ts rather than inventing a spelling \u2014 two spellings of one entity means two mapping files, and the second one starts empty.`)}return value}function mappingFileName(entity,targetEnv){return`${entity}.mapping.${targetEnv}.json`}var META_KEYS=new Set(["_comment","_generated"]);var MappingStore=class{constructor(mappingsDir,targetEnv,now=()=>new Date().toISOString()){this.mappingsDir=mappingsDir;this.targetEnv=targetEnv;this.now=now}mappingsDir;targetEnv;now;cache=new Map;dirty=new Set;load(entity){const cached=this.cache.get(entity);if(cached)return cached;const path=join9(this.mappingsDir,mappingFileName(entity,this.targetEnv));const data={};if(existsSync10(path)){try{const parsed=JSON.parse(readFileSync8(path,"utf8"));for(const[key,value]of Object.entries(parsed)){if(!META_KEYS.has(key))data[key]=value}}catch(error){throw new Error(`mapping file ${path} is not valid JSON \u2014 fix or delete it before seeding. (${error instanceof Error?error.message:String(error)})`)}}this.cache.set(entity,data);return data}get(entityName,naturalKey){const entity=assertMappingEntity(entityName);return this.load(entity)[naturalKey]}getId(entityName,naturalKey){const value=this.get(entityName,naturalKey);return typeof value==="string"?value:void 0}set(entityName,naturalKey,value){const entity=assertMappingEntity(entityName);if(value===void 0||value===null){throw new Error(`refusing to map ${entity}."${naturalKey}" to ${String(value)}`)}const mapping=this.load(entity);if(mapping[naturalKey]===value)return;mapping[naturalKey]=value;this.dirty.add(entity)}keys(entityName){const entity=assertMappingEntity(entityName);return Object.keys(this.load(entity)).sort()}count(entityName){return this.keys(entityName).length}hasChanges(){return this.dirty.size>0}changedEntities(){return[...this.dirty].sort()}flushedEntities(){return[...this.lastFlushed].sort()}lastFlushed=[];flush(){this.lastFlushed=[...this.dirty].sort();if(this.dirty.size===0)return[];if(!existsSync10(this.mappingsDir))mkdirSync(this.mappingsDir,{recursive:true});const written=[];for(const entity of this.dirty){const mapping=this.cache.get(entity)??{};const ordered={};for(const key of Object.keys(mapping).sort())ordered[key]=mapping[key];const body={_comment:"Auto-generated by template/cli (seed | sync | pull). Commit this file.",_generated:this.now(),...ordered};const path=join9(this.mappingsDir,mappingFileName(entity,this.targetEnv));const temp=`${path}.tmp`;writeFileSync(temp,`${JSON.stringify(body,null,2)}
13
+ `,"utf8");renameSync(temp,path);written.push(path)}this.dirty.clear();return written}};function loadLayersConfig(){const path=join10(CONFIG_DIR,"layers.json");if(!existsSync11(path))return{layers:[...LAYER_ORDER],bundleRefFloor:1};const parsed=JSON.parse(readFileSync9(path,"utf8"));const result=validateShape(parsed,{fields:{layers:{type:"array",required:true},bundle_ref_floor:{type:"number",required:false}},ignored:["_comment"]});if(!result.ok||!result.value){throw new Error(`template/config/layers.json is invalid:
14
+ - ${result.errors.join("\n - ")}`)}return{layers:result.value.layers.map(l=>assertLayerName(String(l))),bundleRefFloor:result.value.bundle_ref_floor??1}}async function buildContext(args){const org=loadOrgConfig();const targetEnv=args.targetEnv;const{layers:ownedLayers,bundleRefFloor}=loadLayersConfig();const mappings=new MappingStore(MAPPINGS_DIR,targetEnv);let supabase=null;let orgId=null;if(args.offline){loadEnv(targetEnv,REPO_ROOT)}else{supabase=createSupabaseClient(targetEnv,REPO_ROOT);const resolved=await findOrgBySlug(supabase,org.slug);orgId=resolved?.id??mappings.getId("org",org.slug)??null}return{args,org,targetEnv,repoRoot:REPO_ROOT,supabase,get orgId(){return orgId},mappings,ownedLayers,bundleRefFloor,async refreshOrgId(){if(!supabase)return null;const resolved=await findOrgBySlug(supabase,org.slug);orgId=resolved?.id??mappings.getId("org",org.slug)??null;return orgId},managerOptions(request={}){if(!supabase)throw new Error("this command needs a database connection (remove --offline)");if(!orgId&&!request.allowMissingOrg){throw new Error(`organization "${org.slug}" does not exist in ${targetEnv}. Run \`npm run template -- seed --env ${targetEnv} --layer org\` to create it, or check that this is the environment you meant.`)}return{supabase,orgSlug:org.slug,orgId:orgId??"",targetEnv,repoRoot:REPO_ROOT,dryRun:args.dryRun,nameFilter:args.name,versionPin:args.version,replaceExisting:args.flags.has("replace-existing")}}}}import{createHash}from"node:crypto";import{existsSync as existsSync12,readdirSync as readdirSync3,readFileSync as readFileSync10,statSync as statSync2}from"node:fs";import{join as join11,relative as relative4}from"node:path";var shared_data_default={files:{"data/shared/event-types/call.json":"a2dd46dd409a7d93767268f2bf9bcdd634fb45a75637bde3b64de97dbfbe3569","data/shared/event-types/form.json":"92888cb545ca5fedc741af3f41cbbc6db58ee2c375af4a6ae77eba8f9b9938cb","data/shared/event-types/meeting.json":"554f134769fe2a6f4bf3fea722a529aa104634943247f880607bf62918b73e29","data/shared/event-types/message.json":"8e82033549b30d9b368957227d1818fd3f46cbd0021fab30954cca750e6f66a7","data/shared/event-types/note.json":"e88d74e853155d5528274a7b4110799876dff6f604e5aeb94e22356ecf3b6ecd","data/shared/event-types/process.json":"a086ad1c894cacbb698c78d297f7c2ed6a4c5bdc10301b0cbd06aa8bb87abc37","data/shared/event-types/task.json":"bf9b1cc8d3a4648e9ad276e0db080fd7044323560158291cf599d1e812d9ce52"}};var SHARED_DATA_DIR=join11("data","shared");function walkFiles(dir,keep){if(!existsSync12(dir))return[];const out=[];for(const name of readdirSync3(dir)){const full=join11(dir,name);if(statSync2(full).isDirectory())out.push(...walkFiles(full,keep));else if(keep(name))out.push(relative4(TEMPLATE_ROOT,full).split("\\").join("/"))}return out.sort()}function listSharedDataFiles(){return walkFiles(join11(TEMPLATE_ROOT,SHARED_DATA_DIR),n=>n.endsWith(".json"))}function computeSharedDataHashes(){const out={};for(const f of listSharedDataFiles())out[f]=createHash("sha256").update(readFileSync10(join11(TEMPLATE_ROOT,f))).digest("hex");return out}function sharedDataDriftCheck(){const expected=shared_data_default.files;const actual=computeSharedDataHashes();const problems=[...Object.keys(expected).filter(f=>actual[f]&&actual[f]!==expected[f]).map(f=>`changed: ${f}`),...Object.keys(expected).filter(f=>!actual[f]).map(f=>`missing: ${f}`),...Object.keys(actual).filter(f=>!expected[f]).map(f=>`not in the engine's shared data: ${f}`)];if(problems.length===0){return{name:"shared-data-drift",severity:"ok",message:`all ${Object.keys(actual).length} shared data file(s) match the engine's`}}return{name:"shared-data-drift",severity:"fail",message:`${problems.length} file(s) under template/${SHARED_DATA_DIR} differ from the engine's shared data. Every org seeds the same definitions, so they must be identical; change them in the engine, then here.`,detail:problems}}import{existsSync as existsSync13,readdirSync as readdirSync4,readFileSync as readFileSync11}from"node:fs";import{join as join12}from"node:path";function packageBundleName(){const path=join12(REPO_ROOT,"package.json");if(!existsSync13(path))return null;try{const parsed=JSON.parse(readFileSync11(path,"utf8"));const raw=parsed.oaBundle;const value=typeof raw==="string"?raw:raw?.name;return value?{where:"package.json oaBundle",value}:null}catch{return null}}function configFiles(){const out=[];for(const entry of readdirSync4(REPO_ROOT)){if(/^vite\.config.*\.ts$/.test(entry))out.push(join12(REPO_ROOT,entry))}const harnessDir=join12(REPO_ROOT,"test","visual");if(existsSync13(harnessDir)){for(const entry of readdirSync4(harnessDir)){if(/\.config\.ts$/.test(entry))out.push(join12(harnessDir,entry))}}return out.sort()}function inlinedNamespaces(){const pattern=/__OA_BUNDLE_NAME__\s*:\s*JSON\.stringify\(\s*['"]([^'"]+)['"]\s*\)/g;const out=[];for(const file of configFiles()){let text;try{text=readFileSync11(file,"utf8")}catch{continue}for(const match of text.matchAll(pattern)){out.push({where:file.slice(REPO_ROOT.length+1),value:match[1]})}}return out}function identityChecks(targetEnv){const org=loadOrgConfig();const checks=[];const sources=[packageBundleName(),...inlinedNamespaces()].filter(s=>s!==null);const distinct=[...new Set(sources.map(s=>s.value))];if(sources.length===0){checks.push({name:"identity-bundle-name",severity:"warn",message:'no bundle namespace found in package.json or any vite config \u2014 the theme namespace falls back to "oa-bundle"'})}else if(distinct.length>1){checks.push({name:"identity-bundle-name",severity:"fail",message:`this repo builds ${distinct.length} different [data-oa-bundle] namespaces \u2014 every bundle an org ships must use the same one, or a page mixing them loses styling on all but one`,detail:sources.map(s=>`${s.where}: "${s.value}"`)})}else if(distinct[0]!==org.slug){checks.push({name:"identity-bundle-name",severity:"warn",message:`the bundle namespace is "${distinct[0]}" but this org is "${org.slug}" (${sources.map(s=>s.where).join(", ")}). It only has to be constant across this org's lineages, but matching the slug is how you get that for free. Changing it requires rebuilding and redeploying every lineage together.`})}else{checks.push({name:"identity-bundle-name",severity:"ok",message:`bundle namespace "${distinct[0]}" matches the org slug, consistent across ${sources.length} source(s)`})}const envSlug=process.env.ORG_SLUG??null;const viteSlug=process.env.VITE_ORG_SLUG??null;const mismatched=[...envSlug&&envSlug!==org.slug?[`ORG_SLUG=${envSlug}`]:[],...viteSlug&&viteSlug!==org.slug?[`VITE_ORG_SLUG=${viteSlug}`]:[]];if(mismatched.length>0){checks.push({name:"identity-env-slug",severity:"fail",message:`.env.${targetEnv} names a different org than config/org.json ("${org.slug}"): ${mismatched.join(", ")}. scripts/*.mjs deploy into ORG_SLUG, so bundles and registry rows would land on that org while this CLI configures "${org.slug}".`})}else if(!envSlug){checks.push({name:"identity-env-slug",severity:"warn",message:`.env.${targetEnv} sets no ORG_SLUG, so every deploy script needs --org typed by hand \u2014 which is exactly how a wrong slug gets in. Add ORG_SLUG=${org.slug}.`})}else{checks.push({name:"identity-env-slug",severity:"ok",message:`.env.${targetEnv} ORG_SLUG = "${envSlug}"`})}return checks}function renderSeedReport(report){const lines=[];const mode=report.dryRun?" (dry run \u2014 nothing written)":"";lines.push("");lines.push(`${report.command}: ${report.orgSlug} \u2192 ${report.targetEnv}${mode}`);if(report.orgId)lines.push(` org_id: ${report.orgId}`);lines.push("");for(const layer of report.layers){const counts=`created ${layer.created}, updated ${layer.updated}, skipped ${layer.skipped}`;const status=layer.errors.length>0?"FAILED":"ok";lines.push(` ${layer.layer.padEnd(22)} ${status.padEnd(7)} ${counts} (${layer.duration_ms}ms)`);for(const error of layer.errors){lines.push(` \u2717 ${error.entity}: ${error.error}`)}}const totalErrors=report.layers.reduce((sum,l)=>sum+l.errors.length,0);lines.push("");lines.push(report.success?` \u2713 ${report.layers.length} layer(s) in ${report.totalDuration_ms}ms`:` \u2717 ${totalErrors} error(s) across ${report.layers.length} layer(s)`);lines.push("");return lines.join("\n")}function renderStatus(statuses,header){const lines=["",header,""];lines.push(` ${"layer".padEnd(22)} ${"kind".padEnd(5)} ${"files".padStart(5)} ${"db".padStart(5)} ${"mapped".padStart(6)} state`);for(const s of statuses){const db=s.dbRows===null?"\u2014":String(s.dbRows);const notes=[];if(!s.implemented)notes.push("not ported (host-owned)");if(s.error)notes.push(`ERROR: ${s.error}`);if(s.missingInDb.length)notes.push(`${s.missingInDb.length} file(s) not in DB`);if(s.missingInFiles.length)notes.push(`${s.missingInFiles.length} DB row(s) without a file`);if(s.unmappedInDb.length)notes.push(`${s.unmappedInDb.length} unmapped`);if(!notes.length)notes.push("in sync");lines.push(` ${s.layer.padEnd(22)} ${s.kind.padEnd(5)} ${String(s.files).padStart(5)} ${db.padStart(5)} ${String(s.mappedIds).padStart(6)} ${notes.join("; ")}`)}const detail=statuses.filter(s=>s.missingInDb.length||s.missingInFiles.length||s.unmappedInDb.length);if(detail.length){lines.push("");lines.push(" drift detail");for(const s of detail){if(s.missingInDb.length)lines.push(` ${s.layer} \u2014 in files, not in DB: ${s.missingInDb.join(", ")}`);if(s.missingInFiles.length)lines.push(` ${s.layer} \u2014 in DB, no file: ${s.missingInFiles.join(", ")}`);if(s.unmappedInDb.length)lines.push(` ${s.layer} \u2014 unmapped: ${s.unmappedInDb.join(", ")}`)}}lines.push("");return lines.join("\n")}function renderValidation(results){const lines=[""];let errors=0;for(const result of results){const count=result.errors.length;errors+=count;const state=count===0?"ok":`${count} error(s)`;lines.push(` ${result.layer.padEnd(22)} ${String(result.filesChecked).padStart(3)} file(s) ${state}`);for(const issue of result.errors)lines.push(` \u2717 ${issue.file}: ${issue.message}`);for(const issue of result.warnings)lines.push(` \u26A0 ${issue.file}: ${issue.message}`)}lines.push("");lines.push(errors===0?" \u2713 all files valid":` \u2717 ${errors} error(s)`);lines.push("");return lines.join("\n")}function emit(json,payload,human){console.log(json?JSON.stringify(payload,null,2):human)}async function checkAdvisorLinkage(ctx,supabase){const org=await findOrgBySlug(supabase,ctx.org.slug);if(!org){return{name:"advisor-linkage",severity:"fail",message:`organization "${ctx.org.slug}" not found in ${ctx.targetEnv}`}}if(ctx.org.advisor){return org.advisor?{name:"advisor-linkage",severity:"ok",message:"advisor org, flag set correctly"}:{name:"advisor-linkage",severity:"fail",message:"config says advisor org but organization.advisor is false"}}const expected=ctx.org.advisor_org_slug;if(!expected){return{name:"advisor-linkage",severity:"ok",message:"client org with no advisor configured"}}const advisorOrg=await findOrgBySlug(supabase,expected);if(!advisorOrg){return{name:"advisor-linkage",severity:"warn",message:`advisor org "${expected}" does not exist in ${ctx.targetEnv} yet \u2014 seed it first`}}if(org.advisorOrgId!==advisorOrg.id){return{name:"advisor-linkage",severity:"fail",message:`organization.metadata.advisor_org_id is ${org.advisorOrgId??"null"} but "${expected}" is ${advisorOrg.id} \u2014 advisor-scoped lookups will return nothing`}}return{name:"advisor-linkage",severity:"ok",message:`linked to ${expected} (${advisorOrg.id})`}}async function checkDuplicateDataTypes(ctx,supabase){const{data,error}=await supabase.from("client_data_type").select("id, name").eq("org_id",ctx.orgId);if(error){return{name:"duplicate-rows",severity:"warn",message:`lookup failed: ${error.message}`}}const byName=new Map;for(const row of data??[]){byName.set(row.name,[...byName.get(row.name)??[],row.id])}const dupes=[...byName.entries()].filter(([,ids])=>ids.length>1);return dupes.length===0?{name:"duplicate-rows",severity:"ok",message:`client_data_type: ${byName.size} distinct name(s), no duplicates`}:{name:"duplicate-rows",severity:"fail",message:`client_data_type has ${dupes.length} duplicated name(s) \u2014 sync will refuse to write them`,detail:dupes.map(([name,ids])=>`${name}: ${ids.join(", ")}`)}}async function checkDuplicateMemberships(ctx,supabase){const detail=[];const{data:members,error:memberError}=await supabase.from("org_member").select("id, user_id").eq("org_id",ctx.orgId);if(memberError){return{name:"duplicate-memberships",severity:"warn",message:`org_member lookup failed: ${memberError.message}`}}const memberCounts=new Map;for(const row of members??[]){memberCounts.set(row.user_id,(memberCounts.get(row.user_id)??0)+1)}for(const[userId,count]of memberCounts){if(count>1)detail.push(`org_member: user ${userId} has ${count} rows`)}const{data:advisors,error:advisorError}=await supabase.from("advisor").select("id, user_id").eq("org_id",ctx.orgId);if(!advisorError){const advisorCounts=new Map;for(const row of advisors??[]){advisorCounts.set(row.user_id,(advisorCounts.get(row.user_id)??0)+1)}for(const[userId,count]of advisorCounts){if(count>1)detail.push(`advisor: user ${userId} has ${count} rows`)}}return detail.length===0?{name:"duplicate-memberships",severity:"ok",message:`${memberCounts.size} org member(s), no duplicate rows`}:{name:"duplicate-memberships",severity:"fail",message:"duplicate membership rows \u2014 role resolution uses .maybeSingle() and will throw, hanging login on a portal\u2192platform redirect loop",detail}}async function checkLiveBundle(ctx,supabase){const{data:bundles,error:bundleError}=await supabase.from("component_bundle").select("id, version, bundle_name, is_live, status").eq("org_id",ctx.orgId).eq("bundle_name",ctx.org.bundle_name).eq("is_live",true);if(bundleError){return{name:"live-bundle",severity:"warn",message:`lookup failed: ${bundleError.message}`}}const live=bundles??[];if(live.length===0){return{name:"live-bundle",severity:"warn",message:`no is_live bundle in lineage "${ctx.org.bundle_name}" \u2014 the host has nothing to serve`}}if(live.length>1){return{name:"live-bundle",severity:"fail",message:`${live.length} bundles are is_live in lineage "${ctx.org.bundle_name}" \u2014 exactly one may be`,detail:live.map(b=>b.version)}}const liveVersion=live[0].version;const{data:templates,error:templateError}=await supabase.from("org_template").select("id, remote_version").eq("metadata->>org_slug",ctx.org.slug);if(templateError){return{name:"live-bundle",severity:"warn",message:`is_live=${liveVersion}; org_template lookup failed: ${templateError.message}`}}const rows=templates??[];const pointer=rows[0]?.remote_version??null;if(pointer&&pointer!==liveVersion){return{name:"live-bundle",severity:"warn",message:`org_template.remote_version=${pointer} but is_live=${liveVersion}. The host serves the is_live row. Reconcile from THIS repo:
15
+ npm run deploy:cutover -- --org <slug> --version ${liveVersion} --<env>`}}return{name:"live-bundle",severity:"ok",message:`is_live=${liveVersion}, pointer agrees`}}var LOCAL_CHECKS=new Set(["shared-data-drift","identity-bundle-name","identity-env-slug"]);async function runDoctor(ctx){const filter=ctx.args.check;const localOnly=filter!==null&&LOCAL_CHECKS.has(filter);const checks=[sharedDataDriftCheck(),...identityChecks(ctx.targetEnv)];if(!localOnly){if(!ctx.supabase){throw new Error(`doctor needs a database connection (remove --offline), or pass --check ${[...LOCAL_CHECKS].join(" / --check ")} for the checks that run without one.`)}if(!ctx.orgId){throw new Error(`organization "${ctx.org.slug}" does not exist in ${ctx.targetEnv} \u2014 nothing to check.`)}const supabase=ctx.supabase;checks.push(await checkAdvisorLinkage(ctx,supabase),await checkDuplicateDataTypes(ctx,supabase),await checkDuplicateMemberships(ctx,supabase),await checkLiveBundle(ctx,supabase));const layers=resolveLayers(ctx.ownedLayers,{layer:null,targetEnv:ctx.targetEnv});const managerOptions=ctx.managerOptions();for(const layer of layers){const manager=createManager(layer,managerOptions,ctx.mappings);if(!manager)continue;try{checks.push(...await manager.healthChecks())}catch(error){checks.push({name:`${layer}-checks`,severity:"warn",message:error instanceof Error?error.message:String(error)})}}}const selected=filter?checks.filter(c=>c.name===filter):checks;if(selected.length===0){throw new Error(`--check "${filter}" matched no check. Ran: ${checks.map(c=>c.name).join(", ")}.`)}const failed=selected.filter(c=>c.severity==="fail");const warned=selected.filter(c=>c.severity==="warn");const scope=filter?` [--check ${filter}]`:"";const lines=["",localOnly?`doctor: ${ctx.org.slug}${scope}`:`doctor: ${ctx.org.slug} \u2192 ${ctx.targetEnv}${scope}`,""];for(const check of selected){const icon=check.severity==="ok"?"\u2713":check.severity==="warn"?"\u26A0":"\u2717";lines.push(` ${icon} ${check.name.padEnd(22)} ${check.message}`);for(const line of check.detail??[])lines.push(` ${line}`)}lines.push("");lines.push(failed.length===0?warned.length===0?" \u2713 all checks passed":` \u26A0 ${warned.length} warning(s), no failures`:` \u2717 ${failed.length} check(s) failed`);lines.push("");emit(ctx.args.json,{org:ctx.org.slug,target_env:ctx.targetEnv,check:filter,checks:selected},lines.join("\n"));return failed.length===0?0:1}function runList(ctx){const rows=LAYER_ORDER.map(layer=>{const def=LAYERS[layer];return{layer,kind:def.kind,owned:ctx.ownedLayers.includes(layer),ported:def.implemented,table:def.table,natural_key:def.naturalKey,mapping_entity:def.mappingEntity,source_dir:def.sourceDir?`template/${def.sourceDir}`:"(src/ \u2014 see notes)",envs:def.envs,notes:def.notes??null}});const lines=["",`layers for ${ctx.org.slug} (${ctx.org.advisor?"advisor org":"client org"}${ctx.org.advisor_org_slug?`, advisor: ${ctx.org.advisor_org_slug}`:""})`,"",` ${"layer".padEnd(22)} ${"kind".padEnd(5)} ${"ported".padEnd(7)} source`];for(const row of rows){if(!row.owned)continue;lines.push(` ${row.layer.padEnd(22)} ${row.kind.padEnd(5)} ${(row.ported?"yes":"no").padEnd(7)} ${row.source_dir}`);if(!row.ported&&row.notes)lines.push(` ${row.notes}`)}const unowned=rows.filter(r=>!r.owned);if(unowned.length){lines.push("");lines.push(` not owned by this org: ${unowned.map(r=>r.layer).join(", ")}`)}lines.push("");emit(ctx.args.json,{org:ctx.org.slug,layers:rows},lines.join("\n"));return 0}async function runPrune(ctx){const confirmed=ctx.args.flags.has("confirm-prune");const layers=resolveLayers(ctx.ownedLayers,{layer:ctx.args.layer?assertLayerName(ctx.args.layer):null,targetEnv:ctx.targetEnv});const managerOptions=ctx.managerOptions();const found=[];const deleted=[];const errors=[];for(const layer of layers){const manager=createManager(layer,managerOptions,ctx.mappings);if(!manager)continue;for(const orphan of await manager.orphans()){found.push({...orphan,layer})}}if(confirmed&&!ctx.args.dryRun){const order=["client_input_field","client_form_section","client_form_page"];const sorted=[...found].sort((a,b)=>order.indexOf(a.table)-order.indexOf(b.table));for(const orphan of sorted){const{error}=await ctx.supabase.from(orphan.table).delete().eq("id",orphan.id);if(error){errors.push({label:orphan.label,error:error.message})}else{deleted.push(orphan)}}}const byTable=new Map;for(const orphan of found)byTable.set(orphan.table,(byTable.get(orphan.table)??0)+1);const lines=["",`prune: ${ctx.org.slug} \u2192 ${ctx.targetEnv}`+(confirmed&&!ctx.args.dryRun?"":" (preview \u2014 nothing deleted)"),""];if(found.length===0){lines.push(" \u2713 no orphaned rows")}else{for(const[table,count]of byTable)lines.push(` ${table.padEnd(24)} ${count} orphan(s)`);lines.push("");for(const orphan of found){const mark=deleted.includes(orphan)?"deleted":"would delete";lines.push(` ${mark.padEnd(13)} ${orphan.table.padEnd(22)} ${orphan.label}`)}if(!confirmed){lines.push("");lines.push(" Pass --confirm-prune to delete these rows.")}}for(const failure of errors)lines.push(` \u2717 ${failure.label}: ${failure.error}`);lines.push("");emit(ctx.args.json,{org:ctx.org.slug,target_env:ctx.targetEnv,confirmed:confirmed&&!ctx.args.dryRun,found,deleted,errors},lines.join("\n"));return errors.length===0?0:1}var OrgSeeder=class{constructor(ctx){this.ctx=ctx}ctx;async run(options){const started=Date.now();const layers=resolveLayers(this.ctx.ownedLayers,{layer:options.layer??null,targetEnv:this.ctx.targetEnv});if(options.layer&&layers.length===0){const def=LAYERS[options.layer];throw new Error(`layer "${options.layer}" is not available for ${this.ctx.targetEnv}`+(def.envs.includes(this.ctx.targetEnv)?" \u2014 it is not listed in template/config/layers.json":` \u2014 it only runs in: ${def.envs.join(", ")}`))}const results=[];for(const layer of layers){const bootstrapping=layer==="org"&&this.ctx.orgId===null;const manager=createManager(layer,this.ctx.managerOptions({allowMissingOrg:bootstrapping}),this.ctx.mappings);if(!manager){results.push({layer,created:0,updated:0,skipped:1,entities:[{entity:layer,action:"skipped",id:null,reason:LAYERS[layer].notes??"not ported yet \u2014 still seeded by the host base-template"}],errors:[],duration_ms:0});continue}const result=options.operation==="pull"?await manager.pull():await manager.syncAll();results.push(result);if(layer==="org"&&result.errors.length===0){await this.ctx.refreshOrgId()}if(layer==="org"&&this.ctx.orgId===null){const remaining=layers.slice(layers.indexOf(layer)+1);for(const skipped of remaining){results.push({layer:skipped,created:0,updated:0,skipped:1,entities:[{entity:skipped,action:"skipped",id:null,reason:this.ctx.args.dryRun?"dry run: the org row was not actually created, so nothing downstream can resolve against it. Re-run without --dry-run.":"the org layer did not produce an organization id \u2014 fix that error first; everything here depends on it."}],errors:[],duration_ms:0})}break}}if(!this.ctx.args.dryRun)this.ctx.mappings.flush();return{orgSlug:this.ctx.org.slug,orgId:this.ctx.orgId,targetEnv:this.ctx.targetEnv,dryRun:this.ctx.args.dryRun,command:options.command,layers:results,totalDuration_ms:Date.now()-started,success:results.every(r=>r.errors.length===0)}}};async function runPull(ctx){const layer=ctx.args.layer?assertLayerName(ctx.args.layer):null;const report=await new OrgSeeder(ctx).run({command:"pull",operation:"pull",layer});const written=ctx.args.dryRun?ctx.mappings.changedEntities():ctx.mappings.flushedEntities();const human=renderSeedReport(report)+(ctx.args.dryRun?" (dry run \u2014 no mapping files written)\n":written.length?` mapping files updated: ${written.join(", ")}
16
+ `:" mapping files already up to date\n");emit(ctx.args.json,{...report,mappings_written:written},human);return report.success?0:1}async function runSeed(ctx){const report=await new OrgSeeder(ctx).run({command:"seed",operation:"sync"});emit(ctx.args.json,report,renderSeedReport(report));return report.success?0:1}async function runStatus(ctx){const layers=resolveLayers(ctx.ownedLayers,{layer:ctx.args.layer?ctx.args.layer:null,targetEnv:ctx.targetEnv});const statuses=[];let managerOptions=null;let contextError=null;try{managerOptions=ctx.managerOptions()}catch(error){contextError=error instanceof Error?error.message:String(error)}for(const layer of layers){const def=LAYERS[layer];const manager=managerOptions?createManager(layer,managerOptions,ctx.mappings):null;if(!manager){statuses.push({layer,kind:def.kind,implemented:def.implemented,files:0,dbRows:null,mappedIds:def.mappingEntity?ctx.mappings.count(def.mappingEntity):0,missingInDb:[],missingInFiles:[],unmappedInDb:[],...contextError&&def.implemented?{error:contextError}:{}});continue}statuses.push(await manager.status())}const payload={org:ctx.org.slug,org_id:ctx.orgId,target_env:ctx.targetEnv,advisor_org_slug:ctx.org.advisor_org_slug??null,context_error:contextError,layers:statuses};const header=`status: ${ctx.org.slug} \u2192 ${ctx.targetEnv}`+(ctx.orgId?` (org_id ${ctx.orgId})`:" (org row NOT FOUND)");emit(ctx.args.json,payload,renderStatus(statuses,header));return contextError&&statuses.some(s=>s.implemented)?1:0}async function runSync(ctx){if(!ctx.args.layer){throw new Error("sync needs --layer <name>. Use `seed` to run every layer, or `list` to see the layers.")}const layer=assertLayerName(ctx.args.layer);const report=await new OrgSeeder(ctx).run({command:"sync",operation:"sync",layer});emit(ctx.args.json,report,renderSeedReport(report));return report.success?0:1}function offlineManagerOptions(ctx){return{supabase:null,orgSlug:ctx.org.slug,orgId:"(offline)",targetEnv:ctx.targetEnv,repoRoot:ctx.repoRoot,dryRun:true,nameFilter:ctx.args.name}}function runValidate(ctx){const layers=resolveLayers(ctx.ownedLayers,{layer:ctx.args.layer?ctx.args.layer:null,targetEnv:ctx.targetEnv});const options=offlineManagerOptions(ctx);const results=[];let bundleRefsVisited=0;for(const layer of layers){const manager=createManager(layer,options,ctx.mappings);if(!manager){results.push({layer,filesChecked:0,errors:[],warnings:[{file:"(layer)",message:LAYERS[layer].notes??"not ported yet \u2014 no files in this repo"}]});continue}results.push(manager.validateAll());bundleRefsVisited+=manager.bundleRefsVisited}const floorLayer=layers[0];if(!ctx.args.layer&&floorLayer&&bundleRefsVisited<ctx.bundleRefFloor){results.push({layer:floorLayer,filesChecked:0,errors:[{file:"(repo)",message:"the bundle-ref walker visited zero refs across every layer \u2014 it is passing vacuously. Either every ref was deleted from this repo, or the walk in template/lib/bundle-refs.ts stopped matching the keys refs are stored under."}],warnings:[]})}const errorCount=results.reduce((sum,r)=>sum+r.errors.length,0);emit(ctx.args.json,{org:ctx.org.slug,layers:results,error_count:errorCount},renderValidation(results));return errorCount===0?0:1}var USAGE=`
17
+ org template CLI \u2014 seed and sync this org's configuration
18
+
19
+ status read-only: per-layer file / DB / mapping state and drift
20
+ validate schema-check the files (no database; works with --offline)
21
+ list layers, ports status, and where each one's files live
22
+ sync push ONE layer's files to the database (--layer required)
23
+ seed push every layer this org owns, in dependency order
24
+ pull record database ids into the mapping files
25
+ doctor invariant checks (duplicates, is_live pointer, mapping coverage)
26
+ prune delete rows no file declares (preview by default; --confirm-prune to apply)
27
+
28
+ Options
29
+ --env <local|develop|prod> target database (default: local)
30
+ --develop | --prod aliases for --env
31
+ --layer <name> restrict to one layer
32
+ --name <entity> restrict to one file/entity within a layer
33
+ --check <name> doctor: run one named check (shared-data-drift and identity-bundle-name need no DB)
34
+ --version <bundle-version> pin the bundle whose registry metadata is inlined
35
+ into templates (default: the is_live bundle)
36
+ --dry-run resolve and report, write nothing
37
+ --offline no database at all (validate/list only)
38
+ --json machine-readable report
39
+ --overwrite required to write to develop or prod
40
+ --confirm-prod <org-slug> additionally required to write to prod
41
+ --confirm-prune required for prune to actually delete
42
+ --force allow a prod write from a dirty git tree
43
+ --replace-existing dev-workbooks / dev-client-data, with --name: DELETE the
44
+ member's existing rows and re-seed them (never prod)
45
+
46
+ Write gating: local is free; develop needs --overwrite; prod needs
47
+ --overwrite --confirm-prod <slug> and a clean git tree.
48
+
49
+ Cutover is NOT a layer and is not run by this CLI \u2014 a layer is a desired-state
50
+ converger and a deploy pointer is the opposite shape, so promotion stays a
51
+ separate deliberate act.
52
+
53
+ WHICH repo runs it is per-org, and this text is shared engine, so it cannot
54
+ answer for yours: the rule is that the repo owning the deploy pipeline owns the
55
+ cutover. If this repo has scripts/cutover.mjs and a deploy:cutover script, that
56
+ is the one \u2014 the host refuses any org listed in its REPO_OWNED_CUTOVER map.
57
+ Never run both.
58
+ npm run deploy:cutover -- --org <slug> --version <v> --develop
59
+ `;var WRITE_COMMANDS=new Set(["sync","seed","pull","prune"]);async function main(){const args=parseArgs(process.argv.slice(2));if(!args.command||args.flags.has("help")||args.command==="help"){console.log(USAGE);return args.command&&args.command!=="help"?1:0}const org=loadOrgConfig();assertWriteAllowed(args,{requiresWrite:WRITE_COMMANDS.has(args.command),orgSlug:org.slug,repoRoot:process.cwd()});const ctx=await buildContext(args);switch(args.command){case"status":return runStatus(ctx);case"validate":return runValidate(ctx);case"list":return runList(ctx);case"sync":return runSync(ctx);case"seed":return runSeed(ctx);case"pull":return runPull(ctx);case"doctor":return runDoctor(ctx);case"prune":return runPrune(ctx);default:console.error(`unknown command "${args.command}"`);console.log(USAGE);return 1}}main().then(code=>process.exit(code)).catch(error=>{console.error(`
60
+ \u2717 ${error instanceof Error?error.message:String(error)}
61
+ `);process.exit(1)});