document360-writer 0.5.186 → 0.5.187
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +23 -23
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -276,7 +276,7 @@ try {
|
|
|
276
276
|
/* a session-start nudge must never break the session */
|
|
277
277
|
}
|
|
278
278
|
`;tl="Re-run dev\u2194docs onboarding (protocol v"});var gl={};Ec(gl,{initCommand:()=>Hs,scaffoldInit:()=>Bs});import{input as Kn,confirm as ff}from"@inquirer/prompts";import{basename as al,join as cr}from"node:path";import{existsSync as wn,readFileSync as mf,readdirSync as gf,writeFileSync as yf}from"node:fs";import{writeProjectConfig as cl,readProjectConfig as wf,projectConfigPath as ll,writerDir as kf,DEFAULT_DOCS_DIR as dl,DEFAULT_CAPTURE_DIR as ul,DEFAULT_OUTPUT_DIR as pl}from"document360-engine";function Bs(e,t="berlin"){let n=ll(e);if(wn(n))return{created:!1,path:n,profileName:""};let o={projectId:fl(e)??al(e),docsDir:dl,captureDir:ul,outputDir:pl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:ml(e)};return cl(o,e),hl(e),{created:!0,path:n,profileName:t}}function hl(e){let t=cr(kf(e),".gitignore");wn(t)||yf(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
|
-
`),"utf8")}async function Hs(){let e=process.cwd(),t=ll(e);if(wn(t)&&!await ff({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=fl(e)??al(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:ul}),s=await Kn({message:"Screenshot output directory:",default:pl}),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:dl,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:ml(e)},h=wf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),cl(p,e),hl(e);let b=gn(e);console.log(""),console.log(M(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of yn(b))console.log($);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function fl(e){let t=cr(e,"package.json");if(!wn(t))return null;try{return JSON.parse(mf(t,"utf8")).name??null}catch{return null}}function ml(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)&&!bf(o)&&t.push(n)}return t}function bf(e){try{return gf(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 Bf}from"node:module";import{existsSync as Hf,readFileSync as qf}from"node:fs";import{dirname as _l,join as Ml}from"node:path";function $n(){let e;try{e=Vf.resolve("document360-capture/helpers")}catch{return null}let t=_l(e);for(let n=0;n<5&&!Hf(Ml(t,"package.json"));n++)t=_l(t);try{let n=JSON.parse(qf(Ml(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Vf,hr=qn(()=>{"use strict";Vf=Bf(import.meta.url)});var cu={};Ec(cu,{doctorCommand:()=>ao,renderDoctorChecks:()=>au,runDoctorChecks:()=>iu});import{existsSync as ny}from"node:fs";import{d360GetAll as oy,getAccessToken as ry,isExpired as Qi,loadProfileMap as sy,loadTokens as iy,packageSkillsDir as ru,ENGINE_VERSION as ay,projectConfigPath as cy,readProjectConfig as ly,DEFAULT_DOCS_DIR as dy,fetchManifestSummary as uy,resolveActiveProfile as py,classifyClaudeAuth as hy,CLAUDE_CODE_SETUP_HINT as su,resolveModelSetting as fy,probeModel as my,detectAppType as gy,playbookSkillName as yy,D360AuthError as wy,applyStructureOrder as ky}from"document360-engine";async function iu(e,t){let n=[],o=$n();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${ay}${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=hy();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. ${su}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:su});let i=fy(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 C=await my(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.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 ${C.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=ly(e);if(!c)return n.push({level:"fail",label:`No ${cy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??dy).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??gy(e);if(b){let C=c.appType?"from config":"auto-detected",P=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${P?` \u2192 ${yy(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{$=py(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=iy($.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=sy(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(ny(ru())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ru()}`,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${ge})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${ge}`,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 C={profile:$.name,connection:$.connection};try{await ry(C);let L=await oy(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${L.length} project(s) visible`})}catch(L){n.push({level:"fail",label:`API call failed: ${L.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=E?.projectId??$.project.projectId;if(P&&$.project.workspaceId){try{let L=await uy(C,P,$.project.workspaceId);if(L){let G=(L.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${L.languages?.length??0} language${(L.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(L){L instanceof wy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(L.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??P})`,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 (${L.message.slice(0,80)})`})}try{let L=await ky({cwd:e,profileName:$.name,dryRun:!0}),G=L.categoriesReordered+L.articlesReordered;if(L.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${L.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(G>0){let q=[L.categoriesReordered>0?`${L.categoriesReordered} categor${L.categoriesReordered===1?"y":"ies"}`:"",L.articlesReordered>0?`${L.articlesReordered} article${L.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${q.join(" + ")} out of order on Document360`,fix:"Run /publish \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"})}catch(L){n.push({level:"warn",label:`Reading order: check failed (${L.message.slice(0,80)})`})}}}return n}function au(e){let t=[""];for(let r of e){let s=r.level==="ok"?M("\u2713"):r.level==="warn"?H("\u26A0"):D("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("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"})`}`):D(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ao(e,t){console.log(g("Running checks\u2026"));for(let n of au(await iu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _r=qn(()=>{"use strict";wt();K();hr()});import{Command as Qb}from"commander";import{createRequire as Jb}from"node:module";import{AUTH_MODES as Zb}from"document360-engine";import{input as Ih}from"@inquirer/prompts";import{loginPkce as Oh,refreshTokens as Lh,toStoredTokens as Lc,clearTokens as _h,decodeJwtClaims as Oc,isExpired as Mh,loadTokens as Uh,saveTokens as _c,resolveActiveProfile as Qo,setProfileProject as Fh,readProjectConfig as Wh}from"document360-engine";K();import{select as $h}from"@inquirer/prompts";import{resolveActiveProfile as vh,setProfileProject as xh,resolveProjectId as Ch,listWorkspaces as Rh}from"document360-engine";async function Gn(e,t){let n=vh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ch(o);return{workspaces:await Rh(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ac=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){xh(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function jc(e,t,n){let o;try{o=await Gn(e,n)}catch(s){return console.log(D(`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(D(`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(D(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("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"):" "} ${Ac(h)} ${g(h.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let c=await $h({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Ac(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 Sh}from"@inquirer/prompts";import{resolveActiveProfile as Ph,setProfileProject as Th,listProjects as Eh}from"document360-engine";async function gt(e,t){let n=Ph(e,t),o={profile:n.name,connection:n.connection};return{projects:await Eh(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Nc=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){Th(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ic(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(D(`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(D(`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(D(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("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"):" "} ${Nc(p)} ${g(p.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Sh({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Nc(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 Dh from"picocolors";function Ah(e=process.env){return e.FORCE_HYPERLINK==="0"||!Dh.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 jh(e,t=e,n){return Ah(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Nh=/https?:\/\/[^\s\x1b]+/g;function Yn(e,t){return e.replace(Nh,n=>jh(n,n,t))}function Mc(e){return{...Oc(e.idToken)??{},...Oc(e.accessToken)??{}}}function Jo(e){let t=Mc(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(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Oh(n,{manual:e.manual,promptForRedirect:s=>Ih({message:s})},s=>console.log(Yn(s))),r=Lc(t.name,o);if(_c(r),await Is(r,t.name,s=>console.log(g(s))),console.log(""),console.log(M(`\u2713 Logged in to "${t.name}" as ${Jo(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Wh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await hn(process.cwd(),t.name))}catch{}}async function Is(e,t,n){let r=Mc(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{}Fh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Uc(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=Uh(t.name);if(!o){console.log(D(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Mh(o))if(o.refreshToken)try{let r=Lc(t.name,await Lh(n,o.refreshToken));_c(r),console.log(M(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Fc(e){let t=Qo(process.cwd(),e.profile);_h(t.name)?console.log(M(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Wc,writeProjectConfig as Bh,resolveActiveProfile as Hh,loadTokens as qh,isExpired as Vh}from"document360-engine";function er(e){let t=Wc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(D("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?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=qh(n),p=c?Vh(c)&&!c.refreshToken?H("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Wc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(D(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Bh(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(M(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Hh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(D(n.message)),process.exitCode=1}}K();import{existsSync as Gh,readdirSync as Yh,statSync as Bc}from"node:fs";import{join as Hc}from"node:path";import{apiLogDir as zh}from"document360-engine";function qc(){let e=zh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!Gh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Yh(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Bc(Hc(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Bc(Hc(e,r)).size/1024).toFixed(1);console.log(` ${D(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}K();import{createSession as Kh,resolveAuth as Xh,findByName as Qh,slugify as Jh,touchSession as Zh,upsertSession as ef,resolveActiveProfile as tf}from"document360-engine";async function Vc(e,t,n,o,r,s){let i=Xh(n);i.kind==="none"&&(console.error(""),console.error(D("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(g("Using your Claude subscription (no API key set)."));let c=null;try{c=tf(e,r)}catch(v){console.error(D(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(H(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(D("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Qh(e,o);v||(console.error(D(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(g(`Resuming "${v.name}"`))}let h=Kh({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();ef({uuid:b,name:Jh(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(me(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(g(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(D("agent finished with an error result"));break;case"error":console.error(""),console.error(D(`agent error: ${v.message}`)),process.exit(1)}b&&Zh(b),process.stdout.write(`
|
|
279
|
+
`),"utf8")}async function Hs(){let e=process.cwd(),t=ll(e);if(wn(t)&&!await ff({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=fl(e)??al(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:ul}),s=await Kn({message:"Screenshot output directory:",default:pl}),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:dl,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:ml(e)},h=wf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),cl(p,e),hl(e);let b=gn(e);console.log(""),console.log(M(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of yn(b))console.log($);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function fl(e){let t=cr(e,"package.json");if(!wn(t))return null;try{return JSON.parse(mf(t,"utf8")).name??null}catch{return null}}function ml(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)&&!bf(o)&&t.push(n)}return t}function bf(e){try{return gf(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 Bf}from"node:module";import{existsSync as Hf,readFileSync as qf}from"node:fs";import{dirname as _l,join as Ml}from"node:path";function $n(){let e;try{e=Vf.resolve("document360-capture/helpers")}catch{return null}let t=_l(e);for(let n=0;n<5&&!Hf(Ml(t,"package.json"));n++)t=_l(t);try{let n=JSON.parse(qf(Ml(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Vf,hr=qn(()=>{"use strict";Vf=Bf(import.meta.url)});var cu={};Ec(cu,{doctorCommand:()=>ao,renderDoctorChecks:()=>au,runDoctorChecks:()=>iu});import{existsSync as ny}from"node:fs";import{d360GetAll as oy,getAccessToken as ry,isExpired as Qi,loadProfileMap as sy,loadTokens as iy,packageSkillsDir as ru,ENGINE_VERSION as ay,projectConfigPath as cy,readProjectConfig as ly,DEFAULT_DOCS_DIR as dy,fetchManifestSummary as uy,resolveActiveProfile as py,classifyClaudeAuth as hy,CLAUDE_CODE_SETUP_HINT as su,resolveModelSetting as fy,probeModel as my,detectAppType as gy,playbookSkillName as yy,D360AuthError as wy,applyStructureOrder as ky}from"document360-engine";async function iu(e,t){let n=[],o=$n();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${ay}${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=hy();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. ${su}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:su});let i=fy(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 C=await my(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.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 ${C.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=ly(e);if(!c)return n.push({level:"fail",label:`No ${cy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??dy).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??gy(e);if(b){let C=c.appType?"from config":"auto-detected",P=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${P?` \u2192 ${yy(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{$=py(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=iy($.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=sy(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(ny(ru())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ru()}`,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${ge})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${ge}`,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 C={profile:$.name,connection:$.connection};try{await ry(C);let I=await oy(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=E?.projectId??$.project.projectId;if(P&&$.project.workspaceId){try{let I=await uy(C,P,$.project.workspaceId);if(I){let G=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${I.languages?.length??0} language${(I.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(I){I instanceof wy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??P})`,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 (${I.message.slice(0,80)})`})}try{let I=await ky({cwd:e,profileName:$.name,dryRun:!0}),G=I.categoriesReordered+I.articlesReordered;if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not published (the listing returns published articles). Publish them, then /publish re-syncs the order"});else if(G>0){let q=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${q.join(" + ")} out of order on Document360`,fix:"Run /publish \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"})}catch(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function au(e){let t=[""];for(let r of e){let s=r.level==="ok"?M("\u2713"):r.level==="warn"?H("\u26A0"):D("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("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"})`}`):D(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ao(e,t){console.log(g("Running checks\u2026"));for(let n of au(await iu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _r=qn(()=>{"use strict";wt();K();hr()});import{Command as Qb}from"commander";import{createRequire as Jb}from"node:module";import{AUTH_MODES as Zb}from"document360-engine";import{input as Ih}from"@inquirer/prompts";import{loginPkce as Oh,refreshTokens as Lh,toStoredTokens as Lc,clearTokens as _h,decodeJwtClaims as Oc,isExpired as Mh,loadTokens as Uh,saveTokens as _c,resolveActiveProfile as Qo,setProfileProject as Fh,readProjectConfig as Wh}from"document360-engine";K();import{select as $h}from"@inquirer/prompts";import{resolveActiveProfile as vh,setProfileProject as xh,resolveProjectId as Ch,listWorkspaces as Rh}from"document360-engine";async function Gn(e,t){let n=vh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ch(o);return{workspaces:await Rh(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ac=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){xh(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function jc(e,t,n){let o;try{o=await Gn(e,n)}catch(s){return console.log(D(`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(D(`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(D(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("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"):" "} ${Ac(h)} ${g(h.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let c=await $h({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Ac(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 Sh}from"@inquirer/prompts";import{resolveActiveProfile as Ph,setProfileProject as Th,listProjects as Eh}from"document360-engine";async function gt(e,t){let n=Ph(e,t),o={profile:n.name,connection:n.connection};return{projects:await Eh(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Nc=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){Th(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ic(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(D(`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(D(`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(D(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("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"):" "} ${Nc(p)} ${g(p.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Sh({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Nc(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 Dh from"picocolors";function Ah(e=process.env){return e.FORCE_HYPERLINK==="0"||!Dh.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 jh(e,t=e,n){return Ah(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Nh=/https?:\/\/[^\s\x1b]+/g;function Yn(e,t){return e.replace(Nh,n=>jh(n,n,t))}function Mc(e){return{...Oc(e.idToken)??{},...Oc(e.accessToken)??{}}}function Jo(e){let t=Mc(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(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Oh(n,{manual:e.manual,promptForRedirect:s=>Ih({message:s})},s=>console.log(Yn(s))),r=Lc(t.name,o);if(_c(r),await Is(r,t.name,s=>console.log(g(s))),console.log(""),console.log(M(`\u2713 Logged in to "${t.name}" as ${Jo(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Wh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await hn(process.cwd(),t.name))}catch{}}async function Is(e,t,n){let r=Mc(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{}Fh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Uc(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=Uh(t.name);if(!o){console.log(D(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Mh(o))if(o.refreshToken)try{let r=Lc(t.name,await Lh(n,o.refreshToken));_c(r),console.log(M(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Fc(e){let t=Qo(process.cwd(),e.profile);_h(t.name)?console.log(M(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Wc,writeProjectConfig as Bh,resolveActiveProfile as Hh,loadTokens as qh,isExpired as Vh}from"document360-engine";function er(e){let t=Wc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(D("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?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=qh(n),p=c?Vh(c)&&!c.refreshToken?H("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Wc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(D(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Bh(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(M(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Hh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(D(n.message)),process.exitCode=1}}K();import{existsSync as Gh,readdirSync as Yh,statSync as Bc}from"node:fs";import{join as Hc}from"node:path";import{apiLogDir as zh}from"document360-engine";function qc(){let e=zh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!Gh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Yh(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Bc(Hc(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Bc(Hc(e,r)).size/1024).toFixed(1);console.log(` ${D(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}K();import{createSession as Kh,resolveAuth as Xh,findByName as Qh,slugify as Jh,touchSession as Zh,upsertSession as ef,resolveActiveProfile as tf}from"document360-engine";async function Vc(e,t,n,o,r,s){let i=Xh(n);i.kind==="none"&&(console.error(""),console.error(D("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(g("Using your Claude subscription (no API key set)."));let c=null;try{c=tf(e,r)}catch(v){console.error(D(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(H(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(D("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Qh(e,o);v||(console.error(D(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(g(`Resuming "${v.name}"`))}let h=Kh({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();ef({uuid:b,name:Jh(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(me(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(g(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(D("agent finished with an error result"));break;case"error":console.error(""),console.error(D(`agent error: ${v.message}`)),process.exit(1)}b&&Zh(b),process.stdout.write(`
|
|
280
280
|
`),process.exit($)}import{createInterface as sk}from"node:readline/promises";import{createSession as La,resolveAuth as ik,getSession as ak,setTitle as ck,slugify as lk,touchSession as lp,upsertSession as dk,generateTitle as uk,resolveActiveProfile as dp,resolveModelSetting as pk,readProjectConfig as hk,resolveAndPersistAppType as fk,decodeJwtClaims as cp,isExpired as mk,loadTokens as gk,isDirectiveMention as yk,stripDirectiveMention as wk,appendDirective as kk,reconcileUpgradeActions as bk,stampArticles as $k,listArticleFiles as vk,CONTENT_CAP_VERSION as xk,applyStructureOrder as Ck,orderSyncLine as Rk}from"document360-engine";import{ENGINE_VERSION as of}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."}]}],Gc=24;function Os(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Gc:Math.min(Gc,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 nf(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 Yc(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(nf(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:of}:void 0;for(let o of Yc(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 rf}from"document360-engine";async function zc(e,t){let n=t.currentUuid(),o=n?rf(n):void 0;return console.log(o?g(`
|
|
282
282
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
@@ -285,8 +285,8 @@ try {
|
|
|
285
285
|
`)),{kind:"clear"}}async function Ms(){return{kind:"exit"}}lr();K();import{readMcpConfig as qs,writeMcpConfig as yl}from"document360-engine";async function dr(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?($f(),{kind:"continue"}):t==="add"?(vf(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(xf(e.slice(1)),{kind:"continue"}):(console.log(D(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function $f(){let e=qs(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
|
|
286
286
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
287
287
|
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${W(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function vf(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(D("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(D(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=qs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let c=1;c<o.length;c++)if(o[c]==="-H"||o[c]==="--header"){let p=o[++c],h=p?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(D(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(D(`Unexpected argument: ${o[c]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,yl(r),console.log(""),console.log(M(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function xf(e){let t=e[0];if(!t){console.log(D("Usage: /mcp remove <name>"));return}let n=qs();if(!n.servers[t]){console.log(D(`No server named "${t}".`));return}delete n.servers[t],yl(n),console.log(M(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}K();import{readFileSync as Dm}from"node:fs";import{join as Am}from"node:path";import{select as jm}from"@inquirer/prompts";import{computeSyncStatus as Sr,planPartitions as Nm,relatedArticlePaths as Im,resolveModelForOperation as Om,runPartitioned as Lm,loadProfileMap as _m,resolveActiveProfile as Mm,resolveCrossLinks as Um,applyStructureOrder as gd,orderSyncLine as yd,applyRelatedArticles as wd,relatedSyncLine as kd}from"document360-engine";import se from"picocolors";import Tl from"wrap-ansi";import Xs from"string-width";K();import kt from"picocolors";import Vs from"wrap-ansi";import Gs from"string-width";var kn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); verify: judge the captured pictures and mark them verified (runs automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],wl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function kl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(wl[n])return wl[n];let o=kn.find(r=>r.name===t);return o?o.desc:""}function bl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return kn.filter(n=>n.name.startsWith(t))}function $l(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Cf=new RegExp(`^\\s*/(?:${kn.map(e=>e.name).join("|")})(?:\\s|$)`),vl=e=>Cf.test(e),xl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Cl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Rl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Rf(e){let t=e.replace(/\r/g,"").split(`
|
|
288
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let c=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)c.push(t[o++]);o++,n.push({kind:"code",lines:c});continue}if(xl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Cl(t[o+1])){let c=Rl(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(Rl(t[o++]));n.push({kind:"table",header:c,rows:p});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let c=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];c.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:c});continue}if(r.trim()===""){o++;continue}if(vl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let i=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!vl(t[o])&&!xl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Cl(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ys(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?kt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):kt.italic(t.slice(1,-1)))}var Sf=(e,t)=>e+" ".repeat(Math.max(0,t-Gs(e)));function Pf(e,t,n){let o=e.length,r=e.map((R,C)=>Math.max(Gs(R),...t.map(P=>Gs(P[C]??"")))),s=Math.max(24,n),i=3*o+1,c=[...r],p=()=>c.reduce((R,C)=>R+C,0)+i,h=0;for(;p()>s&&h++<1e4;){let R=-1,C=6;for(let P=0;P<o;P++)c[P]>C&&(C=c[P],R=P);if(R===-1)break;c[R]-=1}let b=(R,C,P)=>kt.gray(R+c.map(
|
|
289
|
-
`)}),
|
|
288
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let c=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)c.push(t[o++]);o++,n.push({kind:"code",lines:c});continue}if(xl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Cl(t[o+1])){let c=Rl(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(Rl(t[o++]));n.push({kind:"table",header:c,rows:p});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let c=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];c.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:c});continue}if(r.trim()===""){o++;continue}if(vl(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let i=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!vl(t[o])&&!xl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Cl(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ys(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?kt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):kt.italic(t.slice(1,-1)))}var Sf=(e,t)=>e+" ".repeat(Math.max(0,t-Gs(e)));function Pf(e,t,n){let o=e.length,r=e.map((R,C)=>Math.max(Gs(R),...t.map(P=>Gs(P[C]??"")))),s=Math.max(24,n),i=3*o+1,c=[...r],p=()=>c.reduce((R,C)=>R+C,0)+i,h=0;for(;p()>s&&h++<1e4;){let R=-1,C=6;for(let P=0;P<o;P++)c[P]>C&&(C=c[P],R=P);if(R===-1)break;c[R]-=1}let b=(R,C,P)=>kt.gray(R+c.map(I=>"\u2500".repeat(I+2)).join(C)+P),$=kt.gray("\u2502"),v=(R,C)=>{let P=c.map((q,Y)=>{let he=R[Y]??"",J=C?kt.bold(he):Ys(he);return Vs(J,q,{hard:!0}).split(`
|
|
289
|
+
`)}),I=Math.max(...P.map(q=>q.length)),G=[];for(let q=0;q<I;q++)G.push(c.map((Y,he)=>`${$} ${Sf(P[he][q]??"",Y)} `).join("")+$);return G.join(`
|
|
290
290
|
`)},E=[b("\u250C","\u252C","\u2510"),v(e,!0)];return E.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((R,C)=>{E.push(v(R,!1)),E.push(C===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),E.join(`
|
|
291
291
|
`)}function Tf(e,t){switch(e.kind){case"heading":return kt.bold(e.text);case"hr":return kt.gray("\u2500".repeat(t));case"para":return Vs(Ys(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[i="",...c]=Vs(Ys(o.text),Math.max(10,t-s.length)).split(`
|
|
292
292
|
`);return` ${r} ${i}`+c.map(p=>`
|
|
@@ -316,10 +316,10 @@ ${s}${p}`).join("")}).join(`
|
|
|
316
316
|
`,"utf8")}function Zs(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function pr(e,t,n){if(t.length===0)return;let o=at(e),r=ur(e);for(let s of t){let i=s.specSource?Ol(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Zs(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Wf(e,o)}function ei(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Ol(n)||o&&r.envHash&&r.envHash!==o?null:r}function Ll(e){let t=at(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function ti(e,t,n){let o=ei(at(e),t,n,ur(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}hr();import{existsSync as Gf,readFileSync as Fl,readdirSync as Wl,writeFileSync as Yf}from"node:fs";import{isAbsolute as zf,join as Bl,resolve as Kf}from"node:path";import{readProjectConfig as Xf,DEFAULT_CAPTURE_DIR as Qf}from"document360-engine";var Ul="0.2.25";function Jf(e,t){if(!e)return!1;let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),o=n(e),r=n(t);for(let s=0;s<Math.max(o.length,r.length);s++){let i=(o[s]??0)-(r[s]??0);if(i!==0)return i>0}return!0}var Zf=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,em=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Hl="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",tm=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Hl}\\s*\\)$`),ql=e=>e[1]??e[2]??e[3]??null,nm=/^[A-Za-z_$][\w$]*$/;function om(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Hl}\\s*\\)\\s*;`).exec(e);return o?ql(o):null}function rm(e,t){let n=t.trim();if(n==="page")return null;let o=tm.exec(n);if(o){let r=ql(o);return r?{selector:r}:{unresolved:!0}}if(nm.test(n)){let r=om(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Vl(e){if(/\bcaptureShot\s*\(/.test(e))return null;let t=(e.match(/\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo/g)??[]).length;if(t>1)return{unresolved:`${t} conditional capture calls`};let n=Zf.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=rm(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let c=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!c)return null;let p=i.selector.includes("'")?'"':"'",h=e.replace(c[0],`${c[0]}
|
|
317
317
|
${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(em,""),h=h.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(h)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(h)&&(h=h.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(b,$)=>`import {${$.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function sm(e){try{return Wl(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Vl(Fl(Bl(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function im(e){let t=Xf(e)?.captureDir??Qf;return zf(t)?t:Kf(e,t)}function Gl(e,t){let n={migrated:[],skipped:[]},o=im(e);if(!Gf(o))return n;let r=t?.captureVersion===void 0?$n():t.captureVersion;if(!Jf(r,Ul))return sm(o)?{...n,heldBackForCapture:{installed:r,required:Ul}}:n;let s;try{s=Wl(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let c=i.slice(0,-8),p=Bl(o,i);try{let h=Fl(p,"utf8"),b=Vl(h);if(b===null)continue;if("unresolved"in b){n.skipped.push({id:c,receiver:b.unresolved});continue}Yf(p,b.next,"utf8"),n.migrated.push(c)}catch{}}return n}function Yl(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires d360-capture ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
|
|
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
|
-
`)}var ed=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function zl(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?ed(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 zl(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 zl(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:ed(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function ve(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 Jl(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=Zl(e,r),E=oi(am(v,p)),R=$===null?null:ei(i,p,$,c),C=i.shots[p]?.review,P=E&&lm(C,dm(v,p))?C:void 0,
|
|
319
|
+
`)}var ed=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function zl(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?ed(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 zl(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 zl(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:ed(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function ve(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 Jl(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=Zl(e,r),E=oi(am(v,p)),R=$===null?null:ei(i,p,$,c),C=i.shots[p]?.review,P=E&&lm(C,dm(v,p))?C:void 0,I=$!==null&&mm($),G=E&&P?.verdict==="ok"?"verified":E&&P?.verdict==="rejected"?"rejected":E?"captured":$===null?"placeholder":I||R?.outcome==="skipped"?"blocked":R?.outcome==="failed"?"broken":"spec",q=$===null?void 0:nd($),Y=I?gm($):R?.reason,he=I?"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&&Xl($).length>0?{unguardedWaits:Xl($)}:{},...$!==null&&Kl($).length>0?{unverifiedForce:Kl($)}:{},...G==="blocked"||G==="broken"?{...Y?{reason:Y}:{},...he?{blockedBy:he}:{}}:{},...G==="rejected"?{...P?.reason?{reason:P.reason}:{},...P?.repaired?{repaired:!0}:{}}:{}}})}function hm(e){let t=vt(e)?.outputDir??ci;return cm(Zl(e,t))}function eo(e){let t=hm(e),n=vt(e)?.outputDir??ci,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${um},${pm}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Yl(Gl(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 td(e,t){let n=vt(e)?.captureDir??br;return oi(yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`))}function fm(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 nd(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=fm(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 mm(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function gm(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 od(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 Kl(e,t=10){let n=od(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
321
|
`))||o.push(r+1));return o}function Xl(e){let t=[],n=od(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 rd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function sd(e,t){let n=vt(e)?.captureDir??br,o=yr(n)?wr(n,`${t}.spec.ts`):kr(e,n,`${t}.spec.ts`);try{return nd(ai(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var ym=["captured","verified","rejected"],wm=e=>ym.includes(e);function $r(e){return[...new Set(e.filter(t=>wm(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[`${we("\u26A0",A.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${A.magenta(o.id.padEnd(n))} ${A.gray(xn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${A.bold("/screenshot capture --failed")}`].join(`
|
|
322
|
-
`)}var km={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},bm={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},id=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function we(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 ad(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(` ${A.bold("Stage this data")} ${A.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(` ${A.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(A.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(A.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(` ${we("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function cd(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=["",` ${we("\u26A0",A.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(A.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(A.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(A.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(A.gray(s(o,p=>p.id)))}return r.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),r}function ld(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${we("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.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 dd(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 $m=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),vm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function xm(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return vm.has(r)?r.toUpperCase():o>0&&$m.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:xm(t?t[2]:e)}}function Cm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Ql(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function Rm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function ud(e,t){let n=new Map;for(let o of e){let r=dd(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 Sm(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=ud(e,t),E=[];E.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${c>0?A.yellow(`${c} ready`):A.gray("0 ready")}`+(p>0?` ${A.gray("\xB7")} ${A.cyan(`${p} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${b>0?A.red(`${b} to spec`):A.gray("0 to spec")} `+A.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Ql(r,o,32)}] ${A.bold(`${R}%`)}`),E.push("");let C=v.map(([J])=>ri(J)),P=Math.min(32,Math.max(7,...C.map(J=>J.name.length))),L=J=>J.length>P?`${J.slice(0,P-1)}\u2026`:mr(J,P),G=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];E.push(A.gray(` ${mr("#",2)} ${mr("Chapter",P)} ${$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:Fe}=C[J],ze=le===ae,lt=L(Fe),Pt=G.map(dt=>{let Yt=n(re,dt.state);return Yt>0?dt.color($t(String(Yt),dt.w)):A.gray($t("\u2014",dt.w))}).join(" ");E.push(` ${A.cyan(mr(Ze,2))} ${ze?A.green(lt):le>0?lt:A.gray(lt)} ${ze?A.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Ql(le,ae,10)} ${Rm(le,ae)}`)}E.push("");let q=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.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,he=c>Y;if(b>0)E.push(` ${we("\u2192",A.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${q}`);else if(c>0&&(he||s===0)){let J=Y>0?A.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(` ${we("\u2192",A.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${J}${q}`)}else if(s>0&&c>0)E.push(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.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(` ${we("\u2192",A.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${q}`);else if(h>0)E.push(` ${we("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.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(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.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(` ${we("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else E.push(` ${we("\u2713",A.green)}all ${o} verified \u2014 ${A.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(A.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return E.push(...ad(e),...ld(e),...cd(e,!1)),E.push(""),E.push(id),E.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Pm(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=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ud(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=ri(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${A.bold(v)} ${A.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let C=Cm(R.file),P=E.get(C)??[];E.has(C)||E.set(C,P),P.push(R)}for(let R of[...E.keys()].sort()){i.push(A.gray(` ${R}`));for(let C of E.get(R)){let P=bm[C.state];if(i.push(` ${we(km[C.state],P)}${P(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let L of Wt(xn(C.reason),84))i.push(A.gray(` ${L}`));C.state==="rejected"&&i.push(A.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...ad(e),...ld(e),...cd(e,!0)),i.push("",id),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?Pm(e,o,n):Sm(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 Jl(e)){let s=dd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function pd(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 Tm(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}=Tm(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 C=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,...C?{note:C}:{}})}}}}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 hd(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(`
|
|
322
|
+
`)}var km={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},bm={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},id=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function we(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 ad(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(` ${A.bold("Stage this data")} ${A.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(` ${A.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(A.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(A.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(` ${we("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function cd(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=["",` ${we("\u26A0",A.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(A.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(A.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(A.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(A.gray(s(o,p=>p.id)))}return r.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),r}function ld(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${we("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.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 dd(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 $m=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),vm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function xm(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return vm.has(r)?r.toUpperCase():o>0&&$m.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:xm(t?t[2]:e)}}function Cm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Ql(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function Rm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function ud(e,t){let n=new Map;for(let o of e){let r=dd(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 Sm(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=ud(e,t),E=[];E.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${c>0?A.yellow(`${c} ready`):A.gray("0 ready")}`+(p>0?` ${A.gray("\xB7")} ${A.cyan(`${p} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${b>0?A.red(`${b} to spec`):A.gray("0 to spec")} `+A.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Ql(r,o,32)}] ${A.bold(`${R}%`)}`),E.push("");let C=v.map(([J])=>ri(J)),P=Math.min(32,Math.max(7,...C.map(J=>J.name.length))),I=J=>J.length>P?`${J.slice(0,P-1)}\u2026`:mr(J,P),G=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];E.push(A.gray(` ${mr("#",2)} ${mr("Chapter",P)} ${$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:Fe}=C[J],ze=le===ae,lt=I(Fe),Pt=G.map(dt=>{let Yt=n(re,dt.state);return Yt>0?dt.color($t(String(Yt),dt.w)):A.gray($t("\u2014",dt.w))}).join(" ");E.push(` ${A.cyan(mr(Ze,2))} ${ze?A.green(lt):le>0?lt:A.gray(lt)} ${ze?A.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Ql(le,ae,10)} ${Rm(le,ae)}`)}E.push("");let q=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.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,he=c>Y;if(b>0)E.push(` ${we("\u2192",A.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${q}`);else if(c>0&&(he||s===0)){let J=Y>0?A.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(` ${we("\u2192",A.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${J}${q}`)}else if(s>0&&c>0)E.push(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.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(` ${we("\u2192",A.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${q}`);else if(h>0)E.push(` ${we("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.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(` ${we("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.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(` ${we("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else E.push(` ${we("\u2713",A.green)}all ${o} verified \u2014 ${A.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(A.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return E.push(...ad(e),...ld(e),...cd(e,!1)),E.push(""),E.push(id),E.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Pm(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=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ud(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=ri(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${A.bold(v)} ${A.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let C=Cm(R.file),P=E.get(C)??[];E.has(C)||E.set(C,P),P.push(R)}for(let R of[...E.keys()].sort()){i.push(A.gray(` ${R}`));for(let C of E.get(R)){let P=bm[C.state];if(i.push(` ${we(km[C.state],P)}${P(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let I of Wt(xn(C.reason),84))i.push(A.gray(` ${I}`));C.state==="rejected"&&i.push(A.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...ad(e),...ld(e),...cd(e,!0)),i.push("",id),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?Pm(e,o,n):Sm(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 Jl(e)){let s=dd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function pd(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 Tm(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}=Tm(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 C=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,...C?{note:C}:{}})}}}}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 hd(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 Em(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 fd(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(A.gray(r)),o.mode==="list"){let p=t?.cwd??process.cwd(),h=di(p,o.scope),b=vt(p)?.docsDir??li,$=ve(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?["",...Em(n.prior)]:[]].join(`
|
|
@@ -331,7 +331,7 @@ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await ca
|
|
|
331
331
|
`)}async function vd(e,t){let n=t?.cwd??process.cwd();return Wm(n)?{kind:"forward-to-agent",prompt:yi(),display:"/discover"}:(console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"})}K();import{checkbox as Bm}from"@inquirer/prompts";import{inventoryRepo as Hm,readProjectConfig as xd,writeProjectConfig as qm}from"document360-engine";function wi(e,t){let n=xd(e);n&&(n.authoritativeSourceFiles=t,qm(n,e))}function Ar(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Cd(e,t){let n=t?.cwd??process.cwd();if(!xd(n))return console.log(D("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Hm(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(W("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(Ar(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Bm({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ar(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};wi(n,r),console.log(M(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}K();import{confirm as eg}from"@inquirer/prompts";import{applyPull as $i,computeSyncStatus as Nd,compareRemoteSources as tg,planPull as Id,planImport as ng,applyImport as og,establishBaselines as rg,rebaselineServerMeta as sg,D360AuthError as ig}from"document360-engine";K();var Rd=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:D,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:W,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:D,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:D,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:me,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:me,mark:"\xB7"}];function Vm(e){return e.path?e.path:`${e.title??"(untitled)"} ${me(`[${e.articleId}]`)}`}function Gm(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function jr(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Ee("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${H("~")} ${H(b.path??"")} ${me(`\u2192 "${b.link.title}"`)}`)}for(let b of Rd){let $=e.entries.filter(v=>v.status===b.status&&!(b.status==="untracked-local"&&v.link));if($.length!==0){n.push(""),n.push(Ee(b.header));for(let v of $)n.push(` ${b.paint(b.mark)} ${b.paint(Vm(v))}${v.detail?me(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=o.length,p=s===r?M("\u2713 everything up to date"):[r>0?M(`\u2713 ${r} up to date`):null,c>0?`${c} to link`:null,...Rd.map(b=>{let $=(e.counts[b.status]??0)-(b.status==="untracked-local"?c:0);return $>0?`${$} ${i[b.status]}`:null})].filter(Boolean).join(me(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${Gm(t)}`:"";return n.push(p+me(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as Ym}from"diff";import Sd from"picocolors";var Pd=80,zm="\x1B[48;2;74;28;28m",Km="\x1B[48;2;24;66;24m",Td="\x1B[49m",ki=e=>String(e).padStart(5);function Ed(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Dd(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function ct(e,t,n){let o=v=>{let E=v.replace(/\r\n/g,`
|
|
332
332
|
`);return E.endsWith(`
|
|
333
333
|
`)||E===""?E:E+`
|
|
334
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),c=Ym("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];c.hunks.forEach((v,E)=>{E>0&&b.push(Sd.gray(" \u2026"));let R=v.oldStart,C=v.newStart,P=[],L=[],G=()=>{for(let q=0;q<P.length;q++){let Y=q<L.length?Ed(P[q],L[q]):void 0;h++,b.push(`${zm}${ki(R++)} - ${Dd(P[q],i,Y)}${Td}`)}for(let q=0;q<L.length;q++){let Y=q<P.length?Ed(P[q],L[q]):void 0;p++,b.push(`${Km}${ki(C++)} + ${Dd(L[q],i,Y)}${Td}`)}P=[],L=[]};for(let q of v.lines){let Y=q[0],he=q.slice(1);Y==="-"?P.push(he):Y==="+"?L.push(he):(G(),b.push(Sd.gray(ki(C))+" "+he.slice(0,i)),R++,C++)}G()});let $=b.slice(0,Pd);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Pd)}}K();import{select as Xm}from"@inquirer/prompts";import{applyPull as Qm,computeSyncStatus as Jm,planPull as Zm}from"document360-engine";var Ad=e=>e===1?"":"s";async function bi(e,t){console.log(""),console.log(`${W("\u25CF")} ${Ee(t.title)} ${me(`(${t.path})`)}`);for(let r of t.notes)console.log(H(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(me(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Ad(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Xm({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Qm({cwd:e.cwd,profileName:e.profileName},t),console.log(M(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function jd(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Jm({cwd:t.cwd,profileName:t.profileName})).entries.filter(c=>c.status==="conflict"&&c.path).map(c=>c.path);if(o){if(!s.includes(o))return console.log(M(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(M("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let c of s){let p=await Zm({cwd:t.cwd,profileName:t.profileName,relPath:c});await bi(t,p)==="keep-local"&&i.push(c)}if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${Ad(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(D(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Od(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ag(t),{kind:"continue"};if(o==="--baseline")return await cg(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await lg(t),{kind:"continue"};if(o)return console.log(D(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await dg(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await vi({cwd:t.cwd,profileName:t.profileName});for(let i of xi(s))console.log(i.tone==="ok"?M(i.text):i.tone==="warn"?H(i.text):g(i.text));console.log("")}catch(r){r instanceof ig?console.log(D(r.message)):console.log(D(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function vi(e){let t=await Nd({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await Id({cwd:e.cwd,profileName:e.profileName,relPath:o.path});$i({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await ng({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});og({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var Nr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ht=e=>e===1?"":"s";function xi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Ht(e.pulled.length)} into local: ${Nr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Ht(e.imported.length)}: ${Nr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Ht(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${Nr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Ht(e.failed.length)} failed: ${Nr(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function ag(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Nd({cwd:e.cwd,profileName:e.profileName});for(let o of jr(n,Date.now()-t))console.log(o);console.log("")}async function cg(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await rg({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await sg({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(M("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(M(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(M(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function lg(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await tg({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ee(String(t.legacyCount))} \xB7 Manifest: ${Ee(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(M("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(D(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function dg(e,t){let n=t.replace(/\\/g,"/"),o=await Id({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bi(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Ee(o.title)} ${me(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=ct(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),$i({cwd:e.cwd,profileName:e.profileName},o);return}console.log(me(` \u23BF Added ${r.added} line${Ht(r.added)}, removed ${r.removed} line${Ht(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>eg({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}$i({cwd:e.cwd,profileName:e.profileName},o),console.log(M(` \u2713 Pulled ${o.path} (sync base advanced).`))}K();import{statSync as ug}from"node:fs";import{resolve as pg}from"node:path";import{estimateBulkCost as hg,planPartitions as fg,readProjectConfig as mg,resolveModelForOperation as gg,runPartitioned as yg,trackedArticlePaths as wg}from"document360-engine";var Ci=3;function Ri(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Si(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Pi(e,t){return t.map(n=>{let o=0;try{o=ug(pg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ti(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
334
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),c=Ym("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];c.hunks.forEach((v,E)=>{E>0&&b.push(Sd.gray(" \u2026"));let R=v.oldStart,C=v.newStart,P=[],I=[],G=()=>{for(let q=0;q<P.length;q++){let Y=q<I.length?Ed(P[q],I[q]):void 0;h++,b.push(`${zm}${ki(R++)} - ${Dd(P[q],i,Y)}${Td}`)}for(let q=0;q<I.length;q++){let Y=q<P.length?Ed(P[q],I[q]):void 0;p++,b.push(`${Km}${ki(C++)} + ${Dd(I[q],i,Y)}${Td}`)}P=[],I=[]};for(let q of v.lines){let Y=q[0],he=q.slice(1);Y==="-"?P.push(he):Y==="+"?I.push(he):(G(),b.push(Sd.gray(ki(C))+" "+he.slice(0,i)),R++,C++)}G()});let $=b.slice(0,Pd);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Pd)}}K();import{select as Xm}from"@inquirer/prompts";import{applyPull as Qm,computeSyncStatus as Jm,planPull as Zm}from"document360-engine";var Ad=e=>e===1?"":"s";async function bi(e,t){console.log(""),console.log(`${W("\u25CF")} ${Ee(t.title)} ${me(`(${t.path})`)}`);for(let r of t.notes)console.log(H(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(me(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Ad(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Xm({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Qm({cwd:e.cwd,profileName:e.profileName},t),console.log(M(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function jd(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Jm({cwd:t.cwd,profileName:t.profileName})).entries.filter(c=>c.status==="conflict"&&c.path).map(c=>c.path);if(o){if(!s.includes(o))return console.log(M(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(M("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let c of s){let p=await Zm({cwd:t.cwd,profileName:t.profileName,relPath:c});await bi(t,p)==="keep-local"&&i.push(c)}if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${Ad(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(D(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Od(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(D(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ag(t),{kind:"continue"};if(o==="--baseline")return await cg(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await lg(t),{kind:"continue"};if(o)return console.log(D(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await dg(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await vi({cwd:t.cwd,profileName:t.profileName});for(let i of xi(s))console.log(i.tone==="ok"?M(i.text):i.tone==="warn"?H(i.text):g(i.text));console.log("")}catch(r){r instanceof ig?console.log(D(r.message)):console.log(D(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function vi(e){let t=await Nd({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await Id({cwd:e.cwd,profileName:e.profileName,relPath:o.path});$i({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await ng({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});og({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var Nr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ht=e=>e===1?"":"s";function xi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Ht(e.pulled.length)} into local: ${Nr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Ht(e.imported.length)}: ${Nr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Ht(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Ht(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${Nr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Ht(e.failed.length)} failed: ${Nr(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function ag(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Nd({cwd:e.cwd,profileName:e.profileName});for(let o of jr(n,Date.now()-t))console.log(o);console.log("")}async function cg(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await rg({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await sg({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(M("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(M(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(M(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function lg(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await tg({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ee(String(t.legacyCount))} \xB7 Manifest: ${Ee(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(M("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(D(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function dg(e,t){let n=t.replace(/\\/g,"/"),o=await Id({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bi(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Ee(o.title)} ${me(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=ct(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),$i({cwd:e.cwd,profileName:e.profileName},o);return}console.log(me(` \u23BF Added ${r.added} line${Ht(r.added)}, removed ${r.removed} line${Ht(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>eg({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}$i({cwd:e.cwd,profileName:e.profileName},o),console.log(M(` \u2713 Pulled ${o.path} (sync base advanced).`))}K();import{statSync as ug}from"node:fs";import{resolve as pg}from"node:path";import{estimateBulkCost as hg,planPartitions as fg,readProjectConfig as mg,resolveModelForOperation as gg,runPartitioned as yg,trackedArticlePaths as wg}from"document360-engine";var Ci=3;function Ri(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function Si(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Pi(e,t){return t.map(n=>{let o=0;try{o=ug(pg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ti(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
335
335
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
336
336
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
337
337
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
@@ -347,7 +347,7 @@ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await ca
|
|
|
347
347
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
348
348
|
Articles:
|
|
349
349
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
350
|
-
`)}function _i(e,t,n){let o=e.reduce((i,c)=>i+c.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${De(r)}\u2013${De(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Mi(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),c=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${De(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Wrote ${v(i)} (${$}) successfully \xB7 ${b}.`),E.push("Next \u2014 push them to Document360:"),E.push("/publish --all"),E.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{E.push(`Wrote ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}function Ui(e,t,n){try{let o=Tg({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Fi(e,t,n){let o=(Wd(e)?.docsDir??Ag).replace(/\/+$/,""),r=t.map(c=>c.path);if(n.path){let c=Mg(n.path,o);return r.includes(c)?{docsDir:o,targets:[c],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${c}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Ug(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let i=Ii(e,o,s);if(i.length===0){let c=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${c} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}async function Bd(e,t){if(!Wd(t.cwd))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ir(e)){for(let
|
|
350
|
+
`)}function _i(e,t,n){let o=e.reduce((i,c)=>i+c.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${De(r)}\u2013${De(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Mi(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),c=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${De(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Wrote ${v(i)} (${$}) successfully \xB7 ${b}.`),E.push("Next \u2014 push them to Document360:"),E.push("/publish --all"),E.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{E.push(`Wrote ${c}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}function Ui(e,t,n){try{let o=Tg({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Fi(e,t,n){let o=(Wd(e)?.docsDir??Ag).replace(/\/+$/,""),r=t.map(c=>c.path);if(n.path){let c=Mg(n.path,o);return r.includes(c)?{docsDir:o,targets:[c],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${c}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Ug(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let i=Ii(e,o,s);if(i.length===0){let c=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${c} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}async function Bd(e,t){if(!Wd(t.cwd))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ir(e)){for(let I of _d(t.cwd,t.profileName))console.log(g(I));return{kind:"continue"}}if(Ct("write",e)){let I=Cn(t.cwd,"write",e,t.profileName);if(I.length>0){for(let G of I)console.log(g(G));return{kind:"continue"}}}let n=Dg(t.cwd);if(n.length===0)return console.log(D("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:i,rewrite:c}=Ni(e),{docsDir:p,targets:h,reason:b,rewriting:$}=Fi(t.cwd,n,{scope:o,path:r,rewrite:c});if(h.length===0)return console.log(b?H(b):H("Nothing to write.")),{kind:"continue"};$&&console.log(H(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=Eg(h),E=ji(i),{model:R,forced:C}=jg(t.cwd,"standard"),P=!!r;if(s&&!P){let I=Pg({files:Oi(t.cwd,n,h),op:"write",model:R});o&&console.log(g(`Scope: ${o} (${h.length} pending).`));for(let G of _i(v,I,E))console.log(G);return console.log(g(`Model: ${R}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${h.length} article${h.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${E} agents at once) on ${R}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let I of Ng({cwd:t.cwd,partitions:v,promptFor:G=>Li(G,p,{rewrite:$||P}),concurrency:E,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(I.type==="partition_status")I.status==="running"?console.log(g(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(M(` \u2713 ${I.label}`)):console.log(D(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Mi(I.results,v,G))console.log(I.ok?M(Y):H(Y));if(I.ok)try{Ig(t.cwd,h.map(Y=>`${p}/${Y}`),{writtenCap:Og})}catch{}let q=Ui(t.cwd,p,h);q&&console.log(H(q))}}catch(I){console.log(D(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}K();import{existsSync as Fg,readdirSync as Hd,statSync as qd}from"node:fs";import{join as Vd}from"node:path";import{inputDir as Wg,readProjectConfig as Bg}from"document360-engine";var Gd=/\.(md|markdown|pdf|txt)$/i;function Wi(e){let t=Wg(e);if(!Fg(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Hd(t)){let s=Vd(t,r),i=!1;try{i=qd(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let c=Hg(s);c>0&&n.push({name:r,docCount:c})}else Gd.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Hg(e){let t=0;for(let n of Hd(e))try{qd(Vd(e,n)).isFile()&&Gd.test(n)&&t++}catch{}return t}function Bi(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function Or(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
351
351
|
`)}var Hi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Yd(e,t){let n=t?.cwd??process.cwd();if(!Bg(n))return console.log(D("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Wi(n);if(o.length===0&&r===0)return console.log(g(Hi)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let p of o)console.log(` ${p.name} ${g(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let c=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Or(c),display:c?`/draft ${c}`:"/draft"}}let i=Bi(o,s);return{kind:"forward-to-agent",prompt:Or(i??"",i?void 0:s),display:`/draft ${s}`}}K();import{listOpenForDocs as qg,readProjectConfig as Vg}from"document360-engine";function qi(e){try{return qg(e).filter(t=>t.kind==="request").length}catch{return 0}}function Vi(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Gi(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
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 zd(e,t){let n=t?.cwd??process.cwd();if(!Vg(n))return console.log(D("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(g(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 Gg}from"@inquirer/prompts";import{findByName as Yg,getSession as zg,listSessions as Kg,relativeTime as Xd}from"document360-engine";async function Qd(e,t){let n=Kg(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("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=Yg(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(D(`No session matches "${o}".`)),Kd(n),{kind:"continue"})}if(!process.stdin.isTTY)return Kd(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Gg({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} ${Xd(c.updatedAt)}`,value:c.uuid,description:c.firstPrompt.slice(0,100)}))}})),r=zg(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Kd(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${g(Xd(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}K();import{renameSession as Xg}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 Jd(e,t){let n=zi(e.join(" "));if(!n)return console.log(D("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xg(o,n)?console.log(M(`\u2713 Session renamed to "${n}"`)):console.log(D("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 Zd,readProjectConfig as Qg,writeProjectConfig as Jg}from"document360-engine";K();function Ki(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Qg(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 Zd().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Jg(o,e),null):`Unknown environment "${r}". Known: ${Zd().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function eu(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(D(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(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}K();import{select as Zg}from"@inquirer/prompts";import{readProjectConfig as ey,readUserConfig as tu,resolveModelSetting as Xi,writeUserConfig as nu}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 ty(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=tu();return s.defaultModel?(delete s.defaultModel,nu(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}}nu({...tu(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ey(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 ou(e,t){let n=e[0]?.trim();if(!n){let i=Xi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ee("Model:")} ${W(i.model)}${i.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${ty(i)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let c=Lr(i),p;try{p=await t.withPausedInput(()=>Zg({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(g("Cancelled.")),{kind:"continue"}}let{lines:h,changed:b,effective:$}=io(t.cwd,p??"default");for(let v of h)console.log(v.startsWith("\u26A0")?H(v):v.startsWith("\u2713")?M(v):g(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")?H(i):i.startsWith("\u2713")?M(i):g(i));return r&&await t.setModel(s),{kind:"continue"}}_r();async function lu(e,t){return await t.withPausedInput(()=>hn(t.cwd)),{kind:"clear"}}async function du(e,t){return await t.withPausedInput(()=>Xo(t.cwd,t.profileName)),{kind:"clear"}}K();import{resolveActiveProfile as by}from"document360-engine";async function uu(e,t){let n=!1;try{n=by(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}K();var pu=async(e,t)=>{try{await t.withPausedInput(()=>Zo({}))}catch(n){console.log(D(`Login failed: ${n.message}`))}return{kind:"continue"}};K();import{resolveActiveProfile as $y,clearTokens as vy,clearProfileProject as xy}from"document360-engine";async function hu(e,t){let n;try{n=$y(t.cwd,t.profileName).name}catch(r){return console.log(D(r.message)),{kind:"continue"}}let o=vy(n);return xy(t.cwd,n),console.log(o?M(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as mu}from"node:child_process";import{existsSync as Zi,readFileSync as Ji,statSync as Ay}from"node:fs";import{homedir as jy}from"node:os";import{basename as Ny,join as po}from"node:path";import{readProjectConfig as Iy,DEFAULT_OUTPUT_DIR as Oy,existingAnnotatedShotPath as Ly,resolveOutputDir as _y}from"document360-engine";import Ae from"picocolors";import{annotationsPath as Cy,resolveOutputDir as Ry,readProjectConfig as Sy,DEFAULT_OUTPUT_DIR as Py,existingAnnotatedShotPath as Ty}from"document360-engine";function Ey(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=Ry(e,Sy(e)?.outputDir??Py),o=new Map(ve(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(Ty(n,i))}`,` facts: ${r(Cy(n,i))}`,` article: ${c}`].join(`
|
|
353
353
|
`)}).join(`
|
|
@@ -378,13 +378,13 @@ ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reach
|
|
|
378
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${xe(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${xe(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${xe(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${xe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${xe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${xe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${xe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${xe(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${xe(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${xe(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${xe(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Zu(e){return e.find(t=>t.lead||t.picker)??null}function Ta(e,t){let n=Zu(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(Ow),i.join(`
|
|
380
380
|
|
|
381
|
-
`)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Mw(e);if(!e.hasDocs){let s=Zu(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:Lw,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${xe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${xe(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${xe(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 Aa}from"node:fs";import{spawnSync as Uw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as tp,resolveActiveProfile as np,loadTokens as Fw,isExpired as Ww,loadProfileMap as op,localAheadPaths as Bw,loadKnownConflicts as Hw,readDocsPlan as qw,devHintsGuidePath as Vw,DEFAULT_DOCS_DIR as Da,roadmapProgress as Gw,listRoadmap as Yw,readProductBriefState as zw,reconcileCommitRequest as Kw}from"document360-engine";wt();function ep(e){try{return Aa(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=>ep(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ep(Kr(e,o)))}function Na(e,t){try{let n=tp(e);if(!n)return!1;let o=np(e,t),r=op(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Da).replace(/\/+$/,""));return!!(Ea(s)&&Aa(s).length>0||Ea(Vw(e)))}catch{return!1}}function ko(e,t,n){try{let o=tp(e);if(!o)return null;let r=np(e,t),s=Fw(r.name),i=!!s&&(!Ww(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=op(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Da).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Aa(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Uw("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=qw(e);if(ae.length>0){let Ze=(o.docsDir??Da).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Fe=>Fe.path)).length}}catch{}let R=fo(e),C=mo({...R,directives:0}),P=Bw(e,t),
|
|
381
|
+
`)}function wo(e){if(!e.ready)return{kind:"idle"};let t=Mw(e);if(!e.hasDocs){let s=Zu(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:Lw,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${xe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${xe(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${xe(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 Aa}from"node:fs";import{spawnSync as Uw}from"node:child_process";import{join as Kr}from"node:path";import{readProjectConfig as tp,resolveActiveProfile as np,loadTokens as Fw,isExpired as Ww,loadProfileMap as op,localAheadPaths as Bw,loadKnownConflicts as Hw,readDocsPlan as qw,devHintsGuidePath as Vw,DEFAULT_DOCS_DIR as Da,roadmapProgress as Gw,listRoadmap as Yw,readProductBriefState as zw,reconcileCommitRequest as Kw}from"document360-engine";wt();function ep(e){try{return Aa(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=>ep(Kr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ep(Kr(e,o)))}function Na(e,t){try{let n=tp(e);if(!n)return!1;let o=np(e,t),r=op(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Kr(e,(n.docsDir??Da).replace(/\/+$/,""));return!!(Ea(s)&&Aa(s).length>0||Ea(Vw(e)))}catch{return!1}}function ko(e,t,n){try{let o=tp(e);if(!o)return null;let r=np(e,t),s=Fw(r.name),i=!!s&&(!Ww(s)||!!s.refreshToken),c=Na(e,t)||!ja(e,o.authoritativeSourceFiles),p=op(e,r.name),h=p?Object.keys(p.articles).length:0,b=Kr(e,(o.docsDir??Da).replace(/\/+$/,"")),$=!1;try{$=Ea(b)&&Aa(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let ae=Uw("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=qw(e);if(ae.length>0){let Ze=(o.docsDir??Da).replace(/\/+$/,"");E=Ii(e,Ze,ae.map(Fe=>Fe.path)).length}}catch{}let R=fo(e),C=mo({...R,directives:0}),P=Bw(e,t),I=new Set(Hw(e,r.name)),G=P.filter(ae=>I.has(ae)).length,q=P.length-G,Y=qe(e),he=Gw(e),J=Kw(e,new Date().toISOString()),re=zw(e),le=re?{status:re.status,openQuestions:re.openQuestions}:null;return!le&&$&&Yw(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(le={status:"pending",openQuestions:0}),{ready:i&&c&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:C,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:ge,builderStarted:it(e),genreUnknown:n.genreUnknown,roadmap:he,discovery:le,uncommittedDocs:J.dirty.length}}catch{return null}}K();var Xw={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"},sp=160,Oa=200,ip=40;function _e(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function rp(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}: ${_e(typeof r=="string"?r:JSON.stringify(r),ip)}`);return t.length>4&&n.push("\u2026"),_e(n.join(", "),sp)}var Qw=new Set(["file_path","notebook_path"]);function Jw(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 Zw(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 ek(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=Zw(t.local_path);return n("Create article",`"${_e(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=Ia(t.article_id);return n("Update article",o?`"${_e(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)?`"${_e(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?_e(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=ek(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:rp(t)}}let o=Xw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Qw.has(o)?Jw(r,n):r;return{title:e,sep:"",arg:_e(s,sp)}}return{title:e,sep:"",arg:rp(t)}}function tk(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 nk(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(tk).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>_e(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}: ${_e(String(r),ip)}`);return n.length>0?[_e(n.join(" \xB7 "),Oa)]:null}return null}function ok(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 rk(e,t,n){switch(e){case"d360_create_article":{let o=ok(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 ${_e(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=rk(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=nk(r)??r.split(`
|
|
383
|
-
`);return{lines:s.slice(0,t).map(i=>_e(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 ap(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 ap(e,"url")}function ts(e){return ap(e,"preview_url")}var up=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Sk(e,t,n,o){if(up.test(e))try{let r=dp(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 pp(e=process.cwd(),t="auto",n,o){let r=ik(t);r.kind==="none"&&(console.error(""),console.error(D("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)),Pk(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" 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=sk({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let C=b;b=null,C(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 C=R.trim();if(C){if(C.startsWith("/")){let P=Ju(C);if(!P)continue;let
|
|
383
|
+
`);return{lines:s.slice(0,t).map(i=>_e(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 ap(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 ap(e,"url")}function ts(e){return ap(e,"preview_url")}var up=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Sk(e,t,n,o){if(up.test(e))try{let r=dp(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 pp(e=process.cwd(),t="auto",n,o){let r=ik(t);r.kind==="none"&&(console.error(""),console.error(D("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)),Pk(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" 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=sk({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let C=b;b=null,C(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 C=R.trim();if(C){if(C.startsWith("/")){let P=Ju(C);if(!P)continue;let I=Qu[P.name];if(!I){console.log(D(`Unknown command: /${P.name}`)),console.log(g("Type /help for the list."));continue}let G=await I(P.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=ak(G.uuid);c={uuid:G.uuid,firstPrompt:q?.firstPrompt??null,titleFired:!0},lp(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"),he=q.slice(1).find(ae=>!ae.startsWith("--")),J=Y?vk(e,he):[],re=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),le=re?q[2]&&!q[2].startsWith("--")?[q[2]]:co(ve(e)):[];if(await _a(i,G.prompt,r,c,e,n),Y)try{$k(e,J,{reviewedCap:xk})}catch{}if(re&&le.length>0)try{for(let ae of uo(e,le))console.log(ae)}catch{}}else Tk(e,n);continue}if(yk(C)){let P=wk(C);if(P){try{kk(e,{title:P,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await _a(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${P}". 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 "${P}" and the article path(s) you wrote.`,r,c,e,n);continue}}c.firstPrompt||(c.firstPrompt=C),await _a(i,C,r,c,e,n)}}}finally{i.close(),p.close()}}function Pk(e,t){console.log(""),console.log(Vn("document360-writer")),console.log(g(` cwd: ${e}`));let n=pk(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ek(e,t)),!hk(e))console.log(H(" 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(H(` ${r}`))}catch{}try{let r=fk(e);r.persisted&&r.appType?console.log(g(` \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=bk(e);for(let s of or(r.applied))console.log(H(` ${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"?H:g;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(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Tk(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(g(` Next: ${yo(o.rec.lead)}`))}catch{}}function Ek(e,t){try{let n=dp(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=gk(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...cp(r.idToken)??{},...cp(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return mk(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function Dk(){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 Ak(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;dk({uuid:t,name:r??lk(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function jk(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||uk(o,t).then(r=>{r&&ck(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r,s){let i=new Map,c=!1;for await(let p of e.send(t))p.type==="tool"&&up.test(p.name)&&(c=!0),Nk(p,o,r,n,i);if(c)try{let p=Rk(await Ck({cwd:r,profileName:s}));p&&console.log(p)}catch{}}function Nk(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ak(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(`
|
|
385
385
|
|
|
386
386
|
`),console.log(`${M("\u25CF")} ${Ee(s.title)}${s.arg!==null?me(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let i=c=>c===1?"":"s";console.log(me(` \u23BF Added ${s.added} line${i(s.added)}, removed ${s.removed} line${i(s.removed)}`));for(let c of s.lines)console.log(c);s.hidden>0&&console.log(g(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let i=Qr(e.output,4,e.isError?void 0:s.name,s.input),c=e.isError?D:me;i.lines.forEach((p,h)=>console.log(c((h===0?" \u23BF ":" ")+p))),i.hidden>0&&console.log(g(` \u2026 +${i.hidden} lines`)),e.isError||Sk(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
387
|
-
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${Qn(s)}\u2192${Qn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(lp(t.uuid),t.titleFired||jk(t,n));break}case"error":console.error(""),console.error(D(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Dk();break}}import{render as Yb}from"ink";import{resolveAuth as zb}from"document360-engine";import{useCallback as ee,useEffect as Ue,useMemo as qa,useRef as oe,useState as X}from"react";import{Box as ue,Text as
|
|
387
|
+
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${Qn(s)}\u2192${Qn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(lp(t.uuid),t.titleFired||jk(t,n));break}case"error":console.error(""),console.error(D(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Dk();break}}import{render as Yb}from"ink";import{resolveAuth as zb}from"document360-engine";import{useCallback as ee,useEffect as Ue,useMemo as qa,useRef as oe,useState as X}from"react";import{Box as ue,Text as O,useApp as zk,useInput as Kk,useStdout as Xk}from"ink";import{existsSync as En,readFileSync as cs,readdirSync as Qk}from"node:fs";import{basename as vo,isAbsolute as Jk,join as Va}from"node:path";import{createSession as Lp,classifyClaudeAuth as Za,CLAUDE_CODE_SETUP_HINT as Zk,loginPkce as eb,toStoredTokens as tb,saveTokens as nb,getAccessToken as ob,resolveActiveProfile as Me,resolveProjectId as rb,getArticle as sb,decodeJwtClaims as An,isExpired as St,loadTokens as Gt,clearTokens as ib,clearProfileProject as ab,setTitle as cb,slugify as lb,touchSession as Ga,upsertSession as db,generateTitle as _p,findByName as ub,listSessions as pb,renameSession as hb,suggestNextAction as fb,readProjectConfig as de,writeProjectConfig as Mp,resolveAndPersistAppType as mb,detectAppType as gb,resolveModelSetting as ec,loadProfileMap as Up,applyPull as Fp,computeSyncStatus as Ya,lintDocs as Wp,compareRemoteSources as yb,planPull as Bp,establishBaselines as wb,rebaselineServerMeta as kb,inventoryRepo as bb,knownEnvironments as $b,resolveEnvironment as vb,planPartitions as za,partitionEvenly as xb,screenshotPlaceholderIds as Cb,trackedArticlePaths as Rb,runPartitioned as ls,estimateBulkCost as Hp,resolveModelForOperation as ds,readDocsPlan as Sb,checkForUpdate as Pb,detectInstallKind as Tb,isSelfUpdatable as Eb,devHintsGuidePath as qp,toolFeedbackPath as Vp,reconcileToolFeedback as Db,reconcileUpgradeActions as Ab,stampArticles as Ka,listArticleFiles as Gp,CONTENT_CAP_VERSION as Xa,ENGINE_VERSION as Zp,DEFAULT_DOCS_DIR as tc,setProfileProject as jb,writeCrashLog as Nb,applyStructureOrder as Qa,orderSyncLine as Ja,applyRelatedArticles as Yp,relatedSyncLine as zp}from"document360-engine";hr();wt();import{spawn as hp}from"node:child_process";function Ik(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Ok(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?hp([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):hp(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",i=>o(i===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Ma(e){for(let[t,n]of Ik())if(await Ok(t,n,e))return!0;return!1}var Lk=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Ua(e,t){if(t.closed)return e;let n=e.split(`
|
|
388
388
|
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Lk.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
389
389
|
`)}import{existsSync as _k,mkdirSync as Mk,readFileSync as Uk,writeFileSync as Fk}from"node:fs";import{join as fp}from"node:path";import{writerDir as Wk}from"document360-engine";function mp(e){return fp(Wk(e),".sessions")}function gp(e,t){return fp(mp(e),`${t}.json`)}function yp(e,t,n){try{Mk(mp(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Fk(gp(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Fa(e,t){try{let n=gp(e,t);if(!_k(n))return[];let o=JSON.parse(Uk(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Bk=e=>`\x1B]0;${e}\x07`,Hk=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function wp(e){process.stdout.isTTY&&process.stdout.write(e)}function Tn(e){wp(Bk(e))}function ns(e){wp(Hk(e))}var os=["\xB7 "," \xB7"],rs="\u{1F7E3}";_r();lr();K();import{Box as Wa,Text as ke}from"ink";import{jsx as be,jsxs as bo}from"react/jsx-runtime";function qk({row:e,nameW:t,width:n}){switch(e.t){case"head":return be(ke,{color:Z,bold:!0,children:e.s});case"text":return be(ke,{children:e.s});case"dim":return be(ke,{dimColor:!0,children:e.s});case"sub":return be(ke,{bold:!0,dimColor:!0,children:e.s});case"good":return be(ke,{color:"green",children:e.s});case"step":return bo(ke,{children:[be(ke,{color:Z,children:`${e.n}. `}),e.s]});case"cmd":{let o=Ls(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1);return bo(Wa,{flexDirection:"column",children:[bo(ke,{children:[" ",be(ke,{color:Z,children:o.nameCell}),!o.nameOwnLine&&be(ke,{dimColor:!0,children:` ${o.descLines[0]??""}`})]}),r.map((s,i)=>be(ke,{dimColor:!0,children:`${o.indent}${s}`},i))]})}case"gap":return be(ke,{children:" "})}}function kp({tab:e,width:t,version:n,engineVersion:o}){let r=He[e]??He[0],s=6+He.reduce((c,p)=>c+p.label.length+4,0),i="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return bo(Wa,{flexDirection:"column",paddingX:1,children:[bo(ke,{children:[be(ke,{color:Z,bold:!0,children:"Help "}),He.map((c,p)=>p===e?be(ke,{color:"white",backgroundColor:Z,bold:!0,children:` ${c.label} `},c.key):be(ke,{dimColor:!0,children:` ${c.label} `},c.key))]}),be(ke,{color:Z,children:i}),be(Wa,{flexDirection:"column",marginTop:1,children:r.rows.map((c,p)=>be(qk,{row:c,nameW:Os(r.rows),width:t},p))}),be(ke,{dimColor:!0,children:`
|
|
390
390
|
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Vk=/^(?:\d+[.)]|[-*•])\s+/;function bp(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
@@ -397,7 +397,7 @@ ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reach
|
|
|
397
397
|
`),truncated:i>0||p>0}}}return{text:e,truncated:!1}}function Ip(e,t){if(t||e.length===0||/\s$/.test(e)||/[.!?:…]["')\]]?$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function Op(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
398
398
|
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as xo,jsx as _,jsxs as te}from"react/jsx-runtime";var _b={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Kp=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
399
399
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
400
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Mb(e,t,n,o){let r=Za(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",i=ec(e),c=de(e),p=(c?.docsDir??tc).replace(/\/+$/,""),h=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,b={version:t,engineVersion:Zp,captureVersion:$n(),claude:s,model:i.model,modelSource:_b[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:h};if(c===null)return b;try{let $=Me(e,o);b.profile=$.name,b.apiUrl=$.connection.apiUrl,b.prod=$.production,b.project=$.project.projectName??$.project.projectId??"(chosen at login)";let v=Gt($.name);if(v){let E={...An(v.idToken)??{},...An(v.accessToken)??{}},R=E.email??E.preferred_username??"signed in";St(v)?v.refreshToken&&(b.who=R,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=R,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function Ub(e,t){try{let n=Me(e,t),o=Gt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...An(o.idToken)??{},...An(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return St(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Xp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Fb="Ask me to write or update an article\u2026";function Dn({ch:e,dim:t}){let[n,o]=X(!0);return Ue(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),_(
|
|
400
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Mb(e,t,n,o){let r=Za(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",i=ec(e),c=de(e),p=(c?.docsDir??tc).replace(/\/+$/,""),h=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,b={version:t,engineVersion:Zp,captureVersion:$n(),claude:s,model:i.model,modelSource:_b[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:h};if(c===null)return b;try{let $=Me(e,o);b.profile=$.name,b.apiUrl=$.connection.apiUrl,b.prod=$.production,b.project=$.project.projectName??$.project.projectId??"(chosen at login)";let v=Gt($.name);if(v){let E={...An(v.idToken)??{},...An(v.accessToken)??{}},R=E.email??E.preferred_username??"signed in";St(v)?v.refreshToken&&(b.who=R,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=R,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function Ub(e,t){try{let n=Me(e,t),o=Gt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...An(o.idToken)??{},...An(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return St(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Xp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],jn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Fb="Ask me to write or update an article\u2026";function Dn({ch:e,dim:t}){let[n,o]=X(!0);return Ue(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),_(O,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Qp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Jp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Wb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Bb({startTime:e,chars:t}){let[n,o]=X(0);Ue(()=>{let p=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(p)},[]);let r=jn[n%jn.length],s=Xp[Math.floor(n/16)%Xp.length],i=Math.floor((Date.now()-e)/1e3),c=Math.round(t/4);return te(ue,{children:[_(O,{color:Z,children:` ${r} ${s}\u2026 `}),_(O,{color:"gray",children:`(${Jn(i)} \xB7 ~${c} tokens \xB7 esc to interrupt)`})]})}function Hb({text:e}){let[t,n]=X(0);return Ue(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),_(ue,{paddingX:1,children:_(O,{color:Z,children:`${jn[t%jn.length]} ${e}`})})}var qb=12e4;function Vb({p:e}){let[t,n]=X(0);Ue(()=>{let P=setInterval(()=>n(I=>I+1),150);return()=>clearInterval(P)},[]);let o=jn[t%jn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),c=Date.now()-e.lastAt>=qb,p=e.verb??"Converting",h=e.unit??"article",b=e.rows.reduce((P,I)=>P+I.items,0),$=p.toLowerCase(),v=e.rows,E=0;if(v.length>ss){let P=v.findIndex(G=>G.status==="active"||G.status==="pending"),I=Math.max(0,Math.min(P-2,v.length-ss));E=v.slice(0,I).filter(G=>G.status==="done").length,v=v.slice(I,I+ss)}let R=Math.min(40,Math.max(...v.map(P=>Ba(P.label).length),0)),C=P=>P==="failed"?"red":P==="active"?Z:void 0;return te(ue,{flexDirection:"column",children:[te(ue,{children:[_(O,{color:Z,children:` ${o} ${p} ${b} ${h}${b===1?"":"s"} `}),_(O,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Jn(r)} \xB7 esc to stop`})]}),E>0&&_(O,{dimColor:!0,children:` \u2714 +${E} done`}),v.map(P=>te(O,{color:C(P.status),dimColor:P.status==="done"||P.status==="pending",children:[` ${xp[P.status]} ${Ba(P.label).padEnd(R)}`,P.status==="active"&&P.itemsDone!==void 0?` (${P.itemsDone}/${P.items} ${h}${P.items===1?"":"s"})`:P.status!=="pending"?` (${P.items} ${h}${P.items===1?"":"s"})`:"",P.status==="active"?` \u2190 ${$}\u2026`:""]},P.label)),c&&_(O,{color:"yellow",children:` \u26A0 no activity for ${Jn(s)} \u2014 press esc to stop if it's wedged`})]})}var Gb=10800*1e3;function eh({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=zk(),[s,i]=X(n),[c,p]=X(null),[h,b]=X({text:"",pos:0}),$=h.text,v=ee(d=>{b(l=>{let a=typeof d=="function"?d(l.text):d;return{text:a,pos:a.length}})},[]),E=ee(d=>{b(l=>({text:l.text.slice(0,l.pos)+d+l.text.slice(l.pos),pos:l.pos+d.length}))},[]),R=ee(()=>{b(d=>{if(d.pos===0)return d;let l=d.text.slice(0,d.pos),a=Dp(l)??l.slice(0,-1);return{text:a+d.text.slice(d.pos),pos:a.length}})},[]),[C,P]=X(!1),[I,G]=X(!1),[q,Y]=X(0),[he,J]=X(!1),[re,le]=X(null),[ae,Ze]=X(null),[Fe,ze]=X([]),lt=oe(!1),Pt=oe(!1),dt=oe(!1),[Yt,sc]=X(!1),Co=oe(0),[ah,Ro]=X(!1),[ch,So]=X(!1),[ps,ic]=X(null),[lh,zt]=X(0),Tt=oe(0),[hs,Kt]=X(0),[Xt,Po]=X(null),ac=oe(new Map),dh=oe(0),Qt=oe([]),We=oe(null);We.current===null&&(We.current=Lp({cwd:e,profileName:s,allowProdWrites:!1}));let et=oe({uuid:null,firstPrompt:null,titleFired:!1}),To=oe(new Map),cc=oe(null),Jt=oe(!1),fs=oe([]),ye=oe([]),Zt=oe([]),Eo=oe(null),[lc,Et]=X(null),ms=oe(null),[Dt,At]=X(null),[tt,en]=X(null),[nt,tn]=X(null),[Se,nn]=X(null),[je,jt]=X(null),[ut,on]=X(null),[pt,Nt]=X(null),[ot,It]=X(null),[dc,Nn]=X(null),[Ne,Ot]=X(null),[Te,rn]=X(null),[uc,gs]=X([]),Lt=oe([]),In=oe(!1),Ce=oe(null),[Do,ce]=X(null),[pc,Ao]=X(null),jo=oe(!1),On=oe(null),Ln=oe(null),[Ie,_t]=X(null),[No,_n]=X(null),ys=!!(nt||Se||je||ut||pt||ot||Ne||Te||Ie||No),[hc,sn]=X(0),[fc,an]=X(0),[uh,mc]=X(0),ws=qa(()=>{try{let d=ec(e);return d.source==="auto"?`${d.model} (auto)`:d.model}catch{return null}},[e,uh]),{stdout:Be}=Xk(),[,ph]=X(0),gc=oe(`${Be.columns??80}x${Be.rows??24}`),ht=ee(()=>Math.max(20,(Be.columns??80)-1),[Be]),u=ee(d=>{Qt.current.push(d),console.log(Js(d,ht()))},[ht]),Pe=ee((d,l)=>{Co.current++,le(d),Ze(l??null)},[]),Ke=ee(()=>{Co.current++,le(null),Ze(null)},[]),ne=ee(d=>Pe(d,zr({kind:"cmd",cmd:d,reason:""})),[Pe]),Io=ee((d,l)=>{!l?.silent&&d.note&&u({kind:"note",tone:d.tone,text:d.note}),d.picker&&(ze(d.picker.options.map(a=>({cmd:a.cmd,desc:a.desc}))),Nn(d.picker.title)),d.lead&&Pe(d.lead.kind==="cmd"?d.lead.cmd:d.lead.text,zr(d.lead))},[u,Pe]),$e=ee((d,l,a="info")=>{d&&u({kind:"note",tone:a,text:d}),l&&Pe(l.kind==="cmd"?l.cmd:l.text,zr(l))},[u,Pe]),[Mn,ks]=X(null),[hh,yc]=X(!1),cn=ee(d=>{ks(d),yc(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),bs=oe(!1),$s=ee(async()=>{try{if(bs.current||!Eb(Tb())||de(e)?.mode==="engineer")return;let d=await Pb({pkg:Pn,currentVersion:o,force:!0});if(!d.updateAvailable||!d.latest)return;bs.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pn} ${d.current} \u2192 ${d.latest}\u2026 (wait for the \u2713 before you /exit)`}),So(!0),(await Br().finally(()=>So(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${d.latest} \u2014 run /exit, then relaunch to apply.`}),ne("/exit"),ic(d.latest)):u({kind:"note",tone:"warn",text:`Update available (v${d.latest}) but auto-update failed \u2014 run: ${Wr}`})}catch{}},[e,o,u,ne]),Oo=ee(d=>{let l=Ve(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),Ln.current=d,ne("/login"),!1)},[e,s,u,ne]),[Lo,vs]=X(null),Mt=ee(d=>{let l=ko(e,s,{claudeMissing:Za(t).state==="missing",allowAutoAudit:d,genreUnknown:dt.current});return l?wo(l):{kind:"idle"}},[e,s,t]),Un=oe(!0),ln=oe(!1),_o=oe(0),Fn=oe(0);Ue(()=>{let d=setInterval(()=>{if(Un.current){_o.current=0,Fn.current=0;return}if(!C)try{if(!En(qp(e)))return;if(qe(e).status==="current"){Un.current=!0,_o.current=0,Fn.current=0;let a=Mt(!1),m=a.kind==="recommend"?a.rec:null,T=ln.current?`\u2713 Your builder finished the protocol update (v${ge}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";u({kind:"note",tone:"ok",text:`${T}${m?.lead?` ${yo(m.lead)}`:""}`}),ks(null),m&&(m.lead||m.picker)?Io(m,{silent:!0}):ln.current||Pe("write the docs for this repo"),Y(V=>V+1);return}if(ln.current)return;_o.current+=1;let l=_o.current;if((l===4||l%15===0)&&Fn.current<3){Fn.current+=1;let a=Fn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:it(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(d)},[e,C,u,Mt,Io,Pe]),Ue(()=>{let d=lc??vo(e);if(!C){ns(0),Tn(`${rs} ${d}`);return}ns(3);let l=0;Tn(`${os[0]} ${d}`);let a=setInterval(()=>{l=(l+1)%os.length,Tn(`${os[l]} ${d}`)},400);return()=>clearInterval(a)},[C,e,lc]),Ue(()=>()=>ns(0),[]),Ue(()=>{let d=performance.now(),l=[],a=(w,k)=>{let y=performance.now();try{return k()}finally{let x=Math.round(performance.now()-y);x>=80&&l.push(`${w}: ${x}ms`)}};u({kind:"banner",info:a("banner",()=>Mb(e,o,t,s))});let m=Za(t).state==="missing";if(m&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
401
401
|
${Zk}
|
|
402
402
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!de(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
403
403
|
${Kp}`}),ne(m?"/doctor":"/init");return}m&&ne("/doctor");try{let w=Me(e,s),k=Gt(w.name);k&&St(k)&&k.refreshToken?ob({profile:w.name,connection:w.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(y=>y+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),ne("/login")}):(!k||St(k))&&(u({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),ne("/login"))}catch{}try{let w=de(e),k=Me(e,s),y=Gt(k.name);w&&y&&!St(y)&&ja(e,w.authoritativeSourceFiles)&&!Na(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),ne("/scope"))}catch{}try{let w=a("resolve-genre",()=>mb(e));w.persisted&&w.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&de(e)&&(dt.current=!0)}catch{}let T=qe(e);try{if(a("reconcile-devhints",()=>sr(e)),T.status!=="current"&&!it(e)){let w=ir(e);w.length&&(u({kind:"note",tone:"warn",text:w.join(`
|
|
@@ -406,7 +406,7 @@ ${Kp}`}),ne(m?"/doctor":"/init");return}m&&ne("/doctor");try{let w=Me(e,s),k=Gt(
|
|
|
406
406
|
`):"no single phase \u226580ms"}
|
|
407
407
|
cwd: ${e}`}),$s()},[]),Ue(()=>{let d=setInterval(()=>{$s()},Gb);return()=>clearInterval(d)},[$s]),Ue(()=>{if(C||he||Yt||lt.current||Pt.current||re!==null||Fe.length>0||$!==""||Mn!==null||ye.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})},[C,he,re,Fe,$,Mn,ys,q,Mt,Yt]),Ue(()=>{let d=null,l=null,a=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;let m=`${Be.columns??80}x${Be.rows??24}`;m!==gc.current&&(gc.current=m,ph(T=>T+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+El(Qt.current,ht())+"\x1B[?2026l")},80))},400)};return Be.on("resize",a),()=>{d&&clearTimeout(d),l&&clearTimeout(l),Be.off("resize",a)}},[Be,ht]);let Oe=Math.max(20,(Be.columns??80)-1),wc=qa(()=>Ub(e,s),[e,s,q]),xs=(()=>{if(ch)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 hh?{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(ye.current.length>0)return ye.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??tc).replace(/\/+$/,"")),a=(()=>{try{return En(l)&&Qk(l).length>0}catch{return!1}})();try{let m=Me(e,s),T=Gt(m.name);if(!(!!T&&!(St(T)&&!T.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:Fb,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Xe=bl($),kc=Xe.length>0&&!C,Mo=Math.max(3,Math.min(12,(Be.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?Np(c,8,Oe):null,Fo=Ne?Ne.paths.filter(d=>!Ne.query||d.toLowerCase().includes(Ne.query.toLowerCase())).slice(0,8):[],Wo=Ie?Ie.sessions.filter(d=>{let l=Ie.query.toLowerCase();return!l||d.name.toLowerCase().includes(l)||d.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Le=ee((d,l)=>{We.current?.close(),We.current=Lp({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]),bc=ee((d,l,a)=>{if(Qp.test(d))try{let m=Me(e,s),T=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&&T&&f.push(`Preview: ${Jr(m.connection.portalUrl,T,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 N=zu(e,l.display);N&&(d=`${d}
|
|
408
408
|
|
|
409
|
-
${N}`)}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),P(!0),To.current.clear();let T="",V=!1,f=!1,w=!1,k="",y={num:0,closed:!1,cueSeen:!1},x=null,S=()=>{x||(x=setTimeout(()=>{x=null,p(k.length>0?k:null)},60))},U=()=>{x&&clearTimeout(x),x=null,p(null)},B=(N=!1)=>{let{head:F,keep:
|
|
409
|
+
${N}`)}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),P(!0),To.current.clear();let T="",V=!1,f=!1,w=!1,k="",y={num:0,closed:!1,cueSeen:!1},x=null,S=()=>{x||(x=setTimeout(()=>{x=null,p(k.length>0?k:null)},60))},U=()=>{x&&clearTimeout(x),x=null,p(null)},B=(N=!1)=>{let{head:F,keep:L}=Ip(k,N);F.trim()&&u({kind:"assistant",text:Ua(F.trimEnd(),y)}),k=L,U()};try{for await(let N of We.current.send(d))if(N.type==="session"){if(!m.uuid){m.uuid=N.sessionId;let F=new Date().toISOString(),L=ms.current,j=L??lb(m.firstPrompt??"session");db({uuid:N.sessionId,name:j,renamed:!!L,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:F,updatedAt:F}),Et(j),ms.current=null}}else if(N.type==="text"){k+=N.delta,T+=N.delta;let F=Op(k);if(F>0){let L=k.slice(0,F).trimEnd();L&&u({kind:"assistant",text:Ua(L,y)}),k=k.slice(F)}S(),zt(L=>L+N.delta.length)}else if(N.type==="tool"){V=!0,Qp.test(N.name)&&(f=!0);let L=(pe=>typeof pe=="string"&&pe?pe.replace(/\\/g,"/").toLowerCase():null)(N.input.file_path??N.input.notebook_path),j=["Edit","Write","MultiEdit","NotebookEdit"].includes(N.name),z=N.name==="Read"&&L!==null&&L===cc.current;if(cc.current=j?L:null,z)B(),u({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let pe=Xr(N.name,N.input,e);pe&&(B(),u({kind:"tool",title:pe.title,sep:pe.sep,arg:pe.arg}),To.current.set(N.id,{name:N.name,input:N.input}))}}else if(N.type==="article_diff"){let F=ct(N.oldContent,N.newContent,ht());F&&(B(),u({kind:"diff",added:F.added,removed:F.removed,lines:F.lines,hidden:F.hidden}))}else if(N.type==="tool_result"){N.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(N.output)&&(jo.current=!0);let F=To.current.get(N.id);if(F){To.current.delete(N.id),B();let L=Qr(N.output,4,N.isError?void 0:F.name,F.input);u({kind:"tool-result",lines:L.lines,hidden:L.hidden,isError:N.isError}),N.isError||bc(F.name,F.input,N.output)}}else if(N.type==="result"){B(!0),sn(L=>L+N.outputTokens),an(L=>L+N.costUsd);let F=N.inputTokens+N.cacheReadTokens+N.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:N.outputTokens,costUsd:N.costUsd,ok:N.ok,...F>0?{inTokens:F,cachedPct:Math.round(N.cacheReadTokens/F*100)}:{}}),!w&&!V&&!T.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)."}),N.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(T))try{let L=Vp(e);if(En(L)){let j=cs(L,"utf8").trim();j&&(vs(j),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=N.ok&&/\?[\s*_"')\]]*$/.test(T.trimEnd()),N.ok&&y.cueSeen)sc(!0),ze([]);else{let L=N.ok?bp(T,kn.map(j=>j.name)):[];if(L.length>0)ne(L[0]);else if(N.ok&&T.trim()&&!Pt.current){let j=Mt(!1);j.kind==="recommend"&&(j.rec.lead||j.rec.picker)||fb(d,T,e).then(z=>{z&&Co.current===a&&Pe(z)}).catch(()=>{})}}if(m.uuid&&(Ga(m.uuid),!m.titleFired)){m.titleFired=!0;let L=m.uuid,j=m.firstPrompt;j&&_p(j,e).then(z=>{z&&(cb(L,z),Et(z))}).catch(()=>{})}}else N.type==="error"&&(B(!0),w=!0,N.kind==="auth"&&(jo.current=!0),u({kind:"note",text:`agent error: ${N.message}`,tone:"error"}))}finally{if(P(!1),U(),f)try{let N=Ja(await Qa({cwd:e,profileName:s}));N&&u({kind:"note",tone:N.startsWith("\u26A0")?"warn":"info",text:N})}catch{}Y(N=>N+1),et.current.uuid&&yp(e,et.current.uuid,Qt.current),jo.current?(jo.current=!1,On.current=l?.display??d,Pe("/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,bc,ht,Pe,ne,Ke,Mt]),Ft=ee(async d=>{let l=ds(e,"standard");Tt.current=Date.now(),zt(0),P(!0);let a=new AbortController;Ce.current=a;let m=async(T,V)=>{let f=za(T);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 ${T.length} article${T.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${T.length} article${T.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:y=>oo(y.paths),concurrency:no,profileName:s,allowProdWrites:Jt.current,model:l.model,signal:a.signal}))if(k.type==="partition_status")k.status==="running"?ce(y=>y&&{...y,active:[...y.active,k.label],rows:Ge(y.rows,k.label,"active"),lastAt:Date.now()}):ce(y=>y&&{...y,active:y.active.filter(x=>x!==k.label),done:y.done+1,rows:Ge(y.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(y=>{if(!y)return y;let x={...y,lastAt:Date.now()};return k.event.type==="tool"?x.tools=y.tools+1:k.event.type==="text"&&(x.chars=y.chars+k.event.delta.length),x});else if(k.type==="run_done"){w=k.aborted,an(U=>U+k.totalCostUsd),sn(U=>U+k.results.reduce((B,N)=>B+N.outputTokens,0));let y=k.aborted?"Stopped. ":"",x=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:y+mi(k.results,f,x).join(`
|
|
410
410
|
`)});let S=fi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let U=await Qa({cwd:e,profileName:s}),B=Ja(U);B?u({kind:"note",tone:"info",text:B}):U.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`})}catch(U){u({kind:"note",tone:"warn",text:`Order sync failed: ${U.message}`})}try{let U=zp(await Yp({cwd:e,profileName:s}));U&&u({kind:"note",tone:"info",text:U})}catch(U){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${U.message}`})}}}return w};try{if(!await m(d,!1)){let V=await gi(e,s,d);V.length>0&&await m(V,!0)}}catch(T){u({kind:"note",tone:"error",text:`Publish run failed: ${T.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(T=>T+1)}},[e,s,u,t]),Ss=ee(async d=>{await ie(pi(d),{display:`/publish ${d}`,quietUser:!0});try{let l=await Dr(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]),$c=ee(async(d,l)=>{let m=xb(d,3),T=ds(e,"standard"),V=new Map;for(let k of d){let y=ti(e,k,vn(e,k));y&&V.set(k,y)}Tt.current=Date.now(),zt(0),P(!0);let f=new AbortController;Ce.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 ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let w=!1;try{for await(let k of ls({cwd:e,partitions:m,promptFor:y=>fd(y,V),concurrency:6,profileName:s,allowProdWrites:Jt.current,model:T.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ce(y=>y&&{...y,active:[...y.active,k.label],rows:Ge(y.rows,k.label,"active"),lastAt:Date.now()}):ce(y=>y&&{...y,active:y.active.filter(x=>x!==k.label),done:y.done+1,rows:Ge(y.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ce(y=>{if(!y)return y;let x={...y,lastAt:Date.now()};return k.event.type==="tool"?x.tools=y.tools+1:k.event.type==="text"&&(x.chars=y.chars+k.event.delta.length),x});else if(k.type==="run_done"){an(U=>U+k.totalCostUsd),sn(U=>U+k.results.reduce((B,N)=>B+N.outputTokens,0));let y=k.results.filter(U=>U.ok).length,x=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:`${x}Authored specs \u2014 ${y}/${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{Ce.current=null,ce(null),P(!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 y=la(e);y&&u({kind:"note",tone:"info",text:y.join(`
|
|
411
411
|
`)})}},[e,s,u,ie,Bo]),vc=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}),td(e,d)&&$e(`Spec ready \u2014 /screenshot capture ${d} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${d}`,reason:""})},[e,ie,$e]),Wn=ee(async(d,l)=>{if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!ku(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)"}),P(!0),Ao("Waiting for you to finish logging in (browser window)\u2026");let j=new AbortController;Ce.current=j;let z;try{z=await bu({cwd:e,signal:j.signal})}catch(pe){u({kind:"note",tone:"error",text:`Could not launch the login: ${pe.message}`});return}finally{Ce.current=null,Ao(null),P(!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:j.signal.aborted?"warn":"error",text:j.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(j=>[j,sd(e,j)])),m=0;if(d.length>1){let j=d.filter(z=>a.get(z).mutates);if(j.length>0&&(m=j.length,d=d.filter(z=>!a.get(z).mutates),d.length===0)){u({kind:"note",tone:"warn",text:`\u26A0 All ${j.length} spec${j.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${j[0]}`});return}}else if(d.length===1&&a.get(d[0]).mutates){let j=a.get(d[0]),z=$u(e);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${j.what?`: ${rd(j.what)}`:j.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.")})}P(!0);let T=new AbortController;Ce.current=T;let V=d.map(j=>({label:j,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=vu(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?`
|
|
@@ -414,19 +414,19 @@ ${k}`:"")});let y=Date.now(),x=[];try{for(let j of d){if(T.signal.aborted)break;
|
|
|
414
414
|
${j}`).join("")});let F=Cu(U);if(F.length>0&&u({kind:"note",tone:"info",text:F.join(`
|
|
415
415
|
`)}),B.length>0){let j=Math.max(...B.map(z=>z.id.length));u({kind:"note",tone:"error",text:B.map(z=>`\u2717 ${z.id.padEnd(j)} ${Mr(z.detail)}`).join(`
|
|
416
416
|
`)})}if(pr(e,x.map(j=>({id:j.id,outcome:j.outcome,reason:j.detail,specSource:vn(e,j.id)})),new Date().toISOString()),x.length===d.length&&B.length===0&&U.length===0&&Bo(l?.runLine),S.length>0){let j=S.map(pe=>pe.id);u({kind:"note",tone:"info",text:lo(j.length)}),await ie(qt(e,j),{display:"/screenshot verify",quietUser:!0});let z=uo(e,j);z.length>0&&u({kind:"note",tone:"info",text:z.join(`
|
|
417
|
-
`)});return}let
|
|
417
|
+
`)});return}let L=Su({results:x,ids:d,articles:Pu(e,S.map(j=>j.id))});L&&$e(L.note,{kind:"cmd",cmd:L.cmd,reason:""},L.tone)},[e,u,$e,ie,Bo]),Ps=ee(d=>{let l=Gt(d);if(!l||St(l)&&!l.refreshToken)return null;let a={...An(l.idToken)??{},...An(l.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Ts=ee((d,l)=>{if(l){let a=de(e);a&&(a.defaultProfile=d,Mp(a,e))}i(d),Le(void 0,d),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${d}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ps(d)||(u({kind:"note",tone:"warn",text:`Profile "${d}" is not signed in \u2014 sign in with /login.`}),ne("/login")),Y(a=>a+1)},[e,u,Le,Ps,ne]),Ho=ee((d,l,a)=>{zo(e,d,l,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),Le(),Up(e,d)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:yn(gn(e)).join(`
|
|
418
418
|
`)}),cn(Bt()),Un.current=qe(e).status==="current",ln.current=it(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Le,cn]),qo=ee(async d=>{let l;try{l=await Gn(e,d)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),ne("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=l.workspaces.filter(T=>(T.workspace_type??"").toLowerCase()!=="apidocumentation"),m=a.length>0?a:l.workspaces;if(m.length===1){let T=m[0],V=l.workspaces.length-m.length;u({kind:"note",tone:"ok",text:`Selected the "${T.name??T.id}" workspace${V>0?" (skipped the API-documentation workspace)":""}.`}),Ho(l.profile,l.projectId,T);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${m.length} available).`}),ne("/workspace")},[e,u,Ho,ne]),Vo=ee((d,l)=>{Ko(e,d,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Le(),qo(d)},[e,u,Le,qo]),xc=ee(async d=>{let l;try{l=Me(e,d)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:a}=await gt(e,l.name),m=a.find(T=>T.id===l.project.projectId);m?.name&&jb(e,l.name,{projectName:m.name})}catch{}await qo(l.name);return}try{let{projects:a}=await gt(e,l.name);if(a.length===1){let m=a[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${m.name??m.id}".`}),Vo(l.name,{id:m.id,name:m.name});return}if(a.length>1){let m=a.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),jt({cursor:0,current:-1,rows:m,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),ne("/project")}},[e,u,qo,Vo,ne]),dn=ee(()=>{let d=ye.current[0];if(!d)return;Ke();let{plan:l,mode:a}=d;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let T of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${T}`});l.overwritesLocalChanges&&a==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let m=ct(l.oldContent,l.newContent,ht());u(m?{kind:"diff",added:m.added,removed:m.removed,lines:m.lines,hidden:m.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),a==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,ht,Ke]),Es=ee(()=>{if(ye.current.length>0){dn();return}let d=Zt.current;Zt.current=[],d.length>0?(u({kind:"note",tone:"info",text:`Publishing ${d.length} kept-local article${d.length===1?"":"s"} over the portal\u2026`}),Ft(d)):ne("/pull")},[dn,u,Ft,ne]),Cc=ee(d=>{if(ye.current.length===0)return!1;let l=d.trim().toLowerCase(),a=ye.current[0];if(a.mode==="conflict"){if(l==="l"||l==="local")ye.current.shift(),Zt.current.push(a.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${a.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){ye.current.shift();try{Fp({cwd:e,profileName:s},a.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${a.plan.path} (local overwritten, sync base advanced).`})}catch(m){u({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(l==="s"||l==="skip"||l==="n")ye.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${a.plan.path} \u2014 still a conflict.`});else{let m=ye.current.length;return ye.current=[],Zt.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return Es(),!0}if(l==="y"||l==="yes"){let m=ye.current.shift().plan;try{Fp({cwd:e,profileName:s},m),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${m.path} (sync base advanced).`})}catch(T){u({kind:"note",tone:"error",text:`Pull failed: ${T.message}`})}}else if(l==="n"||l==="no"){let m=ye.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${m.path}.`})}else{let m=ye.current.length;return ye.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${m} article(s) left untouched).`}),!0}return Es(),!0},[e,s,Es,u]),Ds=ee(async d=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Ya({cwd:e,profileName:s}),a=d?.replace(/\\/g,"/"),m=l.entries.filter(V=>V.status==="conflict"&&V.path).map(V=>V.path);if(a){if(!m.includes(a)){u({kind:"note",tone:"ok",text:`${a} isn\u2019t in conflict \u2014 nothing to resolve.`});return}m=[a]}if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let T=[];for(let V of m)try{T.push({plan:await Bp({cwd:e,profileName:s,relPath:V}),mode:"conflict"})}catch(f){u({kind:"note",tone:"error",text:`Could not load ${V} from Document360: ${f.message}`})}if(T.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ye.current=T,Zt.current=[],dn()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,dn]),Rc=ee(d=>{let l=Eo.current;if(!l)return!1;if(Eo.current=null,Ke(),d.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:m}=ba(e,l.targets);u({kind:"note",tone:m.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let T of m)u({kind:"note",tone:"error",text:` \u2717 ${T.path}: ${T.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:ar().join(`
|
|
419
419
|
`)}),cn(Ws())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
420
|
-
${Kp}`}),ne("/init"),Ro(!1),!0},[e,u,cn,Ke,ne]),Bn=ee(async d=>{let l=d.slice(1).trim().split(/\s+/),a=(l[0]??"").toLowerCase(),m=l.slice(1);if(Ro(!0),Ir(m)&&["write","check","review","reorder"].includes(a)){let f=so(e,s);if(f.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=k=>a==="write"?`/write ${Md(m,k).join(" ")}`.trim():`/${a} ${[k,...m.filter(y=>y!=="--scope")].join(" ")}`.trim();if(f.length===1){Bn(w(f[0].token));return}It({cursor:0,rows:f,run:k=>{Bn(w(k))}});return}if(Ct(a,m)){let f=so(e,s);if(f.length>1){let w=m.filter(S=>S.startsWith("--")).join(" "),k=S=>`/${a}${S?` ${a==="write"?`--scope ${S}`:S}`:""}${w?` ${w}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),y=f.reduce((S,U)=>S+U.count,0),x={token:"",label:a==="review"?`Everything \u2014 all ${y} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:`Everything \u2014 rewrite all ${y} planned articles`,count:y};It({cursor:0,rows:[x,...f],run:S=>{Bn(k(S))}});return}}let T=async f=>{let w=ea(f);if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(w.mode==="single"){await Wn([w.id],{runLine:[`/screenshot capture ${w.id}`,`/capture ${w.id}`]});return}if(w.mode==="failed"){let y=ta(e,ho(e).rows);if(y.length===0){u({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}await Wn(y);return}if(w.mode==="blocked"){let{blocked:y,rows:x}=ho(e);if(y.length===0){u({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}let S=to(x.filter(U=>U.state==="blocked")).length;u({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(S>0?` If you haven't staged ${S===1?"it":"those "+S+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Wn(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(w.mode==="all"||w.mode==="scope"){let y=w.mode==="scope"?w.scope:void 0,{ready:x,captured:S,blocked:U,rows:B}=ho(e,y),N=[...x,...S,...w.retryBlocked?U:[]];if(N.length===0&&U.length>0&&!w.retryBlocked){let
|
|
420
|
+
${Kp}`}),ne("/init"),Ro(!1),!0},[e,u,cn,Ke,ne]),Bn=ee(async d=>{let l=d.slice(1).trim().split(/\s+/),a=(l[0]??"").toLowerCase(),m=l.slice(1);if(Ro(!0),Ir(m)&&["write","check","review","reorder"].includes(a)){let f=so(e,s);if(f.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=k=>a==="write"?`/write ${Md(m,k).join(" ")}`.trim():`/${a} ${[k,...m.filter(y=>y!=="--scope")].join(" ")}`.trim();if(f.length===1){Bn(w(f[0].token));return}It({cursor:0,rows:f,run:k=>{Bn(w(k))}});return}if(Ct(a,m)){let f=so(e,s);if(f.length>1){let w=m.filter(S=>S.startsWith("--")).join(" "),k=S=>`/${a}${S?` ${a==="write"?`--scope ${S}`:S}`:""}${w?` ${w}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),y=f.reduce((S,U)=>S+U.count,0),x={token:"",label:a==="review"?`Everything \u2014 all ${y} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:`Everything \u2014 rewrite all ${y} planned articles`,count:y};It({cursor:0,rows:[x,...f],run:S=>{Bn(k(S))}});return}}let T=async f=>{let w=ea(f);if(!Ur(e)){await ie(aa(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(w.mode==="single"){await Wn([w.id],{runLine:[`/screenshot capture ${w.id}`,`/capture ${w.id}`]});return}if(w.mode==="failed"){let y=ta(e,ho(e).rows);if(y.length===0){u({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}await Wn(y);return}if(w.mode==="blocked"){let{blocked:y,rows:x}=ho(e);if(y.length===0){u({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ne("/screenshot list");return}let S=to(x.filter(U=>U.state==="blocked")).length;u({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(S>0?` If you haven't staged ${S===1?"it":"those "+S+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Wn(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(w.mode==="all"||w.mode==="scope"){let y=w.mode==="scope"?w.scope:void 0,{ready:x,captured:S,blocked:U,rows:B}=ho(e,y),N=[...x,...S,...w.retryBlocked?U:[]];if(N.length===0&&U.length>0&&!w.retryBlocked){let L=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked";$e(`All ${U.length} shot${U.length===1?"":"s"} in scope ${U.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${L}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(N.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}if(!w.retryBlocked){let L=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked",j=na(B.filter(z=>z.state==="blocked"),L);j&&u({kind:"note",tone:"info",text:j})}let F=w.mode==="scope"?[`/screenshot capture ${w.scope}`,`/capture ${w.scope}`]:["/screenshot capture --all","/capture --all"];await Wn(N,{runLine:F,...w.retryBlocked?{}:{heldBackBlocked:B.filter(L=>L.state==="blocked")}});return}let k=gu(ve(e));if(k.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ne("/screenshot");return}Nt({cursor:0,rows:k,title:"Capture screenshots \u2014 pick what to shoot:"})},V=async()=>{let f=await Sn();f.kind==="forward-to-agent"&&f.prompt&&await ie(f.prompt,{display:f.display,quietUser:!0});let w=la(e);w&&u({kind:"note",tone:"info",text:w.join(`
|
|
421
421
|
`)})};switch(a){case"help":_n({tab:0});return;case"exit":case"quit":We.current?.close(),r();return;case"clear":Le(),Qt.current=[],Ro(!1),Ke(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=Me(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await eb(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>u({kind:"note",tone:"info",text:y})),k=tb(f.name,w);if(nb(k),await Is(k,f.name,y=>u({kind:"note",tone:"info",text:y})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Jo(k)}`}),await xc(s),Ln.current){let y=Ln.current;Ln.current=null;let x=Ve(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),ne(y)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${y}.)`}),ne("/login"),Ln.current=y)}else On.current&&(Pe(On.current,"\u21E5 tab to re-send your last prompt\u2026"),On.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),Y(w=>w+1)}return}case"allow-prod":{let f=!1;try{f=Me(e,s).production}catch{}if(!f){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Jt.current=!0,Le(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=zi(m.join(" ")),w=et.current.uuid;if(!w){if(!f){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ms.current=f,Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=et.current.firstPrompt??"";_p(k,e).then(y=>{y?(Pe(`/rename ${y}`),u({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}hb(w,f),Et(f),Tn(`${rs} ${f}`),u({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=m[0],w=de(e);if(!f){let k=Object.entries(w?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=k.map(([U,B])=>({name:U,env:B.connection?.environment??"custom",prod:B.production===!0,who:Ps(U)})),x=s??w?.defaultProfile,S=Math.max(0,y.findIndex(U=>U.name===x));en({cursor:S,current:S,rows:y});return}if(f==="add"){let k=Ki(e,m[1],m[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),Ts(m[1],!1);return}if(!w?.profiles?.[f]){u({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Ts(f,!0);return}case"doctor":await ao(m,{cwd:e,version:o});return;case"genre":{await Vr(m,{cwd:e});try{dt.current=!(de(e)?.appType??gb(e))}catch{}Y(f=>f+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let f=Yr(e,m.slice(1).join(" ").trim());u({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),Y(w=>w+1);return}u({kind:"note",tone:"info",text:Sa(e).join(`
|
|
422
|
-
`)});return}case"mcp":await dr(m);return;case"init":{if(de(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=$b().map(w=>({name:w,apiUrl:vb(w).apiUrl}));tn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),w=pb(e).filter(x=>x.uuid!==et.current.uuid);if(!f){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}_t({query:"",cursor:0,sessions:w});return}let k=ub(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Le(k.uuid),et.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ga(k.uuid),Qt.current=[];let y=Fa(e,k.uuid);for(let x of y)u(x);u({kind:"note",tone:"ok",text:y.length?`Resumed "${k.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),w;try{w=await Gn(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!f){let y=w.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,y.findIndex(S=>S.id===w.current));nn({cursor:x,current:x,rows:y,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let k=js(w.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Ho(w.profile,w.projectId,k);return}case"project":{let f=m.join(" ").trim(),w;try{w=await gt(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!f){let y=w.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=y.findIndex(S=>S.id===w.current);jt({cursor:Math.max(0,x),current:x,rows:y,profile:w.profile,environment:w.environment});return}let k=Ns(w.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${w.projects.map(y=>y.name??y.id).join(", ")}`});return}Vo(w.profile,k);return}case"logout":{let f;try{f=Me(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let w=ib(f);ab(e,f),Le(),Y(k=>k+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ne("/login");return}case"publish":{if(!Oo(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let y=ve(e),x=$r(y);if(x.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=vr(y);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${x.length} article${x.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Ft(x);return}if(m[0]==="--related"&&m[1]){let y=await Dr(e,s,m[1].replace(/\\/g,"/"));if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(y);return}let f=m.filter(y=>!y.startsWith("--"));if(f[0]){await Ss(f[0]);return}let w=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let y=await Ya({cwd:e,profileName:s}),{clean:x,conflicts:S}=Pr(y.entries),U=w&&k&&S.length>0,B=Er(y.entries);if(B>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${B} article${B===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),S.length>0&&!U&&u({kind:"note",tone:"warn",text:Tr(S.length)}),x.length===0&&!U){if(S.length>0){ne("/resolve");return}u({kind:"note",tone:"ok",text:B>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let N=y.counts["unknown-base"]??0;N>0&&u({kind:"note",tone:"info",text:`(${N} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ao("Reconciling structure on Document360 (order + related articles)\u2026");try{let F=await Qa({cwd:e,profileName:s}),
|
|
422
|
+
`)});return}case"mcp":await dr(m);return;case"init":{if(de(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=$b().map(w=>({name:w,apiUrl:vb(w).apiUrl}));tn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),w=pb(e).filter(x=>x.uuid!==et.current.uuid);if(!f){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}_t({query:"",cursor:0,sessions:w});return}let k=ub(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Le(k.uuid),et.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ga(k.uuid),Qt.current=[];let y=Fa(e,k.uuid);for(let x of y)u(x);u({kind:"note",tone:"ok",text:y.length?`Resumed "${k.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),w;try{w=await Gn(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!f){let y=w.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(y.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,y.findIndex(S=>S.id===w.current));nn({cursor:x,current:x,rows:y,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let k=js(w.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Ho(w.profile,w.projectId,k);return}case"project":{let f=m.join(" ").trim(),w;try{w=await gt(e,s)}catch(y){u({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!f){let y=w.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(y.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=y.findIndex(S=>S.id===w.current);jt({cursor:Math.max(0,x),current:x,rows:y,profile:w.profile,environment:w.environment});return}let k=Ns(w.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${w.projects.map(y=>y.name??y.id).join(", ")}`});return}Vo(w.profile,k);return}case"logout":{let f;try{f=Me(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let w=ib(f);ab(e,f),Le(),Y(k=>k+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ne("/login");return}case"publish":{if(!Oo(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let y=ve(e),x=$r(y);if(x.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=vr(y);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${x.length} article${x.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Ft(x);return}if(m[0]==="--related"&&m[1]){let y=await Dr(e,s,m[1].replace(/\\/g,"/"));if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ft(y);return}let f=m.filter(y=>!y.startsWith("--"));if(f[0]){await Ss(f[0]);return}let w=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let y=await Ya({cwd:e,profileName:s}),{clean:x,conflicts:S}=Pr(y.entries),U=w&&k&&S.length>0,B=Er(y.entries);if(B>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${B} article${B===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),S.length>0&&!U&&u({kind:"note",tone:"warn",text:Tr(S.length)}),x.length===0&&!U){if(S.length>0){ne("/resolve");return}u({kind:"note",tone:"ok",text:B>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let N=y.counts["unknown-base"]??0;N>0&&u({kind:"note",tone:"info",text:`(${N} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ao("Reconciling structure on Document360 (order + related articles)\u2026");try{let F=await Qa({cwd:e,profileName:s}),L=zp(await Yp({cwd:e,profileName:s})),j=Ja(F);j?u({kind:"note",tone:"info",text:j}):F.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`}),L&&u({kind:"note",tone:"info",text:L}),u({kind:"note",tone:"ok",text:j||L?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(j||L)&&ne("/structure")}catch(F){u({kind:"note",tone:"warn",text:`Structure sync failed: ${F.message}`})}finally{Ao(null)}return}if(w){let N=(U?[...x,...S]:x).map(F=>F.path);await Ft(N),S.length>0&&!U&&ne("/resolve");return}on({cursor:0,rows:bd(x,S)})}catch(y){u({kind:"note",tone:"error",text:`Could not compute sync status: ${y.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Oo(d.trim()))return;await Ds(m.find(f=>!f.startsWith("--")));return}case"preview":{let f=m.join(" ").trim();if(!f){let k=[];try{k=Object.keys(Up(e,Me(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ot({query:"",cursor:0,paths:k});return}let w=Jk(f)?f:Va(e,f);if(En(w)){try{u({kind:"preview",name:vo(w),text:Jp(cs(w,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${w}: ${k.message}`})}return}if(Wb.test(f)){try{let k=Me(e,s),y={profile:k.name,connection:k.connection},x=k.project.projectId??rb(y),S=await sb(y,x,f);u({kind:"preview",name:S.title??f,text:S.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=m[0]?.trim();if(!f){let x=Lr(ec(e));At({cursor:x,current:x});return}let{lines:w,changed:k,effective:y}=io(e,f);for(let x of w)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});k&&(mc(x=>x+1),We.current?.setModel(y));return}case"convert":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:w}=Ri(m),k=Rb(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Si(k,f);if(y.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${k.length} are tracked overall.)`});return}let x=za(y),S=3,U=`/convert${f?` --scope ${f}`:""} --run`,B=ds(e,"light");if(!w){let F=Hp({files:Pi(e,y),op:"convert",model:B.model}),L=f?`Scope: ${f} (${y.length} of ${k.length} tracked)
|
|
423
423
|
`:"",j=`
|
|
424
|
-
Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:
|
|
425
|
-
`)+j}),ne(U);return}Tt.current=Date.now(),zt(0),P(!0);let N=new AbortController;Ce.current=N,ce({verb:"Converting",total:x.length,done:0,active:[],rows:$o(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${x.length} partitions (\u2264${S} agents at once) on ${B.model}\u2026 (esc to stop)`});try{for await(let F of ls({cwd:e,partitions:x,promptFor:Ti,concurrency:S,profileName:s,allowProdWrites:Jt.current,model:B.model,signal:N.signal}))if(F.type==="partition_status")F.status==="running"?ce(
|
|
426
|
-
`)})}}catch(F){u({kind:"note",tone:"error",text:`Convert run failed: ${F.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(F=>F+1)}return}case"write":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Sb(e);if(f.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:k,preview:y,concurrency:x,rewrite:S}=Ni(m),{docsDir:U,targets:B,reason:N,rewriting:F}=Fi(e,f,{scope:w,path:k,rewrite:S});if(B.length===0){u({kind:"note",tone:"warn",text:N??"Nothing to write."});return}F&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${B.length} already-written article${B.length===1?"":"s"} (overwrites them; git has your baseline).`});let
|
|
424
|
+
Model: ${B.model}${B.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:L+Ei(x,F,S).join(`
|
|
425
|
+
`)+j}),ne(U);return}Tt.current=Date.now(),zt(0),P(!0);let N=new AbortController;Ce.current=N,ce({verb:"Converting",total:x.length,done:0,active:[],rows:$o(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${x.length} partitions (\u2264${S} agents at once) on ${B.model}\u2026 (esc to stop)`});try{for await(let F of ls({cwd:e,partitions:x,promptFor:Ti,concurrency:S,profileName:s,allowProdWrites:Jt.current,model:B.model,signal:N.signal}))if(F.type==="partition_status")F.status==="running"?ce(L=>L&&{...L,active:[...L.active,F.label],rows:Ge(L.rows,F.label,"active"),lastAt:Date.now()}):ce(L=>L&&{...L,active:L.active.filter(j=>j!==F.label),done:L.done+1,rows:Ge(L.rows,F.label,F.status==="done"?"done":"failed"),lastAt:Date.now()});else if(F.type==="partition_event")ce(L=>{if(!L)return L;let j={...L,lastAt:Date.now()};return F.event.type==="tool"?j.tools=L.tools+1:F.event.type==="text"&&(j.chars=L.chars+F.event.delta.length),j});else if(F.type==="run_done"){an(z=>z+F.totalCostUsd),sn(z=>z+F.results.reduce((pe,rt)=>pe+rt.outputTokens,0));let L=F.aborted?"Stopped. ":"",j=t.kind==="api"?"api":"subscription";u({kind:"note",tone:F.aborted?"warn":F.ok?"ok":"warn",text:L+Di(F.results,x,j).join(`
|
|
426
|
+
`)})}}catch(F){u({kind:"note",tone:"error",text:`Convert run failed: ${F.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(F=>F+1)}return}case"write":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Sb(e);if(f.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:k,preview:y,concurrency:x,rewrite:S}=Ni(m),{docsDir:U,targets:B,reason:N,rewriting:F}=Fi(e,f,{scope:w,path:k,rewrite:S});if(B.length===0){u({kind:"note",tone:"warn",text:N??"Nothing to write."});return}F&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${B.length} already-written article${B.length===1?"":"s"} (overwrites them; git has your baseline).`});let L=za(B),j=ji(x),z=ds(e,"standard"),pe=!!k;if(y&&!pe){let Q=Hp({files:Oi(e,f,B),op:"write",model:z.model}),fe=w?`Scope: ${w} (${B.length} pending)
|
|
427
427
|
`:"",Re=`
|
|
428
|
-
Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:fe+_i(
|
|
429
|
-
`)+Re}),ne(`/write${w?` --scope ${w}`:""}`);return}Tt.current=Date.now(),zt(0),P(!0);let rt=new AbortController;Ce.current=rt,ce({verb:"Writing",total:
|
|
428
|
+
Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:fe+_i(L,Q,j).join(`
|
|
429
|
+
`)+Re}),ne(`/write${w?` --scope ${w}`:""}`);return}Tt.current=Date.now(),zt(0),P(!0);let rt=new AbortController;Ce.current=rt,ce({verb:"Writing",total:L.length,done:0,active:[],rows:$o(L),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${B.length} article${B.length===1?"":"s"} across ${L.length} partition${L.length===1?"":"s"} (\u2264${j} agents at once) on ${z.model}${z.forced?" (forced)":""}\u2026 (esc to stop)`});let pn=new Set;try{for await(let Q of ls({cwd:e,partitions:L,promptFor:fe=>Li(fe,U,{rewrite:F||pe}),concurrency:j,profileName:s,allowProdWrites:Jt.current,model:z.model,signal:rt.signal}))if(Q.type==="partition_status")Q.status==="running"?ce(fe=>fe&&{...fe,active:[...fe.active,Q.label],rows:Ge(fe.rows,Q.label,"active"),lastAt:Date.now()}):ce(fe=>fe&&{...fe,active:fe.active.filter(Re=>Re!==Q.label),done:fe.done+1,rows:Ge(fe.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let fe=null;if(Q.event.type==="tool"){let Re=vp(Q.event.name,Q.event.input,L[Q.index]?.paths??[]);Re&&!pn.has(Re)&&(pn.add(Re),fe=Q.label)}ce(Re=>{if(!Re)return Re;let Qe={...Re,lastAt:Date.now()};return Q.event.type==="tool"?Qe.tools=Re.tools+1:Q.event.type==="text"&&(Qe.chars=Re.chars+Q.event.delta.length),fe&&(Qe.rows=$p(Qe.rows,fe)),Qe})}else if(Q.type==="run_done"){an(ft=>ft+Q.totalCostUsd),sn(ft=>ft+Q.results.reduce((st,gh)=>st+gh.outputTokens,0));let fe=Q.aborted?"Stopped. ":"",Re=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:fe+Mi(Q.results,L,Re).join(`
|
|
430
430
|
`)}),!Q.aborted&&Q.ok)try{let ft=(pn.size>0?[...pn]:B).map(st=>`${U}/${st}`);Ka(e,ft,{writtenCap:Xa})}catch{}let Qe=Q.aborted?null:Ui(e,U,B);if(Qe&&u({kind:"note",tone:"warn",text:Qe}),!Q.aborted&&Q.ok){let ft=w??k??"",st=ft?` ${ft}`:"";$e(Qe?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${st} --fix, then /review${st} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${st} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Qe?`/check${st} --fix`:`/review${st} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Ce.current=null,ce(null),P(!1),Y(Q=>Q+1)}return}case"draft":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:w}=Wi(e);if(f.length===0&&w===0){u({kind:"note",tone:"info",text:Hi});return}let k=m.join(" ").trim();if(!k&&f.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
431
431
|
${f.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
432
432
|
`)}`}),ze(f.map(S=>`/draft ${S.name}`));return}let y="",x;if(k){let S=Bi(f,k);S?y=S:x=k}else y=f[0]?.name??"";await ie(Or(y,x),{display:k?`/draft ${k}`:"/draft",quietUser:!0});return}case"pull":{if(!Oo(d.trim()))return;let f=m.find(w=>w.startsWith("--"));try{if(f==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),x=await Ya({cwd:e,profileName:s});u({kind:"note",tone:"info",text:jr(x,Date.now()-y).join(`
|
|
@@ -437,11 +437,11 @@ ${S.skipped.map(B=>` - ${B.path} (${B.reason})`).join(`
|
|
|
437
437
|
`)}),$e(x.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&&$e(`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}),$e("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(x=>!x.startsWith("--")),y=w?Gp(e,k):[];if(await ie(f.prompt,{display:f.display,quietUser:!0}),w)try{Ka(e,y,{reviewedCap:Xa})}catch{}if(w)$e("\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 x=m.filter(S=>S!=="--fix").join(" ");$e(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --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=Vp(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 y of ga(w))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});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"),ic("")):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 T(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let x=ve(e),S=f.rest.find(N=>!N.startsWith("-")),U=S?[S]:co(x);if(S&&!x.some(N=>N.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(U.length===0){let N=x.filter(
|
|
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=Vp(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 y of ga(w))u({kind:"note",tone:y.startsWith("\u2713")?"ok":y.startsWith("\u2139")?"info":"warn",text:y});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"),ic("")):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 T(f.rest);return}if(f.mode==="checklist"){await V();return}if(f.mode==="verify"){let x=ve(e),S=f.rest.find(N=>!N.startsWith("-")),U=S?[S]:co(x);if(S&&!x.some(N=>N.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(U.length===0){let N=x.filter(L=>L.state==="rejected").length,F=x.filter(L=>L.state==="verified").length;u({kind:"note",tone:"info",text:N>0?`Nothing left to verify. ${N} shot${N===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:F>0?`All ${F} captured shot${F===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(U.length)}),await ie(qt(e,U),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let B=uo(e,U);B.length>0&&u({kind:"note",tone:"info",text:B.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 x=de(e)?.docsDir??tc,S=di(e,f.scope),U=ve(e,S);if(f.picker){if(U.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let j=hd(U);if(j.length===0){u({kind:"note",tone:"info",text:Cr(U,{docsDir:x}).join(`
|
|
442
442
|
`)}),$e(`\u2713 All ${U.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Nt({cursor:0,rows:j,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Cr(U,{scope:S,detail:f.detail,docsDir:x}).join(`
|
|
443
|
-
`)});let B=U.filter(j=>j.state==="placeholder").length,N=U.filter(j=>j.state==="spec").length,F=U.filter(j=>j.state==="captured").length,
|
|
444
|
-
`)}),Pe(vo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,Ds,u,Le,ie,Ft,Ss,xc]),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=>Rp(m,l))),!l||(sc(!1),Rc(l))||Cc(l))return;fs.current.push(l);let a=Ep(l,ac.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Bn(a).finally(()=>J(!1));else if(Ib(a)){u({kind:"user",text:l});let m=Ob(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{Lb(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=Ku(e,a);ie(m??a,{display:l})}},[$,Rc,Cc,Bn,ie]),Sc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=Sp(d);if(Pp(l)){let a=Tp(++dh.current,l);ac.current.set(a,l),E(a)}else E(l);return}E(d)},[E]),un=Math.max(10,Oe-6),Pc=qa(()=>is(h.text,un),[h.text,un]),As=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Ap(is(l.text,un),l.pos,d)})),[un]),Hn=ee(d=>b(l=>({...l,pos:jp(is(l.text,un),l.pos,d)})),[un]),fh=["\x1B[H","\x1B[1~","\x1BOH"],mh=["\x1B[F","\x1B[4~","\x1BOF"],Tc=ee((d,l)=>l.leftArrow?(As(-1),!0):l.rightArrow?(As(1),!0):d&&fh.includes(d)?(Hn("start"),!0):d&&mh.includes(d)?(Hn("end"),!0):l.ctrl&&d==="a"?(Hn("start"),!0):l.ctrl&&d==="e"?(Hn("end"),!0):!1,[As,Hn]);return Kk((d,l)=>{if(l.ctrl&&d==="c"){We.current?.close(),r();return}if(!L){if(C){if(l.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(Do?.verb??"work").toLowerCase(),m=Do?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),Ce.current.abort()}return}In.current||(In.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),We.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),gs([...Lt.current]),v("");return}if(Tc(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&&Sc(d);return}if(Dt){if(l.upArrow){At(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){At(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){At(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[Dt.cursor];At(null);let{lines:m,changed:T,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});T&&(mc(f=>f+1),We.current?.setModel(V));return}if(d==="s"){let a=Je[Dt.cursor];At(null),We.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){At(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 T=!1;try{let V=Gt(a);T=!!V&&!(St(V)&&!V.refreshToken)}catch{T=!1}u({kind:"note",tone:"info",text:T?`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(Se){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)<=Se.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Se.rows[Se.cursor],{profile:m,projectId:T}=Se;nn(null),Ho(m,T,a);return}if(l.escape){nn(null);return}return}if(je){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)<=je.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=je.rows[je.cursor],{profile:m}=je;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Te){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,T)=>T===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Te.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?Ds(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"?vc(a.ids[0]):$c(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(Ne){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[Ne.cursor];if(a){Ot(null);try{u({kind:"preview",name:vo(a),text:Jp(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(Ie){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[Ie.cursor];if(a){_t(null),Le(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 T of m)u(T);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(!$&&Fe.length>0&&!Yt&&d&&/^[1-9]$/.test(d)){let a=Fe[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(T=>{u({kind:"note",tone:T?"ok":"warn",text:T?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."}),T&&a&&vs(null),T&&!a&&yc(!0)});return}if(!Tc(d,l)){if(kc){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($l(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&&Sc(d)}}}),Ue(()=>{if(C||L)return;let d=Lt.current.shift();d!==void 0&&(gs([...Lt.current]),Go(d))},[C,L,Go]),te(ue,{flexDirection:"column",width:Oe,children:[Rs!==null&&te(ue,{marginTop:1,flexDirection:"column",children:[Rs.truncated&&_(I,{dimColor:!0,children:"\u2026"}),_(I,{children:Rs.text})]}),C&&(Do?_(Vb,{p:Do}):_(Bb,{startTime:Tt.current,chars:lh})),!C&&pc?_(Hb,{text:pc}):null,_(ue,{borderStyle:"round",borderColor:wc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Pc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===as(Pc,h.pos),T=Math.min(h.pos,d.end)-d.start;return te(I,{children:[_(I,{color:Z,children:l===0?"> ":" "}),m?te(xo,{children:[a.slice(0,T),_(Dn,{ch:a[T]??" "}),a.slice(T+1)]}):a||" "]},`${l}-${d.start}`)}):te(I,{children:[_(I,{color:Z,children:"> "}),ys?_(Dn,{ch:" "}):re&&!C&&ae?te(xo,{children:[_(Dn,{ch:ae[0],dim:!0}),_(I,{color:"gray",children:ae.slice(1)})]}):re&&!C?te(xo,{children:[_(Dn,{ch:re[0],dim:!0}),_(I,{color:"gray",children:re.slice(1)}),_(I,{dimColor:!0,children:" (tab)"})]}):(xs.isSetup||!ah)&&!C?te(xo,{children:[_(Dn,{ch:xs.text[0],dim:!0}),_(I,{color:"gray",children:xs.text.slice(1)})]}):_(Dn,{ch:" "})]})}),uc.length>0&&_(ue,{flexDirection:"column",paddingX:1,children:uc.map((d,l)=>_(I,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?_(kp,{tab:No.tab,width:Oe,version:o,engineVersion:Zp}):Dt?te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:"Select model"}),_(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===Dt.cursor?Z:void 0,children:[l===Dt.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===Dt.current?" \u2714":""}`.padEnd(16),_(I,{color:"gray",children:d.desc})]},d.label)),_(I,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?te(ue,{flexDirection:"column",paddingX:1,children:[_(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),_(I,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?_(I,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),_(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:[_(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),_(I,{color:"gray",children:d.apiUrl})]},d.name)),_(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Se?te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:"Switch workspace"}),_(I,{dimColor:!0,children:`environment ${Se.environment} \xB7 project ${Se.projectName??`${Se.projectId.slice(0,8)}\u2026`}`}),Se.rows.map((d,l)=>te(I,{color:l===Se.cursor?Z:void 0,children:[l===Se.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Se.current?" \u2714":""}`.padEnd(30),_(I,{color:"gray",children:d.type??""})]},d.id)),_(I,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):je?te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:"Choose project"}),_(I,{dimColor:!0,children:`environment ${je.environment}`}),je.rows.map((d,l)=>te(I,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===je.current?" \u2714":""}`.padEnd(30),_(I,{color:"gray",children:d.sub??""})]},d.id)),_(I,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Te?(()=>{let l=Math.min(Math.max(0,Te.cursor-Math.floor(7)),Math.max(0,Te.rows.length-14)),a=Te.rows.slice(l,l+14),m=Te.rows.filter(T=>T.checked).length;return te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Te.rows.length})`}),l>0?_(I,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((T,V)=>{let f=l+V;return te(I,{color:f===Te.cursor?Z:void 0,children:[f===Te.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,Oe-34)),_(I,{color:"gray",children:Ar(T)})]},T.path)}),l+14<Te.rows.length?_(I,{dimColor:!0,children:` \u2193 ${Te.rows.length-l-14} more`}):null,_(I,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?te(ue,{flexDirection:"column",paddingX:1,children:[_(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,Oe-24))),_(I,{color:"gray",children:` ${d.token}`})]},d.token)}),_(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:[_(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?" ":" ",T=`${l+1}.`.padEnd(3);return te(I,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${T} ${d.label}`.padEnd(Math.min(56,Oe-24)),d.note?_(I,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),_(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:[_(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)),T=l.slice(m,m+12),V=`${l.length}.`.length+1,f=pd(l,Math.max(20,Oe-4-V));return te(xo,{children:[m>0?_(I,{color:"gray",children:` \u2026 ${m} more above`}):null,T.map((w,k)=>{let y=m+k,x=y===a,S=f[y];return te(I,{color:x?Z:void 0,bold:(w.kind==="all"||w.kind==="category")&&!x,children:[x?"\u276F ":" ",`${y+1}.`.padEnd(V),S.head,S.note?_(I,{color:"gray",children:S.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),m+12<l.length?_(I,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),_(I,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ne?te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:`Preview article${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Fo.length===0?_(I,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>te(I,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d]},d)),_(I,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ie?te(ue,{flexDirection:"column",paddingX:1,children:[_(I,{color:Z,bold:!0,children:`Resume session${Ie.query?` \u2014 filter: ${Ie.query}`:" (type to filter)"}`}),Wo.length===0?_(I,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>te(I,{color:l===Ie.cursor?Z:void 0,children:[l===Ie.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),_(I,{color:l===Ie.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Oe-40))})]},d.uuid)),_(I,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):kc?te(ue,{flexDirection:"column",children:[Ut>0?_(I,{dimColor:!0,children:` \u22EF ${Ut} more above`}):null,Cs.map((d,l)=>{let a=Ut+l,m=d.name==="model"&&ws?`${d.desc} (currently ${ws})`:d.desc,T=Math.max(20,Oe-4),V=d.usage.length>T?`${d.usage.slice(0,T-1)}\u2026`:d.usage,f=T-Math.max(V.length,22)-1,w=f<=1?"":m.length>f?`${m.slice(0,f-1)}\u2026`:m;return te(I,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",V.padEnd(22)," ",_(I,{color:a===Uo?Z:"gray",children:w})]},d.name)}),Ut+Cs.length<Xe.length?_(I,{dimColor:!0,children:` \u22EF ${Xe.length-Ut-Cs.length} more below`}):null,_(I,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!$&&Fe.length>0?te(ue,{flexDirection:"column",paddingX:1,children:[dc?_(I,{color:Z,children:dc}):null,Fe.map((d,l)=>{let a=Vt(d),m=a.slice(0,Math.max(20,Oe-5)),T=Oe-m.length-7,V=T>=12?(Cp(d)??kl(a)).slice(0,T):"";return te(I,{children:[_(I,{color:Z,children:l+1})," ",m,V?_(I,{dimColor:!0,children:` \u2014 ${V}`}):null]},a)}),_(I,{dimColor:!0,children:`press 1-${Fe.length} to fill \xB7 esc cancel`})]}):_(ue,{paddingX:1,children:te(I,{color:"gray",children:[wc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ws??"model n/a"}${t.kind==="api"?fc>0?` \xB7 ${De(fc)}`:"":hc>0?` \xB7 ${bt(hc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Kb}from"react/jsx-runtime";async function th(e=process.cwd(),t="auto",n,o="0.0.0"){let r=zb(t);r.kind==="none"&&(console.error(""),console.error(D("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}=Yb(Kb(eh,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
443
|
+
`)});let B=U.filter(j=>j.state==="placeholder").length,N=U.filter(j=>j.state==="spec").length,F=U.filter(j=>j.state==="captured").length,L=U.filter(j=>j.state==="rejected").length;if(B>0){let j=S?`/screenshot author ${S}`:"/screenshot author --all";$e(`${B} of ${U.length} still need${B===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${j} authors them all in parallel.`,{kind:"cmd",cmd:j,reason:""})}else if(N>0){let j=S?`/screenshot capture ${S}`:"/screenshot capture";$e(`${N} spec${N===1?"":"s"} ready to capture \u2014 ${j} takes ${N===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:j,reason:""})}else F>0?$e(`${F} shot${F===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:""}):L>0&&$e(`${L} shot${L===1?"":"s"} failed verification \u2014 /screenshot capture --failed re-shoots ${L===1?"it":"them"} once the spec is fixed.`,{kind:"cmd",cmd:"/screenshot capture --failed",reason:""});return}if(f.mode==="single"){await vc(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,y=Cb(e,{scope:k}).map(x=>x.id);if(y.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await $c(y,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await T(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(qp(e))},u({kind:"note",tone:"warn",text:$a(e,f).join(`
|
|
444
|
+
`)}),Pe(vo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,dn,Ds,u,Le,ie,Ft,Ss,xc]),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=>Rp(m,l))),!l||(sc(!1),Rc(l))||Cc(l))return;fs.current.push(l);let a=Ep(l,ac.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Bn(a).finally(()=>J(!1));else if(Ib(a)){u({kind:"user",text:l});let m=Ob(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{Lb(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=Ku(e,a);ie(m??a,{display:l})}},[$,Rc,Cc,Bn,ie]),Sc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=Sp(d);if(Pp(l)){let a=Tp(++dh.current,l);ac.current.set(a,l),E(a)}else E(l);return}E(d)},[E]),un=Math.max(10,Oe-6),Pc=qa(()=>is(h.text,un),[h.text,un]),As=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Ap(is(l.text,un),l.pos,d)})),[un]),Hn=ee(d=>b(l=>({...l,pos:jp(is(l.text,un),l.pos,d)})),[un]),fh=["\x1B[H","\x1B[1~","\x1BOH"],mh=["\x1B[F","\x1B[4~","\x1BOF"],Tc=ee((d,l)=>l.leftArrow?(As(-1),!0):l.rightArrow?(As(1),!0):d&&fh.includes(d)?(Hn("start"),!0):d&&mh.includes(d)?(Hn("end"),!0):l.ctrl&&d==="a"?(Hn("start"),!0):l.ctrl&&d==="e"?(Hn("end"),!0):!1,[As,Hn]);return Kk((d,l)=>{if(l.ctrl&&d==="c"){We.current?.close(),r();return}if(!I){if(C){if(l.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(Do?.verb??"work").toLowerCase(),m=Do?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),Ce.current.abort()}return}In.current||(In.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),We.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),gs([...Lt.current]),v("");return}if(Tc(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&&Sc(d);return}if(Dt){if(l.upArrow){At(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){At(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){At(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[Dt.cursor];At(null);let{lines:m,changed:T,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});T&&(mc(f=>f+1),We.current?.setModel(V));return}if(d==="s"){let a=Je[Dt.cursor];At(null),We.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){At(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 T=!1;try{let V=Gt(a);T=!!V&&!(St(V)&&!V.refreshToken)}catch{T=!1}u({kind:"note",tone:"info",text:T?`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(Se){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)<=Se.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Se.rows[Se.cursor],{profile:m,projectId:T}=Se;nn(null),Ho(m,T,a);return}if(l.escape){nn(null);return}return}if(je){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)<=je.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=je.rows[je.cursor],{profile:m}=je;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Te){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,T)=>T===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Te.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?Ds(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"?vc(a.ids[0]):$c(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(Ne){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[Ne.cursor];if(a){Ot(null);try{u({kind:"preview",name:vo(a),text:Jp(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(Ie){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[Ie.cursor];if(a){_t(null),Le(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 T of m)u(T);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(!$&&Fe.length>0&&!Yt&&d&&/^[1-9]$/.test(d)){let a=Fe[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(T=>{u({kind:"note",tone:T?"ok":"warn",text:T?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."}),T&&a&&vs(null),T&&!a&&yc(!0)});return}if(!Tc(d,l)){if(kc){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($l(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&&Sc(d)}}}),Ue(()=>{if(C||I)return;let d=Lt.current.shift();d!==void 0&&(gs([...Lt.current]),Go(d))},[C,I,Go]),te(ue,{flexDirection:"column",width:Oe,children:[Rs!==null&&te(ue,{marginTop:1,flexDirection:"column",children:[Rs.truncated&&_(O,{dimColor:!0,children:"\u2026"}),_(O,{children:Rs.text})]}),C&&(Do?_(Vb,{p:Do}):_(Bb,{startTime:Tt.current,chars:lh})),!C&&pc?_(Hb,{text:pc}):null,_(ue,{borderStyle:"round",borderColor:wc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Pc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===as(Pc,h.pos),T=Math.min(h.pos,d.end)-d.start;return te(O,{children:[_(O,{color:Z,children:l===0?"> ":" "}),m?te(xo,{children:[a.slice(0,T),_(Dn,{ch:a[T]??" "}),a.slice(T+1)]}):a||" "]},`${l}-${d.start}`)}):te(O,{children:[_(O,{color:Z,children:"> "}),ys?_(Dn,{ch:" "}):re&&!C&&ae?te(xo,{children:[_(Dn,{ch:ae[0],dim:!0}),_(O,{color:"gray",children:ae.slice(1)})]}):re&&!C?te(xo,{children:[_(Dn,{ch:re[0],dim:!0}),_(O,{color:"gray",children:re.slice(1)}),_(O,{dimColor:!0,children:" (tab)"})]}):(xs.isSetup||!ah)&&!C?te(xo,{children:[_(Dn,{ch:xs.text[0],dim:!0}),_(O,{color:"gray",children:xs.text.slice(1)})]}):_(Dn,{ch:" "})]})}),uc.length>0&&_(ue,{flexDirection:"column",paddingX:1,children:uc.map((d,l)=>_(O,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?_(kp,{tab:No.tab,width:Oe,version:o,engineVersion:Zp}):Dt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Select model"}),_(O,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Je.map((d,l)=>te(O,{color:l===Dt.cursor?Z:void 0,children:[l===Dt.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===Dt.current?" \u2714":""}`.padEnd(16),_(O,{color:"gray",children:d.desc})]},d.label)),_(O,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Switch connection profile"}),tt.rows.map((d,l)=>te(O,{color:l===tt.cursor?Z:void 0,children:[l===tt.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===tt.current?" \u2714":""}`.padEnd(20),_(O,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?_(O,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),_(O,{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,{color:Z,bold:!0,children:"Pick your Document360 environment"}),nt.rows.map((d,l)=>te(O,{color:l===nt.cursor?Z:void 0,children:[l===nt.cursor?"\u276F ":" ",`${l+1}. ${d.name}`.padEnd(16),_(O,{color:"gray",children:d.apiUrl})]},d.name)),_(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Se?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Switch workspace"}),_(O,{dimColor:!0,children:`environment ${Se.environment} \xB7 project ${Se.projectName??`${Se.projectId.slice(0,8)}\u2026`}`}),Se.rows.map((d,l)=>te(O,{color:l===Se.cursor?Z:void 0,children:[l===Se.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Se.current?" \u2714":""}`.padEnd(30),_(O,{color:"gray",children:d.type??""})]},d.id)),_(O,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):je?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:"Choose project"}),_(O,{dimColor:!0,children:`environment ${je.environment}`}),je.rows.map((d,l)=>te(O,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===je.current?" \u2714":""}`.padEnd(30),_(O,{color:"gray",children:d.sub??""})]},d.id)),_(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Te?(()=>{let l=Math.min(Math.max(0,Te.cursor-Math.floor(7)),Math.max(0,Te.rows.length-14)),a=Te.rows.slice(l,l+14),m=Te.rows.filter(T=>T.checked).length;return te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Te.rows.length})`}),l>0?_(O,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((T,V)=>{let f=l+V;return te(O,{color:f===Te.cursor?Z:void 0,children:[f===Te.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,Oe-34)),_(O,{color:"gray",children:Ar(T)})]},T.path)}),l+14<Te.rows.length?_(O,{dimColor:!0,children:` \u2193 ${Te.rows.length-l-14} more`}):null,_(O,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{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(O,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Oe-24))),_(O,{color:"gray",children:` ${d.token}`})]},d.token)}),_(O,{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,{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?" ":" ",T=`${l+1}.`.padEnd(3);return te(O,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${T} ${d.label}`.padEnd(Math.min(56,Oe-24)),d.note?_(O,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),_(O,{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,{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)),T=l.slice(m,m+12),V=`${l.length}.`.length+1,f=pd(l,Math.max(20,Oe-4-V));return te(xo,{children:[m>0?_(O,{color:"gray",children:` \u2026 ${m} more above`}):null,T.map((w,k)=>{let y=m+k,x=y===a,S=f[y];return te(O,{color:x?Z:void 0,bold:(w.kind==="all"||w.kind==="category")&&!x,children:[x?"\u276F ":" ",`${y+1}.`.padEnd(V),S.head,S.note?_(O,{color:"gray",children:S.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),m+12<l.length?_(O,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),_(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ne?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Preview article${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Fo.length===0?_(O,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>te(O,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d]},d)),_(O,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ie?te(ue,{flexDirection:"column",paddingX:1,children:[_(O,{color:Z,bold:!0,children:`Resume session${Ie.query?` \u2014 filter: ${Ie.query}`:" (type to filter)"}`}),Wo.length===0?_(O,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>te(O,{color:l===Ie.cursor?Z:void 0,children:[l===Ie.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),_(O,{color:l===Ie.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Oe-40))})]},d.uuid)),_(O,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):kc?te(ue,{flexDirection:"column",children:[Ut>0?_(O,{dimColor:!0,children:` \u22EF ${Ut} more above`}):null,Cs.map((d,l)=>{let a=Ut+l,m=d.name==="model"&&ws?`${d.desc} (currently ${ws})`:d.desc,T=Math.max(20,Oe-4),V=d.usage.length>T?`${d.usage.slice(0,T-1)}\u2026`:d.usage,f=T-Math.max(V.length,22)-1,w=f<=1?"":m.length>f?`${m.slice(0,f-1)}\u2026`:m;return te(O,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",V.padEnd(22)," ",_(O,{color:a===Uo?Z:"gray",children:w})]},d.name)}),Ut+Cs.length<Xe.length?_(O,{dimColor:!0,children:` \u22EF ${Xe.length-Ut-Cs.length} more below`}):null,_(O,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!$&&Fe.length>0?te(ue,{flexDirection:"column",paddingX:1,children:[dc?_(O,{color:Z,children:dc}):null,Fe.map((d,l)=>{let a=Vt(d),m=a.slice(0,Math.max(20,Oe-5)),T=Oe-m.length-7,V=T>=12?(Cp(d)??kl(a)).slice(0,T):"";return te(O,{children:[_(O,{color:Z,children:l+1})," ",m,V?_(O,{dimColor:!0,children:` \u2014 ${V}`}):null]},a)}),_(O,{dimColor:!0,children:`press 1-${Fe.length} to fill \xB7 esc cancel`})]}):_(ue,{paddingX:1,children:te(O,{color:"gray",children:[wc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ws??"model n/a"}${t.kind==="api"?fc>0?` \xB7 ${De(fc)}`:"":hc>0?` \xB7 ${bt(hc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Kb}from"react/jsx-runtime";async function th(e=process.cwd(),t="auto",n,o="0.0.0"){let r=zb(t);r.kind==="none"&&(console.error(""),console.error(D("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}=Yb(Kb(eh,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
445
445
|
`),process.exit(0)}K();import{writeCrashLog as nh,isBenignTransportError as Xb}from"document360-engine";var oh=!1;function nc(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function rh(e){if(oh)return;oh=!0;let t=(n,o)=>{if(Xb(o)){nh({kind:n,level:"transport",message:nc(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=nh({kind:n,level:"fatal",message:nc(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
446
446
|
`+D(`\u2717 d360-writer crashed: ${nc(o)}`)+`
|
|
447
447
|
`),r&&process.stderr.write(g(` Crash details: ${r}`)+`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document360-writer",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.187",
|
|
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.
|
|
37
|
+
"document360-engine": "^0.2.177",
|
|
38
38
|
"ink": "^5.2.1",
|
|
39
39
|
"picocolors": "^1.1.1",
|
|
40
40
|
"react": "^18.3.1",
|