document360-writer 0.5.77 → 0.5.78

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 CHANGED
@@ -213,7 +213,7 @@ Anything only a human knows that would help document this product. For example:
213
213
  `)}function Oe(e){try{return Ku(ea(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Te(e){let n=kr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ie?"stale":"current",completedVersion:n}}function ro(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ie};try{if(!rn(oo(e)))return n;let o=kr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let i=o?.completedVersion??0;ie>r&&(no(yr(e)),_t(oo(e),na()),ra(e,t),n.guideRefreshed=!0),ie>i&&(Zu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Zs))||(Ju(e,{id:`onb${ie}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Zs}${ie})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ie}${i?` (you last completed v${i})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",ct()].join(`
214
214
  `)}),n.notifiedBuilder=!0))}catch{}return n}function io(e){if(!rn(oo(e)))return[];let t=Te(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ie}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Lt,ct(),Lt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function br(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
215
215
  `)}function so(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Lt,br(),Lt]}function Mt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ie}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Lt,ct(),Lt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Lt,ie,Zs,Ge=Gn(()=>{"use strict";Lt="-".repeat(64),ie=7;Zs="Re-run dev\u2194docs onboarding (protocol v"});var ma={};As(ma,{initCommand:()=>$r,scaffoldInit:()=>xr});import{input as sn,confirm as td}from"@inquirer/prompts";import{basename as ia,join as ao}from"node:path";import{existsSync as Ut,readFileSync as nd,readdirSync as od,writeFileSync as rd}from"node:fs";import{writeProjectConfig as sa,readProjectConfig as id,projectConfigPath as aa,writerDir as sd,DEFAULT_DOCS_DIR as la,DEFAULT_CAPTURE_DIR as ca,DEFAULT_OUTPUT_DIR as ua}from"document360-engine";function xr(e,t="berlin"){let n=aa(e);if(Ut(n))return{created:!1,path:n,profileName:""};let o={projectId:pa(e)??ia(e),docsDir:la,captureDir:ca,outputDir:ua,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:fa(e)};return sa(o,e),da(e),{created:!0,path:n,profileName:t}}function da(e){let t=ao(sd(e),".gitignore");Ut(t)||rd(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
216
- `),"utf8")}async function $r(){let e=process.cwd(),t=aa(e);if(Ut(t)&&!await td({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=pa(e)??ia(e),o=await sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ca}),i=await sn({message:"Screenshot output directory:",default:ua}),c=await sn({message:"Default connection profile name:",default:"berlin"}),p=await sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:la,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:fa(e)},y=id(e);y?.terminologyGlossary&&(g.terminologyGlossary=y.terminologyGlossary),sa(g,e),da(e);let k=Ot(e);console.log(""),console.log(I(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Mt(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function pa(e){let t=ao(e,"package.json");if(!Ut(t))return null;try{return JSON.parse(nd(t,"utf8")).name??null}catch{return null}}function fa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ut(ao(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ao(e,n);Ut(o)&&!ad(o)&&t.push(n)}return t}function ad(e){try{return od(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lo=Gn(()=>{"use strict";W();Ge()});var pl={};As(pl,{doctorCommand:()=>fn,renderDoctorChecks:()=>dl,runDoctorChecks:()=>ul});import{existsSync as Bp}from"node:fs";import{d360GetAll as Vp,getAccessToken as Gp,isExpired as hi,loadProfileMap as Yp,loadTokens as zp,packageSkillsDir as ll,projectConfigPath as Kp,readProjectConfig as Xp,DEFAULT_DOCS_DIR as Qp,fetchManifestSummary as Jp,resolveActiveProfile as Zp,classifyClaudeAuth as ef,CLAUDE_CODE_SETUP_HINT as cl,resolveModelSetting as tf,probeModel as nf,detectAppType as of,playbookSkillName as rf,D360AuthError as sf}from"document360-engine";async function ul(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=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 o=ef();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.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. ${cl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:cl});let r=tf(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let R=await nf(e,r.model??void 0);R.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?t.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"`}):t.push({level:"fail",label:`Model call failed \u2014 ${R.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 i=Xp(e);if(!i)return t.push({level:"fail",label:`No ${Kp(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??Qp).replace(/\/+$/,"");t.push(i.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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=i.authoritativeSourceFiles??[];t.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=i.appType??of(e);if(g){let R=i.appType?"from config":"auto-detected",C=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${R})${C?` \u2192 ${rf(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.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 y;try{y=Zp(e),t.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return t.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=zp(y.name);k?hi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):hi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),t.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=Yp(e,y.name);D?D.projectId&&y.project.projectId&&D.projectId!==y.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),t.push(Bp(ll())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ll()}`,fix:"Reinstall document360-writer (broken install)"});let x=Te(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ie})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${ie}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!hi(k)||k.refreshToken)){let R={profile:y.name,connection:y.connection};try{await Gp(R);let S=await Vp(R,"/v3/projects");t.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=D?.projectId??y.project.projectId;if(C&&y.project.workspaceId)try{let S=await Jp(R,C,y.project.workspaceId);if(S){let N=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof sf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??C})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return t}function dl(e){let t=[""];for(let r of e){let i=r.level==="ok"?I("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(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?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function fn(e,t){console.log(f("Running checks\u2026"));for(let n of dl(await ul(t.cwd)))console.log(n);return{kind:"continue"}}var bo=Gn(()=>{"use strict";Ge();W()});import{Command as yg}from"commander";import{createRequire as kg}from"node:module";import{AUTH_MODES as bg}from"document360-engine";import{input as Cu}from"@inquirer/prompts";import{loginPkce as Pu,refreshTokens as Ru,toStoredTokens as Ms,clearTokens as Tu,decodeJwtClaims as Os,isExpired as Su,loadTokens as Du,saveTokens as Us,resolveActiveProfile as Xn,setProfileProject as ju,readProjectConfig as Au}from"document360-engine";W();import{select as du}from"@inquirer/prompts";import{resolveActiveProfile as pu,setProfileProject as fu,resolveProjectId as mu,listWorkspaces as hu}from"document360-engine";async function nn(e,t){let n=pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??mu(o);return{workspaces:await hu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Is=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function fr(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 Yn(e,t,n,o,r){fu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ns(e,t,n){let o;try{o=await nn(e,n)}catch(i){return console.log($(`Could not list workspaces: ${i.message}`)),1}let r=fr(o.workspaces,t);return r?(Yn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Nt(e,t){let n;try{n=await nn(e,t)}catch(y){console.log($(`Could not list workspaces: ${y.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let y of o)console.log(` ${y.id===c?_("\u25CF"):" "} ${Is(y)} ${f(y.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await du({message:"Select the Document360 workspace for this repo:",choices:o.map(y=>({name:`${Is(y)}${y.id===c?" (current)":""}`,value:y.id}))}),g=o.find(y=>y.id===p);Yn(e,i,r,p,g?.name),console.log(I(`\u2713 Workspace set to "${g?.name??p}" for profile "${i}".`))}W();import{select as gu}from"@inquirer/prompts";import{resolveActiveProfile as wu,setProfileProject as yu,listProjects as ku}from"document360-engine";async function Ve(e,t){let n=wu(e,t),o={profile:n.name,connection:n.connection};return{projects:await ku(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var _s=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function mr(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 zn(e,t,n,o){yu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ls(e,t,n){let o;try{o=await Ve(e,n)}catch(i){return console.log($(`Could not list projects: ${i.message}`)),1}let r=mr(o.projects,t);return r?(zn(e,o.profile,r.id,r.name),console.log(I(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function Kn(e,t){let n;try{n=await Ve(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===i?_("\u25CF"):" "} ${_s(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await gu({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${_s(g)}${g.id===i?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);zn(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import bu from"picocolors";function xu(e=process.env){return e.FORCE_HYPERLINK==="0"||!bu.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 $u(e,t=e,n){return xu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var vu=/https?:\/\/[^\s\x1b]+/g;function on(e,t){return e.replace(vu,n=>$u(n,n,t))}function Ws(e){return{...Os(e.idToken)??{},...Os(e.accessToken)??{}}}function Qn(e){let t=Ws(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 Jn(e){let t=Xn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Pu(n,{manual:e.manual,promptForRedirect:i=>Cu({message:i})},i=>console.log(on(i))),r=Ms(t.name,o);if(Us(r),await hr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Qn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Au(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Nt(process.cwd(),t.name))}catch{}}async function hr(e,t,n){let r=Ws(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Xn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ve(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}ju(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Fs(e){let t=Xn(process.cwd(),e.profile),n=t.connection,o=Du(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Qn(o)}`),Su(o))if(o.refreshToken)try{let r=Ms(t.name,await Ru(n,o.refreshToken));Us(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Hs(e){let t=Xn(process.cwd(),e.profile);Tu(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as qs,writeProjectConfig as Eu,resolveActiveProfile as Iu,loadTokens as Nu,isExpired as _u}from"document360-engine";function Zn(e){let t=qs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("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?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Nu(n),g=p?_u(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function eo(e,t){let n=qs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Eu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function to(e,t){try{let n=Iu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Lu,readdirSync as Ou,statSync as Bs}from"node:fs";import{join as Vs}from"node:path";import{apiLogDir as Mu}from"document360-engine";function Gs(){let e=Mu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Lu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ou(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(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let i=(Bs(Vs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let i=(Bs(Vs(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Uu,resolveAuth as Wu,findByName as Fu,slugify as Hu,touchSession as qu,upsertSession as Bu,resolveActiveProfile as Vu}from"document360-engine";async function Ys(e,t,n,o,r,i){let c=Wu(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Vu(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=Fu(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let y=Uu({cwd:e,resume:g,profileName:r,allowProdWrites:i===!0}),k=g??null,D=1;for await(let x of y.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let R=new Date().toISOString();Bu({uuid:k,name:Hu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:R,updatedAt:R})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(se(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&qu(k),process.stdout.write(`
216
+ `),"utf8")}async function $r(){let e=process.cwd(),t=aa(e);if(Ut(t)&&!await td({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=pa(e)??ia(e),o=await sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:ca}),i=await sn({message:"Screenshot output directory:",default:ua}),c=await sn({message:"Default connection profile name:",default:"berlin"}),p=await sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:la,captureDir:r,outputDir:i,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:fa(e)},y=id(e);y?.terminologyGlossary&&(g.terminologyGlossary=y.terminologyGlossary),sa(g,e),da(e);let k=Ot(e);console.log(""),console.log(I(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of Mt(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function pa(e){let t=ao(e,"package.json");if(!Ut(t))return null;try{return JSON.parse(nd(t,"utf8")).name??null}catch{return null}}function fa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ut(ao(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ao(e,n);Ut(o)&&!ad(o)&&t.push(n)}return t}function ad(e){try{return od(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var lo=Gn(()=>{"use strict";W();Ge()});var pl={};As(pl,{doctorCommand:()=>fn,renderDoctorChecks:()=>dl,runDoctorChecks:()=>ul});import{existsSync as Bp}from"node:fs";import{d360GetAll as Vp,getAccessToken as Gp,isExpired as hi,loadProfileMap as Yp,loadTokens as zp,packageSkillsDir as ll,projectConfigPath as Kp,readProjectConfig as Xp,DEFAULT_DOCS_DIR as Qp,fetchManifestSummary as Jp,resolveActiveProfile as Zp,classifyClaudeAuth as ef,CLAUDE_CODE_SETUP_HINT as cl,resolveModelSetting as tf,probeModel as nf,detectAppType as of,playbookSkillName as rf,D360AuthError as sf}from"document360-engine";async function ul(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=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 o=ef();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.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. ${cl}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:cl});let r=tf(e);if(t.push({level:"ok",label:`Model: ${r.model} (${r.source==="auto"?"auto \u2014 right-sized for docs; /model to change":r.source})`}),o.state==="ready"){let R=await nf(e,r.model??void 0);R.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?t.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"`}):t.push({level:"fail",label:`Model call failed \u2014 ${R.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 i=Xp(e);if(!i)return t.push({level:"fail",label:`No ${Kp(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${i.projectId}`});let c=(i.docsDir??Qp).replace(/\/+$/,"");t.push(i.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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=i.authoritativeSourceFiles??[];t.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=i.appType??of(e);if(g){let R=i.appType?"from config":"auto-detected",C=g==="web"||g==="cli";t.push({level:"ok",label:`Genre: ${g} (${R})${C?` \u2192 ${rf(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else t.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 y;try{y=Zp(e),t.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return t.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=zp(y.name);k?hi(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):hi(k)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(k.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),t.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=Yp(e,y.name);D?D.projectId&&y.project.projectId&&D.projectId!==y.project.projectId?t.push({level:"fail",label:`Category map projectId (${D.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(D.articles).length} articles, ${Object.keys(D.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),t.push(Bp(ll())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ll()}`,fix:"Reinstall document360-writer (broken install)"});let x=Te(e);if(x.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ie})`}):x.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${x.completedVersion}, current is v${ie}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!hi(k)||k.refreshToken)){let R={profile:y.name,connection:y.connection};try{await Gp(R);let S=await Vp(R,"/v3/projects");t.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){t.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=D?.projectId??y.project.projectId;if(C&&y.project.workspaceId)try{let S=await Jp(R,C,y.project.workspaceId);if(S){let N=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${N||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof sf||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??C})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return t}function dl(e){let t=[""];for(let r of e){let i=r.level==="ok"?I("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${i} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${_(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?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function fn(e,t){console.log(f("Running checks\u2026"));for(let n of dl(await ul(t.cwd)))console.log(n);return{kind:"continue"}}var bo=Gn(()=>{"use strict";Ge();W()});import{Command as yg}from"commander";import{createRequire as kg}from"node:module";import{AUTH_MODES as bg}from"document360-engine";import{input as Cu}from"@inquirer/prompts";import{loginPkce as Pu,refreshTokens as Ru,toStoredTokens as Ms,clearTokens as Tu,decodeJwtClaims as Os,isExpired as Su,loadTokens as Du,saveTokens as Us,resolveActiveProfile as Xn,setProfileProject as ju,readProjectConfig as Au}from"document360-engine";W();import{select as du}from"@inquirer/prompts";import{resolveActiveProfile as pu,setProfileProject as fu,resolveProjectId as mu,listWorkspaces as hu}from"document360-engine";async function nn(e,t){let n=pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??mu(o);return{workspaces:await hu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Is=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function fr(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 Yn(e,t,n,o,r){fu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ns(e,t,n){let o;try{o=await nn(e,n)}catch(i){return console.log($(`Could not list workspaces: ${i.message}`)),1}let r=fr(o.workspaces,t);return r?(Yn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(i=>i.name??i.id).join(", ")}`)),1)}async function Nt(e,t){let n;try{n=await nn(e,t)}catch(y){console.log($(`Could not list workspaces: ${y.message}`));return}let{workspaces:o,projectId:r,profile:i,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let y of o)console.log(` ${y.id===c?_("\u25CF"):" "} ${Is(y)} ${f(y.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await du({message:"Select the Document360 workspace for this repo:",choices:o.map(y=>({name:`${Is(y)}${y.id===c?" (current)":""}`,value:y.id}))}),g=o.find(y=>y.id===p);Yn(e,i,r,p,g?.name),console.log(I(`\u2713 Workspace set to "${g?.name??p}" for profile "${i}".`))}W();import{select as gu}from"@inquirer/prompts";import{resolveActiveProfile as wu,setProfileProject as yu,listProjects as ku}from"document360-engine";async function Ve(e,t){let n=wu(e,t),o={profile:n.name,connection:n.connection};return{projects:await ku(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var _s=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function mr(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 zn(e,t,n,o){yu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ls(e,t,n){let o;try{o=await Ve(e,n)}catch(i){return console.log($(`Could not list projects: ${i.message}`)),1}let r=mr(o.projects,t);return r?(zn(e,o.profile,r.id,r.name),console.log(I(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log($(`No project matches "${t}". Available: ${o.projects.map(i=>i.name??i.id).join(", ")}`)),1)}async function Kn(e,t){let n;try{n=await Ve(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:o,profile:r,current:i}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of o)console.log(` ${g.id===i?_("\u25CF"):" "} ${_s(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await gu({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${_s(g)}${g.id===i?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===c);zn(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import bu from"picocolors";function xu(e=process.env){return e.FORCE_HYPERLINK==="0"||!bu.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 $u(e,t=e,n){return xu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var vu=/https?:\/\/[^\s\x1b]+/g;function on(e,t){return e.replace(vu,n=>$u(n,n,t))}function Ws(e){return{...Os(e.idToken)??{},...Os(e.accessToken)??{}}}function Qn(e){let t=Ws(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 Jn(e){let t=Xn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Pu(n,{manual:e.manual,promptForRedirect:i=>Cu({message:i})},i=>console.log(on(i))),r=Ms(t.name,o);if(Us(r),await hr(r,t.name,i=>console.log(f(i))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Qn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Au(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Nt(process.cwd(),t.name))}catch{}}async function hr(e,t,n){let r=Ws(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Xn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await Ve(process.cwd(),t);c=p.find(g=>g.id===r)?.name}catch{}ju(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Fs(e){let t=Xn(process.cwd(),e.profile),n=t.connection,o=Du(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Qn(o)}`),Su(o))if(o.refreshToken)try{let r=Ms(t.name,await Ru(n,o.refreshToken));Us(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Hs(e){let t=Xn(process.cwd(),e.profile);Tu(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as qs,writeProjectConfig as Eu,resolveActiveProfile as Iu,loadTokens as Nu,isExpired as _u}from"document360-engine";function Zn(e){let t=qs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("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?_("\u25CF "):" ",i=o.production?L(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Nu(n),g=p?_u(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${_(n)} \u2192 ${c}${i} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function eo(e,t){let n=qs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Eu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function to(e,t){try{let n=Iu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as Lu,readdirSync as Ou,statSync as Bs}from"node:fs";import{join as Vs}from"node:path";import{apiLogDir as Mu}from"document360-engine";function Gs(){let e=Mu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Lu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ou(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(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let i=(Bs(Vs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${i} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let i=(Bs(Vs(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${i} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Uu,resolveAuth as Wu,findByName as Fu,slugify as Hu,touchSession as qu,upsertSession as Bu,resolveActiveProfile as Vu}from"document360-engine";async function Ys(e,t,n,o,r,i){let c=Wu(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Vu(e,r)}catch(x){console.error($(`Document360 profile error: ${x.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),i||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(o){let x=Fu(e,o);x||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=x.uuid,console.error(f(`Resuming "${x.name}"`))}let y=Uu({cwd:e,resume:g,profileName:r,allowProdWrites:i===!0}),k=g??null,D=1;for await(let x of y.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let R=new Date().toISOString();Bu({uuid:k,name:Hu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:R,updatedAt:R})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(se(` \u2699 ${x.name}`));break;case"result":D=x.ok?0:1,console.error(f(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${x.message}`)),process.exit(1)}k&&qu(k),process.stdout.write(`
217
217
  `),process.exit(D)}import{createInterface as Sm}from"node:readline/promises";import{createSession as Bi,resolveAuth as Dm,getSession as jm,setTitle as Am,slugify as Em,touchSession as Xl,upsertSession as Im,generateTitle as Nm,resolveActiveProfile as Ql,resolveModelSetting as _m,readProjectConfig as Lm,resolveAndPersistAppType as Om,decodeJwtClaims as Kl,isExpired as Mm,loadTokens as Um,isDirectiveMention as Wm,stripDirectiveMention as Fm,appendDirective as Hm}from"document360-engine";var Re=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/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:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author 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 run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{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:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{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:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/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:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Gu(e){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":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function zs(){let e=["document360-writer \u2014 help",""];for(let t of Re){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Gu(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function gr(){console.log("");for(let e of zs())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Yu}from"document360-engine";async function Ks(e,t){let n=t.currentUuid(),o=n?Yu(n):void 0;return console.log(o?f(`
218
218
  (conversation reset \u2014 "${o.name}" is still available via /resume)
219
219
  `):f(`
@@ -271,7 +271,7 @@ Articles:
271
271
  `+e.paths.map(r=>`- ${r}`).join(`
272
272
  `)}function ti(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,i]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${me(r)}\u2013${me(i)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ni(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),g=e.reduce((C,S)=>C+S.costUsd,0),y=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${me(g)} total`:ze(y),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,R=[];if(i.length===0)R.push(`Wrote ${x(c)} (${D}) successfully \xB7 ${k}.`),R.push("Next \u2014 push them to Document360:"),R.push("/publish --all"),R.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{R.push(`Wrote ${p}/${x(c)} (${D}) \xB7 ${k}.`),R.push(`${i.length} partition${i.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of i)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return R}function oi(e,t,n){try{let o=yp({cwd:e,paths:n.map(i=>`${t}/${i}`)});if(o.length===0)return null;let r=new Set(o.map(i=>i.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function ri(e,t,n){let o=(Va(e)?.docsDir??xp).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Rp(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let i=Tp(r,n.scope);if(n.scope&&i.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:i,planCount:r.length,rewriting:!0};let c=Jr(e,o,i);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Ga(e,t){if(!Va(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};if(wo(e)){for(let O of Fa(t.cwd,t.profileName))console.log(f(O));return{kind:"continue"}}let n=bp(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:i,concurrency:c,rewrite:p}=Qr(e),{docsDir:g,targets:y,reason:k,rewriting:D}=ri(t.cwd,n,{scope:o,path:r,rewrite:p});if(y.length===0)return console.log(k?L(k):L("Nothing to write.")),{kind:"continue"};D&&console.log(L(`--rewrite: regenerating ${y.length} already-written article${y.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=kp(y),R=Xr(c),{model:C,forced:S}=$p(t.cwd,"standard"),N=!!r;if(i&&!N){let O=wp({files:Zr(t.cwd,n,y),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${y.length} pending).`));for(let K of ti(x,O,R))console.log(K);return console.log(f(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${y.length} article${y.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${R} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let O of vp({cwd:t.cwd,partitions:x,promptFor:K=>ei(K,g,{rewrite:D||N}),concurrency:R,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(I(` \u2713 ${O.label}`)):console.log($(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let K=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Z of ni(O.results,x,K))console.log(O.ok?I(Z):L(Z));let ce=oi(t.cwd,g,y);ce&&console.log(L(ce))}}catch(O){console.log($(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Sp,readdirSync as Ya,statSync as za}from"node:fs";import{join as Ka}from"node:path";import{inputDir as Dp,readProjectConfig as jp}from"document360-engine";var Xa=/\.(md|markdown|pdf|txt)$/i;function ii(e){let t=Dp(e);if(!Sp(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Ya(t)){let i=Ka(t,r),c=!1;try{c=za(i).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Ap(i);p>0&&n.push({name:r,docCount:p})}else Xa.test(r)&&o++}return n.sort((r,i)=>r.name.localeCompare(i.name)),{features:n,looseDocs:o}}function Ap(e){let t=0;for(let n of Ya(e))try{za(Ka(e,n)).isFile()&&Xa.test(n)&&t++}catch{}return t}function si(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 yo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
273
273
  `)}var ai="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Qa(e,t){let n=t?.cwd??process.cwd();if(!jp(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=ii(n);if(o.length===0&&r===0)return console.log(f(ai)),{kind:"continue"};let i=e.join(" ").trim();if(!i){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:yo(p),display:p?`/draft ${p}`:"/draft"}}let c=si(o,i);return{kind:"forward-to-agent",prompt:yo(c??"",c?void 0:i),display:`/draft ${i}`}}W();import{listOpenForDocs as Ep,readProjectConfig as Ip}from"document360-engine";function li(e){try{return Ep(e).filter(t=>t.kind==="request").length}catch{return 0}}function ci(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function ui(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
274
- `)}var di="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Ja(e,t){let n=t?.cwd??process.cwd();if(!Ip(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ci(e);if(!r&&li(n)===0)return console.log(f(di)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ui(r,o),display:i}}W();import{search as Np}from"@inquirer/prompts";import{findByName as _p,getSession as Lp,listSessions as Op,relativeTime as el}from"document360-engine";async function tl(e,t){let n=Op(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("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=_p(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Za(n),{kind:"continue"})}if(!process.stdin.isTTY)return Za(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Np({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${el(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Lp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Za(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(el(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Mp}from"document360-engine";function pi(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 nl(e,t){let n=pi(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Mp(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(I(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ol,readProjectConfig as Up,writeProjectConfig as Wp}from"document360-engine";W();function fi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Up(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 ol().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Wp(o,e),null):`Unknown environment "${r}". Known: ${ol().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function rl(e,t){let n=e[0];if(!n)return Zn(t.cwd),{kind:"continue"};if(n==="add"){let o=fi(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return eo(t.cwd,n),to(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Fp}from"@inquirer/prompts";import{readProjectConfig as Hp,readUserConfig as il,resolveModelSetting as mi,writeUserConfig as sl}from"document360-engine";var Ie=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{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 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function ko(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Ie.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function qp(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"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function pn(e,t){let n=()=>{let i=mi(e);return i.source==="project"||i.source==="user"||i.source==="env"?i.model??void 0:void 0};if(t==="default"){let i=il();return i.defaultModel?(delete i.defaultModel,sl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${mi(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}sl({...il(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Hp(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 al(e,t){let n=e[0]?.trim();if(!n){let c=mi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model??"Claude Code default")}`),console.log(f(` source: ${qp(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ko(c),g;try{g=await t.withPausedInput(()=>Fp({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Ie[p].value,choices:Ie.map((x,R)=>({name:`${x.label}${R===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:y,changed:k,effective:D}=pn(t.cwd,g??"default");for(let x of y)console.log(x.startsWith("\u26A0")?L(x):x.startsWith("\u2713")?I(x):f(x));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=pn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?I(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}bo();async function fl(e,t){return await t.withPausedInput(()=>Nt(t.cwd)),{kind:"clear"}}async function ml(e,t){return await t.withPausedInput(()=>Kn(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as af}from"document360-engine";async function hl(e,t){let n=!1;try{n=af(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var gl=async(e,t)=>{try{await t.withPausedInput(()=>Jn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as lf,clearTokens as cf,clearProfileProject as uf}from"document360-engine";async function wl(e,t){let n;try{n=lf(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=cf(n);return uf(t.cwd,n),console.log(o?I(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as yl}from"node:fs";import{isAbsolute as df,join as pf,resolve as ff}from"node:path";import{readProjectConfig as mf,screenshotPlaceholderIds as hf,DEFAULT_CAPTURE_DIR as gf,DEFAULT_OUTPUT_DIR as wf}from"document360-engine";var kl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gi(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?kl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:kl(o),setup:t}:{mode:"single",id:o}}function wi(e,t){let n=mf(e),o=n?.captureDir??gf,r=n?.outputDir??wf,i=(c,p)=>df(c)?pf(c,p):ff(e,c,p);return hf(e,{scope:t}).map(({id:c,file:p})=>{let g=yl(i(r,`${c}.png`))?"captured":yl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var yf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},kf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function yi(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${yf[c.state]} ${c.id.padEnd(34)} ${kf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function bl(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
274
+ `)}var di="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Ja(e,t){let n=t?.cwd??process.cwd();if(!Ip(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=ci(e);if(!r&&li(n)===0)return console.log(f(di)),{kind:"continue"};let i=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:ui(r,o),display:i}}W();import{search as Np}from"@inquirer/prompts";import{findByName as _p,getSession as Lp,listSessions as Op,relativeTime as el}from"document360-engine";async function tl(e,t){let n=Op(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("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=_p(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Za(n),{kind:"continue"})}if(!process.stdin.isTTY)return Za(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Np({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async i=>{let c=(i??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${el(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Lp(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Za(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${f(el(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Mp}from"document360-engine";function pi(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 nl(e,t){let n=pi(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Mp(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(I(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ol,readProjectConfig as Up,writeProjectConfig as Wp}from"document360-engine";W();function fi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Up(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 ol().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Wp(o,e),null):`Unknown environment "${r}". Known: ${ol().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function rl(e,t){let n=e[0];if(!n)return Zn(t.cwd),{kind:"continue"};if(n==="add"){let o=fi(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return eo(t.cwd,n),to(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Fp}from"@inquirer/prompts";import{readProjectConfig as Hp,readUserConfig as il,resolveModelSetting as mi,writeUserConfig as sl}from"document360-engine";var Ie=[{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 ko(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ie.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function qp(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 pn(e,t){let n=()=>mi(e).model;if(t==="default"){let i=il();return i.defaultModel?(delete i.defaultModel,sl(i),{lines:[`\u2713 Personal model override cleared \u2014 now: ${mi(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}}sl({...il(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Hp(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 al(e,t){let n=e[0]?.trim();if(!n){let c=mi(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${_(c.model)}${c.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${qp(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=ko(c),g;try{g=await t.withPausedInput(()=>Fp({message:`Select model (current: ${c.model}${c.source==="auto"?" \xB7 auto":""})`,default:Ie[p].value,choices:Ie.map((x,R)=>({name:`${x.label}${R===p?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:y,changed:k,effective:D}=pn(t.cwd,g??"default");for(let x of y)console.log(x.startsWith("\u26A0")?L(x):x.startsWith("\u2713")?I(x):f(x));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:i}=pn(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?I(c):f(c));return r&&await t.setModel(i),{kind:"continue"}}bo();async function fl(e,t){return await t.withPausedInput(()=>Nt(t.cwd)),{kind:"clear"}}async function ml(e,t){return await t.withPausedInput(()=>Kn(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as af}from"document360-engine";async function hl(e,t){let n=!1;try{n=af(t.cwd).production}catch{}return n?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var gl=async(e,t)=>{try{await t.withPausedInput(()=>Jn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as lf,clearTokens as cf,clearProfileProject as uf}from"document360-engine";async function wl(e,t){let n;try{n=lf(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=cf(n);return uf(t.cwd,n),console.log(o?I(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as yl}from"node:fs";import{isAbsolute as df,join as pf,resolve as ff}from"node:path";import{readProjectConfig as mf,screenshotPlaceholderIds as hf,DEFAULT_CAPTURE_DIR as gf,DEFAULT_OUTPUT_DIR as wf}from"document360-engine";var kl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gi(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?kl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:kl(o),setup:t}:{mode:"single",id:o}}function wi(e,t){let n=mf(e),o=n?.captureDir??gf,r=n?.outputDir??wf,i=(c,p)=>df(c)?pf(c,p):ff(e,c,p);return hf(e,{scope:t}).map(({id:c,file:p})=>{let g=yl(i(r,`${c}.png`))?"captured":yl(i(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var yf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},kf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function yi(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(i=>i.file))].sort(),o=e.filter(i=>i.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let i of n){r.push(i);for(let c of e.filter(p=>p.file===i))r.push(` ${yf[c.state]} ${c.id.padEnd(34)} ${kf[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function bl(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
275
275
  `),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
276
276
  `)}async function xo(e,t){let n=gi(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of yi(wi(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
277
277
  `),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.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.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
@@ -288,7 +288,7 @@ Articles:
288
288
  \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.localAhead>0){let n=e.localAhead;t.push({bullet:`${n} article${Ne(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${Ne(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${Ne(n)} up.`})}if(e.behind>0){let n=e.behind;t.push({bullet:`${n} code change${Ne(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${Ne(n)}.`})}return t}function Fl(e,t){let n=t.filter(i=>i.bullet).map(i=>` \u2022 ${i.bullet}`),o=t[0],r=[];o.lead?r.push(Li(o.lead)):o.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let i of t.slice(1,3))i.follow&&r.push(i.follow);return[e,...n,r.join(" "),dm].join(`
289
289
  `)}function yn(e){if(!e.ready)return{kind:"idle"};let t=mm(e);if(!e.hasDocs){let o=t[0];return o&&(o.lead?.kind==="cmd"||o.picker)?{kind:"recommend",rec:{note:Fl("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:pm,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0)return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${Ne(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.`,tone:"info",lead:null,picker:null}};let n=t[0];return n.lead?.kind==="cmd"&&n.lead.cmd==="/audit"&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Ne(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Fl("Welcome back \u2014 where your docs stand:",t),tone:n.tone??"info",lead:n.lead,picker:n.picker}}}import{existsSync as Oi,readdirSync as Ui}from"node:fs";import{spawnSync as hm}from"node:child_process";import{join as Do}from"node:path";import{readProjectConfig as ql,resolveActiveProfile as Bl,loadTokens as gm,isExpired as wm,loadProfileMap as Vl,countLocalAhead as ym,readDocsPlan as km,devHintsGuidePath as bm,DEFAULT_DOCS_DIR as Mi}from"document360-engine";Ge();function Hl(e){try{return Ui(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Wi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Hl(Do(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Hl(Do(e,o)))}function Fi(e,t){try{let n=ql(e);if(!n)return!1;let o=Bl(e,t),r=Vl(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let i=Do(e,(n.docsDir??Mi).replace(/\/+$/,""));return!!(Oi(i)&&Ui(i).length>0||Oi(bm(e)))}catch{return!1}}function kn(e,t,n){try{let o=ql(e);if(!o)return null;let r=Bl(e,t),i=gm(r.name),c=!!i&&(!wm(i)||!!i.refreshToken),p=Fi(e,t)||!Wi(e,o.authoritativeSourceFiles),g=Vl(e,r.name),y=g?Object.keys(g.articles).length:0,k=Do(e,(o.docsDir??Mi).replace(/\/+$/,"")),D=!1;try{D=Oi(k)&&Ui(k).length>0}catch{}let x=0;if(g?.lastAnalyzedCommit)try{let K=hm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});K.status===0&&(x=parseInt((K.stdout||"").trim(),10)||0)}catch{}let R=0;try{let K=km(e);if(K.length>0){let ce=(o.docsDir??Mi).replace(/\/+$/,"");R=Jr(e,ce,K.map(Z=>Z.path)).length}}catch{}let C=hn(e),S=gn({...C,directives:0}),N=ym(e,t),O=Te(e);return{ready:c&&p&&!n.claudeMissing,hasDocs:D,tracked:y,pendingText:S,directives:C.directives,behind:x,pendingWrites:R,localAhead:N,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:O.status,devhintsCompletedVersion:O.completedVersion,devhintsToVersion:ie,builderStarted:Oe(e),genreUnknown:n.genreUnknown}}catch{return null}}W();var xm={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"},Yl=160,qi=200,zl=40;function we(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Gl(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}: ${we(typeof r=="string"?r:JSON.stringify(r),zl)}`);return t.length>4&&n.push("\u2026"),we(n.join(", "),Yl)}var Ke=e=>typeof e=="string"&&e?e:null,Hi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function $m(e){let t=Ke(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}function vm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ke(t.title);if(!o)return null;let r=$m(t.local_path);return n("Create article",`"${we(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ke(t.title),r=Hi(t.article_id);return n("Update article",o?`"${we(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Hi(t.article_id)?`id ${Hi(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",Ke(t.name)?`"${we(Ke(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ke(t.file_path);return n("Upload image",o?we(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function jo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...i]=e.split("__"),c=i.join("__");if(r==="document360"){let y=vm(c,t);if(y)return y}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Gl(t)}}let n=xm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:we(o,Yl)}:{title:e,sep:"",arg:Gl(t)}}function Cm(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 Pm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Cm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>we(r,qi))]}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}: ${we(String(r),zl)}`);return n.length>0?[we(n.join(" \xB7 "),qi)]:null}return null}function Rm(e){let t=Ke(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Tm(e,t,n){switch(e){case"d360_create_article":{let o=Rm(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=Ke(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 ${we(o[0],120)}`:""}`]}default:return null}}function Ao(e,t=4,n,o){let r=e.replace(/\r\n/g,`
290
290
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Tm(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let i=Pm(r)??r.split(`
291
- `);return{lines:i.slice(0,t).map(c=>we(c,qi)),hidden:Math.max(0,i.length-t)}}function Eo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Io(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 No(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var qm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Bm(e,t,n,o){if(qm.test(e))try{let r=Ql(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Io(t,n),p=No(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Eo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function Jl(e=process.cwd(),t="auto",n){let o=Dm(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Vm(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,i=Bi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Sm({input:process.stdin,output:process.stdout}),g=[],y=null,k=!1;p.on("line",R=>{if(y){let C=y;y=null,C(R)}else g.push(R)}),p.on("close",()=>{if(k=!0,y){let R=y;y=null,R(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(R=>{y=R}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Bi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await D();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let S=Wl(C);if(!S)continue;let N=Ul[S.name];if(!N){console.log($(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let O=await N(S.args,x);if(O.kind==="exit")break;if(O.kind==="clear"){x.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(I("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){i.close(),i=Bi({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let K=jm(O.uuid);c={uuid:O.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},Xl(O.uuid),console.log(I(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"?(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await Vi(i,O.prompt,o,c,e)):Gm(e,n);continue}if(Wm(C)){let S=Fm(C);if(S){try{Hm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await Vi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". 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 "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=C),await Vi(i,C,o,c,e)}}}finally{i.close(),p.close()}}function Vm(e,t){console.log(""),console.log(tn("document360-writer")),console.log(f(` cwd: ${e}`));let n=_m(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Ym(e,t)),!Lm(e))console.log(L(" 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(ro(e),!Oe(e))for(let r of io(e))console.log(L(` ${r}`))}catch{}try{let r=Om(e);r.persisted&&r.appType?console.log(f(` \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=kn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?yn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
291
+ `);return{lines:i.slice(0,t).map(c=>we(c,qi)),hidden:Math.max(0,i.length-t)}}function Eo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Io(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 No(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var qm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Bm(e,t,n,o){if(qm.test(e))try{let r=Ql(o),i=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Io(t,n),p=No(n);e.endsWith("publish_article")&&p&&console.log(_(` \u2B95 Live: ${p}`)),c&&i&&console.log(_(` \u2B95 Preview: ${Eo(r.connection.portalUrl,i,c,r.project.languageCode??"en")}`))}catch{}}async function Jl(e=process.cwd(),t="auto",n){let o=Dm(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${_("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${_('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Vm(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,i=Bi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=Sm({input:process.stdin,output:process.stdout}),g=[],y=null,k=!1;p.on("line",R=>{if(y){let C=y;y=null,C(R)}else g.push(R)}),p.on("close",()=>{if(k=!0,y){let R=y;y=null,R(null)}});function D(){return g.length>0?Promise.resolve(g.shift()):k?Promise.resolve(null):(process.stdout.write(_("> ")),new Promise(R=>{y=R}))}let x={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{i.close(),i=Bi({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:R=>{c.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await D();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let S=Wl(C);if(!S)continue;let N=Ul[S.name];if(!N){console.log($(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let O=await N(S.args,x);if(O.kind==="exit")break;if(O.kind==="clear"){x.restartAgent();continue}if(O.kind==="allow-prod"){r=!0,x.restartAgent(),console.log(I("\u2713 Production writes authorized for this session.")),console.log("");continue}if(O.kind==="resume"){i.close(),i=Bi({cwd:e,resume:O.uuid,profileName:n,allowProdWrites:r});let K=jm(O.uuid);c={uuid:O.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},Xl(O.uuid),console.log(I(`\u2713 Resumed "${O.name}"`)),console.log("");continue}O.kind==="forward-to-agent"?(c.firstPrompt||(c.firstPrompt=O.display??O.prompt),await Vi(i,O.prompt,o,c,e)):Gm(e,n);continue}if(Wm(C)){let S=Fm(C);if(S){try{Hm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=C),await Vi(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". 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 "${S}" and the article path(s) you wrote.`,o,c,e);continue}}c.firstPrompt||(c.firstPrompt=C),await Vi(i,C,o,c,e)}}}finally{i.close(),p.close()}}function Vm(e,t){console.log(""),console.log(tn("document360-writer")),console.log(f(` cwd: ${e}`));let n=_m(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ym(e,t)),!Lm(e))console.log(L(" 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(ro(e),!Oe(e))for(let r of io(e))console.log(L(` ${r}`))}catch{}try{let r=Om(e);r.persisted&&r.appType?console.log(f(` \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=kn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),i=r?yn(r):null;if(i?.kind==="recommend"&&i.rec.note){let c=i.rec.tone==="warn"?L:f;for(let p of i.rec.note.split(`
292
292
  `))console.log(c(` ${p}`));i.rec.picker&&console.log(_(` Pick one: ${i.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Gm(e,t){try{let n=kn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?yn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${Li(o.rec.lead)}`))}catch{}}function Ym(e,t){try{let n=Ql(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Um(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let i={...Kl(r.idToken)??{},...Kl(r.accessToken)??{}},c=i.email??i.preferred_username??"signed in";return Mm(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function zm(){console.error(""),console.error(`Sign in with your Claude subscription: run ${_("claude")} once, then retry.`),console.error(` (No Claude Code? ${_("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${_("https://console.anthropic.com/settings/keys")}`)}function Km(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Im({uuid:t,name:r??Em(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Xm(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Nm(o,t).then(r=>{r&&Am(n,r)}).catch(()=>{})}async function Vi(e,t,n,o,r){let i=new Map;for await(let c of e.send(t))Qm(c,o,r,n,i)}function Qm(e,t,n,o,r){switch(e.type){case"session":t.uuid||Km(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=jo(e.name,e.input);i&&(process.stdout.write(`
293
293
 
294
294
  `),console.log(`${I("\u25CF")} ${Pe(i.title)}${i.arg!==null?se(`${i.sep}(${i.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let c=p=>p===1?"":"s";console.log(se(` \u23BF Added ${i.added} line${c(i.added)}, removed ${i.removed} line${c(i.removed)}`));for(let p of i.lines)console.log(p);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=Ao(e.output,4,e.isError?void 0:i.name,i.input),p=e.isError?$:se;c.lines.forEach((g,y)=>console.log(p((y===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Bm(i.name,i.input,e.output,n);break}case"result":process.stdout.write(`
@@ -303,9 +303,9 @@ Articles:
303
303
  `)){if(i.length===0)o.push({start:r,end:r});else for(let c=0;c<i.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,i.length)});r+=i.length+1}return o.length>0?o:[{start:0,end:0}]}function Ho(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function vc(e,t,n){let o=Ho(e,t),r=o+n;if(r<0||r>=e.length)return t;let i=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+i,e[r].end)}function Cc(e,t,n){let o=e[Ho(e,t)];return n==="start"?o.start:o.end}function Pc(e,t,n){let o=Math.max(1,n),r=e.split(`
304
304
  `),i=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(i+=Math.max(1,Math.ceil(p.length/o)),i>=t){let g=i-t;return{text:[g>0?p.slice(g*o):p,...r.slice(c+1)].join(`
305
305
  `),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function Rc(e){let t=!1,n=0,o=0;for(let r of e.split(`
306
- `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as Vo,jsx as E,jsxs as B}from"react/jsx-runtime";var og={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Uc=` 1. /init \u2014 pick your Document360 environment & scaffold config
306
+ `)){let i=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&i<e.length&&(n=i+1),o=i+1}return n}import{Fragment as Vo,jsx as E,jsxs as B}from"react/jsx-runtime";var og={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Uc=` 1. /init \u2014 pick your Document360 environment & scaffold config
307
307
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
308
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function rg(e,t,n,o){let r=ts(n),i=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)",c=ns(e),p=ee(e),g=(p?.docsDir??Hc).replace(/\/+$/,""),y=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:i,model:c.model??"Claude Code default model",modelSource:og[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:y};if(p===null)return k;try{let D=ye(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let x=mt(D.name);if(x){let R={...Ht(x.idToken)??{},...Ht(x.accessToken)??{}},C=R.email??R.preferred_username??"signed in";Xe(x)?x.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function ig(e,t){try{let n=ye(e,t),o=mt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ht(o.idToken)??{},...Ht(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return Xe(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Wc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],qt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],sg="Ask me to write or update an article\u2026";function vn({ch:e,dim:t}){let[n,o]=U(!0);return ke(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ag=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Fc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var lg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cg({startTime:e,chars:t}){let[n,o]=U(0);ke(()=>{let g=setInterval(()=>o(y=>y+1),120);return()=>clearInterval(g)},[]);let r=qt[n%qt.length],i=Wc[Math.floor(n/16)%Wc.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[E(j,{color:F,children:` ${r} ${i}\u2026 `}),E(j,{color:"gray",children:`(${ln(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function ug({text:e}){let[t,n]=U(0);return ke(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(te,{paddingX:1,children:E(j,{color:F,children:`${qt[t%qt.length]} ${e}`})})}var dg=12e4;function pg({p:e}){let[t,n]=U(0);ke(()=>{let N=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(N)},[]);let o=qt[t%qt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=dg,g=e.verb??"Converting",y=e.unit??"article",k=e.rows.reduce((N,O)=>N+O.items,0),D=g.toLowerCase(),x=e.rows,R=0;if(x.length>Wo){let N=x.findIndex(K=>K.status==="active"||K.status==="pending"),O=Math.max(0,Math.min(N-2,x.length-Wo));R=x.slice(0,O).filter(K=>K.status==="done").length,x=x.slice(O,O+Wo)}let C=Math.min(40,Math.max(...x.map(N=>zi(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?F:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[E(j,{color:F,children:` ${o} ${g} ${k} ${y}${k===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${ln(r)} \xB7 esc to stop`})]}),R>0&&E(j,{dimColor:!0,children:` \u2714 +${R} done`}),x.map(N=>B(j,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${hc[N.status]} ${zi(N.label).padEnd(C)}`,N.status==="active"&&N.itemsDone!==void 0?` (${N.itemsDone}/${N.items} ${y}${N.items===1?"":"s"})`:N.status!=="pending"?` (${N.items} ${y}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${ln(i)} \u2014 press esc to stop if it's wedged`})]})}var fg=10800*1e3;function qc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ph(),[i,c]=U(n),[p,g]=U(null),[y,k]=U({text:"",pos:0}),D=y.text,x=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),R=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=$c(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,N]=U(!1),[O,K]=U(!1),[ce,Z]=U(0),[de,Cn]=U(null),[Go,ss]=U(null),[Qe,Je]=U([]),Pn=J(!1),Yo=J(!1),[zo,as]=U(!1),Rn=J(0),[Qc,Tn]=U(!1),[Jc,Sn]=U(!1),[Ko,ls]=U(null),[Zc,ht]=U(0),Ze=J(0),[Bt,gt]=U(0),[wt,Dn]=U(null),cs=J(new Map),eu=J(0),yt=J([]),be=J(null);be.current===null&&(be.current=Tc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=J({uuid:null,firstPrompt:null,titleFired:!1}),jn=J(new Map),kt=J(!1),Xo=J([]),De=J([]),An=J(null),[us,et]=U(null),Qo=J(null),[tt,nt]=U(null),[Le,bt]=U(null),[We,xt]=U(null),[pe,$t]=U(null),[xe,ot]=U(null),[rt,vt]=U(null),[Fe,Ct]=U(null),[ds,Vt]=U(null),[$e,it]=U(null),[he,Pt]=U(null),[ps,Jo]=U([]),st=J([]),Gt=J(!1),ve=J(null),[En,ne]=U(null),[fs,ms]=U(null),In=J(!1),Nn=J(null),Yt=J(null),[Ce,at]=U(null),[Zo,zt]=U(null),[hs,Rt]=U(0),[gs,Tt]=U(0),[tu,ws]=U(0),er=Xi(()=>{try{return ns(e).model??"auto"}catch{return null}},[e,tu]),{stdout:je}=mh(),[,nu]=U(0),ys=J(`${je.columns??80}x${je.rows??24}`),He=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{yt.current.push(l),console.log(jr(l,He()))},[He]),fe=V((l,a)=>{Rn.current++,Cn(l),ss(a??null)},[]),qe=V(()=>{Rn.current++,Cn(null),ss(null)},[]),Y=V(l=>fe(l,So({kind:"cmd",cmd:l,reason:""})),[fe]),ks=V((l,a)=>{!a?.silent&&l.note&&d({kind:"note",tone:l.tone,text:l.note}),l.picker&&(Je(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Vt(l.picker.title)),l.lead&&fe(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,So(l.lead))},[d,fe]),St=V((l,a,s="info")=>{l&&d({kind:"note",tone:s,text:l}),a&&fe(a.kind==="cmd"?a.cmd:a.text,So(a))},[d,fe]),[Kt,tr]=U(null),[ou,bs]=U(!1),Dt=V(l=>{tr(l),bs(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),nr=J(!1),or=V(async()=>{try{if(nr.current||!Kh(zh())||ee(e)?.mode==="engineer")return;let l=await Yh({pkg:pt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;nr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Sn(!0),(await Co().finally(()=>Sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y("/exit"),ls(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${vo}`})}catch{}},[e,o,d,Y]),rr=V(l=>{let a=Me(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),Yt.current=l,Y("/login"),!1)},[e,i,d,Y]),[ir,sr]=U(null),Xt=J(!0),_n=J(0),Qt=J(0);ke(()=>{let l=setInterval(()=>{if(Xt.current){_n.current=0,Qt.current=0;return}if(!S)try{if(!xn(Nc(e)))return;if(Te(e).status==="current"){Xt.current=!0,_n.current=0,Qt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),tr(null),fe("write the docs for this repo");return}_n.current+=1;let a=_n.current;if((a===4||a%15===0)&&Qt.current<3){Qt.current+=1;let s=Qt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Oe(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\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.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),ke(()=>{let l=us??$n(e);if(!S){_o(0),Ft(`${Oo} ${l}`);return}_o(3);let a=0;Ft(`${Lo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Lo.length,Ft(`${Lo[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,us]),ke(()=>()=>_o(0),[]);let Jt=V(l=>{let a=kn(e,i,{claudeMissing:ts(t).state==="missing",allowAutoAudit:l,genreUnknown:Yo.current});return a?yn(a):{kind:"idle"}},[e,i,t]);ke(()=>{let l=performance.now(),a=[],s=(w,P)=>{let T=performance.now();try{return P()}finally{let z=Math.round(performance.now()-T);z>=80&&a.push(`${w}: ${z}ms`)}};d({kind:"banner",info:s("banner",()=>rg(e,o,t,i))});let h=ts(t).state==="missing";if(h&&d({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.
308
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function rg(e,t,n,o){let r=ts(n),i=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)",c=ns(e),p=ee(e),g=(p?.docsDir??Hc).replace(/\/+$/,""),y=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:i,model:c.model,modelSource:og[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:y};if(p===null)return k;try{let D=ye(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let x=mt(D.name);if(x){let R={...Ht(x.idToken)??{},...Ht(x.accessToken)??{}},C=R.email??R.preferred_username??"signed in";Xe(x)?x.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function ig(e,t){try{let n=ye(e,t),o=mt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ht(o.idToken)??{},...Ht(o.accessToken)??{}},i=r.email??r.preferred_username??"signed in";return Xe(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var Wc=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],qt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],sg="Ask me to write or update an article\u2026";function vn({ch:e,dim:t}){let[n,o]=U(!0);return ke(()=>{let r=setInterval(()=>o(i=>!i),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var ag=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Fc(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var lg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cg({startTime:e,chars:t}){let[n,o]=U(0);ke(()=>{let g=setInterval(()=>o(y=>y+1),120);return()=>clearInterval(g)},[]);let r=qt[n%qt.length],i=Wc[Math.floor(n/16)%Wc.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[E(j,{color:F,children:` ${r} ${i}\u2026 `}),E(j,{color:"gray",children:`(${ln(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function ug({text:e}){let[t,n]=U(0);return ke(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(te,{paddingX:1,children:E(j,{color:F,children:`${qt[t%qt.length]} ${e}`})})}var dg=12e4;function pg({p:e}){let[t,n]=U(0);ke(()=>{let N=setInterval(()=>n(O=>O+1),150);return()=>clearInterval(N)},[]);let o=qt[t%qt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),i=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=dg,g=e.verb??"Converting",y=e.unit??"article",k=e.rows.reduce((N,O)=>N+O.items,0),D=g.toLowerCase(),x=e.rows,R=0;if(x.length>Wo){let N=x.findIndex(K=>K.status==="active"||K.status==="pending"),O=Math.max(0,Math.min(N-2,x.length-Wo));R=x.slice(0,O).filter(K=>K.status==="done").length,x=x.slice(O,O+Wo)}let C=Math.min(40,Math.max(...x.map(N=>zi(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?F:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[E(j,{color:F,children:` ${o} ${g} ${k} ${y}${k===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${ln(r)} \xB7 esc to stop`})]}),R>0&&E(j,{dimColor:!0,children:` \u2714 +${R} done`}),x.map(N=>B(j,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${hc[N.status]} ${zi(N.label).padEnd(C)}`,N.status==="active"&&N.itemsDone!==void 0?` (${N.itemsDone}/${N.items} ${y}${N.items===1?"":"s"})`:N.status!=="pending"?` (${N.items} ${y}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${D}\u2026`:""]},N.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${ln(i)} \u2014 press esc to stop if it's wedged`})]})}var fg=10800*1e3;function qc({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ph(),[i,c]=U(n),[p,g]=U(null),[y,k]=U({text:"",pos:0}),D=y.text,x=V(l=>{k(a=>{let s=typeof l=="function"?l(a.text):l;return{text:s,pos:s.length}})},[]),R=V(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=V(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),s=$c(a)??a.slice(0,-1);return{text:s+l.text.slice(l.pos),pos:s.length}})},[]),[S,N]=U(!1),[O,K]=U(!1),[ce,Z]=U(0),[de,Cn]=U(null),[Go,ss]=U(null),[Qe,Je]=U([]),Pn=J(!1),Yo=J(!1),[zo,as]=U(!1),Rn=J(0),[Qc,Tn]=U(!1),[Jc,Sn]=U(!1),[Ko,ls]=U(null),[Zc,ht]=U(0),Ze=J(0),[Bt,gt]=U(0),[wt,Dn]=U(null),cs=J(new Map),eu=J(0),yt=J([]),be=J(null);be.current===null&&(be.current=Tc({cwd:e,profileName:i,allowProdWrites:!1}));let _e=J({uuid:null,firstPrompt:null,titleFired:!1}),jn=J(new Map),kt=J(!1),Xo=J([]),De=J([]),An=J(null),[us,et]=U(null),Qo=J(null),[tt,nt]=U(null),[Le,bt]=U(null),[We,xt]=U(null),[pe,$t]=U(null),[xe,ot]=U(null),[rt,vt]=U(null),[Fe,Ct]=U(null),[ds,Vt]=U(null),[$e,it]=U(null),[he,Pt]=U(null),[ps,Jo]=U([]),st=J([]),Gt=J(!1),ve=J(null),[En,ne]=U(null),[fs,ms]=U(null),In=J(!1),Nn=J(null),Yt=J(null),[Ce,at]=U(null),[Zo,zt]=U(null),[hs,Rt]=U(0),[gs,Tt]=U(0),[tu,ws]=U(0),er=Xi(()=>{try{let l=ns(e);return l.source==="auto"?`${l.model} (auto)`:l.model}catch{return null}},[e,tu]),{stdout:je}=mh(),[,nu]=U(0),ys=J(`${je.columns??80}x${je.rows??24}`),He=V(()=>Math.max(20,(je.columns??80)-1),[je]),d=V(l=>{yt.current.push(l),console.log(jr(l,He()))},[He]),fe=V((l,a)=>{Rn.current++,Cn(l),ss(a??null)},[]),qe=V(()=>{Rn.current++,Cn(null),ss(null)},[]),Y=V(l=>fe(l,So({kind:"cmd",cmd:l,reason:""})),[fe]),ks=V((l,a)=>{!a?.silent&&l.note&&d({kind:"note",tone:l.tone,text:l.note}),l.picker&&(Je(l.picker.options.map(s=>({cmd:s.cmd,desc:s.desc}))),Vt(l.picker.title)),l.lead&&fe(l.lead.kind==="cmd"?l.lead.cmd:l.lead.text,So(l.lead))},[d,fe]),St=V((l,a,s="info")=>{l&&d({kind:"note",tone:s,text:l}),a&&fe(a.kind==="cmd"?a.cmd:a.text,So(a))},[d,fe]),[Kt,tr]=U(null),[ou,bs]=U(!1),Dt=V(l=>{tr(l),bs(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),nr=J(!1),or=V(async()=>{try{if(nr.current||!Kh(zh())||ee(e)?.mode==="engineer")return;let l=await Yh({pkg:pt,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;nr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${pt} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),Sn(!0),(await Co().finally(()=>Sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y("/exit"),ls(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${vo}`})}catch{}},[e,o,d,Y]),rr=V(l=>{let a=Me(e,i);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),Yt.current=l,Y("/login"),!1)},[e,i,d,Y]),[ir,sr]=U(null),Xt=J(!0),_n=J(0),Qt=J(0);ke(()=>{let l=setInterval(()=>{if(Xt.current){_n.current=0,Qt.current=0;return}if(!S)try{if(!xn(Nc(e)))return;if(Te(e).status==="current"){Xt.current=!0,_n.current=0,Qt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),tr(null),fe("write the docs for this repo");return}_n.current+=1;let a=_n.current;if((a===4||a%15===0)&&Qt.current<3){Qt.current+=1;let s=Qt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Oe(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${s}`:`\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.${s}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),ke(()=>{let l=us??$n(e);if(!S){_o(0),Ft(`${Oo} ${l}`);return}_o(3);let a=0;Ft(`${Lo[0]} ${l}`);let s=setInterval(()=>{a=(a+1)%Lo.length,Ft(`${Lo[a]} ${l}`)},400);return()=>clearInterval(s)},[S,e,us]),ke(()=>()=>_o(0),[]);let Jt=V(l=>{let a=kn(e,i,{claudeMissing:ts(t).state==="missing",allowAutoAudit:l,genreUnknown:Yo.current});return a?yn(a):{kind:"idle"}},[e,i,t]);ke(()=>{let l=performance.now(),a=[],s=(w,P)=>{let T=performance.now();try{return P()}finally{let z=Math.round(performance.now()-T);z>=80&&a.push(`${w}: ${z}ms`)}};d({kind:"banner",info:s("banner",()=>rg(e,o,t,i))});let h=ts(t).state==="missing";if(h&&d({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.
309
309
  ${wh}
310
310
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ee(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
311
311
  ${Uc}`}),Y(h?"/doctor":"/init");return}h&&Y("/doctor");try{let w=ye(e,i),P=mt(w.name);P&&Xe(P)&&P.refreshToken?xh({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Z(T=>T+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Y("/login")}):(!P||Xe(P))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Y("/login"))}catch{}try{let w=ee(e),P=ye(e,i),T=mt(P.name);w&&T&&!Xe(T)&&Wi(e,w.authoritativeSourceFiles)&&!Fi(e,i)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Y("/scope"))}catch{}try{let w=s("resolve-genre",()=>Ih(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&ee(e)&&(Yo.current=!0)}catch{}let u=Te(e);try{if(s("reconcile-devhints",()=>ro(e)),u.status!=="current"&&!Oe(e)){let w=io(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
@@ -3,9 +3,10 @@ import type { ReplContext } from '../repl.js';
3
3
  import type { SlashCommandResult } from './index.js';
4
4
  export declare function describeModelSource(r: ResolvedModel): string;
5
5
  /** Set or clear the personal (user-config) model. Returns the status lines plus
6
- the `effective` model to push into the LIVE session via setModel() — undefined
7
- means "let the runtime decide" (its own settings/default chain). Shared by the
8
- REPL command and the TUI case. */
6
+ the `effective` model to push into the LIVE session via setModel() — always
7
+ concrete now (auto resolves to the docs-right Sonnet default; the dev
8
+ environment's Claude Code settings model never leaks in — SNAG-0262).
9
+ Shared by the REPL command and the TUI case. */
9
10
  export declare function applyModelChange(cwd: string, arg: string): {
10
11
  lines: string[];
11
12
  changed: boolean;
@@ -10,5 +10,5 @@ export type ModelChoice = {
10
10
  };
11
11
  export declare const MODEL_CHOICES: ModelChoice[];
12
12
  /** Index of the choice matching the resolved model (for the ✓ marker / initial cursor).
13
- Personal/team/env overrides match by value or label; no override Default. */
13
+ Personal/team/env overrides match by value or label; unsetAuto (the docs-right default). */
14
14
  export declare function currentChoiceIndex(resolved: ResolvedModel): number;
@@ -1,7 +1,7 @@
1
1
  export type BannerInfo = {
2
2
  version: string;
3
3
  claude: string;
4
- /** Resolved model name (alias or full id; 'Claude Code default' when no override). */
4
+ /** Resolved model name (alias or full id always concrete; 'sonnet' on auto, SNAG-0262). */
5
5
  model: string;
6
6
  /** Where the model came from, e.g. '.d360-writer/config.json', '/model setting', 'env'. */
7
7
  modelSource: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.5.77",
3
+ "version": "0.5.78",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -34,7 +34,7 @@
34
34
  "@inquirer/prompts": "^8.4.3",
35
35
  "commander": "^14.0.3",
36
36
  "diff": "^8.0.4",
37
- "document360-engine": "^0.2.100",
37
+ "document360-engine": "^0.2.101",
38
38
  "ink": "^5.2.1",
39
39
  "picocolors": "^1.1.1",
40
40
  "react": "^18.3.1",