document360-writer 0.5.183 → 0.5.185

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +9 -9
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -277,7 +277,7 @@ try {
277
277
  }
278
278
  `;Zc="Re-run dev\u2194docs onboarding (protocol v"});var fl={};Pc(fl,{initCommand:()=>Hs,scaffoldInit:()=>Bs});import{input as Kn,confirm as pf}from"@inquirer/prompts";import{basename as sl,join as cr}from"node:path";import{existsSync as wn,readFileSync as hf,readdirSync as ff,writeFileSync as mf}from"node:fs";import{writeProjectConfig as il,readProjectConfig as gf,projectConfigPath as al,writerDir as yf,DEFAULT_DOCS_DIR as cl,DEFAULT_CAPTURE_DIR as ll,DEFAULT_OUTPUT_DIR as dl}from"document360-engine";function Bs(e,t="berlin"){let n=al(e);if(wn(n))return{created:!1,path:n,profileName:""};let o={projectId:pl(e)??sl(e),docsDir:cl,captureDir:ll,outputDir:dl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:hl(e)};return il(o,e),ul(e),{created:!0,path:n,profileName:t}}function ul(e){let t=cr(yf(e),".gitignore");wn(t)||mf(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
279
279
  `),"utf8")}async function Hs(){let e=process.cwd(),t=al(e);if(wn(t)&&!await pf({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=pl(e)??sl(e),o=await Kn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Kn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ll}),s=await Kn({message:"Screenshot output directory:",default:dl}),i=await Kn({message:"Default connection profile name:",default:"berlin"}),c=await Kn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:cl,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:hl(e)},h=gf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),il(p,e),ul(e);let b=gn(e);console.log(""),console.log(M(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of yn(b))console.log($);return console.log(""),console.log(`${y("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function pl(e){let t=cr(e,"package.json");if(!wn(t))return null;try{return JSON.parse(hf(t,"utf8")).name??null}catch{return null}}function hl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])wn(cr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=cr(e,n);wn(o)&&!wf(o)&&t.push(n)}return t}function wf(e){try{return ff(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lr=qn(()=>{"use strict";K();wt()});import{createRequire as Ff}from"node:module";import{existsSync as Wf,readFileSync as Bf}from"node:fs";import{dirname as Ol,join as Ll}from"node:path";function $n(){let e;try{e=Hf.resolve("document360-capture/helpers")}catch{return null}let t=Ol(e);for(let n=0;n<5&&!Wf(Ll(t,"package.json"));n++)t=Ol(t);try{let n=JSON.parse(Bf(Ll(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Hf,hr=qn(()=>{"use strict";Hf=Ff(import.meta.url)});var iu={};Pc(iu,{doctorCommand:()=>ao,renderDoctorChecks:()=>su,runDoctorChecks:()=>ru});import{existsSync as ey}from"node:fs";import{d360GetAll as ty,getAccessToken as ny,isExpired as Qi,loadProfileMap as oy,loadTokens as ry,packageSkillsDir as nu,ENGINE_VERSION as sy,projectConfigPath as iy,readProjectConfig as ay,DEFAULT_DOCS_DIR as cy,fetchManifestSummary as ly,resolveActiveProfile as dy,classifyClaudeAuth as uy,CLAUDE_CODE_SETUP_HINT as ou,resolveModelSetting as py,probeModel as hy,detectAppType as fy,playbookSkillName as my,D360AuthError as gy}from"document360-engine";async function ru(e,t){let n=[],o=$n();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${sy}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let s=uy();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ou}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ou});let i=py(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let x=await hy(e,i.model??void 0);x.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`}):x.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${x.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let c=ay(e);if(!c)return n.push({level:"fail",label:`No ${iy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??cy).replace(/\/+$/,"");n.push(c.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=c.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let b=c.appType??fy(e);if(b){let x=c.appType?"from config":"auto-detected",T=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${x})${T?` \u2192 ${my(b)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let $;try{$=dy(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=ry($.name);v?Qi(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Qi(v)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${$.name})`}),n.push($.project.workspaceId?{level:"ok",label:`Workspace: ${$.project.workspaceName??$.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let E=oy(e,$.name);E?E.projectId&&$.project.projectId&&E.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${E.projectId}) \u2260 profile projectId (${$.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(E.articles).length} articles, ${Object.keys(E.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(ey(nu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${nu()}`,fix:"Reinstall document360-writer (broken install)"});let R=qe(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${me})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${me}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!Qi(v)||v.refreshToken)){let x={profile:$.name,connection:$.connection};try{await ny(x);let F=await ty(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${F.length} project(s) visible`})}catch(F){n.push({level:"fail",label:`API call failed: ${F.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=E?.projectId??$.project.projectId;if(T&&$.project.workspaceId)try{let F=await ly(x,T,$.project.workspaceId);if(F){let G=(F.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${F.languages?.length??0} language${(F.languages?.length??0)===1?"":"s"}) \xB7 hash ${G||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${$.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(F){F instanceof gy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(F.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${F.message.slice(0,80)})`})}}return n}function su(e){let t=[""];for(let r of e){let s=r.level==="ok"?M("\u2713"):r.level==="warn"?B("\u26A0"):A("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${W(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?M(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):A(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ao(e,t){console.log(y("Running checks\u2026"));for(let n of su(await ru(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _r=qn(()=>{"use strict";wt();K();hr()});import{Command as zb}from"commander";import{createRequire as Kb}from"node:module";import{AUTH_MODES as Xb}from"document360-engine";import{input as jh}from"@inquirer/prompts";import{loginPkce as Nh,refreshTokens as Ih,toStoredTokens as Ic,clearTokens as Oh,decodeJwtClaims as Nc,isExpired as Lh,loadTokens as _h,saveTokens as Oc,resolveActiveProfile as Qo,setProfileProject as Mh,readProjectConfig as Uh}from"document360-engine";K();import{select as kh}from"@inquirer/prompts";import{resolveActiveProfile as bh,setProfileProject as $h,resolveProjectId as vh,listWorkspaces as xh}from"document360-engine";async function Gn(e,t){let n=bh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??vh(o);return{workspaces:await xh(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ec=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function js(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function zo(e,t,n,o,r){$h(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ac(e,t,n){let o;try{o=await Gn(e,n)}catch(s){return console.log(A(`Could not list workspaces: ${s.message}`)),1}let r=js(o.workspaces,t);return r?(zo(e,o.profile,o.projectId,r.id,r.name),console.log(M(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(A(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function hn(e,t){let n;try{n=await Gn(e,t)}catch(h){console.log(A(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?W("\u25CF"):" "} ${Ec(h)} ${y(h.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let c=await kh({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Ec(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);zo(e,s,r,c,p?.name),console.log(M(`\u2713 Workspace set to "${p?.name??c}" for profile "${s}".`))}K();import{select as Ch}from"@inquirer/prompts";import{resolveActiveProfile as Rh,setProfileProject as Sh,listProjects as Ph}from"document360-engine";async function gt(e,t){let n=Rh(e,t),o={profile:n.name,connection:n.connection};return{projects:await Ph(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Dc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ns(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Ko(e,t,n,o){Sh(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function jc(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(A(`Could not list projects: ${s.message}`)),1}let r=Ns(o.projects,t);return r?(Ko(e,o.profile,r.id,r.name),console.log(M(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(A(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xo(e,t){let n;try{n=await gt(e,t)}catch(p){console.log(A(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===s?W("\u25CF"):" "} ${Dc(p)} ${y(p.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Ch({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Dc(p)}${p.id===s?" (current)":""}`,value:p.id}))}),c=o.find(p=>p.id===i);Ko(e,r,i,c?.name),console.log(M(`\u2713 Project set to "${c?.name??i}" for profile "${r}". Next: pick a workspace.`))}K();import Th from"picocolors";function Eh(e=process.env){return e.FORCE_HYPERLINK==="0"||!Th.isColorSupported?!1:e.FORCE_HYPERLINK?!0:!!(e.WT_SESSION||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="WezTerm"||e.TERM_PROGRAM==="ghostty"||e.VTE_VERSION||e.KONSOLE_VERSION)}function Ah(e,t=e,n){return Eh(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Dh=/https?:\/\/[^\s\x1b]+/g;function Yn(e,t){return e.replace(Dh,n=>Ah(n,n,t))}function Lc(e){return{...Nc(e.idToken)??{},...Nc(e.accessToken)??{}}}function Jo(e){let t=Lc(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Zo(e){let t=Qo(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Nh(n,{manual:e.manual,promptForRedirect:s=>jh({message:s})},s=>console.log(Yn(s))),r=Ic(t.name,o);if(Oc(r),await Is(r,t.name,s=>console.log(y(s))),console.log(""),console.log(M(`\u2713 Logged in to "${t.name}" as ${Jo(r)}`)),console.log(y(` access token expires: ${r.expiresAt}`)),console.log(y(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Uh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await hn(process.cwd(),t.name))}catch{}}async function Is(e,t,n){let r=Lc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Qo(process.cwd(),t).project.projectId)return;let i;try{let{projects:c}=await gt(process.cwd(),t);i=c.find(p=>p.id===r)?.name}catch{}Mh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function _c(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=_h(t.name);if(!o){console.log(A(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Lh(o))if(o.refreshToken)try{let r=Ic(t.name,await Ih(n,o.refreshToken));Oc(r),console.log(M(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(B("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Mc(e){let t=Qo(process.cwd(),e.profile);Oh(t.name)?console.log(M(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Uc,writeProjectConfig as Fh,resolveActiveProfile as Wh,loadTokens as Bh,isExpired as Hh}from"document360-engine";function er(e){let t=Uc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(A("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?W("\u25CF "):" ",s=o.production?B(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=Bh(n),p=c?Hh(c)&&!c.refreshToken?B("expired"):y("logged in"):y("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Uc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(A(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Fh(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(M(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Wh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?B(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(A(n.message)),process.exitCode=1}}K();import{existsSync as qh,readdirSync as Vh,statSync as Fc}from"node:fs";import{join as Wc}from"node:path";import{apiLogDir as Gh}from"document360-engine";function Bc(){let e=Gh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!qh(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Vh(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Fc(Wc(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Fc(Wc(e,r)).size/1024).toFixed(1);console.log(` ${A(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}K();import{createSession as Yh,resolveAuth as zh,findByName as Kh,slugify as Xh,touchSession as Qh,upsertSession as Jh,resolveActiveProfile as Zh}from"document360-engine";async function Hc(e,t,n,o,r,s){let i=zh(n);i.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let c=null;try{c=Zh(e,r)}catch(v){console.error(A(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(B(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(A("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Kh(e,o);v||(console.error(A(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(y(`Resuming "${v.name}"`))}let h=Yh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),b=p??null,$=1;for await(let v of h.send(t))switch(v.type){case"session":if(!b){b=v.sessionId;let E=new Date().toISOString();Jh({uuid:b,name:Xh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:E,updatedAt:E})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(fe(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(y(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(A("agent finished with an error result"));break;case"error":console.error(""),console.error(A(`agent error: ${v.message}`)),process.exit(1)}b&&Qh(b),process.stdout.write(`
280
- `),process.exit($)}import{createInterface as nk}from"node:readline/promises";import{createSession as La,resolveAuth as ok,getSession as rk,setTitle as sk,slugify as ik,touchSession as ap,upsertSession as ak,generateTitle as ck,resolveActiveProfile as cp,resolveModelSetting as lk,readProjectConfig as dk,resolveAndPersistAppType as uk,decodeJwtClaims as ip,isExpired as pk,loadTokens as hk,isDirectiveMention as fk,stripDirectiveMention as mk,appendDirective as gk,reconcileUpgradeActions as yk,stampArticles as wk,listArticleFiles as kk,CONTENT_CAP_VERSION as bk}from"document360-engine";import{ENGINE_VERSION as tf}from"document360-engine";function Wt(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function or(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(78)}${i}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let c of Wt(`${i+1}. ${s.feature}`,76))o.push(n(c));o.push(n());for(let c of Wt(s.why,73))o.push(n(` ${c}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}var He=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed quality review."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25CF in review \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],qc=24;function Os(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?qc:Math.min(qc,Math.max(...t))}function Ls(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Wt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function ef(e,t,n){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
280
+ `),process.exit($)}import{createInterface as nk}from"node:readline/promises";import{createSession as La,resolveAuth as ok,getSession as rk,setTitle as sk,slugify as ik,touchSession as ap,upsertSession as ak,generateTitle as ck,resolveActiveProfile as cp,resolveModelSetting as lk,readProjectConfig as dk,resolveAndPersistAppType as uk,decodeJwtClaims as ip,isExpired as pk,loadTokens as hk,isDirectiveMention as fk,stripDirectiveMention as mk,appendDirective as gk,reconcileUpgradeActions as yk,stampArticles as wk,listArticleFiles as kk,CONTENT_CAP_VERSION as bk}from"document360-engine";import{ENGINE_VERSION as tf}from"document360-engine";function Wt(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function or(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(78)}${i}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let c of Wt(`${i+1}. ${s.feature}`,76))o.push(n(c));o.push(n());for(let c of Wt(s.why,73))o.push(n(` ${c}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}var He=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25CF to verify \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],qc=24;function Os(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?qc:Math.min(qc,Math.max(...t))}function Ls(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Wt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function ef(e,t,n){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
281
281
  `)}case"gap":return""}}function Vc(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of He){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Os(o.rows);for(let s of o.rows)n.push(ef(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function _s(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:tf}:void 0;for(let o of Vc(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}K();import{getSession as nf}from"document360-engine";async function Gc(e,t){let n=t.currentUuid(),o=n?nf(n):void 0;return console.log(o?y(`
282
282
  (conversation reset \u2014 "${o.name}" is still available via /resume)
283
283
  `):y(`
@@ -318,12 +318,12 @@ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await ca
318
318
  Run /update to bring the whole toolchain up, then /screenshot again.`}if(e.migrated.length===0&&e.skipped.length===0)return null;let t=[];return e.migrated.length>0&&t.push(`\u2195 Fixed ${e.migrated.length} capture spec${e.migrated.length===1?"":"s"} that cropped the screenshot without telling the annotator \u2014 their callouts were landing outside the image. Re-capture to pick up the fix.`),e.skipped.length>0&&t.push(`\u26A0 ${e.skipped.length} spec${e.skipped.length===1?"":"s"} crop${e.skipped.length===1?"s":""} to something that needs a human eye (${e.skipped.slice(0,3).map(n=>n.id).join(", ")}${e.skipped.length>3?"\u2026":""}) \u2014 /screenshot verify flags them if their callouts are off.`),t.join(`
319
319
  `)}var Jl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Gl(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Jl(n):void 0,...t?{detail:!0}:{}}}function Zn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="verify"||t==="review")return{mode:"verify",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return Gl(e.slice(1));t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return Gl(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Jl(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function $e(e,t){let n=vt(e),o=n?.captureDir??br,r=n?.outputDir??ci,s=(p,h)=>yr(p)?wr(p,h):kr(e,p,h),i=at(e),c=ur(e);return Xl(e,{scope:t}).map(({id:p,file:h})=>{let b=s(o,`${p}.spec.ts`),$=null;if(oi(b))try{$=ai(b,"utf8")}catch{}let v=Ql(e,r),E=oi(sm(v,p)),R=$===null?null:ei(i,p,$,c),x=i.shots[p]?.review,T=E&&am(x,cm(v,p))?x:void 0,F=$!==null&&hm($),G=E&&T?.verdict==="ok"?"verified":E&&T?.verdict==="rejected"?"rejected":E?"captured":$===null?"placeholder":F||R?.outcome==="skipped"?"blocked":R?.outcome==="failed"?"broken":"spec",q=$===null?void 0:ed($),Y=F?fm($):R?.reason,pe=F?"testid":R?.outcome==="skipped"?Zs(R.reason):void 0;return{id:p,file:h,state:G,...q?{mutates:q.mutates,...q.declared?{}:{undeclared:!0}}:{},...$!==null&&zl($).length>0?{unguardedWaits:zl($)}:{},...$!==null&&Yl($).length>0?{unverifiedForce:Yl($)}:{},...G==="blocked"||G==="broken"?{...Y?{reason:Y}:{},...pe?{blockedBy:pe}:{}}:{},...G==="rejected"?{...T?.reason?{reason:T.reason}:{},...T?.repaired?{repaired:!0}:{}}:{}}})}function um(e){let t=vt(e)?.outputDir??ci;return im(Ql(e,t))}function eo(e){let t=um(e),n=vt(e)?.outputDir??ci,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${lm},${dm}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Vl(ql(e));return r&&o.push(r),o.length>0?o.join(`
320
320
  `):null}function vn(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ai(o,"utf8")}catch{return null}}function Zl(e,t){let n=vt(e)?.captureDir??br;return oi(yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`))}function pm(e,t,n){let o=[n.trim()];for(let r=t+1;r<e.length;r++){let s=/^\s*\/\/\s?(.*)$/.exec(e[r]);if(!s)break;let i=s[1].trim();if(!i||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(i)||(o.push(i),o.join(" ").length>400))break}return o.join(" ")}function ed(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(c)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let c=pm(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:c||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),i=/\.fill\(/.test(e);return{mutates:r||i&&s,declared:!1}}function hm(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function fm(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"a stable data-testid"} \u2014 the spec is skipped at compile time, so no capture run can produce this shot. /screenshot checklist builds the hand-off.`}function td(e){return e.split(/\r?\n/).map(t=>{if(/^\s*\*/.test(t))return"";let n=/(?<!:)\/\//.exec(t);return n?t.slice(0,n.index):t})}function Yl(e,t=10){let n=td(e),o=[];for(let[r,s]of n.entries())/\.click\s*\([^)]*force\s*:\s*true/.test(s)&&(/test\.skip\s*\(/.test(n.slice(r+1,r+1+t).join(`
321
- `))||o.push(r+1));return o}function zl(e){let t=[],n=td(e);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let i=o+1;i<n.length&&!/;\s*$/.test(s.trim())&&i<o+4;i++)s+=n[i];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function nd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function od(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ed(ai(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var mm=["captured","verified","rejected"],gm=e=>mm.includes(e);function $r(e){return[...new Set(e.filter(t=>gm(t.state)).map(t=>t.file))].sort()}function vr(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${ye("\u26A0",D.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed quality review:`,...t.map(o=>` ${D.magenta(o.id.padEnd(n))} ${D.gray(xn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${D.bold("/screenshot capture --failed")}`].join(`
321
+ `))||o.push(r+1));return o}function zl(e){let t=[],n=td(e);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let i=o+1;i<n.length&&!/;\s*$/.test(s.trim())&&i<o+4;i++)s+=n[i];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function nd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function od(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return ed(ai(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var mm=["captured","verified","rejected"],gm=e=>mm.includes(e);function $r(e){return[...new Set(e.filter(t=>gm(t.state)).map(t=>t.file))].sort()}function vr(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${ye("\u26A0",D.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${D.magenta(o.id.padEnd(n))} ${D.gray(xn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${D.bold("/screenshot capture --failed")}`].join(`
322
322
  `)}var ym={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},wm={placeholder:D.gray,spec:D.yellow,blocked:D.cyan,broken:D.red,captured:D.blue,verified:D.green,rejected:D.magenta},rd=` ${D.green("\u2714 verified")} ${D.blue("\u25CF to verify")} ${D.yellow("\u25D0 ready")} ${D.magenta("\u2691 rejected")} ${D.cyan("\u2298 blocked")} ${D.red("\u2717 broken")} ${D.gray("\u25CB to spec")}`;function ye(e,t=n=>n){return`${t(e)} `}function xn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function xr(e){let t=xn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function to(e){let t=new Map;for(let n of e){if(n.state!=="blocked")continue;let o=(n.reason??"No reason recorded \u2014 re-run this capture to find out why.").replace(/\s+/g," ").trim(),r=n.blockedBy??"data",s=xr(o),i=`${r} ${s.toLowerCase()}`,c=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,c),c.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function sd(e){let t=to(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((c,p)=>c+p.ids.length,0);r.push(` ${D.bold("Stage this data")} ${D.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let c of n.slice(0,i)){let p=Wt(c.reason,86);r.push(` ${D.cyan($t(`${c.ids.length}\xD7`,4))} ${p[0]??""}`);for(let b of p.slice(1))r.push(` ${b}`);let h=c.ids.slice(0,4).join(" \xB7 ");r.push(D.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(D.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,c)=>i+c.ids.length,0);r.push(` ${ye("\u2298",D.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${D.bold("/screenshot checklist")} builds the hand-off.`)}return r}function id(e,t){let n=e.filter(i=>(i.unguardedWaits?.length??0)>0),o=e.filter(i=>i.undeclared);if(n.length===0&&o.length===0)return[];let r=["",` ${ye("\u26A0",D.yellow)}Some specs were written before later reliability fixes:`],s=(i,c)=>` ${i.slice(0,8).map(c).join(" \xB7 ")}${i.length>8?` \xB7 +${i.length-8} more`:""}`;if(n.length>0){let i=n.length;r.push(D.gray(` ${i} crash${i===1?"es":""} instead of telling you what to stage when the data ${i===1?"it needs":"they need"} is missing`)),t&&r.push(D.gray(s(n,c=>`${c.id}:${c.unguardedWaits.join(",")}`)))}if(o.length>0){let i=o.length,c=o.filter(p=>p.mutates).length;r.push(D.gray(` ${i} do${i===1?"es":""} not say whether ${i===1?"it changes":"they change"} data in your app`+(c>0?`, so ${c===1?"one is":`${c} are`} left out of bulk runs to be safe`:""))),t&&r.push(D.gray(s(o,p=>p.id)))}return r.push(D.gray(` Re-write them all with the current rules: ${D.bold("/screenshot author --all")}`)),r}function ad(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ye("\u26A0",D.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+D.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),D.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),D.gray(` Re-author to check what the click did: ${D.bold("/screenshot author <id>")}`)]}var mr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),$t=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function cd(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var km=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),bm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function $m(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return bm.has(r)?r.toUpperCase():o>0&&km.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ri(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:$m(t?t[2]:e)}}function vm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Kl(e,t,n){let o=t>0?Math.round(e/t*n):0;return D.green("\u2588".repeat(o))+D.gray("\u2591".repeat(Math.max(0,n-o)))}function xm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?D.green(o):n>0?D.yellow(o):D.gray(o)}function ld(e,t){let n=new Map;for(let o of e){let r=cd(o.file,t),s=n.get(r)??[];n.has(r)||n.set(r,s),s.push(o)}return[...n.keys()].sort().map(o=>[o,n.get(o)])}function Cm(e,t){let n=(J,re)=>J.filter(le=>le.state===re).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),c=n(e,"spec"),p=n(e,"blocked"),h=n(e,"broken"),b=n(e,"placeholder"),$=new Set(e.map(J=>J.file)).size,v=ld(e,t),E=[];E.push(` ${D.bold("Screenshots")} ${D.green(`${r}/${o} verified`)} ${D.gray("\xB7")} ${s>0?D.blue(`${s} to verify`):D.gray("0 to verify")}`+(i>0?` ${D.gray("\xB7")} ${D.magenta(`${i} rejected`)}`:"")+` ${D.gray("\xB7")} ${c>0?D.yellow(`${c} ready`):D.gray("0 ready")}`+(p>0?` ${D.gray("\xB7")} ${D.cyan(`${p} blocked`)}`:"")+(h>0?` ${D.gray("\xB7")} ${D.red(`${h} broken`)}`:"")+` ${D.gray("\xB7")} ${b>0?D.red(`${b} to spec`):D.gray("0 to spec")} `+D.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Kl(r,o,32)}] ${D.bold(`${R}%`)}`),E.push("");let x=v.map(([J])=>ri(J)),T=Math.min(32,Math.max(7,...x.map(J=>J.name.length))),F=J=>J.length>T?`${J.slice(0,T-1)}\u2026`:mr(J,T),G=[...s>0?[{head:"To verify",w:9,state:"captured",color:D.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:D.magenta}]:[],{head:"Ready",w:5,state:"spec",color:D.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:D.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:D.red}]:[],{head:"To spec",w:7,state:"placeholder",color:D.red}];E.push(D.gray(` ${mr("#",2)} ${mr("Chapter",T)} ${$t("Verified",8)} ${G.map(J=>$t(J.head,J.w)).join(" ")} Progress`));for(let[J,[,re]]of v.entries()){let le=n(re,"verified"),ae=re.length,{num:Ze,name:Ue}=x[J],ze=le===ae,lt=F(Ue),Pt=G.map(dt=>{let Yt=n(re,dt.state);return Yt>0?dt.color($t(String(Yt),dt.w)):D.gray($t("\u2014",dt.w))}).join(" ");E.push(` ${D.cyan(mr(Ze,2))} ${ze?D.green(lt):le>0?lt:D.gray(lt)} ${ze?D.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Kl(le,ae,10)} ${xm(le,ae)}`)}E.push("");let q=h>0?` ${D.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",Y=e.filter(J=>J.state==="spec"&&J.mutates).length,pe=c>Y;if(b>0)E.push(` ${ye("\u2192",D.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${D.bold("/screenshot author --all")}${q}`);else if(c>0&&(pe||s===0)){let J=Y>0?D.gray(` \u2014 ${c-Y} in one go; ${Y} write${Y===1?"s":""} real data and run${Y===1?"s":""} one at a time`):"";E.push(` ${ye("\u2192",D.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${D.bold("/screenshot capture")}${J}${q}`)}else if(s>0&&c>0)E.push(` ${ye("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 no browser needed")+D.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+q);else if(p>0)E.push(` ${ye("\u2192",D.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${D.bold("/screenshot capture --blocked")}${q}`);else if(h>0)E.push(` ${ye("\u2192",D.red)}${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)E.push(` ${ye("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let J=e.filter(re=>re.state==="rejected"&&re.repaired).length;E.push(` ${ye("\u2691",D.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${D.bold("/screenshot capture --failed")}`:`see the reasons below, then ${D.bold("/screenshot capture --failed")}`))}else E.push(` ${ye("\u2713",D.green)}all ${o} verified \u2014 ${D.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let J=v.filter(([,re])=>re.every(le=>le.state!=="verified")).map(([re])=>{let{num:le,name:ae}=ri(re);return le?`${le} ${ae}`:ae});J.length>0&&E.push(D.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return E.push(...sd(e),...ad(e),...id(e,!1)),E.push(""),E.push(rd),E.push(D.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Rm(e,t,n){let o=new Set(e.map(c=>c.file)),r=e.filter(c=>c.state==="verified").length,s=e.filter(c=>c.state==="captured").length,i=[` ${D.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${D.green(`${r} verified`)}${s>0?D.blue(` \xB7 ${s} to verify`):""}${n?D.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ld(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=ri(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${D.bold(v)} ${D.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let x=vm(R.file),T=E.get(x)??[];E.has(x)||E.set(x,T),T.push(R)}for(let R of[...E.keys()].sort()){i.push(D.gray(` ${R}`));for(let x of E.get(R)){let T=wm[x.state];if(i.push(` ${ye(ym[x.state],T)}${T(x.id)}`),(x.state==="blocked"||x.state==="broken"||x.state==="rejected")&&x.reason){for(let F of Wt(xn(x.reason),84))i.push(D.gray(` ${F}`));x.state==="rejected"&&i.push(D.gray(` ${x.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...sd(e),...ad(e),...id(e,!0)),i.push("",rd),i}function Cr(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??li;return t?.detail||n?Rm(e,o,n):Cm(e,o)}function di(e,t){if(!t||!/^\d+$/.test(t))return t;let n=vt(e)?.docsDir??li,o=String(Number(t));for(let{file:r}of Xl(e)){let s=cd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function dd(e,t){let r=e.map(c=>" ".repeat(c.depth)+c.label),s=Math.max(0,...e.map((c,p)=>c.note?fr(r[p]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((c,p)=>{let h=r[p];if(!c.note)return{head:h,note:""};let b=Math.max(2,i+2-fr(h)),$=c.note.trim(),v=t-fr(h)-b;return{head:h+" ".repeat(b),note:v>1&&fr($)>v?`${$.slice(0,v-1)}\u2026`:$}})}function Sm(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function gr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:c}=Sm(s.file),p=o.get(i)??new Map;o.set(i,p);let h=p.get(c)??[];p.set(c,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),c=[...i.values()].flat().filter(r).map(h=>h.id),p=c.length>0;p&&e.push({kind:"category",action:n,label:`${s} (${c.length})`,ids:c,depth:1});for(let h of[...i.keys()].sort()){let b=i.get(h),$=b.filter(r).map(R=>R.id),v=$.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${$.length})`,ids:$,depth:p?2:1});let E=(p?1:0)+(v?1:0)+1;for(let R of b){let x=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:E,...x?{note:x}:{}})}}}}function ni(e){return e?xn(e):""}function ui(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ni(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ni(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((c,p)=>c.id.localeCompare(p.id))){let c=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${c} \u2014 ${ni(i.reason)}`})}}function ud(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),gr(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),gr(o,n,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var si=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is."," And guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after page.screenshot()/dumpAnnotations() runs with the image already on disk, so a throw"," there turns a successful capture into a reported failure and the shot is thrown away"," (measured: a valid .raw.png plus annotations, reported broken). Guard with isVisible()/"," isEnabled() and click best-effort \u2014 by then there is nothing left to skip.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
323
323
  `);function Pm(e){return e.outcome==="failed"?["REPAIR \u2014 the existing spec FAILED its last capture with:",e.reason,'Read the existing spec first and fix that failure specifically. A "strict mode violation" means the',"locator matched 2+ elements \u2014 scope it to a stable container or take .first(); a click timeout means","the element was absent or unreachable \u2014 if that's because the data isn't staged, the spec must","test.skip with a reason naming what to stage, not time out. Re-verify every selector you keep","against the product source; do not re-emit the same locator and hope."]:["REPAIR \u2014 the existing spec SKIPPED its last capture with:",e.reason,"You are being asked to re-author a shot that SKIPPED, and that is itself the signal: the normal","response to a blocked shot is to STAGE the data, not to rewrite the spec. So treat that reason as","SUSPECT \u2014 assume it is a FALSE skip until you have proved otherwise. Two things make a guard report",'"not staged" when the data exists:',"1. THE TARGET IS NOT RENDERED. Trace the path from the entry point to the element you finally need"," and confirm every intermediate container is OPENED. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM, so the"," count is zero and the skip fires \u2014 for data sitting one click away. Expanding is a step to SCRIPT.","2. THE SELECTOR IS TOO NARROW. If you filtered past a decoy, count the UNNARROWED set and put the",' number in the reason ("Found 6 folder roll-ups but no endpoint-level score"), so the next reader'," can tell absent data from an over-narrow selector without opening the app.","A spec that satisfies every rule in this skill and still cannot reach its target is NOT correct.",'"No changes needed" is earned by tracing reachability end to end \u2014 not by checking conformance.']}var ii="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing \u2014 a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function pd(e,t){let n=e.paths,o=n.filter(i=>t?.get(i)?.outcome==="failed"),r=n.filter(i=>t?.get(i)?.outcome==="skipped"),s=i=>`- ${i}: ${t.get(i).reason.replace(/\s+/g," ").trim()}`;return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(i=>`- ${i}`).join(`
324
324
  `),"",...o.length>0?["REPAIR \u2014 these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...o.map(s),""]:[],...r.length>0?["REPAIR \u2014 these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away \u2014 expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...r.map(s),""]:[],"For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids.",si,ii].join(`
325
325
  `)}async function Rr(e,t,n){let o=Zn(e),r=eo(t?.cwd??process.cwd());if(r&&console.log(D.gray(r)),o.mode==="list"){let p=t?.cwd??process.cwd(),h=di(p,o.scope),b=vt(p)?.docsDir??li,$=$e(p,h);for(let v of Cr($,{scope:h,detail:o.detail,docsDir:b}))console.log(v);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",si,ii,...n?.prior?["",...Pm(n.prior)]:[]].join(`
326
- `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`,si,ii].join(`
326
+ `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,si,ii].join(`
327
327
  `),c=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:c}}var no=3;function pi(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
328
328
  `)}var hd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function hi(e){return e.filter(t=>t.path!==null&&t.status in hd&&!t.link).map(t=>({path:t.path,label:hd[t.status]}))}function Pr(e){let t=hi(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function Tr(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function Er(e){return e.filter(t=>t.link).length}function fi(e,t){try{let n=Om(e,Lm(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=_m(Tm(Em(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Mm(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function wd(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,c)=>i.path.localeCompare(c.path));n.push({kind:"category",label:`${Mm(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let c=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:c,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function oo(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
329
329
  `)}function mi(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),i=e.reduce((v,E)=>v+o(E),0),c=r.reduce((v,E)=>v+o(E),0),p=n==="api"?`${Ee(e.reduce((v,E)=>v+E.costUsd,0))} total`:bt(e.reduce((v,E)=>v+E.outputTokens,0)),h=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=v=>`${v} article${v===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${b(i)} (${h}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${c}/${b(i)} (${h}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)$.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return $}async function xt(e,t){let{model:n}=Nm(e.cwd,"standard"),o=async(r,s)=>{let i=Dm(r);console.log(y(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${no} agents at once) on ${n}\u2026`)),s||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let c=!1;for await(let p of Im({cwd:e.cwd,partitions:i,promptFor:h=>oo(h.paths),concurrency:no,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(y(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(M(` \u2713 ${p.label}`)):console.log(A(` \u2717 ${p.label}`));else if(p.type==="run_done"){c=p.aborted,console.log("");let h=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of mi(p.results,i,h))console.log(p.ok?M($):B($));let b=fi(e.cwd,e.profileName);b&&console.log(y(b));try{let $=md(await fd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(y($))}catch{}try{let $=yd(await gd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(y($))}catch{}}return c};try{if(!await o(t,!1)){let s=await gi(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(A(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ar(e,t,n){let o=jm(e,n);if(o.length===0)return[];let r=new Set(hi((await Sr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function gi(e,t,n){try{let o=new Set(n),r=await Sr({cwd:e,profileName:t});return hi(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function kd(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=$e(r),i=$r(s);if(i.length===0)return console.log(y("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let c=vr(s);return c&&console.log(c),t?await xt(t,i):{kind:"forward-to-agent",prompt:oo(i),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ar(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(M("\u2713 All related articles are already published.")),{kind:"continue"}):await xt(t,r)}if(o==="--all"){console.log(y("Checking what needs publishing\u2026"));try{let r=await Sr({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:i}=Pr(r.entries),c=Er(r.entries),p=e.includes("--force")&&i.length>0;c>0&&console.log(B(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),i.length>0&&!p&&console.log(B(Tr(i.length)));let h=p?[...s,...i]:s;if(h.length===0){if(i.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(M(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=md(await fd({cwd:t.cwd,profileName:t.profileName}));b&&console.log(y(b));let $=yd(await gd({cwd:t.cwd,profileName:t.profileName}));$&&console.log(y($))}catch{}return{kind:"continue"}}return t?await xt(t,h.map(b=>b.path)):{kind:"forward-to-agent",prompt:oo(h.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(A(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(y("Checking what needs publishing\u2026"));let r;try{let s=await Sr({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:c}=Pr(s.entries);r=i;let p=Er(s.entries);if(p>0&&console.log(B(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&console.log(B(Tr(c.length))),r.length===0&&c.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(A(`Could not compute sync status: ${s.message}`)),console.log(y("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(M("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(y(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${y(`(${s.label})`)}`);return console.log(y("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Am({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}if(o==="--all")return await xt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:pi(o),display:`/publish ${o}`}}async function ro(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words \u2014 never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
@@ -352,7 +352,7 @@ Articles:
352
352
  `)}var Yi="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Gd(e,t){let n=t?.cwd??process.cwd();if(!Hg(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Vi(e);if(!r&&qi(n)===0)return console.log(y(Yi)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Gi(r,o),display:s}}K();import{search as qg}from"@inquirer/prompts";import{findByName as Vg,getSession as Gg,listSessions as Yg,relativeTime as zd}from"document360-engine";async function Kd(e,t){let n=Yg(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(y("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Vg(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(A(`No session matches "${o}".`)),Yd(n),{kind:"continue"})}if(!process.stdin.isTTY)return Yd(n),console.log(y("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>qg({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(c=>!i||c.name.toLowerCase().includes(i)||c.firstPrompt.toLowerCase().includes(i)).map(c=>({name:`${c.name} ${zd(c.updatedAt)}`,value:c.uuid,description:c.firstPrompt.slice(0,100)}))}})),r=Gg(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Yd(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${y(zd(t.updatedAt))}`),console.log(` ${y(t.firstPrompt.slice(0,80))}`);console.log("")}K();import{renameSession as zg}from"document360-engine";function zi(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function Xd(e,t){let n=zi(e.join(" "));if(!n)return console.log(A("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(zg(o,n)?console.log(M(`\u2713 Session renamed to "${n}"`)):console.log(A("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(M(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Qd,readProjectConfig as Kg,writeProjectConfig as Xg}from"document360-engine";K();function Ki(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Kg(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Qd().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Xg(o,e),null):`Unknown environment "${r}". Known: ${Qd().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Jd(e,t){let n=e[0];if(!n)return er(t.cwd),{kind:"continue"};if(n==="add"){let o=Ki(t.cwd,e[1],e[2]);return o?(console.log(A(o)),{kind:"continue"}):(console.log(M(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return tr(t.cwd,n),nr(t.cwd,n),console.log(y(" Restarting agent for the new profile\u2026")),{kind:"clear"}}K();import{select as Qg}from"@inquirer/prompts";import{readProjectConfig as Jg,readUserConfig as Zd,resolveModelSetting as Xi,writeUserConfig as eu}from"document360-engine";var Je=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Lr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Je.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Zg(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function io(e,t){let n=()=>Xi(e).model;if(t==="default"){let s=Zd();return s.defaultModel?(delete s.defaultModel,eu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xi(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}eu({...Zd(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Jg(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function tu(e,t){let n=e[0]?.trim();if(!n){let i=Xi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${W(i.model)}${i.source==="auto"?y(" (auto)"):""}`),console.log(y(` source: ${Zg(i)}`)),console.log(y(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let c=Lr(i),p;try{p=await t.withPausedInput(()=>Qg({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Je[c].value,choices:Je.map((v,E)=>({name:`${v.label}${E===c?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}let{lines:h,changed:b,effective:$}=io(t.cwd,p??"default");for(let v of h)console.log(v.startsWith("\u26A0")?B(v):v.startsWith("\u2713")?M(v):y(v));return b&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=io(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?B(i):i.startsWith("\u2713")?M(i):y(i));return r&&await t.setModel(s),{kind:"continue"}}_r();async function au(e,t){return await t.withPausedInput(()=>hn(t.cwd)),{kind:"clear"}}async function cu(e,t){return await t.withPausedInput(()=>Xo(t.cwd,t.profileName)),{kind:"clear"}}K();import{resolveActiveProfile as yy}from"document360-engine";async function lu(e,t){let n=!1;try{n=yy(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(y("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}K();var du=async(e,t)=>{try{await t.withPausedInput(()=>Zo({}))}catch(n){console.log(A(`Login failed: ${n.message}`))}return{kind:"continue"}};K();import{resolveActiveProfile as wy,clearTokens as ky,clearProfileProject as by}from"document360-engine";async function uu(e,t){let n;try{n=wy(t.cwd,t.profileName).name}catch(r){return console.log(A(r.message)),{kind:"continue"}}let o=ky(n);return by(t.cwd,n),console.log(o?M(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):y(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(y("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as hu}from"node:child_process";import{existsSync as Zi,readFileSync as Ji,statSync as Ty}from"node:fs";import{homedir as Ey}from"node:os";import{basename as Ay,join as po}from"node:path";import{readProjectConfig as Dy,DEFAULT_OUTPUT_DIR as jy,existingAnnotatedShotPath as Ny,resolveOutputDir as Iy}from"document360-engine";import Ae from"picocolors";import{annotationsPath as $y,resolveOutputDir as vy,readProjectConfig as xy,DEFAULT_OUTPUT_DIR as Cy,existingAnnotatedShotPath as Ry}from"document360-engine";function Sy(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function co(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function qt(e,t){let n=vy(e,xy(e)?.outputDir??Cy),o=new Map($e(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let c=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(Ry(n,i))}`,` facts: ${r($y(n,i))}`,` article: ${c}`].join(`
353
353
  `)}).join(`
354
354
  `);return[`Run the review-screenshots skill over ${t.length} newly captured screenshot${t.length===1?"":"s"}.`,"","For EACH shot below:","1. READ THE IMAGE FILE. Actually look at the picture \u2014 this judgment cannot be made from the spec"," source or the JSON alone.","2. Read its facts JSON (the `capture` block records what the capture observed: image dimensions,"," crop origin, whether the origin was inferred rather than declared, selectors that never resolved,"," and boxes that fell outside the frame).","3. Read the article to see what the placeholder promises the reader at that point.","4. Record a verdict with d360_verify_screenshot \u2014 every shot gets exactly one call.",' On "rejected": give a one-line plain-language reason, then FIX THE SPEC that produced it and pass'," repaired: true. Do not re-run the capture yourself; the user does that.","",s,"","Then report to the user briefly: ONE line per rejected shot naming the defect in plain words and what","you changed. Do NOT state counts, totals, or the re-capture command \u2014 an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
355
- `)}function lo(e){return`${ye("\u2192",Ae.blue)}Reviewing ${e} new screenshot${e===1?"":"s"} for quality (reading each image)\u2026`}var Py=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function uo(e,t){if(t.length===0)return[];let n=at(e).shots,o=[],r=[],s=[];for(let c of t){let p=n[c]?.review;p?p.verdict==="ok"?o.push(c):r.push({id:c,reason:p.reason??"no reason recorded",repaired:!!p.repaired}):s.push(c)}let i=[""];if(i.push(`${ye("\u2714",Ae.green)}${Ae.green(`${o.length} verified`)}`+(r.length>0?` ${Ae.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Ae.yellow(`? ${s.length} not reviewed`)}`:"")+Ae.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let c=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${Ae.magenta(h.id.padEnd(c))} ${Ae.gray(Py(h.reason))}`);let p=r.filter(h=>h.repaired).length;i.push(`${ye("\u2192",Ae.magenta)}Re-capture the ${r.length} flagged: ${Ae.bold("/screenshot capture --failed")}`+(p<r.length?Ae.gray(` (${r.length-p} still need${r.length-p===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ye("\u26A0",Ae.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Ae.bold("/screenshot verify")} again.`),i}async function pu(e,t){let n=t?.cwd??process.cwd(),o=eo(n);o&&console.log(o);let r=$e(n),s=Sy(e);if(s.mode==="single"){let c=r.find(p=>p.id===s.id);return c?["captured","verified","rejected"].includes(c.state)?{kind:"forward-to-agent",prompt:qt(n,[s.id]),display:`/screenshot verify ${s.id}`}:(console.log(`"${s.id}" has no captured image yet \u2014 /screenshot capture ${s.id} takes the shot first.`),{kind:"continue"}):(console.log(`No screenshot placeholder called "${s.id}". /screenshot list shows them all.`),{kind:"continue"})}let i=co(r);if(i.length===0){let c=r.filter(h=>h.state==="verified").length,p=r.filter(h=>h.state==="rejected").length;return console.log(p>0?`Nothing awaiting review. ${p} shot${p===1?"":"s"} failed review \u2014 re-capture with: /screenshot capture --failed`:c>0?`All ${c} captured shot${c===1?" is":"s are"} already verified.`:"No captured screenshots to review yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:qt(n,i),display:"/screenshot verify"}}var Oy=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ea(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--blocked")||e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:!t&&n?{mode:"blocked"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Oy(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function ho(e,t){let n=$e(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function fu(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||s.state==="verified"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),gr(o,t,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,c)=>i.id.localeCompare(c.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25CF in review \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function ta(e,t){let n=new Set(t.filter(r=>r.state!=="placeholder").map(r=>r.id)),o=t.filter(r=>r.state==="rejected").map(r=>r.id);return[...new Set([...Il(e).filter(r=>n.has(r)),...o])].sort()}function na(e,t){let n=e.length;if(n===0)return null;let o=to(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
355
+ `)}function lo(e){return`${ye("\u2192",Ae.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var Py=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function uo(e,t){if(t.length===0)return[];let n=at(e).shots,o=[],r=[],s=[];for(let c of t){let p=n[c]?.review;p?p.verdict==="ok"?o.push(c):r.push({id:c,reason:p.reason??"no reason recorded",repaired:!!p.repaired}):s.push(c)}let i=[""];if(i.push(`${ye("\u2714",Ae.green)}${Ae.green(`${o.length} verified`)}`+(r.length>0?` ${Ae.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Ae.yellow(`? ${s.length} not verified`)}`:"")+Ae.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let c=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${Ae.magenta(h.id.padEnd(c))} ${Ae.gray(Py(h.reason))}`);let p=r.filter(h=>h.repaired).length;i.push(`${ye("\u2192",Ae.magenta)}Re-capture the ${r.length} flagged: ${Ae.bold("/screenshot capture --failed")}`+(p<r.length?Ae.gray(` (${r.length-p} still need${r.length-p===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ye("\u26A0",Ae.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Ae.bold("/screenshot verify")} again.`),i}async function pu(e,t){let n=t?.cwd??process.cwd(),o=eo(n);o&&console.log(o);let r=$e(n),s=Sy(e);if(s.mode==="single"){let c=r.find(p=>p.id===s.id);return c?["captured","verified","rejected"].includes(c.state)?{kind:"forward-to-agent",prompt:qt(n,[s.id]),display:`/screenshot verify ${s.id}`}:(console.log(`"${s.id}" has no captured image yet \u2014 /screenshot capture ${s.id} takes the shot first.`),{kind:"continue"}):(console.log(`No screenshot placeholder called "${s.id}". /screenshot list shows them all.`),{kind:"continue"})}let i=co(r);if(i.length===0){let c=r.filter(h=>h.state==="verified").length,p=r.filter(h=>h.state==="rejected").length;return console.log(p>0?`Nothing left to verify. ${p} shot${p===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:c>0?`All ${c} captured shot${c===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:qt(n,i),display:"/screenshot verify"}}var Oy=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ea(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--blocked")||e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:!t&&n?{mode:"blocked"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Oy(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function ho(e,t){let n=$e(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function fu(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||s.state==="verified"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),gr(o,t,"capture"),ui(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,c)=>i.id.localeCompare(c.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25CF to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function ta(e,t){let n=new Set(t.filter(r=>r.state!=="placeholder").map(r=>r.id)),o=t.filter(r=>r.state==="rejected").map(r=>r.id);return[...new Set([...Il(e).filter(r=>n.has(r)),...o])].sort()}function na(e,t){let n=e.length;if(n===0)return null;let o=to(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
356
356
  `)}function Ly(e,t){let n=Dy(e)?.outputDir??jy;return Ny(Iy(e,n),t)}function oa(e,t,n,o){let r=Ly(e,t);return Zi(r)&&Ty(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function mu(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var _y=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function gu(e){let t=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),n=t.filter(s=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(s)&&!/^Error Context:/i.test(s)),o=[...new Set(t.filter(s=>_y.test(s)).map(s=>s.replace(/^-\s*/,"")))].slice(0,2),r=t.find(s=>/locator resolved to/i.test(s))?.replace(/^-\s*/,"");return n.length>0||o.length>0?[...new Set([...n].slice(0,2)),...o,...r&&o.length>0?[r.length>120?`${r.slice(0,119)}\u2026`:r]:[]].join(`
357
357
  `):ra(e)}function ra(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
358
358
  `)}var My=/^[A-Za-z0-9._-]+$/;function sa(e){return new Promise((t,n)=>{if(!My.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=hu(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function yu(e,t=Ey()){try{let n=JSON.parse(Ji(po(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Ji(po(e,"package.json"),"utf8")).name}catch{}o||=Ay(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Zi(po(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function wu(e){return new Promise((t,n)=>{let o=hu("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function ia(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function ku(e){try{let t=JSON.parse(Ji(po(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),n=Object.keys(t.profiles??{}),o=t.defaultProfile??(n.length===1?n[0]:n.includes("staging")?"staging":n[0]),r=o?t.profiles?.[o]:void 0;return{production:!!r?.production,name:o,url:r?.connection?.startUrl}}catch{return{production:!1}}}function Ur(e){return Zi(po(e,".d360-writer","capture.json"))}function aa(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
@@ -375,10 +375,10 @@ ${n.map(h=>` \u25CB ${h.title}`).join(`
375
375
  `):null}function Yu(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Gr(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
376
376
  ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
377
377
  `):null}async function zu(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Yr(n,e.slice(1).join(" ").trim());return console.log(r.ok?M(r.line):B(r.line)),{kind:"continue"}}let o=Sa(n);console.log(W(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var Ku={help:_s,"?":_s,clear:Gc,exit:Ms,quit:Ms,init:Hs,mcp:dr,publish:kd,audit:ro,discover:bd,scope:vd,pull:Nd,resolve:Ad,convert:Id,write:Fd,draft:Vd,document:Gd,resume:Kd,rename:Xd,profile:Jd,model:tu,doctor:ao,workspace:au,project:cu,"allow-prod":lu,login:du,logout:uu,screenshot:async(e,t)=>{let n=Zn(e);return n.mode==="capture"?ca(n.rest,t):n.mode==="verify"?pu(n.rest,t):n.mode==="checklist"?Sn():Rr(e,t)},capture:ca,"capture-setup":Sn,devhints:ol,inbox:Pu,"catch-up":Tu,update:Au,reset:Ou,check:Lu,review:Fu,reorder:Wu,structure:Uu,genre:Vr,roadmap:zu};function Xu(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}wt();var jw="Or just tell me what to write or update.",Nw='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function ve(e){return e===1?"":"s"}function zr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function yo(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Iw={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function Ow(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Iw,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ve(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ve(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
378
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ve(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ve(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ve(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ve(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ve(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ve(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ve(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ve(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ve(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ve(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ve(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Qu(e){return e.find(t=>t.lead||t.picker)??null}function Ta(e,t){let n=Qu(t),o=[];n?.lead?o.push(yo(n.lead)):n?.picker&&o.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let c of t.filter(p=>p!==n).slice(0,2))c.follow&&o.push(c.follow);let r=o.join(" "),s=t.filter(c=>c.bullet).map(c=>{let p=c.lead?.kind==="cmd"?c.lead.cmd:null;return` \u2022 ${c.bullet}${p&&!r.includes(p)?` \u2014 ${p}`:""}`}),i=[[e,...s].join(`
378
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ve(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ve(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ve(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ve(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ve(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ve(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ve(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ve(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ve(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ve(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ve(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Qu(e){return e.find(t=>t.lead||t.picker)??null}function Ta(e,t){let n=Qu(t),o=[];n?.lead?o.push(yo(n.lead)):n?.picker&&o.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let c of t.filter(p=>p!==n).slice(0,2))c.follow&&o.push(c.follow);let r=o.join(" "),s=t.filter(c=>c.bullet).map(c=>{let p=c.lead?.kind==="cmd"?c.lead.cmd:null;return` \u2022 ${c.bullet}${p&&!r.includes(p)?` \u2014 ${p}`:""}`}),i=[[e,...s].join(`
379
379
  `)];return o.length&&i.push(o.join(" ")),i.push(jw),i.join(`
380
380
 
381
- `)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Ow(e);if(!e.hasDocs){let s=Qu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ta("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:Nw,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ve(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ve(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ve(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Ea,readdirSync as Da}from"node:fs";import{spawnSync as Lw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as Zu,resolveActiveProfile as ep,loadTokens as _w,isExpired as Mw,loadProfileMap as tp,localAheadPaths as Uw,loadKnownConflicts as Fw,readDocsPlan as Ww,devHintsGuidePath as Bw,DEFAULT_DOCS_DIR as Aa,roadmapProgress as Hw,listRoadmap as qw,readProductBriefState as Vw,reconcileCommitRequest as Gw}from"document360-engine";wt();function Ju(e){try{return Da(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ja(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ju(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ju(Kr(e,o)))}function Na(e,t){try{let n=Zu(e);if(!n)return!1;let o=ep(e,t),r=tp(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Aa).replace(/\/+$/,""));return!!(Ea(s)&&Da(s).length>0||Ea(Bw(e)))}catch{return!1}}function ko(e,t,n){try{let o=Zu(e);if(!o)return null;let r=ep(e,t),s=_w(r.name),i=!!s&&(!Mw(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=tp(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Aa).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Da(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Lw("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ae.status===0&&(v=parseInt((ae.stdout||"").trim(),10)||0)}catch{}let E=0;try{let ae=Ww(e);if(ae.length>0){let Ze=(o.docsDir??Aa).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Ue=>Ue.path)).length}}catch{}let R=fo(e),x=mo({...R,directives:0}),T=Uw(e,t),F=new Set(Fw(e,r.name)),G=T.filter(ae=>F.has(ae)).length,q=T.length-G,Y=qe(e),pe=Hw(e),J=Gw(e,new Date().toISOString()),re=Vw(e),le=re?{status:re.status,openQuestions:re.openQuestions}:null;return!le&&$&&qw(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(le={status:"pending",openQuestions:0}),{ready:i&&c&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:x,directives:R.directives,behind:v,pendingWrites:E,localAhead:q,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:me,builderStarted:it(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:le,uncommittedDocs:J.dirty.length}}catch{return null}}K();var Yw={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},op=160,Oa=200,rp=40;function Le(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function np(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${Le(typeof r=="string"?r:JSON.stringify(r),rp)}`);return t.length>4&&n.push("\u2026"),Le(n.join(", "),op)}var zw=new Set(["file_path","notebook_path"]);function Kw(e,t){if(!t)return e;let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var Rt=e=>typeof e=="string"&&e?e:null,Ia=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Xw(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Qw(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Rt(t.title);if(!o)return null;let r=Xw(t.local_path);return n("Create article",`"${Le(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=Ia(t.article_id);return n("Update article",o?`"${Le(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ia(t.article_id)?`id ${Ia(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",Rt(t.name)?`"${Le(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?Le(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xr(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),c=i.join("__");if(s==="document360"){let b=Qw(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:np(t)}}let o=Yw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&zw.has(o)?Kw(r,n):r;return{title:e,sep:"",arg:Le(s,op)}}return{title:e,sep:"",arg:np(t)}}function Jw(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function Zw(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Jw).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Le(r,Oa))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Le(String(r),rp)}`);return n.length>0?[Le(n.join(" \xB7 "),Oa)]:null}return null}function ek(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function tk(e,t,n){switch(e){case"d360_create_article":{let o=ek(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=Rt(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${Le(o[0],120)}`:""}`]}default:return null}}function Qr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
381
+ `)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Ow(e);if(!e.hasDocs){let s=Qu(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Ta("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:Nw,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ve(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ve(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ve(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Ta("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as Ea,readdirSync as Da}from"node:fs";import{spawnSync as Lw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as Zu,resolveActiveProfile as ep,loadTokens as _w,isExpired as Mw,loadProfileMap as tp,localAheadPaths as Uw,loadKnownConflicts as Fw,readDocsPlan as Ww,devHintsGuidePath as Bw,DEFAULT_DOCS_DIR as Aa,roadmapProgress as Hw,listRoadmap as qw,readProductBriefState as Vw,reconcileCommitRequest as Gw}from"document360-engine";wt();function Ju(e){try{return Da(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ja(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ju(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ju(Kr(e,o)))}function Na(e,t){try{let n=Zu(e);if(!n)return!1;let o=ep(e,t),r=tp(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Aa).replace(/\/+$/,""));return!!(Ea(s)&&Da(s).length>0||Ea(Bw(e)))}catch{return!1}}function ko(e,t,n){try{let o=Zu(e);if(!o)return null;let r=ep(e,t),s=_w(r.name),i=!!s&&(!Mw(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=tp(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Aa).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Da(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Lw("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});ae.status===0&&(v=parseInt((ae.stdout||"").trim(),10)||0)}catch{}let E=0;try{let ae=Ww(e);if(ae.length>0){let Ze=(o.docsDir??Aa).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Ue=>Ue.path)).length}}catch{}let R=fo(e),x=mo({...R,directives:0}),T=Uw(e,t),F=new Set(Fw(e,r.name)),G=T.filter(ae=>F.has(ae)).length,q=T.length-G,Y=qe(e),pe=Hw(e),J=Gw(e,new Date().toISOString()),re=Vw(e),le=re?{status:re.status,openQuestions:re.openQuestions}:null;return!le&&$&&qw(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(le={status:"pending",openQuestions:0}),{ready:i&&c&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:x,directives:R.directives,behind:v,pendingWrites:E,localAhead:q,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:me,builderStarted:it(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:le,uncommittedDocs:J.dirty.length}}catch{return null}}K();var Yw={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},op=160,Oa=200,rp=40;function Le(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function np(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${Le(typeof r=="string"?r:JSON.stringify(r),rp)}`);return t.length>4&&n.push("\u2026"),Le(n.join(", "),op)}var zw=new Set(["file_path","notebook_path"]);function Kw(e,t){if(!t)return e;let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var Rt=e=>typeof e=="string"&&e?e:null,Ia=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Xw(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Qw(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Rt(t.title);if(!o)return null;let r=Xw(t.local_path);return n("Create article",`"${Le(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=Ia(t.article_id);return n("Update article",o?`"${Le(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ia(t.article_id)?`id ${Ia(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",Rt(t.name)?`"${Le(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?Le(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xr(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),c=i.join("__");if(s==="document360"){let b=Qw(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:np(t)}}let o=Yw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&zw.has(o)?Kw(r,n):r;return{title:e,sep:"",arg:Le(s,op)}}return{title:e,sep:"",arg:np(t)}}function Jw(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function Zw(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Jw).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Le(r,Oa))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${Le(String(r),rp)}`);return n.length>0?[Le(n.join(" \xB7 "),Oa)]:null}return null}function ek(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function tk(e,t,n){switch(e){case"d360_create_article":{let o=ek(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=Rt(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${Le(o[0],120)}`:""}`]}default:return null}}function Qr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
382
382
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let i=tk(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=Zw(r)??r.split(`
383
383
  `);return{lines:s.slice(0,t).map(i=>Le(i,Oa)),hidden:Math.max(0,s.length-t)}}function Jr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zr(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function sp(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function es(e){return sp(e,"url")}function ts(e){return sp(e,"preview_url")}var $k=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vk(e,t,n,o){if($k.test(e))try{let r=cp(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Zr(t,n),c=es(n);e.endsWith("publish_article")&&c&&console.log(W(` \u2B95 Live: ${c}`));let p=ts(n);p?console.log(W(` \u2B95 Preview: ${p}`)):i&&s&&console.log(W(` \u2B95 Preview: ${Jr(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function lp(e=process.cwd(),t="auto",n,o){let r=ok(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),xk(e,n),r.kind==="subscription"&&(r.stored?console.log(y(" Using your Claude subscription (no API key set).")):console.log(y(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1},p=nk({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let x=b;b=null,x(R)}else h.push(R)}),p.on("close",()=>{if($=!0,b){let R=b;b=null,R(null)}});function v(){return h.length>0?Promise.resolve(h.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(R=>{b=R}))}let E={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=La({cwd:e,profileName:n,allowProdWrites:s}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await v();if(R===null)break;let x=R.trim();if(x){if(x.startsWith("/")){let T=Xu(x);if(!T)continue;let F=Ku[T.name];if(!F){console.log(A(`Unknown command: /${T.name}`)),console.log(y("Type /help for the list."));continue}let G=await F(T.args,E);if(G.kind==="exit")break;if(G.kind==="clear"){E.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,E.restartAgent(),console.log(M("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){i.close(),i=La({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let q=rk(G.uuid);c={uuid:G.uuid,firstPrompt:q?.firstPrompt??null,titleFired:!0},ap(G.uuid),console.log(M(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=G.display??G.prompt);let q=(G.display??"").trim().split(/\s+/),Y=(q[0]==="/check"||q[0]==="/review")&&q.includes("--fix"),pe=q.slice(1).find(ae=>!ae.startsWith("--")),J=Y?kk(e,pe):[],re=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),le=re?q[2]&&!q[2].startsWith("--")?[q[2]]:co($e(e)):[];if(await _a(i,G.prompt,r,c,e),Y)try{wk(e,J,{reviewedCap:bk})}catch{}if(re&&le.length>0)try{for(let ae of uo(e,le))console.log(ae)}catch{}}else Ck(e,n);continue}if(fk(x)){let T=mk(x);if(T){try{gk(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=x),await _a(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,c,e);continue}}c.firstPrompt||(c.firstPrompt=x),await _a(i,x,r,c,e)}}}finally{i.close(),p.close()}}function xk(e,t){console.log(""),console.log(Vn("document360-writer")),console.log(y(` cwd: ${e}`));let n=lk(e);if(console.log(y(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Rk(e,t)),!dk(e))console.log(B(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(sr(e),!it(e))for(let r of ir(e))console.log(B(` ${r}`))}catch{}try{let r=uk(e);r.persisted&&r.appType?console.log(y(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=yk(e);for(let s of or(r.applied))console.log(B(` ${s}`))}catch{}try{let r=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?wo(r):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?B:y;for(let c of Qs(s.rec.note).split(`
384
384
  `))console.log(i(` ${c}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(c=>c.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Ck(e,t){try{let n=ko(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?wo(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(y(` Next: ${yo(o.rec.lead)}`))}catch{}}function Rk(e,t){try{let n=cp(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=hk(n.name);if(!r)return y(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ip(r.idToken)??{},...ip(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return pk(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):y(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return y(` Document360: ${n.message.split(".")[0]}`)}}function Sk(){console.error(""),console.error(`Sign in with your Claude subscription: run ${W("claude")} once, then retry.`),console.error(` (No Claude Code? ${W("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${W("https://console.anthropic.com/settings/keys")}`)}function Pk(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;ak({uuid:t,name:r??ik(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Tk(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ck(o,t).then(r=>{r&&sk(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r){let s=new Map;for await(let i of e.send(t))Ek(i,o,r,n,s)}function Ek(e,t,n,o,r){switch(e.type){case"session":t.uuid||Pk(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Xr(e.name,e.input,process.cwd());s&&(process.stdout.write(`
@@ -407,7 +407,7 @@ ${zp}`}),ne(m?"/doctor":"/init");return}m&&ne("/doctor");try{let w=_e(e,s),k=Gt(
407
407
  cwd: ${e}`}),$s()},[]),Me(()=>{let d=setInterval(()=>{$s()},Hb);return()=>clearInterval(d)},[$s]),Me(()=>{if(x||pe||Yt||lt.current||Pt.current||re!==null||Ue.length>0||$!==""||Mn!==null||ge.current.length>0||Eo.current||ys)return;let d=Mt(!1);d.kind==="recommend"&&(d.rec.lead||d.rec.picker)&&Io(d.rec,{silent:!0})},[x,pe,re,Ue,$,Mn,ys,q,Mt,Yt]),Me(()=>{let d=null,l=null,a=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;let m=`${We.columns??80}x${We.rows??24}`;m!==fc.current&&(fc.current=m,dh(j=>j+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Pl(Qt.current,ht())+"\x1B[?2026l")},80))},400)};return We.on("resize",a),()=>{d&&clearTimeout(d),l&&clearTimeout(l),We.off("resize",a)}},[We,ht]);let Be=Math.max(20,(We.columns??80)-1),gc=qa(()=>Ob(e,s),[e,s,q]),xs=(()=>{if(ih)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ps!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ps?` v${ps}`:""}\u2026`,isSetup:!0};if(Lo)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Mn)return uh?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(ge.current.length>0)return ge.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let d=de(e);if(!d)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Va(e,(d.docsDir??Za).replace(/\/+$/,"")),a=(()=>{try{return En(l)&&Yk(l).length>0}catch{return!1}})();try{let m=_e(e,s),j=Gt(m.name);if(!(!!j&&!(St(j)&&!j.refreshToken)))return{text:`Sign in with /login (profile "${m.name}")\u2026`,isSetup:!0};if(!m.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!m.project.workspaceId&&!a)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return a?{text:Lb,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Xe=wl($),yc=Xe.length>0&&!x,Mo=Math.max(3,Math.min(12,(We.rows??24)-8)),Uo=Math.min(hs,Math.max(0,Xe.length-1)),Ut=Xe.length<=Mo?0:Math.min(Math.max(0,Uo-Math.floor(Mo/2)),Xe.length-Mo),Cs=Xe.slice(Ut,Ut+Mo),Rs=c!==null?Ap(c,8,Be):null,Fo=je?je.paths.filter(d=>!je.query||d.toLowerCase().includes(je.query.toLowerCase())).slice(0,8):[],Wo=Ne?Ne.sessions.filter(d=>{let l=Ne.query.toLowerCase();return!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ie=ee((d,l)=>{Fe.current?.close(),Fe.current=Np({cwd:e,resume:d,profileName:l??s,allowProdWrites:Jt.current}),d||(et.current={uuid:null,firstPrompt:null,titleFired:!1},Et(null)),sn(0),an(0)},[e,s]),wc=ee((d,l,a)=>{if(_b.test(d))try{let m=_e(e,s),j=typeof l.project_id=="string"&&l.project_id||m.project.projectId,V=Zr(l,a),f=[],w=es(a);d.endsWith("publish_article")&&w&&f.push(`Live: ${w}`);let k=ts(a);k?f.push(`Preview: ${k}`):V&&j&&f.push(`Preview: ${Jr(m.connection.portalUrl,j,V,m.project.languageCode??"en")}`),f.length>0&&u({kind:"link",lines:f})}catch{}},[e,s,u]),ie=ee(async(d,l)=>{Ro(!0),lt.current=!1,Pt.current=!1,Ke(),ze([]),Nn(null),ks(null);let a=Co.current;if(l?.display?.startsWith("/"))try{let P=Gu(e,l.display);P&&(d=`${d}
408
408
 
409
409
  ${P}`)}catch{}l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:d});let m=et.current;m.firstPrompt||(m.firstPrompt=l?.display??d),Tt.current=Date.now(),zt(0),T(!0),To.current.clear();let j="",V=!1,f=!1,w="",k={num:0,closed:!1,cueSeen:!1},g=null,C=()=>{g||(g=setTimeout(()=>{g=null,p(w.length>0?w:null)},60))},S=()=>{g&&clearTimeout(g),g=null,p(null)},L=(P=!1)=>{let{head:H,keep:_}=Dp(w,P);H.trim()&&u({kind:"assistant",text:Ua(H.trimEnd(),k)}),w=_,S()};try{for await(let P of Fe.current.send(d))if(P.type==="session"){if(!m.uuid){m.uuid=P.sessionId;let H=new Date().toISOString(),_=ms.current,U=_??sb(m.firstPrompt??"session");ib({uuid:P.sessionId,name:U,renamed:!!_,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:H,updatedAt:H}),Et(U),ms.current=null}}else if(P.type==="text"){w+=P.delta,j+=P.delta;let H=jp(w);if(H>0){let _=w.slice(0,H).trimEnd();_&&u({kind:"assistant",text:Ua(_,k)}),w=w.slice(H)}C(),zt(_=>_+P.delta.length)}else if(P.type==="tool"){V=!0;let _=(z=>typeof z=="string"&&z?z.replace(/\\/g,"/").toLowerCase():null)(P.input.file_path??P.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(P.name),N=P.name==="Read"&&_!==null&&_===ic.current;if(ic.current=U?_:null,N)L(),u({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let z=Xr(P.name,P.input,e);z&&(L(),u({kind:"tool",title:z.title,sep:z.sep,arg:z.arg}),To.current.set(P.id,{name:P.name,input:P.input}))}}else if(P.type==="article_diff"){let H=ct(P.oldContent,P.newContent,ht());H&&(L(),u({kind:"diff",added:H.added,removed:H.removed,lines:H.lines,hidden:H.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(jo.current=!0);let H=To.current.get(P.id);if(H){To.current.delete(P.id),L();let _=Qr(P.output,4,P.isError?void 0:H.name,H.input);u({kind:"tool-result",lines:_.lines,hidden:_.hidden,isError:P.isError}),P.isError||wc(H.name,H.input,P.output)}}else if(P.type==="result"){L(!0),sn(_=>_+P.outputTokens),an(_=>_+P.costUsd);let H=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...H>0?{inTokens:H,cachedPct:Math.round(P.cacheReadTokens/H*100)}:{}}),!f&&!V&&!j.trim()&&!In.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(j))try{let _=Bp(e);if(En(_)){let U=cs(_,"utf8").trim();U&&(vs(U),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(Pt.current=P.ok&&/\?[\s*_"')\]]*$/.test(j.trimEnd()),P.ok&&k.cueSeen)oc(!0),ze([]);else{let _=P.ok?yp(j,kn.map(U=>U.name)):[];if(_.length>0)ne(_[0]);else if(P.ok&&j.trim()&&!Pt.current){let U=Mt(!1);U.kind==="recommend"&&(U.rec.lead||U.rec.picker)||db(d,j,e).then(N=>{N&&Co.current===a&&Se(N)}).catch(()=>{})}}if(m.uuid&&(Ga(m.uuid),!m.titleFired)){m.titleFired=!0;let _=m.uuid,U=m.firstPrompt;U&&Ip(U,e).then(N=>{N&&(rb(_,N),Et(N))}).catch(()=>{})}}else P.type==="error"&&(L(!0),f=!0,P.kind==="auth"&&(jo.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),S(),Y(P=>P+1),et.current.uuid&&fp(e,et.current.uuid,Qt.current),jo.current?(jo.current=!1,On.current=l?.display??d,Se("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):On.current=null,In.current&&(In.current=!1,Lt.current.length>0&&(u({kind:"note",tone:"info",text:`(${Lt.current.length} queued message(s) discarded)`}),Lt.current=[],gs([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,wc,ht,Se,ne,Ke,Mt]),Ft=ee(async d=>{let l=ds(e,"standard");Tt.current=Date.now(),zt(0),T(!0);let a=new AbortController;xe.current=a;let m=async(j,V)=>{let f=za(j);ce({verb:"Publishing",total:f.length,done:0,active:[],rows:$o(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:V?`Resolving cross-links in ${j.length} article${j.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${j.length} article${j.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u2264${no} agents at once) on ${l.model}\u2026 (esc to stop)`});let w=!1;for await(let k of ls({cwd:e,partitions:f,promptFor:g=>oo(g.paths),concurrency:no,profileName:s,allowProdWrites:Jt.current,model:l.model,signal:a.signal}))if(k.type==="partition_status")k.status==="running"?ce(g=>g&&{...g,active:[...g.active,k.label],rows:Ge(g.rows,k.label,"active"),lastAt:Date.now()}):ce(g=>g&&{...g,active:g.active.filter(C=>C!==k.label),done:g.done+1,rows:Ge(g.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return k.event.type==="tool"?C.tools=g.tools+1:k.event.type==="text"&&(C.chars=g.chars+k.event.delta.length),C});else if(k.type==="run_done"){w=k.aborted,an(L=>L+k.totalCostUsd),sn(L=>L+k.results.reduce((P,H)=>P+H.outputTokens,0));let g=k.aborted?"Stopped. ":"",C=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:g+mi(k.results,f,C).join(`
410
- `)});let S=fi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let L=await qp({cwd:e,profileName:s}),P=Vp(L);P?u({kind:"note",tone:"info",text:P}):L.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${L.skipped}`})}catch(L){u({kind:"note",tone:"warn",text:`Order sync failed: ${L.message}`})}try{let L=Yp(await Gp({cwd:e,profileName:s}));L&&u({kind:"note",tone:"info",text:L})}catch(L){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${L.message}`})}}}return w};try{if(!await m(d,!1)){let V=await gi(e,s,d);V.length>0&&await m(V,!0)}}catch(j){u({kind:"note",tone:"error",text:`Publish run failed: ${j.message}`})}finally{xe.current=null,ce(null),T(!1),Y(j=>j+1)}},[e,s,u,t]),Ss=ee(async d=>{await ie(pi(d),{display:`/publish ${d}`,quietUser:!0});try{let l=await Ar(e,s,d.replace(/\\/g,"/"));l.length>0&&(Nn(`Related articles not yet published (${l.length}):`),ze([`/publish --related ${d}`,...l.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),Bo=ee(d=>{if(d)try{for(let l of Array.isArray(d)?d:[d]){let a=Pa(e,l);if(!a)continue;Yr(e,a.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,u]),kc=ee(async(d,l)=>{let m=kb(d,3),j=ds(e,"standard"),V=new Map;for(let k of d){let g=ti(e,k,vn(e,k));g&&V.set(k,g)}Tt.current=Date.now(),zt(0),T(!0);let f=new AbortController;xe.current=f,ce({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:$o(m),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${d.length} screenshot spec${d.length===1?"":"s"} across ${m.length} partition${m.length===1?"":"s"} (\u22646 agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});let w=!1;try{for await(let k of ls({cwd:e,partitions:m,promptFor:g=>pd(g,V),concurrency:6,profileName:s,allowProdWrites:Jt.current,model:j.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ce(g=>g&&{...g,active:[...g.active,k.label],rows:Ge(g.rows,k.label,"active"),lastAt:Date.now()}):ce(g=>g&&{...g,active:g.active.filter(C=>C!==k.label),done:g.done+1,rows:Ge(g.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return k.event.type==="tool"?C.tools=g.tools+1:k.event.type==="text"&&(C.chars=g.chars+k.event.delta.length),C});else if(k.type==="run_done"){an(L=>L+k.totalCostUsd),sn(L=>L+k.results.reduce((P,H)=>P+H.outputTokens,0));let g=k.results.filter(L=>L.ok).length,C=k.aborted?"Stopped. ":"";w=!k.aborted&&l.setup;let S=k.aborted?"":w?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:`${C}Authored specs \u2014 ${g}/${k.results.length} batches ok.${S}`}),!k.aborted&&k.ok&&Bo(l.runLine)}}catch(k){u({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{xe.current=null,ce(null),T(!1),Y(k=>k+1)}if(w){let k=await Sn();k.kind==="forward-to-agent"&&k.prompt&&await ie(k.prompt,{display:k.display,quietUser:!0});let g=la(e);g&&u({kind:"note",tone:"info",text:g.join(`
410
+ `)});let S=fi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let L=await qp({cwd:e,profileName:s}),P=Vp(L);P?u({kind:"note",tone:"info",text:P}):L.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${L.skipped}`})}catch(L){u({kind:"note",tone:"warn",text:`Order sync failed: ${L.message}`})}try{let L=Yp(await Gp({cwd:e,profileName:s}));L&&u({kind:"note",tone:"info",text:L})}catch(L){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${L.message}`})}}}return w};try{if(!await m(d,!1)){let V=await gi(e,s,d);V.length>0&&await m(V,!0)}}catch(j){u({kind:"note",tone:"error",text:`Publish run failed: ${j.message}`})}finally{xe.current=null,ce(null),T(!1),Y(j=>j+1)}},[e,s,u,t]),Ss=ee(async d=>{await ie(pi(d),{display:`/publish ${d}`,quietUser:!0});try{let l=await Ar(e,s,d.replace(/\\/g,"/"));l.length>0&&(Nn(`Related articles not yet published (${l.length}):`),ze([`/publish --related ${d}`,...l.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ie]),Bo=ee(d=>{if(d)try{for(let l of Array.isArray(d)?d:[d]){let a=Pa(e,l);if(!a)continue;Yr(e,a.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,u]),kc=ee(async(d,l)=>{let m=kb(d,3),j=ds(e,"standard"),V=new Map;for(let k of d){let g=ti(e,k,vn(e,k));g&&V.set(k,g)}Tt.current=Date.now(),zt(0),T(!0);let f=new AbortController;xe.current=f,ce({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:$o(m),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${d.length} screenshot spec${d.length===1?"":"s"} across ${m.length} partition${m.length===1?"":"s"} (\u22646 agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});let w=!1;try{for await(let k of ls({cwd:e,partitions:m,promptFor:g=>pd(g,V),concurrency:6,profileName:s,allowProdWrites:Jt.current,model:j.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ce(g=>g&&{...g,active:[...g.active,k.label],rows:Ge(g.rows,k.label,"active"),lastAt:Date.now()}):ce(g=>g&&{...g,active:g.active.filter(C=>C!==k.label),done:g.done+1,rows:Ge(g.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return k.event.type==="tool"?C.tools=g.tools+1:k.event.type==="text"&&(C.chars=g.chars+k.event.delta.length),C});else if(k.type==="run_done"){an(L=>L+k.totalCostUsd),sn(L=>L+k.results.reduce((P,H)=>P+H.outputTokens,0));let g=k.results.filter(L=>L.ok).length,C=k.aborted?"Stopped. ":"";w=!k.aborted&&l.setup;let S=k.aborted?"":w?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:`${C}Authored specs \u2014 ${g}/${k.results.length} batches ok.${S}`}),!k.aborted&&k.ok&&Bo(l.runLine)}}catch(k){u({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{xe.current=null,ce(null),T(!1),Y(k=>k+1)}if(w){let k=await Sn();k.kind==="forward-to-agent"&&k.prompt&&await ie(k.prompt,{display:k.display,quietUser:!0});let g=la(e);g&&u({kind:"note",tone:"info",text:g.join(`
411
411
  `)})}},[e,s,u,ie,Bo]),bc=ee(async d=>{let l=ti(e,d,vn(e,d))??void 0,a=await Rr([d],void 0,{prior:l});a.kind==="forward-to-agent"&&a.prompt&&await ie(a.prompt,{display:a.display,quietUser:!0}),Zl(e,d)&&be(`Spec ready \u2014 /screenshot capture ${d} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${d}`,reason:""})},[e,ie,be]),Wn=ee(async(d,l)=>{if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!yu(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),Do("Waiting for you to finish logging in (browser window)\u2026");let N=new AbortController;xe.current=N;let z;try{z=await wu({cwd:e,signal:N.signal})}catch(Oe){u({kind:"note",tone:"error",text:`Could not launch the login: ${Oe.message}`});return}finally{xe.current=null,Do(null),T(!1)}if(z.exitCode!==0){ia(z.exitCode,z.output)?u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(z.output)?u({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):u({kind:"note",tone:N.signal.aborted?"warn":"error",text:N.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
412
412
  ${ra(z.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let a=new Map(d.map(N=>[N,od(e,N)])),m=0;if(d.length>1){let N=d.filter(z=>a.get(z).mutates);if(N.length>0&&(m=N.length,d=d.filter(z=>!a.get(z).mutates),d.length===0)){u({kind:"note",tone:"warn",text:`\u26A0 All ${N.length} spec${N.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${N[0]}`});return}}else if(d.length===1&&a.get(d[0]).mutates){let N=a.get(d[0]),z=ku(e);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${N.what?`: ${nd(N.what)}`:N.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(z.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${z.url?` (${z.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}T(!0);let j=new AbortController;xe.current=j;let V=d.map(N=>({label:N,items:1,status:"pending"}));ce({verb:"Capturing",unit:"screenshot",total:d.length,done:0,active:[],rows:V,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=at(e),w=Object.keys(f.shots).length>0,k=bu(l?.heldBackBlocked??[],m);u({kind:"note",tone:"info",text:`Capturing ${d.length} screenshot${d.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
413
413
  ${k}`:"")});let g=Date.now(),C=[];try{for(let N of d){if(j.signal.aborted)break;ce(Q=>Q&&{...Q,active:[N],rows:Ge(Q.rows,N,"active"),lastAt:Date.now()});let{exitCode:z,output:Oe}=await sa({cwd:e,id:N,signal:j.signal,stdio:"pipe"});if(ia(z,Oe)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let rt=j.signal.aborted&&z!==0?"failed":oa(e,N,z,g),pn=rt==="captured"?void 0:rt==="skipped"?mu(Oe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":gu(Oe);C.push({id:N,outcome:rt,detail:pn}),ce(Q=>Q&&{...Q,active:[],done:Q.done+1,rows:Ge(Q.rows,N,rt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(N){u({kind:"note",tone:"error",text:`Capture run failed: ${N.message}`})}finally{xe.current=null,ce(null),T(!1),Y(N=>N+1)}if(C.length===0)return;let S=C.filter(N=>N.outcome==="captured"),L=C.filter(N=>N.outcome==="skipped"),P=C.filter(N=>N.outcome==="failed"),H=d.length-C.length;u({kind:"note",tone:P.length?"warn":S.length?"ok":"info",text:[`\u2713 ${S.length} captured`,L.length?`\u2298 ${L.length} blocked`:"",P.length?`\u2717 ${P.length} broken`:"",H?`${H} not run (stopped)`:""].filter(Boolean).join(" ")+` ${C.length} run${m>0?` \xB7 ${m} held back`:""}`+xu($u(f,C),w).map(N=>`
@@ -437,10 +437,10 @@ ${S.skipped.map(P=>` - ${P.path} (${P.reason})`).join(`
437
437
  `)}),be(C.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:k.length===0?"ok":"warn",text:qr(k).join(`
438
438
  `)}),k.length>0&&be(`Found ${k.length} doc issue${k.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let f=go(e,s);if(f.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
439
439
  `)});return}case"reorder":{let f=Ca(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(f.prompt,{display:f.display,quietUser:!0}),be("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let f=xa(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=m.includes("--fix"),k=m.find(C=>!C.startsWith("--")),g=w?Hp(e,k):[];if(await ie(f.prompt,{display:f.display,quietUser:!0}),w)try{Ka(e,g,{reviewedCap:Xa})}catch{}if(w)be("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let C=m.filter(S=>S!=="--fix").join(" ");be(`The review listed issues above. /review${C?` ${C}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${C?` ${C}`:""} --fix`,reason:""})}return}case"capture-setup":{await V();return}case"devhints":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:yn(gn(e)).join(`
440
- `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e);return}case"discover":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(yi(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(da(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ie(ua(),{display:"/inbox",quietUser:!0});return}case"feedback":{let f=Bp(e),w="";try{w=En(f)?cs(f,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Ma(w.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${f} and copy it manually.`}),k&&vs(null);return}case"document":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,what:w}=Vi(m);if(!w&&qi(e)===0){u({kind:"note",tone:"info",text:Yi});return}let k=`/document${w?` ${w}`:""}${f?" --publish":""}`;await ie(Gi(w,f),{display:k,quietUser:!0});return}case"catch-up":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Oo(d.trim()))return;let{publish:f}=ha(m);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ma({cwd:e,profileName:s});for(let g of ga(w))u({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let k=mo(fo(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(fa({publish:f}),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});return}case"update":{bs.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),So(!0);let f=await Br().finally(()=>So(!1));f.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),rc("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Wr}`});return}case"screenshot":{let f=Zn(m),w=eo(e);if(w&&u({kind:"note",tone:"info",text:w}),f.mode==="capture"){await j(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let C=$e(e),S=f.rest.find(H=>!H.startsWith("-")),L=S?[S]:co(C);if(S&&!C.some(H=>H.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(L.length===0){let H=C.filter(U=>U.state==="rejected").length,_=C.filter(U=>U.state==="verified").length;u({kind:"note",tone:"info",text:H>0?`Nothing awaiting review. ${H} shot${H===1?"":"s"} failed review \u2014 re-capture with /screenshot capture --failed.`:_>0?`All ${_} captured shot${_===1?" is":"s are"} already verified.`:"No captured screenshots to review yet \u2014 /screenshot capture takes the shots first."});return}u({kind:"note",tone:"info",text:lo(L.length)}),await ie(qt(e,L),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let P=uo(e,L);P.length>0&&u({kind:"note",tone:"info",text:P.join(`
440
+ `)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e);return}case"discover":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ie(yi(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(da(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ie(ua(),{display:"/inbox",quietUser:!0});return}case"feedback":{let f=Bp(e),w="";try{w=En(f)?cs(f,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Ma(w.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${f} and copy it manually.`}),k&&vs(null);return}case"document":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,what:w}=Vi(m);if(!w&&qi(e)===0){u({kind:"note",tone:"info",text:Yi});return}let k=`/document${w?` ${w}`:""}${f?" --publish":""}`;await ie(Gi(w,f),{display:k,quietUser:!0});return}case"catch-up":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Oo(d.trim()))return;let{publish:f}=ha(m);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ma({cwd:e,profileName:s});for(let g of ga(w))u({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let k=mo(fo(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ie(fa({publish:f}),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});return}case"update":{bs.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),So(!0);let f=await Br().finally(()=>So(!1));f.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),rc("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Wr}`});return}case"screenshot":{let f=Zn(m),w=eo(e);if(w&&u({kind:"note",tone:"info",text:w}),f.mode==="capture"){await j(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let C=$e(e),S=f.rest.find(H=>!H.startsWith("-")),L=S?[S]:co(C);if(S&&!C.some(H=>H.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(L.length===0){let H=C.filter(U=>U.state==="rejected").length,_=C.filter(U=>U.state==="verified").length;u({kind:"note",tone:"info",text:H>0?`Nothing left to verify. ${H} shot${H===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:_>0?`All ${_} captured shot${_===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}u({kind:"note",tone:"info",text:lo(L.length)}),await ie(qt(e,L),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let P=uo(e,L);P.length>0&&u({kind:"note",tone:"info",text:P.join(`
441
441
  `)});return}if(f.mode==="list"){if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=de(e)?.docsDir??Za,S=di(e,f.scope),L=$e(e,S);if(f.picker){if(L.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let N=ud(L);if(N.length===0){u({kind:"note",tone:"info",text:Cr(L,{docsDir:C}).join(`
442
442
  `)}),be(`\u2713 All ${L.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Nt({cursor:0,rows:N,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Cr(L,{scope:S,detail:f.detail,docsDir:C}).join(`
443
- `)});let P=L.filter(N=>N.state==="placeholder").length,H=L.filter(N=>N.state==="spec").length,_=L.filter(N=>N.state==="captured").length,U=L.filter(N=>N.state==="rejected").length;if(P>0){let N=S?`/screenshot author ${S}`:"/screenshot author --all";be(`${P} of ${L.length} still need${P===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${N} authors them all in parallel.`,{kind:"cmd",cmd:N,reason:""})}else if(H>0){let N=S?`/screenshot capture ${S}`:"/screenshot capture";be(`${H} spec${H===1?"":"s"} ready to capture \u2014 ${N} takes ${H===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:N,reason:""})}else _>0?be(`${_} shot${_===1?"":"s"} captured but not yet verified \u2014 /screenshot verify checks each picture against what its article needs (no browser, no re-capture).`,{kind:"cmd",cmd:"/screenshot verify",reason:""}):U>0&&be(`${U} shot${U===1?"":"s"} failed quality review \u2014 /screenshot capture --failed re-shoots ${U===1?"it":"them"} once the spec is fixed.`,{kind:"cmd",cmd:"/screenshot capture --failed",reason:""});return}if(f.mode==="single"){await bc(f.id);return}if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f.mode==="scope"?f.scope:void 0,g=bb(e,{scope:k}).map(C=>C.id);if(g.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await kc(g,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await j(m);return}case"reset":{let f=ka(e);if(f.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Eo.current={repoName:vo(e),targets:f,hadDevhints:En(Wp(e))},u({kind:"note",tone:"warn",text:$a(e,f).join(`
443
+ `)});let P=L.filter(N=>N.state==="placeholder").length,H=L.filter(N=>N.state==="spec").length,_=L.filter(N=>N.state==="captured").length,U=L.filter(N=>N.state==="rejected").length;if(P>0){let N=S?`/screenshot author ${S}`:"/screenshot author --all";be(`${P} of ${L.length} still need${P===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${N} authors them all in parallel.`,{kind:"cmd",cmd:N,reason:""})}else if(H>0){let N=S?`/screenshot capture ${S}`:"/screenshot capture";be(`${H} spec${H===1?"":"s"} ready to capture \u2014 ${N} takes ${H===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:N,reason:""})}else _>0?be(`${_} shot${_===1?"":"s"} captured but not yet verified \u2014 /screenshot verify checks each picture against what its article needs (no browser, no re-capture).`,{kind:"cmd",cmd:"/screenshot verify",reason:""}):U>0&&be(`${U} shot${U===1?"":"s"} failed verification \u2014 /screenshot capture --failed re-shoots ${U===1?"it":"them"} once the spec is fixed.`,{kind:"cmd",cmd:"/screenshot capture --failed",reason:""});return}if(f.mode==="single"){await bc(f.id);return}if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f.mode==="scope"?f.scope:void 0,g=bb(e,{scope:k}).map(C=>C.id);if(g.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await kc(g,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await j(m);return}case"reset":{let f=ka(e);if(f.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Eo.current={repoName:vo(e),targets:f,hadDevhints:En(Wp(e))},u({kind:"note",tone:"warn",text:$a(e,f).join(`
444
444
  `)}),Se(vo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,As,u,Ie,ie,Ft,Ss,$c]),Go=ee(d=>{let l=(d??$).trim();if(v(""),Po(null),Kt(0),l.startsWith("/")&&(lt.current=!1,Pt.current=!1,Ke(),Nn(null),ze(m=>vp(m,l))),!l||(oc(!1),xc(l))||vc(l))return;fs.current.push(l);let a=Sp(l,sc.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Bn(a).finally(()=>J(!1));else if(Ab(a)){u({kind:"user",text:l});let m=Db(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{jb(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${m}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let m=Yu(e,a);ie(m??a,{display:l})}},[$,xc,vc,Bn,ie]),Cc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=xp(d);if(Cp(l)){let a=Rp(++ch.current,l);sc.current.set(a,l),E(a)}else E(l);return}E(d)},[E]),un=Math.max(10,Be-6),Rc=qa(()=>is(h.text,un),[h.text,un]),Ds=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Tp(is(l.text,un),l.pos,d)})),[un]),Hn=ee(d=>b(l=>({...l,pos:Ep(is(l.text,un),l.pos,d)})),[un]),ph=["\x1B[H","\x1B[1~","\x1BOH"],hh=["\x1B[F","\x1B[4~","\x1BOF"],Sc=ee((d,l)=>l.leftArrow?(Ds(-1),!0):l.rightArrow?(Ds(1),!0):d&&ph.includes(d)?(Hn("start"),!0):d&&hh.includes(d)?(Hn("end"),!0):l.ctrl&&d==="a"?(Hn("start"),!0):l.ctrl&&d==="e"?(Hn("end"),!0):!1,[Ds,Hn]);return Vk((d,l)=>{if(l.ctrl&&d==="c"){Fe.current?.close(),r();return}if(!F){if(x){if(l.escape){if(xe.current){if(!xe.current.signal.aborted){let a=(Ao?.verb??"work").toLowerCase(),m=Ao?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),xe.current.abort()}return}In.current||(In.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Fe.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),gs([...Lt.current]),v("");return}if(Sc(d,l))return;if(l.upArrow){Yo(-1);return}if(l.downArrow){Yo(1);return}if(l.backspace||l.delete){R();return}d&&!l.ctrl&&!l.meta&&Cc(d);return}if(At){if(l.upArrow){Dt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Dt(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){Dt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[At.cursor];Dt(null);let{lines:m,changed:j,effective:V}=io(e,a.value??"default");for(let f of m)u({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});j&&(hc(f=>f+1),Fe.current?.setModel(V));return}if(d==="s"){let a=Je[At.cursor];Dt(null),Fe.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Dt(null);return}return}if(tt){if(l.upArrow){en(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){en(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=tt.rows.length){en(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return||d==="s"){let a=tt.rows[tt.cursor];en(null),Ts(a.name,l.return===!0);return}if(l.escape){en(null);return}return}if(No){if(l.escape){_n(null);return}if(l.leftArrow||l.tab&&l.shift){_n(a=>a&&{tab:(a.tab-1+He.length)%He.length});return}if(l.rightArrow||l.tab){_n(a=>a&&{tab:(a.tab+1)%He.length});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=He.length){_n({tab:Number(d)-1});return}return}if(nt){if(l.upArrow){tn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){tn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=nt.rows.length){tn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=nt.rows[nt.cursor].name;if(tn(null),!Bs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let j=!1;try{let V=Gt(a);j=!!V&&!(St(V)&&!V.refreshToken)}catch{j=!1}u({kind:"note",tone:"info",text:j?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),ne("/login"),Y(V=>V+1);return}if(l.escape){tn(null);return}return}if(Re){if(l.upArrow){nn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){nn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Re.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Re.rows[Re.cursor],{profile:m,projectId:j}=Re;nn(null),Ho(m,j,a);return}if(l.escape){nn(null);return}return}if(De){if(l.upArrow){jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){jt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=De.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=De.rows[De.cursor],{profile:m}=De;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Pe){if(l.upArrow){rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d===" "){rn(a=>a&&{...a,rows:a.rows.map((m,j)=>j===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Pe.rows.filter(m=>m.checked).map(m=>m.path);if(rn(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}wi(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of a)u({kind:"note",tone:"info",text:` ${m}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){rn(null);return}return}if(ot){if(l.upArrow){It(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){It(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ot.rows.length){It(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ot.rows[ot.cursor],m=ot.run;It(null),m(a.token);return}if(l.escape){It(null);return}return}if(ut){if(l.upArrow){on(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){on(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ut.rows.length){on(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ut.rows[ut.cursor];on(null),a.conflict?As(a.paths[0]):a.kind==="article"?Ss(a.paths[0]):Ft(a.paths);return}if(l.escape){on(null);return}return}if(pt){if(l.upArrow){Nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=pt.rows.length){Nt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=pt.rows[pt.cursor];Nt(null),a.action==="capture"?Wn(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?bc(a.ids[0]):kc(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(je){if(l.escape){Ot(null);return}if(l.upArrow){Ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Ot(a=>a&&{...a,cursor:Math.min(Math.max(0,Fo.length-1),a.cursor+1)});return}if(l.return){let a=Fo[je.cursor];if(a){Ot(null);try{u({kind:"preview",name:vo(a),text:Xp(cs(Va(e,a),"utf8"))})}catch(m){u({kind:"note",tone:"error",text:`Could not read ${a}: ${m.message}`})}}return}if(l.backspace||l.delete){Ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){Ot(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(Ne){if(l.escape){_t(null);return}if(l.upArrow){_t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){_t(a=>a&&{...a,cursor:Math.min(Math.max(0,Wo.length-1),a.cursor+1)});return}if(l.return){let a=Wo[Ne.cursor];if(a){_t(null),Ie(a.uuid),et.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Et(a.name),Ga(a.uuid),Qt.current=[];let m=Fa(e,a.uuid);for(let j of m)u(j);u({kind:"note",tone:"ok",text:m.length?`Resumed "${a.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){_t(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){_t(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(l.tab&&!$&&re){v(re),Ke();return}if(!$&&Ue.length>0&&!Yt&&d&&/^[1-9]$/.test(d)){let a=Ue[Number(d)-1];if(a){v(Vt(a));return}}if(!$&&(Lo||Mn)&&d==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let a=Lo!=null;Ma(Lo??Mn).then(j=>{u({kind:"note",tone:j?"ok":"warn",text:j?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),j&&a&&vs(null),j&&!a&&mc(!0)});return}if(!Sc(d,l)){if(yc){if(l.upArrow){Kt(a=>Math.max(0,a-1));return}if(l.downArrow){Kt(a=>Math.min(Xe.length-1,a+1));return}if(l.tab){v("/"+(Xe[hs]?.name??"")+" "),Kt(0);return}if(l.return){let a=Xe[hs];if(a){let m=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(kl(a.usage)&&!m){v("/"+a.name+" "),Kt(0);return}Go("/"+a.name+(m?" "+m:""));return}}}else{if(l.upArrow){if($!==""&&Xt===null){Yo(-1);return}let a=fs.current;if(!a.length)return;let m=Xt===null?a.length-1:Math.max(0,Xt-1);Po(m),v(a[m]??"");return}if(l.downArrow){if($!==""&&Xt===null){Yo(1);return}let a=fs.current;if(Xt===null)return;let m=Xt+1;m>=a.length?(Po(null),v("")):(Po(m),v(a[m]??""));return}}if(l.return){Go();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Kt(0),Ke(),ze([]),Nn(null),lt.current=!0;return}d&&!l.ctrl&&!l.meta&&Cc(d)}}}),Me(()=>{if(x||F)return;let d=Lt.current.shift();d!==void 0&&(gs([...Lt.current]),Go(d))},[x,F,Go]),te(ue,{flexDirection:"column",width:Be,children:[Rs!==null&&te(ue,{marginTop:1,flexDirection:"column",children:[Rs.truncated&&O(I,{dimColor:!0,children:"\u2026"}),O(I,{children:Rs.text})]}),x&&(Ao?O(Bb,{p:Ao}):O(Ub,{startTime:Tt.current,chars:ah})),!x&&dc?O(Fb,{text:dc}):null,O(ue,{borderStyle:"round",borderColor:gc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Rc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===as(Rc,h.pos),j=Math.min(h.pos,d.end)-d.start;return te(I,{children:[O(I,{color:Z,children:l===0?"> ":" "}),m?te(xo,{children:[a.slice(0,j),O(An,{ch:a[j]??" "}),a.slice(j+1)]}):a||" "]},`${l}-${d.start}`)}):te(I,{children:[O(I,{color:Z,children:"> "}),ys?O(An,{ch:" "}):re&&!x&&ae?te(xo,{children:[O(An,{ch:ae[0],dim:!0}),O(I,{color:"gray",children:ae.slice(1)})]}):re&&!x?te(xo,{children:[O(An,{ch:re[0],dim:!0}),O(I,{color:"gray",children:re.slice(1)}),O(I,{dimColor:!0,children:" (tab)"})]}):(xs.isSetup||!sh)&&!x?te(xo,{children:[O(An,{ch:xs.text[0],dim:!0}),O(I,{color:"gray",children:xs.text.slice(1)})]}):O(An,{ch:" "})]})}),lc.length>0&&O(ue,{flexDirection:"column",paddingX:1,children:lc.map((d,l)=>O(I,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?O(gp,{tab:No.tab,width:Be,version:o,engineVersion:Qp}):At?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Select model"}),O(I,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Je.map((d,l)=>te(I,{color:l===At.cursor?Z:void 0,children:[l===At.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===At.current?" \u2714":""}`.padEnd(16),O(I,{color:"gray",children:d.desc})]},d.label)),O(I,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Switch connection profile"}),tt.rows.map((d,l)=>te(I,{color:l===tt.cursor?Z:void 0,children:[l===tt.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===tt.current?" \u2714":""}`.padEnd(20),O(I,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?O(I,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),O(I,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):nt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Pick your Document360 environment"}),nt.rows.map((d,l)=>te(I,{color:l===nt.cursor?Z:void 0,children:[l===nt.cursor?"\u276F ":" ",`${l+1}. ${d.name}`.padEnd(16),O(I,{color:"gray",children:d.apiUrl})]},d.name)),O(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Re?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Switch workspace"}),O(I,{dimColor:!0,children:`environment ${Re.environment} \xB7 project ${Re.projectName??`${Re.projectId.slice(0,8)}\u2026`}`}),Re.rows.map((d,l)=>te(I,{color:l===Re.cursor?Z:void 0,children:[l===Re.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Re.current?" \u2714":""}`.padEnd(30),O(I,{color:"gray",children:d.type??""})]},d.id)),O(I,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):De?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Choose project"}),O(I,{dimColor:!0,children:`environment ${De.environment}`}),De.rows.map((d,l)=>te(I,{color:l===De.cursor?Z:void 0,children:[l===De.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===De.current?" \u2714":""}`.padEnd(30),O(I,{color:"gray",children:d.sub??""})]},d.id)),O(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Pe?(()=>{let l=Math.min(Math.max(0,Pe.cursor-Math.floor(7)),Math.max(0,Pe.rows.length-14)),a=Pe.rows.slice(l,l+14),m=Pe.rows.filter(j=>j.checked).length;return te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Pe.rows.length})`}),l>0?O(I,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((j,V)=>{let f=l+V;return te(I,{color:f===Pe.cursor?Z:void 0,children:[f===Pe.cursor?"\u276F ":" ",j.checked?"\u25C9 ":"\u25CB ",j.path.padEnd(Math.min(48,Be-34)),O(I,{color:"gray",children:Dr(j)})]},j.path)}),l+14<Pe.rows.length?O(I,{dimColor:!0,children:` \u2193 ${Pe.rows.length-l-14} more`}):null,O(I,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Which category? (pick one to scope to)"}),ot.rows.map((d,l)=>{let a=l===ot.cursor,m=`${l+1}.`.padEnd(3);return te(I,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Be-24))),O(I,{color:"gray",children:` ${d.token}`})]},d.token)}),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):ut?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ut.rows.map((d,l)=>{let a=l===ut.cursor,m=d.indent?" ":" ",j=`${l+1}.`.padEnd(3);return te(I,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${j} ${d.label}`.padEnd(Math.min(56,Be-24)),d.note?O(I,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):pt?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:pt.title}),(()=>{let{rows:l,cursor:a}=pt,m=Math.max(0,Math.min(a-Math.floor(12/2),l.length-12)),j=l.slice(m,m+12),V=`${l.length}.`.length+1,f=dd(l,Math.max(20,Be-4-V));return te(xo,{children:[m>0?O(I,{color:"gray",children:` \u2026 ${m} more above`}):null,j.map((w,k)=>{let g=m+k,C=g===a,S=f[g];return te(I,{color:C?Z:void 0,bold:(w.kind==="all"||w.kind==="category")&&!C,children:[C?"\u276F ":" ",`${g+1}.`.padEnd(V),S.head,S.note?O(I,{color:"gray",children:S.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),m+12<l.length?O(I,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),O(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):je?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Preview article${je.query?` \u2014 filter: ${je.query}`:" (type to filter)"}`}),Fo.length===0?O(I,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>te(I,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",d]},d)),O(I,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ne?te(ue,{flexDirection:"column",paddingX:1,children:[O(I,{color:Z,bold:!0,children:`Resume session${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Wo.length===0?O(I,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>te(I,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),O(I,{color:l===Ne.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Be-40))})]},d.uuid)),O(I,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):yc?te(ue,{flexDirection:"column",children:[Ut>0?O(I,{dimColor:!0,children:` \u22EF ${Ut} more above`}):null,Cs.map((d,l)=>{let a=Ut+l;return te(I,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",d.usage.padEnd(22)," ",O(I,{color:a===Uo?Z:"gray",children:d.name==="model"&&ws?`${d.desc} (currently ${ws})`:d.desc})]},d.name)}),Ut+Cs.length<Xe.length?O(I,{dimColor:!0,children:` \u22EF ${Xe.length-Ut-Cs.length} more below`}):null,O(I,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!x&&!$&&Ue.length>0?te(ue,{flexDirection:"column",paddingX:1,children:[cc?O(I,{color:Z,children:cc}):null,Ue.map((d,l)=>{let a=Vt(d),m=a.slice(0,Math.max(20,Be-5)),j=Be-m.length-7,V=j>=12?($p(d)??yl(a)).slice(0,j):"";return te(I,{children:[O(I,{color:Z,children:l+1})," ",m,V?O(I,{dimColor:!0,children:` \u2014 ${V}`}):null]},a)}),O(I,{dimColor:!0,children:`press 1-${Ue.length} to fill \xB7 esc cancel`})]}):O(ue,{paddingX:1,children:te(I,{color:"gray",children:[gc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ws??"model n/a"}${t.kind==="api"?pc>0?` \xB7 ${Ee(pc)}`:"":uc>0?` \xB7 ${bt(uc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Gb}from"react/jsx-runtime";async function Zp(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Vb(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=qb(Gb(Jp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
445
445
  `),process.exit(0)}K();import{writeCrashLog as eh,isBenignTransportError as Yb}from"document360-engine";var th=!1;function ec(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function nh(e){if(th)return;th=!0;let t=(n,o)=>{if(Yb(o)){eh({kind:n,level:"transport",message:ec(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=eh({kind:n,level:"fatal",message:ec(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
446
446
  `+A(`\u2717 d360-writer crashed: ${ec(o)}`)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.5.183",
3
+ "version": "0.5.185",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -34,7 +34,7 @@
34
34
  "@inquirer/prompts": "^8.4.3",
35
35
  "commander": "^14.0.3",
36
36
  "diff": "^8.0.4",
37
- "document360-engine": "^0.2.173",
37
+ "document360-engine": "^0.2.174",
38
38
  "ink": "^5.2.1",
39
39
  "picocolors": "^1.1.1",
40
40
  "react": "^18.3.1",