document360-writer 0.5.18 → 0.5.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +33 -33
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -178,18 +178,18 @@ Anything only a human knows that would help document this product. For example:
178
178
  `)}function Bo(e){try{let t=Sc(ri(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ai(e,t){let o={...Bo(e)??{},emittedVersion:ne,emittedAt:t};Gt(ri(e),`${JSON.stringify(o,null,2)}
179
179
  `)}function Yt(e){try{return Dc(oi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Bo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function In(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!An(En(e)))return n;let o=Bo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(jn(qo(e)),Gt(En(e),si()),ai(e,t),n.guideRefreshed=!0),ne>s&&(Ec(e).some(p=>p.kind==="request"&&p.subject.startsWith(ni))||(Ac(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ni}${ne})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ne}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",ot()].join(`
180
180
  `)}),n.notifiedBuilder=!0))}catch{}return n}function Nn(e){if(!An(En(e)))return[];let t=Ee(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${ne}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Tt,ot(),Tt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Go(){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, and checking"," `.d360-writer/messages/`). 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(`
181
- `)}function _n(){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):",Tt,Go(),Tt]}function St(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," 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):",Tt,ot(),Tt,"","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 Tt,ne,ni,rt=Uo(()=>{"use strict";Tt="-".repeat(64),ne=5;ni="Re-run dev\u2194docs onboarding (protocol v"});var da={};Fl(da,{doctorCommand:()=>en,renderDoctorChecks:()=>ua,runDoctorChecks:()=>ca});import{existsSync as ia}from"node:fs";import{d360GetAll as cd,getAccessToken as ud,isExpired as Er,loadProfileMap as dd,loadTokens as pd,packageSkillsDir as aa,projectConfigPath as fd,readProjectConfig as md,DEFAULT_DOCS_DIR as hd,fetchManifestSummary as gd,resolveActiveProfile as yd,classifyClaudeAuth as wd,CLAUDE_CODE_SETUP_HINT as la,resolveModelSetting as kd,probeModel as bd,devHintsGuidePath as xd}from"document360-engine";async function ca(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=wd();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. ${la}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:la});let r=kd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let w=await bd(e,r.model??void 0);w.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(w.latencyMs/1e3).toFixed(1)}s`}):w.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 ${w.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 s=md(e);if(!s)return t.push({level:"fail",label:`No ${fd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??hd).replace(/\/+$/,"");t.push(s.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=s.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 f;try{f=yd(e),t.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.production?" \u26A0 PRODUCTION":""}`})}catch(w){return t.push({level:"fail",label:`Profile config: ${w.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let x=pd(f.name);x?Er(x)&&!x.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Er(x)?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(x.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${f.name})`}),t.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let k=dd(e,f.name);k?k.projectId&&f.project.projectId&&k.projectId!==f.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.projectId}) \u2260 profile projectId (${f.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /publish)`}),t.push(ia(aa())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${aa()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((ia(xd(e))||A.status!=="unset")&&(A.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):A.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),x&&(!Er(x)||x.refreshToken)){let w={profile:f.name,connection:f.connection};try{await ud(w);let C=await cd(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=k?.projectId??f.project.projectId;if(T&&f.project.workspaceId)try{let C=await gd(w,T,f.project.workspaceId);t.push(C?{level:"ok",label:`Workspace sync manifest: available on ${f.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"})`}:{level:"warn",label:`Workspace sync manifest: not live on ${f.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ua(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${O(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function en(e,t){console.log(m("Running checks\u2026"));for(let n of ua(await ca(t.cwd)))console.log(n);return{kind:"continue"}}var Gn=Uo(()=>{"use strict";rt();W()});import{Command as Vf}from"commander";import{createRequire as zf}from"node:module";import{AUTH_MODES as Kf}from"document360-engine";import{input as rc}from"@inquirer/prompts";import{loginPkce as sc,refreshTokens as ic,toStoredTokens as Hs,clearTokens as ac,decodeJwtClaims as Fs,isExpired as lc,loadTokens as cc,saveTokens as qs,resolveActiveProfile as Cn,setProfileProject as uc,readProjectConfig as dc}from"document360-engine";W();import{select as Gl}from"@inquirer/prompts";import{resolveActiveProfile as Yl,setProfileProject as Vl,resolveProjectId as zl,listWorkspaces as Kl}from"document360-engine";async function qt(e,t){let n=Yl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??zl(o);return{workspaces:await Kl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Os=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Mo(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 vn(e,t,n,o,r){Vl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Us(e,t,n){let o;try{o=await qt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Mo(o.workspaces,t);return r?(vn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Pt(e,t){let n;try{n=await qt(e,t)}catch(x){console.log(v(`Could not list workspaces: ${x.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let x of o)console.log(` ${x.id===c?O("\u25CF"):" "} ${Os(x)} ${m(x.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Gl({message:"Select the Document360 workspace for this repo:",choices:o.map(x=>({name:`${Os(x)}${x.id===c?" (current)":""}`,value:x.id}))}),f=o.find(x=>x.id===p);vn(e,s,r,p,f?.name),console.log(E(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as Xl}from"@inquirer/prompts";import{resolveActiveProfile as Jl,setProfileProject as Ql,listProjects as Zl}from"document360-engine";async function nt(e,t){let n=Jl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Zl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ms=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ls(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 Lo(e,t,n,o){Ql(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ws(e,t){let n;try{n=await nt(e,t)}catch(f){console.log(v(`Could not list projects: ${f.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let f of o)console.log(` ${f.id===s?O("\u25CF"):" "} ${Ms(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await Xl({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${Ms(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);Lo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import ec from"picocolors";function tc(e=process.env){return e.FORCE_HYPERLINK==="0"||!ec.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 nc(e,t=e,n){return tc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var oc=/https?:\/\/[^\s\x1b]+/g;function Bt(e,t){return e.replace(oc,n=>nc(n,n,t))}function Bs(e){return{...Fs(e.idToken)??{},...Fs(e.accessToken)??{}}}function Pn(e){let t=Bs(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 Tn(e){let t=Cn(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await sc(n,{manual:e.manual,promptForRedirect:s=>rc({message:s})},s=>console.log(Bt(s))),r=Hs(t.name,o);if(qs(r),await Wo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Pn(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{dc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Pt(process.cwd(),t.name))}catch{}}async function Wo(e,t,n){let r=Bs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Cn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await nt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}uc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Gs(e){let t=Cn(process.cwd(),e.profile),n=t.connection,o=cc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Pn(o)}`),lc(o))if(o.refreshToken)try{let r=Hs(t.name,await ic(n,o.refreshToken));qs(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Ys(e){let t=Cn(process.cwd(),e.profile);ac(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Vs,writeProjectConfig as pc,resolveActiveProfile as fc,loadTokens as mc,isExpired as hc}from"document360-engine";function Rn(e){let t=Vs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer.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?O("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=mc(n),f=p?hc(p)&&!p.refreshToken?U("expired"):m("logged in"):m("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${s} [${f}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Sn(e,t){let n=Vs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,pc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Dn(e,t){try{let n=fc(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}W();import{existsSync as gc,readdirSync as yc,statSync as zs}from"node:fs";import{join as Ks}from"node:path";import{apiLogDir as wc}from"document360-engine";function Xs(){let e=wc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!gc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=yc(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(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(zs(Ks(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(zs(Ks(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as kc,resolveAuth as bc,findByName as xc,slugify as $c,touchSession as vc,upsertSession as Cc,resolveActiveProfile as Pc}from"document360-engine";async function Js(e,t,n,o,r,s){let c=bc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=Pc(e,r)}catch(w){console.error(v(`Document360 profile error: ${w.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let f;if(o){let w=xc(e,o);w||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),f=w.uuid,console.error(m(`Resuming "${w.name}"`))}let x=kc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let w of x.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let T=new Date().toISOString();Cc({uuid:k,name:$c(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(w.delta);break;case"tool":console.error(oe(` \u2699 ${w.name}`));break;case"result":A=w.ok?0:1,console.error(m(`(${w.inputTokens}\u2192${w.outputTokens} tokens`+(w.costUsd>0?`, $${w.costUsd<.01?w.costUsd.toFixed(4):w.costUsd.toFixed(2)}`:"")+")")),w.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${w.message}`)),process.exit(1)}k&&vc(k),process.stdout.write(`
182
- `),process.exit(A)}import{createInterface as mp}from"node:readline/promises";import{createSession as Jr,resolveAuth as hp,getSession as gp,setTitle as yp,slugify as wp,touchSession as Oa,upsertSession as kp,generateTitle as bp,resolveActiveProfile as Ua,resolveModelSetting as xp,readProjectConfig as $p,decodeJwtClaims as Na,isExpired as vp,loadTokens as Cp}from"document360-engine";var xe=[{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:"/sync",s:"Pull changes made directly in the Document360 portal and reconcile any documentation drift."},{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:"/sync",s:"Pull portal edits; reconcile drift."},{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 Tc(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 Qs(){let e=["document360-writer \u2014 help",""];for(let t of xe){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Tc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Fo(){console.log("");for(let e of Qs())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 Rc}from"document360-engine";async function Zs(e,t){let n=t.currentUuid(),o=n?Rc(n):void 0;return console.log(o?m(`
181
+ `)}function _n(){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):",Tt,Go(),Tt]}function St(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," 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):",Tt,ot(),Tt,"","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 Tt,ne,ni,rt=Uo(()=>{"use strict";Tt="-".repeat(64),ne=5;ni="Re-run dev\u2194docs onboarding (protocol v"});var da={};Fl(da,{doctorCommand:()=>en,renderDoctorChecks:()=>ua,runDoctorChecks:()=>ca});import{existsSync as ia}from"node:fs";import{d360GetAll as cd,getAccessToken as ud,isExpired as Er,loadProfileMap as dd,loadTokens as pd,packageSkillsDir as aa,projectConfigPath as fd,readProjectConfig as md,DEFAULT_DOCS_DIR as hd,fetchManifestSummary as gd,resolveActiveProfile as wd,classifyClaudeAuth as yd,CLAUDE_CODE_SETUP_HINT as la,resolveModelSetting as kd,probeModel as bd,devHintsGuidePath as xd}from"document360-engine";async function ca(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=yd();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. ${la}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:la});let r=kd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await bd(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.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 ${y.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 s=md(e);if(!s)return t.push({level:"fail",label:`No ${fd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??hd).replace(/\/+$/,"");t.push(s.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=s.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 f;try{f=wd(e),t.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let x=pd(f.name);x?Er(x)&&!x.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Er(x)?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(x.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${f.name})`}),t.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let k=dd(e,f.name);k?k.projectId&&f.project.projectId&&k.projectId!==f.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.projectId}) \u2260 profile projectId (${f.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /publish)`}),t.push(ia(aa())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${aa()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((ia(xd(e))||A.status!=="unset")&&(A.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):A.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),x&&(!Er(x)||x.refreshToken)){let y={profile:f.name,connection:f.connection};try{await ud(y);let C=await cd(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=k?.projectId??f.project.projectId;if(T&&f.project.workspaceId)try{let C=await gd(y,T,f.project.workspaceId);if(C){let R=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${f.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${R||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${f.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ua(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${O(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function en(e,t){console.log(m("Running checks\u2026"));for(let n of ua(await ca(t.cwd)))console.log(n);return{kind:"continue"}}var Gn=Uo(()=>{"use strict";rt();W()});import{Command as Vf}from"commander";import{createRequire as zf}from"node:module";import{AUTH_MODES as Kf}from"document360-engine";import{input as rc}from"@inquirer/prompts";import{loginPkce as sc,refreshTokens as ic,toStoredTokens as Hs,clearTokens as ac,decodeJwtClaims as Fs,isExpired as lc,loadTokens as cc,saveTokens as qs,resolveActiveProfile as Cn,setProfileProject as uc,readProjectConfig as dc}from"document360-engine";W();import{select as Gl}from"@inquirer/prompts";import{resolveActiveProfile as Yl,setProfileProject as Vl,resolveProjectId as zl,listWorkspaces as Kl}from"document360-engine";async function qt(e,t){let n=Yl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??zl(o);return{workspaces:await Kl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Os=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Mo(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 vn(e,t,n,o,r){Vl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Us(e,t,n){let o;try{o=await qt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Mo(o.workspaces,t);return r?(vn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Pt(e,t){let n;try{n=await qt(e,t)}catch(x){console.log(v(`Could not list workspaces: ${x.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let x of o)console.log(` ${x.id===c?O("\u25CF"):" "} ${Os(x)} ${m(x.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Gl({message:"Select the Document360 workspace for this repo:",choices:o.map(x=>({name:`${Os(x)}${x.id===c?" (current)":""}`,value:x.id}))}),f=o.find(x=>x.id===p);vn(e,s,r,p,f?.name),console.log(E(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as Xl}from"@inquirer/prompts";import{resolveActiveProfile as Jl,setProfileProject as Ql,listProjects as Zl}from"document360-engine";async function nt(e,t){let n=Jl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Zl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ms=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ls(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 Lo(e,t,n,o){Ql(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ws(e,t){let n;try{n=await nt(e,t)}catch(f){console.log(v(`Could not list projects: ${f.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let f of o)console.log(` ${f.id===s?O("\u25CF"):" "} ${Ms(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await Xl({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${Ms(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);Lo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import ec from"picocolors";function tc(e=process.env){return e.FORCE_HYPERLINK==="0"||!ec.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 nc(e,t=e,n){return tc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var oc=/https?:\/\/[^\s\x1b]+/g;function Bt(e,t){return e.replace(oc,n=>nc(n,n,t))}function Bs(e){return{...Fs(e.idToken)??{},...Fs(e.accessToken)??{}}}function Pn(e){let t=Bs(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 Tn(e){let t=Cn(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await sc(n,{manual:e.manual,promptForRedirect:s=>rc({message:s})},s=>console.log(Bt(s))),r=Hs(t.name,o);if(qs(r),await Wo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Pn(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{dc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Pt(process.cwd(),t.name))}catch{}}async function Wo(e,t,n){let r=Bs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Cn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await nt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}uc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Gs(e){let t=Cn(process.cwd(),e.profile),n=t.connection,o=cc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Pn(o)}`),lc(o))if(o.refreshToken)try{let r=Hs(t.name,await ic(n,o.refreshToken));qs(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Ys(e){let t=Cn(process.cwd(),e.profile);ac(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Vs,writeProjectConfig as pc,resolveActiveProfile as fc,loadTokens as mc,isExpired as hc}from"document360-engine";function Rn(e){let t=Vs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer.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?O("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=mc(n),f=p?hc(p)&&!p.refreshToken?U("expired"):m("logged in"):m("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${s} [${f}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Sn(e,t){let n=Vs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,pc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Dn(e,t){try{let n=fc(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}W();import{existsSync as gc,readdirSync as wc,statSync as zs}from"node:fs";import{join as Ks}from"node:path";import{apiLogDir as yc}from"document360-engine";function Xs(){let e=yc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!gc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=wc(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(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(zs(Ks(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(zs(Ks(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as kc,resolveAuth as bc,findByName as xc,slugify as $c,touchSession as vc,upsertSession as Cc,resolveActiveProfile as Pc}from"document360-engine";async function Js(e,t,n,o,r,s){let c=bc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=Pc(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let f;if(o){let y=xc(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),f=y.uuid,console.error(m(`Resuming "${y.name}"`))}let x=kc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let y of x.send(t))switch(y.type){case"session":if(!k){k=y.sessionId;let T=new Date().toISOString();Cc({uuid:k,name:$c(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(oe(` \u2699 ${y.name}`));break;case"result":A=y.ok?0:1,console.error(m(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}k&&vc(k),process.stdout.write(`
182
+ `),process.exit(A)}import{createInterface as mp}from"node:readline/promises";import{createSession as Jr,resolveAuth as hp,getSession as gp,setTitle as wp,slugify as yp,touchSession as Oa,upsertSession as kp,generateTitle as bp,resolveActiveProfile as Ua,resolveModelSetting as xp,readProjectConfig as $p,decodeJwtClaims as Na,isExpired as vp,loadTokens as Cp}from"document360-engine";var xe=[{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:"/sync",s:"Pull changes made directly in the Document360 portal and reconcile any documentation drift."},{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:"/sync",s:"Pull portal edits; reconcile drift."},{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 Tc(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 Qs(){let e=["document360-writer \u2014 help",""];for(let t of xe){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(Tc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Fo(){console.log("");for(let e of Qs())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 Rc}from"document360-engine";async function Zs(e,t){let n=t.currentUuid(),o=n?Rc(n):void 0;return console.log(o?m(`
183
183
  (conversation reset \u2014 "${o.name}" is still available via /resume)
184
184
  `):m(`
185
185
  (conversation reset \u2014 agent will start fresh on the next prompt)
186
- `)),{kind:"clear"}}async function Ho(){return{kind:"exit"}}W();rt();import{input as Vt,confirm as Nc}from"@inquirer/prompts";import{basename as li,join as On}from"node:path";import{existsSync as Dt,readFileSync as _c,readdirSync as Oc,writeFileSync as Uc}from"node:fs";import{writeProjectConfig as ci,readProjectConfig as Mc,projectConfigPath as ui,writerDir as Lc,DEFAULT_DOCS_DIR as di,DEFAULT_CAPTURE_DIR as pi,DEFAULT_OUTPUT_DIR as fi}from"document360-engine";function mi(e,t="berlin"){let n=ui(e);if(Dt(n))return{created:!1,path:n,profileName:""};let o={projectId:yi(e)??li(e),docsDir:di,captureDir:pi,outputDir:fi,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:wi(e)};return ci(o,e),hi(e),{created:!0,path:n,profileName:t}}function hi(e){let t=On(Lc(e),".gitignore");Dt(t)||Uc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
- `),"utf8")}async function gi(){let e=process.cwd(),t=ui(e);if(Dt(t)&&!await Nc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=yi(e)??li(e),o=await Vt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Vt({message:"Capture directory (where document360-capture .spec.ts files live):",default:pi}),s=await Vt({message:"Screenshot output directory:",default:fi}),c=await Vt({message:"Default connection profile name:",default:"berlin"}),p=await Vt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),f={projectId:o,docsDir:di,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:wi(e)},x=Mc(e);x?.terminologyGlossary&&(f.terminologyGlossary=x.terminologyGlossary),ci(f,e),hi(e);let k=Rt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${c}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let A of St(k))console.log(A);return console.log(""),console.log(`${m("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function yi(e){let t=On(e,"package.json");if(!Dt(t))return null;try{return JSON.parse(_c(t,"utf8")).name??null}catch{return null}}function wi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Dt(On(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=On(e,n);Dt(o)&&!Wc(o)&&t.push(n)}return t}function Wc(e){try{return Oc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Yo,writeMcpConfig as ki}from"document360-engine";async function Un(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Fc(),{kind:"continue"}):t==="add"?(Hc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(qc(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Fc(){let e=Yo(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
186
+ `)),{kind:"clear"}}async function Ho(){return{kind:"exit"}}W();rt();import{input as Vt,confirm as Nc}from"@inquirer/prompts";import{basename as li,join as On}from"node:path";import{existsSync as Dt,readFileSync as _c,readdirSync as Oc,writeFileSync as Uc}from"node:fs";import{writeProjectConfig as ci,readProjectConfig as Mc,projectConfigPath as ui,writerDir as Lc,DEFAULT_DOCS_DIR as di,DEFAULT_CAPTURE_DIR as pi,DEFAULT_OUTPUT_DIR as fi}from"document360-engine";function mi(e,t="berlin"){let n=ui(e);if(Dt(n))return{created:!1,path:n,profileName:""};let o={projectId:wi(e)??li(e),docsDir:di,captureDir:pi,outputDir:fi,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:yi(e)};return ci(o,e),hi(e),{created:!0,path:n,profileName:t}}function hi(e){let t=On(Lc(e),".gitignore");Dt(t)||Uc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
187
+ `),"utf8")}async function gi(){let e=process.cwd(),t=ui(e);if(Dt(t)&&!await Nc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=wi(e)??li(e),o=await Vt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Vt({message:"Capture directory (where document360-capture .spec.ts files live):",default:pi}),s=await Vt({message:"Screenshot output directory:",default:fi}),c=await Vt({message:"Default connection profile name:",default:"berlin"}),p=await Vt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),f={projectId:o,docsDir:di,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:yi(e)},x=Mc(e);x?.terminologyGlossary&&(f.terminologyGlossary=x.terminologyGlossary),ci(f,e),hi(e);let k=Rt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${c}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let A of St(k))console.log(A);return console.log(""),console.log(`${m("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function wi(e){let t=On(e,"package.json");if(!Dt(t))return null;try{return JSON.parse(_c(t,"utf8")).name??null}catch{return null}}function yi(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Dt(On(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=On(e,n);Dt(o)&&!Wc(o)&&t.push(n)}return t}function Wc(e){try{return Oc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Yo,writeMcpConfig as ki}from"document360-engine";async function Un(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Fc(),{kind:"continue"}):t==="add"?(Hc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(qc(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Fc(){let e=Yo(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
188
188
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
189
189
  `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Hc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Yo(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let f=o[++p],x=f?.match(/^([^:=]+)[:=](.+)$/);if(!x){console.log(v(`-H expects key:value (no spaces). Got: ${f??"(nothing)"}`));return}c[x[1].trim()]=x[2].trim()}else{console.log(v(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,ki(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(U(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function qc(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Yo();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],ki(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as ru}from"node:fs";import{join as su}from"node:path";import{select as iu}from"@inquirer/prompts";import{computeSyncStatus as tr,planPartitions as au,relatedArticlePaths as lu,resolveModelForOperation as cu,runPartitioned as uu,loadProfileMap as du,resolveActiveProfile as pu,resolveCrossLinks as fu}from"document360-engine";import V from"picocolors";import Pi from"wrap-ansi";import Qo from"string-width";W();import Fe from"picocolors";import Vo from"wrap-ansi";import zo from"string-width";var bi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),xi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),$i=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Bc(e){let t=e.replace(/\r/g,"").split(`
190
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(bi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&xi(t[o+1])){let p=$i(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push($i(t[o++]));n.push({kind:"table",header:p,rows:f});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!bi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&xi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Ko(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Fe.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Fe.italic(t.slice(1,-1)))}var Gc=(e,t)=>e+" ".repeat(Math.max(0,t-zo(e)));function Yc(e,t,n){let o=e.length,r=e.map((C,S)=>Math.max(zo(C),...t.map(N=>zo(N[S]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,S)=>C+S,0)+c,x=0;for(;f()>s&&x++<1e4;){let C=-1,S=6;for(let N=0;N<o;N++)p[N]>S&&(S=p[N],C=N);if(C===-1)break;p[C]-=1}let k=(C,S,N)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(S)+N),A=Fe.gray("\u2502"),w=(C,S)=>{let N=p.map((ve,ae)=>{let Ce=C[ae]??"",le=S?Fe.bold(Ce):Ko(Ce);return Vo(le,ve,{hard:!0}).split(`
190
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(bi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&xi(t[o+1])){let p=$i(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push($i(t[o++]));n.push({kind:"table",header:p,rows:f});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!bi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&xi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Ko(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Fe.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Fe.italic(t.slice(1,-1)))}var Gc=(e,t)=>e+" ".repeat(Math.max(0,t-zo(e)));function Yc(e,t,n){let o=e.length,r=e.map((C,R)=>Math.max(zo(C),...t.map(N=>zo(N[R]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,R)=>C+R,0)+c,x=0;for(;f()>s&&x++<1e4;){let C=-1,R=6;for(let N=0;N<o;N++)p[N]>R&&(R=p[N],C=N);if(C===-1)break;p[C]-=1}let k=(C,R,N)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(R)+N),A=Fe.gray("\u2502"),y=(C,R)=>{let N=p.map((ve,ae)=>{let Ce=C[ae]??"",le=R?Fe.bold(Ce):Ko(Ce);return Vo(le,ve,{hard:!0}).split(`
191
191
  `)}),H=Math.max(...N.map(ve=>ve.length)),se=[];for(let ve=0;ve<H;ve++)se.push(p.map((ae,Ce)=>`${A} ${Gc(N[Ce][ve]??"",ae)} `).join("")+A);return se.join(`
192
- `)},T=[k("\u250C","\u252C","\u2510"),w(e,!0)];return T.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,S)=>{T.push(w(C,!1)),T.push(S===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),T.join(`
192
+ `)},T=[k("\u250C","\u252C","\u2510"),y(e,!0)];return T.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,R)=>{T.push(y(C,!1)),T.push(R===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),T.join(`
193
193
  `)}function Vc(e,t){switch(e.kind){case"heading":return Fe.bold(e.text);case"hr":return Fe.gray("\u2500".repeat(t));case"para":return Vo(Ko(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Vo(Ko(n),Math.max(10,t-4)).split(`
194
194
  `);return" \u2022 "+o+r.map(s=>`
195
195
  `+s).join("")}).join(`
@@ -216,17 +216,17 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
216
216
  `+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${Kt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${pe(e.costUsd)}`:""))}}function Ti(e,t){return e.map(n=>Zo(n,t)).join(`
217
217
  `)}import{resolveActiveProfile as eu,loadTokens as tu,isExpired as nu,decodeJwtClaims as Ri}from"document360-engine";function ou(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=eu(e,t),o=tu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(nu(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...Ri(o.idToken)??{},...Ri(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${ou(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Xt=3;function nr(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
218
218
  `)}var Si={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Jt(e){return e.filter(t=>t.path!==null&&t.status in Si&&!t.link).map(t=>({path:t.path,label:Si[t.status]}))}function Mn(e){return e.filter(t=>t.link).length}function or(e,t){try{let n=du(e,pu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=fu(ru(su(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function mu(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function Di(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${mu(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Ln(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
219
- `)}function rr(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,T)=>w+o(T),0),p=r.reduce((w,T)=>w+o(T),0),f=n==="api"?`${pe(e.reduce((w,T)=>w+T.costUsd,0))} total`:He(e.reduce((w,T)=>w+T.outputTokens,0)),x=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=w=>`${w} article${w===1?"":"s"}`,A=[];if(s.length===0)A.push(`Published ${k(c)} (${x}) successfully \xB7 ${f}.`),A.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{A.push(`Published ${p}/${k(c)} (${x}) \xB7 ${f}.`),A.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let w of s)A.push(` \u2717 ${w.label}${w.error?` \u2014 ${w.error}`:""}`)}return A}async function er(e,t){let n=au(t),{model:o}=cu(e.cwd,"standard");console.log(m(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Xt} agents at once) on ${o}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of uu({cwd:e.cwd,partitions:n,promptFor:s=>Ln(s.paths),concurrency:Xt,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(m(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(E(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of rr(r.results,n,s))console.log(r.ok?E(p):U(p));let c=or(e.cwd,e.profileName);c&&console.log(m(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Wn(e,t,n){let o=lu(e,n);if(o.length===0)return[];let r=new Set(Jt((await tr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ji(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Wn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await er(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await tr({cwd:t?.cwd??process.cwd()}),s=Jt(r.entries),c=Mn(r.entries);return c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await er(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Ln(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await tr({cwd:t?.cwd??process.cwd()});r=Jt(s.entries);let c=Mn(s.entries);c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log(v(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(E("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>iu({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await er(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:nr(o),display:`/publish ${o}`}}async function Qt(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
- `),display:"/audit"}}W();import{checkbox as hu}from"@inquirer/prompts";import{inventoryRepo as gu,readProjectConfig as Ai,writeProjectConfig as yu}from"document360-engine";function sr(e,t){let n=Ai(e);n&&(n.authoritativeSourceFiles=t,yu(n,e))}function Fn(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Ei(e,t){let n=t?.cwd??process.cwd();if(!Ai(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=gu(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Fn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>hu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Fn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};sr(n,r),console.log(E(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as $u}from"@inquirer/prompts";import{applyPull as Ui,computeSyncStatus as Mi,planPull as vu,establishBaselines as Cu,D360AuthError as Pu}from"document360-engine";W();var Ii=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:oe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:oe,mark:"\xB7"}];function wu(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Hn(e){let t=[],n=e.entries.filter(f=>f.link);if(n.length>0){t.push(""),t.push(Te("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let f of n)t.push(` ${U("~")} ${U(f.path??"")} ${oe(`\u2192 "${f.link.title}"`)}`)}for(let f of Ii){let x=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(x.length!==0){t.push(""),t.push(Te(f.header));for(let k of x)t.push(` ${f.paint(f.mark)} ${f.paint(wu(k))}${k.detail?oe(` (${k.detail})`):""}`)}}let o=e.counts["in-sync"]??0,r=e.entries.length;t.push("");let s={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=n.length,p=r===o?E("\u2713 everything up to date"):[o>0?E(`\u2713 ${o} up to date`):null,c>0?`${c} to link`:null,...Ii.map(f=>{let x=(e.counts[f.status]??0)-(f.status==="untracked-local"?c:0);return x>0?`${x} ${s[f.status]}`:null})].filter(Boolean).join(oe(" \xB7 "));return t.push(p+oe(` \xB7 ${r} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as ku}from"diff";import Ni from"picocolors";var _i=80,bu="\x1B[48;2;74;28;28m",xu="\x1B[48;2;24;66;24m",Oi="\x1B[49m",ir=e=>String(e).padStart(5);function st(e,t,n){let o=w=>{let T=w.replace(/\r\n/g,`
219
+ `)}function rr(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,T)=>y+o(T),0),p=r.reduce((y,T)=>y+o(T),0),f=n==="api"?`${pe(e.reduce((y,T)=>y+T.costUsd,0))} total`:He(e.reduce((y,T)=>y+T.outputTokens,0)),x=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=y=>`${y} article${y===1?"":"s"}`,A=[];if(s.length===0)A.push(`Published ${k(c)} (${x}) successfully \xB7 ${f}.`),A.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{A.push(`Published ${p}/${k(c)} (${x}) \xB7 ${f}.`),A.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let y of s)A.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return A}async function er(e,t){let n=au(t),{model:o}=cu(e.cwd,"standard");console.log(m(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Xt} agents at once) on ${o}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of uu({cwd:e.cwd,partitions:n,promptFor:s=>Ln(s.paths),concurrency:Xt,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(m(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(E(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of rr(r.results,n,s))console.log(r.ok?E(p):U(p));let c=or(e.cwd,e.profileName);c&&console.log(m(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Wn(e,t,n){let o=lu(e,n);if(o.length===0)return[];let r=new Set(Jt((await tr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ji(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Wn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await er(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await tr({cwd:t?.cwd??process.cwd()}),s=Jt(r.entries),c=Mn(r.entries);return c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await er(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Ln(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await tr({cwd:t?.cwd??process.cwd()});r=Jt(s.entries);let c=Mn(s.entries);c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log(v(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(E("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>iu({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await er(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:nr(o),display:`/publish ${o}`}}async function Qt(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
220
+ `),display:"/audit"}}W();import{checkbox as hu}from"@inquirer/prompts";import{inventoryRepo as gu,readProjectConfig as Ai,writeProjectConfig as wu}from"document360-engine";function sr(e,t){let n=Ai(e);n&&(n.authoritativeSourceFiles=t,wu(n,e))}function Fn(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Ei(e,t){let n=t?.cwd??process.cwd();if(!Ai(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=gu(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Fn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>hu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Fn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};sr(n,r),console.log(E(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as $u}from"@inquirer/prompts";import{applyPull as Ui,computeSyncStatus as Mi,planPull as vu,establishBaselines as Cu,D360AuthError as Pu}from"document360-engine";W();var Ii=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:oe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:oe,mark:"\xB7"}];function yu(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Hn(e){let t=[],n=e.entries.filter(f=>f.link);if(n.length>0){t.push(""),t.push(Te("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let f of n)t.push(` ${U("~")} ${U(f.path??"")} ${oe(`\u2192 "${f.link.title}"`)}`)}for(let f of Ii){let x=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(x.length!==0){t.push(""),t.push(Te(f.header));for(let k of x)t.push(` ${f.paint(f.mark)} ${f.paint(yu(k))}${k.detail?oe(` (${k.detail})`):""}`)}}let o=e.counts["in-sync"]??0,r=e.entries.length;t.push("");let s={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=n.length,p=r===o?E("\u2713 everything up to date"):[o>0?E(`\u2713 ${o} up to date`):null,c>0?`${c} to link`:null,...Ii.map(f=>{let x=(e.counts[f.status]??0)-(f.status==="untracked-local"?c:0);return x>0?`${x} ${s[f.status]}`:null})].filter(Boolean).join(oe(" \xB7 "));return t.push(p+oe(` \xB7 ${r} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as ku}from"diff";import Ni from"picocolors";var _i=80,bu="\x1B[48;2;74;28;28m",xu="\x1B[48;2;24;66;24m",Oi="\x1B[49m",ir=e=>String(e).padStart(5);function st(e,t,n){let o=y=>{let T=y.replace(/\r\n/g,`
221
221
  `);return T.endsWith(`
222
222
  `)||T===""?T:T+`
223
- `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=ku("a","b",r,s,"","",{context:3}),f=0,x=0,k=[];p.hunks.forEach((w,T)=>{T>0&&k.push(Ni.gray(" \u2026"));let C=w.oldStart,S=w.newStart;for(let N of w.lines){let H=N[0],se=N.slice(1).slice(0,c);H==="-"?(x++,k.push(`${bu}${ir(C++)} - ${se}${Oi}`)):H==="+"?(f++,k.push(`${xu}${ir(S++)} + ${se}${Oi}`)):(k.push(Ni.gray(ir(S))+" "+se),C++,S++)}});let A=k.slice(0,_i);return{added:f,removed:x,lines:A,hidden:Math.max(0,k.length-_i)}}async function Li(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Tu(t.cwd),{kind:"continue"};if(o==="pull")return await Su(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await Ru(t,e.slice(1)),{kind:"continue"};console.log(v(`Unknown subcommand: /sync ${o}`)),console.log(m("Usage: /sync drift report (local vs Document360)")),console.log(m(" /sync pull <path> pull portal edits into the local file")),console.log(m(" /sync pull --all pull every remote-ahead article")),console.log(m(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof Pu?console.log(v(r.message)):console.log(v(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Tu(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Mi({cwd:e});for(let n of Hn(t))console.log(n);console.log("")}async function Ru(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Cu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(m(` - ${r.path} (${r.reason})`))}}async function Su(e,t){let n=t[0];if(!n){console.log(v("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Mi({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(m(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Te(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await vu({cwd:e.cwd,relPath:r});console.log(""),console.log(`${O("\u25CF")} ${Te(s.title)} ${oe(`(${s.path})`)}`);for(let x of s.notes)console.log(U(` \u26A0 ${x}`));s.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=st(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ui({cwd:e.cwd},s);continue}let p=x=>x===1?"":"s";console.log(oe(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let x of c.lines)console.log(x);if(c.hidden>0&&console.log(m(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>$u({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(m(" Skipped."));continue}Ui({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as Du}from"node:fs";import{resolve as ju}from"node:path";import{estimateBulkCost as Au,planPartitions as Eu,readProjectConfig as Iu,resolveModelForOperation as Nu,runPartitioned as _u,trackedArticlePaths as Ou}from"document360-engine";var ar=3;function lr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function cr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ur(e,t){return t.map(n=>{let o=0;try{o=Du(ju(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function dr(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
223
+ `},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=ku("a","b",r,s,"","",{context:3}),f=0,x=0,k=[];p.hunks.forEach((y,T)=>{T>0&&k.push(Ni.gray(" \u2026"));let C=y.oldStart,R=y.newStart;for(let N of y.lines){let H=N[0],se=N.slice(1).slice(0,c);H==="-"?(x++,k.push(`${bu}${ir(C++)} - ${se}${Oi}`)):H==="+"?(f++,k.push(`${xu}${ir(R++)} + ${se}${Oi}`)):(k.push(Ni.gray(ir(R))+" "+se),C++,R++)}});let A=k.slice(0,_i);return{added:f,removed:x,lines:A,hidden:Math.max(0,k.length-_i)}}async function Li(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await Tu(t.cwd),{kind:"continue"};if(o==="pull")return await Su(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await Ru(t,e.slice(1)),{kind:"continue"};console.log(v(`Unknown subcommand: /sync ${o}`)),console.log(m("Usage: /sync drift report (local vs Document360)")),console.log(m(" /sync pull <path> pull portal edits into the local file")),console.log(m(" /sync pull --all pull every remote-ahead article")),console.log(m(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof Pu?console.log(v(r.message)):console.log(v(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function Tu(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Mi({cwd:e});for(let n of Hn(t))console.log(n);console.log("")}async function Ru(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Cu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(m(` - ${r.path} (${r.reason})`))}}async function Su(e,t){let n=t[0];if(!n){console.log(v("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Mi({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(m(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Te(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await vu({cwd:e.cwd,relPath:r});console.log(""),console.log(`${O("\u25CF")} ${Te(s.title)} ${oe(`(${s.path})`)}`);for(let x of s.notes)console.log(U(` \u26A0 ${x}`));s.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=st(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ui({cwd:e.cwd},s);continue}let p=x=>x===1?"":"s";console.log(oe(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let x of c.lines)console.log(x);if(c.hidden>0&&console.log(m(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>$u({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(m(" Skipped."));continue}Ui({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as Du}from"node:fs";import{resolve as ju}from"node:path";import{estimateBulkCost as Au,planPartitions as Eu,readProjectConfig as Iu,resolveModelForOperation as Nu,runPartitioned as _u,trackedArticlePaths as Ou}from"document360-engine";var ar=3;function lr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function cr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ur(e,t){return t.map(n=>{let o=0;try{o=Du(ju(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function dr(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
224
224
  - Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
225
225
  - Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
226
226
  - Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
227
227
  - Work only on these files:
228
228
  `+e.paths.map(t=>`- ${t}`).join(`
229
- `)}function pr(e,t,n){let o=e.reduce((p,f)=>p+f.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function fr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),f=e.reduce((C,S)=>C+S.costUsd,0),x=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${pe(f)} total`:He(x),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${w(c)} (${A}) successfully \xB7 ${k}.`);else{T.push(`Converted ${p}/${w(c)} (${A}) \xB7 ${k}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function Wi(e,t){if(!Iu(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=lr(e),r=Ou(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=cr(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Eu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:f,forced:x}=Nu(t.cwd,"light");if(!o){let k=Au({files:ur(t.cwd,s),op:"convert",model:f});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let A of pr(c,k,ar))console.log(A);return console.log(m(`Model: ${f}${x?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${c.length} partitions (\u2264${ar} agents at once) on ${f}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of _u({cwd:t.cwd,partitions:c,promptFor:dr,concurrency:ar,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:f}))if(k.type==="partition_status")k.status==="running"?console.log(m(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(E(` \u2713 ${k.label}`)):console.log(v(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let A=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of fr(k.results,c,A))console.log(k.ok?E(w):U(w))}}catch(k){console.log(v(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Fi}from"node:fs";import{resolve as Hi}from"node:path";import{estimateBulkCost as Uu,planPartitions as Mu,readDocsPlan as Lu,readProjectConfig as qi,DEFAULT_DOCS_DIR as Wu,resolveModelForOperation as Fu,runPartitioned as Hu}from"document360-engine";var qu=3,Bu=8;function mr(e){return e===void 0||!Number.isFinite(e)?qu:Math.max(1,Math.min(Math.floor(e),Bu))}function hr(e){let t,n,o=!1,r,s=p=>{let f=Number(p);return p!==void 0&&Number.isFinite(f)?f:void 0};for(let p=0;p<e.length;p++){let f=e[p];if(f==="--preview"||f==="--dry-run")o=!0;else{if(f==="--run"||f==="--yes"||f==="--all")continue;f==="--scope"?t=e[++p]:f?.startsWith("--scope=")?t=f.slice(8):f==="--concurrency"?r=s(e[++p]):f?.startsWith("--concurrency=")?r=s(f.slice(14)):f&&!f.startsWith("--")&&(n=f)}}let c=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:c(t),path:c(n),preview:o,concurrency:r}}function Gu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Yu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function gr(e,t,n){return n.filter(o=>{try{return Fi(Hi(e,t,o)).size===0}catch{return!0}})}function yr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=Fi(Hi(e,c)).size}catch{}return{path:r,bytes:s}})}function wr(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
229
+ `)}function pr(e,t,n){let o=e.reduce((p,f)=>p+f.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function fr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,R)=>C+o(R),0),p=r.reduce((C,R)=>C+o(R),0),f=e.reduce((C,R)=>C+R.costUsd,0),x=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${pe(f)} total`:He(x),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${y(c)} (${A}) successfully \xB7 ${k}.`);else{T.push(`Converted ${p}/${y(c)} (${A}) \xB7 ${k}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function Wi(e,t){if(!Iu(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=lr(e),r=Ou(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=cr(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Eu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:f,forced:x}=Nu(t.cwd,"light");if(!o){let k=Au({files:ur(t.cwd,s),op:"convert",model:f});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let A of pr(c,k,ar))console.log(A);return console.log(m(`Model: ${f}${x?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${c.length} partitions (\u2264${ar} agents at once) on ${f}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of _u({cwd:t.cwd,partitions:c,promptFor:dr,concurrency:ar,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:f}))if(k.type==="partition_status")k.status==="running"?console.log(m(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(E(` \u2713 ${k.label}`)):console.log(v(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let A=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let y of fr(k.results,c,A))console.log(k.ok?E(y):U(y))}}catch(k){console.log(v(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Fi}from"node:fs";import{resolve as Hi}from"node:path";import{estimateBulkCost as Uu,planPartitions as Mu,readDocsPlan as Lu,readProjectConfig as qi,DEFAULT_DOCS_DIR as Wu,resolveModelForOperation as Fu,runPartitioned as Hu}from"document360-engine";var qu=3,Bu=8;function mr(e){return e===void 0||!Number.isFinite(e)?qu:Math.max(1,Math.min(Math.floor(e),Bu))}function hr(e){let t,n,o=!1,r,s=p=>{let f=Number(p);return p!==void 0&&Number.isFinite(f)?f:void 0};for(let p=0;p<e.length;p++){let f=e[p];if(f==="--preview"||f==="--dry-run")o=!0;else{if(f==="--run"||f==="--yes"||f==="--all")continue;f==="--scope"?t=e[++p]:f?.startsWith("--scope=")?t=f.slice(8):f==="--concurrency"?r=s(e[++p]):f?.startsWith("--concurrency=")?r=s(f.slice(14)):f&&!f.startsWith("--")&&(n=f)}}let c=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:c(t),path:c(n),preview:o,concurrency:r}}function Gu(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Yu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function gr(e,t,n){return n.filter(o=>{try{return Fi(Hi(e,t,o)).size===0}catch{return!0}})}function wr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=Fi(Hi(e,c)).size}catch{}return{path:r,bytes:s}})}function yr(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
230
230
  - It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
231
231
  - Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
232
232
  - Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
@@ -234,9 +234,9 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
234
234
  - Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
235
235
  Articles:
236
236
  `+e.paths.map(n=>`- ${n}`).join(`
237
- `)}function kr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function br(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),f=e.reduce((C,S)=>C+S.costUsd,0),x=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${pe(f)} total`:He(x),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${w(c)} (${A}) successfully \xB7 ${k}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${w(c)} (${A}) \xB7 ${k}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function xr(e,t,n){let o=(qi(e)?.docsDir??Wu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Gu(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 s=Yu(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=gr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Bi(e,t){if(!qi(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Lu(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=hr(e),{docsDir:p,targets:f,reason:x}=xr(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(x?U(x):U("Nothing to write.")),{kind:"continue"};let k=Mu(f),A=mr(c),{model:w,forced:T}=Fu(t.cwd,"standard");if(s&&!!!r){let S=Uu({files:yr(t.cwd,n,f),op:"write",model:w});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let N of kr(k,S,A))console.log(N);return console.log(m(`Model: ${w}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${f.length} article${f.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${A} agents at once) on ${w}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let S of Hu({cwd:t.cwd,partitions:k,promptFor:N=>wr(N,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))if(S.type==="partition_status")S.status==="running"?console.log(m(` \u25B8 ${S.label} \u2014 writing\u2026`)):S.status==="done"?console.log(E(` \u2713 ${S.label}`)):console.log(v(` \u2717 ${S.label}`));else if(S.type==="run_done"){console.log("");let N=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of br(S.results,k,N))console.log(S.ok?E(H):U(H))}}catch(S){console.log(v(`Write run failed: ${S.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Vu,readdirSync as Gi,statSync as Yi}from"node:fs";import{join as Vi}from"node:path";import{inputDir as zu,readProjectConfig as Ku}from"document360-engine";var zi=/\.(md|markdown|pdf|txt)$/i;function $r(e){let t=zu(e);if(!Vu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Gi(t)){let s=Vi(t,r),c=!1;try{c=Yi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Xu(s);p>0&&n.push({name:r,docCount:p})}else zi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Xu(e){let t=0;for(let n of Gi(e))try{Yi(Vi(e,n)).isFile()&&zi.test(n)&&t++}catch{}return t}function vr(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 qn(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(`
237
+ `)}function kr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function br(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,R)=>C+o(R),0),p=r.reduce((C,R)=>C+o(R),0),f=e.reduce((C,R)=>C+R.costUsd,0),x=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${pe(f)} total`:He(x),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${y(c)} (${A}) successfully \xB7 ${k}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${y(c)} (${A}) \xB7 ${k}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function xr(e,t,n){let o=(qi(e)?.docsDir??Wu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Gu(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 s=Yu(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=gr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Bi(e,t){if(!qi(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Lu(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=hr(e),{docsDir:p,targets:f,reason:x}=xr(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(x?U(x):U("Nothing to write.")),{kind:"continue"};let k=Mu(f),A=mr(c),{model:y,forced:T}=Fu(t.cwd,"standard");if(s&&!!!r){let R=Uu({files:wr(t.cwd,n,f),op:"write",model:y});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let N of kr(k,R,A))console.log(N);return console.log(m(`Model: ${y}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${f.length} article${f.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${A} agents at once) on ${y}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let R of Hu({cwd:t.cwd,partitions:k,promptFor:N=>yr(N,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(R.type==="partition_status")R.status==="running"?console.log(m(` \u25B8 ${R.label} \u2014 writing\u2026`)):R.status==="done"?console.log(E(` \u2713 ${R.label}`)):console.log(v(` \u2717 ${R.label}`));else if(R.type==="run_done"){console.log("");let N=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of br(R.results,k,N))console.log(R.ok?E(H):U(H))}}catch(R){console.log(v(`Write run failed: ${R.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Vu,readdirSync as Gi,statSync as Yi}from"node:fs";import{join as Vi}from"node:path";import{inputDir as zu,readProjectConfig as Ku}from"document360-engine";var zi=/\.(md|markdown|pdf|txt)$/i;function $r(e){let t=zu(e);if(!Vu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Gi(t)){let s=Vi(t,r),c=!1;try{c=Yi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Xu(s);p>0&&n.push({name:r,docCount:p})}else zi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Xu(e){let t=0;for(let n of Gi(e))try{Yi(Vi(e,n)).isFile()&&zi.test(n)&&t++}catch{}return t}function vr(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 qn(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(`
238
238
  `)}var Cr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ki(e,t){let n=t?.cwd??process.cwd();if(!Ku(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=$r(n);if(o.length===0&&r===0)return console.log(m(Cr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let f of o)console.log(` ${f.name} ${m(`(${f.docCount} doc${f.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:qn(p),display:p?`/draft ${p}`:"/draft"}}let c=vr(o,s);return{kind:"forward-to-agent",prompt:qn(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Ju,readProjectConfig as Qu}from"document360-engine";function Pr(e){try{return Ju(e).filter(t=>t.kind==="request").length}catch{return 0}}function Tr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Rr(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(`
239
- `)}var Sr="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 Xi(e,t){let n=t?.cwd??process.cwd();if(!Qu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Tr(e);if(!r&&Pr(n)===0)return console.log(m(Sr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Rr(r,o),display:s}}W();import{search as Zu}from"@inquirer/prompts";import{findByName as ed,getSession as td,listSessions as nd,relativeTime as Qi}from"document360-engine";async function Zi(e,t){let n=nd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=ed(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Ji(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ji(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Zu({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${Qi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=td(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ji(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Qi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as od}from"document360-engine";function Dr(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 ea(e,t){let n=Dr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(od(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as ta,readProjectConfig as rd,writeProjectConfig as sd}from"document360-engine";W();function jr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=rd(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ta().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},sd(o,e),null):`Unknown environment "${r}". Known: ${ta().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function na(e,t){let n=e[0];if(!n)return Rn(t.cwd),{kind:"continue"};if(n==="add"){let o=jr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Sn(t.cwd,n),Dn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as id}from"@inquirer/prompts";import{readProjectConfig as ad,readUserConfig as oa,resolveModelSetting as Ar,writeUserConfig as ra}from"document360-engine";var Re=[{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 Bn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ld(e){switch(e.source){case"project":return".d360-writer.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 Zt(e,t){let n=()=>{let s=Ar(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=oa();return s.defaultModel?(delete s.defaultModel,ra(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ar(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}}ra({...oa(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ad(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function sa(e,t){let n=e[0]?.trim();if(!n){let c=Ar(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${ld(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Bn(c),f;try{f=await t.withPausedInput(()=>id({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((w,T)=>({name:`${w.label}${T===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:x,changed:k,effective:A}=Zt(t.cwd,f??"default");for(let w of x)console.log(w.startsWith("\u26A0")?U(w):w.startsWith("\u2713")?E(w):m(w));return k&&await t.setModel(A),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Zt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?E(c):m(c));return r&&await t.setModel(s),{kind:"continue"}}Gn();async function pa(e,t){return await t.withPausedInput(()=>Pt(t.cwd)),{kind:"clear"}}async function fa(e,t){return await t.withPausedInput(()=>Ws(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as $d}from"document360-engine";async function ma(e,t){let n=!1;try{n=$d(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var ha=async(e,t)=>{try{await t.withPausedInput(()=>Tn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as vd,clearTokens as Cd,clearProfileProject as Pd}from"document360-engine";async function ga(e,t){let n;try{n=vd(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Cd(n);return Pd(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as ya}from"node:fs";import{isAbsolute as Td,join as Rd,resolve as Sd}from"node:path";import{readProjectConfig as Dd,screenshotPlaceholderIds as jd,DEFAULT_CAPTURE_DIR as Ad,DEFAULT_OUTPUT_DIR as Ed}from"document360-engine";var wa=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ir(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?wa(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:wa(o),setup:t}:{mode:"single",id:o}}function Nr(e,t){let n=Dd(e),o=n?.captureDir??Ad,r=n?.outputDir??Ed,s=(c,p)=>Td(c)?Rd(c,p):Sd(e,c,p);return jd(e,{scope:t}).map(({id:c,file:p})=>{let f=ya(s(r,`${c}.png`))?"captured":ya(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Id={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Nd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function _r(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(s=>s.file))].sort(),o=e.filter(s=>s.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 s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${Id[c.state]} ${c.id.padEnd(34)} ${Nd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ka(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(`
239
+ `)}var Sr="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 Xi(e,t){let n=t?.cwd??process.cwd();if(!Qu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Tr(e);if(!r&&Pr(n)===0)return console.log(m(Sr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Rr(r,o),display:s}}W();import{search as Zu}from"@inquirer/prompts";import{findByName as ed,getSession as td,listSessions as nd,relativeTime as Qi}from"document360-engine";async function Zi(e,t){let n=nd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=ed(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Ji(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ji(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Zu({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${Qi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=td(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ji(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Qi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as od}from"document360-engine";function Dr(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 ea(e,t){let n=Dr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(od(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as ta,readProjectConfig as rd,writeProjectConfig as sd}from"document360-engine";W();function jr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=rd(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ta().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},sd(o,e),null):`Unknown environment "${r}". Known: ${ta().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function na(e,t){let n=e[0];if(!n)return Rn(t.cwd),{kind:"continue"};if(n==="add"){let o=jr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Sn(t.cwd,n),Dn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as id}from"@inquirer/prompts";import{readProjectConfig as ad,readUserConfig as oa,resolveModelSetting as Ar,writeUserConfig as ra}from"document360-engine";var Re=[{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 Bn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function ld(e){switch(e.source){case"project":return".d360-writer.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 Zt(e,t){let n=()=>{let s=Ar(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=oa();return s.defaultModel?(delete s.defaultModel,ra(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ar(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}}ra({...oa(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ad(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function sa(e,t){let n=e[0]?.trim();if(!n){let c=Ar(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${ld(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Bn(c),f;try{f=await t.withPausedInput(()=>id({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((y,T)=>({name:`${y.label}${T===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:x,changed:k,effective:A}=Zt(t.cwd,f??"default");for(let y of x)console.log(y.startsWith("\u26A0")?U(y):y.startsWith("\u2713")?E(y):m(y));return k&&await t.setModel(A),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Zt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?E(c):m(c));return r&&await t.setModel(s),{kind:"continue"}}Gn();async function pa(e,t){return await t.withPausedInput(()=>Pt(t.cwd)),{kind:"clear"}}async function fa(e,t){return await t.withPausedInput(()=>Ws(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as $d}from"document360-engine";async function ma(e,t){let n=!1;try{n=$d(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var ha=async(e,t)=>{try{await t.withPausedInput(()=>Tn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as vd,clearTokens as Cd,clearProfileProject as Pd}from"document360-engine";async function ga(e,t){let n;try{n=vd(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Cd(n);return Pd(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as wa}from"node:fs";import{isAbsolute as Td,join as Rd,resolve as Sd}from"node:path";import{readProjectConfig as Dd,screenshotPlaceholderIds as jd,DEFAULT_CAPTURE_DIR as Ad,DEFAULT_OUTPUT_DIR as Ed}from"document360-engine";var ya=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ir(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ya(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ya(o),setup:t}:{mode:"single",id:o}}function Nr(e,t){let n=Dd(e),o=n?.captureDir??Ad,r=n?.outputDir??Ed,s=(c,p)=>Td(c)?Rd(c,p):Sd(e,c,p);return jd(e,{scope:t}).map(({id:c,file:p})=>{let f=wa(s(r,`${c}.png`))?"captured":wa(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Id={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Nd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function _r(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(s=>s.file))].sort(),o=e.filter(s=>s.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 s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${Id[c.state]} ${c.id.padEnd(34)} ${Nd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ka(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(`
240
240
  `),"","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(`
241
241
  `)}async function Yn(e,t){let n=Ir(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of _r(Nr(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(`
242
242
  `),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(`
@@ -246,12 +246,12 @@ Articles:
246
246
  `)}var Xd={status:Vd,plan:zd,apply:Kd};async function Hr(e,t=Xd){let n={pulled:[],conflicts:[],untrackedRemote:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var Lr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Vn=e=>e===1?"":"s";function qr(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${Vn(e.pulled.length)} into local: ${Lr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Vn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /sync pull <path>): ${Lr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Vn(e.untrackedRemote.length)} in the portal aren't local yet (import comes with portal-aware sync): ${Lr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Vn(e.failed.length)} failed \u2014 left for /sync pull.`),t}async function $a(e,t){let n=t?.cwd??process.cwd();if(!Yd(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Wr(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Hr({cwd:n,profileName:t?.profileName});for(let p of qr(s))console.log(p.startsWith("\u2713")?E(p):p.startsWith("\u2139")?m(p):U(p));let c=Et(At(n));return console.log(m(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Fr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Jd}from"node:child_process";var it="document360-writer",zn=`npm i -g ${it}@latest`;async function Kn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Jd(`npm i -g ${it}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function va(){return console.log(m(`Updating ${it}\u2026`)),(await Kn()).ok?console.log(E("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${zn}`)),{kind:"continue"}}W();rt();import{existsSync as Br,rmSync as Qd}from"node:fs";import{basename as Ca,resolve as Gr}from"node:path";import{execFileSync as Zd}from"node:child_process";import{input as ep}from"@inquirer/prompts";import{readProjectConfig as tp,devHintsGuidePath as np}from"document360-engine";var op=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],rp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Xn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Pa=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ta(e){let t=Xn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Pa(t)?!0:rp.has(t)}function Yr(e){let t=null;try{t=tp(e)}catch{t=null}let n=new Set(op);for(let o of[Xn(t?.docsDir),Xn(t?.captureDir),Xn(t?.outputDir)])o&&Pa(o)&&n.add(o);return[...n].filter(o=>Ta(o)&&Br(Gr(e,o)))}function Vr(e,t){let n=[],o=[];for(let r of t){if(!Ta(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Qd(Gr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Ra(e,t){try{return Zd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
247
247
  `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function sp(e){return Ra(e,".d360-writer/hints")}function ip(e){return Ra(e,".d360-writer/messages")}function zr(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=sp(e),o=ip(e),r=Br(Gr(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Protected: root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${Ca(e)}`]}async function Sa(e,t){let n=Yr(t.cwd);for(let f of zr(t.cwd,n))console.log(n.length===0?m(f):f);if(n.length===0)return{kind:"continue"};let o=Ca(t.cwd);if((await t.withPausedInput(()=>ep({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Br(np(t.cwd)),{removed:c,failed:p}=Vr(t.cwd,n);console.log(E(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let f of p)console.log(v(` \u2717 ${f.path}: ${f.error}`));if(s){for(let f of _n())console.log(f);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var Da={help:Fo,"?":Fo,clear:Zs,exit:Ho,quit:Ho,init:gi,mcp:Un,publish:ji,audit:Qt,scope:Ei,sync:Li,convert:Wi,write:Bi,draft:Ki,document:Xi,resume:Zi,rename:ea,profile:na,model:sa,doctor:en,workspace:pa,project:fa,"allow-prod":ma,login:ha,logout:ga,screenshot:Yn,"capture-setup":tn,devhints:ii,inbox:xa,"catch-up":$a,update:va,reset:Sa};function ja(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}rt();W();var ap={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"},Ea=160,Xr=200,Ia=40;function he(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Aa(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}: ${he(typeof r=="string"?r:JSON.stringify(r),Ia)}`);return t.length>4&&n.push("\u2026"),he(n.join(", "),Ea)}var qe=e=>typeof e=="string"&&e?e:null,Kr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function lp(e){let t=qe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function cp(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=qe(t.title);if(!o)return null;let r=lp(t.local_path);return n("Create article",`"${he(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=qe(t.title),r=Kr(t.article_id);return n("Update article",o?`"${he(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Kr(t.article_id)?`id ${Kr(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",qe(t.name)?`"${he(qe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=qe(t.file_path);return n("Upload image",o?he(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Jn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let x=cp(c,t);if(x)return x}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Aa(t)}}let n=ap[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:he(o,Ea)}:{title:e,sep:"",arg:Aa(t)}}function up(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 dp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(up).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>he(r,Xr))]}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}: ${he(String(r),Ia)}`);return n.length>0?[he(n.join(" \xB7 "),Xr)]:null}return null}function pp(e){let t=qe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function fp(e,t,n){switch(e){case"d360_create_article":{let o=pp(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=qe(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 ${he(o[0],120)}`:""}`]}default:return null}}function Qn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
248
248
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=fp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=dp(r)??r.split(`
249
- `);return{lines:s.slice(0,t).map(c=>he(c,Xr)),hidden:Math.max(0,s.length-t)}}function Zn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function eo(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 to(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 Pp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Tp(e,t,n,o){if(Pp.test(e))try{let r=Ua(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=eo(t,n),p=to(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&s&&console.log(O(` \u2B95 Preview: ${Zn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ma(e=process.cwd(),t="auto",n){let o=hp(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Rp(e,n),o.kind==="subscription"&&(o.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Jr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=mp({input:process.stdin,output:process.stdout}),f=[],x=null,k=!1;p.on("line",T=>{if(x){let C=x;x=null,C(T)}else f.push(T)}),p.on("close",()=>{if(k=!0,x){let T=x;x=null,T(null)}});function A(){return f.length>0?Promise.resolve(f.shift()):k?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(T=>{x=T}))}let w={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Jr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async T=>s.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await A();if(T===null)break;let C=T.trim();if(C){if(C.startsWith("/")){let S=ja(C);if(!S)continue;let N=Da[S.name];if(!N){console.log(v(`Unknown command: /${S.name}`)),console.log(m("Type /help for the list."));continue}let H=await N(S.args,w);if(H.kind==="exit")break;if(H.kind==="clear"){w.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,w.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Jr({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let se=gp(H.uuid);c={uuid:H.uuid,firstPrompt:se?.firstPrompt??null,titleFired:!0},Oa(H.uuid),console.log(E(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await _a(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await _a(s,C,o,c,e)}}}finally{s.close(),p.close()}}function Rp(e,t){console.log(""),console.log(Ht("document360-writer")),console.log(m(` cwd: ${e}`));let n=xp(e);if(console.log(m(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Sp(e,t)),!$p(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{In(e);for(let o of Nn(e))console.log(U(` ${o}`))}catch{}try{let o=Et(At(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Sp(e,t){try{let n=Ua(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=Cp(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Na(r.idToken)??{},...Na(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return vp(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function Dp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function jp(e,t,n){e.uuid=t;let o=new Date().toISOString();kp({uuid:t,name:wp(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Ap(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||bp(o,t).then(r=>{r&&yp(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Ep(c,o,r,n,s)}function Ep(e,t,n,o,r){switch(e.type){case"session":t.uuid||jp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Jn(e.name,e.input);s&&(process.stdout.write(`
249
+ `);return{lines:s.slice(0,t).map(c=>he(c,Xr)),hidden:Math.max(0,s.length-t)}}function Zn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function eo(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 to(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 Pp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Tp(e,t,n,o){if(Pp.test(e))try{let r=Ua(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=eo(t,n),p=to(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&s&&console.log(O(` \u2B95 Preview: ${Zn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ma(e=process.cwd(),t="auto",n){let o=hp(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Rp(e,n),o.kind==="subscription"&&(o.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Jr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=mp({input:process.stdin,output:process.stdout}),f=[],x=null,k=!1;p.on("line",T=>{if(x){let C=x;x=null,C(T)}else f.push(T)}),p.on("close",()=>{if(k=!0,x){let T=x;x=null,T(null)}});function A(){return f.length>0?Promise.resolve(f.shift()):k?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(T=>{x=T}))}let y={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Jr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async T=>s.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await A();if(T===null)break;let C=T.trim();if(C){if(C.startsWith("/")){let R=ja(C);if(!R)continue;let N=Da[R.name];if(!N){console.log(v(`Unknown command: /${R.name}`)),console.log(m("Type /help for the list."));continue}let H=await N(R.args,y);if(H.kind==="exit")break;if(H.kind==="clear"){y.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,y.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Jr({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let se=gp(H.uuid);c={uuid:H.uuid,firstPrompt:se?.firstPrompt??null,titleFired:!0},Oa(H.uuid),console.log(E(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await _a(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await _a(s,C,o,c,e)}}}finally{s.close(),p.close()}}function Rp(e,t){console.log(""),console.log(Ht("document360-writer")),console.log(m(` cwd: ${e}`));let n=xp(e);if(console.log(m(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Sp(e,t)),!$p(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{In(e);for(let o of Nn(e))console.log(U(` ${o}`))}catch{}try{let o=Et(At(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Sp(e,t){try{let n=Ua(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=Cp(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Na(r.idToken)??{},...Na(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return vp(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function Dp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function jp(e,t,n){e.uuid=t;let o=new Date().toISOString();kp({uuid:t,name:yp(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Ap(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||bp(o,t).then(r=>{r&&wp(n,r)}).catch(()=>{})}async function _a(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Ep(c,o,r,n,s)}function Ep(e,t,n,o,r){switch(e.type){case"session":t.uuid||jp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Jn(e.name,e.input);s&&(process.stdout.write(`
250
250
 
251
251
  `),console.log(`${E("\u25CF")} ${Te(s.title)}${s.arg!==null?oe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=st(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(oe(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=Qn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:oe;c.lines.forEach((f,x)=>console.log(p((x===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||Tp(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
252
- `),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Oa(t.uuid),t.titleFired||Ap(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Dp();break}}import{render as qf}from"ink";import{resolveAuth as Bf}from"document360-engine";import{useCallback as Y,useEffect as $e,useMemo as os,useRef as X,useState as F}from"react";import{Box as te,Text as R,useApp as Kp,useInput as Xp,useStdout as Jp}from"ink";import{existsSync as Be,readFileSync as rs,readdirSync as mo}from"node:fs";import{spawnSync as Qp}from"node:child_process";import{basename as rn,isAbsolute as Zp,join as lt}from"node:path";import{createSession as pl,classifyClaudeAuth as cs,CLAUDE_CODE_SETUP_HINT as ef,loginPkce as tf,toStoredTokens as nf,saveTokens as of,getAccessToken as rf,resolveActiveProfile as ue,resolveProjectId as sf,getArticle as af,decodeJwtClaims as It,isExpired as _e,loadTokens as Ge,clearTokens as lf,clearProfileProject as cf,setTitle as uf,slugify as df,touchSession as ss,upsertSession as pf,generateTitle as fl,findByName as ff,listSessions as mf,renameSession as hf,suggestNextAction as gf,readProjectConfig as J,writeProjectConfig as ml,resolveModelSetting as us,loadProfileMap as fo,applyPull as yf,computeSyncStatus as is,planPull as wf,establishBaselines as kf,inventoryRepo as bf,knownEnvironments as xf,resolveEnvironment as $f,planPartitions as as,partitionEvenly as vf,screenshotPlaceholderIds as Cf,trackedArticlePaths as Pf,runPartitioned as co,estimateBulkCost as hl,resolveModelForOperation as uo,readDocsPlan as gl,checkForUpdate as Tf,detectInstallKind as Rf,isSelfUpdatable as Sf,devHintsGuidePath as ds,toolFeedbackPath as Df,reconcileToolFeedback as jf,DEFAULT_DOCS_DIR as sn,setProfileProject as Af,writeCrashLog as Ef}from"document360-engine";rt();import{spawn as La}from"node:child_process";function Ip(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Np(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?La([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):La(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Wa(e){for(let[t,n]of Ip())if(await Np(t,n,e))return!0;return!1}var _p=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Qr(e,t){if(t.closed)return e;let n=e.split(`
252
+ `),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Oa(t.uuid),t.titleFired||Ap(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Dp();break}}import{render as qf}from"ink";import{resolveAuth as Bf}from"document360-engine";import{useCallback as Y,useEffect as $e,useMemo as os,useRef as X,useState as F}from"react";import{Box as te,Text as S,useApp as Kp,useInput as Xp,useStdout as Jp}from"ink";import{existsSync as Be,readFileSync as rs,readdirSync as mo}from"node:fs";import{spawnSync as Qp}from"node:child_process";import{basename as rn,isAbsolute as Zp,join as lt}from"node:path";import{createSession as pl,classifyClaudeAuth as cs,CLAUDE_CODE_SETUP_HINT as ef,loginPkce as tf,toStoredTokens as nf,saveTokens as of,getAccessToken as rf,resolveActiveProfile as ue,resolveProjectId as sf,getArticle as af,decodeJwtClaims as It,isExpired as _e,loadTokens as Ge,clearTokens as lf,clearProfileProject as cf,setTitle as uf,slugify as df,touchSession as ss,upsertSession as pf,generateTitle as fl,findByName as ff,listSessions as mf,renameSession as hf,suggestNextAction as gf,readProjectConfig as J,writeProjectConfig as ml,resolveModelSetting as us,loadProfileMap as fo,applyPull as wf,computeSyncStatus as is,planPull as yf,establishBaselines as kf,inventoryRepo as bf,knownEnvironments as xf,resolveEnvironment as $f,planPartitions as as,partitionEvenly as vf,screenshotPlaceholderIds as Cf,trackedArticlePaths as Pf,runPartitioned as co,estimateBulkCost as hl,resolveModelForOperation as uo,readDocsPlan as gl,checkForUpdate as Tf,detectInstallKind as Rf,isSelfUpdatable as Sf,devHintsGuidePath as ds,toolFeedbackPath as Df,reconcileToolFeedback as jf,DEFAULT_DOCS_DIR as sn,setProfileProject as Af,writeCrashLog as Ef}from"document360-engine";rt();import{spawn as La}from"node:child_process";function Ip(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Np(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?La([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):La(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Wa(e){for(let[t,n]of Ip())if(await Np(t,n,e))return!0;return!1}var _p=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Qr(e,t){if(t.closed)return e;let n=e.split(`
253
253
  `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){_p.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
254
- `)}import{existsSync as Op,mkdirSync as Up,readFileSync as Mp,writeFileSync as Lp}from"node:fs";import{join as Fa}from"node:path";import{writerDir as Wp}from"document360-engine";function Ha(e){return Fa(Wp(e),".sessions")}function qa(e,t){return Fa(Ha(e),`${t}.json`)}function Ba(e,t,n){try{Up(Ha(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Lp(qa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Zr(e,t){try{let n=qa(e,t);if(!Op(n))return[];let o=JSON.parse(Mp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Fp=e=>`\x1B]0;${e}\x07`,Hp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ga(e){process.stdout.isTTY&&process.stdout.write(e)}function nn(e){Ga(Fp(e))}function no(e){Ga(Hp(e))}var oo=["\xB7 "," \xB7"],es="\u{1F7E3}";Gn();var ro=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ya={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Va(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ya[n])return Ya[n];let o=ro.find(r=>r.name===t);return o?o.desc:""}function za(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ro.filter(n=>n.name.startsWith(t))}function Ka(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Xa,Text as re}from"ink";import{jsx as ie,jsxs as so}from"react/jsx-runtime";function qp({row:e}){switch(e.t){case"head":return ie(re,{color:L,bold:!0,children:e.s});case"text":return ie(re,{children:e.s});case"dim":return ie(re,{dimColor:!0,children:e.s});case"sub":return ie(re,{bold:!0,dimColor:!0,children:e.s});case"good":return ie(re,{color:"green",children:e.s});case"step":return so(re,{children:[ie(re,{color:L,children:`${e.n}. `}),e.s]});case"cmd":return so(re,{children:[" ",ie(re,{color:L,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Ja({tab:e,width:t}){let n=xe[e]??xe[0],o=6+xe.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return so(Xa,{flexDirection:"column",paddingX:1,children:[so(re,{children:[ie(re,{color:L,bold:!0,children:"Help "}),xe.map((s,c)=>c===e?ie(re,{color:L,bold:!0,inverse:!0,children:` ${s.label} `},s.key):ie(re,{dimColor:!0,children:` ${s.label} `},s.key))]}),ie(re,{color:L,children:r}),ie(Xa,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ie(qp,{row:s},c))}),ie(re,{dimColor:!0,children:`
254
+ `)}import{existsSync as Op,mkdirSync as Up,readFileSync as Mp,writeFileSync as Lp}from"node:fs";import{join as Fa}from"node:path";import{writerDir as Wp}from"document360-engine";function Ha(e){return Fa(Wp(e),".sessions")}function qa(e,t){return Fa(Ha(e),`${t}.json`)}function Ba(e,t,n){try{Up(Ha(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Lp(qa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Zr(e,t){try{let n=qa(e,t);if(!Op(n))return[];let o=JSON.parse(Mp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Fp=e=>`\x1B]0;${e}\x07`,Hp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ga(e){process.stdout.isTTY&&process.stdout.write(e)}function nn(e){Ga(Fp(e))}function no(e){Ga(Hp(e))}var oo=["\xB7 "," \xB7"],es="\u{1F7E3}";Gn();var ro=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ya={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Va(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ya[n])return Ya[n];let o=ro.find(r=>r.name===t);return o?o.desc:""}function za(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ro.filter(n=>n.name.startsWith(t))}function Ka(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Xa,Text as re}from"ink";import{jsx as ie,jsxs as so}from"react/jsx-runtime";function qp({row:e}){switch(e.t){case"head":return ie(re,{color:L,bold:!0,children:e.s});case"text":return ie(re,{children:e.s});case"dim":return ie(re,{dimColor:!0,children:e.s});case"sub":return ie(re,{bold:!0,dimColor:!0,children:e.s});case"good":return ie(re,{color:"green",children:e.s});case"step":return so(re,{children:[ie(re,{color:L,children:`${e.n}. `}),e.s]});case"cmd":return so(re,{children:[" ",ie(re,{color:L,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Ja({tab:e,width:t}){let n=xe[e]??xe[0],o=6+xe.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return so(Xa,{flexDirection:"column",paddingX:1,children:[so(re,{children:[ie(re,{color:L,bold:!0,children:"Help "}),xe.map((s,c)=>c===e?ie(re,{color:"white",backgroundColor:L,bold:!0,children:` ${s.label} `},s.key):ie(re,{dimColor:!0,children:` ${s.label} `},s.key))]}),ie(re,{color:L,children:r}),ie(Xa,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ie(qp,{row:s},c))}),ie(re,{dimColor:!0,children:`
255
255
  \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Bp=/^(?:\d+[.)]|[-*•])\s+/;function Qa(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
256
256
  `)){let c=s.trim().replace(Bp,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let f=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!f||!o.has(f[1].toLowerCase()))continue;let x=`/${f[1].toLowerCase()}${f[2]?` ${f[2]}`:""}`;if(r.includes(x)||r.push(x),r.length>=n)break}return r}W();function on(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ne(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function ts(e){return e.replace(/^[\w.-]+\//,"")}var io=16,Za={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ns(e){return e.trim().split(/\s+/).slice(1).join(" ")}function el(e,t){let n=ns(t);return e.some(r=>r.trim()===t.trim()||!!n&&ns(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&ns(r)===n)):[]}var Gp='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function Yp(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/sync":return"check Document360 for changes made there";default:return""}}function at(e){return e===1?"":"s"}function Vp(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/sync":return"it reconciles anything changed on Document360";default:return"it\u2019s the most useful next step"}}function tl(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${at(e.pendingWrites)} still unwritten`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${at(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Vp(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${at(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${Yp(s,n)}`),"Or just tell me what to write or update."),r.join(`
257
257
  `)}function nl(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Gp,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${at(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:tl(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${at(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/sync"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${at(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${at(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:tl(e,n,t),title:o,options:n}}var zp=/\[Pasted text #\d+ \+\d+ lines?\]/g;function ol(e){return e.replace(/\r\n?/g,`
@@ -261,37 +261,37 @@ Articles:
261
261
  `)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function lo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function ll(e,t,n){let o=lo(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function cl(e,t,n){let o=e[lo(e,t)];return n==="start"?o.start:o.end}function ul(e,t,n){let o=Math.max(1,n),r=e.split(`
262
262
  `),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let f=s-t;return{text:[f>0?p.slice(f*o):p,...r.slice(c+1)].join(`
263
263
  `),truncated:c>0||f>0}}}return{text:e,truncated:!1}}function dl(e){let t=!1,n=0,o=0;for(let r of e.split(`
264
- `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as ls,jsx as j,jsxs as B}from"react/jsx-runtime";var If={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},yl=` 1. /init \u2014 pick your Document360 environment & scaffold config
264
+ `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as ls,jsx as j,jsxs as B}from"react/jsx-runtime";var If={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},wl=` 1. /init \u2014 pick your Document360 environment & scaffold config
265
265
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
266
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Nf(e,t,n,o){let r=cs(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=us(e),p=J(e),f=(p?.docsDir??sn).replace(/\/+$/,""),x=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${f}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:If[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:x};if(p===null)return k;try{let A=ue(e,o);k.profile=A.name,k.apiUrl=A.connection.apiUrl,k.prod=A.production,k.project=A.project.projectName??A.project.projectId??"(chosen at login)";let w=Ge(A.name);if(w){let T={...It(w.idToken)??{},...It(w.accessToken)??{}},C=T.email??T.preferred_username??"signed in";_e(w)?w.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(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function _f(e,t){try{let n=ue(e,t),o=Ge(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...It(o.idToken)??{},...It(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var wl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],ho=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Of="Ask me to write or update an article\u2026";function po({ch:e,dim:t}){let[n,o]=F(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(R,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Uf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function kl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Mf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bl(e){try{return mo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function xl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>bl(lt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&bl(lt(e,o)))}function $l(e,t){try{let n=J(e);if(!n)return!1;let o=ue(e,t),r=fo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=lt(e,(n.docsDir??sn).replace(/\/+$/,""));return!!(Be(s)&&mo(s).length>0||Be(ds(e)))}catch{return!1}}function Lf({startTime:e,chars:t}){let[n,o]=F(0);$e(()=>{let f=setInterval(()=>o(x=>x+1),120);return()=>clearInterval(f)},[]);let r=ho[n%ho.length],s=wl[Math.floor(n/16)%wl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(R,{color:L,children:` ${r} ${s}\u2026 `}),j(R,{color:"gray",children:`(${Kt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Wf=12e4;function Ff({p:e}){let[t,n]=F(0);$e(()=>{let N=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(N)},[]);let o=ho[t%ho.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Wf,f=e.verb??"Converting",x=e.unit??"article",k=e.rows.reduce((N,H)=>N+H.items,0),A=f.toLowerCase(),w=e.rows,T=0;if(w.length>io){let N=w.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(N-2,w.length-io));T=w.slice(0,H).filter(se=>se.status==="done").length,w=w.slice(H,H+io)}let C=Math.min(40,Math.max(...w.map(N=>ts(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?L:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(R,{color:L,children:` ${o} ${f} ${k} ${x}${k===1?"":"s"} `}),j(R,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Kt(r)} \xB7 esc to stop`})]}),T>0&&j(R,{dimColor:!0,children:` \u2714 +${T} done`}),w.map(N=>B(R,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Za[N.status]} ${ts(N.label).padEnd(C)}`,N.status!=="pending"?` (${N.items} ${x}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${A}\u2026`:""]},N.label)),p&&j(R,{color:"yellow",children:` \u26A0 no activity for ${Kt(s)} \u2014 press esc to stop if it's wedged`})]})}var Hf=10800*1e3;function vl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Kp(),[s,c]=F(n),[p,f]=F(null),[x,k]=F({text:"",pos:0}),A=x.text,w=Y(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),T=Y(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=Y(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=al(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[S,N]=F(!1),[H,se]=F(!1),[ve,ae]=F(0),[Ce,le]=F(null),[Ye,G]=F([]),ct=X(0),[jl,an]=F(!1),[Al,ln]=F(!1),[go,hs]=F(null),[El,ut]=F(0),Ve=X(0),[Nt,dt]=F(0),[pt,cn]=F(null),gs=X(new Map),Il=X(0),ft=X([]),ge=X(null);ge.current===null&&(ge.current=pl({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),un=X(new Map),mt=X(!1),yo=X([]),Ue=X([]),wo=X(null),[ys,ht]=F(null),[ze,Ke]=F(null),[De,gt]=F(null),[Me,yt]=F(null),[de,wt]=F(null),[ye,Xe]=F(null),[Je,kt]=F(null),[ws,Qe]=F(null),[we,Ze]=F(null),[fe,bt]=F(null),[ks,ko]=F([]),et=X([]),_t=X(!1),ke=X(null),[bs,Q]=F(null),dn=X(!1),pn=X(null),Ot=X(null),[be,tt]=F(null),[bo,Ut]=F(null),[xs,xt]=F(0),[$s,$t]=F(0),[Nl,vs]=F(0),xo=os(()=>{try{return us(e).model??"auto"}catch{return null}},[e,Nl]),{stdout:Pe}=Jp(),[,_l]=F(0),Cs=X(`${Pe.columns??80}x${Pe.rows??24}`),Le=Y(()=>Math.max(20,(Pe.columns??80)-1),[Pe]),d=Y(l=>{ft.current.push(l),console.log(Zo(l,Le()))},[Le]),[$o,vo]=F(null),vt=Y(l=>{vo(l),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]),Co=X(!1),Po=Y(async()=>{try{if(Co.current||!Sf(Rf())||J(e)?.mode==="engineer")return;let l=await Tf({pkg:it,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Co.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${it} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),ln(!0),(await Kn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(a=>a.includes("/exit")?a:[...a,"/exit"]),hs(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${zn}`})}catch{}},[e,o,d]),To=Y(l=>{let i=Ie(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Ot.current=l,G(["/login"]),!1)},[e,s,d]),[Ro,So]=F(null),Mt=X(!0),fn=X(0),Lt=X(0);$e(()=>{let l=setInterval(()=>{if(Mt.current){fn.current=0,Lt.current=0;return}if(!S)try{if(!Be(ds(e)))return;if(Ee(e).status==="current"){Mt.current=!0,fn.current=0,Lt.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."}),vo(null),le("write the docs for this repo");return}fn.current+=1;let i=fn.current;if((i===4||i%15===0)&&Lt.current<3){Lt.current+=1;let a=Lt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Yt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),$e(()=>{let l=`d360-writer \xB7 ${ys??rn(e)}`;if(!S){no(0),nn(`${es} ${l}`);return}no(3);let i=0;nn(`${oo[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%oo.length,nn(`${oo[i]} ${l}`)},400);return()=>clearInterval(a)},[S,e,ys]),$e(()=>()=>no(0),[]);let Do=Y(l=>{try{let i=J(e);if(!i)return{kind:"idle"};let a=ue(e,s),g=Ge(a.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=$l(e,s)||!xl(e,i.authoritativeSourceFiles),y=cs(t).state==="missing",b=fo(e,a.name),P=b?Object.keys(b.articles).length:0,I=lt(e,(i.docsDir??sn).replace(/\/+$/,"")),K=!1;try{K=Be(I)&&mo(I).length>0}catch{}let Z=0;if(b?.lastAnalyzedCommit)try{let D=Qp("git",["rev-list","--count",`${b.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});D.status===0&&(Z=parseInt((D.stdout||"").trim(),10)||0)}catch{}let _=0;try{let D=gl(e);if(D.length>0){let M=(i.docsDir??sn).replace(/\/+$/,"");_=gr(e,M,D.map(ee=>ee.path)).length}}catch{}let $={ready:u&&h&&!y,hasDocs:K,tracked:P,pendingText:Et(At(e)),behind:Z,pendingWrites:_,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return nl($)}catch{return{kind:"idle"}}},[e,s,t]);$e(()=>{let l=performance.now(),i=[],a=(y,b)=>{let P=performance.now();try{return b()}finally{let I=Math.round(performance.now()-P);I>=80&&i.push(`${y}: ${I}ms`)}};d({kind:"banner",info:a("banner",()=>Nf(e,o,t,s))});let g=cs(t).state==="missing";if(g&&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.
266
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Nf(e,t,n,o){let r=cs(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=us(e),p=J(e),f=(p?.docsDir??sn).replace(/\/+$/,""),x=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${f}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:If[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:x};if(p===null)return k;try{let A=ue(e,o);k.profile=A.name,k.apiUrl=A.connection.apiUrl,k.prod=A.production,k.project=A.project.projectName??A.project.projectId??"(chosen at login)";let y=Ge(A.name);if(y){let T={...It(y.idToken)??{},...It(y.accessToken)??{}},C=T.email??T.preferred_username??"signed in";_e(y)?y.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(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function _f(e,t){try{let n=ue(e,t),o=Ge(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...It(o.idToken)??{},...It(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var yl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],ho=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Of="Ask me to write or update an article\u2026";function po({ch:e,dim:t}){let[n,o]=F(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Uf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function kl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Mf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bl(e){try{return mo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function xl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>bl(lt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&bl(lt(e,o)))}function $l(e,t){try{let n=J(e);if(!n)return!1;let o=ue(e,t),r=fo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=lt(e,(n.docsDir??sn).replace(/\/+$/,""));return!!(Be(s)&&mo(s).length>0||Be(ds(e)))}catch{return!1}}function Lf({startTime:e,chars:t}){let[n,o]=F(0);$e(()=>{let f=setInterval(()=>o(x=>x+1),120);return()=>clearInterval(f)},[]);let r=ho[n%ho.length],s=yl[Math.floor(n/16)%yl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(S,{color:L,children:` ${r} ${s}\u2026 `}),j(S,{color:"gray",children:`(${Kt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Wf=12e4;function Ff({p:e}){let[t,n]=F(0);$e(()=>{let N=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(N)},[]);let o=ho[t%ho.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Wf,f=e.verb??"Converting",x=e.unit??"article",k=e.rows.reduce((N,H)=>N+H.items,0),A=f.toLowerCase(),y=e.rows,T=0;if(y.length>io){let N=y.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(N-2,y.length-io));T=y.slice(0,H).filter(se=>se.status==="done").length,y=y.slice(H,H+io)}let C=Math.min(40,Math.max(...y.map(N=>ts(N.label).length),0)),R=N=>N==="failed"?"red":N==="active"?L:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(S,{color:L,children:` ${o} ${f} ${k} ${x}${k===1?"":"s"} `}),j(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Kt(r)} \xB7 esc to stop`})]}),T>0&&j(S,{dimColor:!0,children:` \u2714 +${T} done`}),y.map(N=>B(S,{color:R(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Za[N.status]} ${ts(N.label).padEnd(C)}`,N.status!=="pending"?` (${N.items} ${x}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${A}\u2026`:""]},N.label)),p&&j(S,{color:"yellow",children:` \u26A0 no activity for ${Kt(s)} \u2014 press esc to stop if it's wedged`})]})}var Hf=10800*1e3;function vl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Kp(),[s,c]=F(n),[p,f]=F(null),[x,k]=F({text:"",pos:0}),A=x.text,y=Y(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),T=Y(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=Y(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=al(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[R,N]=F(!1),[H,se]=F(!1),[ve,ae]=F(0),[Ce,le]=F(null),[Ye,G]=F([]),ct=X(0),[jl,an]=F(!1),[Al,ln]=F(!1),[go,hs]=F(null),[El,ut]=F(0),Ve=X(0),[Nt,dt]=F(0),[pt,cn]=F(null),gs=X(new Map),Il=X(0),ft=X([]),ge=X(null);ge.current===null&&(ge.current=pl({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),un=X(new Map),mt=X(!1),wo=X([]),Ue=X([]),yo=X(null),[ws,ht]=F(null),[ze,Ke]=F(null),[De,gt]=F(null),[Me,wt]=F(null),[de,yt]=F(null),[we,Xe]=F(null),[Je,kt]=F(null),[ys,Qe]=F(null),[ye,Ze]=F(null),[fe,bt]=F(null),[ks,ko]=F([]),et=X([]),_t=X(!1),ke=X(null),[bs,Q]=F(null),dn=X(!1),pn=X(null),Ot=X(null),[be,tt]=F(null),[bo,Ut]=F(null),[xs,xt]=F(0),[$s,$t]=F(0),[Nl,vs]=F(0),xo=os(()=>{try{return us(e).model??"auto"}catch{return null}},[e,Nl]),{stdout:Pe}=Jp(),[,_l]=F(0),Cs=X(`${Pe.columns??80}x${Pe.rows??24}`),Le=Y(()=>Math.max(20,(Pe.columns??80)-1),[Pe]),d=Y(l=>{ft.current.push(l),console.log(Zo(l,Le()))},[Le]),[$o,vo]=F(null),vt=Y(l=>{vo(l),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]),Co=X(!1),Po=Y(async()=>{try{if(Co.current||!Sf(Rf())||J(e)?.mode==="engineer")return;let l=await Tf({pkg:it,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;Co.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${it} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),ln(!0),(await Kn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(a=>a.includes("/exit")?a:[...a,"/exit"]),hs(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${zn}`})}catch{}},[e,o,d]),To=Y(l=>{let i=Ie(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Ot.current=l,G(["/login"]),!1)},[e,s,d]),[Ro,So]=F(null),Mt=X(!0),fn=X(0),Lt=X(0);$e(()=>{let l=setInterval(()=>{if(Mt.current){fn.current=0,Lt.current=0;return}if(!R)try{if(!Be(ds(e)))return;if(Ee(e).status==="current"){Mt.current=!0,fn.current=0,Lt.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."}),vo(null),le("write the docs for this repo");return}fn.current+=1;let i=fn.current;if((i===4||i%15===0)&&Lt.current<3){Lt.current+=1;let a=Lt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Yt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,R,d]),$e(()=>{let l=`d360-writer \xB7 ${ws??rn(e)}`;if(!R){no(0),nn(`${es} ${l}`);return}no(3);let i=0;nn(`${oo[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%oo.length,nn(`${oo[i]} ${l}`)},400);return()=>clearInterval(a)},[R,e,ws]),$e(()=>()=>no(0),[]);let Do=Y(l=>{try{let i=J(e);if(!i)return{kind:"idle"};let a=ue(e,s),g=Ge(a.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=$l(e,s)||!xl(e,i.authoritativeSourceFiles),w=cs(t).state==="missing",b=fo(e,a.name),P=b?Object.keys(b.articles).length:0,I=lt(e,(i.docsDir??sn).replace(/\/+$/,"")),K=!1;try{K=Be(I)&&mo(I).length>0}catch{}let Z=0;if(b?.lastAnalyzedCommit)try{let D=Qp("git",["rev-list","--count",`${b.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});D.status===0&&(Z=parseInt((D.stdout||"").trim(),10)||0)}catch{}let _=0;try{let D=gl(e);if(D.length>0){let M=(i.docsDir??sn).replace(/\/+$/,"");_=gr(e,M,D.map(ee=>ee.path)).length}}catch{}let $={ready:u&&h&&!w,hasDocs:K,tracked:P,pendingText:Et(At(e)),behind:Z,pendingWrites:_,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return nl($)}catch{return{kind:"idle"}}},[e,s,t]);$e(()=>{let l=performance.now(),i=[],a=(w,b)=>{let P=performance.now();try{return b()}finally{let I=Math.round(performance.now()-P);I>=80&&i.push(`${w}: ${I}ms`)}};d({kind:"banner",info:a("banner",()=>Nf(e,o,t,s))});let g=cs(t).state==="missing";if(g&&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.
267
267
  ${ef}
268
268
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!J(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:
269
- ${yl}`}),G(g?["/doctor","/init"]:["/init"]);return}g&&G(["/doctor"]);try{let y=ue(e,s),b=Ge(y.name);b&&_e(b)&&b.refreshToken?rf({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ae(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!b||_e(b))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let y=J(e),b=ue(e,s),P=Ge(b.name);y&&P&&!_e(P)&&xl(e,y.authoritativeSourceFiles)&&!$l(e,s)&&(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."}),G(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>In(e)),Ee(e).status!=="current")if(Yt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${ne}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let y=Nn(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
270
- `)}),vt(ot()),Mt.current=!1)}}catch{}try{let y=a("reconcile-feedback",()=>jf(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Do(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),Qt().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&ce(y.prompt,{display:y.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),le(u.ghost),G(u.options),u.title&&Qe(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),G(u.options),Qe(u.title));let h=Math.round(performance.now()-l);h>=800&&Ef({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
269
+ ${wl}`}),G(g?["/doctor","/init"]:["/init"]);return}g&&G(["/doctor"]);try{let w=ue(e,s),b=Ge(w.name);b&&_e(b)&&b.refreshToken?rf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ae(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!b||_e(b))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let w=J(e),b=ue(e,s),P=Ge(b.name);w&&P&&!_e(P)&&xl(e,w.authoritativeSourceFiles)&&!$l(e,s)&&(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."}),G(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>In(e)),Ee(e).status!=="current")if(Yt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${ne}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Nn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
270
+ `)}),vt(ot()),Mt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>jf(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>Do(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),Qt().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ce(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),le(u.ghost),G(u.options),u.title&&Qe(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),G(u.options),Qe(u.title));let h=Math.round(performance.now()-l);h>=800&&Ef({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
271
271
  `):"no single phase \u226580ms"}
272
- cwd: ${e}`}),Po()},[]),$e(()=>{let l=setInterval(()=>{Po()},Hf);return()=>clearInterval(l)},[Po]),$e(()=>{if(S||Ye.length>0)return;let l=Do(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Qe(l.title??null))},[S,Ye,ve,Do]),$e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Pe.columns??80}x${Pe.rows??24}`;g!==Cs.current&&(Cs.current=g,_l(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ti(ft.current,Le())+"\x1B[?2026l")},80))},400)};return Pe.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Pe.off("resize",a)}},[Pe,Le]);let je=Math.max(20,(Pe.columns??80)-1),Ps=os(()=>_f(e,s),[e,s,ve]),jo=(()=>{if(Al)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(go!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${go?` v${go}`:""}\u2026`,isSetup:!0};let l=J(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=lt(e,(l.docsDir??sn).replace(/\/+$/,"")),a=(()=>{try{return Be(i)&&mo(i).length>0}catch{return!1}})();try{let g=ue(e,s),u=Ge(g.name);if(!(!!u&&!(_e(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Of,isSetup:!1}:$o?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Wt=za(A),Ts=Wt.length>0&&!S,Ao=p!==null?ul(p,8,je):null,mn=we?we.paths.filter(l=>!we.query||l.toLowerCase().includes(we.query.toLowerCase())).slice(0,8):[],hn=be?be.sessions.filter(l=>{let i=be.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],me=Y((l,i)=>{ge.current?.close(),ge.current=pl({cwd:e,resume:l,profileName:i??s,allowProdWrites:mt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),xt(0),$t(0)},[e,s]),Rs=Y((l,i,a)=>{if(Uf.test(l))try{let g=ue(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,h=eo(i,a),y=[],b=to(a);l.endsWith("publish_article")&&b&&y.push(`Live: ${b}`),h&&u&&y.push(`Preview: ${Zn(g.connection.portalUrl,u,h,g.project.languageCode??"en")}`),y.length>0&&d({kind:"link",lines:y})}catch{}},[e,s,d]),ce=Y(async(l,i)=>{an(!0),le(null),G([]),Qe(null),vo(null),So(null);let a=++ct.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Ve.current=Date.now(),ut(0),N(!0),un.current.clear();let u="",h=!1,y=!1,b="",P={num:0,closed:!1,cueSeen:!1},I=null,K=()=>{I||(I=setTimeout(()=>{I=null,f(b.length>0?b:null)},60))},Z=()=>{I&&clearTimeout(I),I=null,f(null)},_=()=>{if(b.trim()){let $=Qr(b.trimEnd(),P);d({kind:"assistant",text:$})}b="",Z()};try{for await(let $ of ge.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let D=new Date().toISOString(),M=df(g.firstPrompt??"session");pf({uuid:$.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:D,updatedAt:D}),ht(M)}}else if($.type==="text"){b+=$.delta,u+=$.delta;let D=dl(b);if(D>0){let M=b.slice(0,D).trimEnd();M&&d({kind:"assistant",text:Qr(M,P)}),b=b.slice(D)}K(),ut(M=>M+$.delta.length)}else if($.type==="tool"){h=!0;let D=Jn($.name,$.input);D&&(_(),d({kind:"tool",title:D.title,sep:D.sep,arg:D.arg}),un.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let D=st($.oldContent,$.newContent,Le());D&&(_(),d({kind:"diff",added:D.added,removed:D.removed,lines:D.lines,hidden:D.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(dn.current=!0);let D=un.current.get($.id);if(D){un.current.delete($.id),_();let M=Qn($.output,4,$.isError?void 0:D.name,D.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:$.isError}),$.isError||Rs(D.name,D.input,$.output)}}else if($.type==="result"){if(_(),xt(M=>M+$.outputTokens),$t(M=>M+$.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ve.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!y&&!h&&!u.trim()&&!_t.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let M=Df(e);if(Be(M)){let ee=rs(M,"utf8").trim();ee&&(So(ee),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let D=$.ok?Qa(u,ro.map(M=>M.name)):[];if(D.length>0?G(D):$.ok&&u.trim()&&gf(l,u,e).then(M=>{M&&ct.current===a&&le(M)}).catch(()=>{}),g.uuid&&(ss(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,ee=g.firstPrompt;ee&&fl(ee,e).then(q=>{q&&(uf(M,q),ht(q))}).catch(()=>{})}}else $.type==="error"&&(_(),y=!0,$.kind==="auth"&&(dn.current=!0),d({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{N(!1),Z(),ae($=>$+1),Se.current.uuid&&Ba(e,Se.current.uuid,ft.current),dn.current&&(dn.current=!1,pn.current=i?.display??l,G(["/login"])),_t.current&&(_t.current=!1,et.current.length>0&&(d({kind:"note",tone:"info",text:`(${et.current.length} queued message(s) discarded)`}),et.current=[],ko([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Rs,Le]),gn=Y(async l=>{let i=as(l),a=uo(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let g=new AbortController;ke.current=g,Q({verb:"Publishing",total:i.length,done:0,active:[],rows:on(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Xt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of co({cwd:e,partitions:i,promptFor:h=>Ln(h.paths),concurrency:Xt,profileName:s,allowProdWrites:mt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?Q(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):Q(h=>h&&{...h,active:h.active.filter(y=>y!==u.label),done:h.done+1,rows:Ne(h.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")Q(h=>{if(!h)return h;let y={...h,lastAt:Date.now()};return u.event.type==="tool"?y.tools=h.tools+1:u.event.type==="text"&&(y.chars=h.chars+u.event.delta.length),y});else if(u.type==="run_done"){$t(P=>P+u.totalCostUsd),xt(P=>P+u.results.reduce((I,K)=>I+K.outputTokens,0));let h=u.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:h+rr(u.results,i,y).join(`
273
- `)});let b=or(e,s);b&&d({kind:"note",tone:"info",text:b})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,Q(null),N(!1),ae(u=>u+1)}},[e,s,d,t]),Eo=Y(async l=>{await ce(nr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Wn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Qe(`Related articles not yet published (${i.length}):`),G([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ce]),Io=Y(l=>{let i=Ge(l);if(!i||_e(i)&&!i.refreshToken)return null;let a={...It(i.idToken)??{},...It(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),No=Y((l,i)=>{if(i){let a=J(e);a&&(a.defaultProfile=l,ml(a,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Io(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),ae(a=>a+1)},[e,d,me,Io]),yn=Y((l,i,a)=>{vn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),me(),fo(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:St(Rt(e)).join(`
274
- `)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,me,vt]),wn=Y(async l=>{let i;try{i=await qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],h=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),yn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,yn]),kn=Y((l,i)=>{Lo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),me(),wn(l)},[e,d,me,wn]),Ss=Y(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await nt(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Af(e,i.name,{projectName:g.name})}catch{}await wn(i.name);return}try{let{projects:a}=await nt(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),kn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Xe({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,wn,kn]),bn=Y(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=st(l.oldContent,l.newContent,Le());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Le]),Ds=Y(l=>{if(Ue.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ue.current.shift();try{yf({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ue.current.length===0&&G(g=>g.length>0?g:["/sync"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return bn(),!0},[e,s,bn,d]),js=Y(l=>{let i=wo.current;if(!i)return!1;if(wo.current=null,le(null),ct.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Vr(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:_n().join(`
272
+ cwd: ${e}`}),Po()},[]),$e(()=>{let l=setInterval(()=>{Po()},Hf);return()=>clearInterval(l)},[Po]),$e(()=>{if(R||Ye.length>0)return;let l=Do(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Qe(l.title??null))},[R,Ye,ve,Do]),$e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Pe.columns??80}x${Pe.rows??24}`;g!==Cs.current&&(Cs.current=g,_l(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ti(ft.current,Le())+"\x1B[?2026l")},80))},400)};return Pe.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Pe.off("resize",a)}},[Pe,Le]);let je=Math.max(20,(Pe.columns??80)-1),Ps=os(()=>_f(e,s),[e,s,ve]),jo=(()=>{if(Al)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(go!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${go?` v${go}`:""}\u2026`,isSetup:!0};let l=J(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=lt(e,(l.docsDir??sn).replace(/\/+$/,"")),a=(()=>{try{return Be(i)&&mo(i).length>0}catch{return!1}})();try{let g=ue(e,s),u=Ge(g.name);if(!(!!u&&!(_e(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Of,isSetup:!1}:$o?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Wt=za(A),Ts=Wt.length>0&&!R,Ao=p!==null?ul(p,8,je):null,mn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],hn=be?be.sessions.filter(l=>{let i=be.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],me=Y((l,i)=>{ge.current?.close(),ge.current=pl({cwd:e,resume:l,profileName:i??s,allowProdWrites:mt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),xt(0),$t(0)},[e,s]),Rs=Y((l,i,a)=>{if(Uf.test(l))try{let g=ue(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,h=eo(i,a),w=[],b=to(a);l.endsWith("publish_article")&&b&&w.push(`Live: ${b}`),h&&u&&w.push(`Preview: ${Zn(g.connection.portalUrl,u,h,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ce=Y(async(l,i)=>{an(!0),le(null),G([]),Qe(null),vo(null),So(null);let a=++ct.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Ve.current=Date.now(),ut(0),N(!0),un.current.clear();let u="",h=!1,w=!1,b="",P={num:0,closed:!1,cueSeen:!1},I=null,K=()=>{I||(I=setTimeout(()=>{I=null,f(b.length>0?b:null)},60))},Z=()=>{I&&clearTimeout(I),I=null,f(null)},_=()=>{if(b.trim()){let $=Qr(b.trimEnd(),P);d({kind:"assistant",text:$})}b="",Z()};try{for await(let $ of ge.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let D=new Date().toISOString(),M=df(g.firstPrompt??"session");pf({uuid:$.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:D,updatedAt:D}),ht(M)}}else if($.type==="text"){b+=$.delta,u+=$.delta;let D=dl(b);if(D>0){let M=b.slice(0,D).trimEnd();M&&d({kind:"assistant",text:Qr(M,P)}),b=b.slice(D)}K(),ut(M=>M+$.delta.length)}else if($.type==="tool"){h=!0;let D=Jn($.name,$.input);D&&(_(),d({kind:"tool",title:D.title,sep:D.sep,arg:D.arg}),un.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let D=st($.oldContent,$.newContent,Le());D&&(_(),d({kind:"diff",added:D.added,removed:D.removed,lines:D.lines,hidden:D.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(dn.current=!0);let D=un.current.get($.id);if(D){un.current.delete($.id),_();let M=Qn($.output,4,$.isError?void 0:D.name,D.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:$.isError}),$.isError||Rs(D.name,D.input,$.output)}}else if($.type==="result"){if(_(),xt(M=>M+$.outputTokens),$t(M=>M+$.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ve.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!w&&!h&&!u.trim()&&!_t.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let M=Df(e);if(Be(M)){let ee=rs(M,"utf8").trim();ee&&(So(ee),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let D=$.ok?Qa(u,ro.map(M=>M.name)):[];if(D.length>0?G(D):$.ok&&u.trim()&&gf(l,u,e).then(M=>{M&&ct.current===a&&le(M)}).catch(()=>{}),g.uuid&&(ss(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,ee=g.firstPrompt;ee&&fl(ee,e).then(q=>{q&&(uf(M,q),ht(q))}).catch(()=>{})}}else $.type==="error"&&(_(),w=!0,$.kind==="auth"&&(dn.current=!0),d({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{N(!1),Z(),ae($=>$+1),Se.current.uuid&&Ba(e,Se.current.uuid,ft.current),dn.current&&(dn.current=!1,pn.current=i?.display??l,G(["/login"])),_t.current&&(_t.current=!1,et.current.length>0&&(d({kind:"note",tone:"info",text:`(${et.current.length} queued message(s) discarded)`}),et.current=[],ko([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Rs,Le]),gn=Y(async l=>{let i=as(l),a=uo(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let g=new AbortController;ke.current=g,Q({verb:"Publishing",total:i.length,done:0,active:[],rows:on(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Xt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of co({cwd:e,partitions:i,promptFor:h=>Ln(h.paths),concurrency:Xt,profileName:s,allowProdWrites:mt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?Q(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):Q(h=>h&&{...h,active:h.active.filter(w=>w!==u.label),done:h.done+1,rows:Ne(h.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")Q(h=>{if(!h)return h;let w={...h,lastAt:Date.now()};return u.event.type==="tool"?w.tools=h.tools+1:u.event.type==="text"&&(w.chars=h.chars+u.event.delta.length),w});else if(u.type==="run_done"){$t(P=>P+u.totalCostUsd),xt(P=>P+u.results.reduce((I,K)=>I+K.outputTokens,0));let h=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:h+rr(u.results,i,w).join(`
273
+ `)});let b=or(e,s);b&&d({kind:"note",tone:"info",text:b})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,Q(null),N(!1),ae(u=>u+1)}},[e,s,d,t]),Eo=Y(async l=>{await ce(nr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Wn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Qe(`Related articles not yet published (${i.length}):`),G([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ce]),Io=Y(l=>{let i=Ge(l);if(!i||_e(i)&&!i.refreshToken)return null;let a={...It(i.idToken)??{},...It(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),No=Y((l,i)=>{if(i){let a=J(e);a&&(a.defaultProfile=l,ml(a,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Io(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),ae(a=>a+1)},[e,d,me,Io]),wn=Y((l,i,a)=>{vn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),me(),fo(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:St(Rt(e)).join(`
274
+ `)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,me,vt]),yn=Y(async l=>{let i;try{i=await qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],h=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),wn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,wn]),kn=Y((l,i)=>{Lo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),me(),yn(l)},[e,d,me,yn]),Ss=Y(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await nt(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Af(e,i.name,{projectName:g.name})}catch{}await yn(i.name);return}try{let{projects:a}=await nt(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),kn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Xe({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,yn,kn]),bn=Y(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=st(l.oldContent,l.newContent,Le());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Le]),Ds=Y(l=>{if(Ue.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ue.current.shift();try{wf({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ue.current.length===0&&G(g=>g.length>0?g:["/sync"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return bn(),!0},[e,s,bn,d]),js=Y(l=>{let i=yo.current;if(!i)return!1;if(yo.current=null,le(null),ct.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Vr(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:_n().join(`
275
275
  `)}),vt(Go())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
276
- ${yl}`}),G(["/init"]),an(!1),!0},[e,d,vt]),As=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(an(!0),a){case"help":Ut({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ft.current=[],an(!1),le(null),ct.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(h){d({kind:"note",tone:"error",text:h.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),se(!0);try{let h=await tf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>d({kind:"note",tone:"info",text:b})),y=nf(u.name,h);if(of(y),await Wo(y,u.name,b=>d({kind:"note",tone:"info",text:b})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Pn(y)}`}),await Ss(s),Ot.current){let b=Ot.current;Ot.current=null;let P=Ie(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${b}.`}),G([b])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${b}.)`}),G(["/login"]),Ot.current=b)}else pn.current&&(le(pn.current),pn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(h){d({kind:"note",tone:"error",text:`Login failed: ${h.message}`})}finally{se(!1),ae(h=>h+1)}return}case"allow-prod":{let u=!1;try{u=ue(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}mt.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Dr(g.join(" ")),h=Se.current.uuid;if(!h){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=Se.current.firstPrompt??"";fl(y,e).then(b=>{b?(le(`/rename ${b}`),d({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}hf(h,u),ht(u),nn(`${es} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],h=J(e);if(!u){let y=Object.entries(h?.profiles??{});if(y.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=y.map(([K,Z])=>({name:K,env:Z.connection?.environment??"custom",prod:Z.production===!0,who:Io(K)})),P=s??h?.defaultProfile,I=Math.max(0,b.findIndex(K=>K.name===P));gt({cursor:I,current:I,rows:b});return}if(u==="add"){let y=jr(e,g[1],g[2]);if(y){d({kind:"note",tone:"error",text:y});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),No(g[1],!1);return}if(!h?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}No(u,!0);return}case"doctor":await en(g,{cwd:e});return;case"mcp":await Un(g);return;case"init":{if(J(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let u=xf().map(h=>({name:h,apiUrl:$f(h).apiUrl}));yt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),h=mf(e).filter(P=>P.uuid!==Se.current.uuid);if(!u){if(!h.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}tt({query:"",cursor:0,sessions:h});return}let y=ff(e,u);if(!y){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}me(y.uuid),Se.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},ht(y.name),ss(y.uuid),ft.current=[];let b=Zr(e,y.uuid);for(let P of b)d(P);d({kind:"note",tone:"ok",text:b.length?`Resumed "${y.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),h;try{h=await qt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!u){let b=h.workspaces.map(I=>({id:I.id,name:I.name??I.id,type:I.workspace_type}));if(b.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,b.findIndex(I=>I.id===h.current));wt({cursor:P,current:P,rows:b,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let y=Mo(h.workspaces,u);if(!y){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}yn(h.profile,h.projectId,y);return}case"project":{let u=g.join(" ").trim(),h;try{h=await nt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!u){let b=h.projects.map(I=>({id:I.id,name:I.name??I.id,sub:I.sub_domain}));if(b.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=b.findIndex(I=>I.id===h.current);Xe({cursor:Math.max(0,P),current:P,rows:b,profile:h.profile,environment:h.environment});return}let y=Ls(h.projects,u);if(!y){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${h.projects.map(b=>b.name??b.id).join(", ")}`});return}kn(h.profile,y);return}case"logout":{let u;try{u=ue(e,s).name}catch(y){d({kind:"note",tone:"error",text:y.message});return}let h=lf(u);cf(e,u),me(),ae(y=>y+1),d({kind:"note",tone:h?"ok":"info",text:h?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(!To(l.trim()))return;if(g[0]==="--related"&&g[1]){let h=await Wn(e,s,g[1].replace(/\\/g,"/"));if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await gn(h);return}if(g[0]&&g[0]!=="--all"){await Eo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await is({cwd:e,profileName:s}),y=Jt(h.entries),b=Mn(h.entries);if(b>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${b} article${b===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),y.length===0){d({kind:"note",tone:"ok",text:b>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=h.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await gn(y.map(P=>P.path));return}kt({cursor:0,rows:Di(y)})}catch(h){d({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let y=[];try{y=Object.keys(fo(e,ue(e,s).name)?.articles??{})}catch{}if(y.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ze({query:"",cursor:0,paths:y});return}let h=Zp(u)?u:lt(e,u);if(Be(h)){try{d({kind:"preview",name:rn(h),text:kl(rs(h,"utf8"))})}catch(y){d({kind:"note",tone:"error",text:`Could not read ${h}: ${y.message}`})}return}if(Mf.test(u)){try{let y=ue(e,s),b={profile:y.name,connection:y.connection},P=y.project.projectId??sf(b),I=await af(b,P,u);d({kind:"preview",name:I.title??u,text:I.content??"*(article has no content)*"})}catch(y){d({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let P=Bn(us(e));Ke({cursor:P,current:P});return}let{lines:h,changed:y,effective:b}=Zt(e,u);for(let P of h)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});y&&(vs(P=>P+1),ge.current?.setModel(b));return}case"convert":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:h}=lr(g),y=Pf(e,s);if(y.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=cr(y,u);if(b.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${y.length} are tracked overall.)`});return}let P=as(b),I=3,K=`/convert${u?` --scope ${u}`:""} --run`,Z=uo(e,"light");if(!h){let $=hl({files:ur(e,b),op:"convert",model:Z.model}),D=u?`Scope: ${u} (${b.length} of ${y.length} tracked)
276
+ ${wl}`}),G(["/init"]),an(!1),!0},[e,d,vt]),As=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(an(!0),a){case"help":Ut({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ft.current=[],an(!1),le(null),ct.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(h){d({kind:"note",tone:"error",text:h.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),se(!0);try{let h=await tf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>d({kind:"note",tone:"info",text:b})),w=nf(u.name,h);if(of(w),await Wo(w,u.name,b=>d({kind:"note",tone:"info",text:b})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Pn(w)}`}),await Ss(s),Ot.current){let b=Ot.current;Ot.current=null;let P=Ie(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${b}.`}),G([b])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${b}.)`}),G(["/login"]),Ot.current=b)}else pn.current&&(le(pn.current),pn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(h){d({kind:"note",tone:"error",text:`Login failed: ${h.message}`})}finally{se(!1),ae(h=>h+1)}return}case"allow-prod":{let u=!1;try{u=ue(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}mt.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Dr(g.join(" ")),h=Se.current.uuid;if(!h){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Se.current.firstPrompt??"";fl(w,e).then(b=>{b?(le(`/rename ${b}`),d({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}hf(h,u),ht(u),nn(`${es} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],h=J(e);if(!u){let w=Object.entries(h?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=w.map(([K,Z])=>({name:K,env:Z.connection?.environment??"custom",prod:Z.production===!0,who:Io(K)})),P=s??h?.defaultProfile,I=Math.max(0,b.findIndex(K=>K.name===P));gt({cursor:I,current:I,rows:b});return}if(u==="add"){let w=jr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),No(g[1],!1);return}if(!h?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}No(u,!0);return}case"doctor":await en(g,{cwd:e});return;case"mcp":await Un(g);return;case"init":{if(J(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let u=xf().map(h=>({name:h,apiUrl:$f(h).apiUrl}));wt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),h=mf(e).filter(P=>P.uuid!==Se.current.uuid);if(!u){if(!h.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}tt({query:"",cursor:0,sessions:h});return}let w=ff(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}me(w.uuid),Se.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},ht(w.name),ss(w.uuid),ft.current=[];let b=Zr(e,w.uuid);for(let P of b)d(P);d({kind:"note",tone:"ok",text:b.length?`Resumed "${w.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),h;try{h=await qt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!u){let b=h.workspaces.map(I=>({id:I.id,name:I.name??I.id,type:I.workspace_type}));if(b.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,b.findIndex(I=>I.id===h.current));yt({cursor:P,current:P,rows:b,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let w=Mo(h.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}wn(h.profile,h.projectId,w);return}case"project":{let u=g.join(" ").trim(),h;try{h=await nt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!u){let b=h.projects.map(I=>({id:I.id,name:I.name??I.id,sub:I.sub_domain}));if(b.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=b.findIndex(I=>I.id===h.current);Xe({cursor:Math.max(0,P),current:P,rows:b,profile:h.profile,environment:h.environment});return}let w=Ls(h.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${h.projects.map(b=>b.name??b.id).join(", ")}`});return}kn(h.profile,w);return}case"logout":{let u;try{u=ue(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let h=lf(u);cf(e,u),me(),ae(w=>w+1),d({kind:"note",tone:h?"ok":"info",text:h?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(!To(l.trim()))return;if(g[0]==="--related"&&g[1]){let h=await Wn(e,s,g[1].replace(/\\/g,"/"));if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await gn(h);return}if(g[0]&&g[0]!=="--all"){await Eo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await is({cwd:e,profileName:s}),w=Jt(h.entries),b=Mn(h.entries);if(b>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${b} article${b===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:b>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=h.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await gn(w.map(P=>P.path));return}kt({cursor:0,rows:Di(w)})}catch(h){d({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(fo(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ze({query:"",cursor:0,paths:w});return}let h=Zp(u)?u:lt(e,u);if(Be(h)){try{d({kind:"preview",name:rn(h),text:kl(rs(h,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${h}: ${w.message}`})}return}if(Mf.test(u)){try{let w=ue(e,s),b={profile:w.name,connection:w.connection},P=w.project.projectId??sf(b),I=await af(b,P,u);d({kind:"preview",name:I.title??u,text:I.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let P=Bn(us(e));Ke({cursor:P,current:P});return}let{lines:h,changed:w,effective:b}=Zt(e,u);for(let P of h)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});w&&(vs(P=>P+1),ge.current?.setModel(b));return}case"convert":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:h}=lr(g),w=Pf(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=cr(w,u);if(b.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let P=as(b),I=3,K=`/convert${u?` --scope ${u}`:""} --run`,Z=uo(e,"light");if(!h){let $=hl({files:ur(e,b),op:"convert",model:Z.model}),D=u?`Scope: ${u} (${b.length} of ${w.length} tracked)
277
277
  `:"",M=`
278
278
  Model: ${Z.model}${Z.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:D+pr(P,$,I).join(`
279
279
  `)+M}),G([K]);return}Ve.current=Date.now(),ut(0),N(!0);let _=new AbortController;ke.current=_,Q({verb:"Converting",total:P.length,done:0,active:[],rows:on(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${b.length} articles across ${P.length} partitions (\u2264${I} agents at once) on ${Z.model}\u2026 (esc to stop)`});try{for await(let $ of co({cwd:e,partitions:P,promptFor:dr,concurrency:I,profileName:s,allowProdWrites:mt.current,model:Z.model,signal:_.signal}))if($.type==="partition_status")$.status==="running"?Q(D=>D&&{...D,active:[...D.active,$.label],rows:Ne(D.rows,$.label,"active"),lastAt:Date.now()}):Q(D=>D&&{...D,active:D.active.filter(M=>M!==$.label),done:D.done+1,rows:Ne(D.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")Q(D=>{if(!D)return D;let M={...D,lastAt:Date.now()};return $.event.type==="tool"?M.tools=D.tools+1:$.event.type==="text"&&(M.chars=D.chars+$.event.delta.length),M});else if($.type==="run_done"){$t(ee=>ee+$.totalCostUsd),xt(ee=>ee+$.results.reduce((q,z)=>q+z.outputTokens,0));let D=$.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:D+fr($.results,P,M).join(`
280
- `)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{ke.current=null,Q(null),N(!1),ae($=>$+1)}return}case"write":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=gl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:h,path:y,preview:b,concurrency:P}=hr(g),{docsDir:I,targets:K,reason:Z}=xr(e,u,{scope:h,path:y});if(K.length===0){d({kind:"note",tone:"warn",text:Z??"Nothing to write."});return}let _=as(K),$=mr(P),D=uo(e,"standard");if(b&&!!!y){let q=hl({files:yr(e,u,K),op:"write",model:D.model}),z=h?`Scope: ${h} (${K.length} pending)
280
+ `)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{ke.current=null,Q(null),N(!1),ae($=>$+1)}return}case"write":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=gl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:h,path:w,preview:b,concurrency:P}=hr(g),{docsDir:I,targets:K,reason:Z}=xr(e,u,{scope:h,path:w});if(K.length===0){d({kind:"note",tone:"warn",text:Z??"Nothing to write."});return}let _=as(K),$=mr(P),D=uo(e,"standard");if(b&&!!!w){let q=hl({files:wr(e,u,K),op:"write",model:D.model}),z=h?`Scope: ${h} (${K.length} pending)
281
281
  `:"",Ae=`
282
282
  Model: ${D.model}${D.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:z+kr(_,q,$).join(`
283
- `)+Ae}),G([`/write${h?` --scope ${h}`:""}`]);return}Ve.current=Date.now(),ut(0),N(!0);let ee=new AbortController;ke.current=ee,Q({verb:"Writing",total:_.length,done:0,active:[],rows:on(_),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${K.length} article${K.length===1?"":"s"} across ${_.length} partition${_.length===1?"":"s"} (\u2264${$} agents at once) on ${D.model}${D.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let q of co({cwd:e,partitions:_,promptFor:z=>wr(z,I),concurrency:$,profileName:s,allowProdWrites:mt.current,model:D.model,signal:ee.signal}))if(q.type==="partition_status")q.status==="running"?Q(z=>z&&{...z,active:[...z.active,q.label],rows:Ne(z.rows,q.label,"active"),lastAt:Date.now()}):Q(z=>z&&{...z,active:z.active.filter(Ae=>Ae!==q.label),done:z.done+1,rows:Ne(z.rows,q.label,q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(q.type==="partition_event")Q(z=>{if(!z)return z;let Ae={...z,lastAt:Date.now()};return q.event.type==="tool"?Ae.tools=z.tools+1:q.event.type==="text"&&(Ae.chars=z.chars+q.event.delta.length),Ae});else if(q.type==="run_done"){$t(Oo=>Oo+q.totalCostUsd),xt(Oo=>Oo+q.results.reduce((Ml,Ll)=>Ml+Ll.outputTokens,0));let z=q.aborted?"Stopped. ":"",Ae=t.kind==="api"?"api":"subscription";d({kind:"note",tone:q.aborted?"warn":q.ok?"ok":"warn",text:z+br(q.results,_,Ae).join(`
284
- `)}),!q.aborted&&q.ok&&G(["/publish --all","/screenshot --all"])}}catch(q){d({kind:"note",tone:"error",text:`Write run failed: ${q.message}`})}finally{ke.current=null,Q(null),N(!1),ae(q=>q+1)}return}case"draft":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:h}=$r(e);if(u.length===0&&h===0){d({kind:"note",tone:"info",text:Cr});return}let y=g.join(" ").trim();if(!y&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
283
+ `)+Ae}),G([`/write${h?` --scope ${h}`:""}`]);return}Ve.current=Date.now(),ut(0),N(!0);let ee=new AbortController;ke.current=ee,Q({verb:"Writing",total:_.length,done:0,active:[],rows:on(_),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${K.length} article${K.length===1?"":"s"} across ${_.length} partition${_.length===1?"":"s"} (\u2264${$} agents at once) on ${D.model}${D.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let q of co({cwd:e,partitions:_,promptFor:z=>yr(z,I),concurrency:$,profileName:s,allowProdWrites:mt.current,model:D.model,signal:ee.signal}))if(q.type==="partition_status")q.status==="running"?Q(z=>z&&{...z,active:[...z.active,q.label],rows:Ne(z.rows,q.label,"active"),lastAt:Date.now()}):Q(z=>z&&{...z,active:z.active.filter(Ae=>Ae!==q.label),done:z.done+1,rows:Ne(z.rows,q.label,q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(q.type==="partition_event")Q(z=>{if(!z)return z;let Ae={...z,lastAt:Date.now()};return q.event.type==="tool"?Ae.tools=z.tools+1:q.event.type==="text"&&(Ae.chars=z.chars+q.event.delta.length),Ae});else if(q.type==="run_done"){$t(Oo=>Oo+q.totalCostUsd),xt(Oo=>Oo+q.results.reduce((Ml,Ll)=>Ml+Ll.outputTokens,0));let z=q.aborted?"Stopped. ":"",Ae=t.kind==="api"?"api":"subscription";d({kind:"note",tone:q.aborted?"warn":q.ok?"ok":"warn",text:z+br(q.results,_,Ae).join(`
284
+ `)}),!q.aborted&&q.ok&&G(["/publish --all","/screenshot --all"])}}catch(q){d({kind:"note",tone:"error",text:`Write run failed: ${q.message}`})}finally{ke.current=null,Q(null),N(!1),ae(q=>q+1)}return}case"draft":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:h}=$r(e);if(u.length===0&&h===0){d({kind:"note",tone:"info",text:Cr});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
285
285
  ${u.map(I=>` \u2022 ${I.name} (${I.docCount} doc${I.docCount===1?"":"s"})`).join(`
286
- `)}`}),G(u.map(I=>`/draft ${I.name}`));return}let b="",P;if(y){let I=vr(u,y);I?b=I:P=y}else b=u[0]?.name??"";await ce(qn(b,P),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{if(!To(l.trim()))return;let u=(g[0]??"status").toLowerCase();try{if(u==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let h=await is({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Hn(h).join(`
287
- `)});return}if(u==="pull"){let h=g[1];if(!h){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(h==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await is({cwd:e,profileName:s})).entries.filter(I=>I.status==="remote-ahead"&&I.path).map(I=>I.path),y.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[h.replace(/\\/g,"/")];let b=[];for(let P of y)b.push(await wf({cwd:e,profileName:s,relPath:P}));Ue.current=b,bn();return}if(u==="baseline"){let h=g[1],y=h&&h!=="--all"?h.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:y?`Setting the sync baseline for ${y}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let b=await kf({cwd:e,profileName:s,relPaths:y?[y]:void 0});if(b.baselined.length===0&&b.skipped.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}b.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${b.baselined.length} article${b.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),b.skipped.length>0&&d({kind:"note",tone:"warn",text:`${b.skipped.length} skipped:
286
+ `)}`}),G(u.map(I=>`/draft ${I.name}`));return}let b="",P;if(w){let I=vr(u,w);I?b=I:P=w}else b=u[0]?.name??"";await ce(qn(b,P),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"sync":{if(!To(l.trim()))return;let u=(g[0]??"status").toLowerCase();try{if(u==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let h=await is({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Hn(h).join(`
287
+ `)});return}if(u==="pull"){let h=g[1];if(!h){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(h==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await is({cwd:e,profileName:s})).entries.filter(I=>I.status==="remote-ahead"&&I.path).map(I=>I.path),w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[h.replace(/\\/g,"/")];let b=[];for(let P of w)b.push(await yf({cwd:e,profileName:s,relPath:P}));Ue.current=b,bn();return}if(u==="baseline"){let h=g[1],w=h&&h!=="--all"?h.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:w?`Setting the sync baseline for ${w}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let b=await kf({cwd:e,profileName:s,relPaths:w?[w]:void 0});if(b.baselined.length===0&&b.skipped.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}b.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${b.baselined.length} article${b.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),b.skipped.length>0&&d({kind:"note",tone:"warn",text:`${b.skipped.length} skipped:
288
288
  ${b.skipped.map(P=>` - ${P.path} (${P.reason})`).join(`
289
- `)}`}),ae(P=>P+1);return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}catch(h){d({kind:"note",tone:"error",text:`Sync failed: ${h.message}`})}return}case"scope":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=bf(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}bt({cursor:0,rows:u.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(g[0]==="--auto"){let h=J(e);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=g[1]!=="off";ml({...h,autoAudit:y},e),d({kind:"note",tone:"ok",text:y?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Qt();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"capture-setup":{let u=await tn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let h=Or(e);h&&d({kind:"note",tone:"info",text:h.join(`
289
+ `)}`}),ae(P=>P+1);return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}catch(h){d({kind:"note",tone:"error",text:`Sync failed: ${h.message}`})}return}case"scope":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=bf(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}bt({cursor:0,rows:u.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(g[0]==="--auto"){let h=J(e);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";ml({...h,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Qt();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"capture-setup":{let u=await tn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let h=Or(e);h&&d({kind:"note",tone:"info",text:h.join(`
290
290
  `)});return}case"devhints":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:St(Rt(e)).join(`
291
- `)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e);return}case"inbox":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ur(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Mr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=Tr(g);if(!h&&Pr(e)===0){d({kind:"note",tone:"info",text:Sr});return}let y=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(Rr(h,u),{display:y,quietUser:!0});return}case"catch-up":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!To(l.trim()))return;let{publish:u}=Wr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let h=await Hr({cwd:e,profileName:s});for(let b of qr(h))d({kind:"note",tone:b.startsWith("\u2713")?"ok":b.startsWith("\u2139")?"info":"warn",text:b});let y=Et(At(e));d({kind:"note",tone:"info",text:y?`Catching up on ${y}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ce(Fr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Co.current=!0,d({kind:"note",tone:"info",text:`Updating ${it}\u2026 (don\u2019t close this window)`}),ln(!0),(await Kn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),G(h=>h.includes("/exit")?h:[...h,"/exit"]),hs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${zn}`});return}case"screenshot":{let u=Ir(g);if(u.mode==="list"){if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:_r(Nr(e,u.scope),u.scope).join(`
292
- `)});return}if(u.mode==="single"){let _=await Yn(g);_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});return}if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=u.mode==="scope"?u.scope:void 0,y=Cf(e,{scope:h}).map(_=>_.id);if(y.length===0){d({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}let b=6,P=vf(y,3),I=uo(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let K=new AbortController;ke.current=K,Q({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:on(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${b} agents at once) on ${I.model}${I.forced?" (forced)":""}\u2026 (esc to stop)`});let Z=!1;try{for await(let _ of co({cwd:e,partitions:P,promptFor:ka,concurrency:b,profileName:s,allowProdWrites:mt.current,model:I.model,signal:K.signal}))if(_.type==="partition_status")_.status==="running"?Q($=>$&&{...$,active:[...$.active,_.label],rows:Ne($.rows,_.label,"active"),lastAt:Date.now()}):Q($=>$&&{...$,active:$.active.filter(D=>D!==_.label),done:$.done+1,rows:Ne($.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")Q($=>{if(!$)return $;let D={...$,lastAt:Date.now()};return _.event.type==="tool"?D.tools=$.tools+1:_.event.type==="text"&&(D.chars=$.chars+_.event.delta.length),D});else if(_.type==="run_done"){$t(ee=>ee+_.totalCostUsd),xt(ee=>ee+_.results.reduce((q,z)=>q+z.outputTokens,0));let $=_.results.filter(ee=>ee.ok).length,D=_.aborted?"Stopped. ":"";Z=!_.aborted&&u.setup;let M=_.aborted?"":Z?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${$}/${_.results.length} batches ok.${M}`})}}catch(_){d({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{ke.current=null,Q(null),N(!1),ae(_=>_+1)}if(Z){let _=await tn();_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});let $=Or(e);$&&d({kind:"note",tone:"info",text:$.join(`
293
- `)})}return}case"reset":{let u=Yr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}wo.current={repoName:rn(e),targets:u,hadDevhints:Be(ds(e))},d({kind:"note",tone:"warn",text:zr(e,u).join(`
294
- `)}),le(rn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,bn,d,me,ce,gn,Eo,Ss]),xn=Y(l=>{let i=(l??A).trim();if(w(""),cn(null),dt(0),i.startsWith("/")&&(le(null),ct.current++,Qe(null),G(g=>el(g,i))),!i||js(i)||Ds(i))return;yo.current.push(i);let a=il(i,gs.current);i.startsWith("/")?(d({kind:"user",text:i}),As(a)):ce(a,{display:i})},[A,js,Ds,As,ce]),Es=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=ol(l);if(rl(i)){let a=sl(++Il.current,i);gs.current.set(a,i),T(a)}else T(i);return}T(l)},[T]),Ct=Math.max(10,je-6),Is=os(()=>ao(x.text,Ct),[x.text,Ct]),_o=Y(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),$n=Y(l=>k(i=>({...i,pos:ll(ao(i.text,Ct),i.pos,l)})),[Ct]),Ft=Y(l=>k(i=>({...i,pos:cl(ao(i.text,Ct),i.pos,l)})),[Ct]),Ol=["\x1B[H","\x1B[1~","\x1BOH"],Ul=["\x1B[F","\x1B[4~","\x1BOF"],Ns=Y((l,i)=>i.leftArrow?(_o(-1),!0):i.rightArrow?(_o(1),!0):l&&Ol.includes(l)?(Ft("start"),!0):l&&Ul.includes(l)?(Ft("end"),!0):i.ctrl&&l==="a"?(Ft("start"),!0):i.ctrl&&l==="e"?(Ft("end"),!0):!1,[_o,Ft]);return Xp((l,i)=>{if(i.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(S){if(i.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}_t.current||(_t.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(i.return){let a=A.trim();if(!a)return;et.current.push(a),ko([...et.current]),w("");return}if(Ns(l,i))return;if(i.upArrow){$n(-1);return}if(i.downArrow){$n(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Es(l);return}if(ze){if(i.upArrow){Ke(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ke(a=>a&&{...a,cursor:Math.min(Re.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ke(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re[ze.cursor];Ke(null);let{lines:g,changed:u,effective:h}=Zt(e,a.value??"default");for(let y of g)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(vs(y=>y+1),ge.current?.setModel(h));return}if(l==="s"){let a=Re[ze.cursor];Ke(null),ge.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Ke(null);return}return}if(De){if(i.upArrow){gt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){gt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){gt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=De.rows[De.cursor];gt(null),No(a.name,i.return===!0);return}if(i.escape){gt(null);return}return}if(bo){if(i.escape){Ut(null);return}if(i.leftArrow||i.tab&&i.shift){Ut(a=>a&&{tab:(a.tab-1+xe.length)%xe.length});return}if(i.rightArrow||i.tab){Ut(a=>a&&{tab:(a.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ut({tab:Number(l)-1});return}return}if(Me){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Me.rows[Me.cursor].name;if(yt(null),!mi(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let h=Ge(a);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(i.escape){yt(null);return}return}if(de){if(i.upArrow){wt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){wt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=de.rows.length){wt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=de.rows[de.cursor],{profile:g,projectId:u}=de;wt(null),yn(g,u,a);return}if(i.escape){wt(null);return}return}if(ye){if(i.upArrow){Xe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Xe(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ye.rows.length){Xe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ye.rows[ye.cursor],{profile:g}=ye;Xe(null),kn(g,a);return}if(i.escape){Xe(null);return}return}if(fe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){bt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=fe.rows.filter(g=>g.checked).map(g=>g.path);if(bt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}sr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){bt(null);return}return}if(Je){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Je.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Je.rows[Je.cursor];kt(null),a.kind==="article"?Eo(a.paths[0]):gn(a.paths);return}if(i.escape){kt(null);return}return}if(we){if(i.escape){Ze(null);return}if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(Math.max(0,mn.length-1),a.cursor+1)});return}if(i.return){let a=mn[we.cursor];if(a){Ze(null);try{d({kind:"preview",name:rn(a),text:kl(rs(lt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Ze(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ze(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(be){if(i.escape){tt(null);return}if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Math.max(0,hn.length-1),a.cursor+1)});return}if(i.return){let a=hn[be.cursor];if(a){tt(null),me(a.uuid),Se.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},ht(a.name),ss(a.uuid),ft.current=[];let g=Zr(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){tt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){tt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!A&&Ce){w(Ce),le(null),ct.current++;return}if(!A&&Ye.length>0&&l&&/^[1-9]$/.test(l)){let a=Ye[Number(l)-1];if(a){w(a);return}}if(!A&&(Ro||$o)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Ro!=null;Wa(Ro??$o).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&So(null)});return}if(!Ns(l,i)){if(Ts){if(i.upArrow){dt(a=>Math.max(0,a-1));return}if(i.downArrow){dt(a=>Math.min(Wt.length-1,a+1));return}if(i.tab){w("/"+(Wt[Nt]?.name??"")+" "),dt(0);return}if(i.return){let a=Wt[Nt];if(a){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ka(a.usage)&&!g){w("/"+a.name+" "),dt(0);return}xn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(A!==""&&pt===null){$n(-1);return}let a=yo.current;if(!a.length)return;let g=pt===null?a.length-1:Math.max(0,pt-1);cn(g),w(a[g]??"");return}if(i.downArrow){if(A!==""&&pt===null){$n(1);return}let a=yo.current;if(pt===null)return;let g=pt+1;g>=a.length?(cn(null),w("")):(cn(g),w(a[g]??""));return}}if(i.return){xn();return}if(i.backspace||i.delete){C();return}if(i.escape){w(""),dt(0),le(null),G([]),Qe(null);return}l&&!i.ctrl&&!i.meta&&Es(l)}}}),$e(()=>{if(S||H)return;let l=et.current.shift();l!==void 0&&(ko([...et.current]),xn(l))},[S,H,xn]),B(te,{flexDirection:"column",width:je,children:[Ao!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ao.truncated&&j(R,{dimColor:!0,children:"\u2026"}),j(R,{children:Ao.text})]}),S&&(bs?j(Ff,{p:bs}):j(Lf,{startTime:Ve.current,chars:El})),j(te,{borderStyle:"round",borderColor:Ps.prod?"yellow":L,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Is.map((l,i)=>{let a=x.text.slice(l.start,l.end),g=i===lo(Is,x.pos),u=Math.min(x.pos,l.end)-l.start;return B(R,{children:[j(R,{color:L,children:i===0?"> ":" "}),g?B(ls,{children:[a.slice(0,u),j(po,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(R,{children:[j(R,{color:L,children:"> "}),Ce&&!S?B(ls,{children:[j(po,{ch:Ce[0],dim:!0}),j(R,{color:"gray",children:Ce.slice(1)}),j(R,{dimColor:!0,children:" (tab)"})]}):(jo.isSetup||!jl)&&!S?B(ls,{children:[j(po,{ch:jo.text[0],dim:!0}),j(R,{color:"gray",children:jo.text.slice(1)})]}):j(po,{ch:" "})]})}),ks.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ks.map((l,i)=>j(R,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),bo?j(Ja,{tab:bo.tab,width:je}):ze?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Select model"}),j(R,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,i)=>B(R,{color:i===ze.cursor?L:void 0,children:[i===ze.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===ze.current?" \u2714":""}`.padEnd(16),j(R,{color:"gray",children:l.desc})]},l.label)),j(R,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch connection profile"}),De.rows.map((l,i)=>B(R,{color:i===De.cursor?L:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===De.current?" \u2714":""}`.padEnd(20),j(R,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(R,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(R,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Me?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((l,i)=>B(R,{color:i===Me.cursor?L:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),j(R,{color:"gray",children:l.apiUrl})]},l.name)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch workspace"}),j(R,{dimColor:!0,children:`environment ${de.environment} \xB7 project ${de.projectName??`${de.projectId.slice(0,8)}\u2026`}`}),de.rows.map((l,i)=>B(R,{color:i===de.cursor?L:void 0,children:[i===de.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===de.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.type??""})]},l.id)),j(R,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Choose project"}),j(R,{dimColor:!0,children:`environment ${ye.environment}`}),ye.rows.map((l,i)=>B(R,{color:i===ye.cursor?L:void 0,children:[i===ye.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ye.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.sub??""})]},l.id)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let i=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),a=fe.rows.slice(i,i+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),i>0?j(R,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,h)=>{let y=i+h;return B(R,{color:y===fe.cursor?L:void 0,children:[y===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(R,{color:"gray",children:Fn(u)})]},u.path)}),i+14<fe.rows.length?j(R,{dimColor:!0,children:` \u2193 ${fe.rows.length-i-14} more`}):null,j(R,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Je?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Je.rows.map((l,i)=>{let a=i===Je.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(R,{color:a?L:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(R,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(R,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Preview article${we.query?` \u2014 filter: ${we.query}`:" (type to filter)"}`}),mn.length===0?j(R,{color:"gray",children:"no articles match"}):mn.map((l,i)=>B(R,{color:i===we.cursor?L:void 0,children:[i===we.cursor?"\u276F ":" ",l]},l)),j(R,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),hn.length===0?j(R,{color:"gray",children:"no sessions match"}):hn.map((l,i)=>B(R,{color:i===be.cursor?L:void 0,children:[i===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(R,{color:i===be.cursor?L:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(R,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ts?B(te,{flexDirection:"column",children:[Wt.map((l,i)=>B(R,{color:i===Nt?L:void 0,children:[i===Nt?"\u276F ":" ",l.usage.padEnd(22)," ",j(R,{color:i===Nt?L:"gray",children:l.name==="model"&&xo?`${l.desc} (currently ${xo})`:l.desc})]},l.name)),j(R,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!A&&Ye.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ws?j(R,{color:L,children:ws}):null,Ye.map((l,i)=>{let a=l.slice(0,Math.max(20,je-5)),g=je-a.length-7,u=g>=12?Va(l).slice(0,g):"";return B(R,{children:[j(R,{color:L,children:i+1})," ",a,u?j(R,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(R,{dimColor:!0,children:`press 1-${Ye.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(R,{color:"gray",children:[Ps.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${xo??"model n/a"}${t.kind==="api"?$s>0?` \xB7 ${pe($s)}`:"":xs>0?` \xB7 ${He(xs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Gf}from"react/jsx-runtime";async function Cl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Bf(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=qf(Gf(vl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
291
+ `)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e);return}case"inbox":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ur(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Mr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=Tr(g);if(!h&&Pr(e)===0){d({kind:"note",tone:"info",text:Sr});return}let w=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(Rr(h,u),{display:w,quietUser:!0});return}case"catch-up":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!To(l.trim()))return;let{publish:u}=Wr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let h=await Hr({cwd:e,profileName:s});for(let b of qr(h))d({kind:"note",tone:b.startsWith("\u2713")?"ok":b.startsWith("\u2139")?"info":"warn",text:b});let w=Et(At(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ce(Fr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Co.current=!0,d({kind:"note",tone:"info",text:`Updating ${it}\u2026 (don\u2019t close this window)`}),ln(!0),(await Kn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),G(h=>h.includes("/exit")?h:[...h,"/exit"]),hs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${zn}`});return}case"screenshot":{let u=Ir(g);if(u.mode==="list"){if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:_r(Nr(e,u.scope),u.scope).join(`
292
+ `)});return}if(u.mode==="single"){let _=await Yn(g);_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});return}if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=u.mode==="scope"?u.scope:void 0,w=Cf(e,{scope:h}).map(_=>_.id);if(w.length===0){d({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}let b=6,P=vf(w,3),I=uo(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let K=new AbortController;ke.current=K,Q({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:on(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${b} agents at once) on ${I.model}${I.forced?" (forced)":""}\u2026 (esc to stop)`});let Z=!1;try{for await(let _ of co({cwd:e,partitions:P,promptFor:ka,concurrency:b,profileName:s,allowProdWrites:mt.current,model:I.model,signal:K.signal}))if(_.type==="partition_status")_.status==="running"?Q($=>$&&{...$,active:[...$.active,_.label],rows:Ne($.rows,_.label,"active"),lastAt:Date.now()}):Q($=>$&&{...$,active:$.active.filter(D=>D!==_.label),done:$.done+1,rows:Ne($.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")Q($=>{if(!$)return $;let D={...$,lastAt:Date.now()};return _.event.type==="tool"?D.tools=$.tools+1:_.event.type==="text"&&(D.chars=$.chars+_.event.delta.length),D});else if(_.type==="run_done"){$t(ee=>ee+_.totalCostUsd),xt(ee=>ee+_.results.reduce((q,z)=>q+z.outputTokens,0));let $=_.results.filter(ee=>ee.ok).length,D=_.aborted?"Stopped. ":"";Z=!_.aborted&&u.setup;let M=_.aborted?"":Z?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${$}/${_.results.length} batches ok.${M}`})}}catch(_){d({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{ke.current=null,Q(null),N(!1),ae(_=>_+1)}if(Z){let _=await tn();_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});let $=Or(e);$&&d({kind:"note",tone:"info",text:$.join(`
293
+ `)})}return}case"reset":{let u=Yr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}yo.current={repoName:rn(e),targets:u,hadDevhints:Be(ds(e))},d({kind:"note",tone:"warn",text:zr(e,u).join(`
294
+ `)}),le(rn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,bn,d,me,ce,gn,Eo,Ss]),xn=Y(l=>{let i=(l??A).trim();if(y(""),cn(null),dt(0),i.startsWith("/")&&(le(null),ct.current++,Qe(null),G(g=>el(g,i))),!i||js(i)||Ds(i))return;wo.current.push(i);let a=il(i,gs.current);i.startsWith("/")?(d({kind:"user",text:i}),As(a)):ce(a,{display:i})},[A,js,Ds,As,ce]),Es=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=ol(l);if(rl(i)){let a=sl(++Il.current,i);gs.current.set(a,i),T(a)}else T(i);return}T(l)},[T]),Ct=Math.max(10,je-6),Is=os(()=>ao(x.text,Ct),[x.text,Ct]),_o=Y(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),$n=Y(l=>k(i=>({...i,pos:ll(ao(i.text,Ct),i.pos,l)})),[Ct]),Ft=Y(l=>k(i=>({...i,pos:cl(ao(i.text,Ct),i.pos,l)})),[Ct]),Ol=["\x1B[H","\x1B[1~","\x1BOH"],Ul=["\x1B[F","\x1B[4~","\x1BOF"],Ns=Y((l,i)=>i.leftArrow?(_o(-1),!0):i.rightArrow?(_o(1),!0):l&&Ol.includes(l)?(Ft("start"),!0):l&&Ul.includes(l)?(Ft("end"),!0):i.ctrl&&l==="a"?(Ft("start"),!0):i.ctrl&&l==="e"?(Ft("end"),!0):!1,[_o,Ft]);return Xp((l,i)=>{if(i.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(R){if(i.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}_t.current||(_t.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(i.return){let a=A.trim();if(!a)return;et.current.push(a),ko([...et.current]),y("");return}if(Ns(l,i))return;if(i.upArrow){$n(-1);return}if(i.downArrow){$n(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Es(l);return}if(ze){if(i.upArrow){Ke(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ke(a=>a&&{...a,cursor:Math.min(Re.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ke(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re[ze.cursor];Ke(null);let{lines:g,changed:u,effective:h}=Zt(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(vs(w=>w+1),ge.current?.setModel(h));return}if(l==="s"){let a=Re[ze.cursor];Ke(null),ge.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Ke(null);return}return}if(De){if(i.upArrow){gt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){gt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){gt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=De.rows[De.cursor];gt(null),No(a.name,i.return===!0);return}if(i.escape){gt(null);return}return}if(bo){if(i.escape){Ut(null);return}if(i.leftArrow||i.tab&&i.shift){Ut(a=>a&&{tab:(a.tab-1+xe.length)%xe.length});return}if(i.rightArrow||i.tab){Ut(a=>a&&{tab:(a.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ut({tab:Number(l)-1});return}return}if(Me){if(i.upArrow){wt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){wt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){wt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Me.rows[Me.cursor].name;if(wt(null),!mi(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let h=Ge(a);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(i.escape){wt(null);return}return}if(de){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=de.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=de.rows[de.cursor],{profile:g,projectId:u}=de;yt(null),wn(g,u,a);return}if(i.escape){yt(null);return}return}if(we){if(i.upArrow){Xe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Xe(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Xe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=we.rows[we.cursor],{profile:g}=we;Xe(null),kn(g,a);return}if(i.escape){Xe(null);return}return}if(fe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){bt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=fe.rows.filter(g=>g.checked).map(g=>g.path);if(bt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}sr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){bt(null);return}return}if(Je){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Je.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Je.rows[Je.cursor];kt(null),a.kind==="article"?Eo(a.paths[0]):gn(a.paths);return}if(i.escape){kt(null);return}return}if(ye){if(i.escape){Ze(null);return}if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(Math.max(0,mn.length-1),a.cursor+1)});return}if(i.return){let a=mn[ye.cursor];if(a){Ze(null);try{d({kind:"preview",name:rn(a),text:kl(rs(lt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Ze(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ze(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(be){if(i.escape){tt(null);return}if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Math.max(0,hn.length-1),a.cursor+1)});return}if(i.return){let a=hn[be.cursor];if(a){tt(null),me(a.uuid),Se.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},ht(a.name),ss(a.uuid),ft.current=[];let g=Zr(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){tt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){tt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!A&&Ce){y(Ce),le(null),ct.current++;return}if(!A&&Ye.length>0&&l&&/^[1-9]$/.test(l)){let a=Ye[Number(l)-1];if(a){y(a);return}}if(!A&&(Ro||$o)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Ro!=null;Wa(Ro??$o).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&So(null)});return}if(!Ns(l,i)){if(Ts){if(i.upArrow){dt(a=>Math.max(0,a-1));return}if(i.downArrow){dt(a=>Math.min(Wt.length-1,a+1));return}if(i.tab){y("/"+(Wt[Nt]?.name??"")+" "),dt(0);return}if(i.return){let a=Wt[Nt];if(a){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ka(a.usage)&&!g){y("/"+a.name+" "),dt(0);return}xn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(A!==""&&pt===null){$n(-1);return}let a=wo.current;if(!a.length)return;let g=pt===null?a.length-1:Math.max(0,pt-1);cn(g),y(a[g]??"");return}if(i.downArrow){if(A!==""&&pt===null){$n(1);return}let a=wo.current;if(pt===null)return;let g=pt+1;g>=a.length?(cn(null),y("")):(cn(g),y(a[g]??""));return}}if(i.return){xn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),dt(0),le(null),G([]),Qe(null);return}l&&!i.ctrl&&!i.meta&&Es(l)}}}),$e(()=>{if(R||H)return;let l=et.current.shift();l!==void 0&&(ko([...et.current]),xn(l))},[R,H,xn]),B(te,{flexDirection:"column",width:je,children:[Ao!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ao.truncated&&j(S,{dimColor:!0,children:"\u2026"}),j(S,{children:Ao.text})]}),R&&(bs?j(Ff,{p:bs}):j(Lf,{startTime:Ve.current,chars:El})),j(te,{borderStyle:"round",borderColor:Ps.prod?"yellow":L,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Is.map((l,i)=>{let a=x.text.slice(l.start,l.end),g=i===lo(Is,x.pos),u=Math.min(x.pos,l.end)-l.start;return B(S,{children:[j(S,{color:L,children:i===0?"> ":" "}),g?B(ls,{children:[a.slice(0,u),j(po,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(S,{children:[j(S,{color:L,children:"> "}),Ce&&!R?B(ls,{children:[j(po,{ch:Ce[0],dim:!0}),j(S,{color:"gray",children:Ce.slice(1)}),j(S,{dimColor:!0,children:" (tab)"})]}):(jo.isSetup||!jl)&&!R?B(ls,{children:[j(po,{ch:jo.text[0],dim:!0}),j(S,{color:"gray",children:jo.text.slice(1)})]}):j(po,{ch:" "})]})}),ks.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ks.map((l,i)=>j(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),bo?j(Ja,{tab:bo.tab,width:je}):ze?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Select model"}),j(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,i)=>B(S,{color:i===ze.cursor?L:void 0,children:[i===ze.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===ze.current?" \u2714":""}`.padEnd(16),j(S,{color:"gray",children:l.desc})]},l.label)),j(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Switch connection profile"}),De.rows.map((l,i)=>B(S,{color:i===De.cursor?L:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===De.current?" \u2714":""}`.padEnd(20),j(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Me?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((l,i)=>B(S,{color:i===Me.cursor?L:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),j(S,{color:"gray",children:l.apiUrl})]},l.name)),j(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Switch workspace"}),j(S,{dimColor:!0,children:`environment ${de.environment} \xB7 project ${de.projectName??`${de.projectId.slice(0,8)}\u2026`}`}),de.rows.map((l,i)=>B(S,{color:i===de.cursor?L:void 0,children:[i===de.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===de.current?" \u2714":""}`.padEnd(30),j(S,{color:"gray",children:l.type??""})]},l.id)),j(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Choose project"}),j(S,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,i)=>B(S,{color:i===we.cursor?L:void 0,children:[i===we.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===we.current?" \u2714":""}`.padEnd(30),j(S,{color:"gray",children:l.sub??""})]},l.id)),j(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let i=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),a=fe.rows.slice(i,i+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),i>0?j(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,h)=>{let w=i+h;return B(S,{color:w===fe.cursor?L:void 0,children:[w===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(S,{color:"gray",children:Fn(u)})]},u.path)}),i+14<fe.rows.length?j(S,{dimColor:!0,children:` \u2193 ${fe.rows.length-i-14} more`}):null,j(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Je?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Je.rows.map((l,i)=>{let a=i===Je.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(S,{color:a?L:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),mn.length===0?j(S,{color:"gray",children:"no articles match"}):mn.map((l,i)=>B(S,{color:i===ye.cursor?L:void 0,children:[i===ye.cursor?"\u276F ":" ",l]},l)),j(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(S,{color:L,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),hn.length===0?j(S,{color:"gray",children:"no sessions match"}):hn.map((l,i)=>B(S,{color:i===be.cursor?L:void 0,children:[i===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(S,{color:i===be.cursor?L:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ts?B(te,{flexDirection:"column",children:[Wt.map((l,i)=>B(S,{color:i===Nt?L:void 0,children:[i===Nt?"\u276F ":" ",l.usage.padEnd(22)," ",j(S,{color:i===Nt?L:"gray",children:l.name==="model"&&xo?`${l.desc} (currently ${xo})`:l.desc})]},l.name)),j(S,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!A&&Ye.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ys?j(S,{color:L,children:ys}):null,Ye.map((l,i)=>{let a=l.slice(0,Math.max(20,je-5)),g=je-a.length-7,u=g>=12?Va(l).slice(0,g):"";return B(S,{children:[j(S,{color:L,children:i+1})," ",a,u?j(S,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(S,{dimColor:!0,children:`press 1-${Ye.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(S,{color:"gray",children:[Ps.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${xo??"model n/a"}${t.kind==="api"?$s>0?` \xB7 ${pe($s)}`:"":xs>0?` \xB7 ${He(xs)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Gf}from"react/jsx-runtime";async function Cl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Bf(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=qf(Gf(vl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
295
295
  `),process.exit(0)}W();import{writeCrashLog as Pl,isBenignTransportError as Yf}from"document360-engine";var Tl=!1;function ps(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Rl(e){if(Tl)return;Tl=!0;let t=(n,o)=>{if(Yf(o)){Pl({kind:n,level:"transport",message:ps(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Pl({kind:n,level:"fatal",message:ps(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
296
296
  `+v(`\u2717 d360-writer crashed: ${ps(o)}`)+`
297
297
  `),r&&process.stderr.write(m(` Crash details: ${r}`)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.5.18",
3
+ "version": "0.5.19",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {