document360-writer 0.5.242 → 0.5.243
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 +62 -60
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -293,8 +293,8 @@ try {
|
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
295
|
`;Da="Re-run dev\u2194docs onboarding (protocol v"});var sp={};gd(sp,{initCommand:()=>La,scaffoldInit:()=>Ia});import{input as lr,confirm as Nw}from"@inquirer/prompts";import{basename as Xd,join as Ns}from"node:path";import{existsSync as po,readFileSync as jw,readdirSync as Iw,writeFileSync as Lw}from"node:fs";import{writeProjectConfig as Qd,readProjectConfig as Ow,projectConfigPath as Jd,writerDir as _w,DEFAULT_DOCS_DIR as Zd,DEFAULT_CAPTURE_DIR as ep,DEFAULT_OUTPUT_DIR as tp}from"document360-engine";function Ia(e,t="berlin"){let n=Jd(e);if(po(n))return{created:!1,path:n,profileName:""};let o={projectId:op(e)??Xd(e),docsDir:Zd,captureDir:ep,outputDir:tp,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:rp(e)};return Qd(o,e),np(e),{created:!0,path:n,profileName:t}}function np(e){let t=Ns(_w(e),".gitignore");po(t)||Lw(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
296
|
-
`),"utf8")}async function La(){let e=process.cwd(),t=Jd(e);if(po(t)&&!await Nw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=op(e)??Xd(e),o=await lr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await lr({message:"Capture directory (where document360-capture .spec.ts files live):",default:ep}),s=await lr({message:"Screenshot output directory:",default:tp}),i=await lr({message:"Default connection profile name:",default:"berlin"}),a=await lr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Zd,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:rp(e)},p=Ow(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),Qd(l,e),np(e);let g=co(e);console.log(""),console.log(G(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${K(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of uo(g))console.log(k);return console.log(""),console.log(`${y("Then ask:")} ${K('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function op(e){let t=Ns(e,"package.json");if(!po(t))return null;try{return JSON.parse(jw(t,"utf8")).name??null}catch{return null}}function rp(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])po(Ns(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ns(e,n);po(o)&&!Mw(o)&&t.push(n)}return t}function Mw(e){try{return Iw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var js=or(()=>{"use strict";ee();nn()});import{createRequire as ak}from"node:module";import{existsSync as lk,readFileSync as ck}from"node:fs";import{dirname as Dp,join as Np}from"node:path";function Mt(){let e;try{e=uk.resolve("document360-capture/helpers")}catch{return null}let t=Dp(e);for(let n=0;n<5&&!lk(Np(t,"package.json"));n++)t=Dp(t);try{let n=JSON.parse(ck(Np(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var uk,pr=or(()=>{"use strict";uk=ak(import.meta.url)});var bf={};gd(bf,{doctorCommand:()=>Tr,renderDoctorChecks:()=>kf,runDoctorChecks:()=>wf});import{existsSync as K$}from"node:fs";import{d360GetAll as z$,getAccessToken as X$,isExpired as fc,loadProfileMap as Q$,loadTokens as J$,packageSkillsDir as gf,ENGINE_VERSION as Z$,projectConfigPath as ev,readProjectConfig as tv,DEFAULT_DOCS_DIR as nv,fetchManifestSummary as ov,resolveActiveProfile as rv,classifyClaudeAuth as sv,CLAUDE_CODE_SETUP_HINT as yf,resolveModelSetting as iv,probeModel as av,detectAppType as lv,playbookSkillName as cv,D360AuthError as uv,applyStructureOrder as dv}from"document360-engine";async function wf(e,t){let n=[],o=Mt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Z$}${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=sv();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. ${yf}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:yf});let i=iv(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 av(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 a=tv(e);if(!a)return n.push({level:"fail",label:`No ${ev(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??nv).replace(/\/+$/,"");n.push(a.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 ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=a.authoritativeSourceFiles??[];n.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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 g=a.appType??lv(e);if(g){let C=a.appType?"from config":"auto-detected",T=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${C})${T?` \u2192 ${cv(g)} 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 k;try{k=rv(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.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=J$(k.name);v?fc(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):fc(v)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the 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 ${k.name})`}),n.push(k.project.workspaceId?{level:"ok",label:`Workspace: ${k.project.workspaceName??k.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let P=Q$(e,k.name);P?P.projectId&&k.project.projectId&&P.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${P.projectId}) \u2260 profile projectId (${k.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(P.articles).length} articles, ${Object.keys(P.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /push)`}),n.push(K$(gf())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${gf()}`,fix:"Reinstall document360-writer (broken install)"});let S=mt(e);if(S.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Re})`}):S.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${S.completedVersion}, current is v${Re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!fc(v)||v.refreshToken)){let C={profile:k.name,connection:k.connection};try{await X$(C);let D=await z$(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=P?.projectId??k.project.projectId;if(T&&k.project.workspaceId){try{let D=await ov(C,T,k.project.workspaceId);if(D){let I=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${k.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${k.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(D){D instanceof uv||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}try{let D=await dv({cwd:e,profileName:k.name,dryRun:!0}),I=D.categoriesReordered+D.articlesReordered;if(D.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(D.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${D.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(D.unverified)n.push({level:"warn",label:`Reading order: ${D.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(I>0){let O=[D.categoriesReordered>0?`${D.categoriesReordered} categor${D.categoriesReordered===1?"y":"ies"}`:"",D.articlesReordered>0?`${D.articlesReordered} article${D.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${O.join(" + ")} out of order on Document360`,fix:"Run /push \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(D){n.push({level:"warn",label:`Reading order: check failed (${D.message.slice(0,80)})`})}}}return n}function kf(e){let t=[""];for(let r of e){let s=r.level==="ok"?G("\u2713"):r.level==="warn"?H("\u26A0"):N("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${K(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?G(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):N(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Tr(e,t){console.log(y("Running checks\u2026"));for(let n of kf(await wf(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var mi=or(()=>{"use strict";nn();ee();pr()});import{Command as eP}from"commander";import{createRequire as tP}from"node:module";import{AUTH_MODES as nP}from"document360-engine";import{input as Xy}from"@inquirer/prompts";import{loginPkce as Qy,refreshTokens as Jy,toStoredTokens as Cd,clearTokens as Zy,decodeJwtClaims as xd,isExpired as ew,loadTokens as tw,saveTokens as Rd,resolveActiveProfile as ks,setProfileProject as nw,readProjectConfig as ow}from"document360-engine";ee();import{select as Iy}from"@inquirer/prompts";import{resolveActiveProfile as Ly,setProfileProject as Oy,resolveProjectId as _y,listWorkspaces as My}from"document360-engine";async function sr(e,t){let n=Ly(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??_y(o);return{workspaces:await My(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wd=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xa(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 gs(e,t,n,o,r){Oy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function kd(e,t,n){let o;try{o=await sr(e,n)}catch(s){return console.log(N(`Could not list workspaces: ${s.message}`)),1}let r=xa(o.workspaces,t);return r?(gs(e,o.profile,o.projectId,r.id,r.name),console.log(G(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(N(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function io(e,t){let n;try{n=await sr(e,t)}catch(p){console.log(N(`Could not list workspaces: ${p.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===i?K("\u25CF"):" "} ${wd(p)} ${y(p.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let a=await Iy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${wd(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);gs(e,s,r,a,l?.name),console.log(G(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}ee();import{select as Fy}from"@inquirer/prompts";import{resolveActiveProfile as Wy,setProfileProject as Uy,listProjects as By}from"document360-engine";async function Jt(e,t){let n=Wy(e,t),o={profile:n.name,connection:n.connection};return{projects:await By(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var bd=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ca(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 ys(e,t,n,o){Uy(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $d(e,t,n){let o;try{o=await Jt(e,n)}catch(s){return console.log(N(`Could not list projects: ${s.message}`)),1}let r=Ca(o.projects,t);return r?(ys(e,o.profile,r.id,r.name),console.log(G(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(N(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ws(e,t){let n;try{n=await Jt(e,t)}catch(l){console.log(N(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?K("\u25CF"):" "} ${bd(l)} ${y(l.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Fy({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${bd(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);ys(e,r,i,a?.name),console.log(G(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ee();import Hy from"picocolors";function qy(e=process.env){return e.FORCE_HYPERLINK==="0"||!Hy.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 Gy(e,t=e,n){return qy(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Vy=/https?:\/\/[^\s\x1b]+/g;function ir(e,t){return e.replace(Vy,n=>Gy(n,n,t))}import{readProjectConfig as vd,sunsetEnvironment as Yy,resolveActiveProfile as Ky}from"document360-engine";function zy(e,t){let n=vd(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Zt(e,t){try{if(!vd(e))return null;let n=Ky(e,t),o=Yy(n.connection.name);if(!o)return null;let r=zy(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function Sd(e){return{...xd(e.idToken)??{},...xd(e.accessToken)??{}}}function bs(e){let t=Sd(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 $s(e){let t=ks(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Zt(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Qy(n,{manual:e.manual,promptForRedirect:i=>Xy({message:i})},i=>console.log(ir(i))),s=Cd(t.name,r);if(Rd(s),await Ra(s,t.name,i=>console.log(y(i))),console.log(""),console.log(G(`\u2713 Logged in to "${t.name}" as ${bs(s)}`)),console.log(y(` access token expires: ${s.expiresAt}`)),console.log(y(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ow(process.cwd())?.profiles?.[t.name]&&(console.log(""),await io(process.cwd(),t.name))}catch{}}async function Ra(e,t,n){let r=Sd(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ks(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Jt(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}nw(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Pd(e){let t=ks(process.cwd(),e.profile),n=t.connection,o=tw(t.name);if(!o){console.log(N(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${K(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bs(o)}`),ew(o))if(o.refreshToken)try{let r=Cd(t.name,await Jy(n,o.refreshToken));Rd(r),console.log(G(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Td(e){let t=ks(process.cwd(),e.profile);Zy(t.name)?console.log(G(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}ee();import{readProjectConfig as Ed,writeProjectConfig as rw,resolveActiveProfile as sw,loadTokens as iw,isExpired as aw}from"document360-engine";function vs(e){let t=Ed(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(N("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?K("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=iw(n),l=a?aw(a)&&!a.refreshToken?H("expired"):y("logged in"):y("not logged in");console.log(`${r}${K(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function xs(e,t){let n=Ed(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(N(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,rw(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(G(`\u2713 Default profile is now "${t}"${o}`))}function Cs(e,t){try{let n=sw(e,t);console.log(""),console.log(`Profile ${K(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(N(n.message)),process.exitCode=1}}ee();import{existsSync as lw,readdirSync as cw,statSync as Ad}from"node:fs";import{join as Dd}from"node:path";import{apiLogDir as uw}from"document360-engine";function Nd(){let e=uw();if(console.log(""),console.log(`Document360 API logs: ${K(e)}`),!lw(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=cw(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ad(Dd(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ad(Dd(e,r)).size/1024).toFixed(1);console.log(` ${N(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}ee();import{createSession as dw,resolveAuth as pw,findByName as hw,slugify as fw,touchSession as mw,upsertSession as gw,resolveActiveProfile as yw}from"document360-engine";async function jd(e,t,n,o,r,s){let i=pw(n);i.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let a=null;try{a=yw(e,r)}catch(v){console.error(N(`Document360 profile error: ${v.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(N("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let l;if(o){let v=hw(e,o);v||(console.error(N(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),l=v.uuid,console.error(y(`Resuming "${v.name}"`))}let p=dw({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,k=1;for await(let v of p.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let P=new Date().toISOString();gw({uuid:g,name:fw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error($e(` \u2699 ${v.name}`));break;case"result":k=v.ok?0:1,console.error(y(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(N("agent finished with an error result"));break;case"error":console.error(""),console.error(N(`agent error: ${v.message}`)),process.exit(1)}g&&mw(g),process.stdout.write(`
|
|
297
|
-
`),process.exit(k)}import{createInterface as
|
|
296
|
+
`),"utf8")}async function La(){let e=process.cwd(),t=Jd(e);if(po(t)&&!await Nw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=op(e)??Xd(e),o=await lr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await lr({message:"Capture directory (where document360-capture .spec.ts files live):",default:ep}),s=await lr({message:"Screenshot output directory:",default:tp}),i=await lr({message:"Default connection profile name:",default:"berlin"}),a=await lr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Zd,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:rp(e)},p=Ow(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),Qd(l,e),np(e);let g=co(e);console.log(""),console.log(G(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${K(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of uo(g))console.log(k);return console.log(""),console.log(`${y("Then ask:")} ${K('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function op(e){let t=Ns(e,"package.json");if(!po(t))return null;try{return JSON.parse(jw(t,"utf8")).name??null}catch{return null}}function rp(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])po(Ns(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ns(e,n);po(o)&&!Mw(o)&&t.push(n)}return t}function Mw(e){try{return Iw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var js=or(()=>{"use strict";ee();nn()});import{createRequire as ak}from"node:module";import{existsSync as lk,readFileSync as ck}from"node:fs";import{dirname as Dp,join as Np}from"node:path";function Mt(){let e;try{e=uk.resolve("document360-capture/helpers")}catch{return null}let t=Dp(e);for(let n=0;n<5&&!lk(Np(t,"package.json"));n++)t=Dp(t);try{let n=JSON.parse(ck(Np(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var uk,pr=or(()=>{"use strict";uk=ak(import.meta.url)});var bf={};gd(bf,{doctorCommand:()=>Tr,renderDoctorChecks:()=>kf,runDoctorChecks:()=>wf});import{existsSync as K$}from"node:fs";import{d360GetAll as z$,getAccessToken as X$,isExpired as fc,loadProfileMap as Q$,loadTokens as J$,packageSkillsDir as gf,ENGINE_VERSION as Z$,projectConfigPath as ev,readProjectConfig as tv,DEFAULT_DOCS_DIR as nv,fetchManifestSummary as ov,resolveActiveProfile as rv,classifyClaudeAuth as sv,CLAUDE_CODE_SETUP_HINT as yf,resolveModelSetting as iv,probeModel as av,detectAppType as lv,playbookSkillName as cv,D360AuthError as uv,applyStructureOrder as dv}from"document360-engine";async function wf(e,t){let n=[],o=Mt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Z$}${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=sv();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. ${yf}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:yf});let i=iv(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 av(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 a=tv(e);if(!a)return n.push({level:"fail",label:`No ${ev(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??nv).replace(/\/+$/,"");n.push(a.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 ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=a.authoritativeSourceFiles??[];n.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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 g=a.appType??lv(e);if(g){let C=a.appType?"from config":"auto-detected",T=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${C})${T?` \u2192 ${cv(g)} 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 k;try{k=rv(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.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=J$(k.name);v?fc(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):fc(v)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the 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 ${k.name})`}),n.push(k.project.workspaceId?{level:"ok",label:`Workspace: ${k.project.workspaceName??k.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let P=Q$(e,k.name);P?P.projectId&&k.project.projectId&&P.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${P.projectId}) \u2260 profile projectId (${k.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(P.articles).length} articles, ${Object.keys(P.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /push)`}),n.push(K$(gf())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${gf()}`,fix:"Reinstall document360-writer (broken install)"});let S=mt(e);if(S.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Re})`}):S.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${S.completedVersion}, current is v${Re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!fc(v)||v.refreshToken)){let C={profile:k.name,connection:k.connection};try{await X$(C);let D=await z$(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=P?.projectId??k.project.projectId;if(T&&k.project.workspaceId){try{let D=await ov(C,T,k.project.workspaceId);if(D){let I=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${k.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${k.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(D){D instanceof uv||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${D.message.slice(0,80)})`})}try{let D=await dv({cwd:e,profileName:k.name,dryRun:!0}),I=D.categoriesReordered+D.articlesReordered;if(D.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(D.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${D.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(D.unverified)n.push({level:"warn",label:`Reading order: ${D.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(I>0){let O=[D.categoriesReordered>0?`${D.categoriesReordered} categor${D.categoriesReordered===1?"y":"ies"}`:"",D.articlesReordered>0?`${D.articlesReordered} article${D.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${O.join(" + ")} out of order on Document360`,fix:"Run /push \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(D){n.push({level:"warn",label:`Reading order: check failed (${D.message.slice(0,80)})`})}}}return n}function kf(e){let t=[""];for(let r of e){let s=r.level==="ok"?G("\u2713"):r.level==="warn"?H("\u26A0"):N("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${K(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?G(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):N(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Tr(e,t){console.log(y("Running checks\u2026"));for(let n of kf(await wf(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var mi=or(()=>{"use strict";nn();ee();pr()});import{Command as tP}from"commander";import{createRequire as nP}from"node:module";import{AUTH_MODES as oP}from"document360-engine";import{input as Xy}from"@inquirer/prompts";import{loginPkce as Qy,refreshTokens as Jy,toStoredTokens as Cd,clearTokens as Zy,decodeJwtClaims as xd,isExpired as ew,loadTokens as tw,saveTokens as Rd,resolveActiveProfile as ks,setProfileProject as nw,readProjectConfig as ow}from"document360-engine";ee();import{select as Iy}from"@inquirer/prompts";import{resolveActiveProfile as Ly,setProfileProject as Oy,resolveProjectId as _y,listWorkspaces as My}from"document360-engine";async function sr(e,t){let n=Ly(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??_y(o);return{workspaces:await My(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wd=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xa(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 gs(e,t,n,o,r){Oy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function kd(e,t,n){let o;try{o=await sr(e,n)}catch(s){return console.log(N(`Could not list workspaces: ${s.message}`)),1}let r=xa(o.workspaces,t);return r?(gs(e,o.profile,o.projectId,r.id,r.name),console.log(G(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(N(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function io(e,t){let n;try{n=await sr(e,t)}catch(p){console.log(N(`Could not list workspaces: ${p.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===i?K("\u25CF"):" "} ${wd(p)} ${y(p.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let a=await Iy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${wd(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);gs(e,s,r,a,l?.name),console.log(G(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}ee();import{select as Fy}from"@inquirer/prompts";import{resolveActiveProfile as Wy,setProfileProject as Uy,listProjects as By}from"document360-engine";async function Jt(e,t){let n=Wy(e,t),o={profile:n.name,connection:n.connection};return{projects:await By(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var bd=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ca(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 ys(e,t,n,o){Uy(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $d(e,t,n){let o;try{o=await Jt(e,n)}catch(s){return console.log(N(`Could not list projects: ${s.message}`)),1}let r=Ca(o.projects,t);return r?(ys(e,o.profile,r.id,r.name),console.log(G(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(N(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ws(e,t){let n;try{n=await Jt(e,t)}catch(l){console.log(N(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?K("\u25CF"):" "} ${bd(l)} ${y(l.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Fy({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${bd(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);ys(e,r,i,a?.name),console.log(G(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ee();import Hy from"picocolors";function qy(e=process.env){return e.FORCE_HYPERLINK==="0"||!Hy.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 Gy(e,t=e,n){return qy(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Vy=/https?:\/\/[^\s\x1b]+/g;function ir(e,t){return e.replace(Vy,n=>Gy(n,n,t))}import{readProjectConfig as vd,sunsetEnvironment as Yy,resolveActiveProfile as Ky}from"document360-engine";function zy(e,t){let n=vd(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Zt(e,t){try{if(!vd(e))return null;let n=Ky(e,t),o=Yy(n.connection.name);if(!o)return null;let r=zy(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function Sd(e){return{...xd(e.idToken)??{},...xd(e.accessToken)??{}}}function bs(e){let t=Sd(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 $s(e){let t=ks(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Zt(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Qy(n,{manual:e.manual,promptForRedirect:i=>Xy({message:i})},i=>console.log(ir(i))),s=Cd(t.name,r);if(Rd(s),await Ra(s,t.name,i=>console.log(y(i))),console.log(""),console.log(G(`\u2713 Logged in to "${t.name}" as ${bs(s)}`)),console.log(y(` access token expires: ${s.expiresAt}`)),console.log(y(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ow(process.cwd())?.profiles?.[t.name]&&(console.log(""),await io(process.cwd(),t.name))}catch{}}async function Ra(e,t,n){let r=Sd(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ks(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Jt(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}nw(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Pd(e){let t=ks(process.cwd(),e.profile),n=t.connection,o=tw(t.name);if(!o){console.log(N(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${K(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bs(o)}`),ew(o))if(o.refreshToken)try{let r=Cd(t.name,await Jy(n,o.refreshToken));Rd(r),console.log(G(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Td(e){let t=ks(process.cwd(),e.profile);Zy(t.name)?console.log(G(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}ee();import{readProjectConfig as Ed,writeProjectConfig as rw,resolveActiveProfile as sw,loadTokens as iw,isExpired as aw}from"document360-engine";function vs(e){let t=Ed(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(N("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?K("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=iw(n),l=a?aw(a)&&!a.refreshToken?H("expired"):y("logged in"):y("not logged in");console.log(`${r}${K(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function xs(e,t){let n=Ed(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(N(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,rw(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(G(`\u2713 Default profile is now "${t}"${o}`))}function Cs(e,t){try{let n=sw(e,t);console.log(""),console.log(`Profile ${K(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(N(n.message)),process.exitCode=1}}ee();import{existsSync as lw,readdirSync as cw,statSync as Ad}from"node:fs";import{join as Dd}from"node:path";import{apiLogDir as uw}from"document360-engine";function Nd(){let e=uw();if(console.log(""),console.log(`Document360 API logs: ${K(e)}`),!lw(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=cw(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Ad(Dd(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Ad(Dd(e,r)).size/1024).toFixed(1);console.log(` ${N(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}ee();import{createSession as dw,resolveAuth as pw,findByName as hw,slugify as fw,touchSession as mw,upsertSession as gw,resolveActiveProfile as yw}from"document360-engine";async function jd(e,t,n,o,r,s){let i=pw(n);i.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let a=null;try{a=yw(e,r)}catch(v){console.error(N(`Document360 profile error: ${v.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(N("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let l;if(o){let v=hw(e,o);v||(console.error(N(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),l=v.uuid,console.error(y(`Resuming "${v.name}"`))}let p=dw({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,k=1;for await(let v of p.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let P=new Date().toISOString();gw({uuid:g,name:fw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error($e(` \u2699 ${v.name}`));break;case"result":k=v.ok?0:1,console.error(y(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(N("agent finished with an error result"));break;case"error":console.error(""),console.error(N(`agent error: ${v.message}`)),process.exit(1)}g&&mw(g),process.stdout.write(`
|
|
297
|
+
`),process.exit(k)}import{createInterface as BC}from"node:readline/promises";import{createSession as uu,resolveAuth as HC,getSession as qC,setTitle as GC,slugify as VC,touchSession as Zm,upsertSession as YC,generateTitle as KC,resolveActiveProfile as eg,resolveModelSetting as zC,readProjectConfig as XC,readUserConfig as QC,resolveAndPersistAppType as JC,decodeJwtClaims as Qm,isExpired as ZC,loadTokens as eR,isDirectiveMention as tR,stripDirectiveMention as nR,appendDirective as oR,reconcileUpgradeActions as rR,stampArticles as sR,snapshotArticles as iR,listArticleFiles as aR,applyStructureOrder as lR,orderSyncLine as cR,computeSyncStatus as uR}from"document360-engine";import{ENGINE_VERSION as bw}from"document360-engine";function en(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 Rs(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 a of en(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of en(s.why,73))o.push(n(` ${a}`));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}function Ss(e){return[`\u26A0 ${e} screenshot${e===1?"":"s"} that hide${e===1?"s":""} sensitive areas ${e===1?"is":"are"} back to needing a check.`," A blacked-out area only covered the first matching spot on the screen \u2014 so on a list or a table, the",` rows below it were still readable. Blackouts now cover every match, and ${e===1?"that picture needs":"those pictures need"} a fresh look.`].join(`
|
|
298
298
|
`)}var Je=[{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"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{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",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{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:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{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:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."}]},{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 /push --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360. Put a category in front (/push 04-publishing --screenshots) to re-save only that one."},{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 (--push then saves them to Document360)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/push",s:"Save to Document360 as drafts (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers (--all or a path). Lists them and asks first."},{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 \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 a table by article; pick one to read it, then answer (--resolve also closes the threads)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to \u2014 the Microsoft or Google style guide, or just the house rules. Adopting one records what your articles already contain, so nothing you have written suddenly breaks. `pull` brings your Document360 project's own style guide down so the writer works to it; `compile` turns its mechanical statements into checks and tells you which parts only an editor can judge."},{t:"cmd",name:"/lint",s:"The machine pass: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape. Deterministic, costs nothing to run; --fix has the agent correct what it found."},{t:"cmd",name:"/review",s:"The editor pass: a senior editor reads the articles against the house style guide and judges what no rule can. --fix applies the corrections, --blocked narrows to the articles publishing is blocked on. Required before anything goes live."},{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:"/verbose",s:"Raw transcript: every tool call, path and full result (bare: toggle)."},{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."}]}],Id=24;function Sa(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Id:Math.min(Id,Math.max(...t))}function Ps(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=en(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 ww(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=Ps(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(`
|
|
299
299
|
`)}case"gap":return""}}function Ld(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 Je){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Sa(o.rows);for(let s of o.rows)n.push(ww(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Pa(e,t){return en(e,Math.max(10,Math.max(20,t)-2))}function kw(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Pa(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Ps(e.name,e.s,t,o);return s.nameOwnLine?1+s.descLines.length:1+Math.max(0,s.descLines.length-1)}case"step":return r(`${e.n}. ${e.s}`);default:return r(e.s)}}function Od(e,t){let n=Math.min(Math.max(0,t.scroll),Math.max(0,e.length-1)),o=[],r=0;for(let s=n;s<e.length;s++){let i=kw(e[s],t.nameW,t.width);if(r+i>t.budget&&o.length>0)break;o.push(e[s]),r+=i}return{visible:o,above:n,below:e.length-n-o.length,start:n}}function _d(e){let n=r=>Math.max(1,Math.ceil(r/Math.max(10,e.inner))),o=n(e.barWidth)+n(e.barWidth)+1+1+n(e.footerWidth)+7;return Math.max(3,Math.min(22,(e.rows||24)-o))}async function Ta(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:bw}:void 0;for(let o of Ld(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"}}ee();import{getSession as $w}from"document360-engine";async function Md(e,t){let n=t.currentUuid(),o=n?$w(n):void 0;return console.log(o?y(`
|
|
300
300
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
@@ -352,21 +352,21 @@ ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await ca
|
|
|
352
352
|
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,rl,sl].join(`
|
|
353
353
|
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}function Ne(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function vt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}var yr=3;function hl(e){return[`Run the push-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown, using the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself; do not edit the articles map by hand).","4. Report what changed. The article is saved on Document360 as a DRAFT \u2014 do not take it live; /publish does that once it has been signed off."].join(`
|
|
354
354
|
`)}var ch={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function fl(e){return e.filter(t=>t.path!==null&&t.status in ch&&!t.link).map(t=>({path:t.path,label:ch[t.status]}))}function An(e){let t=fl(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function En(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT pushed (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function yo(e,t){let n=sb(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. Run /publish to take ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function ei(e){return e.filter(t=>t.link).length}function ml(e,t){try{let n=uh(e,pl(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=pb(Jk(Zk(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function yh(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${ho(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function wr(e){return[`Run the push-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool, and NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures). Everything you write is a DRAFT \u2014 never take an article live."].join(`
|
|
355
|
-
`)}async function wo(e,t){try{let n=pl(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await ub({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${db}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var it="--skip-review";function kr(e,t){return ib(e,t)}function ti(e,t){try{return kr(e,ph(e,t)).length}catch{return 0}}function Ct(e,t,n="",o){let r=ti(e,o),s=gl(e,o);if(r===0&&s===0)return t;let i=o?` ${o}`:"",a=o?"/push":"/push --all",l=o&&!o.endsWith(".md")?` in ${o}`:"";if(r>0){let g=r===1?"":"s",k=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",v=`/review${i} --blocked --fix`;return{text:`${n}${r} article${g}${l} ${r===1?"carries":"carry"} text no editor has read, so pushing ${r===1?"it is":"them is"} blocked. ${v} reads ${r===1?"it":"just those"} and applies its fixes.${k} Then ${a}.`,cmd:v}}return{text:`${n}${s} article${s===1?"":"s"}${l} break${s===1?"s":""} house style rules that block publishing. /lint${i} --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${a}.`,cmd:`/lint${i} --fix`}}function gl(e,t){try{return dh(e,ph(e,t)).length}catch{return 0}}function wh(e,t){return dh(e,t)}function yl(e,t,n){try{let o=uh(e,pl(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function wl(e,t,n,o=0,r,s){let i=`/push${s?` ${s}`:" --all"}`,a=I=>t[I.index]?.paths.length??0,l=e.filter(I=>I.ok),p=e.filter(I=>!I.ok),g=e.reduce((I,O)=>I+a(O),0),k=l.reduce((I,O)=>I+a(O),0),v=n==="api"?`${Ze(e.reduce((I,O)=>I+O.costUsd,0))} total`:rn(e.reduce((I,O)=>I+O.outputTokens,0)),P=`${l.length}/${e.length} partition${e.length===1?"":"s"}`,S=I=>`${I} article${I===1?"":"s"}`,C=[],T=r?$t({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The push"):null;if(T)return C.push(...T),C.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&C.push(En(o)),C;if(r&&g>0&&r.recorded===0){C.push(`\u2717 Nothing was pushed \u2014 the ${S(g)} in this run are not recorded in the category map, so none of them reached Document360.`),C.push(`Run /doctor (this is usually the agent runtime not running), then re-run ${i}.`);for(let I of p)I.error&&C.push(` \u2717 ${I.label} \u2014 ${I.error}`);return o>0&&C.push(En(o)),C}if(p.length===0&&(!r||r.recorded>=g))C.push(`Pushed ${S(g)} (${P}) successfully \xB7 ${v}.`),C.push(`Saved on Document360 as draft${g===1?"":"s"} \u2014 readers don't see ${g===1?"it":"them"} until /publish takes ${g===1?"it":"them"} live.`);else if(p.length===0&&r)C.push(`Pushed ${r.recorded}/${S(g)} (${P}) \xB7 ${v}.`),C.push(`${g-r.recorded} article${g-r.recorded===1?"":"s"} reported no error but ${g-r.recorded===1?"is":"are"} not recorded on Document360 \u2014 re-run ${i} to retry just those.`);else{C.push(`Pushed ${r?r.recorded:k}/${S(g)} (${P}) \xB7 ${v}.`),C.push(`${p.length} partition${p.length===1?"":"s"} failed \u2014 re-run ${i} to retry just the rest (articles already on Document360 are skipped):`);for(let I of p)C.push(` \u2717 ${I.label}${I.error?` \u2014 ${I.error}`:""}`)}let D=r?_s(r):null;return D&&C.push(D),o>0&&C.push(En(o)),C}async function xt(e,t,n=0,o){let r=ab(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of lb(r,t.length))console.log(H(a));return{kind:"continue"}}let{model:s}=ob(e.cwd,"standard"),i=async(a,l)=>{let p=tb(a);console.log(y(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${a.length} article${a.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${yr} agents at once) on ${s}\u2026`)),l||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let g=!1;for await(let k of rb({cwd:e.cwd,partitions:p,promptFor:v=>wr(v.paths),concurrency:yr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(k.type==="partition_status")k.status==="running"?console.log(y(` \u25B8 ${k.label} \u2014 pushing\u2026`)):k.status==="done"?console.log(G(` \u2713 ${k.label}`)):console.log(N(` \u2717 ${k.label}`));else if(k.type==="run_done"){g=k.aborted,console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription",P=yl(e.cwd,a,e.profileName),S=!k.aborted&&(!!k.blocked||!!k.allEmpty||a.length>0&&P===0);for(let I of wl(k.results,p,v,l?0:n,{recorded:P,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(k.ok&&!S?G(I):H(I));if(S)continue;let C=ml(e.cwd,e.profileName);C&&console.log(y(C));let T=yo(e.cwd,e.profileName);T&&console.log(y(T));try{let I=fh(await hh({cwd:e.cwd,profileName:e.profileName,onRateLimit:O=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?H(I):y(I))}catch{}try{let I=gh(await mh({cwd:e.cwd,profileName:e.profileName}));I&&console.log(y(I))}catch{}let D=await wo(e.cwd,e.profileName);D&&console.log(y(D))}return g};try{if(!await i(t,!1)){let l=await kl(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(N(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function ni(e,t,n){let o=nb(e,n);if(o.length===0)return[];let r=new Set(fl((await Zs({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function kl(e,t,n){try{let o=new Set(n),r=await Zs({cwd:e,profileName:t});return fl(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function oi(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.includes(it),r=e.includes(cb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(v=>!v.startsWith("--")),l=Ie(i),p=Ks(l,a);if(p.length===0)return console.log(y(a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let g=zs(l);g&&console.log(g);let k=Ne("","--screenshots",a).trim();return t?await xt(t,p,0,{skipReview:o,skipStyle:r,scope:k}):{kind:"forward-to-agent",prompt:wr(p),display:`/push ${k}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ni(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(G("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await xt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(y("Checking what needs pushing\u2026"));try{let i=await Zs({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=An(i.entries),p=ei(i.entries),g=e.includes("--force")&&l.length>0;p>0&&console.log(H(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!g&&console.log(H(En(l.length)));let k=g?[...a,...l]:a;if(k.length===0){if(l.length>0){let P=yo(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(y(P)),console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(G(p>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let v=yo(t?.cwd??process.cwd(),t?.profileName);if(v&&console.log(y(v)),t)try{let P=fh(await hh({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?H(P):y(P));let S=gh(await mh({cwd:t.cwd,profileName:t.profileName}));S&&console.log(y(S))}catch{}return{kind:"continue"}}return t?await xt(t,k.map(v=>v.path),g?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:wr(k.map(v=>v.path)),display:"/push --all"}}catch(i){return console.log(N(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(y("Checking what needs pushing\u2026"));let i,a=0;try{let l=await Zs({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:g}=An(l.entries);i=p,a=g.length;let k=ei(l.entries);if(k>0&&console.log(H(`\u26A0 ${k} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(H(En(g.length))),i.length===0&&g.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(N(`Could not compute sync status: ${l.message}`)),console.log(y("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(G("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(y(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of i)console.log(` ${l.path} ${y(`(${l.label})`)}`);return console.log(y("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>eb({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}if(s==="--all")return await xt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:hl(s),display:`/push ${s}`}}ee();import{select as fb}from"@inquirer/prompts";import{computeSyncStatus as mb,localAheadPaths as gb,pendingDrafts as yb,publishArticleLive as wb,publishGateVerdict as kb,publishGateLines as bb,resolveActiveProfile as yE,SKIP_STYLE_FLAG as $b}from"document360-engine";var hb={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},kh=new Set;function Ft(e){let t=hb[e.replace(/^\//,"")];return!t||kh.has(e)?null:(kh.add(e),t)}var vb=150,xb=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),$l=e=>e===1?"":"s",bl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function vl(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function xl(e,t,n){await mb({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return yb(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:r.path}))}function Cb(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function Cl(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=gb(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${$l(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function Rl(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0;for(let i of n){o.onProgress?.(s,n.length,i.label);let a=await wb({articleId:i.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0});a.ok?r.published.push({path:i.path,...a.url?{url:a.url}:{}}):a.blocked?r.blocked.push({path:i.path,message:a.message}):r.failed.push({path:i.path,message:a.error.message}),s+=1,s<n.length&&await xb(vb)}return r}function Sl(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${$l(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);for(let s of t.slice(0,3))s.url&&r.push(` \u2B95 ${s.url}`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 /review --blocked --fix clears ${n.length===1?"it":"them"}:`);for(let s of n.slice(0,3))r.push(` \xB7 ${bl(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${bl(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function bh(e,t){let n=t?.cwd??process.cwd(),o=Ft("publish");if(vl(e))return o&&console.log(y(`\u2192 ${o}`)),console.log(y("Running /push\u2026")),oi(e,t);let r=Ue(n,t?.profileName);if(!r.ok)return console.log(N(r.reason)),{kind:"continue"};o&&console.log(y(`\u2192 ${o}`));let s=e.includes(it),i=e.includes($b),a=e.includes("--all"),l=e.find(P=>!P.startsWith("--"));console.log(y("Checking what is waiting to go live\u2026"));let p;try{p=await xl(n,t?.profileName,l)}catch(P){return console.log(N(`Could not check Document360: ${P.message}`)),{kind:"continue"}}if(p.length===0){for(let P of Cl(n,t?.profileName,l).lines)console.log(P.startsWith("\u2713")?G(P):y(P));return{kind:"continue"}}let g=kb(n,p.map(P=>P.path),{allowUnreviewed:s,allowStyleErrors:i});if(!g.clear){for(let P of bb(g,p.length,l))console.log(H(P));return{kind:"continue"}}console.log(""),console.log(`${p.length} draft${$l(p.length)} ${p.length===1?"is":"are"} ahead of what readers see:`);for(let P of Cb(p.slice(0,12)))console.log(y(P));p.length>12&&console.log(y(` \u2026and ${p.length-12} more`)),console.log("");let k=p;if(!a){let P=await fb({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${p.length} live`,value:"all"},...p.slice(0,8).map(S=>({name:`Just ${S.label}`,value:S.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(P==="none")return console.log(y("Left as drafts. Nothing changed.")),{kind:"continue"};P!=="all"&&(k=p.filter(S=>S.path===P))}let v=await Rl(n,t?.profileName,k,{skipReview:s,skipStyle:i,onProgress:(P,S,C)=>console.log(y(` \u25B8 ${P+1}/${S} ${bl(C)}\u2026`))});console.log("");for(let P of Sl(v))console.log(P.startsWith("\u2713")?G(P):P.startsWith("\u2717")?H(P):y(P));return{kind:"continue"}}async function br(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words, never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
|
|
355
|
+
`)}async function wo(e,t){try{let n=pl(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await ub({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${db}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var it="--skip-review";function kr(e,t){return ib(e,t)}function ti(e,t){try{return kr(e,ph(e,t)).length}catch{return 0}}function Ct(e,t,n="",o){let r=ti(e,o),s=gl(e,o);if(r===0&&s===0)return t;let i=o?` ${o}`:"",a=o?"/push":"/push --all",l=o&&!o.endsWith(".md")?` in ${o}`:"";if(r>0){let g=r===1?"":"s",k=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",v=`/review${i} --blocked --fix`;return{text:`${n}${r} article${g}${l} ${r===1?"carries":"carry"} text no editor has read, so pushing ${r===1?"it is":"them is"} blocked. ${v} reads ${r===1?"it":"just those"} and applies its fixes.${k} Then ${a}.`,cmd:v}}return{text:`${n}${s} article${s===1?"":"s"}${l} break${s===1?"s":""} house style rules that block publishing. /lint${i} --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${a}.`,cmd:`/lint${i} --fix`}}function gl(e,t){try{return dh(e,ph(e,t)).length}catch{return 0}}function wh(e,t){return dh(e,t)}function yl(e,t,n){try{let o=uh(e,pl(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function wl(e,t,n,o=0,r,s){let i=`/push${s?` ${s}`:" --all"}`,a=I=>t[I.index]?.paths.length??0,l=e.filter(I=>I.ok),p=e.filter(I=>!I.ok),g=e.reduce((I,O)=>I+a(O),0),k=l.reduce((I,O)=>I+a(O),0),v=n==="api"?`${Ze(e.reduce((I,O)=>I+O.costUsd,0))} total`:rn(e.reduce((I,O)=>I+O.outputTokens,0)),P=`${l.length}/${e.length} batch${e.length===1?"":"es"}`,S=I=>`${I} article${I===1?"":"s"}`,C=[],T=r?$t({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The push"):null;if(T)return C.push(...T),C.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&C.push(En(o)),C;if(r&&g>0&&r.recorded===0){C.push(`\u2717 Nothing was pushed \u2014 the ${S(g)} in this run are not recorded in the category map, so none of them reached Document360.`),C.push(`Run /doctor (this is usually the agent runtime not running), then re-run ${i}.`);for(let I of p)I.error&&C.push(` \u2717 ${I.label} \u2014 ${I.error}`);return o>0&&C.push(En(o)),C}if(p.length===0&&(!r||r.recorded>=g))C.push(`Pushed ${S(g)} (${P}) successfully \xB7 ${v}.`),C.push(`Saved on Document360 as draft${g===1?"":"s"} \u2014 readers don't see ${g===1?"it":"them"} until /publish takes ${g===1?"it":"them"} live.`);else if(p.length===0&&r)C.push(`Pushed ${r.recorded}/${S(g)} (${P}) \xB7 ${v}.`),C.push(`${g-r.recorded} article${g-r.recorded===1?"":"s"} reported no error but ${g-r.recorded===1?"is":"are"} not recorded on Document360 \u2014 re-run ${i} to retry just those.`);else{C.push(`Pushed ${r?r.recorded:k}/${S(g)} (${P}) \xB7 ${v}.`),C.push(`${p.length} batch${p.length===1?"":"es"} failed \u2014 re-run ${i} to retry just the rest (articles already on Document360 are skipped):`);for(let I of p)C.push(` \u2717 ${I.label}${I.error?` \u2014 ${I.error}`:""}`)}let D=r?_s(r):null;return D&&C.push(D),o>0&&C.push(En(o)),C}async function xt(e,t,n=0,o){let r=ab(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of lb(r,t.length))console.log(H(a));return{kind:"continue"}}let{model:s}=ob(e.cwd,"standard"),i=async(a,l)=>{let p=tb(a);console.log(y(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${a.length} article${a.length===1?"":"s"} in ${p.length} batch${p.length===1?"":"es"} (\u2264${yr} agents at once) on ${s}\u2026`)),l||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let g=!1;for await(let k of rb({cwd:e.cwd,partitions:p,promptFor:v=>wr(v.paths),concurrency:yr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(k.type==="partition_status")k.status==="running"?console.log(y(` \u25B8 ${k.label} \u2014 pushing\u2026`)):k.status==="done"?console.log(G(` \u2713 ${k.label}`)):console.log(N(` \u2717 ${k.label}`));else if(k.type==="run_done"){g=k.aborted,console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription",P=yl(e.cwd,a,e.profileName),S=!k.aborted&&(!!k.blocked||!!k.allEmpty||a.length>0&&P===0);for(let I of wl(k.results,p,v,l?0:n,{recorded:P,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(k.ok&&!S?G(I):H(I));if(S)continue;let C=ml(e.cwd,e.profileName);C&&console.log(y(C));let T=yo(e.cwd,e.profileName);T&&console.log(y(T));try{let I=fh(await hh({cwd:e.cwd,profileName:e.profileName,onRateLimit:O=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?H(I):y(I))}catch{}try{let I=gh(await mh({cwd:e.cwd,profileName:e.profileName}));I&&console.log(y(I))}catch{}let D=await wo(e.cwd,e.profileName);D&&console.log(y(D))}return g};try{if(!await i(t,!1)){let l=await kl(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(N(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function ni(e,t,n){let o=nb(e,n);if(o.length===0)return[];let r=new Set(fl((await Zs({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function kl(e,t,n){try{let o=new Set(n),r=await Zs({cwd:e,profileName:t});return fl(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function oi(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.includes(it),r=e.includes(cb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(v=>!v.startsWith("--")),l=Ie(i),p=Ks(l,a);if(p.length===0)return console.log(y(a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let g=zs(l);g&&console.log(g);let k=Ne("","--screenshots",a).trim();return t?await xt(t,p,0,{skipReview:o,skipStyle:r,scope:k}):{kind:"forward-to-agent",prompt:wr(p),display:`/push ${k}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ni(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(G("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await xt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(y("Checking what needs pushing\u2026"));try{let i=await Zs({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=An(i.entries),p=ei(i.entries),g=e.includes("--force")&&l.length>0;p>0&&console.log(H(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!g&&console.log(H(En(l.length)));let k=g?[...a,...l]:a;if(k.length===0){if(l.length>0){let P=yo(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(y(P)),console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(G(p>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let v=yo(t?.cwd??process.cwd(),t?.profileName);if(v&&console.log(y(v)),t)try{let P=fh(await hh({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?H(P):y(P));let S=gh(await mh({cwd:t.cwd,profileName:t.profileName}));S&&console.log(y(S))}catch{}return{kind:"continue"}}return t?await xt(t,k.map(v=>v.path),g?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:wr(k.map(v=>v.path)),display:"/push --all"}}catch(i){return console.log(N(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(y("Checking what needs pushing\u2026"));let i,a=0;try{let l=await Zs({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:g}=An(l.entries);i=p,a=g.length;let k=ei(l.entries);if(k>0&&console.log(H(`\u26A0 ${k} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(H(En(g.length))),i.length===0&&g.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(N(`Could not compute sync status: ${l.message}`)),console.log(y("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(G("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(y(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of i)console.log(` ${l.path} ${y(`(${l.label})`)}`);return console.log(y("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>eb({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}if(s==="--all")return await xt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:hl(s),display:`/push ${s}`}}ee();import{select as fb}from"@inquirer/prompts";import{computeSyncStatus as mb,localAheadPaths as gb,pendingDrafts as yb,publishArticleLive as wb,publishGateVerdict as kb,publishGateLines as bb,resolveActiveProfile as wE,SKIP_STYLE_FLAG as $b}from"document360-engine";var hb={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},kh=new Set;function Ft(e){let t=hb[e.replace(/^\//,"")];return!t||kh.has(e)?null:(kh.add(e),t)}var vb=150,xb=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),$l=e=>e===1?"":"s",bl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function vl(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function xl(e,t,n){await mb({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return yb(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:r.path}))}function Cb(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function Cl(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=gb(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${$l(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function Rl(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0;for(let i of n){o.onProgress?.(s,n.length,i.label);let a=await wb({articleId:i.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0});a.ok?r.published.push({path:i.path,...a.url?{url:a.url}:{}}):a.blocked?r.blocked.push({path:i.path,message:a.message}):r.failed.push({path:i.path,message:a.error.message}),s+=1,s<n.length&&await xb(vb)}return r}function Sl(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${$l(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);for(let s of t.slice(0,3))s.url&&r.push(` \u2B95 ${s.url}`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 /review --blocked --fix clears ${n.length===1?"it":"them"}:`);for(let s of n.slice(0,3))r.push(` \xB7 ${bl(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${bl(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function bh(e,t){let n=t?.cwd??process.cwd(),o=Ft("publish");if(vl(e))return o&&console.log(y(`\u2192 ${o}`)),console.log(y("Running /push\u2026")),oi(e,t);let r=Ue(n,t?.profileName);if(!r.ok)return console.log(N(r.reason)),{kind:"continue"};o&&console.log(y(`\u2192 ${o}`));let s=e.includes(it),i=e.includes($b),a=e.includes("--all"),l=e.find(P=>!P.startsWith("--"));console.log(y("Checking what is waiting to go live\u2026"));let p;try{p=await xl(n,t?.profileName,l)}catch(P){return console.log(N(`Could not check Document360: ${P.message}`)),{kind:"continue"}}if(p.length===0){for(let P of Cl(n,t?.profileName,l).lines)console.log(P.startsWith("\u2713")?G(P):y(P));return{kind:"continue"}}let g=kb(n,p.map(P=>P.path),{allowUnreviewed:s,allowStyleErrors:i});if(!g.clear){for(let P of bb(g,p.length,l))console.log(H(P));return{kind:"continue"}}console.log(""),console.log(`${p.length} draft${$l(p.length)} ${p.length===1?"is":"are"} ahead of what readers see:`);for(let P of Cb(p.slice(0,12)))console.log(y(P));p.length>12&&console.log(y(` \u2026and ${p.length-12} more`)),console.log("");let k=p;if(!a){let P=await fb({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${p.length} live`,value:"all"},...p.slice(0,8).map(S=>({name:`Just ${S.label}`,value:S.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(P==="none")return console.log(y("Left as drafts. Nothing changed.")),{kind:"continue"};P!=="all"&&(k=p.filter(S=>S.path===P))}let v=await Rl(n,t?.profileName,k,{skipReview:s,skipStyle:i,onProgress:(P,S,C)=>console.log(y(` \u25B8 ${P+1}/${S} ${bl(C)}\u2026`))});console.log("");for(let P of Sl(v))console.log(P.startsWith("\u2713")?G(P):P.startsWith("\u2717")?H(P):y(P));return{kind:"continue"}}async function br(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words, never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
|
|
356
356
|
`),display:"/audit"}}ee();import{readProjectConfig as Rb}from"document360-engine";function Pl(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding: the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief, with every claim cited to its grounding, and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn;'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
|
|
357
357
|
`)}async function $h(e,t){let n=t?.cwd??process.cwd();return Rb(n)?{kind:"forward-to-agent",prompt:Pl(),display:"/discover"}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{checkbox as Sb}from"@inquirer/prompts";import{inventoryRepo as Pb,readProjectConfig as vh,writeProjectConfig as Tb}from"document360-engine";function Tl(e,t){let n=vh(e);n&&(n.authoritativeSourceFiles=t,Tb(n,e))}function ri(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 xh(e,t){let n=t?.cwd??process.cwd();if(!vh(n))return console.log(N("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Pb(n);if(o.length===0)return console.log(y('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(K("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${y(ri(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Sb({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${ri(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(y("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Tl(n,r),console.log(G(`\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"}}ee();import{confirm as Ob}from"@inquirer/prompts";import{applyPull as Dl,computeSyncStatus as jh,compareRemoteSources as _b,planPull as Ih,planImport as Mb,applyImport as Fb,establishBaselines as Wb,rebaselineServerMeta as Ub,D360AuthError as Bb}from"document360-engine";ee();var Ch=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:N,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:K,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:N,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:N,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:$e,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:y,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:y,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:$e,mark:"\xB7"}];function Eb(e){return e.path?e.path:`${e.title??"(untitled)"} ${$e(`[${e.articleId}]`)}`}function Ab(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 si(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(We("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${H("~")} ${H(g.path??"")} ${$e(`\u2192 "${g.link.title}"`)}`)}for(let g of Ch){let k=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(k.length!==0){n.push(""),n.push(We(g.header));for(let v of k)n.push(` ${g.paint(g.mark)} ${g.paint(Eb(v))}${v.detail?$e(` (${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"},a=o.length,l=s===r?G("\u2713 everything up to date"):[r>0?G(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Ch.map(g=>{let k=(e.counts[g.status]??0)-(g.status==="untracked-local"?a:0);return k>0?`${k} ${i[g.status]}`:null})].filter(Boolean).join($e(" \xB7 ")),p=t!==void 0?` \xB7 synced in ${Ab(t)}`:"";return n.push(l+$e(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${p}`)),n}import{structuredPatch as Db}from"diff";import Rh from"picocolors";var Sh=80,Nb="\x1B[48;2;74;28;28m",jb="\x1B[48;2;24;66;24m",Ph="\x1B[49m",El=e=>String(e).padStart(5);function Th(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Eh(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 at(e,t,n){let o=v=>{let P=v.replace(/\r\n/g,`
|
|
358
358
|
`);return P.endsWith(`
|
|
359
359
|
`)||P===""?P:P+`
|
|
360
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Db("a","b",r,s,"","",{context:3}),l=0,p=0,g=[];a.hunks.forEach((v,P)=>{P>0&&g.push(Rh.gray(" \u2026"));let S=v.oldStart,C=v.newStart,T=[],D=[],I=()=>{for(let O=0;O<T.length;O++){let Y=O<D.length?Th(T[O],D[O]):void 0;p++,g.push(`${Nb}${El(S++)} - ${Eh(T[O],i,Y)}${Ph}`)}for(let O=0;O<D.length;O++){let Y=O<T.length?Th(T[O],D[O]):void 0;l++,g.push(`${jb}${El(C++)} + ${Eh(D[O],i,Y)}${Ph}`)}T=[],D=[]};for(let O of v.lines){let Y=O[0],fe=O.slice(1);Y==="-"?T.push(fe):Y==="+"?D.push(fe):(I(),g.push(Rh.gray(El(C))+" "+fe.slice(0,i)),S++,C++)}I()});let k=g.slice(0,Sh);return{added:l,removed:p,lines:k,hidden:Math.max(0,g.length-Sh)}}ee();import{select as Ib}from"@inquirer/prompts";import{applyPull as Dh,computeSyncStatus as Lb,planPull as Ah}from"document360-engine";var ii=e=>e===1?"":"s";async function Al(e,t,n=1){console.log(""),console.log(`${K("\u25CF")} ${We(t.title)} ${$e(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=at(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log($e(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ii(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(y(` \u2026 +${o.hidden} more diff lines`))}else console.log(y(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Ib({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,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"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(Dh({cwd:e.cwd,profileName:e.profileName},t),console.log(G(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(y(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function Nh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Lb({cwd:t.cwd,profileName:t.profileName})).entries.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path);if(o){if(!s.includes(o))return console.log(G(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(G("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,l]of s.entries()){let p=await Ah({cwd:t.cwd,profileName:t.profileName,relPath:l}),g=await Al(t,p,s.length-a);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let k=s.slice(a);if(g==="keep-local-all")i.push(...k),console.log(y(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let v=0;for(let P of k)try{Dh({cwd:t.cwd,profileName:t.profileName},await Ah({cwd:t.cwd,profileName:t.profileName,relPath:P})),v++}catch(S){console.log(N(` \u2717 ${P}: ${S.message}`))}console.log(G(` \u2713 Took the portal copy of ${v} article${ii(v)} (local overwritten, sync base advanced).`))}else console.log(y(` Skipped all ${k.length} \u2014 still conflict${ii(k.length)}.`));break}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${ii(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(N(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Lh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Hb(t),{kind:"continue"};if(o==="--baseline")return await qb(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gb(t),{kind:"continue"};if(o)return console.log(N(`Unknown option: ${o}`)),console.log(y("Usage: /pull pull portal edits + import new portal articles")),console.log(y(" /pull <path> pull one article (or resolve a conflict)")),console.log(y(" /pull --status drift report only (no writes)")),console.log(y(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Vb(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await Nl({cwd:t.cwd,profileName:t.profileName});for(let i of jl(s))console.log(i.tone==="ok"?G(i.text):i.tone==="warn"?H(i.text):y(i.text));console.log("")}catch(r){r instanceof Bb?console.log(N(r.message)):console.log(N(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Nl(e){let t=await jh({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 Ih({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Dl({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 Mb({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Fb({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 ai=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Dn=e=>e===1?"":"s";function jl(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Dn(e.pulled.length)} into local: ${ai(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Dn(e.imported.length)}: ${ai(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Dn(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Dn(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${ai(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Dn(e.failed.length)} failed: ${ai(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 Hb(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await jh({cwd:e.cwd,profileName:e.profileName});for(let o of si(n,Date.now()-t))console.log(o);console.log("")}async function qb(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(y(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Wb({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ub({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(G("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(G(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(G(`\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(y(` - ${s.path} (${s.reason})`))}}async function Gb(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await _b({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${We(String(t.legacyCount))} \xB7 Manifest: ${We(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(G("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(N(`\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(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Vb(e,t){let n=t.replace(/\\/g,"/"),o=await Ih({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Al(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${K("\u25CF")} ${We(o.title)} ${$e(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=at(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(y(" Local file already matches the remote content \u2014 advancing the sync base only.")),Dl({cwd:e.cwd,profileName:e.profileName},o);return}console.log($e(` \u23BF Added ${r.added} line${Dn(r.added)}, removed ${r.removed} line${Dn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(y(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Ob({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}Dl({cwd:e.cwd,profileName:e.profileName},o),console.log(G(` \u2713 Pulled ${o.path} (sync base advanced).`))}ee();import{statSync as Yb}from"node:fs";import{resolve as Kb}from"node:path";import{estimateBulkCost as zb,planPartitions as Xb,readProjectConfig as Qb,resolveModelForOperation as Jb,runPartitioned as Zb,trackedArticlePaths as e$}from"document360-engine";var Il=3;function Ll(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 Ol(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function _l(e,t){return t.map(n=>{let o=0;try{o=Yb(Kb(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ml(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, so be efficient:
|
|
360
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Db("a","b",r,s,"","",{context:3}),l=0,p=0,g=[];a.hunks.forEach((v,P)=>{P>0&&g.push(Rh.gray(" \u2026"));let S=v.oldStart,C=v.newStart,T=[],D=[],I=()=>{for(let O=0;O<T.length;O++){let Y=O<D.length?Th(T[O],D[O]):void 0;p++,g.push(`${Nb}${El(S++)} - ${Eh(T[O],i,Y)}${Ph}`)}for(let O=0;O<D.length;O++){let Y=O<T.length?Th(T[O],D[O]):void 0;l++,g.push(`${jb}${El(C++)} + ${Eh(D[O],i,Y)}${Ph}`)}T=[],D=[]};for(let O of v.lines){let Y=O[0],fe=O.slice(1);Y==="-"?T.push(fe):Y==="+"?D.push(fe):(I(),g.push(Rh.gray(El(C))+" "+fe.slice(0,i)),S++,C++)}I()});let k=g.slice(0,Sh);return{added:l,removed:p,lines:k,hidden:Math.max(0,g.length-Sh)}}ee();import{select as Ib}from"@inquirer/prompts";import{applyPull as Dh,computeSyncStatus as Lb,planPull as Ah}from"document360-engine";var ii=e=>e===1?"":"s";async function Al(e,t,n=1){console.log(""),console.log(`${K("\u25CF")} ${We(t.title)} ${$e(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=at(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log($e(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ii(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(y(` \u2026 +${o.hidden} more diff lines`))}else console.log(y(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Ib({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,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"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(Dh({cwd:e.cwd,profileName:e.profileName},t),console.log(G(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(y(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function Nh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Lb({cwd:t.cwd,profileName:t.profileName})).entries.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path);if(o){if(!s.includes(o))return console.log(G(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(G("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,l]of s.entries()){let p=await Ah({cwd:t.cwd,profileName:t.profileName,relPath:l}),g=await Al(t,p,s.length-a);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let k=s.slice(a);if(g==="keep-local-all")i.push(...k),console.log(y(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let v=0;for(let P of k)try{Dh({cwd:t.cwd,profileName:t.profileName},await Ah({cwd:t.cwd,profileName:t.profileName,relPath:P})),v++}catch(S){console.log(N(` \u2717 ${P}: ${S.message}`))}console.log(G(` \u2713 Took the portal copy of ${v} article${ii(v)} (local overwritten, sync base advanced).`))}else console.log(y(` Skipped all ${k.length} \u2014 still conflict${ii(k.length)}.`));break}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${ii(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(N(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Lh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Hb(t),{kind:"continue"};if(o==="--baseline")return await qb(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gb(t),{kind:"continue"};if(o)return console.log(N(`Unknown option: ${o}`)),console.log(y("Usage: /pull pull portal edits + import new portal articles")),console.log(y(" /pull <path> pull one article (or resolve a conflict)")),console.log(y(" /pull --status drift report only (no writes)")),console.log(y(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Vb(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await Nl({cwd:t.cwd,profileName:t.profileName});for(let i of jl(s))console.log(i.tone==="ok"?G(i.text):i.tone==="warn"?H(i.text):y(i.text));console.log("")}catch(r){r instanceof Bb?console.log(N(r.message)):console.log(N(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Nl(e){let t=await jh({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 Ih({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Dl({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 Mb({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Fb({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 ai=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Dn=e=>e===1?"":"s";function jl(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Dn(e.pulled.length)} into local: ${ai(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Dn(e.imported.length)}: ${ai(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Dn(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Dn(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${ai(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Dn(e.failed.length)} failed: ${ai(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 Hb(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await jh({cwd:e.cwd,profileName:e.profileName});for(let o of si(n,Date.now()-t))console.log(o);console.log("")}async function qb(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(y(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Wb({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ub({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(G("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(G(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(G(`\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(y(` - ${s.path} (${s.reason})`))}}async function Gb(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await _b({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${We(String(t.legacyCount))} \xB7 Manifest: ${We(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(G("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(N(`\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(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Vb(e,t){let n=t.replace(/\\/g,"/"),o=await Ih({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Al(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${K("\u25CF")} ${We(o.title)} ${$e(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=at(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(y(" Local file already matches the remote content \u2014 advancing the sync base only.")),Dl({cwd:e.cwd,profileName:e.profileName},o);return}console.log($e(` \u23BF Added ${r.added} line${Dn(r.added)}, removed ${r.removed} line${Dn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(y(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Ob({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}Dl({cwd:e.cwd,profileName:e.profileName},o),console.log(G(` \u2713 Pulled ${o.path} (sync base advanced).`))}ee();import{statSync as Yb}from"node:fs";import{resolve as Kb}from"node:path";import{estimateBulkCost as zb,planPartitions as Xb,readProjectConfig as Qb,resolveModelForOperation as Jb,runPartitioned as Zb,trackedArticlePaths as e$}from"document360-engine";var Il=3;function Ll(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 Ol(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function _l(e,t){return t.map(n=>{let o=0;try{o=Yb(Kb(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ml(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, so be efficient:
|
|
361
361
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal; you already have everything you need.
|
|
362
362
|
- 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.
|
|
363
363
|
- 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.
|
|
364
364
|
- Work only on these files:
|
|
365
365
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
366
|
-
`)}function Fl(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM
|
|
366
|
+
`)}function Fl(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Ze(r)}\u2013${Ze(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Wl(e,t,n){let o=S=>t[S.index]?.paths.length??0,r=e.filter(S=>S.ok),s=e.filter(S=>!S.ok),i=e.reduce((S,C)=>S+o(C),0),a=r.reduce((S,C)=>S+o(C),0),l=e.reduce((S,C)=>S+C.costUsd,0),p=e.reduce((S,C)=>S+C.outputTokens,0),g=n==="api"?`${Ze(l)} total`:rn(p),k=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,v=S=>`${S} article${S===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${v(i)} (${k}) successfully \xB7 ${g}.`);else{P.push(`Converted ${a}/${v(i)} (${k}) \xB7 ${g}.`),P.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let S of s)P.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`)}return P}async function Oh(e,t){if(!Qb(t.cwd))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ll(e),r=e$(t.cwd,t.profileName);if(r.length===0)return console.log(N("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Ol(r,n);if(s.length===0)return console.log(N(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Xb(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:p}=Jb(t.cwd,"light");if(!o){let g=zb({files:_l(t.cwd,s),op:"convert",model:l});n&&console.log(y(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of Fl(i,g,Il))console.log(k);return console.log(y(`Model: ${l}${p?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(y(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Converting ${s.length} articles in ${i.length} batches (\u2264${Il} agents at once) on ${l}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of Zb({cwd:t.cwd,partitions:i,promptFor:Ml,concurrency:Il,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(g.type==="partition_status")g.status==="running"?console.log(y(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(G(` \u2713 ${g.label}`)):console.log(N(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",v=$t(g,"The conversion");for(let P of v??Wl(g.results,i,k))console.log(v||!g.ok?H(P):G(P))}}catch(g){console.log(N(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}import{statSync as Xh}from"node:fs";import{resolve as Qh}from"node:path";import{estimateBulkCost as $$,lintDocs as v$,planFindingPartitions as x$,planPartitions as C$,readDocsPlan as R$,readProjectConfig as Jh,DEFAULT_DOCS_DIR as S$,resolveModelForOperation as Yh,runPartitioned as Kh,stampArticles as zh,CONTENT_CAP_VERSION as P$}from"document360-engine";ee();import{lintDocs as Bh,guidanceForRules as n$,planFindingPartitions as o$,runPartitioned as r$,resolveModelForOperation as s$,stampArticles as i$}from"document360-engine";import{CONTENT_CAP_VERSION as _h}from"document360-engine";function Mh(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/lint"||t[0]==="/check"?"lint":null:null}function Fh(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function Ye(e){return e==="review"?{reviewedCap:_h}:{checkedCap:_h}}var t$=e=>"ruleId"in e,li=e=>t$(e)?e.severity:"warning",ko=e=>e===1?"":"s";function Ul(e,t){let n=[...new Set([...e.unreviewed,...e.styleErrors.map(s=>s.path)])],o=t??(n.length===1?n[0]:void 0),r=o?` ${o}`:"";return e.unreviewed.length>0?`/review${r} --blocked --fix`:`/lint${r} --fix`}function $r(e){let{cwd:t,after:n,scope:o,aborted:r}=e,s=n.filter(v=>li(v)==="error").length,i=n.filter(v=>li(v)==="warning").length,a=n.filter(v=>li(v)==="suggestion").length,l=Ne("/lint","--fix",o);if(r)return{text:`Stopped. Nothing else changed \u2014 ${l} picks up where this left off.`,cmd:l};if(s>0){let v=new Set(n.filter(P=>li(P)==="error").map(P=>P.path)).size;return{text:`${s} error${ko(s)} in ${v} article${ko(v)} still block${s===1?"s":""} publishing. ${l} has another go at them \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:l}}let p=i>0&&a>0?`${i} warning${ko(i)} and ${a} suggestion${ko(a)} remain (neither blocks publishing). `:i>0?`${i} warning${ko(i)} remain${i===1?"s":""}, which ${i===1?"does":"do"} not block publishing. `:a>0?`${a} suggestion${ko(a)} remain${a===1?"s":""} \u2014 ${a===1?"it is":"they are"} judgment calls and ${a===1?"does":"do"} not block publishing. `:"",g=p===""?"\u2713 Nothing left to fix. ":`\u2713 ${p}`,k=o?"/push":"/push --all";return Ct(t,{text:`${g}Nothing is blocking${o?` in ${o}`:""} \u2014 ${k} saves the articles to Document360 as drafts.`,cmd:k},g,o)}var ui={error:0,warning:1,suggestion:2},a$={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},l$=10,c$=8,u$=96,Wh=34,jn=e=>"ruleId"in e,Nn=e=>jn(e)?e.severity:"warning",Hl=e=>jn(e)?e.ruleId:e.kind;function Bl(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function ci(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Nn(n)]++;return t}function Uh(e){let t=[];for(let n of["error","warning","suggestion"])e[n]>0&&t.push(`${e[n]} ${n}${e[n]===1?"":"s"}`);return t.join(" \xB7 ")}function vr(e,t={}){let n=t.baselined?[]:e.filter(k=>jn(k)&&k.baselined),o=t.baselined?e:e.filter(k=>!(jn(k)&&k.baselined)),r=n.length>0?[ke("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[ke("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let k of o){let v=s.get(k.path)??[];v.push(k),s.set(k.path,v)}let i=ci(o),a=[ke("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${Uh(i)}.`),""],l=[...s.entries()].sort((k,v)=>{let P=ci(k[1]);return ci(v[1]).error-P.error||v[1].length-k[1].length||k[0].localeCompare(v[0])}),p=t.full?l:l.slice(0,l$);for(let[k,v]of p){a.push(` ${k} ${y(Uh(ci(v)))}`);let P=new Map;for(let D of v){let I=Hl(D),O=P.get(I)??[];O.push(D),P.set(I,O)}let S=[...P.entries()].sort((D,I)=>ui[Nn(D[1][0])]-ui[Nn(I[1][0])]||I[1].length-D[1].length||D[0].localeCompare(I[0])),C=t.full?S:S.slice(0,c$);for(let[D,I]of C){let O=[...I].sort((ue,Te)=>ue.line-Te.line),Y=a$[Nn(O[0])],ae=new Set(O.map(ue=>ue.term)).size===1?` ${Bl(`"${O[0].term}"`,Wh)}`:"",le=O.length>1?y(` \xD7${O.length}`):"",he=t.full?O[0].message:Bl(O[0].message,u$);a.push(` ${Y} ${D}${le}${ae}`),a.push(` ${y(he)}`);let ce=O.map(ue=>ae?`L${ue.line}`:`L${ue.line} ${Bl(`"${ue.term}"`,Wh)}`),X=t.full?ce:ce.slice(0,12),ne=ce.length-X.length;a.push(` ${y(X.join(", ")+(ne>0?` \u2026+${ne}`:""))}`)}let T=S.length-C.length;T>0&&a.push(y(` \u2026${T} more rule${T===1?"":"s"} fired here (/lint ${k} --full)`)),a.push("")}let g=l.length-p.length;return g>0&&(a.push(y(` \u2026and ${g} more article${g===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var d$=200;function di(e){let n=[...e.filter(l=>!(jn(l)&&l.baselined))].sort((l,p)=>ui[Nn(l)]-ui[Nn(p)]||l.path.localeCompare(p.path)||l.line-p.line),o=n.slice(0,d$),r=n.length-o.length,s=new Map;for(let l of o){let p=s.get(l.path)??[];p.push(l),s.set(l.path,p)}let i=[...s.entries()].map(([l,p])=>[l,...p.map(g=>` - L${g.line} [${Hl(g)}] (${Nn(g)}): "${g.term}": ${g.message}`)].join(`
|
|
367
367
|
`)).join(`
|
|
368
368
|
`),a=n$(o.map(l=>({id:Hl(l),message:l.message,link:jn(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
|
|
369
|
-
`)}var bo=3;function ql(e,t,n){let o=n.filter(a=>!(jn(a)&&a.baselined));if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=`/lint${r?` ${r}`:""} --fix`,i=o$(o);return i.length<=1?{kind:"single",prompt:di(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return di(o.filter(p=>l.has(p.path)))}}}async function p$(e,t,n){let{model:o}=s$(e.cwd,"standard");console.log(y(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length}
|
|
369
|
+
`)}var bo=3;function ql(e,t,n){let o=n.filter(a=>!(jn(a)&&a.baselined));if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=`/lint${r?` ${r}`:""} --fix`,i=o$(o);return i.length<=1?{kind:"single",prompt:di(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return di(o.filter(p=>l.has(p.path)))}}}async function p$(e,t,n){let{model:o}=s$(e.cwd,"standard");console.log(y(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${bo} at once) on ${o}\u2026`));let r=[];try{for await(let a of r$({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:bo,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(a.type==="partition_status")a.status==="running"?console.log(y(` \u25B8 ${a.label} \u2014 fixing\u2026`)):a.status==="done"?console.log(G(` \u2713 ${a.label}`)):console.log(N(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=a.results.filter(p=>!p.ok);if(l.length&&console.log(H(`\u26A0 ${l.length} batch${l.length===1?"":"es"} not fixed: ${l.map(p=>p.label).join(", ")}`)),a.blocked&&console.log(H(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(H("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!a.allEmpty&&!a.blocked){let p=new Set(l.map(g=>g.label));r.push(...t.partitions.filter(g=>!p.has(g.label)).flatMap(g=>g.paths))}}}catch(a){return console.log(N(`Fix run failed: ${a.message}`)),{kind:"continue"}}if(r.length>0)try{i$(e.cwd,r,Ye("lint"))}catch{}let s=Bh({cwd:e.cwd,scope:n}).filter(a=>!a.baselined);console.log("");for(let a of vr(s))console.log(s.length===0?G(a):H(a));let i=$r({cwd:e.cwd,after:s,before:t.findings,scope:n});return console.log(""),console.log(y(i.text)),{kind:"continue",ownNext:!0}}async function Gl(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=Bh({cwd:t.cwd,scope:o});if(n){let i=ql(t.cwd,e,s);return i?i.kind==="partitioned"?p$(t,i,o):(console.log(y(`Fixing ${i.findings} doc issue${i.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:i.prompt,display:`/lint${r} --fix`}):(console.log(G("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"})}console.log(y("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let i of vr(s,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(s.length===0?G(i):H(i));return s.length>0&&console.log(y(`Run /lint${r} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:s.length>0}}var Hh=async(e,t)=>{let n=Ft("check");return n&&console.log(y(`\u2192 ${n}`)),Gl(e,t)};ee();import{readProjectConfig as h$,loadProfileMap as f$,resolveActiveProfile as m$,desiredCategoryOrder as g$,desiredArticleOrder as y$,DEFAULT_DOCS_DIR as w$}from"document360-engine";var Vl=e=>e.replace(/\\/g,"/"),qh=e=>Vl(e).split("/").pop()??e;function Yl(e){let t=qh(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var k$=Yl;function xr(e,t){try{let n=h$(e);if(!n)return[];let o=m$(e,t),r=f$(e,o.name);if(!r)return[];let s=Vl(n.docsDir??w$).replace(/\/+$/,""),i=new Map;for(let l of y$(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of g$(r)){let p=Vl(l.path),g=p.startsWith(`${s}/`)?p.slice(s.length+1):p===s?"":p;g&&a.push({token:g,label:k$(qh(p)),count:i.get(l.path)??0})}return a}catch{return[]}}function Gh(e,t){let n=xr(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function ln(e,t){if(t.includes("--all")||t.includes("--blocked")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!Cr(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){b$.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var b$=new Set(["--scope","--concurrency"]);function $o(e,t,n,o,r){if(r=r??xr(e,o),r.length<=1)return[];let s=n.filter(p=>p.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=p=>t==="write"?`/write --scope ${p}${i}`:`/${t} ${p}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((p,g)=>p+g.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(p=>` ${l(p.token)} (${p.label} \xB7 ${p.count} article${p.count===1?"":"s"})`)]}function Cr(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Vh(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var T$=3,E$=8;function Kl(e){return e===void 0||!Number.isFinite(e)?T$:Math.max(1,Math.min(Math.floor(e),E$))}function Rr(e){let t,n,o=!1,r=!1,s,i=l=>{let p=Number(l);return l!==void 0&&Number.isFinite(p)?p:void 0};for(let l=0;l<e.length;l++){let p=e[l];if(p==="--preview"||p==="--dry-run")o=!0;else if(p==="--rewrite"||p==="--force")r=!0;else{if(p==="--run"||p==="--yes"||p==="--all")continue;p==="--scope"?t=e[++l]:p?.startsWith("--scope=")?t=p.slice(8):p==="--concurrency"?s=i(e[++l]):p?.startsWith("--concurrency=")?s=i(p.slice(14)):p&&!p.startsWith("--")&&(n=p)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function A$(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function D$(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function zl(e,t,n){return n.filter(o=>{try{return Xh(Qh(e,t,o)).size===0}catch{return!0}})}function Xl(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let i of o.get(r)?.sources??[])try{s+=Xh(Qh(e,i)).size}catch{}return{path:r,bytes:s}})}function Ql(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing, and its structure is NOT the target; match only the project's voice/terminology.
|
|
370
370
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
371
371
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
372
372
|
- Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
|
|
@@ -376,7 +376,7 @@ ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await ca
|
|
|
376
376
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360; these are local drafts.
|
|
377
377
|
Articles:
|
|
378
378
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
379
|
-
`)}function Jl(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"}
|
|
379
|
+
`)}function Jl(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${Ze(r)}\u2013${Ze(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Zl(e,t,n,o){let r=C=>t[C.index]?.paths.length??0,s=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),a=e.reduce((C,T)=>C+r(T),0),l=s.reduce((C,T)=>C+r(T),0),p=e.reduce((C,T)=>C+T.costUsd,0),g=e.reduce((C,T)=>C+T.outputTokens,0),k=n==="api"?`${Ze(p)} total`:rn(g),v=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,P=C=>`${C} article${C===1?"":"s"}`,S=[];if(i.length===0){S.push(`Wrote ${P(a)} (${v}) successfully \xB7 ${k}.`);let C=o?` ${o}`:"",T=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";S.push("Next \u2014 an editorial review, because these were written by an AI:"),S.push(`/review${C} --fix`),S.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${D} if you want them).`)}else{S.push(`Wrote ${l}/${P(a)} (${v}) \xB7 ${k}.`),S.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let C of i)S.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return S}function Sr(e,t,n){try{return v$({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function ec(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function tc(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=x$(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return di(t.filter(s=>r.has(s.path)))}}}function nc(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function pi(e,t,n){let o=(Jh(e)?.docsDir??S$).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=A$(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=D$(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=zl(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function oc(e,t,n){let{targets:o}=pi(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:Yl(s),count:i}))}async function Zh(e,t){if(!Jh(t.cwd))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Cr(e)){for(let D of Gh(t.cwd,t.profileName))console.log(y(D));return{kind:"continue"}}let n=R$(t.cwd);if(n.length===0)return console.log(N("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(ln("write",e)){let D=oc(t.cwd,n,{rewrite:Rr(e).rewrite}),I=$o(t.cwd,"write",e,t.profileName,D);if(I.length>0){for(let O of I)console.log(y(O));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Rr(e),{docsDir:l,targets:p,reason:g,rewriting:k}=pi(t.cwd,n,{scope:o,path:r,rewrite:a});if(p.length===0)return console.log(g?H(g):H("Nothing to write.")),{kind:"continue"};k&&console.log(H(`--rewrite: regenerating ${p.length} already-written article${p.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=C$(p),P=Kl(i),{model:S,forced:C}=Yh(t.cwd,"standard"),T=!!r;if(s&&!T){let D=$$({files:Xl(t.cwd,n,p),op:"write",model:S});o&&console.log(y(`Scope: ${o} (${p.length} pending).`));for(let I of Jl(v,D,P))console.log(I);return console.log(y(`Model: ${S}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(y(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Writing ${p.length} article${p.length===1?"":"s"} in ${v.length} batch${v.length===1?"":"es"} (\u2264${P} agents at once) on ${S}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let D of Kh({cwd:t.cwd,partitions:v,promptFor:I=>Ql(I,l,{rewrite:k||T}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:S}))if(D.type==="partition_status")D.status==="running"?console.log(y(` \u25B8 ${D.label} \u2014 writing\u2026`)):D.status==="done"?console.log(G(` \u2713 ${D.label}`)):console.log(N(` \u2717 ${D.label}`));else if(D.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription",O=$t(D,"The write");if(O){for(let le of O)console.log(H(le));continue}for(let le of Zl(D.results,v,I,o??r))console.log(D.ok?G(le):H(le));if(D.ok)try{zh(t.cwd,p.map(le=>`${l}/${le}`),{writtenCap:P$,reviewedCap:0,checkedCap:0})}catch{}let Y=Sr(t.cwd,l,p),fe=ec(Y);fe&&console.log(H(fe));let ae=e.includes("--skip-style")?null:tc(Y);if(ae){console.log(y(`Fixing ${ae.errors.length} style error(s) in ${ae.articles} article(s) \u2014 one pass\u2026`));let{model:le}=Yh(t.cwd,"standard"),he=[];try{for await(let ce of Kh({cwd:t.cwd,partitions:ae.partitions,promptFor:ae.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:le}))if(ce.type==="partition_status"&&ce.status!=="running")console.log(ce.status==="done"?G(` \u2713 ${ce.label}`):N(` \u2717 ${ce.label}`));else if(ce.type==="run_done"&&!ce.allEmpty&&!ce.blocked){let X=new Set(ce.results.filter(ne=>!ne.ok).map(ne=>ne.label));he.push(...ae.partitions.filter(ne=>!X.has(ne.label)).flatMap(ne=>ne.paths))}}catch(ce){console.log(H(`Style fix pass failed: ${ce.message}`))}if(he.length>0)try{zh(t.cwd,he,Ye("lint"))}catch{}for(let ce of nc(ae.errors.length,Sr(t.cwd,l,p)))console.log(ce.startsWith("\u2713")?G(ce):H(ce))}}}catch(D){console.log(N(`Write run failed: ${D.message}`))}return console.log(""),{kind:"continue"}}ee();import{existsSync as N$,readdirSync as ef,statSync as tf}from"node:fs";import{join as nf}from"node:path";import{inputDir as j$,readProjectConfig as I$}from"document360-engine";var of=/\.(md|markdown|pdf|txt)$/i;function rc(e){let t=j$(e);if(!N$(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ef(t)){let s=nf(t,r),i=!1;try{i=tf(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=L$(s);a>0&&n.push({name:r,docCount:a})}else of.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function L$(e){let t=0;for(let n of ef(e))try{tf(nf(e,n)).isFile()&&of.test(n)&&t++}catch{}return t}function sc(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 hi(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, and 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(`
|
|
380
380
|
`)}var ic="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function rf(e,t){let n=t?.cwd??process.cwd();if(!I$(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=rc(n);if(o.length===0&&r===0)return console.log(y(ic)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(y("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${y(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:hi(a),display:a?`/draft ${a}`:"/draft"}}let i=sc(o,s);return{kind:"forward-to-agent",prompt:hi(i??"",i?void 0:s),display:`/draft ${s}`}}ee();import{listOpenForDocs as O$,readProjectConfig as _$}from"document360-engine";function ac(e){try{return O$(e).filter(t=>t.kind==="request").length}catch{return 0}}function lc(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(it),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function cc(e){let t=["Run the document-handoff skill.",""];return e?t.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: 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."):t.push("No description was given, so 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."),t.push("","Draft only; 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.join(`
|
|
381
381
|
`)}var uc="Nothing to document yet. Say what changed: /document <what you shipped>, or have the builder drop a request via their /devhints hand-off.";async function sf(e,t){let n=t?.cwd??process.cwd();if(!_$(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=lc(e);if(!r&&ac(n)===0)return console.log(y(uc)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:cc(r),display:s}}ee();import{search as M$}from"@inquirer/prompts";import{findByName as F$,getSession as W$,listSessions as U$,relativeTime as lf}from"document360-engine";async function cf(e,t){let n=U$(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(y("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=F$(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(N(`No session matches "${o}".`)),af(n),{kind:"continue"})}if(!process.stdin.isTTY)return af(n),console.log(y("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>M$({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(a=>!i||a.name.toLowerCase().includes(i)||a.firstPrompt.toLowerCase().includes(i)).map(a=>({name:`${a.name} ${lf(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=W$(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function af(e){console.log("");for(let t of e.slice(0,15))console.log(` ${K(t.name)} ${y(lf(t.updatedAt))}`),console.log(` ${y(t.firstPrompt.slice(0,80))}`);console.log("")}ee();import{renameSession as B$}from"document360-engine";function dc(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 uf(e,t){let n=dc(e.join(" "));if(!n)return console.log(N("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(B$(o,n)?console.log(G(`\u2713 Session renamed to "${n}"`)):console.log(N("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(G(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as df,readProjectConfig as H$,writeProjectConfig as q$}from"document360-engine";ee();function pc(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=H$(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 df().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},q$(o,e),null):`Unknown environment "${r}". Known: ${df().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function pf(e,t){let n=e[0];if(!n)return vs(t.cwd),{kind:"continue"};if(n==="add"){let o=pc(t.cwd,e[1],e[2]);return o?(console.log(N(o)),{kind:"continue"}):(console.log(G(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${K(`/profile ${e[1]}`)} then ${K("/login")}`),console.log(y(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return xs(t.cwd,n),Cs(t.cwd,n),console.log(y(" Restarting agent for the new profile\u2026")),{kind:"clear"}}ee();import{select as G$}from"@inquirer/prompts";import{readProjectConfig as V$,readUserConfig as hf,resolveModelSetting as hc,writeUserConfig as ff}from"document360-engine";var Rt=[{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 fi(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Rt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Y$(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 Pr(e,t){let n=()=>hc(e).model;if(t==="default"){let s=hf();return s.defaultModel?(delete s.defaultModel,ff(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${hc(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}}ff({...hf(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=V$(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 mf(e,t){let n=e[0]?.trim();if(!n){let i=hc(t.cwd);if(!process.stdin.isTTY)return console.log(`${We("Model:")} ${K(i.model)}${i.source==="auto"?y(" (auto)"):""}`),console.log(y(` source: ${Y$(i)}`)),console.log(y(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=fi(i),l;try{l=await t.withPausedInput(()=>G$({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Rt[a].value,choices:Rt.map((v,P)=>({name:`${v.label}${P===a?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}let{lines:p,changed:g,effective:k}=Pr(t.cwd,l??"default");for(let v of p)console.log(v.startsWith("\u26A0")?H(v):v.startsWith("\u2713")?G(v):y(v));return g&&await t.setModel(k),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Pr(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?G(i):y(i));return r&&await t.setModel(s),{kind:"continue"}}mi();async function $f(e,t){return await t.withPausedInput(()=>io(t.cwd)),{kind:"clear"}}async function vf(e,t){return await t.withPausedInput(()=>ws(t.cwd,t.profileName)),{kind:"clear"}}ee();import{resolveActiveProfile as pv}from"document360-engine";async function xf(e,t){let n=!1;try{n=pv(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(y("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}ee();var Cf=async(e,t)=>{try{await t.withPausedInput(()=>$s({}))}catch(n){console.log(N(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as hv,clearTokens as fv,clearProfileProject as mv}from"document360-engine";ee();async function Rf(e,t){let n,o;try{let i=hv(t.cwd,t.profileName);n=i.name,o=i.connection.name}catch(i){return console.log(N(i.message)),{kind:"continue"}}let r=fv(n);mv(t.cwd,n),console.log(r?G(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):y(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(y(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let s=Zt(t.cwd,t.profileName);return console.log(s?H(`\u26A0 ${s.why}. Signing out doesn\u2019t change the environment \u2014 ${s.cmd} does.`):y(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{spawn as Pf}from"node:child_process";import{existsSync as gc,readFileSync as mc,statSync as xv}from"node:fs";import{homedir as Cv}from"node:os";import{basename as Rv,join as Nr}from"node:path";import{readProjectConfig as Sv,DEFAULT_OUTPUT_DIR as Pv,existingAnnotatedShotPath as Tv,resolveOutputDir as Ev}from"document360-engine";import et from"picocolors";import{annotationsPath as gv,resolveOutputDir as yv,readProjectConfig as wv,DEFAULT_OUTPUT_DIR as kv,existingAnnotatedShotPath as bv}from"document360-engine";function $v(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Er(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function In(e,t){let n=yv(e,wv(e)?.outputDir??kv),o=new Map(Ie(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(bv(n,i))}`,` facts: ${r(gv(n,i))}`,` article: ${a}`].join(`
|
|
382
382
|
`)}).join(`
|
|
@@ -399,71 +399,73 @@ Articles:
|
|
|
399
399
|
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Bx(e){return im(e,".d360-writer/hints")}function Hx(e){return im(e,".d360-writer/messages")}function Vc(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Bx(e),o=Hx(e),r=Bc(Hc(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${om(e)}`]}async function am(e,t){let n=qc(t.cwd);for(let l of Vc(t.cwd,n))console.log(n.length===0?y(l):l);if(n.length===0)return{kind:"continue"};let o=om(t.cwd);if((await t.withPausedInput(()=>_x({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Bc(Fx(t.cwd)),{removed:i,failed:a}=Gc(t.cwd,n);console.log(G(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(N(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Ds())console.log(l);console.log(y("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(y("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}ee();import{buildBaseline as qx,buildRegistry as zc,clearRegistryCache as Gx,lintArticles as Xc,listAvailablePacks as um,readProjectConfig as Fr,readStyleBaseline as Vx,resolveActivePacks as Yx,styleGuidePath as dm,writeProjectConfig as pm,writeStyleBaseline as Kx,activeRuleSet as zx,buildStyleCompilePrompt as Xx,loadStyleGuide as Qx,listStyleGuides as Jx,getStyleGuide as Zx,resolveActiveProfile as e0,resolveProjectId as t0,STYLE_GUIDE_MAX_CHARS as lm,BUILTIN_RULES as Ri,ALWAYS_ON_PACK as So}from"document360-engine";import{existsSync as hm,mkdirSync as n0,readFileSync as o0,writeFileSync as cm}from"node:fs";import{dirname as r0}from"node:path";import{createHash as s0}from"node:crypto";function i0(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:{sub:"show"}}var Mr="House";async function a0(e,t,n){let o,r;try{let C=e0(e,n);o={profile:C.name,connection:C.connection},r=await t0(o,C.project?.projectId)}catch(C){return{lines:[ke("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),y(" Run /login first.")],restart:!1}}let s=await Jx(o,r);if(s.kind!=="ok")return{lines:[ke("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),y(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),y(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),y(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[ke("\u2139","This Document360 project has no style guides yet."),y(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((T,D)=>{let I=[T.language_code,T.created_by_name,T.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${T.name??T.id}${T.is_default?y(" (default)"):""}${I?y(` ${I}`):""}`}),"",y(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(C=>C.id===t);if(!a)return{lines:[ke("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await Zx(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let C=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[ke("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let p=(l.guide.content??"").trim();if(!p)return{lines:[ke("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let g=dm(e),k=[];if(hm(g))try{cm(`${g}.bak`,o0(g,"utf8"),"utf8"),k.push(y(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let v=p.length>lm?p.slice(0,lm):p,P=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
400
400
|
|
|
401
401
|
`;n0(r0(g),{recursive:!0}),cm(g,`${P}${v}
|
|
402
|
-
`,"utf8");let S=Fr(e)??{projectId:""};return pm({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:s0("sha1").update(v).digest("hex").slice(0,16)}}},e),{lines:[ke("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${v.length.toLocaleString()} characters).`),...k,y(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),y(" Turn its mechanical parts into checks: /style-guide compile"),y(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function l0(e){let t=zc(e).rules.filter(n=>n.pack.toLowerCase()===Mr.toLowerCase()).map(n=>n.id);return{prompt:Xx({guide:Qx(e),packName:Mr,existingRuleIds:t}),display:"/style-guide compile"}}function fm(){return[y(` Review what it wrote: git diff .d360-writer/styles/${Mr}/`),y(` Anything it could not check mechanically is listed in .d360-writer/styles/${Mr}/UNCHECKABLE.md \u2014 /review judges those.`),y(` Turn them on when you are happy: /style-guide use ${Mr.toLowerCase()} (they start as warnings, never blocking)`)]}var lt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Yc=e=>/^v\d/i.test(e)?e:`v${e}`;function mm(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function c0(e){let n=Fr(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:hm(dm(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function u0(e){let t=Fr(e),n=zc(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===So),s=n.packs.filter(l=>l.name.toLowerCase()!==So),i=[`Style guide: ${c0(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Yc(l.version)}`).join(", "):y("none chosen")}`,`Always on: ${y(`d360 (correctness, built in \u2014 ${lt(Ri.length,"rule")})`)}`];for(let l of r)i.push(` ${y(`${l.name.toLowerCase()} ${Yc(l.version)} (anti-slop \u2014 ${lt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(y(" Every article here is machine-written, so these cannot be switched off by")),i.push(y(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Ri.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${lt(a.length,"rule")} active \xB7 ${mm(a)}`);try{let l=Xc({cwd:e}),p=l.findings.filter(k=>!k.baselined),g=p.filter(k=>k.severity==="error").length;i.push(""),i.push(g===0?ke("\u2713",`No style errors across the docs${p.length>0?`, though ${lt(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):ke("\u2717",`${lt(g,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(ke("\u2139",`${lt(l.baselinedCount,"pre-existing issue")} recorded as accepted when a pack was adopted, so they never block.`)),l.ruleErrors.length>0&&i.push(ke("\u26A0",`${lt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(k=>`${k.ruleId} (${k.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(y(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),i}function Kc(e){let t=Fr(e),n=new Set(Yx(t?.styleGuide)),o=um(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),p=a===So,g=l?"\u2713":"\xB7",k=p?y("(always on)"):l?y("(active)"):"",v=i.local?y(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${v} ${i.description??""}`),r.push(` ${y(`${lt(i.rules.length,"rule")} \xB7 ${mm(i.rules)} \xB7 ${Yc(i.version)}`)} ${k}`),i.errors.length>0&&r.push(ke("\u26A0",`${lt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===So)&&(r.push(""),r.push(y(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(y(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(y(" Several: /style-guide use microsoft,google")),r.push(y(" Back to none: /style-guide use none")),r}function d0(e,t){if(!t)return[ke("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=zc(e),o=Ri.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...Ri.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ke("\u26A0",`No active rule called "${t}".`),...p.length>0?[y(` Did you mean: ${p.join(", ")}`)]:[y(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(y(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(ke("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=Xc({cwd:e}).findings.filter(k=>k.ruleId===s),g=p.filter(k=>!k.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${lt(g.length,"finding")}${p.length!==g.length?`, plus ${p.length-g.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(y(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(y(" catch defects of fact, not matters of taste."))):(l.push(y(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(y(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function p0(e,t){let n=(t??"").trim();if(!n)return{lines:[ke("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Kc(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(um(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[ke("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...Kc(e)],restart:!1};let i=Fr(e)??{projectId:""};pm({...i,styleGuide:{...i.styleGuide,packs:o}},e),Gx();let a=[ke("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(So)?"":` (+ ${So}, always on)`}\u2026`)];try{let l=Xc({cwd:e}),p=new Set(l.findings.map(g=>g.path)).size;if(l.findings.length===0)a.push(ke("\u2713",p===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let g=Vx(e),k=qx(l.findings,zx(e));Kx(e,k),a.push(ke("\u2713",`Recorded ${lt(l.findings.length,"existing issue")} across ${lt(p,"article")} as accepted.`),y(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),y(" teammate with a different copy gets a different answer from the same gate."),ke("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),g&&a.push(y(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(l){a.push(ke("\u26A0",`The packs are active, but recording what was already there failed: ${l instanceof Error?l.message:String(l)}`)),a.push(y(" Run /lint to see the current state before publishing."))}return a.push(y(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Si(e,t){let{sub:n,value:o}=i0(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Kc(t.cwd)),{kind:"continue"};case"explain":return r(d0(t.cwd,o)),{kind:"continue"};case"use":{let s=p0(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await a0(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=l0(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(u0(t.cwd)),{kind:"continue"}}}ee();import{lintDocs as Qc,loadStyleGuide as km,buildReviewPrompt as bm,readProjectConfig as $m,DEFAULT_DOCS_DIR as vm,listArticleFiles as xm,planPartitions as w0,runPartitioned as k0,resolveModelForOperation as b0,stampArticles as $0}from"document360-engine";ee();import{readProjectConfig as h0,loadProfileMap as f0,resolveActiveProfile as m0,desiredCategoryOrder as g0,desiredArticleOrder as y0}from"document360-engine";function gm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var ym=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Wr(e,t){try{if(!h0(e))return[];let n=m0(e,t),o=f0(e,n.name);if(!o)return[];let r=new Map;for(let i of y0(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of g0(o)){s.push(gm(ym(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${gm(ym(a.path))}`)}return s}catch{return[]}}async function wm(e,t){let n=Wr(t.cwd,t.profileName);if(n.length===0)return console.log(y("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(K("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Br(e,t){return kr(e,xm(e,t))}function v0(e,t,n){return t.includes("--blocked")?Br(e,n):xm(e,n)}function x0(e,t){let n=$m(e);if(!n)return null;let o=(n.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(P=>!P.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Qc({cwd:e}),l=i?a.filter(P=>P.path===`${o}/${i}`||P.path.startsWith(`${o}/${i}/`)):a,p=s?Br(e,i):void 0,g=p?l.filter(P=>p.includes(P.path)):l,k=i||s?"":Wr(e).join(`
|
|
403
|
-
`);return{prompt:bm({docsRoot:o,scope:i,styleGuide:km(e),deterministicFindings:g,fix:r,structure:k||void 0,...p?{paths:p}:{}}),display:`/review${i?` ${i}`:""}${s?" --blocked":""}${r?" --fix":""}`}}var C0=e=>"ruleId"in e,Ur=3,R0=3;function Jc(e,t){let n=x0(e,t);if(!n)return null;let o=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=v0(e,t,o),s=w0(r,{maxPerPartition:R0});if(s.length<=1)return{kind:"single",...n};let a=($m(e)?.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),p=km(e),g=Qc({cwd:e});return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!t.includes("--blocked"),display:n.display,promptFor:k=>{let v=new Set(k.paths);return bm({docsRoot:a,styleGuide:p,deterministicFindings:g.filter(P=>v.has(P.path)),fix:l,paths:k.paths})}}}async function Cm(e,t){if(e.includes("--blocked")&&Br(t.cwd,e.find(o=>!o.startsWith("--"))).length===0)return console.log(G("\u2713 Nothing is blocked \u2014 every article has been through an editorial read.")),console.log(y(" /review --all --fix re-reviews everything; /push --all saves what has changed to Document360.")),{kind:"continue",ownNext:!0};if(ln("review",e)){let o=$o(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=Jc(t.cwd,e);return n?n.kind==="single"?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:await S0(t,n,e.includes("--fix"),e.find(o=>!o.startsWith("--"))):(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function S0(e,t,n,o){let{model:r}=b0(e.cwd,"standard");console.log(y(`Reviewing ${t.articles} article${t.articles===1?"":"s"}
|
|
404
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function Rm(e,t){if(ln("reorder",e)){let o=$o(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=eu(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{readProjectConfig as T0,writeProjectConfig as Sm,isAppType as E0,playbookSkillName as A0,detectAppType as Pm}from"document360-engine";var Tm=["web","cli","service","library"],D0=new Set(["web","cli"]);function tu(e){return D0.has(e)?`${A0(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Pi(e,t){let n=t.cwd,o=T0(n);if(!o)return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Pm(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${K("Genre:")} ${s} (${i}) \u2014 ${tu(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(y(`Set it: /genre <${Tm.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(y("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Sm(i,n);let a=Pm(n);return console.log(G(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${tu(a)})`:"unclassified (no playbook)"}.`)),console.log(y(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return E0(r)?(Sm({...o,appType:r},n),console.log(G(`\u2713 Genre set to ${r} \u2014 ${tu(r)}.`)),console.log(y(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(N(`Unknown genre "${r}". Choose one of: ${Tm.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}ee();import{listRoadmap as Ti,roadmapProgress as Em,stampRoadmapDone as N0}from"document360-engine";function nu(e){let t=Ti(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=Em(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`)
|
|
402
|
+
`,"utf8");let S=Fr(e)??{projectId:""};return pm({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:s0("sha1").update(v).digest("hex").slice(0,16)}}},e),{lines:[ke("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${v.length.toLocaleString()} characters).`),...k,y(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),y(" Turn its mechanical parts into checks: /style-guide compile"),y(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function l0(e){let t=zc(e).rules.filter(n=>n.pack.toLowerCase()===Mr.toLowerCase()).map(n=>n.id);return{prompt:Xx({guide:Qx(e),packName:Mr,existingRuleIds:t}),display:"/style-guide compile"}}function fm(){return[y(` Review what it wrote: git diff .d360-writer/styles/${Mr}/`),y(` Anything it could not check mechanically is listed in .d360-writer/styles/${Mr}/UNCHECKABLE.md \u2014 /review judges those.`),y(` Turn them on when you are happy: /style-guide use ${Mr.toLowerCase()} (they start as warnings, never blocking)`)]}var lt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Yc=e=>/^v\d/i.test(e)?e:`v${e}`;function mm(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function c0(e){let n=Fr(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:hm(dm(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function u0(e){let t=Fr(e),n=zc(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===So),s=n.packs.filter(l=>l.name.toLowerCase()!==So),i=[`Style guide: ${c0(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Yc(l.version)}`).join(", "):y("none chosen")}`,`Always on: ${y(`d360 (correctness, built in \u2014 ${lt(Ri.length,"rule")})`)}`];for(let l of r)i.push(` ${y(`${l.name.toLowerCase()} ${Yc(l.version)} (anti-slop \u2014 ${lt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(y(" Every article here is machine-written, so these cannot be switched off by")),i.push(y(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Ri.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${lt(a.length,"rule")} active \xB7 ${mm(a)}`);try{let l=Xc({cwd:e}),p=l.findings.filter(k=>!k.baselined),g=p.filter(k=>k.severity==="error").length;i.push(""),i.push(g===0?ke("\u2713",`No style errors across the docs${p.length>0?`, though ${lt(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):ke("\u2717",`${lt(g,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(ke("\u2139",`${lt(l.baselinedCount,"issue")} ${l.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${l.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),l.ruleErrors.length>0&&i.push(ke("\u26A0",`${lt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(k=>`${k.ruleId} (${k.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(y(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),i}function Kc(e){let t=Fr(e),n=new Set(Yx(t?.styleGuide)),o=um(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),p=a===So,g=l?"\u2713":"\xB7",k=p?y("(always on)"):l?y("(active)"):"",v=i.local?y(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${v} ${i.description??""}`),r.push(` ${y(`${lt(i.rules.length,"rule")} \xB7 ${mm(i.rules)} \xB7 ${Yc(i.version)}`)} ${k}`),i.errors.length>0&&r.push(ke("\u26A0",`${lt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===So)&&(r.push(""),r.push(y(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(y(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(y(" Several: /style-guide use microsoft,google")),r.push(y(" Back to none: /style-guide use none")),r}function d0(e,t){if(!t)return[ke("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=zc(e),o=Ri.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...Ri.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ke("\u26A0",`No active rule called "${t}".`),...p.length>0?[y(` Did you mean: ${p.join(", ")}`)]:[y(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(y(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(ke("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=Xc({cwd:e}).findings.filter(k=>k.ruleId===s),g=p.filter(k=>!k.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${lt(g.length,"finding")}${p.length!==g.length?`, plus ${p.length-g.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(y(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(y(" catch defects of fact, not matters of taste."))):(l.push(y(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(y(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function p0(e,t){let n=(t??"").trim();if(!n)return{lines:[ke("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Kc(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(um(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[ke("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...Kc(e)],restart:!1};let i=Fr(e)??{projectId:""};pm({...i,styleGuide:{...i.styleGuide,packs:o}},e),Gx();let a=[ke("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(So)?"":` (+ ${So}, always on)`}\u2026`)];try{let l=Xc({cwd:e}),p=new Set(l.findings.map(g=>g.path)).size;if(l.findings.length===0)a.push(ke("\u2713",p===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let g=Vx(e),k=qx(l.findings,zx(e));Kx(e,k),a.push(ke("\u2713",`Recorded ${lt(l.findings.length,"existing issue")} across ${lt(p,"article")} as accepted.`),y(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),y(" teammate with a different copy gets a different answer from the same gate."),ke("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),g&&a.push(y(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(l){a.push(ke("\u26A0",`The packs are active, but recording what was already there failed: ${l instanceof Error?l.message:String(l)}`)),a.push(y(" Run /lint to see the current state before publishing."))}return a.push(y(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Si(e,t){let{sub:n,value:o}=i0(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Kc(t.cwd)),{kind:"continue"};case"explain":return r(d0(t.cwd,o)),{kind:"continue"};case"use":{let s=p0(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await a0(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=l0(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(u0(t.cwd)),{kind:"continue"}}}ee();import{lintDocs as Qc,loadStyleGuide as km,buildReviewPrompt as bm,readProjectConfig as $m,DEFAULT_DOCS_DIR as vm,listArticleFiles as xm,planPartitions as w0,runPartitioned as k0,resolveModelForOperation as b0,stampArticles as $0}from"document360-engine";ee();import{readProjectConfig as h0,loadProfileMap as f0,resolveActiveProfile as m0,desiredCategoryOrder as g0,desiredArticleOrder as y0}from"document360-engine";function gm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var ym=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Wr(e,t){try{if(!h0(e))return[];let n=m0(e,t),o=f0(e,n.name);if(!o)return[];let r=new Map;for(let i of y0(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of g0(o)){s.push(gm(ym(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${gm(ym(a.path))}`)}return s}catch{return[]}}async function wm(e,t){let n=Wr(t.cwd,t.profileName);if(n.length===0)return console.log(y("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(K("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Br(e,t){return kr(e,xm(e,t))}function v0(e,t,n){return t.includes("--blocked")?Br(e,n):xm(e,n)}function x0(e,t){let n=$m(e);if(!n)return null;let o=(n.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(P=>!P.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Qc({cwd:e}),l=i?a.filter(P=>P.path===`${o}/${i}`||P.path.startsWith(`${o}/${i}/`)):a,p=s?Br(e,i):void 0,g=p?l.filter(P=>p.includes(P.path)):l,k=i||s?"":Wr(e).join(`
|
|
403
|
+
`);return{prompt:bm({docsRoot:o,scope:i,styleGuide:km(e),deterministicFindings:g,fix:r,structure:k||void 0,...p?{paths:p}:{}}),display:`/review${i?` ${i}`:""}${s?" --blocked":""}${r?" --fix":""}`}}var C0=e=>"ruleId"in e,Ur=3,R0=3;function Jc(e,t){let n=x0(e,t);if(!n)return null;let o=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=v0(e,t,o),s=w0(r,{maxPerPartition:R0});if(s.length<=1)return{kind:"single",...n};let a=($m(e)?.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),p=km(e),g=Qc({cwd:e});return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!t.includes("--blocked"),display:n.display,promptFor:k=>{let v=new Set(k.paths);return bm({docsRoot:a,styleGuide:p,deterministicFindings:g.filter(P=>v.has(P.path)),fix:l,paths:k.paths})}}}async function Cm(e,t){if(e.includes("--blocked")&&Br(t.cwd,e.find(o=>!o.startsWith("--"))).length===0)return console.log(G("\u2713 Nothing is blocked \u2014 every article has been through an editorial read.")),console.log(y(" /review --all --fix re-reviews everything; /push --all saves what has changed to Document360.")),{kind:"continue",ownNext:!0};if(ln("review",e)){let o=$o(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=Jc(t.cwd,e);return n?n.kind==="single"?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:await S0(t,n,e.includes("--fix"),e.find(o=>!o.startsWith("--"))):(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function S0(e,t,n,o){let{model:r}=b0(e.cwd,"standard");console.log(y(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Ur} editors at once) on ${r}${n?", applying fixes":", report only"}\u2026`));try{for await(let a of k0({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Ur,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(a.type==="partition_status")a.status==="running"?console.log(y(` \u25B8 ${a.label} \u2014 reviewing\u2026`)):a.status==="done"?console.log(G(` \u2713 ${a.label}`)):console.log(N(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=a.results.filter(p=>!p.ok);console.log(""),console.log(`${a.results.length-l.length}/${t.partitions.length} batches reviewed.`),l.length&&console.log(H(`\u26A0 ${l.length} not reviewed: ${l.map(p=>p.label).join(", ")}`)),a.blocked&&console.log(H(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(H("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let p of Zc(t))console.log(y(p));if(n&&!a.allEmpty&&!a.blocked){let p=new Set(l.map(k=>k.label)),g=t.partitions.filter(k=>!p.has(k.label)).flatMap(k=>k.paths);try{$0(e.cwd,g,Ye("review"))}catch{}}}}catch(a){return console.log(N(`Review failed: ${a.message}`)),{kind:"continue"}}if(!n)return{kind:"continue"};let i=Qc({cwd:e.cwd,scope:o}).filter(a=>!a.baselined).filter(a=>C0(a)&&a.severity==="error");if(console.log(""),i.length>0){let a=Ne("/lint","--fix",o);console.log(y(`Editor applied its fixes, but ${i.length} style error${i.length===1?"":"s"} remain \u2014 ${a} clears them (finding them costs nothing, one pass corrects them).`))}else console.log(y(Ct(e.cwd,{text:"\u2713 Reviewed and fixed. /push --all saves the articles to Document360 as drafts.",cmd:"/push --all"},"",o).text));return{kind:"continue",ownNext:!0}}function Zc(e){return e.wholeKb?["Each editor saw one slice of the docs, so reading order and terminology drift ACROSS categories were not judged.","/structure shows the reading order if you want to check it yourself."]:[]}ee();import{readProjectConfig as P0}from"document360-engine";function eu(e,t){if(!P0(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool: one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
404
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Rm(e,t){if(ln("reorder",e)){let o=$o(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=eu(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{readProjectConfig as T0,writeProjectConfig as Sm,isAppType as E0,playbookSkillName as A0,detectAppType as Pm}from"document360-engine";var Tm=["web","cli","service","library"],D0=new Set(["web","cli"]);function tu(e){return D0.has(e)?`${A0(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Pi(e,t){let n=t.cwd,o=T0(n);if(!o)return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Pm(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${K("Genre:")} ${s} (${i}) \u2014 ${tu(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(y(`Set it: /genre <${Tm.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(y("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Sm(i,n);let a=Pm(n);return console.log(G(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${tu(a)})`:"unclassified (no playbook)"}.`)),console.log(y(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return E0(r)?(Sm({...o,appType:r},n),console.log(G(`\u2713 Genre set to ${r} \u2014 ${tu(r)}.`)),console.log(y(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(N(`Unknown genre "${r}". Choose one of: ${Tm.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}ee();import{listRoadmap as Ti,roadmapProgress as Em,stampRoadmapDone as N0}from"document360-engine";function nu(e){let t=Ti(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=Em(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t){let s=r.status==="done"&&r.replacedBy?` \xB7 replaced by \u201C${r.replacedBy}\u201D`:"";o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}${s}`)}return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)"),t.some(r=>r.stepId)&&o.push('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)'),o}function Ei(e,t){let n=Ti(e).filter(p=>p.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=p=>p.trim().toLowerCase(),s=n.find(p=>r(p.title)===r(o)),i=o?s?[s]:n.filter(p=>r(p.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
|
|
405
405
|
${i.map(p=>` \u25CB ${p.title}`).join(`
|
|
406
406
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
407
407
|
${n.map(p=>` \u25CB ${p.title}`).join(`
|
|
408
408
|
`)}`};let a=i[0].title;N0(e,a,{doneAt:new Date().toISOString()});let l=Em(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function ou(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Ti(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Am(e,t){let n=ou(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
409
409
|
`):null}function Dm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Ti(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
|
|
410
410
|
${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
|
|
411
|
-
`):null}async function Nm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ei(n,e.slice(1).join(" ").trim());return console.log(r.ok?G(r.line):H(r.line)),{kind:"continue"}}let o=nu(n);console.log(K(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var jm={help:Ta,"?":Ta,clear:Md,exit:Ea,quit:Ea,init:La,mcp:Is,push:oi,publish:bh,audit:br,discover:$h,scope:xh,pull:Lh,resolve:Nh,convert:Oh,write:Zh,draft:rf,document:sf,resume:cf,rename:uf,profile:pf,model:mf,doctor:Tr,workspace:$f,project:vf,"allow-prod":xf,login:Cf,logout:Rf,screenshot:async(e,t)=>{let n=hr(e);return n.mode==="capture"?Rc(n.rest,t):n.mode==="verify"?Sf(n.rest,t):n.mode==="checklist"?xo():Js(e,t)},capture:Rc,"capture-setup":xo,devhints:Kd,inbox:Bf,"catch-up":Yf,comments:em,update:nm,reset:am,lint:Gl,check:Hh,"style-guide":Si,review:Cm,reorder:Rm,structure:wm,genre:Pi,roadmap:Nm,share:Gf};function Im(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as j0}from"node:child_process";import{recordAnalyzedCommit as I0,resolveActiveProfile as L0}from"document360-engine";function O0(e){try{let t=j0("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Hr(e,t){try{let n=O0(e);if(!n)return null;let o=L0(e,t);return I0(e,o.name,n)?n:null}catch{return null}}import{CONTENT_CAP_VERSION as _0,stampArticles as M0,articlesChangedSince as F0,docsRootOf as W0}from"document360-engine";function Ai(e,t,n=""){let o=[];try{o=F0(e,t)}catch{return{changed:[],cta:null}}if(o.length===0)return{changed:[],cta:null};try{M0(e,o,{writtenCap:_0,reviewedCap:0,checkedCap:0})}catch{}let r=W0(e),s=p=>{let g=p.replace(/\\/g,"/");return g.startsWith(`${r}/`)?g.slice(r.length+1):g},i=vt(o.map(s)),a=o.length,l=i?"/push":"/push --all";try{return{changed:o,cta:Ct(e,{text:`${n}${a} article${a===1?"":"s"} updated \u2014 ${l} saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}.`,cmd:l},n,i)}}catch{return{changed:o,cta:null}}}nn();var U0="Or just tell me what to write or update.",B0='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function be(e){return e===1?"":"s"}function Po(e,t=0){let n=t>=2?` \xB7 1\u2013${t} to pick another`:"";return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd}${n} \xB7 or just ask me anything\u2026`:e.kind==="answer"&&e.options>=2?`1\u2013${e.options} to answer \xB7 or just ask me anything\u2026`:null}function Lm(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function qr(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:e.kind==="answer"?e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.":`Just tell me: \u201C${e.text}\u201D.`}var Di={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function
|
|
412
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${be(n)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${n} reviewer comment${be(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${be(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${be(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed,o=Ne("/review","--blocked --fix",e.unreviewedScope);t.push({key:"review",bullet:`${n} article${be(n)} ready to send to Document360 ${n===1?"has":"have"} never been editorially reviewed`,lead:{kind:"cmd",cmd:o,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and /push stays blocked until it has"},picker:null,follow:`Then ${o} reviews the ${n} unreviewed article${be(n)} \u2014 /push is blocked until it has.`})}if(e.styleErrors>0){let n=e.styleErrors,o=Ne("/lint","--fix",e.styleErrorScope);t.push({key:"styleguide",bullet:`${n} article${be(n)} ready to send to Document360 break${n===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:o,reason:"finding them costs nothing and one pass corrects them in place \u2014 /push stays blocked until it has"},picker:null,follow:`Then ${o} clears the style errors on ${n} article${be(n)} \u2014 /push is blocked until it has.`,dependsOn:["review"]})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${n} local edit${be(n)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${n} local edit${be(n)} to Document360.`,dependsOn:["discovery","audit"],blockedBy:["review","styleguide"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${be(n)} changed both here and on Document360 (conflicts) \u2014 /push 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${be(n)} (keep yours / take the portal's / skip).`})}if(e.draftAhead>0){let n=e.draftAhead;t.push({key:"golive",bullet:`${n} article${be(n)} ${n===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${n} draft${be(n)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${n} draft${be(n)} live \u2014 until it does, readers see the previous version.`,blockedBy:["review","styleguide"]})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next
|
|
413
|
-
|
|
414
|
-
\u2022 `)
|
|
411
|
+
`):null}async function Nm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ei(n,e.slice(1).join(" ").trim());return console.log(r.ok?G(r.line):H(r.line)),{kind:"continue"}}let o=nu(n);console.log(K(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var jm={help:Ta,"?":Ta,clear:Md,exit:Ea,quit:Ea,init:La,mcp:Is,push:oi,publish:bh,audit:br,discover:$h,scope:xh,pull:Lh,resolve:Nh,convert:Oh,write:Zh,draft:rf,document:sf,resume:cf,rename:uf,profile:pf,model:mf,doctor:Tr,workspace:$f,project:vf,"allow-prod":xf,login:Cf,logout:Rf,screenshot:async(e,t)=>{let n=hr(e);return n.mode==="capture"?Rc(n.rest,t):n.mode==="verify"?Sf(n.rest,t):n.mode==="checklist"?xo():Js(e,t)},capture:Rc,"capture-setup":xo,devhints:Kd,inbox:Bf,"catch-up":Yf,comments:em,update:nm,reset:am,lint:Gl,check:Hh,"style-guide":Si,review:Cm,reorder:Rm,structure:wm,genre:Pi,roadmap:Nm,share:Gf};function Im(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as j0}from"node:child_process";import{recordAnalyzedCommit as I0,resolveActiveProfile as L0}from"document360-engine";function O0(e){try{let t=j0("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Hr(e,t){try{let n=O0(e);if(!n)return null;let o=L0(e,t);return I0(e,o.name,n)?n:null}catch{return null}}import{CONTENT_CAP_VERSION as _0,stampArticles as M0,articlesChangedSince as F0,docsRootOf as W0}from"document360-engine";function Ai(e,t,n=""){let o=[];try{o=F0(e,t)}catch{return{changed:[],cta:null}}if(o.length===0)return{changed:[],cta:null};try{M0(e,o,{writtenCap:_0,reviewedCap:0,checkedCap:0})}catch{}let r=W0(e),s=p=>{let g=p.replace(/\\/g,"/");return g.startsWith(`${r}/`)?g.slice(r.length+1):g},i=vt(o.map(s)),a=o.length,l=i?"/push":"/push --all";try{return{changed:o,cta:Ct(e,{text:`${n}${a} article${a===1?"":"s"} updated \u2014 ${l} saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}.`,cmd:l},n,i)}}catch{return{changed:o,cta:null}}}nn();var U0="Or just tell me what to write or update.",B0='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function be(e){return e===1?"":"s"}function Po(e,t=0){let n=t>=2?` \xB7 1\u2013${t} to pick another`:"";return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd}${n} \xB7 or just ask me anything\u2026`:e.kind==="answer"&&e.options>=2?`1\u2013${e.options} to answer \xB7 or just ask me anything\u2026`:null}function Lm(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function H0(e,t=150){let n=(e??"").replace(/\s+/g," ").trim();if(!n)return null;let o=/[.!?]\s+(?=["“'(A-Z])/.exec(n),r=o?n.slice(0,o.index+1):n;if(r.length<=t)return r;let s=r.slice(0,t),i=s.lastIndexOf(" ");return`${(i>t*.6?s.slice(0,i):s).replace(/[,;:]$/,"")}\u2026`}function qr(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:e.kind==="answer"?e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.":`Just tell me: \u201C${e.text}\u201D.`}var Di={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function q0(e){let t=[];if(e.sunsetEnv){let n=e.sunsetEnv,o=n.replacementProfile?`/profile ${n.replacementProfile}`:`/profile add ${n.replacement}`;t.push({key:"environment",bullet:`this repo publishes to the ${n.name} environment, which is being retired (${n.replacement} is the current one)`,lead:{kind:"cmd",cmd:o,reason:n.replacementProfile?`it switches to your ${n.replacement} profile (then /login if it asks)`:`it creates a ${n.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Di,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;e.discovery.status==="pending"?t.push({key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/push steps)."}):n>0?t.push({key:"discovery",bullet:`product discovery is waiting on ${n} answer${be(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}):e.discovery.answersPending===0&&t.push({key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${be(e.directives)} waiting`);let r=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,s=r>0?` (${r} settle${r===1?"s":""} the product brief)`:"";e.pendingText&&o.push(`your builder left ${e.pendingText}${s}`),t.push({key:"catchup",bullet:o.join(`
|
|
412
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${be(n)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${n} reviewer comment${be(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${be(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${be(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed,o=Ne("/review","--blocked --fix",e.unreviewedScope);t.push({key:"review",bullet:`${n} article${be(n)} ready to send to Document360 ${n===1?"has":"have"} never been editorially reviewed`,lead:{kind:"cmd",cmd:o,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and /push stays blocked until it has"},picker:null,follow:`Then ${o} reviews the ${n} unreviewed article${be(n)} \u2014 /push is blocked until it has.`})}if(e.styleErrors>0){let n=e.styleErrors,o=Ne("/lint","--fix",e.styleErrorScope);t.push({key:"styleguide",bullet:`${n} article${be(n)} ready to send to Document360 break${n===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:o,reason:"finding them costs nothing and one pass corrects them in place \u2014 /push stays blocked until it has"},picker:null,follow:`Then ${o} clears the style errors on ${n} article${be(n)} \u2014 /push is blocked until it has.`,dependsOn:["review"]})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${n} local edit${be(n)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${n} local edit${be(n)} to Document360.`,dependsOn:["discovery","audit"],blockedBy:["review","styleguide"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${be(n)} changed both here and on Document360 (conflicts) \u2014 /push 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${be(n)} (keep yours / take the portal's / skip).`})}if(e.draftAhead>0){let n=e.draftAhead;t.push({key:"golive",bullet:`${n} article${be(n)} ${n===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${n} draft${be(n)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${n} draft${be(n)} live \u2014 until it does, readers see the previous version.`,blockedBy:["review","styleguide"]})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next,r=o.run?null:H0(o.body),s=`docs campaign: ${n.done} of ${n.total} step${be(n.total)} done`;t.push({key:"roadmap",bullet:`${s} \u2014 next: ${o.title}${r?`
|
|
413
|
+
\u2022 ${r}`:""}`,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).`,dependsOn:["genre","discovery","audit"],rowBullet:`${s} \u2014 this is next${r?`
|
|
414
|
+
\u2022 ${r}`:""}`})}if(e.handoff){let n=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),o=e.handoff.unpushed;n>0&&e.handoff.pushConsent==="unconfirmed"?t.push({key:"share",bullet:e.shareExplained?"your docs work is saved on this machine only \u2014 your team can't see it yet":["your docs work is saved on this machine only \u2014 your team can't see it yet","d360-writer keeps everything it produces in .d360-writer/ \u2014 your articles, the map linking","them to Document360, and the channel your builder leaves hints and answers in. It saves that","to git for you automatically, but it won't send anything to your team until you say so."].join(`
|
|
415
|
+
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${be(o)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${be(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Om(e){return e.find(t=>t.lead||t.picker)??null}function G0(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function V0(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:""}function Y0(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function ru(e,t,n){let o=Om(t),r=o?.picker?[]:t.filter(k=>k.lead),s=r.length>=2?r:[],i=new Map(s.map((k,v)=>[k.key,v+1])),a=[];o?.lead?a.push(qr(o.lead)):o?.picker&&a.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let k of t.filter(v=>v!==o&&!v.lead).slice(0,2))k.follow&&a.push(k.follow);s.length>=2&&n&&a.push(`Press 1\u2013${s.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let l=a.join(" "),p=t.filter(k=>k.bullet).map(k=>{let v=i.get(k.key),[P="",...S]=(v&&k.lead?.kind==="prompt"&&k.rowBullet?k.rowBullet:k.bullet).split(`
|
|
416
|
+
\u2022 `);if(v&&k.lead){let T=P.replace(/^→\s+/,"");return[` ${v}. ${G0(k.lead)} \u2014 ${T}${Y0(k,i,v)}`,...S.map(I=>` ${I}`)].join(`
|
|
415
417
|
`)}let C=k.lead?.kind==="cmd"?k.lead.cmd:null;return` \u2022 ${k.bullet}${C&&!l.includes(C)?` \u2014 ${C}`:""}`}),g=[[e,...p].join(`
|
|
416
418
|
`)];return a.length&&g.push(a.join(" ")),g.push(U0),{note:g.join(`
|
|
417
419
|
|
|
418
|
-
`),menu:s.map(k=>
|
|
420
|
+
`),menu:s.map(k=>V0(k.lead))}}function Gr(e,t){let n=t?.pickable===!0,o=p=>t?.header?`${t.header}
|
|
419
421
|
|
|
420
|
-
${p}`:p;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=
|
|
421
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Yr(r[1])}return null}var
|
|
422
|
-
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${T} lines`}}return{verb:"Rewrite",title:C,category:l,note:
|
|
423
|
-
`)),category:l,note:P}}function
|
|
424
|
-
`);if(e==="Read"){let o=n.length,r=Kr(n.map(
|
|
422
|
+
${p}`:p;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=q0(e);if(!e.hasDocs){let p=Om(r);if(p&&(p.lead?.kind==="cmd"||p.picker)){let g=ru(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n);return{kind:"recommend",rec:{note:g.note,tone:p.tone??"info",lead:p.lead,picker:p.picker,menu:g.menu}}}return{kind:"recommend",rec:{note:o(B0),tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let p=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${be(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${p}`),tone:"info",lead:null,picker:null,menu:[]}}}let s=r.filter(p=>p.lead||p.picker),i=s[0]??null;if(!i){let p=ru(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:p.note,tone:"info",lead:null,picker:null,menu:p.menu}}}if((i.key==="audit"||s[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};let l=ru(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:l.note,tone:i.tone??"info",lead:i.lead,picker:i.picker,menu:l.menu}}}import{existsSync as Ni,readdirSync as iu}from"node:fs";import{spawnSync as K0}from"node:child_process";import{join as ji}from"node:path";import{readProjectConfig as Mm,resolveActiveProfile as Fm,loadTokens as z0,isExpired as X0,loadProfileMap as Wm,localAheadPaths as Q0,loadKnownConflicts as J0,draftPendingPaths as Z0,loadOpenCommentCount as eC,readDocsPlan as tC,devHintsGuidePath as nC,DEFAULT_DOCS_DIR as su,roadmapProgress as oC,listRoadmap as rC,readProductBriefState as sC,readDiscoveryQueue as iC,reconcileCommitRequest as aC,reconcileTestidRequest as lC,snapshotHandoff as cC,shareExplainedPath as uC}from"document360-engine";nn();function _m(e){try{return iu(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function au(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>_m(ji(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&_m(ji(e,o)))}function lu(e,t){try{let n=Mm(e);if(!n)return!1;let o=Fm(e,t),r=Wm(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ji(e,(n.docsDir??su).replace(/\/+$/,""));return!!(Ni(s)&&iu(s).length>0||Ni(nC(e)))}catch{return!1}}function Vr(e,t,n){try{let o=Mm(e);if(!o)return null;let r=Fm(e,t),s=z0(r.name),i=!!s&&(!X0(s)||!!s.refreshToken),a=lu(e,t)||!au(e,o.authoritativeSourceFiles),l=Wm(e,r.name),p=l?Object.keys(l.articles).length:0,g=ji(e,(o.docsDir??su).replace(/\/+$/,"")),k=!1;try{k=Ni(g)&&iu(g).length>0}catch{}let v=0;if(l?.lastAnalyzedCommit)try{let De=K0("git",["rev-list","--count",`${l.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});De.status===0&&(v=parseInt((De.stdout||"").trim(),10)||0)}catch{}let P=0;try{let De=tC(e);if(De.length>0){let Pt=(o.docsDir??su).replace(/\/+$/,"");P=zl(e,Pt,De.map(Mo=>Mo.path)).length}}catch{}let S=Ln(e),C=Lr({...S,directives:0}),T=Q0(e,t),D=new Set(J0(e,r.name)),I=T.filter(De=>D.has(De)).length,O=T.length-I,Y=T.filter(De=>!D.has(De)),fe=kr(e,Y),ae=fe.length,le=vt(fe),he=0,ce;try{let De=wh(e,Y);he=De.length,ce=vt(De)}catch{}let X=new Set(T),ne=Z0(e,t).filter(De=>!X.has(De)).length,ue=eC(e,r.name),Te=mt(e),yt=oC(e),St=cC(e,o),Wt=aC(e,new Date().toISOString(),{supersededByHandoff:St!==null});lC(e,new Date().toISOString());let nt=Zt(e,t),Wn=nt?{name:nt.name,replacement:nt.replacement,replacementProfile:nt.replacementProfile}:null,Ke=sC(e),hn=iC(e),Ut=Ke?{status:Ke.status,openQuestions:hn.openQuestions,answersPending:hn.answersPending}:null;return!Ut&&k&&rC(e).some(Pt=>Pt.status==="open"&&(Pt.run??"").trim()==="/discover")&&(Ut={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:k,tracked:p,pendingText:C,directives:S.directives,behind:v,pendingWrites:P,localAhead:O,unreviewed:ae,unreviewedScope:le,styleErrors:he,styleErrorScope:ce,draftAhead:ne,conflicts:I,openComments:ue,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Te.status,devhintsCompletedVersion:Te.completedVersion,devhintsToVersion:Re,builderStarted:Ot(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,roadmap:yt,discovery:Ut,uncommittedDocs:Wt.dirty.length,handoff:St,shareExplained:Ni(uC(e)),sunsetEnv:Wn}}catch{return null}}ee();import{existsSync as dC,readFileSync as pC}from"node:fs";import{isAbsolute as hC,join as fC}from"node:path";import{DEFAULT_DOCS_DIR as mC,findPathByArticleId as gC,isArticleDocPath as yC,loadProfileMap as wC,readProjectConfig as kC,resolveActiveProfile as bC}from"document360-engine";var $C=70;function vC(e,t){return{docsRoot:()=>(kC(e)?.docsDir??mC).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=hC(n)?n:fC(e,n);return dC(o)?pC(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=wC(e,bC(e,t).name);return o?gC(o,n):null}catch{return null}}}}var Yr=(e,t=$C)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Kr(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
423
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Yr(r[1])}return null}var xC=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),CC=new Set(["ai","api","cli","css","csv","dfm","faq","html","http","https","id","json","mcp","pdf","sdk","sso","ui","url","ux","yaml","ado","qa"]);function Um(e,t,n){let o=e.toLowerCase();return CC.has(o)?e.toUpperCase():!t&&xC.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Bm=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function RC(e){let t=Bm(e);return t.length===0?e:t.map((n,o)=>Um(n,o===0,!0)).join(" ")}function Hm(e){let t=typeof e=="string"&&e?e.replace(/\\/g,"/"):null;if(!t)return null;let n=t.split("/").filter(Boolean);return n.length<2?null:RC(n[n.length-2])}function qm(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Bm(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Um(o,r===0,!1)).join(" ")}var ct=e=>typeof e=="string"&&e?e:null,SC=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function PC(e,t){let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=e.replace(/\\/g,"/"),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):o}function TC(e,t){let n=at(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var EC=new Set(["Edit","MultiEdit","Write"]);function AC(e,t,n,o){if(!EC.has(e))return null;let r=ct(t.file_path);if(!r)return null;let s=PC(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!yC(a))return null;let l=Hm(a),p=o.read(s),g=S=>Kr(S)??Kr(p)??qm(a);if(e==="Write"){let S=ct(t.content)??"",C=g(S);if(p===null){let T=S.replace(/\n$/,"").split(`
|
|
424
|
+
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${T} lines`}}return{verb:"Rewrite",title:C,category:l,note:TC(p,S)}}let k=Array.isArray(t.edits)?t.edits.map(S=>({from:ct(S.old_string)??"",to:ct(S.new_string)??""})):[{from:ct(t.old_string)??"",to:ct(t.new_string)??""}],v=k.reduce((S,C)=>{let T=at(C.from,C.to,200);return T?{added:S.added+T.added,removed:S.removed+T.removed}:S},{added:0,removed:0}),P=v.added===0&&v.removed===0?"no change":`+${v.added} \u2212${v.removed}`;return{verb:"Update",title:g(k.map(S=>S.to).join(`
|
|
425
|
+
`)),category:l,note:P}}function DC(e,t,n){let o=()=>{let r=ct(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Kr(n.read(s)):null)??(s?qm(s):SC(r)??"article")};switch(e){case"d360_create_article":{let r=ct(t.title);return r?{verb:"Create",title:Yr(r),category:Hm(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:ct(t.title)?Yr(ct(t.title)):o(),category:null,note:"Document360 draft"};case"d360_fork_article":return{verb:"Fork",title:o(),category:null,note:"new Document360 draft"};case"d360_publish_article":{let r=t.version_number;return{verb:"Publish",title:o(),category:null,note:typeof r=="number"?`v${r}`:null,loud:"LIVE"}}case"d360_unpublish_article":return{verb:"Unpublish",title:o(),category:null,note:"back to draft, removed from readers"};case"d360_create_category":{let r=ct(t.name);return r?{verb:"Create",title:Yr(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=ct(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Yr(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Ii(e,t,n,o,r=vC(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?DC(e.slice(s.length),t,r):AC(e,t,n,r)}catch{return null}}var NC={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"},Vm=160,cu=200,Ym=40;function un(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Gm(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}: ${un(typeof r=="string"?r:JSON.stringify(r),Ym)}`);return t.length>4&&n.push("\u2026"),un(n.join(", "),Vm)}var jC=new Set(["file_path","notebook_path"]);function IC(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 Km=e=>typeof e=="string"&&e?e:null;function LC(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Li(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let g=LC(a,t);if(g)return g}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:Gm(t)}}let o=NC[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&jC.has(o)?IC(r,n):r;return{title:e,sep:"",arg:un(s,Vm)}}return{title:e,sep:"",arg:Gm(t)}}function OC(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 _C(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(OC).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>un(r,cu))]}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}: ${un(String(r),Ym)}`);return n.length>0?[un(n.join(" \xB7 "),cu)]:null}return null}function MC(e){let t=Km(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function FC(e,t,n){switch(e){case"d360_create_article":{let o=MC(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=Km(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 ${un(o[0],120)}`:""}`]}default:return null}}var zm=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function WC(e){return e.replace(/^\s*\d+\t/,"")}function UC(e,t){if(zm.has(e))return[];let n=t.split(`
|
|
426
|
+
`);if(e==="Read"){let o=n.length,r=Kr(n.map(WC).join(`
|
|
425
427
|
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function Oi(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
426
|
-
`).trimEnd();if(n&&zm.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=
|
|
427
|
-
`);return{lines:s.slice(0,t).map(i=>un(i,cu)),hidden:Math.max(0,s.length-t)}}function _i(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Mi(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 Xm(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 Fi(e){return Xm(e,"url")}function Wi(e){return Xm(e,"preview_url")}var tg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,du=null;function Jm(){return du===null&&(du=
|
|
428
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(K(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function
|
|
428
|
+
`).trimEnd();if(n&&zm.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=UC(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=FC(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=_C(r)??r.split(`
|
|
429
|
+
`);return{lines:s.slice(0,t).map(i=>un(i,cu)),hidden:Math.max(0,s.length-t)}}function _i(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Mi(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 Xm(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 Fi(e){return Xm(e,"url")}function Wi(e){return Xm(e,"preview_url")}var tg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,du=null;function Jm(){return du===null&&(du=QC().verboseTranscript===!0),du}function dR(e,t,n,o){if(tg.test(e))try{let r=eg(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Mi(t,n),a=Fi(n);e.endsWith("publish_article")&&a&&console.log(K(` \u2B95 Live: ${a}`));let l=Wi(n);l?console.log(K(` \u2B95 Preview: ${l}`)):i&&s&&console.log(K(` \u2B95 Preview: ${_i(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function ng(e=process.cwd(),t="auto",n,o){let r=HC(t);r.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${K("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${K('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),pR(e,n),r.kind==="subscription"&&(r.stored?console.log(y(" Using your Claude subscription (no API key set).")):console.log(y(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=uu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=BC({input:process.stdin,output:process.stdout}),p=[],g=null,k=!1;l.on("line",S=>{if(g){let C=g;g=null,C(S)}else p.push(S)}),l.on("close",()=>{if(k=!0,g){let S=g;g=null,S(null)}});function v(){return p.length>0?Promise.resolve(p.shift()):k?Promise.resolve(null):(process.stdout.write(K("> ")),new Promise(S=>{g=S}))}let P={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=uu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:S=>{a.pendingName=S},setModel:async S=>i.setModel(S),withPausedInput:async S=>{l.pause();try{return await S()}finally{l.resume()}}};try{for(;;){let S=await v();if(S===null)break;let C=S.trim();if(C){if(C.startsWith("/")){let T=Im(C);if(!T)continue;let D=jm[T.name];if(!D){console.log(N(`Unknown command: /${T.name}`)),console.log(y("Type /help for the list."));continue}let I=await D(T.args,P);if(I.kind==="exit")break;if(I.kind==="clear"){P.restartAgent();continue}if(I.kind==="allow-prod"){s=!0,P.restartAgent(),console.log(G("\u2713 Production writes authorized for this session.")),console.log("");continue}if(I.kind==="resume"){i.close(),i=uu({cwd:e,resume:I.uuid,profileName:n,allowProdWrites:s});let O=qC(I.uuid);a={uuid:I.uuid,firstPrompt:O?.firstPrompt??null,titleFired:!0},Zm(I.uuid),console.log(G(`\u2713 Resumed "${I.name}"`)),console.log("");continue}if(I.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=I.display??I.prompt);let O=I.display??"",Y=O.trim().split(/\s+/),fe=Mh(O),ae=fe?aR(e,Fh(O)):[],le=Y[0]==="/screenshot"&&(Y[1]==="verify"||Y[1]==="review"),he=le?Y[2]&&!Y[2].startsWith("--")?[Y[2]]:Er(Ie(e)):[],X=Y[0]==="/catch-up"&&!fe?iR(e):null;if(await pu(i,I.prompt,r,a,e,n),fe)try{sR(e,ae,Ye(fe))}catch{}if(X){let ne=Ai(e,X);ne.cta&&console.log(y(ne.cta.text))}if(Y[0]==="/audit"&&!Y.includes("--auto")&&Hr(e,n),le&&he.length>0)try{for(let ne of Dr(e,he))console.log(ne)}catch{}if(Y[0]==="/push"){let ne=await wo(e,n);ne&&console.log(y(ne))}if((Y[0]==="/catch-up"||Y[0]==="/document")&&(Y.includes("--push")||Y.includes("--publish")))try{let ne=await uR({cwd:e,profileName:n}),{clean:ue,conflicts:Te}=An(ne.entries);ue.length===0?console.log(y("Nothing new to push \u2014 everything is already up to date on Document360.")):await xt(P,ue.map(yt=>yt.path),Te.length,{skipReview:Y.includes(it)})}catch(ne){console.log(H(`Couldn't check what to push (${ne.message}) \u2014 your drafts are saved; run /push when ready.`))}}else I.kind==="continue"&&I.ownNext||hR(e,n);continue}if(tR(C)){let T=nR(C);if(T){try{oR(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await pu(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await pu(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function pR(e,t){console.log(""),console.log(rr("document360-writer")),console.log(y(` cwd: ${e}`));let n=zC(e);if(console.log(y(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(fR(e,t)),!XC(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(Es(e),!Ot(e))for(let r of As(e))console.log(H(` ${r}`))}catch{}try{let r=JC(e);r.persisted&&r.appType?console.log(y(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=rR(e);for(let s of Rs(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of Ss(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=Vr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Gr(r,{pickable:!1}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:y;for(let a of Ga(s.rec.note).split(`
|
|
430
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(K(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function hR(e,t){try{let n=Vr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Gr(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(y(` Next: ${qr(o.rec.lead)}`))}catch{}}function fR(e,t){try{let n=eg(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=eR(n.name);if(!r)return y(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Qm(r.idToken)??{},...Qm(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return ZC(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):y(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return y(` Document360: ${n.message.split(".")[0]}`)}}function mR(){console.error(""),console.error(`Sign in with your Claude subscription: run ${K("claude")} once, then retry.`),console.error(` (No Claude Code? ${K("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${K("https://console.anthropic.com/settings/keys")}`)}function gR(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;YC({uuid:t,name:r??VC(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function yR(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||KC(o,t).then(r=>{r&&GC(n,r)}).catch(()=>{})}async function pu(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&tg.test(l.name)&&(a=!0),wR(l,o,r,n,i,s);if(a)try{let l=cR(await lR({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?H(l):l)}catch{}}function wR(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||gR(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Jm()?null:Ii(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
429
431
|
|
|
430
432
|
`);let l=[i.category,i.note].filter(g=>!!g).map(g=>$e(` \xB7 ${g}`)),p=i.loud?$e(" \xB7 ")+We(H(i.loud)):"";console.log(`${G("\u25CF")} ${K(We(qa(i.verb)))}${We(i.title)}${l.join("")}${p}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Li(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
431
433
|
|
|
432
|
-
`),console.log(`${$e("\u25CF")} ${a.title}${a.arg!==null?$e(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=at(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log($e(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(y(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Oi(e.output,4,e.isError||Jm()?void 0:i.name,i.input),p=e.isError?N:$e;l.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),l.hidden>0&&console.log(y(` \u2026 +${l.hidden} lines`)),e.isError||
|
|
433
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${ur(i)}\u2192${ur(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Zm(t.uuid),t.titleFired||
|
|
434
|
-
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}function sg(e){let t=e.trimEnd();if(!t)return null;let n
|
|
434
|
+
`),console.log(`${$e("\u25CF")} ${a.title}${a.arg!==null?$e(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=at(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log($e(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(y(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Oi(e.output,4,e.isError||Jm()?void 0:i.name,i.input),p=e.isError?N:$e;l.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),l.hidden>0&&console.log(y(` \u2026 +${l.hidden} lines`)),e.isError||dR(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
435
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${ur(i)}\u2192${ur(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Zm(t.uuid),t.titleFired||yR(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(H(`\u23F3 ${e.message}`)):console.error(N(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&mR();break}}import{render as QS}from"ink";import{resolveAuth as JS}from"document360-engine";import{useCallback as J,useEffect as tt,useMemo as vu,useRef as se,useState as te}from"react";import{Box as xe,Text as U,useApp as HR,useInput as qR,useStdout as GR}from"ink";import{existsSync as Ao,readFileSync as zi,readdirSync as VR,writeFileSync as YR}from"node:fs";import{basename as Qr,dirname as KR,isAbsolute as zR,join as xu}from"node:path";import{createSession as Hg,classifyClaudeAuth as Au,CLAUDE_CODE_SETUP_HINT as XR,loginPkce as QR,toStoredTokens as JR,saveTokens as ZR,getAccessToken as eS,resolveActiveProfile as ut,resolveProjectId as tS,getArticle as nS,decodeJwtClaims as Oo,isExpired as pn,loadTokens as Fn,clearTokens as oS,clearProfileProject as rS,setTitle as sS,slugify as iS,touchSession as Cu,upsertSession as aS,generateTitle as qg,findByName as lS,listSessions as cS,renameSession as uS,suggestNextAction as dS,readProjectConfig as ge,writeProjectConfig as Gg,readUserConfig as Vg,writeUserConfig as pS,resolveAndPersistAppType as hS,detectAppType as Yg,resolveModelSetting as Du,loadProfileMap as Kg,applyPull as Xi,computeSyncStatus as Qi,lintDocs as Ji,compareRemoteSources as fS,planPull as zg,establishBaselines as mS,rebaselineServerMeta as gS,inventoryRepo as yS,knownEnvironments as wS,currentEnvironments as Xg,sunsetEnvironment as Qg,resolveEnvironment as kS,planPartitions as Ru,partitionEvenly as bS,screenshotPlaceholderIds as $S,trackedArticlePaths as vS,runPartitioned as Do,estimateBulkCost as Jg,resolveModelForOperation as No,readDocsPlan as Zg,checkForUpdate as xS,detectInstallKind as CS,isSelfUpdatable as RS,devHintsGuidePath as ey,toolFeedbackPath as ty,reconcileToolFeedback as SS,reconcileUpgradeActions as PS,stampArticles as jo,snapshotArticles as TS,listArticleFiles as ny,CONTENT_CAP_VERSION as ES,ENGINE_VERSION as uy,DEFAULT_DOCS_DIR as Nu,setProfileProject as AS,writeCrashLog as DS,applyStructureOrder as Su,orderSyncLine as Pu,applyRelatedArticles as oy,relatedSyncLine as ry,reconcileDocsGit as NS,shareExplainedPath as jS,ensureDir as IS}from"document360-engine";pr();nn();import{spawn as og}from"node:child_process";function kR(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function bR(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?og([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):og(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 hu(e){for(let[t,n]of kR())if(await bR(t,n,e))return!0;return!1}var rg=/\b(?:reply|respond|answer)\s+with\s+(?:the\s+|a\s+)?(?:number|option|\d+)\b|\bpick one\b|\bpress the number\b|\b(?:tell me|let me know)\s+which\b|\bsay the number\b/i;function $R(e){let t=e.replace(/\s+$/,"").split(`
|
|
436
|
+
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}function sg(e){let t=e.trimEnd();if(!t)return null;let n=$R(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||rg.test(t)?{options:0}:null}function fu(e,t){if(t.closed)return e;let n=e.split(`
|
|
435
437
|
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){rg.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(`
|
|
436
|
-
`)}var
|
|
437
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${S+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var
|
|
438
|
-
`)){let i=s.trim().replace(
|
|
438
|
+
`)}var vR={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},xR={L:"local",P:"portal",S:"skip"},CR={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},RR={Y:"write",N:"skip"};function ig(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function ag(e){return ig(e,vR,xR)}function lg(e){return ig(e,CR,RR)}function mu(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Ui(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function cg(e,t,n,o=Date.now()){let s=e.value>0&&o-e.at<900?e.value*10+t:0,i=s>=1&&s<=n?s:t>=1&&t<=n?t:0;return i===0?{index:null,memory:{value:0,at:o}}:{index:i-1,memory:{value:i,at:o}}}import{existsSync as SR,mkdirSync as PR,readFileSync as TR,writeFileSync as ER}from"node:fs";import{join as ug}from"node:path";import{writerDir as AR}from"document360-engine";function dg(e){return ug(AR(e),".sessions")}function pg(e,t){return ug(dg(e),`${t}.json`)}function hg(e,t,n){try{PR(dg(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");ER(pg(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function gu(e,t){try{let n=pg(e,t);if(!SR(n))return[];let o=JSON.parse(TR(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var DR=e=>`\x1B]0;${e}\x07`,NR=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function fg(e){process.stdout.isTTY&&process.stdout.write(e)}function To(e){fg(DR(e))}function Bi(e){fg(NR(e))}var Hi=["\xB7 "," \xB7"],qi="\u{1F7E3}";mi();var mg=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),jR={hints:0,requests:0,answers:0,directives:0};function yu(e,t){let n=e??jR;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives)}}var Gi=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,gg=e=>e.hints+e.requests+e.answers+e.directives,wu=(e,t)=>e-t>=6e5;function yg(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=wu(t,n),p=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,g={...i,fingerprint:o,counts:r,settled:p,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let v=yu(g.spokenBaseline,r);return{memory:g,speak:null,waiting:Gi(v)?null:v}}if(s)return{memory:g,speak:null,waiting:null};if(p<2)return{memory:g,speak:null,waiting:null};let k=yu(i.spokenBaseline,r);return Gi(k)?{memory:g,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:g,speak:null,waiting:null}:{memory:{...g,spokenBaseline:r,lastSpokeAt:t,settled:p},speak:k,waiting:null}}function wg(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=yu(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Gi(r)?e.lastSpokeAt:t};return Gi(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function zr(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function ku(e){let t=Math.round(e/6e4);if(t<45)return`${t} minutes`;let n=Math.round(e/36e5);if(n<20)return`${n} hour${n===1?"":"s"}`;let o=Math.round(n/24);return o<=1?"a day":`${o} days`}function kg(e){return`\u{1F4E5} ${zr(e)} just arrived from your builder \u2014 /catch-up folds ${gg(e)===1?"it":"them"} into the docs.`}function bg(e,t){return`\u{1F4E5} While you were away (${ku(t)}): ${zr(e)} from your builder \u2014 /catch-up folds ${gg(e)===1?"it":"them"} into the docs.`}function $g(e){return`\u{1F4E5} ${zr(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}js();import{publishGateVerdict as Tu,publishGateLines as Eu,SKIP_STYLE_FLAG as sy}from"document360-engine";ee();import{Box as Xr,Text as Se}from"ink";import{jsx as Pe,jsxs as Eo}from"react/jsx-runtime";function IR({row:e,nameW:t,width:n}){let o=s=>Pa(s,n),r=(s,i)=>Pe(Xr,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Pe(Se,{color:Z,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Pe(Se,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Pe(Se,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Pe(Se,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Pe(Se,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Pe(Xr,{flexDirection:"column",children:s.map((i,a)=>a===0?Eo(Se,{children:[Pe(Se,{color:Z,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Pe(Se,{children:i},a))})}case"cmd":{let s=Ps(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Eo(Xr,{flexDirection:"column",children:[Eo(Se,{children:[" ",Pe(Se,{color:Z,children:s.nameCell}),!s.nameOwnLine&&Pe(Se,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Pe(Se,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Pe(Se,{children:" "})}}function vg({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=Je[e]??Je[0],a=Sa(i.rows),l=Math.max(20,o-2),p=6+Je.reduce((T,D)=>T+D.label.length+4,0),g="\u2500".repeat(Math.min(p,l)),k=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`,v=_d({rows:n,inner:l,barWidth:p,footerWidth:k.length}),{visible:P,above:S,below:C}=Od(i.rows,{width:o,budget:v,scroll:t,nameW:a});return Eo(Xr,{flexDirection:"column",paddingX:1,children:[Eo(Se,{children:[Pe(Se,{color:Z,bold:!0,children:"Help "}),Je.map((T,D)=>D===e?Pe(Se,{color:"white",backgroundColor:Z,bold:!0,children:` ${T.label} `},T.key):Pe(Se,{dimColor:!0,children:` ${T.label} `},T.key))]}),Pe(Se,{color:Z,children:g}),Eo(Xr,{flexDirection:"column",marginTop:1,children:[S>0?Pe(Se,{dimColor:!0,children:`\u22EF ${S} more above`}):null,P.map((T,D)=>Pe(IR,{row:T,nameW:a,width:o},S+D)),C>0?Pe(Se,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Pe(Se,{dimColor:!0,children:`
|
|
439
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${S+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var LR=/^(?:\d+[.)]|[-*•])\s+/;function xg(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
440
|
+
`)){let i=s.trim().replace(LR,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let p=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(p)||r.push(p),r.length>=n)break}return r}ee();function _n(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Be(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Cg(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var OR=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rg(e,t,n){if(!OR.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let i=s.replace(/\\/g,"/");return r===i||r.endsWith(`/${i}`)})??null}function bu(e){return e.replace(/^[\w.-]+\//,"")}var Vi=16,Sg={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Mn(e){return typeof e=="string"?e:e.cmd}function Pg(e){return typeof e=="string"?void 0:e.desc}function $u(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Tg(e,t){let n=$u(t);return e.some(r=>Mn(r).trim()===t.trim()||!!n&&$u(Mn(r))===n)?e.filter(r=>Mn(r).trim()!==t.trim()&&!(n&&$u(Mn(r))===n)):[]}import{isDirectiveMention as LS,stripDirectiveMention as OS,appendDirective as _S,reconcileTestidRequest as MS,builderChannelWired as FS,pendingFingerprint as WS}from"document360-engine";var _R=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Eg(e){return e.replace(/\r\n?/g,`
|
|
439
441
|
`)}function Ag(e){return e.includes(`
|
|
440
442
|
`)||e.length>200}function Dg(e,t){let n=t.split(`
|
|
441
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ng(e,t){return e.replace(
|
|
442
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Ki(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ig(e,t,n){let o=Ki(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Lg(e,t,n){let o=e[Ki(e,t)];return n==="start"?o.start:o.end}var
|
|
443
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ng(e,t){return e.replace(_R,n=>t.get(n)??n)}function jg(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Yi(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
444
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Ki(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ig(e,t,n){let o=Ki(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function Lg(e,t,n){let o=e[Ki(e,t)];return n==="start"?o.start:o.end}var MR=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Og={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},FR=new Set(["hint","message","state"]),WR=["hint","message","roadmap","directive","feedback","state"];function UR(e){return e.startsWith("hints/")?"hint":e.startsWith("messages/")?"message":e==="roadmap.md"?"roadmap":e==="directives.md"?"directive":/^tool-feedback(-archived)?\.md$/.test(e)?"feedback":e.startsWith("cache/")||e.startsWith(".sessions/")||/^(plan|devhints-state|upgrade-state|category-map)\.json$/.test(e)?"state":null}function _g(e,t){let n=e==="Read"?"read":MR.has(e)?"updated":null;if(!n)return null;let o=t.file_path??t.notebook_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/").toLowerCase(),s=".d360-writer/",i=r.lastIndexOf(s);if(i<0)return null;let a=UR(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Mg(e){let t=new Map,n=new Set;for(let r of e)r.verb==="updated"&&n.add(r.path);for(let r of e){if(r.verb==="read"&&n.has(r.path))continue;let s=`${r.category}:${r.verb}`,i=t.get(s);i||t.set(s,i=new Set),i.add(r.path)}let o=[];for(let r of WR)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(FR.has(r)?`${i} ${Og[r]}${i===1?"":"s"} ${s}`:`${Og[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Fg(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
443
445
|
`),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
|
|
444
446
|
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Wg(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 Ug(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
445
|
-
`)){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 Lo,jsx as F,jsxs as oe}from"react/jsx-runtime";var
|
|
447
|
+
`)){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 Lo,jsx as F,jsxs as oe}from"react/jsx-runtime";var US={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},iy=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
446
448
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
447
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
448
|
-
`).length+1,console.log(d)},[_e]),sa=se([]),ns=J(()=>{let u=sa.current;if(u.length===0)return;sa.current=[];let d=Mg(u);d&&ts({kind:"note",tone:"info",text:`\u25CF Housekeeping ${d}`})},[ts]),h=J(u=>{ns(),ts(u)},[ts,ns]),He=se({printed:[],armed:[],printedAt:0}),Qn=se(0),qe=J((u,d)=>{Ke.current++,He.current.armed=[],he(u),X(d??null)},[]),kt=J(()=>{Ke.current++,He.current.armed=[],he(null),X(null)},[]),os=J(u=>{Ke.current++,He.current.armed=[],he(null),X(u)},[]),Q=J(u=>qe(u,Po({kind:"cmd",cmd:u,reason:""})),[qe]),jt=J((u,d)=>{if(!d?.silent&&u.note&&h({kind:"note",tone:d?.tone??u.tone,text:u.note}),!d?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let E=
|
|
449
|
-
`)}catch{}u.picker&&(ue(u.picker.options.map(E=>({cmd:E.cmd,desc:E.desc}))),zn(u.picker.title)),!d?.silent&&u.note&&(He.current.printed=u.menu,He.current.printedAt=Qn.current);let w=Qn.current-He.current.printedAt<Math.max(8,(Oe.rows??24)-4)&&Lm(He.current.printed,u.menu)?u.menu:[];u.lead&&(u.lead.kind==="answer"?os(Po(u.lead,w.length)):qe(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,Po(u.lead,w.length))),He.current.armed=w},[h,qe,os,e,Oe]),Ae=J((u,d,c="info")=>{He.current.armed=[],u&&h({kind:"note",tone:c,text:u}),d&&(d.kind==="answer"?os(Po(d)):qe(d.kind==="cmd"?d.cmd:d.text,Po(d)))},[h,qe,os]),Ko=J((u,d,c,w="info")=>{if(u.producedNothing){Ae("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}Ae(d,c,w)},[Ae]),[zo,ia]=te(null),[vy,Ku]=te(!1),Xt=J((u,d)=>{ia(u),Ku(!1),h({kind:"note",tone:"info",text:d?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),aa=J(()=>{
|
|
450
|
-
`)}),Xt(u.prompt,
|
|
451
|
-
${
|
|
449
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function BS(e,t,n,o){let r=Au(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=Du(e),a=ge(e),l=(a?.docsDir??Nu).replace(/\/+$/,""),p=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,g={version:t,engineVersion:uy,captureVersion:Mt(),claude:s,model:i.model,modelSource:US[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:p};if(a===null)return g;try{let k=ut(e,o);g.profile=k.name,g.apiUrl=k.connection.apiUrl,g.prod=k.production,g.project=k.project.projectName??k.project.projectId??"(chosen at login)";let v=Fn(k.name);if(v){let P={...Oo(v.idToken)??{},...Oo(v.accessToken)??{}},S=P.email??P.preferred_username??"signed in";pn(v)?v.refreshToken&&(g.who=S,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=S,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function HS(e,t){try{let n=ut(e,t),o=Fn(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Oo(o.idToken)??{},...Oo(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return pn(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 ay=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],_o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qS="Ask me to write or update an article\u2026";function Io({ch:e,dim:t}){let[n,o]=te(!0);return tt(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),F(U,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function dn({rows:e,cursor:t,cap:n,render:o}){let r=Ui(e.length,t,n);return oe(Lo,{children:[r.above>0?F(U,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?F(U,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var ly=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function cy(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var GS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function VS({startTime:e,chars:t}){let[n,o]=te(0),r=se(Date.now());tt(()=>{let p=setInterval(()=>o(g=>g+1),120);return()=>clearInterval(p)},[]);let s=_o[n%_o.length],i=ay[Math.floor(n/16)%ay.length],a=vp(e,r.current,Date.now()),l=Math.round(t/4);return oe(xe,{children:[F(U,{color:Z,children:` ${s} ${i}\u2026 `}),F(U,{color:"gray",children:`(${dr(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function YS({text:e}){let[t,n]=te(0);return tt(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),F(xe,{paddingX:1,children:F(U,{color:Z,children:`${_o[t%_o.length]} ${e}`})})}var KS=12e4;function zS({p:e}){let[t,n]=te(0);tt(()=>{let T=setInterval(()=>n(D=>D+1),150);return()=>clearInterval(T)},[]);let o=_o[t%_o.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),a=Date.now()-e.lastAt>=KS,l=e.verb??"Converting",p=e.unit??"article",g=e.rows.reduce((T,D)=>T+D.items,0),k=l.toLowerCase(),v=e.rows,P=0;if(v.length>Vi){let T=v.findIndex(I=>I.status==="active"||I.status==="pending"),D=Math.max(0,Math.min(T-2,v.length-Vi));P=v.slice(0,D).filter(I=>I.status==="done").length,v=v.slice(D,D+Vi)}let S=Math.min(40,Math.max(...v.map(T=>bu(T.label).length),0)),C=T=>T==="failed"?"red":T==="active"?Z:void 0;return oe(xe,{flexDirection:"column",children:[oe(xe,{children:[F(U,{color:Z,children:` ${o} ${l} ${g} ${p}${g===1?"":"s"} `}),F(U,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${dr(r)} \xB7 esc to stop`})]}),P>0&&F(U,{dimColor:!0,children:` \u2714 +${P} done`}),v.map(T=>oe(U,{color:C(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Sg[T.status]} ${bu(T.label).padEnd(S)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${p}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${p}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${k}\u2026`:""]},T.label)),a&&F(U,{color:"yellow",children:` \u26A0 no activity for ${dr(s)} \u2014 press esc to stop if it's wedged`})]})}var XS=10800*1e3;function dy({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=HR(),[s,i]=te(n),[a,l]=te(null),[p,g]=te({text:"",pos:0}),k=p.text,v=J(u=>{g(d=>{let c=typeof u=="function"?u(d.text):u;return{text:c,pos:c.length}})},[]),P=J(u=>{g(d=>({text:d.text.slice(0,d.pos)+u+d.text.slice(d.pos),pos:d.pos+u.length}))},[]),S=J(()=>{g(u=>{if(u.pos===0)return u;let d=u.text.slice(0,u.pos),c=jg(d)??d.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,T]=te(!1),[D,I]=te(!1),[O,Y]=te(0),[fe,ae]=te(!1),[le,he]=te(null),[ce,X]=te(null),[ne,ue]=te([]),Te=se(!1),yt=se(!1),St=se(null),Wt=se(!1),[nt,Wn]=te(!1),Ke=se(0),[hn,Ut]=te(!1),[De,Pt]=te(!1),[Mo,Ou]=te(null),[wy,Bt]=te(0),Tt=se(0),[ea,Un]=te(0),[Bn,Jr]=te(null),_u=se(new Map),ky=se(0),Hn=se([]),dt=se(null);dt.current===null&&(dt.current=Hg({cwd:e,profileName:s,allowProdWrites:!1}));let Et=se({uuid:null,firstPrompt:null,titleFired:!1}),Fo=se(new Map),Mu=se(null),Zr=se(Vg().verboseTranscript===!0),Ht=se(!1),ta=se([]),Ce=se([]),fn=se([]),Wo=se(null),[Fu,mn]=te(null),na=se(null),[gn,yn]=te(null),[qt,qn]=te(null),[Gt,Gn]=te(null),[ze,Vn]=te(null),[pt,wn]=te(null),[At,Yn]=te(null),[Vt,Kn]=te(null),[Yt,kn]=te(null),[Dt,Nt]=te(null),[Le,Uo]=te(null),Wu=se({value:0,at:0}),[wt,bn]=te(null),[Uu,zn]=te(null),[ot,$n]=te(null),[Xe,Xn]=te(null),[Bu,oa]=te([]),vn=se([]),Bo=se(!1),Ee=se(null),[Ho,de]=te(null),[Hu,je]=te(null),es=se(!1),qo=se(null),Go=se(null),[rt,xn]=te(null),[Vo,Cn]=te(null),Yo=!!(Gt||ze||pt||At||Vt||Yt||Dt||Le||wt||ot||Xe||rt||Vo),[qu,Kt]=te(0),[Gu,zt]=te(0),[by,Vu]=te(0),ra=vu(()=>{try{let u=Du(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,by]),{stdout:Oe}=GR(),[,$y]=te(0),Yu=se(`${Oe.columns??80}x${Oe.rows??24}`),_e=J(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),ts=J(u=>{Hn.current.push(u);let d=Va(u,_e());Qn.current+=d.split(`
|
|
450
|
+
`).length+1,console.log(d)},[_e]),sa=se([]),ns=J(()=>{let u=sa.current;if(u.length===0)return;sa.current=[];let d=Mg(u);d&&ts({kind:"note",tone:"info",text:`\u25CF Housekeeping ${d}`})},[ts]),h=J(u=>{ns(),ts(u)},[ts,ns]),He=se({printed:[],armed:[],printedAt:0}),Qn=se(0),qe=J((u,d)=>{Ke.current++,He.current.armed=[],he(u),X(d??null)},[]),kt=J(()=>{Ke.current++,He.current.armed=[],he(null),X(null)},[]),os=J(u=>{Ke.current++,He.current.armed=[],he(null),X(u)},[]),Q=J(u=>qe(u,Po({kind:"cmd",cmd:u,reason:""})),[qe]),jt=J((u,d)=>{if(!d?.silent&&u.note&&h({kind:"note",tone:d?.tone??u.tone,text:u.note}),!d?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let E=jS(e);IS(KR(E)),YR(E,`${new Date().toISOString()}
|
|
451
|
+
`)}catch{}u.picker&&(ue(u.picker.options.map(E=>({cmd:E.cmd,desc:E.desc}))),zn(u.picker.title)),!d?.silent&&u.note&&(He.current.printed=u.menu,He.current.printedAt=Qn.current);let w=Qn.current-He.current.printedAt<Math.max(8,(Oe.rows??24)-4)&&Lm(He.current.printed,u.menu)?u.menu:[];u.lead&&(u.lead.kind==="answer"?os(Po(u.lead,w.length)):qe(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,Po(u.lead,w.length))),He.current.armed=w},[h,qe,os,e,Oe]),Ae=J((u,d,c="info")=>{He.current.armed=[],u&&h({kind:"note",tone:c,text:u}),d&&(d.kind==="answer"?os(Po(d)):qe(d.kind==="cmd"?d.cmd:d.text,Po(d)))},[h,qe,os]),Ko=J((u,d,c,w="info")=>{if(u.producedNothing){Ae("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}Ae(d,c,w)},[Ae]),[zo,ia]=te(null),[vy,Ku]=te(!1),Xt=J((u,d)=>{ia(u),Ku(!1),h({kind:"note",tone:"info",text:d?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),aa=J(()=>{MS(e,new Date().toISOString());let u=Uf(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
|
|
452
|
+
`)}),Xt(u.prompt,FS(e)?{hint:"\u2328 Press c to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,h,Xt]),la=se(!1),ca=J(async()=>{try{if(la.current||!RS(CS())||ge(e)?.mode==="engineer")return;let u=await xS({pkg:Ro,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;la.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${Ro} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Pt(!0),(await xi().finally(()=>Pt(!1))).ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ou(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed \u2014 run: ${vi}`})}catch{}},[e,o,h,Q]),Xo=se(!1),ua=se(null),zu=J(async u=>{if(!Xo.current)try{let d=ge(e);if(!d)return;let c=Xu.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;Xo.current=!0;try{let E=await NS(e,d);if(E.commit?.ok)ua.current=null;else if(E.commit&&!E.commit.ok){let B=`${E.commit.reason}:${E.commit.detail??""}`;ua.current!==B&&(ua.current=B,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${cn(E.commit.reason,E.commit.detail)}`}))}}finally{Xo.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;Xo.current=!0;try{let{lines:E,changed:B}=await ki(e,d);for(let m of E)m.tone==="warn"||m.tone==="error"?h({kind:"note",tone:m.tone,text:m.text}):m.text.includes("\u2B07")&&h({kind:"note",tone:m.tone,text:m.text});B&&Y(m=>m+1)}finally{Xo.current=!1}}catch{}},[e,h]),Jn=J(u=>{let d=Ue(e,s);return d.ok?!0:(h({kind:"note",tone:"warn",text:d.reason}),Go.current=u,Q("/login"),!1)},[e,s,h,Q]),[rs,da]=te(null),Xu=se(null),ht=J((u,d)=>{let c=Vr(e,s,{claudeMissing:Au(t).state==="missing",allowAutoAudit:u,genreUnknown:Wt.current,pendingAnswer:St.current});return Xu.current=c?.handoff??null,c?Gr(c,{header:d,pickable:!0}):{kind:"idle"}},[e,s,t]),pa=se(Date.now()),Qo=se(mg()),Qu=se(0),[Ju,Zu]=te(null),Jo=se(!0),Zn=se(!1),ss=se(0),Zo=se(0);tt(()=>{let u=setInterval(()=>{if(Jo.current){ss.current=0,Zo.current=0;return}if(!C)try{if(!Ao(ey(e)))return;if(mt(e).status==="current"){Jo.current=!0,ss.current=0,Zo.current=0;let c=Zn.current?`\u2713 Your builder finished the protocol update (v${Re}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",w=ht(!1,c),E=w.kind==="recommend"?w.rec:null;ia(null),E?.note?jt(E,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${E?.lead?` ${qr(E.lead)}`:""}`}),E?.lead||E?.picker?jt(E,{silent:!0}):Zn.current||qe("write the docs for this repo")),Y(B=>B+1);return}if(Zn.current)return;ss.current+=1;let d=ss.current;if((d===4||d%15===0)&&Zo.current<3){Zo.current+=1;let c=Zo.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:Ot(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${c}`:`\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.${c}`})}}catch{}},4e3);return()=>clearInterval(u)},[e,C,h,ht,jt,qe]),tt(()=>{let u=Fu??Qr(e);if(!C){Bi(0),To(`${qi} ${u}`);return}Bi(3);let d=0;To(`${Hi[0]} ${u}`);let c=setInterval(()=>{d=(d+1)%Hi.length,To(`${Hi[d]} ${u}`)},400);return()=>clearInterval(c)},[C,e,Fu]),tt(()=>()=>Bi(0),[]),tt(()=>{let u=performance.now(),d=[],c=(f,$)=>{let b=performance.now();try{return $()}finally{let R=Math.round(performance.now()-b);R>=80&&d.push(`${f}: ${R}ms`)}};h({kind:"banner",info:c("banner",()=>BS(e,o,t,s))});let w=Au(t).state==="missing";if(w&&h({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.
|
|
453
|
+
${XR}
|
|
452
454
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ge(e)){h({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
453
|
-
${iy}`}),Q(w?"/doctor":"/init");return}w&&Q("/doctor");try{let f=ut(e,s),$=Fn(f.name);$&&pn($)&&$.refreshToken?
|
|
454
|
-
`)}),Xt(Pn()),Jo.current=!1,Zn.current=!1)}}catch{}try{let f=c("reconcile-feedback",()=>
|
|
455
|
-
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:Ss(f.reopenedForRedaction)})}catch{}let B=c("ready-decision",()=>ht(!0));B.kind==="autoAudit"?(h({kind:"note",tone:"info",text:B.note}),br().then(f=>{f.kind!=="forward-to-agent"||!f.prompt||ye(f.prompt,{display:f.display,quietUser:!0}).then($=>{$.producedNothing||(Hr(e,s),Y(b=>b+1))})})):B.kind==="recommend"&&jt(B.rec);let m=Math.round(performance.now()-u);m>=800&&
|
|
455
|
+
${iy}`}),Q(w?"/doctor":"/init");return}w&&Q("/doctor");try{let f=ut(e,s),$=Fn(f.name);$&&pn($)&&$.refreshToken?eS({profile:f.name,connection:f.connection}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(b=>b+1)}).catch(()=>{h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!$||pn($))&&(h({kind:"note",tone:"warn",text:`Profile "${f.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let f=ge(e),$=ut(e,s),b=Fn($.name);f&&b&&!pn(b)&&au(e,f.authoritativeSourceFiles)&&!lu(e,s)&&(h({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Q("/scope"))}catch{}try{let f=c("resolve-genre",()=>hS(e));f.persisted&&f.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${f.appType} app \u2014 enabled the ${f.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):f.source==="unknown"&&ge(e)&&(Wt.current=!0)}catch{}let E=mt(e);try{if(c("reconcile-devhints",()=>Es(e)),E.status!=="current"&&!Ot(e)){let f=As(e);f.length&&(h({kind:"note",tone:"warn",text:f.join(`
|
|
456
|
+
`)}),Xt(Pn()),Jo.current=!1,Zn.current=!1)}}catch{}try{let f=c("reconcile-feedback",()=>SS(e));f.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${f.archived} resolved item${f.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${f.open>0?`; ${f.open} still open`:""}.`})}catch{}try{let f=c("upgrade-actions",()=>PS(e));f.applied.length>0&&h({kind:"note",tone:"warn",text:Rs(f.applied).join(`
|
|
457
|
+
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:Ss(f.reopenedForRedaction)})}catch{}let B=c("ready-decision",()=>ht(!0));B.kind==="autoAudit"?(h({kind:"note",tone:"info",text:B.note}),br().then(f=>{f.kind!=="forward-to-agent"||!f.prompt||ye(f.prompt,{display:f.display,quietUser:!0}).then($=>{$.producedNothing||(Hr(e,s),Y(b=>b+1))})})):B.kind==="recommend"&&jt(B.rec);let m=Math.round(performance.now()-u);m>=800&&DS({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${d.length?d.join(`
|
|
456
458
|
`):"no single phase \u226580ms"}
|
|
457
|
-
cwd: ${e}`}),ca(),zu({pull:!0})},[]),tt(()=>{let u=setInterval(()=>{ca()},
|
|
459
|
+
cwd: ${e}`}),ca(),zu({pull:!0})},[]),tt(()=>{let u=setInterval(()=>{ca()},XS);return()=>clearInterval(u)},[ca]),tt(()=>{let u=setInterval(()=>{try{let d=Date.now(),c=wu(d,pa.current);if(Qu.current+=1,c&&Qu.current%Math.round(3e5/6e4)!==0)return;let w=WS(e),E=Qo.current,B=w===E.fingerprint&&E.counts?E.counts:Ln(e),m=yg({now:d,lastInputAt:pa.current,fingerprint:w,counts:B,occupied:C||fe||ne.length>0||k!==""||Yo||Ce.current.length>0,prev:E});if(Qo.current=m.memory,Zu(m.waiting),m.speak){h({kind:"note",tone:"info",text:kg(m.speak)});let f=ht(!1);f.kind==="recommend"&&jt(f.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,fe,ne.length,k,Yo,h,ht,jt]),tt(()=>{if(C||fe||Te.current||le!==null||ne.length>0||k!==""||zo!==null||Ce.current.length>0||Wo.current||Yo)return;let u=ht(!1);u.kind==="recommend"&&(u.rec.lead||u.rec.picker)&&jt(u.rec,{silent:!0}),zu({pull:!1})},[C,fe,le,ne,k,zo,Yo,O,ht,nt]),tt(()=>{let u=null,d=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let w=`${Oe.columns??80}x${Oe.rows??24}`;w!==Yu.current&&(Yu.current=w,$y(E=>E+1),d&&clearTimeout(d),d=setTimeout(()=>{d=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+xp(Hn.current,_e())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",c),()=>{u&&clearTimeout(u),d&&clearTimeout(d),Oe.off("resize",c)}},[Oe,_e]);let Ge=Math.max(20,(Oe.columns??80)-1),ed=vu(()=>HS(e,s),[e,s,O]),ha=(()=>{if(De)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Mo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Mo?` v${Mo}`:""}\u2026`,isSetup:!0};if(rs)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(zo)return vy?{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 \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(Ju)return{text:$g(Ju),isSetup:!0};if(Ce.current.length>0){let w=Ce.current.length;return Ce.current[0].mode==="conflict"?{text:w>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${w}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:w>1?`y to write \xB7 n to skip \xB7 ya/na for all ${w}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let u=ge(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let d=xu(e,(u.docsDir??Nu).replace(/\/+$/,"")),c=(()=>{try{return Ao(d)&&VR(d).length>0}catch{return!1}})();try{let w=ut(e,s),E=Fn(w.name);if(!(!!E&&!(pn(E)&&!E.refreshToken)))return{text:`Sign in with /login (profile "${w.name}")\u2026`,isSetup:!0};if(!w.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!w.project.workspaceId&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:qS,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),It=pp(k),td=It.length>0&&!C,xy=12,Lt=mu(Oe.rows),Cy=Oe.rows??24,nd=mu(Oe.rows,{max:xy}),is=Math.min(ea,Math.max(0,It.length-1)),Rn=Ui(It.length,is,nd).start,fa=It.slice(Rn,Rn+nd),ma=a!==null?Fg(a,8,Ge):null,as=ot?ot.paths.filter(u=>!ot.query||u.toLowerCase().includes(ot.query.toLowerCase())).slice(0,8):[],ls=rt?rt.sessions.filter(u=>{let d=rt.query.toLowerCase();return!d||u.name.toLowerCase().includes(d)||u.firstPrompt.toLowerCase().includes(d)}).slice(0,8):[],Ve=J((u,d)=>{dt.current?.close(),dt.current=Hg({cwd:e,resume:u,profileName:d??s,allowProdWrites:Ht.current}),u||(Et.current={uuid:null,firstPrompt:null,titleFired:!1},mn(null)),Kt(0),zt(0)},[e,s]),od=J((u,d,c)=>{if(ly.test(u))try{let w=ut(e,s),E=typeof d.project_id=="string"&&d.project_id||w.project.projectId,B=Mi(d,c),m=[],f=Fi(c);u.endsWith("publish_article")&&f&&m.push(`Live: ${f}`);let $=Wi(c);$?m.push(`Preview: ${$}`):B&&E&&m.push(`Preview: ${_i(w.connection.portalUrl,E,B,w.project.languageCode??"en")}`),m.length>0&&h({kind:"link",lines:m})}catch{}},[e,s,h]),ye=J(async(u,d)=>{Ut(!0),Te.current=!1,yt.current=!1,St.current=null,kt(),ue([]),zn(null),ia(null);let c=Ke.current;if(d?.display?.startsWith("/"))try{let A=Am(e,d.display);A&&(u=`${u}
|
|
458
460
|
|
|
459
|
-
${A}`)}catch{}d?.quietUser||h({kind:"user",text:d?.echoDisplay&&d.display?d.display:u});let w=Et.current;w.firstPrompt||(w.firstPrompt=d?.display??u),Tt.current=Date.now(),Bt(0),T(!0),Fo.current.clear();let E="",B=!1,m=!1,f=!1,$=!1,b="",R={num:0,closed:!1,cueSeen:!1},x=null,_=()=>{x||(x=setTimeout(()=>{x=null,l(b.length>0?b:null)},60))},W=()=>{x&&clearTimeout(x),x=null,l(null)},V=(A=!1)=>{let{head:M,keep:L}=Wg(b,A);M.trim()&&h({kind:"assistant",text:fu(M.trimEnd(),R)}),b=L,W()};try{for await(let A of dt.current.send(u))if(A.type==="session"){if(!w.uuid){w.uuid=A.sessionId;let M=new Date().toISOString(),L=na.current,q=L??
|
|
460
|
-
`)}),Q(Ul(w));return}let E=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let B=new AbortController;Ee.current=B;let m=async(f,$)=>{let b=Ru(f);de({verb:"
|
|
461
|
+
${A}`)}catch{}d?.quietUser||h({kind:"user",text:d?.echoDisplay&&d.display?d.display:u});let w=Et.current;w.firstPrompt||(w.firstPrompt=d?.display??u),Tt.current=Date.now(),Bt(0),T(!0),Fo.current.clear();let E="",B=!1,m=!1,f=!1,$=!1,b="",R={num:0,closed:!1,cueSeen:!1},x=null,_=()=>{x||(x=setTimeout(()=>{x=null,l(b.length>0?b:null)},60))},W=()=>{x&&clearTimeout(x),x=null,l(null)},V=(A=!1)=>{let{head:M,keep:L}=Wg(b,A);M.trim()&&h({kind:"assistant",text:fu(M.trimEnd(),R)}),b=L,W()};try{for await(let A of dt.current.send(u))if(A.type==="session"){if(!w.uuid){w.uuid=A.sessionId;let M=new Date().toISOString(),L=na.current,q=L??iS(w.firstPrompt??"session");aS({uuid:A.sessionId,name:q,renamed:!!L,titled:!1,cwd:e,firstPrompt:w.firstPrompt??"",createdAt:M,updatedAt:M}),mn(q),na.current=null}}else if(A.type==="text"){b+=A.delta,E+=A.delta;let M=Ug(b);if(M>0){let L=b.slice(0,M).trimEnd();L&&h({kind:"assistant",text:fu(L,R)}),b=b.slice(M)}_(),Bt(L=>L+A.delta.length)}else if(A.type==="tool"){B=!0,ly.test(A.name)&&(m=!0);let L=(me=>typeof me=="string"&&me?me.replace(/\\/g,"/").toLowerCase():null)(A.input.file_path??A.input.notebook_path),q=["Edit","Write","MultiEdit","NotebookEdit"].includes(A.name),ie=A.name==="Read"&&L!==null&&L===Mu.current;Mu.current=q?L:null;let we=Zr.current,Qe=we?null:_g(A.name,A.input),z=we?null:Ii(A.name,A.input,e,s);if(Qe)sa.current.push(Qe);else if(z)V(),h({kind:"doc",verb:z.verb,title:z.title,category:z.category,note:z.note,...z.loud?{loud:z.loud}:{}}),Fo.current.set(A.id,{name:A.name,input:A.input,doc:!0,keepResult:z.keepResult});else if(ie)V(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let me=Li(A.name,A.input,e);me&&(V(),h({kind:"tool",title:me.title,sep:me.sep,arg:me.arg}),Fo.current.set(A.id,{name:A.name,input:A.input}))}}else if(A.type==="article_diff"){let M=at(A.oldContent,A.newContent,_e());M&&(V(),h({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(A.type==="tool_result"){A.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(A.output)&&(es.current=!0);let M=Fo.current.get(A.id);if(M){Fo.current.delete(A.id),V();let q=M.doc&&!M.keepResult&&!A.isError?{lines:[],hidden:0}:Oi(A.output,4,A.isError||Zr.current?void 0:M.name,M.input);q.lines.length>0&&h({kind:"tool-result",lines:q.lines,hidden:q.hidden,isError:A.isError}),A.isError||od(M.name,M.input,A.output)}}else if(A.type==="result"){V(!0),Kt(q=>q+A.outputTokens),zt(q=>q+A.costUsd);let M=A.inputTokens+A.cacheReadTokens+A.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:A.outputTokens,costUsd:A.costUsd,ok:A.ok,...M>0?{inTokens:M,cachedPct:Math.round(A.cacheReadTokens/M*100)}:{}}),!f&&!B&&!E.trim()&&!Bo.current&&($=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Two usual causes: the Claude model/runtime (check /doctor \u2014 sign-in + reachability), or a Claude usage limit reached mid-session, which ends every turn instantly and leaves /doctor completely clean."})),A.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(E))try{let q=ty(e);if(Ao(q)){let ie=zi(q,"utf8").trim();ie&&(da(ie),h({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{}let L=A.ok?sg(E):null;if(yt.current=L!==null,St.current=L,A.ok&&(R.cueSeen||(L?.options??0)>=2))Wn(!0),ue([]);else if(L)ue([]);else{let q=A.ok?xg(E,fo.map(ie=>ie.name)):[];if(q.length>0)Q(q[0]);else if(A.ok&&E.trim()&&!yt.current){let ie=ht(!1);ie.kind==="recommend"&&(ie.rec.lead||ie.rec.picker)||dS(u,E,e).then(we=>{we&&Ke.current===c&&qe(we)}).catch(()=>{})}}if(w.uuid&&(Cu(w.uuid),!w.titleFired)){w.titleFired=!0;let q=w.uuid,ie=w.firstPrompt;ie&&qg(ie,e).then(we=>{we&&(sS(q,we),mn(we))}).catch(()=>{})}}else A.type==="error"&&(V(!0),f=!0,A.kind==="auth"&&(es.current=!0),h(A.kind==="limit"?{kind:"note",text:`\u23F3 ${A.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${A.message}`,tone:"error"}))}finally{if(T(!1),W(),ns(),m)try{let A=Pu(await Su({cwd:e,profileName:s,onRateLimit:M=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(M.waitMs/1e3)}s\u2026`)}));A&&h({kind:"note",tone:A.startsWith("\u26A0")?"warn":"info",text:A})}catch{}finally{je(null)}Y(A=>A+1),Et.current.uuid&&hg(e,Et.current.uuid,Hn.current),es.current?(es.current=!1,qo.current=d?.display??u,qe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):qo.current=null,Bo.current&&(Bo.current=!1,vn.current.length>0&&(h({kind:"note",tone:"info",text:`(${vn.current.length} queued message(s) discarded)`}),vn.current=[],oa([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$}},[e,h,od,_e,qe,Q,kt,ht,ns]),ft=J(async(u,d=0,c)=>{let w=Tu(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!w.clear){h({kind:"note",tone:"warn",text:Eu(w,u.length).join(`
|
|
462
|
+
`)}),Q(Ul(w));return}let E=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let B=new AbortController;Ee.current=B;let m=async(f,$)=>{let b=Ru(f);de({verb:"Pushing",total:b.length,done:0,active:[],rows:_n(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:$?`Resolving cross-links in ${f.length} article${f.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${f.length} article${f.length===1?"":"s"} in ${b.length} batch${b.length===1?"":"es"} (\u2264${yr} agents at once) on ${E.model}\u2026 (esc to stop)`});let R=!1;for await(let x of Do({cwd:e,partitions:b,promptFor:_=>wr(_.paths),concurrency:yr,profileName:s,allowProdWrites:Ht.current,allowUnreviewedPublish:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0,model:E.model,signal:B.signal}))if(x.type==="partition_status")x.status==="running"?de(_=>_&&{..._,active:[..._.active,x.label],rows:Be(_.rows,x.label,"active"),lastAt:Date.now()}):de(_=>_&&{..._,active:_.active.filter(W=>W!==x.label),done:_.done+1,rows:Be(_.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")de(_=>{if(!_)return _;let W={..._,lastAt:Date.now()};return x.event.type==="tool"?W.tools=_.tools+1:x.event.type==="text"&&(W.chars=_.chars+x.event.delta.length),W});else if(x.type==="run_done"){R=x.aborted,zt(L=>L+x.totalCostUsd),Kt(L=>L+x.results.reduce((q,ie)=>q+ie.outputTokens,0));let _=x.aborted?"Stopped. ":"",W=t.kind==="api"?"api":"subscription",V=yl(e,u,s),A=!x.aborted&&(!!x.blocked||!!x.allEmpty||u.length>0&&V===0);h({kind:"note",tone:x.aborted?"warn":x.ok&&!A?"ok":"warn",text:_+wl(x.results,b,W,$?0:d,{recorded:V,...x.blocked?{blocked:x.blocked}:{},...x.allEmpty?{allEmpty:!0}:{},...x.bailedEmpty?{bailedEmpty:!0,notRun:x.notRun??0}:{}},c?.scope).join(`
|
|
461
463
|
`)});let M=ml(e,s);if(M&&h({kind:"note",tone:"info",text:M}),!x.aborted&&!A){let L=yo(e,s);L&&h({kind:"note",tone:"info",text:L})}if(!x.aborted&&!A){try{let q=await Su({cwd:e,profileName:s,onRateLimit:we=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(we.waitMs/1e3)}s\u2026`)}),ie=Pu(q);ie?h({kind:"note",tone:ie.startsWith("\u26A0")?"warn":"info",text:ie}):q.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${q.skipped}`})}catch(q){h({kind:"note",tone:"warn",text:`Order sync failed: ${q.message}`})}finally{je(null)}try{let q=ry(await oy({cwd:e,profileName:s}));q&&h({kind:"note",tone:"info",text:q})}catch(q){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${q.message}`})}let L=await wo(e,s);L&&h({kind:"note",tone:"info",text:L})}}return R};try{if(!await m(u,!1)){let $=await kl(e,s,u);$.length>0&&await m($,!0),d>0&&Ae(null,{kind:"cmd",cmd:"/resolve",reason:`${d} conflict${d===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(f){h({kind:"note",tone:"error",text:`Publish run failed: ${f.message}`})}finally{Ee.current=null,de(null),T(!1),Y(f=>f+1)}},[e,s,h,t,Ae]),eo=J(u=>h({kind:"block",text:u.join(`
|
|
462
|
-
`)}),[h]),cs=J(async u=>{let d=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let c=new AbortController;Ee.current=c,de({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:_n(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`${u.headline} on ${d.model}\u2026 (esc to stop)`});let w=!0,E=[],B=!1;try{for await(let m of Do({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:Ht.current,model:d.model,signal:c.signal}))if(m.type==="partition_status")m.status==="running"?de(f=>f&&{...f,active:[...f.active,m.label],rows:Be(f.rows,m.label,"active"),lastAt:Date.now()}):de(f=>f&&{...f,active:f.active.filter($=>$!==m.label),done:f.done+1,rows:Be(f.rows,m.label,m.status==="done"?"done":"failed"),lastAt:Date.now()});else if(m.type==="partition_event")de(f=>{if(!f)return f;let $={...f,lastAt:Date.now()};return m.event.type==="tool"?$.tools=f.tools+1:m.event.type==="text"&&($.chars=f.chars+m.event.delta.length),$});else if(m.type==="run_done"){zt(b=>b+m.totalCostUsd),Kt(b=>b+m.results.reduce((R,x)=>R+x.outputTokens,0));let f=m.results.filter(b=>!b.ok);w=!!m.allEmpty||!!m.blocked,B=!!m.aborted;let $=[`${m.aborted?"Stopped. ":""}${m.results.length-f.length}/${u.partitions.length}
|
|
463
|
-
`)}),!w){let b=new Set(f.map(R=>R.label));E=u.partitions.filter(R=>!b.has(R.label)).flatMap(R=>R.paths)}}}catch(m){h({kind:"note",tone:"error",text:`${u.verb} failed: ${m.message}`})}finally{Ee.current=null,de(null),T(!1),Y(m=>m+1)}return{producedNothing:w,covered:E,aborted:B}},[e,s,h]),Ry=J(async(u,d)=>{let c=await cs({partitions:u.partitions,promptFor:u.promptFor,concurrency:Ur,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"}
|
|
464
|
+
`)}),[h]),cs=J(async u=>{let d=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let c=new AbortController;Ee.current=c,de({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:_n(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`${u.headline} on ${d.model}\u2026 (esc to stop)`});let w=!0,E=[],B=!1;try{for await(let m of Do({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:Ht.current,model:d.model,signal:c.signal}))if(m.type==="partition_status")m.status==="running"?de(f=>f&&{...f,active:[...f.active,m.label],rows:Be(f.rows,m.label,"active"),lastAt:Date.now()}):de(f=>f&&{...f,active:f.active.filter($=>$!==m.label),done:f.done+1,rows:Be(f.rows,m.label,m.status==="done"?"done":"failed"),lastAt:Date.now()});else if(m.type==="partition_event")de(f=>{if(!f)return f;let $={...f,lastAt:Date.now()};return m.event.type==="tool"?$.tools=f.tools+1:m.event.type==="text"&&($.chars=f.chars+m.event.delta.length),$});else if(m.type==="run_done"){zt(b=>b+m.totalCostUsd),Kt(b=>b+m.results.reduce((R,x)=>R+x.outputTokens,0));let f=m.results.filter(b=>!b.ok);w=!!m.allEmpty||!!m.blocked,B=!!m.aborted;let $=[`${m.aborted?"Stopped. ":""}${m.results.length-f.length}/${u.partitions.length} batches ${u.doneNoun}.`,...f.length?[`\u26A0 ${f.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${f.map(b=>b.label).join(", ")}`]:[],...m.blocked?[`\u26A0 ${m.blocked}`]:[],...m.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];if(h({kind:"note",tone:m.aborted||f.length||m.blocked||m.allEmpty?"warn":"ok",text:$.join(`
|
|
465
|
+
`)}),!w){let b=new Set(f.map(R=>R.label));E=u.partitions.filter(R=>!b.has(R.label)).flatMap(R=>R.paths)}}}catch(m){h({kind:"note",tone:"error",text:`${u.verb} failed: ${m.message}`})}finally{Ee.current=null,de(null),T(!1),Y(m=>m+1)}return{producedNothing:w,covered:E,aborted:B}},[e,s,h]),Ry=J(async(u,d)=>{let c=await cs({partitions:u.partitions,promptFor:u.promptFor,concurrency:Ur,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${Ur} editors at once)${d?", applying fixes as they go":", report only"}`,caveatLines:Zc(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."});if(d&&c.covered.length>0)try{jo(e,c.covered,Ye("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted}},[e,cs]),ga=J(async(u,d)=>{if(u.length===0)return;let c=u.reduce((f,$)=>f+$.threads.length,0),w=new Map,E=u.map(f=>(w.set(f.label,f),{label:f.label,paths:f.path?[f.path]:[]})),B=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let m=new AbortController;Ee.current=m,de({verb:"Answering",unit:"article",total:E.length,done:0,active:[],rows:_n(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${E.length} article${E.length===1?"":"s"} (\u2264${Or} agents at once) on ${B.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${d.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let f of Do({cwd:e,partitions:E,promptFor:$=>{let b=w.get($.label);return Wc({articleId:b.articleId,label:b.label,path:b.path,count:b.threads.length,resolve:d.resolve})},concurrency:Or,profileName:s,allowProdWrites:Ht.current,allowCommentResolve:d.resolve,model:B.model,signal:m.signal}))if(f.type==="partition_status")f.status==="running"?de($=>$&&{...$,active:[...$.active,f.label],rows:Be($.rows,f.label,"active"),lastAt:Date.now()}):de($=>$&&{...$,active:$.active.filter(b=>b!==f.label),done:$.done+1,rows:Be($.rows,f.label,f.status==="done"?"done":"failed"),lastAt:Date.now()});else if(f.type==="partition_event")de($=>{if(!$)return $;let b={...$,lastAt:Date.now()};return f.event.type==="tool"?b.tools=$.tools+1:f.event.type==="text"&&(b.chars=$.chars+f.event.delta.length),b});else if(f.type==="run_done"){zt(V=>V+f.totalCostUsd),Kt(V=>V+f.results.reduce((A,M)=>A+M.outputTokens,0));let $=f.results.filter(V=>!V.ok),b=f.results.length-$.length,x=[`${f.aborted?"Stopped. ":""}${b}/${E.length} article${E.length===1?"":"s"} answered.`,...$.length?[`\u26A0 ${$.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${$.map(V=>V.label).join(", ")}`]:[],...f.blocked?[`\u26A0 ${f.blocked}`]:[],...f.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:f.aborted||$.length||f.blocked||f.allEmpty?"warn":"ok",text:x.join(`
|
|
464
466
|
`)});let _=new Set($.map(V=>V.label)),W=[...d.rest??[],...u.filter(V=>_.has(V.label))];if(W.length>0&&!f.aborted&&d.report){let V=W.reduce((M,L)=>M+L.threads.length,0);h({kind:"note",tone:"info",text:`${V} comment${V===1?"":"s"} on ${W.length} other article${W.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let A={...d.report,threads:W.flatMap(M=>M.threads)};eo(_r(A,{width:_e()})),Nt({cursor:0,rows:$i(W),groups:W,resolve:d.resolve,report:A})}else if(W.length>0&&!f.aborted){let V=W.map(M=>M.path).filter(M=>!!M),A=V.length===W.length?vt(V):void 0;Q(A?V.length===1?`/comments ${A}`:`/comments --scope ${A}`:"/comments")}}}catch(f){h({kind:"note",tone:"error",text:`Answering comments failed: ${f.message}`})}finally{Ee.current=null,de(null),T(!1),Y(f=>f+1)}},[e,s,h,Ae,Q,eo,_e]),ya=J(async(u,d)=>{if(d?.skipReview===!0||d?.skipStyle===!0)await ft([u],0,{skipReview:d?.skipReview,skipStyle:d?.skipStyle,scope:u});else{let E=Tu(e,[u],{});if(!E.clear){h({kind:"note",tone:"warn",text:Eu(E,1).join(`
|
|
465
467
|
`)}),Q(Ul(E,u));return}await ye(hl(u),{display:`/publish ${u}`,quietUser:!0})}let w=d?.skipReview?null:await wo(e,s);w&&h({kind:"note",tone:"info",text:w});try{let E=await ni(e,s,u.replace(/\\/g,"/"));E.length>0&&(zn(`Related articles not yet published (${E.length}):`),ue([`/publish --related ${u}`,...E.map(B=>`/publish ${B}`)]))}catch{}},[e,s,ye,ft]),Sy=J(async(u,d)=>{T(!0);try{let c=await Rl(e,s,u,{skipReview:d.skipReview,skipStyle:d.skipStyle,onProgress:(E,B,m)=>je(`Publishing ${E+1}/${B} \u2014 ${m}\u2026`)}),w=c.blocked.length+c.failed.length;h({kind:"note",tone:w>0?"warn":"ok",text:Sl(c).join(`
|
|
466
|
-
`)}),c.blocked.length>0?Q("/review --blocked --fix"):Ae(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{je(null),T(!1),Y(c=>c+1)}},[e,s,h,Q,Ae]),rd=J(async u=>{try{let d=await Qi({cwd:e,profileName:s}),{clean:c,conflicts:w}=An(d.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to publish \u2014 everything is already up to date on Document360."});return}await ft(c.map(E=>E.path),w.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(d){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to publish (${d.message}) \u2014 your drafts are saved; run /publish when ready.`})}},[e,s,ft]),us=J(u=>{if(u)try{for(let d of Array.isArray(u)?u:[u]){let c=ou(e,d);if(!c)continue;Ei(e,c.title).ok&&h({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${c.title}`});return}}catch{}},[e,h]),sd=J(async(u,d)=>{let w=
|
|
468
|
+
`)}),c.blocked.length>0?Q("/review --blocked --fix"):Ae(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{je(null),T(!1),Y(c=>c+1)}},[e,s,h,Q,Ae]),rd=J(async u=>{try{let d=await Qi({cwd:e,profileName:s}),{clean:c,conflicts:w}=An(d.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to publish \u2014 everything is already up to date on Document360."});return}await ft(c.map(E=>E.path),w.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(d){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to publish (${d.message}) \u2014 your drafts are saved; run /publish when ready.`})}},[e,s,ft]),us=J(u=>{if(u)try{for(let d of Array.isArray(u)?u:[u]){let c=ou(e,d);if(!c)continue;Ei(e,c.title).ok&&h({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${c.title}`});return}}catch{}},[e,h]),sd=J(async(u,d)=>{let w=bS(u,3),E=No(e,"standard"),B=new Map,m=new Map;for(let b of u){let R=Tn(e,b),x=za(e,b,R);if(x&&B.set(b,x),R!==null){let _=cl(R);_.length>0&&m.set(b,_)}}Tt.current=Date.now(),Bt(0),T(!0);let f=new AbortController;Ee.current=f,de({verb:"Authoring",unit:"spec",total:w.length,done:0,active:[],rows:_n(w),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Authoring ${u.length} screenshot spec${u.length===1?"":"s"} in ${w.length} batch${w.length===1?"":"es"} (\u22646 agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let $=!1;try{for await(let b of Do({cwd:e,partitions:w,promptFor:R=>lh(R,B,m),concurrency:6,profileName:s,allowProdWrites:Ht.current,model:E.model,signal:f.signal}))if(b.type==="partition_status")b.status==="running"?de(R=>R&&{...R,active:[...R.active,b.label],rows:Be(R.rows,b.label,"active"),lastAt:Date.now()}):de(R=>R&&{...R,active:R.active.filter(x=>x!==b.label),done:R.done+1,rows:Be(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")de(R=>{if(!R)return R;let x={...R,lastAt:Date.now()};return b.event.type==="tool"?x.tools=R.tools+1:b.event.type==="text"&&(x.chars=R.chars+b.event.delta.length),x});else if(b.type==="run_done"){zt(V=>V+b.totalCostUsd),Kt(V=>V+b.results.reduce((A,M)=>A+M.outputTokens,0));let R=b.results.filter(V=>V.ok).length,x=b.aborted?"Stopped. ":"";$=!b.aborted&&d.setup;let _=b.aborted?"":$?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${d.scope?` ${d.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,W=$t(b,"Spec authoring");h({kind:"note",tone:W||b.aborted?"warn":b.ok?"ok":"warn",text:W?W.join(`
|
|
467
469
|
`):`${x}Authored specs \u2014 ${R}/${b.results.length} batches ok.${_}`}),W&&(Q("/doctor"),$=!1),!b.aborted&&b.ok&&!W&&us(d.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Ee.current=null,de(null),T(!1),Y(b=>b+1)}if($){let b=await xo();b.kind==="forward-to-agent"&&b.prompt&&await ye(b.prompt,{display:b.display,quietUser:!0}),aa()}},[e,s,h,ye,us,aa]),id=J(async u=>{let d=za(e,u,Tn(e,u))??void 0,c=await Js([u],void 0,{prior:d});c.kind==="forward-to-agent"&&c.prompt&&await ye(c.prompt,{display:c.display,quietUser:!0}),Yp(e,u)&&Ae(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,ye,Ae]),er=J(async(u,d)=>{if(!yi(e)){await ye(Cc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Df(e)){h({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),je("Waiting for you to finish logging in (browser window)\u2026");let L=new AbortController;Ee.current=L;let q;try{q=await Nf({cwd:e,signal:L.signal})}catch(ie){h({kind:"note",tone:"error",text:`Could not launch the login: ${ie.message}`});return}finally{Ee.current=null,je(null),T(!1)}if(q.exitCode!==0){xc(q.exitCode,q.output)?h({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(q.output)?h({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."}):h({kind:"note",tone:L.signal.aborted?"warn":"error",text:L.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
468
470
|
${$c(q.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(L=>[L,Zp(e,L)])),w=0;if(u.length>1){let L=u.filter(q=>c.get(q).mutates);if(L.length>0&&(w=L.length,u=u.filter(q=>!c.get(q).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${L.length} spec${L.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${L[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let L=c.get(u[0]),q=jf(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${L.what?`: ${Jp(L.what)}`:L.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. `+(q.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${q.url?` (${q.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}T(!0);let E=new AbortController;Ee.current=E;let B=u.map(L=>({label:L,items:1,status:"pending"}));de({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:B,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let m=_t(e),f=Object.keys(m.shots).length>0,$=If(d?.heldBackBlocked??[],w);h({kind:"note",tone:"info",text:`Capturing ${u.length} screenshot${u.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+($?`
|
|
469
471
|
${$}`:"")});let b=Date.now(),R=[];try{for(let L of u){if(E.signal.aborted)break;de(z=>z&&{...z,active:[L],rows:Be(z.rows,L,"active"),lastAt:Date.now()});let{exitCode:q,output:ie}=await vc({cwd:e,id:L,signal:E.signal,stdio:"pipe"});if(xc(q,ie)){h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let we=E.signal.aborted&&q!==0?"failed":bc(e,L,q,b),Qe=we==="captured"?void 0:we==="skipped"?Ef(ie)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Af(ie);R.push({id:L,outcome:we,detail:Qe}),de(z=>z&&{...z,active:[],done:z.done+1,rows:Be(z.rows,L,we==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(L){h({kind:"note",tone:"error",text:`Capture run failed: ${L.message}`})}finally{Ee.current=null,de(null),T(!1),Y(L=>L+1)}if(R.length===0)return;let x=R.filter(L=>L.outcome==="captured"),_=R.filter(L=>L.outcome==="skipped"),W=R.filter(L=>L.outcome==="failed"),V=u.length-R.length;h({kind:"note",tone:W.length?"warn":x.length?"ok":"info",text:[`\u2713 ${x.length} captured`,_.length?`\u2298 ${_.length} blocked`:"",W.length?`\u2717 ${W.length} broken`:"",V?`${V} not run (stopped)`:""].filter(Boolean).join(" ")+` ${R.length} run${w>0?` \xB7 ${w} held back`:""}`+_f(Lf(m,R),f).map(L=>`
|
|
@@ -471,42 +473,42 @@ ${L}`).join("")});let A=Of(_);if(A.length>0&&h({kind:"note",tone:"info",text:A.j
|
|
|
471
473
|
`)}),W.length>0){let L=Math.max(...W.map(q=>q.id.length));h({kind:"note",tone:"error",text:W.map(q=>`\u2717 ${q.id.padEnd(L)} ${gi(q.detail)}`).join(`
|
|
472
474
|
`)})}if(Fs(e,R.map(L=>({id:L.id,outcome:L.outcome,reason:L.detail,specSource:Tn(e,L.id)})),new Date().toISOString()),R.length===u.length&&W.length===0&&_.length===0&&us(d?.runLine),x.length>0){let L=x.map(ie=>ie.id);h({kind:"note",tone:"info",text:Ar(L.length)}),await ye(In(e,L),{display:"/screenshot verify",quietUser:!0});let q=Dr(e,L);q.length>0&&h({kind:"note",tone:"info",text:q.join(`
|
|
473
475
|
`)});return}let M=Mf({results:R,ids:u,articles:Ff(e,x.map(L=>L.id))});M&&Ae(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone)},[e,h,Ae,ye,us]),wa=J(u=>{let d=Fn(u);if(!d||pn(d)&&!d.refreshToken)return null;let c={...Oo(d.idToken)??{},...Oo(d.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),ka=J((u,d)=>{if(d){let c=ge(e);c&&(c.defaultProfile=u,Gg(c,e))}i(u),Ve(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${d?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),wa(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(c=>c+1)},[e,h,Ve,wa,Q]),ds=J((u,d,c)=>{gs(e,u,d,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Ve(),Kg(e,u)||(h({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),h({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:"}),h({kind:"note",tone:"info",text:uo(co(e)).join(`
|
|
474
|
-
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e),h({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,h,Ve,Xt]),ps=J(async u=>{let d;try{d=await sr(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(d.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=d.workspaces.filter(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),w=c.length>0?c:d.workspaces;if(w.length===1){let E=w[0],B=d.workspaces.length-w.length;h({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${B>0?" (skipped the API-documentation workspace)":""}.`}),ds(d.profile,d.projectId,E);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${w.length} available).`}),Q("/workspace")},[e,h,ds,Q]),hs=J((u,d)=>{ys(e,u,d.id,d.name),h({kind:"note",tone:"ok",text:`Project set to "${d.name??d.id}" (agent restarted).`}),Ve(),ps(u)},[e,h,Ve,ps]),ad=J(async u=>{let d;try{d=ut(e,u)}catch{return}if(!d.project.workspaceId){if(d.project.projectId){if(!d.project.projectName)try{let{projects:c}=await Jt(e,d.name),w=c.find(E=>E.id===d.project.projectId);w?.name&&
|
|
476
|
+
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e),h({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,h,Ve,Xt]),ps=J(async u=>{let d;try{d=await sr(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(d.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=d.workspaces.filter(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),w=c.length>0?c:d.workspaces;if(w.length===1){let E=w[0],B=d.workspaces.length-w.length;h({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${B>0?" (skipped the API-documentation workspace)":""}.`}),ds(d.profile,d.projectId,E);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${w.length} available).`}),Q("/workspace")},[e,h,ds,Q]),hs=J((u,d)=>{ys(e,u,d.id,d.name),h({kind:"note",tone:"ok",text:`Project set to "${d.name??d.id}" (agent restarted).`}),Ve(),ps(u)},[e,h,Ve,ps]),ad=J(async u=>{let d;try{d=ut(e,u)}catch{return}if(!d.project.workspaceId){if(d.project.projectId){if(!d.project.projectName)try{let{projects:c}=await Jt(e,d.name),w=c.find(E=>E.id===d.project.projectId);w?.name&&AS(e,d.name,{projectName:w.name})}catch{}await ps(d.name);return}try{let{projects:c}=await Jt(e,d.name);if(c.length===1){let w=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${w.name??w.id}".`}),hs(d.name,{id:w.id,name:w.name});return}if(c.length>1){let w=c.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wn({cursor:0,current:-1,rows:w,profile:d.name,environment:d.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,h,ps,hs,Q]),to=J(()=>{let u=Ce.current[0];if(!u)return;kt();let{plan:d,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${d.title} (${d.path})`});for(let B of d.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${B}`});d.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let w=at(d.oldContent,d.newContent,_e());h(w?{kind:"diff",added:w.added,removed:w.removed,lines:w.lines,hidden:w.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let E=Ce.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:E>1?`(l/p/s \xB7 la/pa/sa for all ${E} \u2014 anything else cancels)`:"(l/p/s \u2014 anything else cancels)"})):h({kind:"note",tone:"info",text:E>1?`Write ${d.path}? (y/n \xB7 ya/na for all ${E} \u2014 anything else cancels)`:`Write ${d.path}? (y/n \u2014 anything else cancels)`})},[h,_e,kt]),tr=J(()=>{if(Ce.current.length>0){to();return}let u=fn.current;fn.current=[],u.length>0?(h({kind:"note",tone:"info",text:`Publishing ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),ft(u)):Q("/pull")},[to,h,ft,Q]),ld=J(u=>{if(Ce.current.length===0)return!1;let d=u.trim(),c=d.toLowerCase(),w=Ce.current[0];if(w.mode==="conflict"){let B=ag(d);if(B){let m=Ce.current.splice(0),f=m.length;if(B==="local"){for(let $ of m)fn.current.push($.plan.path);h({kind:"note",tone:"info",text:`Keeping local for all ${f} \u2014 will publish ${f===1?"it":"them"} over the portal.`})}else if(B==="portal"){let $=0;for(let b of m)try{Xi({cwd:e,profileName:s},b.plan),$++}catch(R){h({kind:"note",tone:"error",text:`Take-portal failed for ${b.plan.path}: ${R.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${$} article${$===1?"":"s"} (local overwritten, sync base advanced).`})}else h({kind:"note",tone:"info",text:`Skipped all ${f} \u2014 still conflict${f===1?"":"s"}.`});return tr(),!0}if(c==="l"||c==="local")Ce.current.shift(),fn.current.push(w.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${w.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){Ce.current.shift();try{Xi({cwd:e,profileName:s},w.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${w.plan.path} (local overwritten, sync base advanced).`})}catch(m){h({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(c==="s"||c==="skip"||c==="n")Ce.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${w.plan.path} \u2014 still a conflict.`});else{let m=Ce.current.length;return Ce.current=[],fn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return tr(),!0}let E=lg(d);if(E){let B=Ce.current.splice(0);if(E==="skip")h({kind:"note",tone:"info",text:`Skipped all ${B.length} article${B.length===1?"":"s"}.`});else{let m=0;for(let f of B)try{Xi({cwd:e,profileName:s},f.plan),m++}catch($){h({kind:"note",tone:"error",text:`Pull failed for ${f.plan.path}: ${$.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${m} article${m===1?"":"s"} (sync base advanced).`})}return tr(),!0}if(c==="y"||c==="yes"){let B=Ce.current.shift().plan;try{Xi({cwd:e,profileName:s},B),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${B.path} (sync base advanced).`})}catch(m){h({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}}else if(c==="n"||c==="no"){let B=Ce.current.shift().plan;h({kind:"note",tone:"info",text:`Skipped ${B.path}.`})}else{let B=Ce.current.length;return Ce.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${B} article(s) left untouched).`}),!0}return tr(),!0},[e,s,tr,h]),ba=J(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let d=await Qi({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),w=d.entries.filter(B=>B.status==="conflict"&&B.path).map(B=>B.path);if(c){if(!w.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}w=[c]}if(w.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let E=[];for(let B of w)try{E.push({plan:await zg({cwd:e,profileName:s,relPath:B}),mode:"conflict"})}catch(m){h({kind:"note",tone:"error",text:`Could not load ${B} from Document360: ${m.message}`})}if(E.length===0)return;h({kind:"note",tone:"info",text:`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),Ce.current=E,fn.current=[],to()}catch(d){h({kind:"note",tone:"error",text:`Could not compute sync status: ${d.message}`})}},[e,s,h,to]),cd=J(u=>{let d=Wo.current;if(!d)return!1;if(Wo.current=null,kt(),u.trim()!==d.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:w}=Gc(e,d.targets);h({kind:"note",tone:w.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`});for(let E of w)h({kind:"note",tone:"error",text:` \u2717 ${E.path}: ${E.error}`});return d.hadDevhints&&(h({kind:"note",tone:"warn",text:Ds().join(`
|
|
475
477
|
`)}),Xt(ja())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
476
|
-
${iy}`}),Q("/init"),Ut(!1),!0},[e,h,Xt,kt,Q]),no=J(async u=>{let d=u.slice(1).trim().split(/\s+/),c=(d[0]??"").toLowerCase(),w=d.slice(1);if(Ut(!0),Cr(w)&&["write","lint","check","review","reorder"].includes(c)){let m=xr(e,s);if(m.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let f=$=>c==="write"?`/write ${Vh(w,$).join(" ")}`.trim():`/${c} ${[$,...w.filter(b=>b!=="--scope")].join(" ")}`.trim();if(m.length===1){no(f(m[0].token));return}bn({cursor:0,rows:m,run:$=>{no(f($))}});return}if(ln(c,w)){let m=c==="write"&&Rr(w).rewrite,f=c==="write"?oc(e,Zg(e),{rewrite:m}):xr(e,s);if(f.length>1){let $=w.filter(A=>A.startsWith("--")).join(" "),b=A=>A==="--blocked"?`/${c} --blocked${$?` ${$}`:""}`.trim():`/${c}${A?` ${c==="write"?`--scope ${A}`:A}`:""}${$?` ${$}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),R=f.reduce((A,M)=>A+M.count,0),x={token:"",label:c==="review"?`Everything \u2014 all ${R} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:m?`Everything \u2014 rewrite all ${R} planned articles`:`Everything \u2014 write all ${R} pending article${R===1?"":"s"}`,count:R},_=c==="review"?Br(e):[],W=_.length>0&&_.length<R?[{token:"--blocked",label:`Only what needs review \u2014 ${_.length} article${_.length===1?"":"s"} publishing is blocked on`,count:_.length}]:[],V=c==="write"?`Write which articles? (counts = ${m?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";bn({cursor:0,rows:[...W,x,...f],run:A=>{no(b(A))},title:V});return}}let E=async m=>{let f=yc(m);if(!yi(e)){await ye(Cc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(f.mode==="single"){await er([f.id],{runLine:[`/screenshot capture ${f.id}`,`/capture ${f.id}`]});return}if(f.mode==="failed"){let b=wc(e,jr(e).rows);if(b.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}await er(b);return}if(f.mode==="blocked"){let{blocked:b,rows:R}=jr(e);if(b.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}let x=gr(R.filter(_=>_.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(x>0?` If you haven't staged ${x===1?"it":"those "+x+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await er(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(f.mode==="all"||f.mode==="scope"){let b=f.mode==="scope"?f.scope:void 0,{ready:R,captured:x,blocked:_,rows:W}=jr(e,b),V=[...R,...x,...f.retryBlocked?_:[]];if(V.length===0&&_.length>0&&!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ae(`All ${_.length} shot${_.length===1?"":"s"} in scope ${_.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${M}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(V.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}if(!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",L=kc(W.filter(q=>q.state==="blocked"),M);L&&h({kind:"note",tone:"info",text:L})}let A=f.mode==="scope"?[`/screenshot capture ${f.scope}`,`/capture ${f.scope}`]:["/screenshot capture --all","/capture --all"];await er(V,{runLine:A,...f.retryBlocked?{}:{heldBackBlocked:W.filter(M=>M.state==="blocked")}});return}let $=Tf(Ie(e));if($.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}kn({cursor:0,rows:$,title:"Capture screenshots \u2014 pick what to shoot:"})},B=async()=>{let m=await xo();m.kind==="forward-to-agent"&&m.prompt&&await ye(m.prompt,{display:m.display,quietUser:!0}),aa()};switch(c){case"help":Cn({tab:0,scroll:0});return;case"exit":case"quit":dt.current?.close(),r();return;case"clear":Ve(),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current},Ut(!1),kt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let m;try{m=ut(e,s)}catch(f){h({kind:"note",tone:"error",text:f.message});return}h({kind:"note",tone:"info",text:`Profile "${m.name}" \u2192 ${m.connection.name} (${m.connection.apiUrl})${m.production?" \u26A0 PRODUCTION":""}`}),I(!0);try{let f=await
|
|
478
|
+
${iy}`}),Q("/init"),Ut(!1),!0},[e,h,Xt,kt,Q]),no=J(async u=>{let d=u.slice(1).trim().split(/\s+/),c=(d[0]??"").toLowerCase(),w=d.slice(1);if(Ut(!0),Cr(w)&&["write","lint","check","review","reorder"].includes(c)){let m=xr(e,s);if(m.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let f=$=>c==="write"?`/write ${Vh(w,$).join(" ")}`.trim():`/${c} ${[$,...w.filter(b=>b!=="--scope")].join(" ")}`.trim();if(m.length===1){no(f(m[0].token));return}bn({cursor:0,rows:m,run:$=>{no(f($))}});return}if(ln(c,w)){let m=c==="write"&&Rr(w).rewrite,f=c==="write"?oc(e,Zg(e),{rewrite:m}):xr(e,s);if(f.length>1){let $=w.filter(A=>A.startsWith("--")).join(" "),b=A=>A==="--blocked"?`/${c} --blocked${$?` ${$}`:""}`.trim():`/${c}${A?` ${c==="write"?`--scope ${A}`:A}`:""}${$?` ${$}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),R=f.reduce((A,M)=>A+M.count,0),x={token:"",label:c==="review"?`Everything \u2014 all ${R} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:m?`Everything \u2014 rewrite all ${R} planned articles`:`Everything \u2014 write all ${R} pending article${R===1?"":"s"}`,count:R},_=c==="review"?Br(e):[],W=_.length>0&&_.length<R?[{token:"--blocked",label:`Only what needs review \u2014 ${_.length} article${_.length===1?"":"s"} publishing is blocked on`,count:_.length}]:[],V=c==="write"?`Write which articles? (counts = ${m?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";bn({cursor:0,rows:[...W,x,...f],run:A=>{no(b(A))},title:V});return}}let E=async m=>{let f=yc(m);if(!yi(e)){await ye(Cc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(f.mode==="single"){await er([f.id],{runLine:[`/screenshot capture ${f.id}`,`/capture ${f.id}`]});return}if(f.mode==="failed"){let b=wc(e,jr(e).rows);if(b.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}await er(b);return}if(f.mode==="blocked"){let{blocked:b,rows:R}=jr(e);if(b.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}let x=gr(R.filter(_=>_.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(x>0?` If you haven't staged ${x===1?"it":"those "+x+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await er(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(f.mode==="all"||f.mode==="scope"){let b=f.mode==="scope"?f.scope:void 0,{ready:R,captured:x,blocked:_,rows:W}=jr(e,b),V=[...R,...x,...f.retryBlocked?_:[]];if(V.length===0&&_.length>0&&!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ae(`All ${_.length} shot${_.length===1?"":"s"} in scope ${_.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${M}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(V.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}if(!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",L=kc(W.filter(q=>q.state==="blocked"),M);L&&h({kind:"note",tone:"info",text:L})}let A=f.mode==="scope"?[`/screenshot capture ${f.scope}`,`/capture ${f.scope}`]:["/screenshot capture --all","/capture --all"];await er(V,{runLine:A,...f.retryBlocked?{}:{heldBackBlocked:W.filter(M=>M.state==="blocked")}});return}let $=Tf(Ie(e));if($.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}kn({cursor:0,rows:$,title:"Capture screenshots \u2014 pick what to shoot:"})},B=async()=>{let m=await xo();m.kind==="forward-to-agent"&&m.prompt&&await ye(m.prompt,{display:m.display,quietUser:!0}),aa()};switch(c){case"help":Cn({tab:0,scroll:0});return;case"exit":case"quit":dt.current?.close(),r();return;case"clear":Ve(),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current},Ut(!1),kt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let m;try{m=ut(e,s)}catch(f){h({kind:"note",tone:"error",text:f.message});return}h({kind:"note",tone:"info",text:`Profile "${m.name}" \u2192 ${m.connection.name} (${m.connection.apiUrl})${m.production?" \u26A0 PRODUCTION":""}`}),I(!0);try{let f=await QR(m.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>h({kind:"note",tone:"info",text:b})),$=JR(m.name,f);if(ZR($),await Ra($,m.name,b=>h({kind:"note",tone:"info",text:b})),h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${m.name}" as ${bs($)}`}),await ad(s),Go.current){let b=Go.current;Go.current=null;let R=Ue(e,s);R.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${b}.`}),Q(b)):(h({kind:"note",tone:"warn",text:`${R.reason} (then ${b}.)`}),Q("/login"),Go.current=b)}else qo.current&&(qe(qo.current,"\u21E5 tab to re-send your last prompt\u2026"),qo.current=null)}catch(f){h({kind:"note",tone:"error",text:`Login failed: ${f.message}`})}finally{I(!1),Y(f=>f+1)}return}case"allow-prod":{let m=!1;try{m=ut(e,s).production}catch{}if(!m){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ht.current=!0,Ve(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let m=dc(w.join(" ")),f=Et.current.uuid;if(!f){if(!m){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}na.current=m,mn(m),To(`${qi} ${m}`),h({kind:"note",tone:"ok",text:`Session will be named "${m}" once it starts.`});return}if(!m){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let $=Et.current.firstPrompt??"";qg($,e).then(b=>{b?(qe(`/rename ${b}`),h({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}uS(f,m),mn(m),To(`${qi} ${m}`),h({kind:"note",tone:"ok",text:`Session renamed to "${m}".`});return}case"profile":{let m=w[0],f=ge(e);if(!m){let $=Object.entries(f?.profiles??{});if($.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=$.map(([_,W])=>({name:_,env:W.connection?.environment??"custom",prod:W.production===!0,who:wa(_)})),R=s??f?.defaultProfile,x=Math.max(0,b.findIndex(_=>_.name===R));qn({cursor:x,current:x,rows:b});return}if(m==="add"){let $=pc(e,w[1],w[2]);if($){h({kind:"note",tone:"error",text:$});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${w[1]}" created (environment: ${w[2]??w[1]}).`}),ka(w[1],!0);return}if(!f?.profiles?.[m]){h({kind:"note",tone:"error",text:`Unknown profile "${m}". Create it: /profile add ${m} <environment>`});return}ka(m,!0);return}case"doctor":await Tr(w,{cwd:e,version:o});return;case"style-guide":{let m=await Si(w,{cwd:e,profileName:s});m.kind==="clear"?(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})):m.kind==="forward-to-agent"&&((await ye(m.prompt,{display:m.display,quietUser:!0})).producedNothing||h({kind:"note",tone:"info",text:fm().join(`
|
|
477
479
|
`)})),Y(f=>f+1);return}case"genre":{let m=ge(e)?.appType??null;(await Pi(w,{cwd:e})).kind==="clear"&&(ge(e)?.appType??null)!==m&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Wt.current=!(ge(e)?.appType??Yg(e))}catch{}Y($=>$+1);return}case"roadmap":{if(w[0]?.toLowerCase()==="done"){let m=Ei(e,w.slice(1).join(" ").trim());h({kind:"note",tone:m.ok?"ok":"warn",text:m.line}),Y(f=>f+1);return}h({kind:"note",tone:"info",text:nu(e).join(`
|
|
478
480
|
`)});return}case"mcp":await Is(w);return;case"init":{if(ge(e)){let f=Zt(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Xg().join("|")}> then /profile <name> (the environment lives on the profile, not the login).`," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
|
|
479
|
-
`)}),f&&h({kind:"note",tone:"warn",text:`\u26A0 ${f.why} \u2014 ${f.cmd} moves this repo.`});return}let m=[...Xg(),...
|
|
481
|
+
`)}),f&&h({kind:"note",tone:"warn",text:`\u26A0 ${f.why} \u2014 ${f.cmd} moves this repo.`});return}let m=[...Xg(),...wS().filter(f=>Qg(f))].map(f=>({name:f,apiUrl:kS(f).apiUrl,note:Qg(f)?"being retired":null}));Gn({cursor:0,rows:m});return}case"resume":{let m=w.join(" ").trim(),f=cS(e).filter(R=>R.uuid!==Et.current.uuid);if(!m){if(!f.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}xn({query:"",cursor:0,sessions:f});return}let $=lS(e,m);if(!$){h({kind:"note",tone:"error",text:`No session matches "${m}".`});return}Ve($.uuid),Et.current={uuid:$.uuid,firstPrompt:$.firstPrompt,titleFired:!0},mn($.name),Cu($.uuid),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current};let b=gu(e,$.uuid);for(let R of b)h(R);h({kind:"note",tone:"ok",text:b.length?`Resumed "${$.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${$.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let m=w.join(" ").trim(),f;try{f=await sr(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!m){let b=f.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,b.findIndex(x=>x.id===f.current));Vn({cursor:R,current:R,rows:b,profile:f.profile,projectId:f.projectId,projectName:f.projectName,environment:f.environment});return}let $=xa(f.workspaces,m);if(!$){h({kind:"note",tone:"error",text:`No workspace matches "${m}".`});return}ds(f.profile,f.projectId,$);return}case"project":{let m=w.join(" ").trim(),f;try{f=await Jt(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!m){let b=f.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=b.findIndex(x=>x.id===f.current);wn({cursor:Math.max(0,R),current:R,rows:b,profile:f.profile,environment:f.environment});return}let $=Ca(f.projects,m);if(!$){h({kind:"note",tone:"error",text:`No project matches "${m}". Available: ${f.projects.map(b=>b.name??b.id).join(", ")}`});return}hs(f.profile,$);return}case"logout":{let m;try{m=ut(e,s).name}catch($){h({kind:"note",tone:"error",text:$.message});return}let f=oS(m);rS(e,m),Ve(),Y($=>$+1),h({kind:"note",tone:f?"ok":"info",text:f?`\u2713 Signed out of "${m}" and cleared its project/workspace selection.`:`Profile "${m}" was not signed in. Cleared any project/workspace selection.`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(vl(w)){let x=Ft("publish");x&&h({kind:"note",tone:"info",text:x}),await no(`/push ${w.join(" ")}`.trim());return}if(!Jn(u.trim()))return;let m=Ft("publish");m&&h({kind:"note",tone:"info",text:m});let f=w.find(x=>!x.startsWith("--")),$={skipReview:w.includes(it),skipStyle:w.includes(sy)};je("Checking what is waiting to go live\u2026");let b;try{b=await xl(e,s,f)}catch(x){h({kind:"note",tone:"error",text:`Could not check Document360: ${x.message}`});return}finally{je(null)}if(b.length===0){let x=Cl(e,s,f);for(let _ of x.lines)h({kind:"note",tone:_.startsWith("\u2713")?"ok":"info",text:_});x.ahead>0&&Q(Ne("/push","",f));return}let R=Tu(e,b.map(x=>x.path),{allowUnreviewed:$.skipReview,allowStyleErrors:$.skipStyle});if(!R.clear){for(let x of Eu(R,b.length,f))h({kind:"note",tone:"warn",text:x});Q(Ne("/review","--blocked --fix",f));return}h({kind:"note",tone:"info",text:`${b.length} draft${b.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Kn({cursor:0,rows:b,opts:$});return}case"push":{if(!Jn(u.trim()))return;let m=w.includes(it),f=w.includes(sy);if(w.includes("--screenshots")||w.includes("--shots")){let x=w.find(A=>!A.startsWith("--")),_=Ie(e),W=Ks(_,x);if(W.length===0){h({kind:"note",tone:"info",text:x?`No captured screenshots in ${x} \u2014 /publish --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."});return}let V=zs(_);V&&h({kind:"note",tone:"warn",text:V}),h({kind:"note",tone:"info",text:`Re-saving ${W.length} article${W.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await ft(W,0,{skipReview:m,skipStyle:f,scope:Ne("","--screenshots",x).trim()});return}if(w[0]==="--related"&&w[1]){let x=await ni(e,s,w[1].replace(/\\/g,"/"));if(x.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await ft(x,0,{skipReview:m,skipStyle:f,scope:`--related ${w[1]}`});return}let $=w.filter(x=>!x.startsWith("--"));if($[0]){await ya($[0],{skipReview:m,skipStyle:f});return}let b=w.includes("--all"),R=w.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let x=await Qi({cwd:e,profileName:s}),{clean:_,conflicts:W}=An(x.entries),V=b&&R&&W.length>0,A=ei(x.entries);if(A>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${A} article${A===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.`}),W.length>0&&!V&&h({kind:"note",tone:"warn",text:En(W.length)}),_.length===0&&!V){let M=yo(e,s);if(M&&h({kind:"note",tone:"info",text:M}),W.length>0){Q("/resolve");return}h({kind:"note",tone:"ok",text:A>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let L=x.counts["unknown-base"]??0;L>0&&h({kind:"note",tone:"info",text:`(${L} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),je("Reconciling structure on Document360 (order + related articles)\u2026");try{let q=await Su({cwd:e,profileName:s,onRateLimit:Qe=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(Qe.waitMs/1e3)}s\u2026`)}),ie=ry(await oy({cwd:e,profileName:s})),we=Pu(q);we?h({kind:"note",tone:we.startsWith("\u26A0")?"warn":"info",text:we}):q.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${q.skipped}`}),ie&&h({kind:"note",tone:"info",text:ie}),q.failures?.length?Q("/structure"):(h({kind:"note",tone:"ok",text:we||ie?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(we||ie)&&Q("/structure"))}catch(q){h({kind:"note",tone:"warn",text:`Structure sync failed: ${q.message}`})}finally{je(null)}return}if(b){let M=(V?[..._,...W]:_).map(L=>L.path);await ft(M,V?0:W.length,{skipReview:m,skipStyle:f});return}Yn({cursor:0,rows:yh(_,W),conflicts:W.length})}catch(x){h({kind:"note",tone:"error",text:`Could not compute sync status: ${x.message}`}),h({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Jn(u.trim()))return;await ba(w.find(m=>!m.startsWith("--")));return}case"preview":{let m=w.join(" ").trim();if(!m){let $=[];try{$=Object.keys(Kg(e,ut(e,s).name)?.articles??{})}catch{}if($.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}$n({query:"",cursor:0,paths:$});return}let f=zR(m)?m:xu(e,m);if(Ao(f)){try{h({kind:"preview",name:Qr(f),text:cy(zi(f,"utf8"))})}catch($){h({kind:"note",tone:"error",text:`Could not read ${f}: ${$.message}`})}return}if(GS.test(m)){try{let $=ut(e,s),b={profile:$.name,connection:$.connection},R=$.project.projectId??tS(b),x=await nS(b,R,m);h({kind:"preview",name:x.title??m,text:x.content??"*(article has no content)*"})}catch($){h({kind:"note",tone:"error",text:`Could not fetch article: ${$.message}`})}return}h({kind:"note",tone:"error",text:`"${m}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let m=w[0]?.trim();if(!m){let R=fi(Du(e));yn({cursor:R,current:R});return}let{lines:f,changed:$,effective:b}=Pr(e,m);for(let R of f)h({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});$&&(Vu(R=>R+1),dt.current?.setModel(b));return}case"verbose":{let m=w[0]?.trim().toLowerCase(),f=m==="on"?!0:m==="off"?!1:!Zr.current;Zr.current=f;try{pS({...Vg(),verboseTranscript:f})}catch{h({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}h({kind:"note",tone:"ok",text:f?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:m,run:f}=Ll(w),$=vS(e,s);if($.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=Ol($,m);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${m}". (${$.length} are tracked overall.)`});return}let R=Ru(b),x=3,_=`/convert${m?` --scope ${m}`:""} --run`,W=No(e,"light");if(!f){let A=Jg({files:_l(e,b),op:"convert",model:W.model}),M=m?`Scope: ${m} (${b.length} of ${$.length} tracked)
|
|
480
482
|
`:"",L=`
|
|
481
483
|
Model: ${W.model}${W.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:M+Fl(R,A,x).join(`
|
|
482
|
-
`)+L}),Q(_);return}Tt.current=Date.now(),Bt(0),T(!0);let V=new AbortController;Ee.current=V,de({verb:"Converting",total:R.length,done:0,active:[],rows:_n(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles
|
|
484
|
+
`)+L}),Q(_);return}Tt.current=Date.now(),Bt(0),T(!0);let V=new AbortController;Ee.current=V,de({verb:"Converting",total:R.length,done:0,active:[],rows:_n(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${R.length} batches (\u2264${x} agents at once) on ${W.model}\u2026 (esc to stop)`});try{for await(let A of Do({cwd:e,partitions:R,promptFor:Ml,concurrency:x,profileName:s,allowProdWrites:Ht.current,model:W.model,signal:V.signal}))if(A.type==="partition_status")A.status==="running"?de(M=>M&&{...M,active:[...M.active,A.label],rows:Be(M.rows,A.label,"active"),lastAt:Date.now()}):de(M=>M&&{...M,active:M.active.filter(L=>L!==A.label),done:M.done+1,rows:Be(M.rows,A.label,A.status==="done"?"done":"failed"),lastAt:Date.now()});else if(A.type==="partition_event")de(M=>{if(!M)return M;let L={...M,lastAt:Date.now()};return A.event.type==="tool"?L.tools=M.tools+1:A.event.type==="text"&&(L.chars=M.chars+A.event.delta.length),L});else if(A.type==="run_done"){zt(ie=>ie+A.totalCostUsd),Kt(ie=>ie+A.results.reduce((we,Qe)=>we+Qe.outputTokens,0));let M=A.aborted?"Stopped. ":"",L=t.kind==="api"?"api":"subscription",q=$t(A,"The conversion");h({kind:"note",tone:q||A.aborted?"warn":A.ok?"ok":"warn",text:q?q.join(`
|
|
483
485
|
`):M+Wl(A.results,R,L).join(`
|
|
484
486
|
`)}),q&&Q("/doctor")}}catch(A){h({kind:"note",tone:"error",text:`Convert run failed: ${A.message}`})}finally{Ee.current=null,de(null),T(!1),Y(A=>A+1)}return}case"write":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=Zg(e);if(m.length===0){h({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:f,path:$,preview:b,concurrency:R,rewrite:x}=Rr(w);if(!$&&!b&&!(ge(e)?.appType??Yg(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${m.length} articles would be written generically.
|
|
485
487
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
486
488
|
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ue(Di.options.map(z=>({cmd:z.cmd,desc:z.desc}))),zn(Di.title);return}let{docsDir:_,targets:W,reason:V,rewriting:A}=pi(e,m,{scope:f,path:$,rewrite:x});if(W.length===0){h({kind:"note",tone:"warn",text:V??"Nothing to write."});return}A&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${W.length} already-written article${W.length===1?"":"s"} (overwrites them; git has your baseline).`});let M=Ru(W),L=Kl(R),q=No(e,"standard"),ie=!!$;if(b&&!ie){let z=Jg({files:Xl(e,m,W),op:"write",model:q.model}),me=f?`Scope: ${f} (${W.length} pending)
|
|
487
489
|
`:"",Me=`
|
|
488
490
|
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:me+Jl(M,z,L).join(`
|
|
489
|
-
`)+Me}),Q(`/write${f?` --scope ${f}`:""}`);return}Tt.current=Date.now(),Bt(0),T(!0);let we=new AbortController;Ee.current=we,de({verb:"Writing",total:M.length,done:0,active:[],rows:_n(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Writing ${W.length} article${W.length===1?"":"s"}
|
|
491
|
+
`)+Me}),Q(`/write${f?` --scope ${f}`:""}`);return}Tt.current=Date.now(),Bt(0),T(!0);let we=new AbortController;Ee.current=we,de({verb:"Writing",total:M.length,done:0,active:[],rows:_n(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Writing ${W.length} article${W.length===1?"":"s"} in ${M.length} batch${M.length===1?"":"es"} (\u2264${L} agents at once) on ${q.model}${q.forced?" (forced)":""}\u2026 (esc to stop)`});let Qe=new Set;try{for await(let z of Do({cwd:e,partitions:M,promptFor:me=>Ql(me,_,{rewrite:A||ie}),concurrency:L,profileName:s,allowProdWrites:Ht.current,model:q.model,signal:we.signal}))if(z.type==="partition_status")z.status==="running"?de(me=>me&&{...me,active:[...me.active,z.label],rows:Be(me.rows,z.label,"active"),lastAt:Date.now()}):de(me=>me&&{...me,active:me.active.filter(Me=>Me!==z.label),done:me.done+1,rows:Be(me.rows,z.label,z.status==="done"?"done":"failed"),lastAt:Date.now()});else if(z.type==="partition_event"){let me=null;if(z.event.type==="tool"){let Me=Rg(z.event.name,z.event.input,M[z.index]?.paths??[]);Me&&!Qe.has(Me)&&(Qe.add(Me),me=z.label)}de(Me=>{if(!Me)return Me;let bt={...Me,lastAt:Date.now()};return z.event.type==="tool"?bt.tools=Me.tools+1:z.event.type==="text"&&(bt.chars=Me.chars+z.event.delta.length),me&&(bt.rows=Cg(bt.rows,me)),bt})}else if(z.type==="run_done"){zt(Fe=>Fe+z.totalCostUsd),Kt(Fe=>Fe+z.results.reduce((st,Sn)=>st+Sn.outputTokens,0));let me=z.aborted?"Stopped. ":"",Me=t.kind==="api"?"api":"subscription",bt=$t(z,"The write");if(h({kind:"note",tone:bt||z.aborted?"warn":z.ok?"ok":"warn",text:bt?bt.join(`
|
|
490
492
|
`):me+Zl(z.results,M,Me,f??$).join(`
|
|
491
|
-
`)}),bt){Q("/doctor");continue}let hd=_s(z);if(hd&&h({kind:"note",tone:"warn",text:hd}),!z.aborted&&z.ok)try{let Fe=(Qe.size>0?[...Qe]:W).map(st=>`${_}/${st}`);jo(e,Fe,{writtenCap:
|
|
493
|
+
`)}),bt){Q("/doctor");continue}let hd=_s(z);if(hd&&h({kind:"note",tone:"warn",text:hd}),!z.aborted&&z.ok)try{let Fe=(Qe.size>0?[...Qe]:W).map(st=>`${_}/${st}`);jo(e,Fe,{writtenCap:ES,reviewedCap:0,checkedCap:0})}catch{}let ro=z.aborted?[]:Sr(e,_,W),fd=ec(ro);fd&&h({kind:"note",tone:"warn",text:fd});let so=z.aborted||w.includes("--skip-style")?null:tc(ro);if(so){let Fe=so.errors.length,st=await cs({partitions:so.partitions,promptFor:so.promptFor,concurrency:bo,verb:"Fixing",doneNoun:"fixed",headline:`${Fe} style error${Fe===1?"":"s"} in ${so.articles} of the new article${so.articles===1?"":"s"} \u2014 fixing now, one pass`});if(st.covered.length>0)try{jo(e,st.covered,Ye("lint"))}catch{}ro=Sr(e,_,W);let Sn=nc(Fe,ro);h({kind:"note",tone:Sn[0].startsWith("\u2713")?"ok":"warn",text:Sn.join(`
|
|
492
494
|
`)})}if(!z.aborted&&z.ok){let Fe=f??$??"",st=Fe?` ${Fe}`:"",Sn=ro.some(va=>va.severity==="error"),md=Fe?"/publish":"/publish --all",Ey=Fe?`/screenshot author ${Fe}`:"/screenshot author --all";Ae(Sn?`Written, but ${ro.filter(va=>va.severity==="error").length} style error(s) are still unfixed. /lint${st} --fix retries them, then /review${st} --fix for editorial quality, then ${md}.`:`Written. I\u2019d run /review${st} --fix next \u2014 editorial review that applies its fixes \u2014 then ${md} pushes the drafts up (add ${Ey} first if you want images).`,{kind:"cmd",cmd:Sn?`/lint${st} --fix`:`/review${st} --fix`,reason:""})}}}catch(z){h({kind:"note",tone:"error",text:`Write run failed: ${z.message}`})}finally{Ee.current=null,de(null),T(!1),Y(z=>z+1)}return}case"draft":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:m,looseDocs:f}=rc(e);if(m.length===0&&f===0){h({kind:"note",tone:"info",text:ic});return}let $=w.join(" ").trim();if(!$&&m.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
493
495
|
${m.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
|
|
494
496
|
`)}`}),ue(m.map(x=>`/draft ${x.name}`));return}let b="",R;if($){let x=sc(m,$);x?b=x:R=$}else b=m[0]?.name??"";await ye(hi(b,R),{display:$?`/draft ${$}`:"/draft",quietUser:!0});return}case"pull":{if(!Jn(u.trim()))return;let m=w.find(f=>f.startsWith("--"));try{if(m==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),R=await Qi({cwd:e,profileName:s});h({kind:"note",tone:"info",text:si(R,Date.now()-b).join(`
|
|
495
|
-
`)});return}if(m==="--baseline"){let b=w.find(W=>!W.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await
|
|
497
|
+
`)});return}if(m==="--baseline"){let b=w.find(W=>!W.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await mS({cwd:e,profileName:s,relPaths:R?[R]:void 0}),_=R?{rebaselined:[],skipped:[]}:await gS({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&_.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${x.baselined.length} article${x.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),_.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&h({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
|
|
496
498
|
${x.skipped.map(W=>` - ${W.path} (${W.reason})`).join(`
|
|
497
|
-
`)}`}),Y(W=>W+1);return}if(m==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await
|
|
498
|
-
`)});return}if(m){h({kind:"note",tone:"error",text:`Unknown option: ${m} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let f=w[0];if(f){let b=await zg({cwd:e,profileName:s,relPath:f.replace(/\\/g,"/")});Ce.current=[{plan:b,mode:b.overwritesLocalChanges?"conflict":"pull"}],fn.current=[],to();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await Nl({cwd:e,profileName:s});for(let b of jl($))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1)}catch(f){h({kind:"note",tone:"error",text:`Pull failed: ${f.message}`})}return}case"scope":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=
|
|
499
|
+
`)}`}),Y(W=>W+1);return}if(m==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await fS({cwd:e,profileName:s}),R=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];R?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&x.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&x.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&x.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:R?"ok":"warn",text:x.join(`
|
|
500
|
+
`)});return}if(m){h({kind:"note",tone:"error",text:`Unknown option: ${m} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let f=w[0];if(f){let b=await zg({cwd:e,profileName:s,relPath:f.replace(/\\/g,"/")});Ce.current=[{plan:b,mode:b.overwritesLocalChanges?"conflict":"pull"}],fn.current=[],to();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await Nl({cwd:e,profileName:s});for(let b of jl($))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1)}catch(f){h({kind:"note",tone:"error",text:`Pull failed: ${f.message}`})}return}case"scope":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=yS(e);if(m.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Xn({cursor:0,rows:m.map(f=>({...f,checked:f.recommended}))});return}case"audit":{if(w[0]==="--auto"){let f=ge(e);if(!f){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=w[1]!=="off";Gg({...f,autoAudit:$},e),h({kind:"note",tone:"ok",text:$?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let m=await br();m.kind==="forward-to-agent"&&m.prompt&&((await ye(m.prompt,{display:m.display,quietUser:!0})).producedNothing||(Hr(e,s),Y($=>$+1)));return}case"lint":case"check":{let m=Ft(c);m&&h({kind:"note",tone:"info",text:`\u2192 ${m}`});let f=w.find(R=>!R.startsWith("--")),$=f?` ${f}`:"",b=Ji({cwd:e,scope:f});if(w.includes("--fix")){let R=ql(e,w,b);if(!R){h({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}if(R.kind==="partitioned"){let V=await cs({partitions:R.partitions,promptFor:R.promptFor,concurrency:bo,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${R.findings} issue${R.findings===1?"":"s"} across ${R.articles} article${R.articles===1?"":"s"} in ${R.partitions.length} batches (\u2264${bo} at once)`});if(V.covered.length>0)try{jo(e,V.covered,Ye("lint"))}catch{}if(V.aborted){let A=$r({cwd:e,after:Ji({cwd:e,scope:f}).filter(M=>!M.baselined),scope:f,aborted:!0});Ae(A.text,{kind:"cmd",cmd:A.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${R.findings} doc issue${R.findings===1?"":"s"}\u2026`});let V=ny(e,f);await ye(R.prompt,{display:R.display,quietUser:!0});try{jo(e,V,Ye("lint"))}catch{}}let x=Ji({cwd:e,scope:f}).filter(V=>!V.baselined),_=Math.max(0,R.findings-x.length);h({kind:"note",tone:x.some(V=>V.severity==="error")?"warn":"ok",text:x.length===0?`\u2713 Lint: all ${R.findings} issue${R.findings===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${_} of ${R.findings}.`,"",...vr(x)].join(`
|
|
499
501
|
`)});let W=$r({cwd:e,after:x,before:R.findings,scope:f});Ae(W.text,{kind:"cmd",cmd:W.cmd,reason:""});return}if(h({kind:"note",tone:b.length===0?"ok":"warn",text:vr(b,{full:w.includes("--full"),baselined:w.includes("--baselined")}).join(`
|
|
500
502
|
`)}),b.length>0){let R=ti(e,f)===0?"; /publish --all publishes as-is":"";Ae(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /lint${$} --fix has the agent fix them in place (or /review${$} --fix for the full editorial pass${R}).`,{kind:"cmd",cmd:`/lint${$} --fix`,reason:""})}return}case"structure":{let m=Wr(e,s);if(m.length===0){h({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}h({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...m].join(`
|
|
501
503
|
`)});return}case"reorder":{let m=eu(e,w);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=await ye(m.prompt,{display:m.display,quietUser:!0}),$=Ct(e,{text:"Reordered locally \u2014 /publish --all syncs the new order to Document360.",cmd:"/publish --all"},"Reordered locally. ");Ko(f,$.text,{kind:"cmd",cmd:$.cmd,reason:""});return}case"review":{let m=Jc(e,w);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=w.includes("--fix"),$=w.find(x=>!x.startsWith("--")),b=f?ny(e,$):[],R=m.kind==="partitioned"?await Ry(m,f):await ye(m.prompt,{display:m.display,quietUser:!0});if("aborted"in R&&R.aborted){let x=Ne("/review","--fix",$);Ae(`Stopped \u2014 the partitions that finished are saved. ${x} picks up the rest${$?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:x,reason:""},"warn");return}if(m.kind!=="partitioned"&&f&&!R.producedNothing)try{jo(e,b,Ye("review"))}catch{}if(f){let x=f&&!R.producedNothing?Ji({cwd:e,scope:$}).filter(W=>!W.baselined&&W.severity==="error"):[];if(x.length>0){let W=new Set(x.map(V=>V.path)).size;h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${x.length} style error${x.length===1?"":"s"} in ${W} article${W===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Ko(R,`Editor applied its fixes, but ${x.length} style error${x.length===1?"":"s"} remain. /lint${$?` ${$}`:""} --fix clears them \u2014 it costs nothing to find them and one pass to correct.`,{kind:"cmd",cmd:`/lint${$?` ${$}`:""} --fix`,reason:""});return}let _=Ct(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish${$?"":" --all"} pushes them up (or /lint${$?` ${$}`:""} for an instant no-token re-scan first).`,cmd:$?"/publish":"/publish --all"},"\u2713 Editor applied its fixes to this scope. ",$);Ko(R,_.text,{kind:"cmd",cmd:_.cmd,reason:""})}else{let x=$?` ${$}`:"",_=ti(e,$)===0&&gl(e,$)===0?`; /publish${$?"":" --all"} publishes as-is`:"";Ko(R,`The review listed issues above. /review${x} --fix lets the editor apply them all (or /lint${x} --fix for just the deterministic ones${_}).`,{kind:"cmd",cmd:`/review${x} --fix`,reason:""})}return}case"capture-setup":{await B();return}case"devhints":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:uo(co(e)).join(`
|
|
502
|
-
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ye(Pl(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Sc(e)===0){h({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 ye(Pc(),{display:"/inbox",quietUser:!0});return}case"share":{let m=ge(e);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=w[0]?.trim().toLowerCase();if(f==="status"){for(let b of wi(e,m))h({kind:"note",tone:b.tone,text:b.text});return}if(f==="on"||f==="off"){for(let b of Tc(e,m,f==="on"))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1);return}if(f){h({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let $=await ki(e,m);for(let b of $.lines)h({kind:"note",tone:b.tone,text:b.text});$.changed&&Y(b=>b+1);return}case"feedback":{let m=ty(e),f="";try{f=Ao(m)?zi(m,"utf8"):""}catch{f=""}if(!/^## /m.test(f)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let $=await hu(f.trim());h({kind:"note",tone:$?"ok":"warn",text:$?"\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 ${m} and copy it manually.`}),$&&da(null);return}case"document":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:m,skipReview:f,what:$}=lc(w);if(!$&&ac(e)===0){h({kind:"note",tone:"info",text:uc});return}let b=`/document${$?` ${$}`:""}${m?" --push":""}`,R=await ye(cc($),{display:b,quietUser:!0});m&&!R.producedNothing&&await rd({skipReview:f});return}case"catch-up":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Jn(u.trim()))return;let{push:m,skipReview:f}=Dc(w);for(let V of await Ac(e))h({kind:"note",tone:V.tone,text:V.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let $=await Lc({cwd:e,profileName:s});for(let V of Oc($))h({kind:"note",tone:V.startsWith("\u2713")?"ok":V.startsWith("\u2139")?"info":"warn",text:V});let b=Nc(e);for(let V of jc(b))h({kind:"note",tone:V.tone,text:V.text});let R=Lr(Ln(e));h({kind:"note",tone:"info",text:R?`Catching up on ${R}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"});let x=
|
|
504
|
+
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ye(Pl(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Sc(e)===0){h({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 ye(Pc(),{display:"/inbox",quietUser:!0});return}case"share":{let m=ge(e);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=w[0]?.trim().toLowerCase();if(f==="status"){for(let b of wi(e,m))h({kind:"note",tone:b.tone,text:b.text});return}if(f==="on"||f==="off"){for(let b of Tc(e,m,f==="on"))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1);return}if(f){h({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let $=await ki(e,m);for(let b of $.lines)h({kind:"note",tone:b.tone,text:b.text});$.changed&&Y(b=>b+1);return}case"feedback":{let m=ty(e),f="";try{f=Ao(m)?zi(m,"utf8"):""}catch{f=""}if(!/^## /m.test(f)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let $=await hu(f.trim());h({kind:"note",tone:$?"ok":"warn",text:$?"\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 ${m} and copy it manually.`}),$&&da(null);return}case"document":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:m,skipReview:f,what:$}=lc(w);if(!$&&ac(e)===0){h({kind:"note",tone:"info",text:uc});return}let b=`/document${$?` ${$}`:""}${m?" --push":""}`,R=await ye(cc($),{display:b,quietUser:!0});m&&!R.producedNothing&&await rd({skipReview:f});return}case"catch-up":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Jn(u.trim()))return;let{push:m,skipReview:f}=Dc(w);for(let V of await Ac(e))h({kind:"note",tone:V.tone,text:V.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let $=await Lc({cwd:e,profileName:s});for(let V of Oc($))h({kind:"note",tone:V.startsWith("\u2713")?"ok":V.startsWith("\u2139")?"info":"warn",text:V});let b=Nc(e);for(let V of jc(b))h({kind:"note",tone:V.tone,text:V.text});let R=Lr(Ln(e));h({kind:"note",tone:"info",text:R?`Catching up on ${R}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"});let x=TS(e),_=await ye(Ic(b),{display:`/catch-up${m?" --push":""}`,quietUser:!0}),W=Ai(e,x);m&&!_.producedNothing?await rd({skipReview:f}):W.cta&&Ko(_,W.cta.text,{kind:"cmd",cmd:W.cta.cmd,reason:""});return}case"comments":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Jn(u.trim()))return;let m=Uc(w);je("Checking Document360 for reviewer comments\u2026"),T(!0);let f=null;try{f=await Mc(e,s,{...m.scope,onProgress:(b,R)=>je(`Checking Document360 for reviewer comments\u2026 ${b}/${R}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{T(!1),je(null)}if(!f)return;Y(b=>b+1);let $=On(f.threads,f.labels);if(f.threads.length===0){h({kind:"note",tone:"ok",text:_r(f,{showAnswered:m.showAnswered,width:_e()}).join(`
|
|
503
505
|
`)});return}if(m.answer&&(m.all||m.scope.path||m.scope.scope||$.length===1)){eo(Fc(f,{full:!0,showAnswered:m.showAnswered,width:_e()})),await ga($,{resolve:m.resolve});return}if($.length===1){eo(bi($[0],{width:_e()})),Uo({group:$[0],cursor:0,fromList:!1,resolve:m.resolve,rest:[]});return}eo(_r(f,{showAnswered:m.showAnswered,width:_e()})),Nt({cursor:0,rows:$i($),groups:$,resolve:m.resolve,report:f});return}case"update":{la.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Pt(!0);let m=await xi().finally(()=>Pt(!1));m.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${m.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ou("")):h({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${vi}`});return}case"screenshot":{let m=hr(w),f=fr(e);if(f&&m.mode!=="list"&&h({kind:"note",tone:"info",text:f}),m.mode==="capture"){await E(m.rest);return}if(m.mode==="checklist"){await B();return}if(m.mode==="verify"){let R=Ie(e),x=m.rest.find(V=>!V.startsWith("-")),_=x?[x]:Er(R);if(x&&!R.some(V=>V.id===x)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${x}". /screenshot list shows them all.`});return}if(_.length===0){let V=R.filter(M=>M.state==="rejected").length,A=R.filter(M=>M.state==="verified").length;h({kind:"note",tone:"info",text:V>0?`Nothing left to verify. ${V} shot${V===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:A>0?`All ${A} captured shot${A===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}h({kind:"note",tone:"info",text:Ar(_.length)}),await ye(In(e,_),{display:x?`/screenshot verify ${x}`:"/screenshot verify",quietUser:!0});let W=Dr(e,_);W.length>0&&h({kind:"note",tone:"info",text:W.join(`
|
|
504
506
|
`)});return}if(m.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=ge(e)?.docsDir??Nu,x=ul(e,m.scope),_=Ie(e,x);if(m.picker){if(_.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let q=ah(_);if(q.length===0){h({kind:"note",tone:"info",text:Qs(_,{docsDir:R}).join(`
|
|
505
507
|
`)});let ie=Ct(e,{text:`\u2713 All ${_.length} screenshots are captured. /publish${x?` ${x}`:""} puts them in the articles; /screenshot capture${x?` ${x}`:""} re-captures.`,cmd:x?`/publish ${x}`:"/publish"},`\u2713 All ${_.length} screenshots are captured. `,x);Ae(ie.text,{kind:"cmd",cmd:ie.cmd,reason:""});return}kn({cursor:0,rows:q,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Qs(_,{scope:x,detail:m.detail,docsDir:R}).join(`
|
|
506
|
-
`)}),f&&h({kind:"note",tone:"info",text:f});let W=_.filter(q=>q.state==="placeholder").length,V=_.filter(q=>q.state==="spec").length,A=_.filter(q=>q.state==="captured").length,M=_.filter(q=>q.state==="rejected").length,L=_.filter(q=>q.state==="spec"&&!q.mutates).length;W>0?Q(x?`/screenshot author ${x}`:"/screenshot author --all"):V>0&&(L>0||A===0)?Q(x?`/screenshot capture ${x}`:"/screenshot capture"):A>0?Q(x?`/screenshot verify ${x}`:"/screenshot verify"):M>0&&Q(x?`/screenshot capture ${x} --failed`:"/screenshot capture --failed");return}if(m.mode==="single"){await id(m.id);return}if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=m.mode==="scope"?m.scope:void 0,b
|
|
507
|
-
`)}),qe(Qr(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,to,ba,h,Ve,ye,ft,ya,ad]),fs=J(u=>{let d=(u??k).trim();if(v(""),Jr(null),Un(0),d.startsWith("/")&&(Te.current=!1,yt.current=!1,St.current=null,kt(),zn(null),ue(w=>Tg(w,d))),!d||(Wn(!1),(Wo.current||Ce.current.length>0)&&h({kind:"user",text:d}),cd(d))||ld(d))return;ta.current.push(d);let c=Ng(d,_u.current);if(d.startsWith("/"))h({kind:"user",text:d}),ae(!0),no(c).finally(()=>ae(!1));else if(IS(c)){h({kind:"user",text:d});let w=LS(c);if(!w)ye(c,{display:d,quietUser:!0});else{try{OS(e,{title:w,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ye(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${w}". 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 "${w}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let w=Dm(e,c);ye(w??c,{display:d})}},[k,cd,ld,no,ye]),ud=J(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=Eg(u);if(Ag(d)){let c=Dg(++ky.current,d);_u.current.set(c,d),P(c)}else P(d);return}P(u)},[P]),oo=Math.max(10,Ge-6),dd=vu(()=>Yi(p.text,oo),[p.text,oo]),$a=J(u=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),ms=J(u=>g(d=>({...d,pos:Ig(Yi(d.text,oo),d.pos,u)})),[oo]),nr=J(u=>g(d=>({...d,pos:Lg(Yi(d.text,oo),d.pos,u)})),[oo]),Py=["\x1B[H","\x1B[1~","\x1BOH"],Ty=["\x1B[F","\x1B[4~","\x1BOF"],pd=J((u,d)=>d.leftArrow?($a(-1),!0):d.rightArrow?($a(1),!0):u&&Py.includes(u)?(nr("start"),!0):u&&Ty.includes(u)?(nr("end"),!0):d.ctrl&&u==="a"?(nr("start"),!0):d.ctrl&&u==="e"?(nr("end"),!0):!1,[$a,nr]);return HR((u,d)=>{if(d.ctrl&&u==="c"){dt.current?.close(),r();return}if(Qo.current.awaySince!==null)try{let c=wg(Qo.current,Date.now(),Ln(e));if(Qo.current=c.memory,Zu(null),c.kind==="delta"){h({kind:"note",tone:"info",text:bg(c.delta,c.awayMs)});let w=ht(!1);w.kind==="recommend"&&jt(w.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${zr(c.delta)} arrived while you were away (${ku(c.awayMs)}).`});let w=ht(!1);w.kind==="recommend"&&jt(w.rec)}}catch{}if(pa.current=Date.now(),!D){if(C){if(d.escape){if(Ee.current){if(!Ee.current.signal.aborted){let c=(Ho?.verb??"work").toLowerCase(),w=Ho?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${w}s)\u2026`}),Ee.current.abort()}return}Bo.current||(Bo.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),dt.current?.interrupt());return}if(d.return){let c=k.trim();if(!c)return;vn.current.push(c),oa([...vn.current]),v("");return}if(pd(u,d))return;if(d.upArrow){ms(-1);return}if(d.downArrow){ms(1);return}if(d.backspace||d.delete){S();return}u&&!d.ctrl&&!d.meta&&ud(u);return}if(gn){if(d.upArrow){yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){yn(c=>c&&{...c,cursor:Math.min(Rt.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Rt.length){yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Rt[gn.cursor];yn(null);let{lines:w,changed:E,effective:B}=Pr(e,c.value??"default");for(let m of w)h({kind:"note",tone:m.startsWith("\u26A0")?"warn":m.startsWith("\u2713")?"ok":"info",text:m});E&&(Vu(m=>m+1),dt.current?.setModel(B));return}if(u==="s"){let c=Rt[gn.cursor];yn(null),dt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(d.escape){yn(null);return}return}if(qt){if(d.upArrow){qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=qt.rows.length){qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=qt.rows[qt.cursor];qn(null),ka(c.name,d.return===!0);return}if(d.escape){qn(null);return}return}if(Vo){if(d.escape){Cn(null);return}if(d.leftArrow||d.tab&&d.shift){Cn(c=>c&&{tab:(c.tab-1+Je.length)%Je.length,scroll:0});return}if(d.rightArrow||d.tab){Cn(c=>c&&{tab:(c.tab+1)%Je.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Je.length){Cn({tab:Number(u)-1,scroll:0});return}if(d.upArrow){Cn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){Cn(c=>{if(!c)return c;let w=(Je[c.tab]??Je[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,w-1),c.scroll+1)}});return}return}if(Gt){if(d.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Gt.rows.length){Gn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Gt.rows[Gt.cursor].name;if(Gn(null),!Ia(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let E=!1;try{let B=Fn(c);E=!!B&&!(pn(B)&&!B.refreshToken)}catch{E=!1}h({kind:"note",tone:"info",text:E?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),Q("/login"),Y(B=>B+1);return}if(d.escape){Gn(null);return}return}if(ze){if(d.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ze.rows.length){Vn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=ze.rows[ze.cursor],{profile:w,projectId:E}=ze;Vn(null),ds(w,E,c);return}if(d.escape){Vn(null);return}return}if(pt){if(d.upArrow){wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){wn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=pt.rows.length){wn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=pt.rows[pt.cursor],{profile:w}=pt;wn(null),hs(w,c);return}if(d.escape){wn(null);return}return}if(Xe){if(d.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Xn(c=>c&&{...c,rows:c.rows.map((w,E)=>E===c.cursor?{...w,checked:!w.checked}:w)});return}if(d.return){let c=Xe.rows.filter(w=>w.checked).map(w=>w.path);if(Xn(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Tl(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let w of c)h({kind:"note",tone:"info",text:` ${w}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Xn(null);return}return}if(wt){if(d.upArrow){bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=wt.rows.length){bn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=wt.rows[wt.cursor],w=wt.run;bn(null),w(c.token);return}if(d.escape){bn(null);return}return}if(At){if(d.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Yn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=At.rows.length){Yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=At.rows[At.cursor],w=At.conflicts;Yn(null),c.conflict?ba(c.paths[0]):c.kind==="article"?ya(c.paths[0]):ft(c.paths,c.kind==="all"?w:0);return}if(d.escape){Yn(null);return}return}if(Vt){if(d.upArrow){Kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Kn(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Vt.rows.length+1){Kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let{cursor:c,rows:w,opts:E}=Vt;Kn(null);let B=c===0?w:[w[c-1]];Sy(B,E);return}if(d.escape){Kn(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Dt){let{rows:c}=Dt;if(d.upArrow){Nt(w=>w&&{...w,cursor:Math.max(0,w.cursor-1)});return}if(d.downArrow){Nt(w=>w&&{...w,cursor:Math.min(c.length-1,w.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let w=cg(Wu.current,Number(u),c.length-1);Wu.current=w.memory,w.index!==null&&Nt(E=>E&&{...E,cursor:w.index+1});return}if(u==="a"||u==="A"){Nt(w=>w&&{...w,cursor:0});return}if(d.return){let w=c[Dt.cursor],{groups:E,resolve:B,report:m}=Dt;if(Nt(null),w.kind==="all"){ga(E,{resolve:B,report:m});return}eo(bi(w.group,{width:_e()})),Uo({group:w.group,cursor:0,fromList:!0,resolve:B,rest:E.filter(f=>f.articleId!==w.group.articleId),report:m});return}if(d.escape){Nt(null),Q("/comments");return}return}if(Le){let c=()=>{let{rest:w,group:E,fromList:B,resolve:m,report:f}=Le;if(Uo(null),!B||!f){Q("/comments");return}let $=[E,...w].sort((b,R)=>b.category.localeCompare(R.category)||b.title.localeCompare(R.title));Nt({cursor:0,rows:$i($),groups:$,resolve:m,report:f})};if(d.upArrow||d.downArrow){Uo(w=>w&&{...w,cursor:w.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&Le.cursor===0){let{group:w,resolve:E,rest:B,report:m}=Le;Uo(null),ga([w],{resolve:E,rest:B,...m?{report:m}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(Yt){if(d.upArrow){kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){kn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Yt.rows.length){kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Yt.rows[Yt.cursor];kn(null),c.action==="capture"?er(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.kind==="shot"?id(c.ids[0]):sd(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){kn(null);return}return}if(ot){if(d.escape){$n(null);return}if(d.upArrow){$n(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){$n(c=>c&&{...c,cursor:Math.min(Math.max(0,as.length-1),c.cursor+1)});return}if(d.return){let c=as[ot.cursor];if(c){$n(null);try{h({kind:"preview",name:Qr(c),text:cy(zi(xu(e,c),"utf8"))})}catch(w){h({kind:"note",tone:"error",text:`Could not read ${c}: ${w.message}`})}}return}if(d.backspace||d.delete){$n(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){$n(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(rt){if(d.escape){xn(null);return}if(d.upArrow){xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){xn(c=>c&&{...c,cursor:Math.min(Math.max(0,ls.length-1),c.cursor+1)});return}if(d.return){let c=ls[rt.cursor];if(c){xn(null),Ve(c.uuid),Et.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},mn(c.name),Cu(c.uuid),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current};let w=gu(e,c.uuid);for(let E of w)h(E);h({kind:"note",tone:"ok",text:w.length?`Resumed "${c.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){xn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){xn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!k&&le){v(le),kt();return}if(!k&&ne.length>0&&!nt&&u&&/^[1-9]$/.test(u)){let c=ne[Number(u)-1];if(c){v(Mn(c));return}}if(!k&&ne.length===0&&!nt&&He.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=He.current.armed[Number(u)-1];if(c){v(c);return}}if(!k&&(rs||zo)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=rs!=null;hu(rs??zo).then(E=>{h({kind:"note",tone:E?"ok":"warn",text:E?c?"\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.":c?"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."}),E&&c&&da(null),E&&!c&&Ku(!0)});return}if(!pd(u,d)){if(td){if(d.upArrow){Un(c=>Math.max(0,c-1));return}if(d.downArrow){Un(c=>Math.min(It.length-1,c+1));return}if(d.tab){v("/"+(It[ea]?.name??"")+" "),Un(0);return}if(d.return){let c=It[ea];if(c){let w=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(hp(c.usage)&&!w){v("/"+c.name+" "),Un(0);return}fs("/"+c.name+(w?" "+w:""));return}}}else{if(d.upArrow){if(k!==""&&Bn===null){ms(-1);return}let c=ta.current;if(!c.length)return;let w=Bn===null?c.length-1:Math.max(0,Bn-1);Jr(w),v(c[w]??"");return}if(d.downArrow){if(k!==""&&Bn===null){ms(1);return}let c=ta.current;if(Bn===null)return;let w=Bn+1;w>=c.length?(Jr(null),v("")):(Jr(w),v(c[w]??""));return}}if(d.return){fs();return}if(d.backspace||d.delete){S();return}if(d.escape){v(""),Un(0),kt(),ue([]),zn(null),Te.current=!0;return}u&&!d.ctrl&&!d.meta&&ud(u)}}}),tt(()=>{if(C||D)return;let u=vn.current.shift();u!==void 0&&(oa([...vn.current]),fs(u))},[C,D,fs]),oe(xe,{flexDirection:"column",width:Ge,children:[ma!==null&&oe(xe,{marginTop:1,flexDirection:"column",children:[ma.truncated&&F(U,{dimColor:!0,children:"\u2026"}),F(U,{children:ma.text})]}),C&&Ho?F(KS,{p:Ho}):null,Hu?F(VS,{text:Hu}):C&&!Ho?F(GS,{startTime:Tt.current,chars:wy}):null,F(xe,{borderStyle:"round",borderColor:ed.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?dd.map((u,d)=>{let c=p.text.slice(u.start,u.end),w=d===Ki(dd,p.pos),E=Math.min(p.pos,u.end)-u.start;return oe(U,{children:[F(U,{color:Z,children:d===0?"> ":" "}),w?oe(Lo,{children:[c.slice(0,E),F(Io,{ch:c[E]??" "}),c.slice(E+1)]}):c||" "]},`${d}-${u.start}`)}):oe(U,{children:[F(U,{color:Z,children:"> "}),Yo?F(Io,{ch:" "}):le&&!C&&ce?oe(Lo,{children:[F(Io,{ch:ce[0],dim:!0}),F(U,{color:"gray",children:ce.slice(1)})]}):le&&!C?oe(Lo,{children:[F(Io,{ch:le[0],dim:!0}),F(U,{color:"gray",children:le.slice(1)}),F(U,{dimColor:!0,children:" (tab)"})]}):(ha.isSetup||!hn)&&!C?oe(Lo,{children:[F(Io,{ch:ha.text[0],dim:!0}),F(U,{color:"gray",children:ha.text.slice(1)})]}):F(Io,{ch:" "})]})}),Bu.length>0&&F(xe,{flexDirection:"column",paddingX:1,children:Bu.map((u,d)=>F(U,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),Vo?F(vg,{tab:Vo.tab,scroll:Vo.scroll,rows:Cy,width:Ge,version:o,engineVersion:uy}):gn?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Select model"}),F(U,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Rt.map((u,d)=>oe(U,{color:d===gn.cursor?Z:void 0,children:[d===gn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===gn.current?" \u2714":""}`.padEnd(16),F(U,{color:"gray",children:u.desc})]},u.label)),F(U,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):qt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch connection profile"}),F(dn,{rows:qt.rows,cursor:qt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===qt.current?" \u2714":""}`.padEnd(20),F(U,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?F(U,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),F(U,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Gt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Pick your Document360 environment"}),F(dn,{rows:Gt.rows,cursor:Gt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),F(U,{color:"gray",children:u.apiUrl}),u.note?F(U,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ze?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch workspace"}),F(U,{dimColor:!0,children:`environment ${ze.environment} \xB7 project ${ze.projectName??`${ze.projectId.slice(0,8)}\u2026`}`}),F(dn,{rows:ze.rows,cursor:ze.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===ze.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.type??""})]},u.id)}),F(U,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):pt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Choose project"}),F(U,{dimColor:!0,children:`environment ${pt.environment}`}),F(dn,{rows:pt.rows,cursor:pt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===pt.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.sub??""})]},u.id)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Xe?(()=>{let d=Math.min(Math.max(0,Xe.cursor-Math.floor(7)),Math.max(0,Xe.rows.length-14)),c=Xe.rows.slice(d,d+14),w=Xe.rows.filter(E=>E.checked).length;return oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Which folders back the user docs? (${w} selected of ${Xe.rows.length})`}),d>0?F(U,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((E,B)=>{let m=d+B;return oe(U,{color:m===Xe.cursor?Z:void 0,children:[m===Xe.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Ge-34)),F(U,{color:"gray",children:ri(E)})]},E.path)}),d+14<Xe.rows.length?F(U,{dimColor:!0,children:` \u2193 ${Xe.rows.length-d-14} more`}):null,F(U,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():wt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:wt.title??"Which category? (pick one to scope to)"}),F(dn,{rows:wt.rows,cursor:wt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,Ge-24))),F(U,{color:"gray",children:` ${u.token}`})]},u.token)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):At?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),F(dn,{rows:At.rows,cursor:At.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),u.note?F(U,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter push (draft) \xB7 esc cancel"})]}):Vt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),F(dn,{rows:[{path:"",articleId:"",label:`Publish all ${Vt.rows.length} live`,version:void 0},...Vt.rows],cursor:Vt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:d===0&&!c,children:[c?"\u276F ":" ",` ${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),d>0?F(U,{color:"gray",children:u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}):null]},`${d}:${u.path||"all"}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish LIVE \xB7 esc leave as drafts"})]}):Dt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Which comments do you want to look at?"}),F(dn,{rows:Dt.rows,cursor:Dt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,Ge-24))),u.kind==="article"?F(U,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),Dt.resolve?F(U,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Le?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`${Le.group.title} \u2014 ${Le.group.threads.length} comment${Le.group.threads.length===1?"":"s"}`}),oe(U,{color:Le.cursor===0?Z:void 0,children:[Le.cursor===0?"\u276F ":" ",Le.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),oe(U,{color:Le.cursor===1?Z:void 0,children:[Le.cursor===1?"\u276F ":" ",Le.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):Yt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:Yt.title}),(()=>{let{rows:u,cursor:d}=Yt,c=Ui(u.length,d,Lt),w=c.start,E=u.slice(c.start,c.end),B=`${u.length}.`.length+1,m=ih(u,Math.max(20,Ge-4-B));return oe(Lo,{children:[w>0?F(U,{color:"gray",children:` \u2026 ${w} more above`}):null,E.map((f,$)=>{let b=w+$,R=b===d,x=m[b];return oe(U,{color:R?Z:void 0,bold:(f.kind==="all"||f.kind==="category")&&!R,children:[R?"\u276F ":" ",`${b+1}.`.padEnd(B),x.head,x.note?F(U,{color:"gray",children:x.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?F(U,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):ot?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Preview article${ot.query?` \u2014 filter: ${ot.query}`:" (type to filter)"}`}),as.length===0?F(U,{color:"gray",children:"no articles match"}):as.map((u,d)=>oe(U,{color:d===ot.cursor?Z:void 0,children:[d===ot.cursor?"\u276F ":" ",u]},u)),F(U,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):rt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Resume session${rt.query?` \u2014 filter: ${rt.query}`:" (type to filter)"}`}),ls.length===0?F(U,{color:"gray",children:"no sessions match"}):ls.map((u,d)=>oe(U,{color:d===rt.cursor?Z:void 0,children:[d===rt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),F(U,{color:d===rt.cursor?Z:"gray",children:u.firstPrompt.slice(0,Math.max(10,Ge-40))})]},u.uuid)),F(U,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):td?oe(xe,{flexDirection:"column",children:[Rn>0?F(U,{dimColor:!0,children:` \u22EF ${Rn} more above`}):null,fa.map((u,d)=>{let c=Rn+d,w=u.name==="model"&&ra?`${u.desc} (currently ${ra})`:u.desc,E=Math.max(20,Ge-4),B=u.usage.length>E?`${u.usage.slice(0,E-1)}\u2026`:u.usage,m=E-Math.max(B.length,22)-1,f=m<=1?"":w.length>m?`${w.slice(0,m-1)}\u2026`:w;return oe(U,{color:c===is?Z:void 0,children:[c===is?"\u276F ":" ",B.padEnd(22)," ",F(U,{color:c===is?Z:"gray",children:f})]},u.name)}),Rn+fa.length<It.length?F(U,{dimColor:!0,children:` \u22EF ${It.length-Rn-fa.length} more below`}):null,F(U,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!k&&ne.length>0?oe(xe,{flexDirection:"column",paddingX:1,children:[Uu?F(U,{color:Z,children:Uu}):null,ne.map((u,d)=>{let c=Mn(u),w=c.slice(0,Math.max(20,Ge-5)),E=Ge-w.length-7,B=E>=12?(Pg(u)??dp(c)).slice(0,E):"";return oe(U,{children:[F(U,{color:Z,children:d+1})," ",w,B?F(U,{dimColor:!0,children:` \u2014 ${B}`}):null]},c)}),F(U,{dimColor:!0,children:`press 1-${ne.length} to fill \xB7 esc cancel`})]}):F(xe,{paddingX:1,children:oe(U,{color:"gray",children:[ed.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ra??"model n/a"}${t.kind==="api"?Gu>0?` \xB7 ${Ze(Gu)}`:"":qu>0?` \xB7 ${rn(qu)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}ee();import{jsx as JS}from"react/jsx-runtime";async function py(e=process.cwd(),t="auto",n,o="0.0.0"){let r=QS(t);r.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=XS(JS(dy,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
508
|
-
`),process.exit(0)}ee();import{writeCrashLog as hy,isBenignTransportError as
|
|
508
|
+
`)}),f&&h({kind:"note",tone:"info",text:f});let W=_.filter(q=>q.state==="placeholder").length,V=_.filter(q=>q.state==="spec").length,A=_.filter(q=>q.state==="captured").length,M=_.filter(q=>q.state==="rejected").length,L=_.filter(q=>q.state==="spec"&&!q.mutates).length;W>0?Q(x?`/screenshot author ${x}`:"/screenshot author --all"):V>0&&(L>0||A===0)?Q(x?`/screenshot capture ${x}`:"/screenshot capture"):A>0?Q(x?`/screenshot verify ${x}`:"/screenshot verify"):M>0&&Q(x?`/screenshot capture ${x} --failed`:"/screenshot capture --failed");return}if(m.mode==="single"){await id(m.id);return}if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=m.mode==="scope"?m.scope:void 0,b=$S(e,{scope:$}).map(R=>R.id);if(b.length===0){h({kind:"note",tone:"info",text:$?`No screenshot placeholders under ${$}.`:"No screenshot placeholders found in the docs."});return}await sd(b,{setup:m.setup,scope:m.mode==="scope"?m.scope:void 0,runLine:m.mode==="scope"?[`/screenshot author ${m.scope}`,`/screenshot ${m.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await E(w);return}case"reset":{let m=qc(e);if(m.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Wo.current={repoName:Qr(e),targets:m,hadDevhints:Ao(ey(e))},h({kind:"note",tone:"warn",text:Vc(e,m).join(`
|
|
509
|
+
`)}),qe(Qr(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,to,ba,h,Ve,ye,ft,ya,ad]),fs=J(u=>{let d=(u??k).trim();if(v(""),Jr(null),Un(0),d.startsWith("/")&&(Te.current=!1,yt.current=!1,St.current=null,kt(),zn(null),ue(w=>Tg(w,d))),!d||(Wn(!1),(Wo.current||Ce.current.length>0)&&h({kind:"user",text:d}),cd(d))||ld(d))return;ta.current.push(d);let c=Ng(d,_u.current);if(d.startsWith("/"))h({kind:"user",text:d}),ae(!0),no(c).finally(()=>ae(!1));else if(LS(c)){h({kind:"user",text:d});let w=OS(c);if(!w)ye(c,{display:d,quietUser:!0});else{try{_S(e,{title:w,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ye(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${w}". 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 "${w}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let w=Dm(e,c);ye(w??c,{display:d})}},[k,cd,ld,no,ye]),ud=J(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=Eg(u);if(Ag(d)){let c=Dg(++ky.current,d);_u.current.set(c,d),P(c)}else P(d);return}P(u)},[P]),oo=Math.max(10,Ge-6),dd=vu(()=>Yi(p.text,oo),[p.text,oo]),$a=J(u=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),ms=J(u=>g(d=>({...d,pos:Ig(Yi(d.text,oo),d.pos,u)})),[oo]),nr=J(u=>g(d=>({...d,pos:Lg(Yi(d.text,oo),d.pos,u)})),[oo]),Py=["\x1B[H","\x1B[1~","\x1BOH"],Ty=["\x1B[F","\x1B[4~","\x1BOF"],pd=J((u,d)=>d.leftArrow?($a(-1),!0):d.rightArrow?($a(1),!0):u&&Py.includes(u)?(nr("start"),!0):u&&Ty.includes(u)?(nr("end"),!0):d.ctrl&&u==="a"?(nr("start"),!0):d.ctrl&&u==="e"?(nr("end"),!0):!1,[$a,nr]);return qR((u,d)=>{if(d.ctrl&&u==="c"){dt.current?.close(),r();return}if(Qo.current.awaySince!==null)try{let c=wg(Qo.current,Date.now(),Ln(e));if(Qo.current=c.memory,Zu(null),c.kind==="delta"){h({kind:"note",tone:"info",text:bg(c.delta,c.awayMs)});let w=ht(!1);w.kind==="recommend"&&jt(w.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${zr(c.delta)} arrived while you were away (${ku(c.awayMs)}).`});let w=ht(!1);w.kind==="recommend"&&jt(w.rec)}}catch{}if(pa.current=Date.now(),!D){if(C){if(d.escape){if(Ee.current){if(!Ee.current.signal.aborted){let c=(Ho?.verb??"work").toLowerCase(),w=Ho?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${w}s)\u2026`}),Ee.current.abort()}return}Bo.current||(Bo.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),dt.current?.interrupt());return}if(d.return){let c=k.trim();if(!c)return;vn.current.push(c),oa([...vn.current]),v("");return}if(pd(u,d))return;if(d.upArrow){ms(-1);return}if(d.downArrow){ms(1);return}if(d.backspace||d.delete){S();return}u&&!d.ctrl&&!d.meta&&ud(u);return}if(gn){if(d.upArrow){yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){yn(c=>c&&{...c,cursor:Math.min(Rt.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Rt.length){yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Rt[gn.cursor];yn(null);let{lines:w,changed:E,effective:B}=Pr(e,c.value??"default");for(let m of w)h({kind:"note",tone:m.startsWith("\u26A0")?"warn":m.startsWith("\u2713")?"ok":"info",text:m});E&&(Vu(m=>m+1),dt.current?.setModel(B));return}if(u==="s"){let c=Rt[gn.cursor];yn(null),dt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(d.escape){yn(null);return}return}if(qt){if(d.upArrow){qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=qt.rows.length){qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=qt.rows[qt.cursor];qn(null),ka(c.name,d.return===!0);return}if(d.escape){qn(null);return}return}if(Vo){if(d.escape){Cn(null);return}if(d.leftArrow||d.tab&&d.shift){Cn(c=>c&&{tab:(c.tab-1+Je.length)%Je.length,scroll:0});return}if(d.rightArrow||d.tab){Cn(c=>c&&{tab:(c.tab+1)%Je.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Je.length){Cn({tab:Number(u)-1,scroll:0});return}if(d.upArrow){Cn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){Cn(c=>{if(!c)return c;let w=(Je[c.tab]??Je[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,w-1),c.scroll+1)}});return}return}if(Gt){if(d.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Gt.rows.length){Gn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Gt.rows[Gt.cursor].name;if(Gn(null),!Ia(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let E=!1;try{let B=Fn(c);E=!!B&&!(pn(B)&&!B.refreshToken)}catch{E=!1}h({kind:"note",tone:"info",text:E?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),Q("/login"),Y(B=>B+1);return}if(d.escape){Gn(null);return}return}if(ze){if(d.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ze.rows.length){Vn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=ze.rows[ze.cursor],{profile:w,projectId:E}=ze;Vn(null),ds(w,E,c);return}if(d.escape){Vn(null);return}return}if(pt){if(d.upArrow){wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){wn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=pt.rows.length){wn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=pt.rows[pt.cursor],{profile:w}=pt;wn(null),hs(w,c);return}if(d.escape){wn(null);return}return}if(Xe){if(d.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Xn(c=>c&&{...c,rows:c.rows.map((w,E)=>E===c.cursor?{...w,checked:!w.checked}:w)});return}if(d.return){let c=Xe.rows.filter(w=>w.checked).map(w=>w.path);if(Xn(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Tl(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let w of c)h({kind:"note",tone:"info",text:` ${w}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Xn(null);return}return}if(wt){if(d.upArrow){bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=wt.rows.length){bn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=wt.rows[wt.cursor],w=wt.run;bn(null),w(c.token);return}if(d.escape){bn(null);return}return}if(At){if(d.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Yn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=At.rows.length){Yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=At.rows[At.cursor],w=At.conflicts;Yn(null),c.conflict?ba(c.paths[0]):c.kind==="article"?ya(c.paths[0]):ft(c.paths,c.kind==="all"?w:0);return}if(d.escape){Yn(null);return}return}if(Vt){if(d.upArrow){Kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Kn(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Vt.rows.length+1){Kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let{cursor:c,rows:w,opts:E}=Vt;Kn(null);let B=c===0?w:[w[c-1]];Sy(B,E);return}if(d.escape){Kn(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Dt){let{rows:c}=Dt;if(d.upArrow){Nt(w=>w&&{...w,cursor:Math.max(0,w.cursor-1)});return}if(d.downArrow){Nt(w=>w&&{...w,cursor:Math.min(c.length-1,w.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let w=cg(Wu.current,Number(u),c.length-1);Wu.current=w.memory,w.index!==null&&Nt(E=>E&&{...E,cursor:w.index+1});return}if(u==="a"||u==="A"){Nt(w=>w&&{...w,cursor:0});return}if(d.return){let w=c[Dt.cursor],{groups:E,resolve:B,report:m}=Dt;if(Nt(null),w.kind==="all"){ga(E,{resolve:B,report:m});return}eo(bi(w.group,{width:_e()})),Uo({group:w.group,cursor:0,fromList:!0,resolve:B,rest:E.filter(f=>f.articleId!==w.group.articleId),report:m});return}if(d.escape){Nt(null),Q("/comments");return}return}if(Le){let c=()=>{let{rest:w,group:E,fromList:B,resolve:m,report:f}=Le;if(Uo(null),!B||!f){Q("/comments");return}let $=[E,...w].sort((b,R)=>b.category.localeCompare(R.category)||b.title.localeCompare(R.title));Nt({cursor:0,rows:$i($),groups:$,resolve:m,report:f})};if(d.upArrow||d.downArrow){Uo(w=>w&&{...w,cursor:w.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&Le.cursor===0){let{group:w,resolve:E,rest:B,report:m}=Le;Uo(null),ga([w],{resolve:E,rest:B,...m?{report:m}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(Yt){if(d.upArrow){kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){kn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Yt.rows.length){kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Yt.rows[Yt.cursor];kn(null),c.action==="capture"?er(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.kind==="shot"?id(c.ids[0]):sd(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){kn(null);return}return}if(ot){if(d.escape){$n(null);return}if(d.upArrow){$n(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){$n(c=>c&&{...c,cursor:Math.min(Math.max(0,as.length-1),c.cursor+1)});return}if(d.return){let c=as[ot.cursor];if(c){$n(null);try{h({kind:"preview",name:Qr(c),text:cy(zi(xu(e,c),"utf8"))})}catch(w){h({kind:"note",tone:"error",text:`Could not read ${c}: ${w.message}`})}}return}if(d.backspace||d.delete){$n(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){$n(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(rt){if(d.escape){xn(null);return}if(d.upArrow){xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){xn(c=>c&&{...c,cursor:Math.min(Math.max(0,ls.length-1),c.cursor+1)});return}if(d.return){let c=ls[rt.cursor];if(c){xn(null),Ve(c.uuid),Et.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},mn(c.name),Cu(c.uuid),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current};let w=gu(e,c.uuid);for(let E of w)h(E);h({kind:"note",tone:"ok",text:w.length?`Resumed "${c.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){xn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){xn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!k&&le){v(le),kt();return}if(!k&&ne.length>0&&!nt&&u&&/^[1-9]$/.test(u)){let c=ne[Number(u)-1];if(c){v(Mn(c));return}}if(!k&&ne.length===0&&!nt&&He.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=He.current.armed[Number(u)-1];if(c){v(c);return}}if(!k&&(rs||zo)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=rs!=null;hu(rs??zo).then(E=>{h({kind:"note",tone:E?"ok":"warn",text:E?c?"\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.":c?"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."}),E&&c&&da(null),E&&!c&&Ku(!0)});return}if(!pd(u,d)){if(td){if(d.upArrow){Un(c=>Math.max(0,c-1));return}if(d.downArrow){Un(c=>Math.min(It.length-1,c+1));return}if(d.tab){v("/"+(It[ea]?.name??"")+" "),Un(0);return}if(d.return){let c=It[ea];if(c){let w=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(hp(c.usage)&&!w){v("/"+c.name+" "),Un(0);return}fs("/"+c.name+(w?" "+w:""));return}}}else{if(d.upArrow){if(k!==""&&Bn===null){ms(-1);return}let c=ta.current;if(!c.length)return;let w=Bn===null?c.length-1:Math.max(0,Bn-1);Jr(w),v(c[w]??"");return}if(d.downArrow){if(k!==""&&Bn===null){ms(1);return}let c=ta.current;if(Bn===null)return;let w=Bn+1;w>=c.length?(Jr(null),v("")):(Jr(w),v(c[w]??""));return}}if(d.return){fs();return}if(d.backspace||d.delete){S();return}if(d.escape){v(""),Un(0),kt(),ue([]),zn(null),Te.current=!0;return}u&&!d.ctrl&&!d.meta&&ud(u)}}}),tt(()=>{if(C||D)return;let u=vn.current.shift();u!==void 0&&(oa([...vn.current]),fs(u))},[C,D,fs]),oe(xe,{flexDirection:"column",width:Ge,children:[ma!==null&&oe(xe,{marginTop:1,flexDirection:"column",children:[ma.truncated&&F(U,{dimColor:!0,children:"\u2026"}),F(U,{children:ma.text})]}),C&&Ho?F(zS,{p:Ho}):null,Hu?F(YS,{text:Hu}):C&&!Ho?F(VS,{startTime:Tt.current,chars:wy}):null,F(xe,{borderStyle:"round",borderColor:ed.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?dd.map((u,d)=>{let c=p.text.slice(u.start,u.end),w=d===Ki(dd,p.pos),E=Math.min(p.pos,u.end)-u.start;return oe(U,{children:[F(U,{color:Z,children:d===0?"> ":" "}),w?oe(Lo,{children:[c.slice(0,E),F(Io,{ch:c[E]??" "}),c.slice(E+1)]}):c||" "]},`${d}-${u.start}`)}):oe(U,{children:[F(U,{color:Z,children:"> "}),Yo?F(Io,{ch:" "}):le&&!C&&ce?oe(Lo,{children:[F(Io,{ch:ce[0],dim:!0}),F(U,{color:"gray",children:ce.slice(1)})]}):le&&!C?oe(Lo,{children:[F(Io,{ch:le[0],dim:!0}),F(U,{color:"gray",children:le.slice(1)}),F(U,{dimColor:!0,children:" (tab)"})]}):(ha.isSetup||!hn)&&!C?oe(Lo,{children:[F(Io,{ch:ha.text[0],dim:!0}),F(U,{color:"gray",children:ha.text.slice(1)})]}):F(Io,{ch:" "})]})}),Bu.length>0&&F(xe,{flexDirection:"column",paddingX:1,children:Bu.map((u,d)=>F(U,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),Vo?F(vg,{tab:Vo.tab,scroll:Vo.scroll,rows:Cy,width:Ge,version:o,engineVersion:uy}):gn?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Select model"}),F(U,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Rt.map((u,d)=>oe(U,{color:d===gn.cursor?Z:void 0,children:[d===gn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===gn.current?" \u2714":""}`.padEnd(16),F(U,{color:"gray",children:u.desc})]},u.label)),F(U,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):qt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch connection profile"}),F(dn,{rows:qt.rows,cursor:qt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===qt.current?" \u2714":""}`.padEnd(20),F(U,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?F(U,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),F(U,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Gt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Pick your Document360 environment"}),F(dn,{rows:Gt.rows,cursor:Gt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),F(U,{color:"gray",children:u.apiUrl}),u.note?F(U,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ze?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch workspace"}),F(U,{dimColor:!0,children:`environment ${ze.environment} \xB7 project ${ze.projectName??`${ze.projectId.slice(0,8)}\u2026`}`}),F(dn,{rows:ze.rows,cursor:ze.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===ze.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.type??""})]},u.id)}),F(U,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):pt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Choose project"}),F(U,{dimColor:!0,children:`environment ${pt.environment}`}),F(dn,{rows:pt.rows,cursor:pt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===pt.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.sub??""})]},u.id)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Xe?(()=>{let d=Math.min(Math.max(0,Xe.cursor-Math.floor(7)),Math.max(0,Xe.rows.length-14)),c=Xe.rows.slice(d,d+14),w=Xe.rows.filter(E=>E.checked).length;return oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Which folders back the user docs? (${w} selected of ${Xe.rows.length})`}),d>0?F(U,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((E,B)=>{let m=d+B;return oe(U,{color:m===Xe.cursor?Z:void 0,children:[m===Xe.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Ge-34)),F(U,{color:"gray",children:ri(E)})]},E.path)}),d+14<Xe.rows.length?F(U,{dimColor:!0,children:` \u2193 ${Xe.rows.length-d-14} more`}):null,F(U,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():wt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:wt.title??"Which category? (pick one to scope to)"}),F(dn,{rows:wt.rows,cursor:wt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,Ge-24))),F(U,{color:"gray",children:` ${u.token}`})]},u.token)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):At?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),F(dn,{rows:At.rows,cursor:At.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),u.note?F(U,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter push (draft) \xB7 esc cancel"})]}):Vt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),F(dn,{rows:[{path:"",articleId:"",label:`Publish all ${Vt.rows.length} live`,version:void 0},...Vt.rows],cursor:Vt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:d===0&&!c,children:[c?"\u276F ":" ",` ${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),d>0?F(U,{color:"gray",children:u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}):null]},`${d}:${u.path||"all"}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish LIVE \xB7 esc leave as drafts"})]}):Dt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Which comments do you want to look at?"}),F(dn,{rows:Dt.rows,cursor:Dt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,Ge-24))),u.kind==="article"?F(U,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),Dt.resolve?F(U,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Le?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`${Le.group.title} \u2014 ${Le.group.threads.length} comment${Le.group.threads.length===1?"":"s"}`}),oe(U,{color:Le.cursor===0?Z:void 0,children:[Le.cursor===0?"\u276F ":" ",Le.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),oe(U,{color:Le.cursor===1?Z:void 0,children:[Le.cursor===1?"\u276F ":" ",Le.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):Yt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:Yt.title}),(()=>{let{rows:u,cursor:d}=Yt,c=Ui(u.length,d,Lt),w=c.start,E=u.slice(c.start,c.end),B=`${u.length}.`.length+1,m=ih(u,Math.max(20,Ge-4-B));return oe(Lo,{children:[w>0?F(U,{color:"gray",children:` \u2026 ${w} more above`}):null,E.map((f,$)=>{let b=w+$,R=b===d,x=m[b];return oe(U,{color:R?Z:void 0,bold:(f.kind==="all"||f.kind==="category")&&!R,children:[R?"\u276F ":" ",`${b+1}.`.padEnd(B),x.head,x.note?F(U,{color:"gray",children:x.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?F(U,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):ot?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Preview article${ot.query?` \u2014 filter: ${ot.query}`:" (type to filter)"}`}),as.length===0?F(U,{color:"gray",children:"no articles match"}):as.map((u,d)=>oe(U,{color:d===ot.cursor?Z:void 0,children:[d===ot.cursor?"\u276F ":" ",u]},u)),F(U,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):rt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Resume session${rt.query?` \u2014 filter: ${rt.query}`:" (type to filter)"}`}),ls.length===0?F(U,{color:"gray",children:"no sessions match"}):ls.map((u,d)=>oe(U,{color:d===rt.cursor?Z:void 0,children:[d===rt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),F(U,{color:d===rt.cursor?Z:"gray",children:u.firstPrompt.slice(0,Math.max(10,Ge-40))})]},u.uuid)),F(U,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):td?oe(xe,{flexDirection:"column",children:[Rn>0?F(U,{dimColor:!0,children:` \u22EF ${Rn} more above`}):null,fa.map((u,d)=>{let c=Rn+d,w=u.name==="model"&&ra?`${u.desc} (currently ${ra})`:u.desc,E=Math.max(20,Ge-4),B=u.usage.length>E?`${u.usage.slice(0,E-1)}\u2026`:u.usage,m=E-Math.max(B.length,22)-1,f=m<=1?"":w.length>m?`${w.slice(0,m-1)}\u2026`:w;return oe(U,{color:c===is?Z:void 0,children:[c===is?"\u276F ":" ",B.padEnd(22)," ",F(U,{color:c===is?Z:"gray",children:f})]},u.name)}),Rn+fa.length<It.length?F(U,{dimColor:!0,children:` \u22EF ${It.length-Rn-fa.length} more below`}):null,F(U,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!k&&ne.length>0?oe(xe,{flexDirection:"column",paddingX:1,children:[Uu?F(U,{color:Z,children:Uu}):null,ne.map((u,d)=>{let c=Mn(u),w=c.slice(0,Math.max(20,Ge-5)),E=Ge-w.length-7,B=E>=12?(Pg(u)??dp(c)).slice(0,E):"";return oe(U,{children:[F(U,{color:Z,children:d+1})," ",w,B?F(U,{dimColor:!0,children:` \u2014 ${B}`}):null]},c)}),F(U,{dimColor:!0,children:`press 1-${ne.length} to fill \xB7 esc cancel`})]}):F(xe,{paddingX:1,children:oe(U,{color:"gray",children:[ed.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ra??"model n/a"}${t.kind==="api"?Gu>0?` \xB7 ${Ze(Gu)}`:"":qu>0?` \xB7 ${rn(qu)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}ee();import{jsx as ZS}from"react/jsx-runtime";async function py(e=process.cwd(),t="auto",n,o="0.0.0"){let r=JS(t);r.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=QS(ZS(dy,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
510
|
+
`),process.exit(0)}ee();import{writeCrashLog as hy,isBenignTransportError as eP}from"document360-engine";var fy=!1;function ju(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function my(e){if(fy)return;fy=!0;let t=(n,o)=>{if(eP(o)){hy({kind:n,level:"transport",message:ju(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=hy({kind:n,level:"fatal",message:ju(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
509
511
|
`+N(`\u2717 d360-writer crashed: ${ju(o)}`)+`
|
|
510
512
|
`),r&&process.stderr.write(y(` Crash details: ${r}`)+`
|
|
511
513
|
`+y(" Run: d360-writer logs")+`
|
|
512
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
514
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var rP=nP(import.meta.url),Zi=rP("../package.json");my("d360-writer");var gt=new tP;function Iu(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}gt.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Iu(e),await $s({profile:e.profile,manual:e.manual})});gt.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Iu(e),await Td({profile:e.profile})});gt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Iu(e),await Pd({profile:e.profile})});var Lu=gt.command("profile").description("Manage connection profiles for the current repo");Lu.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>vs(process.cwd()));Lu.command("use <name>").description("Set the default profile for this repo").action(e=>xs(process.cwd(),e));Lu.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Cs(process.cwd(),e));var gy=gt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");gy.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>io(process.cwd(),e.profile));gy.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await kd(process.cwd(),e,t.profile)});var yy=gt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");yy.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ws(process.cwd(),e.profile));yy.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await $d(process.cwd(),e,t.profile)});gt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(js(),sp));await e()});gt.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Nd());gt.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(mi(),bf)),n=await t(process.cwd(),Zi.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});gt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Zi.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(oP.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await jd(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await ng(e.cwd,e.auth,e.profile,Zi.version):await py(e.cwd,e.auth,e.profile,Zi.version)});gt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|