@kizenapps/cli 1.18.0-3811cee → 1.18.1

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/dist/index.js CHANGED
@@ -147,7 +147,7 @@ deleteall
147
147
  `),r}var pd=e=>e.toString("utf8").split("\0").filter(t=>t!=="");function cv(e){let t=new Map;for(let n of pd(e)){let r=n.indexOf(" "),[,i,o]=n.slice(0,r).split(" "),s=n.slice(r+1),a=t.get(s)??new Map;a.set(Number(o),i??""),t.set(s,a)}return t}function lv(e){let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(10,n),[i="",,o]=e.subarray(n,r).toString("utf8").split(" ");if(o===void 0)throw new _t("cat-file",`missing object ${i}`);let s=r+1,a=s+Number(o);t.set(i,e.subarray(s,a)),n=a+1}return t}async function uv(e,t,n,r){await Xt(n);let i=async(b,y,C)=>{let S;try{S=await dd(e,y,n,t,C)}catch(x){throw new _t(b,xe(x))}if(S.code!==0&&!(b==="merge"&&S.code===1))throw new _t(b,S.stderr.trim()||`exit ${String(S.code)}`);return S};await i("init",["init","-q","--template=","."]),await Xt(he(n,".git","info"),{recursive:!0}),await ld(he(n,".git","info","attributes"),Qw),await i("fast-import",["fast-import","--quiet","--done"],av(r.base,r.live,r.local));let o=(await i("rev-parse",["rev-parse","--verify","local^{tree}"])).stdout.toString("utf8").trim();await i("checkout",["checkout","-q","local","--"]);let s=await i("merge",["merge","--no-ff","--no-edit","--no-verify","-q","live"]),a=cv((await i("ls-files",["ls-files","-u","-z"])).stdout),c=a.size>0;if(s.code===1!==c)throw new _t("merge",s.stderr.trim()||`exit ${String(s.code)}`);let l=[...a].filter(([,b])=>b.has(2)&&b.has(3)),d=[...new Set(l.flatMap(([,b])=>[...b.values()]))],u=d.length===0?new Map:lv((await i("cat-file",["cat-file","--batch"],[ya.encode(d.map(b=>`${b}
148
148
  `).join(""))])).stdout),f=new Set(l.filter(([,b])=>[...b.values()].some(y=>nv(u.get(y)??new Uint8Array))).map(([b])=>b));await i("add",["add","-A","-f"]);let g=(await i("write-tree",["write-tree"])).stdout.toString("utf8").trim(),m=pd((await i("diff-tree",["diff-tree","-r","-z","--no-renames","--no-ext-diff","--no-textconv","--name-status",o,g])).stdout),p=[];for(let b=0;b+1<m.length;b+=2)p.push({status:m[b]??"",path:m[b+1]??""});let h=new Map;for(let{status:b,path:y}of p){if(!Zn(y))throw new _t("merge",`unexpected path "${y}"`);b!=="D"&&h.set(y,await Hw(he(n,...Le(y))))}return{changes:p,contents:h,unmerged:a,binary:f}}var dv=sd.O_NOFOLLOW??0;async function pv(e){let t=await Uw(e,sd.O_RDONLY|dv);try{return new Uint8Array(await t.readFile())}finally{await t.close()}}async function md(e,t){let n=await pa(e,t===void 0?{}:{git:t}),r=await Promise.all(n.files.map(l=>pv(he(e,...Le(l))))),i=n.files.map(l=>l.normalize("NFC")),o=new Set(i).size===i.length?i:n.files,s=new Map,a=new Map,c=new Map;return n.files.forEach((l,d)=>{let u=o[d]??l,f=r[d]??new Uint8Array;s.set(u,f),a.set(u,tv(f)),c.set(u,l)}),{files:s,hashes:a,diskPaths:c,mode:n.mode}}var rd=e=>new Map([...e].map(([t,n])=>[t.normalize("NFC"),n]));async function mv(e,t){let n=Le(t);for(let r=1;r<=n.length;r+=1){let i=await _e(En(he(e,...n.slice(0,r))));if(i===void 0)return"absent";if(r===n.length)return i.isFile()?"file":"blocked";if(!i.isDirectory())return"blocked"}return"blocked"}var ba=e=>e.isFile()&&e.nlink===1n?`${String(e.dev)}:${String(e.ino)}`:void 0;async function fd(e,t){let n=new Set;for(let r of t){let i=await _e(En(he(e,...Le(r)),{bigint:!0})),o=i===void 0?void 0:ba(i);o!==void 0&&n.add(o)}return n}async function gd(e,t){let n=await Vw(e);if(n.length===0)return!1;for(let r of n){let i=he(e,r),o=await En(i,{bigint:!0});if(!(o.isDirectory()?await gd(i,t):t.has(ba(o)??"")))return!1}return!0}async function hd(e,t,n){let r=Le(t);for(let i=1;i<=r.length;i+=1){let o=he(e,...r.slice(0,i)),s=await _e(En(o,{bigint:!0}));if(s===void 0)return"absent";if(s.isFile())return n.has(ba(s)??"")?"absent":"blocked";if(!s.isDirectory())return"blocked";if(i===r.length)return await gd(o,n)?"absent":"blocked"}return"blocked"}async function fv(e,t,n,r){let i=new Set;if(t.length===0)return i;let o=[await Br(e,ca),n==="walk"?await Br(e,".gitignore"):void 0];for(let s of t)o.some(a=>a?.ignores(s)===!0)&&i.add(s);if(n==="git"){let s=l=>/["\\\p{Cc}]/u.test(l),a=async l=>{try{let d=await r(["-c","core.quotePath=false","check-ignore","--",...l.map(u=>`./${u}`)],e);return new Set(d.split(`
149
149
  `))}catch(d){if(d?.code===1)return new Set;let u=d?.stderr;throw new _t("check-ignore",typeof u=="string"&&u.trim()!==""?u.trim():xe(d))}},c=t.filter(l=>!s(l));for(let l=0;l<c.length;l+=100){let d=c.slice(l,l+100),u=await a(d);d.filter(f=>u.has(`./${f}`)).forEach(f=>i.add(f))}for(let l of t.filter(s))(await a([l])).size>0&&i.add(l)}return i}var Zt=e=>[...e].sort();function id(e,t){let[n,r]=[Ui(e),Ui(t)];return n===r||n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}async function gv(e,t,n,r){let i=b=>t.diskPaths.get(b)??b;for(let{path:b}of n.changes)if(jr(b))throw new _t("merge",`unexpected path "${b}"`);let o=new Set(n.changes.filter(({status:b,path:y})=>b==="D"&&t.files.has(y)).map(({path:b})=>b)),s=await fd(e,[...o].map(i)),a=new Set,c=new Set,l=[];for(let{status:b,path:y}of n.changes)b!=="D"&&(t.files.has(y)?a.add(y):await hd(e,y,s)==="absent"?l.push(y):c.add(y));let d=await fv(e,l,t.mode,r);for(let b of l)(d.has(b)?c:a).add(b);let u=new Set,f=[],g=[],m=[];for(let[b,y]of n.unmerged)n.binary.has(b)?m.push(b):c.has(b)||(u.add(b),y.has(1)&&y.has(2)&&!y.has(3)?f.push(b):y.has(1)&&y.has(3)&&!y.has(2)&&g.push(b));let p=[...o].filter(b=>[...c].some(y=>id(y,b)));for(let b of p)o.delete(b),u.add(b);for(let b of[...c,...a])!t.files.has(b)&&p.some(y=>id(b,y))&&(c.delete(b),a.delete(b),u.add(b));let h=new Map;for(let b of a)h.set(b,n.contents.get(b)??new Uint8Array);return{written:Zt(a),deleted:Zt(o),conflicted:Zt(u),deletedOnLive:Zt(f),deletedLocally:Zt(g),binaryConflicts:Zt(m),ignoredIncoming:Zt(c),contents:h}}async function yd(e,t={}){if(e.base===null)return{status:"no_base"};let n=(t.findGit??rv)();if(n===void 0)return{status:"git_unavailable",reason:qw};let r=Vi(e.pluginDir),i=Vi(t.tmpDir??Gw());if(i===r||i.startsWith(r+ud))throw new Error("The merge workspace must not be inside the plugin folder.");let o=await zw(he(i,"appbuilder-merge-"));try{let s=he(o,"home");await Xt(s);let a=iv(t.env??process.env,s),c=await ov(n,a,o);if(c!==void 0)return{status:"git_unavailable",reason:c};let l=rd(_n(e.base.zip).files),d=rd(_n(e.live.zip).files),u=await md(r,t.git),f=await uv(n,a,he(o,"repo"),{base:l,live:d,local:u.files}),g=await gv(r,u,f,t.git??da);return g.written.length===0&&g.deleted.length===0&&g.conflicted.length===0&&g.binaryConflicts.length===0?{status:"up_to_date",ignoredIncoming:g.ignoredIncoming}:{status:"ready",pluginDir:r,baseVersion:e.base.version,liveVersion:e.live.version,...g,localHashes:u.hashes}}finally{await ad(o,{recursive:!0,force:!0})}}function od(e,t){let n=Vi(e,...Le(t));if(!Zn(t)||jr(t)||!n.startsWith(e+ud))throw new zr(t)}async function hv(e,t){let n=Le(t);for(let r=1;r<n.length;r+=1){let i=he(e,...n.slice(0,r));try{await Xt(i)}catch(o){if(o.code!=="EEXIST"||!(await En(i)).isDirectory())throw o}}}async function yv(e,t){let n=new Set;for(let i of t){let o=Le(i);for(let s=1;s<o.length;s+=1)n.add(o.slice(0,s).join("/"))}let r=[...n].sort((i,o)=>Le(o).length-Le(i).length);for(let i of r)await cd(he(e,...Le(i))).catch(()=>{})}var bv=".kizenapp",wv=(e,t)=>t?Ww(e,{bigint:!0}):En(e,{bigint:!0});async function vv(e,t){let n=he(e,bv),r=!1;try{await Xt(n),r=!0}catch(l){if(l.code!=="EEXIST")throw l}let i=async()=>{r&&await cd(n).catch(()=>{})},[o,s]=await Promise.all([t(n,!1),t(e,!0)]),a=o.isDirectory()?o.dev!==s.dev?"is on a different disk than the plugin folder":void 0:"isn't a real folder";if(a!==void 0)throw await i(),new ha(n,a);let c=he(n,`merge-${jw()}`);return await Xt(c),{staging:c,cleanUp:async()=>{await ad(c,{recursive:!0,force:!0}),await i()}}}async function bd(e,t={}){if(e.status!=="ready")return e;let n=Vi(e.pluginDir);for(let g of e.written){if(!e.contents.has(g))throw new zr(g);od(n,g)}for(let g of e.deleted){if(!e.localHashes.has(g))throw new zr(g);od(n,g)}let r=await md(n,t.git),i=Zt(new Set([...e.localHashes.keys(),...r.hashes.keys()].filter(g=>e.localHashes.get(g)!==r.hashes.get(g))));if(i.length>0)throw new Hi(i);let o=g=>r.diskPaths.get(g)??g,s=await fd(n,e.deleted.map(o)),a=[];for(let g of[...e.written,...e.deleted])(e.localHashes.has(g)?await mv(n,o(g))==="file":await hd(n,g,s)==="absent")||a.push(g);if(a.length>0)throw new Hi(a);let{staging:c,cleanUp:l}=await vv(n,t.stat??wv),d=[];try{for(let g of e.written){let m=he(n,...Le(o(g))),p=he(c,"merged",...Le(o(g)));await Xt(td(p),{recursive:!0}),await ld(p,e.contents.get(g)??new Uint8Array,{flag:"wx"}),e.localHashes.has(g)&&await Mw(p,(await En(m)).mode&4095),d.push({path:o(g),source:p,target:m})}}catch(g){throw await l(),g}if(t.isAborted?.()===!0)return await l(),{status:"cancelled"};let u=t.rename??Kw;try{for(let g of e.deleted.map(o)){let m=he(c,"removed",...Le(g));await Xt(td(m),{recursive:!0}),await u(he(n,...Le(g)),m)}await yv(n,e.deleted.map(o));for(let{path:g,source:m,target:p}of d)await hv(n,g),await u(m,p)}catch(g){throw new ga(c,g)}await l();let f={written:e.written,deleted:e.deleted,ignoredIncoming:e.ignoredIncoming};return e.conflicted.length===0&&e.binaryConflicts.length===0?{status:"merged",...f}:{status:"conflicts",...f,conflicted:e.conflicted,deletedOnLive:e.deletedOnLive,deletedLocally:e.deletedLocally,binaryConflicts:e.binaryConflicts}}import{randomUUID as kv}from"crypto";import{mkdir as Av,readFile as xv,rename as wd,rm as Pv,stat as Cv,writeFile as Sv}from"fs/promises";import{dirname as _v,join as kd}from"path";var In=".kizenapp/apps.json",Ad=".corrupt",Ur=class extends Error{constructor(){super(`${In} changed while this command ran, so it wasn't written.`),this.name="AppStateChangedError"}},wa=class extends Error{constructor(){super(`${In} exists but couldn't be read, so it wasn't overwritten. Fix its permissions and run the command again.`),this.name="AppStateUnreadableError"}},Vr=()=>({rest:{},entries:[],corrupt:!1,fingerprint:null}),xd=["environment","businessId","baseApiName","userId"],Pd=e=>e===null||typeof e=="string",Ev=e=>e===void 0||Pd(e),Cd=(e,t)=>F(e)&&xd.every(n=>e[n]===t[n]);function Sd(e){return F(e)&&xd.every(t=>typeof e[t]=="string"&&e[t]!=="")&&Ev(e.folderBaseLiveVersion)&&(typeof e.folderBaseLiveVersion=="string"?typeof e.folderBaseSourcePackageId=="string"&&e.folderBaseSourcePackageId!=="":e.folderBaseSourcePackageId===void 0)&&(e.previewSourcePackageId===void 0||typeof e.previewSourcePackageId=="string")&&Pd(e.lastPushedSourceHash)&&(e.previewRestoredFrom===void 0||typeof e.previewRestoredFrom=="string")&&(e.conflictedPaths===void 0||Array.isArray(e.conflictedPaths)&&e.conflictedPaths.every(t=>typeof t=="string"))}async function _d(e){try{let t=await Cv(e,{bigint:!0});return`${String(t.ino)}:${String(t.size)}:${String(t.mtimeNs)}`}catch(t){if(tt(t))return null;throw t}}var vd=(e,t)=>({doc:{...Vr(),corrupt:!0,fingerprint:t},notice:`${In} ${e}, so it was ignored. It will be moved to ${In}${Ad} on the next write.`});async function Ed(e){let t=kd(e,In),n,r;try{n=await _d(t),r=await xv(t,"utf8")}catch(c){return tt(c)?{doc:Vr()}:{doc:{...Vr(),unreadable:!0},notice:`Couldn't read ${In} (${ke(c)}), so it was ignored and won't be written.`}}let i;try{i=JSON.parse(r)}catch{return vd("is not valid JSON",n)}if(!F(i)||i.apps!==void 0&&!Array.isArray(i.apps))return vd("is not in the expected format",n);let{apps:o,...s}=i,a=Array.isArray(o)?[...o]:[];return{doc:{rest:s,entries:a,corrupt:!1,fingerprint:n}}}function va(e,t){let r=e.entries.filter(i=>Cd(i,t)).at(-1);return r===void 0?{status:"missing"}:Sd(r)?{status:"found",entry:r}:{status:"malformed"}}var Iv=["environment","businessId","baseApiName"];function Id(e,t,n){let r=e.entries.map(i=>{if(!F(i)||!Iv.every(s=>i[s]===t[s])||!Sd(i))return i;let o=n(i);return JSON.stringify(o)===JSON.stringify(i)?i:o});return r.some((i,o)=>i!==e.entries[o])?{...e,entries:r}:null}function ka(e,t){return{...e,entries:[...e.entries.filter(n=>!Cd(n,t)),t]}}async function Td(e,t){if(t.unreadable===!0)throw new wa;let n=kd(e,In),r=`${n}.${kv()}.tmp`;await Av(_v(n),{recursive:!0});let i={...t.rest,apps:t.entries};try{if(await Sv(r,`${JSON.stringify(i,null,2)}
150
- `,{encoding:"utf8",flag:"wx"}),await _d(n)!==(t.fingerprint??null))throw new Ur;if(t.corrupt)try{await wd(n,`${n}${Ad}`)}catch(o){if(!tt(o))throw o}await wd(r,n)}catch(o){throw await Pv(r,{force:!0}).catch(()=>{}),o}}import{join as qi}from"path";var Nd="---\nname: kizen-business-apps\ndescription: Publish, preview, merge, roll back or pull this plugin as a Kizen Business App with `appbuilder app` (versions, push, publish, merge, rollback, pull, actions, preview). Use it when the user wants to release this plugin to their Kizen business, save, update or delete their preview, publish a new Live version, resolve a publish conflict or merge someone else's Live changes, restore an earlier release, download a released version's or their preview's source, or link the app's JS actions to objects.\n---\n\n# Kizen Business Apps\n\n`appbuilder app` publishes the plugin in this folder as a Business App on the business the user is signed in to. Publishing replaces Live for everyone in that business, so every write is a dry run first. Follow these rules exactly.\n\n## Before you start\n\n- Run every command from the plugin folder (the one with `kizen.json`), with `--json`.\n- If `appbuilder app` is an unknown command, the CLI is too old. Ask the user to upgrade `@kizenapps/cli` to 1.18.0 or later, then continue.\n- If a result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}}`, re-read `{{SKILLS_DIR}}/kizen-business-apps/SKILL.md`, and follow the new copy.\n- Never edit, delete or commit anything in `.kizenapp/`. `.kizenapp/apps.json` records what this folder is based on; push and merge depend on it. Your preview's base isn't in it: it lives only in the preview's source on the server (see \"Another machine or folder\"), so publishing works from any machine.\n- The server numbers releases. `kizen.json` `version` isn't sent, so don't bump it for an app release.\n\n## The contract\n\n- `--json` prints one JSON object on stdout. Human text goes to stderr. Parse stdout only.\n- Exit `0`: success, dry runs included. Exit `2`: a decision is needed (`needs_choice` or `base_required`); its `choices` say how to go on. Exit `1`: any other failure, `{ ok: false, code, message, hint? }`.\n- Every `argv` you get (`choices[].argv`, `next[].argv`, `applyArgv`, `login.argv`, and a JS action's `linkArgv`, `linkMenuArgv`, `linkNoMenuArgv` and `unlinkArgv`) is a whole command starting with `appbuilder`. Run it exactly as given. Never add, drop or reorder its flags, and never build these commands yourself. The only edit you may make to any argv is replacing an element that is exactly `<object>` (in `linkArgv`, `linkMenuArgv` and `linkNoMenuArgv`) with an object's api name or id. They carry the account the run used (`--env`, `--business`, `--user`, or its `-c`/`--profile`), so they act on the same business.\n- `push`, `publish`, `merge`, `rollback` and `preview delete` without `--yes` are dry runs: `{ ok: true, applied: false, dryRun: true, \u2026, applyArgv, requiresProductionConsent, next: [] }`. `applyArgv` is that command with `--yes` (and `--allow-production` on `go` or `fmo`). It is pinned to what the dry run showed: `publish` to the preview it reviewed (`--expect-preview <id>`), `merge` to the version it planned (`--release <n>`), `rollback` to its version, `preview delete` to the preview's owner (`--owner <userId>`, yours included) and the preview it reviewed (`--expect-updated <ts>`), with `--delete-app` only when it warned that the app goes too. A `push` apply uploads the folder as it is when the apply runs.\n- `requiresProductionConsent: true` means the target is production (`go` or `fmo`). Show the user the dry run and get their explicit go-ahead in this conversation before running `applyArgv`.\n- Applied results have `applied: true` and `next`: the commands to run next, in order, each `{ step, argv }`. After a merge with conflicts, `next` starts with `{ step: \"resolve\", files, markers }`.\n- An applied publish whose `warnings` say \"this folder's base wasn't advanced\" did publish, but this folder still counts as based on the old Live. The next publish from it stops with `publish_conflict`; run the merge it offers, then push and publish.\n\n## Workflow\n\n1. **Look.** `appbuilder app versions --json` returns `live`, `released`, `previews`, `yourPreview`, `base` and `next`. `published: false` means the app isn't on this business yet; the first push and publish create it.\n2. **Push your preview.** `appbuilder app push --json` is a dry run. Show the user `environment`, `businessId`, `app`, `source.files`, `base` and `warnings`. When they agree, run `applyArgv`. A push saves only the user's own preview; Live doesn't change.\n3. **Link its JS actions.** Read the applied push's `jsActions` and link every action that needs it, `unlinked` and `unknown` alike (see \"JS actions\" below), before you move on.\n4. **Publish.** Run the applied push's `next` step `publish` (`appbuilder app publish --json`), a dry run. Show the user `app`, `conflictCheck`, `nextReleaseAtLeast` and `warnings`. When they agree, run `applyArgv`. It's done when `applied` is `true`; tell the user the new `liveVersion`, then check its `jsActions` again.\n5. **Every change after that:** edit, push (dry run, then `applyArgv`), link new JS actions, publish (dry run, then `applyArgv`).\n\n### Live moved: `publish_conflict`\n\nSomeone published since your preview's base, and publishing now would overwrite their changes. Never answer with `--force`.\n\n1. Run `next[0].argv` (`appbuilder app merge \u2026`), a dry run. Show the user `written`, `deleted`, `conflicted` and any other lists, then run `applyArgv` when they agree. A merge changes only local files.\n2. If the applied merge's `next` starts with a `resolve` step, edit every file in its `files`. The side between `<<<<<<< HEAD` and `=======` is this folder's; the side between `=======` and `>>>>>>> live` is Live's (or the merged `--release`). Keep both sides' intended changes and delete the three marker lines. `appbuilder app push` refuses with `unresolved_conflicts` (listing `files`) until no markers are left.\n3. Then follow the rest of `next`: push (dry run, `applyArgv`), publish (dry run, `applyArgv`).\n\n### No recorded base: `base_required` (exit 2)\n\nThis happens when Live exists, the folder matches neither your preview nor a released version exactly (an exact match is detected and used automatically: `base.source` is `\"preview\"` or `\"detected\"`), and no usable base is recorded for it. That's the first push from a fresh clone, another machine or another developer's folder, or a push whose recorded base no longer applies (that version was deleted, or the app was deleted and created again; a notice in the `message` says which). Show the user the `message` and each choice's `label`:\n\n- \"Preview merging Live vN into this folder\" is a dry run. You may run it without asking. With no base to merge from, it always comes back with `kind: \"fallback\"`, whose `choices` are \"Merge, if this folder was copied from vM\" (`--base <M>`) for recent releases, and \"This folder already contains vN\".\n- \"This folder already contains Live vN\" records the base without merging (`--accept-live-base`). Run it only when the user confirms the folder really contains that version, or the next publish drops Live's changes.\n- \"This folder continues your preview (based on vN)\" (`appbuilder app push --base-from-preview <id>`) is a push dry run that gives this folder your preview's base. Never run it on your own judgment: ask the user whether this folder really is the work they pushed as that preview (for example, carried on from another machine). Run it only when they say yes; a wrong yes lets the next publish overwrite Live's changes. Then show its dry run and run its `applyArgv` as for any push. If the user isn't sure, use the merge preview instead.\n\nAfter the fallback, ask the user which release this folder was copied from:\n\n- They know it: run that release's `--base <M>` choice. It merges for real; continue as after any merge (resolve markers, push, publish). A wrong base drops the changes made since then, so never guess one.\n- They don't know: run the fallback's `applyArgv`. It extracts Live's source into `.kizenapp/live-v<N>-<time>/` (reported as `extracted.dir`) and changes nothing else. Help the user merge Live's changes into this folder by hand, then run the \"This folder already contains vN\" choice, and push.\n\n### Another machine or folder\n\nEvery push and rollback stores the preview's base inside the preview's source on the server, and publish reads it from there. So:\n\n- Publishing a preview the user pushed from another machine or folder needs no merge and no `--force`, unless Live moved since (then it's the usual `publish_conflict`).\n- A push from a folder with nothing recorded takes the preview's base by itself when the folder's files equal the preview's (`base.source: \"preview\"`); otherwise `base_required` offers \"This folder continues your preview\", which only the user may choose.\n- `conflict.reason: \"base_replaced\"` (a `publish_conflict`) means the version your preview was based on has been replaced on the business (the app was deleted and created again). Handle it like any `publish_conflict`: run `next[0].argv`, the merge dry run.\n- `conflict.reason: \"base_unknown\"` (a `publish_conflict`) means the preview's source doesn't say what it's based on. Run `next[0].argv`, a push dry run of this folder; with the user's go-ahead, its `applyArgv`, then publish again.\n- A preview pushed from this folder and published outside the CLI (in Kizen, say) is recognised: the folder's base becomes that Live version, with a notice; don't merge because of the old base.\n\n### Roll back and pull\n\n- `appbuilder app rollback <n> --json` restores released version n as the user's preview (dry run, then `applyArgv`). Its `next` is the publish dry run that makes it Live.\n- `appbuilder app pull <n> --json` downloads release n into a new folder, `../<api_name>-v<n>` or `--out <dir>`, and records n as that folder's base. It never writes into an existing folder and needs no `--yes`. Continue in the folder it reports as `dir`.\n- `appbuilder app pull --preview --json` does the same with the user's own preview, into `../<api_name>-preview` or `--out <dir>`. Pass `<n>` or `--preview`, never both. The result has `source: \"preview\"`, `preview` and `base` instead of `version`. `base.recorded: true` means the folder's base is the preview's base, so you can push and publish from it as usual; `false` (with a warning) means the preview doesn't say what it's based on, and the first push from the folder may stop with `base_required`. `no_preview` means the user has no preview to pull.\n\n### Delete a preview\n\nOnly when the user asks to delete a preview:\n\n1. Run `appbuilder app preview delete --json`, a dry run for the user's own preview. For another developer's preview, add `--owner <userId>` with the user id from `previews[].previewOwner.id` in `appbuilder app versions --json`, and only when the user explicitly named that developer's preview.\n2. Show the user `owner`, `preview` and every `warnings` entry. They say when the preview is the app's only version (deleting it deletes the whole app from the business, settings and secrets included), when it belongs to someone else, and when other users are using it.\n3. When the user agrees to every warning, run `applyArgv`. Never add `--delete-app` yourself; `applyArgv` carries it only when the dry run warned that the app goes too. A dry run with no `applyArgv` can't be applied: relay its `notices` to the user. The result has `status: \"deleted\"` and `appDeleted` (`true` when the app went with it). After deleting their own preview, its `next` is a push dry run, which makes a new preview.\n\n`preview_changed` means the preview was pushed again after the dry run, or deleting it would now delete the whole app when the dry run said it stays: nothing was deleted. Run `next[0].argv`, a new dry run, and show it to the user again.\n\n### JS actions: link them to objects\n\nA JS action template does nothing until it's linked to an object. Always create these links with the CLI, even though the app's setup assistant may have a step for it. `push`, `publish` and `versions` results carry `jsActions`: `{ status, liveVersion, actions, next }`; `appbuilder app actions list --json` returns the same `actions`. Each action is `{ apiName, name, hintObjectName, status, inLive, links, linkArgv, linkMenuArgv, linkNoMenuArgv }`:\n\n- `linked`: it has at least one link (`links[]`, each with the object's `objectName`, `includePerformAction` (the Perform Action menu setting) and `unlinkArgv`). Nothing to do.\n- `unlinked`: in Live (or the app isn't on the business yet) with no link. Link it.\n- `unknown`: only in a preview, so its links can't be listed, and it may not be linked yet. Link it right after the push, like an `unlinked` one.\n\nHow to link:\n\n1. Pick the object with the user. For an `unlinked` action with a hint object, `jsActions.next` has a `link` step naming `hintObjectName`: it only suggests that object. Confirm it with the user, or ask which object (no hint, an `unknown` action, or the user wants another one). Don't run the `link` step itself; step 2's argv makes the one dry run.\n2. Ask whether the action should show in the object's Perform Action menus. Take the action's `linkMenuArgv` if it should, and its `linkNoMenuArgv` if it shouldn't (for a link that exists, that turns the menu off); `linkArgv` leaves a new link off the menus and an existing one as it is. Replace the one element that is exactly `<object>` with the object's api name (like `client_client`) or id, change nothing else, and run it: a dry run of `appbuilder app actions link \u2026`. Contacts counts as an object. Exit 2 with `choice: \"object\"` means several objects match: show the user the `choices` and run the one they pick.\n3. Show the user the dry run (`environment`, `businessId`, `jsAction`, `object`, `change`, `includePerformAction`, `warnings`). When they agree, run `applyArgv`. `status` is `created`, `updated`, `up_to_date` or `already_linked` (the link already existed and its menu setting wasn't changed: for an action only in a preview, linked before while its links couldn't be listed; for an action in Live, linked after this command listed the links, in which case run `appbuilder app actions list` and link it again to set the menu setting the user wants).\n4. Review with `appbuilder app actions list --json`: every action with its `status`, `links` and argvs, and link dry runs in `next`. It lists the links of Live's actions only; a preview-only action stays `unknown` until it's published.\n\nIf a link of an `unknown` action fails with `api_error` and a `hint` saying Kizen couldn't find it, that Kizen environment can only link actions in Live. Relay the hint: publish first, then link it.\n\nA link change to an action in Live (`inLive: true`), whether a new link, a menu setting or an unlink, reaches everyone using Live as soon as it's applied; its dry run's `warnings` say so. Treat it like a publish: confirm the object and the menu setting with the user before running its `applyArgv`.\n\nRemove a link only when the user asks: run that link's `unlinkArgv` (`appbuilder app actions unlink \u2026`, a dry run), then its `applyArgv` when they agree.\n\n### What a push uploads\n\nGit's file list (tracked files, plus untracked ones `.gitignore` doesn't exclude; outside git, everything minus the root `.gitignore`), minus the root `.kizenignore` (gitignore syntax; it can only exclude more). These are never uploaded, whatever either file says: `node_modules`, `.git`, `.kizenapp`, `.kizenappbuilder`, `.copilot-docs`, `__pycache__`, `dist`, `.DS_Store`, `.env`, `.env.*`, `.npmrc`, `credentials.json`, and the skill folders appbuilder manages (`kizen-custom-block` and `kizen-business-apps` under `.claude/skills/` and `.agents/skills/`). Other skills in those folders are uploaded like any file. Check `source.files` in the dry run, and suggest a `.kizenignore` entry for anything that shouldn't ship. A release needs a thumbnail.\n\n## Failures\n\n| `code` | What to do |\n| --- | --- |\n| `not_signed_in` | Ask the user to sign in by running `login.argv` themselves: it opens a browser (see Sandboxes). Then run your command again. |\n| `needs_choice` | `choice` is `environment`: the user is signed in to several. Ask which, then run that choice's `argv`. |\n| `base_required` | See \"No recorded base\" above. |\n| `publish_conflict` | Run `next[0].argv`: a merge dry run; a push dry run when `conflict.reason` is `base_unknown`; or, when your preview changed since the dry run, a new publish dry run. |\n| `unresolved_conflicts` | Resolve the markers in `files`, then push again. |\n| `no_preview` | Push first. For `pull --preview`, the user has no preview: tell them, or pull a release instead. |\n| `preview_changed` | Nothing was deleted. Run `next[0].argv`, a new `preview delete` dry run, and show it to the user before going on. |\n| `preview_incomplete` | Push again, then publish (or pull). |\n| `thumbnail_required` | Add a thumbnail to the plugin, push, then publish. |\n| `source_invalid` | The folder can't be zipped (no `kizen.json`, an unreadable `.kizenignore`, a folder git ignores, or a file over 50 MiB or 200 MiB in all). Fix what `message` says, for example with a `.kizenignore` entry. |\n| `validation_failed` | Fix every item in `issues`, then run the command again. |\n| `forbidden` | Tell the user they need the Marketplace \u203A Business App Developer permission at the Delete/All level. Don't retry. |\n| `production_requires_flag` | You ran a write against `go` or `fmo` without `--allow-production`. Run the dry run, get consent, then its `applyArgv`. |\n| `credentials_invalid` | The API-key file from `-c` or `--profile` is bad. Tell the user what `message` says. Use API keys only when the user asks. |\n| `auth_failed` | Kizen refused the session. Ask the user to sign in again (`appbuilder login`, with `--env <env>` for an environment other than `go`). |\n| `session_store_unwritable`, `network_error` | Usually a sandbox; see below. Otherwise relay `message` and `hint`. |\n| `not_found`, `usage_error`, `api_error`, `local_error` | Relay `message` to the user. |\n\n## Sandboxes\n\n`appbuilder` needs the network and write access to `~/.kizenappbuilder`, where it keeps the sign-in session and refreshes its tokens. It talks to the Kizen environment's hosts, and `push` uploads go to whichever file-storage host Kizen names for each upload.\n\n{{#codex}}\n- Codex's sandbox turns the network off and allows writes only to the workspace and `/tmp`. Run `appbuilder` commands with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]` so the user approves `appbuilder` once. A `network_error` with `sandbox: \"codex_network_disabled\"`, or a `session_store_unwritable`, means it ran without that.\n- `.agents/` is read-only in the sandbox, so `appbuilder setup-codex` needs the escalation too.\n- `appbuilder app pull` writes next to the plugin folder by default, outside the workspace. Escalate it, or pass an `--out <dir>` inside the workspace that `.gitignore` or `.kizenignore` excludes.\n- `not_signed_in`: the user runs `login.argv` in their own terminal. It opens a browser and waits for the sign-in.\n{{/codex}}\n{{#claude}}\n- Claude Code's sandbox, when enabled, allows writes only to the working directory and the network only to allowed domains. Because uploads go to a storage host Kizen picks, a domain list can't cover `appbuilder`. If it fails with `session_store_unwritable` or a `network_error`, ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n- `not_signed_in`: the user types `! ` followed by the `login.argv` command in this session, or runs it in their own terminal. It opens a browser and waits for the sign-in.\n{{/claude}}\n\n## Guardrails\n\n- Never pass `--force`, `--allow-production` or `--accept-live-base`, or run a choice whose `argv` contains one, unless the user explicitly asked for it in this conversation.\n- Always show the user a dry run before you run its `applyArgv`.\n- On exit 2, show the user the `choices` and run the one they pick. The merge preview is the only choice you may run without asking. Never pick \"This folder continues your preview\" for the user.\n- Never edit `.kizenapp/`.\n- Publish only when the user asked to publish.\n- Link a JS action only to an object the user confirmed, and unlink only when the user asked.\n- Delete a preview only when the user asked, and another developer's (`--owner`) only when the user named it.\n";var Rd="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `{{SETUP_COMMAND}} --include-lib` in the plugin directory.\n\n- If it reports `updated` for `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file in this skill directory, or `updated` for `{{SKILLS_DIR}}/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n{{#codex}}\n- In the Codex sandbox `.agents/` is read-only, so run it with `sandbox_permissions: \"require_escalated\"`.\n{{/codex}}\n\n`{{SETUP_COMMAND}}` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `{{SETUP_COMMAND}}` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `appbuilder block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\nWith `--json` (`block targets` and `block push`), stdout is one JSON object and human text goes to stderr. Exit `0` is success (dry runs included), exit `2` means a decision is needed (`needs_choice`), and exit `1` is any other failure. Every `argv` a result gives you (`applyArgv`, `choices[].argv`, `login.argv`) is a whole command starting with `appbuilder`: run it exactly as given, without adding, dropping or reordering flags.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the dry run's `applyArgv` exactly. It is the same push with `--yes`, pinned to the dashboard and dashlet the dry run showed. If `requiresProductionConsent` is `true` (the target is `go` or `fmo`), it also carries `--allow-production`: run it only after the user explicitly agreed to publish to production in this conversation. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings, applyArgv, requiresProductionConsent }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}} --include-lib`, re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, hint?, choice?, choices?, login?, sandbox? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `not_signed_in`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `session_store_unwritable`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`. When `hint` is present, follow it.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, argv, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`. Ask the user using each option's `label`, then run the chosen option's `argv` exactly as given: it is the push with that choice, as a dry run, so continue from its result (show it, then run its `applyArgv`). Ignore `args`, and never construct these flags by hand.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `not_signed_in`, ask the user to sign in by running the `login.argv` command themselves (it opens a browser), then run your command again.\n{{#claude}}\n In Claude Code they can type `! ` followed by that command in this session.\n{{/claude}}\n- On `credentials_invalid`, the API-key file from `-c` or `--profile` is bad. Tell the user to fix the file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `session_store_unwritable`, or a `network_error` with `sandbox: \"codex_network_disabled\"`, a sandbox is blocking `appbuilder`, which needs the network and write access to `~/.kizenappbuilder`.\n{{#codex}}\n Re-run the command with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]`.\n{{/codex}}\n{{#claude}}\n Ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n{{/claude}}\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var $d=`# Designing a Kizen custom block
150
+ `,{encoding:"utf8",flag:"wx"}),await _d(n)!==(t.fingerprint??null))throw new Ur;if(t.corrupt)try{await wd(n,`${n}${Ad}`)}catch(o){if(!tt(o))throw o}await wd(r,n)}catch(o){throw await Pv(r,{force:!0}).catch(()=>{}),o}}import{join as qi}from"path";var Nd="---\nname: kizen-business-apps\ndescription: Publish, preview, merge, roll back or pull this plugin as a Kizen Business App with `appbuilder app` (versions, push, publish, merge, rollback, pull, actions, preview). Use it when the user wants to release this plugin to their Kizen business, save, update or delete their preview, publish a new Live version, resolve a publish conflict or merge someone else's Live changes, restore an earlier release, download a released version's or their preview's source, or link the app's JS actions to objects.\n---\n\n# Kizen Business Apps\n\n`appbuilder app` publishes the plugin in this folder as a Business App on the business the user is signed in to. Publishing replaces Live for everyone in that business, so every write is a dry run first. Follow these rules exactly.\n\n## Before you start\n\n- Run every command from the plugin folder (the one with `kizen.json`), with `--json`.\n- If `appbuilder app` is an unknown command, the CLI is too old. Ask the user to upgrade `@kizenapps/cli` to 1.18.0 or later, then continue.\n- If a result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}}`, re-read `{{SKILLS_DIR}}/kizen-business-apps/SKILL.md`, and follow the new copy.\n- Never edit, delete or commit anything in `.kizenapp/`. `.kizenapp/apps.json` records what this folder is based on; push and merge depend on it. Your preview's base isn't in it: it lives only in the preview's source on the server (see \"Another machine or folder\"), so publishing works from any machine.\n- The server numbers releases with whole numbers (1, 2, 3\u2026) when you publish. They aren't semver, and they can skip numbers, so never predict one: the publish dry run's `nextReleaseAtLeast` is only a lower bound.\n- Business App releases don't publish release notes and don't use `kizen.json` `version` (it isn't sent), so for an app release don't bump `version` or create or edit files in `release_notes_directory`.\n\n## The contract\n\n- `--json` prints one JSON object on stdout. Human text goes to stderr. Parse stdout only.\n- Exit `0`: success, dry runs included. Exit `2`: a decision is needed (`needs_choice` or `base_required`); its `choices` say how to go on. Exit `1`: any other failure, `{ ok: false, code, message, hint? }`.\n- Every `argv` you get (`choices[].argv`, `next[].argv`, `applyArgv`, `login.argv`, and a JS action's `linkArgv`, `linkMenuArgv`, `linkNoMenuArgv` and `unlinkArgv`) is a whole command starting with `appbuilder`. Run it exactly as given. Never add, drop or reorder its flags, and never build these commands yourself. The only edit you may make to any argv is replacing an element that is exactly `<object>` (in `linkArgv`, `linkMenuArgv` and `linkNoMenuArgv`) with an object's api name or id. They carry the account the run used (`--env`, `--business`, `--user`, or its `-c`/`--profile`), so they act on the same business.\n- `push`, `publish`, `merge`, `rollback` and `preview delete` without `--yes` are dry runs: `{ ok: true, applied: false, dryRun: true, \u2026, applyArgv, requiresProductionConsent, next: [] }`. `applyArgv` is that command with `--yes` (and `--allow-production` on `go` or `fmo`). It is pinned to what the dry run showed: `publish` to the preview it reviewed (`--expect-preview <id>`), `merge` to the version it planned (`--release <n>`), `rollback` to its version, `preview delete` to the preview's owner (`--owner <userId>`, yours included) and the preview it reviewed (`--expect-updated <ts>`), with `--delete-app` only when it warned that the app goes too. A `push` apply uploads the folder as it is when the apply runs.\n- `requiresProductionConsent: true` means the target is production (`go` or `fmo`). Show the user the dry run and get their explicit go-ahead in this conversation before running `applyArgv`.\n- Applied results have `applied: true` and `next`: the commands to run next, in order, each `{ step, argv }`. After a merge with conflicts, `next` starts with `{ step: \"resolve\", files, markers }`.\n- An applied publish whose `warnings` say \"this folder's base wasn't advanced\" did publish, but this folder still counts as based on the old Live. The next publish from it stops with `publish_conflict`; run the merge it offers, then push and publish.\n\n## Workflow\n\n1. **Look.** `appbuilder app versions --json` returns `live`, `released`, `previews`, `yourPreview`, `base` and `next`. `published: false` means the app isn't on this business yet; the first push and publish create it.\n2. **Push your preview.** `appbuilder app push --json` is a dry run. Show the user `environment`, `businessId`, `app`, `source.files`, `base` and `warnings`. When they agree, run `applyArgv`. A push saves only the user's own preview; Live doesn't change.\n3. **Link its JS actions.** Read the applied push's `jsActions` and link every action that needs it, `unlinked` and `unknown` alike (see \"JS actions\" below), before you move on.\n4. **Publish.** Run the applied push's `next` step `publish` (`appbuilder app publish --json`), a dry run. Show the user `app`, `conflictCheck`, `nextReleaseAtLeast` and `warnings`. When they agree, run `applyArgv`. It's done when `applied` is `true`; tell the user the new `liveVersion`, then check its `jsActions` again.\n5. **Every change after that:** edit, push (dry run, then `applyArgv`), link new JS actions, publish (dry run, then `applyArgv`).\n\n### Live moved: `publish_conflict`\n\nSomeone published since your preview's base, and publishing now would overwrite their changes. Never answer with `--force`.\n\n1. Run `next[0].argv` (`appbuilder app merge \u2026`), a dry run. Show the user `written`, `deleted`, `conflicted` and any other lists, then run `applyArgv` when they agree. A merge changes only local files.\n2. If the applied merge's `next` starts with a `resolve` step, edit every file in its `files`. The side between `<<<<<<< HEAD` and `=======` is this folder's; the side between `=======` and `>>>>>>> live` is Live's (or the merged `--release`). Keep both sides' intended changes and delete the three marker lines. `appbuilder app push` refuses with `unresolved_conflicts` (listing `files`) until no markers are left.\n3. Then follow the rest of `next`: push (dry run, `applyArgv`), publish (dry run, `applyArgv`).\n\n### No recorded base: `base_required` (exit 2)\n\nThis happens when Live exists, the folder matches neither your preview nor a released version exactly (an exact match is detected and used automatically: `base.source` is `\"preview\"` or `\"detected\"`), and no usable base is recorded for it. That's the first push from a fresh clone, another machine or another developer's folder, or a push whose recorded base no longer applies (that version was deleted, or the app was deleted and created again; a notice in the `message` says which). Show the user the `message` and each choice's `label`:\n\n- \"Preview merging Live vN into this folder\" is a dry run. You may run it without asking. With no base to merge from, it always comes back with `kind: \"fallback\"`, whose `choices` are \"Merge, if this folder was copied from vM\" (`--base <M>`) for recent releases, and \"This folder already contains vN\".\n- \"This folder already contains Live vN\" records the base without merging (`--accept-live-base`). Run it only when the user confirms the folder really contains that version, or the next publish drops Live's changes.\n- \"This folder continues your preview (based on vN)\" (`appbuilder app push --base-from-preview <id>`) is a push dry run that gives this folder your preview's base. Never run it on your own judgment: ask the user whether this folder really is the work they pushed as that preview (for example, carried on from another machine). Run it only when they say yes; a wrong yes lets the next publish overwrite Live's changes. Then show its dry run and run its `applyArgv` as for any push. If the user isn't sure, use the merge preview instead.\n\nAfter the fallback, ask the user which release this folder was copied from:\n\n- They know it: run that release's `--base <M>` choice. It merges for real; continue as after any merge (resolve markers, push, publish). A wrong base drops the changes made since then, so never guess one.\n- They don't know: run the fallback's `applyArgv`. It extracts Live's source into `.kizenapp/live-v<N>-<time>/` (reported as `extracted.dir`) and changes nothing else. Help the user merge Live's changes into this folder by hand, then run the \"This folder already contains vN\" choice, and push.\n\n### Another machine or folder\n\nEvery push and rollback stores the preview's base inside the preview's source on the server, and publish reads it from there. So:\n\n- Publishing a preview the user pushed from another machine or folder needs no merge and no `--force`, unless Live moved since (then it's the usual `publish_conflict`).\n- A push from a folder with nothing recorded takes the preview's base by itself when the folder's files equal the preview's (`base.source: \"preview\"`); otherwise `base_required` offers \"This folder continues your preview\", which only the user may choose.\n- `conflict.reason: \"base_replaced\"` (a `publish_conflict`) means the version your preview was based on has been replaced on the business (the app was deleted and created again). Handle it like any `publish_conflict`: run `next[0].argv`, the merge dry run.\n- `conflict.reason: \"base_unknown\"` (a `publish_conflict`) means the preview's source doesn't say what it's based on. Run `next[0].argv`, a push dry run of this folder; with the user's go-ahead, its `applyArgv`, then publish again.\n- A preview pushed from this folder and published outside the CLI (in Kizen, say) is recognised: the folder's base becomes that Live version, with a notice; don't merge because of the old base.\n\n### Roll back and pull\n\n- `appbuilder app rollback <n> --json` restores released version n as the user's preview (dry run, then `applyArgv`). Its `next` is the publish dry run that makes it Live.\n- `appbuilder app pull <n> --json` downloads release n into a new folder, `../<api_name>-v<n>` or `--out <dir>`, and records n as that folder's base. It never writes into an existing folder and needs no `--yes`. Continue in the folder it reports as `dir`.\n- `appbuilder app pull --preview --json` does the same with the user's own preview, into `../<api_name>-preview` or `--out <dir>`. Pass `<n>` or `--preview`, never both. The result has `source: \"preview\"`, `preview` and `base` instead of `version`. `base.recorded: true` means the folder's base is the preview's base, so you can push and publish from it as usual; `false` (with a warning) means the preview doesn't say what it's based on, and the first push from the folder may stop with `base_required`. `no_preview` means the user has no preview to pull.\n\n### Delete a preview\n\nOnly when the user asks to delete a preview:\n\n1. Run `appbuilder app preview delete --json`, a dry run for the user's own preview. For another developer's preview, add `--owner <userId>` with the user id from `previews[].previewOwner.id` in `appbuilder app versions --json`, and only when the user explicitly named that developer's preview.\n2. Show the user `owner`, `preview` and every `warnings` entry. They say when the preview is the app's only version (deleting it deletes the whole app from the business, settings and secrets included), when it belongs to someone else, and when other users are using it.\n3. When the user agrees to every warning, run `applyArgv`. Never add `--delete-app` yourself; `applyArgv` carries it only when the dry run warned that the app goes too. A dry run with no `applyArgv` can't be applied: relay its `notices` to the user. The result has `status: \"deleted\"` and `appDeleted` (`true` when the app went with it). After deleting their own preview, its `next` is a push dry run, which makes a new preview.\n\n`preview_changed` means the preview was pushed again after the dry run, or deleting it would now delete the whole app when the dry run said it stays: nothing was deleted. Run `next[0].argv`, a new dry run, and show it to the user again.\n\n### JS actions: link them to objects\n\nA JS action template does nothing until it's linked to an object. Always create these links with the CLI, even though the app's setup assistant may have a step for it. `push`, `publish` and `versions` results carry `jsActions`: `{ status, liveVersion, actions, next }`; `appbuilder app actions list --json` returns the same `actions`. Each action is `{ apiName, name, hintObjectName, status, inLive, links, linkArgv, linkMenuArgv, linkNoMenuArgv }`:\n\n- `linked`: it has at least one link (`links[]`, each with the object's `objectName`, `includePerformAction` (the Perform Action menu setting) and `unlinkArgv`). Nothing to do.\n- `unlinked`: in Live (or the app isn't on the business yet) with no link. Link it.\n- `unknown`: only in a preview, so its links can't be listed, and it may not be linked yet. Link it right after the push, like an `unlinked` one.\n\nHow to link:\n\n1. Pick the object with the user. For an `unlinked` action with a hint object, `jsActions.next` has a `link` step naming `hintObjectName`: it only suggests that object. Confirm it with the user, or ask which object (no hint, an `unknown` action, or the user wants another one). Don't run the `link` step itself; step 2's argv makes the one dry run.\n2. Ask whether the action should show in the object's Perform Action menus. Take the action's `linkMenuArgv` if it should, and its `linkNoMenuArgv` if it shouldn't (for a link that exists, that turns the menu off); `linkArgv` leaves a new link off the menus and an existing one as it is. Replace the one element that is exactly `<object>` with the object's api name (like `client_client`) or id, change nothing else, and run it: a dry run of `appbuilder app actions link \u2026`. Contacts counts as an object. Exit 2 with `choice: \"object\"` means several objects match: show the user the `choices` and run the one they pick.\n3. Show the user the dry run (`environment`, `businessId`, `jsAction`, `object`, `change`, `includePerformAction`, `warnings`). When they agree, run `applyArgv`. `status` is `created`, `updated`, `up_to_date` or `already_linked` (the link already existed and its menu setting wasn't changed: for an action only in a preview, linked before while its links couldn't be listed; for an action in Live, linked after this command listed the links, in which case run `appbuilder app actions list` and link it again to set the menu setting the user wants).\n4. Review with `appbuilder app actions list --json`: every action with its `status`, `links` and argvs, and link dry runs in `next`. It lists the links of Live's actions only; a preview-only action stays `unknown` until it's published.\n\nIf a link of an `unknown` action fails with `api_error` and a `hint` saying Kizen couldn't find it, that Kizen environment can only link actions in Live. Relay the hint: publish first, then link it.\n\nA link change to an action in Live (`inLive: true`), whether a new link, a menu setting or an unlink, reaches everyone using Live as soon as it's applied; its dry run's `warnings` say so. Treat it like a publish: confirm the object and the menu setting with the user before running its `applyArgv`.\n\nRemove a link only when the user asks: run that link's `unlinkArgv` (`appbuilder app actions unlink \u2026`, a dry run), then its `applyArgv` when they agree.\n\n### What a push uploads\n\nGit's file list (tracked files, plus untracked ones `.gitignore` doesn't exclude; outside git, everything minus the root `.gitignore`), minus the root `.kizenignore` (gitignore syntax; it can only exclude more). These are never uploaded, whatever either file says: `node_modules`, `.git`, `.kizenapp`, `.kizenappbuilder`, `.copilot-docs`, `__pycache__`, `dist`, `.DS_Store`, `.env`, `.env.*`, `.npmrc`, `credentials.json`, and the skill folders appbuilder manages (`kizen-custom-block` and `kizen-business-apps` under `.claude/skills/` and `.agents/skills/`). Other skills in those folders are uploaded like any file. Check `source.files` in the dry run, and suggest a `.kizenignore` entry for anything that shouldn't ship. A release needs a thumbnail.\n\n## Failures\n\n| `code` | What to do |\n| --- | --- |\n| `not_signed_in` | Ask the user to sign in by running `login.argv` themselves: it opens a browser (see Sandboxes). Then run your command again. |\n| `needs_choice` | `choice` is `environment`: the user is signed in to several. Ask which, then run that choice's `argv`. |\n| `base_required` | See \"No recorded base\" above. |\n| `publish_conflict` | Run `next[0].argv`: a merge dry run; a push dry run when `conflict.reason` is `base_unknown`; or, when your preview changed since the dry run, a new publish dry run. |\n| `unresolved_conflicts` | Resolve the markers in `files`, then push again. |\n| `no_preview` | Push first. For `pull --preview`, the user has no preview: tell them, or pull a release instead. |\n| `preview_changed` | Nothing was deleted. Run `next[0].argv`, a new `preview delete` dry run, and show it to the user before going on. |\n| `preview_incomplete` | Push again, then publish (or pull). |\n| `thumbnail_required` | Add a thumbnail to the plugin, push, then publish. |\n| `source_invalid` | The folder can't be zipped (no `kizen.json`, an unreadable `.kizenignore`, a folder git ignores, or a file over 50 MiB or 200 MiB in all). Fix what `message` says, for example with a `.kizenignore` entry. |\n| `validation_failed` | Fix every item in `issues`, then run the command again. |\n| `forbidden` | Tell the user they need the Marketplace \u203A Business App Developer permission at the Delete/All level. Don't retry. |\n| `production_requires_flag` | You ran a write against `go` or `fmo` without `--allow-production`. Run the dry run, get consent, then its `applyArgv`. |\n| `credentials_invalid` | The API-key file from `-c` or `--profile` is bad. Tell the user what `message` says. Use API keys only when the user asks. |\n| `auth_failed` | Kizen refused the session. Ask the user to sign in again (`appbuilder login`, with `--env <env>` for an environment other than `go`). |\n| `session_store_unwritable`, `network_error` | Usually a sandbox; see below. Otherwise relay `message` and `hint`. |\n| `not_found`, `usage_error`, `api_error`, `local_error` | Relay `message` to the user. |\n\n## Sandboxes\n\n`appbuilder` needs the network and write access to `~/.kizenappbuilder`, where it keeps the sign-in session and refreshes its tokens. It talks to the Kizen environment's hosts, and `push` uploads go to whichever file-storage host Kizen names for each upload.\n\n{{#codex}}\n- Codex's sandbox turns the network off and allows writes only to the workspace and `/tmp`. Run `appbuilder` commands with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]` so the user approves `appbuilder` once. A `network_error` with `sandbox: \"codex_network_disabled\"`, or a `session_store_unwritable`, means it ran without that.\n- `.agents/` is read-only in the sandbox, so `appbuilder setup-codex` needs the escalation too.\n- `appbuilder app pull` writes next to the plugin folder by default, outside the workspace. Escalate it, or pass an `--out <dir>` inside the workspace that `.gitignore` or `.kizenignore` excludes.\n- `not_signed_in`: the user runs `login.argv` in their own terminal. It opens a browser and waits for the sign-in.\n{{/codex}}\n{{#claude}}\n- Claude Code's sandbox, when enabled, allows writes only to the working directory and the network only to allowed domains. Because uploads go to a storage host Kizen picks, a domain list can't cover `appbuilder`. If it fails with `session_store_unwritable` or a `network_error`, ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n- `not_signed_in`: the user types `! ` followed by the `login.argv` command in this session, or runs it in their own terminal. It opens a browser and waits for the sign-in.\n{{/claude}}\n\n## Guardrails\n\n- Never pass `--force`, `--allow-production` or `--accept-live-base`, or run a choice whose `argv` contains one, unless the user explicitly asked for it in this conversation.\n- Always show the user a dry run before you run its `applyArgv`.\n- On exit 2, show the user the `choices` and run the one they pick. The merge preview is the only choice you may run without asking. Never pick \"This folder continues your preview\" for the user.\n- Never edit `.kizenapp/`.\n- Publish only when the user asked to publish.\n- Link a JS action only to an object the user confirmed, and unlink only when the user asked.\n- Delete a preview only when the user asked, and another developer's (`--owner`) only when the user named it.\n";var Rd="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `{{SETUP_COMMAND}} --include-lib` in the plugin directory.\n\n- If it reports `updated` for `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file in this skill directory, or `updated` for `{{SKILLS_DIR}}/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n{{#codex}}\n- In the Codex sandbox `.agents/` is read-only, so run it with `sandbox_permissions: \"require_escalated\"`.\n{{/codex}}\n\n`{{SETUP_COMMAND}}` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `{{SETUP_COMMAND}}` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `appbuilder block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\nWith `--json` (`block targets` and `block push`), stdout is one JSON object and human text goes to stderr. Exit `0` is success (dry runs included), exit `2` means a decision is needed (`needs_choice`), and exit `1` is any other failure. Every `argv` a result gives you (`applyArgv`, `choices[].argv`, `login.argv`) is a whole command starting with `appbuilder`: run it exactly as given, without adding, dropping or reordering flags.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the dry run's `applyArgv` exactly. It is the same push with `--yes`, pinned to the dashboard and dashlet the dry run showed. If `requiresProductionConsent` is `true` (the target is `go` or `fmo`), it also carries `--allow-production`: run it only after the user explicitly agreed to publish to production in this conversation. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings, applyArgv, requiresProductionConsent }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}} --include-lib`, re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, hint?, choice?, choices?, login?, sandbox? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `not_signed_in`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `session_store_unwritable`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`. When `hint` is present, follow it.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, argv, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`. Ask the user using each option's `label`, then run the chosen option's `argv` exactly as given: it is the push with that choice, as a dry run, so continue from its result (show it, then run its `applyArgv`). Ignore `args`, and never construct these flags by hand.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `not_signed_in`, ask the user to sign in by running the `login.argv` command themselves (it opens a browser), then run your command again.\n{{#claude}}\n In Claude Code they can type `! ` followed by that command in this session.\n{{/claude}}\n- On `credentials_invalid`, the API-key file from `-c` or `--profile` is bad. Tell the user to fix the file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `session_store_unwritable`, or a `network_error` with `sandbox: \"codex_network_disabled\"`, a sandbox is blocking `appbuilder`, which needs the network and write access to `~/.kizenappbuilder`.\n{{#codex}}\n Re-run the command with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]`.\n{{/codex}}\n{{#claude}}\n Ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n{{/claude}}\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var $d=`# Designing a Kizen custom block
151
151
 
152
152
  With host chrome (the default), a block must look like a native Kizen dashlet. Follow every rule here exactly. Where a rule says "use judgment", pick the option that looks most native. A block whose \`config.json\` sets \`"host_chrome": false\` follows section M for its card and outer box, and skips every rule marked "with host chrome".
153
153